diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000000..04893416e3 --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,46 @@ +# A pull request with no activity for 3 days gets the `stale` label and a comment, and is closed +# 4 days later (a week in all, as in CONTRIBUTING.md) unless something happens on it. Issues are +# left alone. PRs labelled `goal:world-load` or `keep-open` are never touched. +name: Stale PRs + +on: + schedule: + - cron: "17 */6 * * *" + workflow_dispatch: + inputs: + dry_run: + description: Only log what would be done + type: boolean + default: true + +permissions: + actions: write # where the last run stopped is kept in the cache + issues: read + pull-requests: write + +concurrency: + group: stale + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0 + with: + days-before-issue-stale: -1 + days-before-issue-close: -1 + days-before-pr-stale: 3 + days-before-pr-close: 4 + stale-pr-label: stale + exempt-pr-labels: goal:world-load,keep-open + sort-by: updated + ascending: true + operations-per-run: 300 + debug-only: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} + stale-pr-message: >- + Nothing has happened on this PR for 3 days, so it is marked `stale` and will be closed in + 4 days. A push or a comment takes the mark off: rebase it onto `main` if it conflicts, and + say in one line what it still fixes. If it only waits for a maintainer, a comment saying so is enough. + close-pr-message: >- + Closed after a week with no activity. This is not a verdict on the code: if it still applies to + `main`, rebase it, say so here and it can be reopened. diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index caf2ef4c7e..64a6b08bd3 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -20,6 +20,16 @@ const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/xbox.rs", ]; +/// The per-lane form's sources (`XCL_PER_LANE`): part of only its own cache entries' identity, +/// so editing them does not invalidate the HLSL path's. +const PER_LANE_SOURCES: &[&str] = &[ + "src/gpu/recomp/lane_masks.rs", + "src/gpu/recomp/lower.rs", + "src/gpu/recomp/lower/wave.rs", + "src/gpu/recomp/lower_dxil.rs", + "src/gpu/recomp/ssa.rs", +]; + fn add(h: &mut u64, bytes: &[u8]) { for &byte in bytes { *h ^= byte as u64; @@ -48,4 +58,13 @@ fn main() { add(&mut h, &[0]); } println!("cargo:rustc-env=XCL_TRANSLATOR_SOURCE_ID={h:016x}"); + let mut p = 0xcbf2_9ce4_8422_2325u64; + for relative in PER_LANE_SOURCES { + println!("cargo:rerun-if-changed={relative}"); + add(&mut p, relative.as_bytes()); + add(&mut p, &[0]); + add(&mut p, &std::fs::read(root.join(relative)).expect("read per-lane source")); + add(&mut p, &[0]); + } + println!("cargo:rustc-env=XCL_PER_LANE_SOURCE_ID={p:016x}"); } diff --git a/crates/xcl/src/gpu/dxil/cfg.rs b/crates/xcl/src/gpu/dxil/cfg.rs index d85243f8e3..31b3dcec2a 100644 --- a/crates/xcl/src/gpu/dxil/cfg.rs +++ b/crates/xcl/src/gpu/dxil/cfg.rs @@ -17,6 +17,8 @@ pub enum Term { } pub struct CfgBlock { + /// byte offset of the block's first instruction + pub pc: u64, /// instruction indices (the terminating branch excluded for `Cond`/`Jump` by branch) pub insts: Vec, pub term: Term, @@ -38,6 +40,16 @@ fn is_end(name: &str) -> bool { impl Cfg { pub fn build(code: &[u8]) -> Result { + Self::build_with(code, None) + } + + /// Geometry mode: the ES's `s_setpc_b64` continues at `gs_start` (the GS code) when + /// that is past the start, else ends the program (`recomp::Mode::Geometry`). + pub fn build_geometry(code: &[u8], gs_start: Option) -> Result { + Self::build_with(code, Some(gs_start.filter(|&s| s > 0))) + } + + fn build_with(code: &[u8], setpc: Option>) -> Result { let mut insts: Vec = Vec::new(); let mut off = 0usize; while off + 4 <= code.len() { @@ -48,7 +60,19 @@ impl Cfg { rdna2::resolve_far_jumps(&mut insts); let index: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); let mut leaders: BTreeSet = BTreeSet::from([0]); + let is_setpc = |d: &Decoded| setpc.is_some() && d.inst.name == "S_SETPC_B64" && d.far_target.is_none(); + let setpc_target = match setpc { + Some(Some(t)) => Some(*index.get(&t).ok_or_else(|| format!("GS start {t:#x} is not the start of an instruction"))?), + _ => None, + }; + if let Some(t) = setpc_target { + leaders.insert(t); + } for (i, d) in insts.iter().enumerate() { + if is_setpc(d) { + leaders.insert(i + 1); + continue; + } if let Some(t) = rdna2::branch_target(d) { let ti = *index.get(&t).ok_or_else(|| format!("+{:#x}: branch to {t:#x}, which is not the start of an instruction", d.pc))?; leaders.insert(ti); @@ -70,6 +94,13 @@ impl Cfg { term = Term::End; break; } + if is_setpc(d) { + term = match setpc_target { + Some(t) => Term::Jump(block_of[&t]), + None => Term::End, + }; + break; + } if let Some(t) = rdna2::branch_target(d) { let tb = block_of[&index[&t]]; let name = d.inst.name; @@ -86,7 +117,7 @@ impl Cfg { } list.push(i); } - blocks.push(CfgBlock { insts: list, term, preds: Vec::new() }); + blocks.push(CfgBlock { pc: insts[s].pc, insts: list, term, preds: Vec::new() }); } // a conditional branch whose both edges meet is a jump for b in &mut blocks { @@ -172,7 +203,7 @@ fn make_reducible(blocks: &mut Vec) -> Result<(Vec, BTreeSet usize| match term { Term::Jump(x) => *x = to(*x), @@ -299,7 +330,7 @@ mod tests { use super::*; fn blk(term: Term) -> CfgBlock { - CfgBlock { insts: Vec::new(), term, preds: Vec::new() } + CfgBlock { pc: 0, insts: Vec::new(), term, preds: Vec::new() } } /// The console's loop entered in the middle (`62b584e061c05fc5`'s shape): 0 → {1 | 3}, diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index a754a072a5..f8edbf7c5f 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -279,3 +279,161 @@ fn graphics_stages_with_a_branch_before_their_exports() { assert_eq!(draw(&dvs, &dps, 0), cleared, "branch not taken"); assert_eq!(draw(&dvs, &dps, 1), kept, "branch taken"); } + +/// Geometry mode (ES+GS, the compute pass of `recomp::Mode::Geometry`): an ES that writes +/// its vertex to the LDS ring, the GS that reads its triangle's vertices, writes them to +/// its output area and emits a strip; split and native forms validate (also the ES or GS +/// alone, as the coverage sweep translates them). +#[test] +fn geometry_mode_validates() { + use crate::gpu::recomp::GsInterface; + let e = |n: &str, enc: &str, f: &[(&str, u64)]| encode(n, enc, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut es = Vec::new(); + // v20 = lane * ES item (16 B), ring[v20] = v9 (a fetched input) + es.extend(e("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", 193), ("SRC1", 128)])); + es.extend(e("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", 193), ("SRC1", 256 + 20)])); + es.extend(e("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 20), ("SRC0", 132), ("VSRC1", 20)])); + es.extend(e("DS_WRITE_B32", "ENC_DS", &[("ADDR", 20), ("DATA0", 9)])); + es.extend(e("S_BARRIER", "ENC_SOPP", &[])); + es.extend(e("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 6)])); + let mut gs = Vec::new(); + // v0 = vertex 0's dword offset: read it, write 3 output vertices at s2 + lane * 48 + gs.extend(e("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 130), ("VSRC1", 0)])); + gs.extend(e("DS_READ_B32", "ENC_DS", &[("ADDR", 30), ("VDST", 31)])); + gs.extend(e("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 32), ("SRC0", 193), ("SRC1", 128)])); + gs.extend(e("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 32), ("SRC0", 176), ("VSRC1", 32)])); + gs.extend(e("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 2), ("VSRC1", 32)])); + for k in 0..3u64 { + gs.extend(e("DS_WRITE_B32", "ENC_DS", &[("ADDR", 32), ("DATA0", 31), ("OFFSET0", 16 * k)])); + gs.extend(e("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 0x22)])); + } + gs.extend(e("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 0x12)])); + gs.extend(e("S_ENDPGM", "ENC_SOPP", &[])); + let sig = |name: &str, sv: u32, reg: u32| crate::gpu::dxbc::SigElement { name: name.into(), index: 0, system_value: sv, component_type: 3, register: reg, mask: 0xF, rw_mask: 0xF, stream: 0 }; + let g = GsInterface { + es_inputs: vec![sig("POSITION", 0, 0)], + es_outputs: vec![sig("SV_Position", 1, 0)], + outputs: vec![sig("SV_Position", 1, 0)], + max_vertex_count: 3, + gs_start: Some(es.len() as u64), + }; + let mut code = es.clone(); + code.extend_from_slice(&gs); + let mut es_end = es; + es_end.extend(e("S_ENDPGM", "ENC_SOPP", &[])); + let cases = [ + ("ES+GS", code, g.clone()), + ("ES alone", es_end, GsInterface { gs_start: None, ..g.clone() }), + ("GS alone", gs, GsInterface { gs_start: Some(0), ..g }), + ]; + for (name, code, g) in cases { + for split in [true, false] { + let o = KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + super::kernel::translate_geometry(&code, o, &g).unwrap_or_else(|e| panic!("{name} split {split}: {}", &e[..e.len().min(3000)])); + } + } +} + +/// Exhaustive bit-exact check of the IEEE-754 bit-manipulation formula used by +/// `lower_mem::uf_small_bits` for all 10-bit (mb=5) and 11-bit (mb=6) float inputs. +#[test] +fn uf_small_ieee_bit_math_matches_exact_formula() { + for mb in [5u32, 6u32] { + let p = 1u32 << mb; + let mmask = p - 1; + let mshift = 23 - mb; + let den_scale = f32::from_bits(if mb == 6 { 0x3580_0000 } else { 0x3600_0000 }); + for v in 0..(1u32 << (mb + 5)) { + let e = v >> mb; + let m = v & mmask; + // Reference formula (matching HLSL `uf_small`) + let fm = (m as f32) / (p as f32); + let ref_f = if e == 31 { + f32::from_bits(if m != 0 { 0x7FC0_0000 } else { 0x7F80_0000 }) + } else if e == 0 { + fm * (-14.0f32).exp2() + } else { + ((e as f32) - 15.0).exp2() * (1.0 + fm) + }; + // Exact IEEE bit math + let got_bits = if e == 31 { + if m != 0 { 0x7FC0_0000 } else { 0x7F80_0000 } + } else if e == 0 { + ((m as f32) * den_scale).to_bits() + } else { + ((e + 112) << 23) | (m << mshift) + }; + assert_eq!(got_bits, ref_f.to_bits(), "mb={mb} v={v:#x} (e={e} m={m})"); + } + } +} + +/// Multi-window switch dispatch, vector rawBufferLoad/Store, hoisted FormatLoad +/// descriptors, single/multi-component FormatLoad, and hoisted BVH loads all pass +/// DXIL validation across 1..=4 memory windows and wave configurations. +#[test] +fn multi_window_mem_format_and_bvh_validate() { + let code = prog(&[ + // Load descriptor s[12:15] once, then reuse across repeated BUFFER_LOAD_FORMAT_X + ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 12), ("SBASE", 0), ("OFFSET", 0x40), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX8", "ENC_SMEM", &[("SDATA", 16), ("SBASE", 0), ("OFFSET", 0x80), ("SOFFSET", 125)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 12), ("OFFSET", 0x10), ("SOFFSET", 125)], None), + // Divergent EXEC so lane guards are active (non-constant `act`) + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)], None), + // Repeated single-component format loads sharing s[12:15] (exercises hoisted FmtComp1 + Load2) + ("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 5), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + // Sub-4 and full-4 component format loads + D16 + static MTBUF + small byte load + ("BUFFER_LOAD_FORMAT_XY", "ENC_MUBUF", &[("VDATA", 6), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_XYZW", "ENC_MUBUF", &[("VDATA", 8), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_D16_X", "ENC_MUBUF", &[("VDATA", 12), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_D16_HI_X", "ENC_MUBUF", &[("VDATA", 12), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("TBUFFER_LOAD_FORMAT_X", "ENC_MTBUF", &[("VDATA", 13), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("FORMAT", 28), ("IDXEN", 1)], None), + ("BUFFER_LOAD_UBYTE", "ENC_MUBUF", &[("VDATA", 14), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + // Vector MUBUF & FLAT loads/stores + ("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", &[("VDATA", 16), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_STORE_DWORDX4", "ENC_MUBUF", &[("VDATA", 16), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("GLOBAL_LOAD_DWORDX4", "ENC_FLAT_GLBL", &[("VDST", 20), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("DATA", 20), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 16)], None), + ("GLOBAL_LOAD_USHORT", "ENC_FLAT_GLBL", &[("VDST", 24), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 4)], None), + // BVH node intersection (box32 / box16 / tri hoisted vector loads) + ("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 28), ("VADDR", 0), ("SRSRC", 3), ("DMASK", 0xF)], None), + ]); + for windows in [1u32, 2, 3, 4] { + for (wave64, split) in [(true, false), (false, false)] { + translate(&code, KernelOptions { wave64, split, mem_windows: windows, sampler_base: 0 }) + .unwrap_or_else(|e| panic!("w={windows} wave64={wave64}: {}", &e[..e.len().min(800)])); + if windows > 1 { + translate(&code, KernelOptions { wave64, split, mem_windows: windows | crate::gpu::recomp::HEAP_WINDOWS, sampler_base: 0 }) + .unwrap_or_else(|e| panic!("heap w={windows} wave64={wave64}: {}", &e[..e.len().min(800)])); + } + } + } +} + +/// `image_get_lod` with a static sampler (an S# built from constants in the code) translates +/// to `CalculateLevelOfDetail` on the sampler bound at `s, space1`, shared with a sample of +/// the same S#, and validates. +#[test] +fn ps_get_lod_with_a_static_sampler() { + use crate::gpu::recomp::{Mode, PsInterface}; + let clamp = 2 | 2 << 3 | 2 << 6; + let linear = [clamp, 0x00FF_F000u32, 1 << 20 | 1 << 22, 0]; + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + for (k, &w) in linear.iter().enumerate() { + list.push(if w == 0 { ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 24 + k as u64), ("SSRC0", 128)], None) } else { ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 24 + k as u64), ("SSRC0", 255)], Some(w)) }); + } + // uv = (I, J) of the first barycentric pair (v0, v1); T# s[16:23], S# s[24:27] + list.push(("IMAGE_GET_LOD", "ENC_MIMG", vec![("VDATA", 4), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x3), ("DIM", 1)], None)); + list.push(("IMAGE_SAMPLE", "ENC_MIMG", vec![("VDATA", 6), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x3), ("DIM", 1)], None)); + list.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let code = prog(&refs); + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None }; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let k = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + assert_eq!(k.static_samplers, vec![(linear, false)], "one static sampler, shared by get_lod and sample"); + if crate::gpu::recomp::dxc::location().is_ok() { + super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + } +} diff --git a/crates/xcl/src/gpu/dxil/coverage.rs b/crates/xcl/src/gpu/dxil/coverage.rs index 62c7a84ec7..4ac26cb707 100644 --- a/crates/xcl/src/gpu/dxil/coverage.rs +++ b/crates/xcl/src/gpu/dxil/coverage.rs @@ -123,12 +123,23 @@ pub struct Report { pub times_us: Vec, /// (direct DXIL bytes, HLSL-path DXIL bytes) for programs both paths produced pub sizes: Vec<(usize, usize)>, + /// the slowest programs: (microseconds, program), slowest first, at most [`SLOWEST`] + pub slowest: Vec<(u64, String)>, } +/// How many of the slowest programs a [`Report`] keeps. +pub const SLOWEST: usize = 10; + impl Report { pub fn add(&mut self, name: &str, s: &Sample) { let c = self.stages.entry(s.stage).or_default(); - self.times_us.push(s.time.as_micros() as u64); + let us = s.time.as_micros() as u64; + self.times_us.push(us); + if self.slowest.len() < SLOWEST || self.slowest.last().is_some_and(|l| l.0 < us) { + let at = self.slowest.partition_point(|l| l.0 >= us); + self.slowest.insert(at, (us, name.to_string())); + self.slowest.truncate(SLOWEST); + } match &s.result { Ok(size) => { c.translated += 1; @@ -186,6 +197,10 @@ impl Report { row(&mut s, "all", &self.total()); let (p50, p95, max) = self.time_percentiles(); s.push_str(&format!(" translation time per program: p50 {:.2} ms, p95 {:.2} ms, max {:.2} ms\n", p50 as f64 / 1e3, p95 as f64 / 1e3, max as f64 / 1e3)); + for (us, name) in &self.slowest { + s.push_str(&format!(" slow: {:>9.2} ms {name} +", *us as f64 / 1e3)); + } if !self.sizes.is_empty() { let (d, h): (usize, usize) = self.sizes.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); s.push_str(&format!(" DXIL size, {} programs: direct {} B, HLSL+DXC {} B (direct/HLSL {:.2})\n", self.sizes.len(), d, h, d as f64 / h.max(1) as f64)); @@ -239,7 +254,7 @@ pub fn translate_mode(code: &[u8], mode: &Mode, o: KernelOptions, validate: bool Mode::Vertex(vs) => kernel::translate_vertex(code, KernelOptions { split: false, ..o }, vs), Mode::Pixel(ps) => kernel::translate_pixel(code, KernelOptions { split: false, ..o }, ps), Mode::Mesh(ms) => kernel::translate_mesh(code, o, ms), - Mode::Geometry(_) => Err("geometry mode (ES+GS): not supported by the direct translator".into()), + Mode::Geometry(g) => kernel::translate_geometry(code, o, g), })); let k = match r { Ok(r) => r?, @@ -394,8 +409,7 @@ mod tests { r.add(name, &Sample { stage: stage_name(&mode), result: res, time: t0.elapsed(), hlsl_size: None }); } assert_eq!(r.stages["kernel"].translated, 1, "{}", r.text(5)); - assert_eq!(r.stages["GS"].unsupported, 1); - assert!(r.ranked()[0].0.starts_with("geometry mode")); + assert_eq!(r.stages["GS"].translated, 1, "{}", r.text(5)); } #[test] diff --git a/crates/xcl/src/gpu/dxil/fuzz_tests.rs b/crates/xcl/src/gpu/dxil/fuzz_tests.rs new file mode 100644 index 0000000000..b0f25311b8 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/fuzz_tests.rs @@ -0,0 +1,1364 @@ +//! Randomised differential testing of the emitter: a seeded generator of +//! random-but-valid compute kernels (straight-line and branchy integer and +//! float arithmetic with phis, loops, switches and selects; group-shared +//! loads, stores, barriers and atomics; wave reads; raw buffer I/O). Every +//! module must pass DXC's validator; a subset also runs on the GPU and is +//! compared with a CPU interpreter of the same program. +//! +//! Exactness: float values are small integers (|x| < 64, at most two +//! arithmetic steps from a conversion), so every add / sub / mul result is +//! exactly representable — contraction and denormal modes cannot change any +//! result. Fast-math flags are generated too, but modules using `nsz` or +//! reassociation (which may flip the sign of a zero) are only validated. +//! +//! Kernel ABI as in `ops_tests`: 32 threads (one wave32), inputs in `u2` +//! (`mem`, slot `k` of lane `l` at dword `64·k + l`), results in `u1`. + +use super::container::Stage; +use super::module::{fmf, BinOp, CastOp, Pred, RmwOp, Value}; +use super::ops::{barrier, BitCount, Binary, GroupShared}; +use super::shader::{RawUav, Shader}; +use super::validate; +use crate::gpu::recomp::runner; + +const LANES: usize = 32; +const IN_SLOTS: u32 = 6; + +// --------------------------------------------------------------- PRNG + +struct Rng(u64); + +impl Rng { + fn new(seed: u64) -> Rng { + Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + fn next(&mut self) -> u64 { + // xorshift64* + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + fn chance(&mut self, num: u64, den: u64) -> bool { + self.next() % den < num + } + fn pick(&mut self, xs: &[T]) -> T { + xs[self.below(xs.len())] + } + /// Interesting 32/64-bit patterns as well as uniform ones. + fn bits(&mut self, w: u32) -> u64 { + let mask = if w == 64 { u64::MAX } else { (1u64 << w) - 1 }; + let v = match self.below(6) { + 0 => self.below(8) as u64, + 1 => (self.below(8) as u64).wrapping_neg(), + 2 => 1u64 << (w - 1), + 3 => (1u64 << (w - 1)) - 1, + _ => self.next(), + }; + v & mask + } +} + +// ------------------------------------------------------------------ IR + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum T { + I1, + I32, + I64, + F32, + F64, +} + +impl T { + fn width(self) -> u32 { + match self { + T::I1 => 1, + T::I32 | T::F32 => 32, + T::I64 | T::F64 => 64, + } + } + fn mask(self) -> u64 { + if self.width() == 64 { + u64::MAX + } else { + (1u64 << self.width()) - 1 + } + } + fn is_float(self) -> bool { + matches!(self, T::F32 | T::F64) + } +} + +#[derive(Debug, Clone, Copy)] +enum Opnd { + V(usize), + C(T, u64), +} + +#[derive(Debug, Clone, Copy)] +enum DxUn { + Count, + Lo, + Hi, + Rev, +} + +#[derive(Debug, Clone)] +enum Op { + Bin(BinOp, Opnd, Opnd), + FBin(BinOp, Opnd, Opnd, u64), + Cmp(Pred, Opnd, Opnd), + Select(Opnd, Opnd, Opnd), + Cast(CastOp, Opnd, T), + DxBin(Binary, Opnd, Opnd), + DxUn(DxUn, Opnd), +} + +#[derive(Debug, Clone)] +struct Inst { + dst: usize, + op: Op, +} + +#[derive(Debug, Clone)] +enum Seg { + Insts(Vec), + /// `if (cond) then else` (no else block when `triangle`), phis at the join. + Diamond { cond: Opnd, then_: Vec, else_: Vec, triangle: bool, phis: Vec<(usize, Opnd, Opnd)> }, + /// `switch (sel)` with one phi at the join. + Switch { sel: Opnd, cases: Vec<(u64, Vec, Opnd)>, default: (Vec, Opnd), phi: usize }, + /// `for (ctr = 0; ctr < trip; ctr++) { body; accs = next }`. + Loop { trip: Opnd, ctr: usize, ctr_next: usize, cond: usize, accs: Vec<(usize, Opnd, Opnd)>, body: Vec }, + /// `gs[lane] = v; barrier; dst = gs[(lane + k) & 31]`. + GsExchange { v: Opnd, k: u32, dst: usize }, + /// `cnt[i] = init(i); barrier; atomic op(cnt[lane & 7], v); cmpxchg on a + /// scratch slot; barrier; dst = cnt[(lane >> 2) & 7]`. + GsAtomic { op: RmwOp, v: Opnd, k: u32, dst: usize }, + /// `WaveReadLaneAt(v, lane)` (`None`: `WaveReadLaneFirst`). + Wave { v: Opnd, lane: Option, dst: usize }, + /// `rawBufferLoad` of `n` dwords from input slot `slot`. + Load { slot: u32, dsts: Vec }, +} + +struct Prog { + tys: Vec, + segs: Vec, + lane: usize, + outs: Vec, + gpu_safe: bool, +} + +// ------------------------------------------------------------ generator + +struct Gen { + r: Rng, + tys: Vec, + /// Float values: arithmetic steps since the integer conversion. + depth: Vec, + f64s: bool, + i64s: bool, + gpu_safe: bool, +} + +const INT_OPS: [BinOp; 13] = [ + BinOp::Add, + BinOp::Sub, + BinOp::Mul, + BinOp::UDiv, + BinOp::SDiv, + BinOp::URem, + BinOp::SRem, + BinOp::Shl, + BinOp::LShr, + BinOp::AShr, + BinOp::And, + BinOp::Or, + BinOp::Xor, +]; +const INT_PREDS: [Pred; 10] = [Pred::Eq, Pred::Ne, Pred::UGt, Pred::UGe, Pred::ULt, Pred::ULe, Pred::SGt, Pred::SGe, Pred::SLt, Pred::SLe]; +const F_PREDS: [Pred; 14] = [ + Pred::FOEq, + Pred::FOGt, + Pred::FOGe, + Pred::FOLt, + Pred::FOLe, + Pred::FONe, + Pred::FOrd, + Pred::FUno, + Pred::FUEq, + Pred::FUGt, + Pred::FUGe, + Pred::FULt, + Pred::FULe, + Pred::FUNe, +]; + +impl Gen { + fn val(&mut self, t: T, depth: u8) -> usize { + self.tys.push(t); + self.depth.push(depth); + self.tys.len() - 1 + } + fn of(&self, pool: &[usize], t: T) -> Vec { + pool.iter().copied().filter(|&v| self.tys[v] == t).collect() + } + fn fconst(&mut self, t: T) -> Opnd { + let x = self.r.below(127) as i32 - 63; + Opnd::C(t, if t == T::F32 { (x as f32).to_bits() as u64 } else { (x as f64).to_bits() }) + } + /// An operand of type `t`: a pool value or a constant. Floats only with + /// depth ≤ `max_depth`. + fn opnd(&mut self, pool: &[usize], t: T, max_depth: u8) -> Opnd { + let cands: Vec = self.of(pool, t).into_iter().filter(|&v| !t.is_float() || self.depth[v] <= max_depth).collect(); + if cands.is_empty() || self.r.chance(1, 5) { + return match t { + T::F32 | T::F64 => self.fconst(t), + _ => Opnd::C(t, self.r.bits(t.width())), + }; + } + Opnd::V(self.r.pick(&cands)) + } + fn odepth(&self, o: Opnd) -> u8 { + match o { + Opnd::V(v) => self.depth[v], + Opnd::C(..) => 0, + } + } + fn push(&mut self, out: &mut Vec, pool: &mut Vec, t: T, depth: u8, op: Op) -> Opnd { + let dst = self.val(t, depth); + out.push(Inst { dst, op }); + pool.push(dst); + Opnd::V(dst) + } + fn int_ty(&mut self) -> T { + if self.i64s && self.r.chance(1, 3) { + T::I64 + } else { + T::I32 + } + } + fn any_ty(&mut self) -> T { + let mut ts = vec![T::I1, T::I32, T::I32, T::F32]; + if self.i64s { + ts.push(T::I64); + } + if self.f64s { + ts.push(T::F64); + } + self.r.pick(&ts) + } + fn float_ty(&mut self) -> T { + if self.f64s && self.r.chance(1, 3) { + T::F64 + } else { + T::F32 + } + } + + /// One random instruction (plus guards keeping it well defined). + fn inst(&mut self, out: &mut Vec, pool: &mut Vec) { + match self.r.below(12) { + 0..=3 => { + let t = self.int_ty(); + let op = self.r.pick(&INT_OPS); + let a = self.opnd(pool, t, 0); + let mut b = self.opnd(pool, t, 0); + let w = t.width() as u64; + match op { + BinOp::Shl | BinOp::LShr | BinOp::AShr => b = self.push(out, pool, t, 0, Op::Bin(BinOp::And, b, Opnd::C(t, w - 1))), + BinOp::UDiv | BinOp::URem => b = self.push(out, pool, t, 0, Op::Bin(BinOp::Or, b, Opnd::C(t, 1))), + BinOp::SDiv | BinOp::SRem => { + let pos = self.push(out, pool, t, 0, Op::Bin(BinOp::And, b, Opnd::C(t, t.mask() >> 1))); + b = self.push(out, pool, t, 0, Op::Bin(BinOp::Or, pos, Opnd::C(t, 1))); + } + _ => {} + } + self.push(out, pool, t, 0, Op::Bin(op, a, b)); + } + 4 => { + let op = self.r.pick(&[BinOp::And, BinOp::Or, BinOp::Xor]); + let (a, b) = (self.opnd(pool, T::I1, 0), self.opnd(pool, T::I1, 0)); + self.push(out, pool, T::I1, 0, Op::Bin(op, a, b)); + } + 5 => { + let t = self.int_ty(); + let p = self.r.pick(&INT_PREDS); + let (a, b) = (self.opnd(pool, t, 0), self.opnd(pool, t, 0)); + self.push(out, pool, T::I1, 0, Op::Cmp(p, a, b)); + } + 6 => { + let t = self.any_ty(); + let c = self.opnd(pool, T::I1, 0); + let (a, b) = (self.opnd(pool, t, 2), self.opnd(pool, t, 2)); + let d = self.odepth(a).max(self.odepth(b)); + self.push(out, pool, t, d, Op::Select(c, a, b)); + } + 7 => { + let choices: &[(CastOp, T, T)] = &[ + (CastOp::ZExt, T::I1, T::I32), + (CastOp::SExt, T::I1, T::I32), + (CastOp::Trunc, T::I32, T::I1), + (CastOp::ZExt, T::I32, T::I64), + (CastOp::SExt, T::I32, T::I64), + (CastOp::Trunc, T::I64, T::I32), + (CastOp::SExt, T::I1, T::I64), + ]; + let (op, from, to) = self.r.pick(choices); + if !self.i64s && (from == T::I64 || to == T::I64) { + return; + } + let v = self.opnd(pool, from, 0); + self.push(out, pool, to, 0, Op::Cast(op, v, to)); + } + 8 => { + // int → float of a 6-bit value (signed: sign-extended from 6 bits). + let t = self.float_ty(); + let x = self.opnd(pool, T::I32, 0); + let (op, v) = if self.r.chance(1, 2) { + (CastOp::UIToFP, self.push(out, pool, T::I32, 0, Op::Bin(BinOp::And, x, Opnd::C(T::I32, 63)))) + } else { + let sh = self.push(out, pool, T::I32, 0, Op::Bin(BinOp::Shl, x, Opnd::C(T::I32, 26))); + (CastOp::SIToFP, self.push(out, pool, T::I32, 0, Op::Bin(BinOp::AShr, sh, Opnd::C(T::I32, 26)))) + }; + self.push(out, pool, t, 0, Op::Cast(op, v, t)); + } + 9 => { + let t = self.float_ty(); + match self.r.below(4) { + 0 | 1 => { + let op = self.r.pick(&[BinOp::Add, BinOp::Sub, BinOp::Mul]); + let (a, b) = (self.opnd(pool, t, 1), self.opnd(pool, t, 1)); + let flags = self.r.pick(&[fmf::NONE, fmf::NONE, fmf::FAST, fmf::NO_NANS | fmf::NO_INFS, fmf::NO_SIGNED_ZEROS]); + let d = self.odepth(a).max(self.odepth(b)) + 1; + // `nsz` / reassociation may flip the sign of a zero result. + if flags & (fmf::NO_SIGNED_ZEROS | fmf::UNSAFE_ALGEBRA) != 0 { + self.gpu_safe = false; + } + self.push(out, pool, t, d, Op::FBin(op, a, b, flags)); + } + 2 => { + let p = self.r.pick(&F_PREDS); + let (a, b) = (self.opnd(pool, t, 2), self.opnd(pool, t, 2)); + self.push(out, pool, T::I1, 0, Op::Cmp(p, a, b)); + } + _ => { + let (it, op) = if t == T::F32 { (T::I32, CastOp::BitCast) } else { (T::I64, CastOp::BitCast) }; + if it == T::I64 && !self.i64s { + return; + } + let v = self.opnd(pool, t, 2); + self.push(out, pool, it, 0, Op::Cast(op, v, it)); + } + } + } + 10 => { + if !self.f64s { + return; + } + if self.r.chance(1, 2) { + let v = self.opnd(pool, T::F32, 2); + let d = self.odepth(v); + self.push(out, pool, T::F64, d, Op::Cast(CastOp::FPExt, v, T::F64)); + } else { + let v = self.opnd(pool, T::F64, 2); + let d = self.odepth(v); + self.push(out, pool, T::F32, d, Op::Cast(CastOp::FPTrunc, v, T::F32)); + } + } + _ => { + if self.r.chance(1, 2) { + let op = self.r.pick(&[Binary::IMax, Binary::IMin, Binary::UMax, Binary::UMin]); + let t = self.int_ty(); + let (a, b) = (self.opnd(pool, t, 0), self.opnd(pool, t, 0)); + self.push(out, pool, t, 0, Op::DxBin(op, a, b)); + } else { + let u = self.r.pick(&[DxUn::Count, DxUn::Lo, DxUn::Hi, DxUn::Rev]); + let t = self.int_ty(); + let a = self.opnd(pool, t, 0); + let rt = if matches!(u, DxUn::Rev) { t } else { T::I32 }; + self.push(out, pool, rt, 0, Op::DxUn(u, a)); + } + } + } + } + + fn insts(&mut self, pool: &mut Vec, n: usize) -> Vec { + let mut out = Vec::new(); + for _ in 0..n { + self.inst(&mut out, pool); + } + out + } + + /// A value of type `t` from `pool` for a phi / output. + fn result(&mut self, pool: &[usize], t: T) -> Opnd { + self.opnd(pool, t, 2) + } +} + +fn generate(seed: u64) -> Prog { + let mut g = Gen { r: Rng::new(seed), tys: Vec::new(), depth: Vec::new(), f64s: false, i64s: false, gpu_safe: true }; + g.f64s = g.r.chance(1, 4); + g.i64s = g.r.chance(1, 2); + let lane = g.val(T::I32, 0); + let mut pool = vec![lane]; + let mut segs = Vec::new(); + // Inputs first. + for slot in 0..g.r.below(3) as u32 + 1 { + let n = g.r.pick(&[1usize, 2, 3, 4]); + let dsts: Vec = (0..n).map(|_| g.val(T::I32, 0)).collect(); + pool.extend(&dsts); + segs.push(Seg::Load { slot: slot % IN_SLOTS, dsts }); + } + let n_segs = if g.r.chance(1, 8) { g.r.below(40) + 10 } else { g.r.below(10) + 2 }; + for _ in 0..n_segs { + match g.r.below(9) { + 0..=2 => { + let n = g.r.below(12) + 1; + segs.push(Seg::Insts(g.insts(&mut pool, n))); + } + 3 => { + let cond = g.opnd(&pool, T::I1, 0); + let triangle = g.r.chance(1, 3); + let (mut tp, mut ep) = (pool.clone(), pool.clone()); + let n = g.r.below(6); + let then_ = g.insts(&mut tp, n); + let n = g.r.below(6); + let else_ = if triangle { Vec::new() } else { g.insts(&mut ep, n) }; + let mut phis = Vec::new(); + for _ in 0..g.r.below(3) + 1 { + let t = g.any_ty(); + let (a, b) = (g.result(&tp, t), g.result(&ep, t)); + let d = g.odepth(a).max(g.odepth(b)); + let dst = g.val(t, d); + phis.push((dst, a, b)); + } + pool.extend(phis.iter().map(|p| p.0)); + segs.push(Seg::Diamond { cond, then_, else_, triangle, phis }); + } + 4 => { + let raw = g.opnd(&pool, T::I32, 0); + let mut pre = Vec::new(); + let sel = if g.r.chance(1, 2) { g.push(&mut pre, &mut pool, T::I32, 0, Op::Bin(BinOp::And, raw, Opnd::C(T::I32, 7))) } else { raw }; + segs.push(Seg::Insts(pre)); + let t = g.any_ty(); + let mut vals: Vec = Vec::new(); + let mut cases = Vec::new(); + for _ in 0..g.r.below(5) + 1 { + let v = if g.r.chance(2, 3) { g.r.below(8) as u64 } else { g.r.bits(32) }; + if vals.contains(&v) { + continue; + } + vals.push(v); + let mut cp = pool.clone(); + let n = g.r.below(4); + let body = g.insts(&mut cp, n); + let out = g.result(&cp, t); + cases.push((v, body, out)); + } + let mut dp = pool.clone(); + let n = g.r.below(4); + let dbody = g.insts(&mut dp, n); + let dout = g.result(&dp, t); + let d = cases.iter().map(|c| g.odepth(c.2)).max().unwrap_or(0).max(g.odepth(dout)); + let phi = g.val(t, d); + pool.push(phi); + segs.push(Seg::Switch { sel, cases, default: (dbody, dout), phi }); + } + 5 => { + let x = g.opnd(&pool, T::I32, 0); + let mut pre = Vec::new(); + let trip = g.push(&mut pre, &mut pool, T::I32, 0, Op::Bin(BinOp::And, x, Opnd::C(T::I32, 7))); + segs.push(Seg::Insts(pre)); + let ctr = g.val(T::I32, 0); + let cond = g.val(T::I1, 0); + // Accumulators: integers only (float values would grow). + let mut accs: Vec<(usize, Opnd)> = Vec::new(); + for _ in 0..g.r.below(3) + 1 { + let t = if g.r.chance(1, 4) { T::I1 } else { g.int_ty() }; + let init = g.opnd(&pool, t, 0); + accs.push((g.val(t, 0), init)); + } + let mut bp = pool.clone(); + bp.push(ctr); + bp.extend(accs.iter().map(|a| a.0)); + let n = g.r.below(8) + 1; + let body = g.insts(&mut bp, n); + let ctr_next = g.val(T::I32, 0); + let accs = accs + .into_iter() + .map(|(dst, init)| { + let t = g.tys[dst]; + let next = g.opnd(&bp, t, 0); + (dst, init, next) + }) + .collect::>(); + pool.extend(accs.iter().map(|a| a.0)); + segs.push(Seg::Loop { trip, ctr, ctr_next, cond, accs, body }); + } + 6 => { + let v = g.opnd(&pool, T::I32, 0); + let dst = g.val(T::I32, 0); + pool.push(dst); + segs.push(Seg::GsExchange { v, k: g.r.below(32) as u32, dst }); + } + 7 => { + let op = g.r.pick(&[RmwOp::Add, RmwOp::Sub, RmwOp::And, RmwOp::Or, RmwOp::Xor, RmwOp::Max, RmwOp::Min, RmwOp::UMax, RmwOp::UMin]); + let v = g.opnd(&pool, T::I32, 0); + let dst = g.val(T::I32, 0); + pool.push(dst); + segs.push(Seg::GsAtomic { op, v, k: g.r.next() as u32, dst }); + } + _ => { + let t = g.r.pick(&[T::I32, T::I32, T::F32, T::I1]); + let v = g.opnd(&pool, t, 2); + let d = g.odepth(v); + let dst = g.val(t, d); + pool.push(dst); + let lane = if g.r.chance(3, 4) { Some(g.r.below(LANES) as u32) } else { None }; + segs.push(Seg::Wave { v, lane, dst }); + } + } + } + // Outputs: up to 12 distinct values, latest first. + let mut outs: Vec = Vec::new(); + for &v in pool.iter().rev() { + if outs.len() < 12 && (g.r.chance(1, 2) || outs.len() < 3) { + outs.push(v); + } + } + Prog { tys: g.tys, segs, lane, outs, gpu_safe: g.gpu_safe } +} + +// -------------------------------------------------------------- emitter + +struct Emit<'a> { + s: Shader, + p: &'a Prog, + vals: Vec>, + lane: Value, + gs_n: u32, +} + +impl Emit<'_> { + fn ty(&mut self, t: T) -> super::module::Ty { + match t { + T::I1 => self.s.m.i1(), + T::I32 => self.s.m.i32(), + T::I64 => self.s.m.i64(), + T::F32 => self.s.m.f32(), + T::F64 => self.s.m.f64(), + } + } + fn o(&mut self, o: Opnd) -> Value { + match o { + Opnd::V(v) => self.vals[v].unwrap_or_else(|| panic!("value {v} used before definition")), + Opnd::C(t, bits) => match t { + T::F32 => self.s.m.f32c(bits as u32), + T::F64 => { + let ty = self.s.m.f64(); + self.s.m.const_float(ty, bits) + } + _ => { + let ty = self.ty(t); + self.s.m.const_int(ty, bits) + } + }, + } + } + fn insts(&mut self, is: &[Inst]) { + for i in is { + let v = match &i.op { + Op::Bin(op, a, b) => { + let (a, b) = (self.o(*a), self.o(*b)); + self.s.m.bin(*op, a, b) + } + Op::FBin(op, a, b, f) => { + let (a, b) = (self.o(*a), self.o(*b)); + self.s.m.fbin(*op, a, b, *f) + } + Op::Cmp(p, a, b) => { + let (a, b) = (self.o(*a), self.o(*b)); + self.s.m.cmp(*p, a, b) + } + Op::Select(c, a, b) => { + let (c, a, b) = (self.o(*c), self.o(*a), self.o(*b)); + self.s.m.select(c, a, b) + } + Op::Cast(op, v, t) => { + let v = self.o(*v); + let t = self.ty(*t); + self.s.m.cast(*op, v, t) + } + Op::DxBin(op, a, b) => { + let (a, b) = (self.o(*a), self.o(*b)); + self.s.binary(*op, a, b) + } + Op::DxUn(u, a) => { + let a = self.o(*a); + match u { + DxUn::Count => self.s.bit_count(BitCount::Countbits, a), + DxUn::Lo => self.s.bit_count(BitCount::FirstbitLo, a), + DxUn::Hi => self.s.bit_count(BitCount::FirstbitHi, a), + DxUn::Rev => self.s.bfrev(a), + } + } + }; + self.vals[i.dst] = Some(v); + } + } + fn gs(&mut self, n: u64) -> GroupShared { + let i32 = self.s.m.i32(); + self.gs_n += 1; + let name = format!("gs{}", self.gs_n); + self.s.groupshared(&name, i32, n) + } + fn seg(&mut self, seg: &Seg, mem: RawUav) { + match seg { + Seg::Insts(is) => self.insts(is), + Seg::Diamond { cond, then_, else_, triangle, phis } => { + let c = self.o(*cond); + let pre = self.s.m.current_block(); + let tb = self.s.m.new_block(); + let eb = if *triangle { None } else { Some(self.s.m.new_block()) }; + let join = self.s.m.new_block(); + self.s.m.cond_br(c, tb, eb.unwrap_or(join)); + self.s.m.set_block(tb); + self.insts(then_); + let tv: Vec = phis.iter().map(|p| self.o(p.1)).collect(); + self.s.m.br(join); + let from_else = match eb { + Some(eb) => { + self.s.m.set_block(eb); + self.insts(else_); + self.s.m.br(join); + eb + } + None => pre, + }; + let ev: Vec = phis.iter().map(|p| self.o(p.2)).collect(); + self.s.m.set_block(join); + for (k, p) in phis.iter().enumerate() { + let t = self.ty(self.p.tys[p.0]); + let phi = self.s.m.phi(t); + self.s.m.add_incoming(phi, tv[k], tb); + self.s.m.add_incoming(phi, ev[k], from_else); + self.vals[p.0] = Some(phi); + } + } + Seg::Switch { sel, cases, default, phi } => { + let v = self.o(*sel); + let blocks: Vec<_> = cases.iter().map(|_| self.s.m.new_block()).collect(); + let db = self.s.m.new_block(); + let join = self.s.m.new_block(); + let cv: Vec<(Value, _)> = cases.iter().zip(&blocks).map(|(c, &b)| (self.s.m.i32c(c.0 as u32), b)).collect(); + self.s.m.switch(v, db, &cv); + let mut inc = Vec::new(); + for (c, &b) in cases.iter().zip(&blocks).chain(std::iter::once((&(0u64, default.0.clone(), default.1), &db))) { + self.s.m.set_block(b); + self.insts(&c.1); + let r = self.o(c.2); + self.s.m.br(join); + inc.push((r, b)); + } + self.s.m.set_block(join); + let t = self.ty(self.p.tys[*phi]); + let ph = self.s.m.phi(t); + for (r, b) in inc { + self.s.m.add_incoming(ph, r, b); + } + self.vals[*phi] = Some(ph); + } + Seg::Loop { trip, ctr, ctr_next, cond, accs, body } => { + let trip = self.o(*trip); + let inits: Vec = accs.iter().map(|a| self.o(a.1)).collect(); + let pre = self.s.m.current_block(); + let header = self.s.m.new_block(); + let bb = self.s.m.new_block(); + let exit = self.s.m.new_block(); + self.s.m.br(header); + self.s.m.set_block(header); + let i32 = self.s.m.i32(); + let cp = self.s.m.phi(i32); + self.vals[*ctr] = Some(cp); + let mut aps = Vec::new(); + for a in accs { + let t = self.ty(self.p.tys[a.0]); + let ph = self.s.m.phi(t); + self.vals[a.0] = Some(ph); + aps.push(ph); + } + let c = self.s.m.cmp(Pred::ULt, cp, trip); + self.vals[*cond] = Some(c); + self.s.m.cond_br(c, bb, exit); + self.s.m.set_block(bb); + self.insts(body); + let one = self.s.m.i32c(1); + let n = self.s.m.bin(BinOp::Add, cp, one); + self.vals[*ctr_next] = Some(n); + let nexts: Vec = accs.iter().map(|a| self.o(a.2)).collect(); + self.s.m.br(header); + let zero = self.s.m.i32c(0); + self.s.m.add_incoming(cp, zero, pre); + self.s.m.add_incoming(cp, n, bb); + for (k, ph) in aps.into_iter().enumerate() { + self.s.m.add_incoming(ph, inits[k], pre); + self.s.m.add_incoming(ph, nexts[k], bb); + } + self.s.m.set_block(exit); + } + Seg::GsExchange { v, k, dst } => { + let g = self.gs(LANES as u64); + let v = self.o(*v); + self.s.gs_store(g, self.lane, v); + self.s.barrier(barrier::GROUP_SYNC); + let kc = self.s.m.i32c(*k); + let i = self.s.m.bin(BinOp::Add, self.lane, kc); + let m = self.s.m.i32c(LANES as u32 - 1); + let i = self.s.m.bin(BinOp::And, i, m); + let r = self.s.gs_load(g, i); + self.vals[*dst] = Some(r); + } + Seg::GsAtomic { op, v, k, dst } => { + let g = self.gs(9); + let v = self.o(*v); + let seven = self.s.m.i32c(7); + let idx = self.s.m.bin(BinOp::And, self.lane, seven); + let kc = self.s.m.i32c(*k); + let init = self.s.m.bin(BinOp::Mul, idx, kc); + let init = self.s.m.bin(BinOp::Xor, init, kc); + self.s.gs_store(g, idx, init); + self.s.barrier(barrier::GROUP_SYNC); + // `atomicrmw sub` as an add of the negation, the form DXC and the translator + // emit: NVIDIA Blackwell drivers refuse pipelines with a groupshared + // `atomicrmw sub` (CreateComputePipelineState E_OUTOFMEMORY). + let (op, v) = if *op == RmwOp::Sub { + let zero = self.s.m.i32c(0); + (RmwOp::Add, self.s.m.bin(BinOp::Sub, zero, v)) + } else { + (*op, v) + }; + self.s.gs_atomic(op, g, idx, v); + let eight = self.s.m.i32c(8); + self.s.gs_cmpxchg(g, eight, v, init); + self.s.barrier(barrier::GROUP_SYNC); + let two = self.s.m.i32c(2); + let i = self.s.m.bin(BinOp::LShr, self.lane, two); + let i = self.s.m.bin(BinOp::And, i, seven); + let r = self.s.gs_load(g, i); + self.vals[*dst] = Some(r); + } + Seg::Wave { v, lane, dst } => { + let v = self.o(*v); + let r = match lane { + Some(l) => { + let lc = self.s.m.i32c(*l); + self.s.wave_read_lane_at(v, lc) + } + None => self.s.wave_read_lane_first(v), + }; + self.vals[*dst] = Some(r); + } + Seg::Load { slot, dsts } => { + let off = self.slot(*slot); + let mask = (1u8 << dsts.len()) - 1; + let r = self.s.raw_load(mem, off, mask); + for (d, v) in dsts.iter().zip(r) { + self.vals[*d] = Some(v); + } + } + } + } + /// Byte offset of dword `64·k + lane`. + fn slot(&mut self, k: u32) -> Value { + let base = self.s.m.i32c(64 * k); + let i = self.s.m.bin(BinOp::Add, base, self.lane); + let two = self.s.m.i32c(2); + self.s.m.bin(BinOp::Shl, i, two) + } +} + +/// Output words of value `v`: one dword, two for 64-bit values (lo, hi). +fn out_words(t: T) -> usize { + if t.width() == 64 { + 2 + } else { + 1 + } +} + +fn emit(p: &Prog) -> Vec { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let res = s.raw_uav(1, 0); + let mem = s.raw_uav(2, 0); + let lane = s.flattened_thread_id_in_group(); + let mut e = Emit { s, p, vals: vec![None; p.tys.len()], lane, gs_n: 0 }; + e.vals[p.lane] = Some(lane); + for seg in &p.segs { + e.seg(seg, mem); + } + let mut k = 0u32; + let i32 = e.s.m.i32(); + let i64 = e.s.m.i64(); + for &o in &p.outs { + let v = e.vals[o].unwrap(); + let words = match p.tys[o] { + T::I1 => vec![e.s.m.cast(CastOp::ZExt, v, i32)], + T::I32 => vec![v], + T::F32 => vec![e.s.m.bitcast(v, i32)], + T::I64 | T::F64 => { + let v = e.s.m.bitcast(v, i64); + let lo = e.s.m.cast(CastOp::Trunc, v, i32); + let c = e.s.m.const_int(i64, 32); + let hi = e.s.m.bin(BinOp::LShr, v, c); + vec![lo, e.s.m.cast(CastOp::Trunc, hi, i32)] + } + }; + for w in words { + let off = e.slot(k); + e.s.raw_store(res, off, &[w]); + k += 1; + } + } + // A four-component store (stride 4 dwords per lane) of lane-derived words. + let n = k.min(4) as u32; + if n > 0 { + let base = e.s.m.i32c(64 * k); + let four = e.s.m.i32c(4); + let i = e.s.m.bin(BinOp::Mul, lane, four); + let i = e.s.m.bin(BinOp::Add, base, i); + let two = e.s.m.i32c(2); + let off = e.s.m.bin(BinOp::Shl, i, two); + let words: Vec = (0..n) + .map(|c| { + let cc = e.s.m.i32c(c * 0x1111); + e.s.m.bin(BinOp::Xor, lane, cc) + }) + .collect(); + e.s.raw_store(res, off, &words); + } + e.s.finish([LANES as u32, 1, 1], Some(LANES as u32)) +} + +// ----------------------------------------------------------- interpreter + +fn sext(v: u64, w: u32) -> i64 { + if w == 64 { + v as i64 + } else { + ((v << (64 - w)) as i64) >> (64 - w) + } +} + +fn f(t: T, bits: u64) -> f64 { + if t == T::F32 { + f32::from_bits(bits as u32) as f64 + } else { + f64::from_bits(bits) + } +} + +fn fbits(t: T, x: f64) -> u64 { + if t == T::F32 { + (x as f32).to_bits() as u64 + } else { + x.to_bits() + } +} + +struct Interp<'a> { + p: &'a Prog, + env: Vec>, +} + +impl Interp<'_> { + fn o(&self, l: usize, o: Opnd) -> u64 { + match o { + Opnd::V(v) => self.env[l][v], + Opnd::C(t, b) => b & t.mask(), + } + } + fn ot(&self, o: Opnd) -> T { + match o { + Opnd::V(v) => self.p.tys[v], + Opnd::C(t, _) => t, + } + } + fn insts(&mut self, l: usize, is: &[Inst]) { + for i in is { + let t = self.p.tys[i.dst]; + let r = match &i.op { + Op::Bin(op, a, b) => { + let (x, y) = (self.o(l, *a), self.o(l, *b)); + let w = t.width(); + let (sx, sy) = (sext(x, w), sext(y, w)); + match op { + BinOp::Add => x.wrapping_add(y), + BinOp::Sub => x.wrapping_sub(y), + BinOp::Mul => x.wrapping_mul(y), + BinOp::UDiv => x / y, + BinOp::URem => x % y, + BinOp::SDiv => sx.wrapping_div(sy) as u64, + BinOp::SRem => sx.wrapping_rem(sy) as u64, + BinOp::Shl => x << y, + BinOp::LShr => x >> y, + BinOp::AShr => (sx >> y) as u64, + BinOp::And => x & y, + BinOp::Or => x | y, + BinOp::Xor => x ^ y, + } + } + Op::FBin(op, a, b, _) => { + let (x, y) = (f(t, self.o(l, *a)), f(t, self.o(l, *b))); + let r = match op { + BinOp::Add => x + y, + BinOp::Sub => x - y, + BinOp::Mul => x * y, + _ => unreachable!(), + }; + fbits(t, r) + } + Op::Cmp(p, a, b) => { + let at = self.ot(*a); + let (x, y) = (self.o(l, *a), self.o(l, *b)); + let r = if at.is_float() { + let (x, y) = (f(at, x), f(at, y)); + let uno = x.is_nan() || y.is_nan(); + let (lt, eq, gt) = (x < y, x == y, x > y); + match p { + Pred::FOEq => eq, + Pred::FOGt => gt, + Pred::FOGe => gt || eq, + Pred::FOLt => lt, + Pred::FOLe => lt || eq, + Pred::FONe => lt || gt, + Pred::FOrd => !uno, + Pred::FUno => uno, + Pred::FUEq => uno || eq, + Pred::FUGt => uno || gt, + Pred::FUGe => uno || gt || eq, + Pred::FULt => uno || lt, + Pred::FULe => uno || lt || eq, + Pred::FUNe => uno || lt || gt, + _ => unreachable!(), + } + } else { + let w = at.width(); + let (sx, sy) = (sext(x, w), sext(y, w)); + match p { + Pred::Eq => x == y, + Pred::Ne => x != y, + Pred::UGt => x > y, + Pred::UGe => x >= y, + Pred::ULt => x < y, + Pred::ULe => x <= y, + Pred::SGt => sx > sy, + Pred::SGe => sx >= sy, + Pred::SLt => sx < sy, + Pred::SLe => sx <= sy, + _ => unreachable!(), + } + }; + r as u64 + } + Op::Select(c, a, b) => { + if self.o(l, *c) != 0 { + self.o(l, *a) + } else { + self.o(l, *b) + } + } + Op::Cast(op, v, _) => { + let ft = self.ot(*v); + let x = self.o(l, *v); + match op { + CastOp::ZExt | CastOp::Trunc | CastOp::BitCast => x, + CastOp::SExt => sext(x, ft.width()) as u64, + CastOp::UIToFP => fbits(t, x as f64), + CastOp::SIToFP => fbits(t, sext(x, ft.width()) as f64), + CastOp::FPExt | CastOp::FPTrunc => fbits(t, f(ft, x)), + _ => unreachable!(), + } + } + Op::DxBin(op, a, b) => { + let (x, y) = (self.o(l, *a), self.o(l, *b)); + let w = t.width(); + let (sx, sy) = (sext(x, w), sext(y, w)); + match op { + Binary::IMax => sx.max(sy) as u64, + Binary::IMin => sx.min(sy) as u64, + Binary::UMax => x.max(y), + Binary::UMin => x.min(y), + _ => unreachable!(), + } + } + Op::DxUn(u, a) => { + let at = self.ot(*a); + let x = self.o(l, *a); + let w = at.width(); + match u { + DxUn::Count => x.count_ones() as u64, + DxUn::Lo => { + if x == 0 { + u32::MAX as u64 + } else { + x.trailing_zeros() as u64 + } + } + DxUn::Hi => { + if x == 0 { + u32::MAX as u64 + } else { + (x.leading_zeros() - (64 - w)) as u64 + } + } + DxUn::Rev => x.reverse_bits() >> (64 - w), + } + } + }; + self.env[l][i.dst] = r & t.mask(); + } + } + + fn seg(&mut self, seg: &Seg, mem: &[u32]) { + match seg { + Seg::Insts(is) => (0..LANES).for_each(|l| self.insts(l, is)), + Seg::Diamond { cond, then_, else_, phis, .. } => { + for l in 0..LANES { + let taken = self.o(l, *cond) != 0; + self.insts(l, if taken { then_ } else { else_ }); + let vs: Vec = phis.iter().map(|p| self.o(l, if taken { p.1 } else { p.2 })).collect(); + for (p, v) in phis.iter().zip(vs) { + self.env[l][p.0] = v; + } + } + } + Seg::Switch { sel, cases, default, phi } => { + for l in 0..LANES { + let v = self.o(l, *sel); + let (body, out) = cases.iter().find(|c| c.0 & 0xffff_ffff == v).map_or((&default.0, default.1), |c| (&c.1, c.2)); + self.insts(l, body); + self.env[l][*phi] = self.o(l, out); + } + } + Seg::Loop { trip, ctr, accs, body, .. } => { + for l in 0..LANES { + let trip = self.o(l, *trip); + let mut vals: Vec = accs.iter().map(|a| self.o(l, a.1)).collect(); + let mut i = 0u64; + loop { + self.env[l][*ctr] = i; + for (a, v) in accs.iter().zip(&vals) { + self.env[l][a.0] = *v; + } + if i >= trip { + break; + } + self.insts(l, body); + vals = accs.iter().map(|a| self.o(l, a.2)).collect(); + i += 1; + } + } + } + Seg::GsExchange { v, k, dst } => { + let vs: Vec = (0..LANES).map(|l| self.o(l, *v)).collect(); + for l in 0..LANES { + self.env[l][*dst] = vs[(l + *k as usize) & (LANES - 1)]; + } + } + Seg::GsAtomic { op, v, k, dst } => { + let mut cnt: Vec = (0..8u32).map(|i| i.wrapping_mul(*k) ^ *k).collect(); + for l in 0..LANES { + let x = self.o(l, *v) as u32; + let c = &mut cnt[l & 7]; + *c = match op { + RmwOp::Add => c.wrapping_add(x), + RmwOp::Sub => c.wrapping_sub(x), + RmwOp::And => *c & x, + RmwOp::Or => *c | x, + RmwOp::Xor => *c ^ x, + RmwOp::Max => (*c as i32).max(x as i32) as u32, + RmwOp::Min => (*c as i32).min(x as i32) as u32, + RmwOp::UMax => (*c).max(x), + RmwOp::UMin => (*c).min(x), + _ => unreachable!(), + }; + } + for l in 0..LANES { + self.env[l][*dst] = cnt[(l >> 2) & 7] as u64; + } + } + Seg::Wave { v, lane, dst } => { + let src = lane.unwrap_or(0) as usize; + let x = self.o(src, *v); + for l in 0..LANES { + self.env[l][*dst] = x; + } + } + Seg::Load { slot, dsts } => { + for l in 0..LANES { + for (c, d) in dsts.iter().enumerate() { + self.env[l][*d] = mem[64 * *slot as usize + l + c] as u64; + } + } + } + } + } +} + +/// Expected `res` dwords: `(index, value)` pairs. +fn interpret(p: &Prog, mem: &[u32]) -> Vec<(usize, u32)> { + let mut it = Interp { p, env: vec![vec![0; p.tys.len()]; LANES] }; + for l in 0..LANES { + it.env[l][p.lane] = l as u64; + } + for seg in &p.segs { + it.seg(seg, mem); + } + let mut out = Vec::new(); + let mut k = 0; + for &o in &p.outs { + let n = out_words(p.tys[o]); + for wi in 0..n { + for l in 0..LANES { + let v = it.env[l][o]; + out.push((64 * k + l, (v >> (32 * wi)) as u32)); + } + k += 1; + } + } + for l in 0..LANES { + for c in 0..k.min(4) { + out.push((64 * k + 4 * l + c, (l as u32) ^ (c as u32 * 0x1111))); + } + } + out +} + +fn inputs(seed: u64) -> Vec { + let mut r = Rng::new(seed ^ 0xDEAD_BEEF); + (0..64 * IN_SLOTS as usize).map(|_| r.bits(32) as u32).collect() +} + +// ---------------------------------------------------------------- tests + +fn check_valid(seed: u64, c: &[u8]) { + if let Err(e) = validate::validate(c) { + let dis = validate::disassemble(c).unwrap_or_else(|d| d); + panic!("seed {seed}: validator rejected the module:\n{e}\n--- disassembly ---\n{dis}"); + } +} + +fn run_seeds(range: std::ops::Range, gpu_every: u64) -> (usize, usize) { + let gpu = matches!(runner::wave32_supported(), Ok(true)); + let mut ran = 0; + // GPU-run containers whose digest takes each final-block layout. + let mut tails = [0usize; 2]; + for seed in range.clone() { + let p = generate(seed); + let c = emit(&p); + check_valid(seed, &c); + if gpu && p.gpu_safe && seed % gpu_every == 0 { + let mem = inputs(seed); + let r = runner::run_with(&c, &runner::KernelState::default(), &mem, &[], &[]).unwrap_or_else(|e| panic!("seed {seed}: GPU run ({} bytes, {} instructions): {e}", c.len(), instructions(&c))); + for (i, v) in interpret(&p, &mem) { + if r.raw[i] != v { + let dis = validate::disassemble(&c).unwrap_or_else(|d| d); + panic!("seed {seed}: res[{i}] = {:#x}, CPU {v:#x}\nprogram: {:#?}\n--- disassembly ---\n{dis}", r.raw[i], p.segs); + } + } + ran += 1; + tails[((c.len() - 20) % 64 >= 56) as usize] += 1; + } + } + eprintln!("fuzz seeds {range:?}: validated {}, GPU-compared {ran} (digest tails < 56 / >= 56: {tails:?})", range.clone().count()); + (range.count(), ran) +} + +/// Instructions in the module's disassembly (for failure reports). +fn instructions(c: &[u8]) -> usize { + validate::disassemble(c).map(|d| d.lines().filter(|l| l.starts_with(" ") && !l.trim_start().starts_with(';')).count()).unwrap_or(0) +} + +#[test] +fn fuzz_validate_and_gpu_0() { + run_seeds(0..500, 1); +} +#[test] +fn fuzz_validate_and_gpu_1() { + run_seeds(500..1000, 1); +} +#[test] +fn fuzz_validate_and_gpu_2() { + run_seeds(1000..1500, 1); +} +#[test] +fn fuzz_validate_and_gpu_3() { + run_seeds(1500..2000, 1); +} +/// Prints the disassembly of one generated module (`FUZZ_SEED=n`). +#[test] +#[ignore] +fn debug_seed() { + let seed: u64 = std::env::var("FUZZ_SEED").map(|s| s.parse().unwrap()).unwrap_or(0); + let p = generate(seed); + let c = emit(&p); + println!("{}", validate::disassemble(&c).unwrap()); + println!("{:?}", validate::validate(&c)); + println!("program: {:#?} +outs: {:?}", p.segs, p.outs); + if let Ok(w) = std::env::var("FUZZ_WATCH") { + let i: usize = w.parse().unwrap(); + let mem = inputs(seed); + let exp = interpret(&p, &mem).into_iter().find(|&(j, _)| j == i); + println!("watch res[{i}]: CPU {exp:x?}; mem[0..70] = {:x?}", &mem[..70.min(mem.len())]); + } + println!("seed {seed}: {} bytes, {} instructions, gpu_safe {}", c.len(), instructions(&c), p.gpu_safe); + if p.gpu_safe && matches!(runner::wave32_supported(), Ok(true)) { + let mem = inputs(seed); + match runner::run_with(&c, &runner::KernelState::default(), &mem, &[], &[]) { + Ok(r) => { + let bad = interpret(&p, &mem).into_iter().filter(|&(i, v)| r.raw[i] != v).count(); + println!("GPU run: {bad} mismatching results"); + } + Err(e) => println!("GPU run: {e}"), + } + } +} + +/// Regression: i64 / double instructions built with plain [`super::module::Module`] +/// methods (not the `Shader` helpers) must still set `Int64Ops`, `Doubles` +/// and — for int ↔ double conversions and double division — +/// `DoubleExtensions` ("Flags must match usage" otherwise). +#[test] +fn shader_flags_follow_plain_instruction_types() { + type Build = fn(&mut Shader, Value) -> Value; + let cases: [Build; 4] = [ + |s, x| { + let i64 = s.m.i64(); + let w = s.m.cast(CastOp::ZExt, x, i64); + let p = s.m.bin(BinOp::Mul, w, w); + let i32 = s.m.i32(); + s.m.cast(CastOp::Trunc, p, i32) + }, + |s, x| { + let (f32, f64) = (s.m.f32(), s.m.f64()); + let f = s.m.bitcast(x, f32); + let d = s.m.cast(CastOp::FPExt, f, f64); + let d = s.m.fbin(BinOp::Add, d, d, 0); + let f = s.m.cast(CastOp::FPTrunc, d, f32); + let i32 = s.m.i32(); + s.m.bitcast(f, i32) + }, + |s, x| { + let f64 = s.m.f64(); + let d = s.m.cast(CastOp::UIToFP, x, f64); + let i32 = s.m.i32(); + s.m.cast(CastOp::FPToSI, d, i32) + }, + |s, x| { + let (f32, f64) = (s.m.f32(), s.m.f64()); + let f = s.m.bitcast(x, f32); + let d = s.m.cast(CastOp::FPExt, f, f64); + let q = s.m.fbin(BinOp::SDiv, d, d, 0); + let f = s.m.cast(CastOp::FPTrunc, q, f32); + let i32 = s.m.i32(); + s.m.bitcast(f, i32) + }, + ]; + for (i, build) in cases.iter().enumerate() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let res = s.raw_uav(1, 0); + let lane = s.flattened_thread_id_in_group(); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, lane, two); + let v = build(&mut s, lane); + s.raw_store(res, off, &[v]); + let c = s.finish([32, 1, 1], None); + check_valid(i as u64, &c); + } +} + +/// Hand-reduced forms of the fuzz seeds that fail only on AMD (RDNA4, +/// amdxc64), for bisecting on that hardware: `cargo test -p xcl --lib +/// gpu::dxil::fuzz_tests::amd_reduced_seeds -- --ignored --nocapture`. +/// Prints one PASS / FAIL line per variant (first mismatching dword) and +/// panics at the end if any failed. `T::I32` value 0 is the lane index. +#[test] +#[ignore] +fn amd_reduced_seeds() { + use Opnd::{C, V}; + let gpu = matches!(runner::wave32_supported(), Ok(true)); + if !gpu { + eprintln!("SKIPPED: no wave32 GPU"); + return; + } + let ins = |dst, op| Inst { dst, op }; + // Seed 722 shape: x = in[lane]; w = WaveReadLaneFirst(x); a phi over a + // divergent switch on x where the default and `case 1` take w (so a lane + // alone in `case 1` must still see lane 0's x). + let s722 = |countbits_case: bool| { + let mut cases = vec![(1u64, vec![], V(3)), (2, vec![], V(0))]; + let mut tys = vec![T::I32, T::I32, T::I32, T::I32, T::I32]; + if countbits_case { + cases.push((227944867, vec![ins(5, Op::DxUn(DxUn::Count, C(T::I64, 10215786766456627865)))], V(1))); + tys.push(T::I32); + } + Prog { tys, segs: vec![Seg::Load { slot: 0, dsts: vec![1, 2] }, Seg::Wave { v: V(1), lane: None, dst: 3 }, Seg::Switch { sel: V(1), cases, default: (vec![], V(3)), phi: 4 }], lane: 0, outs: vec![4], gpu_safe: true } + }; + // Seed 1599 shape: c = Countbits.i64(2); out ((c >> (lane & 31)) | Bfrev(c)) & 31. + let s1599 = |dynamic: bool, rev: bool| { + let src = if dynamic { V(2) } else { C(T::I64, 2) }; + let mut insts = vec![]; + if dynamic { + // in[lane] & 0 | 2, as i64 (2 on every lane, unknown to the driver). + insts.push(ins(6, Op::Bin(BinOp::And, V(1), C(T::I32, 0)))); + insts.push(ins(7, Op::Bin(BinOp::Or, V(6), C(T::I32, 2)))); + insts.push(ins(2, Op::Cast(CastOp::ZExt, V(7), T::I64))); + } + insts.push(ins(3, Op::DxUn(DxUn::Count, src))); + insts.push(ins(8, Op::Bin(BinOp::And, V(0), C(T::I32, 31)))); + insts.push(ins(9, Op::Bin(BinOp::LShr, V(3), V(8)))); + insts.push(ins(4, Op::DxUn(DxUn::Rev, V(3)))); + insts.push(ins(10, Op::Bin(BinOp::Or, V(9), V(4)))); + insts.push(ins(5, Op::Bin(BinOp::And, V(10), C(T::I32, 31)))); + let tys = vec![T::I32, T::I32, T::I64, T::I32, T::I32, T::I32, T::I32, T::I32, T::I32, T::I32, T::I32]; + let outs = if rev { vec![5, 3, 9, 4] } else { vec![3] }; + Prog { tys, segs: vec![Seg::Load { slot: 0, dsts: vec![1] }, Seg::Insts(insts)], lane: 0, outs, gpu_safe: true } + }; + let progs = [ + ("722 switch + WaveReadLaneFirst", s722(false)), + ("722 switch + WaveReadLaneFirst + Countbits.i64 case", s722(true)), + ("1599 Countbits.i64(const 2)", s1599(false, false)), + ("1599 Countbits.i64(const 2) -> shift / Bfrev", s1599(false, true)), + ("1599 Countbits.i64(dynamic 2) -> shift / Bfrev", s1599(true, true)), + ]; + let mut failed = 0; + for (name, p) in &progs { + let c = emit(p); + check_valid(0, &c); + let mem = inputs(722); + let r = runner::run_with(&c, &runner::KernelState::default(), &mem, &[], &[]).unwrap_or_else(|e| panic!("{name}: GPU run: {e}")); + match interpret(p, &mem).into_iter().find(|&(i, v)| r.raw[i] != v) { + None => eprintln!("PASS {name}"), + Some((i, v)) => { + failed += 1; + eprintln!("FAIL {name}: res[{i}] = {:#x}, CPU {v:#x}\n{}", r.raw[i], validate::disassemble(&c).unwrap_or_else(|d| d)); + } + } + } + for seed in [722u64, 1599] { + let p = generate(seed); + let c = emit(&p); + let mem = inputs(seed); + let r = runner::run_with(&c, &runner::KernelState::default(), &mem, &[], &[]).unwrap_or_else(|e| panic!("seed {seed}: GPU run: {e}")); + let bad = interpret(&p, &mem).into_iter().filter(|&(i, v)| r.raw[i] != v).count(); + eprintln!("{} full seed {seed}: {bad} mismatching dwords", if bad == 0 { "PASS" } else { "FAIL" }); + failed += (bad != 0) as usize; + } + assert_eq!(failed, 0, "{failed} AMD repro variants failed"); +} diff --git a/crates/xcl/src/gpu/dxil/geometry_tests.rs b/crates/xcl/src/gpu/dxil/geometry_tests.rs new file mode 100644 index 0000000000..57d4cce9a9 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/geometry_tests.rs @@ -0,0 +1,168 @@ +//! Geometry mode in the direct translator: a GS with per-lane loops and cuts, validated in +//! every form and its records compared on the GPU with a model (and the HLSL path's native form). + +use super::kernel::{translate_geometry, KernelOptions}; +use crate::gpu::dxbc::SigElement; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::{dxc, mesh_passthrough, runner, translate_geometry as hlsl_geometry, GsInterface, IO_GS_PRIMS, MESH_HEADER}; + +fn sig(name: &str, sv: u32, reg: u32, ty: u32) -> SigElement { + SigElement { name: name.into(), index: 0, system_value: sv, component_type: ty, register: reg, mask: 0xF, rw_mask: 0xF, stream: 0 } +} + +/// ES: nothing but the jump into the GS. GS: EXEC = this wave's primitives, each lane +/// emits 2..5 vertices in a loop (EXEC narrowing per lane, `s_cbranch_execz` out), a cut +/// after the second vertex; vertex = (lane, k, primitive, 1.0), (count, lane, lane, lane). +fn branchy_program() -> (Vec, GsInterface) { + let e = |n: &str, enc: &str, f: &[(&str, u64)], lit: Option| encode(n, enc, f, lit).unwrap_or_else(|x| panic!("{n}: {x}")); + const V: u64 = 256; + let es = e("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 6)], None); + let mut gs: Vec> = Vec::new(); + gs.push(e("S_BFE_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x80008))); + gs.push(e("S_BFM_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 0), ("SSRC1", 128)], None)); + gs.push(e("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", 193), ("SRC1", 128)], None)); + gs.push(e("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", 193), ("SRC1", V + 20)], None)); + gs.push(e("V_AND_B32", "ENC_VOP2", &[("VDST", 21), ("SRC0", 131), ("VSRC1", 2)], None)); // prim & 3 + gs.push(e("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 21), ("SRC0", 130), ("VSRC1", 21)], None)); // + 2 + gs.push(e("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 50), ("SRC0", V + 20), ("SRC1", 255), ("SRC2", 2)], Some(160))); + gs.push(e("V_MOV_B32", "ENC_VOP1", &[("VDST", 52), ("SRC0", 242)], None)); // 1.0 + gs.push(e("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 128)], None)); + let top = gs.len(); + gs.push(e("V_CMP_LT_U32", "ENC_VOPC", &[("SRC0", 4), ("VSRC1", 21)], None)); + gs.push(e("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)], None)); + let execz = gs.len(); + gs.push(Vec::new()); // s_cbranch_execz end + gs.push(e("V_MOV_B32", "ENC_VOP1", &[("VDST", 51), ("SRC0", 4)], None)); + gs.push(e("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 50), ("DATA0", 20), ("DATA1", 51), ("OFFSET0", 0), ("OFFSET1", 1)], None)); + gs.push(e("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 50), ("DATA0", 2), ("DATA1", 52), ("OFFSET0", 2), ("OFFSET1", 3)], None)); + gs.push(e("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 50), ("DATA0", 21), ("DATA1", 20), ("OFFSET0", 4), ("OFFSET1", 5)], None)); + gs.push(e("DS_WRITE2_B32", "ENC_DS", &[("ADDR", 50), ("DATA0", 20), ("DATA1", 20), ("OFFSET0", 6), ("OFFSET1", 7)], None)); + gs.push(e("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 50), ("SRC0", 160), ("VSRC1", 50)], None)); + gs.push(e("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 0x22)], None)); // emit + gs.push(e("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 129)], None)); + let skip = gs.len(); + gs.push(Vec::new()); // s_cbranch_scc0 past the cut + gs.push(e("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 0x12)], None)); // cut + let after_cut = gs.len(); + gs.push(e("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)], None)); + let back = gs.len(); + gs.push(Vec::new()); // s_branch top + let end = gs.len(); + gs.push(e("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 0x3)], None)); + gs.push(e("S_ENDPGM", "ENC_SOPP", &[], None)); + let pc = |gs: &Vec>, i: usize| gs[..i].iter().map(|p| if p.is_empty() { 4 } else { p.len() }).sum::() as i64; + let br = |gs: &Vec>, name: &str, at: usize, to: usize| { + let rel = (pc(gs, to) - pc(gs, at) - 4) / 4; + e(name, "ENC_SOPP", &[("SIMM16", rel as i16 as u16 as u64)], None) + }; + gs[execz] = br(&gs, "S_CBRANCH_EXECZ", execz, end); + gs[skip] = br(&gs, "S_CBRANCH_SCC0", skip, after_cut); + gs[back] = br(&gs, "S_BRANCH", back, top); + let g = GsInterface { + es_inputs: vec![], + es_outputs: vec![sig("SV_Position", 1, 0, 3)], + outputs: vec![sig("SV_Position", 1, 0, 3), sig("TEXCOORD", 0, 1, 1)], + max_vertex_count: 5, + gs_start: Some(es.len() as u64), + }; + let mut code = es; + code.extend(gs.concat()); + (code, g) +} + +fn opts(split: bool, windows: u32) -> KernelOptions { + KernelOptions { wave64: true, split, mem_windows: windows, sampler_base: 0 } +} + +/// Both forms, ES alone, GS alone and four memory windows translate and validate. +#[test] +fn geometry_forms_validate() { + let (code, g) = branchy_program(); + for split in [false, true] { + translate_geometry(&code, opts(split, 1), &g).unwrap_or_else(|e| panic!("split {split}: {e}")); + translate_geometry(&code, opts(split, 4), &g).unwrap_or_else(|e| panic!("split {split}, 4 windows: {e}")); + let es_alone = GsInterface { gs_start: None, ..g.clone() }; + translate_geometry(&code[..4], opts(split, 1), &es_alone).unwrap_or_else(|e| panic!("ES alone: {e}")); + let gs_alone = GsInterface { gs_start: Some(0), ..g.clone() }; + translate_geometry(&code[4..], opts(split, 1), &gs_alone).unwrap_or_else(|e| panic!("GS alone: {e}")); + } +} + +/// The records of `branchy_program` for `prims` primitives: (group, record dwords). +fn expected_records(g: &GsInterface, prims: usize) -> Vec { + let rec = g.record(); + let (rd, vd, maxv) = (rec.record_dwords(), rec.vert_dwords(), rec.max_vertices as usize); + let groups = prims.div_ceil(21); + let mut out = vec![0u32; groups * rd]; + for grp in 0..groups { + let r = &mut out[grp * rd..(grp + 1) * rd]; + let (mut vb, mut tb) = (0usize, 0usize); + for lane in 0..21.min(prims - grp * 21) { + let p = grp * 21 + lane; + let n = (p & 3) + 2; + for k in 0..n { + let v = MESH_HEADER + (vb + k) * vd; + r[v..v + 8].copy_from_slice(&[lane as u32, k as u32, p as u32, 0x3F80_0000, n as u32, lane as u32, lane as u32, lane as u32]); + } + if n == 5 { + let b = vb as u32; + r[MESH_HEADER + maxv * vd + tb] = (b + 2) | (b + 3) << 10 | (b + 4) << 20; + tb += 1; + } + vb += n; + } + r[0] = vb as u32; + r[1] = tb as u32; + } + out +} + +/// The direct translation's records (GPU, mesh pass-through included) for per-lane loops, +/// cuts and a partial last group, against a model of the program, in the split form and +/// (64-lane hardware) the native one; the HLSL path's records in the same forms must agree too. +#[test] +fn gpu_geometry_direct_records() { + if runner::adapter().is_err() || runner::wave64_programs_supported() != Ok(true) || dxc::location().is_err() || runner::mesh_shaders_supported() != Ok(true) { + runner::skip_test("no GPU / DXC / mesh shaders"); + return; + } + let (code, g) = branchy_program(); + let rec = g.record(); + let msb = dxc::compile(&mesh_passthrough(&rec), "main", "ms_6_6", &[]).unwrap(); + let ps_src = "struct V { float4 pos : SV_Position; nointerpolation uint4 p0 : TEXCOORD0; };\nfloat4 main(V v) : SV_Target0 { return float4(1.0, (float)v.p0.y, 0.0, 1.0); }\n"; + let ps = dxc::compile(ps_src, "main", "ps_6_6", &[]).unwrap(); + let prims = 25; + let mut io = vec![0u32; 128]; + io[IO_GS_PRIMS] = prims as u32; + let mem = vec![0u32; 64]; + let want = expected_records(&g, prims); + let check = |what: &str, got: &[u32]| { + // the vertex / triangle slots past the counts are not written + let rd = rec.record_dwords(); + let (vd, maxv) = (rec.vert_dwords(), rec.max_vertices as usize); + let diff: Vec = (0..want.len()) + .filter(|&i| { + let (grp, o) = (i / rd, i % rd); + let r = &want[grp * rd..]; + let used = o < MESH_HEADER || (o < MESH_HEADER + maxv * vd && (o - MESH_HEADER) / vd < r[0] as usize) || (o >= MESH_HEADER + maxv * vd && o - MESH_HEADER - maxv * vd < r[1] as usize); + used && want[i] != got[i] + }) + .take(16) + .collect(); + assert!(diff.is_empty(), "{what}: records differ at {diff:?}: got {:?}, want {:?}", diff.iter().map(|&i| got[i]).collect::>(), diff.iter().map(|&i| want[i]).collect::>()); + }; + let mut forms = vec![true]; + if runner::wave64_supported() == Ok(true) { + forms.push(false); + } + for split in forms { + let direct = translate_geometry(&code, opts(split, 1), &g).unwrap().dxil; + let (_, got) = runner::mesh_draw(&direct, &msb, &ps, 2, rec.record_dwords(), &io, &mem, 32, [0.0; 4]).unwrap(); + check(&format!("direct, split {split}"), &got); + let t = hlsl_geometry(&code, g.clone(), split, 1).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let hlsl = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let (_, got) = runner::mesh_draw(&hlsl, &msb, &ps, 2, rec.record_dwords(), &io, &mem, 32, [0.0; 4]).unwrap(); + check(&format!("HLSL, split {split}"), &got); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index efcf15a00c..d28a2ffcb6 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -17,7 +17,8 @@ use super::lower::{ComputeInit, Init, Lw, Partner, VAR_BUDGET, VAR_SCC, VAR_VGPR use super::module::{Block, Pred, Value}; use super::shader::{RawUav, Shader}; use super::ssa::Ssa; -use crate::gpu::recomp::{CsInterface, MsInterface, PsInterface, VsInterface, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use crate::gpu::rdna2::Decoded; +use crate::gpu::recomp::{CsInterface, GsInterface, MsInterface, PsInterface, VsInterface, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS, MESH_HEADER}; #[derive(Debug, Clone, Copy)] pub struct KernelOptions { @@ -36,7 +37,7 @@ pub struct KernelOptions { /// Version of the direct translator's output, part of the on-disk translation cache's /// identity (`recomp::pso`): bump it on any change that alters the emitted containers /// (the `gpu/dxil` sources are not in build.rs's translator source hash). -pub const TRANSLATOR_VERSION: u32 = 5; +pub const TRANSLATOR_VERSION: u32 = 7; /// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this /// translator, with the HLSL path as the fallback for what it cannot translate yet. @@ -85,14 +86,21 @@ pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Resul translate_entry(code, o, Entry::Pixel(ps.clone())) } +/// A geometry-mode (ES+GS) program: the compute pass that writes one mesh record per +/// group of 21 triangles into `res` (the recompiler's `Mode::Geometry`). Always wave64. +pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Result { + translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone())) +} + /// The entry ABI. #[derive(Clone)] -enum Entry { +pub enum Entry { Kernel, Compute(CsInterface), Mesh(MsInterface), Vertex(VsInterface), Pixel(PsInterface), + Geometry(GsInterface), } /// A compute-mode program (the CS ABI of `cs`). @@ -131,121 +139,22 @@ fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec } fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Result { - let cfg = Cfg::build(code)?; - let split = o.wave64 && o.split; - let kernel = matches!(entry, Entry::Kernel); - let cs = match &entry { - Entry::Compute(cs) => Some(cs.clone()), + let geo = match &entry { + Entry::Geometry(g) => Some(g.clone()), _ => None, }; - let ms = match &entry { - Entry::Mesh(ms) => Some(ms.clone()), - _ => None, + let cfg = match &geo { + Some(g) => Cfg::build_geometry(code, g.gs_start)?, + None => Cfg::build(code)?, }; + let kernel = matches!(entry, Entry::Kernel); let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); - let split = split && !gfx; - let stage = match &entry { - Entry::Vertex(_) => Stage::Vertex, - Entry::Pixel(_) => Stage::Pixel, - _ => Stage::Compute, - }; - let mut s = Shader::new(stage, (6, 6)); - let io = s.raw_uav(0, 0); - let res = if kernel || ms.is_some() { Some(s.raw_uav(1, 0)) } else { None }; - let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, cs.is_some()); - let i32 = s.m.i32(); - let z = s.m.i32c(0); - let mut lw = Lw { - s, - ssa: Ssa::new(i32), - init: Init { io: Some(io), compute: None, vgpr_base: None, entry: Block(0), touched: BTreeSet::new() }, - wave64: o.wave64, - split, - lane: z, - lane31: z, - upper: z, - half: z, - mems, - heap_mem, - res, - fmt_table: None, - ntmp: 0, - scratch: None, - static_samplers: Default::default(), - static_used: Vec::new(), - sampler_base: o.sampler_base, - dyn_rm: false, - has_f64_round_op: false, - exec_cache: HashMap::new(), - xs: None, - xw: None, - xc: None, - waves: 1, - cw: z, - xn: z, - xslot: 1, - lds: None, - lds_top: 8191, - dpp_enable: None, - partner: Partner::Present, - mesh: None, - gfx: None, - gfx_half: None, - whole_live: Default::default(), - guard_override: None, - mask_override: None, - exchange_error: None, - pc: 0, - }; - { - let Lw { s, ssa, init, .. } = &mut lw; - ssa.expect_preds(s, Block(0), 0, &mut |s, v| init.load(s, v)); - } - // LDS and the split form's exchange slot size (16 words for a coherent s_load_dwordx16, - // 32 for ds_bpermute), as the HLSL kernel sizes them - let mut uses_lds = false; - let mut slot = 1u32; - for d in &cfg.insts { - let n = d.inst.name; - if d.enc.name == "ENC_DS" && !matches!(n, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") { - uses_lds = true; - } - if n == "DS_BPERMUTE_B32" { - slot = slot.max(32); - } - if d.enc.name == "ENC_SMEM" && ["GLC", "DLC"].iter().any(|f| crate::gpu::rdna2::field_value(d.enc, &d.words, f) == Some(1)) { - let w = match n.rsplit('_').next().unwrap_or("") { - "DWORDX2" => 2, - "DWORDX4" => 4, - "DWORDX8" => 8, - "DWORDX16" => 16, - _ => 1, - }; - slot = slot.max(w); - } - } + let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); - lw.static_samplers = crate::gpu::recomp::constant_samplers(&cfg.insts, &leaders); - let group_threads: Option = match &entry { - Entry::Vertex(_) | Entry::Pixel(_) => None, - Entry::Kernel => None, - Entry::Compute(cs) => Some(cs.threads.iter().product()), - Entry::Mesh(ms) => Some(ms.threads), - }; - if let (Some(t), true) = (group_threads, split) { - lw.waves = t.div_ceil(64).max(1); - } - if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { - lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(&cfg.insts, kernel); - } - lw.setup_storage(uses_lds, if split { slot } else { 1 }); - if let (Some(t), true) = (group_threads, split) { - lw.partner = match t { - 0..=32 => Partner::Missing, - 33..=64 => Partner::Present, - _ => Partner::Spin, - }; - } + let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); + let uses_lds = lw.lds.is_some(); + let res = lw.res; + let io = lw.init.io.expect("the I/O buffer"); let numthreads = match &entry { Entry::Kernel => { lw.setup_lanes(); @@ -266,6 +175,15 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu mesh_init(&mut lw, ms, tid, io); [ms.threads, 1, 1] } + Entry::Geometry(g) => { + let (tid, _) = lw.setup_lanes_compute([64, 1, 1], uses_lds); + let used: BTreeSet = cfg.insts.iter().flat_map(|d| { + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + r.into_iter().chain(w) + }).collect(); + geom_init(&mut lw, g, tid, io, &used); + [64, 1, 1] + } Entry::Vertex(vs) => { lw.setup_lanes_gfx(); let used: BTreeSet = cfg.insts.iter().flat_map(|d| { @@ -286,6 +204,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu // them in a program with branches, those up to the first s_endpgm in straight-line code let branchy = cfg.insts.iter().any(|d| crate::gpu::rdna2::branch_target(d).is_some()); (lw.dyn_rm, lw.has_f64_round_op) = super::lower::round_modes(&cfg.insts, !branchy); + lw.f32_rm = super::lower_round::f32_round_writes(&cfg.insts); for d in cfg.insts.iter().filter(|_| kernel) { if !branchy && d.inst.name.starts_with("S_ENDPGM") { break; @@ -303,6 +222,16 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu let n = cfg.blocks.len(); let mut heads: Vec> = vec![None; n]; let entry = *cfg.rpo.first().ok_or("empty program")?; + // split geometry mode: the GS's first block is entered from the phase switch (one edge) + // instead of from the ES blocks that jump there + if let (Some(g), true) = (&geo, split) { + let gs_block = (0..n).find(|&b| g.gs_start.is_some_and(|s| s > 0 && cfg.blocks[b].pc == s)); + if let Some(t) = gs_block { + let gs_preds = cfg.blocks[t].preds.iter().filter(|&&p| cfg.blocks[p].pc >= g.gs_start.unwrap_or(0)).count(); + let es = cfg.blocks[t].preds.len() > gs_preds; + heads[t] = Some(lw.block(Some(gs_preds + es as usize))); + } + } let mut head = |lw: &mut Lw, b: usize| -> Block { if let Some(h) = heads[b] { return h; @@ -312,18 +241,51 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu heads[b] = Some(h); h }; + // geometry mode: which blocks are GS code; the split form runs the ES in both hardware + // waves, then (`switch`: a group barrier) the GS in the lower one with fresh registers + let gs_start = geo.as_ref().and_then(|g| g.gs_start); + let in_gs = |b: usize| gs_start.is_some_and(|s| cfg.blocks[b].pc >= s); + let two_phase = split && gs_start.is_some_and(|s| s > 0); + let gs_only = split && gs_start == Some(0); + let es_xn = lw.xn; + if gs_only { + lw.partner = Partner::Missing; + lw.xn = lw.c(0); + } let h0 = head(&mut lw, entry); - lw.edge(Block(0), h0); let exit = lw.block(None); + if gs_only { + // the GS alone: in the lower hardware wave only + let gate = lw.block(Some(1)); + lw.edge(Block(0), gate); + lw.s.m.set_block(gate); + let up = lw.upper; + lw.cond_br(up, exit, h0); + } else { + lw.edge(Block(0), h0); + } + let switch = if two_phase { Some(lw.block(None)) } else { None }; + let mut gs_entry: Option = None; for &b in &cfg.rpo { let h = head(&mut lw, b); lw.s.m.set_block(h); + let es_block = two_phase && !in_gs(b); + if two_phase { + if in_gs(b) { + lw.partner = Partner::Missing; + lw.xn = lw.c(0); + } else { + lw.partner = Partner::Present; + lw.xn = es_xn; + } + } + let end = if es_block { switch.unwrap() } else { exit }; if cfg.headers.contains(&b) { // a lane's loop iterations are capped (the recompiler's LOOP_GUARD) let left = lw.rd(VAR_BUDGET); let none = lw.cmpc(Pred::Eq, left, 0); let cont = lw.block(Some(1)); - lw.cond_br(none, exit, cont); + lw.cond_br(none, end, cont); lw.s.m.set_block(cont); let one = lw.c(1); let l = lw.sub(left, one); @@ -333,6 +295,11 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu lw.inst(&cfg.insts[i])?; } match cfg.blocks[b].term { + Term::Jump(t) if es_block && in_gs(t) => { + // the ES's s_setpc_b64 into the GS: through the phase switch + gs_entry = Some(t); + lw.br(end); + } Term::Jump(t) => { let t = head(&mut lw, t); lw.br(t); @@ -342,7 +309,27 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu let (t, f) = (head(&mut lw, t), head(&mut lw, f)); lw.cond_br(c, t, f); } - Term::End => lw.br(exit), + Term::End => lw.br(end), + } + } + if let Some(sw) = switch { + lw.s.m.set_block(sw); + lw.seal(sw); + lw.partner = Partner::Present; + lw.xn = es_xn; + lw.s.barrier(super::ops::barrier::GROUP_SYNC); + match gs_entry { + Some(t) => { + let gs = lw.block(Some(1)); + let up = lw.upper; + lw.cond_br(up, exit, gs); + lw.s.m.set_block(gs); + let vars: Vec = lw.init.touched.iter().copied().filter(|&v| v < VAR_BUDGET && v != VAR_SCC && v != 126 && v != 127).collect(); + lw.geom_gs_phase_registers(&vars); + let h = head(&mut lw, t); + lw.br(h); + } + None => lw.br(exit), } } lw.s.m.set_block(exit); @@ -358,28 +345,184 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu if gfx { lw.finish_gfx(); } + if geo.is_some() { + if split { + // the record comes from the lower hardware wave (the GS phase's) + let epi = lw.block(Some(1)); + let done = lw.block(Some(2)); + let up = lw.upper; + lw.cond_br(up, done, epi); + lw.s.m.set_block(epi); + lw.geom_epilogue(); + lw.br(done); + lw.s.m.set_block(done); + } else { + lw.geom_epilogue(); + } + } lw.s.m.ret(); lw.s.m.set_block(Block(0)); lw.s.m.br(h0); - if let Some(e) = lw.exchange_error.take() { - return Err(e); - } let hw = if split || !o.wave64 { 32 } else { 64 }; - let c = if gfx { - let g = lw.gfx.take().ok_or("graphics entry without graphics I/O")?; - let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; - lw.s.try_finish_graphics(g.io, info) - } else { - lw.s.try_finish(numthreads, Some(hw)) + lw.finish(numthreads, hw) +} + +impl Lw { + /// The translator's state for a program (`insts`, its blocks starting at `leaders`) at + /// `entry`: the shader with its buffers, + /// the SSA's entry block, the program's LDS and the split form's exchange storage and + /// partner. The caller then sets up the lanes for its entry (`setup_lanes*`), lowers the + /// program's blocks, branches from `Block(0)` to the first of them and ends with + /// [`Lw::finish`]. #1426's block walk (`translate_on_this_thread`) and the recompiler's + /// per-lane lowering (`recomp::lower_dxil`) both build their `Lw` here. + pub fn new(insts: &[Decoded], leaders: &BTreeSet, o: KernelOptions, entry: &Entry) -> Lw { + let split = o.wave64 && o.split; + let kernel = matches!(entry, Entry::Kernel); + let cs = match entry { + Entry::Compute(cs) => Some(cs.clone()), + _ => None, + }; + let ms = match entry { + Entry::Mesh(ms) => Some(ms.clone()), + _ => None, + }; + let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); + let split = split && !gfx; + let stage = match entry { + Entry::Vertex(_) => Stage::Vertex, + Entry::Pixel(_) => Stage::Pixel, + _ => Stage::Compute, + }; + let mut s = Shader::new(stage, (6, 6)); + let io = s.raw_uav(0, 0); + let res = if kernel || ms.is_some() || matches!(entry, Entry::Geometry(_)) { Some(s.raw_uav(1, 0)) } else { None }; + let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, cs.is_some()); + let i32 = s.m.i32(); + let z = s.m.i32c(0); + let mut lw = Lw { + s, + ssa: Ssa::new(i32), + init: Init { io: Some(io), compute: None, vgpr_base: None, entry: Block(0), touched: BTreeSet::new() }, + wave64: o.wave64, + split, + lane: z, + lane31: z, + upper: z, + half: z, + mems, + heap_mem, + res, + fmt_table: None, + fmt_desc_cache: HashMap::new(), + fmt_comp1_cache: HashMap::new(), + uma_base_val: None, + ntmp: 0, + scratch: None, + static_samplers: Default::default(), + static_used: Vec::new(), + sampler_base: o.sampler_base, + dyn_rm: false, + f32_rm: false, + has_f64_round_op: false, + exec_cache: HashMap::new(), + xs: None, + xw: None, + xc: None, + waves: 1, + cw: z, + xn: z, + xslot: 1, + lds: None, + lds_top: 8191, + dpp_enable: None, + partner: Partner::Present, + mesh: None, + geom: None, + gfx: None, + gfx_half: None, + whole_live: Default::default(), + guard_override: None, + mask_override: None, + exchange_error: None, + pc: 0, + }; + { + let Lw { s, ssa, init, .. } = &mut lw; + ssa.expect_preds(s, Block(0), 0, &mut |s, v| init.load(s, v)); + } + // LDS and the split form's exchange slot size (16 words for a coherent s_load_dwordx16, + // 32 for ds_bpermute), as the HLSL kernel sizes them + // geometry mode always has the LDS (the ES ring and the GS output) + let mut uses_lds = matches!(entry, Entry::Geometry(_)); + let mut slot = 1u32; + for d in insts { + let n = d.inst.name; + if d.enc.name == "ENC_DS" && !matches!(n, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") { + uses_lds = true; + } + if n == "DS_BPERMUTE_B32" { + slot = slot.max(32); + } + if d.enc.name == "ENC_SMEM" && ["GLC", "DLC"].iter().any(|f| crate::gpu::rdna2::field_value(d.enc, &d.words, f) == Some(1)) { + let w = match n.rsplit('_').next().unwrap_or("") { + "DWORDX2" => 2, + "DWORDX4" => 4, + "DWORDX8" => 8, + "DWORDX16" => 16, + _ => 1, + }; + slot = slot.max(w); + } + } + lw.static_samplers = crate::gpu::recomp::constant_samplers(insts, leaders); + let group_threads: Option = match entry { + Entry::Vertex(_) | Entry::Pixel(_) => None, + Entry::Kernel => None, + Entry::Compute(cs) => Some(cs.threads.iter().product()), + Entry::Mesh(ms) => Some(ms.threads), + Entry::Geometry(_) => Some(64), + }; + if let (Some(t), true) = (group_threads, split) { + lw.waves = t.div_ceil(64).max(1); + } + if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { + lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); + } + lw.setup_storage(uses_lds, if split { slot } else { 1 }); + if let (Some(t), true) = (group_threads, split) { + lw.partner = match t { + 0..=32 => Partner::Missing, + 33..=64 => Partner::Present, + _ => Partner::Spin, + }; + } + lw } - .map_err(|e| format!("direct DXIL builder error: {e}"))?; - if cfg!(any(test, debug_assertions)) { - if let Err(e) = super::validate::validate(&c) { - let dis = super::validate::disassemble(&c).unwrap_or_else(|d| d); - return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}")); + + /// The finished container and the static samplers the program bound, once every block + /// is closed: `numthreads` and the hardware wave size `hw` for a compute-like entry, the + /// stage's I/O for a VS / PS. + pub fn finish(mut self, numthreads: [u32; 3], hw: u32) -> Result { + if let Some(e) = self.exchange_error.take() { + return Err(e); + } + let stage = self.s.stage; + let c = if matches!(stage, Stage::Vertex | Stage::Pixel) { + let g = self.gfx.take().ok_or("graphics entry without graphics I/O")?; + let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; + self.s.try_finish_graphics(g.io, info) + } else { + self.s.try_finish(numthreads, Some(hw)) + } + .map_err(|e| format!("direct DXIL builder error: {e}"))?; + if cfg!(any(test, debug_assertions)) { + if let Err(e) = super::validate::validate(&c) { + let dis = super::validate::disassemble(&c).unwrap_or_else(|d| d); + return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}")); + } } + Ok(Kernel { dxil: c, static_samplers: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect() }) } - Ok(Kernel { dxil: c, static_samplers: lw.static_used.iter().map(|&(w, c, _)| (w, c)).collect() }) } /// The kernel's epilogue: SGPRs and SCC from lane 0, every touched VGPR per lane. @@ -412,7 +555,7 @@ fn store_registers(lw: &mut Lw, res: super::shader::RawUav) { /// The compute entry's fixed registers (the HLSL compute mode's prologue): group ids /// after the user SGPRs, TG_SIZE, SCC = 0, EXEC = the wave's threads, v0..v2 = thread id. -fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { +pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { let mut sgpr = HashMap::new(); let mut next = cs.user_sgprs; for k in 0..3 { @@ -450,7 +593,7 @@ fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { /// The mesh entry's registers (the HLSL mesh mode's prologue): SGPRs from `io` with the /// wave index in s3[27:24], SCC 0, EXEC = the wave's threads, v5 = group · threads + slot, /// other VGPRs 0; and the record slots. -fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::RawUav) { +pub fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::RawUav) { let lanes: u32 = if lw.wave64 { 64 } else { 32 }; let l = lw.c(lanes); let wave = lw.bin(super::module::BinOp::UDiv, tid, l); @@ -527,3 +670,101 @@ fn entry_exec(lw: &mut Lw, total: u32, tid: Value) -> (Value, Value) { }; (lo, hi) } + +/// The geometry entry's registers (the HLSL geometry mode's prologue): the group's +/// primitives from `io`, s2 = the GS output area, s3 = ES vertices | GS primitives << 8, +/// SCC 0, EXEC = every lane; v0 / v1 = LDS offsets of each GS lane's triangle vertices, +/// v2 = primitive id, v5 = vertex id, the fetch shader's VGPRs from the pre-fetched +/// vertices; and the GS state (`lower_geom`). +fn geom_init(lw: &mut Lw, g: &GsInterface, _tid: Value, io: super::shader::RawUav, used: &BTreeSet) { + use crate::gpu::recomp::{fetched_registers, GS_PRIMS_PER_GROUP, IO_GS_PRIMS, IO_GS_VERTICES}; + let pg = GS_PRIMS_PER_GROUP; + let rec_i = g.record(); + let o = lw.c((IO_GS_PRIMS * 4) as u32); + let total = lw.s.raw_load(io, o, 1)[0]; + let o = lw.c((IO_GS_VERTICES * 4) as u32); + let vin = lw.s.raw_load(io, o, 1)[0]; + let gid = lw.s.group_id(0); + let kp = lw.c(pg); + let p0 = lw.mul(gid, kp); + let more = lw.cmp(Pred::UGt, total, p0); + let left = lw.sub(total, p0); + let left = lw.umin(left, kp); + let zero = lw.c(0); + let np = lw.sel(more, left, zero); + let k3 = lw.c(3); + let nv = lw.mul(np, k3); + let kr = lw.c(rec_i.record_dwords() as u32); + let rec = lw.mul(gid, kr); + let mut sgpr = HashMap::new(); + let s2 = lw.c(g.es_ring_bytes()); + sgpr.insert(2, s2); + let np8 = lw.shlc(np, 8); + let s3 = lw.or(nv, np8); + sgpr.insert(3, s3); + sgpr.insert(VAR_SCC, zero); + if lw.split && g.gs_start == Some(0) { + // the GS alone runs in the lower hardware wave only: no partner half + lw.partner = Partner::Missing; + lw.xn = zero; + } + let t = lw.b(true); + let (lo, hi) = lw.ballot(t); + sgpr.insert(126, lo); + sgpr.insert(127, hi); + let lane = lw.lane; + let item = g.es_item_bytes() / 4; + let in_np = lw.cmp(Pred::ULt, lane, np); + let l3 = lw.mul(lane, k3); + let ki = lw.c(item); + let a0 = lw.mul(l3, ki); + let l31 = lw.addc(l3, 1); + let a1 = lw.mul(l31, ki); + let a1 = lw.shlc(a1, 16); + let v0 = lw.or(a0, a1); + let v0 = lw.sel(in_np, v0, zero); + let l32 = lw.addc(l3, 2); + let v1 = lw.mul(l32, ki); + let v1 = lw.sel(in_np, v1, zero); + let v2 = lw.add(p0, lane); + let p03 = lw.mul(p0, k3); + let v5 = lw.add(p03, lane); + let mut vgpr = HashMap::new(); + vgpr.insert(0, v0); + vgpr.insert(1, v1); + vgpr.insert(2, v2); + vgpr.insert(5, v5); + let nreg = g.input_registers(); + let fetched = fetched_registers(&g.es_inputs); + let in_nv = lw.cmp(Pred::ULt, lane, nv); + let mem = lw.mems[0]; + for &v in used.iter().filter(|&&v| (9..256).contains(&v)) { + let k = ((v - 9) / 4) as usize; + if k >= fetched.len() || fetched[k] >= nreg { + continue; + } + let (r, c) = (fetched[k], ((v - 9) % 4) as u32); + // mem.Load(vin + ((p0 * 3 + lane) * nreg + r) * 16 + 4c), 0 past the group's vertices + let kn = lw.c(nreg); + let x = lw.mul(v5, kn); + let x = lw.addc(x, r); + let x = lw.shlc(x, 4); + let x = lw.add(vin, x); + let x = lw.addc(x, 4 * c); + let val = lw.s.raw_load(mem, x, 1)[0]; + let val = lw.sel(in_nv, val, zero); + vgpr.insert(v as u32, val); + } + lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); + let maxt = g.max_vertex_count.saturating_sub(2).max(1); + let i32 = lw.s.m.i32(); + let arr = lw.s.m.array(maxt as u64, i32); + let tri = lw.s.m.alloca(arr, 4); + let (emitted, strip, ntri, base) = (lw.tmp_var(), lw.tmp_var(), lw.tmp_var(), lw.tmp_var()); + for v in [emitted, strip, ntri] { + lw.wr(v, zero); + } + let none = lw.c(u32::MAX); + lw.wr(base, none); + lw.geom = Some(super::lower_geom::GeomCtx { g: g.clone(), emitted, strip, ntri, base, tri, maxt, rec }); +} diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index cbb17b93bd..3d4c760f41 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -79,6 +79,9 @@ impl Init { if var == VAR_BUDGET { return s.m.i32c(LOOP_BUDGET); } + if var == super::lower_round::VAR_F32_MODE { + return s.m.i32c(super::lower_round::MODE_INIT); + } if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD { return s.m.i32c(0); } @@ -151,6 +154,12 @@ pub struct Lw { pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, + /// cached decoded format descriptors hoisted to `d3`'s defining block + pub fmt_desc_cache: HashMap<(Value, Option), super::lower_mem::FmtDesc>, + /// cached single-component format decode parameters hoisted to `d3`'s defining block + pub fmt_comp1_cache: HashMap<(Value, Option), super::lower_mem::FmtComp1>, + /// cached `IO_UMA_BASE_HI` loaded once in the entry block for multi-window address math + pub uma_base_val: Option, /// temporaries handed out (`lower_mem::VAR_TMP`) pub ntmp: u32, /// the lane's scratch array (an alloca in the entry block) @@ -161,6 +170,9 @@ pub struct Lw { /// the program writes a non-default MODE[3:2] and has f16 rounding ops (no f64 ones): /// f16 results round in software under `VAR_FP16_RM` (the recompiler's `dynamic_f16_rm`) pub dyn_rm: bool, + /// the program writes a non-default MODE[1:0]: rounding f32 instructions round by + /// `lower_round::VAR_F32_MODE` (`lower_round`) + pub f32_rm: bool, pub has_f64_round_op: bool, /// static samplers bound so far: (S#, comparison, handle) at `s, space1` pub static_used: Vec<([u32; 4], bool, super::ops::Sampler)>, @@ -188,6 +200,8 @@ pub struct Lw { pub partner: Partner, /// mesh mode: the record slots pub mesh: Option, + /// geometry mode (ES+GS) + pub geom: Option, /// VS / PS entry pub gfx: Option, /// a wave32 program in 64-lane hardware: this hardware half is the upper one (i1) @@ -892,6 +906,12 @@ impl Lw { if name == "s_sendmsg" && self.mesh.is_some() { return self.mesh_sendmsg(d); } + if self.geom.is_some() && self.geom_inst(d, &name).is_some() { + return Ok(()); + } + if name == "s_denorm_mode" && self.f32_rm { + return self.denorm_mode(Self::fv(d, "SIMM16") as u32); + } if NOOPS.contains(&name.as_str()) { return Ok(()); } @@ -955,7 +975,10 @@ impl Lw { "s_round_mode" => { let simm = Self::fv(d, "SIMM16") as u16; let (sp, dp) = ((simm & 3) as u32, ((simm >> 2) & 3) as u32); - if sp != 0 { + if self.f32_rm { + let v = self.c(sp); + self.mode_write(v, 3); + } else if sp != 0 { return err(d, "non-default f32 round mode"); } if dp != 0 && self.has_f64_round_op { @@ -977,6 +1000,22 @@ impl Lw { fn setreg(&mut self, d: &Decoded, name: &str) -> LResult<()> { let simm = Self::fv(d, "SIMM16") as u16; let (sp_mask, dp_mask, off) = hwreg_mode_round_masks(simm); + if self.f32_rm { + // the mirrored MODE bits (single-precision round / denormal modes) + let (id, offset, width) = decode_hwreg(simm); + if id == 1 { + let wmask = if width >= 32 { u32::MAX } else { ((1u32 << width) - 1) << offset }; + let src = if name == "s_setreg_imm32_b32" { + let imm = d.literal.ok_or_else(|| format!("{}: literal", rdna2::format(d)))?; + self.c(imm) + } else { + let sd = Self::field(d, "SDST"); + self.code32(sd, None, false).ok_or_else(|| format!("{}: register", rdna2::format(d)))? + }; + let v = self.shlc(src, offset); + self.mode_write(v, wmask); + } + } if sp_mask == 0 && dp_mask == 0 { return Ok(()); } @@ -984,7 +1023,7 @@ impl Lw { let imm = d.literal.ok_or_else(|| format!("{}: literal", rdna2::format(d)))?; let sp = hwreg_imm_field(imm, off, 0, sp_mask); let dp = hwreg_imm_field(imm, off, 2, dp_mask); - if sp != 0 { + if sp != 0 && !self.f32_rm { return err(d, "non-default f32 round mode"); } if dp_mask != 0 && dp != 0 && self.has_f64_round_op { @@ -1002,7 +1041,7 @@ impl Lw { } return Ok(()); } - if sp_mask != 0 { + if sp_mask != 0 && !self.f32_rm { return err(d, "dynamic f32 round mode"); } if self.has_f64_round_op { diff --git a/crates/xcl/src/gpu/dxil/lower_geom.rs b/crates/xcl/src/gpu/dxil/lower_geom.rs new file mode 100644 index 0000000000..52bac78b3c --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lower_geom.rs @@ -0,0 +1,269 @@ +//! Geometry mode (ES+GS) for the direct translator: the recompiler's +//! `Mode::Geometry` (`recomp/emit.rs`), a compute pass that runs the ES for the +//! three vertices of each of 21 triangles per group (pre-fetched by XCL), then +//! the GS, and writes the emitted vertices and strip triangles as one mesh +//! record per group into `res` (drawn by the pass-through mesh shader). +//! +//! Per lane: `emitted` / `strip` / `ntri` counters, the lowest LDS address the +//! GS phase wrote (where its output vertices are), and the strip triangles +//! (`[maxt x i32]` in a local array). The split wave64 form runs the ES in both +//! hardware waves, then the GS in the lower one alone with fresh registers. + +use super::lower::{Lw, Partner}; +use super::module::{Pred, Value}; +use super::ops::WaveOp; +use crate::gpu::rdna2::{self, Decoded}; +use crate::gpu::recomp::{ranked, GsInterface, MESH_HEADER}; + +pub struct GeomCtx { + pub g: GsInterface, + pub emitted: u32, + pub strip: u32, + pub ntri: u32, + pub base: u32, + /// local `[maxt x i32]` of strip triangles (k0 | k1 << 10 | k2 << 20) + pub tri: Value, + pub maxt: u32, + pub rec: Value, +} + +impl GeomCtx { + /// Whether `pc` is in the GS code (after the ES's `s_setpc_b64` target). + pub fn gs_phase(&self, pc: u64) -> bool { + self.g.gs_start.is_some_and(|s| pc >= s) + } +} + +impl Lw { + /// Geometry-mode instructions: `s_sendmsg` GS emit / cut, `s_barrier` (none in the + /// split form's GS phase, which runs in one hardware wave). `None`: the usual lowering. + pub fn geom_inst(&mut self, d: &Decoded, name: &str) -> Option<()> { + let gs_phase = self.geom.as_ref()?.gs_phase(d.pc); + match name { + "s_barrier" if self.split && gs_phase => Some(()), + "s_sendmsg" => { + // MSG_GS (2): op 1 cut, 2 emit, 3 emit + cut (stream 0); the rest: nothing + let simm = rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0); + let (msg, op, stream) = (simm & 0xF, (simm >> 4) & 3, (simm >> 8) & 3); + if msg == 2 && stream == 0 { + self.gs_emit_cut(op); + } + Some(()) + } + _ => None, + } + } + + fn gs_emit_cut(&mut self, op: u64) { + let (ve, vs, vn, tri, maxt) = { + let g = self.geom.as_ref().expect("geometry"); + (g.emitted, g.strip, g.ntri, g.tri, g.maxt) + }; + let act = self.act(); + if op & 2 != 0 { + // strip triangle j = (j, j+1, j+2), odd j with the first two swapped + let k = self.rd(ve); + let strip = self.rd(vs); + let ntri = self.rd(vn); + let two = self.cmpc(Pred::UGe, strip, 2); + let room = self.cmpc(Pred::ULt, ntri, maxt); + let c = self.land(act, two); + let c = self.land(c, room); + let k1 = self.c(1); + let k2 = self.c(2); + let km1 = self.sub(k, k1); + let km2 = self.sub(k, k2); + let k20 = self.shlc(k, 20); + let a = self.shlc(km1, 10); + let even = self.or(km2, a); + let even = self.or(even, k20); + let b = self.shlc(km2, 10); + let odd = self.or(km1, b); + let odd = self.or(odd, k20); + let par = self.andc(strip, 1); + let ev = self.cmpc(Pred::Eq, par, 0); + let val = self.sel(ev, even, odd); + let last = self.c(maxt - 1); + let idx = self.umin(ntri, last); + let zero = self.c(0); + let p = self.s.m.gep(tri, &[zero, idx]); + let old = self.s.m.load(p, 4); + let nv = self.sel(c, val, old); + self.s.m.store(p, nv, 4); + let n1 = self.addc(ntri, 1); + let n = self.sel(c, n1, ntri); + self.wr(vn, n); + let e1 = self.addc(k, 1); + let e = self.sel(act, e1, k); + self.wr(ve, e); + let s1 = self.addc(strip, 1); + let st = self.sel(act, s1, strip); + self.wr(vs, st); + } + if op & 1 != 0 { + let strip = self.rd(vs); + let z = self.c(0); + let st = self.sel(act, z, strip); + self.wr(vs, st); + } + } + + /// A GS-phase LDS store at byte address `at` (active lanes only): the lowest one is + /// where the lane's output vertices start. + pub fn geom_note_store(&mut self, at: Value) { + let Some(g) = self.geom.as_ref() else { return }; + if !g.gs_phase(self.pc) { + return; + } + let v = g.base; + let cur = self.rd(v); + let m = self.umin(cur, at); + self.wr(v, m); + } + + /// The split form's GS phase starts like a new program in the lower hardware wave: + /// no partner half, registers as at entry, EXEC of the wave's lanes. + pub fn geom_gs_phase_registers(&mut self, vars: &[u32]) { + self.partner = Partner::Missing; + self.xn = self.c(0); + self.exec_cache.clear(); + for &v in vars { + let x = { + let Lw { s, init, .. } = self; + init.load(s, v) + }; + self.wr(v, x); + } + let t = self.b(true); + let (lo, hi) = self.ballot(t); + self.wr(126, lo); + self.wr(127, hi); + let z = self.c(0); + self.wr(super::lower::VAR_SCC, z); + let g = self.geom.as_ref().expect("geometry"); + let (ve, vs, vn, vb) = (g.emitted, g.strip, g.ntri, g.base); + for v in [ve, vs, vn] { + self.wr(v, z); + } + let m = self.c(u32::MAX); + self.wr(vb, m); + } + + /// The record: vertex / triangle counts (lane 0), the emitted vertices from LDS and + /// the strip triangles, each lane after the lanes before it (wave prefix sums). + pub fn geom_epilogue(&mut self) { + let (g, ve, vn, vbase, tri, rec) = { + let x = self.geom.as_ref().expect("geometry"); + (x.g.clone(), x.emitted, x.ntri, x.base, x.tri, x.rec) + }; + let res = self.res.expect("res"); + let r = g.record(); + let (vd, vbytes) = (r.vert_dwords() as u32, g.vertex_bytes()); + let (maxv, maxp) = (r.max_vertices, r.max_primitives); + let emitted = self.rd(ve); + let ntri = self.rd(vn); + let gs_base = self.rd(vbase); + let vb = self.s.wave_prefix_op(emitted, WaveOp::Sum, true); + let tb = self.s.wave_prefix_op(ntri, WaveOp::Sum, true); + let tv = self.s.wave_active_op(emitted, WaveOp::Sum, true); + let tt = self.s.wave_active_op(ntri, WaveOp::Sum, true); + let lane = self.lane; + let first = self.cmpc(Pred::Eq, lane, 0); + let _ = self.guarded(first, &mut |lw| { + let a = lw.c(maxv); + let nv = lw.umin(tv, a); + let b = lw.c(maxp); + let np = lw.umin(tt, b); + let k4 = lw.c(4); + let o0 = lw.mul(rec, k4); + let o1 = lw.addc(o0, 4); + lw.s.raw_store(res, o0, &[nv]); + lw.s.raw_store(res, o1, &[np]); + Ok(()) + }); + // vertices: k < emitted (and a GS-phase LDS store happened), vb + k < maxv + let pos_reg = g.outputs.iter().find(|e| e.system_value == 1).map(|e| e.register).unwrap_or(0); + let regs: Vec = std::iter::once(pos_reg).chain(ranked(&g.outputs, true).iter().map(|e| e.register)).collect(); + let has = self.cmpc(Pred::Ne, gs_base, u32::MAX); + let kmax = self.c(maxv); + let left = self.sub(kmax, vb); + let room = self.cmp(Pred::UGt, kmax, vb); + let z = self.c(0); + let left = self.sel(room, left, z); + let n = self.umin(emitted, left); + let n = self.sel(has, n, z); + let lds = self.lds.expect("lds"); + self.counted_loop(n, &mut |lw, k| { + let vi = lw.add(vb, k); + let kb = lw.c(vbytes); + let so = lw.mul(k, kb); + let src = lw.add(gs_base, so); + let kd = lw.c(vd); + let dv = lw.mul(vi, kd); + let dst = lw.addc(rec, MESH_HEADER as u32); + let dst = lw.add(dst, dv); + for (slot, &r) in regs.iter().enumerate() { + for c in 0..4u32 { + let a = lw.addc(src, 16 * r + 4 * c); + let i = lw.lshrc(a, 2); + let i = lw.andc(i, 8191); + let v = lw.s.gs_load(lds, i); + let o = lw.addc(dst, 4 * slot as u32 + c); + let o = lw.shlc(o, 2); + lw.s.raw_store(res, o, &[v]); + } + } + }); + // triangles: j < ntri, tb + j < maxp + let pmax = self.c(maxp); + let left = self.sub(pmax, tb); + let room = self.cmp(Pred::UGt, pmax, tb); + let left = self.sel(room, left, z); + let n = self.umin(ntri, left); + let prim_base = (MESH_HEADER + maxv as usize * vd as usize) as u32; + self.counted_loop(n, &mut |lw, j| { + let zero = lw.c(0); + let p = lw.s.m.gep(tri, &[zero, j]); + let t = lw.s.m.load(p, 4); + let a = lw.andc(t, 0x3FF); + let a = lw.add(a, vb); + let b = lw.lshrc(t, 10); + let b = lw.andc(b, 0x3FF); + let b = lw.add(b, vb); + let b = lw.shlc(b, 10); + let c = lw.lshrc(t, 20); + let c = lw.andc(c, 0x3FF); + let c = lw.add(c, vb); + let c = lw.shlc(c, 20); + let v = lw.or(a, b); + let v = lw.or(v, c); + let o = lw.addc(rec, prim_base); + let o = lw.add(o, tb); + let o = lw.add(o, j); + let o = lw.shlc(o, 2); + lw.s.raw_store(res, o, &[v]); + }); + } + + /// `for (k = 0; k < n; k++) body(k)` with a real loop (the counter in an SSA variable). + fn counted_loop(&mut self, n: Value, body: &mut dyn FnMut(&mut Lw, Value)) { + let kv = self.tmp_var(); + let z = self.c(0); + self.wr(kv, z); + let head = self.block(None); + let lp = self.block(Some(1)); + let out = self.block(Some(1)); + self.br(head); + self.s.m.set_block(head); + let k = self.rd(kv); + let more = self.cmp(Pred::ULt, k, n); + self.cond_br(more, lp, out); + self.s.m.set_block(lp); + body(self, k); + let k1 = self.addc(k, 1); + self.wr(kv, k1); + self.br(head); + self.seal(head); + self.s.m.set_block(out); + } +} diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index dc37a95569..90ee245bff 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -12,6 +12,28 @@ use super::ops_core::op; use crate::gpu::rdna2::{self, Decoded}; impl Lw { + /// The sampler of the MIMG at `pc`: a static sampler (bound at `s, space1` in order of + /// first use) when the console bound one there, else the heap sampler the S# indexes. + fn mimg_sampler(&mut self, pc: u64, has_c: bool, s3: Value) -> Sampler { + match self.static_samplers.get(&pc).copied() { + Some(w) => match self.static_used.iter().find(|u| u.0 == w && u.1 == has_c) { + Some(u) => u.2, + None => { + let k = self.static_used.len() as u32; + let cur = self.cur(); + self.s.m.set_block(self.init.entry); + let h = self.s.sampler(self.sampler_base + k, 1, has_c); + self.s.m.set_block(cur); + self.static_used.push((w, has_c, h)); + h + } + }, + None => { + let si = self.andc(s3, 0xFFF); + self.s.heap_sampler(si, has_c, true) + } + } + } fn f3(&mut self, a: [Value; 3], b: [Value; 3], op: fn(&mut Lw, Value, Value) -> Value) -> [Value; 3] { [op(self, a[0], b[0]), op(self, a[1], b[1]), op(self, a[2], b[2])] } @@ -32,15 +54,6 @@ impl Lw { let f32 = self.s.m.f32(); self.s.op(55, "dot3", Some(f32), f32, &[a[0], a[1], a[2], b[0], b[1], b[2]], super::module::FnAttrs::ReadNone) } - fn load3f(&mut self, at: Value) -> [Value; 3] { - let mut r = [at; 3]; - for (k, slot) in r.iter_mut().enumerate() { - let a = self.addc(at, 4 * k as u32); - let v = self.mem_ld(a); - *slot = self.f(v); - } - r - } /// `bvh_intersect`: one BVH node → 4 result dwords (written to temporaries). #[allow(clippy::too_many_arguments)] @@ -52,27 +65,34 @@ impl Lw { for box32 in [true, false] { let is = self.cmpc(Pred::Eq, ty, if box32 { 5 } else { 4 }); self.guarded(is, &mut |lw| { - let mut child = [ones; 4]; - for (k, c) in child.iter_mut().enumerate() { - let a = lw.addc(at, 4 * k as u32); - *c = lw.mem_ld(a); - } + // Box32 is 28 contiguous dwords (4 children + 4×6 box floats); + // Box16 is 16 contiguous dwords (4 children + 4×3 packed f16 pairs). + // Load the whole node in one window switch using 4-dword rawBufferLoads. + let at_al = lw.andc(at, !3); + let chunks = if box32 { 7usize } else { 4usize }; + let words = lw.with_mem_i32s(None, chunks * 4, &mut |lw, m| { + let mut out = Vec::with_capacity(chunks * 4); + for j in 0..chunks { + let a = lw.addc(at_al, 16 * j as u32); + out.extend(lw.s.raw_load(m, a, 0xF)); + } + out + }); + let child = [words[0], words[1], words[2], words[3]]; let ninf = lw.s.m.f32c(0xFF80_0000); let pinf = lw.s.m.f32c(0x7F80_0000); let mut tn = [pinf; 4]; let mut id = [ones; 4]; - for k in 0..4u32 { + for k in 0..4usize { let (mn, mx) = if box32 { - let a = lw.addc(at, 16 + 24 * k); - let b = lw.addc(at, 28 + 24 * k); - (lw.load3f(a), lw.load3f(b)) + let b = 4 + 6 * k; + ( + [lw.f(words[b]), lw.f(words[b + 1]), lw.f(words[b + 2])], + [lw.f(words[b + 3]), lw.f(words[b + 4]), lw.f(words[b + 5])], + ) } else { - let a = lw.addc(at, 16 + 12 * k); - let mut h = [ones; 3]; - for (j, slot) in h.iter_mut().enumerate() { - let x = lw.addc(a, 4 * j as u32); - *slot = lw.mem_ld(x); - } + let b = 4 + 3 * k; + let h = [words[b], words[b + 1], words[b + 2]]; let hx16 = lw.lshrc(h[0], 16); let hy16 = lw.lshrc(h[1], 16); let hz16 = lw.lshrc(h[2], 16); @@ -102,7 +122,7 @@ impl Lw { let a = lw.fmax(a, lo[2]); let b = lw.fmin(hi[0], hi[1]); let b = lw.fmin(b, hi[2]); - let cv = lw.cmpc(Pred::Ne, child[k as usize], u32::MAX); + let cv = lw.cmpc(Pred::Ne, child[k], u32::MAX); let mut all = cv; for c in 0..3 { let le = lw.fcmp(Pred::FOLe, mn[c], mx[c]); @@ -115,8 +135,8 @@ impl Lw { let hit = lw.land(all, ab); let x = lw.land(b0, at_); let hit = lw.land(hit, x); - tn[k as usize] = lw.sel(hit, a, pinf); - id[k as usize] = lw.sel(hit, child[k as usize], ones); + tn[k] = lw.sel(hit, a, pinf); + id[k] = lw.sel(hit, child[k], ones); } for (i, j) in [(0usize, 1usize), (2, 3), (0, 2), (1, 3), (1, 2)] { let lt = lw.fcmp(Pred::FOLt, tn[j], tn[i]); @@ -145,9 +165,20 @@ impl Lw { let p0 = lw.add(at, a0); let p1 = lw.add(at, a1); let p2 = lw.addc(at, 24); - let v0 = lw.load3f(p0); - let v1 = lw.load3f(p1); - let v2 = lw.load3f(p2); + let p60 = lw.addc(at, 60); + let (p0, p1, p2, p60) = (lw.andc(p0, !3), lw.andc(p1, !3), lw.andc(p2, !3), lw.andc(p60, !3)); + let words = lw.with_mem_i32s(None, 10, &mut |lw, m| { + let mut out = Vec::with_capacity(10); + out.extend(lw.s.raw_load(m, p0, 0x7)); + out.extend(lw.s.raw_load(m, p1, 0x7)); + out.extend(lw.s.raw_load(m, p2, 0x7)); + out.push(lw.s.raw_load(m, p60, 0x1)[0]); + out + }); + let v0 = [lw.f(words[0]), lw.f(words[1]), lw.f(words[2])]; + let v1 = [lw.f(words[3]), lw.f(words[4]), lw.f(words[5])]; + let v2 = [lw.f(words[6]), lw.f(words[7]), lw.f(words[8])]; + let tw = words[9]; let e1 = lw.f3(v1, v0, Lw::fsub); let e2 = lw.f3(v2, v0, Lw::fsub); let p = lw.cross(dir, e2); @@ -176,8 +207,6 @@ impl Lw { let di = lw.fsub(det, i); let b0 = lw.fsub(di, j); let bc = [b0, i, j, z]; - let p60 = lw.addc(at, 60); - let tw = lw.mem_ld(p60); let sh = lw.shlc(ty, 3); let tid = lw.shr_masked(tw, sh); let s0 = lw.andc(tid, 3); @@ -427,8 +456,23 @@ impl Lw { 3 => TexKind::CubeArray, 4 => TexKind::D1Array, 5 => TexKind::D2Array, + // multisampled: the fragment index is the sample index (D3D12 MSAA resources have + // no FMASK; their samples are stored uncompressed) + 6 => TexKind::D2MS, + 7 => TexKind::D2MSArray, _ => return err(d, "MIMG dim"), }; + let ms = matches!(dim, 6 | 7); + if ms && (sampling || base == "get_lod") { + return err(d, "MIMG sample MSAA"); + } + if ms && !matches!(base, "load" | "msaa_load" | "get_resinfo") { + // stores / atomics need RWTexture2DMS (SM 6.7, WriteableMSAATextures) + return err(d, "MIMG MSAA store / atomic / load_mip"); + } + if base == "msaa_load" && !ms { + return err(d, "image_msaa_load on a single-sampled dim"); + } if sampling { if f("UNORM") != 0 && dim != 3 { @@ -459,25 +503,7 @@ impl Lw { let ps = self.gfx.as_ref().is_some_and(|g| g.ps.is_some()); let spatial: Vec = coords[..kind.grads().min(coords.len())].to_vec(); let tex = self.s.heap_texture(tw0, kind, false, CompType::F32, 4, true); - let smp: Sampler = match self.static_samplers.get(&d.pc).copied() { - // the console's static samplers: bound at s, space1 in order of first use - Some(w) => match self.static_used.iter().find(|u| u.0 == w && u.1 == has_c) { - Some(u) => u.2, - None => { - let k = self.static_used.len() as u32; - let cur = self.cur(); - self.s.m.set_block(self.init.entry); - let h = self.s.sampler(self.sampler_base + k, 1, has_c); - self.s.m.set_block(cur); - self.static_used.push((w, has_c, h)); - h - } - }, - None => { - let si = self.andc(s3, 0xFFF); - self.s.heap_sampler(si, has_c, true) - } - }; + let smp: Sampler = self.mimg_sampler(d.pc, has_c, s3); if let Some(o) = ovgpr { // texel offset / size of the sampled mip (0 for lz / gather; else the LOD given, else 0) let level = match (&lod, has_lz || gather) { @@ -613,9 +639,6 @@ impl Lw { if !self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) { return err(d, "image_get_lod outside PS"); } - if self.static_samplers.contains_key(&d.pc) { - return err(d, "image_get_lod with a static sampler"); - } let coords: Vec = (0..body as usize).map(|k| compf(self, i_body + k)).collect(); let spatial: Vec = match dim { 3 => self.cube_dir(coords[0], coords[1], coords[2]).to_vec(), @@ -623,8 +646,7 @@ impl Lw { }; let s3 = self.sreg(ssamp + 3); let tex = self.s.heap_texture(tw0, kind, false, CompType::F32, 4, true); - let si = self.andc(s3, 0xFFF); - let smp = self.s.heap_sampler(si, false, true); + let smp = self.mimg_sampler(d.pc, false, s3); let a = self.s.calculate_lod(tex, smp, &spatial, true); let b = self.s.calculate_lod(tex, smp, &spatial, false); let z = self.c(0); @@ -638,6 +660,19 @@ impl Lw { return self.image_result(vdata, &vals, d16, act); } + if base == "get_resinfo" && ms { + // one level; the sample count is a T# field (LAST_LEVEL), read by the program itself + let tex = self.s.heap_texture(tw0, kind, false, CompType::F32, 4, true); + let dims = self.s.get_dimensions(tex.handle, None); + let one = self.c(1); + let w = self.s.m.extract(dims, 0); + let hh = self.s.m.extract(dims, 1); + let dd = if dim == 7 { self.s.m.extract(dims, 2) } else { one }; + let r = [w, hh, dd, one]; + let vals: Vec = comps.iter().map(|&c| r[c as usize]).collect(); + return self.image_result(vdata, &vals, false, act); + } + if base == "get_resinfo" { let mipv = compu(self, 0); let tex = self.s.heap_texture(tw0, kind, false, CompType::F32, 4, true); @@ -674,6 +709,9 @@ impl Lw { let fmt = self.lshrc(tw1, 20); let fmt = self.andc(fmt, 0x1FF); let cls = self.img_cls(fmt); + if ms { + return self.mimg_msaa(base, &ic, tw0, lkind, cls, &comps, vdata, d16, act); + } match base { "load" | "load_mip" => { let tmps = [self.tmp_var(), self.tmp_var(), self.tmp_var(), self.tmp_var()]; @@ -791,6 +829,68 @@ impl Lw { } } + /// `image_load` / `image_msaa_load` on a multisampled T#: `ic` = x, y, (slice,) fragment. + /// `image_load` reads the DMASK components of that sample; `image_msaa_load` reads the one + /// DMASK component of the four samples fragment .. fragment + 3 (a gather of samples). + /// Samples past the resource's count read 0 (made explicit: D3D leaves them undefined). + #[allow(clippy::too_many_arguments)] + fn mimg_msaa(&mut self, base: &str, ic: &[Value], tw0: Value, kind: TexKind, cls: Value, comps: &[u64], vdata: u64, d16: bool, act: Value) -> LResult<()> { + let nc = kind.coords(); + let frag = ic[nc]; + let coords = ic[..nc].to_vec(); + let samples: Vec = if base == "msaa_load" { (0..4).map(|k| self.addc(frag, k)).collect() } else { vec![frag] }; + // per sample: the texel's four channels as raw bits + let tmps: Vec<[u32; 4]> = samples.iter().map(|_| [self.tmp_var(), self.tmp_var(), self.tmp_var(), self.tmp_var()]).collect(); + let z = self.c(0); + for t in &tmps { + for &v in t { + self.wr(v, z); + } + } + for (cv, ct) in [(1u32, CompType::U32), (2, CompType::I32), (0, CompType::F32)] { + let is = self.cmpc(Pred::Eq, cls, cv); + let samples = samples.clone(); + let coords = coords.clone(); + let tmps = tmps.clone(); + self.guarded(is, &mut |lw| { + let tex: Texture = lw.s.heap_texture(tw0, kind, false, ct, 4, true); + let dims = lw.s.get_dimensions(tex.handle, None); + let count = lw.s.m.extract(dims, 3); + for (si, &sv) in samples.iter().enumerate() { + let r = lw.s.texture_load_sample(tex, sv, &coords); + let inside = lw.cmp(Pred::ULt, sv, count); + for k in 0..4 { + let b = lw.bits(r[k]); + let zz = lw.c(0); + let b = lw.sel(inside, b, zz); + lw.wr(tmps[si][k], b); + } + } + Ok(()) + })?; + } + let raw: Vec = if base == "msaa_load" { + let c = comps.first().copied().unwrap_or(0) as usize; + tmps.iter().map(|t| self.rd(t[c])).collect() + } else { + comps.iter().map(|&c| self.rd(tmps[0][c as usize])).collect() + }; + let vals: Vec = if d16 { + raw.iter() + .map(|&x| { + let fx = self.f(x); + let h = self.s.f32_to_f16(fx); + let lo = self.andc(x, 0xFFFF); + let fl = self.cmpc(Pred::Eq, cls, 0); + self.sel(fl, h, lo) + }) + .collect() + } else { + raw + }; + self.image_result(vdata, &vals, d16, act) + } + /// A compare-exchange loop on a texel (`rmw32` on an `At::Ref` texel). fn texel_cas(&mut self, h: Value, ic: &[Value], opn: &str, v: Value) -> Value { // the initial value: an atomic or 0 reads it without changing it diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 97c0e3bd7f..22df80f465 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -114,84 +114,271 @@ enum At { Lds(Value), } +/// Hoisted descriptor-level format info for `FormatLoad` / `FormatStore`. +#[derive(Clone, Copy)] +pub struct FmtDesc { + pub info: Value, + pub n: Value, + pub ty: Value, + pub isint: Value, + pub nb: Value, + pub has: Value, + pub t: [Value; 6], +} + +/// Hoisted single-component format decode parameters for `BUFFER_LOAD_FORMAT_X` +/// (and 1-component `d16` format loads), computed once in `d3`'s defining block. +#[derive(Clone, Copy)] +pub struct FmtComp1 { + pub desc: FmtDesc, + pub s0: Value, + pub s1: Value, + pub one_val: Value, + pub off_bytes: Value, + pub off_bits: Value, + pub big: Value, + pub sh: Value, + pub mu: Value, + pub maxu: Value, + pub maxs: Value, + pub w16: Value, + pub w32: Value, + pub mb: Value, + pub mmask: Value, + pub mshift: Value, + pub den_scale: Value, + pub cge: Value, + pub dflt: Value, +} + impl Lw { - /// Runs `f` on the memory window the last `window` selected (`mem`, `mem1`.. at u2..): - /// a switch over the windows when the program may address several, as the HLSL kernel's - /// `xcl_m*` accessors; returns `f`'s value (i32 or i64). - fn with_mem(&mut self, f: &mut dyn FnMut(&mut Lw, RawUav) -> Option) -> Option { + /// Runs `f` on the active memory window (`mem`, `mem1`.. at u2.., or descriptor heap + /// when `self.heap_mem` is set via `XCL_HEAP_WINDOWS`), returning `out_tys.len()` values + /// merged across the window arms via a single `switch` (or single guarded heap lookup) + /// and direct phis (`f` must not write SSA variables). Out-of-range windows (`w >= n`) + /// jump to `join` (reads 0, stores and atomics dropped), matching `#1693` semantics. + pub(crate) fn with_mem_many_tys( + &mut self, + mut guard: Option, + out_tys: &[super::module::Ty], + f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, + ) -> Vec { + if let Some(c) = guard { + match self.s.m.const_u64(c) { + Some(1) => guard = None, + Some(0) => return out_tys.iter().map(|&t| self.s.m.const_int(t, 0)).collect(), + _ => {} + } + } + // Descriptor-heap windows (`#1693`, `XCL_HEAP_WINDOWS=1`): single guarded heap lookup + // combined with `guard`, stacking cleanly with vector loads/stores & FormatLoad opt. if let Some(coherent) = self.heap_mem { - return self.with_heap_mem(coherent, f); + let windows = self.mems.len() as u32; + let w = self.rd(super::lower::VAR_WIN); + let inside = self.cmpc(Pred::ULt, w, windows); + let cond = match guard { + Some(g) => self.and(g, inside), + None => inside, + }; + if self.s.m.const_u64(cond) == Some(0) { + return out_tys.iter().map(|&t| self.s.m.const_int(t, 0)).collect(); + } + if self.s.m.const_u64(cond) == Some(1) { + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + debug_assert_eq!(vals.len(), out_tys.len()); + return vals; + } + let from = self.cur(); + let then = self.block(None); + let join = self.block(None); + self.cond_br(cond, then, join); + self.seal(then); + self.s.m.set_block(then); + #[cfg(debug_assertions)] + self.ssa.begin_log(); + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + #[cfg(debug_assertions)] + debug_assert!(self.ssa.end_log().is_empty(), "with_mem closure wrote SSA var"); + debug_assert_eq!(vals.len(), out_tys.len()); + let end = self.cur(); + self.s.m.br(join); + self.ssa.seal_region_join(join, from, from, Vec::new()); + self.s.m.set_block(join); + let mut out = Vec::with_capacity(out_tys.len()); + for (j, &ty) in out_tys.iter().enumerate() { + let z = self.s.m.const_int(ty, 0); + let phi = self.s.m.phi(ty); + self.s.m.add_incoming(phi, z, from); + self.s.m.add_incoming(phi, vals[j], end); + out.push(phi); + } + return out; } - if self.mems.len() <= 1 { - let m = self.mems[0]; - return f(self, m); + // Single window, or window known at translation time: at most one branch for `guard`. + let fixed_mem = if self.mems.len() <= 1 { + Some(self.mems[0]) + } else { + let w = self.rd(super::lower::VAR_WIN); + if let Some(k) = self.s.m.const_u64(w) { + if (k as usize) < self.mems.len() { + Some(self.mems[k as usize]) + } else { + return out_tys.iter().map(|&t| self.s.m.const_int(t, 0)).collect(); + } + } else { + None + } + }; + if let Some(m) = fixed_mem { + let Some(cond) = guard else { + let vals = f(self, m); + debug_assert_eq!(vals.len(), out_tys.len()); + return vals; + }; + let from = self.cur(); + let then = self.block(None); + let join = self.block(None); + self.cond_br(cond, then, join); + self.seal(then); + self.s.m.set_block(then); + #[cfg(debug_assertions)] + self.ssa.begin_log(); + let vals = f(self, m); + #[cfg(debug_assertions)] + debug_assert!(self.ssa.end_log().is_empty(), "with_mem closure wrote SSA var"); + debug_assert_eq!(vals.len(), out_tys.len()); + let end = self.cur(); + self.s.m.br(join); + self.ssa.seal_region_join(join, from, from, Vec::new()); + self.s.m.set_block(join); + let mut out = Vec::with_capacity(out_tys.len()); + for (j, &ty) in out_tys.iter().enumerate() { + let z = self.s.m.const_int(ty, 0); + let phi = self.s.m.phi(ty); + self.s.m.add_incoming(phi, z, from); + self.s.m.add_incoming(phi, vals[j], end); + out.push(phi); + } + return out; } + // Multi-window dispatch via a single LLVM `switch` (default -> `join` for out-of-range + // or inactive lane, matching `#1693` window semantics). let w = self.rd(super::lower::VAR_WIN); - let (tl, th) = (self.tmp_var(), self.tmp_var()); - let z = self.c(0); - self.wr(tl, z); - self.wr(th, z); - let mut kind = 0u8; // 0 none, 1 i32, 2 i64 let mems = self.mems.clone(); + let n = mems.len(); + let from = self.cur(); + let arms: Vec = (0..n).map(|_| self.block(None)).collect(); + let join = self.block(None); + let w_eff = if let Some(cond) = guard { + let skip = self.c(n as u32); + self.sel(cond, w, skip) + } else { + w + }; + let cases: Vec<(Value, super::module::Block)> = (0..n).map(|k| (self.c(k as u32), arms[k])).collect(); + self.s.m.switch(w_eff, join, &cases); + for &arm in &arms { + self.edge(from, arm); + self.seal(arm); + } + let mut arm_vals: Vec> = Vec::with_capacity(n); + let mut arm_ends: Vec = Vec::with_capacity(n); for (k, &m) in mems.iter().enumerate() { - // a window outside them matches none (the `switch` default: reads 0, stores - // and atomics dropped) - let is = self.cmpc(Pred::Eq, w, k as u32); - let _ = self.guarded(is, &mut |lw| { - if let Some(v) = f(lw, m) { - let t = lw.s.m.type_of(v); - if t == lw.s.m.i64() { - let (l, h) = lw.unpack64(v); - lw.wr(tl, l); - lw.wr(th, h); - kind = 2; - } else { - lw.wr(tl, v); - kind = 1; - } - } - Ok(()) - }); + self.s.m.set_block(arms[k]); + #[cfg(debug_assertions)] + self.ssa.begin_log(); + let vals = f(self, m); + #[cfg(debug_assertions)] + debug_assert!(self.ssa.end_log().is_empty(), "with_mem closure wrote SSA var"); + debug_assert_eq!(vals.len(), out_tys.len()); + arm_ends.push(self.cur()); + arm_vals.push(vals); + self.s.m.br(join); } - match kind { - 0 => None, - 1 => Some(self.rd(tl)), - _ => { - let (l, h) = (self.rd(tl), self.rd(th)); - Some(self.pack64(l, h)) + self.ssa.seal_region_join(join, from, from, Vec::new()); + self.s.m.set_block(join); + let mut out = Vec::with_capacity(out_tys.len()); + for (j, &ty) in out_tys.iter().enumerate() { + let phi = self.s.m.phi(ty); + let z = self.s.m.const_int(ty, 0); + self.s.m.add_incoming(phi, z, from); + for k in 0..n { + self.s.m.add_incoming(phi, arm_vals[k][j], arm_ends[k]); } + out.push(phi); } + out + } + + pub(crate) fn with_mem_i32s( + &mut self, + guard: Option, + n: usize, + f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, + ) -> Vec { + let i32 = self.s.m.i32(); + let tys = vec![i32; n]; + self.with_mem_many_tys(guard, &tys, f) + } + + pub(crate) fn with_mem_void( + &mut self, + guard: Option, + f: &mut dyn FnMut(&mut Lw, RawUav), + ) { + let _ = self.with_mem_many_tys(guard, &[], &mut |lw, m| { + f(lw, m); + Vec::new() + }); } fn mraw_atomic(&mut self, op: AtomicOp, a: Value, v: Value) -> Value { - self.with_mem(&mut |lw, m| Some(lw.s.raw_atomic(m, op, a, v))).expect("atomic value") + let ty = self.s.m.type_of(v); + self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_atomic(m, op, a, v)])[0] } fn mraw_cmpxchg(&mut self, a: Value, c: Value, n: Value) -> Value { - self.with_mem(&mut |lw, m| Some(lw.s.raw_cmpxchg(m, a, c, n))).expect("cmpxchg value") + let ty = self.s.m.type_of(c); + self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_cmpxchg(m, a, c, n)])[0] } /// `mem.Load(a & ~3)` pub fn mem_ld(&mut self, a: Value) -> Value { let a = self.andc(a, !3); - self.with_mem(&mut |lw, m| Some(lw.s.raw_load(m, a, 1)[0])).expect("load value") + self.with_mem_i32s(None, 1, &mut |lw, m| lw.s.raw_load(m, a, 1))[0] + } + /// `mem.Load2/3/4(a & ~3)` (1..=4 consecutive dwords in one window switch). + pub(crate) fn mem_ld_n(&mut self, guard: Option, a: Value, count: u32) -> Vec { + debug_assert!((1..=4).contains(&count)); + let a = self.andc(a, !3); + let mask = ((1u32 << count) - 1) as u8; + self.with_mem_i32s(guard, count as usize, &mut |lw, m| lw.s.raw_load(m, a, mask)) } /// `mem.Store(a & ~3, v)` pub fn mem_st(&mut self, a: Value, v: Value) { let a = self.andc(a, !3); - self.with_mem(&mut |lw, m| { - lw.s.raw_store(m, a, &[v]); - None - }); + self.with_mem_void(None, &mut |lw, m| lw.s.raw_store(m, a, &[v])); + } + /// `mem.Store1..4(a & ~3, vals)` in one window switch. + fn mem_st_n(&mut self, guard: Option, a: Value, vals: &[Value]) { + debug_assert!((1..=4).contains(&vals.len())); + let a = self.andc(a, !3); + self.with_mem_void(guard, &mut |lw, m| lw.s.raw_store(m, a, vals)); } - /// `ld_raw`: four dwords from an unaligned byte address. - fn ld_raw(&mut self, a: Value) -> [Value; 4] { + /// `ld_raw`: four dwords from an unaligned byte address (one Load4 + one Load1 + /// in a single window switch, optionally combined with a lane guard). + fn ld_raw_guarded(&mut self, guard: Option, a: Value) -> [Value; 4] { let b = self.andc(a, !3); + let b16 = self.addc(b, 16); let s = self.andc(a, 3); let s = self.shlc(s, 3); - let mut w = Vec::new(); - for k in 0..5 { - let at = self.addc(b, 4 * k); - w.push(self.mem_ld(at)); - } + let w = self.with_mem_i32s(guard, 5, &mut |lw, m| { + let mut v = lw.s.raw_load(m, b, 0xF); + v.push(lw.s.raw_load(m, b16, 1)[0]); + v + }); let k32 = self.c(32); let inv = self.sub(k32, s); let inv = self.andc(inv, 31); @@ -205,6 +392,22 @@ impl Lw { } r } + + /// One unaligned dword from byte address `a` (one Load2 in a single window switch). + fn ld_raw_u32_guarded(&mut self, guard: Option, a: Value) -> Value { + let b = self.andc(a, !3); + let s = self.andc(a, 3); + let s = self.shlc(s, 3); + let w = self.with_mem_i32s(guard, 2, &mut |lw, m| lw.s.raw_load(m, b, 0x3)); + let k32 = self.c(32); + let inv = self.sub(k32, s); + let inv = self.andc(inv, 31); + let sz = self.cmpc(Pred::Eq, s, 0); + let lo = self.bin(BinOp::LShr, w[0], s); + let hi = self.bin(BinOp::Shl, w[1], inv); + let x = self.or(lo, hi); + self.sel(sz, w[0], x) + } /// `st_part`: atomically replace the bits `m` of the dword at `b` by `v`. fn st_part(&mut self, b: Value, m: Value, v: Value) { let nm = self.not(m); @@ -272,8 +475,12 @@ impl Lw { // ------------------------------------------------------------ formats - /// `FMT_INFO[min(fmt, 77)]` (a constant table) for a dynamic format. + /// `FMT_INFO[min(fmt, 77)]` (a constant table) for a dynamic format; constant-folded + /// when `fmt` is known at translation time. pub(crate) fn fmt_info(&mut self, fmt: Value) -> Value { + if let Some(k) = self.s.m.const_u64(fmt) { + return self.c(buf_format_info(k.min(77) as usize)); + } let i32 = self.s.m.i32(); let g = match self.fmt_table { Some(g) => g, @@ -292,6 +499,128 @@ impl Lw { let p = self.s.m.gep(g, &[z, i]); self.s.m.load(p, 4) } + /// Emits pure instructions into `v`'s defining block (before its terminator if already + /// terminated) so every use of `v` can share them without duplicating across branches. + fn in_def_block(&mut self, v: Value, f: impl FnOnce(&mut Lw) -> T) -> T { + let Some(b) = self.s.m.def_block(v) else { + return f(self); + }; + let cur = self.cur(); + if b == cur { + return f(self); + } + let prev_ins = self.s.m.set_insert_before_term(true); + self.s.m.set_block(b); + let r = f(self); + self.s.m.set_block(cur); + self.s.m.set_insert_before_term(prev_ins); + r + } + fn fmt_desc(&mut self, d3: Value, mtbuf_fmt: Option) -> FmtDesc { + let key = (d3, mtbuf_fmt); + if let Some(&cached) = self.fmt_desc_cache.get(&key) { + return cached; + } + let anchor = if mtbuf_fmt.is_some() { self.c(0) } else { d3 }; + let desc = self.in_def_block(anchor, |lw| { + let fmt = match mtbuf_fmt { + Some(k) => lw.c(k), + None => { + let x = lw.lshrc(d3, 12); + lw.andc(x, 0x7F) + } + }; + let info = lw.fmt_info(fmt); + let n = lw.andc(info, 7); + let ty = lw.lshrc(info, 3); + let ty = lw.andc(ty, 7); + let t = [0, 1, 2, 3, 4, 5].map(|k| lw.cmpc(Pred::Eq, ty, k)); + let isint = lw.lor(t[4], t[5]); + let nb = lw.fmt_bytes(info); + let has = lw.nz(n); + FmtDesc { info, n, ty, isint, nb, has, t } + }); + self.fmt_desc_cache.insert(key, desc); + desc + } + fn fmt_comp1(&mut self, d3: Value, mtbuf_fmt: Option) -> FmtComp1 { + let key = (d3, mtbuf_fmt); + if let Some(&cached) = self.fmt_comp1_cache.get(&key) { + return cached; + } + let desc = self.fmt_desc(d3, mtbuf_fmt); + let c1 = self.in_def_block(d3, |lw| { + let sel = lw.andc(d3, 7); + let s0 = lw.cmpc(Pred::Eq, sel, 0); + let s1 = lw.cmpc(Pred::Eq, sel, 1); + let one = lw.c(1); + let onef = lw.c(0x3F80_0000); + let one_val = lw.sel(desc.isint, one, onef); + let k4 = lw.c(4); + let ci = lw.sub(sel, k4); + let ci = lw.andc(ci, 3); + let z = lw.c(0); + let w0 = lw.lshrc(desc.info, 8); + let w0 = lw.andc(w0, 63); + let w1 = lw.lshrc(desc.info, 14); + let w1 = lw.andc(w1, 63); + let w2 = lw.lshrc(desc.info, 20); + let w2 = lw.andc(w2, 63); + let gt0 = lw.cmpc(Pred::UGt, ci, 0); + let gt1 = lw.cmpc(Pred::UGt, ci, 1); + let gt2 = lw.cmpc(Pred::UGt, ci, 2); + let o0 = lw.sel(gt0, w0, z); + let o1 = lw.sel(gt1, w1, z); + let o2 = lw.sel(gt2, w2, z); + let off = lw.add(o0, o1); + let off = lw.add(off, o2); + let off_bytes = lw.lshrc(off, 3); + let off_bits = lw.andc(off, 7); + let k6 = lw.c(6); + let c6 = lw.mul(ci, k6); + let sh_info = lw.addc(c6, 8); + let sh_info = lw.andc(sh_info, 31); + let w = lw.bin(BinOp::LShr, desc.info, sh_info); + let w = lw.andc(w, 63); + let big = lw.cmpc(Pred::UGe, w, 32); + let k32 = lw.c(32); + let sh = lw.sub(k32, w); + let sh = lw.andc(sh, 31); + let w31 = lw.andc(w, 31); + let mu = lw.bin(BinOp::Shl, one, w31); + let mu = lw.sub(mu, one); + let maxu = lw.uitof(mu); + let fmaxu = lw.fc(4294967295.0); + let maxu = lw.sel(big, fmaxu, maxu); + let wm1 = lw.sub(w, one); + let wm1 = lw.andc(wm1, 31); + let ms = lw.bin(BinOp::Shl, one, wm1); + let ms = lw.sub(ms, one); + let maxs = lw.uitof(ms); + let fmaxs = lw.fc(2147483647.0); + let maxs = lw.sel(big, fmaxs, maxs); + let w11 = lw.cmpc(Pred::Eq, w, 11); + let w16 = lw.cmpc(Pred::Eq, w, 16); + let w32 = lw.cmpc(Pred::Eq, w, 32); + let k5 = lw.c(5); + let mb = lw.sel(w11, k6, k5); + let k63 = lw.c(63); + let k31 = lw.c(31); + let mmask = lw.sel(w11, k63, k31); + let k17 = lw.c(17); + let k18 = lw.c(18); + let mshift = lw.sel(w11, k17, k18); + let sc6 = lw.s.m.f32c(0x3580_0000); // 2^-20 + let sc5 = lw.s.m.f32c(0x3600_0000); // 2^-19 + let den_scale = lw.sel(w11, sc6, sc5); + let cge = lw.cmp(Pred::ULe, desc.n, ci); + let is3 = lw.cmpc(Pred::Eq, ci, 3); + let dflt = lw.sel(is3, one_val, z); + FmtComp1 { desc, s0, s1, one_val, off_bytes, off_bits, big, sh, mu, maxu, maxs, w16, w32, mb, mmask, mshift, den_scale, cge, dflt } + }); + self.fmt_comp1_cache.insert(key, c1); + c1 + } fn fmt_bytes(&mut self, info: Value) -> Value { let mut t = self.c(0); for sh in [8, 14, 20, 26] { @@ -340,74 +669,48 @@ impl Lw { let big = self.cmpc(Pred::UGe, w, 32); self.sel(big, v, vm) } - fn exp2f(&mut self, x: Value) -> Value { - self.un(super::ops_core::op::EXP, x) - } - fn uf_small(&mut self, v: Value, mb: Value) -> Value { + /// Exact IEEE-754 conversion of 10-bit (mb=5) or 11-bit (mb=6) unsigned float to f32 bits. + fn uf_small_bits(&mut self, v: Value, mb: Value, mmask: Value, mshift: Value, den_scale: Value) -> Value { let e = self.bin(BinOp::LShr, v, mb); - let one = self.c(1); - let p = self.bin(BinOp::Shl, one, mb); - let pm = self.sub(p, one); - let m = self.and(v, pm); - let fm = self.uitof(m); - let fp = self.uitof(p); - let fm = self.fdiv(fm, fp); + let m = self.and(v, mmask); let mnz = self.nz(m); - let qn = self.s.m.f32c(0x7FC0_0000); - let inf = self.s.m.f32c(0x7F80_0000); + let qn = self.c(0x7FC0_0000); + let inf = self.c(0x7F80_0000); let special = self.sel(mnz, qn, inf); - let m14 = self.fc(-14.0); - let p14 = self.exp2f(m14); - let den = self.fmul(fm, p14); - let ef = self.uitof(e); - let k15 = self.fc(15.0); - let eb = self.fsub(ef, k15); - let pe = self.exp2f(eb); - let one_f = self.fc(1.0); - let mant = self.fadd(one_f, fm); - let norm = self.fmul(pe, mant); + let fm = self.uitof(m); + let den = self.fmul(fm, den_scale); + let den = self.bits(den); + let eb = self.addc(e, 112); + let exp_bits = self.shlc(eb, 23); + let mant_bits = self.bin(BinOp::Shl, m, mshift); + let norm = self.or(exp_bits, mant_bits); let e0 = self.cmpc(Pred::Eq, e, 0); let r = self.sel(e0, den, norm); let e31 = self.cmpc(Pred::Eq, e, 31); self.sel(e31, special, r) } - fn fmt_comp(&mut self, r: &[Value; 4], info: Value, c: u32) -> Value { - let n = self.andc(info, 7); - let ty = self.lshrc(info, 3); - let ty = self.andc(ty, 7); - let t4 = self.cmpc(Pred::Eq, ty, 4); - let t5 = self.cmpc(Pred::Eq, ty, 5); - let isint = self.lor(t4, t5); - let mut off = self.c(0); - for k in 0..c { - let w = self.lshrc(info, 8 + 6 * k); - let w = self.andc(w, 63); - off = self.add(off, w); - } - let w = self.lshrc(info, (8 + 6 * c) & 31); - let w = self.andc(w, 63); - let v = self.bits_at(r, off, w); - let k32 = self.c(32); - let sh = self.sub(k32, w); - let sh = self.andc(sh, 31); + /// Decodes raw component bits `v` using pre-computed format parameters. + #[allow(clippy::too_many_arguments)] + fn fmt_decode_val( + &mut self, + v: Value, + desc: &FmtDesc, + big: Value, + sh: Value, + maxu: Value, + maxs: Value, + w16: Value, + w32: Value, + mb: Value, + mmask: Value, + mshift: Value, + den_scale: Value, + cge: Value, + dflt: Value, + ) -> Value { let x = self.bin(BinOp::Shl, v, sh); let x = self.bin(BinOp::AShr, x, sh); - let big = self.cmpc(Pred::UGe, w, 32); let sv = self.sel(big, v, x); - let w31 = self.andc(w, 31); - let one = self.c(1); - let mu = self.bin(BinOp::Shl, one, w31); - let mu = self.sub(mu, one); - let maxu = self.uitof(mu); - let fmaxu = self.fc(4294967295.0); - let maxu = self.sel(big, fmaxu, maxu); - let wm1 = self.sub(w, one); - let wm1 = self.andc(wm1, 31); - let ms = self.bin(BinOp::Shl, one, wm1); - let ms = self.sub(ms, one); - let maxs = self.uitof(ms); - let fmaxs = self.fc(2147483647.0); - let maxs = self.sel(big, fmaxs, maxs); let fv = self.uitof(v); let fsv = self.sitof(sv); let zf = self.fc(0.0); @@ -428,32 +731,133 @@ impl Lw { let f_sn = self.bits(sn); let h = self.s.f16_to_f32(v); let hb = self.bits(h); - let w11 = self.cmpc(Pred::Eq, w, 11); - let k6 = self.c(6); - let k5 = self.c(5); - let mb = self.sel(w11, k6, k5); - let uf = self.uf_small(v, mb); - let ufb = self.bits(uf); - let w16 = self.cmpc(Pred::Eq, w, 16); - let w32 = self.cmpc(Pred::Eq, w, 32); + let ufb = self.uf_small_bits(v, mb, mmask, mshift, den_scale); let flt = self.sel(w16, hb, ufb); let flt = self.sel(w32, v, flt); let fvb = self.bits(fv); let fsvb = self.bits(fsv); let mut res = flt; - for (k, val) in [(5u32, sv), (4, v), (3, fsvb), (2, fvb), (1, f_sn), (0, f_un)] { - let is = self.cmpc(Pred::Eq, ty, k); - res = self.sel(is, val, res); + for (k, val) in [(5usize, sv), (4, v), (3, fsvb), (2, fvb), (1, f_sn), (0, f_un)] { + res = self.sel(desc.t[k], val, res); + } + self.sel(cge, dflt, res) + } + fn fmt_comp(&mut self, r: &[Value; 4], desc: &FmtDesc, c: u32) -> Value { + let mut off = self.c(0); + for k in 0..c { + let w = self.lshrc(desc.info, 8 + 6 * k); + let w = self.andc(w, 63); + off = self.add(off, w); } - let cge = self.cmpc(Pred::ULe, n, c); + let w = self.lshrc(desc.info, (8 + 6 * c) & 31); + let w = self.andc(w, 63); + let v = self.bits_at(r, off, w); + let k32 = self.c(32); + let sh = self.sub(k32, w); + let sh = self.andc(sh, 31); + let big = self.cmpc(Pred::UGe, w, 32); + let w31 = self.andc(w, 31); + let one = self.c(1); + let mu = self.bin(BinOp::Shl, one, w31); + let mu = self.sub(mu, one); + let maxu = self.uitof(mu); + let fmaxu = self.fc(4294967295.0); + let maxu = self.sel(big, fmaxu, maxu); + let wm1 = self.sub(w, one); + let wm1 = self.andc(wm1, 31); + let ms = self.bin(BinOp::Shl, one, wm1); + let ms = self.sub(ms, one); + let maxs = self.uitof(ms); + let fmaxs = self.fc(2147483647.0); + let maxs = self.sel(big, fmaxs, maxs); + let w11 = self.cmpc(Pred::Eq, w, 11); + let w16 = self.cmpc(Pred::Eq, w, 16); + let w32 = self.cmpc(Pred::Eq, w, 32); + let k6 = self.c(6); + let k5 = self.c(5); + let mb = self.sel(w11, k6, k5); + let k63 = self.c(63); + let k31 = self.c(31); + let mmask = self.sel(w11, k63, k31); + let k17 = self.c(17); + let k18 = self.c(18); + let mshift = self.sel(w11, k17, k18); + let sc6 = self.s.m.f32c(0x3580_0000); + let sc5 = self.s.m.f32c(0x3600_0000); + let den_scale = self.sel(w11, sc6, sc5); + let cge = self.cmpc(Pred::ULe, desc.n, c); let dflt = if c == 3 { let a = self.c(1); let b = self.c(0x3F80_0000); - self.sel(isint, a, b) + self.sel(desc.isint, a, b) } else { self.c(0) }; - self.sel(cge, dflt, res) + self.fmt_decode_val(v, desc, big, sh, maxu, maxs, w16, w32, mb, mmask, mshift, den_scale, cge, dflt) + } + /// Decodes a single dynamically chosen component `ci` (0..3) from `r` (used for + /// 2- and 3-component `FormatLoad`s so unused channels are not decoded). + fn fmt_comp_dyn(&mut self, r: &[Value; 4], desc: &FmtDesc, ci: Value) -> Value { + let z = self.c(0); + let w0 = self.lshrc(desc.info, 8); + let w0 = self.andc(w0, 63); + let w1 = self.lshrc(desc.info, 14); + let w1 = self.andc(w1, 63); + let w2 = self.lshrc(desc.info, 20); + let w2 = self.andc(w2, 63); + let gt0 = self.cmpc(Pred::UGt, ci, 0); + let gt1 = self.cmpc(Pred::UGt, ci, 1); + let gt2 = self.cmpc(Pred::UGt, ci, 2); + let o0 = self.sel(gt0, w0, z); + let o1 = self.sel(gt1, w1, z); + let o2 = self.sel(gt2, w2, z); + let off = self.add(o0, o1); + let off = self.add(off, o2); + let k6 = self.c(6); + let c6 = self.mul(ci, k6); + let sh_info = self.addc(c6, 8); + let sh_info = self.andc(sh_info, 31); + let w = self.bin(BinOp::LShr, desc.info, sh_info); + let w = self.andc(w, 63); + let v = self.bits_at(r, off, w); + let k32 = self.c(32); + let sh = self.sub(k32, w); + let sh = self.andc(sh, 31); + let big = self.cmpc(Pred::UGe, w, 32); + let w31 = self.andc(w, 31); + let one = self.c(1); + let mu = self.bin(BinOp::Shl, one, w31); + let mu = self.sub(mu, one); + let maxu = self.uitof(mu); + let fmaxu = self.fc(4294967295.0); + let maxu = self.sel(big, fmaxu, maxu); + let wm1 = self.sub(w, one); + let wm1 = self.andc(wm1, 31); + let ms = self.bin(BinOp::Shl, one, wm1); + let ms = self.sub(ms, one); + let maxs = self.uitof(ms); + let fmaxs = self.fc(2147483647.0); + let maxs = self.sel(big, fmaxs, maxs); + let w11 = self.cmpc(Pred::Eq, w, 11); + let w16 = self.cmpc(Pred::Eq, w, 16); + let w32 = self.cmpc(Pred::Eq, w, 32); + let k5 = self.c(5); + let mb = self.sel(w11, k6, k5); + let k63 = self.c(63); + let k31 = self.c(31); + let mmask = self.sel(w11, k63, k31); + let k17 = self.c(17); + let k18 = self.c(18); + let mshift = self.sel(w11, k17, k18); + let sc6 = self.s.m.f32c(0x3580_0000); + let sc5 = self.s.m.f32c(0x3600_0000); + let den_scale = self.sel(w11, sc6, sc5); + let cge = self.cmp(Pred::ULe, desc.n, ci); + let is3 = self.cmpc(Pred::Eq, ci, 3); + let onef = self.c(0x3F80_0000); + let one_val = self.sel(desc.isint, one, onef); + let dflt = self.sel(is3, one_val, z); + self.fmt_decode_val(v, desc, big, sh, maxu, maxs, w16, w32, mb, mmask, mshift, den_scale, cge, dflt) } fn dst_sel(&mut self, c: &[Value; 4], sel: Value, isint: Value) -> Value { let k4 = self.c(4); @@ -645,8 +1049,7 @@ impl Lw { let imm = Self::fv(d, "OFFSET") as u32; let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); let soff = if soff == 125 { self.c(0) } else { self.code32(soff, None, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))? }; - let mut vals = Vec::new(); - if name.starts_with("s_buffer_load") { + let mut vals = if name.starts_with("s_buffer_load") { let (d0, d1, d2) = (self.sreg(sbase), self.sreg(sbase + 1), self.sreg(sbase + 2)); let k = self.c(imm); let off = self.add(k, soff); @@ -656,14 +1059,28 @@ impl Lw { let sz = self.cmpc(Pred::Eq, st, 0); let lim = self.mul(d2, st); let lim = self.sel(sz, d2, lim); - for i in 0..count { - let o = self.addc(off, 4 * i); - let ok = self.cmp(Pred::ULt, o, lim); - let a = self.add(d0, o); - let v = self.mem_ld(a); - let z = self.c(0); - vals.push(self.sel(ok, v, z)); - } + let base = self.add(d0, off); + let base_aligned = self.andc(base, !3); + let raw = self.with_mem_i32s(None, count as usize, &mut |lw, m| { + let mut out = Vec::with_capacity(count as usize); + let mut done = 0u32; + while done < count { + let chunk = (count - done).min(4); + let at = lw.addc(base_aligned, 4 * done); + let mask = ((1u32 << chunk) - 1) as u8; + out.extend(lw.s.raw_load(m, at, mask)); + done += chunk; + } + out + }); + let z = self.c(0); + (0..count) + .map(|i| { + let o = self.addc(off, 4 * i); + let ok = self.cmp(Pred::ULt, o, lim); + self.sel(ok, raw[i as usize], z) + }) + .collect::>() } else { let imm = ((imm << 11) as i32 >> 11) as u32; let b = self.sreg(sbase); @@ -672,11 +1089,20 @@ impl Lw { self.window_at(hi, b, &[Ea::S(k), Ea::U(soff)], false); let a = self.add(b, k); let a = self.add(a, soff); - for i in 0..count { - let at = self.addc(a, 4 * i); - vals.push(self.mem_ld(at)); - } - } + let base_aligned = self.andc(a, !3); + self.with_mem_i32s(None, count as usize, &mut |lw, m| { + let mut out = Vec::with_capacity(count as usize); + let mut done = 0u32; + while done < count { + let chunk = (count - done).min(4); + let at = lw.addc(base_aligned, 4 * done); + let mask = ((1u32 << chunk) - 1) as u8; + out.extend(lw.s.raw_load(m, at, mask)); + done += chunk; + } + out + }) + }; let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)); if self.split && coherent { // both halves take the lower half's values @@ -752,14 +1178,12 @@ impl Lw { let nv = self.c(n); return self.guarded(c, &mut |lw| lw.st_bytes(a, [data, z, z, z], nv)); } - return self.guarded(act, &mut |lw| { - let r = lw.ld_raw(a); - let z = lw.c(0); - let raw = lw.sel(ok, r[0], z); - let nv = lw.d16_merge(v, raw, n, signed, half); - lw.vset(vdata, nv); - Ok(()) - }); + let r0 = self.ld_raw_u32_guarded(Some(act), a); + let z = self.c(0); + let raw = self.sel(ok, r0, z); + let nv = self.d16_merge(v, raw, n, signed, half); + self.write32(&Dst::V(vdata), nv); + return Ok(()); } if let Some((n, signed, store)) = small { let nb = self.c(n); @@ -771,131 +1195,201 @@ impl Lw { let nv = self.c(n); return self.guarded(c, &mut |lw| lw.st_bytes(a, [v, z, z, z], nv)); } - return self.guarded(act, &mut |lw| { - let r = lw.ld_raw(a); - let bits = 8 * n; - let val = if signed { - let x = lw.shlc(r[0], 32 - bits); - lw.ashrc(x, 32 - bits) - } else { - lw.andc(r[0], ((1u64 << bits) - 1) as u32) - }; - let z = lw.c(0); - let val = lw.sel(ok, val, z); - lw.vset(vdata, val); - Ok(()) - }); + let r0 = self.ld_raw_u32_guarded(Some(act), a); + let bits = 8 * n; + let val = if signed { + let x = self.shlc(r0, 32 - bits); + self.ashrc(x, 32 - bits) + } else { + self.andc(r0, ((1u64 << bits) - 1) as u32) + }; + let z = self.c(0); + let val = self.sel(ok, val, z); + self.write32(&Dst::V(vdata), val); + return Ok(()); } match kind { BufKind::Load => { - let oks: Vec = (0..count).map(|i| { - let b = self.c(4 * i as u32 + 4); - in_range(self, b) - }).collect(); - self.guarded(act, &mut |lw| { - for i in 0..count { - let at = lw.addc(a, 4 * i as u32); - let v = lw.mem_ld(at); - let z = lw.c(0); - let v = lw.sel(oks[i as usize], v, z); - lw.vset(vdata + i, v); - } - Ok(()) - }) + let oks: Vec = (0..count) + .map(|i| { + let b = self.c(4 * i as u32 + 4); + in_range(self, b) + }) + .collect(); + let loaded = self.mem_ld_n(Some(act), a, count as u32); + let z = self.c(0); + for i in 0..count { + let v = self.sel(oks[i as usize], loaded[i as usize], z); + self.write32(&Dst::V(vdata + i), v); + } + Ok(()) } BufKind::Store => { let vals: Vec = (0..count).map(|i| self.vreg(vdata + i)).collect(); - let oks: Vec = (0..count).map(|i| { - let b = self.c(4 * i as u32 + 4); - in_range(self, b) - }).collect(); - self.guarded(act, &mut |lw| { - for i in 0..count as usize { - let at = lw.addc(a, 4 * i as u32); - let v = vals[i]; - lw.guarded(oks[i], &mut |lw| { - lw.mem_st(at, v); - Ok(()) - })?; - } - Ok(()) - }) + let oks: Vec = (0..count) + .map(|i| { + let b = self.c(4 * i as u32 + 4); + in_range(self, b) + }) + .collect(); + for i in 0..count as usize { + let at = self.addc(a, 4 * i as u32); + let c = self.land(act, oks[i]); + self.mem_st_n(Some(c), at, &[vals[i]]); + } + Ok(()) } BufKind::FormatLoad => { - let fmt = if d.enc.name == "ENC_MTBUF" { - self.c(f("FORMAT") as u32) - } else { - let x = self.lshrc(d3, 12); - self.andc(x, 0x7F) + let mtbuf_fmt = (d.enc.name == "ENC_MTBUF").then_some(f("FORMAT") as u32); + let single_comp = match d16_format { + Some((_, components, _)) => components == 1, + None => count == 1, }; - let info = self.fmt_info(fmt); - let ty = self.lshrc(info, 3); - let ty = self.andc(ty, 7); - let t4 = self.cmpc(Pred::Eq, ty, 4); - let t5 = self.cmpc(Pred::Eq, ty, 5); - let isint = self.lor(t4, t5); - let nb = self.fmt_bytes(info); - let rng = in_range(self, nb); - let n7 = self.andc(info, 7); - let has = self.nz(n7); - let ok = self.land(has, rng); - let cur: Vec = (0..count).map(|i| self.vreg(vdata + i)).collect(); - self.guarded(act, &mut |lw| { - let r = lw.ld_raw(a); - let c = [lw.fmt_comp(&r, info, 0), lw.fmt_comp(&r, info, 1), lw.fmt_comp(&r, info, 2), lw.fmt_comp(&r, info, 3)]; - let z = lw.c(0); - if let Some((_, components, high)) = d16_format { + if single_comp { + let c1 = self.fmt_comp1(d3, mtbuf_fmt); + let rng = in_range(self, c1.desc.nb); + let ok = self.land(c1.desc.has, rng); + let ea = self.add(a, c1.off_bytes); + let eb = self.andc(ea, !3); + let ea3 = self.andc(ea, 3); + let ea3_8 = self.shlc(ea3, 3); + let s = self.or(ea3_8, c1.off_bits); + let w = self.with_mem_i32s(Some(act), 2, &mut |lw, m| lw.s.raw_load(m, eb, 0x3)); + let lo = self.bin(BinOp::LShr, w[0], s); + let k32 = self.c(32); + let inv = self.sub(k32, s); + let inv = self.andc(inv, 31); + let hi = self.bin(BinOp::Shl, w[1], inv); + let x = self.or(lo, hi); + let sz = self.cmpc(Pred::Eq, s, 0); + let v_raw = self.sel(sz, w[0], x); + let vm = self.and(v_raw, c1.mu); + let v = self.sel(c1.big, v_raw, vm); + let dec = self.fmt_decode_val( + v, + &c1.desc, + c1.big, + c1.sh, + c1.maxu, + c1.maxs, + c1.w16, + c1.w32, + c1.mb, + c1.mmask, + c1.mshift, + c1.den_scale, + c1.cge, + c1.dflt, + ); + let s_val = self.sel(c1.s1, c1.one_val, dec); + let s_val = self.selc(c1.s0, 0, s_val); + let z = self.c(0); + if let Some((_, _, high)) = d16_format { + let cur0 = self.vreg(vdata); + let lo16 = self.andc(s_val, 0xFFFF); + let sf = self.f(s_val); + let h16 = self.s.f32_to_f16(sf); + let h = self.sel(c1.desc.isint, lo16, h16); + if high { + let h = self.shlc(h, 16); + let h = self.sel(ok, h, z); + let l = self.andc(cur0, 0xFFFF); + let res = self.or(l, h); + self.write32(&Dst::V(vdata), res); + } else { + let res = self.sel(ok, h, z); + self.write32(&Dst::V(vdata), res); + } + } else { + let res = self.sel(ok, s_val, z); + self.write32(&Dst::V(vdata), res); + } + return Ok(()); + } + let desc = self.fmt_desc(d3, mtbuf_fmt); + let rng = in_range(self, desc.nb); + let ok = self.land(desc.has, rng); + let r = self.ld_raw_guarded(Some(act), a); + let z = self.c(0); + let num_comp = d16_format.map_or(count, |(_, components, _)| components); + if num_comp < 4 { + let decode_sel = |lw: &mut Lw, comp: u64| -> Value { + let sel = lw.lshrc(d3, 3 * comp as u32); + let sel = lw.andc(sel, 7); + let k4 = lw.c(4); + let ci = lw.sub(sel, k4); + let ci = lw.andc(ci, 3); + let dec = lw.fmt_comp_dyn(&r, &desc, ci); + let one = lw.c(1); + let onef = lw.c(0x3F80_0000); + let o = lw.sel(desc.isint, one, onef); + let s1 = lw.cmpc(Pred::Eq, sel, 1); + let v = lw.sel(s1, o, dec); + let s0 = lw.cmpc(Pred::Eq, sel, 0); + lw.selc(s0, 0, v) + }; + if let Some((_, components, _)) = d16_format { let half = |lw: &mut Lw, comp: u64| -> Value { - let sel = lw.lshrc(d3, 3 * comp as u32); - let sel = lw.andc(sel, 7); - let s = lw.dst_sel(&c, sel, isint); + let s = decode_sel(lw, comp); let lo = lw.andc(s, 0xFFFF); let sf = lw.f(s); let h = lw.s.f32_to_f16(sf); - lw.sel(isint, lo, h) + lw.sel(desc.isint, lo, h) }; - if high { - let h = half(lw, 0); - let h = lw.shlc(h, 16); - let h = lw.sel(ok, h, z); - let l = lw.andc(cur[0], 0xFFFF); - let v = lw.or(l, h); - lw.vset(vdata, v); - } else { - for i in 0..count { - let lo = half(lw, 2 * i); - let hi = if 2 * i + 1 < components { half(lw, 2 * i + 1) } else { z }; - let hi = lw.shlc(hi, 16); - let v = lw.or(lo, hi); - let v = lw.sel(ok, v, z); - lw.vset(vdata + i, v); - } + for i in 0..count { + let lo = half(self, 2 * i); + let hi = if 2 * i + 1 < components { half(self, 2 * i + 1) } else { z }; + let hi = self.shlc(hi, 16); + let v = self.or(lo, hi); + let v = self.sel(ok, v, z); + self.write32(&Dst::V(vdata + i), v); + } + } else { + for i in 0..count { + let s = decode_sel(self, i); + let v = self.sel(ok, s, z); + self.write32(&Dst::V(vdata + i), v); } - return Ok(()); } - for i in 0..count { - let sel = lw.lshrc(d3, 3 * i as u32); + return Ok(()); + } + let c = [self.fmt_comp(&r, &desc, 0), self.fmt_comp(&r, &desc, 1), self.fmt_comp(&r, &desc, 2), self.fmt_comp(&r, &desc, 3)]; + if let Some((_, components, _)) = d16_format { + let half = |lw: &mut Lw, comp: u64| -> Value { + let sel = lw.lshrc(d3, 3 * comp as u32); let sel = lw.andc(sel, 7); - let s = lw.dst_sel(&c, sel, isint); - let v = lw.sel(ok, s, z); - lw.vset(vdata + i, v); + let s = lw.dst_sel(&c, sel, desc.isint); + let lo = lw.andc(s, 0xFFFF); + let sf = lw.f(s); + let h = lw.s.f32_to_f16(sf); + lw.sel(desc.isint, lo, h) + }; + for i in 0..count { + let lo = half(self, 2 * i); + let hi = if 2 * i + 1 < components { half(self, 2 * i + 1) } else { z }; + let hi = self.shlc(hi, 16); + let v = self.or(lo, hi); + let v = self.sel(ok, v, z); + self.write32(&Dst::V(vdata + i), v); } - Ok(()) - }) + } else { + for i in 0..count { + let sel = self.lshrc(d3, 3 * i as u32); + let sel = self.andc(sel, 7); + let s = self.dst_sel(&c, sel, desc.isint); + let v = self.sel(ok, s, z); + self.write32(&Dst::V(vdata + i), v); + } + } + Ok(()) } BufKind::FormatStore => { - let fmt = if d.enc.name == "ENC_MTBUF" { - self.c(f("FORMAT") as u32) - } else { - let x = self.lshrc(d3, 12); - self.andc(x, 0x7F) - }; - let info = self.fmt_info(fmt); - let nb = self.fmt_bytes(info); + let mtbuf_fmt = (d.enc.name == "ENC_MTBUF").then_some(f("FORMAT") as u32); + let desc = self.fmt_desc(d3, mtbuf_fmt); + let info = desc.info; + let nb = desc.nb; let rng = in_range(self, nb); - let n7 = self.andc(info, 7); - let has = self.nz(n7); - let ok = self.land(has, rng); + let ok = self.land(desc.has, rng); let z = self.c(0); let vals: [Value; 4] = if let Some((_, components, high)) = d16_format { let ty = self.lshrc(info, 3); @@ -1285,12 +1779,10 @@ impl Lw { } let vd = Self::fv(d, "VDST"); let v = self.vreg(vd); - return self.guarded(act, &mut |lw| { - let r = lw.ld_raw(a); - let nv = lw.d16_merge(v, r[0], n, signed, half); - lw.vset(vd, nv); - Ok(()) - }); + let r0 = self.ld_raw_u32_guarded(Some(act), a); + let nv = self.d16_merge(v, r0, n, signed, half); + self.write32(&Dst::V(vd), nv); + return Ok(()); } let (store, count) = match op { "load_dword" | "load_dword_addtid" => (false, 1), @@ -1323,23 +1815,15 @@ impl Lw { }; if store { let vals: Vec = (0..count).map(|i| self.vreg(Self::fv(d, "DATA") + i)).collect(); - self.guarded(act, &mut |lw| { - for (i, &v) in vals.iter().enumerate() { - let at = lw.addc(a, 4 * i as u32); - lw.mem_st(at, v); - } - Ok(()) - }) + self.mem_st_n(Some(act), a, &vals); + Ok(()) } else { let vd = Self::fv(d, "VDST"); - self.guarded(act, &mut |lw| { - for i in 0..count { - let at = lw.addc(a, 4 * i as u32); - let v = lw.mem_ld(at); - lw.vset(vd + i, v); - } - Ok(()) - }) + let loaded = self.mem_ld_n(Some(act), a, count as u32); + for i in 0..count { + self.write32(&Dst::V(vd + i), loaded[i as usize]); + } + Ok(()) } } @@ -1396,6 +1880,7 @@ impl Lw { self.s.gs_load(g, i) } fn lds_st(&mut self, at: Value, v: Value) { + self.geom_note_store(at); let i = self.lds_index(at); let g = self.lds.expect("lds"); self.s.gs_store(g, i, v); diff --git a/crates/xcl/src/gpu/dxil/lower_round.rs b/crates/xcl/src/gpu/dxil/lower_round.rs new file mode 100644 index 0000000000..2aad99e1dc --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lower_round.rs @@ -0,0 +1,478 @@ +//! Directed f32 rounding: MODE.FP_ROUND[1:0] (single precision) = 1 (toward +inf), 2 (toward +//! -inf) or 3 (toward zero), which the HLSL path cannot express (DXIL float operations always +//! round to nearest even). +//! +//! Only programs that write a non-default single-precision rounding mode somewhere +//! (`f32_round_writes`) get this: MODE[1:0] and MODE[5:4] (FP_DENORM single) live in +//! `VAR_F32_MODE` (initially 0x30: nearest even, denormals kept), updated by `s_round_mode`, +//! `s_denorm_mode` and `s_setreg*` of MODE. Each rounding f32 instruction computes its result +//! exactly and rounds it by the current mode; with the mode a constant (the usual +//! `s_round_mode` immediate) the selects fold to one rounding. +//! +//! Exact values: an f32 product is exact in f64; a sum is `s + e` from TwoSum in f64 (exact, +//! as f32 inputs cannot overflow f64); an fma is TwoSum(a·b, c). The f64 → f32 rounding is done +//! on the bits (no float operation sees an f32 denormal, so the GPU's f32 denormal handling +//! cannot interfere), with `e` deciding the direction when `s` itself is an f32 value. +//! +//! Denormals as RDNA defines FP_DENORM (bit 4: keep input denormals, bit 5: keep output +//! denormals): flushed inputs become ±0 before the operation, flushed results become ±0 after +//! rounding. Round to nearest even keeps the translator's usual (native) code. + +use super::lower::{LResult, Lw}; +use super::module::{BinOp, CastOp, Pred, Value}; + +/// MODE[1:0] | MODE[5:4] << 4 (single-precision round and denormal modes), `f32_rm` programs. +pub const VAR_F32_MODE: u32 = super::lower::VAR_BUDGET + 5; +/// The MODE bits `VAR_F32_MODE` mirrors. +pub const MODE_BITS: u32 = 0x33; +/// Initial MODE (nearest even, f32 denormals kept: what the translator assumes elsewhere). +pub const MODE_INIT: u32 = 0x30; + +const MASK52: u64 = (1 << 52) - 1; + +impl Lw { + /// The current single-precision MODE bits (None: the program never directs f32 rounding). + pub fn f32_mode(&mut self) -> Option { + if self.f32_rm { + Some(self.rd(VAR_F32_MODE)) + } else { + None + } + } + + /// MODE ← (MODE & !mask) | (v & mask), on the mirrored bits. + pub fn mode_write(&mut self, v: Value, mask: u32) { + let mask = mask & MODE_BITS; + if mask == 0 || !self.f32_rm { + return; + } + let cur = self.rd(VAR_F32_MODE); + let keep = self.andc(cur, !mask); + let nv = self.andc(v, mask); + let r = self.or(keep, nv); + self.wr(VAR_F32_MODE, r); + } + + fn bits64(&mut self, x: Value) -> Value { + let t = self.i64(); + self.s.m.bitcast(x, t) + } + fn dbl(&mut self, b: Value) -> Value { + let t = self.f64ty(); + self.s.m.bitcast(b, t) + } + fn sh64(&mut self, op: BinOp, a: Value, k: u64) -> Value { + let k = self.c64(k); + self.bin(op, a, k) + } + fn and64(&mut self, a: Value, k: u64) -> Value { + let k = self.c64(k); + self.and(a, k) + } + + /// f32 bits with denormals flushed to ±0 when MODE bit `bit` is clear. + fn flush_den(&mut self, u: Value, mode: Value, bit: u32) -> Value { + let keep = self.andc(mode, 1 << bit); + let keep = self.nz(keep); + let e = self.andc(u, 0x7F80_0000); + let den = self.cmpc(Pred::Eq, e, 0); + let sign = self.andc(u, 0x8000_0000); + let f = self.sel(den, sign, u); + self.sel(keep, u, f) + } + + /// The exact f64 of f32 bits `u` (input denormals flushed by MODE bit 4). Denormals are + /// built from their bits: no f32 float operation sees them. + fn ext_exact(&mut self, u: Value, mode: Value) -> Value { + let u = self.flush_den(u, mode, 4); + let exp = self.andc(u, 0x7F80_0000); + let mant = self.andc(u, 0x7F_FFFF); + let ez = self.cmpc(Pred::Eq, exp, 0); + let mnz = self.nz(mant); + let den = self.land(ez, mnz); + let fu = self.f(u); + let f64t = self.f64ty(); + let n = self.s.m.cast(CastOp::FPExt, fu, f64t); + // denormal: mant · 2^-149 = 2^(top - 149) · 1.f, top = the highest set bit + let top = self.firstbithigh(mant); + let ex = self.addc(top, 874); + let ex = self.zext64(ex); + let ex = self.sh64(BinOp::Shl, ex, 52); + let sh = self.c(52); + let sh = self.sub(sh, top); + let sh = self.andc(sh, 63); + let sh = self.zext64(sh); + let m = self.zext64(mant); + let m = self.bin(BinOp::Shl, m, sh); + let m = self.and64(m, MASK52); + let sg = self.andc(u, 0x8000_0000); + let sg = self.zext64(sg); + let sg = self.sh64(BinOp::Shl, sg, 32); + let b = self.or(sg, ex); + let b = self.or(b, m); + let dv = self.dbl(b); + self.sel(den, dv, n) + } + + /// The exact f64 of an i32 / u32 (built from its bits). + fn int_exact(&mut self, a: Value, signed: bool) -> Value { + let (neg, mag) = if signed { + let neg = self.cmpc(Pred::SLt, a, 0); + let z = self.c(0); + let n = self.sub(z, a); + (Some(neg), self.sel(neg, n, a)) + } else { + (None, a) + }; + let top = self.firstbithigh(mag); + let ex = self.addc(top, 1023); + let ex = self.zext64(ex); + let ex = self.sh64(BinOp::Shl, ex, 52); + let sh = self.c(52); + let sh = self.sub(sh, top); + let sh = self.andc(sh, 63); + let sh = self.zext64(sh); + let m = self.zext64(mag); + let m = self.bin(BinOp::Shl, m, sh); + let m = self.and64(m, MASK52); + let mut b = self.or(ex, m); + if let Some(neg) = neg { + let sg = self.c64(1 << 63); + let z = self.c64(0); + let sg = self.sel(neg, sg, z); + b = self.or(b, sg); + } + let zero = self.cmpc(Pred::Eq, mag, 0); + let z = self.c64(0); + let b = self.sel(zero, z, b); + self.dbl(b) + } + + /// f32 bits of the exact value `s + e` (`s` its f64 rounding, `e` the remainder or +0) + /// rounded by MODE (`rm` 1: +inf, 2: -inf, 3: zero; 0 is not used here), output denormals + /// flushed by MODE bit 5. `s` NaN / inf: `native`. + fn round_exact(&mut self, s: Value, e: Value, mode: Value, native: Value) -> Value { + let sb = self.bits64(s); + let sg = self.sh64(BinOp::LShr, sb, 63); + let neg = self.trunc32(sg); + let neg = self.nz(neg); + let ex = self.sh64(BinOp::LShr, sb, 52); + let ex = self.trunc32(ex); + let ex = self.andc(ex, 0x7FF); + let mant = self.and64(sb, MASK52); + let ez = self.cmpc(Pred::Eq, ex, 0); + let one = self.c(1); + let exe = self.sel(ez, one, ex); + let imp = self.c64(1 << 52); + let mi = self.or(mant, imp); + let m = self.sel(ez, mant, mi); + // f32 biased exponent + let k896 = self.c(896); + let e32 = self.sub(exe, k896); + let normal = self.cmpc(Pred::SGe, e32, 1); + let k30 = self.c(30); + let sub = self.sub(k30, e32); + let k29 = self.c(29); + let sh = self.sel(normal, k29, sub); + let big = self.cmpc(Pred::UGt, sh, 63); + let k63 = self.c(63); + let sh = self.sel(big, k63, sh); + let sh = self.zext64(sh); + let keep = self.bin(BinOp::LShr, m, sh); + let one64 = self.c64(1); + let lowm = self.bin(BinOp::Shl, one64, sh); + let lowm = self.sub(lowm, one64); + let rest = self.and(m, lowm); + let em1 = self.sub(e32, one); + let em1 = self.shlc(em1, 23); + let z32 = self.c(0); + let base = self.sel(normal, em1, z32); + let base = self.zext64(base); + let mag = self.add(base, keep); + let over = self.cmpc(Pred::SGe, e32, 255); + let maxf = self.c64(0x7F7F_FFFF); + let mag = self.sel(over, maxf, mag); + let rnz = self.nz(rest); + let rnz = self.lor(rnz, over); + // the remainder: nonzero, and its sign + let eb = self.bits64(e); + let emag = self.and64(eb, !(1u64 << 63)); + let enz = self.nz(emag); + let es = self.sh64(BinOp::LShr, eb, 63); + let es = self.trunc32(es); + let eneg = self.nz(es); + // |exact| < |s| = an f32 value: truncation is one below it + let opp = self.xor(eneg, neg); + let nr = self.lnot(rnz); + let below = self.land(nr, enz); + let below = self.land(below, opp); + let bl = self.u(below); + let bl = self.zext64(bl); + let mag = self.sub(mag, bl); + let inexact = self.lor(rnz, enz); + let rm = self.andc(mode, 3); + let is_p = self.cmpc(Pred::Eq, rm, 1); + let is_n = self.cmpc(Pred::Eq, rm, 2); + let pos = self.lnot(neg); + let up_p = self.land(is_p, pos); + let up_n = self.land(is_n, neg); + let up = self.lor(up_p, up_n); + let up = self.land(up, inexact); + let upv = self.u(up); + let upv = self.zext64(upv); + let mag = self.add(mag, upv); + let mag = self.trunc32(mag); + let sgn = self.u(neg); + let sgn = self.shlc(sgn, 31); + let r = self.or(sgn, mag); + let r = self.flush_den(r, mode, 5); + let special = self.cmpc(Pred::Eq, ex, 0x7FF); + self.sel(special, native, r) + } + + /// The final f32 (float) of a directed operation: `native` (round to nearest even) when + /// MODE[1:0] = 0, else `directed()`. Folds when the mode is a constant. + fn by_mode(&mut self, native: Value, mode: Value, directed: &mut dyn FnMut(&mut Lw) -> Value) -> Value { + let rm = self.andc(mode, 3); + let is_ne = self.cmpc(Pred::Eq, rm, 0); + if self.s.m.const_u64(is_ne) == Some(1) { + return native; + } + let d = directed(self); + let d = self.f(d); + self.sel(is_ne, native, d) + } + + /// TwoSum: (s, e) with s = fl(a + b), e = a + b - s exactly. + fn two_sum(&mut self, a: Value, b: Value) -> (Value, Value) { + let s = self.fadd(a, b); + let bb = self.fsub(s, a); + let ab = self.fsub(s, bb); + let da = self.fsub(a, ab); + let db = self.fsub(b, bb); + let e = self.fadd(da, db); + (s, e) + } + + /// Sum `a + b` (f64, exact inputs) rounded by MODE; an exact zero from a sum is -0 toward + /// -inf unless both addends are +0 (IEEE 754 6.3). + fn round_sum(&mut self, a: Value, b: Value, mode: Value, native: Value) -> Value { + let (s, e) = self.two_sum(a, b); + let r = self.round_exact(s, e, mode, native); + let mag = self.andc(r, 0x7FFF_FFFF); + let zero = self.cmpc(Pred::Eq, mag, 0); + let ab = self.bits64(a); + let bb = self.bits64(b); + let o = self.or(ab, bb); + let z = self.c64(0); + let both_pos = self.cmp(Pred::Eq, o, z); + let rm = self.andc(mode, 3); + let is_n = self.cmpc(Pred::Eq, rm, 2); + // the sum's own zero (a flushed tiny result has s nonzero) + let sb = self.bits64(s); + let sm = self.and64(sb, !(1u64 << 63)); + let sz = self.cmp(Pred::Eq, sm, z); + let c = self.land(zero, sz); + let c = self.land(c, is_n); + let np = self.lnot(both_pos); + let c = self.land(c, np); + let negz = self.c(0x8000_0000); + self.sel(c, negz, r) + } + + /// `a + b` (f32 bits, modifiers applied), `native` the nearest-even float result. + pub fn rm_add(&mut self, a: Value, b: Value, native: Value) -> Value { + let Some(mode) = self.f32_mode() else { return native }; + self.by_mode(native, mode, &mut |lw| { + let x = lw.ext_exact(a, mode); + let y = lw.ext_exact(b, mode); + let nb = lw.bits(native); + lw.round_sum(x, y, mode, nb) + }) + } + + /// `a · b`. + pub fn rm_mul(&mut self, a: Value, b: Value, native: Value) -> Value { + let Some(mode) = self.f32_mode() else { return native }; + self.by_mode(native, mode, &mut |lw| { + let x = lw.ext_exact(a, mode); + let y = lw.ext_exact(b, mode); + let p = lw.fmul(x, y); + let z = lw.dc(0.0); + let nb = lw.bits(native); + lw.round_exact(p, z, mode, nb) + }) + } + + /// `a · b + c`, one rounding. + pub fn rm_fma(&mut self, a: Value, b: Value, c: Value, native: Value) -> Value { + let Some(mode) = self.f32_mode() else { return native }; + self.by_mode(native, mode, &mut |lw| { + let x = lw.ext_exact(a, mode); + let y = lw.ext_exact(b, mode); + let w = lw.ext_exact(c, mode); + let p = lw.fmul(x, y); + let nb = lw.bits(native); + lw.round_sum(p, w, mode, nb) + }) + } + + /// `v_mad_f32` / `v_mac_f32`: the product rounded, then the sum rounded. + pub fn rm_mad(&mut self, a: Value, b: Value, c: Value, native: Value) -> Value { + if self.f32_mode().is_none() { + return native; + } + let fa = self.f(a); + let fb = self.f(b); + let pn = self.fmul(fa, fb); + let p = self.rm_mul(a, b, pn); + let pb = self.bits(p); + let fc = self.f(c); + let sn = self.fadd(p, fc); + let r = self.rm_add(pb, c, sn); + // nearest even: the native mad as before + let mode = self.rd(VAR_F32_MODE); + let rm = self.andc(mode, 3); + let is_ne = self.cmpc(Pred::Eq, rm, 0); + self.sel(is_ne, native, r) + } + + /// An integer converted to f32 (`v_cvt_f32_i32` / `_u32`). + pub fn rm_cvt_int(&mut self, a: Value, signed: bool, native: Value) -> Value { + let Some(mode) = self.f32_mode() else { return native }; + self.by_mode(native, mode, &mut |lw| { + let x = lw.int_exact(a, signed); + let z = lw.dc(0.0); + let nb = lw.bits(native); + lw.round_exact(x, z, mode, nb) + }) + } + + /// An f64 converted to f32 (`v_cvt_f32_f64`). + pub fn rm_cvt_f64(&mut self, a: Value, native: Value) -> Value { + let Some(mode) = self.f32_mode() else { return native }; + self.by_mode(native, mode, &mut |lw| { + let z = lw.dc(0.0); + let nb = lw.bits(native); + lw.round_exact(a, z, mode, nb) + }) + } + + /// `a · 2^n` (`v_ldexp_f32`): rounds only into the denormal range. + pub fn rm_ldexp(&mut self, a: Value, n: Value, native: Value) -> Value { + let Some(mode) = self.f32_mode() else { return native }; + self.by_mode(native, mode, &mut |lw| { + let x = lw.ext_exact(a, mode); + // n clamped to ±400 keeps the product exact in f64 and the f32 result the same + let lo = lw.c(-400i32 as u32); + let hi = lw.c(400); + let n = lw.imax(n, lo); + let n = lw.imin(n, hi); + let e = lw.addc(n, 1023); + let e = lw.zext64(e); + let e = lw.sh64(BinOp::Shl, e, 52); + let p2 = lw.dbl(e); + let p = lw.fmul(x, p2); + let z = lw.dc(0.0); + let nb = lw.bits(native); + lw.round_exact(p, z, mode, nb) + }) + } + + /// Square root, correctly rounded in the directed modes (nearest even keeps the native + /// `sqrt`). The input is scaled into the normal range (· 2^100, exact), the native root is + /// corrected to the largest f32 whose square (exact in f64) is ≤ the input, stepped up + /// toward +inf when inexact, and scaled back (· 2^-50). + pub fn rm_sqrt(&mut self, a: Value, native: Value) -> Value { + let Some(mode) = self.f32_mode() else { return native }; + self.by_mode(native, mode, &mut |lw| { + let u = lw.flush_den(a, mode, 4); + let x = lw.ext_exact(u, mode); + let exp = lw.andc(u, 0x7F80_0000); + let small = lw.cmpc(Pred::Eq, exp, 0); + let k100 = lw.dc(2f64.powi(100)); + let one = lw.dc(1.0); + let k = lw.sel(small, k100, one); + let y = lw.fmul(x, k); + let f32t = lw.s.m.f32(); + let yf = lw.s.m.cast(CastOp::FPTrunc, y, f32t); + let r = lw.un(super::ops::FUnary::Sqrt, yf); + let mut lo = lw.bits(r); + for _ in 0..2 { + let q = lw.square64(lo); + let gt = lw.fcmp(Pred::FOGt, q, y); + let dn = lw.addc(lo, u32::MAX); + lo = lw.sel(gt, dn, lo); + } + for _ in 0..2 { + let upb = lw.addc(lo, 1); + let q = lw.square64(upb); + let le = lw.fcmp(Pred::FOLe, q, y); + lo = lw.sel(le, upb, lo); + } + let q = lw.square64(lo); + let exact = lw.fcmp(Pred::FOEq, q, y); + let rm = lw.andc(mode, 3); + let is_p = lw.cmpc(Pred::Eq, rm, 1); + let inex = lw.lnot(exact); + let up = lw.land(is_p, inex); + let upv = lw.u(up); + let res = lw.add(lo, upv); + let back = lw.c(50 << 23); + let scaled = lw.sub(res, back); + let res = lw.sel(small, scaled, res); + // ±0 (flushed denormals too), negative, inf, NaN: sqrt(±0) = ±0, else native + let mag = lw.andc(u, 0x7FFF_FFFF); + let z = lw.cmpc(Pred::Eq, mag, 0); + let negv = lw.cmpc(Pred::SLt, u, 0); + let infnan = lw.cmpc(Pred::UGe, mag, 0x7F80_0000); + let sp = lw.lor(z, negv); + let sp = lw.lor(sp, infnan); + let nb = lw.bits(native); + let sg = lw.andc(u, 0x8000_0000); + let zr = lw.sel(z, sg, nb); + lw.sel(sp, zr, res) + }) + } + + /// The square of a normal f32 (bits) in f64 (exact: 48 significant bits). + fn square64(&mut self, b: Value) -> Value { + let f = self.f(b); + let t = self.f64ty(); + let d = self.s.m.cast(CastOp::FPExt, f, t); + self.fmul(d, d) + } + + /// `s_denorm_mode`: FP_DENORM single (MODE[5:4]) from SIMM16[1:0]. + pub fn denorm_mode(&mut self, simm: u32) -> LResult<()> { + let v = self.c((simm & 3) << 4); + self.mode_write(v, 0x30); + Ok(()) + } +} + +/// Whether the program writes a non-default single-precision rounding mode (MODE[1:0]): +/// `s_round_mode` / `s_setreg_imm32_b32` with a nonzero value there, or any `s_setreg_b32` +/// covering those bits (a run-time value). +pub fn f32_round_writes(insts: &[crate::gpu::rdna2::Decoded]) -> bool { + use super::lower::{hwreg_imm_field, hwreg_mode_round_masks}; + insts.iter().any(|d| { + let name = d.inst.name.to_ascii_lowercase(); + let simm = crate::gpu::rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0) as u16; + match name.as_str() { + "s_round_mode" => simm & 3 != 0, + "s_setreg_imm32_b32" => { + let (sp, _, off) = hwreg_mode_round_masks(simm); + sp != 0 && hwreg_imm_field(d.literal.unwrap_or(0), off, 0, sp) != 0 + } + "s_setreg_b32" => hwreg_mode_round_masks(simm).0 != 0, + _ => false, + } + }) +} + +/// Instructions whose f32 rounding obeys MODE[1:0] but that the directed path does not +/// implement: a translation error in programs that direct f32 rounding. +pub fn f32_round_unsupported(name: &str) -> bool { + matches!(name, "v_fma_mix_f32" | "v_dot2_f32_f16" | "v_dot2c_f32_f16" | "v_interp_p1_f32" | "v_interp_p2_f32") +} diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index 0313539e45..beafdcd682 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -333,6 +333,9 @@ impl Lw { } pub fn valu(&mut self, d: &Decoded, name: &str) -> LResult<()> { + if self.f32_rm && super::lower_round::f32_round_unsupported(name) { + return err(d, "directed f32 rounding of this instruction"); + } if name.starts_with("v_interp_") { return self.interp_gfx(d, name); } @@ -408,6 +411,13 @@ impl Lw { self.fres(&m, e) }}; } + if self.f32_rm { + if let Some(e) = self.valu_f32_rm(name, &m, &u, cur)? { + let res = self.fres(&m, e); + self.vwrite(d, &dst, res); + return Ok(()); + } + } let res: Value = match name { "v_mov_b32" | "v_mov_fed_b32" => a, "v_not_b32" => self.not(a), @@ -1051,6 +1061,126 @@ impl Lw { Ok(()) } + /// Source bits with abs / neg applied on the bits (no float operation: denormals stay). + fn fsrc_bits(&mut self, m: &Mods, i: usize, u: Value) -> Value { + let mut s = u; + if m.abs[i] { + s = self.andc(s, 0x7FFF_FFFF); + } + if m.neg[i] { + let k = self.c(0x8000_0000); + s = self.xor(s, k); + } + s + } + + /// The f32 instructions that round by MODE[1:0] in a program directing f32 rounding + /// (`lower_round`): the result as a float before output modifiers, None for the rest. + fn valu_f32_rm(&mut self, name: &str, m: &Mods, u: &[Src], cur: Value) -> LResult> { + let z = self.c(0); + let raw = |i: usize| u.get(i).map(|s| s.w()).unwrap_or(z); + let (a, b, c) = (raw(0), raw(1), raw(2)); + let ba = self.fsrc_bits(m, 0, a); + let bb = self.fsrc_bits(m, 1, b); + let bc = self.fsrc_bits(m, 2, c); + let (fa, fb, fc) = (self.f(ba), self.f(bb), self.f(bc)); + let legacy_zero = |lw: &mut Lw, x: Value, y: Value| { + let zz = lw.fc(0.0); + let xz = lw.fcmp(Pred::FOEq, x, zz); + let yz = lw.fcmp(Pred::FOEq, y, zz); + lw.lor(xz, yz) + }; + Ok(Some(match name { + "v_add_f32" => { + let n = self.fadd(fa, fb); + self.rm_add(ba, bb, n) + } + "v_sub_f32" | "v_subrev_f32" => { + let (x, y) = if name == "v_sub_f32" { (ba, bb) } else { (bb, ba) }; + let k = self.c(0x8000_0000); + let ny = self.xor(y, k); + let (fx, fy) = (self.f(x), self.f(y)); + let n = self.fsub(fx, fy); + self.rm_add(x, ny, n) + } + "v_mul_f32" => { + let n = self.fmul(fa, fb); + self.rm_mul(ba, bb, n) + } + "v_mul_legacy_f32" => { + let n = self.fmul(fa, fb); + let r = self.rm_mul(ba, bb, n); + let lz = legacy_zero(self, fa, fb); + let zz = self.fc(0.0); + self.sel(lz, zz, r) + } + "v_fma_f32" | "v_div_fmas_f32" => { + let n = self.fmad(fa, fb, fc); + self.rm_fma(ba, bb, bc, n) + } + "v_fma_legacy_f32" => { + let n = self.fmad(fa, fb, fc); + let r = self.rm_fma(ba, bb, bc, n); + let lz = legacy_zero(self, fa, fb); + self.sel(lz, fc, r) + } + "v_fmac_f32" | "v_fmac_legacy_f32" => { + let fcur = self.f(cur); + let n = self.fmad(fa, fb, fcur); + let r = self.rm_fma(ba, bb, cur, n); + if name == "v_fmac_legacy_f32" { + let lz = legacy_zero(self, fa, fb); + self.sel(lz, fcur, r) + } else { + r + } + } + "v_fmamk_f32" => { + let fk = self.f(b); + let n = self.fmad(fa, fk, fc); + self.rm_fma(ba, b, bc, n) + } + "v_fmaak_f32" => { + let fk = self.f(c); + let n = self.fmad(fa, fb, fk); + self.rm_fma(ba, bb, c, n) + } + "v_mad_f32" => { + let n = self.mad_nf(fa, fb, fc); + self.rm_mad(ba, bb, bc, n) + } + "v_mac_f32" => { + let fcur = self.f(cur); + let n = self.mad_nf(fa, fb, fcur); + self.rm_mad(ba, bb, cur, n) + } + "v_madmk_f32" => { + let fk = self.f(b); + let n = self.mad_nf(fa, fk, fc); + self.rm_mad(ba, b, bc, n) + } + "v_madak_f32" => { + let fk = self.f(c); + let n = self.mad_nf(fa, fb, fk); + self.rm_mad(ba, bb, c, n) + } + "v_cvt_f32_i32" | "v_cvt_f32_u32" => { + let signed = name == "v_cvt_f32_i32"; + let n = if signed { self.sitof(a) } else { self.uitof(a) }; + self.rm_cvt_int(a, signed, n) + } + "v_sqrt_f32" => { + let n = self.un(op::SQRT, fa); + self.rm_sqrt(ba, n) + } + "v_ldexp_f32" => { + let n = self.ldexp_f(fa, b); + self.rm_ldexp(ba, b, n) + } + _ => return Ok(None), + })) + } + pub fn vopc(&mut self, d: &Decoded, rest: &str, cmpx: bool, outs: &[&Operand], u: &[Src], m: &Mods) -> LResult<()> { let (opn, ty) = rest.rsplit_once('_').ok_or_else(|| format!("{}: VOPC", rdna2::format(d)))?; if u.len() < 2 { diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index c6ec5c5b09..6c40030351 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -923,6 +923,7 @@ impl Lw { let a = f64v(self, 0); let t = self.s.m.f32(); let f = self.s.m.cast(CastOp::FPTrunc, a, t); + let f = self.rm_cvt_f64(a, f); let f = match m.omod { 1..=3 => { let k = self.fc([2.0, 4.0, 0.5][m.omod as usize - 1]); diff --git a/crates/xcl/src/gpu/dxil/lower_window.rs b/crates/xcl/src/gpu/dxil/lower_window.rs index 06efbe2f0e..1339aa3d48 100644 --- a/crates/xcl/src/gpu/dxil/lower_window.rs +++ b/crates/xcl/src/gpu/dxil/lower_window.rs @@ -4,7 +4,6 @@ use super::lower::{Lw, VAR_WIN}; use super::module::{Pred, Value}; -use super::shader::RawUav; use crate::gpu::rdna2::Decoded; /// A term of a 64-bit effective address (`window_at`). @@ -26,11 +25,29 @@ impl Lw { self.mems.len() > 1 } - /// The high dword of the UMA base (`IO_UMA_BASE_HI` of the io buffer, `xcl_uma_base`). + /// The high dword of the UMA base (`IO_UMA_BASE_HI` of the io buffer, `xcl_uma_base`), + /// hoisted to the entry block so multi-window shaders load it once rather than on every + /// memory operation. fn uma_base(&mut self) -> Value { + if let Some(v) = self.uma_base_val { + return v; + } let io = self.init.io.expect("io"); let off = self.c(crate::gpu::recomp::IO_UMA_BASE_HI as u32 * 4); - self.s.raw_load(io, off, 1)[0] + let cur = self.cur(); + let entry = self.init.entry; + let v = if cur == entry { + self.s.raw_load(io, off, 1)[0] + } else { + let prev = self.s.m.set_insert_before_term(true); + self.s.m.set_block(entry); + let v = self.s.raw_load(io, off, 1)[0]; + self.s.m.set_block(cur); + self.s.m.set_insert_before_term(prev); + v + }; + self.uma_base_val = Some(v); + v } /// Selects the window of an access whose 64-bit effective address is `hi:lo` plus @@ -128,47 +145,4 @@ impl Lw { }; self.window_at(hi, lo, &[Ea::U(l4), off], write); } - - /// `with_mem` with the windows in the descriptor heap (`Options::heap_windows`): window - /// `w` is the raw UAV `ResourceDescriptorHeap[NonUniformResourceIndex(MEM_HEAP_BASE + w)]` - /// (`globallycoherent` where the root windows are); a `w` outside the windows does what - /// the HLSL accessor does (reads 0, stores and atomics dropped). - pub(super) fn with_heap_mem( - &mut self, - coherent: bool, - f: &mut dyn FnMut(&mut Lw, RawUav) -> Option, - ) -> Option { - let windows = self.mems.len() as u32; - let w = self.rd(VAR_WIN); - let (tl, th) = (self.tmp_var(), self.tmp_var()); - let z = self.c(0); - self.wr(tl, z); - self.wr(th, z); - let mut kind = 0u8; // 0 none, 1 i32, 2 i64 - let inside = self.cmpc(Pred::ULt, w, windows); - let _ = self.guarded(inside, &mut |lw| { - let i = lw.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); - let m = lw.s.heap_raw_buffer_uav(i, coherent); - if let Some(v) = f(lw, m) { - if lw.s.m.type_of(v) == lw.s.m.i64() { - let (l, h) = lw.unpack64(v); - lw.wr(tl, l); - lw.wr(th, h); - kind = 2; - } else { - lw.wr(tl, v); - kind = 1; - } - } - Ok(()) - }); - match kind { - 0 => None, - 1 => Some(self.rd(tl)), - _ => { - let (l, h) = (self.rd(tl), self.rd(th)); - Some(self.pack64(l, h)) - } - } - } } diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index 902a2198d8..6fe75d575f 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -19,9 +19,11 @@ pub mod graphics; pub mod kernel; mod lanes; pub mod lower; +mod lower_geom; mod lower_gfx; mod lower_image; mod lower_mem; +mod lower_round; mod lower_valu; mod lower_wide; mod lower_window; @@ -43,3 +45,11 @@ mod ops_tests; mod bitreader_tests; #[cfg(test)] mod robustness_tests; +#[cfg(test)] +mod fuzz_tests; +#[cfg(test)] +mod msaa_tests; +#[cfg(test)] +mod round_tests; +#[cfg(test)] +mod geometry_tests; diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 3462ca3610..cc37c4fa74 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -249,8 +249,10 @@ pub struct Module { func_ids: HashMap, globals: Vec, insts: Vec, + def_block: Vec, blocks: Vec>, cur: Block, + insert_before_term: bool, md: Vec, named_md: Vec<(String, Vec)>, md_strings: HashMap, @@ -275,8 +277,10 @@ impl Module { func_ids: HashMap::new(), globals: Vec::new(), insts: Vec::new(), + def_block: Vec::new(), blocks: vec![Vec::new()], cur: Block(0), + insert_before_term: false, md: Vec::new(), named_md: Vec::new(), md_strings: HashMap::new(), @@ -521,6 +525,24 @@ impl Module { pub fn current_block(&self) -> Block { self.cur } + /// Block where `v` is defined (entry block for constants, globals and functions). + pub fn def_block(&self, v: Value) -> Option { + match v { + Value::Inst(i) => { + let b = self.def_block[i as usize]; + (b.0 < self.blocks.len() as u32).then_some(b) + } + _ => Some(Block(0)), + } + } + /// When enabled, emitting into an already-terminated block inserts immediately + /// before its terminator (used for hoisting pure computations to a value's + /// defining block). Returns the previous setting. + pub fn set_insert_before_term(&mut self, on: bool) -> bool { + let prev = self.insert_before_term; + self.insert_before_term = on; + prev + } /// Whether the current block already ends in a terminator. pub fn terminated(&self) -> bool { self.blocks[self.cur.0 as usize].last().is_some_and(|&i| { @@ -529,12 +551,20 @@ impl Module { } fn push(&mut self, op: Op, ty: Ty) -> Value { - if self.terminated() { + let terminated = self.terminated(); + if terminated && !self.insert_before_term { self.fail(format!("instruction after a terminator in block {:?}", self.cur)); } let id = self.insts.len() as u32; self.insts.push(InstDef { op, ty }); - self.blocks[self.cur.0 as usize].push(id); + self.def_block.push(self.cur); + let list = &mut self.blocks[self.cur.0 as usize]; + if terminated && self.insert_before_term { + let at = list.len() - 1; + list.insert(at, id); + } else { + list.push(id); + } Value::Inst(id) } @@ -608,6 +638,7 @@ impl Module { pub fn phi_at(&mut self, b: Block, ty: Ty) -> Value { let id = self.insts.len() as u32; self.insts.push(InstDef { op: Op::Phi(Vec::new()), ty }); + self.def_block.push(b); let list = &mut self.blocks[b.0 as usize]; let at = list.iter().position(|&i| !matches!(self.insts[i as usize].op, Op::Phi(_))).unwrap_or(list.len()); list.insert(at, id); @@ -618,11 +649,13 @@ impl Module { pub fn detached_phi(&mut self, ty: Ty) -> Value { let id = self.insts.len() as u32; self.insts.push(InstDef { op: Op::Phi(Vec::new()), ty }); + self.def_block.push(Block(u32::MAX)); Value::Inst(id) } /// Puts a [`Module::detached_phi`] after the existing phis of block `b`. pub fn place_phi(&mut self, b: Block, phi: Value) { let Value::Inst(id) = phi else { panic!("not a phi") }; + self.def_block[id as usize] = b; let list = &mut self.blocks[b.0 as usize]; let at = list.iter().position(|&i| !matches!(self.insts[i as usize].op, Op::Phi(_))).unwrap_or(list.len()); list.insert(at, id); @@ -1077,9 +1110,19 @@ impl Module { /// Replaces every use of `old` by `new` in the entry's instructions and in /// metadata (e.g. to drop a trivial phi). `old` itself stays in its block. pub fn replace_all_uses(&mut self, old: Value, new: Value) { + self.replace_uses(&HashMap::from([(old, new)])); + } + + /// `replace_all_uses` for every `old → new` of `map` in one pass over the module: a use + /// becomes the end of its chain (`a → b`, `b → c`: a use of `a` becomes `c`), as the same + /// calls one at a time in order would leave it. + pub fn replace_uses(&mut self, map: &HashMap) { + if map.is_empty() { + return; + } let r = |v: &mut Value| { - if *v == old { - *v = new; + while let Some(&n) = map.get(v) { + *v = n; } }; for inst in &mut self.insts { diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 74153ff4ad..d852d8a413 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; -use super::{FnAttrs, Module, Op, Ty, Value}; +use super::{BinOp, CastOp, FnAttrs, Module, Op, Pred, Ty, Value}; impl Op { /// Calls `f` on every value operand. @@ -84,15 +84,160 @@ impl Module { n.starts_with("dx.op.wave") || n.starts_with("dx.op.quad") } + fn is_const_global_ptr(&self, v: Value) -> bool { + match v { + Value::Global(g) => self.globals[g as usize].constant, + Value::Inst(i) => match &self.insts[i as usize].op { + Op::Gep(base, _) => self.is_const_global_ptr(*base), + _ => false, + }, + _ => false, + } + } + fn cse_kind(&self, op: &Op) -> Cse { match op { Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Gep(..) => Cse::Dom, + Op::Load(p, _) if self.is_const_global_ptr(*p) => Cse::Dom, Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => Cse::Dom, Op::Call(f, _) if self.wave_call(*f) && !self.funcs[*f as usize].name.starts_with("dx.op.waveIsFirstLane") => Cse::Block, _ => Cse::No, } } + /// Cheap algebraic & constant simplification on already-resolved operands. + fn simplify_op(&mut self, op: &Op, ty: Ty) -> Option { + // Keep 64-bit instructions intact so Int64Ops / Doubles shader flags stay consistent. + if matches!(self.types[ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { + return None; + } + match *op { + Op::Select(c, t, f) => { + if t == f { + return Some(t); + } + match self.const_u64(c) { + Some(1) => Some(t), + Some(0) => Some(f), + _ => None, + } + } + Op::Bin(bop, a, b, 0) => { + let w = self.int_width(ty)?; + // avoid dropping 64-bit ops that keep Int64Ops shader flags consistent + if w > 32 { + return None; + } + let mask = (1u64 << w) - 1; + let (ca, cb) = (self.const_u64(a), self.const_u64(b)); + if let (Some(x), Some(y)) = (ca, cb) { + let r = match bop { + BinOp::Add => Some(x.wrapping_add(y)), + BinOp::Sub => Some(x.wrapping_sub(y)), + BinOp::Mul => Some(x.wrapping_mul(y)), + BinOp::And => Some(x & y), + BinOp::Or => Some(x | y), + BinOp::Xor => Some(x ^ y), + BinOp::Shl if y < w as u64 => Some(x << y), + BinOp::LShr if y < w as u64 => Some(x >> y), + BinOp::AShr if y < w as u64 => Some((((x << (64 - w)) as i64) >> (64 - w + y as u32)) as u64), + BinOp::UDiv if y != 0 => Some(x / y), + BinOp::URem if y != 0 => Some(x % y), + _ => None, + }; + if let Some(r) = r { + return Some(self.const_int(ty, r & mask)); + } + } + match (bop, cb) { + (BinOp::Add | BinOp::Sub | BinOp::Or | BinOp::Xor | BinOp::Shl | BinOp::LShr | BinOp::AShr, Some(0)) => return Some(a), + (BinOp::And, Some(m)) if m == mask => return Some(a), + (BinOp::And | BinOp::Mul, Some(0)) => return Some(b), + (BinOp::Mul, Some(1)) => return Some(a), + _ => {} + } + match (bop, ca) { + (BinOp::Add | BinOp::Or | BinOp::Xor, Some(0)) => return Some(b), + (BinOp::And, Some(m)) if m == mask => return Some(b), + (BinOp::And | BinOp::Mul | BinOp::Shl | BinOp::LShr, Some(0)) => return Some(a), + (BinOp::Mul, Some(1)) => return Some(b), + _ => {} + } + if a == b { + match bop { + BinOp::And | BinOp::Or => return Some(a), + BinOp::Sub | BinOp::Xor => return Some(self.const_int(ty, 0)), + _ => {} + } + } + None + } + Op::Cmp(p, a, b) => { + let at = self.value_ty(a); + let w = self.int_width(at)?; + if w > 32 { + return None; + } + if let (Some(x), Some(y)) = (self.const_u64(a), self.const_u64(b)) { + let sx = |v: u64| ((v << (64 - w)) as i64) >> (64 - w); + let r = match p { + Pred::Eq => Some(x == y), + Pred::Ne => Some(x != y), + Pred::UGt => Some(x > y), + Pred::UGe => Some(x >= y), + Pred::ULt => Some(x < y), + Pred::ULe => Some(x <= y), + Pred::SGt => Some(sx(x) > sx(y)), + Pred::SGe => Some(sx(x) >= sx(y)), + Pred::SLt => Some(sx(x) < sx(y)), + Pred::SLe => Some(sx(x) <= sx(y)), + _ => None, + }; + if let Some(r) = r { + return Some(self.const_int(ty, r as u64)); + } + } + if a == b { + let r = match p { + Pred::Eq | Pred::ULe | Pred::UGe | Pred::SLe | Pred::SGe => Some(true), + Pred::Ne | Pred::ULt | Pred::UGt | Pred::SLt | Pred::SGt => Some(false), + _ => None, + }; + if let Some(r) = r { + return Some(self.const_int(ty, r as u64)); + } + } + None + } + Op::Cast(CastOp::BitCast, Value::Inst(j), to) => { + if matches!(self.types[self.insts[j as usize].ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { + return None; + } + if let Op::Cast(CastOp::BitCast, inner, _) = self.insts[j as usize].op { + if self.value_ty(inner) == to { + return Some(inner); + } + } + None + } + Op::Cast(cop @ (CastOp::ZExt | CastOp::SExt | CastOp::Trunc), v, to) => { + let sw = self.int_width(self.value_ty(v))?; + let dw = self.int_width(to)?; + if sw > 32 || dw > 32 { + return None; + } + let x = self.const_u64(v)?; + let r = match cop { + CastOp::ZExt | CastOp::Trunc => x & ((1u64 << dw) - 1), + CastOp::SExt => ((((x << (64 - sw)) as i64) >> (64 - sw)) as u64) & ((1u64 << dw) - 1), + _ => unreachable!(), + }; + Some(self.const_int(to, r)) + } + _ => None, + } + } + /// Whether an unused instruction can go. 64-bit values stay: helpers already set /// the Int64Ops / Doubles / DoubleExtensions flags for them. fn removable(&self, op: &Op, ty: Ty, wide: &[Ty]) -> bool { @@ -284,6 +429,7 @@ impl Module { Leave(usize), } let mut stack = if skip("cse") { Vec::new() } else { vec![Step::Enter(0)] }; + let mut cse_replaced = false; while let Some(step) = stack.pop() { let b = match step { Step::Leave(mark) => { @@ -304,16 +450,24 @@ impl Module { let i = self.blocks[b][k] as usize; let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); op.map_operands(|v| resolve(&mut repl, v)); - let kind = self.cse_kind(&op); - if repl[i].is_none() && kind != Cse::No { - let key = (op.clone(), self.insts[i].ty); - let t = if kind == Cse::Dom { &mut table } else { &mut local }; - if let Some(&v) = t.get(&key) { - repl[i] = Some(v); + if repl[i].is_none() { + if let Some(s) = self.simplify_op(&op, self.insts[i].ty) { + repl[i] = Some(s); + cse_replaced = true; } else { - let old = t.insert(key.clone(), Value::Inst(i as u32)); - if kind == Cse::Dom { - undo.push((key, old)); + let kind = self.cse_kind(&op); + if kind != Cse::No { + let key = (op.clone(), self.insts[i].ty); + let t = if kind == Cse::Dom { &mut table } else { &mut local }; + if let Some(&v) = t.get(&key) { + repl[i] = Some(v); + cse_replaced = true; + } else { + let old = t.insert(key.clone(), Value::Inst(i as u32)); + if kind == Cse::Dom { + undo.push((key, old)); + } + } } } } @@ -323,6 +477,42 @@ impl Module { stack.push(Step::Enter(c)); } } + // second trivial-phi fixed point if CSE/simplification collapsed incoming values + if cse_replaced && !skip("phi") { + loop { + let mut changed = false; + for &b in &order { + for &i in &self.blocks[b as usize] { + let i = i as usize; + if repl[i].is_some() { + continue; + } + let Op::Phi(inc) = &self.insts[i].op else { break }; + let me = Value::Inst(i as u32); + let mut same: Option = None; + let mut trivial = true; + for &(v, _) in inc { + let v = resolve(&mut repl, v); + if v == me || Some(v) == same { + continue; + } + if same.is_some() { + trivial = false; + break; + } + same = Some(v); + } + if let (true, Some(v)) = (trivial, same) { + repl[i] = Some(v); + changed = true; + } + } + } + if !changed { + break; + } + } + } // phis may name values defined later (back edges): resolve once more for &b in &order { for k in 0..self.blocks[b as usize].len() { diff --git a/crates/xcl/src/gpu/dxil/msaa_tests.rs b/crates/xcl/src/gpu/dxil/msaa_tests.rs new file mode 100644 index 0000000000..bd094f436e --- /dev/null +++ b/crates/xcl/src/gpu/dxil/msaa_tests.rs @@ -0,0 +1,254 @@ +//! Multisampled textures: the `dx.op` helpers (`Texture2DMS` / `Texture2DMSArray` loads, +//! sample counts, sample positions) and the direct translator's MSAA image instructions +//! (`image_load` / `image_msaa_load` / `image_get_resinfo` with DIM 2D_MSAA(_ARRAY)), run on +//! the GPU against a CPU reference. The test textures are filled sample by sample +//! (`runner::TexDim::D2Ms`). + +use super::container::Stage; +use super::module::{BinOp, CastOp, Value}; +use super::ops::*; +use super::shader::{RawUav, Shader}; +use super::validate; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim}; +use windows::Win32::Graphics::Dxgi::Common::*; + +fn check(c: &[u8]) { + if let Err(e) = validate::validate(c) { + let dis = validate::disassemble(c).unwrap_or_else(|d| d); + panic!("validator rejected the shader:\n{e}\n--- disassembly ---\n{dis}"); + } +} + +fn gpu_ready() -> bool { + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => true, + (a, _, d) => { + runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }); + false + } + } +} + +/// 4×4 RGBA32F, 4 samples: sample s of (x, y) = (x, y, s, x + 4y + 16s). +fn ms_rgba() -> TestTexture { + let mut data = Vec::new(); + for y in 0..4u32 { + for x in 0..4u32 { + for s in 0..4u32 { + for v in [x as f32, y as f32, s as f32, (x + 4 * y + 16 * s) as f32] { + data.extend_from_slice(&v.to_le_bytes()); + } + } + } + } + TestTexture { dim: TexDim::D2Ms(4), format: DXGI_FORMAT_R32G32B32A32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 16, data, uav: false } +} + +/// 4×4×3 R32_UINT array, 2 samples: 1000z + 100s + x + 4y. +fn ms_array_u32() -> TestTexture { + let mut data = Vec::new(); + for z in 0..3u32 { + for y in 0..4u32 { + for x in 0..4u32 { + for s in 0..2u32 { + data.extend_from_slice(&(1000 * z + 100 * s + x + 4 * y).to_le_bytes()); + } + } + } + } + TestTexture { dim: TexDim::D2MsArray(2), format: DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 3, texel_bytes: 4, data, uav: false } +} + +/// The ops: heap `Texture2DMS` / `Texture2DMSArray` loads per sample, +/// `GetDimensions` (sample count in `w`) and `GetSamplePosition`. +#[test] +fn msaa_texture_ops_run() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let res: RawUav = s.raw_uav(1, 0); + let lane = s.flattened_thread_id_in_group(); + let c = |s: &mut Shader, v: u32| s.m.i32c(v); + // lane → x = l % 4, y = l / 4 % 4, sample = l / 16 (32 lanes: samples 0, 1) + let x = { + let k = c(&mut s, 3); + s.m.bin(BinOp::And, lane, k) + }; + let y = { + let k = c(&mut s, 2); + let t = s.m.bin(BinOp::LShr, lane, k); + let k3 = c(&mut s, 3); + s.m.bin(BinOp::And, t, k3) + }; + let smp = { + let k = c(&mut s, 4); + s.m.bin(BinOp::LShr, lane, k) + }; + let i0 = c(&mut s, 0); + let i2 = c(&mut s, 2); + let t = s.heap_texture(i0, TexKind::D2MS, false, CompType::F32, 4, false); + let ta = s.heap_texture(i2, TexKind::D2MSArray, false, CompType::U32, 1, false); + let r = s.texture_load_sample(t, smp, &[x, y]); + // the array: slice = sample index too (0 / 1), sample 1 - smp + let one = c(&mut s, 1); + let other = s.m.bin(BinOp::Sub, one, smp); + let ra = s.texture_load_sample(ta, other, &[x, y, smp]); + let d = s.get_dimensions(t.handle, None); + let da = s.get_dimensions(ta.handle, None); + let pos = s.texture2dms_sample_position(t, smp); + let i32 = s.m.i32(); + let mut outs: Vec = r.iter().map(|&v| s.m.bitcast(v, i32)).collect(); + outs.push(ra[0]); + for i in [0, 1, 3] { + outs.push(s.m.extract(d, i)); + } + for i in [0, 1, 2, 3] { + outs.push(s.m.extract(da, i)); + } + for p in pos { + outs.push(s.m.bitcast(p, i32)); + } + for (k, &v) in outs.iter().enumerate() { + let base = c(&mut s, 64 * k as u32); + let i = s.m.bin(BinOp::Add, base, lane); + let two = c(&mut s, 2); + let off = s.m.bin(BinOp::Shl, i, two); + let v = if s.m.type_of(v) == s.m.i1() { s.m.cast(CastOp::ZExt, v, i32) } else { v }; + s.raw_store(res, off, &[v]); + } + let dxil = s.finish([32, 1, 1], Some(32)); + check(&dxil); + if !gpu_ready() || runner::wave32_supported() != Ok(true) { + return; + } + let tex = [ms_rgba(), ms_array_u32()]; + let r = runner::run_with(&dxil, &KernelState::default(), &[0; 64], &tex, &[]).expect("GPU run"); + let o = |k: usize, l: usize| r.raw[64 * k + l]; + let mut seen = Vec::new(); + for l in 0..32 { + let (x, y, s) = ((l % 4) as u32, (l / 4 % 4) as u32, (l / 16) as u32); + let got: Vec = (0..4).map(|k| f32::from_bits(o(k, l))).collect(); + assert_eq!(got, vec![x as f32, y as f32, s as f32, (x + 4 * y + 16 * s) as f32], "Texture2DMS load lane {l}"); + assert_eq!(o(4, l), 1000 * s + 100 * (1 - s) + x + 4 * y, "Texture2DMSArray load lane {l}"); + assert_eq!([o(5, l), o(6, l), o(7, l)], [4, 4, 4], "Texture2DMS dims lane {l}"); + assert_eq!([o(8, l), o(9, l), o(10, l), o(11, l)], [4, 4, 3, 2], "Texture2DMSArray dims lane {l}"); + let p = (f32::from_bits(o(12, l)), f32::from_bits(o(13, l))); + assert!((-0.5..0.5).contains(&p.0) && (-0.5..0.5).contains(&p.1), "sample position lane {l}: {p:?}"); + if l % 16 == 0 { + seen.push(p); + } + } + assert_ne!(seen[0], seen[1], "samples 0 and 1 at different positions"); +} + +/// `RenderTargetGetSampleCount` / `RenderTargetGetSamplePosition` validate in a pixel shader. +#[test] +fn render_target_sample_ops_validate() { + use super::graphics::{CompType as SigComp, GraphicsIo, SemKind, SigElement, StageInfo}; + let mut s = Shader::new(Stage::Pixel, (6, 6)); + let mut io = GraphicsIo::new(Stage::Pixel); + let _pos = io.input(SigElement::new("SV_Position", 0, SemKind::Position, SigComp::F32, 4)); + let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, SigComp::F32, 4)); + let n = s.render_target_sample_count(); + let f32 = s.m.f32(); + let nf = s.m.cast(CastOp::UIToFP, n, f32); + let one = s.m.i32c(1); + let p = s.render_target_sample_position(one); + let z = s.m.f32c(0); + for (c, v) in [nf, p[0], p[1], z].into_iter().enumerate() { + io.store_output(&mut s, tgt, 0, c as u8, v); + } + let c = s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }); + check(&c); +} + +fn mimg(name: &str, f: &[(&str, u64)]) -> Vec { + encode(name, "ENC_MIMG", f, None).unwrap_or_else(|e| panic!("{name}: {e}")) +} + +fn tsharp(index: u32, format: u32, ty: u32) -> [u32; 8] { + [index, format << 20, 0, ty << 28, 0, 0, 0, 0] +} + +fn run_direct(code: &[u8], st: &KernelState, tex: &[TestTexture]) -> runner::KernelResult { + let k = runner::direct_kernel_full(code, true).unwrap_or_else(|e| panic!("direct translation: {e}")); + check(&k.dxil); + runner::run_with_statics(&k.dxil, st, &[], tex, &[], &k.static_samplers).expect("GPU run") +} + +/// Console MSAA image instructions through the direct translator: `image_load` of one sample +/// (2D MSAA and 2D MSAA array), `image_msaa_load` (one component of four samples; samples +/// past the count read 0), `image_get_resinfo`, D16 `image_msaa_load`. +#[test] +fn gpu_direct_msaa_image_loads() { + let mut code = Vec::new(); + // T# 0: 2D MSAA RGBA32F (s[16:23], SRSRC 4); T# 1: 2D MSAA array R32_UINT (s[24:31], 6) + code.extend(mimg("IMAGE_LOAD", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0xF), ("DIM", 6), ("UNORM", 1)])); + code.extend(mimg("IMAGE_MSAA_LOAD", &[("VDATA", 14), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x8), ("DIM", 6), ("UNORM", 1)])); + code.extend(mimg("IMAGE_GET_RESINFO", &[("VDATA", 18), ("VADDR", 5), ("SRSRC", 4), ("DMASK", 0xF), ("DIM", 6)])); + code.extend(mimg("IMAGE_LOAD", &[("VDATA", 22), ("VADDR", 30), ("SRSRC", 6), ("DMASK", 0x1), ("DIM", 7), ("UNORM", 1)])); + code.extend(mimg("IMAGE_MSAA_LOAD", &[("VDATA", 24), ("VADDR", 30), ("SRSRC", 6), ("DMASK", 0x1), ("DIM", 7), ("UNORM", 1)])); + code.extend(mimg("IMAGE_GET_RESINFO", &[("VDATA", 40), ("VADDR", 5), ("SRSRC", 6), ("DMASK", 0xF), ("DIM", 7)])); + // D16: the y channel (exact small integers) of four samples as halves + code.extend(mimg("IMAGE_MSAA_LOAD", &[("VDATA", 44), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x2), ("DIM", 6), ("UNORM", 1), ("D16", 1)])); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + if !gpu_ready() { + return; + } + let mut st = KernelState::default(); + st.sgpr[16..24].copy_from_slice(&tsharp(0, 77, 14)); + st.sgpr[24..32].copy_from_slice(&tsharp(2, 20, 15)); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let (x, y) = ((l % 4) as u32, (l / 4 % 4) as u32); + r[0] = x; + r[1] = y; + r[2] = (l / 16) as u32; // fragment 0..3 + r[5] = 0; + r[30] = x; + r[31] = y; + r[32] = (l / 16 % 3) as u32; // slice + r[33] = (l % 2) as u32; // fragment + } + let r = run_direct(&code, &st, &[ms_rgba(), ms_array_u32()]); + for l in 0..64 { + let v = &r.vgpr[l]; + let (x, y, fr) = ((l % 4) as u32, (l / 4 % 4) as u32, (l / 16) as u32); + let fl = |i: usize| f32::from_bits(v[i]); + assert_eq!([fl(10), fl(11), fl(12), fl(13)], [x as f32, y as f32, fr as f32, (x + 4 * y + 16 * fr) as f32], "lane {l} image_load 2D MSAA"); + for k in 0..4u32 { + let s = fr + k; + let want = if s < 4 { (x + 4 * y + 16 * s) as f32 } else { 0.0 }; + assert_eq!(fl(14 + k as usize), want, "lane {l} image_msaa_load sample {s}"); + } + assert_eq!(&v[18..22], &[4, 4, 1, 1], "lane {l} resinfo 2D MSAA"); + let (z, f2) = ((l / 16 % 3) as u32, (l % 2) as u32); + assert_eq!(v[22], 1000 * z + 100 * f2 + x + 4 * y, "lane {l} image_load 2D MSAA array"); + for k in 0..4u32 { + let s = f2 + k; + let want = if s < 2 { 1000 * z + 100 * s + x + 4 * y } else { 0 }; + assert_eq!(v[24 + k as usize], want, "lane {l} image_msaa_load array sample {s}"); + } + assert_eq!(&v[40..44], &[4, 4, 3, 1], "lane {l} resinfo 2D MSAA array"); + let h = |s: u32| if s < 4 { half_bits(y as f32) } else { 0 }; + assert_eq!(v[44], h(fr) | h(fr + 1) << 16, "lane {l} d16 msaa_load lo"); + assert_eq!(v[45], h(fr + 2) | h(fr + 3) << 16, "lane {l} d16 msaa_load hi"); + } +} + +/// binary16 bits of a small integer-valued f32. +fn half_bits(v: f32) -> u32 { + if v == 0.0 { + return 0; + } + let b = v.to_bits(); + let e = ((b >> 23) & 0xFF) as i32 - 127 + 15; + ((e as u32) << 10) | ((b >> 13) & 0x3FF) +} + +/// Stores and atomics on MSAA T#s need writable MSAA textures (SM 6.7): a translation error. +#[test] +fn direct_msaa_store_is_rejected() { + let mut code = mimg("IMAGE_STORE", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 6), ("UNORM", 1)]); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let e = runner::direct_kernel(&code, true).unwrap_err(); + assert!(e.contains("MSAA"), "{e}"); +} diff --git a/crates/xcl/src/gpu/dxil/ops.rs b/crates/xcl/src/gpu/dxil/ops.rs index e0d4e71d66..75f2257c38 100644 --- a/crates/xcl/src/gpu/dxil/ops.rs +++ b/crates/xcl/src/gpu/dxil/ops.rs @@ -172,10 +172,14 @@ impl CompType { pub enum TexKind { D1 = 1, D2 = 2, + /// `Texture2DMS` (SRV only: writable MSAA UAVs need SM 6.7). + D2MS = 3, D3 = 4, Cube = 5, D1Array = 6, D2Array = 7, + /// `Texture2DMSArray` (SRV only). + D2MSArray = 8, CubeArray = 9, } @@ -184,8 +188,8 @@ impl TexKind { pub fn coords(self) -> usize { match self { TexKind::D1 => 1, - TexKind::D2 | TexKind::D1Array => 2, - TexKind::D3 | TexKind::D2Array | TexKind::Cube => 3, + TexKind::D2 | TexKind::D1Array | TexKind::D2MS => 2, + TexKind::D3 | TexKind::D2Array | TexKind::Cube | TexKind::D2MSArray => 3, TexKind::CubeArray => 4, } } @@ -193,7 +197,7 @@ impl TexKind { pub fn offsets(self) -> usize { match self { TexKind::D1 | TexKind::D1Array => 1, - TexKind::D2 | TexKind::D2Array => 2, + TexKind::D2 | TexKind::D2Array | TexKind::D2MS | TexKind::D2MSArray => 2, TexKind::D3 => 3, TexKind::Cube | TexKind::CubeArray => 0, } @@ -202,7 +206,7 @@ impl TexKind { pub fn grads(self) -> usize { match self { TexKind::D1 | TexKind::D1Array => 1, - TexKind::D2 | TexKind::D2Array => 2, + TexKind::D2 | TexKind::D2Array | TexKind::D2MS | TexKind::D2MSArray => 2, TexKind::D3 | TexKind::Cube | TexKind::CubeArray => 3, } } @@ -735,6 +739,7 @@ impl Shader { /// A texture from `ResourceDescriptorHeap[index]` with `ncomp` /// components of `comp` (`Texture2D` = `(D2, false, F32, 4)`). pub fn heap_texture(&mut self, index: Value, kind: TexKind, uav: bool, comp: CompType, ncomp: u32, nonuniform: bool) -> Texture { + assert!(!(uav && matches!(kind, TexKind::D2MS | TexKind::D2MSArray)), "RWTexture2DMS needs SM 6.7"); let h = self.handle_from_heap(index, false, nonuniform); let handle = self.annotate(h, kind as u32 | if uav { 0x1000 } else { 0 }, typed_props(comp, ncomp)); Texture { handle, kind, uav, comp } @@ -791,6 +796,32 @@ impl Shader { let r = self.op(66, "textureLoad", Some(t), rt, &args, FnAttrs::ReadOnly); self.ret4(r) } + /// `TextureLoad` of sample `sample` of a multisampled texture (`D2MS` / + /// `D2MSArray`: the op's `mipLevelOrSampleCount` operand is the sample index). + pub fn texture_load_sample(&mut self, tex: Texture, sample: Value, coords: &[Value]) -> [Value; 4] { + assert!(matches!(tex.kind, TexKind::D2MS | TexKind::D2MSArray) && !tex.uav, "texture_load_sample: a multisampled SRV"); + self.texture_load(tex, Some(sample), coords, &[]) + } + /// `Texture2DMSGetSamplePosition` (op 75): the position of sample `index` + /// relative to the pixel centre (`{x, y}`; (0, 0) for an invalid index). + pub fn texture2dms_sample_position(&mut self, tex: Texture, index: Value) -> [Value; 2] { + let f32 = self.m.f32(); + let st = self.m.named_struct("dx.types.SamplePos", &[f32, f32]); + let r = self.op(75, "texture2DMSGetSamplePosition", None, st, &[tex.handle, index], FnAttrs::ReadOnly); + [self.m.extract(r, 0), self.m.extract(r, 1)] + } + /// `RenderTargetGetSamplePosition` (op 76, pixel shaders). + pub fn render_target_sample_position(&mut self, index: Value) -> [Value; 2] { + let f32 = self.m.f32(); + let st = self.m.named_struct("dx.types.SamplePos", &[f32, f32]); + let r = self.op(76, "renderTargetGetSamplePosition", None, st, &[index], FnAttrs::ReadOnly); + [self.m.extract(r, 0), self.m.extract(r, 1)] + } + /// `RenderTargetGetSampleCount` (op 77, pixel shaders). + pub fn render_target_sample_count(&mut self) -> Value { + let i32 = self.m.i32(); + self.op(77, "renderTargetGetSampleCount", None, i32, &[], FnAttrs::ReadOnly) + } /// `TextureLoad` on a UAV loading more than one component needs /// `TypedUavLoadAdditionalFormats`; call this to declare it. pub fn typed_uav_load_additional_formats(&mut self) { @@ -928,6 +959,7 @@ impl Shader { /// components the resource kind defines (the validator rejects reads of /// undefined ones, e.g. `z` of a `Texture2D`). Buffers: `x` = elements /// (raw buffers: bytes). `mip` is `None` for UAVs and buffers. + /// Multisampled textures: `mip` `None`, the sample count in `w`. pub fn get_dimensions(&mut self, handle: Value, mip: Option) -> Value { let i32 = self.m.i32(); let st = self.m.named_struct("dx.types.Dimensions", &[i32, i32, i32, i32]); diff --git a/crates/xcl/src/gpu/dxil/round_tests.rs b/crates/xcl/src/gpu/dxil/round_tests.rs new file mode 100644 index 0000000000..876205b277 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/round_tests.rs @@ -0,0 +1,449 @@ +//! Directed f32 rounding in the direct translator (`lower_round`), on the GPU against a CPU +//! reference that rounds exact results (integer arithmetic with a sticky bit, independent of +//! the translator's f64 method). + +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::runner::{self, KernelState}; + +const V: u64 = 256; + +fn gpu_ready() -> bool { + match (runner::adapter(), runner::wave64_programs_supported()) { + (Ok(_), Ok(true)) => true, + (a, _) => { + runner::skip_test(if a.is_err() { "no GPU" } else { "no wave64" }); + false + } + } +} + +// ------------------------------------------------------------------ reference + +/// RDNA FP_ROUND: 0 nearest even, 1 +inf, 2 -inf, 3 zero. +#[derive(Clone, Copy, Debug)] +struct Mode { + rm: u32, + keep_in: bool, + keep_out: bool, +} + +/// f32 → (sign, m, e) with value m · 2^e (m < 2^24); None for inf / NaN. +fn parts(x: u32, keep_in: bool) -> Option<(bool, u128, i32)> { + let s = x >> 31 == 1; + let e = ((x >> 23) & 0xFF) as i32; + let f = (x & 0x7F_FFFF) as u128; + match e { + 255 => None, + 0 if !keep_in => Some((s, 0, 0)), + 0 => Some((s, f, -149)), + _ => Some((s, f | 1 << 23, e - 150)), + } +} + +fn bitlen(v: u128) -> i32 { + 128 - v.leading_zeros() as i32 +} + +/// Round sign · (mag · 2^exp + sticky·ε) (0 < ε ≪ 2^exp) to f32 bits. +fn round(sign: bool, mag: u128, exp: i32, sticky: bool, m: Mode) -> u32 { + let sg = (sign as u32) << 31; + if mag == 0 && !sticky { + return sg; + } + // a lone sticky: some value far below every f32 + let (mag, exp) = if mag == 0 { (1u128, -400) } else { (mag, exp) }; + let top = bitlen(mag) - 1 + exp; // value in [2^top, 2^(top+1)) + let mut lsb = if top < -126 { -149 } else { top - 23 }; + let sh = lsb - exp; + let (mut kept, rem, half) = if sh >= 128 { + (0u128, 1u128, u128::MAX) + } else if sh > 0 { + (mag >> sh, mag & ((1u128 << sh) - 1), 1u128 << (sh - 1)) + } else { + (mag << (-sh), 0, 1) + }; + let inexact = rem != 0 || sticky; + let up = match m.rm { + 0 => rem > half || (rem == half && (sticky || kept & 1 == 1)), + 1 => inexact && !sign, + 2 => inexact && sign, + _ => false, + }; + kept += up as u128; + if kept >= 1 << 24 { + kept >>= 1; + lsb += 1; + } + let away = match m.rm { + 0 => true, + 1 => !sign, + 2 => sign, + _ => false, + }; + if lsb + 23 > 127 { + return sg | if away { 0x7F80_0000 } else { 0x7F7F_FFFF }; + } + let bits = if kept < 1 << 23 { kept as u32 } else { (((lsb + 23 + 127) as u32) << 23) | (kept as u32 - (1 << 23)) }; + if !m.keep_out && bits < 0x80_0000 { + return sg; + } + sg | bits +} + +/// Exact sum of ±ma·2^ea and ±mb·2^eb → round. `both_pos_zero`: both addends are +0. +fn sum(sa: bool, ma: u128, ea: i32, sb: bool, mb: u128, eb: i32, m: Mode, both_pos_zero: bool) -> u32 { + if ma == 0 && mb == 0 { + let neg = if m.rm == 2 { !both_pos_zero } else { sa && sb }; + return (neg as u32) << 31; + } + let tops = [if ma == 0 { i32::MIN } else { ea + bitlen(ma) }, if mb == 0 { i32::MIN } else { eb + bitlen(mb) }]; + let t = tops[0].max(tops[1]) - 100; + // an operand entirely below 2^t is < 2^(T-52): only a sticky bit for the result + let al = |mm: u128, e: i32| -> (u128, bool) { + if mm == 0 { + (0, false) + } else if e >= t { + (mm << (e - t), false) + } else { + (0, true) + } + }; + let (a, ast) = al(ma, ea); + let (b, bst) = al(mb, eb); + let va = if sa { -(a as i128) } else { a as i128 }; + let vb = if sb { -(b as i128) } else { b as i128 }; + let s = va + vb; + let st_sign = if ast { Some(sa) } else if bst { Some(sb) } else { None }; + if s == 0 && st_sign.is_none() { + // exact cancellation: +0, or -0 toward -inf + return ((m.rm == 2) as u32) << 31; + } + let neg = s < 0 || (s == 0 && st_sign == Some(true)); + let mag = s.unsigned_abs(); + match st_sign { + None => round(neg, mag, t, false, m), + Some(ss) if ss == neg || mag == 0 => round(neg, mag, t, true, m), + // |s| - ε = (|s| - 1) + (1 - ε) + Some(_) => round(neg, mag - 1, t, true, m), + } +} + +fn is_nan(x: u32) -> bool { + x & 0x7FFF_FFFF > 0x7F80_0000 +} + +/// The CPU result of an operation on f32 bits; None: a special case left to native (inf/NaN). +fn ref_add(a: u32, b: u32, m: Mode) -> Option { + let (sa, ma, ea) = parts(a, m.keep_in)?; + let (sb, mb, eb) = parts(b, m.keep_in)?; + let bpz = !sa && !sb; + Some(sum(sa, ma, ea, sb, mb, eb, m, bpz)) +} + +fn ref_mul(a: u32, b: u32, m: Mode) -> Option { + let (sa, ma, ea) = parts(a, m.keep_in)?; + let (sb, mb, eb) = parts(b, m.keep_in)?; + Some(round(sa ^ sb, ma * mb, ea + eb, false, m)) +} + +fn ref_fma(a: u32, b: u32, c: u32, m: Mode) -> Option { + let (sa, ma, ea) = parts(a, m.keep_in)?; + let (sb, mb, eb) = parts(b, m.keep_in)?; + let (sc, mc, ec) = parts(c, m.keep_in)?; + let sp = sa ^ sb; + let bpz = !sp && !sc; + Some(sum(sp, ma * mb, ea + eb, sc, mc, ec, m, bpz)) +} + +fn ref_sqrt(a: u32, m: Mode) -> Option { + let (s, ma, ea) = parts(a, m.keep_in)?; + if ma == 0 { + return Some((s as u32) << 31); + } + if s { + return None; + } + // sqrt(ma · 2^ea): make the exponent even and the integer large (≥ 2^100) + let (mut mm, mut e) = (ma, ea); + if e & 1 != 0 { + mm <<= 1; + e -= 1; + } + let k = (100 - bitlen(mm)).max(0) & !1; + mm <<= k; + e -= k; + let r = isqrt(mm); + Some(round(false, r, e / 2, r * r != mm, m)) +} + +fn isqrt(n: u128) -> u128 { + let mut x = (n as f64).sqrt() as u128; + while x * x > n { + x -= 1; + } + while (x + 1) * (x + 1) <= n { + x += 1; + } + x +} + +fn ref_cvt_int(a: u32, signed: bool, m: Mode) -> u32 { + let (neg, mag) = if signed { ((a as i32) < 0, (a as i32).unsigned_abs()) } else { (false, a) }; + round(neg, mag as u128, 0, false, m) +} + +fn ref_ldexp(a: u32, n: i32, m: Mode) -> Option { + let (s, ma, ea) = parts(a, m.keep_in)?; + if ma == 0 { + return Some((s as u32) << 31); + } + Some(round(s, ma, ea + n.clamp(-400, 400), false, m)) +} + +fn ref_cvt_f64(d: u64, m: Mode) -> Option { + let s = d >> 63 == 1; + let e = ((d >> 52) & 0x7FF) as i32; + let f = (d & ((1 << 52) - 1)) as u128; + match e { + 0x7FF => None, + 0 => Some(round(s, f, -1074, false, m)), + _ => Some(round(s, f | 1 << 52, e - 1075, false, m)), + } +} + +// ------------------------------------------------------------------ inputs + +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u32 { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 32) as u32 + } + /// An f32 with an exponent from a chosen band (denormal, small, unit, large, near overflow). + fn f32(&mut self) -> u32 { + let r = self.next(); + let sign = r & 0x8000_0000; + let mant = self.next() & 0x7F_FFFF; + let exp = match r % 8 { + 0 => 0, + 1 => 1 + r / 8 % 30, + 2 => 254 - r / 8 % 4, + _ => 110 + r / 8 % 36, + }; + sign | exp << 23 | mant + } +} + +/// Lane inputs: v0 a, v1 b, v2 c, v3 integer, v4 ldexp exponent, v[6:7] f64. +fn inputs(seed: u64) -> Vec<[u32; 8]> { + let mut g = Rng(seed); + let mut v = Vec::new(); + for l in 0..64 { + let a = g.f32(); + let mut b = g.f32(); + let mut c = g.f32(); + match l % 8 { + // exact cancellation (zero signs), nearby magnitudes, tiny addend + 0 => b = a ^ 0x8000_0000, + 1 => b = (a & 0xFF80_0000) | (g.next() & 0x7F_FFFF), + 2 => b = (a & 0x8000_0000) | 0x0000_0001, + 3 => c = 0x8000_0000 | (g.next() & 0x7F_FFFF), + _ => {} + } + if l == 5 { + b = 0x8000_0000; // +x + -0 + } + let i = g.next(); + let n = (g.next() % 300) as i32 - 200; + let d = ((g.next() as u64) << 32 | g.next() as u64) & !(0x7FFu64 << 52) | ((800 + g.next() % 450) as u64) << 52; + v.push([a, b, c, i, n as u32, 0, d as u32, (d >> 32) as u32]); + } + v +} + +fn ops_program(prefix: &[Vec]) -> Vec { + let mut code: Vec = prefix.concat(); + let ins: &[(&str, &str, &[(&str, u64)])] = &[ + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V), ("VSRC1", 1)]), + ("V_SUB_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V), ("VSRC1", 1)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", V), ("VSRC1", 1)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2)]), + ("V_SQRT_F32", "ENC_VOP1", &[("VDST", 14), ("SRC0", V)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 3)]), + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 16), ("SRC0", V + 3)]), + ("V_LDEXP_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V), ("SRC1", V + 4)]), + ("V_MAD_F32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2)]), + ("V_CVT_F32_F64", "ENC_VOP1", &[("VDST", 19), ("SRC0", V + 6)]), + // abs / neg source modifiers + ("V_ADD_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V), ("SRC1", V + 1), ("ABS", 1), ("NEG", 2)]), + ]; + for (n, e, f) in ins { + code.extend(encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code +} + +fn check_lane(l: usize, v: &[u32], inp: &[u32; 8], m: Mode) { + let (a, b, c, i, n) = (inp[0], inp[1], inp[2], inp[3], inp[4] as i32); + let d = inp[6] as u64 | (inp[7] as u64) << 32; + let neg = |x: u32| x ^ 0x8000_0000; + let cases: [(&str, usize, Option); 11] = [ + ("add", 10, ref_add(a, b, m)), + ("sub", 11, ref_add(a, neg(b), m)), + ("mul", 12, ref_mul(a, b, m)), + ("fma", 13, ref_fma(a, b, c, m)), + ("sqrt", 14, ref_sqrt(a, m)), + ("cvt_f32_i32", 15, Some(ref_cvt_int(i, true, m))), + ("cvt_f32_u32", 16, Some(ref_cvt_int(i, false, m))), + ("ldexp", 17, ref_ldexp(a, n, m)), + // mad: the product rounded, then the sum + ("mad", 18, ref_mul(a, b, m).and_then(|p| if is_nan(p) || p & 0x7FFF_FFFF == 0x7F80_0000 { None } else { ref_add(p, c, m) })), + ("cvt_f32_f64", 19, ref_cvt_f64(d, m)), + ("add |a| + -b", 20, ref_add(a & 0x7FFF_FFFF, neg(b), m)), + ]; + for (name, r, want) in cases { + let Some(want) = want else { continue }; + let got = v[r]; + if is_nan(want) && is_nan(got) { + continue; + } + assert_eq!(got, want, "lane {l} {name} mode {m:?}: inputs a {a:#010x} b {b:#010x} c {c:#010x} i {i:#x} n {n} d {d:#018x}: got {:e} want {:e}", f32::from_bits(got), f32::from_bits(want)); + } +} + +fn run(code: &[u8], st: &KernelState) -> runner::KernelResult { + let k = runner::direct_kernel_full(code, true).unwrap_or_else(|e| panic!("direct translation: {e}")); + if let Err(e) = super::validate::validate(&k.dxil) { + panic!("validator: {e}"); + } + runner::run_with_statics(&k.dxil, st, &[], &[], &[], &k.static_samplers).expect("GPU run") +} + +fn state(inp: &[[u32; 8]]) -> KernelState { + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[..8].copy_from_slice(&inp[l]); + } + st +} + +/// The reference itself on hand-checked values. +#[test] +fn directed_reference_basics() { + let m = |rm| Mode { rm, keep_in: true, keep_out: true }; + let one = 1.0f32.to_bits(); + let tiny = 1; + assert_eq!(ref_add(one, tiny, m(1)), Some(one + 1)); + assert_eq!(ref_add(one, tiny, m(2)), Some(one)); + assert_eq!(ref_add(one, tiny | 0x8000_0000, m(3)), Some(one - 1)); + assert_eq!(ref_add(one, tiny | 0x8000_0000, m(0)), Some(one)); + assert_eq!(ref_add(one, one | 0x8000_0000, m(2)), Some(0x8000_0000)); + assert_eq!(ref_add(one, one | 0x8000_0000, m(1)), Some(0)); + assert_eq!(ref_mul(f32::MAX.to_bits(), 2.0f32.to_bits(), m(3)), Some(f32::MAX.to_bits())); + assert_eq!(ref_mul(f32::MAX.to_bits(), 2.0f32.to_bits(), m(1)), Some(0x7F80_0000)); + assert_eq!(ref_mul(f32::MAX.to_bits() | 0x8000_0000, 2.0f32.to_bits(), m(1)), Some(f32::MAX.to_bits() | 0x8000_0000)); + assert_eq!(ref_sqrt(2.0f32.to_bits(), m(3)), Some(2f32.sqrt().to_bits())); + assert_eq!(ref_sqrt(2.0f32.to_bits(), m(1)), Some(2f32.sqrt().to_bits() + 1)); + assert_eq!(ref_sqrt(4.0f32.to_bits(), m(1)), Some(2.0f32.to_bits())); + assert_eq!(ref_cvt_int(0x0100_0001, false, m(1)), 16777218f32.to_bits()); + assert_eq!(ref_cvt_int(0x0100_0001, false, m(3)), 16777216f32.to_bits()); + // RNE reference agrees with the host on random sums / products + let mut g = Rng(7); + for _ in 0..20000 { + let (a, b, c) = (g.f32(), g.f32(), g.f32()); + let (fa, fb, fc) = (f32::from_bits(a), f32::from_bits(b), f32::from_bits(c)); + if let Some(r) = ref_add(a, b, m(0)) { + assert!(r == (fa + fb).to_bits() || is_nan(r), "add {a:#x} {b:#x}"); + } + if let Some(r) = ref_mul(a, b, m(0)) { + assert_eq!(r, (fa * fb).to_bits(), "mul {a:#x} {b:#x}"); + } + if let Some(r) = ref_fma(a, b, c, m(0)) { + assert!(r == fa.mul_add(fb, fc).to_bits() || is_nan(r), "fma {a:#x} {b:#x} {c:#x}"); + } + if let Some(r) = ref_sqrt(a, m(0)) { + assert_eq!(r, fa.sqrt().to_bits(), "sqrt {a:#x}"); + } + // directed results bracket the exact value: RTN ≤ RNE ≤ RTP, RTZ toward zero + if let (Some(lo), Some(hi)) = (ref_add(a, b, m(2)), ref_add(a, b, m(1))) { + let (lo, hi) = (f32::from_bits(lo), f32::from_bits(hi)); + assert!(lo <= fa + fb && fa + fb <= hi, "bracket {a:#x} {b:#x}"); + } + } +} + +/// Constant modes from `s_round_mode`: every rounding op, all three directions. +#[test] +fn gpu_direct_f32_round_modes_static() { + if !gpu_ready() { + return; + } + for rm in [1u32, 2, 3] { + let code = ops_program(&[encode("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", rm as u64)], None).unwrap()]); + let k = runner::direct_kernel_full(&code, true).unwrap_or_else(|e| panic!("direct translation: {e}")); + for seed in 0..16u64 { + let inp = inputs(rm as u64 * 977 + seed * 13); + let r = runner::run_with_statics(&k.dxil, &state(&inp), &[], &[], &[], &k.static_samplers).expect("GPU run"); + let m = Mode { rm, keep_in: true, keep_out: true }; + for l in 0..64 { + check_lane(l, &r.vgpr[l], &inp[l], m); + } + } + } +} + +/// A run-time mode (`s_setreg_b32` of MODE[1:0] from s0) and denormal flushing +/// (`s_denorm_mode 0`), plus a return to nearest even. +#[test] +fn gpu_direct_f32_round_modes_dynamic_and_denormals() { + if !gpu_ready() { + return; + } + let hw = |id: u64, off: u64, w: u64| id | off << 6 | (w - 1) << 11; + for rm in [0u32, 1, 2, 3] { + let code = ops_program(&[encode("S_SETREG_B32", "ENC_SOPK", &[("SIMM16", hw(1, 0, 2)), ("SDST", 0)], None).unwrap()]); + let inp = inputs(31 + rm as u64); + let mut st = state(&inp); + st.sgpr[0] = rm; + let r = run(&code, &st); + let m = Mode { rm, keep_in: true, keep_out: true }; + for l in 0..64 { + if rm == 0 { + // nearest even: the translator's usual code; check the exactly rounded ops + let v = &r.vgpr[l]; + let (a, b) = (inp[l][0], inp[l][1]); + let want = ref_add(a, b, m); + if let Some(w) = want { + let den = |x: u32| x & 0x7F80_0000 == 0 && x & 0x7F_FFFF != 0; + if !den(a) && !den(b) && !den(w) { + assert_eq!(v[10], w, "lane {l} add RNE"); + } + } + } else { + check_lane(l, &r.vgpr[l], &inp[l], m); + } + } + } + // flushed denormals (FP_DENORM single = 0) with round toward +inf + let code = ops_program(&[ + encode("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 1)], None).unwrap(), + encode("S_DENORM_MODE", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap(), + ]); + let inp = inputs(4242); + let r = run(&code, &state(&inp)); + let m = Mode { rm: 1, keep_in: false, keep_out: false }; + for l in 0..64 { + check_lane(l, &r.vgpr[l], &inp[l], m); + } +} + +/// Unimplemented directed ops are translation errors, not silent nearest-even results. +#[test] +fn direct_f32_round_mode_unsupported_op_rejected() { + let mut code = encode("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 3)], None).unwrap(); + code.extend(encode("V_DOT2_F32_F16", "ENC_VOP3P", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("SRC2", V)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let e = runner::direct_kernel(&code, true).unwrap_err(); + assert!(e.contains("directed f32 rounding"), "{e}"); +} diff --git a/crates/xcl/src/gpu/dxil/tests.rs b/crates/xcl/src/gpu/dxil/tests.rs index 67e6baf0dc..af8d2e960e 100644 --- a/crates/xcl/src/gpu/dxil/tests.rs +++ b/crates/xcl/src/gpu/dxil/tests.rs @@ -177,3 +177,42 @@ fn blocks_are_written_in_reverse_post_order() { let want: Vec = (0..64).map(|l| ((l as u32) << 2) + 7 + sgpr[l]).collect(); assert_eq!(&r.raw[..64], &want[..]); } + +/// `replace_uses` makes a whole map of trivial phis in one pass and leaves the module as +/// `replace_all_uses` one at a time in order does, a chain included (`a → b`, then `b → v`, +/// as the SSA construction makes when `b` turns trivial after `a`). +#[test] +fn batched_replacements_match_one_at_a_time() { + let build = |batched: bool| { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let io = s.raw_uav(0, 0); + let res = s.raw_uav(1, 0); + let lane = s.thread_id_in_group(0); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, lane, two); + let next = s.m.new_block(); + let x = s.raw_load(io, off, 1)[0]; + s.m.br(next); + let entry = s.m.entry_block(); + s.m.set_block(next); + let i32 = s.m.i32(); + let b = s.m.phi(i32); + s.m.add_incoming(b, x, entry); + let a = s.m.phi(i32); + s.m.add_incoming(a, b, entry); + let sum = s.m.bin(BinOp::Add, a, b); + s.raw_store(res, off, &[sum]); + if batched { + s.m.replace_uses(&std::collections::HashMap::from([(a, b), (b, x)])); + } else { + s.m.replace_all_uses(a, b); + s.m.replace_all_uses(b, x); + } + s.finish([64, 1, 1], None) + }; + let c = build(true); + assert_eq!(c, build(false)); + if let Err(e) = validate::validate(&c) { + panic!("validator rejected the kernel:\n{e}"); + } +} diff --git a/crates/xcl/src/gpu/recomp/dxil/assemble.rs b/crates/xcl/src/gpu/recomp/dxil/assemble.rs new file mode 100644 index 0000000000..490db860aa --- /dev/null +++ b/crates/xcl/src/gpu/recomp/dxil/assemble.rs @@ -0,0 +1,129 @@ +//! A DXIL module as LLVM IR text (or bitcode) to a signed container, through the PC DXC's +//! libraries: `dxcompiler.dll`'s assembler builds the container from the module's `dx.*` +//! metadata, `dxil.dll`'s validator checks and signs it. Neither DXC's HLSL front end nor its +//! optimiser runs: a retail compute program's module (8.6 MB of IR, 1 MB of DXIL) takes 0.75 s, +//! where its HLSL takes 25 s through `dxc::compile`. +//! +//! What a module needs on top of what the validator checks (RX 7800 XT, Windows driver): +//! an `!llvm.ident`. Without one the container validates and signs, but +//! `CreateComputePipelineState` faults inside the AMD driver. + +use std::ffi::c_void; + +use windows::core::{Interface, GUID, HRESULT}; +use windows::Win32::Graphics::Direct3D::Dxc::{ + DxcValidatorFlags_InPlaceEdit, IDxcAssembler, IDxcOperationResult, IDxcUtils, IDxcValidator, CLSID_DxcAssembler, CLSID_DxcUtils, CLSID_DxcValidator, DXC_CP_UTF8, +}; + +type CreateInstance = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT; + +fn errors(r: &IDxcOperationResult) -> String { + unsafe { r.GetErrorBuffer().map(|b| String::from_utf8_lossy(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize())).into_owned()).unwrap_or_default() } +} + +unsafe fn make(create: CreateInstance, clsid: &GUID) -> Result { + let mut p = std::ptr::null_mut(); + create(clsid, &T::IID, &mut p).ok().map_err(|e| format!("DxcCreateInstance: {e}"))?; + Ok(T::from_raw(p)) +} + +/// The module `ir` as a validated, signed DXIL container; the assembler's or the validator's +/// messages as the error. +pub fn assemble(ir: &str) -> Result, String> { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; + let create = super::super::dxc::create_instance().ok_or("dxcompiler.dll not found")?; + unsafe { + let create = std::mem::transmute::(create); + // (`dxc` loaded dxil.dll by its full path, before dxcompiler.dll) + let signer = GetModuleHandleW(crate::util::wide("dxil.dll").as_ptr()); + let sign = (!signer.is_null()).then(|| GetProcAddress(signer, b"DxcCreateInstance\0".as_ptr())).flatten().ok_or("assemble: no dxil.dll to sign with")?; + let utils: IDxcUtils = make(create, &CLSID_DxcUtils)?; + let blob = utils.CreateBlob(ir.as_ptr() as *const c_void, ir.len() as u32, DXC_CP_UTF8).map_err(|e| format!("assemble: {e}"))?; + let asm: IDxcAssembler = make(create, &CLSID_DxcAssembler)?; + let r = asm.AssembleToContainer(&blob).map_err(|e| format!("assemble: {e}"))?; + if r.GetStatus().map_err(|e| format!("assemble: {e}"))?.is_err() { + return Err(format!("assemble: {}", errors(&r))); + } + let container = r.GetResult().map_err(|e| format!("assemble: {e}"))?; + let v: IDxcValidator = make(std::mem::transmute::(sign as usize), &CLSID_DxcValidator)?; + let r = v.Validate(&container, DxcValidatorFlags_InPlaceEdit).map_err(|e| format!("validate: {e}"))?; + if r.GetStatus().map_err(|e| format!("validate: {e}"))?.is_err() { + return Err(format!("validate: {}", errors(&r))); + } + Ok(std::slice::from_raw_parts(container.GetBufferPointer() as *const u8, container.GetBufferSize()).to_vec()) + } +} + +#[cfg(test)] +mod tests { + use super::super::super::runner; + + /// A CS of the ABI root signature, written by hand: `mem[i] = 3 i + 1` through `u2`. + const IR: &str = r#"target datalayout = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64" +target triple = "dxil-ms-dx" +%dx.types.Handle = type { i8* } +%dx.types.ResBind = type { i32, i32, i32, i8 } +%dx.types.ResourceProperties = type { i32, i32 } +%struct.RWByteAddressBuffer = type { i32 } +define void @main() { + %1 = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 2, i32 2, i32 0, i8 1 }, i32 2, i1 false) + %2 = call i32 @dx.op.threadId.i32(i32 93, i32 0) + %3 = mul i32 %2, 3 + %4 = add i32 %3, 1 + %5 = shl i32 %2, 2 + %6 = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle %1, %dx.types.ResourceProperties { i32 4107, i32 0 }) + call void @dx.op.rawBufferStore.i32(i32 140, %dx.types.Handle %6, i32 %5, i32 undef, i32 %4, i32 undef, i32 undef, i32 undef, i8 1, i32 4) + ret void +} +declare i32 @dx.op.threadId.i32(i32, i32) #0 +declare void @dx.op.rawBufferStore.i32(i32, %dx.types.Handle, i32, i32, i32, i32, i32, i32, i8, i32) #1 +declare %dx.types.Handle @dx.op.annotateHandle(i32, %dx.types.Handle, %dx.types.ResourceProperties) #0 +declare %dx.types.Handle @dx.op.createHandleFromBinding(i32, %dx.types.ResBind, i32, i1) #0 +attributes #0 = { nounwind readnone } +attributes #1 = { nounwind } +!llvm.ident = !{!0} +!dx.version = !{!1} +!dx.valver = !{!2} +!dx.shaderModel = !{!3} +!dx.resources = !{!4} +!dx.entryPoints = !{!7} +!0 = !{!"xcl"} +!1 = !{i32 1, i32 6} +!2 = !{i32 1, i32 6} +!3 = !{!"cs", i32 6, i32 6} +!4 = !{null, !5, null, null} +!5 = !{!6} +!6 = !{i32 0, %struct.RWByteAddressBuffer* undef, !"", i32 0, i32 2, i32 1, i32 11, i1 false, i1 false, i1 false, null} +!7 = !{void ()* @main, !"main", null, !4, !8} +!8 = !{i32 0, i64 16, i32 4, !9} +!9 = !{i32 64, i32 1, i32 1} +"#; + + /// The text assembles, signs and runs on the GPU; a module the validator rejects (a use + /// before its definition) is an error, not a container. + #[test] + fn ir_text_assembles_signs_and_runs() { + if super::super::super::dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + // a Windows SDK's `bin\\x64` has dxcompiler.dll without dxil.dll: nothing to sign with + let dxil = match super::assemble(IR) { + Err(e) if e.contains("no dxil.dll") => { + runner::skip_test("no dxil.dll"); + return; + } + r => r.unwrap(), + }; + assert_eq!(&dxil[..4], b"DXBC"); + let bad = super::assemble(&IR.replace("%3 = mul i32 %2, 3", "%3 = mul i32 %4, 3")).unwrap_err(); + assert!(bad.contains("dominate"), "{bad}"); + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return; + } + let out = runner::dispatch(&dxil, [1, 1, 1], &[], &[0u32; 64]).unwrap(); + let want: Vec = (0..64).map(|i| 3 * i + 1).collect(); + assert_eq!(&out[..64], &want[..]); + } +} diff --git a/crates/xcl/src/gpu/recomp/dxil/mod.rs b/crates/xcl/src/gpu/recomp/dxil/mod.rs new file mode 100644 index 0000000000..fb1a5dffd8 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/dxil/mod.rs @@ -0,0 +1,3 @@ +//! A DXIL module without HLSL: assembled and signed from LLVM IR text (`assemble`). + +pub mod assemble; diff --git a/crates/xcl/src/gpu/recomp/lane_masks.rs b/crates/xcl/src/gpu/recomp/lane_masks.rs new file mode 100644 index 0000000000..bdb04fb157 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lane_masks.rs @@ -0,0 +1,1099 @@ +//! Lane masks as per-lane booleans: what a backend that writes DXIL itself (no HLSL, so no +//! structured control flow) needs in order to run console code without emulating EXEC. +//! +//! The HLSL path keeps EXEC as a wave-uniform value and guards every vector write with the +//! lane's bit of it. With an unstructured CFG each lane can instead branch on its own bit and +//! leave reconvergence to the host driver. Per program this works out: +//! - every lane mask (EXEC, VCC, any SGPR a mask is kept in) as a boolean function of *atoms* – +//! the lane's result of a VALU compare or carry, a wave-uniform SCC, a mask it cannot follow, +//! a join it cannot resolve – as a reduced ordered BDD; +//! - every branch on a mask (`s_cbranch_execz/execnz/vccz/vccnz`, SCC of a mask op) as a branch +//! of each lane on its own bit, and a branch on any other SCC as a uniform one; +//! - for every block, what holds in each lane that reaches it: a forward dataflow over the +//! branch conditions; facts a back edge carries about atoms its loop redefines are dropped; +//! - which vector instructions still need a guard: those where reaching the instruction does +//! not imply the lane's EXEC bit. +//! +//! Branching lane by lane on a mask assumes what compiled code does: it jumps over work that +//! inactive lanes would not change anyway, or it tests a uniform value. A join of a mask is +//! resolved when every lane coming in has it set (or clear) – EXEC restored where the branches +//! meet – and becomes an atom otherwise. A loop head's join is guessed from its forward edges +//! and checked against its back edges; a wrong guess becomes an atom and the analysis restarts. +//! +//! Nothing translates with this yet: `xcl shaders --recomp` reports its counts. + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use super::x64_masks; +use crate::gpu::rdna2::{self, Decoded, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR}; + +type R = Result; + +/// A BDD node: 0 = false, 1 = true. +type B = u32; +const FALSE: B = 0; +const TRUE: B = 1; +/// More nodes than this: the program fails with "lane conditions too large". +const MAX_NODES: usize = 1 << 20; +/// New nodes one reach fact may take before it is weakened. +const STEP_NODES: usize = 1 << 9; +/// Passes of the reach fixpoint, restarts after wrong loop-head guesses included. +const MAX_ROUNDS: usize = 256; +const EXEC: usize = 126; +const VCC: usize = 106; +/// The SCC slot of a join. +const SCC: usize = 128; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Op { + And, + Or, + Xor, +} + +struct Bdd { + /// (atom, low, high); the terminals have atom u32::MAX, so atoms created first are on top + nodes: Vec<(u32, B, B)>, + unique: HashMap<(u32, B, B), B>, + memo: HashMap<(Op, B, B), B>, + /// node count `mk` fails at + limit: usize, +} + +impl Bdd { + fn new() -> Self { + Bdd { nodes: vec![(u32::MAX, 0, 0), (u32::MAX, 1, 1)], unique: HashMap::new(), memo: HashMap::new(), limit: MAX_NODES } + } + + /// `f`'s result, or None when it needs more than `STEP_NODES` new nodes (those it made stay: + /// they are valid nodes, and the memo stays right). For results that can be weakened. + fn within(&mut self, f: impl FnOnce(&mut Self) -> R) -> Option { + self.limit = (self.nodes.len() + STEP_NODES).min(MAX_NODES); + let r = f(self); + self.limit = MAX_NODES; + r.ok() + } + + /// The function "atom v", whatever the limits: what a weakened result falls back on. + fn atom(&mut self, v: u32) -> B { + if let Some(&n) = self.unique.get(&(v, FALSE, TRUE)) { + return n; + } + let n = self.nodes.len() as B; + self.nodes.push((v, FALSE, TRUE)); + self.unique.insert((v, FALSE, TRUE), n); + n + } + + fn mk(&mut self, v: u32, lo: B, hi: B) -> R { + if lo == hi { + return Ok(lo); + } + if let Some(&n) = self.unique.get(&(v, lo, hi)) { + return Ok(n); + } + if self.nodes.len() >= self.limit { + return Err("lane conditions too large"); + } + let n = self.nodes.len() as B; + self.nodes.push((v, lo, hi)); + self.unique.insert((v, lo, hi), n); + Ok(n) + } + + fn apply(&mut self, op: Op, a: B, b: B) -> R { + let (a, b) = (a.min(b), a.max(b)); + match (op, a) { + (Op::And, FALSE) => return Ok(FALSE), + (Op::Or, TRUE) => return Ok(TRUE), + (Op::And, TRUE) | (Op::Or | Op::Xor, FALSE) => return Ok(b), + _ if a == b => return Ok(if op == Op::Xor { FALSE } else { a }), + _ => {} + } + if let Some(&n) = self.memo.get(&(op, a, b)) { + return Ok(n); + } + let (na, nb) = (self.nodes[a as usize], self.nodes[b as usize]); + let v = na.0.min(nb.0); + let (a0, a1) = if na.0 == v { (na.1, na.2) } else { (a, a) }; + let (b0, b1) = if nb.0 == v { (nb.1, nb.2) } else { (b, b) }; + let lo = self.apply(op, a0, b0)?; + let hi = self.apply(op, a1, b1)?; + let n = self.mk(v, lo, hi)?; + self.memo.insert((op, a, b), n); + Ok(n) + } + + fn and(&mut self, a: B, b: B) -> R { + self.apply(Op::And, a, b) + } + + fn or(&mut self, a: B, b: B) -> R { + self.apply(Op::Or, a, b) + } + + fn not(&mut self, a: B) -> R { + self.apply(Op::Xor, a, TRUE) + } + + /// a → b, without building a ∧ ¬b. + fn implies(&self, a: B, b: B) -> bool { + self.implies_in(a, b, &mut HashSet::new()) + } + + fn implies_in(&self, a: B, b: B, seen: &mut HashSet<(B, B)>) -> bool { + if a == FALSE || b == TRUE || a == b { + return true; + } + if a == TRUE && b == FALSE { + return false; + } + if !seen.insert((a, b)) { + return true; + } + let (na, nb) = (self.nodes[a as usize], self.nodes[b as usize]); + let v = na.0.min(nb.0); + let (a0, a1) = if na.0 == v { (na.1, na.2) } else { (a, a) }; + let (b0, b1) = if nb.0 == v { (nb.1, nb.2) } else { (b, b) }; + self.implies_in(a0, b0, seen) && self.implies_in(a1, b1, seen) + } + + /// a → ¬b, i.e. a ∧ b is false, without building it. + fn disjoint(&self, a: B, b: B, seen: &mut HashSet<(B, B)>) -> bool { + if a == FALSE || b == FALSE { + return true; + } + if a == TRUE && b == TRUE { + return false; + } + if a == b || !seen.insert((a, b)) { + return a != b; + } + let (na, nb) = (self.nodes[a as usize], self.nodes[b as usize]); + let v = na.0.min(nb.0); + let (a0, a1) = if na.0 == v { (na.1, na.2) } else { (a, a) }; + let (b0, b1) = if nb.0 == v { (nb.1, nb.2) } else { (b, b) }; + self.disjoint(a0, b0, seen) && self.disjoint(a1, b1, seen) + } + + /// `a` with the atoms `drop` names quantified away (∃). + fn exists(&mut self, a: B, drop: &dyn Fn(u32) -> bool, memo: &mut HashMap) -> R { + if a <= TRUE { + return Ok(a); + } + if let Some(&n) = memo.get(&a) { + return Ok(n); + } + let (v, lo, hi) = self.nodes[a as usize]; + let (lo, hi) = (self.exists(lo, drop, memo)?, self.exists(hi, drop, memo)?); + let n = if drop(v) { self.or(lo, hi)? } else { self.mk(v, lo, hi)? }; + memo.insert(a, n); + Ok(n) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Atom { + /// the lane's result of the VALU compare / carry at this pc (before EXEC) + Lane(u64), + /// SCC written at this pc: uniform + Scc(u64), + /// a mask the analysis cannot follow, read at this pc from this register + Opaque(u64, usize), + /// an unresolved join of this slot (SGPR, `SCC`) at the start of this block + Join(usize, usize), + /// EXEC at launch, where it need not hold every lane that runs (`LaunchExec::Unknown`) + Launch, +} + +/// EXEC at the program's start, as the analysis takes it. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum LaunchExec { + /// every lane that runs is in EXEC: kernel mode (lanes outside it leave at once) and compute + All, + /// unknown per lane: a PS, whose helper lanes start outside EXEC and run on. A vector + /// instruction keeps its guard until EXEC is written. + Unknown, +} + +/// The masks at a program point. `regs[r]`: the lane function of the mask SGPR r holds (wave64: +/// in the pair's first register), None when it holds nothing the analysis knows as a mask. +/// EXEC always has one. `scc`: (lane function, true when it is a mask op's "result has the +/// lane's bit" rather than a uniform value). +#[derive(Clone, PartialEq)] +struct State { + regs: Vec>, + scc: Option<(B, bool)>, +} + +/// How a block's successor is reached: unconditionally, or by its branch taken / not taken. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Edge { + Always, + Taken, + NotTaken, +} + +/// A basic block of the program, as the lowering walks it. +#[derive(Clone, Debug)] +pub struct Block { + /// its instructions: indices into the decoded program + pub insts: std::ops::Range, + pub succ: Vec<(usize, Edge)>, + /// predecessors that the entry reaches, back edges included + pub preds: Vec, + /// it ends in a branch on a lane mask: each lane takes it on its own bit + pub lane_branch: bool, +} + +/// What the analysis found in a program. +#[derive(Debug, Default)] +pub struct Summary { + /// vector instructions (VALU writes, memory, LDS, exports) + pub vector: usize, + /// pcs of those that still need a guard on the lane's EXEC bit + pub guarded: Vec, + /// pcs of the mask-width `s_wqm` whose result is every lane (whole-quad mode of the launch + /// EXEC, `LaunchExec::Unknown`) + pub wqm_all: Vec, + /// conditional branches on a lane mask (each lane decides) and on uniform values + pub lane_branches: usize, + pub uniform_branches: usize, + /// the CFG (block 0 is the entry) and the order to lower it in (reverse postorder of the + /// blocks the entry reaches: every block after its forward predecessors) + pub blocks: Vec, + pub order: Vec, +} + +/// Executed with the lane's EXEC bit (VOPC and the lane reads / writes are mask producers). +fn is_vector(d: &Decoded) -> bool { + let n = d.inst.name; + !n.starts_with("S_") && !n.starts_with("V_CMP") && !matches!(n, "V_READLANE_B32" | "V_READFIRSTLANE_B32" | "V_WRITELANE_B32") +} + +struct Lanes<'a> { + insts: &'a [Decoded], + wave64: bool, + launch: LaunchExec, + bdd: Bdd, + atoms: HashMap, + /// block each atom is born in + born: Vec, + /// block → its instruction index range, successors (block, edge), predecessors (block, + /// index in its successors) + blocks: Vec<(usize, usize)>, + succ: Vec>, + preds: Vec>, + /// reverse postorder, and for each block: Some(blocks of its loop) when it heads one + order: Vec, + body: Vec>>, + /// per instruction: SGPRs it overwrites (`x64_masks::uses`), SGPRs it may change, whether + /// it writes SCC + effects: Vec<(u128, u128, bool)>, +} + +impl<'a> Lanes<'a> { + fn new(insts: &'a [Decoded], wave64: bool, launch: LaunchExec) -> R { + let starts: HashMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let mut leaders = BTreeSet::from([0usize]); + let mut target = vec![None; insts.len()]; + for (i, d) in insts.iter().enumerate() { + let indirect = d.far_target.is_none() && (d.inst.flags & F_INDIRECT != 0 || matches!(d.inst.name, "S_SETPC_B64" | "S_SWAPPC_B64")); + if indirect { + return Err("indirect jump"); + } + if let Some(t) = rdna2::branch_target(d) { + let &j = starts.get(&t).ok_or("branch into an instruction")?; + if j == 0 { + return Err("branch to the entry"); + } + target[i] = Some(j); + leaders.extend([j, i + 1]); + } else if d.inst.flags & F_TERMINATOR != 0 { + leaders.insert(i + 1); + } + } + leaders.retain(|&i| i < insts.len()); + let firsts: Vec = leaders.into_iter().collect(); + let block_of: HashMap = firsts.iter().enumerate().map(|(b, &i)| (i, b)).collect(); + let blocks: Vec<(usize, usize)> = firsts.iter().enumerate().map(|(b, &i)| (i, firsts.get(b + 1).copied().unwrap_or(insts.len()))).collect(); + let succ: Vec> = blocks + .iter() + .map(|&(_, end)| { + let d = &insts[end - 1]; + let next = block_of.get(&end).copied(); + match target[end - 1] { + Some(t) if d.inst.flags & F_CONDITIONAL != 0 => [Some((block_of[&t], Edge::Taken)), next.map(|n| (n, Edge::NotTaken))].into_iter().flatten().collect(), + Some(t) => vec![(block_of[&t], Edge::Always)], + None if d.inst.flags & F_TERMINATOR != 0 => vec![], + None => next.map(|n| (n, Edge::Always)).into_iter().collect(), + } + }) + .collect(); + let n = blocks.len(); + // reverse postorder of what the entry reaches + let (mut order, mut seen, mut stack) = (Vec::new(), vec![false; n], vec![(0usize, 0usize)]); + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, i) = *top; + if let Some(&(s, _)) = succ[b].get(i) { + top.1 += 1; + if !seen[s] { + seen[s] = true; + stack.push((s, 0)); + } + } else { + order.push(b); + stack.pop(); + } + } + order.reverse(); + let mut rpo = vec![usize::MAX; n]; + for (i, &b) in order.iter().enumerate() { + rpo[b] = i; + } + let mut preds = vec![Vec::new(); n]; + for &b in &order { + for (k, &(s, _)) in succ[b].iter().enumerate() { + preds[s].push((b, k)); + } + } + // dominators (Cooper, Harvey, Kennedy) – a retreating edge must go to a dominator + let mut idom = vec![usize::MAX; n]; + idom[0] = 0; + let intersect = |idom: &[usize], mut a: usize, mut b: usize| { + while a != b { + while rpo[a] > rpo[b] { + a = idom[a]; + } + while rpo[b] > rpo[a] { + b = idom[b]; + } + } + a + }; + loop { + let mut changed = false; + for &b in &order[1..] { + let new = preds[b].iter().map(|p| p.0).filter(|&p| idom[p] != usize::MAX).reduce(|a, p| intersect(&idom, a, p)).unwrap_or(usize::MAX); + changed |= idom[b] != new; + idom[b] = new; + } + if !changed { + break; + } + } + let dominates = |h: usize, mut b: usize| loop { + if b == h { + return true; + } + if b == 0 { + return false; + } + b = idom[b]; + }; + let mut body: Vec>> = vec![None; n]; + for &h in &order { + for &(p, _) in &preds[h] { + if rpo[p] < rpo[h] { + continue; + } + if !dominates(h, p) { + return Err("irreducible control flow"); + } + let inside = body[h].get_or_insert_with(|| vec![false; n]); + inside[h] = true; + let mut work = vec![p]; + while let Some(b) = work.pop() { + if !inside[b] { + inside[b] = true; + work.extend(preds[b].iter().map(|q| q.0)); + } + } + } + } + let effects = insts + .iter() + .map(|d| { + let written = x64_masks::uses(d).1; + let explicit = rdna2::sgpr_uses(d).1.iter().fold(0u128, |m, &r| m | 1 << r); + let kill = if d.inst.name.starts_with("S_MOVREL") { !0 } else { written | explicit }; + (written, kill, d.ienc.operands.iter().any(|o| o.output && o.ty == "OPR_SSRC_SPECIAL_SCC")) + }) + .collect(); + Ok(Lanes { insts, wave64, launch, bdd: Bdd::new(), atoms: HashMap::new(), born: Vec::new(), blocks, succ, preds, order, body, effects }) + } + + fn atom(&mut self, a: Atom, block: usize) -> R { + let fresh = self.born.len() as u32; + let v = *self.atoms.entry(a).or_insert(fresh); + if v == fresh { + self.born.push(block); + } + Ok(self.bdd.atom(v)) + } + + /// `step` within `STEP_NODES` new nodes; past that, what the instruction writes becomes + /// unknown: EXEC and SCC atoms, no mask in the other registers (weaker, still sound). + fn step_bounded(&mut self, st: &mut State, i: usize, block: usize) -> R<()> { + let mut next = st.clone(); + self.bdd.limit = (self.bdd.nodes.len() + STEP_NODES).min(MAX_NODES); + let r = self.step(&mut next, i, block); + self.bdd.limit = MAX_NODES; + if r.is_ok() { + *st = next; + return Ok(()); + } + let d = &self.insts[i]; + let (_, kill, writes_scc) = self.effects[i]; + for r in (0..128).filter(|&r| kill >> r & 1 != 0) { + self.kill(st, r); + } + if st.regs[EXEC].is_none() || d.inst.name.starts_with("V_CMPX") { + st.regs[EXEC] = Some(self.atom(Atom::Opaque(d.pc, EXEC), block)?); + } + if writes_scc { + st.scc = Some((self.atom(Atom::Scc(d.pc), block)?, true)); + } + Ok(()) + } + + /// A scalar source read as a mask: a register's lane function, all lanes, none, or None. + fn mask_src(&self, st: &State, d: &Decoded, code: u64) -> Option { + match code { + 128 => Some(FALSE), + 193 => Some(TRUE), + 255 if d.literal == Some(0) => Some(FALSE), + 255 if d.literal == Some(!0) && !self.wave64 => Some(TRUE), + c if c < 128 => st.regs[c as usize], + _ => None, + } + } + + /// … and an atom where the analysis cannot follow it. + fn need(&mut self, st: &State, d: &Decoded, code: u64, block: usize) -> R { + match self.mask_src(st, d, code) { + Some(v) => Ok(v), + None => self.atom(Atom::Opaque(d.pc, code as usize), block), + } + } + + fn combine(&mut self, op: &str, a: B, b: B) -> R> { + let bdd = &mut self.bdd; + Ok(Some(match op { + "AND" => bdd.and(a, b)?, + "OR" => bdd.or(a, b)?, + "XOR" => bdd.apply(Op::Xor, a, b)?, + "ANDN2" => (bdd.not(b).and_then(|nb| bdd.and(a, nb)))?, + "ORN2" => (bdd.not(b).and_then(|nb| bdd.or(a, nb)))?, + "ANDN1" => (bdd.not(a).and_then(|na| bdd.and(na, b)))?, + "ORN1" => (bdd.not(a).and_then(|na| bdd.or(na, b)))?, + "NAND" => (bdd.and(a, b).and_then(|x| bdd.not(x)))?, + "NOR" => (bdd.or(a, b).and_then(|x| bdd.not(x)))?, + "XNOR" => (bdd.apply(Op::Xor, a, b).and_then(|x| bdd.not(x)))?, + _ => return Ok(None), + })) + } + + /// One instruction's effect on the masks. + fn step(&mut self, st: &mut State, i: usize, block: usize) -> R<()> { + let d = &self.insts[i]; + let (written, kill, writes_scc) = self.effects[i]; + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); + let e = st.regs[EXEC].expect("EXEC"); + let mut set: Vec<(usize, B)> = Vec::new(); + let mut scc = None; + if name.starts_with("V_") { + if name.starts_with("V_CMPX") { + let l = self.atom(Atom::Lane(d.pc), block)?; + set.push((EXEC, self.bdd.and(l, e)?)); + } else if written != 0 && !matches!(name, "V_READLANE_B32" | "V_READFIRSTLANE_B32") { + // compares and carries: the lane's result, 0 in inactive lanes + let l = self.atom(Atom::Lane(d.pc), block)?; + set.push((written.trailing_zeros() as usize, self.bdd.and(l, e)?)); + } + } else if let Some(base) = name.strip_suffix(if self.wave64 { "_B64" } else { "_B32" }) { + let (s0, s1, sd) = (fv("SSRC0").unwrap_or(0), fv("SSRC1").unwrap_or(0), fv("SDST").map(|v| v as usize)); + let op = base.trim_start_matches("S_"); + if let Some(op) = op.strip_suffix("_SAVEEXEC").or_else(|| op.strip_suffix("_WREXEC")) { + let a = self.need(st, d, s0, block)?; + let new = self.combine(op, a, e)?.ok_or("unknown saveexec")?; + set.push((EXEC, new)); + if let Some(sd) = sd.filter(|&r| r < 128) { + set.push((sd, if base.ends_with("_WREXEC") { new } else { e })); + } + scc = Some((new, true)); + } else { + let (a, b) = (self.mask_src(st, d, s0), self.mask_src(st, d, s1)); + let value = match (op, a, b) { + ("MOV", Some(a), _) => Some(a), + ("NOT", Some(a), _) => Some(self.bdd.not(a)?), + ("WQM", Some(a), _) => self.wqm(a), + ("CSELECT", Some(a), Some(b)) => match st.scc { + Some((u, false)) => { + let (ua, nu) = (self.bdd.and(u, a)?, self.bdd.not(u)?); + let nub = self.bdd.and(nu, b)?; + Some(self.bdd.or(ua, nub)?) + } + _ => None, + }, + (_, Some(a), Some(b)) => self.combine(op, a, b)?, + _ => None, + }; + if let (Some(v), Some(sd)) = (value, sd.filter(|&r| r < 128)) { + set.push((sd, v)); + if !matches!(op, "MOV" | "CSELECT") { + scc = Some((v, true)); + } + } + } + } + // mask compares (`s_cmp_lg_u64 exec, 0`): whether the lane's bits differ / agree + let cmp = if self.wave64 { ("S_CMP_EQ_U64", "S_CMP_LG_U64") } else { ("S_CMP_EQ_U32", "S_CMP_LG_U32") }; + if name == cmp.0 || name == cmp.1 { + let (s0, s1) = (fv("SSRC0").unwrap_or(255), fv("SSRC1").unwrap_or(255)); + if let (Some(a), Some(b)) = (self.mask_src(st, d, s0), self.mask_src(st, d, s1)) { + if s0 < 128 || s1 < 128 { + let x = self.bdd.apply(Op::Xor, a, b)?; + scc = Some((if name == cmp.0 { self.bdd.not(x)? } else { x }, true)); + } + } + } + // whatever else the instruction writes is no longer a known mask + for r in (0..128).filter(|&r| kill >> r & 1 != 0) { + self.kill(st, r); + } + for (r, v) in set { + self.kill(st, r); + st.regs[r] = Some(v); + } + if st.regs[EXEC].is_none() { + st.regs[EXEC] = Some(self.atom(Atom::Opaque(d.pc, EXEC), block)?); + } + if writes_scc { + st.scc = match scc { + Some(s) => Some(s), + None => Some((self.atom(Atom::Scc(d.pc), block)?, false)), + }; + } + Ok(()) + } + + /// `s_wqm` of a mask: the lanes whose quad has a lane in it. Followed only where that is a + /// mask the analysis knows: none or every lane, and the launch EXEC (`LaunchExec::Unknown`), + /// since a lane that runs outside it is a helper lane of a quad with a lane in it. + fn wqm(&mut self, a: B) -> Option { + if a <= TRUE { + return Some(a); + } + let launch = *self.atoms.get(&Atom::Launch)?; + (a == self.bdd.atom(launch)).then_some(TRUE) + } + + fn kill(&self, st: &mut State, r: usize) { + st.regs[r] = None; + // wave64: the pair starting one register lower + if self.wave64 && r > 0 { + st.regs[r - 1] = None; + } + } + + /// Whether `c` is the same in every lane that reaches with its EXEC bit (`reach` and `e`): + /// then a lane deciding by its own bit decides as the whole wave does. Unknown (too large + /// to build) is no. + fn uniform_over(&mut self, reach: B, e: B, c: B) -> bool { + let Some(re) = self.bdd.within(|bdd| bdd.and(reach, e)) else { return false }; + if self.bdd.implies(re, c) { + return true; + } + match self.bdd.within(|bdd| bdd.not(c)) { + Some(nc) => self.bdd.implies(re, nc), + None => false, + } + } + + /// The condition under which a lane takes the branch ending a block, and whether it is a + /// lane mask's. + fn cond(&mut self, st: &State, d: &Decoded, block: usize) -> R<(B, bool)> { + let e = st.regs[EXEC].expect("EXEC"); + let (c, lane, negate) = match d.inst.name { + n @ ("S_CBRANCH_SCC0" | "S_CBRANCH_SCC1") => { + let (c, lane) = match st.scc { + Some(s) => s, + None => (self.atom(Atom::Scc(d.pc), block)?, false), + }; + (c, lane, n == "S_CBRANCH_SCC0") + } + n @ ("S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ") => { + let v = match st.regs[VCC] { + Some(v) => v, + None => self.atom(Atom::Opaque(d.pc, VCC), block)?, + }; + (self.bdd.and(v, e)?, true, n == "S_CBRANCH_VCCZ") + } + n @ ("S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ") => (e, true, n == "S_CBRANCH_EXECZ"), + _ => (self.atom(Atom::Scc(d.pc), block)?, false, false), + }; + Ok((if negate { self.bdd.not(c)? } else { c }, lane)) + } + + /// `cond` within `STEP_NODES` new nodes; past that, an unknown per-lane condition. + fn cond_bounded(&mut self, st: &State, d: &Decoded, block: usize) -> R<(B, bool)> { + self.bdd.limit = (self.bdd.nodes.len() + STEP_NODES).min(MAX_NODES); + let r = self.cond(st, d, block); + self.bdd.limit = MAX_NODES; + match r { + Ok(c) => Ok(c), + Err(_) => Ok((self.atom(Atom::Scc(d.pc), block)?, true)), + } + } + + /// Simulates a block from `st`: the facts and states on its outgoing edges. + fn run_block(&mut self, b: usize, reach: B, mut st: State) -> R> { + let (first, end) = self.blocks[b]; + for i in first..end { + self.step_bounded(&mut st, i, b)?; + } + let last = &self.insts[end - 1]; + let mut out = Vec::new(); + for k in 0..self.succ[b].len() { + let fact = match self.succ[b][k].1 { + Edge::Always => reach, + edge => { + // a fact too large to build is left without the branch's condition (weaker) + let (c, _) = self.cond_bounded(&st, last, b)?; + self.bdd + .within(|bdd| { + let c = if edge == Edge::Taken { c } else { bdd.not(c)? }; + bdd.and(reach, c) + }) + .unwrap_or(reach) + } + }; + out.push((fact, st.clone())); + } + Ok(out) + } + + /// Block b's reach and masks from its predecessors' edges. Back edges add their facts + /// with the loop's atoms dropped; their masks only count with `back_masks` (the check of a + /// loop head's guess). + fn join(&mut self, b: usize, outs: &[Vec<(B, State)>], forced: &HashSet<(usize, usize)>, back_masks: bool) -> R<(B, State)> { + let mut reach = FALSE; + let mut edges: Vec<(B, State)> = Vec::new(); + for &(p, k) in &self.preds[b].clone() { + let Some((fact, st)) = outs[p].get(k) else { continue }; + let back = self.body[b].as_ref().is_some_and(|inside| inside[p]); + let carried = if back { + let (inside, born) = (self.body[b].as_ref().unwrap(), &self.born); + self.bdd.within(|bdd| bdd.exists(*fact, &|v| inside[born[v as usize]], &mut HashMap::new())).unwrap_or(TRUE) + } else { + *fact + }; + reach = self.bdd.within(|bdd| bdd.or(reach, carried)).unwrap_or(TRUE); + if *fact != FALSE && (!back || back_masks) { + edges.push((*fact, st.clone())); + } + } + let mut st = State { regs: vec![None; 128], scc: None }; + st.regs[EXEC] = Some(FALSE); + if edges.is_empty() { + return Ok((reach, st)); + } + // an SCC a mask op set on any incoming edge, back edges included (their masks may not + // count here, but a lane's own SCC carried around a loop is still a lane's: thehollowedone, + // #1745) + let scc_lane = self.preds[b].iter().any(|&(p, k)| outs[p].get(k).is_some_and(|(f, s)| *f != FALSE && s.scc.is_some_and(|x| x.1))); + for slot in 0..=SCC { + let get = |s: &State| if slot == SCC { s.scc.map(|x| x.0) } else { s.regs[slot] }; + let lane = scc_lane; + let v = if forced.contains(&(b, slot)) { + Some(self.atom(Atom::Join(b, slot), b)?) + } else if edges.iter().any(|(_, s)| get(s).is_none()) { + None + } else { + let first = get(&edges[0].1).unwrap(); + Some(if edges.iter().all(|(_, s)| get(s) == Some(first)) { + first + } else if edges.iter().all(|(fact, s)| self.bdd.implies(*fact, get(s).unwrap())) { + TRUE + } else if edges.iter().all(|(fact, s)| self.bdd.disjoint(*fact, get(s).unwrap(), &mut HashSet::new())) { + FALSE + } else { + self.atom(Atom::Join(b, slot), b)? + }) + }; + if slot == SCC { + // unknown but a lane's on some edge: an unknown lane condition, not a uniform one + let v = match v { + None if lane => Some(self.atom(Atom::Join(b, SCC), b)?), + v => v, + }; + st.scc = v.map(|v| (v, lane)); + } else { + st.regs[slot] = v; + } + } + if st.regs[EXEC].is_none() { + st.regs[EXEC] = Some(self.atom(Atom::Join(b, EXEC), b)?); + } + Ok((reach, st)) + } + + fn analyze(mut self) -> R { + let n = self.blocks.len(); + let mut entry = State { regs: vec![None; 128], scc: None }; + entry.regs[EXEC] = Some(match self.launch { + LaunchExec::All => TRUE, + LaunchExec::Unknown => self.atom(Atom::Launch, 0)?, + }); + let mut forced = HashSet::new(); + let mut reach = vec![FALSE; n]; + let mut ins: Vec> = vec![None; n]; + let mut outs: Vec> = vec![Vec::new(); n]; + // blocks to recompute: every block first, then those an incoming edge changed for. Any + // fixpoint of the facts is sound (it is weaker than the least one), so a wrong loop-head + // guess only makes that head recompute instead of restarting from nothing. + let order = self.order.clone(); + let mut dirty = vec![false; n]; + for &b in &order { + dirty[b] = true; + } + let heads: Vec = order.iter().copied().filter(|&h| self.body[h].is_some()).collect(); + let mut rounds = 0; + loop { + while order.iter().any(|&b| dirty[b]) { + rounds += 1; + if rounds > MAX_ROUNDS { + return Err("no fixpoint"); + } + for &b in &order { + if !std::mem::take(&mut dirty[b]) { + continue; + } + let (r, st) = if b == 0 { (TRUE, entry.clone()) } else { self.join(b, &outs, &forced, false)? }; + if ins[b].as_ref() == Some(&st) && reach[b] == r { + continue; + } + reach[b] = r; + ins[b] = Some(st.clone()); + let out = self.run_block(b, r, st)?; + if out != outs[b] { + for &(s, _) in &self.succ[b] { + dirty[s] = true; + } + outs[b] = out; + } + } + } + // loop heads: does the guess from the forward edges hold on the back edges too? + let mut wrong = false; + for &h in &heads { + let (_, full) = self.join(h, &outs, &forced, true)?; + let guess = ins[h].as_ref().unwrap(); + for slot in 0..=SCC { + let (g, f) = if slot == SCC { (guess.scc.map(|x| x.0), full.scc.map(|x| x.0)) } else { (guess.regs[slot], full.regs[slot]) }; + if g != f && forced.insert((h, slot)) { + wrong = true; + dirty[h] = true; + } + } + } + if !wrong { + break; + } + } + let mut sum = Summary::default(); + let mut implied: HashMap<(B, B), bool> = HashMap::new(); + let mut lane_branch = vec![false; self.blocks.len()]; + for &b in &self.order.clone() { + let mut st = ins[b].clone().unwrap(); + let (first, end) = self.blocks[b]; + for i in first..end { + let d = &self.insts[i]; + if is_vector(d) { + sum.vector += 1; + let key = (reach[b], st.regs[EXEC].unwrap()); + let covered = match implied.get(&key) { + Some(&c) => c, + None => *implied.entry(key).or_insert(self.bdd.implies(key.0, key.1)), + }; + if !covered { + sum.guarded.push(d.pc); + } + } + // an SCC a mask op set, read by a scalar instruction: the console reads the whole + // wave's, each lane here its own bit, the same only where it is constant over EXEC + let n = d.inst.name; + if ["S_CSELECT", "S_CMOV", "S_ADDC", "S_SUBB"].iter().any(|p| n.starts_with(p)) { + if let Some((c, true)) = st.scc { + let e = st.regs[EXEC].unwrap(); + if !self.uniform_over(reach[b], e, c) { + return Err("a scalar read of the SCC of a mask op, with lanes in EXEC without its bit"); + } + } + } + if d.inst.name == if self.wave64 { "S_WQM_B64" } else { "S_WQM_B32" } { + let s0 = rdna2::field_value(d.enc, &d.words, "SSRC0").unwrap_or(0); + if self.mask_src(&st, d, s0).and_then(|a| self.wqm(a)) == Some(TRUE) { + sum.wqm_all.push(d.pc); + } + } + self.step_bounded(&mut st, i, b)?; + } + let last = &self.insts[end - 1]; + if self.succ[b].iter().any(|s| s.1 != Edge::Always) { + let (c, lane) = self.cond_bounded(&st, last, b)?; + // a lane branch is each lane's only where the condition is constant over the lanes + // in EXEC (`s_and_saveexec` then `s_cbranch_execz`); `s_cbranch_vccz` on a mask some + // lanes in EXEC lack takes the whole wave's way on the console (Kalmarv, #1745) + if lane && !self.uniform_over(reach[b], st.regs[EXEC].unwrap(), c) { + return Err("a branch on whether any lane of a mask is set, with lanes in EXEC without its bit"); + } + let (_, lane) = self.cond_bounded(&st, last, b)?; + if lane { + sum.lane_branches += 1; + } else { + sum.uniform_branches += 1; + } + lane_branch[b] = lane; + } + } + sum.blocks = (0..self.blocks.len()) + .map(|b| Block { + insts: self.blocks[b].0..self.blocks[b].1, + succ: self.succ[b].clone(), + preds: self.preds[b].iter().map(|p| p.0).collect(), + lane_branch: lane_branch[b], + }) + .collect(); + sum.order = self.order.clone(); + Ok(sum) + } +} + +/// Analyses a decoded program (far jumps resolved) that starts with every lane in EXEC. +pub fn analyze(insts: &[Decoded], wave64: bool) -> R { + analyze_launch(insts, wave64, LaunchExec::All) +} + +/// Analyses a decoded program (far jumps resolved) that starts with EXEC as `launch` says. +pub fn analyze_launch(insts: &[Decoded], wave64: bool, launch: LaunchExec) -> R { + if insts.is_empty() { + return Ok(Summary::default()); + } + Lanes::new(insts, wave64, launch)?.analyze() +} + +/// Decodes and analyses a program. +pub fn analyze_code(code: &[u8], wave64: bool) -> R { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { return Err("cannot decode") }; + off += d.len; + insts.push(d); + } + rdna2::resolve_far_jumps(&mut insts); + analyze(&insts, wave64) +} + +#[cfg(test)] +mod tests { + use super::*; + + const V: u64 = 256; + type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + const CMP: I = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]); + const MOV2: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)]); + const MOV3: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 130)]); + const RESTORE: I = ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]); + + /// Every instruction here is one dword: a branch's SIMM16 is (target − index − 1). + fn run(lines: &[I]) -> R { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + assert_eq!(bytes.len(), lines.len() * 4); + analyze_code(&bytes, true) + } + + #[test] + fn implication_tests_agree_with_the_built_formulas() { + let mut bdd = Bdd::new(); + let x: Vec = (0..4).map(|v| bdd.mk(v, FALSE, TRUE).unwrap()).collect(); + let mut fs = vec![FALSE, TRUE]; + for &a in &x { + for &b in &x { + let (and, or, xor) = (bdd.and(a, b).unwrap(), bdd.or(a, b).unwrap(), bdd.apply(Op::Xor, a, b).unwrap()); + let na = bdd.not(a).unwrap(); + fs.extend([a, and, or, xor, na]); + } + } + for &a in &fs { + for &b in &fs { + let nb = bdd.not(b).unwrap(); + let (built_imp, built_dis) = (bdd.and(a, nb).unwrap() == FALSE, bdd.and(a, b).unwrap() == FALSE); + assert_eq!(bdd.implies(a, b), built_imp, "{a} → {b}"); + assert_eq!(bdd.disjoint(a, b, &mut HashSet::new()), built_dis, "{a} ∧ {b}"); + } + } + } + + #[test] + fn a_skipped_if_needs_no_guard() { + // v_cmp; s_and_saveexec s[0:1], vcc; s_cbranch_execz L; v_mov; L: exec |= s[0:1]; v_mov + let s = run(&[ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + MOV2, + RESTORE, + MOV3, + ENDPGM, + ]) + .unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches, s.uniform_branches), (2, 0, 1, 0)); + // the CFG the lowering walks: entry (to the skip), the v_mov, the join + let b = &s.blocks; + assert_eq!(b.iter().map(|b| b.insts.clone()).collect::>(), vec![0..3, 3..4, 4..7]); + assert_eq!(b[0].succ, vec![(2, Edge::Taken), (1, Edge::NotTaken)]); + assert_eq!((b[1].succ.clone(), b[2].preds.clone()), (vec![(2, Edge::Always)], vec![0, 1])); + assert_eq!(b.iter().map(|b| b.lane_branch).collect::>(), vec![true, false, false]); + assert_eq!(s.order, vec![0, 1, 2]); + } + + #[test] + fn an_if_without_its_skip_is_guarded() { + let s = run(&[CMP, ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), MOV2, RESTORE, MOV3, ENDPGM]).unwrap(); + assert_eq!(s.vector, 2); + assert_eq!(s.guarded, vec![8], "only the v_mov under the narrowed EXEC"); + } + + #[test] + fn lanes_leaving_a_loop_keep_it_unguarded() { + // s_mov s[0:1], exec; L: v_cmp; v_add; exec &= ~vcc; s_cbranch_execnz L; exec |= s[0:1] + let s = run(&[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + CMP, + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 5)]), + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + RESTORE, + MOV3, + ENDPGM, + ]) + .unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches), (2, 0, 1)); + } + + #[test] + fn a_loop_that_narrows_exec_is_found_on_its_back_edge() { + // s4 = 0; L: v_mov; v_cmp; exec &= vcc; s4 += 1; s_cmp_lt s4, 10; s_cbranch_scc1 L; v_mov + // – the head's guess (all lanes) is wrong once the back edge is seen + let s = run(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 128)]), + MOV2, + CMP, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)]), + ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 138)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFA)]), + MOV3, + ENDPGM, + ]) + .unwrap(); + assert_eq!(s.guarded, vec![4, 28]); + assert_eq!((s.lane_branches, s.uniform_branches), (0, 1)); + } + + #[test] + fn a_vccz_branch_is_a_lane_branch_only_where_vcc_is_the_exec() { + // v_cmp; s_cbranch_vccz L: the console skips only when no lane in EXEC has the bit, so + // lanes in EXEC without it run the v_mov too; deciding per lane would skip it: refused + let err = run(&[CMP, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV2, MOV3, ENDPGM]).err(); + assert_eq!(err, Some("a branch on whether any lane of a mask is set, with lanes in EXEC without its bit")); + // v_cmp; s_and_saveexec s0, vcc; s_cbranch_vccz L: VCC ∧ EXEC is the new EXEC, the same + // as each lane's bit for every lane in it: a lane branch + let save: I = ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]); + let s = run(&[CMP, save, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV2, MOV3, ENDPGM]).unwrap(); + assert_eq!((s.vector, s.guarded.len(), s.lane_branches), (2, 1, 1)); + } + + #[test] + fn unsupported_control_flow_is_refused() { + // a loop entered at two places + let two_entries = run(&[ + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), + MOV2, + MOV3, + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0xFFFD)]), + ENDPGM, + ]); + assert_eq!(two_entries.unwrap_err(), "irreducible control flow"); + assert_eq!(run(&[("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 0)]), ENDPGM]).unwrap_err(), "indirect jump"); + assert_eq!(run(&[MOV2, ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFFE)]), ENDPGM]).unwrap_err(), "branch to the entry"); + } + + fn run_launch(lines: &[I], launch: LaunchExec) -> R { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let mut insts = Vec::new(); + let mut off = 0usize; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + rdna2::resolve_far_jumps(&mut insts); + analyze_launch(&insts, true, launch) + } + + #[test] + fn a_lane_outside_exec_at_launch_keeps_its_guard_until_exec_is_written() { + // v_mov (a helper lane must not write); exec = -1; v_mov (every lane writes) + let p = [MOV2, ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)]), MOV3, ENDPGM]; + let all = run_launch(&p, LaunchExec::All).unwrap(); + assert_eq!((all.vector, all.guarded.len()), (2, 0)); + let unknown = run_launch(&p, LaunchExec::Unknown).unwrap(); + assert_eq!(unknown.guarded, vec![0], "only the v_mov before EXEC is written"); + } + + #[test] + fn a_lane_branch_still_proves_exec_when_the_launch_exec_is_unknown() { + // as `a_skipped_if_needs_no_guard`: inside the if only lanes with their bit run, but the + // restored EXEC after the join is the launch EXEC again + let p = [ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + MOV2, + RESTORE, + MOV3, + ENDPGM, + ]; + assert_eq!(run_launch(&p, LaunchExec::All).unwrap().guarded.len(), 0); + let s = run_launch(&p, LaunchExec::Unknown).unwrap(); + assert_eq!((s.vector, s.guarded.clone(), s.lane_branches), (2, vec![20], 1)); + } + + #[test] + fn whole_quad_mode_of_the_launch_exec_is_every_lane() { + // s[0:1] = exec; s_wqm exec, exec; v_mov (helper lanes too); exec &= s[0:1]; v_mov + let wqm: I = ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]); + let p: [I; 6] = [ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + wqm, + MOV2, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + MOV3, + ENDPGM, + ]; + let s = run_launch(&p, LaunchExec::Unknown).unwrap(); + assert_eq!(s.guarded, vec![16], "only the v_mov after EXEC is narrowed to the launch EXEC again"); + assert_eq!(s.wqm_all, vec![4]); + assert_eq!(run_launch(&p, LaunchExec::All).unwrap().guarded.len(), 0); + // the quads of any other mask are not followed + let s = run_launch(&[CMP, ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 106)]), MOV2, ENDPGM], LaunchExec::All).unwrap(); + assert_eq!((s.guarded, s.wqm_all), (vec![8], vec![])); + } +} diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs new file mode 100644 index 0000000000..1b5942dea4 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -0,0 +1,4322 @@ +//! Lowering of console programs to DXIL-shaped IR, for the direct backend (`XCL_RECOMP_DXIL`). +//! +//! The console CFG is kept: blocks become blocks, and every register dword is an SSA value +//! (`ssa`). EXEC is not a number here but each lane's own bit (`i1`): a mask branch +//! (`s_cbranch_execz`, `vccz`, SCC of a mask op) is a branch of each lane on its bit, and a +//! vector instruction keeps a guard (`select(bit, new, old)`) only where `lane_masks` could not +//! prove the bit set. An SGPR therefore has two views: its number (`Var::S`) and, when it holds +//! a mask, the lane's bit of it (`Var::M`). Writing one view leaves a marker in the other – `undef` +//! – so a number read where only a mask was written (or the reverse, across a join) is found once +//! every phi is complete, and the program is refused (it stays on the HLSL path). A bit read where +//! only a number was written is the lane's bit of that number. At the end of the program every +//! lane is back, so a mask stored as a number there is the wave's ballot of the bits. +//! +//! Kernel mode only for now (the ABI of `runner`): registers come from `io` and go back to `res`. +//! The IR is written through `Ir`, the part of the DXIL module builder this needs. + +use std::collections::HashSet; + +use super::lane_masks::{self, Edge, Summary}; +use super::ssa::{Sink, Ssa, Var}; +use super::{KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS}; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +mod wave; + +type R = Result; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Bin { + Add, + Sub, + Mul, + And, + Or, + Xor, + Shl, + LShr, + AShr, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Cmp { + Eq, + Ne, + Ult, + Ule, + Ugt, + Uge, + Slt, + Sle, + Sgt, + Sge, +} + +/// What the lowering needs from the DXIL module builder. Blocks are numbered in the order +/// `new_block` creates them, the first being the entry; `And` / `Or` / `Xor` take `i1` or `i32`. +pub trait Ir: Sink { + fn new_block(&mut self) -> usize; + fn at(&mut self, block: usize); + fn int(&mut self, v: u32) -> Self::V; + fn boolean(&mut self, v: bool) -> Self::V; + fn bin(&mut self, op: Bin, a: Self::V, b: Self::V) -> Self::V; + fn icmp(&mut self, c: Cmp, a: Self::V, b: Self::V) -> Self::V; + fn select(&mut self, c: Self::V, a: Self::V, b: Self::V) -> Self::V; + /// `i1` → `i32` (0 / 1) + fn zext(&mut self, b: Self::V) -> Self::V; + /// the console lane of this thread + fn lane(&mut self) -> Self::V; + /// compute: the group's id, component k (x, y, z) + fn group_id(&mut self, k: u32) -> Self::V; + /// compute, a group of `threads`: this thread's console thread (its flat index in the group) + /// and that thread's id (x, y, z). The console forms a wave from consecutive threads, lane l + /// the l-th of them, so the flat index is the wave's first thread plus `lane()`; a PC driver + /// need not, in 2-D / 3-D groups, so the threads are numbered as the waves arrive + fn compute_ids(&mut self, threads: [u32; 3]) -> (Self::V, [Self::V; 3]); + /// the wave's ballot of `c`: lanes 0–31, 32–63 + fn ballot(&mut self, c: Self::V) -> [Self::V; 2]; + /// `ballot` where only the word of this lane's 32-lane half is used (the other may be + /// anything): a wave64 split into two 32-lane hardware waves needs no exchange for it + fn ballot_half(&mut self, c: Self::V) -> [Self::V; 2]; + /// `v` as lane `lane` holds it (`WaveReadLaneAt`); `lane` may differ between lanes and is + /// always one running this instruction too + fn read_lane(&mut self, v: Self::V, lane: Self::V) -> Self::V; + /// `read_lane` of a lane in this lane's 32-lane half (DPP, permlane, swizzle) + fn read_lane_half(&mut self, v: Self::V, lane: Self::V) -> Self::V; + /// Whether a whole-wave `ballot` / `read_lane` meets another hardware wave (the split form + /// of a wave64 program): then it needs every lane of the console wave where it runs. + fn whole_needs_exchange(&self) -> bool { + false + } + /// the number of bits set in `v` (`countbits`) + fn count_bits(&mut self, v: Self::V) -> Self::V; + /// `d` lowered with another lowering's instruction semantics (#1426's `Lw::inst_guarded`): + /// `inputs` are the registers it reads, `guard` (i1) decides this lane's register writes and + /// memory effects, and the values of `outputs` after it come back in order. Err when there + /// is no such lowering or it refuses `d`. + fn foreign(&mut self, _d: &Decoded, _guard: Self::V, _inputs: &[(Var, Self::V)], _outputs: &[Var]) -> R> { + Err("no foreign lowering".into()) + } + fn io_load(&mut self, dword: Self::V) -> Self::V; + fn res_store(&mut self, dword: Self::V, value: Self::V); + /// the dword of the flat memory (`mem`, u2) at a byte address (a multiple of 4); out of + /// range reads 0 and writes nothing, as D3D12 raw buffers do + fn mem_load(&mut self, addr: Self::V) -> Self::V; + fn mem_store(&mut self, addr: Self::V, value: Self::V); + /// the 4 GiB memory windows the program addresses: with more than one, `mem_load` / + /// `mem_store` (window 0 only) are not used, and memory instructions go to `foreign` + fn mem_windows(&self) -> u32 { + 1 + } + fn br(&mut self, target: usize); + fn br_if(&mut self, c: Self::V, then: usize, otherwise: usize); + fn ret(&mut self); + /// VS / PS: the stage's start (in the DXIL adapter #1426's `setup_vertex` / `setup_pixel`), + /// with `vregs` the VGPRs the program names. None: this IR has no graphics entry, and the + /// program is refused. + fn graphics_start(&mut self, vregs: &[u16]) -> Option> { + let _ = vregs; + None + } + /// … and its end (`finish_gfx`: the outputs, the PS discard), where every lane is back + fn graphics_end(&mut self) {} +} + +/// What a VS / PS starts with (`Ir::graphics_start`). +pub struct GraphicsStart { + /// the registers the stage sets beyond the user SGPRs from `io`: (SGPR, value), (VGPR, + /// value); a VGPR it does not set starts as 0 + pub sgprs: Vec<(u8, V)>, + pub vgprs: Vec<(u16, V)>, + /// the lane's bit of the launch EXEC: false in a PS's helper lanes, which run the program too + pub exec: V, +} + +const EXEC: u8 = 126; +const VCC: u8 = 106; + +/// The program's stage: where its registers come from and go. +#[derive(Clone, Copy)] +pub enum Stage<'a> { + /// `runner`'s ABI: the whole register file from `io`, back to `res` + Kernel, + /// a compute program: user SGPRs from `io`, then the group ids and TG_SIZE it enables, + /// thread ids in v0–v2; it ends without storing registers + Compute(&'a super::CsInterface), + /// a vertex / pixel shader: user SGPRs from `io`, the rest from `Ir::graphics_start`; it ends + /// in `Ir::graphics_end` + Vertex, + Pixel, +} + +struct Lower<'a, I: Ir> { + ir: I, + ssa: Ssa, + sum: &'a Summary, + guarded: HashSet, + wave64: bool, + /// the markers: a number where a mask was written, a bit where a number was + num_marker: I::V, + bit_marker: I::V, + /// values read as numbers / as mask bits, checked once every phi is complete + num_uses: Vec, + bit_uses: Vec, + lane: Option, + /// per IR block: not every lane that reached one of the program's lane branches gets here + /// before they meet again (a loop that lanes leave one by one, an arm some lanes skip) + partial: Vec, + /// stale-value ownership for blocks split by a coalesced run: backbone blocks of console + /// block b (`blk(b)` and its continuations) share `blk(b)` for both defs and uses, while a + /// run's inner block keeps its own `def_owner` (any def there is partial to outside reads) + /// and `blk(b)` as its `use_owner` (reads of earlier defs in the same console block stay valid) + def_owner: Vec, + use_owner: Vec, + /// inside a coalesced guarded run's own block: only lanes with EXEC set enter, so writes + /// need no per-instruction guard + unguarded: bool, + /// the IR block each mask bit was written in, and the mask bits read (block, value) + def_block: std::collections::HashMap, + lane_uses: Vec<(usize, I::V)>, + /// a DPP instruction's first source, read from its source lane, and its write enable + dpp_src: Option, + dpp_en: Option, + /// survey mode (`survey_compute`): every refusal is noted here and the lowering goes on + noted: Option>, + /// a VS / PS (`lower_graphics`): `s_wqm` only of the launch EXEC (its quads' helper lanes) + graphics: bool, +} + +/// A vector memory store: a side effect inactive lanes must not have. +fn is_store(d: &Decoded) -> bool { + let n = d.inst.name; + (n.starts_with("GLOBAL_STORE_") || n.starts_with("FLAT_STORE_")) && matches!(d.enc.name, "ENC_FLAT_GLBL" | "ENC_FLAT") +} + +/// A PS instruction that needs all four lanes of each quad: an image sample or gather with an +/// implicit LOD (no `_L` / `_LZ`, no gradients `_D` / `_CD`), `image_get_lod`, `s_wqm`. The +/// console has them from whole-quad mode; DXIL leaves derivatives undefined where control flow is +/// not uniform over the quad. +fn whole_quad(name: &str) -> bool { + if name == "IMAGE_GET_LOD" || name.starts_with("S_WQM_") { + return true; + } + match name.strip_prefix("IMAGE_SAMPLE").or_else(|| name.strip_prefix("IMAGE_GATHER4")) { + Some(rest) => !rest.split('_').any(|t| matches!(t, "L" | "LZ" | "D" | "CD")), + None => false, + } +} + +/// Cross-lane and wave-level ops stay out of coalesced guarded runs (they need the parent +/// block's lane participation, e.g. fetch-inactive or whole-wave mask reads). +fn is_cross_lane(d: &Decoded) -> bool { + let n = d.inst.name; + matches!(d.variant, Variant::Dpp16 | Variant::Dpp8) + || n.starts_with("V_PERMLANE") + || n.starts_with("V_MBCNT_") + || n.starts_with("V_READLANE") + || n.starts_with("V_READFIRSTLANE") + || n.starts_with("V_WRITELANE") + || n.starts_with("DS_SWIZZLE") + || n.starts_with("DS_BPERMUTE") + || n.starts_with("DS_PERMUTE") +} + +/// Any write to an SGPR, mask (VCC / EXEC / M0), or SCC must run for all lanes outside a +/// coalesced run (inactive lanes clear their bit in a VALU mask write rather than keeping it). +fn writes_scalar_or_scc(d: &Decoded) -> bool { + let (_, written) = super::x64_masks::uses(d); + let (_, explicit_w) = rdna2::sgpr_uses(d); + let writes = explicit_w.iter().fold(written, |m, &r| m | 1u128 << r) & !(1u128 << 125); + writes != 0 + || d.inst.name.starts_with("V_CMPX") + || d.ienc + .operands + .iter() + .any(|o| o.output && matches!(o.ty, "OPR_VCC" | "OPR_EXEC" | "OPR_SDST_EXEC" | "OPR_SDST_M0" | "OPR_SSRC_SPECIAL_SCC")) +} + +/// Pure no-ops in this lowering: allowed inside a coalesced run without breaking it. +fn is_run_noop(d: &Decoded) -> bool { + matches!( + d.inst.name, + "V_NOP" | "S_NOP" | "S_WAITCNT" | "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_LGKMCNT" | "S_WAITCNT_EXPCNT" | "S_INST_PREFETCH" | "S_CLAUSE" + ) +} + +/// Guarded instructions with side effects that inactive lanes must not execute even alone. +fn must_branch(d: &Decoded) -> bool { + let n = d.inst.name; + is_store(d) + || n.contains("_STORE_") + || n.starts_with("IMAGE_STORE") + || n.contains("_ATOMIC_") + || (n.starts_with("DS_") && !n.starts_with("DS_READ") && !n.starts_with("DS_NOP")) + || n == "EXP" +} + +fn can_coalesce(d: &Decoded, guarded: &HashSet) -> bool { + guarded.contains(&d.pc) && !is_cross_lane(d) && !whole_quad(d.inst.name) && !writes_scalar_or_scc(d) +} + +/// Exclusive end of a block's non-terminator instructions. +fn block_body_end(insts: &[Decoded], range: &std::ops::Range) -> usize { + let mut end = range.end; + if end > range.start { + let d = &insts[end - 1]; + let name = d.inst.name; + if name.starts_with("S_CBRANCH") || name == "S_BRANCH" || name.starts_with("S_ENDPGM") || d.far_target.is_some() { + end -= 1; + } + } + end +} + +/// Straight-line runs of guarded instructions in one console block that benefit from a single +/// per-lane EXEC branch instead of per-write `select`s (or per-store branches): any run with +/// a `must_branch` instruction or at least two guarded instructions. +fn coalesced_runs(insts: &[Decoded], range: &std::ops::Range, guarded: &HashSet) -> Vec> { + let end = block_body_end(insts, range); + let mut runs = Vec::new(); + let mut start: Option = None; + let mut last_end = 0usize; + let mut inst_count = 0usize; + let mut branch = false; + let mut flush = |start: &mut Option, last_end: usize, inst_count: &mut usize, branch: &mut bool| { + if let Some(s) = start.take() { + if *branch || *inst_count >= 2 { + runs.push(s..last_end); + } + *inst_count = 0; + *branch = false; + } + }; + for i in range.start..end { + let d = &insts[i]; + if is_run_noop(d) { + continue; + } + if can_coalesce(d, guarded) { + if start.is_none() { + start = Some(i); + } + last_end = i + 1; + inst_count += 1; + branch |= must_branch(d); + } else { + flush(&mut start, last_end, &mut inst_count, &mut branch); + } + } + flush(&mut start, last_end, &mut inst_count, &mut branch); + runs +} + +/// IR block of analysis block b (block 0 is the prologue). +fn blk(b: usize) -> usize { + b + 1 +} + +impl<'a, I: Ir> Lower<'a, I> { + fn lane(&mut self) -> I::V { + *self.lane.get_or_insert_with(|| self.ir.lane()) + } + + fn read(&mut self, b: usize, var: Var) -> I::V { + self.ssa.read(&mut self.ir, b, var) + } + + fn read_num(&mut self, b: usize, r: u8) -> R { + let v = self.read(b, Var::S(r)); + if self.ssa.resolve_value(v) == self.num_marker { + return Err(format!("s{r}: a mask read as a number")); + } + self.num_uses.push(v); + self.lane_uses.push((b, v)); + Ok(v) + } + + /// The lane's bit of the mask in s (wave64: the pair from s). + fn read_bit(&mut self, b: usize, r: u8) -> R { + let m = self.read(b, Var::M(r)); + if self.ssa.resolve_value(m) != self.bit_marker { + self.bit_uses.push(m); + if r != EXEC { + self.lane_uses.push((b, m)); + } + return Ok(m); + } + // only numbers written: the lane's bit of them + let lane = self.lane(); + let word = if self.wave64 { + let (lo, hi) = (self.read_num(b, r)?, self.read_num(b, r + 1)?); + let c32 = self.ir.int(32); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + self.ir.select(upper, hi, lo) + } else { + self.read_num(b, r)? + }; + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, lane, c31); + let shifted = self.ir.bin(Bin::LShr, word, sh); + let one = self.ir.int(1); + let bit = self.ir.bin(Bin::And, shifted, one); + let zero = self.ir.int(0); + Ok(self.ir.icmp(Cmp::Ne, bit, zero)) + } + + /// SCC, written and read like an SGPR number: a lane that skipped the block writing it + /// keeps its own older value (`stale`). + /// `v` as written in block b: in a block some lanes skip, a value made elsewhere (an older + /// mask copied, a shared constant) gets a copy of its own, so `stale` sees the write here. + fn own(&mut self, b: usize, v: I::V, bit: bool) -> I::V { + let v = match self.def_block.get(&v) { + Some(&d) if d != b && self.partial[b] => { + let z = if bit { self.ir.boolean(false) } else { self.ir.int(0) }; + self.ir.bin(Bin::Or, v, z) + } + _ => v, + }; + self.def_block.entry(v).or_insert(b); + v + } + + fn write_scc(&mut self, b: usize, v: I::V) { + let v = self.own(b, v, true); + self.ssa.write(b, Var::Scc, v); + } + + fn read_scc(&mut self, b: usize) -> I::V { + let v = self.read(b, Var::Scc); + self.lane_uses.push((b, v)); + v + } + + fn write_num(&mut self, b: usize, r: u8, v: I::V) { + let v = self.own(b, v, false); + self.ssa.write(b, Var::S(r), v); + self.ssa.write(b, Var::M(r), self.bit_marker); + if self.wave64 && r > 0 { + // a mask in the pair from s is no longer that mask + self.ssa.write(b, Var::M(r - 1), self.bit_marker); + } + } + + fn write_bit(&mut self, b: usize, r: u8, bit: I::V) { + let bit = if r != EXEC { self.own(b, bit, true) } else { bit }; + self.ssa.write(b, Var::M(r), bit); + self.ssa.write(b, Var::S(r), self.num_marker); + if self.wave64 { + self.ssa.write(b, Var::S(r + 1), self.num_marker); + self.ssa.write(b, Var::M(r + 1), self.bit_marker); + if r > 0 { + self.ssa.write(b, Var::M(r - 1), self.bit_marker); + } + } + } + + /// Whether s holds a mask here (its bit view is not the marker). + fn holds_mask(&mut self, b: usize, r: u8) -> bool { + let m = self.read(b, Var::M(r)); + self.ssa.resolve_value(m) != self.bit_marker + } + + /// A scalar or vector source operand as a number. + fn src(&mut self, b: usize, d: &Decoded, code: u64) -> R { + if let (233 | 234 | 250, Some(v)) = (code, self.dpp_src) { + return Ok(v); + } + Ok(match code { + 0..=105 | 106 | 107 | 124 | 126 | 127 => self.read_num(b, code as u8)?, + 128..=192 => self.ir.int((code - 128) as u32), + 193..=208 => self.ir.int((-((code - 192) as i32)) as u32), + 240..=247 => self.ir.int([0.5f32, -0.5, 1.0, -1.0, 2.0, -2.0, 4.0, -4.0][(code - 240) as usize].to_bits()), + 248 => self.ir.int(0x3E22_F983), + 253 => { + let s = self.read_scc(b); + self.ir.zext(s) + } + 255 => self.ir.int(d.literal.ok_or("missing literal")?), + 256..=511 => self.read(b, Var::V((code - 256) as u16)), + _ => return Err(format!("source code {code}")), + }) + } + + /// A scalar source operand as a mask's lane bit: a register, all lanes or none. + fn src_bit(&mut self, b: usize, code: u64) -> R { + match code { + 0..=105 | 106 | 107 | 126 | 127 => self.read_bit(b, code as u8), + 128 => Ok(self.ir.boolean(false)), + 193 => Ok(self.ir.boolean(true)), + _ => Err(format!("mask source code {code}")), + } + } + + fn write_v(&mut self, b: usize, d: &Decoded, r: u16, v: I::V) -> R<()> { + let v = match self.dpp_en.take() { + Some(en) => { + let old = self.read(b, Var::V(r)); + self.ir.select(en, v, old) + } + None => v, + }; + let v = if !self.unguarded && self.guarded.contains(&d.pc) { + let old = self.read(b, Var::V(r)); + let e = self.read_bit(b, EXEC)?; + self.ir.select(e, v, old) + } else { + v + }; + self.ssa.write(b, Var::V(r), v); + Ok(()) + } + + fn not(&mut self, a: I::V) -> I::V { + let t = self.ir.boolean(true); + self.ir.bin(Bin::Xor, a, t) + } + + /// A bitwise mask op of SALU / saveexec on lane bits. + fn bit_op(&mut self, op: &str, a: I::V, e: I::V) -> R { + Ok(match op { + "AND" => self.ir.bin(Bin::And, a, e), + "OR" => self.ir.bin(Bin::Or, a, e), + "XOR" => self.ir.bin(Bin::Xor, a, e), + "ANDN2" => { + let ne = self.not(e); + self.ir.bin(Bin::And, a, ne) + } + "ORN2" => { + let ne = self.not(e); + self.ir.bin(Bin::Or, a, ne) + } + "ANDN1" => { + let na = self.not(a); + self.ir.bin(Bin::And, na, e) + } + "ORN1" => { + let na = self.not(a); + self.ir.bin(Bin::Or, na, e) + } + "NAND" | "NOR" | "XNOR" => { + let inner = match op { + "NAND" => Bin::And, + "NOR" => Bin::Or, + _ => Bin::Xor, + }; + let x = self.ir.bin(inner, a, e); + self.not(x) + } + _ => return Err(format!("mask op {op}")), + }) + } + + fn salu(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); + let (s0, s1, sd) = (fv("SSRC0").unwrap_or(0), fv("SSRC1").unwrap_or(0), fv("SDST").unwrap_or(0) as u8); + if self.wave_salu(b, d)? { + return Ok(()); + } + if name == "S_GETPC_B64" { + // the address after it, as the program's offset (#1426's `s_getpc_b64`): read only by + // the far jump `resolve_far_jumps` resolved + let (lo, hi) = (self.ir.int((d.pc + d.len as u64) as u32), self.ir.int(0)); + self.write_num(b, sd, lo); + self.write_num(b, sd + 1, hi); + return Ok(()); + } + let width = if self.wave64 { "_B64" } else { "_B32" }; + // s_wqm: every lane where the analysis found it so (whole-quad mode of the launch EXEC); + // any other mask would need the lanes of the quad + if name.strip_prefix("S_WQM") == Some(width) { + if !self.sum.wqm_all.contains(&d.pc) { + return Err(format!("{name} of a mask other than the launch EXEC")); + } + let t = self.ir.boolean(true); + self.write_bit(b, sd, t); + self.write_scc(b, t); + return Ok(()); + } + // mask-width ops: on lane bits when they write EXEC, are a saveexec, or read a mask + if let Some(base) = name.strip_suffix(width) { + let op = base.trim_start_matches("S_"); + let saveexec = op.strip_suffix("_SAVEEXEC").or_else(|| op.strip_suffix("_WREXEC")); + // SOP1 has no SSRC1: only the sources the encoding has + let srcs: Vec = std::iter::once(s0).chain(d.enc.field("SSRC1").map(|_| s1)).collect(); + let reads_mask = srcs.iter().any(|&c| c <= 127 && c != 124 && self.holds_mask(b, c as u8)); + let bitwise = matches!(op, "MOV" | "NOT" | "AND" | "OR" | "XOR" | "ANDN2" | "ORN2" | "NAND" | "NOR" | "XNOR"); + if let Some(op) = saveexec { + let a = self.src_bit(b, s0)?; + let old = self.read_bit(b, EXEC)?; + let new = self.bit_op(op, a, old)?; + self.write_bit(b, EXEC, new); + if sd != 125 { + self.write_bit(b, sd, if base.ends_with("_WREXEC") { new } else { old }); + } + self.write_scc(b, new); + return Ok(()); + } + if op == "CSELECT" && (sd == EXEC || reads_mask) { + // `s_cselect_b64 s, exec, 0`: the lane's bit of the source SCC picks + let (a, c) = (self.src_bit(b, s0)?, self.src_bit(b, s1)?); + let scc = self.read_scc(b); + let v = self.ir.select(scc, a, c); + self.write_bit(b, sd, v); + return Ok(()); + } + if bitwise && (sd == EXEC || reads_mask) { + let a = self.src_bit(b, s0)?; + let v = match op { + "MOV" => a, + "NOT" => self.not(a), + _ => { + let c = self.src_bit(b, s1)?; + self.bit_op(op, a, c)? + } + }; + self.write_bit(b, sd, v); + if op != "MOV" { + self.write_scc(b, v); + } + return Ok(()); + } + } + // mask compares (`s_cmp_lg_u64 exec, 0`): whether the lane's bits differ / agree + let cmp64 = if self.wave64 { ["S_CMP_EQ_U64", "S_CMP_LG_U64"] } else { ["S_CMP_EQ_U32", "S_CMP_LG_U32"] }; + if cmp64.contains(&name) && [s0, s1].iter().any(|&c| c <= 127 && self.holds_mask(b, c as u8)) { + let (a, c) = (self.src_bit(b, s0)?, self.src_bit(b, s1)?); + let x = self.ir.bin(Bin::Xor, a, c); + let v = if name == cmp64[0] { self.not(x) } else { x }; + self.write_scc(b, v); + return Ok(()); + } + // numbers + let num2 = |l: &mut Self, op: Bin| -> R { + let (a, c) = (l.src(b, d, s0)?, l.src(b, d, s1)?); + Ok(l.ir.bin(op, a, c)) + }; + let nonzero = |l: &mut Self, v: I::V| { + let z = l.ir.int(0); + l.ir.icmp(Cmp::Ne, v, z) + }; + match name { + "S_MOV_B32" => { + let v = self.src(b, d, s0)?; + self.write_num(b, sd, v); + } + "S_MOVK_I32" => { + let v = self.ir.int(fv("SIMM16").unwrap_or(0) as u16 as i16 as i32 as u32); + self.write_num(b, sd, v); + } + "S_MOV_B64" => { + let (lo, hi) = self.src64(b, d, s0)?; + self.write_num(b, sd, lo); + self.write_num(b, sd + 1, hi); + } + "S_ADD_U32" | "S_SUB_U32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let (op, carry) = if name == "S_ADD_U32" { (Bin::Add, true) } else { (Bin::Sub, false) }; + let v = self.ir.bin(op, a, c); + // carry out: the sum wrapped below a; borrow: a < b + let scc = if carry { self.ir.icmp(Cmp::Ult, v, a) } else { self.ir.icmp(Cmp::Ult, a, c) }; + self.write_num(b, sd, v); + self.write_scc(b, scc); + } + "S_CSELECT_B32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let scc = self.read_scc(b); + let v = self.ir.select(scc, a, c); + self.write_num(b, sd, v); + } + "S_CSELECT_B64" => { + let ((al, ah), (cl, ch)) = (self.src64(b, d, s0)?, self.src64(b, d, s1)?); + let scc = self.read_scc(b); + let (lo, hi) = (self.ir.select(scc, al, cl), self.ir.select(scc, ah, ch)); + self.write_num(b, sd, lo); + self.write_num(b, sd + 1, hi); + } + "S_ADDC_U32" | "S_SUBB_U32" => { + // with SCC as the carry in / borrow in, and the carry / borrow out in SCC + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let cin = self.read_scc(b); + let cin = self.ir.zext(cin); + let (v, out) = if name == "S_ADDC_U32" { + let t = self.ir.bin(Bin::Add, a, c); + let v = self.ir.bin(Bin::Add, t, cin); + let (c1, c2) = (self.ir.icmp(Cmp::Ult, t, a), self.ir.icmp(Cmp::Ult, v, t)); + (v, self.ir.bin(Bin::Or, c1, c2)) + } else { + let t = self.ir.bin(Bin::Sub, a, c); + let v = self.ir.bin(Bin::Sub, t, cin); + let (b1, b2) = (self.ir.icmp(Cmp::Ult, a, c), self.ir.icmp(Cmp::Ult, t, cin)); + (v, self.ir.bin(Bin::Or, b1, b2)) + }; + self.write_num(b, sd, v); + self.write_scc(b, out); + } + "S_ADD_I32" | "S_SUB_I32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let op = if name == "S_ADD_I32" { Bin::Add } else { Bin::Sub }; + let v = self.ir.bin(op, a, c); + // signed overflow: the operands' signs agree (add) / differ (sub) and the result's differs + let (av, cv) = (self.ir.bin(Bin::Xor, a, v), self.ir.bin(Bin::Xor, c, v)); + let both = if op == Bin::Add { + self.ir.bin(Bin::And, av, cv) + } else { + let ac = self.ir.bin(Bin::Xor, a, c); + self.ir.bin(Bin::And, ac, av) + }; + let z = self.ir.int(0); + let scc = self.ir.icmp(Cmp::Slt, both, z); + self.write_num(b, sd, v); + self.write_scc(b, scc); + } + "S_MUL_I32" => { + let v = num2(self, Bin::Mul)?; + self.write_num(b, sd, v); + } + "S_AND_B32" | "S_OR_B32" | "S_XOR_B32" => { + let op = match name { + "S_AND_B32" => Bin::And, + "S_OR_B32" => Bin::Or, + _ => Bin::Xor, + }; + let v = num2(self, op)?; + let scc = nonzero(self, v); + self.write_num(b, sd, v); + self.write_scc(b, scc); + } + "S_LSHL_B32" | "S_LSHR_B32" | "S_ASHR_I32" => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, c, c31); + let op = match name { + "S_LSHL_B32" => Bin::Shl, + "S_LSHR_B32" => Bin::LShr, + _ => Bin::AShr, + }; + let v = self.ir.bin(op, a, sh); + let scc = nonzero(self, v); + self.write_num(b, sd, v); + self.write_scc(b, scc); + } + n if n.starts_with("S_CMP_") && (n.ends_with("_U32") || n.ends_with("_I32")) => { + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let signed = n.ends_with("_I32"); + let p = match &n[6..8] { + "EQ" => Cmp::Eq, + "LG" => Cmp::Ne, + "GT" => if signed { Cmp::Sgt } else { Cmp::Ugt }, + "GE" => if signed { Cmp::Sge } else { Cmp::Uge }, + "LT" => if signed { Cmp::Slt } else { Cmp::Ult }, + "LE" => if signed { Cmp::Sle } else { Cmp::Ule }, + _ => return Err(format!("unsupported {n}")), + }; + let v = self.ir.icmp(p, a, c); + self.write_scc(b, v); + } + "S_NOP" | "S_WAITCNT" | "S_WAITCNT_VSCNT" | "S_WAITCNT_VMCNT" | "S_WAITCNT_LGKMCNT" | "S_WAITCNT_EXPCNT" | "S_INST_PREFETCH" | "S_CLAUSE" => {} + "S_SETREG_IMM32_B32" | "S_SETREG_B32" => { + let s = fv("SIMM16").unwrap_or(0); + return Err(format!("unsupported {name} hwreg {} offset {} size {}", s & 0x3F, (s >> 6) & 0x1F, ((s >> 11) & 0x1F) + 1)); + } + n => return Err(format!("unsupported {n}")), + } + Ok(()) + } + + /// A 64-bit scalar source: a register pair or a constant. + fn src64(&mut self, b: usize, d: &Decoded, code: u64) -> R<(I::V, I::V)> { + Ok(match code { + 0..=105 | 106 | 126 => (self.read_num(b, code as u8)?, self.read_num(b, code as u8 + 1)?), + 128..=192 => (self.ir.int((code - 128) as u32), self.ir.int(0)), + 193..=208 => (self.ir.int((-((code - 192) as i32)) as u32), self.ir.int(u32::MAX)), + 255 => (self.ir.int(d.literal.ok_or("missing literal")?), self.ir.int(0)), + _ => return Err(format!("64-bit source code {code}")), + }) + } + + fn valu(&mut self, b: usize, d: &Decoded) -> R<()> { + if d.inst.name == "V_NOP" { + return Ok(()); + } + if matches!(d.variant, Variant::Dpp16 | Variant::Dpp8) { + self.dpp(b, d)?; + } + let r = self.valu_op(b, d); + (self.dpp_src, self.dpp_en) = (None, None); + r + } + + fn valu_op(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if d.variant == Variant::Sdwa { + return Err(format!("unsupported {name}: SDWA")); + } + if self.wave_valu(b, d)? { + return Ok(()); + } + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f); + let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); + if vop3 && ["ABS", "NEG", "CLAMP", "OMOD", "OP_SEL"].iter().any(|f| fv(f).unwrap_or(0) != 0) { + return Err(format!("unsupported {name}: VOP3 modifiers")); + } + // sources: VOP1 / VOP2 / VOPC put src1 in VSRC1 (a VGPR); VOP3 in SRC1 + let s0 = fv("SRC0").unwrap_or(0); + let s1 = if vop3 { fv("SRC1").unwrap_or(0) } else { fv("VSRC1").map(|v| v + 256).unwrap_or(0) }; + let vdst = fv("VDST").unwrap_or(0); + if let Some(rest) = name.strip_prefix("V_CMP") { + let (x, cond) = match rest.strip_prefix("X_") { + Some(c) => (true, c), + None => (false, rest.trim_start_matches('_')), + }; + let (pred, ty) = cond.split_once('_').ok_or_else(|| format!("unsupported {name}"))?; + let signed = match ty { + "U32" => false, + "I32" => true, + _ => return Err(format!("unsupported {name}")), + }; + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let c = match pred { + "EQ" => self.ir.icmp(Cmp::Eq, a, c), + "NE" => self.ir.icmp(Cmp::Ne, a, c), + "GT" => self.ir.icmp(if signed { Cmp::Sgt } else { Cmp::Ugt }, a, c), + "GE" => self.ir.icmp(if signed { Cmp::Sge } else { Cmp::Uge }, a, c), + "LT" => self.ir.icmp(if signed { Cmp::Slt } else { Cmp::Ult }, a, c), + "LE" => self.ir.icmp(if signed { Cmp::Sle } else { Cmp::Ule }, a, c), + "F" => self.ir.boolean(false), + "T" => self.ir.boolean(true), + _ => return Err(format!("unsupported {name}")), + }; + // the lane's result, 0 in inactive lanes + let e = self.read_bit(b, EXEC)?; + let bit = self.ir.bin(Bin::And, c, e); + let dst = if x { EXEC } else if vop3 { vdst as u8 } else { VCC }; + self.write_bit(b, dst, bit); + return Ok(()); + } + let v = match name { + "V_MOV_B32" => self.src(b, d, s0)?, + "V_CNDMASK_B32" => { + let sel = if vop3 { fv("SRC2").unwrap_or(0) } else { VCC as u64 }; + let m = self.src_bit(b, sel)?; + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + self.ir.select(m, c, a) + } + _ => { + // the opcode first: an unsupported VOP1 has no SRC1, which would read as s0 + const TWO_SOURCE: &[&str] = &[ + "V_ADD_NC_U32", "V_ADD_U32", "V_SUB_NC_U32", "V_SUB_U32", "V_SUBREV_NC_U32", "V_SUBREV_U32", "V_AND_B32", "V_OR_B32", "V_XOR_B32", + "V_MUL_LO_U32", "V_LSHL_ADD_U32", "V_ADD_LSHL_U32", "V_LSHL_OR_B32", "V_AND_OR_B32", "V_OR3_B32", "V_XOR3_B32", "V_ADD3_U32", + "V_LSHLREV_B32", "V_LSHRREV_B32", "V_ASHRREV_I32", + ]; + if !TWO_SOURCE.contains(&name) { + return Err(format!("unsupported {name}")); + } + let (a, c) = (self.src(b, d, s0)?, self.src(b, d, s1)?); + let c31 = self.ir.int(31); + match name { + "V_ADD_NC_U32" | "V_ADD_U32" => self.ir.bin(Bin::Add, a, c), + "V_SUB_NC_U32" | "V_SUB_U32" => self.ir.bin(Bin::Sub, a, c), + "V_SUBREV_NC_U32" | "V_SUBREV_U32" => self.ir.bin(Bin::Sub, c, a), + "V_AND_B32" => self.ir.bin(Bin::And, a, c), + "V_OR_B32" => self.ir.bin(Bin::Or, a, c), + "V_XOR_B32" => self.ir.bin(Bin::Xor, a, c), + "V_MUL_LO_U32" => self.ir.bin(Bin::Mul, a, c), + // three-source integer ops (VOP3): shifts take the low 5 bits of their amount + "V_LSHL_ADD_U32" | "V_ADD_LSHL_U32" | "V_LSHL_OR_B32" | "V_AND_OR_B32" | "V_OR3_B32" | "V_XOR3_B32" | "V_ADD3_U32" => { + let e = self.src(b, d, fv("SRC2").unwrap_or(0))?; + match name { + "V_LSHL_ADD_U32" | "V_LSHL_OR_B32" => { + let sh = self.ir.bin(Bin::And, c, c31); + let x = self.ir.bin(Bin::Shl, a, sh); + self.ir.bin(if name == "V_LSHL_ADD_U32" { Bin::Add } else { Bin::Or }, x, e) + } + "V_ADD_LSHL_U32" => { + let x = self.ir.bin(Bin::Add, a, c); + let sh = self.ir.bin(Bin::And, e, c31); + self.ir.bin(Bin::Shl, x, sh) + } + "V_AND_OR_B32" => { + let x = self.ir.bin(Bin::And, a, c); + self.ir.bin(Bin::Or, x, e) + } + _ => { + let op = match name { + "V_OR3_B32" => Bin::Or, + "V_XOR3_B32" => Bin::Xor, + _ => Bin::Add, + }; + let x = self.ir.bin(op, a, c); + self.ir.bin(op, x, e) + } + } + } + "V_LSHLREV_B32" | "V_LSHRREV_B32" | "V_ASHRREV_I32" => { + let sh = self.ir.bin(Bin::And, a, c31); + let op = match name { + "V_LSHLREV_B32" => Bin::Shl, + "V_LSHRREV_B32" => Bin::LShr, + _ => Bin::AShr, + }; + self.ir.bin(op, c, sh) + } + n => return Err(format!("unsupported {n}")), + } + } + }; + self.write_v(b, d, vdst as u16, v) + } + + /// `s_load_dword{,x2,x4,x8,x16}`: dwords of the flat memory into SGPRs, from + /// `s[sbase] + offset + soffset` (one memory window, as `emit::smem` with `mem_windows` 1). + fn smem(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if self.ir.mem_windows() > 1 { + return Err(format!("unsupported {name}: several memory windows")); + } + let count = match name.strip_prefix("S_LOAD_") { + Some("DWORD") => 1, + Some("DWORDX2") => 2, + Some("DWORDX4") => 4, + Some("DWORDX8") => 8, + Some("DWORDX16") => 16, + _ => return Err(format!("unsupported {name}")), + }; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f); + let (sdata, sbase) = (fv("SDATA") as u8, fv("SBASE") as u8); + let imm = (((fv("OFFSET") as u32) << 11) as i32 >> 11) as u32; // 21-bit signed + let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); + let base = self.read_num(b, sbase)?; + let imm = self.ir.int(imm); + let mut a = self.ir.bin(Bin::Add, base, imm); + if soff != 125 { + let s = self.src(b, d, soff)?; + a = self.ir.bin(Bin::Add, a, s); + } + let m = self.ir.int(!3); + let a = self.ir.bin(Bin::And, a, m); + let vals: Vec = (0..count) + .map(|i| { + let o = self.ir.int(4 * i as u32); + let ai = self.ir.bin(Bin::Add, a, o); + self.ir.mem_load(ai) + }) + .collect(); + for (i, v) in vals.into_iter().enumerate() { + self.write_num(b, sdata + i as u8, v); + } + Ok(()) + } + + /// `global_` / `flat_` `load` / `store_dword{,x2,x3,x4}` on the flat memory. A standalone + /// guarded load keeps the old register in lanes without their EXEC bit (`write_v`); guarded + /// stores and coalesced runs are lowered unguarded in a block only those lanes enter (`splits`). + fn vmem(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if self.ir.mem_windows() > 1 { + return Err(format!("unsupported {name}: several memory windows")); + } + let op = name.trim_start_matches("GLOBAL_").trim_start_matches("FLAT_"); + let (store, count) = match op { + "LOAD_DWORD" => (false, 1), + "LOAD_DWORDX2" => (false, 2), + "LOAD_DWORDX3" => (false, 3), + "LOAD_DWORDX4" => (false, 4), + "STORE_DWORD" => (true, 1), + "STORE_DWORDX2" => (true, 2), + "STORE_DWORDX3" => (true, 3), + "STORE_DWORDX4" => (true, 4), + _ => return Err(format!("unsupported {name}")), + }; + let global = d.enc.name == "ENC_FLAT_GLBL"; + if !global && d.enc.name != "ENC_FLAT" { + return Err(format!("{name}: {}", d.enc.name)); + } + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let raw = fv("OFFSET") as u32; + let off = if global { ((raw << 20) as i32 >> 20) as u32 } else { raw }; + let saddr = fv("SADDR"); + let mut a = self.read(b, Var::V(fv("ADDR") as u16)); + if global && saddr != 0x7D && saddr != 0x7F { + let s = self.read_num(b, saddr as u8)?; + a = self.ir.bin(Bin::Add, s, a); + } + let off = self.ir.int(off); + let a = self.ir.bin(Bin::Add, a, off); + for i in 0..count { + let o = self.ir.int(4 * i as u32); + let ai = self.ir.bin(Bin::Add, a, o); + let m = self.ir.int(!3); + let ai = self.ir.bin(Bin::And, ai, m); + if store { + let v = self.read(b, Var::V(fv("DATA") as u16 + i as u16)); + self.ir.mem_store(ai, v); + } else { + let v = self.ir.mem_load(ai); + self.write_v(b, d, fv("VDST") as u16 + i as u16, v)?; + } + } + Ok(()) + } + + /// The condition under which a lane takes the branch ending block b. + fn cond(&mut self, b: usize, d: &Decoded) -> R { + Ok(match d.inst.name { + "S_CBRANCH_SCC1" => self.read_scc(b), + "S_CBRANCH_SCC0" => { + let s = self.read_scc(b); + self.not(s) + } + n @ ("S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ") => { + let (v, e) = (self.read_bit(b, VCC)?, self.read_bit(b, EXEC)?); + let c = self.ir.bin(Bin::And, v, e); + if n == "S_CBRANCH_VCCZ" { + self.not(c) + } else { + c + } + } + "S_CBRANCH_EXECNZ" => self.read_bit(b, EXEC)?, + "S_CBRANCH_EXECZ" => { + let e = self.read_bit(b, EXEC)?; + self.not(e) + } + n => return Err(format!("unsupported branch {n}")), + }) + } + + /// Whether a lane reading mask bit v in block c may see its own stale bit: v (or a phi + /// operand reaching it) was written in another block that not every lane passed through. + /// The hardware's whole-wave write left the absent lanes' bits 0 there; this lane kept its + /// own older one. EXEC is not concerned: an absent lane's bit is 0 in both. + fn stale(&self, c: usize, v: I::V) -> bool { + let mut seen = HashSet::new(); + let mut work = vec![v]; + while let Some(v) = work.pop() { + let v = self.ssa.resolve_value(v); + if !seen.insert(v) { + continue; + } + match self.ssa.phi_operands(v) { + Some(ops) => work.extend_from_slice(ops), + None => { + if let Some(&b) = self.def_block.get(&v) { + if self.def_owner[b] != self.use_owner[c] && self.partial[b] { + return true; + } + } + } + } + } + false + } + + /// Whether v is (or is a phi reaching) `marker`. + fn reaches(&self, v: I::V, marker: I::V) -> bool { + let mut seen = HashSet::new(); + let mut work = vec![v]; + while let Some(v) = work.pop() { + let v = self.ssa.resolve_value(v); + if v == marker { + return true; + } + if seen.insert(v) { + if let Some(ops) = self.ssa.phi_operands(v) { + work.extend_from_slice(ops); + } + } + } + false + } +} + +/// Per analysis block: whether some lane that reached a lane branch may not pass through it +/// before the lanes meet again – it is reachable from the branch but does not post-dominate +/// both of its successors (lanes that take the other one never get there; a loop's own latch +/// counts: the lanes that leave do not come back to it). +fn partial_blocks(sum: &Summary) -> Vec { + let n = sum.blocks.len(); + let words = (n + 1).div_ceil(64); + // post-dominators over the blocks the entry reaches, with a virtual exit n + let full = vec![!0u64; words]; + let mut pdom: Vec> = vec![full; n + 1]; + pdom[n] = vec![0u64; words]; + pdom[n][n / 64] |= 1 << (n % 64); + let mut changed = true; + while changed { + changed = false; + for &b in sum.order.iter().rev() { + let succ: Vec = if sum.blocks[b].succ.is_empty() { vec![n] } else { sum.blocks[b].succ.iter().map(|s| s.0).collect() }; + let mut new = vec![!0u64; words]; + for s in succ { + for (w, x) in new.iter_mut().zip(&pdom[s]) { + *w &= x; + } + } + new[b / 64] |= 1 << (b % 64); + if new != pdom[b] { + pdom[b] = new; + changed = true; + } + } + } + let mut partial = vec![false; n]; + for &x in &sum.order { + if !sum.blocks[x].lane_branch { + continue; + } + let mut seen = vec![false; n]; + let mut work: Vec = sum.blocks[x].succ.iter().map(|s| s.0).collect(); + while let Some(b) = work.pop() { + if std::mem::replace(&mut seen[b], true) { + continue; + } + if sum.blocks[x].succ.iter().any(|&(s, _)| pdom[s][b / 64] >> (b % 64) & 1 == 0) { + partial[b] = true; + } + work.extend(sum.blocks[b].succ.iter().map(|s| s.0)); + } + } + partial +} + +/// Lowers a kernel-mode program (far jumps resolved) into `ir`, which gets it complete, with +/// the mask registers whose value at the end may differ from the console's: written in a block +/// some lanes skipped, so those lanes still hold their own older bits (`stale`). Nothing reads +/// them in the program (that would be refused); only the kernel ABI's store of every register. +pub fn lower_kernel(insts: &[Decoded], wave64: bool, ir: I) -> R<(I, Vec)> { + lower(insts, Stage::Kernel, wave64, ir) +} + +/// Lowers a compute program (far jumps resolved) into `ir`. +pub fn lower_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool, ir: I) -> R { + Ok(lower(insts, Stage::Compute(cs), wave64, ir)?.0) +} + +/// Lowers a vertex or pixel shader (`pixel`; far jumps resolved) into `ir`. `lanes32`: a wave64 +/// program runs in 32-lane hardware waves (NVIDIA), as the HLSL path runs it with `upper_lanes`; +/// the per-lane form takes such a program only where it reads no lane 32–63 that holds anything. +pub fn lower_graphics(insts: &[Decoded], pixel: bool, wave64: bool, lanes32: bool, ir: I) -> R { + if wave64 && lanes32 && super::upper_lanes::analyze(insts).reads.values().any(|&r| r != super::upper_lanes::Read::Native) { + return Err("wave64 VS / PS in 32-lane waves: a read of lanes 32–63".into()); + } + Ok(lower(insts, if pixel { Stage::Pixel } else { Stage::Vertex }, wave64, ir)?.0) +} + +fn lower(insts: &[Decoded], stage: Stage, wave64: bool, ir: I) -> R<(I, Vec)> { + lower_with(insts, stage, wave64, ir, false).map(|(ir, stale, _)| (ir, stale)) +} + +/// Survey: every reason the per-lane form refuses a compute program, not only the first. An +/// instruction it refuses is left out and the lowering goes on, so a later reason may follow +/// from an earlier one; a program the lane-mask analysis refuses gives that one reason. +pub fn survey_compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool, ir: I) -> Vec { + match lower_with(insts, Stage::Compute(cs), wave64, ir, true) { + Ok((_, _, noted)) => noted, + Err(e) => vec![e], + } +} + +fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, survey: bool) -> R<(I, Vec, Vec)> { + let kernel = matches!(stage, Stage::Kernel); + let graphics = matches!(stage, Stage::Vertex | Stage::Pixel); + // a PS: lanes may run outside the launch EXEC (its helper lanes); a VS has none, each D3D + // vertex invocation being one lane + let pixel = matches!(stage, Stage::Pixel); + let launch = if pixel { lane_masks::LaunchExec::Unknown } else { lane_masks::LaunchExec::All }; + let sum = lane_masks::analyze_launch(insts, wave64, launch).map_err(|e| e.to_string())?; + let n = sum.blocks.len(); + if n == 0 { + return Err("empty program".into()); + } + // IR blocks: 0 prologue, 1..=n the program's, n + 1 exit, n + 2 lane 0's scalar stores, + // n + 3 every lane's vector stores, n + 4 the way to the exit of lanes outside EXEC at launch, + // then for every coalesced guarded run (only the lanes with their EXEC bit enter): the run's + // block and the one the rest of its block continues in. `tail[b]`: the IR block the + // program's block b ends in. + let (exit, sstore, vstore, skip) = (n + 1, n + 2, n + 3, n + 4); + let guarded: HashSet = sum.guarded.iter().copied().collect(); + let mut splits: Vec, usize, usize)>> = vec![Vec::new(); n]; // (run, body, cont) + let mut count = n + 5; + for (b, block) in sum.blocks.iter().enumerate() { + for run in coalesced_runs(insts, &block.insts, &guarded) { + splits[b].push((run, count, count + 1)); + count += 2; + } + } + let tail: Vec = (0..n).map(|b| splits[b].last().map_or(blk(b), |s| s.2)).collect(); + let mut partial = vec![false; count]; + let mut def_owner: Vec = (0..count).collect(); + let mut use_owner: Vec = (0..count).collect(); + for (b, p) in partial_blocks(&sum).into_iter().enumerate() { + partial[blk(b)] = p; + for &(_, s, c) in &splits[b] { + partial[s] = true; + partial[c] = p; + def_owner[s] = s; + use_owner[s] = blk(b); + def_owner[c] = blk(b); + use_owner[c] = blk(b); + } + } + let ends: Vec = sum.order.iter().copied().filter(|&b| sum.blocks[b].succ.is_empty()).collect(); + let mut preds = vec![Vec::new(); count]; + preds[blk(0)] = vec![0]; + for &b in &sum.order { + let mut seen = Vec::new(); + for &(s, _) in &sum.blocks[b].succ { + if !seen.contains(&s) { + seen.push(s); + preds[blk(s)].push(tail[b]); + } + } + let mut prev = blk(b); + for &(_, s, c) in &splits[b] { + preds[s] = vec![prev]; + preds[c] = vec![prev, s]; + prev = c; + } + } + // compute: every lane that runs is in EXEC, and nothing is stored at the end – the skip and + // store blocks are left unreachable (a bare `ret`) + if kernel { + preds[skip] = vec![0]; + preds[sstore] = vec![exit]; + preds[vstore] = vec![exit, sstore]; + } + preds[exit] = kernel.then_some(skip).into_iter().chain(ends.iter().map(|&b| tail[b])).collect(); + for i in 0..count { + let id = ir.new_block(); + debug_assert_eq!(id, i); + } + let num_marker = ir.undef(Var::S(0)); + let bit_marker = ir.undef(Var::M(0)); + let mut l = Lower { + ssa: Ssa::new(preds.clone()), + ir, + + sum: &sum, + guarded, + wave64, + num_marker, + bit_marker, + num_uses: Vec::new(), + bit_uses: Vec::new(), + lane: None, + partial, + def_owner, + use_owner, + unguarded: false, + def_block: std::collections::HashMap::new(), + lane_uses: Vec::new(), + dpp_src: None, + dpp_en: None, + noted: survey.then(Vec::new), + graphics, + }; + // the registers the program names, and the ones the runner reads back + let mut sregs: Vec = vec![VCC, VCC + 1, 124, EXEC, EXEC + 1]; + let mut vregs: Vec = Vec::new(); + for d in insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as u8)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as u16)); + } + sregs.retain(|&r| (r as usize) < KERNEL_SGPRS && r != 125); + sregs.sort_unstable(); + sregs.dedup(); + vregs.sort_unstable(); + vregs.dedup(); + + // prologue: the SGPRs from `io` (kernel: the whole register file; compute: the user data) + l.ir.at(0); + l.ssa.seal(&mut l.ir, 0); + let lane = l.lane(); + for &r in &sregs { + let a = l.ir.int(r as u32); + let v = l.ir.io_load(a); + l.write_num(0, r, v); + } + let mut row = None; + match stage { + Stage::Kernel => { + let a = l.ir.int(KERNEL_SCC_SLOT as u32); + let scc = l.ir.io_load(a); + let z = l.ir.int(0); + let scc = l.ir.icmp(Cmp::Ne, scc, z); + l.ssa.write(0, Var::Scc, scc); + let (base, stride) = (l.ir.int(KERNEL_SGPRS as u32), l.ir.int(KERNEL_VGPRS as u32)); + let r = l.ir.bin(Bin::Mul, lane, stride); + let r = l.ir.bin(Bin::Add, base, r); + for &v in &vregs { + let o = l.ir.int(v as u32); + let a = l.ir.bin(Bin::Add, r, o); + let x = l.ir.io_load(a); + l.ssa.write(0, Var::V(v), x); + } + row = Some(r); + // lanes outside EXEC go straight to the end + let active = l.read_bit(0, EXEC)?; + l.write_bit(0, EXEC, active); + l.ir.br_if(active, blk(0), skip); + // … with their bits of every mask 0, as a whole-wave write leaves them + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + let f = l.ir.boolean(false); + for &r in &sregs { + l.ssa.write(skip, Var::M(r), f); + } + l.ir.br(exit); + } + Stage::Compute(cs) => { + let (flat, tid) = l.ir.compute_ids(cs.threads); + // system SGPRs after the user data: the enabled group ids, then TG_SIZE + let mut next = cs.user_sgprs as u8; + for k in 0..3 { + if cs.tgid[k as usize] { + let g = l.ir.group_id(k); + l.write_num(0, next, g); + next += 1; + } + } + if cs.tg_size { + // waves in the group (a last partial one counts) | this wave's index << 6 + let lanes = if wave64 { 64 } else { 32 }; + let waves = l.ir.int(cs.threads.iter().product::().div_ceil(lanes)); + let sh = l.ir.int(lanes.trailing_zeros()); + let w = l.ir.bin(Bin::LShr, flat, sh); + let six = l.ir.int(6); + let w = l.ir.bin(Bin::Shl, w, six); + let v = l.ir.bin(Bin::Or, waves, w); + l.write_num(0, next, v); + } + let f = l.ir.boolean(false); + l.ssa.write(0, Var::Scc, f); + for &v in &vregs { + let x = match v { + 0 => tid[0], + 1 if cs.tid_components >= 2 => tid[1], + 2 if cs.tid_components >= 3 => tid[2], + _ => l.ir.int(0), + }; + l.ssa.write(0, Var::V(v), x); + } + // every lane that runs is in EXEC + let t = l.ir.boolean(true); + l.write_bit(0, EXEC, t); + l.ir.br(blk(0)); + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + l.ir.ret(); + } + Stage::Vertex | Stage::Pixel => { + let Some(start) = l.ir.graphics_start(&vregs) else { + return Err("VS / PS: this IR has no graphics entry".into()); + }; + for &(r, v) in &start.sgprs { + l.write_num(0, r, v); + } + let f = l.ir.boolean(false); + l.ssa.write(0, Var::Scc, f); + for &v in &vregs { + let x = match start.vgprs.iter().find(|x| x.0 == v) { + Some(&(_, x)) => x, + None => l.ir.int(0), + }; + l.ssa.write(0, Var::V(v), x); + } + // every lane runs the program: a PS's helper lanes with their EXEC bit clear (the + // kernel's way out for lanes outside EXEC would leave their quads short) + l.write_bit(0, EXEC, start.exec); + l.ir.br(blk(0)); + l.ir.at(skip); + l.ssa.seal(&mut l.ir, skip); + l.ir.ret(); + } + } + + // the program, in reverse postorder; a block is sealed once all its predecessors are in + let mut done = vec![false; count]; + done[0] = true; + done[skip] = true; + let seal_ready = |l: &mut Lower, done: &[bool], b: usize| { + if preds[b].iter().all(|&p| done[p]) { + l.ssa.seal(&mut l.ir, b); + true + } else { + false + } + }; + let mut sealed = vec![false; count]; + sealed[0] = true; + for &b in &sum.order.clone() { + let ib = blk(b); + l.ir.at(ib); + if !sealed[ib] { + sealed[ib] = seal_ready(&mut l, &done, ib); + } + if b == 0 && !pixel { + // the analysis takes the lanes that start the program as its EXEC (a PS keeps the + // launch EXEC from its start: there the analysis does not know it) + let t = l.ir.boolean(true); + l.write_bit(ib, EXEC, t); + } + let block = &sum.blocks[b]; + let last = block.insts.end - 1; + let body_end = block_body_end(insts, &block.insts); + let mut cur = ib; + let mut split = splits[b].iter().peekable(); + let mut i = block.insts.start; + while i < body_end { + if let Some(&(ref run, s, c)) = split.next_if(|x| x.0.start == i) { + // a coalesced guarded run: only the lanes with their EXEC bit enter `s`, + // lowered unguarded; updated registers merge through SSA phis at `c` + let e = l.read_bit(cur, EXEC)?; + l.ir.br_if(e, s, c); + done[cur] = true; + l.ir.at(s); + l.ssa.seal(&mut l.ir, s); + l.unguarded = true; + for j in run.clone() { + let r = l.lower_inst(s, &insts[j]); + l.note_inst(r, s, &insts[j])?; + } + l.unguarded = false; + l.ir.br(c); + done[s] = true; + l.ir.at(c); + l.ssa.seal(&mut l.ir, c); + cur = c; + i = run.end; + } else { + let name = insts[i].inst.name; + if matches!(stage, Stage::Pixel) && whole_quad(name) && l.partial[cur] { + l.note_inst(Err(format!("{name}: needs whole quads, in a block not every lane reaches")), cur, &insts[i])?; + i += 1; + continue; + } + let r = l.lower_inst(cur, &insts[i]); + l.note_inst(r, cur, &insts[i])?; + i += 1; + } + } + match block.succ.as_slice() { + [] => l.ir.br(exit), + [(t, Edge::Always)] => l.ir.br(blk(*t)), + [(t, _), (f, _)] if t == f => l.ir.br(blk(*t)), + [(t, Edge::Taken), (f, Edge::NotTaken)] => match l.cond(cur, &insts[last]) { + Ok(c) => l.ir.br_if(c, blk(*t), blk(*f)), + Err(e) => { + l.note(Err(e))?; + let c = l.ir.boolean(true); + l.ir.br_if(c, blk(*t), blk(*f)); + } + }, + s => { + l.note(Err(format!("block {b}: successors {s:?}")))?; + l.ir.br(blk(s[0].0)); + } + } + done[cur] = true; + for &(s, _) in &block.succ { + let is = blk(s); + if !sealed[is] && l.sum.order.contains(&s) { + // the successor's own code comes later; sealing it early is fine once its + // predecessors are all in + if preds[is].iter().all(|&p| done[p]) { + l.ssa.seal(&mut l.ir, is); + sealed[is] = true; + } + } + } + } + for b in 1..=n { + if !sealed[b] && preds[b].iter().all(|&p| done[p]) { + l.ssa.seal(&mut l.ir, b); + sealed[b] = true; + } + } + + l.ir.at(exit); + l.ssa.seal(&mut l.ir, exit); + let mut stale: Vec = Vec::new(); + let Some(row) = row else { + // compute: nothing to store; a VS / PS: its end + if graphics { + l.ir.graphics_end(); + } + l.ir.ret(); + for b in [sstore, vstore] { + l.ir.at(b); + l.ssa.seal(&mut l.ir, b); + l.ir.ret(); + } + return l.finish(stale); + }; + // kernel exit: every lane is here; masks the runner reads as numbers are the wave's ballots + let mut sval: Vec<(u8, I::V)> = Vec::new(); + let mut i = 0; + while i < sregs.len() { + let r = sregs[i]; + i += 1; + let s = l.read(exit, Var::S(r)); + if l.ssa.resolve_value(s) != l.num_marker && !l.reaches(s, l.num_marker) { + l.num_uses.push(s); + if l.stale(exit, s) { + stale.push(r); + } + sval.push((r, s)); + continue; + } + if !l.holds_mask(exit, r) { + if l.wave64 && r > 0 && sval.iter().any(|&(x, _)| x == r) { + continue; // the upper half of a mask stored with its pair + } + return Err(format!("s{r}: neither a number nor a mask at the end")); + } + // read directly: a stale bit here is reported, not refused (only the ABI's store sees it) + let m = l.read(exit, Var::M(r)); + if r != EXEC && l.stale(exit, m) { + stale.push(r); + if l.wave64 { + stale.push(r + 1); // the upper half comes from the same mask + } + } + let [lo, hi] = l.ir.ballot(m); + sval.push((r, lo)); + if l.wave64 { + sval.retain(|&(x, _)| x != r + 1); + sval.push((r + 1, hi)); + if sregs.get(i) == Some(&(r + 1)) { + i += 1; + } + } + } + let scc = l.read(exit, Var::Scc); + if l.stale(exit, scc) { + stale.push(KERNEL_SCC_SLOT as u8); + } + let vval: Vec<(u16, I::V)> = vregs.iter().map(|&v| (v, l.read(exit, Var::V(v)))).collect(); + let z = l.ir.int(0); + let first = l.ir.icmp(Cmp::Eq, lane, z); + l.ir.br_if(first, sstore, vstore); + l.ir.at(sstore); + l.ssa.seal(&mut l.ir, sstore); + for &(r, v) in &sval { + let a = l.ir.int(r as u32); + l.ir.res_store(a, v); + } + let a = l.ir.int(KERNEL_SCC_SLOT as u32); + let s = l.ir.zext(scc); + l.ir.res_store(a, s); + l.ir.br(vstore); + l.ir.at(vstore); + l.ssa.seal(&mut l.ir, vstore); + for &(v, x) in &vval { + let o = l.ir.int(v as u32); + let a = l.ir.bin(Bin::Add, row, o); + l.ir.res_store(a, x); + } + l.ir.ret(); + l.finish(stale) +} + +impl Lower<'_, I> { + /// Every phi is complete: no number may come from a mask, nor a mask bit from a number, nor + /// a lane read a mask bit it kept from before a write it skipped. + fn finish(mut self, mut stale: Vec) -> R<(I, Vec, Vec)> { + if self.num_uses.iter().any(|&v| self.reaches(v, self.num_marker)) { + self.note(Err("a mask read as a number (through a join)".into()))?; + } + if self.bit_uses.iter().any(|&v| self.reaches(v, self.bit_marker)) { + self.note(Err("a number read as a mask (through a join)".into()))?; + } + if self.lane_uses.iter().any(|&(c, v)| self.stale(c, v)) { + self.note(Err("a value written while some lanes were elsewhere, read after they met again".into()))?; + } + stale.sort_unstable(); + stale.dedup(); + Ok((self.ir, stale, self.noted.unwrap_or_default())) + } + + /// A refused instruction in block b: as `note`, and in survey mode the SGPRs (and, for a + /// scalar instruction, SCC) it writes are left as 0 in both views (number and mask bit), + /// so that a later read does not report a refusal that only follows from this one. + /// An instruction this lowering has no semantics of, through `Ir::foreign` (#1426's + /// per-instruction lowering) with the lane-mask analysis's guard: `true` where EXEC is proven + /// (or inside a coalesced guarded run's block, `in_guarded_run`), else the lane's EXEC bit. Its SGPR + /// operands are read as numbers (a mask read whole is refused, as everywhere), the mask a + /// VALU reads lane by lane (`v_cndmask_b32`'s selector, a carry-in) as a number holding only + /// this lane's bit, and a mask it writes (a compare, a carry-out) comes back as this lane's + /// bit of the ballot it makes. Of the instructions writing EXEC, only `v_cmpx_*` is taken. + fn bridge(&mut self, b: usize, d: &Decoded, in_guarded_run: bool) -> R<()> { + let name = d.inst.name; + let (whole, written) = super::x64_masks::uses(d); + let (_, explicit_w) = rdna2::sgpr_uses(d); + let writes = explicit_w.iter().fold(written, |m, &r| m | 1u128 << r); + // `v_cmpx_*`: EXEC goes in as this lane's bit and comes back as its bit of the result + let cmpx = name.starts_with("V_CMPX"); + if writes & (3 << 126) != 0 && !cmpx { + return Err("writes EXEC".into()); + } + if name == "S_BARRIER" && self.partial[b] { + return Err("a barrier where some lanes are elsewhere".into()); + } + // instructions whose #1426 semantics are known to differ from the HLSL path and the + // console (each reported on #1426): left to the fallback until fixed there + const DIFFERS_ON_1426: &[&str] = &[ + // f32 → f16 of a value below the smallest f16 denormal: 0 instead of rounding to it + "V_CVT_F16_F32", + // f16 products round toward zero (`LegacyF32ToF16`) where the console rounds to + // nearest even (vladbondarenko97's f16 programs; itsSio is fixing it on `main`) + "V_MUL_F16", + "V_PK_MUL_F16", + ]; + if DIFFERS_ON_1426.contains(&name) { + return Err("its #1426 semantics differ from the console's".into()); + } + let operand = |input: bool, ty: &str| d.ienc.operands.iter().any(|o| o.input == input && o.output != input && o.ty == ty); + let mut inputs: Vec<(Var, I::V)> = Vec::new(); + // SGPRs read whole: numbers (EXEC included, which holds a mask here: refused) + for r in (0..128u8).filter(|&r| whole >> r & 1 != 0 && r != 125 && !(cmpx && r >= EXEC)) { + let v = self.read_num(b, r)?; + inputs.push((Var::S(r), v)); + } + // a mask read lane by lane: a number with only this lane's bit + let vop3 = d.enc.name.starts_with("ENC_VOP3") || d.enc.name.starts_with("VOP3"); + let lane_mask = if cmpx { + Some(EXEC as u64) + } else if matches!(name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") { + Some(if vop3 { rdna2::field_value(d.enc, &d.words, "SRC2").unwrap_or(0) } else { VCC as u64 }) + } else { + None + }; + if let Some(m) = lane_mask { + if m > 127 { + return Err(format!("{name}: mask operand {m}")); + } + let bit = self.src_bit(b, m)?; + let lane = self.lane(); + let one = self.ir.zext(bit); + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, lane, c31); + let own = self.ir.bin(Bin::Shl, one, sh); + if self.wave64 { + let (c32, z) = (self.ir.int(32), self.ir.int(0)); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + let (lo, hi) = (self.ir.select(upper, z, own), self.ir.select(upper, own, z)); + inputs.push((Var::S(m as u8), lo)); + inputs.push((Var::S(m as u8 + 1), hi)); + } else { + // #1426 reads the mask as an SGPR pair in wave32 too: the upper one is 0 + let z = self.ir.int(0); + inputs.push((Var::S(m as u8), own)); + inputs.push((Var::S(m as u8 + 1), z)); + } + } + if operand(true, "OPR_SSRC_SPECIAL_SCC") { + let s = self.read_scc(b); + let s = self.ir.zext(s); + inputs.push((Var::Scc, s)); + } + // VGPRs read, and the ones written (a write keeps the old value where the guard is off) + let (vr, vw) = rdna2::vgpr_uses(d); + let mut vregs: Vec = vr.iter().chain(&vw).map(|&v| v as u16).collect(); + vregs.sort_unstable(); + vregs.dedup(); + for &v in &vregs { + let x = self.read(b, Var::V(v)); + inputs.push((Var::V(v), x)); + } + // outputs: VGPRs, SGPRs (their current values seeded too, so an output the instruction + // leaves alone reads back unchanged), SCC + let sw: Vec = (0..128u8).filter(|&r| writes >> r & 1 != 0 && r != 125).collect(); + for &r in &sw { + if !inputs.iter().any(|&(v, _)| v == Var::S(r)) { + let x = self.read(b, Var::S(r)); + inputs.push((Var::S(r), x)); + } + } + let writes_scc = operand(false, "OPR_SSRC_SPECIAL_SCC"); + let mut outputs: Vec = vw.iter().map(|&v| Var::V(v as u16)).collect(); + outputs.extend(sw.iter().map(|&r| Var::S(r))); + if writes_scc { + outputs.push(Var::Scc); + } + let guard = if cmpx || in_guarded_run || !self.guarded.contains(&d.pc) { self.ir.boolean(true) } else { self.read_bit(b, EXEC)? }; + let vals = self.ir.foreign(d, guard, &inputs, &outputs)?; + for (&var, &v) in outputs.iter().zip(&vals) { + match var { + Var::V(_) => self.ssa.write(b, var, v), + Var::Scc => { + let z = self.ir.int(0); + let s = self.ir.icmp(Cmp::Ne, v, z); + self.write_scc(b, s); + } + Var::S(_) | Var::M(_) => {} + } + } + if name.starts_with("V_") && !sw.is_empty() { + // a mask (a compare, a carry-out): this lane's bit of the ballot the instruction made + let base = sw[0]; + let lo = vals[outputs.iter().position(|&v| v == Var::S(base)).unwrap()]; + let word = match (self.wave64, outputs.iter().position(|&v| v == Var::S(base + 1))) { + (true, Some(k)) => { + let lane = self.lane(); + let c32 = self.ir.int(32); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + self.ir.select(upper, vals[k], lo) + } + _ => lo, + }; + let lane = self.lane(); + let c31 = self.ir.int(31); + let sh = self.ir.bin(Bin::And, lane, c31); + let x = self.ir.bin(Bin::LShr, word, sh); + let one = self.ir.int(1); + let x = self.ir.bin(Bin::And, x, one); + let z = self.ir.int(0); + let bit = self.ir.icmp(Cmp::Ne, x, z); + self.write_bit(b, base, bit); + } else { + for (&var, &v) in outputs.iter().zip(&vals) { + if let Var::S(r) = var { + self.write_num(b, r, v); + } + } + } + Ok(()) + } + + /// Lowers one non-terminator instruction in block `b`, falling back to `bridge`. + fn lower_inst(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + let r = if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") { + self.smem(b, d) + } else if name.starts_with("S_") { + self.salu(b, d) + } else if name.starts_with("V_") { + self.valu(b, d) + } else if name.starts_with("GLOBAL_") || name.starts_with("FLAT_") { + self.vmem(b, d) + } else if name == "DS_SWIZZLE_B32" { + self.swizzle(b, d) + } else { + Err(format!("unsupported {name}")) + }; + self.or_bridge(r, b, d, self.unguarded) + } + + /// `r`, or an instruction it calls unsupported lowered through `bridge`. + fn or_bridge(&mut self, r: R<()>, b: usize, d: &Decoded, in_guarded_run: bool) -> R<()> { + match r { + Err(e) if e.starts_with("unsupported ") => match self.bridge(b, d, in_guarded_run) { + Ok(()) => Ok(()), + Err(f) if f == "no foreign lowering" => Err(e), + Err(f) => Err(format!("{e} ({f})")), + }, + r => r, + } + } + + fn note_inst(&mut self, r: R<()>, b: usize, d: &Decoded) -> R<()> { + if r.is_err() && self.noted.is_some() { + let (z, f) = (self.ir.int(0), self.ir.boolean(false)); + for s in rdna2::sgpr_uses(d).1 { + if s < KERNEL_SGPRS as u64 && s != 125 { + self.ssa.write(b, Var::S(s as u8), z); + self.ssa.write(b, Var::M(s as u8), f); + } + } + if d.inst.name.starts_with("S_") { + self.ssa.write(b, Var::Scc, f); + } + } + self.note(r) + } + + /// A refusal: the error, or in survey mode noted and passed over. + fn note(&mut self, r: R<()>) -> R<()> { + match (r, &mut self.noted) { + (Err(e), Some(n)) => { + n.push(e); + Ok(()) + } + (r, _) => r, + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use std::collections::HashMap; + + /// The IR as a small program, run lane by lane on the CPU: what the lowering means, + /// without a DXIL writer or a GPU. + #[derive(Clone, Debug)] + enum Ins { + Int(u32), + Bool(bool), + Bin(Bin, u32, u32), + Icmp(Cmp, u32, u32), + Select(u32, u32, u32), + Zext(u32), + Lane, + GroupId(u32), + /// the flat thread index in the group: the wave's first thread + lane + Flat, + /// component k of a flat index `v` in a group whose x, y sizes are given + ThreadId(u32, u32, [u32; 2]), + Ballot(u32, usize), + ReadLane(u32, u32), + /// as `Ballot` and `ReadLane`, but the lowering may use only its own 32-lane half's part + BallotHalf(u32, usize), + ReadLaneHalf(u32, u32), + CountBits(u32), + IoLoad(u32), + ResStore(u32, u32), + MemLoad(u32), + MemStore(u32, u32), + Phi(Vec<(u32, usize)>), + /// a VS / PS start: VGPR v from the lane's row of `io` (as in kernel mode), and the + /// lane's bit of the launch EXEC from `io[126..=127]` + GfxVgpr(u16), + GfxExec, + } + + #[derive(Clone, Debug)] + enum Term { + None, + Br(usize), + BrIf(u32, usize, usize), + Ret, + } + + #[derive(Default)] + struct Interp { + /// per block: (value id, instruction) in order, and the terminator + blocks: Vec<(Vec<(u32, Ins)>, Term)>, + cur: usize, + next: u32, + forward: HashMap, + undef: HashMap, + phi_block: HashMap, + } + + impl Interp { + fn push(&mut self, ins: Ins) -> u32 { + self.next += 1; + let v = self.next; + self.blocks[self.cur].0.push((v, ins)); + v + } + fn res(&self, mut v: u32) -> u32 { + while let Some(&n) = self.forward.get(&v) { + v = n; + } + v + } + fn selects(&self) -> usize { + self.blocks.iter().map(|(ins, _)| ins.iter().filter(|(_, op)| matches!(op, Ins::Select(..))).count()).sum() + } + fn br_ifs(&self) -> usize { + self.blocks.iter().filter(|(_, t)| matches!(t, Term::BrIf(..))).count() + } + } + + impl Sink for Interp { + type V = u32; + fn phi(&mut self, block: usize, _: Var) -> u32 { + self.next += 1; + let v = self.next; + self.blocks[block].0.insert(0, (v, Ins::Phi(Vec::new()))); + self.phi_block.insert(v, block); + v + } + fn incoming(&mut self, phi: u32, value: u32, pred: usize) { + let b = self.phi_block[&phi]; + for (id, ins) in &mut self.blocks[b].0 { + if *id == phi { + if let Ins::Phi(ops) = ins { + ops.push((value, pred)); + } + } + } + } + fn replace(&mut self, old: u32, new: u32) { + self.forward.insert(old, new); + let b = self.phi_block[&old]; + self.blocks[b].0.retain(|(id, _)| *id != old); + } + fn undef(&mut self, var: Var) -> u32 { + let bit = matches!(var, Var::M(_) | Var::Scc); + if let Some(&v) = self.undef.get(&bit) { + return v; + } + self.next += 1; + let v = self.next; + self.undef.insert(bit, v); + v + } + } + + impl Ir for Interp { + fn new_block(&mut self) -> usize { + self.blocks.push((Vec::new(), Term::None)); + self.blocks.len() - 1 + } + fn at(&mut self, block: usize) { + self.cur = block; + } + fn int(&mut self, v: u32) -> u32 { + self.push(Ins::Int(v)) + } + fn boolean(&mut self, v: bool) -> u32 { + self.push(Ins::Bool(v)) + } + fn bin(&mut self, op: Bin, a: u32, b: u32) -> u32 { + self.push(Ins::Bin(op, a, b)) + } + fn icmp(&mut self, c: Cmp, a: u32, b: u32) -> u32 { + self.push(Ins::Icmp(c, a, b)) + } + fn select(&mut self, c: u32, a: u32, b: u32) -> u32 { + self.push(Ins::Select(c, a, b)) + } + fn zext(&mut self, b: u32) -> u32 { + self.push(Ins::Zext(b)) + } + fn lane(&mut self) -> u32 { + self.push(Ins::Lane) + } + fn group_id(&mut self, k: u32) -> u32 { + self.push(Ins::GroupId(k)) + } + fn compute_ids(&mut self, threads: [u32; 3]) -> (u32, [u32; 3]) { + let flat = self.push(Ins::Flat); + let xy = [threads[0], threads[1]]; + (flat, [0, 1, 2].map(|k| self.push(Ins::ThreadId(k, flat, xy)))) + } + fn ballot(&mut self, c: u32) -> [u32; 2] { + [self.push(Ins::Ballot(c, 0)), self.push(Ins::Ballot(c, 1))] + } + fn ballot_half(&mut self, c: u32) -> [u32; 2] { + [self.push(Ins::BallotHalf(c, 0)), self.push(Ins::BallotHalf(c, 1))] + } + fn read_lane(&mut self, v: u32, lane: u32) -> u32 { + self.push(Ins::ReadLane(v, lane)) + } + fn read_lane_half(&mut self, v: u32, lane: u32) -> u32 { + self.push(Ins::ReadLaneHalf(v, lane)) + } + fn count_bits(&mut self, v: u32) -> u32 { + self.push(Ins::CountBits(v)) + } + fn io_load(&mut self, dword: u32) -> u32 { + self.push(Ins::IoLoad(dword)) + } + fn res_store(&mut self, dword: u32, value: u32) { + self.push(Ins::ResStore(dword, value)); + } + fn mem_load(&mut self, addr: u32) -> u32 { + self.push(Ins::MemLoad(addr)) + } + fn mem_store(&mut self, addr: u32, value: u32) { + self.push(Ins::MemStore(addr, value)); + } + fn br(&mut self, target: usize) { + self.blocks[self.cur].1 = Term::Br(target); + } + fn br_if(&mut self, c: u32, then: usize, otherwise: usize) { + self.blocks[self.cur].1 = Term::BrIf(c, then, otherwise); + } + fn ret(&mut self) { + self.blocks[self.cur].1 = Term::Ret; + } + fn graphics_start(&mut self, vregs: &[u16]) -> Option> { + let vgprs = vregs.iter().map(|&v| (v, self.push(Ins::GfxVgpr(v)))).collect(); + let exec = self.push(Ins::GfxExec); + Some(GraphicsStart { sgprs: Vec::new(), vgprs, exec }) + } + } + + /// One lane's position: block, instruction index, the block it came from, its values. + struct LaneState { + block: usize, + at: usize, + from: usize, + env: HashMap, + done: bool, + } + + impl Interp { + /// A value in a lane: what it computed, or 0 for `undef` (a marker of the lowering). + fn value(&self, env: &HashMap, v: u32) -> u32 { + let v = self.res(v); + if self.undef.values().any(|&u| u == v) { + return 0; + } + *env.get(&v).unwrap_or_else(|| panic!("value {v} not defined")) + } + } + + impl Interp { + /// Runs the program over `lanes` lanes; `io` in, `res` out. Ballots wait for every lane. + fn run(&self, lanes: usize, io: &[u32], res: &mut [u32], mem: &mut [u32]) { + self.run_with(lanes, 0, [0; 3], io, res, mem) + } + + /// One wave of a compute group: its first thread `base`, the group `group`. + fn run_with(&self, lanes: usize, base: u32, group: [u32; 3], io: &[u32], res: &mut [u32], mem: &mut [u32]) { + let mut ls: Vec = (0..lanes).map(|_| LaneState { block: 0, at: 0, from: 0, env: HashMap::new(), done: false }).collect(); + let mut steps = 0usize; + loop { + // run every lane up to a ballot or its end + for (lane, s) in ls.iter_mut().enumerate() { + while !s.done { + steps += 1; + assert!(steps < 10_000_000, "runaway program"); + let (ins, term) = &self.blocks[s.block]; + if s.at == 0 { + // phis read their operands from the edge taken, all at once + let vals: Vec<(u32, u32)> = ins + .iter() + .filter_map(|(id, i)| match i { + Ins::Phi(ops) => { + let (v, _) = ops.iter().find(|(_, p)| *p == s.from).unwrap_or_else(|| panic!("phi {id} in block {} has no operand from {}", s.block, s.from)); + Some((*id, self.value(&s.env, *v))) + } + _ => None, + }) + .collect(); + s.env.extend(vals); + } + if s.at < ins.len() { + let (id, i) = &ins[s.at]; + let g = |v: &u32| self.value(&s.env, *v); + let r = match i { + Ins::Phi(_) => None, + Ins::Int(x) => Some(*x), + Ins::Bool(x) => Some(*x as u32), + Ins::Bin(op, a, b) => { + let (a, b) = (g(a), g(b)); + Some(match op { + Bin::Add => a.wrapping_add(b), + Bin::Sub => a.wrapping_sub(b), + Bin::Mul => a.wrapping_mul(b), + Bin::And => a & b, + Bin::Or => a | b, + Bin::Xor => a ^ b, + Bin::Shl => a << (b & 31), + Bin::LShr => a >> (b & 31), + Bin::AShr => ((a as i32) >> (b & 31)) as u32, + }) + } + Ins::Icmp(c, a, b) => { + let (a, b) = (g(a), g(b)); + let (sa, sb) = (a as i32, b as i32); + Some(match c { + Cmp::Eq => a == b, + Cmp::Ne => a != b, + Cmp::Ult => a < b, + Cmp::Ule => a <= b, + Cmp::Ugt => a > b, + Cmp::Uge => a >= b, + Cmp::Slt => sa < sb, + Cmp::Sle => sa <= sb, + Cmp::Sgt => sa > sb, + Cmp::Sge => sa >= sb, + } as u32) + } + Ins::Select(c, a, b) => Some(if g(c) != 0 { g(a) } else { g(b) }), + Ins::Zext(b) => Some(g(b)), + Ins::Lane => Some(lane as u32), + Ins::GroupId(k) => Some(group[*k as usize]), + Ins::Flat => Some(base + lane as u32), + Ins::ThreadId(k, v, [x, y]) => Some(match k { + 0 => g(v) % x, + 1 => g(v) / x % y, + _ => g(v) / (x * y), + }), + Ins::Ballot(..) | Ins::BallotHalf(..) | Ins::ReadLane(..) | Ins::ReadLaneHalf(..) => break, + Ins::CountBits(v) => Some(g(v).count_ones()), + Ins::IoLoad(a) => Some(io[g(a) as usize]), + Ins::MemLoad(a) => Some(mem.get((g(a) / 4) as usize).copied().unwrap_or(0)), + Ins::MemStore(a, v) => { + let (a, v) = (g(a), g(v)); + if let Some(w) = mem.get_mut((a / 4) as usize) { + *w = v; + } + None + } + Ins::ResStore(a, v) => { + res[g(a) as usize] = g(v); + None + } + Ins::GfxVgpr(v) => Some(io[KERNEL_SGPRS + lane * KERNEL_VGPRS + *v as usize]), + Ins::GfxExec => Some(io[EXEC as usize + lane / 32] >> (lane % 32) & 1), + }; + if let Some(r) = r { + s.env.insert(*id, r); + } + s.at += 1; + continue; + } + match term { + Term::Br(t) => { + s.from = s.block; + s.block = *t; + } + Term::BrIf(c, t, f) => { + s.from = s.block; + s.block = if s.env[&self.res(*c)] != 0 { *t } else { *f }; + } + Term::Ret => s.done = true, + Term::None => panic!("block {} has no terminator", s.block), + } + s.at = 0; + } + } + if ls.iter().all(|s| s.done) { + return; + } + // the lanes waiting at the first wave operation (in block order: a loop's body + // before what follows it) run it together, as the lanes active there + let (b, at) = ls.iter().filter(|s| !s.done).map(|s| (s.block, s.at)).min().unwrap(); + let group: Vec = (0..ls.len()).filter(|&l| !ls[l].done && (ls[l].block, ls[l].at) == (b, at)).collect(); + let (id, ins) = &self.blocks[b].0[at]; + let out: Vec = match ins { + Ins::Ballot(c, half) | Ins::BallotHalf(c, half) => { + let mut bits = 0u64; + for &l in &group { + if self.value(&ls[l].env, *c) != 0 { + bits |= 1 << l; + } + } + let word = (bits >> (32 * half)) as u32; + // the half-local form: the other half's word is garbage, so a lowering + // that reads it gets a wrong result here + let local = matches!(ins, Ins::BallotHalf(..)); + group.iter().map(|&l| if local && l / 32 != *half { 0xA5A5_0000 | l as u32 } else { word }).collect() + } + Ins::ReadLane(v, from) | Ins::ReadLaneHalf(v, from) => group + .iter() + .map(|&l| { + let src = self.value(&ls[l].env, *from) as usize; + assert!(group.contains(&src), "lane {l} reads lane {src}, which is elsewhere"); + if matches!(ins, Ins::ReadLaneHalf(..)) { + assert_eq!(src / 32, l / 32, "lane {l} reads lane {src} of the other half"); + } + self.value(&ls[src].env, *v) + }) + .collect(), + _ => unreachable!(), + }; + for (&l, x) in group.iter().zip(out) { + ls[l].env.insert(*id, x); + ls[l].at += 1; + } + } + } + } + + pub(crate) type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + /// A GPU that runs `[WaveSize(32)]` programs, as the per-lane tests need (WARP, the CI + /// adapter, has neither 32 nor 64: skipped, as `recomp::tests::gpu_ready` does). + pub(crate) fn gpu_waves() -> bool { + use super::super::runner; + runner::adapter().is_ok() && runner::wave32_supported() == Ok(true) + } + + pub(crate) const V: u64 = 256; + pub(crate) const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + + // wave32 programs shared by the CPU tests and the comparison with the HLSL path + pub(crate) const STRAIGHT: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 133)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 1)]), + ENDPGM, + ]; + /// v_cmp_gt_u32 vcc, 16, v0; s_and_saveexec s0, vcc; s_cbranch_execz L; v_mov v1, 7; + /// L: s_or exec, exec, s0; v_add v2, v1, 1 + pub(crate) const SKIPPED_IF: &[I] = &[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 129), ("VSRC1", 1)]), + ENDPGM, + ]; + /// s_mov s0, exec; L: v_add v1, v1, 1; v_cmp_ge_u32 vcc, v1, v0; exec &= ~vcc; + /// s_cbranch_execnz L; exec |= s0 → v1 = max(1, lane) + pub(crate) const LEAVING_LOOP: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + /// s1 = 0; L: s1 += 3; v1 += 1; s_cmp_lt_u32 s1, 12; s_cbranch_scc1 L + pub(crate) const UNIFORM_LOOP: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 131)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 140)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ENDPGM, + ]; + + /// v1 = 4·lane; s[4:5] = mem[2..4]; v2 = mem[lane] + s4; then lanes below 16 store v2 at + /// mem[64 + lane] (a guarded store: no skip branch), and every lane stores v0 at mem[128 + lane] + pub(crate) const MEMORY: &[I] = &[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 1), ("SADDR", 125), ("OFFSET", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 2), ("SADDR", 125), ("OFFSET", 0x100)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 6)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 125), ("OFFSET", 0x200)]), + ENDPGM, + ]; + + /// A compute program: 64 threads, user SGPRs s0–s1, the group id x in s2; + /// mem[64·group + thread] = 3·thread + s0 + group + pub(crate) const COMPUTE: &[I] = &[ + ("S_MUL_I32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 192)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 3), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", V + 1), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 0), ("VSRC1", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 2), ("VSRC1", 1)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 125), ("OFFSET", 0)]), + ENDPGM, + ]; + + // f32 programs: the per-lane form refuses f32 so far, and `lower_dxil`'s + // `f32_programs_on_the_gpu` runs them on the HLSL path, checks its registers with the + // `check_f32_*` below (32 lanes) and compares the per-lane form with it where it lowers them + + /// f32 VOP2 / VOP3 arithmetic on v1 = 2^lane and v2 = 2^lane · (1 + lane / 64), with the + /// VOP3 modifiers, and v19 = NaN (0x7FFFFFFF) into min / max / clamp. Every product is exact, + /// so `FMad` gives the same fused or not. + pub(crate) const F32_ARITHMETIC: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 192), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 191), ("VSRC1", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 151), ("VSRC1", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 145), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + // 0.5 + x, x - p, x - (-4), x · x, min / max(2, x) + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 240), ("VSRC1", 2)]), + ("V_SUB_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 2), ("VSRC1", 1)]), + ("V_SUBREV_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 247), ("VSRC1", 2)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 2), ("VSRC1", 2)]), + ("V_MIN_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 244), ("VSRC1", 2)]), + ("V_MAX_F32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 244), ("VSRC1", 2)]), + // fma(x, -2, p), mad(x, 0.5, v3); mac v11 = 4 · x + p, fmac v12 = -0.5 · x + v3 + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", 245), ("SRC2", V + 1)]), + ("V_MAD_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 2), ("SRC1", 240), ("SRC2", V + 3)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 1)]), + ("V_MAC_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", 246), ("VSRC1", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 3)]), + ("V_FMAC_F32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 241), ("VSRC1", 2)]), + // -|x| · |-4| (abs before neg); omod 0.5, 2, 4 (with neg on src2); clamp at 1 and at 0 + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 2), ("SRC1", 247), ("ABS", 3), ("NEG", 1)]), + ("V_ADD_F32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 2), ("SRC1", V + 1), ("OMOD", 3)]), + ("V_SUB_F32", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 1), ("SRC1", V + 2), ("OMOD", 1)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", V + 1), ("SRC2", V + 2), ("NEG", 4), ("OMOD", 2)]), + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 4), ("SRC1", 240), ("CLAMP", 1)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 2), ("SRC1", 243), ("SRC2", 244), ("CLAMP", 1)]), + // min(NaN, x), max(x, -NaN), clamp(NaN · 1); VOP3 fmac v23 = |-0.5| · x + p + ("V_MIN_F32", "ENC_VOP2", &[("VDST", 20), ("SRC0", V + 19), ("VSRC1", 2)]), + ("V_MAX_F32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 2), ("SRC1", V + 19), ("NEG", 2)]), + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 19), ("SRC1", 242), ("CLAMP", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 1)]), + ("V_FMAC_F32", "ENC_VOP3", &[("VDST", 23), ("SRC0", 241), ("SRC1", V + 2), ("ABS", 1)]), + ENDPGM, + ]; + + /// f32 compares of a = v3 (NaN in every fourth lane, 2^lane in the others) with 4.0: all 16 + /// predicates into s[2k], two with VOP3 abs / neg, then VOPC into VCC and a cndmask of it, + /// and v_cmpx narrowing EXEC for a v_mov. + pub(crate) const F32_COMPARES: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 192), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 191), ("VSRC1", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 151), ("VSRC1", 1)]), + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 131), ("VSRC1", 0)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 4)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V + 1), ("VSRC1", 19)]), + ("V_CMP_F_F32", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_LT_F32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_EQ_F32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_LE_F32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_GT_F32", "ENC_VOP3", &[("VDST", 8), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_LG_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_GE_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_O_F32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_U_F32", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NGE_F32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NLG_F32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NGT_F32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NLE_F32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NEQ_F32", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_NLT_F32", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 3), ("SRC1", 246)]), + ("V_CMP_TRU_F32", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 3), ("SRC1", 246)]), + // -|a| == -4; !(|-2| > -a) + ("V_CMP_EQ_F32", "ENC_VOP3", &[("VDST", 32), ("SRC0", V + 3), ("SRC1", 247), ("ABS", 1), ("NEG", 1)]), + ("V_CMP_NGT_F32", "ENC_VOP3", &[("VDST", 34), ("SRC0", 245), ("SRC1", V + 3), ("ABS", 1), ("NEG", 2)]), + // vcc = a < 4, v6 = vcc ? p : 0; exec = a >= 4, v7 = 1.0 there + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 246)]), + ("V_CMP_LT_F32", "ENC_VOPC", &[("SRC0", V + 3), ("VSRC1", 5)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 128), ("VSRC1", 1)]), + ("V_CMPX_GE_F32", "ENC_VOPC", &[("SRC0", V + 3), ("VSRC1", 5)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 242)]), + ENDPGM, + ]; + + /// f32 ↔ i32 / u32 / f16 conversions: v2 = lane − 16, v4 = (lane << 26 | lane) rounded, + /// v6 = (lane − 16) / 4 into the f32 → integer ones, v11 = v4² (out of range) and v19 = NaN + /// into the saturating ones; binary16 in and out (denormals, ties to even, overflow, NaN), + /// with OP_SEL halves, omod and clamp. + pub(crate) const F32_CONVERSIONS: &[I] = &[ + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 154), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 3)]), + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 3)]), + ("V_CVT_F32_I32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 1), ("OMOD", 3), ("CLAMP", 1)]), + ("V_MUL_F32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 2), ("SRC1", 240), ("OMOD", 3)]), + ("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 6)]), + ("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 6)]), + ("V_CVT_RPI_I32_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 6)]), + ("V_CVT_FLR_I32_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 6)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 4), ("VSRC1", 4)]), + ("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 11)]), + ("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 11)]), + ("V_CVT_I32_F32", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 11), ("NEG", 1)]), + ("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V + 19)]), + ("V_CVT_I32_F32", "ENC_VOP1", &[("VDST", 16), ("SRC0", V + 19)]), + // v17 = f16 (lane & 31) << 9 | (lane & 31), the lane in the high half; v20 = it in the + // high half, the lane in the low one + ("V_AND_B32", "ENC_VOP2", &[("VDST", 23), ("SRC0", 159), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 17), ("SRC0", 137), ("VSRC1", 23)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 17), ("SRC0", V + 23), ("VSRC1", 17)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 20), ("SRC0", 144), ("VSRC1", 17)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 20), ("SRC0", V), ("VSRC1", 20)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 18), ("SRC0", 144), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 17), ("SRC0", V + 18), ("VSRC1", 17)]), + ("V_CVT_F32_F16", "ENC_VOP1", &[("VDST", 21), ("SRC0", V + 17)]), + ("V_CVT_F32_F16", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 20), ("OP_SEL", 1)]), + // v24 = 1 + (lane & 31) · 2^-14: f16 ties at lanes 8 and 24; into v25's low half + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 137), ("VSRC1", 23)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 24), ("SRC0", 255), ("VSRC1", 24), ("LITERAL", 0x3F80_0000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", V + 20)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 25), ("SRC0", V + 24)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 26), ("SRC0", V)]), + ("V_CVT_F16_F32", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 6), ("OP_SEL", 8)]), + // f16 denormals (· 2^-20), below the smallest one (· 2^-25), NaN, overflow, clamp + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 28), ("SRC0", 255), ("VSRC1", 24), ("LITERAL", 0x3580_0000)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 27), ("SRC0", V + 28)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 28), ("SRC0", 255), ("VSRC1", 24), ("LITERAL", 0x3300_0000)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 29), ("SRC0", V + 28)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 30), ("SRC0", V + 19)]), + ("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 31), ("SRC0", V + 11)]), + ("V_CVT_F16_F32", "ENC_VOP3", &[("VDST", 32), ("SRC0", V + 6), ("CLAMP", 1)]), + ENDPGM, + ]; + + /// floor / ceil / trunc / rndne / fract of v3 = (lane − 16) / 8 (ties, signed zeros), fract + /// of −2^-30 (just below 1.0), and two with VOP3 modifiers. + pub(crate) const F32_ROUNDING: &[I] = &[ + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 2), ("LITERAL", 0x3E00_0000)]), + ("V_FLOOR_F32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 3)]), + ("V_CEIL_F32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 3)]), + ("V_TRUNC_F32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 3)]), + ("V_RNDNE_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 3)]), + ("V_FRACT_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 3)]), + ("V_FRACT_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255), ("LITERAL", 0xB080_0000)]), + ("V_FLOOR_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 3), ("NEG", 1), ("OMOD", 1)]), + ("V_FRACT_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 3), ("ABS", 1), ("CLAMP", 1)]), + ENDPGM, + ]; + + /// rcp / rsq / sqrt / log of v1 = 1 + (lane & 31) / 32, exp / sin / cos of v2 = v1 − 1.5, + /// and three with VOP3 modifiers (log2 |0| = −∞ at lane 16). The GPU's are approximate. + pub(crate) const F32_TRANSCENDENTALS: &[I] = &[ + ("V_AND_B32", "ENC_VOP2", &[("VDST", 23), ("SRC0", 159), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 146), ("VSRC1", 23)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 1), ("LITERAL", 0x3F80_0000)]), + ("V_ADD_F32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V + 1), ("SRC1", 243)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 241), ("VSRC1", 2)]), + ("V_RCP_F32", "ENC_VOP1", &[("VDST", 3), ("SRC0", V + 1)]), + ("V_RCP_IFLAG_F32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 1)]), + ("V_RSQ_F32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 1)]), + ("V_SQRT_F32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 1)]), + ("V_EXP_F32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 2)]), + ("V_LOG_F32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 1)]), + ("V_SIN_F32", "ENC_VOP1", &[("VDST", 9), ("SRC0", V + 2)]), + ("V_COS_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 2)]), + ("V_EXP_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 2), ("NEG", 1), ("OMOD", 1)]), + ("V_SIN_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("CLAMP", 1)]), + ("V_LOG_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 2), ("ABS", 1)]), + ENDPGM, + ]; + + /// v_fmamk / fmaak / madmk / madak (products exact) and min3 / max3 / med3 of a = the lane + /// (NaN in every fourth lane), b = lane − 16 and 4.0, one with VOP3 abs / neg. + pub(crate) const F32_THREE_SOURCE: &[I] = &[ + ("V_LSHRREV_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", 129), ("SRC1", 193)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F32_I32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)]), + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 3), ("SRC0", V)]), + ("V_AND_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 131), ("VSRC1", 0)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 4)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", V + 3), ("VSRC1", 19)]), + ("V_FMAMK_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3FC0_0000)]), + ("V_FMAAK_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3E80_0000)]), + ("V_MADMK_F32", "ENC_VOP2", &[("VDST", 8), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3FC0_0000)]), + ("V_MADAK_F32", "ENC_VOP2", &[("VDST", 9), ("SRC0", V + 3), ("VSRC1", 2), ("LITERAL", 0x3E80_0000)]), + ("V_MIN3_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 5), ("SRC1", V + 2), ("SRC2", 246)]), + ("V_MAX3_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 5), ("SRC1", V + 2), ("SRC2", 246)]), + ("V_MED3_F32", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 5), ("SRC1", V + 2), ("SRC2", 246)]), + ("V_MED3_F32", "ENC_VOP3", &[("VDST", 13), ("SRC0", V + 2), ("SRC1", V + 5), ("SRC2", 246), ("ABS", 1), ("NEG", 2)]), + ENDPGM, + ]; + + // f16 and packed programs, as the f32 ones: `lower_dxil`'s `f16_programs_on_the_gpu` checks + // the HLSL path's registers with the `check_f16_*` below and compares the per-lane form with it + + /// f16 VOP1 / VOP2 / VOP3 on x = 1 + lane · 2^-10 (v1, and v6's low half; v6's high half is + /// −2 − lane · 2^-9): ties to even, denormal results and their ties, overflow, a fused fma + /// just below a tie (lane 1), NaN into min / max / med3, OP_SEL halves, omod and clamp, and + /// f16 ↔ i16 / u16. + pub(crate) const F16_ARITHMETIC: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x3C00)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0xC000)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 6), ("SRC0", V + 6), ("SRC1", 144), ("SRC2", V + 1)]), + // v2 = 2^-11, v3 = 2^-15 (a denormal), v4 = 65504, v5 = NaN, v7 = 2^-11 · (1 − 2^-10) + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 255), ("LITERAL", 0x1000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 255), ("LITERAL", 0x0200)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 255), ("LITERAL", 0x7BFF)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 255), ("LITERAL", 0x7E00)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 255), ("LITERAL", 0x0FFE)]), + // x + 2^-11, 2^-11 − x (ties), x · 2^-15 (denormal ties), x · 65504 (∞ from lane 1), + // fma(x, v7, x) + ("V_ADD_F16", "ENC_VOP2", &[("VDST", 8), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_SUB_F16", "ENC_VOP2", &[("VDST", 9), ("SRC0", V + 2), ("VSRC1", 1)]), + ("V_MUL_F16", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 1), ("VSRC1", 3)]), + ("V_MUL_F16", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 1), ("VSRC1", 4)]), + ("V_FMA_F16", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 1), ("SRC1", V + 7), ("SRC2", V + 1)]), + // min(NaN, x), max(x, −NaN); v15's high half = v6's + x, its low half kept + ("V_MIN_F16", "ENC_VOP2", &[("VDST", 13), ("SRC0", V + 5), ("VSRC1", 1)]), + ("V_MAX_F16", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 1), ("SRC1", V + 5), ("NEG", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", V)]), + ("V_ADD_F16", "ENC_VOP3", &[("VDST", 15), ("SRC0", V + 6), ("SRC1", V + 1), ("OP_SEL", 9)]), + // omod: (x · 0.5) · 2, (x · x − 1) · 4; clamp of 65504 · 2 + ("V_MUL_F16", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", 240), ("OMOD", 1)]), + ("V_FMA_F16", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 1), ("SRC1", V + 1), ("SRC2", 243), ("OMOD", 2)]), + ("V_MUL_F16", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 4), ("SRC1", 244), ("CLAMP", 1)]), + // ldexp(x, −lane): denormals and their ties from lane 15, 0 from lane 26 + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 20), ("SRC0", 128), ("VSRC1", 0)]), + ("V_LDEXP_F16", "ENC_VOP2", &[("VDST", 19), ("SRC0", V + 1), ("VSRC1", 20)]), + // fract of v6's high half; q = (lane − 16) / 2 into rndne (ties, −0 at lane 15), i16, u16; + // u16 2049 · lane into f16 (a tie at lane 16) + ("V_FRACT_F16", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 6), ("OP_SEL", 1)]), + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 25), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F16_I16", "ENC_VOP1", &[("VDST", 24), ("SRC0", V + 25)]), + ("V_MUL_F16", "ENC_VOP2", &[("VDST", 26), ("SRC0", 240), ("VSRC1", 24)]), + ("V_RNDNE_F16", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 26)]), + ("V_CVT_I16_F16", "ENC_VOP1", &[("VDST", 27), ("SRC0", V + 26)]), + ("V_CVT_U16_F16", "ENC_VOP1", &[("VDST", 28), ("SRC0", V + 26)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 30), ("SRC0", V), ("SRC1", 139), ("SRC2", V)]), + ("V_CVT_F16_U16", "ENC_VOP1", &[("VDST", 29), ("SRC0", V + 30)]), + // med3(NaN, x, 2); fmac v32 = x · 2^-11 + x + ("V_MED3_F16", "ENC_VOP3", &[("VDST", 31), ("SRC0", V + 5), ("SRC1", V + 1), ("SRC2", 244)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 32), ("SRC0", V + 1)]), + ("V_FMAC_F16", "ENC_VOP2", &[("VDST", 32), ("SRC0", V + 1), ("VSRC1", 2)]), + ENDPGM, + ]; + + /// VOP3P packed math on v1 = x | y << 16 (x, y as in `F16_ARITHMETIC`), v2 = 2^-11 | 2^-15 << 16, + /// v3 = NaN | 65504 << 16 and the u16 / i16 pairs v4 = 2049 · lane | (0xFFFF − lane) << 16, + /// v5 = (0x8000 + lane << 10) | (0x7FF0 + lane) << 16: OP_SEL / OP_SEL_HI picking swapped and + /// broadcast halves, NEG / NEG_HI, clamp (f16, and saturating u16 / i16), and + /// v_cvt_pkrtz_f16_f32 (toward zero, 65504 for the out-of-range ones). + pub(crate) const F16_PACKED: &[I] = &[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x3C00)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0xC000)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V + 9), ("SRC1", 144), ("SRC2", V + 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 255), ("LITERAL", 0x0200_1000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 255), ("LITERAL", 0x7BFF_7E00)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 255), ("LITERAL", 0x0FFE_0FFE)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 139), ("SRC2", V)]), + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 11), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0xFFFF)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 11), ("SRC1", 144), ("SRC2", V + 10)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 138), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 12), ("SRC0", 255), ("VSRC1", 12), ("LITERAL", 0x8000)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x7FF0)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 13), ("SRC1", 144), ("SRC2", V + 12)]), + // v1 + v2; v1.hi · v2.lo | v1.lo · v2.hi; fma(v1, v7, v1) (v7 as in `F16_ARITHMETIC`) + ("V_PK_ADD_F16", "ENC_VOP3P", &[("VDST", 14), ("SRC0", V + 1), ("SRC1", V + 2), ("OP_SEL_HI", 3)]), + ("V_PK_MUL_F16", "ENC_VOP3P", &[("VDST", 15), ("SRC0", V + 1), ("SRC1", V + 2), ("OP_SEL", 1), ("OP_SEL_HI", 2)]), + ("V_PK_FMA_F16", "ENC_VOP3P", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", V + 7), ("SRC2", V + 1), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)]), + // min(v3, v1), max(v1, −v3), v1 + (−lo | hi of v1's high half), clamp(v3.hi · v1) + ("V_PK_MIN_F16", "ENC_VOP3P", &[("VDST", 17), ("SRC0", V + 3), ("SRC1", V + 1), ("OP_SEL_HI", 3)]), + ("V_PK_MAX_F16", "ENC_VOP3P", &[("VDST", 18), ("SRC0", V + 1), ("SRC1", V + 3), ("OP_SEL_HI", 3), ("NEG", 2), ("NEG_HI", 2)]), + ("V_PK_ADD_F16", "ENC_VOP3P", &[("VDST", 19), ("SRC0", V + 1), ("SRC1", V + 1), ("OP_SEL_HI", 3), ("NEG_HI", 1)]), + ("V_PK_MUL_F16", "ENC_VOP3P", &[("VDST", 20), ("SRC0", V + 3), ("SRC1", V + 1), ("OP_SEL", 1), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + // u16 / i16: wrapping, saturating (clamp), v4.lo · v5.hi | v4.hi · v5.hi, v4 · v4 + v5 + ("V_PK_ADD_U16", "ENC_VOP3P", &[("VDST", 21), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3)]), + ("V_PK_ADD_U16", "ENC_VOP3P", &[("VDST", 22), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + ("V_PK_SUB_U16", "ENC_VOP3P", &[("VDST", 23), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + ("V_PK_ADD_I16", "ENC_VOP3P", &[("VDST", 24), ("SRC0", V + 5), ("SRC1", V + 5), ("OP_SEL_HI", 3), ("CLAMP", 1)]), + ("V_PK_SUB_I16", "ENC_VOP3P", &[("VDST", 25), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL_HI", 3)]), + ("V_PK_MUL_LO_U16", "ENC_VOP3P", &[("VDST", 26), ("SRC0", V + 4), ("SRC1", V + 5), ("OP_SEL", 2), ("OP_SEL_HI", 3)]), + ("V_PK_MAD_U16", "ENC_VOP3P", &[("VDST", 27), ("SRC0", V + 4), ("SRC1", V + 4), ("SRC2", V + 5), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)]), + // pkrtz of 1 + lane · 2^-11 and of 65520 + 16 · lane (f32) + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 31), ("SRC0", 140), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 29), ("SRC0", 255), ("VSRC1", 31), ("LITERAL", 0x3F80_0000)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 255), ("VSRC1", 31), ("LITERAL", 0x477F_F000)]), + ("V_CVT_PKRTZ_F16_F32", "ENC_VOP2", &[("VDST", 28), ("SRC0", V + 29), ("VSRC1", 30)]), + ENDPGM, + ]; + + /// binary16 of an f64 (exact: an f16 sum or product), rounded to nearest even: denormals, + /// and ∞ past 65504 + pub(crate) fn f16_bits(x: f64) -> u32 { + let s = (x.is_sign_negative() as u32) << 15; + let a = x.abs(); + if a.is_infinite() { + return s | 0x7C00; + } + let e = ((a.to_bits() >> 52) as i32 - 1023).max(-14); + let q = (a * 2f64.powi(10 - e)).round_ties_even() as u32; + s | ((e + 14) as u32 * 1024 + q).min(0x7C00) + } + + pub(crate) fn check_f16_arithmetic(_: &[u32], v: &[Vec]) { + let h = |b: u32| f16_to_f32(b & 0xFFFF) as f64; + let p = |e: i32| 2f64.powi(e); + for (l, r) in v.iter().enumerate() { + let (x, y) = (0x3C00 + l as u32, 0xC000 + l as u32); + let (fx, fy, q) = (h(x), h(y), (l as f64 - 16.0) / 2.0); + assert_eq!((r[1], r[6]), (x, y << 16 | x), "lane {l}"); + // v8, v9, v12, v17, v19, v29 and v32 round to nearest even on the console (MODE.FP_ROUND + // = 0) and the HLSL path gives them rounded toward zero on NVIDIA (`f32tof16`, whose + // rounding the driver picks), so they are left to the per-lane comparison + let want = [ + (10, f16_bits(fx * p(-15))), + (11, f16_bits(fx * 65504.0)), + (13, x), + (14, x), + (15, f16_bits(fy + fx) << 16 | l as u32), + (16, x), + (18, 0x3C00), + (22, f16_bits(fy - fy.floor())), + (23, f16_bits(q.round_ties_even())), + (24, f16_bits(l as f64 - 16.0)), + (26, f16_bits(q)), + (27, q as i32 as u32 & 0xFFFF), + (28, q as u32), + (31, x), + ]; + for (i, w) in want { + assert_eq!(r[i], w, "lane {l} v{i}: {:#x} against {w:#x}", r[i]); + } + } + } + + pub(crate) fn check_f16_packed(_: &[u32], v: &[Vec]) { + let h = |b: u32| f16_to_f32(b & 0xFFFF) as f64; + let p = |e: i32| 2f64.powi(e); + let pk = |lo: u32, hi: u32| lo & 0xFFFF | hi << 16; + let i16s = |a: u32| a as u16 as i16 as i32; + let sat = |a: i32| a.clamp(-32768, 32767) as u32; + for (l, r) in v.iter().enumerate() { + let n = l as u32; + let (x, y) = (0x3C00 + n, 0xC000 + n); + let (fx, fy) = (h(x), h(y)); + let (a0, a1, c0, c1) = (2049 * n, 0xFFFF - n, 0x8000 + (n << 10), 0x7FF0 + n); + assert_eq!((r[1], r[4], r[5]), (pk(x, y), pk(a0, a1), pk(c0, c1)), "lane {l}"); + // v14 and v16 as v8 and v12 of `check_f16_arithmetic` + let want = [ + (15, pk(f16_bits(fy * p(-11)), f16_bits(fx * p(-15)))), + (17, pk(x, y)), + (18, pk(x, y)), + (19, pk(f16_bits(2.0 * fx), 0)), + (20, pk(0x3C00, 0)), + (21, pk(a0 + c0, a1 + c1)), + (22, pk((a0 + c0).min(0xFFFF), (a1 + c1).min(0xFFFF))), + (23, pk(a0.saturating_sub(c0), a1.saturating_sub(c1))), + (24, pk(sat(2 * i16s(c0)), sat(2 * i16s(c1)))), + (25, pk(a0.wrapping_sub(c0), a1.wrapping_sub(c1))), + (26, pk(a0 * c1, a1 * c1)), + (27, pk(a0 * a0 + c0, a1 * a1 + c1)), + (28, pk(0x3C00 + n / 2, 0x7BFF)), + ]; + for (i, w) in want { + assert_eq!(r[i], w, "lane {l} v{i}: {:#x} against {w:#x}", r[i]); + } + } + } + + pub(crate) fn check_f32_arithmetic(_: &[u32], v: &[Vec]) { + let sat = |x: f32| x.clamp(0.0, 1.0); + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f32::from_bits(r[i]); + let (p, x) = (f(1), f(2)); + assert_eq!((p, x), (2f32.powi(l as i32), 2f32.powi(l as i32) * (1.0 + l as f32 / 64.0)), "lane {l}"); + let y = x + 0.5; + let want = [y, x - p, x + 4.0, x * x, x.min(2.0), x.max(2.0), x * -2.0 + p, x * 0.5 + y, 4.0 * x + p, -0.5 * x + y, -x * 4.0, (x + p) * 0.5, (p - x) * 2.0, (p * p - x) * 4.0, sat((x - p) * 0.5), sat(2.0 - x)]; + for (i, w) in want.iter().enumerate() { + assert_eq!(f(3 + i).to_bits(), w.to_bits(), "lane {l} v{}: {} against {w}", 3 + i, f(3 + i)); + } + assert_eq!((r[20], r[21], r[22]), (r[2], r[2], 0), "lane {l}: NaN into min, max, clamp"); + assert_eq!(f(23), 0.5 * x + p, "lane {l}: VOP3 fmac"); + } + } + + pub(crate) fn check_f32_compares(s: &[u32], v: &[Vec]) { + let preds: [fn(f32, f32) -> bool; 18] = [ + |_, _| false, + |a, b| a < b, + |a, b| a == b, + |a, b| a <= b, + |a, b| a > b, + |a, b| a < b || a > b, + |a, b| a >= b, + |a, b| !a.is_nan() && !b.is_nan(), + |a, b| a.is_nan() || b.is_nan(), + |a, b| !(a >= b), + |a, b| !(a < b || a > b), + |a, b| !(a > b), + |a, b| !(a <= b), + |a, b| !(a == b), + |a, b| !(a < b), + |_, _| true, + |a, _| -a.abs() == -4.0, + |a, _| !(2.0 > -a), + ]; + let a: Vec = (0..32).map(|l| if l % 4 == 0 { f32::from_bits(0x7FFF_FFFF) } else { 2f32.powi(l) }).collect(); + let mask = |p: &dyn Fn(f32) -> bool| (0..32).filter(|&l| p(a[l])).fold(0u32, |m, l| m | 1 << l); + for (k, p) in preds.iter().enumerate() { + assert_eq!(s[2 * k], mask(&|x| p(x, 4.0)), "s{}", 2 * k); + } + assert_eq!(s[106], mask(&|x| x < 4.0), "vcc"); + assert_eq!(s[126], mask(&|x| x >= 4.0), "exec"); + for (l, r) in v.iter().enumerate() { + assert_eq!(r[3], a[l].to_bits(), "lane {l}"); + assert_eq!(r[6], if a[l] < 4.0 { r[1] } else { 0 }, "lane {l}: cndmask"); + assert_eq!(r[7], if a[l] >= 4.0 { 1f32.to_bits() } else { 0 }, "lane {l}: under v_cmpx"); + } + } + + pub(crate) fn check_f32_conversions(_: &[u32], v: &[Vec]) { + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f32::from_bits(r[i]); + let (li, q) = (l as i32 - 16, (l as i32 - 16) as f32 / 4.0); + assert_eq!(f(2), li as f32, "lane {l}"); + assert_eq!(f(4), ((l as u32) << 26 | l as u32) as f32, "lane {l}: u32 rounded to nearest even"); + assert_eq!(f(5), (li as f32 * 0.5).clamp(0.0, 1.0), "lane {l}: omod and clamp"); + assert_eq!(f(6), q, "lane {l}"); + // the HLSL path's cvt_i32 / cvt_u32 saturate as Rust's `as` does, NaN giving 0 + assert_eq!((r[7], r[8]), (q as i32 as u32, q as u32), "lane {l}: truncated"); + assert_eq!((r[9], r[10]), ((q + 0.5).floor() as i32 as u32, q.floor() as i32 as u32), "lane {l}: rpi, flr"); + assert_eq!((r[12], r[13], r[14]), (f(11) as i32 as u32, f(11) as u32, (-f(11)) as i32 as u32), "lane {l}: out of range"); + assert_eq!((r[15], r[16]), (0, 0), "lane {l}: NaN"); + assert_eq!(f(21), f16_to_f32(r[17] & 0xFFFF), "lane {l}"); + assert_eq!(r[22], r[21], "lane {l}: the high half"); + assert_eq!(r[25] >> 16, r[20] >> 16, "lane {l}: the half kept"); + assert_eq!(r[26] & 0xFFFF, l as u32, "lane {l}: the half kept"); + assert_eq!(r[29], (l != 0) as u32, "lane {l}: below the smallest denormal"); + assert_eq!(r[30], 0x7FFF, "lane {l}: NaN"); + assert_eq!(r[31], if l == 0 { 0 } else { 0x7C00 }, "lane {l}: overflow"); + } + let lo = |l: usize, i: usize| v[l][i] & 0xFFFF; + assert_eq!([lo(0, 21), lo(1, 17), lo(30, 17)], [0, 0x0201, 0x3C1E]); + assert_eq!((f32::from_bits(v[1][21]), f32::from_bits(v[30][21])), (513.0 * 2f32.powi(-24), 1.0 + 30.0 / 1024.0), "f16 in"); + // 1 + k · 2^-14 at k = 1, 8, 16, 24, 31: ties to even at 8 and 24 + assert_eq!([1, 8, 16, 24, 31].map(|l| lo(l, 25)), [0x3C00, 0x3C00, 0x3C01, 0x3C02, 0x3C02]); + assert_eq!([0, 16, 18, 20].map(|l| v[l][26] >> 16), [0xC400, 0, 0x3800, 0x3C00], "f16 into the high half"); + assert_eq!([0, 18, 20, 31].map(|l| lo(l, 32)), [0, 0x3800, 0x3C00, 0x3C00], "clamp"); + assert_eq!(lo(0, 27), 0x0010, "2^-20: an f16 denormal"); + } + + pub(crate) fn check_f32_rounding(_: &[u32], v: &[Vec]) { + for (l, r) in v.iter().enumerate() { + let x = (l as i32 - 16) as f32 / 8.0; + let want = [x.floor(), x.ceil(), x.trunc(), x.round_ties_even(), x - x.floor()]; + for (i, w) in want.iter().enumerate() { + assert_eq!(r[4 + i], w.to_bits(), "lane {l} v{}", 4 + i); + } + assert_eq!(r[9], 0x3F7F_FFFF, "fract(-2^-30): below 1.0"); + assert_eq!(r[10], (2.0 * (-x).floor()).to_bits(), "lane {l} v10"); + assert_eq!(f32::from_bits(r[11]), x.abs() - x.abs().floor(), "lane {l}"); + } + } + + pub(crate) fn check_f32_three_source(_: &[u32], v: &[Vec]) { + let med3 = |a: f32, b: f32, c: f32| a.min(b).max(a.max(b).min(c)); + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f32::from_bits(r[i]); + let (x, y) = (l as f32, l as f32 - 16.0); + let a = if l % 4 == 0 { f32::from_bits(0x7FFF_FFFF) } else { x }; + assert_eq!([f(6), f(7), f(8), f(9)], [x * 1.5 + y, x * y + 0.25, x * 1.5 + y, x * y + 0.25], "lane {l}"); + assert_eq!([f(10), f(11), f(12)], [a.min(y).min(4.0), a.max(y).max(4.0), med3(a, y, 4.0)], "lane {l}"); + assert_eq!(f(13), med3(y.abs(), -a, 4.0), "lane {l}"); + } + } + + pub(crate) fn check_f32_transcendentals(_: &[u32], v: &[Vec]) { + let sat = |x: f32| x.clamp(0.0, 1.0); + for (l, r) in v.iter().enumerate() { + let x = 1.0 + (l & 31) as f32 / 32.0; + let y = x - 1.5; + let t = y * 6.283_185_3; + assert_eq!((r[1], r[2]), (x.to_bits(), y.to_bits()), "lane {l}"); + let want = [1.0 / x, 1.0 / x, 1.0 / x.sqrt(), x.sqrt(), y.exp2(), x.log2(), t.sin(), t.cos(), 2.0 * (-y).exp2(), sat(t.sin()), y.abs().log2()]; + for (i, w) in want.iter().enumerate() { + assert!(f32_close(r[3 + i], w.to_bits()), "lane {l} v{}: {} against {w}", 3 + i, f32::from_bits(r[3 + i])); + } + } + } + + /// The same bits, or within `approximate_float_unary_ops_are_within_tolerance`'s tolerance. + pub(crate) fn f32_close(a: u32, b: u32) -> bool { + let (a, b) = (f32::from_bits(a), f32::from_bits(b)); + a.to_bits() == b.to_bits() || (a - b).abs() <= 1e-3f32.max(b.abs() * 1e-5) + } + + /// binary16 in the low 16 bits → f32 (`f16tof32`) + pub(crate) fn f16_to_f32(h: u32) -> f32 { + let (s, e, m) = (h >> 15 & 1, h >> 10 & 0x1F, h & 0x3FF); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 => f32::from_bits(0x7F80_0000 | m << 13), + _ => f32::from_bits((e + 112) << 23 | m << 13), + }; + if s == 1 { -v } else { v } + } + + // integer programs, as the f32 ones: `lower_dxil`'s `integer_programs_on_the_gpu` checks the + // HLSL path's registers with the `check_int_*` below and compares the per-lane form with it + + /// a = lane · 0x9E3779B9 (v1), b = lane − (a >> 13) (v2, negative but at lane 0) and + /// c = 0x7FFFFFF0 + lane (v3, past i32::MAX from lane 16) + const INT_INPUTS: [I; 5] = [ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255), ("LITERAL", 0x9E37_79B9)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V + 9)]), + ("V_LSHRREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 141), ("VSRC1", 1)]), + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x7FFF_FFF0)]), + ]; + + /// Integer VALU on a, b, c (`INT_INPUTS`): high products, 24-bit and 16-bit multiplies (OP_SEL + /// halves), bitfields with offset + width past 32 and width 0, align, SAD, min3 / max3 / med3, + /// clamped (saturating) adds, bit counts and scans of 0 and −1, packs that saturate. + pub(crate) const INT_ARITHMETIC: &[I] = &[ + INT_INPUTS[0], INT_INPUTS[1], INT_INPUTS[2], INT_INPUTS[3], INT_INPUTS[4], + ("V_MUL_HI_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_MUL_HI_I32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_MUL_U32_U24", "ENC_VOP2", &[("VDST", 12), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_HI_U32_U24", "ENC_VOP2", &[("VDST", 13), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_I32_I24", "ENC_VOP2", &[("VDST", 14), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MUL_HI_I32_I24", "ENC_VOP2", &[("VDST", 15), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MAD_I32_I24", "ENC_VOP3", &[("VDST", 17), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + // bfe(a, lane, 8) unsigned and signed, bfe(a, 4, lane), bfi, bfm(lane, 4) + ("V_BFE_U32", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 1), ("SRC1", V), ("SRC2", 136)]), + ("V_BFE_I32", "ENC_VOP3", &[("VDST", 19), ("SRC0", V + 1), ("SRC1", V), ("SRC2", 136)]), + ("V_BFE_U32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 132), ("SRC2", V)]), + ("V_BFI_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_BFM_B32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V), ("SRC1", 132)]), + ("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 23), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V)]), + ("V_ALIGNBYTE_B32", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V)]), + ("V_XAD_U32", "ENC_VOP3", &[("VDST", 25), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_U8", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_HI_U8", "ENC_VOP3", &[("VDST", 27), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_U16", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_SAD_U32", "ENC_VOP3", &[("VDST", 29), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MSAD_U8", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MIN3_U32", "ENC_VOP3", &[("VDST", 31), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MAX3_I32", "ENC_VOP3", &[("VDST", 32), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MED3_U32", "ENC_VOP3", &[("VDST", 33), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MED3_I32", "ENC_VOP3", &[("VDST", 34), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MIN3_I32", "ENC_VOP3", &[("VDST", 35), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + ("V_MAX3_U32", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)]), + // clamp: a + b + c, a + b, b − a (u32); a + c, b − c (i32); a + c without + ("V_ADD3_U32", "ENC_VOP3", &[("VDST", 37), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3), ("CLAMP", 1)]), + ("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 38), ("SRC0", V + 1), ("SRC1", V + 2), ("CLAMP", 1)]), + ("V_SUB_NC_U32", "ENC_VOP3", &[("VDST", 39), ("SRC0", V + 2), ("SRC1", V + 1), ("CLAMP", 1)]), + ("V_ADD_NC_I32", "ENC_VOP3", &[("VDST", 40), ("SRC0", V + 1), ("SRC1", V + 3), ("CLAMP", 1)]), + ("V_SUB_NC_I32", "ENC_VOP3", &[("VDST", 41), ("SRC0", V + 2), ("SRC1", V + 3), ("CLAMP", 1)]), + ("V_ADD_NC_I32", "ENC_VOP3", &[("VDST", 42), ("SRC0", V + 1), ("SRC1", V + 3)]), + // bcnt(a) + lane, ffbh / ffbl / ffbh_i32 (0 and −1 at lane 0), bfrev, not, xnor + ("V_BCNT_U32_B32", "ENC_VOP3", &[("VDST", 43), ("SRC0", V + 1), ("SRC1", V)]), + ("V_FFBH_U32", "ENC_VOP1", &[("VDST", 44), ("SRC0", V + 1)]), + ("V_FFBL_B32", "ENC_VOP1", &[("VDST", 45), ("SRC0", V + 2)]), + ("V_FFBH_I32", "ENC_VOP1", &[("VDST", 46), ("SRC0", V + 2)]), + ("V_BFREV_B32", "ENC_VOP1", &[("VDST", 47), ("SRC0", V + 1)]), + ("V_NOT_B32", "ENC_VOP1", &[("VDST", 48), ("SRC0", V + 2)]), + ("V_XNOR_B32", "ENC_VOP2", &[("VDST", 49), ("SRC0", V + 1), ("VSRC1", 2)]), + // packs of (a, b) to u16 and (b, c) to i16; 16-bit mads of a.hi · b.lo, a.lo · b.hi + ("V_CVT_PK_U16_U32", "ENC_VOP3", &[("VDST", 50), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_CVT_PK_I16_I32", "ENC_VOP3", &[("VDST", 51), ("SRC0", V + 2), ("SRC1", V + 3)]), + ("V_MAD_U32_U16", "ENC_VOP3", &[("VDST", 52), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3), ("OP_SEL", 1)]), + ("V_MAD_I32_I16", "ENC_VOP3", &[("VDST", 53), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3), ("OP_SEL", 2)]), + ("V_MIN_I32", "ENC_VOP2", &[("VDST", 54), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_MAX_U32", "ENC_VOP2", &[("VDST", 55), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 56), ("SRC0", V + 1), ("SRC1", V), ("SRC2", V + 3)]), + ("V_ADD_LSHL_U32", "ENC_VOP3", &[("VDST", 57), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V)]), + ENDPGM, + ]; + + /// Carries on a, b, c (`INT_INPUTS`): VOP3 carry-outs into s20..s30 and carry-ins from them, + /// a VOP2 chain through VCC, a VOP3 cndmask on s22, v_mad_u64_u32 / v_mad_i64_i32 with their + /// carry-outs (s32, s34) and the 64-bit shifts by 2 · lane + 3 (65 at lane 31: 1). + pub(crate) const INT_CARRIES: &[I] = &[ + INT_INPUTS[0], INT_INPUTS[1], INT_INPUTS[2], INT_INPUTS[3], INT_INPUTS[4], + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 10), ("SDST", 20), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 11), ("SDST", 22), ("SRC0", V + 1), ("SRC1", V + 3), ("SRC2", 20)]), + ("V_SUB_CO_U32", "VOP3_SDST_ENC", &[("VDST", 12), ("SDST", 24), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 13), ("SDST", 26), ("SRC0", V + 3), ("SRC1", V + 2), ("SRC2", 24)]), + ("V_SUBREV_CO_U32", "VOP3_SDST_ENC", &[("VDST", 14), ("SDST", 28), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 15), ("SDST", 30), ("SRC0", V + 2), ("SRC1", V + 3), ("SRC2", 28)]), + // vcc = a > b; a + b + vcc, c − a − vcc, a − c − vcc, each into vcc + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 2)]), + ("V_ADD_CO_CI_U32", "ENC_VOP2", &[("VDST", 16), ("SRC0", V + 1), ("VSRC1", 2)]), + ("V_SUB_CO_CI_U32", "ENC_VOP2", &[("VDST", 17), ("SRC0", V + 3), ("VSRC1", 1)]), + ("V_SUBREV_CO_CI_U32", "ENC_VOP2", &[("VDST", 18), ("SRC0", V + 3), ("VSRC1", 1)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 19), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", 22)]), + // v[20:21] = a · b + (c | a << 32), v[24:25] the same signed; shifts of them and of v[22:23] + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 22), ("SRC0", V + 3)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 23), ("SRC0", V + 1)]), + ("V_MAD_U64_U32", "VOP3_SDST_ENC", &[("VDST", 20), ("SDST", 32), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 22)]), + ("V_MAD_I64_I32", "VOP3_SDST_ENC", &[("VDST", 24), ("SDST", 34), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 22)]), + ("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", 129), ("SRC2", 131)]), + ("V_LSHLREV_B64", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 4), ("SRC1", V + 20)]), + ("V_LSHRREV_B64", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 4), ("SRC1", V + 22)]), + ("V_ASHRREV_I64", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 4), ("SRC1", V + 24)]), + ENDPGM, + ]; + + /// `INT_INPUTS`' a, b, c of a lane + fn int_inputs(l: usize) -> (u32, u32, u32) { + let a = (l as u32).wrapping_mul(0x9E37_79B9); + (a, (l as u32).wrapping_sub(a >> 13), 0x7FFF_FFF0 + l as u32) + } + + pub(crate) fn check_int_arithmetic(_: &[u32], v: &[Vec]) { + let (u24, i24) = (|x: u32| (x & 0xFF_FFFF) as u64, |x: u32| ((x << 8) as i32 >> 8) as i64); + let i16s = |x: u32| x as u16 as i16 as i32; + let bytes = |x: u32| x.to_le_bytes().map(|b| b as i32); + let first = |n: u32, x: u32| if x == 0 { u32::MAX } else { n }; + for (l, r) in v.iter().enumerate() { + let (a, b, c) = int_inputs(l); + let n = l as u32; + let (ai, bi, ci) = (a as i32, b as i32, c as i32); + assert_eq!((r[1], r[2], r[3]), (a, b, c), "lane {l}"); + let mask = |w: u32| ((1u64 << w) - 1) as u32; + let sext = |x: u32, w: u32| if w == 0 { 0 } else { ((x << (32 - w)) as i32 >> (32 - w)) as u32 }; + let (ba, bb) = (bytes(a), bytes(b)); + let sad8: i32 = (0..4).map(|k| (ba[k] - bb[k]).abs()).sum(); + let msad8: i32 = (0..4).filter(|&k| bb[k] != 0).map(|k| (ba[k] - bb[k]).abs()).sum(); + let sad16 = (i16s(a) as u16 as i32 - b as u16 as i32).abs() + ((a >> 16) as i32 - (b >> 16) as i32).abs(); + let med3 = |x: u32, y: u32, z: u32| x.min(y).max(x.max(y).min(z)); + let med3i = |x: i32, y: i32, z: i32| x.min(y).max(x.max(y).min(z)); + let ffbh_i = |x: u32| if x == 0 || x == u32::MAX { u32::MAX } else { (x ^ (x as i32 >> 31) as u32).leading_zeros() }; + let want = [ + ((a as u64 * b as u64) >> 32) as u32, + ((ai as i64 * bi as i64) >> 32) as u32, + (u24(a) * u24(b)) as u32, + ((u24(a) * u24(b)) >> 32) as u32, + (i24(a) * i24(b)) as u32, + ((i24(a) * i24(b)) >> 32) as u32, + ((u24(a) * u24(b)) as u32).wrapping_add(c), + ((i24(a) * i24(b)) as u32).wrapping_add(c), + a >> (n & 31) & mask(8), + sext((ai >> (n & 31)) as u32 & mask(8), 8), + a >> 4 & mask(n & 31), + a & b | !a & c, + mask(n & 31) << 4, + (((a as u64) << 32 | b as u64) >> (n & 31)) as u32, + (((a as u64) << 32 | b as u64) >> (8 * (n & 3))) as u32, + (a ^ b).wrapping_add(c), + (sad8 as u32).wrapping_add(c), + ((sad8 as u32) << 16).wrapping_add(c), + (sad16 as u32).wrapping_add(c), + a.abs_diff(b).wrapping_add(c), + (msad8 as u32).wrapping_add(c), + a.min(b).min(c), + ai.max(bi).max(ci) as u32, + med3(a, b, c), + med3i(ai, bi, ci) as u32, + ai.min(bi).min(ci) as u32, + a.max(b).max(c), + (a as u64 + b as u64 + c as u64).min(u32::MAX as u64) as u32, + a.saturating_add(b), + b.saturating_sub(a), + ai.saturating_add(ci) as u32, + bi.saturating_sub(ci) as u32, + a.wrapping_add(c), + a.count_ones() + n, + first(a.leading_zeros(), a), + first(b.trailing_zeros(), b), + ffbh_i(b), + a.reverse_bits(), + !b, + !(a ^ b), + a.min(0xFFFF) | b.min(0xFFFF) << 16, + bi.clamp(-32768, 32767) as u32 & 0xFFFF | (ci.clamp(-32768, 32767) as u32) << 16, + (a >> 16).wrapping_mul(b & 0xFFFF).wrapping_add(c), + (i16s(a) * i16s(b >> 16)).wrapping_add(ci) as u32, + ai.min(bi) as u32, + a.max(b), + (a << (n & 31)).wrapping_add(c), + a.wrapping_add(b) << (n & 31), + ]; + for (k, w) in want.iter().enumerate() { + assert_eq!(r[10 + k], *w, "lane {l} v{}: {:#x} against {w:#x}", 10 + k, r[10 + k]); + } + } + } + + pub(crate) fn check_int_carries(s: &[u32], v: &[Vec]) { + let mut masks = [0u32; 8]; + for (l, r) in v.iter().enumerate() { + let (a, b, c) = int_inputs(l); + let (a64, b64, c64) = (a as u64, b as u64, c as u64); + let bit = |m: u32| (m >> l & 1) as u64; + let carry = [a64 + b64 > u32::MAX as u64, a64 + c64 + bit(s[20]) > u32::MAX as u64, b > a, b64 + bit(s[24]) > c64, a > b, b64 + bit(s[28]) > c64]; + let want = [a.wrapping_add(b), (a64 + c64 + bit(s[20])) as u32, a.wrapping_sub(b), (c64.wrapping_sub(b64 + bit(s[24]))) as u32, b.wrapping_sub(a), (c64.wrapping_sub(b64 + bit(s[28]))) as u32]; + for k in 0..6 { + assert_eq!(r[10 + k], want[k], "lane {l} v{}", 10 + k); + masks[k] |= (carry[k] as u32) << l; + } + // the VCC chain + let v0 = (a > b) as u64; + let w16 = a64 + b64 + v0; + let v1 = (w16 >> 32) as u64; + let v2 = (a64 + v1 > c64) as u64; + let v3 = (c64 + v2 > a64) as u64; + assert_eq!([r[16], r[17], r[18]], [w16 as u32, c64.wrapping_sub(a64 + v1) as u32, a64.wrapping_sub(c64 + v2) as u32], "lane {l}: through vcc"); + masks[6] |= (v3 as u32) << l; + assert_eq!(r[19], if bit(s[22]) == 1 { b } else { a }, "lane {l}: cndmask"); + let addend = c64 | a64 << 32; + let (wu, cu) = (a64 * b64).overflowing_add(addend); + let wi = ((a as i32 as i64 * b as i32 as i64) as u64).wrapping_add(addend); + masks[7] |= (cu as u32) << l; + let sh = (2 * l as u32 + 3) & 63; + let pair = |i: usize| r[i] as u64 | (r[i + 1] as u64) << 32; + assert_eq!([pair(20), pair(22), pair(24)], [wu, addend, wi], "lane {l}: mads"); + assert_eq!([pair(26), pair(28), pair(30)], [wu << sh, addend >> sh, ((wi as i64) >> sh) as u64], "lane {l}: 64-bit shifts"); + } + let got = [s[20], s[22], s[24], s[26], s[28], s[30], s[106], s[32]]; + assert_eq!(got, masks, "carry-outs s20..s30, vcc, s32"); + } + + pub(crate) fn compute_cs() -> crate::gpu::recomp::CsInterface { + crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 } + } + + /// A compute program run on the CPU over `groups` groups (wave32): the memory after. + pub(crate) fn run_compute(lines: &[I], cs: &crate::gpu::recomp::CsInterface, groups: u32, sgprs: &[u32], mem: &[u32]) -> Vec { + run_compute_waves(lines, cs, false, groups, sgprs, mem) + } + + /// … in wave32 or wave64: each wave takes the next `lanes` threads of its group, as on the + /// console (the last one fewer). + pub(crate) fn run_compute_waves(lines: &[I], cs: &crate::gpu::recomp::CsInterface, wave64: bool, groups: u32, sgprs: &[u32], mem: &[u32]) -> Vec { + let ir = lower_compute(&decode(lines), cs, wave64, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let lanes = if wave64 { 64 } else { 32 }; + let mut io = vec![0u32; KERNEL_SGPRS]; + io[..sgprs.len()].copy_from_slice(sgprs); + let mut res = vec![0u32; KERNEL_SGPRS]; + let mut mem = mem.to_vec(); + let threads: u32 = cs.threads.iter().product(); + for g in 0..groups { + for w in (0..threads).step_by(lanes as usize) { + ir.run_with(lanes.min(threads - w) as usize, w, [g, 0, 0], &io, &mut res, &mut mem); + } + } + mem + } + + /// 2-D and 3-D groups of 64 threads. + pub(crate) const ID_SHAPES: [[u32; 3]; 2] = [[8, 8, 1], [4, 4, 4]]; + + /// Each thread of a 64-thread group of an `ID_SHAPES` shape stores its ids and its lane + /// (`mbcnt` of EXEC) as `x | y << 8 | z << 16 | lane << 24` at word `group * 64 + flat index`. + pub(crate) fn ids_program(threads: [u32; 3], wave64: bool) -> Vec { + let mut p: Vec = vec![("S_MUL_I32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 192)])]; + // v4 = flat index: (y << 3) + x, or (z << 4) + (y << 2) + x + if threads[2] == 1 { + p.push(("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 1), ("SRC1", 131), ("SRC2", V)])); + } else { + p.push(("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 1), ("SRC1", 130), ("SRC2", V)])); + p.push(("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 2), ("SRC1", 132), ("SRC2", V + 4)])); + } + // v[8:9] = (group * 64 + flat) * 4; v5 = lane + p.extend_from_slice(&[ + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 3), ("VSRC1", 4)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 4)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 126), ("SRC1", 128)]), + ]); + if wave64 { + p.push(("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 127), ("SRC1", V + 5)])); + } + p.push(("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 1), ("SRC1", 136), ("SRC2", V)])); + if threads[2] > 1 { + p.push(("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", 144), ("SRC2", V + 7)])); + } + p.extend_from_slice(&[ + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 5), ("SRC1", 152), ("SRC2", V + 7)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 125), ("OFFSET", 0)]), + ENDPGM, + ]); + p + } + + pub(crate) fn ids_cs(threads: [u32; 3]) -> crate::gpu::recomp::CsInterface { + let tid_components = if threads[2] > 1 { 3 } else { 2 }; + crate::gpu::recomp::CsInterface { threads, tid_components, ..compute_cs() } + } + + pub(crate) fn memory_image() -> Vec { + (0..256).map(|i| 1000 + i).collect() + } + + // f64 programs, as the f32 ones: `lower_dxil`'s `f64_programs_on_the_gpu` checks the HLSL + // path's registers with `check_f64` and compares the per-lane form with it + + /// f64 on x = 1 + lane / 32 + lane · 2^-52 (v[2:3]): x + 2^-53 (ties to even), x · 2^-1040 + /// (a denormal in and out), x · f64::MAX (∞ from lane 1), fma(x, x, −x · x) (the rounding + /// error: nonzero only fused), NaN into min / max, VOP3 abs / neg / omod / clamp; floor / ceil + /// / trunc / rndne / fract / frexp of q = (lane − 16) / 4 (ties, −0 at lane 15); f64 ↔ f32 / + /// i32 / u32 (a tie, overflow, saturation, NaN); rcp / rsq / sqrt. + pub(crate) const F64_ARITHMETIC: &[I] = &[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 143), ("VSRC1", 0)]), + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 255), ("VSRC1", 3), ("LITERAL", 0x3FF0_0000)]), + // v[4:5] = 2^-53, v[6:7] = 2^-1040, v[8:9] = f64::MAX, v[10:11] = NaN + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 255), ("LITERAL", 0x3CA0_0000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 128)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 132)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 193)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255), ("LITERAL", 0x7FEF_FFFF)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 129)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", 255), ("LITERAL", 0x7FF8_0000)]), + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 12), ("SRC0", V + 2), ("SRC1", V + 4)]), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 14), ("SRC0", V + 2), ("SRC1", V + 6)]), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 16), ("SRC0", V + 2), ("SRC1", V + 8)]), + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 18), ("SRC0", V + 2), ("SRC1", V + 2)]), + ("V_FMA_F64", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", V + 18), ("NEG", 4)]), + ("V_MIN_F64", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 10), ("SRC1", V + 2)]), + ("V_MAX_F64", "ENC_VOP3", &[("VDST", 24), ("SRC0", V + 2), ("SRC1", V + 10), ("NEG", 2)]), + // −x · |−4|, (x − 1) · 4, clamp(fma(x, x, −1)) + ("V_MUL_F64", "ENC_VOP3", &[("VDST", 26), ("SRC0", V + 2), ("SRC1", 247), ("ABS", 2), ("NEG", 1)]), + ("V_ADD_F64", "ENC_VOP3", &[("VDST", 28), ("SRC0", V + 2), ("SRC1", 243), ("OMOD", 2)]), + ("V_FMA_F64", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 2), ("SRC1", V + 2), ("SRC2", 243), ("CLAMP", 1)]), + // q = ldexp(lane − 16, −2) + ("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 144), ("VSRC1", 0)]), + ("V_CVT_F64_I32", "ENC_VOP1", &[("VDST", 34), ("SRC0", V + 32)]), + ("V_LDEXP_F64", "ENC_VOP3", &[("VDST", 36), ("SRC0", V + 34), ("SRC1", 194)]), + ("V_FLOOR_F64", "ENC_VOP1", &[("VDST", 38), ("SRC0", V + 36)]), + ("V_CEIL_F64", "ENC_VOP1", &[("VDST", 40), ("SRC0", V + 36)]), + ("V_TRUNC_F64", "ENC_VOP1", &[("VDST", 42), ("SRC0", V + 36)]), + ("V_RNDNE_F64", "ENC_VOP1", &[("VDST", 44), ("SRC0", V + 36)]), + ("V_FRACT_F64", "ENC_VOP1", &[("VDST", 46), ("SRC0", V + 36)]), + ("V_FREXP_MANT_F64", "ENC_VOP1", &[("VDST", 48), ("SRC0", V + 36)]), + ("V_FREXP_EXP_I32_F64", "ENC_VOP1", &[("VDST", 50), ("SRC0", V + 36)]), + // f32 of z = 1 + 2^-24 + lane · 2^-52 (a tie at lane 0) and of f64::MAX; i32 of −4x, of + // x · f64::MAX and of NaN, u32 of −4x and of NaN + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 52), ("SRC0", 255), ("VSRC1", 0), ("LITERAL", 0x1000_0000)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 53), ("SRC0", 255), ("LITERAL", 0x3FF0_0000)]), + ("V_CVT_F32_F64", "ENC_VOP1", &[("VDST", 51), ("SRC0", V + 52)]), + ("V_CVT_F32_F64", "ENC_VOP1", &[("VDST", 54), ("SRC0", V + 8)]), + ("V_CVT_I32_F64", "ENC_VOP1", &[("VDST", 55), ("SRC0", V + 26)]), + ("V_CVT_I32_F64", "ENC_VOP1", &[("VDST", 56), ("SRC0", V + 16)]), + ("V_CVT_I32_F64", "ENC_VOP1", &[("VDST", 57), ("SRC0", V + 10)]), + ("V_CVT_U32_F64", "ENC_VOP1", &[("VDST", 58), ("SRC0", V + 26)]), + ("V_CVT_U32_F64", "ENC_VOP1", &[("VDST", 59), ("SRC0", V + 10)]), + // f64 of u32::MAX − lane and of the f32 at v51 + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 193), ("VSRC1", 0)]), + ("V_CVT_F64_U32", "ENC_VOP1", &[("VDST", 60), ("SRC0", V + 1)]), + ("V_CVT_F64_F32", "ENC_VOP1", &[("VDST", 62), ("SRC0", V + 51)]), + ("V_RCP_F64", "ENC_VOP1", &[("VDST", 64), ("SRC0", V + 2)]), + ("V_RSQ_F64", "ENC_VOP1", &[("VDST", 66), ("SRC0", V + 2)]), + ("V_SQRT_F64", "ENC_VOP1", &[("VDST", 68), ("SRC0", V + 2)]), + ENDPGM, + ]; + + pub(crate) fn check_f64(_: &[u32], v: &[Vec]) { + for (l, r) in v.iter().enumerate() { + let f = |i: usize| f64::from_bits(r[i] as u64 | (r[i + 1] as u64) << 32); + let x = 1.0 + l as f64 / 32.0 + l as f64 * 2f64.powi(-52); + let q = (l as f64 - 16.0) / 4.0; + assert_eq!(f(2).to_bits(), x.to_bits(), "lane {l}"); + let p = x * x; + let e = if q == 0.0 { 0 } else { (q.abs().to_bits() >> 52) as i32 - 1022 }; + let want = [ + x + 2f64.powi(-53), + x * 2f64.powi(-1040), + x * f64::MAX, + p, + x.mul_add(x, -p), + x, + x, + -4.0 * x, + (x - 1.0) * 4.0, + x.mul_add(x, -1.0).clamp(0.0, 1.0), + (l as f64 - 16.0), + q, + q.floor(), + q.ceil(), + q.trunc(), + q.round_ties_even(), + q - q.floor(), + q / 2f64.powi(e), + ]; + for (k, w) in want.iter().enumerate() { + let i = 12 + 2 * k + if k >= 10 { 2 } else { 0 }; + assert_eq!(f(i).to_bits(), w.to_bits(), "lane {l} v[{i}:{}]: {} against {w}", i + 1, f(i)); + } + assert_eq!(r[50], e as u32, "lane {l}: frexp_exp"); + let z = 1.0 + 2f64.powi(-24) + l as f64 * 2f64.powi(-52); + assert_eq!([r[51], r[54]], [(z as f32).to_bits(), f32::INFINITY.to_bits()], "lane {l}: f32 of f64"); + assert_eq!([r[55], r[56], r[57], r[58], r[59]], [(-4.0 * x) as i32 as u32, i32::MAX as u32, 0, 0, 0], "lane {l}: i32 / u32 of f64"); + assert_eq!([f(60), f(62)], [(u32::MAX - l as u32) as f64, z as f32 as f64], "lane {l}: f64 of u32, f32"); + // the GPU's rcp / rsq / sqrt are close, not exact + for (i, w) in [(64, 1.0 / x), (66, 1.0 / x.sqrt()), (68, x.sqrt())] { + assert!((f(i) - w).abs() <= w * 1e-12, "lane {l} v[{i}:{}]: {} against {w}", i + 1, f(i)); + } + } + } + + /// A line's bytes; a `("LITERAL", k)` field is the instruction's literal dword. + pub(crate) fn encode_line((n, e, f): &I) -> Vec { + let lit = f.iter().find(|(k, _)| *k == "LITERAL").map(|&(_, v)| v as u32); + let f: Vec<(&str, u64)> = f.iter().copied().filter(|(k, _)| *k != "LITERAL").collect(); + rdna2::encode(n, e, &f, lit).unwrap() + } + + pub(crate) fn decode(lines: &[I]) -> Vec { + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); + let mut out = Vec::new(); + let mut off = 0; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + out.push(d); + } + rdna2::resolve_far_jumps(&mut out); + out + } + + /// A branch or a scalar select on whether any lane of a mask is set decides for the whole + /// wave on the console: with lanes in EXEC that lack the bit (VCC = lanes 0–15, EXEC = all), + /// each lane deciding by its own bit would differ in lanes 16–31, so the program is refused + /// (Kalmarv's five programs on #1745); where the mask is constant over EXEC it is taken. + #[test] + fn a_whole_wave_decision_on_a_mask_some_lanes_lack_is_refused() { + const CMP: I = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]); + const MOV7: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]); + const AND: I = ("S_AND_B32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 106), ("SSRC1", 126)]); + let programs: [(&str, Vec); 5] = [ + ("vccnz", vec![CMP, ("S_CBRANCH_VCCNZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("vccz", vec![CMP, ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("and + scc1", vec![CMP, AND, ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("cmp_lg + scc1", vec![CMP, ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 106), ("SSRC1", 128)]), ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]), + ("and + cselect", vec![CMP, AND, ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 133), ("SSRC1", 135)]), ENDPGM]), + ]; + for (name, p) in programs { + let err = lower_kernel(&decode(&p), false, Interp::default()).err().unwrap_or_else(|| panic!("{name}: taken")); + assert!(err.contains("any lane of a mask") || err.contains("SCC of a mask op"), "{name}: {err}"); + } + // the mask op's SCC reaching the `s_cselect` only around the loop's back edge + // (thehollowedone's program on #1745: 7 where the console gives 5 in lanes 16–31) + let around: Vec = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 130)]), + CMP, + ("S_CMP_GT_U32", "ENC_SOPC", &[("SSRC0", 129), ("SSRC1", 128)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 133), ("SSRC1", 135)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 1)]), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)]), + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 128)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 2)]), + AND, + ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0xFFF9)]), + ENDPGM, + ]; + let err = lower_kernel(&decode(&around), false, Interp::default()).err().expect("around the loop: taken"); + assert!(err.contains("SCC of a mask op") || err.contains("any lane of a mask"), "around the loop: {err}"); + // VCC = EXEC: the same in every lane in EXEC, so each lane decides as the wave does + let uniform: [I; 4] = [("S_MOV_B32", "ENC_SOP1", &[("SDST", 106), ("SSRC0", 126)]), ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 1)]), MOV7, ENDPGM]; + let (s, v) = state(32); + let (_, v) = run(&uniform, false, &s, &v); + assert!(v.iter().all(|r| r[1] == 7)); + } + + /// A cross-lane scalar op on s0 holding a number takes the number path (the check for the + /// upper dword of a mask pair at s must not compute r - 1 for s0: nobodyttk, #1269). + #[test] + fn a_wave_op_on_s0_holding_a_number() { + let lines: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 255), ("LITERAL", 0xF0F0)]), + ("S_BCNT1_I32_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 0)]), + ENDPGM, + ]; + // the CPU lowering has no number form of it (DXIL takes it from #1426): refused, no panic + let err = lower_kernel(&decode(lines), false, Interp::default()).err().expect("refused"); + assert_eq!(err, "unsupported S_BCNT1_I32_B32"); + } + + /// `s_wqm` of a mask sets every lane of a quad with a bit; `s_cselect` picks a mask or a + /// number by SCC. + #[test] + fn whole_quad_mode_and_conditional_selects() { + let lines: &[I] = &[ + // vcc = lane 5 only; s0 = wqm(vcc) = lanes 4–7 + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 133), ("VSRC1", 0)]), + ("S_WQM_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128), ("SRC1", 129), ("SRC2", 0)]), + // scc = (0 == 0): s1 = s0 (a mask), s2 = 5 + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 128)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 128)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 133), ("SSRC1", 135)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 128), ("SRC1", 129), ("SRC2", 1)]), + // scc = (0 == 1): s3 = 7, s4 = no lanes + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 128), ("SSRC1", 129)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 133), ("SSRC1", 135)]), + ("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 0), ("SSRC1", 128)]), + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 128), ("SRC1", 129), ("SRC2", 4)]), + ENDPGM, + ]; + let (s, v) = state(32); + let (s, v) = run(lines, false, &s, &v); + assert_eq!((s[2], s[3]), (5, 7)); + for (l, regs) in v.iter().enumerate() { + let quad = (4..8).contains(&l) as u32; + assert_eq!((regs[1], regs[2], regs[3]), (quad, quad, 0), "lane {l}"); + } + } + + /// `s_addc_u32` / `s_subb_u32` take SCC as the carry / borrow in and leave theirs in SCC. + #[test] + fn add_with_carry_and_subtract_with_borrow() { + let lines: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 255), ("LITERAL", 0xFFFF_FFFF)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 0), ("SSRC1", 129)]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 128), ("SSRC1", 128)]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 0), ("SSRC1", 128)]), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 128), ("SSRC1", 129)]), + ("S_SUBB_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 133), ("SSRC1", 129)]), + ("S_SUBB_U32", "ENC_SOP2", &[("SDST", 6), ("SSRC0", 133), ("SSRC1", 129)]), + ENDPGM, + ]; + let (s, v) = state(32); + let (s, _) = run(lines, false, &s, &v); + // 0xFFFFFFFF + 1 = 0 carry 1; 0 + 0 + 1 = 1; 0xFFFFFFFF + 0 + 0 = 0xFFFFFFFF + assert_eq!((s[1], s[2], s[5]), (0, 1, 0xFFFF_FFFF)); + // 0 - 1 = 0xFFFFFFFF borrow 1; 5 - 1 - 1 = 3; 5 - 1 - 0 = 4 + assert_eq!((s[3], s[4], s[6]), (0xFFFF_FFFF, 3, 4)); + } + + /// A far jump (`s_getpc_b64`, a constant added, `s_setpc_b64`, as a retail program jumps + /// over a long `then` block) is a plain jump: the lanes skip the instructions it jumps over. + #[test] + fn a_far_jump_skips_what_it_jumps_over() { + let far: &[I] = &[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 2)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 255), ("LITERAL", 32)]), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 128)]), + ("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 2)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 136)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 137)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 138)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 139)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 0)]), + ENDPGM, + ]; + let (s, v) = state(32); + let (s, v) = run(far, false, &s, &v); + // the address it computed: after `s_getpc_b64` (8) plus 32, past the four moves + assert_eq!((s[2], s[3]), (40, 0)); + for (l, regs) in v.iter().enumerate() { + assert_eq!((regs[1], regs[2]), (7, 7 + l as u32), "lane {l}"); + } + } + + /// The kernel run on the CPU: initial (sgpr, vgpr[lane]) → final ones. + fn run(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec]) -> (Vec, Vec>) { + let (s, v, _) = run_mem(lines, wave64, sgpr, vgpr, &[]); + (s, v) + } + + /// … with the flat memory too: (sgpr, vgpr[lane], memory after). + pub(crate) fn run_mem(lines: &[I], wave64: bool, sgpr: &[u32], vgpr: &[Vec], mem: &[u32]) -> (Vec, Vec>, Vec) { + let insts = decode(lines); + let (ir, _) = lower_kernel(&insts, wave64, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let lanes = if wave64 { 64 } else { 32 }; + let mut io = vec![0u32; KERNEL_SGPRS + 64 * KERNEL_VGPRS]; + io[..sgpr.len()].copy_from_slice(sgpr); + for (l, regs) in vgpr.iter().enumerate().take(lanes) { + io[KERNEL_SGPRS + l * KERNEL_VGPRS..][..regs.len()].copy_from_slice(regs); + } + let mut res = io.clone(); + let mut mem = mem.to_vec(); + ir.run(lanes, &io, &mut res, &mut mem); + let v = (0..lanes).map(|l| res[KERNEL_SGPRS + l * KERNEL_VGPRS..][..KERNEL_VGPRS].to_vec()).collect(); + (res[..KERNEL_SGPRS].to_vec(), v, mem) + } + + pub(crate) fn state(lanes: usize) -> (Vec, Vec>) { + let mut s = vec![0u32; KERNEL_SGPRS]; + s[126] = u32::MAX; + s[127] = u32::MAX; + // v0 = the lane, v1 = 0 + (s, (0..lanes).map(|l| { let mut v = vec![0u32; 8]; v[0] = l as u32; v }).collect()) + } + + #[test] + fn straight_line_scalar_and_vector_arithmetic() { + let (s, v) = state(32); + let (s, v) = run(STRAIGHT, false, &s, &v); + assert_eq!((s[0], s[1]), (5, 10)); + for (l, regs) in v.iter().enumerate() { + assert_eq!((regs[1], regs[2]), (10, 10 + l as u32), "lane {l}"); + } + } + + /// The survey goes on past a refused instruction: both are reported, and a program the + /// lowering takes gives none. + #[test] + fn the_survey_reports_every_refusal() { + let mut lines = STRAIGHT.to_vec(); + lines.insert(2, ("V_ADD_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 1)])); + lines.insert(4, ("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 1)])); + let cs = compute_cs(); + assert!(lower_compute(&decode(&lines), &cs, false, Interp::default()).is_err()); + assert_eq!(survey_compute(&decode(&lines), &cs, false, Interp::default()), ["unsupported V_ADD_F32", "unsupported V_MUL_F32"]); + assert!(survey_compute(&decode(STRAIGHT), &cs, false, Interp::default()).is_empty()); + } + + #[test] + fn a_skipped_if_runs_only_its_lanes() { + let (s, v) = state(32); + let (s, v) = run(SKIPPED_IF, false, &s, &v); + for (l, regs) in v.iter().enumerate() { + let want = if l < 16 { 7 } else { 0 }; + assert_eq!((regs[1], regs[2]), (want, want + 1), "lane {l}"); + } + assert_eq!(s[106], 0xFFFF, "vcc: the lanes below 16"); + assert_eq!((s[0], s[126]), (u32::MAX, u32::MAX), "saved and restored EXEC"); + } + + #[test] + fn lanes_leave_a_loop_one_by_one() { + let (s, v) = state(32); + let (s, v) = run(LEAVING_LOOP, false, &s, &v); + for (l, regs) in v.iter().enumerate() { + assert_eq!(regs[1], (l as u32).max(1), "lane {l}"); + } + assert_eq!(s[126], u32::MAX); + } + + #[test] + fn a_uniform_loop_with_a_scalar_counter() { + let (s, v) = state(32); + let (s, v) = run(UNIFORM_LOOP, false, &s, &v); + assert_eq!(s[1], 12); + assert!(v.iter().all(|r| r[1] == 4)); + } + + #[test] + fn lanes_outside_exec_at_launch_keep_their_registers() { + let (mut s, v) = state(32); + s[126] = 0x0000_00FF; + let (s, v) = run(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 137)]), ENDPGM], false, &s, &v); + for (l, regs) in v.iter().enumerate() { + assert_eq!(regs[1], if l < 8 { 9 } else { 0 }, "lane {l}"); + } + assert_eq!(s[126], 0xFF); + } + + /// A VS / PS run on the CPU in one wave of `lanes` lanes (a wave64 one in 32 lanes: in + /// 32-lane waves): `launch` its launch EXEC, `vgpr[lane]` the registers it starts with. The + /// memory after. + fn run_graphics(lines: &[I], pixel: bool, wave64: bool, lanes: usize, launch: u64, vgpr: &[Vec], mem: &[u32]) -> Vec { + let ir = lower_graphics(&decode(lines), pixel, wave64, wave64 && lanes == 32, Interp::default()).unwrap_or_else(|e| panic!("{e}")); + let mut io = vec![0u32; KERNEL_SGPRS + 64 * KERNEL_VGPRS]; + io[EXEC as usize] = launch as u32; + io[EXEC as usize + 1] = (launch >> 32) as u32; + for (l, regs) in vgpr.iter().enumerate().take(lanes) { + io[KERNEL_SGPRS + l * KERNEL_VGPRS..][..regs.len()].copy_from_slice(regs); + } + let mut res = vec![0u32; KERNEL_SGPRS]; + let mut mem = mem.to_vec(); + ir.run(lanes, &io, &mut res, &mut mem); + mem + } + + /// v7 = 9, stored at v[8:9] (the lane's address: 4 × lane) + const SET_V7: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 137)]); + const STORE_V7: I = ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 125), ("OFFSET", 0)]); + + fn store_rows() -> Vec> { + (0..64).map(|l| { let mut v = vec![0u32; 10]; v[0] = l; v[1] = 15; v[8] = 4 * l; v }).collect() + } + + #[test] + fn a_ps_helper_lane_runs_the_program_but_does_not_store() { + // even lanes covered, odd lanes helper lanes + let launch = 0x5555_5555u64; + let want: Vec = memory_image().iter().enumerate().map(|(l, &m)| if l < 32 && l % 2 == 0 { 9 } else { m }).collect(); + let exact = run_graphics(&[SET_V7, STORE_V7, ENDPGM], true, false, 32, launch, &store_rows(), &memory_image()); + assert_eq!(exact, want, "before EXEC is written, the store keeps its guard"); + // whole-quad mode, then back to the launch EXEC before the store (as compiled PSs do) + let wqm32: Vec = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), + SET_V7, + ("S_AND_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + STORE_V7, + ENDPGM, + ]; + assert_eq!(run_graphics(&wqm32, true, false, 32, launch, &store_rows(), &memory_image()), want); + // the same in wave64, run in 32-lane waves + let wqm64: Vec = vec![ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), + SET_V7, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + STORE_V7, + ENDPGM, + ]; + assert_eq!(run_graphics(&wqm64, true, true, 32, launch, &store_rows(), &memory_image()), want); + // a VS: each D3D vertex invocation is one lane, so every lane that runs is in EXEC at + // launch and stores, whatever bit its start gives it + let all: Vec = memory_image().iter().enumerate().map(|(l, &m)| if l < 32 { 9 } else { m }).collect(); + assert_eq!(run_graphics(&[SET_V7, STORE_V7, ENDPGM], false, false, 32, launch, &store_rows(), &memory_image()), all); + // … so its store keeps no guard (no block of its own), where a PS's does + let blocks = |pixel: bool| lower_graphics(&decode(&[SET_V7, STORE_V7, ENDPGM]), pixel, false, false, Interp::default()).unwrap().blocks.len(); + assert_eq!(blocks(false) + 2, blocks(true), "a guarded store adds two blocks: the PS's only"); + } + + #[test] + fn whole_quad_instructions_need_every_lane_of_the_quad() { + // v_cmp (lanes above 15); s_and_saveexec s0; s_cbranch_execz L; s_wqm exec, s0; v_mov; + // L: exec |= s0 – the s_wqm of the launch EXEC, in a block only some lanes reach + let p: Vec = vec![ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)]), + ("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + SET_V7, + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + let e = lower_graphics(&decode(&p), true, false, false, Interp::default()).err(); + assert_eq!(e.as_deref(), Some("S_WQM_B32: needs whole quads, in a block not every lane reaches")); + // s_wqm of another mask: the lanes of the quad are not read + let other: Vec = vec![("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]), ("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 106)]), SET_V7, ENDPGM]; + let e = lower_graphics(&decode(&other), true, false, false, Interp::default()).err(); + assert_eq!(e.as_deref(), Some("S_WQM_B32 of a mask other than the launch EXEC")); + for (name, quad) in [ + ("IMAGE_SAMPLE", true), + ("IMAGE_SAMPLE_B_CL", true), + ("IMAGE_GATHER4_C", true), + ("IMAGE_GET_LOD", true), + ("S_WQM_B64", true), + ("IMAGE_SAMPLE_L", false), + ("IMAGE_SAMPLE_C_LZ_O", false), + ("IMAGE_SAMPLE_D_G16", false), + ("IMAGE_SAMPLE_CD", false), + ("IMAGE_GATHER4_LZ", false), + ("IMAGE_LOAD", false), + ] { + assert_eq!(whole_quad(name), quad, "{name}"); + } + } + + #[test] + fn a_wave64_vs_in_32_lane_waves_that_reads_upper_lanes_is_refused() { + // whole-wave code writes lanes 32–63 (v6 = 5), then v_readlane of lane 32 + let p: Vec = vec![ + ("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 193)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 133)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 6), ("SRC1", 128 + 32)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)]), + ENDPGM, + ]; + let insts = decode(&p); + assert_eq!(super::super::upper_lanes::analyze(&insts).reads.values().copied().collect::>(), vec![super::super::upper_lanes::Read::Const(5)]); + let e = lower_graphics(&insts, false, true, true, Interp::default()).err(); + assert_eq!(e.as_deref(), Some("wave64 VS / PS in 32-lane waves: a read of lanes 32–63")); + assert!(lower_graphics(&insts, false, true, false, Interp::default()).is_ok(), "in 64-lane waves the lanes are there"); + } + + #[test] + fn wave64_masks_span_both_words() { + // v_cmp_gt_u32 vcc, 40, v0 over 64 lanes: lanes 0–39 + let (s, v) = state(64); + let (s, _) = run(&[("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), ENDPGM], true, &s, &v); + assert_eq!((s[106], s[107]), (u32::MAX, 0xFF)); + } + + /// The lowering run on the CPU and the HLSL path run on the GPU give the same registers. + #[test] + fn the_lowering_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + for (name, lines) in [("straight", STRAIGHT), ("skipped if", SKIPPED_IF), ("leaving loop", LEAVING_LOOP), ("uniform loop", UNIFORM_LOOP), ("memory", MEMORY)] { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap(); + let (cs, cv, cmem) = run_mem(lines, false, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let insts = decode(lines); + // masks some lanes kept their own older bits of (`lower_kernel`'s `stale`): only the + // kernel ABI's final store sees them + let (_, stale) = lower_kernel(&insts, false, Interp::default()).unwrap(); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(cs[r], gpu.sgpr[r], "{name}: s{r}"); + } + for l in 0..32 { + for &r in &vregs { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "{name}: lane {l} v{r}"); + } + } + } + } + + // wave64 versions of the programs above: 64-bit EXEC / VCC / saved masks, and thresholds + // past lane 32 so that both words of every mask matter + /// v_cmp_gt_u32 vcc, 40, v0; s_and_saveexec_b64 s[0:1], vcc; s_cbranch_execz L; v_mov v1, 7; + /// L: s_or_b64 exec, exec, s[0:1]; v_add v2, v1, 1 + const SKIPPED_IF_W64: &[I] = &[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 1)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 129), ("VSRC1", 1)]), + ENDPGM, + ]; + /// s_mov_b64 s[0:1], exec; L: v_add v1, v1, 1; v_cmp_ge_u32 vcc, v1, v0; + /// exec &= ~vcc (b64); s_cbranch_execnz L; exec |= s[0:1] → v1 = max(1, lane), 64 lanes + const LEAVING_LOOP_W64: &[I] = &[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFC)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + /// `MEMORY` over 64 lanes: lanes below 40 take the guarded store + const MEMORY_W64: &[I] = &[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 1), ("SADDR", 125), ("OFFSET", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 2), ("SADDR", 125), ("OFFSET", 0x100)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 6)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 125), ("OFFSET", 0x200)]), + ENDPGM, + ]; + + #[test] + fn a_wave64_mask_left_behind_is_reported_in_both_halves() { + // VCC from the loop's last v_cmp: lanes that left earlier kept their own bits in both words + let (_, stale) = lower_kernel(&decode(LEAVING_LOOP_W64), true, Interp::default()).unwrap(); + assert_eq!(stale, vec![106, 107]); + } + + /// The wave64 lowering run on the CPU and the HLSL path's native wave64 form run on a GPU + /// with 64-lane waves give the same registers and memory. + #[test] + fn the_wave64_lowering_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + for (name, lines) in [ + ("straight", STRAIGHT), + ("skipped if", SKIPPED_IF_W64), + ("leaving loop", LEAVING_LOOP_W64), + ("uniform loop", UNIFORM_LOOP), + ("memory", MEMORY_W64), + ] { + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let (s, v) = state(64); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64: true, split_wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap(); + let (cs, cv, cmem) = run_mem(lines, true, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let insts = decode(lines); + let (_, stale) = lower_kernel(&insts, true, Interp::default()).unwrap(); + let mut sregs: Vec = vec![106, 107, 126, 127]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(cs[r], gpu.sgpr[r], "{name}: s{r}"); + } + for l in 0..64 { + for &r in &vregs { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "{name}: lane {l} v{r}"); + } + } + } + } + + /// The split form (two hardware wave32s per console wave64, `lower_dxil::kernel_split`) run + /// on the GPU gives the registers and memory of the wave64 lowering run on the CPU: masks + /// across both halves, lane reads through the exchange (readfirstlane, readlane, the counts + /// of EXEC as numbers, mbcnt), and the reads that stay in their half (DPP, permlanex16, + /// ds_swizzle). A whole-wave read where lanes leave one by one is refused. + #[test] + fn the_split_form_agrees_with_the_wave64_lowering_on_the_gpu() { + use super::super::{lower_dxil, runner}; + if !gpu_waves() { + runner::skip_test("no GPU with 32-lane waves"); + return; + } + let reads = lane_reads(true); + // reads across the halves both ways: readlane of lane 41 (the lower half needs the + // upper's), readfirstlane with EXEC from lane 40 up (the first lane is in the upper + // half), and a 64-bit compare mask counted as a number + const ACROSS: &[I] = &[ + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", 169)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", 131)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 168), ("VSRC1", 0)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 11), ("SSRC0", 106)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 168)]), + ("V_CMPX_LE_U32", "ENC_VOPC", &[("SRC0", V + 2), ("VSRC1", 0)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 1)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 13), ("SSRC0", 126)]), + ENDPGM, + ]; + for (name, lines) in [ + ("across the halves", ACROSS), + ("straight", STRAIGHT), + ("skipped if", SKIPPED_IF_W64), + ("leaving loop", LEAVING_LOOP_W64), + ("uniform loop", UNIFORM_LOOP), + ("memory", MEMORY_W64), + ("lane reads", &reads[..]), + ] { + let insts = decode(lines); + let (dxil, stale) = lower_dxil::kernel_split(&insts).unwrap_or_else(|e| panic!("{name}: {e}")); + let (s, v) = state(64); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap_or_else(|e| panic!("{name}: {e}")); + let (cs, cv, cmem) = run_mem(lines, true, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let mut sregs: Vec = vec![106, 107, 126, 127]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(gpu.sgpr[r], cs[r], "{name}: s{r}"); + } + for l in 0..64 { + for &r in &vregs { + assert_eq!(gpu.vgpr[l][r], cv[l][r], "{name}: lane {l} v{r}"); + } + } + } + // compute mode: a 64-thread group as two hardware wave32s, threads numbered by arrival + let cs = compute_cs(); + let dxil = lower_dxil::compute_split(&decode(COMPUTE), &cs).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&gpu[..cpu.len()], &cpu[..], "compute"); + // two console waves per group: their halves pair up through #1426's arrival counters + // and meet in its spin loop. Each thread stores its lane (`mbcnt` of EXEC: the mask + // words exchanged), its thread id and its console wave's first thread + // (`readfirstlane`: a lane of the other half for the upper one) + const TWO_WAVES: &[I] = &[ + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 135)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 3), ("VSRC1", 0)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 4)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 126), ("SRC1", 128)]), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 127), ("SRC1", V + 5)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 5), ("SRC1", 136), ("SRC2", V)]), + ("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 7), ("SRC0", 10), ("SRC1", 144), ("SRC2", V + 7)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 7), ("SADDR", 125), ("OFFSET", 0)]), + ENDPGM, + ]; + let big = crate::gpu::recomp::CsInterface { threads: [128, 1, 1], ..compute_cs() }; + let dxil = lower_dxil::compute_split(&decode(TWO_WAVES), &big).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [2, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute_waves(TWO_WAVES, &big, true, 2, &[100, 0], &mem); + assert_eq!(&gpu[..256], &cpu[..256], "two console waves per group"); + assert!(cpu[..256].iter().any(|&w| w >> 16 == 64), "the CPU run's second wave starts at thread 64"); + // the waterfall's readfirstlane is in a block lanes leave one by one: native wave64 + // takes it, the split form cannot meet the other half there + let insts = decode(&waterfall(true)); + assert!(lower_kernel(&insts, true, Interp::default()).is_ok()); + let e = lower_dxil::kernel_split(&insts).unwrap_err(); + assert!(e.contains("split form"), "{e}"); + } + + #[test] + fn scalar_and_vector_memory_with_a_guarded_store() { + let (s, v) = state(32); + let (s, v, mem) = run_mem(MEMORY, false, &s, &v, &memory_image()); + assert_eq!((s[4], s[5]), (1002, 1003)); + for l in 0..32 { + assert_eq!(v[l][2], 2002 + l as u32, "lane {l}"); + assert_eq!(mem[64 + l], if l < 16 { 2002 + l as u32 } else { 1064 + l as u32 }, "guarded store, lane {l}"); + assert_eq!(mem[128 + l], l as u32, "store, lane {l}"); + } + // the store under the narrowed EXEC is the guarded one + let insts = decode(MEMORY); + let sum = lane_masks::analyze(&insts, false).unwrap(); + assert_eq!(sum.guarded.iter().filter(|&&pc| insts.iter().any(|d| d.pc == pc && is_store(d))).count(), 1); + } + + #[test] + fn a_compute_program_takes_its_group_and_thread_ids() { + let mem = run_compute(COMPUTE, &compute_cs(), 3, &[100, 0], &vec![0u32; 256]); + for g in 0..3u32 { + for t in 0..64u32 { + assert_eq!(mem[(64 * g + t) as usize], 3 * t + 100 + g, "group {g} thread {t}"); + } + } + } + + #[test] + fn a_2d_or_3d_group_numbers_its_threads_as_the_console_does() { + // a wave takes consecutive threads, lane l the l-th: x fastest, then y, then z + for threads in ID_SHAPES { + for wave64 in [false, true] { + let lanes = if wave64 { 64 } else { 32 }; + let mem = run_compute_waves(&ids_program(threads, wave64), &ids_cs(threads), wave64, 2, &[100, 0], &[0u32; 256]); + for g in 0..2u32 { + for t in 0..64u32 { + let (x, y, z) = (t % threads[0], t / threads[0] % threads[1], t / (threads[0] * threads[1])); + let want = x | y << 8 | z << 16 | (t % lanes) << 24; + assert_eq!(mem[(64 * g + t) as usize], want, "{threads:?} wave64 {wave64}: group {g} thread {t}"); + } + } + } + } + } + + /// The same through the HLSL path on the GPU, which numbers the threads by arrival. + #[test] + fn a_2d_or_3d_group_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Mode, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + for wave64 in [false, true] { + if wave64 && runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + for threads in ID_SHAPES { + let lines = ids_program(threads, wave64); + let cs = ids_cs(threads); + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let t = translate(&bytes, &Options { mode: Mode::Compute(cs.clone()), wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [2, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute_waves(&lines, &cs, wave64, 2, &[100, 0], &mem); + assert_eq!(&gpu[..128], &cpu[..128], "{threads:?} wave64 {wave64}"); + } + } + } + + /// The compute program through the HLSL path on the GPU and through the lowering on the CPU. + #[test] + fn a_compute_program_agrees_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Mode, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let cs = compute_cs(); + let t = translate(&bytes, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&gpu[..cpu.len()], &cpu[..]); + } + + #[test] + fn a_mask_left_behind_by_lanes_that_skipped_its_write() { + // VCC written inside the loop that lanes leave one by one: the console's last write left + // the earlier leavers' bits 0, each lane here kept its own. Stored at the end: reported. + let insts = decode(LEAVING_LOOP); + let (_, stale) = lower_kernel(&insts, false, Interp::default()).unwrap(); + assert_eq!(stale, vec![106]); + // read after the loop (v_cndmask on VCC): refused + let mut lines = LEAVING_LOOP.to_vec(); + lines.insert(6, ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 128), ("VSRC1", 0)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + // a mask written before the lanes split is read after they meet: fine + let insts = decode(SKIPPED_IF); + assert_eq!(lower_kernel(&insts, false, Interp::default()).unwrap().1, Vec::::new()); + // an older mask copied in the arm some lanes skip (s_mov s4, s0), read after they meet: + // the copy is the arm's write, not the older value's (found by MiguelMachado-dev) + let mut lines = SKIPPED_IF.to_vec(); + lines[2] = ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)]); + lines.insert(3, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 0)])); + lines.insert(6, ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 128), ("SRC1", 129), ("SRC2", 4)])); + // (s4 holds a mask before the lanes split, so the join is mask against mask) + lines.insert(1, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + } + + #[test] + fn a_scalar_counted_in_a_loop_lanes_leave_is_not_each_lanes_own() { + // s_add_u32 s1, s1, 1 in the loop lanes leave one by one: the console counts the wave's + // passes, each lane here only its own (a waterfall loop's key is the same case) + // s_mov s0, exec; s1 = 0; L: v_add v1, v1, 1; s1 += 1; v_cmp_ge vcc, v1, v0; + // exec &= ~vcc; s_cbranch_execnz L; exec |= s0 + let mut lines: Vec = vec![ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)]), + ("V_CMP_GE_U32", "ENC_VOPC", &[("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + let (_, stale) = lower_kernel(&decode(&lines), false, Interp::default()).unwrap(); + assert!(stale.contains(&1), "{stale:?}"); + // read after the loop: refused + lines.insert(8, ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 1)])); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes were elsewhere"), "{err}"); + } + + #[test] + fn vop3_operand_selects_are_refused() { + let op_sel: &[I] = &[("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V), ("OP_SEL", 1)]), ENDPGM]; + let err = lower_kernel(&decode(op_sel), false, Interp::default()).err().expect("refused"); + assert!(err.contains("modifiers"), "{err}"); + let plain: &[I] = &[("V_ADD_NC_U32", "ENC_VOP3", &[("VDST", 1), ("SRC0", V), ("SRC1", V)]), ENDPGM]; + assert!(lower_kernel(&decode(plain), false, Interp::default()).is_ok()); + } + + #[test] + fn a_mask_read_as_a_number_is_refused() { + // s_bcnt1-like use: s_add_u32 s2, vcc_lo, 0 after a v_cmp + let insts = decode(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 106), ("SSRC1", 128)]), + ENDPGM, + ]); + assert!(lower_kernel(&insts, false, Interp::default()).is_err()); + } + + /// Cross-lane reads with EXEC narrowed to the lanes above 4 (`v_cmpx`): readfirstlane, + /// the counts of EXEC as a number, mbcnt, readlane / writelane, DPP16 / DPP8 sources, + /// permlanex16 and ds_swizzle. + fn lane_reads(wave64: bool) -> Vec { + let mut p: Vec = vec![ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 132)]), + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", V + 2), ("VSRC1", 0)]), + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V)]), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 126), ("SRC1", 128)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", 131)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 4), ("SRC1", 137)]), + ("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 2), ("SRC1", 130)]), + // row_shr:1 with bound_ctrl; quad_perm [3,2,1,0] on rows 1 and 3; DPP8 reversed, added + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 6), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF), ("BOUND_CTRL", 1)]), + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 7), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x1B), ("ROW_MASK", 0xA), ("BANK_MASK", 0xF)]), + ("V_ADD_NC_U32", "VOP2_VOP_DPP8", &[("VDST", 8), ("SRC0", 0xE9), ("VSRC0", 4), ("VSRC1", 0), ("LANE_SEL_0", 7), ("LANE_SEL_1", 6), ("LANE_SEL_2", 5), ("LANE_SEL_3", 4), ("LANE_SEL_4", 3), ("LANE_SEL_5", 2), ("LANE_SEL_6", 1), ("LANE_SEL_7", 0)]), + ("S_MOVK_I32", "ENC_SOPK", &[("SDST", 5), ("SIMM16", 0x3210)]), + ("S_MOVK_I32", "ENC_SOPK", &[("SDST", 6), ("SIMM16", 0x7F54)]), + ("V_PERMLANEX16_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 4), ("SRC1", 5), ("SRC2", 6)]), + // xor 1 (and 0x1F, or 0, xor 1); quad mode [3,2,1,0] + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 10), ("ADDR", 4), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 11), ("ADDR", 4), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)]), + ]; + if wave64 { + p.extend_from_slice(&[ + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 127), ("SRC1", V + 3)]), + ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 126)]), + ("S_FF1_I32_B64", "ENC_SOP1", &[("SDST", 7), ("SSRC0", 126)]), + ]); + } else { + p.extend_from_slice(&[ + ("S_BCNT1_I32_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 126)]), + ("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 7), ("SSRC0", 126)]), + ]); + } + p.push(ENDPGM); + p + } + + /// A waterfall loop: each pass takes the first lane's key (readfirstlane), the lanes with + /// that key do the work and leave; the readfirstlane is in a block lanes leave one by one. + fn waterfall(wave64: bool) -> Vec { + let w: [I; 4] = if wave64 { + [ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("S_XOR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + ] + } else { + [ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 126)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("S_XOR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 0)]), + ] + }; + vec![ + ("V_AND_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 0)]), + w[0], + ("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 2)]), + ("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", 2), ("VSRC1", 2)]), + w[1], + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 2), ("VSRC1", 3)]), + w[2], + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFA)]), + w[3], + ENDPGM, + ] + } + + /// The lowering (on the CPU) and the HLSL path (on the GPU) give the same registers. + fn agrees_with_hlsl(name: &str, lines: &[I], wave64: bool, skip: &[usize]) { + use super::super::{dxc, runner, translate, Options}; + let lanes = if wave64 { 64 } else { 32 }; + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect(); + let (s, v) = state(lanes); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let gpu = runner::run(&dxil, &st, &[]).unwrap(); + let (cs, cv) = run(lines, wave64, &s, &v); + let insts = decode(lines); + let (_, stale) = lower_kernel(&insts, wave64, Interp::default()).unwrap(); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + if wave64 { + sregs.extend([107, 127]); + } + // (a stale wave64 mask is reported by its first register; the pair's second is stale too) + let stale_at = |r: usize| stale.contains(&(r as u8)) || (wave64 && r > 0 && r % 2 == 1 && stale.contains(&(r as u8 - 1))); + for &r in sregs.iter().filter(|&&r| !stale_at(r) && !skip.contains(&r)) { + assert_eq!(cs[r], gpu.sgpr[r], "{name}: s{r}"); + } + for l in 0..lanes { + for &r in &vregs { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "{name}: lane {l} v{r}"); + } + } + } + + #[test] + fn cross_lane_reads_on_the_cpu() { + for wave64 in [false, true] { + let lanes = if wave64 { 64 } else { 32 }; + let (s, v) = state(lanes); + let (s, v) = run(&lane_reads(wave64), wave64, &s, &v); + assert_eq!(s[2], 5, "readfirstlane: the first lane in EXEC"); + assert_eq!(s[3], lanes as u32 - 5, "s_bcnt1 of EXEC"); + assert_eq!(s[4], 27, "readlane 9 of 3 * lane"); + assert_eq!(s[7], 5, "s_ff1 of EXEC"); + for (l, r) in v.iter().enumerate() { + let (l32, active) = (l as u32, l > 4); + assert_eq!(r[3], if active { l32 - 5 } else { 0 }, "lane {l}: mbcnt"); + assert_eq!(r[5], if l == 2 { 5 } else { 0 }, "lane {l}: writelane, whatever EXEC holds"); + // row_shr:1, bound_ctrl: 0 at a row's first lane or from a lane outside EXEC + let want = if !active || l % 16 == 0 || l - 1 <= 4 { 0 } else { 3 * (l32 - 1) }; + assert_eq!(r[6], want, "lane {l}: DPP16 row_shr"); + let rev = (l32 & !7) | (7 - (l32 & 7)); + let want = if active { l32 + if rev > 4 { 3 * rev } else { 0 } } else { 0 }; + assert_eq!(r[8], want, "lane {l}: DPP8"); + let x = l32 ^ 1; + assert_eq!(r[10], if active && x > 4 { 3 * x } else { 0 }, "lane {l}: ds_swizzle xor 1"); + } + } + } + + #[test] + fn a_waterfall_loop_reads_the_first_lane_of_each_pass() { + for wave64 in [false, true] { + let lanes = if wave64 { 64 } else { 32 }; + let (s, v) = state(lanes); + let (_, v) = run(&waterfall(wave64), wave64, &s, &v); + for (l, r) in v.iter().enumerate() { + assert_eq!(r[3], l as u32 & 3, "lane {l}"); + } + } + // a lane of any lane, where some lanes have left: refused + let mut lines = waterfall(false); + lines.insert(3, ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", V + 2), ("SRC1", 129)])); + lines[8] = ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFF8)]); + let err = lower_kernel(&decode(&lines), false, Interp::default()).err().expect("refused"); + assert!(err.contains("some lanes are elsewhere"), "{err}"); + } + + #[test] + fn cross_lane_reads_agree_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + agrees_with_hlsl("lane reads, wave32", &lane_reads(false), false, &[]); + // s2 and the saved EXEC s4 after the loop: the last pass's on the console; each lane's own + // last pass's in the lowering (written where lanes leave one by one; not refused yet) + agrees_with_hlsl("waterfall, wave32", &waterfall(false), false, &[2, 4]); + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + agrees_with_hlsl("lane reads, wave64", &lane_reads(true), true, &[]); + agrees_with_hlsl("waterfall, wave64", &waterfall(true), true, &[2, 4, 5]); + } + + /// Guarded straight-line run under narrowed EXEC (no skip branch): VALU ops, a guarded load, + /// `s_waitcnt`, and two guarded stores all coalesce into one per-lane branch with 0 selects. + pub(crate) fn coalesced_run(wave64: bool) -> Vec { + let (cmp, save, restore): (&'static [(&'static str, u64)], &str, &str) = if wave64 { + (&[("SRC0", 168), ("VSRC1", 0)], "S_AND_SAVEEXEC_B64", "S_OR_B64") + } else { + (&[("SRC0", 144), ("VSRC1", 0)], "S_AND_SAVEEXEC_B32", "S_OR_B32") + }; + vec![ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)]), + ("V_CMP_GT_U32", "ENC_VOPC", cmp), + (save, "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 138), ("VSRC1", 0)]), + ("V_MUL_LO_U32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 2), ("SRC1", 131)]), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 3), ("VSRC1", 0)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 8), ("SADDR", 125), ("OFFSET", 0)]), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 5), ("VSRC1", 2)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 4), ("SADDR", 125), ("OFFSET", 0x100)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 6), ("SADDR", 125), ("OFFSET", 0x200)]), + (restore, "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 6)]), + ENDPGM, + ] + } + + /// Guarded runs separated by a scalar write, a `v_cmp`, and a cross-lane `v_readlane`, plus + /// `v_cndmask` and a twice-written VGPR inside coalesced runs. + pub(crate) const COALESCED_BREAKS: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 133)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 135), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 0)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 131)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 2), ("VSRC1", 1)]), + ("V_XOR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 3), ("VSRC1", 2)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 136), ("VSRC1", 0)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", V + 3), ("VSRC1", 4)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 129), ("VSRC1", 5)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 1), ("SRC1", 131)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 3), ("VSRC1", 6)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 130), ("VSRC1", 7)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + + /// Two coalesced runs separated by a scalar write inside an already-`partial` block (arm of a + /// skipped `if`), reading SGPR `s2` and `vcc` written earlier in that same console block. + pub(crate) const COALESCED_IN_PARTIAL: &[I] = &[ + ("S_AND_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 126), ("SSRC1", 128)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 152), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 10)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 139)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 140), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 2), ("VSRC1", 0)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 1)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 2), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 3)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 2), ("VSRC1", 4)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 129), ("VSRC1", 5)]), + ENDPGM, + ]; + + /// A 4-iteration uniform loop whose body narrows EXEC (no skip branch) around a coalesced run. + pub(crate) const COALESCED_IN_LOOP: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 128)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 1), ("VSRC1", 2)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)]), + ("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 2), ("SSRC1", 132)]), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)]), + ENDPGM, + ]; + + /// Guarded run of f32 instructions lowered through `Ir::foreign` (`Lw::inst_guarded`). + pub(crate) const COALESCED_F32_RUN: &[I] = &[ + ("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 242), ("VSRC1", 1)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 244), ("VSRC1", 2)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 4), ("SRC0", V + 3), ("SRC1", 240), ("SRC2", 242)]), + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 242), ("VSRC1", 4)]), + ENDPGM, + ]; + + #[test] + fn guarded_run_coalesces_into_one_branch_with_no_selects() { + for (wave64, lanes, cut) in [(false, 32usize, 16usize), (true, 64usize, 40usize)] { + let lines = coalesced_run(wave64); + let insts = decode(&lines); + let sum = lane_masks::analyze(&insts, wave64).unwrap(); + assert_eq!(sum.guarded.len(), 7, "wave64={wave64}"); + let (ir, stale) = lower_kernel(&insts, wave64, Interp::default()).unwrap(); + assert!(stale.is_empty(), "{stale:?}"); + // wave64 has 1 prologue select to pick EXEC's lo/hi dword; 0 per-write selects in either mode + assert_eq!(ir.selects(), usize::from(wave64), "wave64={wave64}: coalesced run removes all per-write selects"); + assert_eq!(ir.br_ifs(), 3, "wave64={wave64}: entry + 1 coalesced run + exit"); + + let (s, v) = state(lanes); + let (s, v, mem) = run_mem(&lines, wave64, &s, &v, &memory_image()); + assert_eq!(s[126], u32::MAX); + if wave64 { + assert_eq!(s[127], u32::MAX); + } + for l in 0..lanes { + let l32 = l as u32; + if l < cut { + let (v2, v5) = (l32 + 10, 1000 + l32); + let (v3, v6) = (v2 * 3, v5 + v2); + let v4 = v3 ^ l32; + assert_eq!((v[l][2], v[l][3], v[l][4], v[l][5], v[l][6], v[l][7]), (v2, v3, v4, v5, v6, v4 + v6), "wave64={wave64} lane {l}"); + assert_eq!((mem[64 + l], mem[128 + l]), (v4, v6), "wave64={wave64} lane {l} mem"); + } else { + assert_eq!((v[l][2], v[l][3], v[l][4], v[l][5], v[l][6], v[l][7]), (0, 0, 0, 0, 0, 0), "wave64={wave64} lane {l}"); + assert_eq!((mem[64 + l], mem[128 + l]), (1064 + l32, 1128 + l32), "wave64={wave64} lane {l} mem"); + } + } + } + + // a single guarded VALU or load keeps its select rather than adding a branch + for single_op in [ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 135)][..]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 125), ("OFFSET", 0)][..]), + ] { + let single = decode(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + single_op, + ("S_OR_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]); + let (ir, _) = lower_kernel(&single, false, Interp::default()).unwrap(); + assert_eq!((ir.selects(), ir.br_ifs()), (1, 2), "{}", single_op.0); + } + } + + #[test] + fn guard_coalescing_breaks_at_scalar_compare_and_cross_lane_ops() { + let (ir, stale) = lower_kernel(&decode(COALESCED_BREAKS), false, Interp::default()).unwrap(); + assert!(stale.is_empty(), "{stale:?}"); + assert_eq!((ir.selects(), ir.br_ifs()), (1, 6)); // only v_cndmask's select; 4 runs + entry/exit + let (s, v) = state(32); + let (s, v) = run(COALESCED_BREAKS, false, &s, &v); + assert_eq!((s[2], s[3], s[106], s[126]), (8, 10, 0xFF, u32::MAX)); + for l in 0..32usize { + let l32 = l as u32; + let want = if l < 16 { + let (v1, v3) = (l32 + 7, l32 + 15); + let v4 = v3 ^ (v1 + l32); + (v1, v4, 10 + (if l < 8 { v4 } else { v3 }) + 3) + } else { + (0, 0, 0) + }; + assert_eq!((v[l][1], v[l][4], v[l][7]), want, "lane {l}"); + } + + // two coalesced runs inside a partial block (with a scalar write in between) stay non-stale + let (s, v) = state(32); + let (_, v) = run(COALESCED_IN_PARTIAL, false, &s, &v); + for l in 0..32usize { + let l32 = l as u32; + let v4 = if l < 12 { l32 + 24 } else { 0 }; + let v5 = if l < 24 { 12 + v4 } else { 0 }; + assert_eq!((v[l][4], v[l][5], v[l][6]), (v4, v5, v5 + 1), "partial lane {l}"); + } + + // coalesced run inside a loop: 0 selects, SSA phis carry loop values cleanly + let (ir, _) = lower_kernel(&decode(COALESCED_IN_LOOP), false, Interp::default()).unwrap(); + assert_eq!(ir.selects(), 0); + let (s, v) = state(32); + let (s, v) = run(COALESCED_IN_LOOP, false, &s, &v); + assert_eq!((s[2], s[126]), (4, u32::MAX)); + for l in 0..32 { + assert_eq!((v[l][1], v[l][2]), if l < 16 { (4, 10) } else { (0, 0) }, "loop lane {l}"); + } + + // guarded VALU carry-out (VOP3_SDST_ENC) and cross-lane ds_swizzle split runs + let cs = decode(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 144), ("VSRC1", 0)]), + ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 0)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 1)]), + ("V_ADD_CO_U32", "VOP3_SDST_ENC", &[("VDST", 3), ("SDST", 106), ("SRC0", V + 1), ("SRC1", V + 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 129), ("VSRC1", 3)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 130), ("VSRC1", 4)]), + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 5), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 129), ("VSRC1", 6)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 8), ("SRC0", 130), ("VSRC1", 7)]), + ENDPGM, + ]); + let sum = lane_masks::analyze(&cs, false).unwrap(); + let guarded: HashSet = sum.guarded.iter().copied().collect(); + assert_eq!(coalesced_runs(&cs, &sum.blocks[0].insts, &guarded), vec![2..4, 5..7, 8..10]); + } + + #[test] + fn coalesced_guarded_runs_agree_with_the_hlsl_path_on_the_gpu() { + use super::super::{dxc, runner, translate, Options}; + if !gpu_waves() || dxc::location().is_err() { + runner::skip_test(if !gpu_waves() { "no GPU with 32-lane waves" } else { "no DXC" }); + return; + } + agrees_with_hlsl("coalesced breaks, wave32", COALESCED_BREAKS, false, &[]); + agrees_with_hlsl("coalesced in partial, wave32", COALESCED_IN_PARTIAL, false, &[]); + agrees_with_hlsl("coalesced in loop, wave32", COALESCED_IN_LOOP, false, &[]); + let check_mem = |wave64: bool| { + let (lines, lanes) = (coalesced_run(wave64), if wave64 { 64 } else { 32 }); + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); + let (s, v) = state(lanes); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let t = translate(&bytes, &Options { wave64, split_wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap(); + let (cs, cv, cmem) = run_mem(&lines, wave64, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "wave64={wave64}: memory"); + for l in 0..lanes { + for r in 0..8 { + assert_eq!(cv[l][r], gpu.vgpr[l][r], "wave64={wave64}: lane {l} v{r}"); + } + } + assert_eq!(cs[126], gpu.sgpr[126]); + if wave64 { + assert_eq!(cs[127], gpu.sgpr[127]); + } + }; + check_mem(false); + if runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + check_mem(true); + } +} diff --git a/crates/xcl/src/gpu/recomp/lower/wave.rs b/crates/xcl/src/gpu/recomp/lower/wave.rs new file mode 100644 index 0000000000..7d3ceceb77 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lower/wave.rs @@ -0,0 +1,472 @@ +//! Cross-lane operations of the lowering: `v_readlane`, `v_readfirstlane`, `v_writelane`, +//! DPP16 / DPP8 sources, `v_permlane(x)16`, `ds_swizzle_b32`, `v_mbcnt`, and the counts of a +//! mask as a number (`s_bcnt1`, `s_ff1`). +//! +//! A lane reads another through `Ir::read_lane` (`WaveReadLaneAt`), which needs that lane to +//! be running the same instruction. Here a lane is where the console has it except across a +//! lane branch: the lanes that went the other way are elsewhere. So: +//! - a read of a lane in EXEC is always fine: that lane is here (readfirstlane, and DPP, +//! permlane and swizzle without fetch-inactive, whose source outside EXEC reads 0 or keeps +//! the destination); +//! - a read of any lane (readlane, writelane, fetch-inactive) needs every lane here, so it is +//! refused in a block not every lane reaches (`partial`), and the program stays on HLSL; +//! - a mask as a number is the ballot of its bits, which counts the lanes that are here: exact +//! for EXEC (a lane elsewhere is outside it), and for any mask where every lane is here. +//! +//! DPP, permlane(x)16, ds_swizzle and `v_mbcnt_hi` only need this lane's 32-lane half, so they +//! use `Ir::read_lane_half` / `Ir::ballot_half`; readfirstlane, readlane, writelane, `v_mbcnt_lo` +//! and a mask as a number need the whole wave (`read_lane`, `ballot`). With one hardware wave per +//! console wave they are the same; a wave64 split into two 32-lane hardware waves exchanges data +//! between the halves only for the whole-wave forms. +//! +//! Lanes outside EXEC when a kernel-mode program starts leave at once (`lower_kernel`), so a +//! read of one of those is not the console's; compute waves start with every lane in EXEC. + +use super::{Bin, Cmp, Ir, Lower, Var, EXEC, R}; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +impl Lower<'_, I> { + fn all_lanes(&self, b: usize, what: &str) -> R<()> { + if self.partial[b] { + Err(format!("{what} where some lanes are elsewhere")) + } else { + Ok(()) + } + } + + /// Whether operand `code` names a register holding a mask here, and the pair's register. + fn mask_reg(&mut self, b: usize, code: u64) -> Option<(u8, bool)> { + if code > 127 || code == 124 || code == 125 { + return None; + } + let r = code as u8; + if self.holds_mask(b, r) { + return Some((r, false)); + } + // the upper dword of a wave64 mask pair + (self.wave64 && r > 0 && self.holds_mask(b, r - 1)).then(|| (r - 1, true)) + } + + /// The mask in s as numbers (lanes 0–31, 32–63): the ballot of its bits; with `half`, + /// only this lane's half of it is right (`Ir::ballot_half`). + fn mask_words(&mut self, b: usize, r: u8, half: bool) -> R<[I::V; 2]> { + if r != EXEC || (!half && self.ir.whole_needs_exchange()) { + self.all_lanes(b, "a mask read as a number")?; + } + let bit = self.read_bit(b, r)?; + let [lo, hi] = if half { self.ir.ballot_half(bit) } else { self.ir.ballot(bit) }; + Ok(if self.wave64 { [lo, hi] } else { [lo, self.ir.int(0)] }) + } + + /// A 32-bit scalar operand as a number, also where it holds (half of) a mask. + fn word(&mut self, b: usize, d: &Decoded, code: u64) -> R { + self.word_in(b, d, code, false) + } + + /// `word`; with `half`, a mask's word is only right for the lanes of the half it covers. + fn word_in(&mut self, b: usize, d: &Decoded, code: u64, half: bool) -> R { + match self.mask_reg(b, code) { + Some((r, hi)) => Ok(self.mask_words(b, r, half)?[hi as usize]), + None => self.src(b, d, code), + } + } + + /// A 64-bit scalar operand as numbers, also where it holds a mask. + fn words(&mut self, b: usize, d: &Decoded, code: u64) -> R<[I::V; 2]> { + match self.mask_reg(b, code) { + Some((r, false)) => self.mask_words(b, r, false), + Some((_, true)) => Err("a 64-bit operand across two masks".into()), + None => { + let (lo, hi) = self.src64(b, d, code)?; + Ok([lo, hi]) + } + } + } + + /// The lowest set bit of x, 32 if none. + fn ctz(&mut self, x: I::V) -> I::V { + let (z, one) = (self.ir.int(0), self.ir.int(1)); + let neg = self.ir.bin(Bin::Sub, z, x); + let low = self.ir.bin(Bin::And, x, neg); + let below = self.ir.bin(Bin::Sub, low, one); + self.ir.count_bits(below) + } + + /// The lowest set bit of the 64-bit (lo, hi), `none` if none. + fn first_set(&mut self, [lo, hi]: [I::V; 2], none: u32) -> I::V { + let z = self.ir.int(0); + let (cl, ch) = (self.ctz(lo), self.ctz(hi)); + let c32 = self.ir.int(32); + let ch = self.ir.bin(Bin::Add, ch, c32); + let none = self.ir.int(none); + let hz = self.ir.icmp(Cmp::Eq, hi, z); + let h = self.ir.select(hz, none, ch); + let lz = self.ir.icmp(Cmp::Eq, lo, z); + self.ir.select(lz, h, cl) + } + + /// Bit `l` of the 64-bit (lo, hi). + fn bit_at(&mut self, [lo, hi]: [I::V; 2], l: I::V) -> I::V { + let (c31, c32, one, z) = (self.ir.int(31), self.ir.int(32), self.ir.int(1), self.ir.int(0)); + let low = self.ir.icmp(Cmp::Ult, l, c32); + let w = self.ir.select(low, lo, hi); + let sh = self.ir.bin(Bin::And, l, c31); + let w = self.ir.bin(Bin::LShr, w, sh); + let w = self.ir.bin(Bin::And, w, one); + self.ir.icmp(Cmp::Ne, w, z) + } + + /// The lanes in EXEC, as numbers; with `half`, only this lane's half is right. + fn exec_words(&mut self, b: usize, half: bool) -> R<[I::V; 2]> { + // split: the other half's word comes through an exchange, which both halves must reach + if !half && self.ir.whole_needs_exchange() { + self.all_lanes(b, "EXEC as a number in the split form")?; + } + let e = self.read_bit(b, EXEC)?; + let [lo, hi] = if half { self.ir.ballot_half(e) } else { self.ir.ballot(e) }; + Ok([lo, if self.wave64 { hi } else { self.ir.int(0) }]) + } + + /// `v` of lane `l` (in this lane's 32-lane half) if that lane is in EXEC (or + /// `inactive_too`); whether it was. + fn read_from(&mut self, b: usize, v: I::V, l: I::V, inactive_too: bool, what: &str) -> R<(I::V, I::V)> { + let ok = if inactive_too { + self.all_lanes(b, what)?; + self.ir.boolean(true) + } else { + let e = self.exec_words(b, true)?; + self.bit_at(e, l) + }; + // a lane outside EXEC may be elsewhere: read this lane's own value instead, unused + let me = self.lane(); + let at = self.ir.select(ok, l, me); + Ok((self.ir.read_lane_half(v, at), ok)) + } + + fn c(&mut self, v: u32) -> I::V { + self.ir.int(v) + } + + /// `(lane & !keep) | x` + fn lane_with(&mut self, keep_not: u32, x: I::V) -> I::V { + let me = self.lane(); + let k = self.c(!keep_not); + let hi = self.ir.bin(Bin::And, me, k); + self.ir.bin(Bin::Or, hi, x) + } + + /// `(k >> (bits * (lane & group))) & field`: a lane's entry of a packed selector. + fn packed(&mut self, k: I::V, bits: u32, group: u32, field: u32) -> I::V { + let me = self.lane(); + let (g, w, f) = (self.c(group), self.c(bits), self.c(field)); + let i = self.ir.bin(Bin::And, me, g); + let sh = self.ir.bin(Bin::Mul, i, w); + let x = self.ir.bin(Bin::LShr, k, sh); + self.ir.bin(Bin::And, x, f) + } + + /// The source lane of DPP16 control `ctrl`, and whether it is inside the row. + fn dpp16_lane(&mut self, ctrl: u64) -> R<(I::V, I::V)> { + let me = self.lane(); + let n = (ctrl & 15) as u32; + let t = self.ir.boolean(true); + let row = |l: &mut Self| { + let c = l.c(15); + l.ir.bin(Bin::And, me, c) + }; + Ok(match ctrl { + 0x000..=0x0FF => { + let k = self.c(ctrl as u32); + let x = self.packed(k, 2, 3, 3); + (self.lane_with(3, x), t) + } + 0x101..=0x10F => { + let (r, cn, c16) = (row(self), self.c(n), self.c(16)); + let to = self.ir.bin(Bin::Add, r, cn); + let ok = self.ir.icmp(Cmp::Ult, to, c16); + (self.ir.bin(Bin::Add, me, cn), ok) + } + 0x111..=0x11F => { + let (r, cn) = (row(self), self.c(n)); + let ok = self.ir.icmp(Cmp::Uge, r, cn); + (self.ir.bin(Bin::Sub, me, cn), ok) + } + 0x121..=0x12F => { + let (r, cn, c15) = (row(self), self.c(n), self.c(15)); + let x = self.ir.bin(Bin::Sub, r, cn); + let x = self.ir.bin(Bin::And, x, c15); + (self.lane_with(15, x), t) + } + 0x140 => { + let (r, c15) = (row(self), self.c(15)); + let x = self.ir.bin(Bin::Sub, c15, r); + (self.lane_with(15, x), t) + } + 0x141 => { + let (c7, c8) = (self.c(7), self.c(8)); + let x = self.ir.bin(Bin::And, me, c7); + let x = self.ir.bin(Bin::Sub, c7, x); + let h = self.ir.bin(Bin::And, me, c8); + let x = self.ir.bin(Bin::Or, x, h); + (self.lane_with(15, x), t) + } + 0x150..=0x15F => { + let x = self.c(n); + (self.lane_with(15, x), t) + } + 0x160..=0x16F => { + let cn = self.c(n); + (self.ir.bin(Bin::Xor, me, cn), t) + } + _ => return Err(format!("DPP_CTRL {ctrl:#x}")), + }) + } + + /// A DPP instruction's first source, read from its source lane, and its write enable + /// (`dpp_src`, `dpp_en`, taken by `src` and `write_v`). + pub(super) fn dpp(&mut self, b: usize, d: &Decoded) -> R<()> { + let name = d.inst.name; + if name.starts_with("V_CMP") { + return Err(format!("{name}: DPP compare")); + } + let e = super::super::emit::ext_encoding(d).ok_or("DPP encoding")?; + let f = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + if ["SRC0_ABS", "SRC0_NEG", "SRC1_ABS", "SRC1_NEG"].iter().any(|m| f(m) != 0) { + return Err(format!("{name}: DPP modifiers")); + } + let v = self.read(b, Var::V(f("VSRC0") as u16)); + let (val, en) = if d.variant == Variant::Dpp16 { + let (l, inside) = self.dpp16_lane(f("DPP_CTRL"))?; + // outside the row: this lane's own, unused (the lane number may be out of range) + let me = self.lane(); + let l = self.ir.select(inside, l, me); + let (val, ok) = self.read_from(b, v, l, f("FI") == 1, "DPP fetch-inactive")?; + let ok = self.ir.bin(Bin::And, ok, inside); + let z = self.c(0); + let mut en = None; + let val = if f("BOUND_CTRL") == 1 { + self.ir.select(ok, val, z) + } else { + en = Some(ok); + val + }; + let (rm, bm) = (f("ROW_MASK") as u32, f("BANK_MASK") as u32); + if rm != 0xF || bm != 0xF { + let me = self.lane(); + let (k, s4, s2, c3) = (self.c(rm), self.c(4), self.c(2), self.c(3)); + let r = self.ir.bin(Bin::LShr, me, s4); + let r = self.ir.bin(Bin::LShr, k, r); + let k = self.c(bm); + let q = self.ir.bin(Bin::LShr, me, s2); + let q = self.ir.bin(Bin::And, q, c3); + let q = self.ir.bin(Bin::LShr, k, q); + let both = self.ir.bin(Bin::And, r, q); + let one = self.c(1); + let both = self.ir.bin(Bin::And, both, one); + let on = self.ir.icmp(Cmp::Ne, both, z); + en = Some(match en { + Some(ok) => self.ir.bin(Bin::And, ok, on), + None => on, + }); + } + (val, en) + } else { + let sel: u64 = (0..8).map(|i| f(&format!("LANE_SEL_{i}")) << (3 * i)).sum(); + let fi = rdna2::field_value(d.enc, &d.words, "SRC0") == Some(0xEA); + let k = self.c(sel as u32); + let x = self.packed(k, 3, 7, 7); + let l = self.lane_with(7, x); + let (val, ok) = self.read_from(b, v, l, fi, "DPP8 fetch-inactive")?; + let z = self.c(0); + (self.ir.select(ok, val, z), None) + }; + self.dpp_src = Some(val); + self.dpp_en = en; + Ok(()) + } + + /// The cross-lane VALU instructions; `false` for any other. + pub(super) fn wave_valu(&mut self, b: usize, d: &Decoded) -> R { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let (s0, s1, vdst) = (fv("SRC0"), fv("SRC1"), fv("VDST")); + let wmask = if self.wave64 { 63 } else { 31 }; + match name { + "V_READFIRSTLANE_B32" => { + let v = self.src(b, d, s0)?; + let r = if s0 >= 256 { + let e = self.exec_words(b, false)?; + let l = self.first_set(e, 0); + self.ir.read_lane(v, l) + } else { + v + }; + self.write_num(b, vdst as u8, r); + } + "V_READLANE_B32" => { + self.all_lanes(b, "v_readlane")?; + let (v, sel) = (self.src(b, d, s0)?, self.word(b, d, s1)?); + let m = self.c(wmask); + let l = self.ir.bin(Bin::And, sel, m); + let r = self.ir.read_lane(v, l); + self.write_num(b, vdst as u8, r); + } + "V_WRITELANE_B32" => { + // whatever EXEC holds + self.all_lanes(b, "v_writelane")?; + let (a, sel) = (self.word(b, d, s0)?, self.word(b, d, s1)?); + let m = self.c(wmask); + let l = self.ir.bin(Bin::And, sel, m); + let me = self.lane(); + let hit = self.ir.icmp(Cmp::Eq, me, l); + let old = self.read(b, Var::V(vdst as u16)); + let v = self.ir.select(hit, a, old); + self.ssa.write(b, Var::V(vdst as u16), v); + } + "V_MBCNT_LO_U32_B32" | "V_MBCNT_HI_U32_B32" => { + // mbcnt_hi counts the upper lanes' own half only (0 below lane 32); mbcnt_lo + // gives the upper lanes all of the lower half + let hi_half = name == "V_MBCNT_HI_U32_B32"; + let (m, add) = (self.word_in(b, d, s0, hi_half)?, self.src(b, d, s1)?); + // the lanes below this one, in this half of the mask + let me = self.lane(); + let (c31, c32, one, z, all) = (self.c(31), self.c(32), self.c(1), self.c(0), self.c(u32::MAX)); + let sh = self.ir.bin(Bin::And, me, c31); + let below = self.ir.bin(Bin::Shl, one, sh); + let below = self.ir.bin(Bin::Sub, below, one); + let upper = self.ir.icmp(Cmp::Uge, me, c32); + let lt = if name == "V_MBCNT_LO_U32_B32" { self.ir.select(upper, all, below) } else { self.ir.select(upper, below, z) }; + let x = self.ir.bin(Bin::And, m, lt); + let n = self.ir.count_bits(x); + let r = self.ir.bin(Bin::Add, n, add); + self.write_v(b, d, vdst as u16, r)?; + } + "V_PERMLANE16_B32" | "V_PERMLANEX16_B32" => { + let op_sel = fv("OP_SEL"); + if ["ABS", "NEG", "CLAMP", "OMOD"].iter().any(|f| fv(f) != 0) || op_sel & !3 != 0 { + return Err(format!("{name}: VOP3 modifiers")); + } + let (fi, bound) = (op_sel & 1 == 1, op_sel & 2 == 2); + let v = self.src(b, d, s0)?; + let (lo, hi) = (self.word(b, d, s1)?, self.word(b, d, fv("SRC2"))?); + let me = self.lane(); + let (c8, c15, c16) = (self.c(8), self.c(15), self.c(16)); + let r = self.ir.bin(Bin::And, me, c15); + let first8 = self.ir.icmp(Cmp::Ult, r, c8); + let k = self.ir.select(first8, lo, hi); + let n = self.packed(k, 4, 7, 15); + // the same row (permlane16) or the other row of the 32-lane half + let row = self.ir.bin(Bin::And, me, c16); + let row = if name == "V_PERMLANEX16_B32" { self.ir.bin(Bin::Xor, row, c16) } else { row }; + let x = self.ir.bin(Bin::Or, row, n); + let l = self.lane_with(31, x); + let (val, ok) = self.read_from(b, v, l, fi, "v_permlane fetch-inactive")?; + let other = if bound { self.c(0) } else { self.read(b, Var::V(vdst as u16)) }; + let r = self.ir.select(ok, val, other); + self.write_v(b, d, vdst as u16, r)?; + } + _ => return Ok(false), + } + Ok(true) + } + + /// `ds_swizzle_b32`: a lane reads another of its 32-lane half (`emit::swizzle_lane`). + pub(super) fn swizzle(&mut self, b: usize, d: &Decoded) -> R<()> { + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let off = fv("OFFSET0") | fv("OFFSET1") << 8; + let v = self.read(b, Var::V(fv("ADDR") as u16)); + let me = self.lane(); + let c31 = self.c(31); + let i = self.ir.bin(Bin::And, me, c31); + let x = if off >= 0xE000 { + return Err("ds_swizzle FFT mode".into()); + } else if off >= 0xC000 { + // rotate by offset[9:5] lanes, left or right (offset[10]); masked bits stay + let mask = (off & 0x1F) as u32; + let r = ((off >> 5) & 0x1F) as u32; + let r = if off & 0x400 != 0 { r.wrapping_neg() } else { r }; + let (cm, cn, cr) = (self.c(mask), self.c(!mask & 31), self.c(r)); + let kept = self.ir.bin(Bin::And, i, cm); + let moved = self.ir.bin(Bin::Add, i, cr); + let moved = self.ir.bin(Bin::And, moved, cn); + self.ir.bin(Bin::Or, kept, moved) + } else if off & 0x8000 != 0 { + let k = self.c(off as u32); + let q = self.packed(k, 2, 3, 3); + let c28 = self.c(28); + let base = self.ir.bin(Bin::And, i, c28); + self.ir.bin(Bin::Or, base, q) + } else { + let (and, or, xor) = (self.c((off & 0x1F) as u32), self.c(((off >> 5) & 0x1F) as u32), self.c(((off >> 10) & 0x1F) as u32)); + let x = self.ir.bin(Bin::And, i, and); + let x = self.ir.bin(Bin::Or, x, or); + self.ir.bin(Bin::Xor, x, xor) + }; + let l = self.lane_with(31, x); + let (val, ok) = self.read_from(b, v, l, false, "")?; + let z = self.c(0); + let r = self.ir.select(ok, val, z); + self.write_v(b, d, fv("VDST") as u16, r) + } + + /// Scalar counts of a mask; `false` for any other instruction. + pub(super) fn wave_salu(&mut self, b: usize, d: &Decoded) -> R { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let (s0, sd) = (fv("SSRC0"), fv("SDST") as u8); + // `s_wqm` of a mask (`s_wqm_b64 exec, exec`): a lane's bit is set when any lane of its + // quad has its bit; the quad is in the lane's own half of the mask + // (the launch EXEC's, and any in a VS / PS, are `salu`'s) + let wqm = if self.wave64 { "S_WQM_B64" } else { "S_WQM_B32" }; + if name == wqm && !self.graphics && !self.sum.wqm_all.contains(&d.pc) { + let Some((r, false)) = self.mask_reg(b, s0) else { return Err(format!("unsupported {name} of a number")) }; + let [lo, hi] = self.mask_words(b, r, true)?; + let lane = self.lane(); + let (c32, c28, f) = (self.c(32), self.c(28), self.c(0xF)); + let upper = self.ir.icmp(Cmp::Uge, lane, c32); + let w = self.ir.select(upper, hi, lo); + let q = self.ir.bin(Bin::And, lane, c28); + let w = self.ir.bin(Bin::LShr, w, q); + let w = self.ir.bin(Bin::And, w, f); + let z = self.c(0); + let bit = self.ir.icmp(Cmp::Ne, w, z); + self.write_bit(b, sd, bit); + self.write_scc(b, bit); + return Ok(true); + } + let (ones, count) = match name { + "S_BCNT1_I32_B32" | "S_BCNT1_I32_B64" => (true, true), + "S_BCNT0_I32_B32" | "S_BCNT0_I32_B64" => (false, true), + "S_FF1_I32_B32" | "S_FF1_I32_B64" => (true, false), + _ => return Ok(false), + }; + // only where the source is a mask: numbers take the usual path + if self.mask_reg(b, s0).is_none() { + return Ok(false); + } + let w = if name.ends_with("_B64") { + self.words(b, d, s0)? + } else { + [self.word(b, d, s0)?, self.c(0)] + }; + let w = if ones { + w + } else { + let all = self.c(u32::MAX); + let hi = if name.ends_with("_B64") { self.ir.bin(Bin::Xor, w[1], all) } else { w[1] }; + [self.ir.bin(Bin::Xor, w[0], all), hi] + }; + let r = if count { + let (lo, hi) = (self.ir.count_bits(w[0]), self.ir.count_bits(w[1])); + let r = self.ir.bin(Bin::Add, lo, hi); + let z = self.c(0); + let c = self.ir.icmp(Cmp::Ne, r, z); + self.ssa.write(b, Var::Scc, c); + r + } else { + self.first_set(w, u32::MAX) + }; + self.write_num(b, sd, r); + Ok(true) + } +} diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs new file mode 100644 index 0000000000..7107e53854 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -0,0 +1,771 @@ +//! The direct lowering (`lower`) written into a DXIL module through `gpu::dxil`'s builder: +//! the per-lane form of a program as a signed container, with no HLSL and no DXC. +//! +//! `Ir` maps one to one onto the builder: blocks, phis (`phi_at` / `add_incoming`), integer +//! ops, compares, `select`, the thread / group / lane ids, `waveActiveBallot`, and raw buffer +//! loads and stores on the ABI's root UAVs (u0 `io`, u1 `res`, u2 `mem`). The builder state is +//! #1426's translator state (`gpu::dxil::lower::Lw`, built by `Lw::new` and finished by +//! `Lw::finish`), so its per-entry setup (`setup_lanes_compute`) and its instruction +//! lowering are reachable from here. A phi the SSA +//! construction finds trivial has its uses replaced (`Module::replace_uses`); the phi itself +//! stays in its block, unused. The replacements are collected and made in one pass in +//! `DxilIr::finish`: one pass over the module per trivial phi made the lowering quadratic in +//! the program's size, and nothing reads an instruction's operands back before then (the +//! SSA construction resolves a replaced phi itself). + +use super::lower::{self, Bin, Cmp, Ir}; +use super::ssa::{Sink, Var}; +use crate::gpu::dxil::kernel::{Entry, KernelOptions}; +use crate::gpu::dxil::lower::Lw; +use crate::gpu::dxil::module::{BinOp, Block, CastOp, Pred, Value}; +use crate::gpu::dxil::shader::RawUav; +use crate::gpu::rdna2::Decoded; +use std::collections::{BTreeSet, HashMap}; + +struct DxilIr { + lw: Lw, + io: RawUav, + res: Option, + mem: RawUav, + /// each `Ir` block: where it starts (its phis) and where it ends now (its branch; later than + /// the start when #1426's lowering of an instruction in it made blocks of its own) + blocks: Vec, + tails: Vec, + /// the `Ir` block being written + cur: usize, + /// `compute_ids` set up the lanes (`Lw::lane` is the console lane) + lanes_set: bool, + /// a split compute program's thread ids, set up with its lanes in the constructor: the + /// lowering takes `lane()` before `compute_ids`, and in the split form the console lane + /// is not the hardware lane (the upper half's are 32-63) + ids: Option<(Value, [Value; 3])>, + /// trivial phis → what replaces their uses, made in the module by `finish` + replaced: HashMap, +} + +impl DxilIr { + /// The builder state for `insts` at `entry` (a kernel or a compute program), with one memory + /// window; a compute program's is coherent, as the HLSL path declares it. + fn new(insts: &[Decoded], wave64: bool, entry: &Entry) -> DxilIr { + Self::with(insts, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, entry) + } + + /// `new` in the split form (two hardware wave32s per console wave64): #1426's `Lw` numbers + /// the threads as the hardware waves arrive and lays out the halves' exchange storage; its + /// `ballot` / `read_lane_uniform` meet the other half (a group barrier for one console + /// wave per group, the spin meet for more). + fn split(insts: &[Decoded], entry: &Entry) -> DxilIr { + Self::with(insts, KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }, entry) + } + + /// The builder state with the runtime's options `o` (memory windows, sampler registers, the + /// split form). + fn with(insts: &[Decoded], o: KernelOptions, entry: &Entry) -> DxilIr { + // block leaders for the constant-sampler scan: the first instruction, branch targets + // and the instruction after a branch + let mut leaders: BTreeSet = insts.first().map(|d| d.pc).into_iter().collect(); + for (i, d) in insts.iter().enumerate() { + if let Some(t) = crate::gpu::rdna2::branch_target(d) { + leaders.insert(t); + leaders.extend(insts.get(i + 1).map(|n| n.pc)); + } + } + let mut lw = Lw::new(insts, &leaders, o, entry); + // the rounding modes the program sets, as `kernel::translate_on_this_thread` finds them: + // #1426's `s_round_mode` / `s_setreg` refuse a mode they cannot honour from these + let branchy = insts.iter().any(|d| crate::gpu::rdna2::branch_target(d).is_some()); + (lw.dyn_rm, lw.has_f64_round_op) = crate::gpu::dxil::lower::round_modes(insts, !branchy); + // a kernel's lanes in the split form: the console lane each hardware lane stands for, + // set up in the entry block (a compute program's come with `compute_ids`) + let mut ids = None; + let lanes_set = match entry { + // (a kernel always: `Lw`'s lane bit, `lane31`, is what #1426's lowering of a carry-in or + // a `v_cndmask` reads, and stays 0 without it) + Entry::Kernel => { + lw.setup_lanes(); + true + } + Entry::Compute(cs) if lw.split => { + let lds = lw.lds.is_some(); + ids = Some(lw.setup_lanes_compute(cs.threads, lds)); + true + } + _ => false, + }; + let io = lw.init.io.expect("the I/O buffer"); + let (res, mem) = (lw.res, lw.mems[0]); + DxilIr { lw, io, res, mem, blocks: Vec::new(), tails: Vec::new(), cur: 0, lanes_set, ids, replaced: HashMap::new() } + } + + fn ty(&mut self, var: Var) -> crate::gpu::dxil::module::Ty { + match var { + Var::M(_) | Var::Scc => self.lw.s.m.i1(), + Var::S(_) | Var::V(_) => self.lw.s.m.i32(), + } + } + + /// The container: `Lw`'s entry block jumps to the first `Ir` block (as `kernel.rs` ends it), + /// the lowering's blocks are sealed for `Lw`'s variables (every edge into them is known once + /// the lowering is done), then `Lw::finish`. + fn finish(mut self, numthreads: [u32; 3], hw: u32) -> Result { + // the trivial phis' uses first, as `replace` would have left them + self.lw.s.m.replace_uses(&self.replaced); + let first = *self.blocks.first().ok_or("no blocks")?; + self.lw.s.m.set_block(Block(0)); + self.lw.br(first); + for i in 0..self.blocks.len() { + let b = self.blocks[i]; + if !self.lw.ssa.is_sealed(b) { + self.lw.seal(b); + } + } + self.lw.finish(numthreads, hw) + } + + fn bytes(&mut self, dword: Value) -> Value { + let four = self.lw.s.m.i32c(4); + self.lw.s.m.bin(BinOp::Mul, dword, four) + } +} + +impl Sink for DxilIr { + type V = Value; + fn phi(&mut self, block: usize, var: Var) -> Value { + let t = self.ty(var); + self.lw.s.m.phi_at(self.blocks[block], t) + } + fn incoming(&mut self, phi: Value, value: Value, pred: usize) { + self.lw.s.m.add_incoming(phi, value, self.tails[pred]); + } + fn replace(&mut self, old: Value, new: Value) { + // every use of the trivial phi becomes `new` (in `finish`); the phi stays in its + // block, unused + self.replaced.insert(old, new); + } + fn undef(&mut self, var: Var) -> Value { + let t = self.ty(var); + self.lw.s.m.undef(t) + } +} + +impl Ir for DxilIr { + fn new_block(&mut self) -> usize { + // not `Block(0)`: `Lw` keeps writing there (static samplers, scratch) until `finish` + let b = self.lw.s.m.new_block(); + self.blocks.push(b); + self.tails.push(b); + self.blocks.len() - 1 + } + fn at(&mut self, block: usize) { + self.cur = block; + self.lw.s.m.set_block(self.tails[block]); + } + fn int(&mut self, v: u32) -> Value { + self.lw.s.m.i32c(v) + } + fn boolean(&mut self, v: bool) -> Value { + self.lw.s.m.i1c(v) + } + fn bin(&mut self, op: Bin, a: Value, b: Value) -> Value { + let op = match op { + Bin::Add => BinOp::Add, + Bin::Sub => BinOp::Sub, + Bin::Mul => BinOp::Mul, + Bin::And => BinOp::And, + Bin::Or => BinOp::Or, + Bin::Xor => BinOp::Xor, + Bin::Shl => BinOp::Shl, + Bin::LShr => BinOp::LShr, + Bin::AShr => BinOp::AShr, + }; + self.lw.s.m.bin(op, a, b) + } + fn icmp(&mut self, c: Cmp, a: Value, b: Value) -> Value { + let p = match c { + Cmp::Eq => Pred::Eq, + Cmp::Ne => Pred::Ne, + Cmp::Ult => Pred::ULt, + Cmp::Ule => Pred::ULe, + Cmp::Ugt => Pred::UGt, + Cmp::Uge => Pred::UGe, + Cmp::Slt => Pred::SLt, + Cmp::Sle => Pred::SLe, + Cmp::Sgt => Pred::SGt, + Cmp::Sge => Pred::SGe, + }; + self.lw.s.m.cmp(p, a, b) + } + fn select(&mut self, c: Value, a: Value, b: Value) -> Value { + self.lw.s.m.select(c, a, b) + } + fn zext(&mut self, b: Value) -> Value { + let t = self.lw.s.m.i32(); + self.lw.s.m.cast(CastOp::ZExt, b, t) + } + fn lane(&mut self) -> Value { + if self.lanes_set { + self.lw.lane + } else { + self.lw.s.wave_lane_index() + } + } + fn group_id(&mut self, k: u32) -> Value { + self.lw.s.group_id(k) + } + fn compute_ids(&mut self, threads: [u32; 3]) -> (Value, [Value; 3]) { + // #1426's compute entry: 2-D / 3-D groups numbered as their waves arrive, the counter + // in the program's top LDS word when it has LDS + if let Some(ids) = self.ids { + return ids; + } + let lds = self.lw.lds.is_some(); + let ids = self.lw.setup_lanes_compute(threads, lds); + self.lanes_set = true; + ids + } + fn whole_needs_exchange(&self) -> bool { + self.lw.split + } + fn ballot(&mut self, c: Value) -> [Value; 2] { + if self.lw.split { + // this half's word from the hardware, the other's through the exchange + let (lo, hi) = self.lw.ballot(c); + return [lo, hi]; + } + let w = self.lw.s.wave_ballot(c); + [w[0], w[1]] + } + // one hardware wave per console wave (native wave64, or wave32): the half-local forms are + fn mem_windows(&self) -> u32 { + self.lw.mems.len() as u32 + } + // the same operations; in the split form only the reader's half is right (`Ir::ballot_half`) + fn ballot_half(&mut self, c: Value) -> [Value; 2] { + if self.lw.split { + let w = self.lw.s.wave_ballot(c); + return [w[0], w[0]]; + } + self.ballot(c) + } + /// #1426's semantics of `d` (`Lw::inst_guarded`) in the current block: the inputs are written + /// into `Lw`'s SSA there first, so it reads them and nothing from other blocks (which its SSA + /// doesn't know). A register it touches that is neither an input nor an output refuses the + /// instruction: `Lw` would read that register's value at the program's start. Blocks it makes + /// (a guarded access, the memory window switch) end the `Ir` block in the last of them. + fn foreign(&mut self, d: &Decoded, guard: Value, inputs: &[(Var, Value)], outputs: &[Var]) -> Result, String> { + use crate::gpu::dxil::lower::{VAR_BUDGET, VAR_SCC, VAR_VGPR}; + let var = |v: Var| match v { + Var::S(r) => r as u32, + Var::V(n) => VAR_VGPR + n as u32, + Var::Scc => VAR_SCC, + Var::M(_) => unreachable!("a lane-bit view is not a register"), + }; + for &(v, x) in inputs { + self.lw.wr(var(v), x); + } + // the registers `Lw` touches for `d` alone + let before = std::mem::take(&mut self.lw.init.touched); + self.lw.pc = d.pc; + let r = self.lw.inst_guarded(d, guard, None); + let used = std::mem::replace(&mut self.lw.init.touched, before); + self.lw.init.touched.extend(&used); + r?; + let known: BTreeSet = inputs.iter().map(|&(v, _)| var(v)).chain(outputs.iter().map(|&v| var(v))).collect(); + if let Some(r) = used.iter().find(|&&r| r < VAR_BUDGET && !known.contains(&r)) { + return Err(format!("it reads register {r} the per-lane form did not pass")); + } + let tail = self.lw.cur(); + self.tails[self.cur] = tail; + Ok(outputs.iter().map(|&v| self.lw.rd(var(v))).collect()) + } + fn read_lane(&mut self, v: Value, lane: Value) -> Value { + if self.lw.split { + // the lowering's lane reads take the same lane in every lane (readlane, + // readfirstlane, writelane's source) + return self.lw.read_lane_uniform(v, lane); + } + self.lw.s.wave_read_lane_at(v, lane) + } + fn read_lane_half(&mut self, v: Value, lane: Value) -> Value { + if self.lw.split { + return self.lw.read_lane_half(v, lane); + } + self.read_lane(v, lane) + } + fn count_bits(&mut self, v: Value) -> Value { + self.lw.s.bit_count(crate::gpu::dxil::ops::BitCount::Countbits, v) + } + fn io_load(&mut self, dword: Value) -> Value { + let a = self.bytes(dword); + let io = self.io; + self.lw.s.raw_load(io, a, 1)[0] + } + fn res_store(&mut self, dword: Value, value: Value) { + let a = self.bytes(dword); + let res = self.res.expect("res is bound in kernel mode"); + self.lw.s.raw_store(res, a, &[value]); + } + fn mem_load(&mut self, addr: Value) -> Value { + let mem = self.mem; + self.lw.s.raw_load(mem, addr, 1)[0] + } + fn mem_store(&mut self, addr: Value, value: Value) { + let mem = self.mem; + self.lw.s.raw_store(mem, addr, &[value]); + } + // through `Lw`, which records the edges for its own variables (the split form's exchange + // count and dead flag, its temporaries); the lowering's blocks are sealed in `finish` + fn br(&mut self, target: usize) { + let b = self.blocks[target]; + self.lw.br(b); + } + fn br_if(&mut self, c: Value, then: usize, otherwise: usize) { + let (t, f) = (self.blocks[then], self.blocks[otherwise]); + self.lw.cond_br(c, t, f); + } + fn ret(&mut self) { + self.lw.s.m.ret(); + } +} + +/// A kernel-mode program in its per-lane form, as a signed DXIL container (one wave of +/// `WaveSize` = the program's wave size), and the masks whose final value may differ from +/// the console's (`lower::lower_kernel`). +pub fn kernel(insts: &[Decoded], wave64: bool) -> Result<(Vec, Vec), String> { + let (ir, stale) = lower::lower_kernel(insts, wave64, DxilIr::new(insts, wave64, &Entry::Kernel))?; + let lanes = if wave64 { 64 } else { 32 }; + Ok((ir.finish([lanes, 1, 1], lanes)?.dxil, stale)) +} + +/// `kernel` in the split form: a wave64 program as two hardware wave32s (`DxilIr::split`). +/// EXEC at launch must be the whole console wave, as the CPU interpreter and the HLSL path +/// start it. +pub fn kernel_split(insts: &[Decoded]) -> Result<(Vec, Vec), String> { + let (ir, stale) = lower::lower_kernel(insts, true, DxilIr::split(insts, &Entry::Kernel))?; + Ok((ir.finish([64, 1, 1], 32)?.dxil, stale)) +} + +/// `compute` in the split form: each console wave64 as two hardware wave32s, threads numbered +/// by arrival (`Lw::setup_lanes_compute`). +pub fn compute_split(insts: &[Decoded], cs: &super::CsInterface) -> Result, String> { + let ir = lower::lower_compute(insts, cs, true, DxilIr::split(insts, &Entry::Compute(cs.clone())))?; + Ok(ir.finish(cs.threads, 32)?.dxil) +} + +/// `compute` from the program's code (decoded, far jumps resolved). +pub fn compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) -> Result, String> { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let d = crate::gpu::rdna2::decode(&code[off..], off as u64).map_err(|e| format!("cannot decode ({e:?})"))?; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + compute(&insts, cs, wave64) +} + +/// Survey: every reason the per-lane form refuses a compute program (`lower::survey_compute`). +pub fn survey_compute_code(code: &[u8], cs: &super::CsInterface, wave64: bool) -> Vec { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + match crate::gpu::rdna2::decode(&code[off..], off as u64) { + Ok(d) => { + off += d.len; + insts.push(d); + } + Err(e) => return vec![format!("cannot decode ({e:?})")], + } + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + lower::survey_compute(&insts, cs, wave64, DxilIr::new(&insts, wave64, &Entry::Compute(cs.clone()))) +} + +/// A compute program in its per-lane form, as a signed DXIL container. +pub fn compute(insts: &[Decoded], cs: &super::CsInterface, wave64: bool) -> Result, String> { + let ir = lower::lower_compute(insts, cs, wave64, DxilIr::new(insts, wave64, &Entry::Compute(cs.clone())))?; + Ok(ir.finish(cs.threads, if wave64 { 64 } else { 32 })?.dxil) +} + + +/// `XCL_PER_LANE=1` (with `XCL_DIRECT_DXIL`): compute programs try the per-lane form first, then +/// #1426's per-instruction form, then the HLSL path. +pub fn enabled() -> bool { + std::env::var("XCL_PER_LANE").is_ok_and(|v| v == "1") +} + +/// A compute program in its per-lane form with the runtime's options `o` (`pso::direct_compute`): +/// the container and its static samplers. +pub fn compute_with(code: &[u8], cs: &super::CsInterface, o: KernelOptions) -> Result { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let d = crate::gpu::rdna2::decode(&code[off..], off as u64).map_err(|e| format!("cannot decode ({e:?})"))?; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + // as `kernel::translate_entry`: a thread with a large stack, a panic is a refusal + let cs = cs.clone(); + std::thread::Builder::new() + .name("xcl-per-lane".into()) + .stack_size(256 << 20) + .spawn(move || { + let ir = lower::lower_compute(&insts, &cs, o.wave64, DxilIr::with(&insts, o, &Entry::Compute(cs.clone())))?; + ir.finish(cs.threads, if o.wave64 && !o.split { 64 } else { 32 }) + }) + .map_err(|e| format!("per-lane thread: {e}"))? + .join() + .map_err(|e| { + let msg = e.downcast_ref::().cloned().or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default(); + format!("the per-lane lowering panicked: {msg}") + })? +} + +#[cfg(test)] +mod tests { + use super::super::lower::tests::*; + use super::super::{dxc, runner, translate, Mode, Options}; + + fn gpu() -> bool { + if !gpu_waves() { + runner::skip_test("no GPU with 32-lane waves"); + return false; + } + true + } + + /// A rounding mode #1426's lowering cannot honour refuses the program, as #1426 and the HLSL + /// path do, instead of the per-lane form computing with the default mode (Kalmarv, #1745): + /// f32 toward zero by `s_setreg`, f64 by `s_round_mode` and by `s_setreg`. + #[test] + fn a_rounding_mode_the_lowering_cannot_honour_is_refused() { + let add_f32: I = ("V_ADD_F32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 1)]); + let add_f64: I = ("V_ADD_F64", "ENC_VOP3", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 2)]); + let programs: [(&str, Vec); 3] = [ + ("f32 by s_setreg", vec![("S_SETREG_IMM32_B32", "ENC_SOPK", &[("SIMM16", 0x801), ("LITERAL", 3)]), add_f32, ENDPGM]), + ("f64 by s_round_mode", vec![("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 0xC)]), add_f64, ENDPGM]), + ("f64 by s_setreg", vec![("S_SETREG_IMM32_B32", "ENC_SOPK", &[("SIMM16", 0x881), ("LITERAL", 3)]), add_f64, ENDPGM]), + ]; + for (name, p) in programs { + assert!(super::kernel(&decode(&p), false).is_err(), "{name}: taken"); + } + // denormal bits only (MODE[7:4]): the default rounding, taken + let denorm: Vec = vec![("S_SETREG_IMM32_B32", "ENC_SOPK", &[("SIMM16", 0x1901), ("LITERAL", 0xF)]), add_f32, ENDPGM]; + super::kernel(&decode(&denorm), false).unwrap(); + } + + /// An instruction lowered by #1426 that writes to `Lw`'s entry block after the program's + /// blocks are written (scratch) gives a container, and runs. + #[test] + fn a_bridged_instruction_may_write_to_the_entry_block() { + // scratch through #1426's lowering: its array is allocated in `Lw`'s entry block once + // the program's blocks are written (an "instruction after a terminator" before) + let lines: &[I] = &[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V)]), + ("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 1), ("SADDR", 0x7F)]), + ("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 3), ("ADDR", 2), ("SADDR", 0x7F)]), + ENDPGM, + ]; + let dxil = super::kernel(&decode(lines), false).map(|r| r.0); + let dxil = dxil.unwrap_or_else(|e| panic!("{e}")); + if !gpu() { + return; + } + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let out = runner::run(&dxil, &st, &[]).unwrap(); + for l in 0..32 { + assert_eq!(out.vgpr[l][3], l as u32, "lane {l}"); + } + } + + /// The f16 and packed programs of `lower`'s tests, as `f32_programs_on_the_gpu`. + #[test] + fn f16_programs_on_the_gpu() { + programs_on_the_gpu(&[("f16 arithmetic", F16_ARITHMETIC, check_f16_arithmetic, &[]), ("f16 packed", F16_PACKED, check_f16_packed, &[])]); + } + + /// The per-lane form as real DXIL on the GPU agrees with the lowering run on the CPU (and so + /// with the HLSL path, which `lower`'s tests compare it with): registers and memory. + #[test] + fn per_lane_kernels_run_on_the_gpu() { + if !gpu() { + return; + } + let run = coalesced_run(false); + for (name, lines) in [ + ("straight", STRAIGHT), + ("skipped if", SKIPPED_IF), + ("leaving loop", LEAVING_LOOP), + ("uniform loop", UNIFORM_LOOP), + ("memory", MEMORY), + ("coalesced run", &run[..]), + ("coalesced breaks", COALESCED_BREAKS), + ("coalesced in partial", COALESCED_IN_PARTIAL), + ("coalesced in loop", COALESCED_IN_LOOP), + ] { + let insts = decode(lines); + let (dxil, stale) = super::kernel(&insts, false).unwrap_or_else(|e| panic!("{name}: {e}")); + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let mem = memory_image(); + let gpu = runner::run(&dxil, &st, &mem).unwrap_or_else(|e| panic!("{name}: {e}")); + let (cs, cv, cmem) = run_mem(lines, false, &s, &v, &mem); + assert_eq!(&gpu.mem[..cmem.len()], &cmem[..], "{name}: memory"); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = crate::gpu::rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + for &r in sregs.iter().filter(|&&r| !stale.contains(&(r as u8))) { + assert_eq!(gpu.sgpr[r], cs[r], "{name}: s{r}"); + } + for l in 0..32 { + for &r in &vregs { + assert_eq!(gpu.vgpr[l][r], cv[l][r], "{name}: lane {l} v{r}"); + } + } + } + } + + /// The integer programs of `lower`'s tests, as `f32_programs_on_the_gpu`. + #[test] + fn integer_programs_on_the_gpu() { + programs_on_the_gpu(&[("integer arithmetic", INT_ARITHMETIC, check_int_arithmetic, &[]), ("integer carries", INT_CARRIES, check_int_carries, &[])]); + } + + /// The f32 programs of `lower`'s tests on the GPU: the HLSL path gives the expected + /// registers (`check_f32_*`, wave32), and the per-lane DXIL gives the HLSL path's, register + /// for register (rcp within `f32_close`: HLSL's `rcp` is a fast fdiv). While the per-lane + /// form refuses a program, that half is SKIPPED with the refusal. + #[test] + fn f32_programs_on_the_gpu() { + programs_on_the_gpu(&[ + ("f32 arithmetic", F32_ARITHMETIC, check_f32_arithmetic, &[]), + ("f32 compares", F32_COMPARES, check_f32_compares, &[]), + ("f32 conversions", F32_CONVERSIONS, check_f32_conversions, &[]), + ("f32 rounding", F32_ROUNDING, check_f32_rounding, &[]), + ("f32 transcendentals", F32_TRANSCENDENTALS, check_f32_transcendentals, &[3, 4]), + ("f32 three-source", F32_THREE_SOURCE, check_f32_three_source, &[]), + ]); + } + + /// A program of `lower`'s tests, the check of its registers on the HLSL path (wave32), and + /// the VGPRs the per-lane form need only match within `f32_close`. + type Program = (&'static str, &'static [I], fn(&[u32], &[Vec]), &'static [usize]); + + /// `f32_programs_on_the_gpu`'s two halves, for any programs. + fn programs_on_the_gpu(programs: &[Program]) { + if !gpu() { + return; + } + if dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let wave64 = runner::wave64_supported() == Ok(true); + for &(name, lines, check, approx) in programs { + for w64 in [false, true] { + let lanes = if w64 { 64 } else { 32 }; + if w64 && !wave64 { + runner::skip_test(&format!("{name}, wave64: no wave64")); + continue; + } + let (s, v) = state(lanes); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let bytes: Vec = lines.iter().flat_map(encode_line).collect(); + let t = translate(&bytes, &Options { wave64: w64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{name}: {:?}", t.unsupported_why); + let hlsl = runner::run(&dxc::compile(&t.hlsl, "main", "cs_6_6", &["-Gis"]).unwrap(), &st, &[]).unwrap(); + if !w64 { + check(&hlsl.sgpr, &hlsl.vgpr[..32]); + } + let insts = decode(lines); + let (dxil, stale) = match super::kernel(&insts, w64) { + Ok(k) => k, + Err(e) => { + runner::skip_test(&format!("{name}, wave{lanes}, per-lane form: refused ({e})")); + continue; + } + }; + let direct = runner::run(&dxil, &st, &[]).unwrap(); + let mut sregs: Vec = vec![106, 126]; + let mut vregs: Vec = Vec::new(); + for d in &insts { + let (r, w) = crate::gpu::rdna2::sgpr_uses(d); + sregs.extend(r.iter().chain(&w).map(|&x| x as usize).filter(|&x| x < 125)); + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + vregs.extend(r.iter().chain(&w).map(|&x| x as usize)); + } + if w64 { + sregs.extend([107, 127]); + } + let stale_at = |r: usize| stale.contains(&(r as u8)) || (w64 && r % 2 == 1 && stale.contains(&(r as u8 - 1))); + for &r in sregs.iter().filter(|&&r| !stale_at(r)) { + assert_eq!(direct.sgpr[r], hlsl.sgpr[r], "{name}, wave{lanes}: s{r}"); + } + for l in 0..lanes { + for &r in &vregs { + let (d, h) = (direct.vgpr[l][r], hlsl.vgpr[l][r]); + let same = if approx.contains(&r) { f32_close(d, h) } else { d == h }; + assert!(same, "{name}, wave{lanes}: lane {l} v{r}: {d:#x} against {h:#x}"); + } + } + } + } + } + + /// 2-D and 3-D groups in the per-lane form: the threads numbered as the waves arrive + /// (`Lw::setup_lanes_compute`), each wave's lanes the console's consecutive threads, as the + /// lowering run on the CPU has them. + #[test] + fn a_per_lane_2d_or_3d_group_runs_on_the_gpu() { + if !gpu() { + return; + } + for wave64 in [false, true] { + if wave64 && runner::wave64_supported() != Ok(true) { + runner::skip_test("no wave64"); + return; + } + for threads in ID_SHAPES { + let lines = ids_program(threads, wave64); + let cs = ids_cs(threads); + let dxil = super::compute(&decode(&lines), &cs, wave64).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [2, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute_waves(&lines, &cs, wave64, 2, &[100, 0], &mem); + assert_eq!(&gpu[..128], &cpu[..128], "{threads:?} wave64 {wave64}"); + } + } + } + + /// A wave64 program in the split form through `compute_with` (the runtime's path on a GPU + /// with 32-lane waves only): 32-lane hardware waves (`WaveSize(32)`, not 64), the console's + /// wave64 results (MiguelMachado-dev found `compute_with` passing 64). + #[test] + fn the_runtime_path_takes_the_split_form() { + if !gpu() { + return; + } + for threads in ID_SHAPES { + let lines = ids_program(threads, true); + let cs = ids_cs(threads); + let bytes: Vec = lines.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); + let o = super::KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let k = super::compute_with(&bytes, &cs, o).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&k.dxil, [2, 1, 1], &[100, 0], &mem).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let cpu = run_compute_waves(&lines, &cs, true, 2, &[100, 0], &mem); + assert_eq!(&gpu[..128], &cpu[..128], "{threads:?}"); + } + } + + /// The f64 program of `lower`'s tests, as `f32_programs_on_the_gpu`. + #[test] + fn f64_programs_on_the_gpu() { + programs_on_the_gpu(&[("f64", F64_ARITHMETIC, check_f64, &[])]); + } + + #[test] + fn a_per_lane_compute_program_runs_on_the_gpu() { + if !gpu() { + return; + } + let cs = compute_cs(); + let dxil = super::compute(&decode(COMPUTE), &cs, false).unwrap(); + let mem = vec![0u32; 256]; + let gpu = runner::dispatch(&dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&gpu[..cpu.len()], &cpu[..]); + // and the HLSL path, for good measure + if dxc::location().is_ok() { + let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); + let t = translate(&bytes, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + let hlsl = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + assert_eq!(runner::dispatch(&hlsl, [3, 1, 1], &[100, 0], &mem).unwrap(), gpu); + } + } + + /// With the runtime's four memory windows (`compute_with`), the memory instructions go + /// through #1426's window switch (blocks of its own in the `Ir` block) and the program + /// still gives the CPU lowering's memory. + #[test] + fn a_per_lane_program_with_four_memory_windows_runs_on_the_gpu() { + let cs = compute_cs(); + let bytes: Vec = COMPUTE.iter().flat_map(|(n, e, f)| crate::gpu::rdna2::encode(n, e, f, None).unwrap()).collect(); + let o = super::KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; + if !gpu() { + return; + } + let k = super::compute_with(&bytes, &cs, o).unwrap(); + let mem = vec![0u32; 256]; + let out = runner::dispatch(&k.dxil, [3, 1, 1], &[100, 0], &mem).unwrap(); + let cpu = run_compute(COMPUTE, &cs, 3, &[100, 0], &mem); + assert_eq!(&out[..cpu.len()], &cpu[..]); + } + + /// Coalesced guarded runs lowered through `Ir::foreign` (`Lw::inst_guarded` with `guard = true` + /// inside the run's block): f32 arithmetic against HLSL, and 4-window memory load/store inside + /// a coalesced run (wave32 and split wave64, `Lw` making window-switch blocks inside the run) + /// against the CPU lowering. + #[test] + fn coalesced_foreign_runs_agree_on_the_gpu() { + if !gpu() { + return; + } + // 4-window compute: lanes below the cut (16 in wave32; 40 in split wave64, spanning both + // wave32 halves) run a coalesced load + add + store via `foreign` + let cs = compute_cs(); + let mem = memory_image(); + for (wave64, split) in [(false, false), (true, true)] { + let run = coalesced_run(wave64); + let bytes: Vec = run.iter().flat_map(encode_line).collect(); + let o = super::KernelOptions { wave64, split, mem_windows: 4, sampler_base: 0 }; + let k = super::compute_with(&bytes, &cs, o).unwrap(); + let out = runner::dispatch(&k.dxil, [1, 1, 1], &[0, 0], &mem).unwrap(); + let cpu = run_compute_waves(&run, &cs, wave64, 1, &[0, 0], &mem); + assert_eq!(&out[..cpu.len()], &cpu[..], "4-window coalesced memory via foreign (wave64={wave64}, split={split})"); + } + + if dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } + let (s, v) = state(32); + let mut st = runner::KernelState::default(); + st.sgpr.copy_from_slice(&s); + for (l, regs) in v.iter().enumerate() { + st.vgpr[l][..regs.len()].copy_from_slice(regs); + } + let bytes: Vec = COALESCED_F32_RUN.iter().flat_map(encode_line).collect(); + let t = translate(&bytes, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let hlsl = runner::run(&dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(), &st, &[]).unwrap(); + let (dxil, _) = super::kernel(&decode(COALESCED_F32_RUN), false).unwrap(); + let direct = runner::run(&dxil, &st, &[]).unwrap(); + for l in 0..32 { + for r in 0..=5 { + assert_eq!(direct.vgpr[l][r], hlsl.vgpr[l][r], "lane {l} v{r}"); + } + } + assert_eq!((direct.sgpr[106], direct.sgpr[126]), (hlsl.sgpr[106], hlsl.sgpr[126])); + } +} diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 71012d565c..1a1a8ba79d 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -52,6 +52,10 @@ //! `ByteAddressBuffer` (`mem`); initial SGPRs (user data) come from `io`. Textures come next. pub mod dxc; +pub mod dxil; +pub mod lane_masks; +pub mod lower; +pub mod lower_dxil; pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; @@ -59,6 +63,7 @@ pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; pub mod runner; +pub mod ssa; #[cfg(test)] mod tests; #[cfg(test)] @@ -629,6 +634,12 @@ impl Conts { /// leaves at its next iteration and the program runs to its end. const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;"; +/// Structured code longer than this many bytes per byte of program falls back to the `pc` form. +/// Each guard of the structured form lists every pending skip flag, so it grows with the +/// square of the flags: one retail program made 455 B per byte (148 MB, 14 MB as `pc` blocks), +/// the next largest 61 (#1307). +const STRUCTURED_BYTES_PER_CODE_BYTE: usize = 128; + /// The loops the translator emits: ranges spanned by backward jumps (far jumps included), /// partly overlapping ones merged until they nest, sorted. `x64_masks` uses them for the /// exits through `LOOP_GUARD`. @@ -1378,6 +1389,7 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> B } pub fn translate(code: &[u8], opt: &Options) -> Result { + let program = code; let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; @@ -1482,6 +1494,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // structured control flow: plain if / loops, no block dispatch on `pc` (much // smaller for DXC and the driver on big programs) emit_structured(&sctx, &mut em, &mut code, 0, u64::MAX, None, 0, &Conts::default(), &BTreeSet::new(), 1, &mut blocks, &mut flags); + if code.len() > STRUCTURED_BYTES_PER_CODE_BYTE * program.len() { + return translate(program, &Options { structured: false, ..opt.clone() }); + } } else { if gs_jump.is_some() && opt.split_wave64 && opt.wave64 { code.push_str(" uint pc = xcl_entry_pc;\n"); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 496543a53c..8a8b95b065 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -235,12 +235,18 @@ mod translated { if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { return 0; } - identity_with( + let id = identity_with( env!("XCL_TRANSLATOR_SOURCE_ID"), super::dxc::toolchain_identity(), Backend::current(), crate::gpu::dxil::kernel::TRANSLATOR_VERSION, - ) + ); + // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity + if Backend::current() != Backend::Hlsl && crate::gpu::recomp::lower_dxil::enabled() { + identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) + } else { + id + } }) } @@ -605,6 +611,20 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::detect_wave64(code); let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base }; + // `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses + if super::lower_dxil::enabled() { + match super::lower_dxil::compute_with(code, &cs, o) { + Ok(k) => { + crate::gpu::dxil::coverage::record_translated("CS per-lane"); + dump_direct(blob, &k.dxil); + return Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }); + } + Err(e) => { + let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); + crate::xlog_info!("[SHADER] per-lane fallback reason=\"{reason}\" detail=\"{}\" – per-instruction form", e.lines().next().unwrap_or("")); + } + } + } let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?; dump_direct(blob, &k.dxil); Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }) @@ -791,6 +811,20 @@ pub fn graphics_wave32_for_device(device: &ID3D12Device) -> bool { pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { let (code, g) = super::geometry_program(vs, gs)?; let record = g.record(); + // `XCL_DIRECT_DXIL=1`: the compute pass through the direct DXIL translator (HLSL fallback) + if crate::gpu::dxil::kernel::enabled() { + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: split_wave64, mem_windows: mem_windows(), sampler_base: 0 }; + match crate::gpu::dxil::kernel::translate_geometry(&code, o, &g) { + Ok(k) => { + crate::gpu::dxil::coverage::record_translated("GS"); + let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0); + let msb = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0; + let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref())); + return Ok(TwoPass { cs: k.dxil, ms: msb, record, mesh_groups_per_record, samplers: k.static_samplers }); + } + Err(e) => direct_fallback("GS", &e), + } + } let translation = super::translate_geometry(&code, g, split_wave64, mem_windows())?; finish_two_pass(translation, record, ps) } diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index f647dbd2c6..7ddd3889b8 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -136,6 +136,21 @@ pub enum TexDim { Cube, /// Typed buffer (test only): `width` elements of `format`, `height` = `depth` = 1. Buffer, + /// Multisampled 2D texture with this many samples (SRV only). `data` holds every + /// sample: texel (x, y) sample s at `((y · width + x) · samples + s) · texel_bytes`; + /// `format` needs 32-bit channels (the samples are written by a per-sample draw). + D2Ms(u32), + /// Multisampled 2D array (`depth` slices, laid out as `D2Ms` slice after slice). + D2MsArray(u32), +} + +impl TexDim { + fn samples(self) -> Option { + match self { + TexDim::D2Ms(n) | TexDim::D2MsArray(n) => Some(n), + _ => None, + } + } } /// A texture for kernel tests: SRV at heap index 2·i, UAV (if `uav`) at 2·i + 1. @@ -161,6 +176,8 @@ pub struct TestSampler { struct Bound { _heaps: [ID3D12DescriptorHeap; 2], + /// what the multisampled-texture fill draws use (alive until the list ran) + _msaa: Vec, textures: Vec<(ID3D12Resource, Vec, u64)>, _upload: Option, } @@ -208,7 +225,27 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t let mut descs = Vec::new(); let mut total = 0u64; let mut plans = Vec::new(); + let mut msaa_plans = Vec::new(); for t in textures { + if let Some(n) = t.dim.samples() { + // the samples go through a raw buffer read by the fill draw (+16: Load4 at the end) + let size = t.data.len() as u64 + 16; + msaa_plans.push(total); + total = (total + size + 511) & !511; + descs.push(D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: t.width as u64, + Height: t.height, + DepthOrArraySize: t.depth as u16, + MipLevels: 1, + Format: t.format, + SampleDesc: DXGI_SAMPLE_DESC { Count: n, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }); + plans.push(Vec::new()); + continue; + } let (dim, depth_or_array) = match t.dim { TexDim::D3 => (D3D12_RESOURCE_DIMENSION_TEXTURE3D, t.depth), _ => (D3D12_RESOURCE_DIMENSION_TEXTURE2D, t.depth), @@ -249,7 +286,12 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t if let Some(up) = &upload { let mut p = std::ptr::null_mut(); up.Map(0, None, Some(&mut p)).map_err(e)?; - for (t, fps) in textures.iter().zip(&plans) { + let mut mk = 0; + for t in textures.iter().filter(|t| t.dim.samples().is_some()) { + std::ptr::copy_nonoverlapping(t.data.as_ptr(), (p as *mut u8).add(msaa_plans[mk] as usize), t.data.len()); + mk += 1; + } + for (t, fps) in textures.iter().zip(&plans).filter(|(t, _)| t.dim.samples().is_none()) { let row = (t.width * t.texel_bytes) as usize; let slices = t.depth as usize; for z in 0..slices { @@ -265,7 +307,25 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t } up.Unmap(0, None); } + let mut msaa = Vec::new(); + let mut mk = 0; for (i, ((t, rd), fps)) in textures.iter().zip(&descs).zip(&plans).enumerate() { + if t.dim.samples().is_some() { + assert!(!t.uav, "multisampled test textures are SRVs"); + let f = msaa_fill(dev, list, t, rd, upload.as_ref().unwrap(), msaa_plans[mk])?; + mk += 1; + let mut sv = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: t.format, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; + if let TexDim::D2MsArray(_) = t.dim { + sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; + sv.Anonymous.Texture2DMSArray = D3D12_TEX2DMS_ARRAY_SRV { FirstArraySlice: 0, ArraySize: t.depth }; + } else { + sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS; + } + dev.CreateShaderResourceView(&f.tex, Some(&sv), at(&heap, 2 * i, inc)); + out.push((f.tex.clone(), Vec::new(), 0)); + msaa.push(f); + continue; + } let mut r: Option = None; dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, rd, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r) .map_err(e)?; @@ -311,6 +371,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; uv.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { ArraySize: t.depth, ..Default::default() }; } + TexDim::D2Ms(_) | TexDim::D2MsArray(_) => unreachable!(), TexDim::Buffer => { sv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; sv.Anonymous.Buffer = D3D12_BUFFER_SRV { NumElements: t.width, ..Default::default() }; @@ -331,7 +392,97 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t out.push((r, rfps, readable)); } list.SetDescriptorHeaps(&[Some(heap.clone()), Some(sheap.clone())]); - Ok(Bound { _heaps: [heap, sheap], textures: out, _upload: upload }) + Ok(Bound { _heaps: [heap, sheap], _msaa: msaa, textures: out, _upload: upload }) +} + +struct MsaaFill { + tex: ID3D12Resource, + _data: ID3D12Resource, + _pso: ID3D12PipelineState, + _rs: ID3D12RootSignature, + _rtv: ID3D12DescriptorHeap, +} + +/// Write every sample of a multisampled test texture: a full-screen draw per slice whose +/// pixel shader runs per sample (`SV_SampleIndex`) and returns the sample's bits from u0. +/// Leaves `list` with another pipeline and root signature bound. +unsafe fn msaa_fill(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t: &TestTexture, rd: &D3D12_RESOURCE_DESC, upload: &ID3D12Resource, at: u64) -> Result { + let n = t.dim.samples().unwrap(); + assert!(t.texel_bytes % 4 == 0 && t.texel_bytes <= 16, "multisampled test textures need 32-bit channels"); + let ty = match t.format { + DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_R32G32_FLOAT | DXGI_FORMAT_R32G32B32A32_FLOAT => "float4", + DXGI_FORMAT_R32_UINT | DXGI_FORMAT_R32G32_UINT | DXGI_FORMAT_R32G32B32A32_UINT => "uint4", + DXGI_FORMAT_R32_SINT | DXGI_FORMAT_R32G32_SINT | DXGI_FORMAT_R32G32B32A32_SINT => "int4", + _ => return Err(format!("multisampled test texture format {:?}", t.format)), + }; + // u0: the samples of this slice + let src = format!( + "RWByteAddressBuffer D : register(u0);\n\ + float4 vs(uint id : SV_VertexID) : SV_Position {{ float2 p = float2((id << 1) & 2, id & 2); return float4(p * float2(2, -2) + float2(-1, 1), 0, 1); }}\n\ + {ty} ps(float4 pos : SV_Position, uint s : SV_SampleIndex) : SV_Target {{\n\ + uint2 xy = uint2(pos.xy);\n\ + uint i = ((xy.y * {w}u + xy.x) * {n}u + s) * {b}u;\n\ + uint4 v = D.Load4(i);\n\ + uint k = {b}u / 4u; v = uint4(v.x, k > 1u ? v.y : 0u, k > 2u ? v.z : 0u, k > 3u ? v.w : 0u);\n\ + return ({ty})({conv}(v));\n\ + }}\n", + w = t.width, + b = t.texel_bytes, + conv = if ty == "float4" { "asfloat" } else { "" }, + ); + let vs = super::dxc::compile(&src, "vs", "vs_6_6", &[])?; + let ps = super::dxc::compile(&src, "ps", "ps_6_6", &[])?; + let rs = root_signature(dev, false)?; + let mut pd = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as _, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as _, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: n, Quality: 0 }, + ..Default::default() + }; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = true.into(); + pd.RTVFormats[0] = t.format; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|x| format!("CreateGraphicsPipelineState (MSAA fill): {x}"))?; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, rd, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut r) + .map_err(|x| format!("MSAA texture: {x}"))?; + let tex = r.ok_or("texture")?; + let size = t.data.len() as u64 + 16; + let data = buffer(dev, size, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?; + list.CopyBufferRegion(&data, 0, upload, at, size); + list.ResourceBarrier(&[transition(&data, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + let rtv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: t.depth.max(1), ..Default::default() }) + .map_err(e)?; + let rinc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + list.SetPipelineState(&pso); + list.SetGraphicsRootSignature(&rs); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: t.width as f32, Height: t.height as f32, MinDepth: 0.0, MaxDepth: 1.0 }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { left: 0, top: 0, right: t.width as i32, bottom: t.height as i32 }]); + let slice_bytes = (t.width * t.height * n * t.texel_bytes) as u64; + for z in 0..t.depth.max(1) { + let h = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: rtv_heap.GetCPUDescriptorHandleForHeapStart().ptr + z as usize * rinc }; + let mut rv = D3D12_RENDER_TARGET_VIEW_DESC { Format: t.format, ..Default::default() }; + if let TexDim::D2MsArray(_) = t.dim { + rv.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; + rv.Anonymous.Texture2DMSArray = D3D12_TEX2DMS_ARRAY_RTV { FirstArraySlice: z, ArraySize: 1 }; + } else { + rv.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS; + } + dev.CreateRenderTargetView(&tex, Some(&rv), h); + list.OMSetRenderTargets(1, Some(&h), false, None); + list.SetGraphicsRootUnorderedAccessView(0, data.GetGPUVirtualAddress() + z as u64 * slice_bytes); + list.DrawInstanced(3, 1, 0, 0); + } + list.ResourceBarrier(&[transition(&tex, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)]); + Ok(MsaaFill { tex, _data: data, _pso: pso, _rs: rs, _rtv: rtv_heap }) } fn buffer(dev: &ID3D12Device, size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, uav: bool) -> Result { @@ -537,6 +688,8 @@ pub fn run_with_statics( transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), ]); let bound = bind_resources(dev, &list, textures, samplers)?; + // multisampled test textures were filled by draws + list.SetPipelineState(&pso); list.SetComputeRootSignature(&rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); diff --git a/crates/xcl/src/gpu/recomp/ssa.rs b/crates/xcl/src/gpu/recomp/ssa.rs new file mode 100644 index 0000000000..0a7fd4698d --- /dev/null +++ b/crates/xcl/src/gpu/recomp/ssa.rs @@ -0,0 +1,304 @@ +//! SSA form of the console registers for the direct DXIL lowering, built while the blocks are +//! lowered (the on-the-fly construction of Braun et al., "Simple and Efficient Construction of +//! Static Single Assignment Form", CC 2013). +//! +//! Every register dword (s0–s127, v0–v255, SCC) is a variable. The lowering writes a variable +//! when an instruction defines it and reads it when one uses it; a read in a block without a +//! definition looks through the predecessors, placing a phi where they can disagree. A block +//! whose predecessors are not all lowered yet (a loop head, before its back edges) is *unsealed*: +//! its phis are left incomplete and filled in when it is sealed. A phi whose operands are all one +//! value (or itself) is trivial and is replaced by that value, through the sink's `replace`. +//! +//! The values themselves live in the DXIL module; this only decides where phis go. The sink is +//! the module builder. + +use std::collections::HashMap; +use std::hash::Hash; + +/// A register dword of the console program: what the SSA form tracks. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum Var { + /// s as a number (`i32`) + S(u8), + /// the lane's bit of the mask held in s (wave64: the pair from s) (`i1`) + M(u8), + V(u16), + Scc, +} + +/// What the construction needs from the module builder. +pub trait Sink { + type V: Copy + Eq + Hash + std::fmt::Debug; + /// A new phi at the top of `block` for `var` (`i1` for SCC, `i32` for a register). + fn phi(&mut self, block: usize, var: Var) -> Self::V; + fn incoming(&mut self, phi: Self::V, value: Self::V, pred: usize); + /// Every use of `old` becomes `new`, and `old` (a trivial phi) is dropped. + fn replace(&mut self, old: Self::V, new: Self::V); + /// The value of a variable read before any definition reaches it. + fn undef(&mut self, var: Var) -> Self::V; +} + +pub struct Ssa { + preds: Vec>, + defs: Vec>, + sealed: Vec, + /// per unsealed block: the phis placed before its predecessors were known + incomplete: Vec>, + /// the operands of each live phi, and the phis that use each value + operands: HashMap>, + users: HashMap>, + /// trivial phis removed → what replaced them + forward: HashMap, +} + +impl Ssa { + /// `preds[b]`: the predecessors of block b, all of them, back edges included. + pub fn new(preds: Vec>) -> Self { + let n = preds.len(); + Ssa { + preds, + defs: vec![HashMap::new(); n], + sealed: vec![false; n], + incomplete: vec![Vec::new(); n], + operands: HashMap::new(), + users: HashMap::new(), + forward: HashMap::new(), + } + } + + /// What a value stands for now: itself, or what replaced it as a trivial phi. + pub fn resolve_value(&self, v: V) -> V { + self.resolve(v) + } + + /// The operands of a live phi (None for any other value). + pub fn phi_operands(&self, v: V) -> Option<&[V]> { + self.operands.get(&v).map(|o| o.as_slice()) + } + + fn resolve(&self, mut v: V) -> V { + while let Some(&n) = self.forward.get(&v) { + v = n; + } + v + } + + pub fn write(&mut self, block: usize, var: Var, value: V) { + self.defs[block].insert(var, value); + } + + pub fn read>(&mut self, sink: &mut S, block: usize, var: Var) -> V { + if let Some(&v) = self.defs[block].get(&var) { + return self.resolve(v); + } + let v = if !self.sealed[block] { + let phi = self.new_phi(sink, block, var); + self.incomplete[block].push((var, phi)); + phi + } else if self.preds[block].len() == 1 { + let p = self.preds[block][0]; + self.read(sink, p, var) + } else if self.preds[block].is_empty() { + sink.undef(var) + } else { + // the phi is the definition while its operands are read (a loop through here) + let phi = self.new_phi(sink, block, var); + self.write(block, var, phi); + self.add_operands(sink, block, var, phi) + }; + self.write(block, var, v); + v + } + + /// Every predecessor of `block` has been lowered: complete its phis. + pub fn seal>(&mut self, sink: &mut S, block: usize) { + for (var, phi) in std::mem::take(&mut self.incomplete[block]) { + self.add_operands(sink, block, var, phi); + } + self.sealed[block] = true; + } + + fn new_phi>(&mut self, sink: &mut S, block: usize, var: Var) -> V { + let phi = sink.phi(block, var); + self.operands.insert(phi, Vec::new()); + phi + } + + fn add_operands>(&mut self, sink: &mut S, block: usize, var: Var, phi: V) -> V { + for p in self.preds[block].clone() { + let v = self.read(sink, p, var); + sink.incoming(phi, v, p); + self.operands.get_mut(&phi).expect("live phi").push(v); + self.users.entry(v).or_default().push(phi); + } + self.remove_trivial(sink, phi) + } + + fn remove_trivial>(&mut self, sink: &mut S, phi: V) -> V { + let mut same = None; + for &op in &self.operands[&phi] { + let op = self.resolve(op); + if Some(op) == same || op == phi { + continue; + } + if same.is_some() { + return phi; + } + same = Some(op); + } + let Some(same) = same else { return phi }; // only reachable through itself: kept + sink.replace(phi, same); + self.forward.insert(phi, same); + self.operands.remove(&phi); + // phis that used this one may have become trivial in turn + for user in self.users.remove(&phi).unwrap_or_default() { + if user != phi && self.operands.contains_key(&user) { + self.remove_trivial(sink, user); + } + } + same + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Records what the construction asks of a module builder. + #[derive(Default)] + struct Log { + next: u32, + phis: Vec<(u32, usize, Var)>, + incoming: Vec<(u32, u32, usize)>, + replaced: Vec<(u32, u32)>, + } + + impl Log { + fn value(&mut self) -> u32 { + self.next += 1; + self.next + } + fn live_phis(&self) -> Vec { + self.phis.iter().map(|p| p.0).filter(|p| !self.replaced.iter().any(|r| r.0 == *p)).collect() + } + } + + impl Sink for Log { + type V = u32; + fn phi(&mut self, block: usize, var: Var) -> u32 { + let v = self.value(); + self.phis.push((v, block, var)); + v + } + fn incoming(&mut self, phi: u32, value: u32, pred: usize) { + self.incoming.push((phi, value, pred)); + } + fn replace(&mut self, old: u32, new: u32) { + self.replaced.push((old, new)); + } + fn undef(&mut self, _: Var) -> u32 { + 0 + } + } + + const R: Var = Var::V(3); + + #[test] + fn a_straight_line_needs_no_phi() { + // 0 → 1 → 2 + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0], vec![1]]), Log::default()); + let a = log.value(); + ssa.write(0, R, a); + for b in 0..3 { + ssa.seal(&mut log, b); + } + assert_eq!(ssa.read(&mut log, 2, R), a); + assert!(log.phis.is_empty()); + } + + #[test] + fn a_diamond_joins_two_definitions() { + // 0 → {1, 2} → 3, each arm defines R + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0], vec![0], vec![1, 2]]), Log::default()); + let (a, b) = (log.value(), log.value()); + for blk in 0..4 { + ssa.seal(&mut log, blk); + } + ssa.write(1, R, a); + ssa.write(2, R, b); + let j = ssa.read(&mut log, 3, R); + assert_eq!(log.live_phis(), vec![j]); + assert_eq!(log.incoming, vec![(j, a, 1), (j, b, 2)]); + } + + #[test] + fn one_arm_defining_still_joins_with_the_value_from_before() { + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0], vec![0], vec![1, 2]]), Log::default()); + let (a, b) = (log.value(), log.value()); + for blk in 0..4 { + ssa.seal(&mut log, blk); + } + ssa.write(0, R, a); + ssa.write(1, R, b); + let j = ssa.read(&mut log, 3, R); + assert_eq!(log.incoming, vec![(j, b, 1), (j, a, 2)]); + } + + #[test] + fn a_loop_that_changes_the_register_keeps_its_phi() { + // 0 → 1 (head) → 2 (body) → 1, 1 → 3 (exit); the body increments R + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0, 2], vec![1], vec![1]]), Log::default()); + let a = log.value(); + ssa.seal(&mut log, 0); + ssa.write(0, R, a); + let head = ssa.read(&mut log, 1, R); // head not sealed yet: incomplete phi + ssa.seal(&mut log, 2); + let body_in = ssa.read(&mut log, 2, R); + assert_eq!(body_in, head); + let inc = log.value(); + ssa.write(2, R, inc); + ssa.seal(&mut log, 1); // back edge known + ssa.seal(&mut log, 3); + assert_eq!(ssa.read(&mut log, 3, R), head); + assert_eq!(log.live_phis(), vec![head]); + assert_eq!(log.incoming, vec![(head, a, 0), (head, inc, 2)]); + } + + #[test] + fn a_loop_that_leaves_the_register_alone_drops_its_phi() { + let (mut ssa, mut log) = (Ssa::new(vec![vec![], vec![0, 2], vec![1], vec![1]]), Log::default()); + let a = log.value(); + ssa.seal(&mut log, 0); + ssa.write(0, R, a); + let head = ssa.read(&mut log, 1, R); + ssa.seal(&mut log, 2); + let _ = ssa.read(&mut log, 2, R); + ssa.seal(&mut log, 1); + ssa.seal(&mut log, 3); + assert_eq!(log.replaced, vec![(head, a)]); + assert!(log.live_phis().is_empty()); + assert_eq!(ssa.read(&mut log, 3, R), a, "reads after the removal see the replacement"); + } + + #[test] + fn removing_a_phi_cascades_to_the_phis_built_on_it() { + // nested loops that never change R: inner head 2's phi uses outer head 1's phi + // 0 → 1 → 2 → 3 → 2, 3 → 4 → 1, 4 → 5 + let preds = vec![vec![], vec![0, 4], vec![1, 3], vec![2], vec![3], vec![4]]; + let (mut ssa, mut log) = (Ssa::new(preds), Log::default()); + let a = log.value(); + ssa.seal(&mut log, 0); + ssa.write(0, R, a); + let outer = ssa.read(&mut log, 1, R); + let inner = ssa.read(&mut log, 2, R); + ssa.seal(&mut log, 3); + let _ = ssa.read(&mut log, 3, R); + ssa.seal(&mut log, 2); + ssa.seal(&mut log, 4); + let _ = ssa.read(&mut log, 4, R); + ssa.seal(&mut log, 1); + ssa.seal(&mut log, 5); + assert!(log.live_phis().is_empty(), "both heads' phis go: {:?} {:?}", outer, inner); + assert_eq!(ssa.read(&mut log, 5, R), a); + } +} diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 846cb5cd86..e1f73ef484 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3946,12 +3946,25 @@ fn gpu_geometry_wave32_prefix_count_over_a_mask() { assert!(windowed.hlsl.contains("RWByteAddressBuffer mem3 : register(u5)")); super::dxc::compile(&windowed.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); // the native wave64 form keeps the program, and computes the reference where it can run - let native = translate_geometry(&code, g, false, 1).unwrap(); + let native = translate_geometry(&code, g.clone(), false, 1).unwrap(); if runner::wave64_supported() == Ok(true) { run(&native); } else { runner::skip_test("no wave64"); } + // the direct DXIL translator's compute pass computes the same, split and native + let direct = |split: bool| { + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }; + let cs = crate::gpu::dxil::kernel::translate_geometry(&code, o, &g).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(2000)])).dxil; + let mem = runner::dispatch(&cs, [1, 1, 1], &io, &vec![0u32; 0x400 / 4 + 3 * 64]).unwrap(); + let got: Vec<[u32; 3]> = (0..64).map(|l| [0, 1, 2].map(|k| mem[0x100 + 64 * k + l])).collect(); + let wrong: Vec<_> = (0..64).filter(|&l| got[l] != want[l]).map(|l| (l, got[l], want[l])).collect(); + assert!(wrong.is_empty(), "direct split {split} (got [vcc, s[10:11], exec], want): {wrong:?}"); + }; + direct(true); + if runner::wave64_supported() == Ok(true) { + direct(false); + } } /// A DS read whose destination overlaps its address register reads the address first @@ -7594,6 +7607,38 @@ fn fspx_containers_translate_and_compile() { assert_eq!(ok, n); } +/// Structured code past `STRUCTURED_BYTES_PER_CODE_BYTE` is translated in the `pc` form (#1307). +/// n conditional forward jumps whose targets all come after them, in the same order, keep up to +/// n skip flags pending, and every guard lists them: 200 cross the bound, 50 do not. This checks +/// the switch only. Here the `pc` form keeps the same stretch under one `pc` guard and is no +/// smaller; the gain is on programs whose `pc` form is split into blocks, such as the retail +/// one of #1307 (148 MB -> 14 MB). +#[test] +fn oversized_structured_code_falls_back_to_pc_blocks() { + let crossing = |n: usize| { + let i = |name: &str, e: &str, f: &[(&str, u64)]| encode(name, e, f, None).unwrap(); + let mut code: Vec = Vec::new(); + let mut at = Vec::new(); + for k in 0..n as u64 { + code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)])); + code.extend(i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128 + k % 16)])); + at.push(code.len()); + code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)])); + } + for a in at { + let d = ((code.len() - a) / 4 - 1) as u16; + code[a..a + 2].copy_from_slice(&d.to_le_bytes()); + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 0), ("VSRC1", 1)])); + } + code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + let t = translate(&code, &Options::default()).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + t.hlsl.contains("pc ==") + }; + assert!(!crossing(50), "50 crossing jumps: structured"); + assert!(crossing(200), "200 crossing jumps: past the bound, pc blocks"); +} + /// Random nests of loops with `continue` / `break` of any loop around them – backward jumps out of /// inner loops, loops whose end is an inner loop's – give the same state as structured code and as /// the block dispatcher (`structured: false`). diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 336abd93fb..333ac9778b 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -255,6 +255,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + let (console_args_off, console_count_off) = (args_off, count_off); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if !gfx && !compute { // A pipeline still being built (or whose build failed): its stand-in draws nothing, and @@ -287,7 +288,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { list.SetGraphicsRootSignature(r); } - return pc(this, sig, max, args, args_off, count_buf, count_off); + return fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); } if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -297,19 +298,86 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - match bind_abi(this, list, pso, gfx) { - Ok(()) => { - count(if gfx { DRAWS } else { DISPATCHES }); - pc(this, sig, max, args, args_off, count_buf, count_off) + // the records bounded on the GPU first (a garbage record would hang it): this changes the + // list's compute bindings, which `bind_abi` sets again + let bounded = super::indirect_clamp::bound(list, with(this, |s| s.allocator), sig, max, args, console_args_off, count_buf, console_count_off); + let result = bind_abi(this, list, pso, gfx); + if let Ok(()) = result { + count(if gfx { DRAWS } else { DISPATCHES }); + fresh_indirect_arguments(this, || match &bounded { + Some(b) => pc(this, sig, max, b.raw(), 0, count_buf, count_off), + None => pc(this, sig, max, args, args_off, count_buf, count_off), + }); + } + if let Some(b) = bounded { + b.finish(list); + } + if let Err(e) = result { + count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect with a translated pipeline skipped: {e}"); } - Err(e) => { - count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect with a translated pipeline skipped: {e}"); - } + } +} + +/// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses +static ARGUMENT_ORDER: Mutex> = Mutex::new(None); + +/// `op` (an ExecuteIndirect on `list`) reading the arguments and count the list wrote before it. +/// +/// The console orders a dispatch that writes indirect arguments before the ExecuteIndirect that +/// reads them with a barrier that reaches the PC as a UAV barrier (`list_x::resource_barrier_x`). +/// NVIDIA's driver (RTX 5090) fetches an ExecuteIndirect's arguments without waiting for that +/// barrier: it ran the count that was there before the list in all but a few of 100 tries, also +/// when the dispatch wrote them through another resource over the same memory, as translated +/// shaders do through the memory window buffers (`execute_indirect_reads_the_arguments_written_before_it`). +/// A retail title's ExecuteIndirect after the dispatch that writes its group count then runs +/// whatever count the memory held before. A transition to INDIRECT_ARGUMENT makes the driver +/// wait for the writes – of any buffer, as measured there. The title's buffer is in the title's +/// state (its transitions reach the PC list), so a buffer of XCL's own takes it, COMMON -> +/// INDIRECT_ARGUMENT before and back after. Only on a list XCL made (`list_x::on_create`) and +/// not a bundle, which cannot hold barriers; its type comes from XCL's state, not a call to it. +unsafe fn fresh_indirect_arguments(list: *mut c_void, op: impl FnOnce()) { + let tracked = super::list_x::tracked_list_type(list).is_some_and(|t| t != D3D12_COMMAND_LIST_TYPE_BUNDLE); + let buffer = if tracked { ID3D12GraphicsCommandList::from_raw_borrowed(&list).and_then(|l| argument_order_buffer(l)) } else { None }; + let Some(buffer) = buffer else { return op() }; + let b = buffer.as_raw() as usize; + super::list_x::transition(list, b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + op(); + super::list_x::transition(list, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); +} + +/// The device's buffer for `fresh_indirect_arguments` (made on first use) +unsafe fn argument_order_buffer(list: &ID3D12GraphicsCommandList) -> Option { + let mut dev: Option = None; + list.GetDevice(&mut dev).ok()?; + let dev = dev?; + let mut g = ARGUMENT_ORDER.lock().unwrap(); + if let Some((_, b)) = g.as_ref().filter(|(d, _)| *d == dev.as_raw() as usize) { + return Some(b.clone()); + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut b: Option = None; + if let Err(e) = dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut b) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect: no buffer to order its arguments after the writes before it ({e}) – it may read old ones"); } + return None; } + let b = b?; + *g = Some((dev.as_raw() as usize, b.clone())); + Some(b) } /// A DrawInstanced of the console's rect list (three corners of each rectangle, the fourth @@ -991,6 +1059,134 @@ mod tests { assert!(!pso_async::is_pending(building)); } + /// A dispatch writes an ExecuteIndirect's group count through another buffer over the same + /// memory (as translated shaders write through the memory windows), a UAV barrier (what a + /// console barrier becomes), then the ExecuteIndirect: it runs the count just written, not + /// the one the memory held before the list (`fresh_indirect_arguments`; without it an RTX + /// 5090 ran the old count in nearly every try). + #[test] + fn execute_indirect_reads_the_arguments_written_before_it() { + use crate::gpu::{fence, recomp::runner::skip_test}; + use std::mem::{transmute_copy, ManuallyDrop}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + const TRIES: u32 = 40; + // mode 0: write (x, 1, 1) at a[0..12]; mode 1: count the groups + let src = r#" +#define RS "RootConstants(num32BitConstants=2, b0), UAV(u0), UAV(u1)" +cbuffer C : register(b0) { uint mode; uint x; }; +RWByteAddressBuffer a : register(u0); +RWByteAddressBuffer c : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint t : SV_GroupIndex) { + if (t != 0u) return; + if (mode == 0u) a.Store3(0, uint3(x, 1u, 1u)); else c.InterlockedAdd(0, 1u); +} +"#; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let dxil = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let cs = D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: cs, ..Default::default() }).unwrap(); + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }, None, &mut sig).unwrap(); + let sig = sig.unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let desc = |width| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + // the arguments and the buffer the dispatch writes them through: one memory + let mut heap: Option = None; + let heap_desc = D3D12_HEAP_DESC { SizeInBytes: 1 << 16, Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; + dev.CreateHeap(&heap_desc, &mut heap).unwrap(); + let heap = heap.unwrap(); + let placed = || { + let mut r: Option = None; + dev.CreatePlacedResource(&heap, 0, &desc(1 << 16), D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + let (args, written) = (placed(), placed()); + // the group count, read on the CPU + let cpu_heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + let mut groups: Option = None; + dev.CreateCommittedResource(&cpu_heap, D3D12_HEAP_FLAG_NONE, &desc(256), D3D12_RESOURCE_STATE_COMMON, None, &mut groups).unwrap(); + let groups = groups.unwrap(); + let mut count = std::ptr::null_mut(); + groups.Map(0, None, Some(&mut count)).unwrap(); + let count = count as *mut u32; + let uav_barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }) }, + }; + let run = |list: &ID3D12GraphicsCommandList, close: &dyn Fn()| { + close(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let v = done.GetCompletedValue() + 1; + queue.Signal(&done, v).unwrap(); + fence::wait(&done, v, &dev, None, 10_000).unwrap(); + }; + let (mut old, mut wrong) = (0u32, Vec::new()); + for k in 0..TRIES { + // each try writes a count the memory does not hold yet + let new = if k % 2 == 0 { 4096 } else { 0 }; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let record = |x: u32| -> ID3D12GraphicsCommandList { + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, &pso).unwrap(); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(1, written.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, groups.GetGPUVirtualAddress()); + list.SetComputeRoot32BitConstants(0, 2, [0u32, x].as_ptr() as _, 0); + list.Dispatch(1, 1, 1); + list + }; + let before = record(old); + run(&before, &|| before.Close().unwrap()); + alloc.Reset().unwrap(); + *count = 0; + let list = record(new); + list.ResourceBarrier(&[uav_barrier.clone()]); + list.SetComputeRoot32BitConstants(0, 2, [1u32, 0].as_ptr() as _, 0); + // from here as XCL records a title's ExecuteIndirect: on the adopted list + let raw = list.as_raw(); + real::adopt(raw, real::Kind::CommandList); + list_x::on_create(raw, alloc.as_raw() as usize, 0, ty); + type Ei = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); + type Close = unsafe extern "system" fn(*mut c_void) -> windows::core::HRESULT; + let ei: Ei = std::mem::transmute(real::orig_fn(raw, 59)); + fresh_indirect_arguments(raw, || ei(raw, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0, 0)); + let close: Close = std::mem::transmute(real::orig_fn(raw, 9)); + run(&list, &|| close(raw).unwrap()); + let ran = std::ptr::read_volatile(count); + if ran != new { + wrong.push((k, ran)); + } + old = new; + } + groups.Unmap(0, None); + assert!(wrong.is_empty(), "{} of {TRIES} ExecuteIndirects ran another group count than the one written before them (try, groups): {wrong:?}", wrong.len()); + } + } + /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. fn test_rts0_blob() -> Vec { let words: [u32; 12] = [ diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 5247d09586..b238bef4c8 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -674,6 +674,13 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { if matches!(format, 86 | 115) && flags & 5 != 0 { d[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); } + // R9G9B9E5_SHAREDEXP targets / UAVs: PC D3D12 forbids ALLOW_RENDER_TARGET and + // ALLOW_UNORDERED_ACCESS on format 67 (Series S 1920x1080 target, flags 0x300005: + // E_INVALIDARG) – R11G11B10_FLOAT is the same 32 bpp unsigned HDR float format with full + // PC RTV/UAV/SRV support. Sampled-only R9G9B9E5 textures stay format 67. + if format == 67 && flags & 5 != 0 { + d[0x20..0x24].copy_from_slice(&26u32.to_le_bytes()); + } // a depth buffer the console also lets shaders write (a retail game's: ALLOW_DEPTH_STENCIL | // ALLOW_UNORDERED_ACCESS): the PC refuses the pair – the depth buffer stays if flags & 2 != 0 { @@ -723,10 +730,11 @@ fn depth_typeless(f: u32) -> Option { } /// The format of a render target / depth view or pipeline on the PC: `pc_view_format`, and a -/// B5G5R5A1 / B4G4R4A4 target is R8G8B8A8 (`pc_resource_desc`). +/// B5G5R5A1 / B4G4R4A4 target is R8G8B8A8, an R9G9B9E5 target is R11G11B10_FLOAT (`pc_resource_desc`). pub fn pc_target_format(f: u32) -> u32 { match f { 86 | 115 => 28, + 67 => 26, f => pc_view_format(f), } } @@ -749,6 +757,8 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { (53 | 55, 0 | 53 | 55) => 56, // a target made R8G8B8A8 (`pc_resource_desc`) (28, 86 | 115) => 28, + // a target made R11G11B10_FLOAT (`pc_resource_desc`) + (26, 67) => 26, (_, v) => v, } } @@ -1041,6 +1051,7 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); + super::indirect_clamp::note_signature(*ppv as usize, u32::from_le_bytes(pc[..4].try_into().unwrap()), &list); } hr } @@ -1142,6 +1153,11 @@ mod tests { x[0x20] = 86; // B5G5R5A1 target that is also a UAV x[0x30..0x34].copy_from_slice(&0x5u32.to_le_bytes()); assert_eq!(desc(&x), (28, 0x5)); + x[0x20] = 67; // R9G9B9E5_SHAREDEXP target + UAV + x[0x30..0x34].copy_from_slice(&0x30_0005u32.to_le_bytes()); + assert_eq!(desc(&x), (26, 0x5)); + x[0x30..0x34].copy_from_slice(&0x0u32.to_le_bytes()); // sampled-only R9G9B9E5 stays format 67 + assert_eq!(desc(&x), (67, 0)); // views: a D24S8 format or R16_UNORM of the D16S8 buffer read depth; stencil formats plane 1 assert_eq!(pc_shader_view_format(44, 45), 46); assert_eq!(pc_shader_view_format(44, 56), 46); @@ -1152,7 +1168,9 @@ mod tests { assert_eq!(pc_shader_view_format(19, 62), 22); assert_eq!(pc_shader_view_format(28, 86), 28); assert_eq!(pc_shader_view_format(86, 86), 86, "a B5G5R5A1 texture that stayed one"); - assert_eq!((pc_target_format(86), pc_target_format(118), pc_view_format(117)), (28, 45, 10)); + assert_eq!(pc_shader_view_format(26, 67), 26); + assert_eq!(pc_shader_view_format(67, 67), 67, "a sampled-only R9G9B9E5 texture that stayed one"); + assert_eq!((pc_target_format(86), pc_target_format(67), pc_target_format(118), pc_view_format(117)), (28, 26, 45, 10)); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/indirect_clamp.hlsl b/crates/xcl/src/hle/d3d12x/indirect_clamp.hlsl new file mode 100644 index 0000000000..ae2b8fd2ec --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/indirect_clamp.hlsl @@ -0,0 +1,94 @@ +// Bounds a title's indirect draw and dispatch records before ExecuteIndirect reads them +// (`indirect_clamp.rs`). One group walks every record in chunks of THREADS: each record is +// copied whole, its draw or dispatch arguments are clamped to per-record limits, and a running +// total of the work the records ask for (a prefix sum across the chunk) empties every record +// past BUDGET. + +#define THREADS 1024 +// per record: vertices (or indices) per instance, vertices times instances, groups per +// dimension, groups per dispatch; a group counts as 64 threads, a mesh group as 128 +#define MAX_VERTICES (1u << 24) +#define MAX_VERTEX_INSTANCES (1u << 26) +#define MAX_GROUPS_DIM 65535u +#define MAX_GROUPS (1u << 22) +#define BUDGET (1u << 29) + +RWByteAddressBuffer source : register(u0); // the UMA window holding the title's records +RWByteAddressBuffer bounded : register(u1); // our copy, which ExecuteIndirect reads +RWByteAddressBuffer counts : register(u2); // the UMA window holding the count (if any) + +cbuffer Config : register(b0) { + uint records; // the call's maximum command count + uint source_at; // byte offset of record 0 in `source` + uint stride; // bytes per record (a multiple of 4) + uint action_at; // byte offset of the draw or dispatch arguments in a record + uint kind; // 0 draw, 1 indexed draw, 2 dispatch, 3 mesh dispatch + uint count_at; // byte offset of the count in `counts`; 0xFFFFFFFF: no count buffer +}; + +groupshared uint scan[THREADS]; +groupshared uint carry; + +uint sat_add(uint a, uint b) { + uint s = a + b; + return s < a ? 0xFFFFFFFFu : s; +} + +// Clamps one record's arguments in place and returns the work they ask for. +uint clamp_args(inout uint3 a) { + if (kind <= 1) { + a.x = min(a.x, MAX_VERTICES); + a.y = min(a.y, MAX_VERTEX_INSTANCES / max(a.x, 1u)); + return a.x * a.y; + } + a = min(a, uint3(MAX_GROUPS_DIM, MAX_GROUPS_DIM, MAX_GROUPS_DIM)); + a.y = min(a.y, MAX_GROUPS / max(a.x, 1u)); + a.z = min(a.z, MAX_GROUPS / max(a.x * a.y, 1u)); + return a.x * a.y * a.z * (kind == 3 ? 128u : 64u); +} + +[numthreads(THREADS, 1, 1)] +void main(uint t : SV_GroupIndex) { + if (t == 0) + carry = 0; + uint live = records; + if (count_at != 0xFFFFFFFFu) + live = min(live, counts.Load(count_at)); + GroupMemoryBarrierWithGroupSync(); + for (uint first = 0; first < records; first += THREADS) { + uint i = first + t; + uint3 a = uint3(0, 0, 0); + uint work = 0; + if (i < records) { + uint src = source_at + i * stride; + uint dst = i * stride; + for (uint k = 0; k < stride; k += 4) + bounded.Store(dst + k, source.Load(src + k)); + a = source.Load3(src + action_at); + work = clamp_args(a); + } + // records past the count are never executed: they take none of the budget + scan[t] = i < live ? work : 0; + GroupMemoryBarrierWithGroupSync(); + for (uint d = 1; d < THREADS; d <<= 1) { + uint before = t >= d ? scan[t - d] : 0; + GroupMemoryBarrierWithGroupSync(); + scan[t] = sat_add(scan[t], before); + GroupMemoryBarrierWithGroupSync(); + } + uint total = sat_add(carry, scan[t]); + if (i < records) { + if (total > BUDGET) { + if (kind <= 1) + a.y = 0; + else + a = uint3(0, 0, 0); + } + bounded.Store3(i * stride + action_at, a); + } + GroupMemoryBarrierWithGroupSync(); + if (t == THREADS - 1) + carry = total; + GroupMemoryBarrierWithGroupSync(); + } +} diff --git a/crates/xcl/src/hle/d3d12x/indirect_clamp.rs b/crates/xcl/src/hle/d3d12x/indirect_clamp.rs new file mode 100644 index 0000000000..93dec17fce --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/indirect_clamp.rs @@ -0,0 +1,455 @@ +//! ExecuteIndirect's arguments, bounded on the GPU before the PC reads them. +//! +//! A title's own compute passes write most indirect arguments. A pass XCL skips (its pipeline +//! still being built, or untranslated) or translates wrongly leaves whatever the memory held, +//! and a draw of four billion vertices or a dispatch past the PC's limits runs until Windows +//! resets the display driver (0x887a0006). So, before an ExecuteIndirect with a translated +//! pipeline, a compute shader of ours (`indirect_clamp.hlsl`) copies the call's records into a +//! buffer of ours, clamps each record's draw or dispatch arguments, and empties the records past +//! a budget for the whole call; the PC call then reads that copy. The idea is VIctory's +//! (github.com/Marvisak/VIctory, `victory-gpu/src/indirect.rs`); this is XCL's own code. +//! +//! Only signatures without root arguments are bounded (those with them are skipped on +//! translated pipelines anyway), and only records in console buffers in unified memory; any +//! other call runs as before. `XCL_INDIRECT_CLAMP=0` turns it off. +//! +//! The limits (`indirect_clamp.hlsl`) are estimates, not measurements: 2^24 vertices per +//! instance, 2^26 vertex instances and 2^22 groups (65,535 per dimension) per record, 2^29 +//! vertex instances or threads per call. A title that really needs more loses that work. +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use super::real; + +/// Bytes of records one call may copy (larger calls run unbounded). +const MAX_BYTES: u64 = 16 << 20; +const CONFIG_WORDS: u32 = 6; +const NO_COUNT: u32 = u32::MAX; + +pub(super) fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_INDIRECT_CLAMP").is_ok_and(|v| v.trim() == "0")) +} + +/// A command signature whose records can be bounded: bytes per record, where its draw or +/// dispatch arguments start in one, and their kind (0 draw, 1 indexed draw, 2 dispatch, +/// 3 mesh dispatch). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Signature { + stride: u32, + action_at: u32, + kind: u32, +} + +static SIGNATURES: Mutex>> = Mutex::new(None); + +impl Signature { + /// From the PC argument list (`[type, …]` per argument, the action last): None for a + /// signature that sets root arguments or whose action is not a draw or dispatch. + fn parse(stride: u32, args: &[[u32; 4]]) -> Option { + let ([action, ..], before) = args.split_last()?; + let (kind, action_bytes) = match D3D12_INDIRECT_ARGUMENT_TYPE(*action as i32) { + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW => (0, 16), + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED => (1, 20), + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH => (2, 12), + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH => (3, 12), + _ => return None, + }; + let mut at = 0u32; + for &[ty, ..] in before { + at += match D3D12_INDIRECT_ARGUMENT_TYPE(ty as i32) { + // D3D12_VERTEX_BUFFER_VIEW, D3D12_INDEX_BUFFER_VIEW + D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW | D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW => 16, + _ => return None, + }; + } + if stride == 0 || !stride.is_multiple_of(4) || at + action_bytes > stride { + return None; + } + Some(Self { stride, action_at: at, kind }) + } +} + +/// Note a command signature the title created (its PC argument list); one that cannot be +/// bounded is forgotten, so a new signature at a released one's address is never mistaken for it. +pub(super) fn note_signature(sig: usize, stride: u32, args: &[[u32; 4]]) { + let mut g = SIGNATURES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + match Signature::parse(stride, args) { + Some(s) => map.insert(sig, s), + None => map.remove(&sig), + }; +} + +fn signature(sig: usize) -> Option { + SIGNATURES.lock().unwrap().as_ref()?.get(&sig).copied() +} + +struct Clamper { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +/// per device; None: it could not be made (logged once, not tried again) +static CLAMPERS: Mutex>>>> = Mutex::new(None); + +unsafe fn clamper(dev: &ID3D12Device) -> Option> { + let mut g = CLAMPERS.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + let key = dev.as_raw() as usize; + if let Some(c) = map.get(&key) { + return c.clone(); + } + let made = make_clamper(dev).map(Arc::new); + if let Err(e) = &made { + crate::xlog_warn!("D3D12.X: ExecuteIndirect arguments run unbounded: {e}"); + } + let made = made.ok(); + map.insert(key, made.clone()); + made +} + +unsafe fn make_clamper(dev: &ID3D12Device) -> Result { + let dxil = crate::gpu::recomp::dxc::compile(include_str!("indirect_clamp.hlsl"), "main", "cs_6_0", &[])?; + let uav = |reg| D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: reg, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let params = [ + uav(0), + uav(1), + uav(2), + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: CONFIG_WORDS } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).map_err(|e| format!("root signature: {e}"))?; + let blob = blob.ok_or("no root signature blob")?; + let root: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize())) + .map_err(|e| format!("root signature: {e}"))?; + let mut pd = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(root.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }; + let pso = dev.CreateComputePipelineState(&pd); + ManuallyDrop::drop(&mut pd.pRootSignature); + Ok(Clamper { root, pso: pso.map_err(|e| format!("pipeline: {e}"))? }) +} + +/// Bounded copies a list recorded, per allocator, until its reset; and those free again. +#[derive(Default)] +struct Scratch { + held: HashMap>, + free: Vec<(usize, u64, ID3D12Resource)>, +} + +static SCRATCH: Mutex> = Mutex::new(None); +/// free buffers kept for reuse (the rest are released) +const FREE_KEPT: usize = 64; + +/// A buffer of at least `bytes` in UNORDERED_ACCESS, held for `allocator` until its reset. +unsafe fn scratch(dev: &ID3D12Device, allocator: usize, bytes: u64) -> Option { + let key = dev.as_raw() as usize; + let mut g = SCRATCH.lock().unwrap(); + let s = g.get_or_insert_with(Default::default); + let reuse = s.free.iter().enumerate().filter(|(_, (d, n, _))| *d == key && *n >= bytes).min_by_key(|(_, (_, n, _))| *n).map(|(i, _)| i); + let entry = match reuse { + Some(i) => s.free.swap_remove(i), + None => { + let size = bytes.next_power_of_two().max(64 << 10); + let mut out: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + None, + &mut out, + ) + .ok()?; + (key, size, out?) + } + }; + let r = entry.2.clone(); + s.held.entry(allocator).or_default().push(entry); + Some(r) +} + +/// The GPU is done with what lists recorded from `allocator` (reset or released): its copies +/// can be reused. +pub(super) fn allocator_reset(allocator: usize) { + let mut g = SCRATCH.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if let Some(done) = s.held.remove(&allocator) { + s.free.extend(done); + if s.free.len() > FREE_KEPT { + s.free.sort_by_key(|e| std::cmp::Reverse(e.1)); + s.free.truncate(FREE_KEPT); + } + } +} + +/// Where `bytes` at console offset `offset` of console buffer `res` are on the GPU: the GPU +/// address of the unified memory window holding them and their offset in it. +unsafe fn in_window(res: usize, offset: u64, bytes: u64) -> Option<(u64, u32)> { + let (p, len) = real::console_buffer(res)?; + if !offset.is_multiple_of(4) || offset.checked_add(bytes)? > len as u64 { + return None; + } + let (window, at) = real::uma_window_buffer(p.checked_add(usize::try_from(offset).ok()?)?, usize::try_from(bytes).ok()?)?; + let at = u32::try_from(at).ok()?; + at.checked_add(u32::try_from(bytes).ok()?)?; + let window = window as *mut c_void; + Some((ID3D12Resource::from_raw_borrowed(&window)?.GetGPUVirtualAddress(), at)) +} + +/// The config words for a call: max records, where they are, the signature and the count. +fn config(sig: Signature, max: u32, source_at: u32, count_at: Option) -> [u32; CONFIG_WORDS as usize] { + [max, source_at, sig.stride, sig.action_at, sig.kind, count_at.unwrap_or(NO_COUNT)] +} + +unsafe fn transition(list: &ID3D12GraphicsCommandList, r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: ManuallyDrop::new(Some(r.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + ..Default::default() + }; + list.ResourceBarrier(std::slice::from_ref(&barrier)); + let mut t = ManuallyDrop::into_inner(barrier.Anonymous.Transition); + ManuallyDrop::drop(&mut t.pResource); +} + +/// A bounded copy of a call's records, in INDIRECT_ARGUMENT until [`Bounded::finish`]. +pub(super) struct Bounded(ID3D12Resource); + +impl Bounded { + /// The copy, for the PC ExecuteIndirect (at offset 0). + pub(super) fn raw(&self) -> usize { + self.0.as_raw() as usize + } + + /// After the PC call: back to UNORDERED_ACCESS (the state each use starts from; a list may + /// run more than once). + pub(super) unsafe fn finish(self, list: &ID3D12GraphicsCommandList) { + transition(list, &self.0, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } +} + +/// Record the bounding of an ExecuteIndirect's records on `list` (offsets are console ones, +/// before `real::buffer_delta`). Changes the list's compute root signature, its root arguments +/// and its pipeline, so the caller binds its own after this. None: the call runs as it is. +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn bound( + list: &ID3D12GraphicsCommandList, allocator: usize, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64, +) -> Option { + if !enabled() || max == 0 { + return None; + } + let s = signature(sig)?; + let bytes = u64::from(max) * u64::from(s.stride); + if bytes > MAX_BYTES { + return None; + } + let (source, source_at) = in_window(args, args_off, bytes)?; + let (counts, count_at) = match count_buf { + 0 => (source, None), + c => match in_window(c, count_off, 4) { + Some((w, at)) => (w, Some(at)), + // a count we cannot read: every record takes from the budget + None => (source, None), + }, + }; + let mut dev: Option = None; + list.GetDevice(&mut dev).ok()?; + let dev = dev?; + let c = clamper(&dev)?; + let out = scratch(&dev, allocator, bytes)?; + let cfg = config(s, max, source_at, count_at); + // the title's writes to its records (through any view) before our reads + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, ..Default::default() }]); + list.SetPipelineState(&c.pso); + list.SetComputeRootSignature(&c.root); + list.SetComputeRootUnorderedAccessView(0, source); + list.SetComputeRootUnorderedAccessView(1, out.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, counts); + list.SetComputeRoot32BitConstants(3, CONFIG_WORDS, cfg.as_ptr().cast(), 0); + list.Dispatch(1, 1, 1); + transition(list, &out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + Some(Bounded(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn signatures_without_root_arguments_are_bounded() { + let (draw, indexed, dispatch, mesh) = ( + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW.0 as u32, + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32, + ); + let (vbv, ibv, constant) = ( + D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW.0 as u32, + D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW.0 as u32, + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT.0 as u32, + ); + assert_eq!(Signature::parse(16, &[[draw, 0, 0, 0]]), Some(Signature { stride: 16, action_at: 0, kind: 0 })); + assert_eq!(Signature::parse(12, &[[dispatch, 0, 0, 0]]), Some(Signature { stride: 12, action_at: 0, kind: 2 })); + assert_eq!(Signature::parse(16, &[[mesh, 0, 0, 0]]), Some(Signature { stride: 16, action_at: 0, kind: 3 })); + // buffer views before the draw: 16 bytes each + assert_eq!( + Signature::parse(52, &[[vbv, 0, 0, 0], [ibv, 0, 0, 0], [indexed, 0, 0, 0]]), + Some(Signature { stride: 52, action_at: 32, kind: 1 }) + ); + // root arguments, a stride too small or unaligned, no action, an action not last + assert_eq!(Signature::parse(20, &[[constant, 0, 0, 1], [draw, 0, 0, 0]]), None); + assert_eq!(Signature::parse(16, &[[indexed, 0, 0, 0]]), None); + assert_eq!(Signature::parse(18, &[[draw, 0, 0, 0]]), None); + assert_eq!(Signature::parse(16, &[]), None); + assert_eq!(Signature::parse(32, &[[draw, 0, 0, 0], [vbv, 0, 0, 0]]), None); + } + + #[test] + fn a_signature_that_cannot_be_bounded_replaces_one_at_the_same_address() { + let sig = 0x7300_0010usize; + let draw = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW.0 as u32; + note_signature(sig, 16, &[[draw, 0, 0, 0]]); + assert!(signature(sig).is_some()); + note_signature(sig, 20, &[[D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT.0 as u32, 0, 0, 1], [draw, 0, 0, 0]]); + assert!(signature(sig).is_none()); + } + + #[test] + fn config_words_follow_the_shader() { + let s = Signature { stride: 52, action_at: 32, kind: 1 }; + assert_eq!(config(s, 7, 128, Some(64)), [7, 128, 52, 32, 1, 64]); + assert_eq!(config(s, 7, 128, None)[5], NO_COUNT); + } + + /// The shader on the GPU: clamped records, and records past the budget emptied; everything + /// else in a record copied as it is. + #[test] + fn gpu_records_are_clamped_and_budgeted() { + use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + if crate::gpu::recomp::dxc::create_instance().is_none() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let dev = dev.unwrap(); + let Some(c) = clamper(&dev) else { panic!("the clamp pipeline was not made") }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let buffer = |bytes: u64, heap, state, flags| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() + }; + let mut out = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out).unwrap(); + out.unwrap() + }; + // indexed draws after a 16-byte vertex buffer view: 36 bytes a record; 2,000 records + // (two chunks of the shader's 1,024), the count buffer after them + let (stride, n) = (36u32, 2000u32); + let words = (stride / 4) as usize; + let mut data = vec![0u32; words * n as usize + 1]; + for i in 0..n as usize { + let r = &mut data[i * words..(i + 1) * words]; + r[..4].copy_from_slice(&[0xAAAA_0000 + i as u32, 0xBBBB, 0xCCCC, 0xDDDD]); + // index count, instances, first index, base vertex, first instance + r[4..9].copy_from_slice(&[3, 1, 7, 0xFFFF_FFFF, 9]); + } + data[words..words + 9][4..6].copy_from_slice(&[u32::MAX, 5]); // 1: too many indices + data[2 * words + 4..2 * words + 6].copy_from_slice(&[1 << 20, 1 << 20]); // 2: too many instances + // 1,000..1,500: 2^20 vertex instances each; after records 1 and 2 (2^26 each) and + // 998 of 3, the budget (2^29) holds 383 of them: record 1,383 is the first past it + for i in 1000..1500 { + data[i * words + 4..i * words + 6].copy_from_slice(&[1 << 10, 1 << 10]); + } + data[words * n as usize] = 1600; // the count + let bytes = (data.len() * 4) as u64; + let upload = buffer(bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE); + let mut mapped: *mut c_void = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::copy_nonoverlapping(data.as_ptr(), mapped.cast(), data.len()); + upload.Unmap(0, None); + let src = buffer(bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let out = buffer(u64::from(stride * n), D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let readback = buffer(u64::from(stride * n), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + list.CopyBufferRegion(&src, 0, &upload, 0, bytes); + transition(&list, &src, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + let s = Signature { stride, action_at: 16, kind: 1 }; + let cfg = config(s, n, 0, Some(stride * n)); + list.SetPipelineState(&c.pso); + list.SetComputeRootSignature(&c.root); + list.SetComputeRootUnorderedAccessView(0, src.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, out.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, src.GetGPUVirtualAddress()); + list.SetComputeRoot32BitConstants(3, CONFIG_WORDS, cfg.as_ptr().cast(), 0); + list.Dispatch(1, 1, 1); + transition(&list, &out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&readback, 0, &out, 0, u64::from(stride * n)); + list.Close().unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, event).unwrap(); + assert_eq!(WaitForSingleObject(event, 10_000), WAIT_OBJECT_0); + CloseHandle(event).unwrap(); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let got = std::slice::from_raw_parts(mapped.cast::(), words * n as usize).to_vec(); + readback.Unmap(0, None); + let rec = |i: usize| &got[i * words..(i + 1) * words]; + assert_eq!(rec(0), &[0xAAAA_0000, 0xBBBB, 0xCCCC, 0xDDDD, 3, 1, 7, 0xFFFF_FFFF, 9], "an ordinary record is copied as it is"); + assert_eq!(&rec(1)[4..6], &[1 << 24, 4], "indices per instance clamped, instances to 2^26 vertex instances"); + assert_eq!(&rec(2)[4..6], &[1 << 20, 1 << 6], "instances clamped to 2^26 vertex instances"); + assert_eq!(&rec(1382)[4..6], &[1 << 10, 1 << 10], "within the budget"); + assert_eq!(&rec(1383)[4..6], &[1 << 10, 0], "past the budget: no instances"); + assert_eq!(&rec(1550)[4..6], &[3, 0], "every record after it is emptied too"); + assert_eq!(rec(1499)[0], 0xAAAA_0000 + 1499, "the rest of an emptied record is kept"); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index afa4f91e46..0fdfb78277 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -89,7 +89,13 @@ unsafe fn list_type(list: *mut c_void) -> D3D12_COMMAND_LIST_TYPE { pc:: D3D12_COMMAND_LIST_TYPE>(list, PC_GET_TYPE)(list) } -unsafe fn transition(list: *mut c_void, res: usize, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { +/// The type of a list XCL keeps state for (`on_create`), without a call to the list; None for +/// any other +pub(super) fn tracked_list_type(list: *mut c_void) -> Option { + LISTS.lock().unwrap().as_ref()?.get(&(list as usize))?.list_type +} + +pub(super) unsafe fn transition(list: *mut c_void, res: usize, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f0357981..653ff39242 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -17,6 +17,7 @@ pub mod device_x; pub mod dxgi_device; mod cpu_writes; mod fence_x; +mod indirect_clamp; pub mod frame; pub mod guard; mod late_release; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fed31e6224..7d655b2da4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5406,6 +5406,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { if n == 0 { super::alloc_pool::forget(this as usize); super::list_x::on_allocator_release(this as usize); + super::indirect_clamp::allocator_reset(this as usize); } n } @@ -5426,6 +5427,7 @@ unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { if hr >= 0 { // the GPU is done with what lists recorded from this allocator used super::console_list::allocator_reset(this); + super::indirect_clamp::allocator_reset(this as usize); } hr } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 040d78a0ce..740b69ef9f 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -220,6 +220,165 @@ struct Target { used_extra: Vec<(usize, usize)>, } +/// Per-heap free-tile allocator for `Pages`. +/// +/// Keeping free tiles partitioned by pool heap (sorted descending so `.pop()` yields ascending +/// contiguous tile indices) prevents streaming churn across 100+ 64 MiB pools from scattering a +/// single texture across dozens of heaps — which otherwise explodes `Pages::map` into dozens of +/// `UpdateTileMappings` calls per texture. +struct TilePool { + /// Free tile indices for each pool heap (descending when `!dirty_sort[h]`). + free_by_heap: Vec>, + /// Whether `free_by_heap[h]` must be sorted descending before popping. + dirty_sort: Vec, + /// Total free tiles currently available across all heaps. + free_total: usize, + /// Tiles given back, reusable after `COOL`. + cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, +} + +impl TilePool { + fn new() -> Self { + TilePool { + free_by_heap: Vec::new(), + dirty_sort: Vec::new(), + free_total: 0, + cooling: std::collections::VecDeque::new(), + } + } + + fn add_heap(&mut self, pool_pages: u32) -> u32 { + let h = self.free_by_heap.len() as u32; + self.free_by_heap.push((0..pool_pages).rev().collect()); + self.dirty_sort.push(false); + self.free_total += pool_pages as usize; + h + } + + fn push_cooling(&mut self, tile: Tile, now: std::time::Instant) { + self.cooling.push_back((tile, now)); + } + + /// Move every cooled tile (`>= COOL`) into its pool heap's free list so best-fit allocation + /// sees all ready tiles at once. + fn drain_cooling(&mut self, now: std::time::Instant) { + while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + let Some(((h, t), _)) = self.cooling.pop_front() else { break }; + let idx = h as usize; + if idx < self.free_by_heap.len() { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.free_total += 1; + } + } + } + + fn return_tiles(&mut self, tiles: &[Tile]) { + for &(h, t) in tiles { + let idx = h as usize; + if idx < self.free_by_heap.len() { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.free_total += 1; + } + } + } + + /// Pick the pool heap to take up to `rem` tiles from: + /// 1. `preferred` if it fits all `rem` tiles (keeps partial-overlap placements on 1 heap), + /// 2. otherwise best-fit heap with `len >= rem` (fits the whole texture in 1 heap without + /// splitting fuller pools), + /// 3. otherwise the heap with the most free tiles (minimizing distinct heaps touched). + fn pick_heap(&self, rem: usize, preferred: Option) -> Option { + if self.free_total == 0 { + return None; + } + if let Some(p) = preferred.map(|h| h as usize).filter(|&h| h < self.free_by_heap.len()) { + if self.free_by_heap[p].len() >= rem { + return Some(p); + } + } + let mut best_fit: Option<(usize, usize)> = None; + let mut largest: Option<(usize, usize)> = None; + for (h, tiles) in self.free_by_heap.iter().enumerate() { + let len = tiles.len(); + if len == 0 { + continue; + } + if len >= rem { + if best_fit.is_none_or(|(_, blen)| len < blen) { + best_fit = Some((h, len)); + } + } else if largest.is_none_or(|(lh, llen)| len > llen || (len == llen && preferred == Some(h as u32) && preferred != Some(lh as u32))) { + largest = Some((h, len)); + } + } + best_fit.or(largest).map(|(h, _)| h) + } + + /// Allocate `count` tiles, preferring a single heap and ascending contiguous offsets. + /// `make_heap` allocates a new backing pool heap of `pool_pages` tiles when `free_total == 0`. + /// On failure, any tiles already taken are returned untouched. + fn take_batch( + &mut self, + count: usize, + preferred: Option, + now: std::time::Instant, + pool_pages: u32, + mut make_heap: impl FnMut() -> Option, + ) -> Option> { + if count == 0 { + return Some(Vec::new()); + } + self.drain_cooling(now); + let mut out = Vec::with_capacity(count); + while out.len() < count { + let rem = count - out.len(); + let h = match self.pick_heap(rem, preferred) { + Some(h) => h, + None => { + let Some(new_h) = make_heap() else { + self.return_tiles(&out); + return None; + }; + let added = self.add_heap(pool_pages); + debug_assert_eq!(added, new_h); + added as usize + } + }; + if self.dirty_sort[h] { + self.free_by_heap[h].sort_unstable_by(|a, b| b.cmp(a)); + self.dirty_sort[h] = false; + } + let free = &mut self.free_by_heap[h]; + let take = rem.min(free.len()); + for _ in 0..take { + let t = free.pop().unwrap(); + out.push((h as u32, t)); + } + self.free_total -= take; + } + Some(out) + } +} + +/// Allocate one 64 MiB default heap for `Pages`. +unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { + let desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_PAGES as u64 * PAGE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + // every kind of texture (resource heap tier 2: the only flags for both) + Flags: D3D12_HEAP_FLAG_NONE, + }; + let mut heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&desc, &mut heap)) { + crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); + return None; + } + heap +} + /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { queue: ID3D12CommandQueue, @@ -227,9 +386,7 @@ struct Pages { fence: ID3D12Fence, value: u64, pools: Vec, - free: Vec, - /// tiles given back, reusable after `COOL` - cooling: std::collections::VecDeque<(Tile, std::time::Instant)>, + pool: TilePool, /// title page address → its video memory pages: std::collections::HashMap, /// extra / sub-64 KiB tiles keyed by `(va, tile_index)` so repeated placements at the same @@ -241,6 +398,13 @@ struct Pages { targets: std::collections::HashMap, /// queue → the fence value it last waited for waited: std::collections::HashMap, + /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device + reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// reusable scratch buffers for `map()` + scratch_heaps: Vec, + scratch_flags: Vec, + scratch_offsets: Vec, + scratch_counts: Vec, } // D3D12 objects are free-threaded @@ -259,6 +423,7 @@ impl Pages { return None; } let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; + let _ = queue.SetName(windows::core::w!("xcl vram tile-mapping queue")); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); Some(Pages { @@ -266,58 +431,52 @@ impl Pages { fence, value: 0, pools: Vec::new(), - free: Vec::new(), - cooling: std::collections::VecDeque::new(), + pool: TilePool::new(), pages: std::collections::HashMap::new(), extra_pages: std::collections::HashMap::new(), idle: std::collections::VecDeque::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + reservable_cache: std::collections::HashMap::new(), + scratch_heaps: Vec::new(), + scratch_flags: Vec::new(), + scratch_offsets: Vec::new(), + scratch_counts: Vec::new(), }) } /// Pages no resource used for `IDLE` go back to the pools. fn sweep(&mut self, now: std::time::Instant) { - sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut self.cooling, now); - } - - unsafe fn take_tile(&mut self, dev: &ID3D12Device) -> Option { - if let Some(t) = self.free.pop() { - return Some(t); - } - if self.cooling.front().is_some_and(|(_, at)| at.elapsed() >= COOL) { - return self.cooling.pop_front().map(|(t, _)| t); - } - let desc = D3D12_HEAP_DESC { - SizeInBytes: POOL_PAGES as u64 * PAGE as u64, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - Alignment: 0, - // every kind of texture (resource heap tier 2: the only flags for both) - Flags: D3D12_HEAP_FLAG_NONE, - }; - let mut heap: Option = None; - if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&desc, &mut heap)) { - crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); - return None; - } - self.pools.push(heap?); - let h = self.pools.len() as u32 - 1; - self.free.extend((1..POOL_PAGES).rev().map(|t| (h, t))); - Some((h, 0)) + sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut self.pool.cooling, now); } /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. unsafe fn map(&mut self, res: &ID3D12Resource, tiles: &[Tile]) { - let mut heaps: Vec = tiles.iter().map(|t| t.0).collect(); - heaps.sort_unstable(); - heaps.dedup(); - for h in heaps { - let ranges = heap_ranges(h, tiles); - let flags: Vec = ranges.iter().map(|r| if r.0 { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }).collect(); - let offsets: Vec = ranges.iter().map(|r| r.1).collect(); - let counts: Vec = ranges.iter().map(|r| r.2).collect(); + if tiles.is_empty() { + return; + } + self.scratch_heaps.clear(); + self.scratch_heaps.extend(tiles.iter().map(|t| t.0)); + self.scratch_heaps.sort_unstable(); + self.scratch_heaps.dedup(); + for i in 0..self.scratch_heaps.len() { + let h = self.scratch_heaps[i]; + let ranges = heap_ranges_trimmed(h, tiles); + if ranges.is_empty() { + continue; + } + self.scratch_flags.clear(); + self.scratch_offsets.clear(); + self.scratch_counts.clear(); + let mut num_tiles = 0u32; + for &(mapped, off, count) in &ranges { + self.scratch_flags.push(if mapped { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }); + self.scratch_offsets.push(off); + self.scratch_counts.push(count); + num_tiles += count; + } let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); - let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles.len() as u32, UseBox: false.into(), ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: num_tiles, UseBox: false.into(), ..Default::default() }; self.queue.UpdateTileMappings( res, 1, @@ -325,9 +484,9 @@ impl Pages { Some(®ion), &self.pools[h as usize], ranges.len() as u32, - Some(flags.as_ptr()), - Some(offsets.as_ptr()), - Some(counts.as_ptr()), + Some(self.scratch_flags.as_ptr()), + Some(self.scratch_offsets.as_ptr()), + Some(self.scratch_counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); } @@ -338,6 +497,9 @@ impl Pages { /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return /// to the pool even while the title keeps the COM object alive. unsafe fn unmap(&mut self, res: &ID3D12Resource, total: u32) { + if total == 0 { + return; + } let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; let flag = D3D12_TILE_RANGE_FLAG_NULL; @@ -364,7 +526,7 @@ impl Pages { if p.users == 0 { if immediate_cool { if let Some(p) = self.pages.remove(&a) { - self.cooling.push_back((p.tile, now)); + self.pool.push_cooling(p.tile, now); } } else { p.idle_since = Some(now); @@ -379,7 +541,7 @@ impl Pages { if p.users == 0 { if immediate_cool { if let Some(p) = self.extra_pages.remove(&k) { - self.cooling.push_back((p.tile, now)); + self.pool.push_cooling(p.tile, now); } } else { p.idle_since = Some(now); @@ -395,49 +557,69 @@ impl Pages { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); + + let mut missing = 0usize; + let mut preferred: Option = None; + for i in 0..total as usize { + let existing = if i < own { + self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) + } else { + self.extra_pages.get(&(va, i)).map(|p| p.tile.0) + }; + match existing { + Some(h) if preferred.is_none() => preferred = Some(h), + Some(_) => {} + None => missing += 1, + } + } + + let pools = &mut self.pools; + let pool = &mut self.pool; + let fresh = pool.take_batch(missing, preferred, now, POOL_PAGES, || { + let heap = alloc_pool_heap(dev)?; + pools.push(heap); + Some(pools.len() as u32 - 1) + })?; + let mut fresh_iter = fresh.into_iter(); + let mut tiles = Vec::with_capacity(total as usize); let mut used = Vec::with_capacity(own); let mut used_extra = Vec::new(); for i in 0..total as usize { let tile = if i < own { let a = first + i * PAGE; - let tile = match self.pages.get_mut(&a) { + let t = match self.pages.get_mut(&a) { Some(p) => { p.users += 1; p.idle_since = None; - Some(p.tile) + p.tile } - None => self.take_tile(dev).inspect(|&t| { + None => { + let t = fresh_iter.next().unwrap(); self.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); - }), + t + } }; - if tile.is_some() { - used.push(a); - } - tile + used.push(a); + t } else { let k = (va, i); - let tile = match self.extra_pages.get_mut(&k) { + let t = match self.extra_pages.get_mut(&k) { Some(p) => { p.users += 1; p.idle_since = None; - Some(p.tile) + p.tile } - None => self.take_tile(dev).inspect(|&t| { + None => { + let t = fresh_iter.next().unwrap(); self.extra_pages.insert(k, Page { tile: t, users: 1, idle_since: None }); - }), + t + } }; - if tile.is_some() { - used_extra.push(k); - } - tile + used_extra.push(k); + t }; - let Some(t) = tile else { break }; - tiles.push(t); - } - if tiles.len() < total as usize { - self.release_tiles(used, used_extra, now, true); - return None; + tiles.push(tile); } self.map(res, &tiles); Some((used, used_extra)) @@ -460,6 +642,16 @@ fn heap_ranges(heap: u32, tiles: &[Tile]) -> Vec<(bool, u32, u32)> { out } +/// Like `heap_ranges`, with any trailing `SKIP` range trimmed so `UpdateTileMappings` only walks +/// up to the last tile belonging to `heap`. +fn heap_ranges_trimmed(heap: u32, tiles: &[Tile]) -> Vec<(bool, u32, u32)> { + let mut out = heap_ranges(heap, tiles); + while out.last().is_some_and(|r| !r.0) { + out.pop(); + } + out +} + /// 64 KiB page boundaries `P` with `va <= P < va + bytes`, capped at `total` tiles: /// `(first_page, count)`. Because every `P` lies strictly inside `[va, va + bytes)`, two /// non-overlapping ranges never share a page here even when `va` is only 4 KiB aligned. @@ -532,12 +724,18 @@ unsafe fn place_on_pages( crate::xlog_info!("D3D12.X: GPU-owned texture at {va:#x} ({}x{}, format {}, {} samples) not reserved ({why}): in an arena", desc.Width, desc.Height, desc.Format.0, desc.SampleDesc.Count); } }; - if !reservable(dev, &tiled) { + let dev_key = dev.as_raw() as usize; + let is_reservable = { + let mut g = PAGES.lock().unwrap(); + let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; + *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)) + }; + if !is_reservable { log("no tiled support for its format or sample count"); return None; } - let mut g = PAGES.lock().unwrap(); - let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; + // CreateReservedResource and GetResourceTiling do not touch `PAGES`; keep them outside the + // lock so concurrent streaming threads, `before_execute`, and `page_bytes` do not serialize. let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); if hr < 0 || (*ppv).is_null() { log(&format!("{hr:#x}")); @@ -547,14 +745,24 @@ unsafe fn place_on_pages( let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); - let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) else { - drop(g); + let bound = { + let mut g = PAGES.lock().unwrap(); + if let Some(Some(pages)) = g.get_mut(&dev_key) { + if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); + true + } else { + false + } + } else { + false + } + }; + if !bound { drop(windows::core::IUnknown::from_raw(raw)); *ppv = std::ptr::null_mut(); return None; - }; - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); - drop(g); + } PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) } @@ -620,7 +828,7 @@ fn forget_pages(resource: usize) { } } -/// Before GPU work on `queue`: it waits for the pages mapped since its last work on that device. +/// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device. pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let mut dev: Option = None; if queue.GetDevice(&mut dev).is_err() { @@ -725,10 +933,78 @@ mod tests { let tiles = [(0, 5), (0, 6), (1, 0), (1, 1), (0, 9), (0, 10), (0, 11)]; assert_eq!(heap_ranges(0, &tiles), [(true, 5, 2), (false, 0, 2), (true, 9, 3)]); assert_eq!(heap_ranges(1, &tiles), [(false, 0, 2), (true, 0, 2), (false, 0, 3)]); + assert_eq!(heap_ranges_trimmed(1, &tiles), [(false, 0, 2), (true, 0, 2)]); // shared pages out of order: runs break where the tiles do assert_eq!(heap_ranges(0, &[(0, 3), (0, 1), (0, 2)]), [(true, 3, 1), (true, 1, 2)]); } + /// Streaming churn across 100+ 64 MiB pool heaps: cooling tiles returned in interleaved + /// cross-heap order are regrouped per heap and sorted into contiguous ascending runs, so new + /// textures stay inside 1 pool heap (1 UpdateTileMappings call, 1 contiguous range) instead of + /// scattering across dozens of heaps. + #[test] + fn tile_pool_keeps_churned_allocations_in_single_heap_and_contiguous() { + let t0 = Instant::now(); + let mut pool = TilePool::new(); + let heaps_made = std::cell::Cell::new(0u32); + let mut make = || { + let h = heaps_made.get(); + heaps_made.set(h + 1); + Some(h) + }; + + // Fill 100 pools (64 tiles each for a fast unit test, same multi-heap topology as 1024). + const P: u32 = 64; + let mut live: Vec> = Vec::new(); + for _ in 0..100 { + live.push(pool.take_batch(P as usize, None, t0, P, &mut make).unwrap()); + } + assert_eq!(heaps_made.get(), 100); + assert_eq!(pool.free_total, 0); + + // Free 32 tiles from every pool in interleaved round-robin order (worst-case churn across + // all 100 pools in `cooling`). + for tile_idx in 0..32usize { + for h in 0..100usize { + pool.push_cooling(live[h][tile_idx], t0); + } + } + assert_eq!(pool.cooling.len(), 3200); + + // After COOL, allocating 100 textures of 32 tiles each must: + // - allocate ZERO new heaps, + // - place EVERY texture into exactly 1 single pool heap (1 UpdateTileMappings call), + // - yield 1 single contiguous tile range (0..32) per texture! + let t1 = t0 + COOL + Duration::from_millis(1); + for _ in 0..100 { + let alloc = pool.take_batch(32, None, t1, P, &mut make).unwrap(); + assert_eq!(alloc.len(), 32); + let h0 = alloc[0].0; + assert!(alloc.iter().all(|&(h, _)| h == h0), "texture scattered across multiple heaps"); + let ranges = heap_ranges_trimmed(h0, &alloc); + assert_eq!(ranges, [(true, 0, 32)], "expected 1 contiguous ascending range"); + } + assert_eq!(heaps_made.get(), 100, "must reuse cooled tiles without making new heaps"); + assert_eq!(pool.free_total, 0); + + // Partial overlap preference: if heap 7 has free tiles and preferred=Some(7), use heap 7. + for t in 10..18u32 { + pool.push_cooling((7, t), t1); + pool.push_cooling((3, t), t1); + } + let t2 = t1 + COOL + Duration::from_millis(1); + let pref = pool.take_batch(8, Some(7), t2, P, &mut make).unwrap(); + assert!(pref.iter().all(|&(h, _)| h == 7), "preferred heap should be chosen"); + assert_eq!(heap_ranges_trimmed(7, &pref), [(true, 10, 8)]); + + // Rollback on OOM: requesting more tiles than available when make_heap fails returns every + // popped tile cleanly so free_total is preserved. + assert_eq!(pool.free_total, 8); + let fail = pool.take_batch(16, None, t2, P, || None); + assert!(fail.is_none()); + assert_eq!(pool.free_total, 8, "OOM rollback must return all popped tiles"); + } + /// Idle pages go back after `IDLE`, and a sweep looks at the queue of idle pages alone: one /// used again stays, one idle again later goes when that is `IDLE` ago, and the sweeps of /// 20 000 placements beside 200 000 pages in use take no time to speak of (a look at every @@ -1032,4 +1308,116 @@ mod tests { drop(last); } } + + /// Reproduces the multi-pool streaming churn pattern on the active D3D12 driver (comparing + /// scattered cross-heap `UpdateTileMappings` against single-heap contiguous + /// `UpdateTileMappings`, both with `FLAG_NONE` and per-texture `Signal`): + /// `cargo test -p xcl --lib -- --ignored --exact hle::d3d12x::vram::tests::churn_update_tile_mappings_timing --nocapture` + #[test] + #[ignore] + fn churn_update_tile_mappings_timing() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + unsafe { + let mut dev: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("D3D12 device"); + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + const HEAPS: usize = 64; + const TILES_PER_TEX: usize = 32; // 2 MiB tiled texture + const TEX_COUNT: usize = 256; + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: 64 * PAGE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_NONE, + }; + let mut heaps = Vec::with_capacity(HEAPS); + for _ in 0..HEAPS { + let mut h: Option = None; + dev.CreateHeap(&heap_desc, &mut h).unwrap(); + heaps.push(h.unwrap()); + } + let tex_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1024, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let make_textures = || -> Vec { + (0..TEX_COUNT) + .map(|_| { + let mut r: Option = None; + dev.CreateReservedResource(&tex_desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }) + .collect() + }; + + // BEFORE pattern: flat-FIFO cooling scatters each 32-tile texture across 32 heaps, + // calling UpdateTileMappings(FLAG_NONE) per heap + Signal per texture. + let old_res = make_textures(); + let mut fval = 0u64; + let t0 = Instant::now(); + let mut old_calls = 0usize; + for (k, r) in old_res.iter().enumerate() { + let tiles: Vec = (0..TILES_PER_TEX).map(|i| (((k + i) % HEAPS) as u32, (i % 64) as u32)).collect(); + let mut hs: Vec = tiles.iter().map(|t| t.0).collect(); + hs.sort_unstable(); + hs.dedup(); + for h in hs { + let ranges = heap_ranges(h, &tiles); + let flags: Vec = ranges.iter().map(|x| if x.0 { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_SKIP }).collect(); + let offsets: Vec = ranges.iter().map(|x| x.1).collect(); + let counts: Vec = ranges.iter().map(|x| x.2).collect(); + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles.len() as u32, UseBox: false.into(), ..Default::default() }; + queue.UpdateTileMappings(r, 1, Some(&coord), Some(®ion), &heaps[h as usize], ranges.len() as u32, Some(flags.as_ptr()), Some(offsets.as_ptr()), Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE); + old_calls += 1; + } + fval += 1; + queue.Signal(&fence, fval).unwrap(); + } + let old_submit = t0.elapsed(); + fence.SetEventOnCompletion(fval, windows::Win32::Foundation::HANDLE::default()).unwrap(); + let old_total = t0.elapsed(); + + // AFTER pattern: per-heap contiguous TilePool -> 1 heap, 1 contiguous range, + // D3D12_TILE_MAPPING_FLAG_NONE, per-texture Signal. + let new_res = make_textures(); + let t1 = Instant::now(); + let mut new_calls = 0usize; + for (k, r) in new_res.iter().enumerate() { + let h = k % HEAPS; + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: TILES_PER_TEX as u32, UseBox: false.into(), ..Default::default() }; + let flag = D3D12_TILE_RANGE_FLAG_NONE; + let off = 0u32; + let cnt = TILES_PER_TEX as u32; + queue.UpdateTileMappings(r, 1, Some(&coord), Some(®ion), &heaps[h], 1, Some(&flag), Some(&off), Some(&cnt), D3D12_TILE_MAPPING_FLAG_NONE); + new_calls += 1; + fval += 1; + queue.Signal(&fence, fval).unwrap(); + } + let new_submit = t1.elapsed(); + fence.SetEventOnCompletion(fval, windows::Win32::Foundation::HANDLE::default()).unwrap(); + let new_total = t1.elapsed(); + + println!( + "BEFORE ({TEX_COUNT} x 2MiB textures, {old_calls} UpdateTileMappings + {TEX_COUNT} Signals): submit={old_submit:?} gpu_done={old_total:?}" + ); + println!( + "AFTER ({TEX_COUNT} x 2MiB textures, {new_calls} UpdateTileMappings + {TEX_COUNT} Signals): submit={new_submit:?} gpu_done={new_total:?}" + ); + assert!(new_calls < old_calls); + } + } } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 591ca94cbb..92c04341d4 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -309,6 +309,24 @@ struct RecompAgg { wave_resolved: BTreeMap, /// `--example MNEMONIC`: listing of the first program missing it, its HLSL and profile example: Option<(String, String, &'static str)>, + /// `lane_masks` (direct DXIL): programs analysed, those with no guard left, vector + /// instructions, those still guarded, lane branches, uniform branches; failures by reason + lanes: [usize; 6], + lanes_failed: BTreeMap, + /// compute programs, per-lane DXIL (`lower_dxil`) vs #1426's per-instruction form: tried, + /// per-lane ok, per-instruction ok, both ok, per-lane bytes and per-instruction bytes where + /// both are ok; why the per-lane form refused (first words of the reason) + cs_forms: [usize; 6], + cs_lane_why: BTreeMap, + /// survey of every refusal, per stage (CS, MS): tried, wave64, per-lane ok, per-instruction + /// ok, both ok, per-lane refused only for instructions (no structural reason), the same with + /// the per-instruction form ok, refused by the lane-mask analysis + forms: BTreeMap, + /// "stage | reason" → programs (each reason once per program): every per-lane reason, the + /// structural ones that are a program's only structural reason, the per-instruction reasons + lane_every: BTreeMap, + lane_sole: BTreeMap, + inst_why: BTreeMap, } impl RecompAgg { @@ -349,6 +367,28 @@ impl RecompAgg { e.1 += b; } self.hlsl_bytes += o.hlsl_bytes; + for (a, b) in self.lanes.iter_mut().zip(o.lanes) { + *a += b; + } + for (k, v) in o.lanes_failed { + *self.lanes_failed.entry(k).or_default() += v; + } + for (a, b) in self.cs_forms.iter_mut().zip(o.cs_forms) { + *a += b; + } + for (k, v) in o.cs_lane_why { + *self.cs_lane_why.entry(k).or_default() += v; + } + for (k, v) in o.forms { + for (a, b) in self.forms.entry(k).or_default().iter_mut().zip(v) { + *a += b; + } + } + for (m, o) in [(&mut self.lane_every, o.lane_every), (&mut self.lane_sole, o.lane_sole), (&mut self.inst_why, o.inst_why)] { + for (k, v) in o { + *m.entry(k).or_default() += v; + } + } } fn add(&mut self, name: &str, code: &[u8], keep: usize, mode: recomp::Mode) { @@ -358,6 +398,20 @@ impl RecompAgg { return; } } + // `XCL_RECOMP_STAGES=CS,MS`: only programs of these stages + if let Ok(st) = std::env::var("XCL_RECOMP_STAGES") { + let l = match &mode { + recomp::Mode::Vertex(_) => "VS", + recomp::Mode::Pixel(_) => "PS", + recomp::Mode::Kernel => "kernel", + recomp::Mode::Mesh(_) => "MS", + recomp::Mode::Geometry(_) => "GS", + recomp::Mode::Compute(_) => "CS", + }; + if !st.split(',').any(|x| x == l) { + return; + } + } self.programs += 1; let wave64 = recomp::detect_wave64(code); self.wave32 += !wave64 as usize; @@ -389,6 +443,69 @@ impl RecompAgg { self.graphics_wave32 += 1; } } + if let recomp::Mode::Compute(cs) = &mode { + let lane = recomp::lower_dxil::compute_code(code, cs, wave64); + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; + let inst = crate::gpu::dxil::kernel::translate_compute(code, o, cs).map(|k| k.dxil); + self.cs_forms[0] += 1; + self.cs_forms[1] += lane.is_ok() as usize; + self.cs_forms[2] += inst.is_ok() as usize; + if let (Ok(a), Ok(b)) = (&lane, &inst) { + self.cs_forms[3] += 1; + self.cs_forms[4] += a.len(); + self.cs_forms[5] += b.len(); + } + if let Err(e) = &lane { + let key: String = e.split([':', '(']).next().unwrap_or("").split_whitespace().take(5).collect::>().join(" "); + *self.cs_lane_why.entry(key).or_default() += 1; + } + } + let survey_cs = match &mode { + recomp::Mode::Compute(cs) => Some(("CS", cs.clone())), + // the mesh pass is a compute pass of the NGG program: its threads in a 1-D group + recomp::Mode::Mesh(ms) => Some(("MS", recomp::CsInterface { threads: [ms.threads, 1, 1], tid_components: 1, ..Default::default() })), + _ => None, + }; + if let Some((st, cs)) = survey_cs { + let lane = recomp::lower_dxil::survey_compute_code(code, &cs, wave64); + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; + let inst = match &mode { + recomp::Mode::Mesh(ms) => crate::gpu::dxil::kernel::translate_mesh(code, o, ms).map(|_| ()), + _ => crate::gpu::dxil::kernel::translate_compute(code, o, &cs).map(|_| ()), + }; + let mut keys: Vec<(String, bool)> = lane.iter().map(|r| (survey_key(r), survey_structural(r))).collect(); + keys.sort(); + keys.dedup(); + let structural: Vec<&String> = keys.iter().filter(|k| k.1).map(|k| &k.0).collect(); + let lm = lane.len() == 1 && ["lane conditions", "indirect jump", "branch to the entry", "irreducible", "no fixpoint", "cannot decode"].iter().any(|w| lane[0].starts_with(w)); + let f = self.forms.entry(st.to_string()).or_default(); + let bridge = !lane.is_empty() && structural.is_empty(); + for (i, c) in [true, wave64, lane.is_empty(), inst.is_ok(), lane.is_empty() && inst.is_ok(), bridge, bridge && inst.is_ok(), lm].into_iter().enumerate() { + f[i] += c as usize; + } + for (k, _) in &keys { + *self.lane_every.entry(format!("{st} | {k}")).or_default() += 1; + } + if let [k] = structural[..] { + *self.lane_sole.entry(format!("{st} | {k}")).or_default() += 1; + } + if let Err(e) = &inst { + *self.inst_why.entry(format!("{st} | {}", survey_key(e.lines().next().unwrap_or("")))).or_default() += 1; + } + } + match recomp::lane_masks::analyze_code(code, wave64) { + Ok(s) => { + let counts = [1, s.guarded.is_empty() as usize, s.vector, s.guarded.len(), s.lane_branches, s.uniform_branches]; + for (a, b) in self.lanes.iter_mut().zip(counts) { + *a += b; + } + } + Err(why) => *self.lanes_failed.entry(why.to_string()).or_default() += 1, + } + // `XCL_RECOMP_NO_HLSL=1`: the direct DXIL survey alone + if std::env::var("XCL_RECOMP_NO_HLSL").is_ok() { + return; + } // `XCL_RECOMP_WINDOWS=4`: as a title with unified memory translates (`pso::mem_windows`) let mem_windows = std::env::var("XCL_RECOMP_WINDOWS").ok().and_then(|v| v.parse().ok()).unwrap_or(1); match recomp::translate(code, &recomp::Options { mode, wave64, mem_windows, ..Default::default() }) { @@ -1493,6 +1610,45 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim "VS/PS and the wave size (the driver picks it): wave32 {} (handled – the halves of a 64-wide wave run separately), wave64 {}; hazards in 32-thread waves: {:?}; reads of lanes ≥ 32 resolved (32-lane GPUs): {:?}", rc.graphics_wave32, rc.graphics_wave64, rc.wave_hazards, rc.wave_resolved ); + let c = &rc.cs_forms; + let mut why: Vec<_> = rc.cs_lane_why.iter().collect(); + why.sort_by(|a, b| b.1.cmp(a.1)); + println!( + "compute programs, direct DXIL: {} tried; per-lane form {} ok, per-instruction form (#1426) {} ok; where both are ok ({}): per-lane {} KB, per-instruction {} KB of DXIL; per-lane refused for: {:?}", + c[0], c[1], c[2], c[3], c[4] / 1024, c[5] / 1024, &why[..why.len().min(15)] + ); + for (st, f) in &rc.forms { + println!( + "{st} programs, every refusal: {} tried ({} wave64); per-lane ok {}, per-instruction ok {}, both {}; per-lane refused for instructions only {} (per-instruction ok on {} of them); lane-mask analysis refused {}", + f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7] + ); + } + for (title, m) in [ + ("per-lane reasons (stage | reason → programs; [S] structural)", &rc.lane_every), + ("the only structural reason of a program (stage | reason → programs)", &rc.lane_sole), + ("per-instruction form (#1426) refused (stage | first line → programs)", &rc.inst_why), + ] { + let mut v: Vec<_> = m.iter().collect(); + v.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0))); + println!("{title}:"); + for (k, n) in v.iter().take(top.max(40)) { + let tag = if survey_structural(k.split(" | ").nth(1).unwrap_or("")) { "[S] " } else { "" }; + println!(" {n:>6} {tag}{k}"); + } + } + let l = &rc.lanes; + println!( + "lane masks (direct DXIL, no EXEC emulation): analysed {} of {} programs, {} with no guard left; vector instructions {}, still guarded {} ({:.1}%); branches per lane {}, uniform {}; not analysed: {:?}", + l[0], + rc.programs, + l[1], + l[2], + l[3], + l[3] as f64 * 100.0 / l[2].max(1) as f64, + l[4], + l[5], + rc.lanes_failed + ); if let Some((x, hlsl, profile)) = &rc.example { println!("example: {x}"); @@ -1713,6 +1869,14 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: let max_bytes = opt("--max-bytes").map(|v| v as usize).unwrap_or(16384); let timeout = std::time::Duration::from_secs(opt("--timeout").unwrap_or(10)); let skipped = AtomicUsize::new(0); + // `--lanes`: compute programs through the per-lane form too (`recomp::lower_dxil`); where it + // translates, its DXIL size against the per-instruction form's, and the refusals ranked + let lanes = args.iter().any(|a| a == "--lanes"); + let lanes_tried = AtomicUsize::new(0); + let lanes_ok = AtomicUsize::new(0); + let lanes_bytes = AtomicUsize::new(0); + let lanes_vs = AtomicUsize::new(0); + let lanes_why: Mutex> = Mutex::new(HashMap::new()); // `--hash H`: only the container whose `[SHADER]` hash (FNV-64 of the container) is H, every // record searched; `--dump DIR`: write each program's direct DXIL (and with `--compare` the // HLSL path's source and DXIL) to DIR, for diffing the two (`dxc -dumpbin`) @@ -1767,6 +1931,26 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) }; let time = t.elapsed(); + if let (true, recomp::Mode::Compute(cs)) = (lanes, &mode) { + lanes_tried.fetch_add(1, Ordering::Relaxed); + // under the sweep's timeout too (the thread is left to finish) + let (tx, rx) = std::sync::mpsc::channel(); + let (c, csc) = (code.to_vec(), cs.clone()); + std::thread::spawn(move || { + let _ = tx.send(recomp::lower_dxil::compute_with(&c, &csc, o)); + }); + match rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) { + Ok(k) => { + lanes_ok.fetch_add(1, Ordering::Relaxed); + lanes_bytes.fetch_add(k.dxil.len(), Ordering::Relaxed); + lanes_vs.fetch_add(r.as_ref().map_or(0, |d| d.len()), Ordering::Relaxed); + if trace { + eprintln!("per-lane: {name} FSSM#{fi}: {} B, per-instruction {:?} B", k.dxil.len(), r.as_ref().map(|d| d.len())); + } + } + Err(e) => *lanes_why.lock().unwrap().entry(survey_key(&e)).or_default() += 1, + } + } let dump = |suffix: &str, bytes: &[u8]| { if let Some(d) = &dump_dir { let _ = std::fs::write(d.join(format!("{blob_hash:016x}_f{fi}_{:x}.{suffix}", p.offset)), bytes); @@ -1809,8 +1993,62 @@ fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std: println!("{}", rep.json(top)); } else { println!("{} programs from {} sampled records (seed {seed}; {} over {max_bytes} B skipped){}{}", results.len(), order.len().min(input.len()), skipped.load(Ordering::Relaxed), if validate { ", validated" } else { "" }, if compare { ", compared with HLSL+DXC" } else { "" }); + if lanes { + let mut why: Vec<(String, usize)> = lanes_why.into_inner().unwrap().into_iter().collect(); + why.sort_by(|a, b| b.1.cmp(&a.1)); + why.truncate(top); + println!("per-lane form: {} of {} compute programs; where it translates, {} B against {} B per instruction; refused for: {why:?}", lanes_ok.load(Ordering::Relaxed), lanes_tried.load(Ordering::Relaxed), lanes_bytes.load(Ordering::Relaxed), lanes_vs.load(Ordering::Relaxed)); + } print!("{}", rep.text(top)); println!("time {:.1} s", t0.elapsed().as_secs_f64()); } 0 } + +/// A survey reason without its program's numbers: registers as `sN`, other numbers as `N` +/// (an `s_setreg`'s hardware register is kept), at most eight words. +fn survey_key(r: &str) -> String { + let r = r.split(" (").next().unwrap_or(r); + let words: Vec<&str> = r.split_whitespace().collect(); + let mut out: Vec = Vec::new(); + for (i, raw) in words.iter().enumerate() { + let w = raw.trim_end_matches([':', ',']); + let digits = |x: &str| !x.is_empty() && x.bytes().all(|b| b.is_ascii_digit()); + let w = if w.strip_prefix('s').is_some_and(digits) { + "sN".to_string() + } else if digits(w) && !(i > 0 && words[i - 1] == "hwreg") { + "N".to_string() + } else { + w.to_string() + }; + out.push(if raw.ends_with(':') { format!("{w}:") } else { w }); + if out.len() == 8 { + break; + } + } + out.join(" ") +} + +/// A per-lane refusal no instruction lowering removes (the CFG, masks across joins, lanes +/// elsewhere, the group shape), as opposed to an instruction the per-lane form lacks. +fn survey_structural(r: &str) -> bool { + [ + "2-D / 3-D", + "elsewhere", + "read as a number", + "read as a mask", + "across two masks", + "successors", + "unsupported branch", + "neither a number nor a mask", + "empty program", + "lane conditions", + "indirect jump", + "branch to the entry", + "irreducible", + "no fixpoint", + "cannot decode", + ] + .iter() + .any(|w| r.contains(w)) +} diff --git a/scripts/smoke-title.tests.ps1 b/scripts/smoke-title.tests.ps1 new file mode 100644 index 0000000000..1c94bbbfc6 --- /dev/null +++ b/scripts/smoke-title.tests.ps1 @@ -0,0 +1,40 @@ +# Run with powershell.exe or pwsh.exe. Checks the `title:` line of smoke.ps1's block (#677): the +# hash of the game folder's name, as Python's hashlib.sha256(name.strip().encode()).hexdigest()[:8] +# gives it, or the -Title label. A fixture stands in for xcl.exe. +$ErrorActionPreference = 'Stop' +$smoke = Join-Path $PSScriptRoot 'smoke.ps1' +$fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-smoke-title-' + [guid]::NewGuid()) +$null = New-Item -ItemType Directory -Path $fixture +try { + $xcl = Join-Path $fixture 'xcl.cmd' + [IO.File]::WriteAllText($xcl, "@echo off`r`necho Log: %~dp0xcl.log`r`n") + [IO.File]::WriteAllText((Join-Path $fixture 'xcl.log'), "(1 frames shown, 1 PresentX calls)`n") + function Get-SmokeTitle([hashtable]$Arguments) { + $block = & $smoke -Seconds 1 -Xcl $xcl @Arguments + $line = $block -split "`n" | Where-Object { $_ -like 'title:*' } + $line.Substring('title: '.Length).Trim() + } + # names built from character codes: this file stays ASCII for Windows PowerShell 5.1 + $cases = @( + @('SomeTitle', '27693731'), + @(('Caf' + [char]0xE9 + ' Folder'), '5256b5ea'), + @(([string][char]0x65E5 + [char]0x672C + ' pack ' + [char]::ConvertFromUtf32(0x1F3AE)), 'dbd98f4b'), + @(' Padded Name ', 'f8b1d479') + ) + foreach ($case in $cases) { + foreach ($game in @("D:\Games\$($case[0])", "D:\Games\$($case[0])\")) { + $got = Get-SmokeTitle @{ Game = $game } + if ($got -ne $case[1]) { throw "title of '$game' is '$got', expected '$($case[1])'" } + } + } + $got = Get-SmokeTitle @{ Game = 'D:\Games\SomeTitle'; Title = ' my label: one ' } + if ($got -ne 'my label: one') { throw "-Title printed '$got'" } + foreach ($bad in @('', ' ', "a`nb", 'a`b', ('a' + [char]0x2028 + 'commit: 0123456'), ('a' + [char]0x85 + 'b'))) { + $threw = $false + try { $null = & $smoke -Game 'D:\Games\SomeTitle' -Seconds 1 -Xcl $xcl -Title $bad } catch { $threw = $true } + if (-not $threw) { throw "-Title '$bad' was accepted" } + } + 'smoke-title: ok' +} finally { + Remove-Item -LiteralPath $fixture -Recurse -Force +} diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 index f0738cdb98..b7859c9242 100644 --- a/scripts/smoke.ps1 +++ b/scripts/smoke.ps1 @@ -2,16 +2,32 @@ # prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built # from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). # -# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] +# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] [-Title