From b07fbab305851670339b15993a1fb97891941d28 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:09:22 -0500 Subject: [PATCH 1/7] dxil: geometry mode (ES+GS) in the direct translator The recompiler's Mode::Geometry as a direct compute pass: the ES for the three vertices of 21 triangles per group (pre-fetched inputs), s_setpc_b64 into the GS, s_sendmsg GS emit / cut building strip triangles per lane, and the mesh record (vertex / triangle counts, vertices copied from the GS output area in LDS, triangles) written after wave prefix sums. The split wave64 form runs the ES in both hardware waves, then a group barrier and the GS in the lower wave with fresh registers, as the HLSL kernel does. cfg::Cfg::build_geometry, lower_geom.rs; pso::console_geometry tries it under XCL_DIRECT_DXIL=1 (HLSL fallback); coverage routes Mode::Geometry. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/cfg.rs | 33 +++- crates/xcl/src/gpu/dxil/core_tests.rs | 54 ++++++ crates/xcl/src/gpu/dxil/coverage.rs | 5 +- crates/xcl/src/gpu/dxil/kernel.rs | 221 ++++++++++++++++++++- crates/xcl/src/gpu/dxil/lower.rs | 5 + crates/xcl/src/gpu/dxil/lower_geom.rs | 269 ++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_mem.rs | 1 + crates/xcl/src/gpu/dxil/mod.rs | 1 + crates/xcl/src/gpu/recomp/pso.rs | 14 ++ crates/xcl/src/gpu/recomp/tests.rs | 15 +- 10 files changed, 606 insertions(+), 12 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/lower_geom.rs diff --git a/crates/xcl/src/gpu/dxil/cfg.rs b/crates/xcl/src/gpu/dxil/cfg.rs index d85243f8e3..b76ec81a3c 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 { diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index a754a072a5..25e03a4c7a 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -279,3 +279,57 @@ 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)])); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/coverage.rs b/crates/xcl/src/gpu/dxil/coverage.rs index 62c7a84ec7..83941fda32 100644 --- a/crates/xcl/src/gpu/dxil/coverage.rs +++ b/crates/xcl/src/gpu/dxil/coverage.rs @@ -239,7 +239,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 +394,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/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 371ac0622c..bbe02cedb6 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -17,7 +17,7 @@ use super::lower::{ComputeInit, Init, Lw, Partner, VAR_BUDGET, VAR_SCC, VAR_VGPR use super::module::{Block, Pred, Value}; use super::shader::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::recomp::{CsInterface, GsInterface, MsInterface, PsInterface, VsInterface, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS, MESH_HEADER}; #[derive(Debug, Clone, Copy)] pub struct KernelOptions { @@ -84,6 +84,12 @@ 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 { @@ -92,6 +98,7 @@ enum Entry { Mesh(MsInterface), Vertex(VsInterface), Pixel(PsInterface), + Geometry(GsInterface), } /// A compute-mode program (the CS ABI of `cs`). @@ -121,7 +128,14 @@ fn translate_entry(code: &[u8], o: KernelOptions, entry: Entry) -> Result Result { - let cfg = Cfg::build(code)?; + let geo = match &entry { + Entry::Geometry(g) => Some(g.clone()), + _ => None, + }; + let cfg = match &geo { + Some(g) => Cfg::build_geometry(code, g.gs_start)?, + None => Cfg::build(code)?, + }; let split = o.wave64 && o.split; let kernel = matches!(entry, Entry::Kernel); let cs = match &entry { @@ -141,7 +155,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu }; 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 res = if kernel || ms.is_some() || geo.is_some() { Some(s.raw_uav(1, 0)) } else { None }; // compute work across groups relies on coherent memory (as the HLSL compute mode's // `globallycoherent` windows) let mems: Vec<_> = (0..o.mem_windows.clamp(1, 4)).map(|k| if cs.is_some() { s.raw_uav_coherent(2 + k, 0) } else { s.raw_uav(2 + k, 0) }).collect(); @@ -180,6 +194,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu dpp_enable: None, partner: Partner::Present, mesh: None, + geom: None, gfx: None, gfx_half: None, whole_live: Default::default(), @@ -194,7 +209,8 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu } // 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; + // geometry mode always has the LDS (the ES ring and the GS output) + let mut uses_lds = geo.is_some(); let mut slot = 1u32; for d in &cfg.insts { let n = d.inst.name; @@ -222,6 +238,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu 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); @@ -257,6 +274,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| { @@ -294,6 +320,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; @@ -303,18 +339,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); @@ -324,6 +393,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); @@ -333,7 +407,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); @@ -349,6 +443,21 @@ 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); @@ -518,3 +627,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 b1499d1381..a33c53fb77 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -185,6 +185,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) @@ -889,6 +891,9 @@ 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 NOOPS.contains(&name.as_str()) { return Ok(()); } 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_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 9b80d12221..fbc9802528 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -1417,6 +1417,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/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index 64cb156681..3f82887f10 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -19,6 +19,7 @@ pub mod graphics; pub mod kernel; mod lanes; pub mod lower; +mod lower_geom; mod lower_gfx; mod lower_image; mod lower_mem; diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 46e237b2c1..9df52f882d 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -785,6 +785,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/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0705c45933..f8f87d2715 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3881,12 +3881,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 From 2dcc926d80b82c7963be884a154666437f58ba35 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:07:40 -0500 Subject: [PATCH 2/7] dxil: Texture2DMS / Texture2DMSArray ops, MSAA image loads in the direct translator ops.rs: TexKind::D2MS / D2MSArray, texture_load_sample, Texture2DMSGetSamplePosition, RenderTargetGetSampleCount / SamplePosition. lower_image.rs: image_load and image_msaa_load (one component of four samples) on 2D MSAA (array) T#s, the fragment index as sample index (no FMASK in D3D12), samples past the count read 0; image_get_resinfo (one level). Stores / atomics (RWTexture2DMS, SM 6.7) and sampling stay translation errors. runner.rs (test only): TexDim::D2Ms / D2MsArray filled sample by sample with a per-sample draw. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/lower_image.rs | 93 +++++++++ crates/xcl/src/gpu/dxil/mod.rs | 2 + crates/xcl/src/gpu/dxil/msaa_tests.rs | 254 +++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/ops.rs | 40 +++- crates/xcl/src/gpu/recomp/runner.rs | 157 ++++++++++++++- 5 files changed, 540 insertions(+), 6 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/msaa_tests.rs diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index fd93832e67..c9a1358a6d 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -427,8 +427,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 { @@ -638,6 +653,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 +702,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 +822,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/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index 3f82887f10..3415ddfe9d 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -43,3 +43,5 @@ mod ops_tests; mod bitreader_tests; #[cfg(test)] mod robustness_tests; +#[cfg(test)] +mod msaa_tests; 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/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()); From 65154b3b315fe4ed24b27bb17f787b8895fd3eef Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:19:26 -0500 Subject: [PATCH 3/7] dxil: directed f32 rounding (MODE round toward +inf / -inf / zero) Programs writing a non-default MODE[1:0] track MODE[1:0] / FP_DENORM single in an SSA variable; f32 add/sub/mul/fma/mad/fmac/fmamk/fmaak/div_fmas, int and f64 conversions, ldexp and sqrt compute exactly (f64 products, TwoSum) and round on the bits by the mode, denormals flushed as FP_DENORM says. Constant modes fold, run-time modes select per instruction. Direct-only (DXIL has no directed rounding). Tests against an integer CPU reference; docs. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/kernel.rs | 2 + crates/xcl/src/gpu/dxil/lower.rs | 34 +- crates/xcl/src/gpu/dxil/lower_round.rs | 478 +++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_valu.rs | 130 +++++++ crates/xcl/src/gpu/dxil/lower_wide.rs | 1 + crates/xcl/src/gpu/dxil/mod.rs | 3 + crates/xcl/src/gpu/dxil/round_tests.rs | 449 +++++++++++++++++++++++ 7 files changed, 1094 insertions(+), 3 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/lower_round.rs create mode 100644 crates/xcl/src/gpu/dxil/round_tests.rs diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index bbe02cedb6..c5c34f3cd6 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -180,6 +180,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Resu 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, @@ -303,6 +304,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; diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index a33c53fb77..b803df6e57 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); } @@ -158,6 +161,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)>, @@ -894,6 +900,9 @@ impl Lw { 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(()); } @@ -957,7 +966,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 { @@ -979,6 +991,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(()); } @@ -986,7 +1014,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 { @@ -1004,7 +1032,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_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/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index 3415ddfe9d..ceef29a783 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -23,6 +23,7 @@ mod lower_geom; mod lower_gfx; mod lower_image; mod lower_mem; +mod lower_round; mod lower_valu; mod lower_wide; pub mod module; @@ -45,3 +46,5 @@ mod bitreader_tests; mod robustness_tests; #[cfg(test)] mod msaa_tests; +#[cfg(test)] +mod round_tests; 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}"); +} From f458b55214dc0cf74fa5383d3a334ee434f65781 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:31:16 -0500 Subject: [PATCH 4/7] dxil: fuzz tests (random programs, direct vs HLSL on the GPU) Restores fuzz_tests.rs, left out of #1426 only for the diff-size limit. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/fuzz_tests.rs | 1276 +++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/mod.rs | 2 + 2 files changed, 1278 insertions(+) create mode 100644 crates/xcl/src/gpu/dxil/fuzz_tests.rs 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..552856faa2 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/fuzz_tests.rs @@ -0,0 +1,1276 @@ +//! 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!("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); + } +} diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index ceef29a783..1185c040b9 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -45,6 +45,8 @@ mod bitreader_tests; #[cfg(test)] mod robustness_tests; #[cfg(test)] +mod fuzz_tests; +#[cfg(test)] mod msaa_tests; #[cfg(test)] mod round_tests; From 210f773557fe478c9acc53d8c87abc02eb38ec74 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:14:38 -0500 Subject: [PATCH 5/7] dxil fuzz: amd_reduced_seeds (ignored) for seeds 722 / 1599; debug_seed FUZZ_WATCH Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/fuzz_tests.rs | 88 +++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/fuzz_tests.rs b/crates/xcl/src/gpu/dxil/fuzz_tests.rs index 552856faa2..b0f25311b8 100644 --- a/crates/xcl/src/gpu/dxil/fuzz_tests.rs +++ b/crates/xcl/src/gpu/dxil/fuzz_tests.rs @@ -1209,6 +1209,14 @@ fn debug_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); @@ -1274,3 +1282,83 @@ fn shader_flags_follow_plain_instruction_types() { 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"); +} From ee85bc2686e0df7a818cd5fa0f3889e632a274e7 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:33:51 -0500 Subject: [PATCH 6/7] dxil: geometry GPU record test (loops, cuts), CfgBlock::pc for split copies, TRANSLATOR_VERSION 5 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/cfg.rs | 4 +- crates/xcl/src/gpu/dxil/geometry_tests.rs | 174 ++++++++++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 2 +- crates/xcl/src/gpu/dxil/mod.rs | 2 + 4 files changed, 179 insertions(+), 3 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/geometry_tests.rs diff --git a/crates/xcl/src/gpu/dxil/cfg.rs b/crates/xcl/src/gpu/dxil/cfg.rs index b76ec81a3c..31b3dcec2a 100644 --- a/crates/xcl/src/gpu/dxil/cfg.rs +++ b/crates/xcl/src/gpu/dxil/cfg.rs @@ -203,7 +203,7 @@ fn make_reducible(blocks: &mut Vec) -> Result<(Vec, BTreeSet usize| match term { Term::Jump(x) => *x = to(*x), @@ -330,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/geometry_tests.rs b/crates/xcl/src/gpu/dxil/geometry_tests.rs new file mode 100644 index 0000000000..7684904250 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/geometry_tests.rs @@ -0,0 +1,174 @@ +//! 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, where the HLSL path's records must agree too. +/// +/// The HLSL path's *split* form is not compared: with branches in the GS it emits the ES's +/// `s_setpc_b64` as a fall-through into the GS code and gives the GS phase's entry pc no +/// dispatcher case, so the ES phase runs the GS and the GS phase nothing (empty records). +#[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); + if !split { + 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("HLSL, native", &got); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index c5c34f3cd6..8a5c92c0ee 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -35,7 +35,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 = 4; +pub const TRANSLATOR_VERSION: u32 = 5; /// `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. diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index 1185c040b9..1a592eb662 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -50,3 +50,5 @@ mod fuzz_tests; mod msaa_tests; #[cfg(test)] mod round_tests; +#[cfg(test)] +mod geometry_tests; From 2a2d54b0ff51388528b7015f96a98221525c0437 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:10:36 -0500 Subject: [PATCH 7/7] dxil: geometry record test also compares the HLSL split form (fixed by #1689) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/geometry_tests.rs | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/geometry_tests.rs b/crates/xcl/src/gpu/dxil/geometry_tests.rs index 7684904250..57d4cce9a9 100644 --- a/crates/xcl/src/gpu/dxil/geometry_tests.rs +++ b/crates/xcl/src/gpu/dxil/geometry_tests.rs @@ -119,11 +119,7 @@ fn expected_records(g: &GsInterface, prims: usize) -> Vec { /// 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, where the HLSL path's records must agree too. -/// -/// The HLSL path's *split* form is not compared: with branches in the GS it emits the ES's -/// `s_setpc_b64` as a fall-through into the GS code and gives the GS phase's entry pc no -/// dispatcher case, so the ES phase runs the GS and the GS phase nothing (empty records). +/// (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) { @@ -163,12 +159,10 @@ fn gpu_geometry_direct_records() { 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); - if !split { - 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("HLSL, native", &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); } }