diff --git a/crates/xcl/src/gpu/dxil/bitreader_tests.rs b/crates/xcl/src/gpu/dxil/bitreader_tests.rs new file mode 100644 index 000000000..5e888eeb5 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/bitreader_tests.rs @@ -0,0 +1,155 @@ +//! A test-only reader for the bitstream [`super::bitstream::BitWriter`] +//! produces (unabbreviated records only), used to check record layouts +//! that the validator and disassembler do not distinguish (e.g. atomic +//! ordering codes the LLVM reader maps leniently). + +use super::module::{BinOp, Module, RmwOp}; + +#[derive(Debug, Default)] +pub(super) struct Block { + pub id: u32, + pub records: Vec<(u32, Vec)>, + pub blocks: Vec, +} + +impl Block { + /// Depth-first search for the first block with `id`. + pub fn find(&self, id: u32) -> Option<&Block> { + if self.id == id { + return Some(self); + } + self.blocks.iter().find_map(|b| b.find(id)) + } + pub fn records_with(&self, code: u32) -> Vec<&[u64]> { + self.records.iter().filter(|r| r.0 == code).map(|r| &r.1[..]).collect() + } +} + +struct Reader<'a> { + b: &'a [u8], + pos: usize, // bit position +} + +impl Reader<'_> { + fn fixed(&mut self, w: u32) -> u64 { + let mut v = 0u64; + for i in 0..w { + let bit = (self.b[self.pos / 8] >> (self.pos % 8)) & 1; + v |= (bit as u64) << i; + self.pos += 1; + } + v + } + fn vbr(&mut self, w: u32) -> u64 { + let hi = 1u64 << (w - 1); + let (mut v, mut shift) = (0u64, 0); + loop { + let c = self.fixed(w); + v |= (c & (hi - 1)) << shift; + shift += w - 1; + if c & hi == 0 { + return v; + } + } + } + fn align32(&mut self) { + self.pos = self.pos.div_ceil(32) * 32; + } + fn block(&mut self, id: u32, width: u32, end_bit: Option) -> Block { + let mut blk = Block { id, ..Default::default() }; + loop { + if end_bit.is_none() && self.pos + width as usize > self.b.len() * 8 { + return blk; + } + match self.fixed(width) { + 0 => { + self.align32(); + if let Some(e) = end_bit { + assert_eq!(self.pos, e, "block length mismatch for block {id}"); + } + return blk; + } + 1 => { + let sub = self.vbr(8) as u32; + let w = self.vbr(4) as u32; + self.align32(); + let words = self.fixed(32) as usize; + let end = self.pos + words * 32; + blk.blocks.push(self.block(sub, w, Some(end))); + } + 3 => { + let code = self.vbr(6) as u32; + let n = self.vbr(6); + let ops = (0..n).map(|_| self.vbr(6)).collect(); + blk.records.push((code, ops)); + } + a => panic!("unexpected abbreviation id {a}"), + } + } + } +} + +/// Parses bitcode (with the `BC\xC0\xDE` magic) into its block tree; the +/// root is a pseudo block with id `u32::MAX`. +pub(super) fn parse(bc: &[u8]) -> Block { + assert_eq!(&bc[..4], b"BC\xC0\xDE"); + let mut r = Reader { b: &bc[4..], pos: 0 }; + r.block(u32::MAX, 2, None) +} + +const BLOCK_FUNCTION: u32 = 12; +const FUNC_CODE_INST_ATOMICRMW: u32 = 38; +const FUNC_CODE_INST_CMPXCHG: u32 = 46; +/// `bitc::ORDERING_SEQCST` (the in-memory `AtomicOrdering` value is 7, the +/// bitcode code is 6). +const ORDERING_SEQCST: u64 = 6; + +fn atomic_module() -> Vec { + let mut m = Module::new(); + m.define_entry("main"); + let i32 = m.i32(); + let arr = m.array(4, i32); + let g = m.global("g", arr, 3, None, false, 4); + let zero = m.i32c(0); + let p = m.gep(g, &[zero, zero]); + let one = m.i32c(1); + let a = m.atomic_rmw(RmwOp::Add, p, one); + let b = m.cmpxchg(p, a, one); + let _ = m.bin(BinOp::Add, a, b); + m.ret(); + m.to_bitcode("dxil-ms-dx", "") +} + +#[test] +fn reader_round_trips_block_structure() { + let bc = atomic_module(); + let root = parse(&bc); + assert!(root.find(8).is_some(), "module block"); + assert!(root.find(BLOCK_FUNCTION).is_some(), "function block"); +} + +#[test] +fn atomics_use_bitcode_ordering_codes() { + let root = parse(&atomic_module()); + let f = root.find(BLOCK_FUNCTION).unwrap(); + let rmw = f.records_with(FUNC_CODE_INST_ATOMICRMW); + assert_eq!(rmw.len(), 1); + // [ptr, val, op, vol, ordering, synchscope] + assert_eq!(rmw[0][4], ORDERING_SEQCST, "atomicrmw ordering: {:?}", rmw[0]); + assert_eq!(rmw[0][5], 1, "crossthread synch scope"); + let cx = f.records_with(FUNC_CODE_INST_CMPXCHG); + assert_eq!(cx.len(), 1); + // [ptr, cmp, new, vol, success, synchscope, failure, weak] + assert_eq!(cx[0][4], ORDERING_SEQCST, "cmpxchg success ordering: {:?}", cx[0]); + assert_eq!(cx[0][6], ORDERING_SEQCST, "cmpxchg failure ordering: {:?}", cx[0]); +} + +#[test] +fn float_constants_ignore_bits_above_their_width() { + let mut m = Module::new(); + let (f16, f32) = (m.f16(), m.f32()); + let one = m.f32c(1.0f32.to_bits()); + assert_eq!(m.const_float(f32, 0xFFFF_0000_0000_0000 | 1.0f32.to_bits() as u64), one); + let h = m.const_float(f16, 0x3C00); + assert_eq!(m.const_float(f16, 0x1_3C00), h); +} diff --git a/crates/xcl/src/gpu/dxil/bitstream.rs b/crates/xcl/src/gpu/dxil/bitstream.rs new file mode 100644 index 000000000..70757093f --- /dev/null +++ b/crates/xcl/src/gpu/dxil/bitstream.rs @@ -0,0 +1,155 @@ +//! LLVM bitstream writer: fixed and VBR fields, nested blocks with +//! back-patched lengths, and unabbreviated records. +//! +//! DXIL accepts the plain bitstream container without any abbreviations, +//! which keeps the writer small; size is not a concern for shader modules +//! (the driver re-encodes them anyway). + +/// Bit-level writer, little-endian within 32-bit words as LLVM defines. +pub struct BitWriter { + out: Vec, + acc: u64, + nbits: u32, + /// Open blocks: (byte offset of the length word, outer abbreviation width). + blocks: Vec<(usize, u32)>, + width: u32, +} + +/// Abbreviation width used for every block we open (IDs 0..3 need 2 bits). +pub const ABBREV_WIDTH: u32 = 3; + +impl Default for BitWriter { + fn default() -> Self { + Self::new() + } +} + +impl BitWriter { + pub fn new() -> Self { + BitWriter { out: Vec::new(), acc: 0, nbits: 0, blocks: Vec::new(), width: 2 } + } + + pub fn emit(&mut self, value: u64, width: u32) { + debug_assert!(width <= 32); + debug_assert!(width == 64 || value >> width == 0, "value {value:#x} does not fit {width} bits"); + self.acc |= value << self.nbits; + self.nbits += width; + while self.nbits >= 8 { + self.out.push(self.acc as u8); + self.acc >>= 8; + self.nbits -= 8; + } + } + + pub fn vbr(&mut self, mut value: u64, width: u32) { + let hi = 1u64 << (width - 1); + while value >= hi { + self.emit((value & (hi - 1)) | hi, width); + value >>= width - 1; + } + self.emit(value, width); + } + + pub fn align32(&mut self) { + if self.nbits > 0 { + self.emit(0, 8 - self.nbits); + } + while self.out.len() % 4 != 0 { + self.out.push(0); + } + } + + pub fn enter_block(&mut self, id: u32) { + self.emit(1, self.width); // ENTER_SUBBLOCK + self.vbr(id as u64, 8); + self.vbr(ABBREV_WIDTH as u64, 4); + self.align32(); + let at = self.out.len(); + self.out.extend_from_slice(&[0; 4]); + self.blocks.push((at, self.width)); + self.width = ABBREV_WIDTH; + } + + pub fn end_block(&mut self) { + self.emit(0, self.width); // END_BLOCK + self.align32(); + let (at, outer) = self.blocks.pop().expect("end_block without enter_block"); + let words = ((self.out.len() - at - 4) / 4) as u32; + self.out[at..at + 4].copy_from_slice(&words.to_le_bytes()); + self.width = outer; + } + + /// An unabbreviated record. + pub fn record(&mut self, code: u32, ops: &[u64]) { + self.emit(3, self.width); // UNABBREV_RECORD + self.vbr(code as u64, 6); + self.vbr(ops.len() as u64, 6); + for &op in ops { + self.vbr(op, 6); + } + } + + /// A record whose operands are the bytes of a string. + pub fn record_str(&mut self, code: u32, prefix: &[u64], s: &str) { + let mut ops = prefix.to_vec(); + ops.extend(s.bytes().map(u64::from)); + self.record(code, &ops); + } + + pub fn finish(mut self) -> Vec { + assert!(self.blocks.is_empty(), "unterminated bitstream block"); + self.align32(); + self.out + } +} + +/// LLVM's signed VBR operand encoding: sign in bit 0. +pub fn signed(v: i64) -> u64 { + if v >= 0 { + (v as u64) << 1 + } else if v == i64::MIN { + 1 // "-0": LLVM's encoding of INT64_MIN + } else { + ((v.unsigned_abs()) << 1) | 1 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vbr_and_fixed_fields_pack_little_endian() { + let mut w = BitWriter::new(); + w.emit(0b10, 2); + w.vbr(5, 3); // 0b101 needs continuation in 3-bit VBR: chunks 01|1, 01|0... check value round trip below + w.align32(); + let bytes = w.finish(); + assert_eq!(bytes.len(), 4); + // Decode back: 2 bits, then VBR3. + let word = u32::from_le_bytes(bytes[..4].try_into().unwrap()); + assert_eq!(word & 3, 0b10); + let (c0, c1) = ((word >> 2) & 7, (word >> 5) & 7); + assert_eq!(c0, 0b101); // low 2 bits of 5 = 01, continuation bit set + assert_eq!(c1, 0b001); // remaining 1, no continuation + } + + #[test] + fn block_lengths_are_back_patched_in_words() { + let mut w = BitWriter::new(); + w.enter_block(8); + w.record(1, &[1]); + w.end_block(); + let b = w.finish(); + let len = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize; + assert_eq!(b.len(), 8 + len * 4); + } + + #[test] + fn signed_vbr_operands() { + assert_eq!(signed(0), 0); + assert_eq!(signed(3), 6); + assert_eq!(signed(-3), 7); + assert_eq!(signed(i64::MIN), 1); + } +} diff --git a/crates/xcl/src/gpu/dxil/cfg.rs b/crates/xcl/src/gpu/dxil/cfg.rs new file mode 100644 index 000000000..d85243f8e --- /dev/null +++ b/crates/xcl/src/gpu/dxil/cfg.rs @@ -0,0 +1,318 @@ +//! Basic blocks of a decoded RDNA2 program, their edges and a reverse +//! post-order (the emission order: every block after its dominators). + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::gpu::rdna2::{self, Decoded}; + +/// How a block ends. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Term { + /// falls through / jumps to the block (index) + Jump(usize), + /// conditional branch: (instruction index of the branch, taken, not taken) + Cond(usize, usize, usize), + /// s_endpgm or the end of the code + End, +} + +pub struct CfgBlock { + /// instruction indices (the terminating branch excluded for `Cond`/`Jump` by branch) + pub insts: Vec, + pub term: Term, + pub preds: Vec, +} + +pub struct Cfg { + pub insts: Vec, + pub blocks: Vec, + /// reachable blocks in reverse post-order (blocks[rpo[0]] is the entry) + pub rpo: Vec, + /// targets of back edges (loop headers) + pub headers: BTreeSet, +} + +fn is_end(name: &str) -> bool { + matches!(name, "S_ENDPGM" | "S_ENDPGM_SAVED" | "S_ENDPGM_ORDERED_PS_DONE") +} + +impl Cfg { + pub fn build(code: &[u8]) -> Result { + let mut insts: Vec = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let d = rdna2::decode(&code[off..], off as u64).map_err(|e| format!("+{off:#x}: cannot decode ({e:?})"))?; + off += d.len; + insts.push(d); + } + 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]); + for (i, d) in insts.iter().enumerate() { + 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); + leaders.insert(i + 1); + } else if d.inst.flags & rdna2::F_TERMINATOR != 0 || is_end(d.inst.name) { + leaders.insert(i + 1); + } + } + let starts: Vec = leaders.into_iter().filter(|&l| l < insts.len()).collect(); + let block_of: BTreeMap = starts.iter().enumerate().map(|(b, &i)| (i, b)).collect(); + let mut blocks = Vec::new(); + for (b, &s) in starts.iter().enumerate() { + let e = starts.get(b + 1).copied().unwrap_or(insts.len()); + let mut list = Vec::new(); + let mut term = if e < insts.len() { Term::Jump(b + 1) } else { Term::End }; + for i in s..e { + let d = &insts[i]; + if is_end(d.inst.name) { + term = Term::End; + break; + } + if let Some(t) = rdna2::branch_target(d) { + let tb = block_of[&index[&t]]; + let name = d.inst.name; + term = if name == "S_BRANCH" || d.far_target.is_some() { + Term::Jump(tb) + } else { + let next = if e < insts.len() { b + 1 } else { usize::MAX }; + if next == usize::MAX { + return Err(format!("+{:#x}: conditional branch at the end of the code", d.pc)); + } + Term::Cond(i, tb, next) + }; + break; + } + list.push(i); + } + blocks.push(CfgBlock { insts: list, term, preds: Vec::new() }); + } + // a conditional branch whose both edges meet is a jump + for b in &mut blocks { + if let Term::Cond(_, t, f) = b.term { + if t == f { + b.term = Term::Jump(t); + } + } + } + // DXIL requires reducible control flow (AMD's compiler faults on an irreducible + // CFG; the console compiler emits loops entered in the middle): split nodes until + // every retreating edge is a back edge to a dominator + let (post, headers) = make_reducible(&mut blocks)?; + let succ = succ_of; + let reach: BTreeSet = post.iter().copied().collect(); + for &b in &post { + for t in succ(&blocks[b]) { + if !blocks[t].preds.contains(&b) { + blocks[t].preds.push(b); + } + } + } + let _ = reach; + Ok(Cfg { insts, blocks, rpo: post, headers }) + } +} + +/// Makes the CFG reducible by splitting: for an irreducible edge's innermost multi-entry +/// cycle region, the region minus its first entry (in RPO) is copied for the edges entering +/// it elsewhere. The reverse post-order and loop headers of the result; gives up past four +/// times the original block count. +fn make_reducible(blocks: &mut Vec) -> Result<(Vec, BTreeSet), String> { + let limit = 4 * blocks.len() + 256; + loop { + let (post, headers) = order(blocks); + let Some((_, t)) = irreducible_edge(blocks, &post) else { return Ok((post, headers)) }; + let n = blocks.len(); + let mut pos = vec![usize::MAX; n]; + for (i, &b) in post.iter().enumerate() { + pos[b] = i; + } + let mut preds = vec![Vec::new(); n]; + for &b in &post { + for s in succ_of(&blocks[b]) { + preds[s].push(b); + } + } + // nodes reachable from `from` within `inside`, along successors or predecessors + let reach = |from: usize, inside: &[bool], fwd: bool| { + let mut seen = vec![false; n]; + let mut stack = vec![from]; + seen[from] = true; + while let Some(x) = stack.pop() { + let next = if fwd { succ_of(&blocks[x]) } else { preds[x].clone() }; + for y in next { + if inside[y] && !seen[y] { + seen[y] = true; + stack.push(y); + } + } + } + seen + }; + // shrink to the innermost cycle region around `t` with more than one entry + let mut inside: Vec = (0..n).map(|b| pos[b] != usize::MAX).collect(); + let (region, entries) = loop { + let (f, r) = (reach(t, &inside, true), reach(t, &inside, false)); + let region: Vec = (0..n).map(|b| f[b] && r[b]).collect(); + let entries: Vec = (0..n).filter(|&b| region[b] && (b == post[0] || preds[b].iter().any(|&p| !region[p]))).collect(); + if entries.len() != 1 { + break (region, entries); + } + inside = region; + inside[entries[0]] = false; + if !inside[t] { + return Err("irreducible control flow (no multi-entry region)".into()); + } + }; + if blocks.len() >= limit || entries.is_empty() { + return Err(format!("irreducible control flow (still after splitting to {} blocks)", blocks.len())); + } + let h = *entries.iter().min_by_key(|&&e| pos[e]).unwrap(); + let mut copy = vec![usize::MAX; n]; + for b in (0..n).filter(|&b| region[b] && b != h) { + copy[b] = blocks.len(); + blocks.push(CfgBlock { insts: blocks[b].insts.clone(), term: blocks[b].term.clone(), preds: Vec::new() }); + } + let redirect = |term: &mut Term, to: &dyn Fn(usize) -> usize| match term { + Term::Jump(x) => *x = to(*x), + Term::Cond(_, x, y) => { + *x = to(*x); + *y = to(*y) + } + Term::End => {} + }; + // the copies stay among themselves except for `h` and the region's exits + for b in (0..n).filter(|&b| copy[b] != usize::MAX) { + redirect(&mut blocks[copy[b]].term, &|x| if copy[x] != usize::MAX { copy[x] } else { x }); + } + // edges from outside the region into its other entries go to the copies + for p in (0..n).filter(|&p| !region[p] && pos[p] != usize::MAX) { + redirect(&mut blocks[p].term, &|x| if region[x] && x != h { copy[x] } else { x }); + } + } +} + +fn succ_of(b: &CfgBlock) -> Vec { + match b.term { + Term::Jump(t) => vec![t], + Term::Cond(_, t, f) => vec![t, f], + Term::End => vec![], + } +} + +/// Reachable blocks in reverse post-order from the entry (iterative DFS) and the targets of +/// retreating edges. +fn order(blocks: &[CfgBlock]) -> (Vec, BTreeSet) { + let n = blocks.len(); + let succ = succ_of; + let mut state = vec![0u8; n]; // 0 new, 1 on stack, 2 done + let mut post = Vec::new(); + let mut headers = BTreeSet::new(); + if n > 0 { + let mut stack: Vec<(usize, usize)> = vec![(0, 0)]; + state[0] = 1; + while let Some(&mut (b, ref mut k)) = stack.last_mut() { + let s = succ(&blocks[b]); + if *k < s.len() { + let t = s[*k]; + *k += 1; + match state[t] { + 0 => { + state[t] = 1; + stack.push((t, 0)); + } + 1 => { + headers.insert(t); + } + _ => {} + } + } else { + state[b] = 2; + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + (post, headers) +} + +/// A retreating edge (a, t) of the reverse post-order `rpo` whose target does not dominate +/// its source (the CFG is irreducible), if any. +fn irreducible_edge(blocks: &[CfgBlock], rpo: &[usize]) -> Option<(usize, usize)> { + let mut pos = vec![usize::MAX; blocks.len()]; + for (i, &b) in rpo.iter().enumerate() { + pos[b] = i; + } + let mut preds = vec![Vec::new(); blocks.len()]; + for &b in rpo { + for t in succ_of(&blocks[b]) { + preds[t].push(b); + } + } + // Cooper–Harvey–Kennedy dominators over the RPO + let mut idom = vec![usize::MAX; blocks.len()]; + let entry = *rpo.first()?; + idom[entry] = entry; + let mut changed = true; + while changed { + changed = false; + for &b in &rpo[1..] { + let mut nd = usize::MAX; + for &p in preds[b].iter().filter(|&&p| idom[p] != usize::MAX) { + nd = if nd == usize::MAX { + p + } else { + let (mut x, mut y) = (p, nd); + while x != y { + while pos[x] > pos[y] { + x = idom[x]; + } + while pos[y] > pos[x] { + y = idom[y]; + } + } + x + }; + } + if idom[b] != nd { + idom[b] = nd; + changed = true; + } + } + } + let dominates = |a: usize, mut b: usize| loop { + if a == b { + return true; + } + if b == entry { + return false; + } + b = idom[b]; + }; + rpo.iter().find_map(|&a| succ_of(&blocks[a]).into_iter().find(|&t| pos[t] <= pos[a] && !dominates(t, a)).map(|t| (a, t))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn blk(term: Term) -> CfgBlock { + CfgBlock { insts: Vec::new(), term, preds: Vec::new() } + } + + /// The console's loop entered in the middle (`62b584e061c05fc5`'s shape): 0 → {1 | 3}, + /// 1 → 2, cycle 2 → 3 → {2 | 4}; split into a single-entry loop. + #[test] + fn loop_entered_in_the_middle_is_split() { + let mut b = vec![blk(Term::Cond(0, 3, 1)), blk(Term::Jump(2)), blk(Term::Jump(3)), blk(Term::Cond(0, 2, 4)), blk(Term::End)]; + let (rpo, headers) = order(&b); + assert!(irreducible_edge(&b, &rpo).is_some()); + let (rpo, headers2) = make_reducible(&mut b).unwrap(); + assert!(irreducible_edge(&b, &rpo).is_none()); + assert_eq!(b.len(), 6); + assert_eq!(headers.len(), 1); + assert_eq!(headers2.len(), 1); + } +} diff --git a/crates/xcl/src/gpu/dxil/container.rs b/crates/xcl/src/gpu/dxil/container.rs new file mode 100644 index 000000000..b92b10ede --- /dev/null +++ b/crates/xcl/src/gpu/dxil/container.rs @@ -0,0 +1,498 @@ +//! The DXBC container around a DXIL program: feature flags (`SFI0`), +//! signatures (`ISG1`/`OSG1`), pipeline state validation info (`PSV0`), the +//! program (`DXIL`) and the container digest D3D12 checks. +//! +//! The digest is DXBC's retail hash: MD5 over everything after the digest +//! field, with a non-standard final block (bit count in the first and +//! `(bits >> 2) | 1` in the last dword). Computing it here means shipped +//! builds need neither `dxcompiler.dll` nor `dxil.dll`; the validator is a +//! test oracle only. + +/// DXIL shader kinds (`DXIL::ShaderKind`, also PSV's stage numbering). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Stage { + Pixel = 0, + Vertex = 1, + Geometry = 2, + Hull = 3, + Domain = 4, + Compute = 5, + Mesh = 13, + Amplification = 14, +} + +impl Stage { + pub fn profile_prefix(self) -> &'static str { + match self { + Stage::Pixel => "ps", + Stage::Vertex => "vs", + Stage::Geometry => "gs", + Stage::Hull => "hs", + Stage::Domain => "ds", + Stage::Compute => "cs", + Stage::Mesh => "ms", + Stage::Amplification => "as", + } + } +} + +/// PSV resource types (`PSVResourceType`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PsvResType { + Sampler = 1, + Cbv = 2, + SrvTyped = 3, + SrvRaw = 4, + SrvStructured = 5, + UavTyped = 6, + UavRaw = 7, + UavStructured = 8, +} + +/// One bound resource as PSV0 lists it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PsvResource { + pub res_type: PsvResType, + pub space: u32, + pub lower: u32, + pub upper: u32, + /// `DXIL::ResourceKind` (11 raw buffer, 12 structured buffer, 2 texture 2D…). + pub kind: u32, + pub flags: u32, +} + +/// Pipeline state validation info. +#[derive(Debug, Clone)] +pub struct Psv { + pub stage: Stage, + /// Wave lane count range (0 / `u32::MAX` when unconstrained). + pub min_wave: u32, + pub max_wave: u32, + pub numthreads: [u32; 3], + pub resources: Vec, + pub entry: String, +} + +/// Retail DXBC container digest of `data` (the bytes after the digest field). +pub fn hash(data: &[u8]) -> [u8; 16] { + let mut st = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476]; + let bits = (data.len() as u32).wrapping_mul(8); + let left = data.len() % 64; + let full = data.len() - left; + for blk in data[..full].chunks_exact(64) { + md5_block(&mut st, blk); + } + let rest = &data[full..]; + let mut blk = [0u8; 64]; + if left >= 56 { + blk[..left].copy_from_slice(rest); + blk[left] = 0x80; + md5_block(&mut st, &blk); + let mut last = [0u8; 64]; + last[..4].copy_from_slice(&bits.to_le_bytes()); + last[60..].copy_from_slice(&((bits >> 2) | 1).to_le_bytes()); + md5_block(&mut st, &last); + } else { + blk[..4].copy_from_slice(&bits.to_le_bytes()); + blk[4..4 + left].copy_from_slice(rest); + blk[4 + left] = 0x80; + blk[60..].copy_from_slice(&((bits >> 2) | 1).to_le_bytes()); + md5_block(&mut st, &blk); + } + let mut out = [0u8; 16]; + for (i, w) in st.iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&w.to_le_bytes()); + } + out +} + +fn md5_block(st: &mut [u32; 4], blk: &[u8]) { + const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]; + let m: Vec = blk.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + let [mut a, mut b, mut c, mut d] = *st; + for i in 0..64 { + let (f, g) = match i / 16 { + 0 => ((b & c) | (!b & d), i), + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), + 2 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | !d), (7 * i) % 16), + }; + let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32; + let f = f.wrapping_add(a).wrapping_add(k).wrapping_add(m[g]); + a = d; + d = c; + c = b; + b = b.wrapping_add(f.rotate_left(S[(i / 16) * 4 + i % 4])); + } + st[0] = st[0].wrapping_add(a); + st[1] = st[1].wrapping_add(b); + st[2] = st[2].wrapping_add(c); + st[3] = st[3].wrapping_add(d); +} + +fn fourcc(s: &[u8; 4]) -> u32 { + u32::from_le_bytes(*s) +} + +/// The `DXIL` part: program header, bitcode header, bitcode. +fn program_part(stage: Stage, sm: (u32, u32), dxil_version: (u32, u32), bitcode: &[u8]) -> Vec { + assert!(bitcode.len() % 4 == 0); + let mut p = Vec::with_capacity(24 + bitcode.len()); + let total = 24 + bitcode.len(); + p.extend_from_slice(&(((stage as u32) << 16) | (sm.0 << 4) | sm.1).to_le_bytes()); + p.extend_from_slice(&((total / 4) as u32).to_le_bytes()); + p.extend_from_slice(&fourcc(b"DXIL").to_le_bytes()); + p.extend_from_slice(&((dxil_version.0 << 8) | dxil_version.1).to_le_bytes()); + p.extend_from_slice(&16u32.to_le_bytes()); + p.extend_from_slice(&(bitcode.len() as u32).to_le_bytes()); + p.extend_from_slice(bitcode); + p +} + +/// PSV0 with `PSVRuntimeInfo3` (validator 1.8+). +fn psv_part(psv: &Psv) -> Vec { + let mut p = Vec::new(); + let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); + w(&mut p, 52); + p.extend_from_slice(&[0; 16]); // stage-specific union (none for compute) + w(&mut p, psv.min_wave); + w(&mut p, psv.max_wave); + p.extend_from_slice(&[psv.stage as u8, 0, 0, 0]); // stage, uses view id, union + p.extend_from_slice(&[0; 4]); // signature element counts / input vectors + p.extend_from_slice(&[0; 4]); // output vectors per stream + for n in psv.numthreads { + w(&mut p, n); + } + w(&mut p, 1); // entry function name: offset 1 in the string table + w(&mut p, psv.resources.len() as u32); + if !psv.resources.is_empty() { + w(&mut p, 24); + for r in &psv.resources { + for v in [r.res_type as u32, r.space, r.lower, r.upper, r.kind, r.flags] { + w(&mut p, v); + } + } + } + // String table: "" then the entry name, padded to 4 bytes. + let mut strings = vec![0u8]; + strings.extend_from_slice(psv.entry.as_bytes()); + strings.push(0); + while strings.len() % 4 != 0 { + strings.push(0); + } + w(&mut p, strings.len() as u32); + p.extend_from_slice(&strings); + w(&mut p, 0); // semantic index table + p +} + +/// An empty input / output signature. +fn empty_signature() -> Vec { + let mut p = Vec::new(); + p.extend_from_slice(&0u32.to_le_bytes()); + p.extend_from_slice(&8u32.to_le_bytes()); + p +} + +/// Builds the signed container for a DXIL program. +pub fn container(stage: Stage, sm: (u32, u32), bitcode: &[u8], features: u64, psv: &Psv) -> Vec { + let dxil_version = (1, sm.1.min(8)); + let parts: Vec<([u8; 4], Vec)> = vec![ + (*b"SFI0", features.to_le_bytes().to_vec()), + (*b"ISG1", empty_signature()), + (*b"OSG1", empty_signature()), + (*b"PSV0", psv_part(psv)), + (*b"DXIL", program_part(stage, sm, dxil_version, bitcode)), + ]; + let header = 32 + 4 * parts.len(); + let total: usize = header + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); + let mut out = Vec::with_capacity(total); + out.extend_from_slice(b"DXBC"); + out.extend_from_slice(&[0; 16]); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&(total as u32).to_le_bytes()); + out.extend_from_slice(&(parts.len() as u32).to_le_bytes()); + let mut off = header; + for (_, d) in &parts { + out.extend_from_slice(&(off as u32).to_le_bytes()); + off += 8 + d.len(); + } + for (cc, d) in &parts { + out.extend_from_slice(cc); + out.extend_from_slice(&(d.len() as u32).to_le_bytes()); + out.extend_from_slice(d); + } + let digest = hash(&out[20..]); + out[4..20].copy_from_slice(&digest); + out +} + +// ------------------------------------------------- graphics signatures + +/// One row of an `ISG1`/`OSG1`/`PSG1` signature (`DxilProgramSignatureElement`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SigPartElement { + pub stream: u32, + pub name: String, + pub index: u32, + /// `D3D_NAME` system value. + pub system_value: u32, + /// `D3D_REGISTER_COMPONENT_TYPE` (1 uint, 2 sint, 3 float). + pub comp_type: u32, + /// Register (row), `u32::MAX` for unallocated system values (depth, coverage…). + pub register: u32, + pub mask: u8, + /// Inputs: components read; outputs: components never written. + pub rw_mask: u8, + pub min_precision: u32, +} + +/// A signature part. Elements are written in the given order; each name is +/// stored once, in first-use order of `name_order` and then of the elements +/// (DXC writes names in declaration order while sorting elements by register). +pub fn signature_part(elems: &[SigPartElement], name_order: &[&str]) -> Vec { + let mut strings: Vec = Vec::new(); + let mut offs: Vec<(String, u32)> = Vec::new(); + let base = 8 + 32 * elems.len() as u32; + for n in name_order.iter().copied().chain(elems.iter().map(|e| e.name.as_str())) { + if !offs.iter().any(|(s, _)| s == n) { + offs.push((n.to_string(), base + strings.len() as u32)); + strings.extend_from_slice(n.as_bytes()); + strings.push(0); + } + } + while strings.len() % 4 != 0 { + strings.push(0); + } + let mut p = Vec::new(); + let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); + w(&mut p, elems.len() as u32); + w(&mut p, 8); + for e in elems { + let off = offs.iter().find(|(s, _)| *s == e.name).unwrap().1; + for v in [e.stream, off, e.index, e.system_value, e.comp_type, e.register] { + w(&mut p, v); + } + p.extend_from_slice(&[e.mask, e.rw_mask, 0, 0]); + w(&mut p, e.min_precision); + } + p.extend_from_slice(&strings); + p +} + +/// One signature element as PSV0 lists it (`PSVSignatureElement0`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PsvSigElement { + /// Empty for system values (PSV stores no name for them). + pub name: String, + pub indices: Vec, + pub rows: u8, + pub start_row: u8, + pub cols: u8, + pub start_col: u8, + pub allocated: bool, + /// `DXIL::SemanticKind`. + pub kind: u8, + /// `PSVComponentType` (1 uint32, 2 sint32, 3 float32, 4 uint16, 5 sint16, 6 float16). + pub comp_type: u8, + /// `DXIL::InterpolationMode`. + pub interp: u8, + pub dynamic_mask: u8, + pub stream: u8, +} + +/// PSV0 for any stage: `PSVRuntimeInfo3` plus signature elements and the +/// input → output dependency tables. +#[derive(Debug, Clone)] +pub struct PsvFull { + pub stage: Stage, + /// The 16-byte stage union of `PSVRuntimeInfo0` (VS/PS/MS/... info). + pub stage_info: [u8; 16], + pub min_wave: u32, + pub max_wave: u32, + pub uses_view_id: bool, + /// The 2-byte union of `PSVRuntimeInfo1` (GS max vertices / MS prim vectors + topology). + pub info1: [u8; 2], + pub numthreads: [u32; 3], + pub resources: Vec, + pub entry: String, + pub inputs: Vec, + pub outputs: Vec, + pub prims: Vec, + pub input_vectors: u8, + pub output_vectors: [u8; 4], + /// Tables after the signature elements, in order: view-ID output masks + /// (if `uses_view_id`), input → output dependency tables, and the + /// patch-constant / primitive tables (dwords). + pub tables: Vec>, +} + +/// Writes PSV0 for [`PsvFull`]. +pub fn psv_part_full(psv: &PsvFull) -> Vec { + let mut p = Vec::new(); + let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); + w(&mut p, 52); + p.extend_from_slice(&psv.stage_info); + w(&mut p, psv.min_wave); + w(&mut p, psv.max_wave); + p.extend_from_slice(&[psv.stage as u8, psv.uses_view_id as u8, psv.info1[0], psv.info1[1]]); + p.extend_from_slice(&[psv.inputs.len() as u8, psv.outputs.len() as u8, psv.prims.len() as u8, psv.input_vectors]); + p.extend_from_slice(&psv.output_vectors); + for n in psv.numthreads { + w(&mut p, n); + } + let all: Vec<&PsvSigElement> = psv.inputs.iter().chain(&psv.outputs).chain(&psv.prims).collect(); + // String table: "" then non-system names in element order (not + // deduplicated, as DXC writes it), then the entry name. + let mut strings = vec![0u8]; + let mut name_off = Vec::new(); + for e in &all { + if e.name.is_empty() { + name_off.push(0); + } else { + name_off.push(strings.len() as u32); + strings.extend_from_slice(e.name.as_bytes()); + strings.push(0); + } + } + let entry_off = strings.len() as u32; + strings.extend_from_slice(psv.entry.as_bytes()); + strings.push(0); + while strings.len() % 4 != 0 { + strings.push(0); + } + w(&mut p, entry_off); + w(&mut p, psv.resources.len() as u32); + if !psv.resources.is_empty() { + w(&mut p, 24); + for r in &psv.resources { + for v in [r.res_type as u32, r.space, r.lower, r.upper, r.kind, r.flags] { + w(&mut p, v); + } + } + } + w(&mut p, strings.len() as u32); + p.extend_from_slice(&strings); + // Semantic index table: each element's index list, reusing an existing run. + let mut table: Vec = Vec::new(); + let mut idx_off = Vec::new(); + for e in &all { + let n = e.indices.len(); + let found = if n == 0 || table.len() < n { None } else { (0..=table.len() - n).find(|&i| table[i..i + n] == e.indices[..]) }; + idx_off.push(match found { + Some(i) => i as u32, + None => { + table.extend_from_slice(&e.indices); + (table.len() - n) as u32 + } + }); + } + w(&mut p, table.len() as u32); + for v in &table { + w(&mut p, *v); + } + if !all.is_empty() { + w(&mut p, 16); + for (i, e) in all.iter().enumerate() { + w(&mut p, name_off[i]); + w(&mut p, idx_off[i]); + let cs = (e.cols & 0xF) | ((e.start_col & 3) << 4) | ((e.allocated as u8) << 6); + p.extend_from_slice(&[e.rows, e.start_row, cs, e.kind, e.comp_type, e.interp, (e.dynamic_mask & 0xF) | ((e.stream & 3) << 4), 0]); + } + } + for t in &psv.tables { + for v in t { + w(&mut p, *v); + } + } + p +} + +/// Builds the signed container with explicit signature parts (`psg` for +/// mesh primitive outputs) and a prebuilt PSV0. +#[allow(clippy::too_many_arguments)] +pub fn container_with_signatures(stage: Stage, sm: (u32, u32), bitcode: &[u8], features: u64, isg: Vec, osg: Vec, psg: Option>, psv: Vec) -> Vec { + let dxil_version = (1, sm.1.min(8)); + let mut parts: Vec<([u8; 4], Vec)> = vec![(*b"SFI0", features.to_le_bytes().to_vec()), (*b"ISG1", isg), (*b"OSG1", osg)]; + if let Some(p) = psg { + parts.push((*b"PSG1", p)); + } + parts.push((*b"PSV0", psv)); + parts.push((*b"DXIL", program_part(stage, sm, dxil_version, bitcode))); + let header = 32 + 4 * parts.len(); + let total: usize = header + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); + let mut out = Vec::with_capacity(total); + out.extend_from_slice(b"DXBC"); + out.extend_from_slice(&[0; 16]); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&(total as u32).to_le_bytes()); + out.extend_from_slice(&(parts.len() as u32).to_le_bytes()); + let mut off = header; + for (_, d) in &parts { + out.extend_from_slice(&(off as u32).to_le_bytes()); + off += 8 + d.len(); + } + for (cc, d) in &parts { + out.extend_from_slice(cc); + out.extend_from_slice(&(d.len() as u32).to_le_bytes()); + out.extend_from_slice(d); + } + let digest = hash(&out[20..]); + out[4..20].copy_from_slice(&digest); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// DXC 1.9 output for a 64-thread compute shader storing to two root UAVs + /// (see `tests/data/dxil/*.hlsl`). + const DXC_CS: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_cs_raw_uav.dxil"); + + #[test] + fn digest_matches_dxc_signed_container() { + assert_eq!(hash(&DXC_CS[20..]), DXC_CS[4..20]); + } + + #[test] + fn digest_covers_both_tail_layouts() { + // Lengths with < 56 and >= 56 trailing bytes take different final blocks; + // both must differ from each other and be stable. + let a = hash(&[7u8; 64 + 10]); + let b = hash(&[7u8; 64 + 60]); + assert_ne!(a, b); + assert_eq!(a, hash(&[7u8; 64 + 10])); + } + + #[test] + fn psv_matches_dxc_layout_for_compute_with_two_raw_uavs() { + let psv = Psv { + stage: Stage::Compute, + min_wave: 64, + max_wave: 64, + numthreads: [64, 1, 1], + resources: (0..2) + .map(|i| PsvResource { res_type: PsvResType::UavRaw, space: 0, lower: i, upper: i, kind: 11, flags: 0 }) + .collect(), + entry: "main".into(), + }; + let ours = psv_part(&psv); + let theirs = part(DXC_CS, b"PSV0"); + assert_eq!(ours, theirs); + } + + pub(crate) fn part<'a>(c: &'a [u8], cc: &[u8; 4]) -> &'a [u8] { + let n = u32::from_le_bytes(c[28..32].try_into().unwrap()) as usize; + for i in 0..n { + let off = u32::from_le_bytes(c[32 + 4 * i..36 + 4 * i].try_into().unwrap()) as usize; + if &c[off..off + 4] == cc { + let len = u32::from_le_bytes(c[off + 4..off + 8].try_into().unwrap()) as usize; + return &c[off + 8..off + 8 + len]; + } + } + panic!("no {cc:?} part") + } +} diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs new file mode 100644 index 000000000..a754a072a --- /dev/null +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -0,0 +1,281 @@ +//! Checks of the direct compute translator (`kernel`, `lower`): translated +//! programs pass the validator. The GPU differential tests are the +//! recompiler's instruction tests run with `XCL_DIRECT_DXIL=1`. + +use super::kernel::{translate, KernelOptions}; +use crate::gpu::rdna2::encode; + +fn prog(list: &[(&str, &str, &[(&str, u64)], Option)]) -> Vec { + let mut v = Vec::new(); + for (n, e, f, l) in list { + v.extend(encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))); + } + v.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + v +} + +#[test] +fn straight_line_and_loop_kernels_validate() { + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 138)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)], None), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 0)], None), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)], None), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 257), ("VSRC1", 2)], None), + ]); + for (wave64, split) in [(false, false), (true, true), (true, false)] { + translate(&code, KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }).unwrap_or_else(|e| panic!("wave64 {wave64} split {split}: {e}")); + } +} + +/// Development aid: `XCL_DUMP_HLSL=` compiles a compute shader with DXC +/// and prints the disassembly (DXC's lowering of an HLSL intrinsic is the +/// reference for the direct path's). +#[test] +#[ignore] +fn dump_dxc_lowering() { + let Ok(path) = std::env::var("XCL_DUMP_HLSL") else { return }; + let src = std::fs::read_to_string(path).unwrap(); + let c = crate::gpu::recomp::dxc::compile(&src, "main", "cs_6_6", &[]).unwrap(); + println!("{}", super::validate::disassemble(&c).unwrap()); +} + +#[test] +fn f64_conversions_validate() { + for (name, enc) in [("V_CVT_F32_F64", "ENC_VOP1"), ("V_CVT_F64_F32", "ENC_VOP1"), ("V_CVT_I32_F64", "ENC_VOP1"), ("V_CVT_F64_I32", "ENC_VOP1")] { + let code = prog(&[(name, enc, &[("VDST", 2), ("SRC0", 256)], None)]); + if let Err(e) = translate(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }) { + panic!("{name}: {}", &e[..e.len().min(600)]); + } + } + let code = prog(&[("V_FMA_F64", "ENC_VOP3", &[("VDST", 2), ("SRC0", 256), ("SRC1", 258), ("SRC2", 260)], None)]); + translate(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }).map_err(|e| e[..e.len().min(600)].to_string()).unwrap(); + let code = prog(&[("V_SQRT_F64", "ENC_VOP1", &[("VDST", 2), ("SRC0", 256)], None)]); + translate(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }).map_err(|e| e[..e.len().min(600)].to_string()).unwrap(); +} + +#[test] +fn f64_bisect() { + let cases: Vec<(&str, Vec)> = vec![ + ("add", prog(&[("V_ADD_F64", "ENC_VOP3", &[("VDST", 2), ("SRC0", 256), ("SRC1", 258)], None)])), + ("fma_k", prog(&[("V_FMA_F64", "ENC_VOP3", &[("VDST", 2), ("SRC0", 256), ("SRC1", 258), ("SRC2", 242)], None)])), + ("fma_v", prog(&[("V_FMA_F64", "ENC_VOP3", &[("VDST", 2), ("SRC0", 256), ("SRC1", 258), ("SRC2", 260)], None)])), + ]; + let mut bad = Vec::new(); + for (n, c) in cases { + if let Err(e) = translate(&c, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }) { + bad.push(format!("{n}: {}", &e[..e.len().min(200)])); + } + } + assert!(bad.is_empty(), "{bad:#?}"); +} + +/// A long program (thousands of guarded memory accesses between a register's write and +/// its final store) translates, validates and stays reasonably fast. +#[test] +fn long_programs_translate() { + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + list.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", 129)], None)); + for i in 0..2000u64 { + list.push(("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", vec![("VDST", 2 + (i % 4)), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 4 * (i % 64))], None)); + list.push(("V_ADD_NC_U32", "ENC_VOP2", vec![("VDST", 1), ("SRC0", 256 + 2 + (i % 4)), ("VSRC1", 1)], None)); + } + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let code = prog(&refs); + let t = std::time::Instant::now(); + translate(&code, KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(500)])); + println!("4001 instructions: {:?}", t.elapsed()); +} + +/// A direct-translated VS links with an HLSL-path PS and vice versa (both declare their +/// signatures as the HLSL entry structs do), drawing the same pixels as two direct stages. +#[test] +fn direct_and_hlsl_graphics_stages_link() { + use crate::gpu::dxbc::SigElement as S; + use crate::gpu::recomp::{runner, translate, Mode, Options, PsInterface, VsInterface}; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; + if !super::graphics::tests::draw_ready() { + return; + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + let el = |name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8| S { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 }; + const V: u64 = 256; + let vs_code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11)], None), + ("EXP", "ENC_EXP", &[("TGT", 33), ("EN", 0x3), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 0), ("VSRC3", 0)], None), + ]); + let vsi = VsInterface { + inputs: vec![el("POSITION", 0, 0, 3, 0, 3), el("COLOR", 0, 0, 3, 1, 0xF)], + outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF), el("TEXCOORD", 3, 0, 3, 2, 0x3)], + attr_base: 4, + params: None, + }; + let ps_code = prog(&[ + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 5), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 1)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 6), ("VSRC", 1), ("ATTR", 1), ("ATTRCHAN", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None), + ]); + let psi = PsInterface { + inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF), el("TEXCOORD", 3, 0, 3, 2, 0x3)], + outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: None, + }; + let (vo, po) = (Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }, Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }); + let hvs = crate::gpu::recomp::dxc::compile(&translate(&vs_code, &vo).unwrap().hlsl, "main", "vs_6_6", &[]).unwrap(); + let hps = crate::gpu::recomp::dxc::compile(&translate(&ps_code, &po).unwrap().hlsl, "main", "ps_6_6", &[]).unwrap(); + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let dvs = super::kernel::translate_vertex(&vs_code, ko, &vsi).unwrap().dxil; + let dps = super::kernel::translate_pixel(&ps_code, ko, &psi).unwrap().dxil; + let c = [0.8f32, 0.6, 0.4, 1.0]; + let verts: Vec = [[-1.0f32, -1.0], [-1.0, 3.0], [3.0, -1.0]].iter().flat_map(|p| [p[0], p[1], c[0], c[1], c[2], c[3]]).collect(); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 8 }, + ]; + let draw = |vs: &[u8], ps: &[u8]| runner::draw(vs, ps, &layout, &verts, 24, &[], &[], 8, [0.0; 4]).unwrap(); + let want = draw(&hvs, &hps); + assert_eq!(draw(&dvs, &dps), want, "direct VS + direct PS"); + assert_eq!(draw(&dvs, &hps), want, "direct VS + HLSL PS"); + assert_eq!(draw(&hvs, &dps), want, "HLSL VS + direct PS"); +} + +fn sig(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> crate::gpu::dxbc::SigElement { + crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } +} + +/// VS / PS with a branch: the blocks after it are created after the exit block, whose +/// output stores read registers they define (once "forward reference to value N", +/// `module.rs` writing blocks in creation order). Also a PS reading SV_IsFrontFace +/// (declared uint, as the validator demands). +#[test] +fn branchy_graphics_stages_validate() { + use crate::gpu::recomp::{PsInterface, VsInterface}; + let body = |exp: (&'static str, &'static str, &'static [(&'static str, u64)], Option)| { + prog(&[ + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 242)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 256 + 4)], None), + exp, + ]) + }; + let vs_code = body(("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 4), ("VSRC3", 5), ("DONE", 1)], None)); + let vsi = VsInterface { inputs: vec![], outputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], attr_base: 4, params: None }; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + for wave64 in [true, false] { + super::kernel::translate_vertex(&vs_code, KernelOptions { wave64, ..ko }, &vsi).unwrap_or_else(|e| panic!("VS wave64 {wave64}: {}", &e[..e.len().min(800)])); + } + // v2 = front face (SPI_PS_INPUT_ENA bit 12 after the two I/J pairs of 0x3) + let ps_code = body(("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 2), ("VSRC3", 5), ("DONE", 1), ("VM", 1)], None)); + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x1002, attrs: None }; + for wave64 in [true, false] { + super::kernel::translate_pixel(&ps_code, KernelOptions { wave64, ..ko }, &psi).unwrap_or_else(|e| panic!("PS wave64 {wave64}: {}", &e[..e.len().min(800)])); + } +} + +/// A long pixel shader (guarded memory accesses make thousands of joins between a +/// register's write and the output stores) translates quickly and stays small: the +/// SSA builder drops trivial phis, `Module::optimize` cleans up the rest. +#[test] +fn long_pixel_shader_translates_fast() { + use crate::gpu::recomp::PsInterface; + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + for r in 4..16u64 { + list.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", r), ("SRC0", 129 + r)], None)); + } + for i in 0..1500u64 { + list.push(("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", 20 + (i % 4)), ("VADDR", 0), ("SRSRC", 1), ("SOFFSET", 128), ("OFFSET", 4 * (i % 64)), ("OFFEN", 1)], None)); + list.push(("V_ADD_F32", "ENC_VOP2", vec![("VDST", 4 + (i % 4)), ("SRC0", 256 + 20 + (i % 4)), ("VSRC1", 4 + (i % 4))], None)); + } + list.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let code = prog(&refs); + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None }; + let t = std::time::Instant::now(); + let k = super::kernel::translate_pixel(&code, KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + println!("3000 instructions: {:?}, {} B", t.elapsed(), k.dxil.len()); +} + +/// A vertex and a pixel shader that branch before their exports translate (their epilogue then +/// uses values of blocks created after the exit block), and draw what the HLSL path's stages +/// draw, whichever way the branch goes. +#[test] +fn graphics_stages_with_a_branch_before_their_exports() { + use crate::gpu::dxbc::SigElement as S; + use crate::gpu::recomp::{runner, translate, Mode, Options, PsInterface, VsInterface}; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; + let el = |name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8| S { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 }; + const V: u64 = 256; + // s0 != 0 skips the instruction that clears a colour channel + let vs_code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 242)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None), + ("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11)], None), + ("EXP", "ENC_EXP", &[("TGT", 33), ("EN", 0x3), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 0), ("VSRC3", 0)], None), + ]); + let vsi = VsInterface { + inputs: vec![el("POSITION", 0, 0, 3, 0, 3), el("COLOR", 0, 0, 3, 1, 0xF)], + outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF), el("TEXCOORD", 3, 0, 3, 2, 0x3)], + attr_base: 4, + params: None, + }; + let ps_code = prog(&[ + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 5), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 1)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 6), ("VSRC", 1), ("ATTR", 1), ("ATTRCHAN", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 242)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None), + ]); + let psi = PsInterface { + inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF), el("TEXCOORD", 3, 0, 3, 2, 0x3)], + outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: None, + }; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let dvs = super::kernel::translate_vertex(&vs_code, ko, &vsi).unwrap_or_else(|e| panic!("VS: {}", &e[..e.len().min(600)])).dxil; + let dps = super::kernel::translate_pixel(&ps_code, ko, &psi).unwrap_or_else(|e| panic!("PS: {}", &e[..e.len().min(600)])).dxil; + if !super::graphics::tests::draw_ready() { + return; + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + let (vo, po) = (Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }, Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }); + let hvs = crate::gpu::recomp::dxc::compile(&translate(&vs_code, &vo).unwrap().hlsl, "main", "vs_6_6", &[]).unwrap(); + let hps = crate::gpu::recomp::dxc::compile(&translate(&ps_code, &po).unwrap().hlsl, "main", "ps_6_6", &[]).unwrap(); + let c = [0.8f32, 0.6, 0.4, 1.0]; + let verts: Vec = [[-1.0f32, -1.0], [-1.0, 3.0], [3.0, -1.0]].iter().flat_map(|p| [p[0], p[1], c[0], c[1], c[2], c[3]]).collect(); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 8 }, + ]; + let draw = |vs: &[u8], ps: &[u8], s0: u32| runner::draw(vs, ps, &layout, &verts, 24, &[s0], &[], 8, [0.0; 4]).unwrap(); + let (cleared, kept) = (draw(&hvs, &hps, 0), draw(&hvs, &hps, 1)); + assert_ne!(cleared, kept, "the branch changes the picture"); + assert_eq!(draw(&dvs, &dps, 0), cleared, "branch not taken"); + assert_eq!(draw(&dvs, &dps, 1), kept, "branch taken"); +} diff --git a/crates/xcl/src/gpu/dxil/coverage.rs b/crates/xcl/src/gpu/dxil/coverage.rs new file mode 100644 index 000000000..62c7a84ec --- /dev/null +++ b/crates/xcl/src/gpu/dxil/coverage.rs @@ -0,0 +1,409 @@ +//! Coverage measurement for the direct DXIL translator. +//! +//! * [`Report`]: per-stage outcome counts (translated / unsupported / validator-failed / +//! panicked), a ranked histogram of unsupported constructs, translation times and DXIL +//! sizes (direct vs the HLSL + DXC path). Used by `xcl shaders … --direct`. +//! * [`translate_mode`]: one console program through the direct translator for a +//! `recomp::Mode`, with panics caught and classified. +//! * Live fallbacks (`XCL_DIRECT_DXIL`): [`record_fallback`] counts the HLSL fallbacks of +//! `pso.rs` by (stage, reason); with `XCL_DIRECT_DXIL_STATS=1` [`dump_fallbacks`] prints +//! the summary (called at process exit; harmless to call more than once). + +use std::collections::BTreeMap; +use std::sync::Mutex; +use std::time::Duration; + +use super::kernel::{self, KernelOptions}; +use crate::gpu::recomp::Mode; + +/// The stage name of a recompiler mode (as the corpus CLI prints it). +pub fn stage_name(mode: &Mode) -> &'static str { + match mode { + Mode::Kernel => "kernel", + Mode::Compute(_) => "CS", + Mode::Vertex(_) => "VS", + Mode::Pixel(_) => "PS", + Mode::Mesh(_) => "MS", + Mode::Geometry(_) => "GS", + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Outcome { + Translated, + Unsupported, + ValidatorFailed, + Panicked, + /// the sweep gave up waiting (`xcl shaders --direct --timeout`) + Timeout, +} + +/// Classifies a translator error string. +pub fn classify(err: &str) -> Outcome { + if err.contains("translator panicked") || err.starts_with("panic:") { + Outcome::Panicked + } else if err.starts_with("timeout:") { + Outcome::Timeout + } else if err.contains("failed validation") || err.starts_with("validator:") { + Outcome::ValidatorFailed + } else { + Outcome::Unsupported + } +} + +/// The histogram key of a translator error: the instruction mnemonic plus the reason with +/// operands, offsets and numbers stripped, so equal constructs collapse into one bucket. +/// Errors look like `"v_foo v1, v2: unsupported …"` (`lower::unsupported`) or free text. +pub fn reason_key(err: &str) -> String { + let first = err.lines().next().unwrap_or("").trim(); + let first = first.strip_prefix("the direct DXIL translator panicked: ").map(|m| m.trim()).unwrap_or(first); + let (head, why) = match first.split_once(": ") { + Some((h, w)) => (h.trim(), w.trim()), + None => ("", first), + }; + // an instruction head: mnemonic first (`s_`, `v_`, `ds_`, `buffer_`, …); drop its operands + let mnemonic = head.split_whitespace().next().filter(|m| m.contains('_') && m.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')); + let norm = |s: &str| -> String { + let mut out = String::new(); + let mut last_num = false; + for tok in s.split_whitespace() { + let t = tok.trim_matches(|c: char| ",;:()[]".contains(c)); + let numeric = !t.is_empty() && (t.starts_with("0x") || t.starts_with("+0x") || t.chars().all(|c| c.is_ascii_digit() || c == '-' || c == '+')); + if numeric { + if !last_num { + out.push_str(" N"); + } + last_num = true; + continue; + } + last_num = false; + out.push(' '); + out.push_str(tok); + } + let out = out.trim().to_string(); + if out.len() > 120 { format!("{}…", &out[..out.char_indices().take_while(|(i, _)| *i < 120).last().map(|(i, c)| i + c.len_utf8()).unwrap_or(0)]) } else { out } + }; + match mnemonic { + Some(m) => format!("{m}: {}", norm(why)), + None => norm(first), + } +} + +/// One program's result. +#[derive(Debug, Clone)] +pub struct Sample { + pub stage: &'static str, + /// `Ok(dxil size)` or the error + pub result: Result, + pub time: Duration, + /// DXIL size of the HLSL + DXC path (`--compare`), when it compiled + pub hlsl_size: Option, +} + +#[derive(Debug, Default, Clone)] +pub struct StageCounts { + pub translated: usize, + pub unsupported: usize, + pub validator_failed: usize, + pub panicked: usize, + pub timeout: usize, +} + +impl StageCounts { + pub fn total(&self) -> usize { + self.translated + self.unsupported + self.validator_failed + self.panicked + self.timeout + } +} + +#[derive(Debug, Default, Clone)] +pub struct Report { + pub stages: BTreeMap<&'static str, StageCounts>, + /// reason key → (programs, stages it was seen in, one example program) + pub reasons: BTreeMap, String)>, + pub times_us: Vec, + /// (direct DXIL bytes, HLSL-path DXIL bytes) for programs both paths produced + pub sizes: Vec<(usize, usize)>, +} + +impl Report { + pub fn add(&mut self, name: &str, s: &Sample) { + let c = self.stages.entry(s.stage).or_default(); + self.times_us.push(s.time.as_micros() as u64); + match &s.result { + Ok(size) => { + c.translated += 1; + if let Some(h) = s.hlsl_size { + self.sizes.push((*size, h)); + } + } + Err(e) => { + match classify(e) { + Outcome::Panicked => c.panicked += 1, + Outcome::Timeout => c.timeout += 1, + Outcome::ValidatorFailed => c.validator_failed += 1, + _ => c.unsupported += 1, + } + let r = self.reasons.entry(reason_key(e)).or_insert_with(|| (0, BTreeMap::new(), name.to_string())); + r.0 += 1; + *r.1.entry(s.stage).or_default() += 1; + } + } + } + + pub fn total(&self) -> StageCounts { + let mut t = StageCounts::default(); + for c in self.stages.values() { + t.translated += c.translated; + t.unsupported += c.unsupported; + t.validator_failed += c.validator_failed; + t.panicked += c.panicked; + t.timeout += c.timeout; + } + t + } + + /// Reasons ranked by programs (ties by name). + pub fn ranked(&self) -> Vec<(&String, usize)> { + let mut v: Vec<_> = self.reasons.iter().map(|(k, v)| (k, v.0)).collect(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + v + } + + /// (p50, p95, max) translation time in microseconds. + pub fn time_percentiles(&self) -> (u64, u64, u64) { + percentiles(&self.times_us) + } + + pub fn text(&self, top: usize) -> String { + let mut s = String::from("direct DXIL coverage\n stage total translated unsupported validator panicked timeout\n"); + let row = |s: &mut String, name: &str, c: &StageCounts| { + let pct = if c.total() > 0 { 100.0 * c.translated as f64 / c.total() as f64 } else { 0.0 }; + s.push_str(&format!(" {name:<7} {:>7} {:>8} ({pct:>5.1}%) {:>10} {:>10} {:>9} {:>8}\n", c.total(), c.translated, c.unsupported, c.validator_failed, c.panicked, c.timeout)); + }; + for (k, c) in &self.stages { + row(&mut s, k, c); + } + row(&mut s, "all", &self.total()); + let (p50, p95, max) = self.time_percentiles(); + s.push_str(&format!(" translation time per program: p50 {:.2} ms, p95 {:.2} ms, max {:.2} ms\n", p50 as f64 / 1e3, p95 as f64 / 1e3, max as f64 / 1e3)); + if !self.sizes.is_empty() { + let (d, h): (usize, usize) = self.sizes.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); + s.push_str(&format!(" DXIL size, {} programs: direct {} B, HLSL+DXC {} B (direct/HLSL {:.2})\n", self.sizes.len(), d, h, d as f64 / h.max(1) as f64)); + } + let ranked = self.ranked(); + if !ranked.is_empty() { + s.push_str(&format!(" unsupported constructs ({} kinds, top {}):\n", ranked.len(), top.min(ranked.len()))); + for (k, n) in ranked.iter().take(top) { + let r = &self.reasons[*k]; + let stages: Vec = r.1.iter().map(|(s, n)| format!("{s} {n}")).collect(); + s.push_str(&format!(" {n:>6} {k} [{}] e.g. {}\n", stages.join(", "), r.2)); + } + } + s + } + + pub fn json(&self, top: usize) -> String { + let esc = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n"); + let counts = |c: &StageCounts| format!("{{\"total\":{},\"translated\":{},\"unsupported\":{},\"validator_failed\":{},\"panicked\":{},\"timeout\":{}}}", c.total(), c.translated, c.unsupported, c.validator_failed, c.panicked, c.timeout); + let stages: Vec = self.stages.iter().map(|(k, c)| format!("\"{k}\":{}", counts(c))).collect(); + let reasons: Vec = self.ranked().iter().take(top).map(|(k, n)| format!("{{\"reason\":\"{}\",\"programs\":{n},\"example\":\"{}\"}}", esc(k), esc(&self.reasons[*k].2))).collect(); + let (p50, p95, max) = self.time_percentiles(); + let (d, h): (usize, usize) = self.sizes.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); + format!( + "{{\"stages\":{{{}}},\"all\":{},\"time_us\":{{\"p50\":{p50},\"p95\":{p95},\"max\":{max}}},\"size\":{{\"programs\":{},\"direct\":{d},\"hlsl\":{h}}},\"unsupported\":[{}]}}", + stages.join(","), + counts(&self.total()), + self.sizes.len(), + reasons.join(",") + ) + } +} + +pub fn percentiles(v: &[u64]) -> (u64, u64, u64) { + if v.is_empty() { + return (0, 0, 0); + } + let mut v = v.to_vec(); + v.sort_unstable(); + let at = |p: f64| v[((v.len() - 1) as f64 * p).round() as usize]; + (at(0.5), at(0.95), *v.last().unwrap()) +} + +/// One program through the direct translator for `mode`. Panics (outside the translator's +/// own thread) come back as `"panic: …"`; `validate` runs DXC's validator on the result +/// (the translator itself only validates in debug / test builds). +pub fn translate_mode(code: &[u8], mode: &Mode, o: KernelOptions, validate: bool) -> Result, String> { + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match mode { + Mode::Kernel => kernel::translate_full(code, o), + Mode::Compute(cs) => kernel::translate_compute(code, o, cs), + 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()), + })); + let k = match r { + Ok(r) => r?, + Err(e) => { + let msg = e.downcast_ref::().cloned().or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default(); + return Err(format!("panic: {msg}")); + } + }; + if validate { + super::validate::validate(&k.dxil).map_err(|e| format!("validator: {}", e.lines().next().unwrap_or("")))?; + } + Ok(k.dxil) +} + +/// Deterministic sample of `n` of `0..len` (splitmix64-driven partial Fisher–Yates), in +/// ascending order. `n >= len` returns everything. +pub fn sample_indices(len: usize, n: usize, seed: u64) -> Vec { + let mut idx: Vec = (0..len).collect(); + if n >= len { + return idx; + } + let mut st = seed; + let mut next = || { + st = st.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = st; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + }; + for i in 0..n { + let j = i + (next() % (len - i) as u64) as usize; + idx.swap(i, j); + } + idx.truncate(n); + idx.sort_unstable(); + idx +} + +// ---- live fallbacks ---------------------------------------------------------------------- + +static FALLBACKS: Mutex> = Mutex::new(BTreeMap::new()); +static TRANSLATED: Mutex> = Mutex::new(BTreeMap::new()); + +/// `XCL_DIRECT_DXIL_STATS=1`: keep and print the live fallback summary. +pub fn stats_enabled() -> bool { + std::env::var("XCL_DIRECT_DXIL_STATS").is_ok_and(|v| !v.is_empty() && v != "0") +} + +/// A live shader the direct path translated (`stage`: "CS", "VS", "PS", "MS"). +pub fn record_translated(stage: &str) { + if let Ok(mut m) = TRANSLATED.lock() { + *m.entry(stage.to_string()).or_default() += 1; + } +} + +/// A live shader that fell back to the HLSL path. Returns the reason key (for the log line). +pub fn record_fallback(stage: &str, err: &str) -> String { + let key = reason_key(err); + if let Ok(mut m) = FALLBACKS.lock() { + *m.entry((stage.to_string(), key.clone())).or_default() += 1; + } + key +} + +/// The live summary: per stage direct / fallback counts and the fallback reasons ranked. +pub fn fallback_summary() -> String { + let fb = FALLBACKS.lock().map(|m| m.clone()).unwrap_or_default(); + let ok = TRANSLATED.lock().map(|m| m.clone()).unwrap_or_default(); + let mut per_stage: BTreeMap = ok.iter().map(|(k, v)| (k.clone(), (*v, 0))).collect(); + for ((st, _), n) in &fb { + per_stage.entry(st.clone()).or_default().1 += n; + } + let mut s = String::from("[SHADER] direct DXIL summary:"); + for (st, (d, f)) in &per_stage { + s.push_str(&format!(" {st} direct {d} / HLSL fallback {f};")); + } + let mut v: Vec<_> = fb.into_iter().collect(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + for ((st, why), n) in v { + s.push_str(&format!("\n {n:>5} {st} {why}")); + } + s +} + +/// Prints [`fallback_summary`] to stderr and the log when `XCL_DIRECT_DXIL_STATS` is set. +pub fn dump_fallbacks() { + if stats_enabled() { + let s = fallback_summary(); + eprintln!("{s}"); + crate::xlog_info!("{}", s); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::rdna2; + + #[test] + fn reason_keys_collapse_operands() { + let a = reason_key("v_foo_f32 v1, v2, 0x10: unsupported modifier 3"); + let b = reason_key("v_foo_f32 v7, s3, 0x20: unsupported modifier 4"); + assert_eq!(a, b); + assert_eq!(a, "v_foo_f32: unsupported modifier N"); + assert_eq!(reason_key("geometry mode (ES+GS): not supported"), "geometry mode (ES+GS): not supported"); + assert_eq!(classify("the direct DXIL translator panicked: boom"), Outcome::Panicked); + assert_eq!(classify("direct DXIL failed validation: x"), Outcome::ValidatorFailed); + assert_eq!(classify("v_x: y"), Outcome::Unsupported); + assert_eq!(classify("timeout: over 10 s"), Outcome::Timeout); + } + + #[test] + fn sampling_is_seeded_and_bounded() { + let a = sample_indices(1000, 50, 7); + assert_eq!(a.len(), 50); + assert_eq!(a, sample_indices(1000, 50, 7)); + assert_ne!(a, sample_indices(1000, 50, 8)); + assert!(a.windows(2).all(|w| w[0] < w[1])); + assert_eq!(sample_indices(5, 50, 1), vec![0, 1, 2, 3, 4]); + } + + #[test] + fn report_counts_and_ranks() { + let mut r = Report::default(); + let t = Duration::from_micros; + r.add("a", &Sample { stage: "CS", result: Ok(100), time: t(10), hlsl_size: Some(200) }); + r.add("b", &Sample { stage: "CS", result: Err("v_bar v1: no".into()), time: t(20), hlsl_size: None }); + r.add("c", &Sample { stage: "PS", result: Err("v_bar v3: no".into()), time: t(30), hlsl_size: None }); + r.add("d", &Sample { stage: "PS", result: Err("s_baz: no".into()), time: t(40), hlsl_size: None }); + r.add("e", &Sample { stage: "VS", result: Err("direct DXIL failed validation: bad".into()), time: t(50), hlsl_size: None }); + r.add("f", &Sample { stage: "GS", result: Err("panic: oops".into()), time: t(1000), hlsl_size: None }); + let all = r.total(); + assert_eq!((all.translated, all.unsupported, all.validator_failed, all.panicked), (1, 3, 1, 1)); + assert_eq!(r.stages["PS"].unsupported, 2); + assert_eq!(r.ranked()[0], (&"v_bar: no".to_string(), 2)); + assert_eq!(r.time_percentiles(), (40, 1000, 1000)); + let txt = r.text(10); + assert!(txt.contains("v_bar: no") && txt.contains("direct/HLSL 0.50"), "{txt}"); + let j = r.json(10); + assert!(j.contains("\"CS\":{\"total\":2,\"translated\":1") && j.contains("\"reason\":\"v_bar: no\",\"programs\":2"), "{j}"); + } + + /// Synthetic programs from the RDNA2 encoder through the real translator. + #[test] + fn synthetic_programs_through_translate_mode() { + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let ok = rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).expect("encode"); + let mut r = Report::default(); + for (name, code, mode) in [("ok", ok.clone(), Mode::Kernel), ("gs", ok, Mode::Geometry(Default::default()))] { + let t0 = std::time::Instant::now(); + let res = translate_mode(&code, &mode, o, false).map(|d| d.len()); + 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")); + } + + #[test] + fn live_fallback_summary() { + record_translated("CS"); + let k = record_fallback("PS", "v_qq v1: unsupported"); + assert_eq!(k, "v_qq: unsupported"); + let s = fallback_summary(); + assert!(s.contains("PS v_qq: unsupported"), "{s}"); + } +} diff --git a/crates/xcl/src/gpu/dxil/graphics.rs b/crates/xcl/src/gpu/dxil/graphics.rs new file mode 100644 index 000000000..0668b8043 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/graphics.rs @@ -0,0 +1,1145 @@ +//! Graphics stages for the direct DXIL emitter: vertex, pixel and mesh +//! shaders — signature elements and their packing, the I/O intrinsics +//! (`loadInput`, `storeOutput`, mesh outputs, discard, coverage…), the +//! `dx.entryPoints` signature metadata, `dx.viewIdState`, and the +//! `ISG1`/`OSG1`/`PSG1`/`PSV0` container parts. +//! +//! Layouts and rules follow DXC's output for small HLSL programs (NCSA +//! licence; see `docs/specs/2026-11-24-direct-dxil.md`): element +//! packing is DXC's default prefix-stable first fit, the PSV0 dependency +//! tables are recomputed from the emitted code the way the validator does. + +use std::collections::{BTreeSet, HashMap}; + +use super::container::{self, PsvFull, PsvSigElement, SigPartElement, Stage}; +use super::module::{Block, FnAttrs, InstInfo, Md, Ty, Value}; +use super::shader::{Feature, ResClass, Shader, DATALAYOUT, TRIPLE}; + +/// The data layout DXC writes with `-enable-16bit-types`. +pub const DATALAYOUT_NATIVE16: &str = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64"; + +/// `DXIL::SemanticKind`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SemKind { + Arbitrary = 0, + VertexId = 1, + InstanceId = 2, + Position = 3, + RenderTargetArrayIndex = 4, + ViewportArrayIndex = 5, + ClipDistance = 6, + CullDistance = 7, + PrimitiveId = 10, + SampleIndex = 12, + IsFrontFace = 13, + Coverage = 14, + InnerCoverage = 15, + Target = 16, + Depth = 17, + DepthLessEqual = 18, + DepthGreaterEqual = 19, + StencilRef = 20, + ShadingRate = 29, + CullPrimitive = 30, +} + +impl SemKind { + const ALL: [SemKind; 20] = [ + SemKind::Arbitrary, + SemKind::VertexId, + SemKind::InstanceId, + SemKind::Position, + SemKind::RenderTargetArrayIndex, + SemKind::ViewportArrayIndex, + SemKind::ClipDistance, + SemKind::CullDistance, + SemKind::PrimitiveId, + SemKind::SampleIndex, + SemKind::IsFrontFace, + SemKind::Coverage, + SemKind::InnerCoverage, + SemKind::Target, + SemKind::Depth, + SemKind::DepthLessEqual, + SemKind::DepthGreaterEqual, + SemKind::StencilRef, + SemKind::ShadingRate, + SemKind::CullPrimitive, + ]; + /// The kind for a `D3D_NAME` system value (as console / DXBC signatures carry it). + pub fn from_d3d_name(name: u32) -> Option { + Self::ALL.into_iter().find(|k| k.d3d_name() == name) + } + /// `D3D_NAME` as signature parts store it. + pub fn d3d_name(self) -> u32 { + match self { + SemKind::Arbitrary => 0, + SemKind::Position => 1, + SemKind::ClipDistance => 2, + SemKind::CullDistance => 3, + SemKind::RenderTargetArrayIndex => 4, + SemKind::ViewportArrayIndex => 5, + SemKind::VertexId => 6, + SemKind::PrimitiveId => 7, + SemKind::InstanceId => 8, + SemKind::IsFrontFace => 9, + SemKind::SampleIndex => 10, + SemKind::Target => 64, + SemKind::Depth => 65, + SemKind::Coverage => 66, + SemKind::DepthGreaterEqual => 67, + SemKind::DepthLessEqual => 68, + SemKind::StencilRef => 69, + SemKind::InnerCoverage => 70, + SemKind::ShadingRate => 24, + SemKind::CullPrimitive => 25, + } + } +} + +/// Component types (`DXIL::ComponentType`) supported in signatures. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CompType { + /// `bool` (`SV_CullPrimitive`, …): stored and loaded as `i32`. + Bool, + I32, + U32, + F32, + I16, + U16, + F16, +} + +impl CompType { + /// From a `D3D_REGISTER_COMPONENT_TYPE` (1 uint, 2 sint, 3 float). + pub fn from_d3d(t: u32) -> Option { + match t { + 1 => Some(CompType::U32), + 2 => Some(CompType::I32), + 3 => Some(CompType::F32), + _ => None, + } + } + fn md(self) -> u8 { + match self { + CompType::Bool => 1, + CompType::I16 => 2, + CompType::U16 => 3, + CompType::I32 => 4, + CompType::U32 => 5, + CompType::F16 => 8, + CompType::F32 => 9, + } + } + /// `D3D_REGISTER_COMPONENT_TYPE`. + fn d3d(self) -> u32 { + match self { + CompType::U32 | CompType::Bool => 1, + CompType::I32 => 2, + CompType::F32 => 3, + CompType::U16 => 4, + CompType::I16 => 5, + CompType::F16 => 6, + } + } + fn is_16bit(self) -> bool { + matches!(self, CompType::F16 | CompType::I16 | CompType::U16) + } + fn psv(self) -> u8 { + match self { + CompType::U32 | CompType::Bool => 1, + CompType::I32 => 2, + CompType::F32 => 3, + CompType::U16 => 4, + CompType::I16 => 5, + CompType::F16 => 6, + } + } + /// `D3D_MIN_PRECISION` (0 with native 16-bit types). + fn min_precision(self, native16: bool) -> u32 { + if native16 { + return 0; + } + match self { + CompType::F16 => 1, + CompType::I16 => 4, + CompType::U16 => 5, + _ => 0, + } + } + fn is_float(self) -> bool { + matches!(self, CompType::F32 | CompType::F16) + } +} + +/// `DXIL::InterpolationMode`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Interp { + Undefined = 0, + Constant = 1, + Linear = 2, + LinearCentroid = 3, + LinearNoperspective = 4, + LinearNoperspectiveCentroid = 5, + LinearSample = 6, + LinearNoperspectiveSample = 7, +} + +/// Mesh output topology. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Topology { + Line = 1, + Triangle = 2, +} + +/// A signature element as declared (one HLSL parameter / struct member). +#[derive(Debug, Clone)] +pub struct SigElement { + pub name: String, + /// Semantic index of each row. + pub indices: Vec, + pub kind: SemKind, + pub ty: CompType, + /// `None`: DXC's default for the stage and type. + pub interp: Option, + pub cols: u8, + /// Fixed placement (row, column); `None` packs like DXC. + pub place: Option<(u32, u8)>, +} + +impl SigElement { + /// A one-row element `name` of `cols` components. + pub fn new(name: &str, index: u32, kind: SemKind, ty: CompType, cols: u8) -> SigElement { + SigElement { name: name.into(), indices: vec![index], kind, ty, interp: None, cols, place: None } + } + /// An arbitrary (user) semantic. + pub fn user(name: &str, index: u32, ty: CompType, cols: u8) -> SigElement { + SigElement::new(name, index, SemKind::Arbitrary, ty, cols) + } + /// An element from a DXBC-style signature row (`D3D_NAME`, component type, + /// component mask): columns span the mask, the start column is kept as a + /// fixed placement only if `register` is given. + pub fn from_d3d(name: &str, index: u32, system_value: u32, component_type: u32, mask: u8, register: Option) -> Option { + let kind = SemKind::from_d3d_name(system_value)?; + let ty = CompType::from_d3d(component_type)?; + if mask & 0xF == 0 { + return None; + } + let start = mask.trailing_zeros() as u8; + let hi = 7 - (mask & 0xF).leading_zeros() as u8; + let cols = hi - start + 1; + let mut e = SigElement::new(name, index, kind, ty, cols); + e.place = register.map(|r| (r, start)); + Some(e) + } + pub fn interp(mut self, i: Interp) -> SigElement { + self.interp = Some(i); + self + } + /// `rows` rows with consecutive semantic indices from the first. + pub fn rows(mut self, rows: u32) -> SigElement { + let first = self.indices[0]; + self.indices = (first..first + rows).collect(); + self + } + pub fn at(mut self, row: u32, col: u8) -> SigElement { + self.place = Some((row, col)); + self + } + fn nrows(&self) -> u32 { + self.indices.len() as u32 + } +} + +/// Which signature an element belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Dir { + In, + Out, + Prim, +} + +/// A handle to a declared element (its id within its signature). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Sig { + dir: Dir, + id: u32, +} + +/// How an element is laid out (`DXIL::SemanticInterpretationKind`, simplified). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Interpretation { + /// User semantic: packed. + Arb, + /// System value packed like a user one, but nothing may follow it in its row. + Sv, + /// `SV_ClipDistance` / `SV_CullDistance`: share rows only with each other. + ClipCull, + /// Not packed: `register` -1 (depth, coverage, sample index…). + NotPacked, + /// `SV_Target`: row = semantic index. + Target, +} + +/// Placed element. +#[derive(Debug, Clone)] +struct Placed { + e: SigElement, + interp: Interp, + /// `None`: unallocated. + at: Option<(u32, u8)>, + /// Components read (inputs) / written (outputs), relative to the start column. + usage: u8, +} + +/// Vertex / pixel / mesh I/O declared on a shader. +pub struct GraphicsIo { + stage: Stage, + inputs: Vec, + outputs: Vec, + prims: Vec, + usage: HashMap<(u8, u32), u8>, + uses_sample_index: bool, +} + +/// Stage-specific entry information. +#[derive(Debug, Clone, Copy)] +pub enum StageInfo { + Vertex, + Pixel { early_depth_stencil: bool }, + Mesh { numthreads: [u32; 3], max_vertices: u32, max_primitives: u32, topology: Topology, payload_bytes: u32 }, +} + +fn dir_code(d: Dir) -> u8 { + d as u8 +} + +impl GraphicsIo { + pub fn new(stage: Stage) -> GraphicsIo { + assert!(matches!(stage, Stage::Vertex | Stage::Pixel | Stage::Mesh), "graphics I/O for {stage:?}"); + GraphicsIo { stage, inputs: Vec::new(), outputs: Vec::new(), prims: Vec::new(), usage: HashMap::new(), uses_sample_index: false } + } + + /// Declares an input element (VS/PS). + pub fn input(&mut self, e: SigElement) -> Sig { + assert_ne!(self.stage, Stage::Mesh, "mesh shaders have no input signature"); + self.inputs.push(e); + Sig { dir: Dir::In, id: self.inputs.len() as u32 - 1 } + } + /// Declares an output element (VS/PS outputs, MS vertex outputs). + pub fn output(&mut self, e: SigElement) -> Sig { + self.outputs.push(e); + Sig { dir: Dir::Out, id: self.outputs.len() as u32 - 1 } + } + /// Declares a mesh primitive output element. + pub fn primitive(&mut self, e: SigElement) -> Sig { + assert_eq!(self.stage, Stage::Mesh); + self.prims.push(e); + Sig { dir: Dir::Prim, id: self.prims.len() as u32 - 1 } + } + + fn elem(&self, s: Sig) -> &SigElement { + match s.dir { + Dir::In => &self.inputs[s.id as usize], + Dir::Out => &self.outputs[s.id as usize], + Dir::Prim => &self.prims[s.id as usize], + } + } + + fn mark(&mut self, s: Sig, col: u8) { + let e = self.elem(s); + assert!(col < e.cols, "column {col} outside {} ({} columns)", e.name, e.cols); + *self.usage.entry((dir_code(s.dir), s.id)).or_default() |= 1 << col; + } + + fn scalar_ty(s: &mut Shader, t: CompType) -> Ty { + match t { + CompType::F32 => s.m.f32(), + CompType::F16 => s.m.f16(), + CompType::I32 | CompType::U32 | CompType::Bool => s.m.i32(), + CompType::I16 | CompType::U16 => s.m.int(16), + } + } + + /// `loadInput` of component `col` of row `row` (relative to the element). + /// PS `SV_SampleIndex` is read with `sampleIndex` instead. + pub fn load_input(&mut self, s: &mut Shader, sig: Sig, row: u32, col: u8) -> Value { + assert_eq!(sig.dir, Dir::In); + let e = self.elem(sig).clone(); + if e.kind == SemKind::SampleIndex { + self.uses_sample_index = true; + let i32 = s.m.i32(); + return s.op(90, "sampleIndex", Some(i32), i32, &[], FnAttrs::ReadNone); + } + assert!(row < e.nrows()); + self.mark(sig, col); + let t = Self::scalar_ty(s, e.ty); + let (id, r, c) = (s.m.i32c(sig.id), s.m.i32c(row), s.m.i8c(col)); + let i32 = s.m.i32(); + let undef = s.m.undef(i32); + s.op(4, "loadInput", Some(t), t, &[id, r, c, undef], FnAttrs::ReadNone) + } + + /// `storeOutput` of `v` into component `col` of row `row`. + pub fn store_output(&mut self, s: &mut Shader, sig: Sig, row: u32, col: u8, v: Value) { + assert_eq!(sig.dir, Dir::Out); + assert_ne!(self.stage, Stage::Mesh, "mesh vertex outputs use store_vertex_output"); + let e = self.elem(sig).clone(); + assert!(row < e.nrows()); + self.mark(sig, col); + let t = Self::scalar_ty(s, e.ty); + let v = s.m.bitcast(v, t); + let (id, r, c) = (s.m.i32c(sig.id), s.m.i32c(row), s.m.i8c(col)); + let void = s.m.void(); + s.op(5, "storeOutput", Some(t), void, &[id, r, c, v], FnAttrs::NoUnwind); + } + + // ---- pixel shader + + /// `discard` when `cond` holds. + pub fn discard(&mut self, s: &mut Shader, cond: Value) { + assert_eq!(self.stage, Stage::Pixel); + let void = s.m.void(); + s.op(82, "discard", None, void, &[cond], FnAttrs::NoUnwind); + } + /// The input `SV_Coverage` mask. + pub fn coverage(&mut self, s: &mut Shader) -> Value { + assert_eq!(self.stage, Stage::Pixel); + let i32 = s.m.i32(); + s.op(91, "coverage", Some(i32), i32, &[], FnAttrs::ReadNone) + } + /// `SV_InnerCoverage`. + pub fn inner_coverage(&mut self, s: &mut Shader) -> Value { + assert_eq!(self.stage, Stage::Pixel); + let i32 = s.m.i32(); + s.op(92, "innerCoverage", Some(i32), i32, &[], FnAttrs::ReadNone) + } + /// `IsHelperLane()`. + pub fn is_helper_lane(&mut self, s: &mut Shader) -> Value { + let i1 = s.m.i1(); + s.op(221, "isHelperLane", Some(i1), i1, &[], FnAttrs::ReadOnly) + } + + // ---- mesh shader + + pub fn set_mesh_output_counts(&mut self, s: &mut Shader, vertices: Value, primitives: Value) { + assert_eq!(self.stage, Stage::Mesh); + let void = s.m.void(); + s.op(168, "setMeshOutputCounts", None, void, &[vertices, primitives], FnAttrs::NoUnwind); + } + /// Triangle (three indices) or line (two; the third operand is 0, as + /// DXC emits it) indices of primitive `prim`. + pub fn emit_indices(&mut self, s: &mut Shader, prim: Value, idx: &[Value]) { + assert_eq!(self.stage, Stage::Mesh); + assert!(matches!(idx.len(), 2 | 3), "{} indices per primitive", idx.len()); + let void = s.m.void(); + let mut a = vec![prim]; + a.extend_from_slice(idx); + if idx.len() == 2 { + a.push(s.m.i32c(0)); + } + s.op(169, "emitIndices", None, void, &a, FnAttrs::NoUnwind); + } + pub fn store_vertex_output(&mut self, s: &mut Shader, sig: Sig, row: u32, col: u8, v: Value, vertex: Value) { + assert_eq!((self.stage, sig.dir), (Stage::Mesh, Dir::Out)); + self.store_mesh(s, sig, row, col, v, vertex, 171, "storeVertexOutput"); + } + pub fn store_primitive_output(&mut self, s: &mut Shader, sig: Sig, row: u32, col: u8, v: Value, prim: Value) { + assert_eq!(sig.dir, Dir::Prim); + self.store_mesh(s, sig, row, col, v, prim, 172, "storePrimitiveOutput"); + } + #[allow(clippy::too_many_arguments)] + fn store_mesh(&mut self, s: &mut Shader, sig: Sig, row: u32, col: u8, v: Value, index: Value, op: u32, name: &str) { + let e = self.elem(sig).clone(); + assert!(row < e.nrows()); + self.mark(sig, col); + let t = Self::scalar_ty(s, e.ty); + let v = s.m.bitcast(v, t); + let (id, r, c) = (s.m.i32c(sig.id), s.m.i32c(row), s.m.i8c(col)); + let void = s.m.void(); + s.op(op, name, Some(t), void, &[id, r, c, v, index], FnAttrs::NoUnwind); + } + /// `GetMeshPayload` as a pointer to `payload` (a named struct type + /// `struct.`); fields are read with GEP + load. + pub fn mesh_payload(&mut self, s: &mut Shader, payload: Ty, struct_name: &str) -> Value { + assert_eq!(self.stage, Stage::Mesh); + let p = s.m.ptr(payload, 0); + let i32 = s.m.i32(); + let fty = s.m.func_ty(p, &[i32]); + let f = s.m.declare(&format!("dx.op.getMeshPayload.{struct_name}"), fty, FnAttrs::ReadOnly); + let opc = s.m.i32c(170); + s.m.call(f, &[opc]) + } + + // ---- layout + + fn interpretation(&self, dir: Dir, k: SemKind) -> Interpretation { + use SemKind::*; + match (self.stage, dir, k) { + (_, _, Arbitrary) => Interpretation::Arb, + (Stage::Pixel, Dir::Out, Target) => Interpretation::Target, + (Stage::Pixel, Dir::Out, Depth | DepthLessEqual | DepthGreaterEqual | Coverage | StencilRef) => Interpretation::NotPacked, + (Stage::Pixel, Dir::In, SampleIndex) => Interpretation::NotPacked, + (Stage::Pixel, Dir::In, Coverage | InnerCoverage) => panic!("{k:?} is not a signature element (use coverage())"), + (Stage::Mesh, Dir::Prim, CullPrimitive) => Interpretation::NotPacked, + (_, _, ClipDistance | CullDistance) => Interpretation::ClipCull, + _ => Interpretation::Sv, + } + } + + fn default_interp(&self, dir: Dir, e: &SigElement) -> Interp { + use SemKind::*; + match (self.stage, dir) { + (Stage::Vertex, Dir::In) | (Stage::Pixel, Dir::Out) => Interp::Undefined, + (_, Dir::Prim) => Interp::Constant, + _ => match e.kind { + Position => Interp::LinearNoperspective, + Arbitrary | ClipDistance | CullDistance if e.ty.is_float() => Interp::Linear, + SampleIndex if self.stage == Stage::Pixel => Interp::Constant, + _ => Interp::Constant, + }, + } + } + + /// DXC's default prefix-stable first-fit packing. + fn place(&self, dir: Dir) -> Vec { + let list = match dir { + Dir::In => &self.inputs, + Dir::Out => &self.outputs, + Dir::Prim => &self.prims, + }; + // Per row: occupied columns, interpolation, and the first column after a system value. + #[derive(Clone, Default)] + struct Row { + used: u8, + interp: Option, + sv_end: bool, + clip_cull: bool, + } + let mut rows: Vec = Vec::new(); + let no_pack = self.stage == Stage::Vertex && dir == Dir::In; + let mut next_row = 0u32; + let mut out = Vec::new(); + for (id, e) in list.iter().enumerate() { + let interp = e.interp.unwrap_or_else(|| self.default_interp(dir, e)); + let usage = self.usage.get(&(dir_code(dir), id as u32)).copied().unwrap_or(0); + let ip = self.interpretation(dir, e.kind); + let mask = ((1u16 << e.cols) - 1) as u8; + let at = match (ip, e.place) { + (Interpretation::NotPacked, _) => None, + (_, Some(p)) => Some(p), + (Interpretation::Target, None) => Some((e.indices[0], 0)), + _ if no_pack => { + next_row += e.nrows(); + Some((next_row - e.nrows(), 0)) + } + _ => { + let fits = |rows: &Vec, r: u32, c: u8| { + (r..r + e.nrows()).all(|r| match rows.get(r as usize) { + None => true, + Some(row) => { + row.used & (mask << c) == 0 + && (row.used >> c) == 0 + && row.interp.is_none_or(|i| i == interp) + && (row.used == 0 || row.clip_cull == (ip == Interpretation::ClipCull)) + && (!row.sv_end || ip == Interpretation::Sv) + } + }) + }; + let mut found = None; + 'search: for r in 0.. { + for c in 0..=(4 - e.cols) { + if fits(&rows, r, c) { + found = Some((r, c)); + break 'search; + } + } + } + found + } + }; + if let Some((r, c)) = at { + for r in r..r + e.nrows() { + if rows.len() <= r as usize { + rows.resize(r as usize + 1, Row::default()); + } + let row = &mut rows[r as usize]; + row.used |= mask << c; + row.interp = Some(interp); + row.sv_end |= ip == Interpretation::Sv; + row.clip_cull |= ip == Interpretation::ClipCull; + } + } + out.push(Placed { e: e.clone(), interp, at, usage }); + } + out + } +} + +/// Number of allocated rows (signature vectors). +fn vectors(p: &[Placed]) -> u32 { + p.iter().filter_map(|e| e.at.map(|(r, _)| r + e.e.nrows())).max().unwrap_or(0) +} + +/// Number of allocated scalar components as `dx.viewIdState` counts them. +fn components(p: &[Placed]) -> u32 { + p.iter().filter_map(|e| e.at.map(|(r, c)| (r + e.e.nrows() - 1) * 4 + c as u32 + e.e.cols as u32)).max().unwrap_or(0) +} + +fn sig_part(p: &[Placed], output: bool, native16: bool) -> Vec { + let mut rows = Vec::new(); + for e in p { + let (reg, col) = e.at.map_or((u32::MAX, 0), |(r, c)| (r, c)); + let mask = (((1u16 << e.e.cols) - 1) as u8) << col; + let used = e.usage << col; + let rw = if output { !used & 0xF } else { used }; + for (i, &idx) in e.e.indices.iter().enumerate() { + rows.push(SigPartElement { + stream: 0, + name: e.e.name.clone(), + index: idx, + system_value: e.e.kind.d3d_name(), + comp_type: e.e.ty.d3d(), + register: if reg == u32::MAX { reg } else { reg + i as u32 }, + mask, + rw_mask: if e.at.is_none() && !output { 0 } else { rw }, + min_precision: e.e.ty.min_precision(native16), + }); + } + } + rows.sort_by_key(|r| (r.register, r.mask.trailing_zeros())); + let names: Vec<&str> = p.iter().map(|e| e.e.name.as_str()).collect(); + container::signature_part(&rows, &names) +} + +fn psv_elems(p: &[Placed]) -> Vec { + p.iter() + .map(|e| { + let (r, c) = e.at.unwrap_or((0, 0)); + PsvSigElement { + name: if e.e.kind == SemKind::Arbitrary { e.e.name.clone() } else { String::new() }, + indices: e.e.indices.clone(), + rows: e.e.nrows() as u8, + start_row: r as u8, + cols: e.e.cols, + start_col: c, + allocated: e.at.is_some(), + kind: e.e.kind as u8, + comp_type: e.e.ty.psv(), + interp: e.interp as u8, + dynamic_mask: 0, + stream: 0, + } + }) + .collect() +} + +/// Input component → set of output components (`row * 4 + col`), from the code. +struct Deps { + /// For each output component, the input components it depends on. + out: HashMap<(u8, u32), BTreeSet>, +} + +/// Input components each value depends on, through data flow, memory and +/// control dependence (as DXC's `ComputeViewIdState`). +fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Placed]) -> Deps { + let m = &s.m; + let nb = m.block_count(); + // Successors and the branch condition of each block. + let mut succ: Vec> = vec![Vec::new(); nb]; + let mut cond: Vec> = vec![None; nb]; + for b in 0..nb { + if let Some(&last) = m.block_insts(Block(b as u32)).last() { + if let InstInfo::Term(c, ss) = m.inst_info(last) { + succ[b] = ss.iter().map(|x| x.0 as usize).collect(); + if ss.len() > 1 { + cond[b] = c; + } + } + } + } + // Immediate post-dominators with a virtual exit `nb` (Cooper, Harvey and Kennedy's + // iteration over the reverse CFG; sets per block were quadratic in time and memory). + let rsucc: Vec> = (0..nb).map(|b| if succ[b].is_empty() { vec![nb] } else { succ[b].clone() }).collect(); + let mut rpreds: Vec> = vec![Vec::new(); nb + 1]; + for (b, ss) in rsucc.iter().enumerate() { + for &x in ss { + rpreds[x].push(b); + } + } + // reverse postorder of the reverse CFG from the exit + let mut order: Vec = Vec::with_capacity(nb + 1); + { + let mut seen = vec![false; nb + 1]; + let mut stack: Vec<(usize, usize)> = vec![(nb, 0)]; + seen[nb] = true; + while let Some((v, k)) = stack.last_mut() { + if let Some(&w) = rpreds[*v].get(*k) { + *k += 1; + if !seen[w] { + seen[w] = true; + stack.push((w, 0)); + } + } else { + order.push(*v); + stack.pop(); + } + } + order.reverse(); + } + let mut rank = vec![usize::MAX; nb + 1]; + for (k, &v) in order.iter().enumerate() { + rank[v] = k; + } + let mut ipdom: Vec> = vec![None; nb + 1]; + ipdom[nb] = Some(nb); + let mut changed = true; + while changed { + changed = false; + for &v in order.iter().skip(1) { + let mut new: Option = None; + for &x in &rsucc[v] { + if ipdom[x].is_none() { + continue; + } + new = Some(match new { + None => x, + Some(mut p) => { + let mut q = x; + while p != q { + while rank[p] > rank[q] { + p = ipdom[p].unwrap(); + } + while rank[q] > rank[p] { + q = ipdom[q].unwrap(); + } + } + p + } + }); + } + if new.is_some() && ipdom[v] != new { + ipdom[v] = new; + changed = true; + } + } + } + // Block b is control dependent on branch block a if b post-dominates a + // successor of a but does not strictly post-dominate a: the blocks from the + // successor up the post-dominator tree to (excluding) a's immediate post-dominator. + let mut ctrl: Vec> = vec![Vec::new(); nb]; + let mut stamp = vec![usize::MAX; nb + 1]; + for a in 0..nb { + if cond[a].is_none() { + continue; + } + let stop = ipdom[a]; + let mut marked: Vec = Vec::new(); + for &x in &succ[a] { + let mut r = Some(x); + while let Some(v) = r { + if Some(v) == stop || v == nb || stamp[v] == a { + break; + } + stamp[v] = a; + marked.push(v); + r = ipdom[v].filter(|&p| p != v); + } + } + marked.sort_unstable(); + for v in marked { + ctrl[v].push(a); + } + } + // Instruction → block. + let mut block_of: HashMap = HashMap::new(); + let mut root_stores: HashMap> = HashMap::new(); + for b in 0..nb { + for &i in m.block_insts(Block(b as u32)) { + block_of.insert(i, b); + if let InstInfo::Store(p, v) = m.inst_info(i) { + root_stores.entry(root(s, p)).or_default().push(v); + } + if let InstInfo::Other(ops) = m.inst_info(i) { + // atomics write memory too + if ops.len() >= 2 { + if let Value::Global(_) = root(s, ops[0]) { + root_stores.entry(root(s, ops[0])).or_default().extend_from_slice(&ops[1..]); + } + } + } + } + } + let in_base: Vec> = inputs.iter().map(|e| e.at.map(|(r, c)| r * 4 + c as u32)).collect(); + let mut memo: HashMap> = HashMap::new(); + let mut ctrl_memo: HashMap> = HashMap::new(); + + struct Cx<'a> { + s: &'a Shader, + block_of: &'a HashMap, + ctrl: &'a Vec>, + cond: &'a Vec>, + root_stores: &'a HashMap>, + in_base: &'a [Option], + inputs: &'a [Placed], + } + fn block_deps(cx: &Cx, b: usize, memo: &mut HashMap>, cm: &mut HashMap>) -> BTreeSet { + if let Some(d) = cm.get(&b) { + return d.clone(); + } + cm.insert(b, BTreeSet::new()); + let mut d = BTreeSet::new(); + for &a in &cx.ctrl[b] { + if let Some(c) = cx.cond[a] { + d.extend(value_deps(cx, c, memo, cm)); + } + if a != b { + d.extend(block_deps(cx, a, memo, cm)); + } + } + cm.insert(b, d.clone()); + d + } + fn value_deps(cx: &Cx, v: Value, memo: &mut HashMap>, cm: &mut HashMap>) -> BTreeSet { + let Value::Inst(i) = v else { return BTreeSet::new() }; + if let Some(d) = memo.get(&v) { + return d.clone(); + } + memo.insert(v, BTreeSet::new()); + let m = &cx.s.m; + let mut d = BTreeSet::new(); + match m.inst_info(i) { + InstInfo::Call(name, args) if name.starts_with("dx.op.loadInput.") => { + let id = m.const_u64(args[1]).unwrap() as usize; + let col = m.const_u64(args[3]).unwrap() as u32; + if let Some(base) = cx.in_base[id] { + match m.const_u64(args[2]) { + Some(r) => { + d.insert(base + r as u32 * 4 + col); + } + None => { + for r in 0..cx.inputs[id].e.nrows() { + d.insert(base + r * 4 + col); + } + d.extend(value_deps(cx, args[2], memo, cm)); + } + } + } + } + InstInfo::Call(_, args) => { + for &a in args { + d.extend(value_deps(cx, a, memo, cm)); + } + } + InstInfo::Phi(list) => { + for &(x, from) in list { + d.extend(value_deps(cx, x, memo, cm)); + d.extend(block_deps(cx, from.0 as usize, memo, cm)); + if let Some(c) = cx.cond[from.0 as usize] { + d.extend(value_deps(cx, c, memo, cm)); + } + } + } + InstInfo::Load(p) => { + d.extend(value_deps(cx, p, memo, cm)); + if let Some(vs) = cx.root_stores.get(&root(cx.s, p)) { + for &x in vs { + d.extend(value_deps(cx, x, memo, cm)); + } + } + } + InstInfo::Other(ops) => { + for x in ops { + d.extend(value_deps(cx, x, memo, cm)); + } + } + InstInfo::Store(..) | InstInfo::Term(..) => {} + } + let _ = cx.block_of; + memo.insert(v, d.clone()); + d + } + + let cx = Cx { s, block_of: &block_of, ctrl: &ctrl, cond: &cond, root_stores: &root_stores, in_base: &in_base, inputs }; + let mut out: HashMap<(u8, u32), BTreeSet> = HashMap::new(); + let bases = |p: &[Placed]| -> Vec> { p.iter().map(|e| e.at.map(|(r, c)| r * 4 + c as u32)).collect() }; + let (ob, pb) = (bases(outputs), bases(prims)); + for b in 0..nb { + for &i in m.block_insts(Block(b as u32)) { + let InstInfo::Call(name, args) = m.inst_info(i) else { continue }; + let (dir, base) = if name.starts_with("dx.op.storeOutput.") || name.starts_with("dx.op.storeVertexOutput.") { + (0u8, &ob) + } else if name.starts_with("dx.op.storePrimitiveOutput.") { + (1u8, &pb) + } else { + continue; + }; + let id = m.const_u64(args[1]).unwrap() as usize; + let Some(base) = base[id] else { continue }; + let col = m.const_u64(args[3]).unwrap() as u32; + let row = m.const_u64(args[2]).unwrap() as u32; + let mut d = value_deps(&cx, args[4], &mut memo, &mut ctrl_memo); + d.extend(block_deps(&cx, b, &mut memo, &mut ctrl_memo)); + if args.len() > 5 { + d.extend(value_deps(&cx, args[5], &mut memo, &mut ctrl_memo)); + } + out.entry((dir, base + row * 4 + col)).or_default().extend(d); + } + } + Deps { out } +} + +/// The global (or other base) a pointer is derived from. +fn root(s: &Shader, p: Value) -> Value { + let mut p = p; + loop { + match p { + Value::Inst(i) => match s.m.inst_info(i) { + InstInfo::Other(ops) if !ops.is_empty() => p = ops[0], + _ => return p, + }, + _ => return p, + } + } +} + +/// Dependency table: for each input component `0..n_in`, a bitmask over +/// `n_out` output components, `ceil(n_out / 32)` dwords each. +fn dep_table(deps: &Deps, dir: u8, n_in: u32, n_out: u32) -> Vec { + let words = n_out.div_ceil(32) as usize; + let mut t = vec![0u32; n_in as usize * words]; + for (&(d, o), ins) in &deps.out { + if d != dir || o >= n_out { + continue; + } + for &i in ins { + if i < n_in { + t[i as usize * words + (o / 32) as usize] |= 1 << (o % 32); + } + } + } + t +} + +impl Shader { + /// Writes metadata, bitcode and the signed container for a vertex, + /// pixel or mesh entry point with the I/O declared in `io`. + /// Panics on a builder error (tests; translators use [`Shader::try_finish_graphics`]). + pub fn finish_graphics(self, io: GraphicsIo, info: StageInfo) -> Vec { + self.try_finish_graphics(io, info).unwrap_or_else(|e| panic!("DXIL builder: {e}")) + } + + /// [`Shader::finish_graphics`], or the first builder error. + pub fn try_finish_graphics(mut self, io: GraphicsIo, info: StageInfo) -> Result, String> { + if self.stage != io.stage { + return Err(format!("{:?} shader with {:?} I/O", self.stage, io.stage)); + } + match (self.stage, info) { + (Stage::Vertex, StageInfo::Vertex) | (Stage::Pixel, StageInfo::Pixel { .. }) | (Stage::Mesh, StageInfo::Mesh { .. }) => {} + (st, i) => return Err(format!("stage {st:?} with {i:?}")), + } + if !self.m.terminated() { + self.m.ret(); + } + self.m.optimize(); + self.infer_type_features(); + let ins = io.place(Dir::In); + let outs = io.place(Dir::Out); + let prims = io.place(Dir::Prim); + + let mut flags: u64 = self.features.iter().map(|f| f.metadata_bit()).fold(0, |a, b| a | b); + let mut sfi0: u64 = self.features.iter().map(|f| f.container_bit()).fold(0, |a, b| a | b); + let rt_vp = outs.iter().chain(&prims).any(|e| matches!(e.e.kind, SemKind::RenderTargetArrayIndex | SemKind::ViewportArrayIndex)); + // DXC sets this for vertex shaders only (not for mesh shaders). + if rt_vp && self.stage == Stage::Vertex { + flags |= 1 << 9; + sfi0 |= 0x2000; + } + // 16-bit signature elements: min precision unless native 16-bit types are enabled. + let native16 = self.features.contains(&Feature::NativeLowPrecision); + if !native16 && ins.iter().chain(&outs).chain(&prims).any(|e| e.e.ty.is_16bit()) { + flags |= 1 << 5; + sfi0 |= 0x10; + } + // Bound UAVs outside pixel/compute shaders (DXC: not for mesh shaders, + // nor for heap-indexed UAVs). + if self.stage == Stage::Vertex && self.bindings.iter().any(|b| b.class == ResClass::Uav) { + flags |= 1 << 16; + sfi0 |= 0x4; + } + if self.stage == Stage::Pixel { + if outs.iter().any(|e| e.e.kind == SemKind::StencilRef) { + flags |= 1 << 11; + sfi0 |= 0x200; + } + if let StageInfo::Pixel { early_depth_stencil: true } = info { + flags |= 1 << 3; + } + } + + // Dependency tables (from the code, before metadata is added). + let deps = compute_deps(&self, &ins, &outs, &prims); + let (n_in, n_out, n_prim) = (components(&ins), components(&outs), components(&prims)); + + let stage = self.stage; + let sm = self.sm; + let m = &mut self.m; + let one = m.md_i32(1); + let ver = m.md_i32(sm.1); + let dx_version = m.md_node(&[Some(one), Some(ver)]); + let valver = m.md_i32(super::validate::VALVER.1); + let dx_valver = m.md_node(&[Some(one), Some(valver)]); + let prefix = m.md_str(stage.profile_prefix()); + let smaj = m.md_i32(sm.0); + let shader_model = m.md_node(&[Some(prefix), Some(smaj), Some(ver)]); + + // dx.viewIdState: [inputs, outputs, (prim outputs), tables…]. + let mut vis = vec![n_in, n_out]; + if stage == Stage::Mesh { + vis.push(n_prim); + } + if n_in > 0 && n_out > 0 { + vis.extend(dep_table(&deps, 0, n_in, n_out)); + } + let i32 = m.i32(); + let at = m.array(vis.len() as u64, i32); + let elems: Vec = vis.iter().map(|&v| m.i32c(v)).collect(); + let arr = m.aggregate(at, &elems); + let arr_md = m.md_value(arr); + let view_id = m.md_node(&[Some(arr_md)]); + + // Signature metadata. + let sig_list = |m: &mut super::module::Module, p: &[Placed]| -> Option { + if p.is_empty() { + return None; + } + let nodes: Vec> = p + .iter() + .enumerate() + .map(|(i, e)| { + let id = m.md_i32(i as u32); + let name = m.md_str(&e.e.name); + let ct = m.i8c(e.e.ty.md()); + let ct = m.md_value(ct); + let k = m.i8c(e.e.kind as u8); + let k = m.md_value(k); + let idx: Vec> = e.e.indices.iter().map(|&x| Some(m.md_i32(x))).collect(); + let idx = m.md_node(&idx); + let ip = m.i8c(e.interp as u8); + let ip = m.md_value(ip); + let rows = m.md_i32(e.e.nrows()); + let cols = m.i8c(e.e.cols); + let cols = m.md_value(cols); + let (r, c) = e.at.map_or((u32::MAX, 0xFF), |(r, c)| (r, c)); + let r = m.md_i32(r); + let c = m.i8c(c); + let c = m.md_value(c); + let ext = if e.usage != 0 { + let t = m.md_i32(3); + let u = m.md_i32(e.usage as u32); + Some(m.md_node(&[Some(t), Some(u)])) + } else { + None + }; + Some(m.md_node(&[Some(id), Some(name), Some(ct), Some(k), Some(idx), Some(ip), Some(rows), Some(cols), Some(r), Some(c), ext])) + }) + .collect(); + Some(m.md_node(&nodes)) + }; + let in_md = sig_list(m, &ins); + let out_md = sig_list(m, &outs); + let prim_md = sig_list(m, &prims); + let sigs = if in_md.is_none() && out_md.is_none() && prim_md.is_none() { None } else { Some(m.md_node(&[in_md, out_md, prim_md])) }; + + let (resources, psv_res) = self.resource_metadata(); + let m = &mut self.m; + + // Entry properties. + let mut props: Vec> = Vec::new(); + if flags != 0 { + let tag = m.md_i32(0); + let v = m.md_i64(flags); + props.extend([Some(tag), Some(v)]); + } + let mut numthreads = [0u32; 3]; + if let StageInfo::Mesh { numthreads: nt, max_vertices, max_primitives, topology, payload_bytes, .. } = info { + numthreads = nt; + let tag = m.md_i32(9); + let ntv: Vec> = nt.iter().map(|&n| Some(m.md_i32(n))).collect(); + let ntn = m.md_node(&ntv); + let (mv, mp, tp, pb) = (m.md_i32(max_vertices), m.md_i32(max_primitives), m.md_i32(topology as u32), m.md_i32(payload_bytes)); + let node = m.md_node(&[Some(ntn), Some(mv), Some(mp), Some(tp), Some(pb)]); + props.extend([Some(tag), Some(node)]); + } + let props_node = if props.is_empty() { None } else { Some(m.md_node(&props)) }; + let fv = m.func_value(self.entry); + let fmd = m.md_value(fv); + let name = m.md_str("main"); + let entry = m.md_node(&[Some(fmd), Some(name), sigs, resources, props_node]); + + // `!llvm.ident`, as DXC writes first: AMD's driver compiler (amdxc64) crashes at + // PSO creation on modules without it. + let ident = m.md_str("xcl"); + let ident = m.md_node(&[Some(ident)]); + m.named_md("llvm.ident", &[ident]); + m.named_md("dx.version", &[dx_version]); + m.named_md("dx.valver", &[dx_valver]); + m.named_md("dx.shaderModel", &[shader_model]); + if let Some(r) = resources { + m.named_md("dx.resources", &[r]); + } + m.named_md("dx.viewIdState", &[view_id]); + m.named_md("dx.entryPoints", &[entry]); + let bitcode = m.try_to_bitcode(TRIPLE, if native16 { DATALAYOUT_NATIVE16 } else { DATALAYOUT })?; + + // PSV0. + let (iv, ov, pv) = (vectors(&ins), vectors(&outs), vectors(&prims)); + let mut stage_info = [0u8; 16]; + let mut info1 = [0u8; 2]; + match info { + StageInfo::Vertex => stage_info[0] = outs.iter().any(|e| e.e.kind == SemKind::Position) as u8, + StageInfo::Pixel { .. } => { + stage_info[0] = outs.iter().any(|e| matches!(e.e.kind, SemKind::Depth | SemKind::DepthLessEqual | SemKind::DepthGreaterEqual)) as u8; + stage_info[1] = (io.uses_sample_index + || ins.iter().any(|e| e.e.kind == SemKind::SampleIndex || matches!(e.interp, Interp::LinearSample | Interp::LinearNoperspectiveSample))) + as u8; + } + StageInfo::Mesh { max_vertices, max_primitives, topology, payload_bytes, .. } => { + let groupshared_bytes = self.m.global_bytes_layout(3, native16) as u32; + stage_info[0..4].copy_from_slice(&groupshared_bytes.to_le_bytes()); + stage_info[8..12].copy_from_slice(&payload_bytes.to_le_bytes()); + stage_info[12..14].copy_from_slice(&(max_vertices as u16).to_le_bytes()); + stage_info[14..16].copy_from_slice(&(max_primitives as u16).to_le_bytes()); + info1 = [pv as u8, topology as u8]; + } + } + let mut tables = Vec::new(); + if iv > 0 && ov > 0 { + tables.push(dep_table(&deps, 0, iv * 4, ov * 4)); + } + let psv = PsvFull { + stage, + stage_info, + min_wave: 0, + max_wave: u32::MAX, + uses_view_id: false, + info1, + numthreads, + resources: psv_res, + entry: "main".into(), + inputs: psv_elems(&ins), + outputs: psv_elems(&outs), + prims: psv_elems(&prims), + input_vectors: iv as u8, + output_vectors: [ov as u8, 0, 0, 0], + tables, + }; + let psg = if stage == Stage::Mesh { Some(sig_part(&prims, true, native16)) } else { None }; + let (isg, osg) = (sig_part(&ins, false, native16), sig_part(&outs, true, native16)); + Ok(container::container_with_signatures(stage, sm, &bitcode, sfi0, isg, osg, psg, container::psv_part_full(&psv))) + } +} + +#[cfg(test)] +#[path = "graphics_tests.rs"] +pub(in crate::gpu::dxil) mod tests; diff --git a/crates/xcl/src/gpu/dxil/graphics_tests.rs b/crates/xcl/src/gpu/dxil/graphics_tests.rs new file mode 100644 index 000000000..d2d8f8876 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/graphics_tests.rs @@ -0,0 +1,1195 @@ +//! Graphics-stage checks: container parts byte for byte against DXC 1.9 +//! output for the HLSL programs in `tests/data/dxil/dxc_{vs,ps,ms}_*.hlsl`, the +//! validator on every emitted shader, and draws on the GPU. + +use super::*; +use crate::gpu::dxil::module::{BinOp, CastOp, Pred}; +use crate::gpu::dxil::validate; + +pub(super) fn part<'a>(c: &'a [u8], cc: &[u8; 4]) -> Option<&'a [u8]> { + let n = u32::from_le_bytes(c[28..32].try_into().unwrap()) as usize; + (0..n).find_map(|i| { + let off = u32::from_le_bytes(c[32 + 4 * i..36 + 4 * i].try_into().unwrap()) as usize; + (&c[off..off + 4] == cc).then(|| { + let len = u32::from_le_bytes(c[off + 4..off + 8].try_into().unwrap()) as usize; + &c[off + 8..off + 8 + len] + }) + }) +} + +fn hex(b: &[u8]) -> String { + b.chunks(16).enumerate().map(|(i, c)| format!("{:04x}: {}\n", i * 16, c.iter().map(|x| format!("{x:02x}")).collect::>().join(" "))).collect() +} + +/// Asserts the signature and PSV parts match DXC's. +fn assert_parts_match(ours: &[u8], dxc: &[u8]) { + for cc in [b"ISG1", b"OSG1", b"PSG1", b"PSV0"] { + let (a, b) = (part(ours, cc), part(dxc, cc)); + assert_eq!(a.is_some(), b.is_some(), "{} presence", String::from_utf8_lossy(cc)); + if let (Some(a), Some(b)) = (a, b) { + assert!(a == b, "{} differs\n--- ours\n{}--- dxc\n{}", String::from_utf8_lossy(cc), hex(a), hex(b)); + } + } +} + +pub(super) fn assert_valid(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}"); + } +} + +/// `tests/data/dxil/dxc_vs_basic.hlsl`. +fn vs_basic() -> Vec { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let pos = io.input(SigElement::user("POSITION", 0, CompType::F32, 3)); + let col = io.input(SigElement::user("COLOR", 0, CompType::F32, 4)); + let vid = io.input(SigElement::new("SV_VertexID", 0, SemKind::VertexId, CompType::U32, 1)); + let opos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let ocol = io.output(SigElement::user("COLOR", 0, CompType::F32, 4)); + let otc = io.output(SigElement::user("TEXCOORD", 1, CompType::F32, 2)); + let v = io.load_input(&mut s, vid, 0, 0); + let c: Vec = (0..4).map(|i| io.load_input(&mut s, col, 0, i)).collect(); + let p: Vec = (0..3).map(|i| io.load_input(&mut s, pos, 0, i)).collect(); + let f32 = s.m.f32(); + let vf = s.m.cast(CastOp::UIToFP, v, f32); + let one = s.m.f32c(1.0f32.to_bits()); + let zero = s.m.f32c(0); + for (i, &x) in p.iter().chain([&one]).enumerate() { + io.store_output(&mut s, opos, 0, i as u8, x); + } + for (i, &x) in c.iter().enumerate() { + io.store_output(&mut s, ocol, 0, i as u8, x); + } + io.store_output(&mut s, otc, 0, 0, vf); + io.store_output(&mut s, otc, 0, 1, zero); + s.finish_graphics(io, StageInfo::Vertex) +} + +/// `tests/data/dxil/dxc_ps_basic.hlsl`. +fn ps_basic() -> Vec { + 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, CompType::F32, 4)); + let col = io.input(SigElement::user("COLOR", 0, CompType::F32, 4)); + let tc = io.input(SigElement::user("TEXCOORD", 1, CompType::F32, 2)); + let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + let uv: Vec = (0..2).map(|i| io.load_input(&mut s, tc, 0, i)).collect(); + let c: Vec = (0..4).map(|i| io.load_input(&mut s, col, 0, i)).collect(); + for i in 0..4 { + let r = s.m.fbin(BinOpF::Add.into(), c[i], uv[i % 2], 0); + io.store_output(&mut s, tgt, 0, i as u8, r); + } + s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }) +} + +/// `BinOp` for float adds (readability). +enum BinOpF { + Add, +} +impl From for crate::gpu::dxil::module::BinOp { + fn from(_: BinOpF) -> Self { + crate::gpu::dxil::module::BinOp::Add + } +} + +const DXC_VS_BASIC: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_vs_basic.dxil"); +const DXC_PS_BASIC: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ps_basic.dxil"); + +#[test] +fn vs_basic_parts_match_dxc() { + assert_parts_match(&vs_basic(), DXC_VS_BASIC); +} + +#[test] +fn vs_basic_validates() { + assert_valid(&vs_basic()); +} + +#[test] +fn ps_basic_parts_match_dxc() { + assert_parts_match(&ps_basic(), DXC_PS_BASIC); +} + +#[test] +fn ps_basic_validates() { + assert_valid(&ps_basic()); +} + + +fn f(s: &mut Shader, v: f32) -> Value { + s.m.f32c(v.to_bits()) +} + +/// `tests/data/dxil/dxc_ps_modes.hlsl`: interpolation modes, system values, +/// discard, coverage, two targets and depth. +fn ps_modes() -> Vec { + 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, CompType::F32, 4)); + let mode = io.input(SigElement::user("MODE", 0, CompType::U32, 1)); + let c = io.input(SigElement::user("TEXCOORD", 0, CompType::F32, 2).interp(Interp::LinearCentroid)); + let t = io.input(SigElement::user("TEXCOORD", 1, CompType::F32, 1).interp(Interp::LinearNoperspective)); + let smp = io.input(SigElement::user("TEXCOORD", 2, CompType::F32, 3).interp(Interp::LinearSample)); + let ff = io.input(SigElement::new("SV_IsFrontFace", 0, SemKind::IsFrontFace, CompType::U32, 1)); + let pid = io.input(SigElement::new("SV_PrimitiveID", 0, SemKind::PrimitiveId, CompType::U32, 1)); + let q = io.input(SigElement::user("Q", 0, CompType::F32, 1).interp(Interp::LinearNoperspectiveCentroid)); + let ta = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + let tb = io.output(SigElement::new("SV_Target", 1, SemKind::Target, CompType::F32, 4)); + let depth = io.output(SigElement::new("SV_Depth", 0, SemKind::Depth, CompType::F32, 1)); + + let qv = io.load_input(&mut s, q, 0, 0); + let pv = io.load_input(&mut s, pid, 0, 0); + let fv = io.load_input(&mut s, ff, 0, 0); + let zero_i = s.m.i32c(0); + let front = s.m.cmp(Pred::Ne, fv, zero_i); + let sv: Vec = (0..3).map(|i| io.load_input(&mut s, smp, 0, i)).collect(); + let tv = io.load_input(&mut s, t, 0, 0); + let cv: Vec = (0..2).map(|i| io.load_input(&mut s, c, 0, i)).collect(); + let mv = io.load_input(&mut s, mode, 0, 0); + let pz = io.load_input(&mut s, pos, 0, 2); + let cov = io.coverage(&mut s); + let three = s.m.i32c(3); + let is3 = s.m.cmp(Pred::Eq, mv, three); + let kill = s.m.new_block(); + let join = s.m.new_block(); + s.m.cond_br(is3, kill, join); + s.m.set_block(kill); + let t_ = s.m.i1c(true); + io.discard(&mut s, t_); + s.m.br(join); + s.m.set_block(join); + let (one, zero) = (f(&mut s, 1.0), f(&mut s, 0.0)); + let sel = s.m.select(front, one, zero); + let sum = s.m.bin(BinOp::Add, cov, pv); + let f32 = s.m.f32(); + let sumf = s.m.cast(CastOp::UIToFP, sum, f32); + let w = s.m.fbin(BinOp::Add, sumf, qv, 0); + for (i, &x) in [cv[0], cv[1], tv, sv[0]].iter().enumerate() { + io.store_output(&mut s, ta, 0, i as u8, x); + } + for (i, &x) in [sv[1], sv[2], sel, w].iter().enumerate() { + io.store_output(&mut s, tb, 0, i as u8, x); + } + io.store_output(&mut s, depth, 0, 0, pz); + s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }) +} + +/// `tests/data/dxil/dxc_ps_packing.hlsl`: row sharing between user semantics and +/// system values, mixed types, unpacked `SV_SampleIndex`, unused inputs. +fn ps_packing() -> Vec { + let mut s = Shader::new(Stage::Pixel, (6, 6)); + let mut io = GraphicsIo::new(Stage::Pixel); + let a = io.input(SigElement::user("A", 0, CompType::U32, 1)); + let ff = io.input(SigElement::new("SV_IsFrontFace", 0, SemKind::IsFrontFace, CompType::U32, 1)); + let b = io.input(SigElement::user("B", 0, CompType::U32, 1)); + let c = io.input(SigElement::user("C", 0, CompType::F32, 1)); + let d = io.input(SigElement::user("D", 0, CompType::F32, 2)); + let e = io.input(SigElement::user("E", 0, CompType::F32, 1).interp(Interp::Constant)); + let si = io.input(SigElement::new("SV_SampleIndex", 0, SemKind::SampleIndex, CompType::U32, 1)); + let p = io.input(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let h = io.input(SigElement::user("H", 0, CompType::I32, 1)); + let _rest = io.input(SigElement::user("REST", 0, CompType::U32, 4)); + let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + let f32 = s.m.f32(); + let mut acc = f(&mut s, 0.0); + for (sig, int) in [(a, true), (ff, true), (b, true), (c, false), (d, false), (e, false), (si, true), (p, false), (h, true)] { + let v = io.load_input(&mut s, sig, 0, 0); + let v = if int { s.m.cast(CastOp::UIToFP, v, f32) } else { v }; + acc = s.m.fbin(BinOp::Add, acc, v, 0); + } + for i in 0..4 { + io.store_output(&mut s, tgt, 0, i, acc); + } + s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }) +} + +/// `tests/data/dxil/dxc_vs_packing.hlsl`: output packing with system values, +/// a two-row matrix, `SV_RenderTargetArrayIndex`, `SV_InstanceID`. +fn vs_packing() -> Vec { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let vid = io.input(SigElement::new("SV_VertexID", 0, SemKind::VertexId, CompType::U32, 1)); + let iid = io.input(SigElement::new("SV_InstanceID", 0, SemKind::InstanceId, CompType::U32, 1)); + let oa = io.output(SigElement::user("A", 0, CompType::F32, 2)); + let ob = io.output(SigElement::user("B", 0, CompType::F32, 2)); + let oc = io.output(SigElement::user("C", 0, CompType::F32, 1)); + let od = io.output(SigElement::user("D", 0, CompType::U32, 1)); + let op = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let oe = io.output(SigElement::user("E", 0, CompType::F32, 1)); + let ort = io.output(SigElement::new("SV_RenderTargetArrayIndex", 0, SemKind::RenderTargetArrayIndex, CompType::U32, 1)); + let of = io.output(SigElement::user("F", 0, CompType::U32, 2)); + let og = io.output(SigElement::user("G", 0, CompType::F32, 3)); + let om = io.output(SigElement::user("M", 0, CompType::F32, 2).rows(2)); + let oi = io.output(SigElement::user("I", 0, CompType::U32, 1)); + let v = io.load_input(&mut s, vid, 0, 0); + let i = io.load_input(&mut s, iid, 0, 0); + let f32 = s.m.f32(); + let vf = s.m.cast(CastOp::UIToFP, v, f32); + for c in 0..2 { + io.store_output(&mut s, oa, 0, c, vf); + let one = f(&mut s, 1.0); + io.store_output(&mut s, ob, 0, c, one); + } + let two = f(&mut s, 2.0); + io.store_output(&mut s, oc, 0, 0, two); + io.store_output(&mut s, od, 0, 0, i); + for c in 0..4 { + let z = f(&mut s, 0.0); + io.store_output(&mut s, op, 0, c, z); + } + let three = f(&mut s, 3.0); + io.store_output(&mut s, oe, 0, 0, three); + io.store_output(&mut s, ort, 0, 0, v); + io.store_output(&mut s, of, 0, 0, i); + io.store_output(&mut s, of, 0, 1, i); + for c in 0..3 { + let x = f(&mut s, 4.0); + io.store_output(&mut s, og, 0, c, x); + } + let (m1, m2, m3) = (f(&mut s, 1.0), f(&mut s, 2.0), f(&mut s, 3.0)); + io.store_output(&mut s, om, 0, 0, m1); + io.store_output(&mut s, om, 0, 1, m2); + io.store_output(&mut s, om, 1, 0, m3); + io.store_output(&mut s, om, 1, 1, vf); + let five = s.m.i32c(5); + io.store_output(&mut s, oi, 0, 0, five); + s.finish_graphics(io, StageInfo::Vertex) +} + +/// `tests/data/dxil/dxc_ms_basic.hlsl`: vertex and primitive outputs. +fn ms_basic() -> Vec { + let mut s = Shader::new(Stage::Mesh, (6, 6)); + let mut io = GraphicsIo::new(Stage::Mesh); + let pos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let col = io.output(SigElement::user("COLOR", 0, CompType::F32, 4)); + let pid = io.primitive(SigElement::new("SV_PrimitiveID", 0, SemKind::PrimitiveId, CompType::U32, 1)); + let extra = io.primitive(SigElement::user("EXTRA", 0, CompType::F32, 2).interp(Interp::Constant)); + let tid = s.thread_id_in_group(0); + let (three, one) = (s.m.i32c(3), s.m.i32c(1)); + io.set_mesh_output_counts(&mut s, three, one); + let lt = s.m.cmp(Pred::ULt, tid, three); + let (bv, test, bp, end) = (s.m.new_block(), s.m.new_block(), s.m.new_block(), s.m.new_block()); + s.m.cond_br(lt, bv, test); + s.m.set_block(bv); + let f32 = s.m.f32(); + let x = s.m.cast(CastOp::UIToFP, tid, f32); + let (z, o) = (f(&mut s, 0.0), f(&mut s, 1.0)); + for (c, &v) in [x, z, z, o].iter().enumerate() { + io.store_vertex_output(&mut s, pos, 0, c as u8, v, tid); + } + for (c, &v) in [o, z, z, o].iter().enumerate() { + io.store_vertex_output(&mut s, col, 0, c as u8, v, tid); + } + s.m.br(test); + s.m.set_block(test); + let zero = s.m.i32c(0); + let first = s.m.cmp(Pred::Eq, tid, zero); + s.m.cond_br(first, bp, end); + s.m.set_block(bp); + let two = s.m.i32c(2); + io.emit_indices(&mut s, zero, &[zero, one, two]); + let seven = s.m.i32c(7); + io.store_primitive_output(&mut s, pid, 0, 0, seven, zero); + let f2 = f(&mut s, 2.0); + io.store_primitive_output(&mut s, extra, 0, 0, o, zero); + io.store_primitive_output(&mut s, extra, 0, 1, f2, zero); + s.m.br(end); + s.m.set_block(end); + let info = StageInfo::Mesh { numthreads: [32, 1, 1], max_vertices: 3, max_primitives: 1, topology: Topology::Triangle, payload_bytes: 0 }; + s.finish_graphics(io, info) +} + +const DXC_PS_MODES: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ps_modes.dxil"); +const DXC_PS_PACKING: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ps_packing.dxil"); +const DXC_VS_PACKING: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_vs_packing.dxil"); +const DXC_MS_BASIC: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ms_basic.dxil"); + +#[test] +fn ps_modes_parts_match_dxc() { + let c = ps_modes(); + assert_parts_match(&c, DXC_PS_MODES); + assert_eq!(part(&c, b"SFI0"), part(DXC_PS_MODES, b"SFI0")); + assert_valid(&c); +} + +#[test] +fn ps_packing_parts_match_dxc() { + let c = ps_packing(); + assert_parts_match(&c, DXC_PS_PACKING); + assert_valid(&c); +} + +#[test] +fn vs_packing_parts_match_dxc() { + let c = vs_packing(); + assert_parts_match(&c, DXC_VS_PACKING); + assert_eq!(part(&c, b"SFI0"), part(DXC_VS_PACKING, b"SFI0")); + assert_valid(&c); +} + +#[test] +fn ms_basic_parts_match_dxc() { + let c = ms_basic(); + assert_parts_match(&c, DXC_MS_BASIC); + assert_valid(&c); +} + +// ---- GPU draws + +/// The draw test's pixel shader: `SV_Target = float4(COLOR.rgb * mem[0..3], float(ID) + mem[3])` +/// where `ID` is a `nointerpolation uint` (the provoking vertex's id) and +/// `mem` the raw UAV `u2` the draw benches bind to their flat memory. +fn draw_ps() -> Vec { + let mut s = Shader::new(Stage::Pixel, (6, 6)); + let mut io = GraphicsIo::new(Stage::Pixel); + let mem = s.raw_uav(2, 0); + let _pos = io.input(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let col = io.input(SigElement::user("COLOR", 0, CompType::F32, 4)); + let id = io.input(SigElement::user("ID", 0, CompType::U32, 1)); + let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + let zero = s.m.i32c(0); + let k = s.raw_load(mem, zero, 0xF); + let f32 = s.m.f32(); + for c in 0..3 { + let x = io.load_input(&mut s, col, 0, c); + let kc = s.m.bitcast(k[c as usize], f32); + let r = s.m.fbin(BinOp::Mul, x, kc, 0); + io.store_output(&mut s, tgt, 0, c, r); + } + let i = io.load_input(&mut s, id, 0, 0); + let fi = s.m.cast(CastOp::UIToFP, i, f32); + let k3 = s.m.bitcast(k[3], f32); + let w = s.m.fbin(BinOp::Add, fi, k3, 0); + io.store_output(&mut s, tgt, 0, 3, w); + s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }) +} + +/// The draw test's vertex shader: `POSITION.xy` (z = 0, w = 1), `COLOR` +/// passed through, `ID = SV_VertexID + 5`. +fn draw_vs() -> Vec { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let pos = io.input(SigElement::user("POSITION", 0, CompType::F32, 2)); + let col = io.input(SigElement::user("COLOR", 0, CompType::F32, 4)); + let vid = io.input(SigElement::new("SV_VertexID", 0, SemKind::VertexId, CompType::U32, 1)); + let opos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let ocol = io.output(SigElement::user("COLOR", 0, CompType::F32, 4)); + let oid = io.output(SigElement::user("ID", 0, CompType::U32, 1)); + let x = io.load_input(&mut s, pos, 0, 0); + let y = io.load_input(&mut s, pos, 0, 1); + let (z, o) = (f(&mut s, 0.0), f(&mut s, 1.0)); + for (c, &v) in [x, y, z, o].iter().enumerate() { + io.store_output(&mut s, opos, 0, c as u8, v); + } + for c in 0..4 { + let v = io.load_input(&mut s, col, 0, c); + io.store_output(&mut s, ocol, 0, c, v); + } + let v = io.load_input(&mut s, vid, 0, 0); + let five = s.m.i32c(5); + let id = s.m.bin(BinOp::Add, v, five); + io.store_output(&mut s, oid, 0, 0, id); + s.finish_graphics(io, StageInfo::Vertex) +} + +const SIZE: u32 = 8; +const CLEAR: [f32; 4] = [0.0, 0.0, 0.0, 0.5]; +const MEM: [f32; 4] = [2.0, 0.5, 1.0, 0.25]; +const COLOR: [f32; 4] = [0.25, 0.5, 0.75, 1.0]; + +/// Pixel (x, y) is covered by the triangle (-1,-1), (-1,1.1), (1.1,-1) iff x <= y. +fn expect_triangle(px: &[[f32; 4]], inside: [f32; 4]) { + for y in 0..SIZE as usize { + for x in 0..SIZE as usize { + let want = if x <= y { inside } else { CLEAR }; + assert_eq!(px[y * SIZE as usize + x], want, "pixel ({x}, {y})"); + } + } +} + +/// Whether the runner's VS/PS draw path can run here. It is exercised upstream only where +/// wave64 programs run (`recomp::tests::gpu_ready`); on an adapter with neither 32- nor +/// 64-lane waves (WARP / the Basic Render Driver on CI) even a DXC-compiled VS/PS draw +/// removes the device, which would then fail every later GPU test in the process. +pub(in crate::gpu::dxil) fn draw_ready() -> bool { + use crate::gpu::recomp::runner; + match runner::wave64_programs_supported() { + Ok(true) => true, + Ok(false) => { + runner::skip_test("no wave64"); + false + } + Err(_) => { + runner::skip_test("no GPU"); + false + } + } +} + +#[test] +fn emitted_vs_ps_draw_a_triangle() { + use crate::gpu::recomp::runner; + use windows::Win32::Graphics::Dxgi::Common::*; + if !draw_ready() { + return; + } + let (vs, ps) = (draw_vs(), draw_ps()); + assert_valid(&vs); + assert_valid(&ps); + let tri = [(-1.0f32, -1.0f32), (-1.0, 1.1), (1.1, -1.0)]; + let verts: Vec = tri.iter().flat_map(|&(x, y)| [x, y].into_iter().chain(COLOR)).collect(); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 8 }, + ]; + let mem: Vec = MEM.iter().map(|f| f.to_bits()).collect(); + let px = match runner::draw(&vs, &ps, &layout, &verts, 24, &[], &mem, SIZE, CLEAR) { + Ok(p) => p, + Err(e) if e.contains("no D3D12") || e.contains("adapter") => return runner::skip_test(&e), + Err(e) => panic!("draw: {e}"), + }; + // Provoking vertex 0 → ID 5. + expect_triangle(&px, [COLOR[0] * MEM[0], COLOR[1] * MEM[1], COLOR[2] * MEM[2], 5.0 + MEM[3]]); +} + +/// The mesh test's mesh shader: 3 threads, thread `t` writes vertex `t` of +/// the draw test's triangle (`ID = t + 5`), thread 0 the indices and counts. +fn draw_ms() -> Vec { + let mut s = Shader::new(Stage::Mesh, (6, 6)); + let mut io = GraphicsIo::new(Stage::Mesh); + let opos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let ocol = io.output(SigElement::user("COLOR", 0, CompType::F32, 4)); + let oid = io.output(SigElement::user("ID", 0, CompType::U32, 1)); + let tid = s.thread_id_in_group(0); + let (zero, one, two, three) = (s.m.i32c(0), s.m.i32c(1), s.m.i32c(2), s.m.i32c(3)); + io.set_mesh_output_counts(&mut s, three, one); + // x = (t == 2) ? 1.1 : -1; y = (t == 1) ? 1.1 : -1 + let (m1, big) = (f(&mut s, -1.0), f(&mut s, 1.1)); + let is2 = s.m.cmp(Pred::Eq, tid, two); + let is1 = s.m.cmp(Pred::Eq, tid, one); + let x = s.m.select(is2, big, m1); + let y = s.m.select(is1, big, m1); + let (z, o) = (f(&mut s, 0.0), f(&mut s, 1.0)); + for (c, &v) in [x, y, z, o].iter().enumerate() { + io.store_vertex_output(&mut s, opos, 0, c as u8, v, tid); + } + for (c, &v) in COLOR.iter().enumerate() { + let k = f(&mut s, v); + io.store_vertex_output(&mut s, ocol, 0, c as u8, k, tid); + } + let five = s.m.i32c(5); + let id = s.m.bin(BinOp::Add, tid, five); + io.store_vertex_output(&mut s, oid, 0, 0, id, tid); + let first = s.m.cmp(Pred::Eq, tid, zero); + let (bp, end) = (s.m.new_block(), s.m.new_block()); + s.m.cond_br(first, bp, end); + s.m.set_block(bp); + io.emit_indices(&mut s, zero, &[zero, one, two]); + s.m.br(end); + s.m.set_block(end); + let info = StageInfo::Mesh { numthreads: [3, 1, 1], max_vertices: 3, max_primitives: 1, topology: Topology::Triangle, payload_bytes: 0 }; + s.finish_graphics(io, info) +} + +/// An empty compute pass for the two-pass mesh bench. +fn empty_cs() -> Vec { + Shader::new(Stage::Compute, (6, 6)).finish([1, 1, 1], None) +} + +#[test] +fn emitted_ms_ps_draw_a_triangle() { + use crate::gpu::recomp::runner; + match runner::mesh_shaders_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no mesh shaders"), + Err(e) => return runner::skip_test(&e), + } + let (cs, ms, ps) = (empty_cs(), draw_ms(), draw_ps()); + assert_valid(&ms); + let mem: Vec = MEM.iter().map(|f| f.to_bits()).collect(); + let (px, _) = runner::mesh_draw(&cs, &ms, &ps, 1, 4, &[], &mem, SIZE, CLEAR).expect("mesh draw"); + expect_triangle(&px, [COLOR[0] * MEM[0], COLOR[1] * MEM[1], COLOR[2] * MEM[2], 5.0 + MEM[3]]); +} + +/// `tests/data/dxil/dxc_ms_payload.hlsl`: payload, groupshared memory, line +/// topology, `SV_CullPrimitive` (unpacked bool), `SV_RenderTargetArrayIndex` +/// sharing a primitive row. +fn ms_payload() -> Vec { + let mut s = Shader::new(Stage::Mesh, (6, 6)); + let mut io = GraphicsIo::new(Stage::Mesh); + let pos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let k = io.primitive(SigElement::user("PRIMK", 0, CompType::U32, 1)); + let cull = io.primitive(SigElement::new("SV_CullPrimitive", 0, SemKind::CullPrimitive, CompType::Bool, 1)); + let rt = io.primitive(SigElement::new("SV_RenderTargetArrayIndex", 0, SemKind::RenderTargetArrayIndex, CompType::U32, 1)); + let (i32, f32) = (s.m.i32(), s.m.f32()); + let arr3 = s.m.array(3, f32); + let pay_ty = s.m.named_struct("struct.Pay", &[i32, arr3]); + let gs_ty = s.m.array(16, i32); + let gs = s.m.global("gs", gs_ty, 3, None, false, 4); + + let tid = s.flattened_thread_id_in_group(); + let pay = io.mesh_payload(&mut s, pay_ty, "struct.Pay"); + let (c0, c1, c2, c3, c4, c15) = (s.m.i32c(0), s.m.i32c(1), s.m.i32c(2), s.m.i32c(3), s.m.i32c(4), s.m.i32c(15)); + let pa = s.m.gep_fields(pay, &[c0, c0]); + let a = s.m.load(pa, 4); + let slot = s.m.bin(BinOp::And, tid, c15); + let p = s.m.gep(gs, &[c0, slot]); + s.m.store(p, a, 4); + let void = s.m.void(); + let mode = s.m.i32c(9); + s.op(80, "barrier", None, void, &[mode], FnAttrs::NoDuplicate); + io.set_mesh_output_counts(&mut s, c4, c2); + let lt4 = s.m.cmp(Pred::ULt, tid, c4); + let (bv, test, bp, end) = (s.m.new_block(), s.m.new_block(), s.m.new_block(), s.m.new_block()); + s.m.cond_br(lt4, bv, end); + s.m.set_block(bv); + let t1 = s.m.bin(BinOp::Add, tid, c1); + let t1m = s.m.bin(BinOp::And, t1, c15); + let q = s.m.gep(gs, &[c0, t1m]); + let g = s.m.load(q, 4); + let gf = s.m.cast(CastOp::UIToFP, g, f32); + let r = s.m.bin(BinOp::URem, tid, c3); + let pb = s.m.gep_fields(pay, &[c0, c1, r]); + let b = s.m.load(pb, 4); + let (z, o) = (f(&mut s, 0.0), f(&mut s, 1.0)); + for (c, &v) in [gf, b, z, o].iter().enumerate() { + io.store_vertex_output(&mut s, pos, 0, c as u8, v, tid); + } + let lt2 = s.m.cmp(Pred::ULt, tid, c2); + s.m.cond_br(lt2, bp, end); + s.m.set_block(bp); + io.emit_indices(&mut s, tid, &[tid, t1]); + io.store_primitive_output(&mut s, k, 0, 0, tid, tid); + io.store_primitive_output(&mut s, cull, 0, 0, c0, tid); + io.store_primitive_output(&mut s, rt, 0, 0, c1, tid); + s.m.br(end); + s.m.set_block(test); + s.m.br(end); + s.m.set_block(end); + let info = StageInfo::Mesh { numthreads: [16, 2, 1], max_vertices: 4, max_primitives: 2, topology: Topology::Line, payload_bytes: 16 }; + s.finish_graphics(io, info) +} + +/// `tests/data/dxil/dxc_ps_outputs.hlsl`: `SV_Target2`, coverage / depth-GE / +/// stencil outputs, centroid position, a primitive attribute and the render +/// target index as inputs. +fn ps_outputs() -> Vec { + let mut s = Shader::new(Stage::Pixel, (6, 6)); + let mut io = GraphicsIo::new(Stage::Pixel); + let p = io.input(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4).interp(Interp::LinearNoperspectiveCentroid)); + let k = io.input(SigElement::user("PRIMK", 0, CompType::U32, 1)); + let rt = io.input(SigElement::new("SV_RenderTargetArrayIndex", 0, SemKind::RenderTargetArrayIndex, CompType::U32, 1)); + let c = io.output(SigElement::new("SV_Target", 2, SemKind::Target, CompType::F32, 4)); + let cov = io.output(SigElement::new("SV_Coverage", 0, SemKind::Coverage, CompType::U32, 1)); + let d = io.output(SigElement::new("SV_DepthGreaterEqual", 0, SemKind::DepthGreaterEqual, CompType::F32, 1)); + let st = io.output(SigElement::new("SV_StencilRef", 0, SemKind::StencilRef, CompType::U32, 1)); + let rv = io.load_input(&mut s, rt, 0, 0); + let kv = io.load_input(&mut s, k, 0, 0); + let px = io.load_input(&mut s, p, 0, 0); + let f32 = s.m.f32(); + let kf = s.m.cast(CastOp::UIToFP, kv, f32); + let rf = s.m.cast(CastOp::UIToFP, rv, f32); + let four = f(&mut s, 4.0); + let gt = s.m.cmp(Pred::FOGt, px, four); + let (two, zero, one, half) = (f(&mut s, 2.0), f(&mut s, 0.0), f(&mut s, 1.0), f(&mut s, 0.5)); + let z = s.m.select(gt, two, zero); + for (i, &v) in [kf, rf, z, one].iter().enumerate() { + io.store_output(&mut s, c, 0, i as u8, v); + } + let c1 = s.m.i32c(1); + io.store_output(&mut s, cov, 0, 0, c1); + io.store_output(&mut s, d, 0, 0, half); + io.store_output(&mut s, st, 0, 0, kv); + s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }) +} + +/// `tests/data/dxil/dxc_vs_control.hlsl`: outputs that depend on inputs only +/// through branches and a loop (control dependence in the PSV0 tables). +fn vs_control() -> Vec { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let p = io.input(SigElement::user("POSITION", 0, CompType::F32, 4)); + let c = io.input(SigElement::user("C", 0, CompType::F32, 1)); + let iid = io.input(SigElement::new("SV_InstanceID", 0, SemKind::InstanceId, CompType::U32, 1)); + let opos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let oa = io.output(SigElement::user("A", 0, CompType::F32, 1)); + let ob = io.output(SigElement::user("B", 0, CompType::F32, 1)); + let n = io.load_input(&mut s, iid, 0, 0); + let cv = io.load_input(&mut s, c, 0, 0); + let pv: Vec = (0..4).map(|i| io.load_input(&mut s, p, 0, i)).collect(); + let half = f(&mut s, 0.5); + let big = s.m.cmp(Pred::FOGt, cv, half); + let entry = s.m.current_block(); + let (b8, b10, b13, b14, b15, b17) = (s.m.new_block(), s.m.new_block(), s.m.new_block(), s.m.new_block(), s.m.new_block(), s.m.new_block()); + s.m.cond_br(big, b8, b10); + s.m.set_block(b8); + let two = f(&mut s, 2.0); + let x2 = s.m.fbin(BinOp::Mul, pv[0], two, 0); + s.m.br(b10); + s.m.set_block(b10); + let f32 = s.m.f32(); + let a = s.m.phi(f32); + let zero = f(&mut s, 0.0); + s.m.add_incoming(a, x2, b8); + s.m.add_incoming(a, zero, entry); + let c0 = s.m.i32c(0); + let none = s.m.cmp(Pred::Eq, n, c0); + s.m.cond_br(none, b15, b13); + s.m.set_block(b13); + s.m.br(b17); + s.m.set_block(b14); + s.m.br(b15); + s.m.set_block(b17); + let i32 = s.m.i32(); + let acc = s.m.phi(f32); + let i = s.m.phi(i32); + let next = s.m.fbin(BinOp::Add, acc, pv[1], 0); + let c1 = s.m.i32c(1); + let inext = s.m.bin(BinOp::Add, i, c1); + let done = s.m.cmp(Pred::Eq, inext, n); + s.m.cond_br(done, b14, b17); + let one = f(&mut s, 1.0); + s.m.add_incoming(acc, next, b17); + s.m.add_incoming(acc, one, b13); + s.m.add_incoming(i, inext, b17); + s.m.add_incoming(i, c0, b13); + s.m.set_block(b15); + let b = s.m.phi(f32); + s.m.add_incoming(b, one, b10); + s.m.add_incoming(b, next, b14); + for (k, &v) in pv.iter().enumerate() { + io.store_output(&mut s, opos, 0, k as u8, v); + } + io.store_output(&mut s, oa, 0, 0, a); + io.store_output(&mut s, ob, 0, 0, b); + s.finish_graphics(io, StageInfo::Vertex) +} + + +const DXC_MS_PAYLOAD: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ms_payload.dxil"); +const DXC_PS_OUTPUTS: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ps_outputs.dxil"); +const DXC_VS_CONTROL: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_vs_control.dxil"); + +#[test] +fn ms_payload_parts_match_dxc() { + let c = ms_payload(); + assert_parts_match(&c, DXC_MS_PAYLOAD); + assert_eq!(part(&c, b"SFI0"), part(DXC_MS_PAYLOAD, b"SFI0")); + assert_valid(&c); +} + +#[test] +fn ps_outputs_parts_match_dxc() { + let c = ps_outputs(); + assert_parts_match(&c, DXC_PS_OUTPUTS); + assert_eq!(part(&c, b"SFI0"), part(DXC_PS_OUTPUTS, b"SFI0")); + assert_valid(&c); +} + +#[test] +fn vs_control_dependence_matches_dxc() { + let c = vs_control(); + assert_parts_match(&c, DXC_VS_CONTROL); + assert_valid(&c); +} + +/// A pixel shader reading a per-primitive attribute: `SV_Target = +/// float4(COLOR.rgb, PRIMK)`, discarding pixels left of x = 4. +fn prim_ps() -> Vec { + 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, CompType::F32, 4)); + let col = io.input(SigElement::user("COLOR", 0, CompType::F32, 4)); + let _id = io.input(SigElement::user("ID", 0, CompType::U32, 1)); + let k = io.input(SigElement::user("PRIMK", 0, CompType::U32, 1)); + let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + let x = io.load_input(&mut s, pos, 0, 0); + let four = f(&mut s, 4.0); + let left = s.m.cmp(Pred::FOLt, x, four); + io.discard(&mut s, left); + for c in 0..3 { + let v = io.load_input(&mut s, col, 0, c); + io.store_output(&mut s, tgt, 0, c, v); + } + let kv = io.load_input(&mut s, k, 0, 0); + let f32 = s.m.f32(); + let kf = s.m.cast(CastOp::UIToFP, kv, f32); + io.store_output(&mut s, tgt, 0, 3, kf); + s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }) +} + +/// [`draw_ms`] plus a primitive attribute `PRIMK = 9`. +fn prim_ms() -> Vec { + let mut s = Shader::new(Stage::Mesh, (6, 6)); + let mut io = GraphicsIo::new(Stage::Mesh); + let opos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let ocol = io.output(SigElement::user("COLOR", 0, CompType::F32, 4)); + let oid = io.output(SigElement::user("ID", 0, CompType::U32, 1)); + let ok = io.primitive(SigElement::user("PRIMK", 0, CompType::U32, 1)); + let tid = s.thread_id_in_group(0); + let (zero, one, two, three) = (s.m.i32c(0), s.m.i32c(1), s.m.i32c(2), s.m.i32c(3)); + io.set_mesh_output_counts(&mut s, three, one); + let (m1, big) = (f(&mut s, -1.0), f(&mut s, 1.1)); + let is2 = s.m.cmp(Pred::Eq, tid, two); + let is1 = s.m.cmp(Pred::Eq, tid, one); + let x = s.m.select(is2, big, m1); + let y = s.m.select(is1, big, m1); + let (z, o) = (f(&mut s, 0.0), f(&mut s, 1.0)); + for (c, &v) in [x, y, z, o].iter().enumerate() { + io.store_vertex_output(&mut s, opos, 0, c as u8, v, tid); + } + for (c, &v) in COLOR.iter().enumerate() { + let k = f(&mut s, v); + io.store_vertex_output(&mut s, ocol, 0, c as u8, k, tid); + } + io.store_vertex_output(&mut s, oid, 0, 0, tid, tid); + let first = s.m.cmp(Pred::Eq, tid, zero); + let (bp, end) = (s.m.new_block(), s.m.new_block()); + s.m.cond_br(first, bp, end); + s.m.set_block(bp); + io.emit_indices(&mut s, zero, &[zero, one, two]); + let nine = s.m.i32c(9); + io.store_primitive_output(&mut s, ok, 0, 0, nine, zero); + s.m.br(end); + s.m.set_block(end); + let info = StageInfo::Mesh { numthreads: [3, 1, 1], max_vertices: 3, max_primitives: 1, topology: Topology::Triangle, payload_bytes: 0 }; + s.finish_graphics(io, info) +} + +#[test] +fn emitted_ms_primitive_attribute_reaches_the_pixel_shader() { + use crate::gpu::recomp::runner; + match runner::mesh_shaders_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no mesh shaders"), + Err(e) => return runner::skip_test(&e), + } + let (cs, ms, ps) = (empty_cs(), prim_ms(), prim_ps()); + assert_valid(&ms); + assert_valid(&ps); + let (px, _) = runner::mesh_draw(&cs, &ms, &ps, 1, 4, &[], &[0; 4], SIZE, CLEAR).expect("mesh draw"); + for y in 0..SIZE as usize { + for x in 0..SIZE as usize { + let want = if x <= y && x >= 4 { [COLOR[0], COLOR[1], COLOR[2], 9.0] } else { CLEAR }; + assert_eq!(px[y * SIZE as usize + x], want, "pixel ({x}, {y})"); + } + } +} + +/// `storeOutput` of each (element, column, value), row 0. +fn store_all(io: &mut GraphicsIo, s: &mut Shader, stores: &[(Sig, u8, Value)]) { + for &(sig, c, v) in stores { + io.store_output(s, sig, 0, c, v); + } +} + +/// `tests/data/dxil/dxc_vs_clip.hlsl`: clip and cull distances (two clip elements +/// sharing a row), `SV_ViewportArrayIndex`. +fn vs_clip() -> Vec { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let ip = io.input(SigElement::user("POSITION", 0, CompType::F32, 4)); + let pos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let a = io.output(SigElement::user("A", 0, CompType::F32, 2)); + let clip = io.output(SigElement::new("SV_ClipDistance", 0, SemKind::ClipDistance, CompType::F32, 3)); + let c = io.output(SigElement::user("C", 0, CompType::F32, 1)); + let cull = io.output(SigElement::new("SV_CullDistance", 0, SemKind::CullDistance, CompType::F32, 2)); + let clip1 = io.output(SigElement::new("SV_ClipDistance", 1, SemKind::ClipDistance, CompType::F32, 1)); + let vp = io.output(SigElement::new("SV_ViewportArrayIndex", 0, SemKind::ViewportArrayIndex, CompType::U32, 1)); + let p: Vec = (0..4).map(|i| io.load_input(&mut s, ip, 0, i)).collect(); + let one = s.m.i32c(1); + let st = [ + (pos, 0, p[0]), (pos, 1, p[1]), (pos, 2, p[2]), (pos, 3, p[3]), + (a, 0, p[0]), (a, 1, p[1]), + (clip, 0, p[0]), (clip, 1, p[1]), (clip, 2, p[2]), + (c, 0, p[3]), + (cull, 0, p[2]), (cull, 1, p[3]), + (clip1, 0, p[0]), + (vp, 0, one), + ]; + store_all(&mut io, &mut s, &st); + s.finish_graphics(io, StageInfo::Vertex) +} + +/// `tests/data/dxil/dxc_vs_clip_rows.hlsl`: clip/cull distances never share a +/// row with user semantics. +fn vs_clip_rows() -> Vec { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let ip = io.input(SigElement::user("POSITION", 0, CompType::F32, 4)); + let pos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let a = io.output(SigElement::user("A", 0, CompType::F32, 1)); + let clip = io.output(SigElement::new("SV_ClipDistance", 0, SemKind::ClipDistance, CompType::F32, 1)); + let b = io.output(SigElement::user("B", 0, CompType::F32, 1)); + let cull = io.output(SigElement::new("SV_CullDistance", 0, SemKind::CullDistance, CompType::F32, 1)); + let c = io.output(SigElement::user("C", 0, CompType::F32, 1)); + let d = io.output(SigElement::user("D", 0, CompType::F32, 2)); + let p: Vec = (0..4).map(|i| io.load_input(&mut s, ip, 0, i)).collect(); + let (one, two) = (f(&mut s, 1.0), f(&mut s, 2.0)); + let st = [ + (pos, 0, p[0]), (pos, 1, p[1]), (pos, 2, p[2]), (pos, 3, p[3]), + (a, 0, p[0]), (clip, 0, p[1]), (b, 0, p[2]), (cull, 0, p[3]), (c, 0, one), (d, 0, two), (d, 1, two), + ]; + store_all(&mut io, &mut s, &st); + s.finish_graphics(io, StageInfo::Vertex) +} + +const DXC_VS_CLIP: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_vs_clip.dxil"); +const DXC_VS_CLIP_ROWS: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_vs_clip_rows.dxil"); + +#[test] +fn vs_clip_parts_match_dxc() { + let c = vs_clip(); + assert_parts_match(&c, DXC_VS_CLIP); + assert_eq!(part(&c, b"SFI0"), part(DXC_VS_CLIP, b"SFI0")); + assert_valid(&c); +} + +#[test] +fn vs_clip_rows_parts_match_dxc() { + let c = vs_clip_rows(); + assert_parts_match(&c, DXC_VS_CLIP_ROWS); + assert_valid(&c); +} + +const DXC_PS_EARLY: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ps_early.dxil"); + +/// `tests/data/dxil/dxc_ps_early.hlsl`: `[earlydepthstencil]` (shader flag only). +#[test] +fn ps_early_depth_matches_dxc() { + let mut s = Shader::new(Stage::Pixel, (6, 6)); + let mut io = GraphicsIo::new(Stage::Pixel); + let p = io.input(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let t = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + for c in 0..4 { + let v = io.load_input(&mut s, p, 0, c); + io.store_output(&mut s, t, 0, c, v); + } + let c = s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: true }); + assert_parts_match(&c, DXC_PS_EARLY); + assert_valid(&c); + let dis = validate::disassemble(&c).unwrap(); + assert!(dis.contains("!{i32 0, i64 8}"), "{dis}"); +} + +const DXC_VS_UAV: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_vs_uav.dxil"); + +/// `tests/data/dxil/dxc_vs_uav.hlsl`: a bound UAV in a vertex shader needs the +/// UAVs-at-every-stage flag. +#[test] +fn vs_uav_matches_dxc() { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let mem = s.raw_uav(2, 0); + let vid = io.input(SigElement::new("SV_VertexID", 0, SemKind::VertexId, CompType::U32, 1)); + let pos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let v = io.load_input(&mut s, vid, 0, 0); + let four = s.m.i32c(4); + let off = s.m.bin(BinOp::Shl, v, four); + let k = s.raw_load(mem, off, 0xF); + for (c, &x) in k.iter().enumerate() { + io.store_output(&mut s, pos, 0, c as u8, x); + } + let c = s.finish_graphics(io, StageInfo::Vertex); + assert_parts_match(&c, DXC_VS_UAV); + assert_eq!(part(&c, b"SFI0"), part(DXC_VS_UAV, b"SFI0")); + assert_valid(&c); +} + +/// A pixel shader sampling heap texture 0 with sampler 0 at +/// `uv = SV_Position.xy / 8` (implicit LOD), `w = ddx_fine(uv.x) * 8`. +fn sampling_ps() -> Vec { + use crate::gpu::dxil::ops::{CompType as OpsComp, Deriv, TexKind}; + 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, CompType::F32, 4)); + let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + let zero = s.m.i32c(0); + let tex = s.heap_texture(zero, TexKind::D2, false, OpsComp::F32, 4, false); + let smp = s.heap_sampler(zero, false, false); + let x = io.load_input(&mut s, pos, 0, 0); + let y = io.load_input(&mut s, pos, 0, 1); + let eighth = f(&mut s, 0.125); + let u = s.m.fbin(BinOp::Mul, x, eighth, 0); + let v = s.m.fbin(BinOp::Mul, y, eighth, 0); + let r = s.sample(tex, smp, &[u, v], &[], None); + let du = s.deriv(Deriv::FineX, u); + let eight = f(&mut s, 8.0); + let w = s.m.fbin(BinOp::Mul, du, eight, 0); + for (c, &val) in [r[0], r[1], r[2], w].iter().enumerate() { + io.store_output(&mut s, tgt, 0, c as u8, val); + } + s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }) +} + +/// Full-screen triangle VS: `SV_Position` from `POSITION.xy`. +fn fullscreen_vs() -> Vec { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let pos = io.input(SigElement::user("POSITION", 0, CompType::F32, 2)); + let out = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let x = io.load_input(&mut s, pos, 0, 0); + let y = io.load_input(&mut s, pos, 0, 1); + let (z, o) = (f(&mut s, 0.0), f(&mut s, 1.0)); + for (c, &v) in [x, y, z, o].iter().enumerate() { + io.store_output(&mut s, out, 0, c as u8, v); + } + s.finish_graphics(io, StageInfo::Vertex) +} + +/// Implicit-LOD sampling and fine derivatives in an emitted pixel shader +/// (the `ops` library could only test these in compute shaders). +#[test] +fn emitted_ps_samples_a_texture_with_implicit_lod() { + use crate::gpu::recomp::runner; + use std::mem::transmute_copy; + use windows::Win32::Graphics::Direct3D::*; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + if !draw_ready() { + return; + } + let (vs, ps) = (fullscreen_vs(), sampling_ps()); + assert_valid(&vs); + assert_valid(&ps); + // 4×4 RGBA32F texture: texel (i, j) = (i, j, 10·i + j, 1). + let mut data = Vec::new(); + for j in 0..4 { + for i in 0..4 { + for v in [i as f32, j as f32, (10 * i + j) as f32, 1.0] { + data.extend_from_slice(&v.to_le_bytes()); + } + } + } + let tex = runner::ViewTexture { + res: D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }, + srv: D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }, + }, + data, + row_bytes: 64, + }; + let sampler = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxLOD: f32::MAX, + ..Default::default() + }; + let px = unsafe { + let factory: IDXGIFactory6 = match CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) { + Ok(f) => f, + Err(e) => return runner::skip_test(&format!("{e}")), + }; + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((adapter, _)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else { + return runner::skip_test("no adapter"); + }; + let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).expect("device"); + let rs = crate::gpu::recomp::pso::abi_root_signature(&dev, true).expect("root signature"); + let names = [c"POSITION"]; + let elems = [D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(names[0].as_ptr() as *const u8), + SemanticIndex: 0, + Format: DXGI_FORMAT_R32G32_FLOAT, + InputSlot: 0, + AlignedByteOffset: 0, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + }]; + 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, + InputLayout: D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: 1 }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, 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] = DXGI_FORMAT_R32G32B32A32_FLOAT; + let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).expect("graphics PSO"); + let verts = [-1.0f32, -1.0, -1.0, 3.0, 3.0, -1.0]; + let draw = runner::Draw { sgprs: vec![], scissor: [0, 0, SIZE as i32, SIZE as i32] }; + runner::draw_on_multi(&dev, &pso, &rs, &verts, 8, &[draw], &[0; 4], &[tex], &[sampler], SIZE, CLEAR).expect("draw") + }; + for y in 0..SIZE as usize { + for x in 0..SIZE as usize { + let (i, j) = ((x / 2) as f32, (y / 2) as f32); + assert_eq!(px[y * SIZE as usize + x], [i, j, 10.0 * i + j, 1.0], "pixel ({x}, {y})"); + } + } +} + +#[test] +fn elements_from_dxbc_rows() { + let e = SigElement::from_d3d("TEXCOORD", 3, 0, 3, 0b0110, Some(2)).unwrap(); + assert_eq!((e.kind, e.ty, e.cols, e.place), (SemKind::Arbitrary, CompType::F32, 2, Some((2, 1)))); + let e = SigElement::from_d3d("SV_Position", 0, 1, 3, 0xF, None).unwrap(); + assert_eq!((e.kind, e.cols, e.place), (SemKind::Position, 4, None)); + assert_eq!(SigElement::from_d3d("SV_Target", 1, 64, 1, 0x1, None).unwrap().kind, SemKind::Target); + assert_eq!(SemKind::from_d3d_name(25), Some(SemKind::CullPrimitive)); + assert!(SigElement::from_d3d("X", 0, 999, 3, 1, None).is_none()); +} + +/// `tests/data/dxil/dxc_ps_min16.hlsl` / `dxc_ps_native16.hlsl` (`-enable-16bit-types`): +/// `half2 a : A, uint16_t b : B → half4 SV_Target`. +fn ps_16bit(native: bool) -> Vec { + let mut s = Shader::new(Stage::Pixel, (6, 6)); + if native { + s.require(crate::gpu::dxil::shader::Feature::NativeLowPrecision); + } + let mut io = GraphicsIo::new(Stage::Pixel); + let a = io.input(SigElement::user("A", 0, CompType::F16, 2)); + let b = io.input(SigElement::user("B", 0, CompType::U16, 1)); + let t = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F16, 4)); + let bv = io.load_input(&mut s, b, 0, 0); + let a0 = io.load_input(&mut s, a, 0, 0); + let a1 = io.load_input(&mut s, a, 0, 1); + let h = s.m.f16(); + let bf = s.m.cast(CastOp::UIToFP, bv, h); + let one = s.m.const_float(h, 0x3C00); + for (c, &v) in [a0, a1, bf, one].iter().enumerate() { + io.store_output(&mut s, t, 0, c as u8, v); + } + s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }) +} + +const DXC_PS_MIN16: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ps_min16.dxil"); +const DXC_PS_NATIVE16: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ps_native16.dxil"); + +#[test] +fn ps_16bit_signatures_match_dxc() { + for (native, dxc) in [(false, DXC_PS_MIN16), (true, DXC_PS_NATIVE16)] { + let c = ps_16bit(native); + assert_parts_match(&c, dxc); + assert_eq!(part(&c, b"SFI0"), part(dxc, b"SFI0"), "native {native}"); + assert_valid(&c); + } +} + +/// Groupshared sizes under the native 16-bit layout: DXC reports 18 bytes +/// of PSV0 groupshared memory for `groupshared uint16_t g[6]; groupshared +/// half h[3];` with `-enable-16bit-types` (36 with the 32-bit layout). +#[test] +fn groupshared_bytes_follow_the_16bit_layout() { + let mut s = Shader::new(Stage::Mesh, (6, 6)); + let (i16, f16) = (s.m.int(16), s.m.f16()); + let (a, b) = (s.m.array(6, i16), s.m.array(3, f16)); + s.m.global("g", a, 3, None, false, 2); + s.m.global("h", b, 3, None, false, 2); + assert_eq!(s.m.global_bytes_layout(3, true), 18); + assert_eq!(s.m.global_bytes(3), 36); +} + +const DXC_CS_RESOURCES: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_cs_resources.dxil"); +const DXC_PS_RESOURCES: &[u8] = include_bytes!("../../../../../tests/data/dxil/dxc_ps_resources.dxil"); + +/// `tests/data/dxil/dxc_cs_resources.hlsl`: statically bound SRVs of every buffer +/// kind and a texture (space 1), a cbuffer, a sampler and a comparison +/// sampler, and a raw UAV — `dx.resources` and PSV0 from the shared +/// resource helper on the compute path. +#[test] +fn cs_static_resources_match_dxc() { + use crate::gpu::dxil::ops::{CompType as OpsComp, TexKind}; + let mut s = Shader::new(Stage::Compute, (6, 6)); + let rawb = s.srv_raw(0, 0); + let sb = s.srv_structured(1, 0, 8); + let tb = s.srv_typed(2, 0, OpsComp::F32, 4); + let tex = s.srv_texture(3, 1, TexKind::D2, OpsComp::F32, 4); + let cb = s.cbv(0, 0, 32); + let smp = s.sampler(0, 0, false); + let cmp = s.sampler(1, 0, true); + let res = s.raw_uav(1, 0); + let id = s.flattened_thread_id_in_group(); + let i32 = s.m.i32(); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, id, two); + let a = s.raw_load(rawb, off, 1)[0]; + let b = s.structured_load(sb, id, 0, 3)[1]; + let c = s.buffer_load(tb, id)[0]; + let c = s.m.bitcast(c, i32); + let one = s.m.i32c(1); + let d = s.cbuffer_load_legacy(cb, one, i32)[1]; + let v = s.m.bin(BinOp::Add, a, b); + let v = s.m.bin(BinOp::Add, v, c); + let v = s.m.bin(BinOp::Add, v, d); + let (h, z) = (f(&mut s, 0.5), f(&mut s, 0.0)); + let x = s.sample_level(tex, smp, &[h, h], &[], z)[0]; + let y = s.sample_cmp_level_zero(tex, cmp, &[h, h], &[], h)[0]; + let fs = s.m.fbin(BinOp::Add, x, y, 0); + let fi = s.m.cast(CastOp::BitCast, fs, i32); + let v = s.m.bin(BinOp::Add, v, fi); + s.raw_store(res, off, &[v]); + let c = s.finish([32, 1, 1], None); + assert_valid(&c); + for cc in [b"PSV0", b"SFI0"] { + let (a, b) = (part(&c, cc).unwrap(), part(DXC_CS_RESOURCES, cc).unwrap()); + assert!(a == b, "{} differs\n--- ours\n{}--- dxc\n{}", String::from_utf8_lossy(cc), hex(a), hex(b)); + } + let dis = validate::disassemble(&c).unwrap(); + for needle in [ + "@dx.op.cbufferLoadLegacy.i32(i32 59", + "i32 0, i32 0, i32 1, i32 11, i32 0, null}", + "i32 0, i32 1, i32 1, i32 12, i32 0, !", + "i32 1, i32 3, i32 1, i32 2, i32 0, !", + "i32 0, i32 0, i32 1, i32 32, null}", + "i32 0, i32 1, i32 1, i32 1, null}", + ] { + assert!(dis.contains(needle), "missing `{needle}` in:\n{dis}"); + } +} + +/// `tests/data/dxil/dxc_ps_resources.hlsl`: a root-constant style cbuffer +/// (8 bytes, `b2, space1`), a texture and a sampler on the graphics path. +#[test] +fn ps_static_resources_match_dxc() { + use crate::gpu::dxil::ops::{CompType as OpsComp, TexKind}; + 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, CompType::F32, 4)); + let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + let tex = s.srv_texture(0, 0, TexKind::D2, OpsComp::F32, 4); + let smp = s.sampler(3, 0, false); + let rc = s.cbv(2, 1, 8); + let i32 = s.m.i32(); + let zero = s.m.i32c(0); + let row = s.cbuffer_load_legacy(rc, zero, i32); + let f32 = s.m.f32(); + let scale = s.m.bitcast(row[1], f32); + let k = s.m.cast(CastOp::UIToFP, row[0], f32); + let x = io.load_input(&mut s, pos, 0, 0); + let y = io.load_input(&mut s, pos, 0, 1); + let u = s.m.fbin(BinOp::Mul, x, scale, 0); + let v = s.m.fbin(BinOp::Mul, y, scale, 0); + let r = s.sample(tex, smp, &[u, v], &[], None); + for (c, &val) in r.iter().enumerate() { + let o = s.m.fbin(BinOp::Add, val, k, 0); + io.store_output(&mut s, tgt, 0, c as u8, o); + } + let c = s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }); + assert_parts_match(&c, DXC_PS_RESOURCES); + assert_eq!(part(&c, b"SFI0"), part(DXC_PS_RESOURCES, b"SFI0")); + assert_valid(&c); +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs new file mode 100644 index 000000000..371ac0622 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -0,0 +1,520 @@ +//! Direct translation of an RDNA2 program in the recompiler's kernel ABI +//! (`recomp::runner`): u0 `io` = 128 SGPRs (SCC in slot 125) then 64 lanes × +//! 256 VGPRs; u1 `res` = the same layout after the program (+ exports); +//! u2 `mem` = flat memory. As the HLSL kernel does, the registers the program +//! touches are loaded at entry and stored at the end (SGPRs + SCC by lane 0, +//! VGPRs by every lane); the rest of `res` stays 0. +//! +//! [`translate_compute`] is the recompiler's compute mode (the real CS ABI, +//! `recomp::CsInterface`): user SGPRs from `io`, then the enabled group ids +//! and TG_SIZE; v0..v2 = thread id in the group; results only through memory. + +use std::collections::{BTreeSet, HashMap}; + +use super::cfg::{Cfg, Term}; +use super::container::Stage; +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}; + +#[derive(Debug, Clone, Copy)] +pub struct KernelOptions { + /// wave64 program (64-bit EXEC / VCC) or wave32 + pub wave64: bool, + /// the GPU runs only 32-lane waves: a wave64 program runs as two halves + pub split: bool, + /// 4 GiB memory windows the program may address (`recomp::Options::mem_windows`): + /// `mem` at u2, then `mem1`.. at u3.. + pub mem_windows: u32, + /// first register (space 1) of the static samplers (another stage may come first) + pub sampler_base: u32, +} + +/// 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; + +/// `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. +pub fn enabled() -> bool { + std::env::var("XCL_DIRECT_DXIL").is_ok_and(|v| v == "1" || v == "all") +} + +/// `XCL_DIRECT_DXIL=all`: console vertex and pixel shaders too (each stage falls back to +/// the HLSL path on its own; the signatures are declared as the HLSL entries declare them, +/// so a direct stage links with an HLSL one). +pub fn enabled_graphics() -> bool { + std::env::var("XCL_DIRECT_DXIL").is_ok_and(|v| v == "all") +} + +/// Translates `code` into a signed DXIL compute container, or names the first +/// instruction it cannot translate. +pub fn translate(code: &[u8], o: KernelOptions) -> Result, String> { + translate_full(code, o).map(|k| k.dxil) +} + +/// A translated kernel: the container and the static samplers it samples with +/// (S# built from constants in the code, register `s, space1` — the HLSL +/// kernel's `Translation::static_samplers`). +pub struct Kernel { + pub dxil: Vec, + pub static_samplers: Vec<([u32; 4], bool)>, +} + +pub fn translate_full(code: &[u8], o: KernelOptions) -> Result { + translate_entry(code, o, Entry::Kernel) +} + +/// A mesh-mode (NGG) program: the first pass that writes one record per group into +/// `res` (the recompiler's `Mode::Mesh`; the pass-through mesh shader draws them). +pub fn translate_mesh(code: &[u8], o: KernelOptions, ms: &MsInterface) -> Result { + translate_entry(code, o, Entry::Mesh(ms.clone())) +} + +/// A vertex shader (the recompiler's `Mode::Vertex`; wave-size independent). +pub fn translate_vertex(code: &[u8], o: KernelOptions, vs: &VsInterface) -> Result { + translate_entry(code, o, Entry::Vertex(vs.clone())) +} + +/// A pixel shader (the recompiler's `Mode::Pixel`; wave-size independent). +pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Result { + translate_entry(code, o, Entry::Pixel(ps.clone())) +} + +/// The entry ABI. +#[derive(Clone)] +enum Entry { + Kernel, + Compute(CsInterface), + Mesh(MsInterface), + Vertex(VsInterface), + Pixel(PsInterface), +} + +/// A compute-mode program (the CS ABI of `cs`). +pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result { + translate_entry(code, o, Entry::Compute(cs.clone())) +} + +fn translate_entry(code: &[u8], o: KernelOptions, entry: Entry) -> Result { + // memory windows through the descriptor heap (`recomp::HEAP_WINDOWS` in the count, + // `XCL_HEAP_WINDOWS=1`) are not translated yet: the caller falls back to HLSL + if o.mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0 { + return Err("unsupported: heap memory windows (XCL_HEAP_WINDOWS)".into()); + } + // SSA construction recurses along the CFG (one level per guarded memory access between + // a register's definition and its use): a thread with a large stack for big programs + let code = code.to_vec(); + std::thread::Builder::new() + .name("xcl-dxil-translate".into()) + .stack_size(256 << 20) + .spawn(move || translate_on_this_thread(&code, o, entry)) + .map_err(|e| format!("translator thread: {e}"))? + .join() + .map_err(|e| { + let msg = e.downcast_ref::().cloned().or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default(); + format!("the direct DXIL translator panicked: {msg}") + })? +} + +fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry) -> Result { + let cfg = Cfg::build(code)?; + let split = o.wave64 && o.split; + let kernel = matches!(entry, Entry::Kernel); + let cs = match &entry { + Entry::Compute(cs) => Some(cs.clone()), + _ => None, + }; + let ms = match &entry { + Entry::Mesh(ms) => Some(ms.clone()), + _ => None, + }; + let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); + let split = split && !gfx; + let stage = match &entry { + Entry::Vertex(_) => Stage::Vertex, + Entry::Pixel(_) => Stage::Pixel, + _ => Stage::Compute, + }; + let mut s = Shader::new(stage, (6, 6)); + let io = s.raw_uav(0, 0); + let res = if kernel || ms.is_some() { 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(); + let i32 = s.m.i32(); + let z = s.m.i32c(0); + let mut lw = Lw { + s, + ssa: Ssa::new(i32), + init: Init { io: Some(io), compute: None, vgpr_base: None, entry: Block(0), touched: BTreeSet::new() }, + wave64: o.wave64, + split, + lane: z, + lane31: z, + upper: z, + half: z, + mems, + res, + fmt_table: None, + ntmp: 0, + scratch: None, + static_samplers: Default::default(), + static_used: Vec::new(), + sampler_base: o.sampler_base, + dyn_rm: false, + has_f64_round_op: false, + exec_cache: HashMap::new(), + xs: None, + xw: None, + xc: None, + waves: 1, + cw: z, + xn: z, + xslot: 1, + lds: None, + lds_top: 8191, + dpp_enable: None, + partner: Partner::Present, + mesh: None, + gfx: None, + gfx_half: None, + whole_live: Default::default(), + guard_override: None, + mask_override: None, + exchange_error: None, + pc: 0, + }; + { + let Lw { s, ssa, init, .. } = &mut lw; + ssa.expect_preds(s, Block(0), 0, &mut |s, v| init.load(s, v)); + } + // LDS and the split form's exchange slot size (16 words for a coherent s_load_dwordx16, + // 32 for ds_bpermute), as the HLSL kernel sizes them + let mut uses_lds = false; + let mut slot = 1u32; + for d in &cfg.insts { + let n = d.inst.name; + if d.enc.name == "ENC_DS" && !matches!(n, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "DS_NOP") { + uses_lds = true; + } + if n == "DS_BPERMUTE_B32" { + slot = slot.max(32); + } + if d.enc.name == "ENC_SMEM" && ["GLC", "DLC"].iter().any(|f| crate::gpu::rdna2::field_value(d.enc, &d.words, f) == Some(1)) { + let w = match n.rsplit('_').next().unwrap_or("") { + "DWORDX2" => 2, + "DWORDX4" => 4, + "DWORDX8" => 8, + "DWORDX16" => 16, + _ => 1, + }; + slot = slot.max(w); + } + } + let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + lw.static_samplers = crate::gpu::recomp::constant_samplers(&cfg.insts, &leaders); + let group_threads: Option = match &entry { + Entry::Vertex(_) | Entry::Pixel(_) => None, + Entry::Kernel => None, + Entry::Compute(cs) => Some(cs.threads.iter().product()), + Entry::Mesh(ms) => Some(ms.threads), + }; + if let (Some(t), true) = (group_threads, split) { + lw.waves = t.div_ceil(64).max(1); + } + if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { + lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(&cfg.insts, kernel); + } + lw.setup_storage(uses_lds, if split { slot } else { 1 }); + if let (Some(t), true) = (group_threads, split) { + lw.partner = match t { + 0..=32 => Partner::Missing, + 33..=64 => Partner::Present, + _ => Partner::Spin, + }; + } + let numthreads = match &entry { + Entry::Kernel => { + lw.setup_lanes(); + let lane = lw.lane; + let k = lw.c((KERNEL_VGPRS * 4) as u32); + let b = lw.mul(lane, k); + let base = lw.addc(b, (KERNEL_SGPRS * 4) as u32); + lw.init.vgpr_base = Some(base); + [if o.wave64 { 64 } else { 32 }, 1, 1] + } + Entry::Compute(cs) => { + let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); + compute_init(&mut lw, cs, tid, gtid); + cs.threads + } + Entry::Mesh(ms) => { + let (tid, _) = lw.setup_lanes_compute([ms.threads, 1, 1], uses_lds); + mesh_init(&mut lw, ms, tid, io); + [ms.threads, 1, 1] + } + Entry::Vertex(vs) => { + lw.setup_lanes_gfx(); + let used: BTreeSet = cfg.insts.iter().flat_map(|d| { + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + r.into_iter().chain(w) + }).collect(); + lw.setup_vertex(vs, &used); + [1, 1, 1] + } + Entry::Pixel(ps) => { + lw.setup_lanes_gfx(); + let modes = crate::gpu::recomp::emit::ps_attr_modes(&cfg.insts, ps.input_ena); + lw.setup_pixel(ps, &modes); + [1, 1, 1] + } + }; + // the HLSL kernel loads and stores every register its emitted instructions name: all of + // 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); + for d in cfg.insts.iter().filter(|_| kernel) { + if !branchy && d.inst.name.starts_with("S_ENDPGM") { + break; + } + let (sr, sw) = crate::gpu::rdna2::sgpr_uses(d); + let (vr, vw) = crate::gpu::rdna2::vgpr_uses(d); + for r in sr.into_iter().chain(sw) { + lw.init.touched.insert(r as u32); + } + for r in vr.into_iter().chain(vw).filter(|&r| r < 256) { + lw.init.touched.insert(VAR_VGPR + r as u32); + } + } + + let n = cfg.blocks.len(); + let mut heads: Vec> = vec![None; n]; + let entry = *cfg.rpo.first().ok_or("empty program")?; + let mut head = |lw: &mut Lw, b: usize| -> Block { + if let Some(h) = heads[b] { + return h; + } + let preds = cfg.blocks[b].preds.len() + (b == entry) as usize; + let h = lw.block(Some(preds)); + heads[b] = Some(h); + h + }; + let h0 = head(&mut lw, entry); + lw.edge(Block(0), h0); + let exit = lw.block(None); + for &b in &cfg.rpo { + let h = head(&mut lw, b); + lw.s.m.set_block(h); + 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.s.m.set_block(cont); + let one = lw.c(1); + let l = lw.sub(left, one); + lw.wr(VAR_BUDGET, l); + } + for &i in &cfg.blocks[b].insts { + lw.inst(&cfg.insts[i])?; + } + match cfg.blocks[b].term { + Term::Jump(t) => { + let t = head(&mut lw, t); + lw.br(t); + } + Term::Cond(i, t, f) => { + let c = lw.branch_cond(&cfg.insts[i])?; + let (t, f) = (head(&mut lw, t), head(&mut lw, f)); + lw.cond_br(c, t, f); + } + Term::End => lw.br(exit), + } + } + lw.s.m.set_block(exit); + lw.seal(exit); + // the epilogue uses values of the program's blocks, which were created after `exit`: it goes + // into a block of its own after them (only a phi may refer to a later block's value) + let tail = lw.block(Some(1)); + lw.br(tail); + lw.s.m.set_block(tail); + if let (Some(res), true) = (res, kernel) { + store_registers(&mut lw, res); + } + if gfx { + lw.finish_gfx(); + } + lw.s.m.ret(); + lw.s.m.set_block(Block(0)); + lw.s.m.br(h0); + if let Some(e) = lw.exchange_error.take() { + return Err(e); + } + let hw = if split || !o.wave64 { 32 } else { 64 }; + let c = if gfx { + let g = lw.gfx.take().ok_or("graphics entry without graphics I/O")?; + let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; + lw.s.try_finish_graphics(g.io, info) + } else { + lw.s.try_finish(numthreads, Some(hw)) + } + .map_err(|e| format!("direct DXIL builder error: {e}"))?; + if cfg!(any(test, debug_assertions)) { + if let Err(e) = super::validate::validate(&c) { + let dis = super::validate::disassemble(&c).unwrap_or_else(|d| d); + return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}")); + } + } + Ok(Kernel { dxil: c, static_samplers: lw.static_used.iter().map(|&(w, c, _)| (w, c)).collect() }) +} + +/// The kernel's epilogue: SGPRs and SCC from lane 0, every touched VGPR per lane. +fn store_registers(lw: &mut Lw, res: super::shader::RawUav) { + let touched: Vec = lw.init.touched.iter().copied().collect(); + let mut sg: BTreeSet = touched.iter().copied().filter(|&v| v < VAR_VGPR && v != VAR_SCC).collect(); + sg.extend([106, 107, 124, 126, 127]); + let vg: Vec = touched.iter().copied().filter(|&v| (VAR_VGPR..VAR_BUDGET).contains(&v)).collect(); + let svals: Vec<(u32, Value)> = sg.iter().map(|&r| (r, lw.rd(r))).collect(); + let scc = lw.rd(VAR_SCC); + let vvals: Vec<(u32, Value)> = vg.iter().map(|&r| (r - VAR_VGPR, lw.rd(r))).collect(); + let lane = lw.lane; + let first = lw.cmpc(Pred::Eq, lane, 0); + let _ = lw.guarded(first, &mut |lw| { + for &(r, v) in &svals { + let off = lw.c(r * 4); + lw.s.raw_store(res, off, &[v]); + } + let off = lw.c((KERNEL_SCC_SLOT * 4) as u32); + lw.s.raw_store(res, off, &[scc]); + Ok(()) + }); + let base = lw.init.vgpr_base.expect("vgpr base"); + for (r, v) in vvals { + let k = lw.c(r * 4); + let off = lw.add(base, k); + lw.s.raw_store(res, off, &[v]); + } +} + +/// The compute entry's fixed registers (the HLSL compute mode's prologue): group ids +/// after the user SGPRs, TG_SIZE, SCC = 0, EXEC = the wave's threads, v0..v2 = thread id. +fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { + let mut sgpr = HashMap::new(); + let mut next = cs.user_sgprs; + for k in 0..3 { + if cs.tgid[k] { + let g = lw.s.group_id(k as u32); + sgpr.insert(next, g); + next += 1; + } + } + let lanes: u32 = if lw.wave64 { 64 } else { 32 }; + let total: u32 = cs.threads.iter().product(); + if cs.tg_size { + // (threads / lanes) | (gi / lanes) << 6 + let w = lw.c(total / lanes); + let l = lw.c(lanes); + let i = lw.bin(super::module::BinOp::UDiv, tid, l); + let i = lw.shlc(i, 6); + let v = lw.or(w, i); + sgpr.insert(next, v); + } + let zero = lw.c(0); + sgpr.insert(VAR_SCC, zero); + let (lo, hi) = entry_exec(lw, total, tid); + sgpr.insert(126, lo); + sgpr.insert(127, hi); + let mut vgpr = HashMap::new(); + for (k, &g) in gtid.iter().enumerate() { + if k == 0 || cs.tid_components as usize > k { + vgpr.insert(k as u32, g); + } + } + lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); +} + +/// The mesh entry's registers (the HLSL mesh mode's prologue): SGPRs from `io` with the +/// wave index in s3[27:24], SCC 0, EXEC = the wave's threads, v5 = group · threads + slot, +/// other VGPRs 0; and the record slots. +fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::RawUav) { + let lanes: u32 = if lw.wave64 { 64 } else { 32 }; + let l = lw.c(lanes); + let wave = lw.bin(super::module::BinOp::UDiv, tid, l); + let lane = lw.lane; + let base = lw.mul(wave, l); + let slot = lw.add(base, lane); + let gid = lw.s.group_id(0); + let kr = lw.c(ms.record_dwords() as u32); + let rec = lw.mul(gid, kr); + let kv = lw.c(ms.vert_dwords() as u32); + let sv = lw.mul(slot, kv); + let vtx = lw.addc(rec, MESH_HEADER as u32); + let vtx = lw.add(vtx, sv); + let prm = lw.addc(rec, (MESH_HEADER + ms.max_vertices as usize * ms.vert_dwords()) as u32); + let prm = lw.add(prm, slot); + let zero = lw.c(0); + let mut sgpr = HashMap::new(); + let o3 = lw.c(12); + let s3 = lw.s.raw_load(io, o3, 1)[0]; + let s3 = lw.andc(s3, 0xF0FF_FFFF); + let w24 = lw.shlc(wave, 24); + let s3 = lw.or(s3, w24); + sgpr.insert(3, s3); + sgpr.insert(VAR_SCC, zero); + let (lo, hi) = entry_exec(lw, ms.threads, tid); + sgpr.insert(126, lo); + sgpr.insert(127, hi); + let kt = lw.c(ms.threads); + let g = lw.mul(gid, kt); + let v5 = lw.add(g, slot); + let mut vgpr = HashMap::new(); + vgpr.insert(5, v5); + lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); + lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, outputs: ms.outputs.clone() }); +} + +/// EXEC at entry: the console wave's threads (static per wave in the split form: no +/// exchange); a constant when every wave of the group is full, so vector writes need no +/// lane guard. +fn entry_exec(lw: &mut Lw, total: u32, tid: Value) -> (Value, Value) { + let zero = lw.c(0); + let wave_threads: u32 = if lw.wave64 { 64 } else { 32 }; + let (lo, hi) = if total % wave_threads == 0 { + let all = lw.c(u32::MAX); + (all, if lw.wave64 { all } else { zero }) + } else if lw.split { + let base = lw.andc(tid, !63); + let t = lw.c(total); + let n = lw.sub(t, base); + let k64 = lw.c(64); + let n = lw.umin(n, k64); + let all = lw.c(u32::MAX); + let one = lw.c(1); + let n31 = lw.andc(n, 31); + let part = lw.bin(super::module::BinOp::Shl, one, n31); + let part = lw.sub(part, one); + let ge32 = lw.cmpc(Pred::UGe, n, 32); + let lo = lw.sel(ge32, all, part); + let k32 = lw.c(32); + let nh = lw.sub(n, k32); + let nh31 = lw.andc(nh, 31); + let parth = lw.bin(super::module::BinOp::Shl, one, nh31); + let parth = lw.sub(parth, one); + let ge64 = lw.cmpc(Pred::UGe, n, 64); + let gt32 = lw.cmpc(Pred::UGt, n, 32); + let hi = lw.sel(gt32, parth, zero); + let hi = lw.sel(ge64, all, hi); + (lo, hi) + } else { + let t = lw.s.m.i1c(true); + let w = lw.s.wave_ballot(t); + // HLSL ballot(): (m.x, m.y) — the second word is 0 in a 32-lane wave + (w[0], if lw.wave64 { w[1] } else { zero }) + }; + (lo, hi) +} diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs new file mode 100644 index 000000000..04491ba07 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -0,0 +1,564 @@ +//! Lane masks and cross-lane values. +//! +//! Every lane mask (EXEC, VCC, compare results, carries) is a wave-uniform +//! value built with `WaveActiveBallot`; a lane tests its own bit +//! ([`Lw::lanebit`], cached per block). In the split form (a wave64 console +//! program on a GPU with 32-lane waves only, `docs/wave64-on-wave32.md`) the +//! two hardware halves of the console wave are the whole thread group and +//! meet at a group barrier to exchange one word each: ballot words and +//! `v_readlane` values. Lane reads the ISA keeps inside a 32-lane half (DPP, +//! `ds_swizzle`, permlane) need no exchange. + +use super::lower::{Lw, Partner}; +use super::module::{BinOp, Pred, RmwOp, Value}; +use super::ops::barrier; + +impl Lw { + /// Groupshared storage, created in the entry block before anything else: + /// the program's LDS (`lds_words` > 0) and, in the split form, the halves' + /// exchange words — in the top of the LDS block when there is one (D3D12 + /// allows 32 KB, the whole LDS), as the HLSL kernel lays it out. + pub fn setup_storage(&mut self, lds: bool, slot: u32) { + let i32 = self.s.m.i32(); + self.xslot = slot.max(1); + if lds { + let g = self.s.groupshared("xcl_lds", i32, 8192); + self.lds = Some(g); + if self.split { + // HLSL: exchange base = 8192 - slots - counters - 1 (slots = 4 · slot per console + // wave, 2 counters each); the program's LDS stops below it + let slots = 4 * self.xslot * self.waves; + let base = 8192 - slots - 2 * self.waves - 1; + self.lds_top = base - 1; + self.xs = Some((g, base)); + self.xc = Some((g, base + slots)); + self.xw = Some((g, 8191)); + } else { + self.lds_top = 8191; + } + } else if self.split { + let w = self.s.groupshared("xcl_xw", i32, 1); + self.xw = Some((w, 0)); + if self.waves > 1 { + let x = self.s.groupshared("xcl_xs", i32, (4 * self.xslot * self.waves) as u64); + self.xs = Some((x, 0)); + let c = self.s.groupshared("xcl_xc", i32, 2 * self.waves as u64); + self.xc = Some((c, 0)); + } + } + } + + /// Lane setup at the start of the entry block (after [`Lw::setup_storage`]). + pub fn setup_lanes(&mut self) { + let lane = if self.split { + // each hardware wave takes the next 32 console lanes as it arrives (the PC need + // not form waves from consecutive thread indices): a groupshared counter + let (xw, at) = self.xw.expect("split storage"); + let z = self.c(0); + let ai = self.c(at); + let p = self.s.gs_ptr(xw, ai); + self.s.m.store(p, z, 4); + self.s.barrier(barrier::GROUP_SYNC); + let first = self.s.wave_is_first_lane(); + let k = self.selc(first, 32, z); + let got = self.s.m.atomic_rmw(RmwOp::Add, p, k); + let base = self.s.wave_read_lane_first(got); + let hw = self.s.wave_lane_index(); + self.add(base, hw) + } else if self.wave64 { + self.s.flattened_thread_id_in_group() + } else { + self.s.wave_lane_index() + }; + self.lane = lane; + self.lane31 = self.andc(lane, 31); + self.upper = self.cmpc(Pred::UGe, lane, 32); + self.half = self.lshrc(lane, 5); + } + + /// Compute-mode lane setup (the HLSL compute entry's): the console thread index in the + /// group (`gi` as the program sees it) and the thread id components; also sets the + /// console lane. Split wave64: hardware waves take the next 32 console threads as they + /// arrive (`xcl_x_thread`); 2-D / 3-D groups in native waves: the next `lanes` threads + /// of full waves (`XCL_WT`). + pub fn setup_lanes_compute(&mut self, threads: [u32; 3], lds_top_word: bool) -> (Value, [Value; 3]) { + let [x, y, z] = threads; + let total = x * y * z; + let lanes: u32 = if self.wave64 { 64 } else { 32 }; + let zero = self.c(0); + let tid = if self.split { + let (xw, at) = self.xw.expect("split storage"); + let ai = self.c(at); + let p = self.s.gs_ptr(xw, ai); + self.s.m.store(p, zero, 4); + if let Some((xc, cb)) = self.xc { + // the arrival counters start at 0 (`if (gi < 2 * waves) XCL_XC(gi) = 0`) + let gi = self.s.flattened_thread_id_in_group(); + let last = self.c(2 * self.waves - 1); + let i = self.umin(gi, last); + let i = self.addc(i, cb); + let q = self.s.gs_ptr(xc, i); + self.s.m.store(q, zero, 4); + } + self.s.barrier(barrier::GROUP_SYNC); + let t = self.s.m.i1c(true); + let n = self.s.wave_all_bit_count(t); + let full = self.cmpc(Pred::Eq, n, 32); + let first = self.s.wave_is_first_lane(); + let take = self.land(first, full); + let k = self.selc(take, 32, zero); + let got = self.s.m.atomic_rmw(RmwOp::Add, p, k); + let dflt = self.c(total & !31); + let base = self.sel(take, got, dflt); + let base = self.s.wave_read_lane_first(base); + let t = self.s.m.i1c(true); + let rank = self.s.wave_prefix_bit_count(t); + self.add(base, rank) + } else if y * z > 1 { + let i32 = self.s.m.i32(); + let (g, at) = match (self.lds, lds_top_word) { + (Some(l), true) => (l, 8191), + _ => (self.s.groupshared("xcl_wt", i32, 1), 0), + }; + let ai = self.c(at); + let p = self.s.gs_ptr(g, ai); + self.s.m.store(p, zero, 4); + self.s.barrier(barrier::GROUP_SYNC); + let hw = self.s.wave_lane_index(); + let t = self.s.m.i1c(true); + let n = self.s.wave_all_bit_count(t); + let full = self.cmpc(Pred::Eq, n, lanes); + let first = self.s.wave_is_first_lane(); + let take = self.land(first, full); + let k = self.selc(take, lanes, zero); + let got = self.s.m.atomic_rmw(RmwOp::Add, p, k); + let dflt = self.c(total & !(lanes - 1)); + let base = self.sel(take, got, dflt); + let base = self.s.wave_read_lane_first(base); + let tid = self.add(base, hw); + self.s.barrier(barrier::GROUP_SYNC); + tid + } else { + self.s.flattened_thread_id_in_group() + }; + if self.split { + self.cw = self.lshrc(tid, 6); + // lanes of the partner half: threads > ((tid & ~31) ^ 32) ? min(32, threads - ..) : 0 + let other = self.andc(tid, !31); + let k32 = self.c(32); + let other = self.xor(other, k32); + let t = self.c(total); + let has = self.cmp(Pred::UGt, t, other); + let left = self.sub(t, other); + let n = self.umin(left, k32); + let z = self.c(0); + self.xn = self.sel(has, n, z); + } + let lane = if self.split { + self.andc(tid, 63) + } else { + self.s.wave_lane_index() + }; + self.lane = lane; + self.lane31 = self.andc(lane, 31); + self.upper = self.cmpc(Pred::UGe, lane, 32); + self.half = self.lshrc(lane, 5); + let gtid = if self.split || y * z > 1 { + let kx = self.c(x); + let kxy = self.c(x * y); + let ky = self.c(y); + let gx = self.bin(BinOp::URem, tid, kx); + let q = self.bin(BinOp::UDiv, tid, kx); + let gy = self.bin(BinOp::URem, q, ky); + let gz = self.bin(BinOp::UDiv, tid, kxy); + [gx, gy, gz] + } else { + [self.s.thread_id_in_group(0), self.s.thread_id_in_group(1), self.s.thread_id_in_group(2)] + }; + (tid, gtid) + } + + /// This lane's bit of the mask (lo, hi), cached per block. + pub fn lanebit(&mut self, lo: Value, hi: Value) -> Value { + let key = (self.cur(), lo, hi); + if let Some(&v) = self.exec_cache.get(&key) { + return v; + } + let w = if self.wave64 { + let u = self.upper; + self.sel(u, hi, lo) + } else { + lo + }; + let l = self.lane31; + let sh = self.bin(BinOp::LShr, w, l); + let b = self.andc(sh, 1); + let v = self.nz(b); + self.exec_cache.insert(key, v); + v + } + + /// The bit of lane `l` (uniform or per-lane i32) of the mask (lo, hi). + pub fn lanebit_at(&mut self, lo: Value, hi: Value, l: Value) -> Value { + let w = if self.wave64 { + let up = self.cmpc(Pred::UGe, l, 32); + self.sel(up, hi, lo) + } else { + lo + }; + let l31 = self.andc(l, 31); + let sh = self.bin(BinOp::LShr, w, l31); + let b = self.andc(sh, 1); + self.nz(b) + } + + /// Group barrier for the split form's exchanges. + fn meet(&mut self) { + self.s.barrier(barrier::GROUP_SYNC); + } + + /// Split form: this half gives `vals` (uniform in the half), gets the other half's. + pub fn exchange_n(&mut self, vals: &[Value]) -> Vec { + match self.partner.clone() { + Partner::Present => {} + Partner::Spin => return self.exchange_spin(vals), + Partner::Missing => return vals.iter().map(|_| self.c(0)).collect(), + Partner::Unsupported(why) => { + self.exchange_error.get_or_insert_with(|| format!("pc {:#x}: wave64 exchange: {why}", self.pc)); + return vals.iter().map(|_| self.c(0)).collect(); + } + } + let (xs, base) = self.xs_storage(); + let slot = self.xslot; + assert!(vals.len() as u32 <= slot, "exchange of {} words, slot {slot}", vals.len()); + let h = self.half; + let k = self.c(slot); + let mine = self.mul(h, k); + let mine = self.addc(mine, base); + for (i, &v) in vals.iter().enumerate() { + let at = self.addc(mine, i as u32); + let p = self.s.gs_ptr(xs, at); + self.s.m.store(p, v, 4); + } + self.meet(); + let one = self.c(1); + let o = self.xor(h, one); + let theirs = self.mul(o, k); + let theirs = self.addc(theirs, base); + let mut out = Vec::new(); + for i in 0..vals.len() { + let at = self.addc(theirs, i as u32); + let q = self.s.gs_ptr(xs, at); + out.push(self.s.m.load(q, 4)); + } + self.meet(); + out + } + + /// The spin exchange (several console waves per group): the HLSL `xcl_x_meet` with + /// `XCL_X_SPIN`. Each half stores its words in its slot (double-buffered by the parity + /// of the exchange count), fences, adds its lane count to its arrival counter and waits + /// (one lane, bounded) for the partner's counter; a partner that never arrives marks + /// the wave dead and its exchanges give 0 from then on. + fn exchange_spin(&mut self, vals: &[Value]) -> Vec { + let stores: Vec<(Value, Value)> = vals.iter().enumerate().map(|(i, &v)| (self.c(i as u32), v)).collect(); + let loads: Vec = (0..vals.len()).map(|i| self.c(i as u32)).collect(); + self.spin_exchange(&stores, &loads) + } + + /// The spin exchange with explicit slot offsets: this half stores `(offset, value)` + /// pairs (per lane allowed), then reads the partner's slot at `loads`. + fn spin_exchange(&mut self, stores: &[(Value, Value)], loads: &[Value]) -> Vec { + use super::lower::{VAR_XDEAD, VAR_XK}; + let (xs, base) = self.xs.expect("spin slots"); + let (xc, cbase) = self.xc.expect("spin counters"); + let slot = self.xslot; + let k = self.rd(VAR_XK); + let k1 = self.addc(k, 1); + self.wr(VAR_XK, k1); + let (cw, h, xn) = (self.cw, self.half, self.xn); + let par = self.andc(k, 1); + let at = |lw: &mut Lw, half: Value| -> Value { + let x = lw.shlc(cw, 1); + let x = lw.add(x, half); + let x = lw.shlc(x, 1); + let x = lw.add(x, par); + let ks = lw.c(slot); + let x = lw.mul(x, ks); + lw.addc(x, base) + }; + let mine = at(self, h); + for &(o, v) in stores { + let a = self.add(mine, o); + let p = self.s.gs_ptr(xs, a); + self.s.m.store(p, v, 4); + } + let met = self.tmp_var(); + let z = self.c(0); + self.wr(met, z); + let dead = self.rd(VAR_XDEAD); + let alive = self.cmpc(Pred::Eq, dead, 0); + let has = self.cmpc(Pred::Ne, xn, 0); + let go = self.land(alive, has); + let _ = self.guarded(go, &mut |lw| { + lw.s.barrier(barrier::TGSM_FENCE); + let t = lw.s.m.i1c(true); + let lanes = lw.s.wave_all_bit_count(t); + let ok = lw.tmp_var(); + let one = lw.c(1); + lw.wr(ok, one); + let first = lw.s.wave_is_first_lane(); + let need = lw.mul(k1, xn); + let own = lw.shlc(cw, 1); + let own = lw.add(own, h); + let own = lw.addc(own, cbase); + let one_ = lw.c(1); + let ho = lw.xor(h, one_); + let other = lw.shlc(cw, 1); + let other = lw.add(other, ho); + let other = lw.addc(other, cbase); + lw.guarded(first, &mut |lw| { + lw.s.gs_atomic(super::module::RmwOp::Add, xc, own, lanes); + let pre = lw.cur(); + let lp = lw.block(Some(2)); + let ex = lw.block(Some(1)); + lw.br(lp); + lw.s.m.set_block(lp); + let i32 = lw.s.m.i32(); + let n = lw.s.m.phi(i32); + let z = lw.c(0); + lw.s.m.add_incoming(n, z, pre); + let c = lw.s.gs_atomic(super::module::RmwOp::Add, xc, other, z); + let d = lw.sub(c, need); + let done = lw.cmp(Pred::SGe, d, z); + let n1 = lw.addc(n, 1); + let out = lw.cmpc(Pred::UGe, n1, 1 << 20); + let stop = lw.lor(done, out); + let me = lw.cur(); + lw.s.m.add_incoming(n, n1, me); + lw.cond_br(stop, ex, lp); + lw.s.m.set_block(ex); + let okv = lw.u(done); + lw.wr(ok, okv); + Ok(()) + })?; + let okv = lw.rd(ok); + let okf = lw.s.wave_read_lane_first(okv); + let fail = lw.cmpc(Pred::Eq, okf, 0); + let d0 = lw.rd(VAR_XDEAD); + let d1 = lw.selc(fail, 1, d0); + lw.wr(VAR_XDEAD, d1); + lw.s.barrier(barrier::TGSM_FENCE); + lw.wr(met, okf); + Ok(()) + }); + let one = self.c(1); + let ho = self.xor(h, one); + let theirs = at(self, ho); + let metv = self.rd(met); + let ok = self.nz(metv); + let mut out = Vec::new(); + for &o in loads { + let a = self.add(theirs, o); + let q = self.s.gs_ptr(xs, a); + let v = self.s.m.load(q, 4); + let z = self.c(0); + out.push(self.sel(ok, v, z)); + } + out + } + + /// The exchange words (created on first use when the program has no LDS). + fn xs_storage(&mut self) -> (super::ops::GroupShared, u32) { + if let Some(x) = self.xs { + return x; + } + let i32 = self.s.m.i32(); + let x = self.s.groupshared("xcl_xs", i32, 2 * self.xslot as u64); + self.xs = Some((x, 0)); + (x, 0) + } + + pub fn exchange(&mut self, v: Value) -> Value { + self.exchange_n(&[v])[0] + } + + /// Split form: `v` of any lane `l` of the console wave (`ds_bpermute`): every lane + /// gives its value, 32 words per half. + pub fn read_lane_any(&mut self, v: Value, l: Value) -> Value { + if !self.split { + return self.rla(v, l); + } + if self.partner == Partner::Spin { + let l31 = self.lane31; + let src31 = self.andc(l, 31); + let other = self.spin_exchange(&[(l31, v)], &[src31])[0]; + let own = self.s.wave_read_lane_at(v, src31); + let lh = self.lshrc(l, 5); + let h = self.half; + let same = self.cmp(Pred::Eq, lh, h); + return self.sel(same, own, other); + } + if self.partner != Partner::Present { + // no partner half: only this half's lanes (the others read 0) + let _ = self.exchange_n(&[]); + let src31 = self.andc(l, 31); + let own = self.s.wave_read_lane_at(v, src31); + let lh = self.lshrc(l, 5); + let h = self.half; + let same = self.cmp(Pred::Eq, lh, h); + let z = self.c(0); + return self.sel(same, own, z); + } + let (xs, base) = self.xs_storage(); + let h = self.half; + let mine = self.shlc(h, 5); + let mine = self.addc(mine, base); + let l31 = self.lane31; + let at = self.add(mine, l31); + let p = self.s.gs_ptr(xs, at); + self.s.m.store(p, v, 4); + self.meet(); + let one = self.c(1); + let o = self.xor(h, one); + let theirs = self.shlc(o, 5); + let theirs = self.addc(theirs, base); + let src31 = self.andc(l, 31); + let at = self.add(theirs, src31); + let q = self.s.gs_ptr(xs, at); + let other = self.s.m.load(q, 4); + self.meet(); + let own = self.s.wave_read_lane_at(v, src31); + let lh = self.lshrc(l, 5); + let same = self.cmp(Pred::Eq, lh, h); + self.sel(same, own, other) + } + + /// The program's ballot of `cond` → (lo, hi) mask words. + pub fn ballot(&mut self, cond: Value) -> (Value, Value) { + let w = self.s.wave_ballot(cond); + if !self.wave64 { + let z = self.c(0); + // a wave32 program in 64-lane hardware: each half is its own wave + if let Some(h) = self.gfx_half { + return (self.sel(h, w[1], w[0]), z); + } + return (w[0], z); + } + if !self.split { + return (w[0], w[1]); + } + let m = w[0]; + let o = self.exchange(m); + let u = self.upper; + let lo = self.sel(u, o, m); + let hi = self.sel(u, m, o); + (lo, hi) + } + + /// The hardware lane of console lane `l` (`l + 32 · xcl_half` for a wave32 program in + /// 64-lane hardware). + fn hw_lane(&mut self, l: Value) -> Value { + match self.gfx_half { + Some(h) => { + let k = self.c(32); + let z = self.c(0); + let o = self.sel(h, k, z); + self.add(l, o) + } + None => l, + } + } + + /// `v` of lane `l` (the same index in every lane: v_readlane, v_readfirstlane). + pub fn read_lane_uniform(&mut self, v: Value, l: Value) -> Value { + if !self.split { + return self.rla(v, l); + } + let l31 = self.andc(l, 31); + let m = self.s.wave_read_lane_at(v, l31); + let o = self.exchange(m); + let lh = self.lshrc(l, 5); + let mine = self.cmp(Pred::Eq, lh, self.half); + self.sel(mine, m, o) + } + + /// `v` of lane `l` within the reader's 32-lane half (DPP, swizzle, permlane). + pub fn read_lane_half(&mut self, v: Value, l: Value) -> Value { + if self.split { + let l31 = self.andc(l, 31); + self.s.wave_read_lane_at(v, l31) + } else { + self.rla(v, l) + } + } + + /// The HLSL `rla(v, l)`: `WaveReadLaneAt(v, l + 32 · xcl_half)`; in a pixel shader, lanes + /// of the reader's own quad through quad reads (they see helper lanes, wave reads do + /// not), and a helper lane of another quad through a live lane of that quad. + pub fn rla(&mut self, v: Value, l: Value) -> Value { + let h = self.hw_lane(l); + let w = self.s.wave_read_lane_at(v, h); + if !self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) { + return w; + } + let q: Vec = (0..4u32).map(|k| { + let kk = self.c(k); + self.s.quad_read_lane_at(v, kk) + }).collect(); + let pick = |lw: &mut Lw, r: &[Value]| -> Value { + let b1 = lw.andc(l, 1); + let b1 = lw.nz(b1); + let b2 = lw.andc(l, 2); + let b2 = lw.nz(b2); + let hi = lw.sel(b1, r[3], r[2]); + let lo = lw.sel(b1, r[1], r[0]); + lw.sel(b2, hi, lo) + }; + let qv = pick(self, &q); + let t = self.s.m.i1c(true); + let lv = self.s.wave_ballot(t); + let wi = self.lshrc(h, 5); + let k3 = self.c(3); + let wi = self.umin(wi, k3); + let lvw = { + let mut x = lv[3]; + for k in (0..3).rev() { + let is = self.cmpc(Pred::Eq, wi, k); + x = self.sel(is, lv[k as usize], x); + } + x + }; + let sh = self.andc(h, 28); + let nib = self.bin(BinOp::LShr, lvw, sh); + let nib = self.andc(nib, 15); + let qbase = self.andc(h, !3); + let fl = self.firstbitlow(nib); + let src = self.add(qbase, fl); + let r: Vec = q.iter().map(|&qq| self.s.wave_read_lane_at(qq, src)).collect(); + let rv = pick(self, &r); + let h3 = self.andc(h, 3); + let own = self.bin(BinOp::LShr, nib, h3); + let own = self.andc(own, 1); + let helper = self.cmpc(Pred::Eq, own, 0); + let nnz = self.nz(nib); + let use_r = self.land(nnz, helper); + let w = self.sel(use_r, rv, w); + let lq = self.lshrc(l, 2); + let mq = self.lshrc(self.lane, 2); + let same = self.cmp(Pred::Eq, lq, mq); + self.sel(same, qv, w) + } + + /// First set lane of (lo, hi), 0 when none (the recompiler's `first_lane`). + pub fn first_lane(&mut self, lo: Value, hi: Value) -> Value { + let fl = self.firstbitlow(lo); + let fh = self.firstbitlow(hi); + let fh = self.addc(fh, 32); + let hnz = self.nz(hi); + let z = self.c(0); + let hv = self.sel(hnz, fh, z); + let lnz = self.nz(lo); + self.sel(lnz, fl, hv) + } +} diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs new file mode 100644 index 000000000..b1499d138 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -0,0 +1,1996 @@ +//! RDNA2 instruction → DXIL lowering for the direct compute translator. +//! +//! The model is the recompiler's (`recomp/emit.rs`, the semantic reference +//! for every instruction): each console lane is one thread; SGPRs, SCC, VCC, +//! M0 and EXEC are SSA values every thread of the console wave computes alike; +//! VGPRs are per-thread SSA values whose writes keep the old value in lanes +//! EXEC disables; lane masks come from ballots (`lanes.rs`). Register dwords +//! are SSA variables ([`super::ssa`]): no register arrays, no scratch. +//! +//! Variables: SGPR code `c` (0..=127; slot 125 = SCC, as in the kernel ABI), +//! VGPR `v` = 128 + v, the loop budget = [`VAR_BUDGET`]. + +use std::collections::{BTreeSet, HashMap}; + +use super::module::{BinOp, Block, CastOp, Pred, Value}; +use super::ops::{BitCount, Binary, FClass, FUnary, Tertiary}; +use super::shader::{Feature, RawUav, Shader}; +use super::ssa::Ssa; +use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; + +pub const VAR_SCC: u32 = 125; +pub const VAR_VGPR: u32 = 128; +pub const VAR_BUDGET: u32 = 128 + 256; +/// MODE[3:2] (f16 / f64 rounding) when the program changes it (`Lw::dyn_rm`) +pub const VAR_FP16_RM: u32 = VAR_BUDGET + 1; +/// the memory window the next access uses (`xcl_w`) +pub const VAR_WIN: u32 = VAR_BUDGET + 2; +/// split form, several console waves per group: exchanges so far, and the "partner never +/// arrived" flag (`xcl_xk`, `xcl_x_dead`) +pub const VAR_XK: u32 = VAR_BUDGET + 3; +pub const VAR_XDEAD: u32 = VAR_BUDGET + 4; +/// loop iterations a lane may run (the recompiler's `xcl_budget`) +pub const LOOP_BUDGET: u32 = 1 << 16; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dst { + V(u64), + S(u64), + Null, +} + +/// What the translator could not handle: the instruction and why. +pub type LResult = Result; + +pub(crate) fn err(d: &Decoded, why: &str) -> LResult { + Err(format!("{}: {why}", rdna2::format(d))) +} + +/// Compute-mode initial values (the real CS ABI): fixed SGPRs (group ids, TG_SIZE, +/// SCC, EXEC) and v0..v2 (thread id in the group); other VGPRs start at 0, other SGPRs +/// (user data) come from `io`. +pub struct ComputeInit { + pub sgpr: HashMap, + pub vgpr: HashMap, + pub zero: Value, +} + +/// Mesh (NGG) first pass: where this group's record and this thread's vertex / +/// primitive slots are in `res` (dwords), and the per-vertex outputs. +pub struct MeshCtx { + pub rec: Value, + pub vtx: Value, + pub prm: Value, + pub outputs: Vec, +} + +/// Initial register values: loaded from `io` in the entry block on first use. +pub struct Init { + pub io: Option, + pub compute: Option, + /// byte offset of this lane's VGPRs in `io` + pub vgpr_base: Option, + pub entry: Block, + pub touched: BTreeSet, +} + +impl Init { + pub fn load(&mut self, s: &mut Shader, var: u32) -> Value { + if var == VAR_BUDGET { + return s.m.i32c(LOOP_BUDGET); + } + if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD { + return s.m.i32c(0); + } + if var >= super::lower_mem::VAR_TMP { + return s.m.i32c(0); + } + if let Some(ci) = &self.compute { + if let Some(&v) = ci.sgpr.get(&var) { + return v; + } + if var >= VAR_VGPR { + return ci.vgpr.get(&(var - VAR_VGPR)).copied().unwrap_or(ci.zero); + } + } + let cur = s.m.current_block(); + s.m.set_block(self.entry); + self.touched.insert(var); + let io = self.io.expect("io"); + let v = if var < VAR_VGPR { + let off = s.m.i32c(var * 4); + s.raw_load(io, off, 1)[0] + } else { + let base = self.vgpr_base.expect("vgpr base"); + let k = s.m.i32c((var - VAR_VGPR) * 4); + let off = s.m.bin(BinOp::Add, base, k); + s.raw_load(io, off, 1)[0] + }; + s.m.set_block(cur); + v + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Partner { + Present, + /// several console waves per group: the halves pair up through arrival counters + Spin, + Missing, + Unsupported(&'static str), +} + +#[derive(Default, Clone, Copy)] +pub struct Mods { + pub abs: [bool; 3], + pub neg: [bool; 3], + pub omod: u64, + pub clamp: bool, + pub opsel: u64, +} + +pub struct Lw { + pub s: Shader, + pub ssa: Ssa, + pub init: Init, + pub wave64: bool, + /// wave64 program in two hardware wave32 halves + pub split: bool, + /// console lane (0..63 / 0..31) + pub lane: Value, + pub lane31: Value, + /// lane >= 32 (i1) + pub upper: Value, + /// lane >> 5 + pub half: Value, + /// the memory windows `mem`, `mem1`.. (u2..) + pub mems: Vec, + pub res: Option, + /// the buffer format table (`FMT_INFO`), created on first use + pub fmt_table: Option, + /// temporaries handed out (`lower_mem::VAR_TMP`) + pub ntmp: u32, + /// the lane's scratch array (an alloca in the entry block) + pub scratch: Option, + /// MIMG instructions (pc) whose S# is built from constants in the code: the HLSL + /// kernel binds those as static samplers + pub static_samplers: std::collections::BTreeMap, + /// 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, + 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)>, + pub sampler_base: u32, + pub exec_cache: HashMap<(Block, Value, Value), Value>, + /// groupshared exchange words of the split form + /// split form: the halves' exchange words (storage, first index) and the lane counter + pub xs: Option<(super::ops::GroupShared, u32)>, + pub xw: Option<(super::ops::GroupShared, u32)>, + /// arrival counters of the spin exchange (two per console wave) + pub xc: Option<(super::ops::GroupShared, u32)>, + /// console waves per group, this thread's console wave and its partner half's lanes + pub waves: u32, + pub cw: Value, + pub xn: Value, + /// words per half in an exchange + pub xslot: u32, + /// the program's LDS (`xcl_lds`, 8192 dwords) and its last usable dword + pub lds: Option, + pub lds_top: u32, + /// DPP write enable of the instruction being lowered + pub dpp_enable: Option, + /// the split form's partner half: present, missing (a console wave of at most 32 + /// threads: its masks / lane reads see 0), or the exchange is not supported here + pub partner: Partner, + /// mesh mode: the record slots + pub mesh: Option, + /// VS / PS entry + pub gfx: Option, + /// a wave32 program in 64-lane hardware: this hardware half is the upper one (i1) + pub gfx_half: Option, + /// split form: SGPRs whole-live after each instruction (`recomp::x64_masks::by_pc`) + pub whole_live: std::collections::BTreeMap, + /// set when an exchange was needed where it is not supported + pub exchange_error: Option, + pub pc: u64, + /// Lowering under an externally chosen guard ([`Lw::inst_guarded`]): when set, + /// `act()` (this lane is active: VGPR write selects, guarded memory) returns it + /// instead of this lane's bit of the SSA EXEC. + pub guard_override: Option, + /// When set, the wave-wide mask cross-lane instructions see (DPP source lanes, + /// readfirstlane, ds_swizzle / bpermute) instead of the SSA EXEC. + pub mask_override: Option<(Value, Value)>, +} + +impl Lw { + // ------------------------------------------------------------ SSA access + + pub fn cur(&self) -> Block { + self.s.m.current_block() + } + + pub fn rd(&mut self, var: u32) -> Value { + self.init.touched.insert(var); + let b = self.cur(); + let Lw { s, ssa, init, .. } = self; + ssa.read(s, b, var, &mut |s, v| init.load(s, v)) + } + + pub fn wr(&mut self, var: u32, v: Value) { + self.init.touched.insert(var); + let b = self.cur(); + self.ssa.write(b, var, v); + } + + /// Creates a block (registered with the SSA builder, sealing itself after `preds` edges). + pub fn block(&mut self, preds: Option) -> Block { + let b = self.s.m.new_block(); + if let Some(n) = preds { + let Lw { s, ssa, init, .. } = self; + ssa.expect_preds(s, b, n, &mut |s, v| init.load(s, v)); + } + b + } + + pub fn edge(&mut self, from: Block, to: Block) { + let Lw { s, ssa, init, .. } = self; + ssa.add_pred(s, to, from, &mut |s, v| init.load(s, v)); + } + + pub fn br(&mut self, to: Block) { + let from = self.cur(); + self.s.m.br(to); + self.edge(from, to); + } + + pub fn cond_br(&mut self, c: Value, t: Block, f: Block) { + if t == f { + return self.br(t); + } + let from = self.cur(); + self.s.m.cond_br(c, t, f); + self.edge(from, t); + self.edge(from, f); + } + + pub fn seal(&mut self, b: Block) { + let Lw { s, ssa, init, .. } = self; + ssa.seal(s, b, &mut |s, v| init.load(s, v)); + } + + /// Runs `body` only in lanes where `cond` holds (a real branch: memory + /// accesses of disabled lanes must not happen). Registers `body` writes + /// merge through phis at the join. + pub fn guarded(&mut self, cond: Value, body: &mut dyn FnMut(&mut Lw) -> LResult<()>) -> LResult<()> { + // a condition known at translation time (e.g. EXEC proven all ones): no branch + match self.s.m.const_u64(cond) { + Some(1) => return body(self), + Some(0) => return Ok(()), + _ => {} + } + let from = self.cur(); + let then = self.block(None); + let join = self.block(None); + self.cond_br(cond, then, join); + self.seal(then); + self.s.m.set_block(then); + self.ssa.begin_log(); + let r = body(self); + let written = self.ssa.end_log(); + r?; + let end = self.cur(); + self.br(join); + // only what the body wrote merges at the join; other registers read straight + // through `from` (no walk through both edges of every guard) + self.ssa.seal_region_join(join, from, end, written); + self.s.m.set_block(join); + Ok(()) + } + + // ------------------------------------------------------------ values + + pub fn c(&mut self, v: u32) -> Value { + self.s.m.i32c(v) + } + pub fn b(&mut self, v: bool) -> Value { + self.s.m.i1c(v) + } + /// Integer binop, folded when both operands are constants (and the trivial + /// identities with 0 / 1 / all ones), else emitted. + pub fn bin(&mut self, op: BinOp, a: Value, b: Value) -> Value { + let t = self.s.m.type_of(a); + if let Some(w) = self.s.m.int_width(t) { + let (ca, cb) = (self.s.m.const_u64(a), self.s.m.const_u64(b)); + let mask = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 }; + if let (Some(x), Some(y)) = (ca, cb) { + if let Some(r) = fold_bin(op, x, y, w) { + return self.s.m.const_int(t, r & mask); + } + } + match (op, cb) { + (BinOp::Add | BinOp::Sub | BinOp::Or | BinOp::Xor | BinOp::Shl | BinOp::LShr | BinOp::AShr, Some(0)) => return a, + (BinOp::And, Some(m)) if m == mask => return a, + (BinOp::And | BinOp::Mul, Some(0)) => return b, + (BinOp::Mul, Some(1)) => return a, + _ => {} + } + match (op, ca) { + (BinOp::Add | BinOp::Or | BinOp::Xor, Some(0)) => return b, + (BinOp::And, Some(m)) if m == mask => return b, + (BinOp::And | BinOp::Mul | BinOp::Shl | BinOp::LShr, Some(0)) => return a, + (BinOp::Mul, Some(1)) => return b, + _ => {} + } + } + self.s.m.bin(op, a, b) + } + pub fn add(&mut self, a: Value, b: Value) -> Value { + self.bin(BinOp::Add, a, b) + } + pub fn sub(&mut self, a: Value, b: Value) -> Value { + self.bin(BinOp::Sub, a, b) + } + pub fn mul(&mut self, a: Value, b: Value) -> Value { + self.bin(BinOp::Mul, a, b) + } + pub fn and(&mut self, a: Value, b: Value) -> Value { + self.bin(BinOp::And, a, b) + } + pub fn or(&mut self, a: Value, b: Value) -> Value { + self.bin(BinOp::Or, a, b) + } + pub fn xor(&mut self, a: Value, b: Value) -> Value { + self.bin(BinOp::Xor, a, b) + } + pub fn not(&mut self, a: Value) -> Value { + let t = self.s.m.type_of(a); + let m = self.s.m.const_int(t, u64::MAX); + self.xor(a, m) + } + pub fn andc(&mut self, a: Value, k: u32) -> Value { + let k = self.c(k); + self.and(a, k) + } + pub fn addc(&mut self, a: Value, k: u32) -> Value { + let k = self.c(k); + self.add(a, k) + } + /// `a << (b & 31)` etc. (HLSL masks shift counts) + pub fn shl(&mut self, a: Value, b: Value) -> Value { + let b = self.mask_shift(a, b); + self.bin(BinOp::Shl, a, b) + } + pub fn lshr(&mut self, a: Value, b: Value) -> Value { + let b = self.mask_shift(a, b); + self.bin(BinOp::LShr, a, b) + } + pub fn ashr(&mut self, a: Value, b: Value) -> Value { + let b = self.mask_shift(a, b); + self.bin(BinOp::AShr, a, b) + } + fn mask_shift(&mut self, a: Value, b: Value) -> Value { + let t = self.s.m.type_of(a); + let w = self.s.m.int_width(t).unwrap_or(32); + let k = self.s.m.const_int(t, (w - 1) as u64); + self.bin(BinOp::And, b, k) + } + pub fn shlc(&mut self, a: Value, k: u32) -> Value { + let k = self.c(k); + self.bin(BinOp::Shl, a, k) + } + pub fn lshrc(&mut self, a: Value, k: u32) -> Value { + let k = self.c(k); + self.bin(BinOp::LShr, a, k) + } + pub fn ashrc(&mut self, a: Value, k: u32) -> Value { + let k = self.c(k); + self.bin(BinOp::AShr, a, k) + } + pub fn cmp(&mut self, p: Pred, a: Value, b: Value) -> Value { + let t = self.s.m.type_of(a); + if let (Some(w), Some(x), Some(y)) = (self.s.m.int_width(t), self.s.m.const_u64(a), self.s.m.const_u64(b)) { + let sx = |v: u64| if w >= 64 { v as i64 } else { ((v << (64 - w)) as i64) >> (64 - w) }; + let r = match p { + Pred::Eq => Some(x == y), + Pred::Ne => Some(x != y), + Pred::UGt => Some(x > y), + Pred::UGe => Some(x >= y), + Pred::ULt => Some(x < y), + Pred::ULe => Some(x <= y), + Pred::SGt => Some(sx(x) > sx(y)), + Pred::SGe => Some(sx(x) >= sx(y)), + Pred::SLt => Some(sx(x) < sx(y)), + Pred::SLe => Some(sx(x) <= sx(y)), + _ => None, + }; + if let Some(r) = r { + return self.s.m.i1c(r); + } + } + self.s.m.cmp(p, a, b) + } + pub fn cmpc(&mut self, p: Pred, a: Value, k: u32) -> Value { + let k = self.c(k); + self.cmp(p, a, k) + } + pub fn sel(&mut self, c: Value, t: Value, f: Value) -> Value { + if t == f { + return t; + } + match self.s.m.const_u64(c) { + Some(1) => t, + Some(0) => f, + _ => self.s.m.select(c, t, f), + } + } + pub fn selc(&mut self, c: Value, t: u32, f: Value) -> Value { + let t = self.c(t); + self.sel(c, t, f) + } + /// i1 → i32 0 / 1 + pub fn u(&mut self, c: Value) -> Value { + let i32 = self.s.m.i32(); + self.s.m.cast(CastOp::ZExt, c, i32) + } + /// i32 != 0 + pub fn nz(&mut self, a: Value) -> Value { + let t = self.s.m.type_of(a); + let z = self.s.m.const_int(t, 0); + self.cmp(Pred::Ne, a, z) + } + pub fn lnot(&mut self, c: Value) -> Value { + let t = self.b(true); + self.xor(c, t) + } + pub fn land(&mut self, a: Value, b: Value) -> Value { + self.and(a, b) + } + pub fn lor(&mut self, a: Value, b: Value) -> Value { + self.or(a, b) + } + pub fn i64(&mut self) -> super::module::Ty { + self.s.require(Feature::Int64Ops); + self.s.m.i64() + } + pub fn zext64(&mut self, a: Value) -> Value { + let t = self.i64(); + self.s.m.cast(CastOp::ZExt, a, t) + } + pub fn sext64(&mut self, a: Value) -> Value { + let t = self.i64(); + self.s.m.cast(CastOp::SExt, a, t) + } + pub fn trunc32(&mut self, a: Value) -> Value { + let t = self.s.m.i32(); + self.s.m.cast(CastOp::Trunc, a, t) + } + pub fn c64(&mut self, v: u64) -> Value { + let t = self.i64(); + self.s.m.const_int(t, v) + } + /// (lo, hi) → i64 + pub fn pack64(&mut self, lo: Value, hi: Value) -> Value { + let l = self.zext64(lo); + let h = self.zext64(hi); + let k = self.c64(32); + let h = self.bin(BinOp::Shl, h, k); + self.or(l, h) + } + /// i64 → (lo, hi) + pub fn unpack64(&mut self, v: Value) -> (Value, Value) { + let lo = self.trunc32(v); + let k = self.c64(32); + let h = self.bin(BinOp::LShr, v, k); + let hi = self.trunc32(h); + (lo, hi) + } + pub fn f(&mut self, a: Value) -> Value { + let t = self.s.m.f32(); + self.s.m.bitcast(a, t) + } + pub fn bits(&mut self, a: Value) -> Value { + let t = self.s.m.type_of(a); + if t == self.s.m.f64() { + panic!("bits of a double"); + } + let i = self.s.m.i32(); + self.s.m.bitcast(a, i) + } + pub fn fc(&mut self, x: f32) -> Value { + self.s.m.f32c(x.to_bits()) + } + pub fn fbin(&mut self, op: BinOp, a: Value, b: Value) -> Value { + self.s.m.fbin(op, a, b, 0) + } + pub fn fadd(&mut self, a: Value, b: Value) -> Value { + self.fbin(BinOp::Add, a, b) + } + pub fn fsub(&mut self, a: Value, b: Value) -> Value { + self.fbin(BinOp::Sub, a, b) + } + pub fn fmul(&mut self, a: Value, b: Value) -> Value { + self.fbin(BinOp::Mul, a, b) + } + /// `fdiv` (bitcode BINOP_SDIV on floats; BINOP_UDIV is invalid there) + pub fn fdiv(&mut self, a: Value, b: Value) -> Value { + self.fbin(BinOp::SDiv, a, b) + } + /// HLSL `-x` (`fsub -0.0, x`) + pub fn fneg(&mut self, a: Value) -> Value { + let t = self.s.m.type_of(a); + let bits = if t == self.s.m.f64() { 1u64 << 63 } else if t == self.s.m.f16() { 0x8000 } else { 0x8000_0000 }; + let z = self.s.m.const_float(t, bits); + self.fsub(z, a) + } + pub fn fabs(&mut self, a: Value) -> Value { + self.s.funary(FUnary::FAbs, a) + } + pub fn un(&mut self, opc: FUnary, a: Value) -> Value { + self.s.funary(opc, a) + } + pub fn fmin(&mut self, a: Value, b: Value) -> Value { + self.s.binary(Binary::FMin, a, b) + } + pub fn fmax(&mut self, a: Value, b: Value) -> Value { + self.s.binary(Binary::FMax, a, b) + } + pub fn umin(&mut self, a: Value, b: Value) -> Value { + self.s.binary(Binary::UMin, a, b) + } + pub fn umax(&mut self, a: Value, b: Value) -> Value { + self.s.binary(Binary::UMax, a, b) + } + pub fn imin(&mut self, a: Value, b: Value) -> Value { + self.s.binary(Binary::IMin, a, b) + } + pub fn imax(&mut self, a: Value, b: Value) -> Value { + self.s.binary(Binary::IMax, a, b) + } + pub fn fmad(&mut self, a: Value, b: Value, c: Value) -> Value { + self.s.tertiary(Tertiary::FMad, a, b, c) + } + pub fn isnan(&mut self, a: Value) -> Value { + self.s.fclass(FClass::IsNaN, a) + } + pub fn isinf(&mut self, a: Value) -> Value { + self.s.fclass(FClass::IsInf, a) + } + pub fn fcmp(&mut self, p: Pred, a: Value, b: Value) -> Value { + self.s.m.cmp(p, a, b) + } + pub fn countbits(&mut self, a: Value) -> Value { + self.s.bit_count(BitCount::Countbits, a) + } + /// HLSL `firstbitlow` (−1 for 0) + pub fn firstbitlow(&mut self, a: Value) -> Value { + self.s.bit_count(BitCount::FirstbitLo, a) + } + /// leading zeros from bit 31 (−1 for 0): DXIL `FirstbitHi` + pub fn lzcnt(&mut self, a: Value) -> Value { + self.s.bit_count(BitCount::FirstbitHi, a) + } + /// HLSL `firstbithigh(uint)`: bit index from bit 0 (−1 for 0) + pub fn firstbithigh(&mut self, a: Value) -> Value { + let r = self.lzcnt(a); + let k = self.c(31); + let s = self.sub(k, r); + let none = self.cmpc(Pred::Eq, r, u32::MAX); + self.selc(none, u32::MAX, s) + } + pub fn reversebits(&mut self, a: Value) -> Value { + self.s.bfrev(a) + } + pub fn uitof(&mut self, a: Value) -> Value { + let t = self.s.m.f32(); + self.s.m.cast(CastOp::UIToFP, a, t) + } + pub fn sitof(&mut self, a: Value) -> Value { + let t = self.s.m.f32(); + self.s.m.cast(CastOp::SIToFP, a, t) + } + pub fn ftoui(&mut self, a: Value) -> Value { + let t = self.s.m.i32(); + self.s.m.cast(CastOp::FPToUI, a, t) + } + pub fn ftosi(&mut self, a: Value) -> Value { + let t = self.s.m.i32(); + self.s.m.cast(CastOp::FPToSI, a, t) + } + + // ------------------------------------------------------------ registers + + pub fn sreg(&mut self, code: u64) -> Value { + match code { + 0..=124 | 126 | 127 => self.rd(code as u32), + _ => self.c(0), + } + } + pub fn vreg(&mut self, n: u64) -> Value { + self.rd(VAR_VGPR + n as u32) + } + pub fn scc(&mut self) -> Value { + self.rd(VAR_SCC) + } + pub fn set_scc(&mut self, c: Value) { + let v = self.u(c); + self.wr(VAR_SCC, v); + } + pub fn scc_bit(&mut self) -> Value { + let s = self.scc(); + self.nz(s) + } + + /// 32-bit value of a scalar source code (0..255) or VALU source (256+ = VGPR). + pub fn code32(&mut self, code: u64, lit: Option, f16: bool) -> Option { + Some(match code { + 0..=124 | 126 | 127 => self.sreg(code), + 125 => self.c(0), + 128..=192 => self.c((code - 128) as u32), + 193..=208 => self.c((-((code - 192) as i64)) as u32), + 240..=248 => { + let v = if f16 { f16_const(code)? } else { f32_const(code)?.to_bits() }; + self.c(v) + } + 251 | 252 => { + let (l, h) = if code == 251 { (106, 107) } else { (126, 127) }; + // wave32: the high half (vcc_hi / exec_hi) is not part of the mask + let o = if self.wave64 { + let (l, h) = (self.sreg(l), self.sreg(h)); + self.or(l, h) + } else { + self.sreg(l) + }; + let z = self.cmpc(Pred::Eq, o, 0); + self.u(z) + } + 253 => self.scc(), + 255 => self.c(lit?), + 256..=511 => self.vreg(code - 256), + 235..=238 => self.c(0), + 239 => self.c(0x7FFF_FFFF), + _ => return None, + }) + } + + /// 64-bit value (lo, hi) of a scalar source code. + pub fn code64(&mut self, code: u64, lit: Option, f64: bool) -> Option<(Value, Value)> { + Some(match code { + 0..=123 | 126 => (self.sreg(code), self.sreg(code + 1)), + 125 => (self.c(0), self.c(0)), + 128..=192 => (self.c((code - 128) as u32), self.c(0)), + 193..=208 => (self.c((-((code - 192) as i64)) as u32), self.c(u32::MAX)), + 248 => (self.c(0x6DC9_C882), self.c(0x3FC4_5F30)), + 240..=247 => { + let b = (f32_const(code)? as f64).to_bits(); + (self.c(b as u32), self.c((b >> 32) as u32)) + } + // src_vccz / src_execz / scc: a 0 / 1 value, zero-extended + 251 | 252 | 253 => (self.code32(code, None, false)?, self.c(0)), + 255 => { + if f64 { + (self.c(0), self.c(lit?)) + } else { + (self.c(lit?), self.c(0)) + } + } + 256..=510 => (self.vreg(code - 256), self.vreg(code - 255)), + _ => return None, + }) + } + + pub fn field(d: &Decoded, f: &str) -> u64 { + rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f) + } + pub fn fv(d: &Decoded, f: &str) -> u64 { + rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) + } + + pub fn read(&mut self, d: &Decoded, o: &Operand, f16: bool) -> Option { + match o.field { + Some("LITERAL") => Some(self.c(d.literal?)), + Some(f) => { + let v = Self::field(d, f); + let width = d.enc.field_width(f); + if o.ty.starts_with("OPR_VGPR") && width <= 8 { + return Some(self.vreg(v)); + } + match o.ty { + "OPR_SIMM16" => Some(self.c(v as u32)), + "OPR_SIMM32" => Some(self.c(d.literal?)), + _ => self.code32(v, d.literal, f16), + } + } + None => match o.ty { + "OPR_VCC" => Some(self.sreg(106)), + "OPR_EXEC" | "OPR_SDST_EXEC" => Some(self.sreg(126)), + "OPR_SDST_M0" => Some(self.sreg(124)), + "OPR_SSRC_SPECIAL_SCC" => Some(self.scc()), + _ => None, + }, + } + } + + pub fn read64(&mut self, d: &Decoded, o: &Operand, f64: bool) -> Option<(Value, Value)> { + match o.field { + Some(f) => { + let v = Self::field(d, f); + if o.ty.starts_with("OPR_VGPR") && d.enc.field_width(f) <= 8 { + return Some((self.vreg(v), self.vreg(v + 1))); + } + self.code64(v, d.literal, f64) + } + None => match o.ty { + "OPR_VCC" => Some((self.sreg(106), self.sreg(107))), + "OPR_EXEC" | "OPR_SDST_EXEC" => Some((self.sreg(126), self.sreg(127))), + _ => None, + }, + } + } + + pub fn dst_of(d: &Decoded, o: &Operand) -> Dst { + match o.field { + Some(f) => { + let v = Self::field(d, f); + match o.ty { + "OPR_EXEC" => Dst::S(126), + "OPR_VCC" => Dst::S(106), + t if t.starts_with("OPR_VGPR") => Dst::V(v), + _ if v == 125 => Dst::Null, + _ if v > 127 => Dst::Null, + _ => Dst::S(v), + } + } + None => match o.ty { + "OPR_VCC" => Dst::S(106), + "OPR_EXEC" => Dst::S(126), + _ => Dst::Null, + }, + } + } + + /// Explicit operands: (outputs, inputs) in spec order. + pub fn ops(d: &Decoded) -> (Vec<&'static Operand>, Vec<&'static Operand>) { + let mut outs = Vec::new(); + let mut ins = Vec::new(); + for o in d.ienc.operands { + if o.implicit && !(o.field.is_none() && o.ty == "OPR_VCC") { + continue; + } + if o.output { + outs.push(o); + } else if o.input { + ins.push(o); + } + } + (outs, ins) + } + + /// This lane's EXEC bit. + pub fn act(&mut self) -> Value { + if let Some(g) = self.guard_override { + return g; + } + let lo = self.sreg(126); + let hi = if self.wave64 { self.sreg(127) } else { self.c(0) }; + self.lanebit(lo, hi) + } + + /// The wave-wide active mask (lo, hi) cross-lane instructions consult: the + /// override if set, else the SSA EXEC (hi = 0 in wave32). + pub fn exec_mask(&mut self) -> (Value, Value) { + if let Some(m) = self.mask_override { + return m; + } + let lo = self.sreg(126); + let hi = if self.wave64 { self.sreg(127) } else { self.c(0) }; + (lo, hi) + } + + /// Lowers one instruction under a guard chosen by the caller instead of the + /// SSA EXEC: `guard` (i1) decides whether this lane's VGPR writes and memory + /// effects happen (a constant `true` folds every select / branch away); + /// `mask`, if given, is the wave-wide mask cross-lane instructions see (e.g. a + /// ballot of the guard), else they read the SSA EXEC. Instructions that write + /// EXEC still update the SSA EXEC registers (126/127); EXEC read as a plain + /// scalar operand (`s_mov s0, exec`) reads them too. Control flow (branches) + /// is the caller's business: use this for non-branch instructions. + pub fn inst_guarded(&mut self, d: &Decoded, guard: Value, mask: Option<(Value, Value)>) -> LResult<()> { + let (g, m) = (self.guard_override.replace(guard), std::mem::replace(&mut self.mask_override, mask)); + let r = self.inst(d); + self.guard_override = g; + self.mask_override = m; + r + } + + pub fn write32(&mut self, dst: &Dst, val: Value) { + match *dst { + Dst::V(n) => { + let old = self.vreg(n); + let a = self.act(); + let v = self.sel(a, val, old); + self.wr(VAR_VGPR + n as u32, v); + } + Dst::S(n) => { + if n <= 127 && n != 125 { + self.wr(n as u32, val); + } + } + Dst::Null => {} + } + } + + pub fn write64(&mut self, dst: &Dst, lo: Value, hi: Value) { + match *dst { + Dst::V(n) => { + let a = self.act(); + let (o0, o1) = (self.vreg(n), self.vreg(n + 1)); + let v0 = self.sel(a, lo, o0); + let v1 = self.sel(a, hi, o1); + self.wr(VAR_VGPR + n as u32, v0); + self.wr(VAR_VGPR + n as u32 + 1, v1); + } + Dst::S(n) => { + if n != 125 { + self.wr(n as u32, lo); + } + if n + 1 <= 127 && n + 1 != 125 { + self.wr(n as u32 + 1, hi); + } + } + Dst::Null => {} + } + } + + /// Lane mask from a per-lane condition (inactive lanes give 0) into a register (pair). + pub fn write_mask(&mut self, dst: &Dst, cond: Value) { + let a = self.act(); + let c = self.land(a, cond); + // split form: a mask only ever read lane by lane (or going nowhere, or 0 anyway) + // needs only this half's word (`recomp::x64_masks`, the HLSL `xcl_x_ballot_local`) + let local = self.split + && (self.s.m.const_u64(cond) == Some(0) + || match *dst { + Dst::S(n) => n < 126 && self.whole_live.get(&self.pc).is_some_and(|live| live & (3u128 << n) == 0), + Dst::Null => true, + Dst::V(_) => false, + }); + let (lo, hi) = if local { + let w = self.s.wave_ballot(c)[0]; + let z = self.c(0); + let u = self.upper; + (self.sel(u, z, w), self.sel(u, w, z)) + } else { + self.ballot(c) + }; + if self.wave64 { + self.write64(dst, lo, hi); + } else { + self.write32(dst, lo); + } + } + + /// This lane's bit of a mask (lo, hi). + pub fn lane_of(&mut self, lo: Value, hi: Value) -> Value { + if self.wave64 { + self.lanebit(lo, hi) + } else { + let z = self.c(0); + self.lanebit(lo, z) + } + } + + // ------------------------------------------------------------ dispatch + + pub fn inst(&mut self, d: &Decoded) -> LResult<()> { + let name = d.inst.name.to_ascii_lowercase(); + self.pc = d.pc; + self.dpp_enable = None; + if name == "s_sendmsg" && self.mesh.is_some() { + return self.mesh_sendmsg(d); + } + if NOOPS.contains(&name.as_str()) { + return Ok(()); + } + match d.enc.name { + "ENC_SOPP" => self.sopp(d, &name), + "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => self.salu(d, &name), + "ENC_SMEM" => self.smem(d, &name), + "ENC_MUBUF" | "ENC_MTBUF" => self.mubuf(d, &name), + "ENC_EXP" => self.export(d), + "ENC_DS" => self.ds(d, &name), + "ENC_VINTRP" => self.interp_gfx(d, &name), + "ENC_MIMG" => self.mimg(d, &name), + "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => self.flat(d, &name), + e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => self.valu(d, &name), + _ => err(d, "encoding"), + } + } + + /// The condition of a conditional branch (i1). + pub fn branch_cond(&mut self, d: &Decoded) -> LResult { + let name = d.inst.name.to_ascii_lowercase(); + let zero = |s: &mut Self, l: u64| { + let lo = s.sreg(l); + let v = if s.wave64 { + let hi = s.sreg(l + 1); + s.or(lo, hi) + } else { + lo + }; + s.cmpc(Pred::Eq, v, 0) + }; + Ok(match name.as_str() { + "s_cbranch_scc0" => { + let s = self.scc(); + self.cmpc(Pred::Eq, s, 0) + } + "s_cbranch_scc1" => { + let s = self.scc(); + self.cmpc(Pred::Ne, s, 0) + } + "s_cbranch_vccz" => zero(self, 106), + "s_cbranch_vccnz" => { + let z = zero(self, 106); + self.lnot(z) + } + "s_cbranch_execz" => zero(self, 126), + "s_cbranch_execnz" => { + let z = zero(self, 126); + self.lnot(z) + } + _ => return err(d, "conditional branch"), + }) + } + + fn sopp(&mut self, d: &Decoded, name: &str) -> LResult<()> { + match name { + "s_barrier" => { + self.s.barrier(super::ops::barrier::GROUP_SYNC); + Ok(()) + } + "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 { + return err(d, "non-default f32 round mode"); + } + if dp != 0 && self.has_f64_round_op { + return err(d, "non-default f64 round mode"); + } + if self.dyn_rm { + let v = self.c(dp); + self.wr(VAR_FP16_RM, v); + } + Ok(()) + } + _ if NOOPS.contains(&name) => Ok(()), + _ => err(d, "SOPP"), + } + } + + // ------------------------------------------------------------ scalar ALU + + 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 sp_mask == 0 && dp_mask == 0 { + return Ok(()); + } + if name == "s_setreg_imm32_b32" { + 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 { + return err(d, "non-default f32 round mode"); + } + if dp_mask != 0 && dp != 0 && self.has_f64_round_op { + return err(d, "non-default f64 round mode"); + } + if dp_mask != 0 && self.dyn_rm { + let v = if dp_mask == 3 { + self.c(dp) + } else { + let cur = self.rd(VAR_FP16_RM); + let keep = self.andc(cur, !dp_mask & 3); + self.orc(keep, dp) + }; + self.wr(VAR_FP16_RM, v); + } + return Ok(()); + } + if sp_mask != 0 { + return err(d, "dynamic f32 round mode"); + } + if self.has_f64_round_op { + return err(d, "dynamic f64 round mode"); + } + if self.dyn_rm { + let sd = Self::field(d, "SDST"); + let src = self.code32(sd, None, false).ok_or_else(|| format!("{}: register", rdna2::format(d)))?; + let sh = 2 - off; + let v = match dp_mask { + 3 => { + let x = self.lshrc(src, sh); + self.andc(x, 3) + } + 1 => { + let x = self.lshrc(src, sh); + let bit = self.andc(x, 1); + let cur = self.rd(VAR_FP16_RM); + let keep = self.andc(cur, 2); + self.or(keep, bit) + } + _ => { + let bit = self.andc(src, 1); + let bit = self.shlc(bit, 1); + let cur = self.rd(VAR_FP16_RM); + let keep = self.andc(cur, 1); + self.or(keep, bit) + } + }; + self.wr(VAR_FP16_RM, v); + } + Ok(()) + } + + fn salu(&mut self, d: &Decoded, name: &str) -> LResult<()> { + if matches!(name, "s_setreg_imm32_b32" | "s_setreg_b32") { + return self.setreg(d, name); + } + if matches!(name, "s_getreg_b32") { + return err(d, "s_getreg"); + } + if matches!(name, "s_movrels_b32" | "s_movrels_b64" | "s_movreld_b32" | "s_movreld_b64" | "s_movrelsd_2_b32") { + return self.smovrel(d, name); + } + let (outs, ins) = Self::ops(d); + let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64"); + let dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + let simm = Self::fv(d, "SIMM16") as u16; + let base = name.trim_end_matches("_b32").trim_end_matches("_b64"); + if d.enc.name == "ENC_SOPK" { + let k_s = simm as i16 as i32 as u32; + let k_u = simm as u32; + let sd = Self::field(d, "SDST"); + let cur = self.code32(sd, None, false).ok_or("register").or_else(|e| err(d, e))?; + let dst = Dst::S(sd); + let ks = self.c(k_s); + match name { + "s_movk_i32" => self.write32(&dst, ks), + "s_cmovk_i32" => { + let c = self.scc_bit(); + let v = self.sel(c, ks, cur); + self.write32(&dst, v) + } + "s_addk_i32" => { + let t = self.add(cur, ks); + let a = self.xor(cur, t); + let b = self.xor(ks, t); + let x = self.and(a, b); + let x = self.lshrc(x, 31); + self.wr(VAR_SCC, x); + self.write32(&dst, t); + } + "s_mulk_i32" => { + let v = self.mul(cur, ks); + self.write32(&dst, v) + } + "s_version" | "s_waitcnt_vscnt" | "s_waitcnt_vmcnt" | "s_waitcnt_expcnt" | "s_waitcnt_lgkmcnt" => {} + _ if name.starts_with("s_cmpk_") => { + let (op, signed) = cmp_op(&name[7..]).ok_or("comparison").or_else(|e| err(d, e))?; + let k = if signed { ks } else { self.c(k_u) }; + let c = self.cmp(int_pred(op, signed), cur, k); + self.set_scc(c); + } + _ => return err(d, "SOPK"), + } + return Ok(()); + } + if d.enc.name == "ENC_SOPC" { + if matches!(name, "s_bitcmp0_b64" | "s_bitcmp1_b64") { + let (a0, a1) = self.read64(d, ins[0], false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + let b = self.read(d, ins[1], false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + let b32 = self.andc(b, 32); + let lowhalf = self.cmpc(Pred::Eq, b32, 0); + let w = self.sel(lowhalf, a0, a1); + let sh = self.lshr(w, b); + let bit = self.andc(sh, 1); + if name == "s_bitcmp0_b64" { + let c = self.cmpc(Pred::Eq, bit, 0); + self.set_scc(c); + } else { + self.wr(VAR_SCC, bit); + } + return Ok(()); + } + if name.ends_with("_u64") { + let a = self.read64(d, ins[0], false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + let b = self.read64(d, ins[1], false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + let (p, eq) = match name { + "s_cmp_eq_u64" => (Pred::Eq, true), + "s_cmp_lg_u64" => (Pred::Ne, false), + _ => return err(d, "SOPC"), + }; + let c0 = self.cmp(p, a.0, b.0); + let c1 = self.cmp(p, a.1, b.1); + let c = if eq { self.land(c0, c1) } else { self.lor(c0, c1) }; + self.set_scc(c); + return Ok(()); + } + let a = self.read(d, ins[0], false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + let b = self.read(d, ins[1], false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + if let Some(rest) = name.strip_prefix("s_cmp_") { + let (op, signed) = cmp_op(rest).ok_or("comparison").or_else(|e| err(d, e))?; + let c = self.cmp(int_pred(op, signed), a, b); + self.set_scc(c); + return Ok(()); + } + match name { + "s_bitcmp0_b32" | "s_bitcmp1_b32" => { + let sh = self.lshr(a, b); + let bit = self.andc(sh, 1); + if name == "s_bitcmp0_b32" { + let c = self.cmpc(Pred::Eq, bit, 0); + self.set_scc(c); + } else { + self.wr(VAR_SCC, bit); + } + } + _ => return err(d, "SOPC"), + } + return Ok(()); + } + // SOP1 / SOP2 + let saveexec = name.contains("saveexec") || name.contains("wrexec"); + if saveexec { + // a b32 source is one register (m0, a 32-bit constant): no 64-bit pair to read + let s0 = if name.ends_with("_b32") { + let lo = self.read(d, ins[0], false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + (lo, self.c(0)) + } else { + self.read64(d, ins[0], false).ok_or_else(|| format!("{}: op", rdna2::format(d)))? + }; + let (el, eh) = (self.sreg(126), self.sreg(127)); + let opn = base.split('_').nth(1).unwrap_or("").to_string(); + let op = |s: &mut Self, a: Value, e: Value| -> Option { + Some(match opn.as_str() { + "and" => s.and(a, e), + "or" => s.or(a, e), + "xor" => s.xor(a, e), + "andn2" => { + let n = s.not(e); + s.and(a, n) + } + "orn2" => { + let n = s.not(e); + s.or(a, n) + } + "nand" => { + let x = s.and(a, e); + s.not(x) + } + "nor" => { + let x = s.or(a, e); + s.not(x) + } + "xnor" => { + let x = s.xor(a, e); + s.not(x) + } + "andn1" => { + let n = s.not(a); + s.and(n, e) + } + "orn1" => { + let n = s.not(a); + s.or(n, e) + } + _ => return None, + }) + }; + let t0 = op(self, s0.0, el).ok_or_else(|| format!("{}: saveexec", rdna2::format(d)))?; + let t1 = op(self, s0.1, eh).ok_or_else(|| format!("{}: saveexec", rdna2::format(d)))?; + let wrexec = name.contains("wrexec"); + if !self.wave64 || name.ends_with("_b32") { + self.wr(126, t0); + let c = self.nz(t0); + self.set_scc(c); + self.write32(&dst, if wrexec { t0 } else { el }); + } else { + self.wr(126, t0); + self.wr(127, t1); + let o = self.or(t0, t1); + let c = self.nz(o); + self.set_scc(c); + if wrexec { + self.write64(&dst, t0, t1); + } else { + self.write64(&dst, el, eh); + } + } + return Ok(()); + } + if name == "s_swappc_b64" || name == "s_setpc_b64" { + let (sd, s0) = (Self::field(d, "SDST"), Self::field(d, "SSRC0")); + if name == "s_swappc_b64" && sd == s0 { + return Ok(()); + } + return err(d, "indirect branch"); + } + if name == "s_getpc_b64" { + let pc = d.pc + d.len as u64; + let (lo, hi) = (self.c(pc as u32), self.c(0)); + self.write64(&dst, lo, hi); + return Ok(()); + } + if matches!(name, "s_bitset0_b64" | "s_bitset1_b64") { + let i = self.read(d, ins[0], false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + let (lo, hi) = match &dst { + Dst::S(n) => (self.sreg(*n), self.sreg(*n + 1)), + _ => (self.c(0), self.c(0)), + }; + let one = self.c(1); + let mask = self.shl(one, i); + let i32b = self.andc(i, 32); + let low = self.cmpc(Pred::Eq, i32b, 0); + let z = self.c(0); + let ml = self.sel(low, mask, z); + let mh = self.sel(low, z, mask); + let (nl, nh) = if name == "s_bitset1_b64" { + (self.or(lo, ml), self.or(hi, mh)) + } else { + let a = self.not(ml); + let b = self.not(mh); + (self.and(lo, a), self.and(hi, b)) + }; + self.write64(&dst, nl, nh); + return Ok(()); + } + if wide { + return self.salu64(d, name, &dst, &ins); + } + let a = match ins.first() { + Some(o) => Some(self.read(d, o, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?), + None => None, + }; + let b = match ins.get(1) { + Some(o) => Some(self.read(d, o, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?), + None => None, + }; + let z = self.c(0); + let a = a.unwrap_or(z); + let b = b.unwrap_or(z); + // result, and SCC: None, Some(Nz) = result != 0, Some(Val(i1)) + enum Scc { + No, + Nz, + Is(Value), + } + let (res, scc): (Value, Scc) = match name { + "s_mov_b32" => (a, Scc::No), + "s_cmov_b32" => { + let cur = match &dst { + Dst::S(n) => self.sreg(*n), + _ => self.c(0), + }; + let c = self.scc_bit(); + (self.sel(c, a, cur), Scc::No) + } + "s_not_b32" => (self.not(a), Scc::Nz), + "s_brev_b32" => (self.reversebits(a), Scc::No), + "s_bcnt0_i32_b32" => { + let n = self.countbits(a); + let k = self.c(32); + (self.sub(k, n), Scc::Nz) + } + "s_bcnt1_i32_b32" => (self.countbits(a), Scc::Nz), + "s_ff0_i32_b32" => { + let n = self.not(a); + (self.firstbitlow(n), Scc::No) + } + "s_ff1_i32_b32" => (self.firstbitlow(a), Scc::No), + "s_flbit_i32_b32" => (self.lzcnt(a), Scc::No), + "s_flbit_i32" => (self.ffbh_i(a), Scc::No), + "s_abs_i32" => { + let n = self.sub(z, a); + let neg = self.cmp(Pred::SLt, a, z); + (self.sel(neg, n, a), Scc::Nz) + } + "s_sext_i32_i8" => { + let x = self.shlc(a, 24); + (self.ashrc(x, 24), Scc::No) + } + "s_sext_i32_i16" => { + let x = self.shlc(a, 16); + (self.ashrc(x, 16), Scc::No) + } + "s_and_b32" => (self.and(a, b), Scc::Nz), + "s_or_b32" => (self.or(a, b), Scc::Nz), + "s_xor_b32" => (self.xor(a, b), Scc::Nz), + "s_andn2_b32" => { + let n = self.not(b); + (self.and(a, n), Scc::Nz) + } + "s_orn2_b32" => { + let n = self.not(b); + (self.or(a, n), Scc::Nz) + } + "s_nand_b32" => { + let x = self.and(a, b); + (self.not(x), Scc::Nz) + } + "s_nor_b32" => { + let x = self.or(a, b); + (self.not(x), Scc::Nz) + } + "s_xnor_b32" => { + let x = self.xor(a, b); + (self.not(x), Scc::Nz) + } + "s_add_u32" => { + let t = self.add(a, b); + let c = self.cmp(Pred::ULt, t, a); + (t, Scc::Is(c)) + } + "s_sub_u32" => { + let t = self.sub(a, b); + let c = self.cmp(Pred::UGt, b, a); + (t, Scc::Is(c)) + } + "s_addc_u32" => { + let sc = self.scc(); + let t0 = self.add(a, b); + let t = self.add(t0, sc); + let (a6, b6, s6) = (self.zext64(a), self.zext64(b), self.zext64(sc)); + let x = self.add(a6, b6); + let x = self.add(x, s6); + let lim = self.c64(0xFFFF_FFFF); + let c = self.cmp(Pred::UGt, x, lim); + (t, Scc::Is(c)) + } + "s_subb_u32" => { + let sc = self.scc(); + let t0 = self.sub(a, b); + let t = self.sub(t0, sc); + let (a6, b6, s6) = (self.zext64(a), self.zext64(b), self.zext64(sc)); + let x = self.add(b6, s6); + let c = self.cmp(Pred::UGt, x, a6); + (t, Scc::Is(c)) + } + "s_add_i32" => { + let t = self.add(a, b); + let x = self.xor(a, t); + let y = self.xor(b, t); + let x = self.and(x, y); + let x = self.lshrc(x, 31); + (t, Scc::Is(self.nz(x))) + } + "s_sub_i32" => { + let t = self.sub(a, b); + let x = self.xor(a, b); + let y = self.xor(a, t); + let x = self.and(x, y); + let x = self.lshrc(x, 31); + (t, Scc::Is(self.nz(x))) + } + "s_mul_i32" => (self.mul(a, b), Scc::No), + "s_mul_hi_u32" => (self.mul_hi(a, b, false), Scc::No), + "s_mul_hi_i32" => (self.mul_hi(a, b, true), Scc::No), + "s_lshl_b32" => (self.shl(a, b), Scc::Nz), + "s_lshr_b32" => (self.lshr(a, b), Scc::Nz), + "s_ashr_i32" => (self.ashr(a, b), Scc::Nz), + "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => { + let k = name.as_bytes()[6] - b'0'; + let s = self.shlc(a, k as u32); + let t = self.add(s, b); + let (a6, b6) = (self.zext64(a), self.zext64(b)); + let kk = self.c64(k as u64); + let x = self.bin(BinOp::Shl, a6, kk); + let x = self.add(x, b6); + let lim = self.c64(0xFFFF_FFFF); + let c = self.cmp(Pred::UGt, x, lim); + (t, Scc::Is(c)) + } + "s_bfm_b32" => (self.bfm(a, b), Scc::No), + "s_bfe_u32" => (self.sbfe_u(a, b), Scc::Nz), + "s_bfe_i32" => (self.sbfe_i(a, b), Scc::Nz), + "s_min_u32" => { + let c = self.cmp(Pred::ULt, a, b); + (self.umin(a, b), Scc::Is(c)) + } + "s_max_u32" => { + let c = self.cmp(Pred::UGt, a, b); + (self.umax(a, b), Scc::Is(c)) + } + "s_min_i32" => { + let c = self.cmp(Pred::SLt, a, b); + (self.imin(a, b), Scc::Is(c)) + } + "s_max_i32" => { + let c = self.cmp(Pred::SGt, a, b); + (self.imax(a, b), Scc::Is(c)) + } + "s_cselect_b32" => { + let c = self.scc_bit(); + (self.sel(c, a, b), Scc::No) + } + "s_wqm_b32" => (self.wqm(a), Scc::Nz), + "s_bitset0_b32" | "s_bitset1_b32" => { + let cur = match &dst { + Dst::S(n) => self.sreg(*n), + _ => self.c(0), + }; + let one = self.c(1); + let m = self.shl(one, a); + if name == "s_bitset1_b32" { + (self.or(cur, m), Scc::No) + } else { + let n = self.not(m); + (self.and(cur, n), Scc::No) + } + } + "s_absdiff_i32" => { + let t = self.sub(a, b); + let n = self.sub(z, t); + let neg = self.cmp(Pred::SLt, t, z); + (self.sel(neg, n, t), Scc::Nz) + } + "s_pack_ll_b32_b16" => { + let l = self.andc(a, 0xFFFF); + let h = self.shlc(b, 16); + (self.or(l, h), Scc::No) + } + "s_pack_lh_b32_b16" => { + let l = self.andc(a, 0xFFFF); + let h = self.andc(b, 0xFFFF_0000); + (self.or(l, h), Scc::No) + } + "s_pack_hh_b32_b16" => { + let l = self.lshrc(a, 16); + let h = self.andc(b, 0xFFFF_0000); + (self.or(l, h), Scc::No) + } + _ => return err(d, "SALU"), + }; + match scc { + Scc::No => {} + Scc::Nz => { + let c = self.nz(res); + self.set_scc(c); + } + Scc::Is(c) => self.set_scc(c), + } + self.write32(&dst, res); + Ok(()) + } + + fn smovrel(&mut self, d: &Decoded, name: &str) -> LResult<()> { + let dst = Self::field(d, "SDST"); + let src = Self::field(d, "SSRC0"); + if dst > 123 || src > 123 { + return err(d, "scalar movrel register"); + } + let m0 = self.sreg(124); + let (rd, wr, wide) = match name { + "s_movrels_b32" => (Some(m0), None, false), + "s_movrels_b64" => (Some(m0), None, true), + "s_movreld_b32" => (None, Some(m0), false), + "s_movreld_b64" => (None, Some(m0), true), + _ => { + let r = self.andc(m0, 0x3FF); + let w = self.lshrc(m0, 16); + let w = self.andc(w, 0x3FF); + (Some(r), Some(w), false) + } + }; + let words = if wide { 2 } else { 1 }; + let mut vals = Vec::new(); + for word in 0..words { + if let Some(idx) = rd { + // select chain over every register from src + word up to s123 + let mut v = self.c(0); + for k in 0..=123u64.saturating_sub(src + word) { + let r = self.sreg(src + word + k); + let is = self.cmpc(Pred::Eq, idx, k as u32); + v = self.sel(is, r, v); + } + vals.push(v); + } else { + vals.push(self.sreg(src + word)); + } + } + if let Some(idx) = wr { + for k in 0..=123u64.saturating_sub(dst + words - 1) { + let is = self.cmpc(Pred::Eq, idx, k as u32); + for w in 0..words { + let old = self.sreg(dst + k + w); + let v = self.sel(is, vals[w as usize], old); + self.wr((dst + k + w) as u32, v); + } + } + } else { + for w in 0..words { + self.wr((dst + w) as u32, vals[w as usize]); + } + } + Ok(()) + } + + fn salu64(&mut self, d: &Decoded, name: &str, dst: &Dst, ins: &[&Operand]) -> LResult<()> { + let e = || format!("{}: op", rdna2::format(d)); + let a = match ins.first() { + Some(o) => Some(self.read64(d, o, false).ok_or_else(e)?), + None => None, + }; + let b = match ins.get(1) { + Some(o) => { + if o.size == 32 { + let v = self.read(d, o, false).ok_or_else(e)?; + let z = self.c(0); + Some((v, z)) + } else { + Some(self.read64(d, o, false).ok_or_else(e)?) + } + } + None => None, + }; + let z = self.c(0); + let (al, ah) = a.unwrap_or((z, z)); + let (bl, bh) = b.unwrap_or((z, z)); + let one_word = matches!(name, "s_bcnt0_i32_b64" | "s_bcnt1_i32_b64" | "s_ff0_i32_b64" | "s_ff1_i32_b64" | "s_flbit_i32_b64" | "s_flbit_i32_i64"); + let mut nz = true; + let (lo, hi): (Value, Value) = match name { + "s_mov_b64" => { + nz = false; + (al, ah) + } + "s_cmov_b64" => { + nz = false; + let (c0, c1) = match dst { + Dst::S(n) => (self.sreg(*n), self.sreg(*n + 1)), + _ => (z, z), + }; + let c = self.scc_bit(); + (self.sel(c, al, c0), self.sel(c, ah, c1)) + } + "s_not_b64" => (self.not(al), self.not(ah)), + "s_cselect_b64" => { + nz = false; + let c = self.scc_bit(); + (self.sel(c, al, bl), self.sel(c, ah, bh)) + } + "s_wqm_b64" => (self.wqm(al), self.wqm(ah)), + "s_brev_b64" => { + nz = false; + (self.reversebits(ah), self.reversebits(al)) + } + "s_bcnt1_i32_b64" => { + let x = self.countbits(al); + let y = self.countbits(ah); + (self.add(x, y), z) + } + "s_bcnt0_i32_b64" => { + let x = self.countbits(al); + let y = self.countbits(ah); + let k = self.c(64); + let t = self.sub(k, x); + (self.sub(t, y), z) + } + "s_ff1_i32_b64" | "s_ff0_i32_b64" => { + nz = false; + let (l, h) = if name == "s_ff0_i32_b64" { (self.not(al), self.not(ah)) } else { (al, ah) }; + let fl = self.firstbitlow(l); + let fh = self.firstbitlow(h); + let fh32 = self.addc(fh, 32); + let hnz = self.nz(h); + let m1 = self.c(u32::MAX); + let hv = self.sel(hnz, fh32, m1); + let lnz = self.nz(l); + (self.sel(lnz, fl, hv), z) + } + "s_flbit_i32_b64" | "s_flbit_i32_i64" => { + nz = false; + let (l, h) = if name == "s_flbit_i32_i64" { + let neg = self.cmp(Pred::SLt, ah, z); + let nl = self.not(al); + let nh = self.not(ah); + (self.sel(neg, nl, al), self.sel(neg, nh, ah)) + } else { + (al, ah) + }; + let lh = self.lzcnt(h); + let ll = self.lzcnt(l); + let ll32 = self.addc(ll, 32); + let lnz = self.nz(l); + let m1 = self.c(u32::MAX); + let lv = self.sel(lnz, ll32, m1); + let hnz = self.nz(h); + (self.sel(hnz, lh, lv), z) + } + "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => { + let v = self.pack64(al, ah); + let sh = self.andc(bl, 63); + let sh = self.zext64(sh); + let w = match name { + "s_lshl_b64" => self.bin(BinOp::Shl, v, sh), + "s_lshr_b64" => self.bin(BinOp::LShr, v, sh), + _ => self.bin(BinOp::AShr, v, sh), + }; + self.unpack64(w) + } + "s_bfm_b64" => { + nz = false; + let wdt = self.andc(al, 63); + let off = self.andc(bl, 63); + let all = self.c64(u64::MAX); + let k64 = self.c(64); + let sh = self.sub(k64, wdt); + let sh = self.andc(sh, 63); + let sh = self.zext64(sh); + let m = self.bin(BinOp::LShr, all, sh); + let wz = self.cmpc(Pred::Eq, wdt, 0); + let z64 = self.c64(0); + let m = self.sel(wz, z64, m); + let off = self.zext64(off); + let r = self.bin(BinOp::Shl, m, off); + self.unpack64(r) + } + "s_bfe_u64" | "s_bfe_i64" => { + let v = self.pack64(al, ah); + let w = self.lshrc(bl, 16); + let w = self.andc(w, 0x7F); + let o = self.andc(bl, 63); + let o64 = self.zext64(o); + let wz = self.cmpc(Pred::Eq, w, 0); + let wbig = self.cmpc(Pred::UGe, w, 64); + let k64 = self.c(64); + let s = self.sub(k64, w); + let s = self.andc(s, 63); + let s64 = self.zext64(s); + let z64 = self.c64(0); + let r = if name == "s_bfe_u64" { + let x = self.bin(BinOp::LShr, v, o64); + let all = self.c64(u64::MAX); + let m = self.bin(BinOp::LShr, all, s64); + let xm = self.and(x, m); + let r = self.sel(wbig, x, xm); + self.sel(wz, z64, r) + } else { + let x = self.bin(BinOp::AShr, v, o64); + let y = self.bin(BinOp::Shl, x, s64); + let y = self.bin(BinOp::AShr, y, s64); + let r = self.sel(wbig, x, y); + self.sel(wz, z64, r) + }; + self.unpack64(r) + } + _ => { + let op = name.trim_start_matches("s_").trim_end_matches("_b64"); + match op { + "and" => (self.and(al, bl), self.and(ah, bh)), + "or" => (self.or(al, bl), self.or(ah, bh)), + "xor" => (self.xor(al, bl), self.xor(ah, bh)), + "andn2" => { + let (x, y) = (self.not(bl), self.not(bh)); + (self.and(al, x), self.and(ah, y)) + } + "orn2" => { + let (x, y) = (self.not(bl), self.not(bh)); + (self.or(al, x), self.or(ah, y)) + } + "nand" => { + let (x, y) = (self.and(al, bl), self.and(ah, bh)); + (self.not(x), self.not(y)) + } + "nor" => { + let (x, y) = (self.or(al, bl), self.or(ah, bh)); + (self.not(x), self.not(y)) + } + "xnor" => { + let (x, y) = (self.xor(al, bl), self.xor(ah, bh)); + (self.not(x), self.not(y)) + } + _ => return err(d, "SALU64"), + } + } + }; + if nz { + let c = if one_word { + self.nz(lo) + } else { + let o = self.or(lo, hi); + self.nz(o) + }; + self.set_scc(c); + } + if one_word { + self.write32(dst, lo); + } else { + self.write64(dst, lo, hi); + } + Ok(()) + } + + // ------------------------------------------------------------ helpers (PRELUDE) + + pub fn mul_hi(&mut self, a: Value, b: Value, signed: bool) -> Value { + let (x, y) = if signed { (self.sext64(a), self.sext64(b)) } else { (self.zext64(a), self.zext64(b)) }; + let p = self.mul(x, y); + let k = self.c64(32); + let h = self.bin(BinOp::LShr, p, k); + self.trunc32(h) + } + pub fn bfm(&mut self, a: Value, b: Value) -> Value { + let w = self.andc(a, 31); + let wz = self.cmpc(Pred::Eq, w, 0); + let k = self.c(32); + let s = self.sub(k, w); + let s = self.andc(s, 31); + let all = self.c(u32::MAX); + let m = self.bin(BinOp::LShr, all, s); + let m = self.selc(wz, 0, m); + self.shl(m, b) + } + pub fn ffbh_i(&mut self, v: Value) -> Value { + let z = self.c(0); + let neg = self.cmp(Pred::SLt, v, z); + let n = self.not(v); + let x = self.sel(neg, n, v); + self.lzcnt(x) + } + pub fn sbfe_u(&mut self, v: Value, c: Value) -> Value { + let o = self.andc(c, 31); + let w = self.lshrc(c, 16); + let w = self.andc(w, 0x7F); + let x = self.bin(BinOp::LShr, v, o); + let k = self.c(32); + let s = self.sub(k, w); + let s = self.andc(s, 31); + let all = self.c(u32::MAX); + let m = self.bin(BinOp::LShr, all, s); + let xm = self.and(x, m); + let big = self.cmpc(Pred::UGe, w, 32); + let r = self.sel(big, x, xm); + let wz = self.cmpc(Pred::Eq, w, 0); + self.selc(wz, 0, r) + } + pub fn sbfe_i(&mut self, v: Value, c: Value) -> Value { + let o = self.andc(c, 31); + let w = self.lshrc(c, 16); + let w = self.andc(w, 0x7F); + let k = self.c(32); + let s = self.sub(k, w); + let s = self.andc(s, 31); + let x = self.bin(BinOp::AShr, v, o); + let y = self.bin(BinOp::Shl, x, s); + let y = self.bin(BinOp::AShr, y, s); + let big = self.cmpc(Pred::UGe, w, 32); + let r = self.sel(big, x, y); + let wz = self.cmpc(Pred::Eq, w, 0); + self.selc(wz, 0, r) + } + pub fn bfe_u(&mut self, v: Value, o: Value, w: Value) -> Value { + let o = self.andc(o, 31); + let w = self.andc(w, 31); + let x = self.bin(BinOp::LShr, v, o); + let k = self.c(32); + let s = self.sub(k, w); + let s = self.andc(s, 31); + let all = self.c(u32::MAX); + let m = self.bin(BinOp::LShr, all, s); + let r = self.and(x, m); + let wz = self.cmpc(Pred::Eq, w, 0); + self.selc(wz, 0, r) + } + pub fn bfe_i(&mut self, v: Value, o: Value, w: Value) -> Value { + let o = self.andc(o, 31); + let w = self.andc(w, 31); + let k = self.c(32); + let s = self.sub(k, w); + let s = self.andc(s, 31); + let x = self.bin(BinOp::AShr, v, o); + let y = self.bin(BinOp::Shl, x, s); + let y = self.bin(BinOp::AShr, y, s); + let wz = self.cmpc(Pred::Eq, w, 0); + self.selc(wz, 0, y) + } + pub fn wqm(&mut self, m: Value) -> Value { + let a = self.lshrc(m, 1); + let q = self.or(m, a); + let b = self.lshrc(q, 2); + let q = self.or(q, b); + let q = self.andc(q, 0x1111_1111); + let k = self.c(15); + self.mul(q, k) + } +} + +/// Instructions without an effect in this execution model. +pub const NOOPS: &[&str] = &[ + "s_nop", "s_waitcnt", "s_waitcnt_vscnt", "s_waitcnt_vmcnt", "s_waitcnt_expcnt", "s_waitcnt_lgkmcnt", "s_waitcnt_depctr", + "s_inst_prefetch", "s_clause", "s_code_end", "s_setprio", "s_sleep", "s_icache_inv", "s_dcache_inv", "s_gl1_inv", "s_ttracedata", + "s_ttracedata_imm", "v_nop", "s_denorm_mode", "s_sendmsg", "s_sendmsghalt", "s_set_gpr_idx_off", "s_version", "buffer_gl0_inv", + "buffer_gl1_inv", "ds_nop", +]; + +pub fn f32_const(code: u64) -> Option { + Some(match code { + 240 => 0.5, + 241 => -0.5, + 242 => 1.0, + 243 => -1.0, + 244 => 2.0, + 245 => -2.0, + 246 => 4.0, + 247 => -4.0, + 248 => 0.159_154_94, + _ => return None, + }) +} + +pub fn f16_const(code: u64) -> Option { + Some(match code { + 240 => 0x3800, + 241 => 0xB800, + 242 => 0x3C00, + 243 => 0xBC00, + 244 => 0x4000, + 245 => 0xC000, + 246 => 0x4400, + 247 => 0xC400, + 248 => 0x3118, + _ => return None, + }) +} + +pub fn cmp_op(rest: &str) -> Option<(&'static str, bool)> { + let (op, ty) = rest.rsplit_once('_')?; + let signed = ty == "i32"; + Some(( + match op { + "eq" => "==", + "lg" => "!=", + "gt" => ">", + "ge" => ">=", + "lt" => "<", + "le" => "<=", + _ => return None, + }, + signed, + )) +} + +pub fn int_pred(op: &str, signed: bool) -> Pred { + match (op, signed) { + ("==", _) => Pred::Eq, + ("!=", _) => Pred::Ne, + (">", false) => Pred::UGt, + (">=", false) => Pred::UGe, + ("<", false) => Pred::ULt, + ("<=", false) => Pred::ULe, + (">", true) => Pred::SGt, + (">=", true) => Pred::SGe, + ("<", true) => Pred::SLt, + _ => Pred::SLe, + } +} + +/// Layout of the SDWA / DPP extension dword for this instruction's base encoding. +pub fn ext_encoding(d: &Decoded) -> Option<&'static Encoding> { + let base = match d.enc.name { + "ENC_VOP1" => "VOP1", + "ENC_VOP2" => "VOP2", + "ENC_VOPC" => "VOPC", + _ => return None, + }; + let name = match (d.variant, base) { + (Variant::Sdwa, "VOPC") => "VOPC_VOP_SDWA_SDST_ENC".to_string(), + (Variant::Sdwa, b) => format!("{b}_VOP_SDWA"), + (Variant::Dpp16, b) => format!("{b}_VOP_DPP16"), + (Variant::Dpp8, b) => format!("{b}_VOP_DPP8"), + _ => return None, + }; + rdna2::encoding(&name) +} + +impl Lw { + pub fn orc(&mut self, a: Value, k: u32) -> Value { + let k = self.c(k); + self.or(a, k) + } +} + +/// `(id, offset, width)` of an `OPR_HWREG` `SIMM16`. +fn decode_hwreg(simm16: u16) -> (u32, u32, u32) { + ((simm16 & 0x3F) as u32, ((simm16 >> 6) & 0x1F) as u32, (((simm16 >> 11) & 0x1F) + 1) as u32) +} + +/// Bits of MODE[1:0] (sp) and MODE[3:2] (dp / f16) a `s_setreg*` touches, and its offset. +pub fn hwreg_mode_round_masks(simm16: u16) -> (u32, u32, u32) { + let (id, offset, width) = decode_hwreg(simm16); + if id != 1 { + return (0, 0, 0); + } + let covers = |b: u32| b >= offset && b < offset + width; + let sp = (covers(0) as u32) | ((covers(1) as u32) << 1); + let dp = (covers(2) as u32) | ((covers(3) as u32) << 1); + (sp, dp, offset) +} + +/// The value `s_setreg_imm32_b32` writes to MODE[base +: 2] (masked). +pub fn hwreg_imm_field(imm: u32, offset: u32, base: u32, mask: u32) -> u32 { + let mut v = 0u32; + if mask & 1 != 0 { + v |= (imm >> (base - offset)) & 1; + } + if mask & 2 != 0 { + v |= ((imm >> (base + 1 - offset)) & 1) << 1; + } + v +} + +/// Instructions whose f16 result rounding obeys MODE[3:2]. +pub fn is_f16_rounded_op(name: &str) -> bool { + matches!( + name, + "v_interp_p2_f16" | "v_cvt_f16_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" | "v_pk_add_f16" | "v_pk_mul_f16" | "v_pk_fma_f16" + | "v_pk_fmac_f16" | "v_pk_min_f16" | "v_pk_max_f16" | "v_add_f16" | "v_sub_f16" | "v_subrev_f16" | "v_mul_f16" | "v_min_f16" + | "v_max_f16" | "v_fma_f16" | "v_med3_f16" | "v_min3_f16" | "v_max3_f16" | "v_frexp_mant_f16" | "v_mad_f16" | "v_fmac_f16" + | "v_fmamk_f16" | "v_fmaak_f16" | "v_ldexp_f16" | "v_rcp_f16" | "v_rsq_f16" | "v_sqrt_f16" | "v_log_f16" | "v_exp_f16" + | "v_sin_f16" | "v_cos_f16" | "v_fract_f16" | "v_floor_f16" | "v_ceil_f16" | "v_trunc_f16" | "v_rndne_f16" | "v_cvt_f16_u16" + | "v_cvt_f16_i16" + ) +} + +/// Instructions whose f64 rounding obeys MODE[3:2]. +pub fn is_f64_rounded_op(name: &str) -> bool { + name.contains("_f64") + && !name.starts_with("v_cmp_") + && !name.starts_with("v_cmpx_") + && !matches!(name, "v_cvt_f32_f64" | "v_cvt_i32_f64" | "v_cvt_u32_f64" | "v_frexp_exp_i32_f64") +} + +/// The recompiler's `configure_round_modes`: (dynamic f16 rounding, has f64 rounding ops). +pub fn round_modes(insts: &[Decoded], stop_at_endpgm: bool) -> (bool, bool) { + let (mut f16, mut f64, mut writes) = (false, false, false); + for d in insts { + let name = d.inst.name.to_ascii_lowercase(); + if stop_at_endpgm && matches!(name.as_str(), "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done") { + break; + } + f16 |= is_f16_rounded_op(&name); + f64 |= is_f64_rounded_op(&name); + let simm = rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0) as u16; + match name.as_str() { + "s_round_mode" => writes |= (simm >> 2) & 3 != 0, + "s_setreg_imm32_b32" => { + let (_, dp_mask, off) = hwreg_mode_round_masks(simm); + writes |= dp_mask != 0 && hwreg_imm_field(d.literal.unwrap_or(0), off, 2, dp_mask) != 0; + } + "s_setreg_b32" => writes |= hwreg_mode_round_masks(simm).1 != 0, + _ => {} + } + } + (writes && f16 && !f64, f64) +} + +/// Constant folding of an integer binop on `w`-bit values (None: undefined in LLVM — +/// division by zero, shifts by the width or more — or not folded). +fn fold_bin(op: BinOp, x: u64, y: u64, w: u32) -> Option { + let sx = |v: u64| if w >= 64 { v as i64 } else { ((v << (64 - w)) as i64) >> (64 - w) }; + Some(match op { + BinOp::Add => x.wrapping_add(y), + BinOp::Sub => x.wrapping_sub(y), + BinOp::Mul => x.wrapping_mul(y), + BinOp::And => x & y, + BinOp::Or => x | y, + BinOp::Xor => x ^ y, + BinOp::Shl if y < w as u64 => x << y, + BinOp::LShr if y < w as u64 => x >> y, + BinOp::AShr if y < w as u64 => (sx(x) >> y) as u64, + BinOp::UDiv if y != 0 => x / y, + BinOp::URem if y != 0 => x % y, + _ => return None, + }) +} diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs new file mode 100644 index 000000000..71d5a579b --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lower_gfx.rs @@ -0,0 +1,433 @@ +//! Vertex and pixel shader entries for the direct translator (the recompiler's +//! `Mode::Vertex` / `Mode::Pixel`, `recomp/emit.rs` `finish` / `export_graphics` +//! / `interp`): signatures declared exactly as the HLSL entry structs declare +//! them (so they pack and link alike, also against an HLSL-path partner stage), +//! initial VGPRs from the inputs, exports into output temporaries stored once +//! at the end (unwritten components are 0, as `(XclOut)0`), `v_interp_*` as +//! the PC rasteriser's interpolated inputs, and the PS `discard` of lanes +//! without a DONE export. + +use std::collections::{BTreeMap, HashMap}; + +use super::graphics::{CompType as GCt, GraphicsIo, Interp, SemKind, Sig, SigElement as GSig}; +use super::lower::{err, LResult, Lw}; +use super::module::{Pred, Value}; +use crate::gpu::dxbc::SigElement; +use crate::gpu::rdna2::{self, Decoded}; +use crate::gpu::recomp::{elements_at, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, PsInterface, VsInterface}; + +/// An output element: its signature handle, components and the temporaries holding them. +pub struct GfxOut { + pub sig: Sig, + pub comps: u8, + pub float: bool, + pub vars: Vec, +} + +pub struct GfxCtx { + pub io: GraphicsIo, + pub vs: Option, + pub ps: Option, + /// VS: SV_Position, then the params `p` (`ranked(outputs, true)`) + pub pos: Option, + pub params: Vec, + /// PS: the inputs `a` (`ranked(inputs, false)`), SV_Target by index, depth + pub ps_in: Vec<(Sig, bool)>, + pub targets: BTreeMap, + pub depth: Option, + /// PS: a DONE export happened somewhere (`xcl_live` decides the discard) + pub ps_done: bool, + pub live_var: u32, +} + +fn gct(component_type: u32) -> GCt { + match component_type { + 1 => GCt::U32, + 2 => GCt::I32, + _ => GCt::F32, + } +} + +/// Components of an output element: clip / cull distances by their mask, the rest 4. +fn out_comps(e: &SigElement) -> u8 { + if matches!(e.system_value, 2 | 3) { + 8 - e.mask.leading_zeros() as u8 + } else { + 4 + } +} + +impl Lw { + fn gfx(&mut self) -> &mut GfxCtx { + self.gfx.as_mut().expect("graphics entry") + } + + fn out_vars(&mut self, n: u8) -> Vec { + let z = self.c(0); + (0..n) + .map(|_| { + let t = self.tmp_var(); + self.wr(t, z); + t + }) + .collect() + } + + /// Lane setup of the graphics stages (the HLSL VS / PS entry's): a wave64 program + /// uses the hardware lane; a wave32 program in 64-lane hardware runs each half as + /// its own wave (`xcl_w32`, `xcl_half`). + pub fn setup_lanes_gfx(&mut self) { + let hw = self.s.wave_lane_index(); + if self.wave64 { + self.lane = hw; + } else { + let n = self.s.wave_lane_count(); + let w32 = self.cmpc(Pred::UGt, n, 32); + let h = self.lshrc(hw, 5); + let z = self.c(0); + let half = self.sel(w32, h, z); + let hnz = self.nz(half); + self.gfx_half = Some(hnz); + self.lane = self.andc(hw, 31); + } + let lane = self.lane; + self.lane31 = self.andc(lane, 31); + self.upper = self.cmpc(Pred::UGe, lane, 32); + self.half = self.lshrc(lane, 5); + } + + /// VS entry: signatures, initial registers. + pub fn setup_vertex(&mut self, vs: &VsInterface, used_vgprs: &std::collections::BTreeSet) { + let mut io = GraphicsIo::new(super::container::Stage::Vertex); + let inputs: Vec = vs.inputs.iter().filter(|e| e.system_value == 0 && !e.name.starts_with("SV_")).cloned().collect(); + let mut attr: HashMap = HashMap::new(); + for e in &inputs { + let s = io.input(GSig::user(&e.name, e.index, gct(e.component_type), 4)); + attr.insert(e.register, s); + } + let vid = io.input(GSig::new("SV_VertexID", 0, SemKind::VertexId, GCt::U32, 1)); + let iid = io.input(GSig::new("SV_InstanceID", 0, SemKind::InstanceId, GCt::U32, 1)); + let pos_sig = io.output(GSig::new("SV_Position", 0, SemKind::Position, GCt::F32, 4)); + let mut outs = Vec::new(); + for e in ranked(&vs.outputs, true) { + let n = out_comps(e); + let kind = match e.system_value { + 2 => SemKind::ClipDistance, + 3 => SemKind::CullDistance, + _ => SemKind::Arbitrary, + }; + let s = io.output(GSig::new(&e.name, e.index, kind, gct(e.component_type), n)); + outs.push((s, n, e.component_type == 3)); + } + // initial VGPRs: v0 = vertex id, v3 = instance id, the fetch shader's attribute VGPRs + let mut vgpr = HashMap::new(); + let vidv = io.load_input(&mut self.s, vid, 0, 0); + let iidv = io.load_input(&mut self.s, iid, 0, 0); + for &v in used_vgprs { + let sv_at = vs.inputs.iter().find(|e| matches!(e.system_value, 6 | 8) && vs.input_vgpr(e.register) == Some(v)); + let val = if v == 0 { + Some(vidv) + } else if v == 3 { + Some(iidv) + } else if let Some(e) = sv_at { + Some(if e.system_value == 6 { vidv } else { iidv }) + } else { + inputs.iter().find_map(|e| { + vs.input_vgpr(e.register).filter(|&b| v >= b && v < b + 4).map(|b| (attr[&e.register], (v - b) as u8)) + }).map(|(s, c)| { + let x = io.load_input(&mut self.s, s, 0, c); + let i32 = self.s.m.i32(); + self.s.m.bitcast(x, i32) + }) + }; + if let Some(x) = val { + vgpr.insert(v as u32, x); + } + } + self.gfx_common_init(vgpr); + let pos = GfxOut { sig: pos_sig, comps: 4, float: true, vars: self.out_vars(4) }; + let params = outs.into_iter().map(|(sig, n, float)| GfxOut { sig, comps: n, float, vars: self.out_vars(n) }).collect(); + self.gfx = Some(GfxCtx { io, vs: Some(vs.clone()), ps: None, pos: Some(pos), params, ps_in: Vec::new(), targets: BTreeMap::new(), depth: None, ps_done: false, live_var: 0 }); + } + + /// PS entry: signatures, initial registers (`modes`: the interpolation of each + /// attribute from the I/J pair its `v_interp` uses, `emit::ps_attr_modes`). + pub fn setup_pixel(&mut self, ps: &PsInterface, modes: &BTreeMap) { + let mut io = GraphicsIo::new(super::container::Stage::Pixel); + let conservative = ps.outputs.iter().any(|e| matches!(e.system_value, 67 | 68)); + let mut pos_e = GSig::new("SV_Position", 0, SemKind::Position, GCt::F32, 4); + if conservative { + pos_e = pos_e.interp(Interp::LinearNoperspectiveCentroid); + } + let pos = io.input(pos_e); + let mut ps_in = Vec::new(); + for (k, e) in ranked(&ps.inputs, false).iter().enumerate() { + let attr = ps_slot_attribute(ps, k); + let m = attr.and_then(|a| modes.get(&(a as u32))).cloned().unwrap_or_default(); + let float = e.component_type == 3; + let interp = if !float { + Interp::Constant + } else { + match m.as_str() { + "sample" => Interp::LinearSample, + "centroid" => Interp::LinearCentroid, + "noperspective" => Interp::LinearNoperspective, + "noperspective centroid" => Interp::LinearNoperspectiveCentroid, + "noperspective sample" => Interp::LinearNoperspectiveSample, + "nointerpolation" => Interp::Constant, + _ => Interp::Linear, + } + }; + let s = io.input(GSig::user(&e.name, e.index, gct(e.component_type), 4).interp(interp)); + ps_in.push((s, float)); + } + // DXIL wants SV_IsFrontFace as uint (`bool` in HLSL becomes uint 0 / 0xFFFFFFFF) + let ff = (ps.input_ena >> 12 & 1 == 1).then(|| io.input(GSig::new("SV_IsFrontFace", 0, SemKind::IsFrontFace, GCt::U32, 1).interp(Interp::Constant))); + let mut targets = BTreeMap::new(); + let mut depth = None; + let mut any = false; + for e in &ps.outputs { + match e.system_value { + 64 => { + let s = io.output(GSig::new("SV_Target", e.index, SemKind::Target, gct(e.component_type), 4)); + targets.insert(e.index, (GfxOut { sig: s, comps: 4, float: e.component_type == 3, vars: Vec::new() }, e.component_type)); + any = true; + } + 65 | 67 | 68 => { + let kind = match e.system_value { + 65 => SemKind::Depth, + 67 => SemKind::DepthGreaterEqual, + _ => SemKind::DepthLessEqual, + }; + let s = io.output(GSig::new(match kind { + SemKind::Depth => "SV_Depth", + SemKind::DepthGreaterEqual => "SV_DepthGreaterEqual", + _ => "SV_DepthLessEqual", + }, 0, kind, GCt::F32, 1)); + depth = Some(GfxOut { sig: s, comps: 1, float: true, vars: Vec::new() }); + any = true; + } + _ => {} + } + } + if !any { + let s = io.output(GSig::new("SV_Target", 7, SemKind::Target, GCt::F32, 4)); + targets.insert(7, (GfxOut { sig: s, comps: 4, float: true, vars: Vec::new() }, 3)); + } + // initial VGPRs: the system values SPI_PS_INPUT_ENA enables + let mut vgpr = HashMap::new(); + let sys = |bit: u32| ps_input_vgpr(ps.input_ena, bit); + for (bit, c) in [(8u32, 0u8), (9, 1), (10, 2), (11, 3)] { + if let Some(v) = sys(bit) { + let x = io.load_input(&mut self.s, pos, 0, c); + let i32 = self.s.m.i32(); + vgpr.insert(v as u32, self.s.m.bitcast(x, i32)); + } + } + if let (Some(v), Some(ff)) = (sys(12), ff) { + let x = io.load_input(&mut self.s, ff, 0, 0); + let b = self.nz(x); + let one = self.c(0x3F80_0000); + let z = self.c(0); + vgpr.insert(v as u32, self.sel(b, one, z)); + } + if let Some(v) = sys(14) { + vgpr.insert(v as u32, io.coverage(&mut self.s)); + } + self.gfx_common_init(vgpr); + for (o, _) in targets.values_mut() { + o.vars = self.out_vars(4); + } + if let Some(d) = depth.as_mut() { + d.vars = self.out_vars(1); + } + let live_var = self.tmp_var(); + let f = self.c(0); + self.wr(live_var, f); + self.gfx = Some(GfxCtx { io, vs: None, ps: Some(ps.clone()), pos: None, params: Vec::new(), ps_in, targets, depth, ps_done: false, live_var }); + } + + /// SGPRs from `io`, SCC 0, EXEC = `ballot(true)`. + fn gfx_common_init(&mut self, vgpr: HashMap) { + let zero = self.c(0); + let mut sgpr = HashMap::new(); + sgpr.insert(super::lower::VAR_SCC, zero); + let t = self.s.m.i1c(true); + let (lo, hi) = self.ballot(t); + sgpr.insert(126, lo); + sgpr.insert(127, hi); + self.init.compute = Some(super::lower::ComputeInit { sgpr, vgpr, zero }); + } + + /// The end of a graphics stage: the PS discard, then every output component. + pub fn finish_gfx(&mut self) { + let mut g = self.gfx.take().expect("graphics entry"); + if g.ps_done { + let live = self.rd(g.live_var); + let dead = self.cmpc(Pred::Eq, live, 0); + g.io.discard(&mut self.s, dead); + } + let mut all: Vec<&GfxOut> = Vec::new(); + all.extend(g.pos.iter()); + all.extend(g.params.iter()); + all.extend(g.targets.values().map(|(o, _)| o)); + all.extend(g.depth.iter()); + let stores: Vec<(Sig, u8, bool, u32)> = all.iter().flat_map(|o| o.vars.iter().enumerate().map(move |(c, &v)| (o.sig, c as u8, o.float, v))).collect(); + for (sig, c, float, var) in stores { + let v = self.rd(var); + let v = if float { self.f(v) } else { v }; + g.io.store_output(&mut self.s, sig, 0, c, v); + } + self.gfx = Some(g); + } + + /// `out[c] = v` in active lanes. + fn set_out(&mut self, var: u32, v: Value) { + let a = self.act(); + let old = self.rd(var); + let n = self.sel(a, v, old); + self.wr(var, n); + } + + /// Graphics exports (`export_graphics`). + pub fn export_gfx(&mut self, d: &Decoded, en: u64, tgt: u64, compr: bool, srcs: &[Value]) -> LResult<()> { + let done = Self::fv(d, "DONE") == 1; + let enabled = |c: usize| if compr { en >> (c / 2 * 2) & 3 != 0 } else { en >> c & 1 == 1 }; + let comp = |lw: &mut Lw, c: usize| -> Value { + if compr { + let r = srcs[c / 2]; + if c % 2 == 0 { + lw.andc(r, 0xFFFF) + } else { + lw.lshrc(r, 16) + } + } else { + srcs[c] + } + }; + let pixel = self.gfx().ps.is_some(); + if !pixel { + match tgt { + 12 => { + let vars = self.gfx().pos.as_ref().expect("pos").vars.clone(); + for (c, &var) in vars.iter().enumerate() { + if enabled(c) { + let v = comp(self, c); + self.set_out(var, v); + } + } + } + 13..=15 => {} + 32..=63 => { + let vs = self.gfx().vs.clone().expect("vs"); + let k = (tgt - 32) as usize; + let at = vs_param_register(&vs, k).map(|r| elements_at(&vs.outputs, true, r)).unwrap_or_default(); + for j in at { + let (vars, n) = { + let o = &self.gfx().params[j]; + (o.vars.clone(), o.comps) + }; + for c in 0..n as usize { + if enabled(c) { + let v = comp(self, c); + self.set_out(vars[c], v); + } + } + } + } + _ => return err(d, "export target"), + } + return Ok(()); + } + match tgt { + 0..=7 => { + let t = self.gfx().targets.get(&(tgt as u32)).map(|(o, ct)| (o.vars.clone(), *ct)); + if let Some((vars, ct)) = t { + for (c, &var) in vars.iter().enumerate() { + if !enabled(c) { + continue; + } + let raw = comp(self, c); + let v = match (ct, compr) { + (3, true) => { + let f = self.s.f16_to_f32(raw); + self.bits(f) + } + (2, true) => self.sx16(raw), + _ => raw, + }; + self.set_out(var, v); + } + } + } + 8 => { + let dv = self.gfx().depth.as_ref().map(|o| o.vars[0]); + if let (true, Some(var)) = (en & 1 == 1, dv) { + self.set_out(var, srcs[0]); + } + } + 9 => {} + _ => return err(d, "export target"), + } + if done { + self.gfx().ps_done = true; + let lv = self.gfx().live_var; + let one = self.c(1); + self.set_out(lv, one); + } + Ok(()) + } + + /// `v_interp_*`: the attribute comes interpolated from the PC rasteriser. + pub fn interp_gfx(&mut self, d: &Decoded, name: &str) -> LResult<()> { + let Some(ps) = self.gfx.as_ref().and_then(|g| g.ps.clone()) else { return err(d, "interpolation outside PS") }; + let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); + let (vdst, ij, attr, chan) = if d.enc.name == "ENC_VINTRP" { + (f("VDST"), f("VSRC"), f("ATTR"), f("ATTRCHAN")) + } else { + let s1 = f("SRC1"); + (f("VDST"), if s1 >= 256 { s1 - 256 } else { s1 }, f("SRC0") & 0x3F, f("SRC0") >> 6 & 3) + }; + let Some(slot) = ps_attribute_slot(&ps, attr as usize, chan as usize) else { return err(d, "attribute outside ISG1") }; + let load = |lw: &mut Lw| -> Value { + let g = lw.gfx.as_mut().expect("gfx"); + let (sig, _) = g.ps_in[slot]; + let x = g.io.load_input(&mut lw.s, sig, 0, chan as u8); + let i32 = lw.s.m.i32(); + lw.s.m.bitcast(x, i32) + }; + let dst = super::lower::Dst::V(vdst); + match name { + "v_interp_p1_f32" | "v_interp_p1ll_f16" | "v_interp_p1lv_f16" => {} + "v_interp_p2_f32" => { + let v = load(self); + self.write32(&dst, v); + } + "v_interp_mov_f32" => { + if ij != 2 { + return err(d, "v_interp_mov p10/p20"); + } + let v = load(self); + self.write32(&dst, v); + } + "v_interp_p2_f16" => { + let x = load(self); + let xf = self.f(x); + let h = self.to_f16(xf); + let cur = self.vreg(vdst); + let hi = rdna2::field_value(d.enc, &d.words, "OP_SEL").unwrap_or(0) >> 3 & 1 == 1; + let v = if hi { + let l = self.andc(cur, 0xFFFF); + let hs = self.shlc(h, 16); + self.or(l, hs) + } else { + let hh = self.andc(cur, 0xFFFF_0000); + self.or(hh, h) + }; + self.write32(&dst, v); + } + _ => return err(d, "interpolation"), + } + Ok(()) + } +} diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs new file mode 100644 index 000000000..fd93832e6 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -0,0 +1,879 @@ +//! Image (MIMG) lowering: samples, gathers, loads, stores, atomics and +//! resource info through descriptor-heap views (T# word 0 = SRV heap index, +//! the UAV at the next index; S# word 3 [11:0] = sampler heap index), and +//! `image_bvh(64)_intersect_ray` on the flat memory (port of +//! `recomp/emit.rs` `mimg` and `bvh_intersect`; compute rules: no implicit +//! derivatives, so implicit-LOD samples take LOD 0 / the bias). + +use super::lower::{err, LResult, Lw, VAR_VGPR}; +use super::module::{BinOp, Pred, Value}; +use super::ops::{AtomicOp, CompType, Sampler, TexKind, Texture}; +use super::ops_core::op; +use crate::gpu::rdna2::{self, Decoded}; + +impl Lw { + fn f3(&mut self, a: [Value; 3], b: [Value; 3], op: fn(&mut Lw, Value, Value) -> Value) -> [Value; 3] { + [op(self, a[0], b[0]), op(self, a[1], b[1]), op(self, a[2], b[2])] + } + fn cross(&mut self, a: [Value; 3], b: [Value; 3]) -> [Value; 3] { + let x0 = self.fmul(a[1], b[2]); + let x1 = self.fmul(a[2], b[1]); + let x = self.fsub(x0, x1); + let y0 = self.fmul(a[2], b[0]); + let y1 = self.fmul(a[0], b[2]); + let y = self.fsub(y0, y1); + let z0 = self.fmul(a[0], b[1]); + let z1 = self.fmul(a[1], b[0]); + let z = self.fsub(z0, z1); + [x, y, z] + } + /// HLSL `dot(float3, float3)` = `Dot3`. + fn dot3(&mut self, a: [Value; 3], b: [Value; 3]) -> Value { + let f32 = self.s.m.f32(); + self.s.op(55, "dot3", Some(f32), f32, &[a[0], a[1], a[2], b[0], b[1], b[2]], super::module::FnAttrs::ReadNone) + } + fn load3f(&mut self, at: Value) -> [Value; 3] { + let mut r = [at; 3]; + for (k, slot) in r.iter_mut().enumerate() { + let a = self.addc(at, 4 * k as u32); + let v = self.mem_ld(a); + *slot = self.f(v); + } + r + } + + /// `bvh_intersect`: one BVH node → 4 result dwords (written to temporaries). + #[allow(clippy::too_many_arguments)] + fn bvh_intersect(&mut self, ty: Value, at: Value, tmax: Value, o: [Value; 3], dir: [Value; 3], inv: [Value; 3], sort: Value, out: [u32; 4]) -> LResult<()> { + let ones = self.c(u32::MAX); + for &t in &out { + self.wr(t, ones); + } + for box32 in [true, false] { + let is = self.cmpc(Pred::Eq, ty, if box32 { 5 } else { 4 }); + self.guarded(is, &mut |lw| { + let mut child = [ones; 4]; + for (k, c) in child.iter_mut().enumerate() { + let a = lw.addc(at, 4 * k as u32); + *c = lw.mem_ld(a); + } + let ninf = lw.s.m.f32c(0xFF80_0000); + let pinf = lw.s.m.f32c(0x7F80_0000); + let mut tn = [pinf; 4]; + let mut id = [ones; 4]; + for k in 0..4u32 { + let (mn, mx) = if box32 { + let a = lw.addc(at, 16 + 24 * k); + let b = lw.addc(at, 28 + 24 * k); + (lw.load3f(a), lw.load3f(b)) + } else { + let a = lw.addc(at, 16 + 12 * k); + let mut h = [ones; 3]; + for (j, slot) in h.iter_mut().enumerate() { + let x = lw.addc(a, 4 * j as u32); + *slot = lw.mem_ld(x); + } + let hx16 = lw.lshrc(h[0], 16); + let hy16 = lw.lshrc(h[1], 16); + let hz16 = lw.lshrc(h[2], 16); + let mn = [lw.s.f16_to_f32(h[0]), lw.s.f16_to_f32(hx16), lw.s.f16_to_f32(h[1])]; + let mx = [lw.s.f16_to_f32(hy16), lw.s.f16_to_f32(h[2]), lw.s.f16_to_f32(hz16)]; + (mn, mx) + }; + let d1 = lw.f3(mn, o, Lw::fsub); + let t1 = lw.f3(d1, inv, Lw::fmul); + let d2 = lw.f3(mx, o, Lw::fsub); + let t2 = lw.f3(d2, inv, Lw::fmul); + let mut lo = [pinf; 3]; + let mut hi = [pinf; 3]; + for c in 0..3 { + let ge = lw.fcmp(Pred::FOGe, o[c], mn[c]); + let le = lw.fcmp(Pred::FOLe, o[c], mx[c]); + let slab = lw.land(ge, le); + let ii = lw.isinf(inv[c]); + let l0 = lw.sel(slab, ninf, pinf); + let h0 = lw.sel(slab, pinf, ninf); + let mn_t = lw.fmin(t1[c], t2[c]); + let mx_t = lw.fmax(t1[c], t2[c]); + lo[c] = lw.sel(ii, l0, mn_t); + hi[c] = lw.sel(ii, h0, mx_t); + } + let a = lw.fmax(lo[0], lo[1]); + let a = lw.fmax(a, lo[2]); + let b = lw.fmin(hi[0], hi[1]); + let b = lw.fmin(b, hi[2]); + let cv = lw.cmpc(Pred::Ne, child[k as usize], u32::MAX); + let mut all = cv; + for c in 0..3 { + let le = lw.fcmp(Pred::FOLe, mn[c], mx[c]); + all = lw.land(all, le); + } + let ab = lw.fcmp(Pred::FOLe, a, b); + let z = lw.fc(0.0); + let b0 = lw.fcmp(Pred::FOGe, b, z); + let at_ = lw.fcmp(Pred::FOLe, a, tmax); + let hit = lw.land(all, ab); + let x = lw.land(b0, at_); + let hit = lw.land(hit, x); + tn[k as usize] = lw.sel(hit, a, pinf); + id[k as usize] = lw.sel(hit, child[k as usize], ones); + } + for (i, j) in [(0usize, 1usize), (2, 3), (0, 2), (1, 3), (1, 2)] { + let lt = lw.fcmp(Pred::FOLt, tn[j], tn[i]); + let sw = lw.land(sort, lt); + let (ti, tj) = (lw.sel(sw, tn[j], tn[i]), lw.sel(sw, tn[i], tn[j])); + let (ii, ij) = (lw.sel(sw, id[j], id[i]), lw.sel(sw, id[i], id[j])); + tn[i] = ti; + tn[j] = tj; + id[i] = ii; + id[j] = ij; + } + for k in 0..4 { + lw.wr(out[k], id[k]); + } + Ok(()) + })?; + } + let tri = self.cmpc(Pred::ULe, ty, 3); + self.guarded(tri, &mut |lw| { + let t1 = lw.cmpc(Pred::Eq, ty, 1); + let k0 = lw.c(0); + let a0 = lw.selc(t1, 12, k0); + let k36 = lw.c(36); + let k12 = lw.c(12); + let a1 = lw.sel(t1, k36, k12); + let p0 = lw.add(at, a0); + let p1 = lw.add(at, a1); + let p2 = lw.addc(at, 24); + let v0 = lw.load3f(p0); + let v1 = lw.load3f(p1); + let v2 = lw.load3f(p2); + let e1 = lw.f3(v1, v0, Lw::fsub); + let e2 = lw.f3(v2, v0, Lw::fsub); + let p = lw.cross(dir, e2); + let det = lw.dot3(e1, p); + let sv = lw.f3(o, v0, Lw::fsub); + let q = lw.cross(sv, e1); + let i = lw.dot3(sv, p); + let j = lw.dot3(dir, q); + let t = lw.dot3(e2, q); + let z = lw.fc(0.0); + let ij = lw.fadd(i, j); + let dpos = lw.fcmp(Pred::FOGt, det, z); + let c1 = lw.fcmp(Pred::FOGe, i, z); + let c2 = lw.fcmp(Pred::FOGe, j, z); + let c3 = lw.fcmp(Pred::FOLe, ij, det); + let hp = lw.land(c1, c2); + let hp = lw.land(hp, c3); + let dneg = lw.fcmp(Pred::FOLt, det, z); + let n1 = lw.fcmp(Pred::FOLe, i, z); + let n2 = lw.fcmp(Pred::FOLe, j, z); + let n3 = lw.fcmp(Pred::FOGe, ij, det); + let hn = lw.land(dneg, n1); + let hn = lw.land(hn, n2); + let hn = lw.land(hn, n3); + let hit = lw.sel(dpos, hp, hn); + let di = lw.fsub(det, i); + let b0 = lw.fsub(di, j); + let bc = [b0, i, j, z]; + let p60 = lw.addc(at, 60); + let tw = lw.mem_ld(p60); + let sh = lw.shlc(ty, 3); + let tid = lw.shr_masked(tw, sh); + let s0 = lw.andc(tid, 3); + let s1 = lw.lshrc(tid, 2); + let s1 = lw.andc(s1, 3); + let bci = lw.pick4f(&bc, s0); + let bcj = lw.pick4f(&bc, s1); + let res = [lw.bits(t), lw.bits(det), lw.bits(bci), lw.bits(bcj)]; + let miss = [lw.c(0x7F80_0000), lw.c(0x3F80_0000), lw.c(0), lw.c(0)]; + for k in 0..4 { + let v = lw.sel(hit, res[k], miss[k]); + lw.wr(out[k], v); + } + Ok(()) + }) + } + fn shr_masked(&mut self, a: Value, s: Value) -> Value { + self.lshr(a, s) + } + fn pick4f(&mut self, r: &[Value; 4], i: Value) -> Value { + let mut v = r[3]; + for k in (0..3).rev() { + let is = self.cmpc(Pred::Eq, i, k); + v = self.sel(is, r[k as usize], v); + } + v + } + + /// `cube_dir`: AMD cube coordinates (sc/|2ma| + 1.5, tc/|2ma| + 1.5, face) → direction. + fn cube_dir(&mut self, s: Value, t: Value, face: Value) -> [Value; 3] { + let k15 = self.fc(1.5); + let k2 = self.fc(2.0); + let u = self.fsub(s, k15); + let u = self.fmul(u, k2); + let v = self.fsub(t, k15); + let v = self.fmul(v, k2); + let r = self.un(op::ROUND_NE, face); + let fi = self.ftoui(r); + let f = self.andc(fi, 7); + let one = self.fc(1.0); + let m1 = self.fc(-1.0); + let nu = self.fneg(u); + let nv = self.fneg(v); + // faces 0..5 (anything else as 5) + let table: [[Value; 3]; 6] = [[one, nv, nu], [m1, nv, u], [u, one, v], [u, m1, nv], [u, nv, one], [nu, nv, m1]]; + let mut out = table[5]; + for k in (0..5).rev() { + let is = self.cmpc(Pred::Eq, f, k as u32); + for c in 0..3 { + out[c] = self.sel(is, table[k][c], out[c]); + } + } + out + } + + /// The cube of a cube-array coordinate: face + 8 · cube → cube (as float). + fn cube_slice(&mut self, face: Value) -> Value { + let r = self.un(op::ROUND_NE, face); + let fi = self.ftoui(r); + let c = self.lshrc(fi, 3); + self.uitof(c) + } + + pub fn mimg(&mut self, d: &Decoded, name: &str) -> LResult<()> { + let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); + if f("TFE") != 0 || f("LWE") != 0 { + return err(d, "MIMG tfe/lwe"); + } + let (a16, d16) = (f("A16") == 1, f("D16") == 1); + let dim = f("DIM"); + let dmask = f("DMASK"); + let (vdata, srsrc, ssamp) = (f("VDATA"), Self::field(d, "SRSRC"), Self::field(d, "SSAMP")); + let nsa = f("NSA"); + let nsa_enc = rdna2::encoding(&format!("MIMG_NSA{nsa}")); + let addr_reg = |j: u64| -> u64 { + match nsa_enc { + Some(e) if nsa > 0 && j > 0 => { + let letter = (b'A' + (j - 1).min(25) as u8) as char; + rdna2::field_value(e, &d.words, &format!("VADDR{letter}")).unwrap_or(0) + } + _ => f("VADDR") + j, + } + }; + let base = name.trim_start_matches("image_"); + if base == "bvh_intersect_ray" || base == "bvh64_intersect_ray" { + let wide = base == "bvh64_intersect_ray"; + let r = |lw: &mut Lw, j: u64| lw.vreg(addr_reg(j)); + let node = r(self, 0); + let node_hi = if wide { Some(r(self, 1)) } else { None }; + let k = if wide { 2 } else { 1 }; + let fl = |lw: &mut Lw, j: u64| { + let v = lw.vreg(addr_reg(j)); + lw.f(v) + }; + let extent = fl(self, k); + let origin = [fl(self, k + 1), fl(self, k + 2), fl(self, k + 3)]; + let (dir, inv) = if a16 { + let (h0, h1, h2) = (r(self, k + 4), r(self, k + 5), r(self, k + 6)); + let h0s = self.lshrc(h0, 16); + let h1s = self.lshrc(h1, 16); + let h2s = self.lshrc(h2, 16); + ( + [self.s.f16_to_f32(h0), self.s.f16_to_f32(h0s), self.s.f16_to_f32(h1)], + [self.s.f16_to_f32(h1s), self.s.f16_to_f32(h2), self.s.f16_to_f32(h2s)], + ) + } else { + ([fl(self, k + 4), fl(self, k + 5), fl(self, k + 6)], [fl(self, k + 7), fl(self, k + 8), fl(self, k + 9)]) + }; + let (d0, d1) = (self.sreg(srsrc), self.sreg(srsrc + 1)); + // address: ((d1 & 0xFF) << 32 | d0) << 8 + node offset (8-byte units); low 32 bits + let nlo = self.andc(node, !7); + let base_lo = self.shlc(d0, 8); + let off_lo = self.shlc(nlo, 3); + let a = self.add(base_lo, off_lo); + // the window: bits 32.. of the 64-bit address + if self.mems.len() > 1 { + let d1lo = self.andc(d1, 0xFF); + let b64 = self.pack64(d0, d1lo); + let k8 = self.c64(8); + let b64 = self.bin(BinOp::Shl, b64, k8); + let nlo64 = self.zext64(nlo); + let off = match node_hi { + Some(hi) => { + let h64 = self.zext64(hi); + let k32 = self.c64(32); + let h64 = self.bin(BinOp::Shl, h64, k32); + self.or(h64, nlo64) + } + None => nlo64, + }; + let k3 = self.c64(3); + let off = self.bin(BinOp::Shl, off, k3); + let full = self.add(b64, off); + let (_, hi) = self.unpack64(full); + self.window(hi); + } + let ty = self.andc(node, 7); + let sort = { + let s = self.lshrc(d1, 31); + self.nz(s) + }; + let act = self.act(); + let out = [self.tmp_var(), self.tmp_var(), self.tmp_var(), self.tmp_var()]; + self.guarded(act, &mut |lw| { + lw.bvh_intersect(ty, a, extent, origin, dir, inv, sort, out)?; + for (c, &t) in out.iter().enumerate() { + let v = lw.rd(t); + lw.wr(VAR_VGPR + (vdata + c as u64) as u32, v); + } + Ok(()) + })?; + return Ok(()); + } + let body = [1u64, 2, 3, 3, 2, 3, 3, 4][dim as usize]; + let sampling = base.starts_with("sample") || base.starts_with("gather4"); + let rest = base.trim_start_matches("sample").trim_start_matches("gather4"); + let mods: Vec<&str> = if sampling { rest.split('_').filter(|x| !x.is_empty()).collect() } else { Vec::new() }; + let (has_cl, has_o) = (mods.contains(&"cl"), mods.contains(&"o")); + let (has_b, has_c, has_d, has_l, has_lz) = + (mods.contains(&"b"), mods.contains(&"c"), mods.contains(&"d") || mods.contains(&"cd"), mods.contains(&"l"), mods.contains(&"lz")); + let grad_n = if has_d { [1u64, 2, 3, 2, 1, 2, 2, 2][dim as usize] } else { 0 }; + let h = if a16 { 16 } else { 32 }; + let mut shape: Vec<(u32, bool)> = Vec::new(); + let (mut i_bias, mut i_cmp, mut i_grad, mut i_body, mut i_extra, mut i_clamp) = (None, None, 0usize, 0usize, None, None); + if sampling { + if has_o { + shape.push((32, true)); + } + if has_b { + i_bias = Some(shape.len()); + shape.push((h, !a16)); + } + if has_c { + i_cmp = Some(shape.len()); + shape.push((32, true)); + } + i_grad = shape.len(); + for _ in 0..2 * grad_n { + shape.push((32, true)); + } + i_body = shape.len(); + for k in 0..body { + shape.push((h, !a16 || (grad_n != 0 && k == 0))); + } + if has_l { + i_extra = Some(shape.len()); + shape.push((h, !a16)); + } + if has_cl { + i_clamp = Some(shape.len()); + shape.push((h, !a16)); + } + } else if base == "get_resinfo" { + i_extra = Some(0); + shape.push((32, true)); + } else { + i_body = 0; + for _ in 0..body { + shape.push((h, !a16)); + } + if base.ends_with("_mip") { + i_extra = Some(shape.len()); + shape.push((h, !a16)); + } + } + let mut pos: Vec<(u64, Option)> = Vec::new(); + let mut cursor = 0u64; + for &(w, starts) in &shape { + if (w == 32 || starts) && cursor % 2 == 1 { + cursor += 1; + } + pos.push((cursor / 2, (w == 16).then_some(cursor % 2))); + cursor += if w == 32 { 2 } else { 1 }; + } + let compu = |lw: &mut Lw, i: usize| -> Value { + let (dw, half) = pos[i]; + let v = lw.vreg(addr_reg(dw)); + match half { + None => v, + Some(hh) => { + let x = lw.lshrc(v, 16 * hh as u32); + lw.andc(x, 0xFFFF) + } + } + }; + let compf = |lw: &mut Lw, i: usize| -> Value { + let (dw, half) = pos[i]; + let v = lw.vreg(addr_reg(dw)); + match half { + None => lw.f(v), + Some(hh) => { + let x = lw.lshrc(v, 16 * hh as u32); + let x = lw.andc(x, 0xFFFF); + lw.s.f16_to_f32(x) + } + } + }; + let tw0 = self.sreg(srsrc); + let tw1 = self.sreg(srsrc + 1); + let act = self.act(); + let comps: Vec = (0..4).filter(|c| dmask >> c & 1 == 1).collect(); + let kind = match dim { + 0 => TexKind::D1, + 1 => TexKind::D2, + 2 => TexKind::D3, + // cube T#s are cube arrays (face + 8 · cube), as the HLSL path's TextureCubeArray + 3 => TexKind::CubeArray, + 4 => TexKind::D1Array, + 5 => TexKind::D2Array, + _ => return err(d, "MIMG dim"), + }; + + if sampling { + if f("UNORM") != 0 && dim != 3 { + return err(d, "MIMG unorm"); + } + let bias = i_bias.map(|i| compf(self, i)); + let cmp = i_cmp.map(|i| compf(self, i)); + let grads = if has_d { + let dx: Vec = (0..grad_n as usize).map(|k| compf(self, i_grad + k)).collect(); + let dy: Vec = (0..grad_n as usize).map(|k| compf(self, i_grad + grad_n as usize + k)).collect(); + Some((dx, dy)) + } else { + None + }; + let mut coords: Vec = (0..body as usize).map(|k| compf(self, i_body + k)).collect(); + let lod = i_extra.map(|i| compf(self, i)); + let cl = i_clamp.map(|i| compf(self, i)); + let s3 = self.sreg(ssamp + 3); + let gather = base.starts_with("gather4"); + let ovgpr = if has_o { + if dim == 3 { + return err(d, "MIMG offset cube"); + } + Some(compu(self, 0)) + } else { + None + }; + let ps = self.gfx.as_ref().is_some_and(|g| g.ps.is_some()); + let spatial: Vec = coords[..kind.grads().min(coords.len())].to_vec(); + let tex = self.s.heap_texture(tw0, kind, false, CompType::F32, 4, true); + let smp: Sampler = match self.static_samplers.get(&d.pc).copied() { + // the console's static samplers: bound at s, space1 in order of first use + Some(w) => match self.static_used.iter().find(|u| u.0 == w && u.1 == has_c) { + Some(u) => u.2, + None => { + let k = self.static_used.len() as u32; + let cur = self.cur(); + self.s.m.set_block(self.init.entry); + let h = self.s.sampler(self.sampler_base + k, 1, has_c); + self.s.m.set_block(cur); + self.static_used.push((w, has_c, h)); + h + } + }, + None => { + let si = self.andc(s3, 0xFFF); + self.s.heap_sampler(si, has_c, true) + } + }; + if let Some(o) = ovgpr { + // texel offset / size of the sampled mip (0 for lz / gather; else the LOD given, else 0) + let level = match (&lod, has_lz || gather) { + (_, true) => self.c(0), + (Some(l), _) => { + let r = self.un(op::ROUND_NE, *l); + let z = self.fc(0.0); + let r = self.fmax(r, z); + self.ftoui(r) + } + // the implicit LOD of a pixel shader's sample, rounded + (None, false) if ps && grads.is_none() && !has_c => { + let l = self.s.calculate_lod(tex, smp, &spatial, true); + let r = self.un(op::ROUND_NE, l); + let z = self.fc(0.0); + let r = self.fmax(r, z); + self.ftoui(r) + } + _ => self.c(0), + }; + let dims = self.s.get_dimensions(tex.handle, Some(level)); + let one = self.c(1); + let (w, hh, dd) = match dim { + 0 => (self.s.m.extract(dims, 0), one, one), + 1 => (self.s.m.extract(dims, 0), self.s.m.extract(dims, 1), one), + 2 => (self.s.m.extract(dims, 0), self.s.m.extract(dims, 1), self.s.m.extract(dims, 2)), + 4 => (self.s.m.extract(dims, 0), one, one), + _ => (self.s.m.extract(dims, 0), self.s.m.extract(dims, 1), one), + }; + let mut ofs = Vec::new(); + for (sh, size) in [(26u32, w), (18, hh), (10, dd)] { + let x = self.shlc(o, sh); + let x = self.ashrc(x, 26); + let xf = self.sitof(x); + let sf = self.uitof(size); + ofs.push(self.fdiv(xf, sf)); + } + for (k, c) in coords.iter_mut().enumerate() { + if (dim == 4 && k == 1) || (dim == 5 && k == 2) { + continue; + } + *c = self.fadd(*c, ofs[k]); + } + } + // array layers are rounded; cube coordinates become a direction and a cube index + let coord: Vec = match dim { + 3 => { + let mut v = self.cube_dir(coords[0], coords[1], coords[2]).to_vec(); + v.push(self.cube_slice(coords[2])); + v + } + 4 => vec![coords[0], self.un(op::ROUND_NE, coords[1])], + 5 => vec![coords[0], coords[1], self.un(op::ROUND_NE, coords[2])], + _ => coords.clone(), + }; + let floor = |lw: &mut Lw, l: Value| match cl { + Some(c) => lw.fmax(l, c), + None => l, + }; + let r: [Value; 4] = if gather { + if comps.len() != 1 { + return err(d, "gather4 dmask"); + } + match cmp { + Some(z) => self.s.gather_cmp(tex, smp, &coord, &[], comps[0] as u32, z), + None => self.s.gather(tex, smp, &coord, &[], comps[0] as u32), + } + } else { + match (&cmp, &grads, &lod, &bias) { + (Some(z), _, _, _) if has_lz || !ps => { + let v = self.s.sample_cmp_level_zero(tex, smp, &coord, &[], *z); + [v[0]; 4] + } + (Some(z), _, _, _) => { + let v = self.s.sample_cmp(tex, smp, &coord, &[], *z, if dim == 3 { None } else { cl }); + [v[0]; 4] + } + (None, Some((dx, dy)), _, _) if dim == 3 => { + let len = |lw: &mut Lw, x: &[Value]| { + let a = lw.fmul(x[0], x[0]); + let b = x.get(1).copied().unwrap_or_else(|| lw.fc(0.0)); + let bb = lw.fmul(b, b); + let s = lw.fadd(a, bb); + lw.un(op::SQRT, s) + }; + let z = self.c(0); + let dims = self.s.get_dimensions(tex.handle, Some(z)); + let size = self.s.m.extract(dims, 0); + let lx = len(self, dx); + let ly = len(self, dy); + let m = self.fmax(lx, ly); + let sf = self.uitof(size); + let m = self.fmul(m, sf); + let eps = self.fc(1e-8); + let m = self.fmax(m, eps); + let l = self.un(op::LOG, m); + let l = floor(self, l); + self.s.sample_level(tex, smp, &coord, &[], l) + } + (None, Some((dx, dy)), _, _) => self.s.sample_grad(tex, smp, &coord, &[], dx, dy, cl), + (None, None, Some(l), _) => self.s.sample_level(tex, smp, &coord, &[], *l), + (None, None, None, Some(b)) if ps => self.s.sample_bias(tex, smp, &coord, &[], *b, if dim == 3 { None } else { cl }), + (None, None, None, Some(b)) => { + let l = floor(self, *b); + self.s.sample_level(tex, smp, &coord, &[], l) + } + _ if has_lz || !ps => { + let z = self.fc(0.0); + let l = floor(self, z); + self.s.sample_level(tex, smp, &coord, &[], l) + } + _ => self.s.sample(tex, smp, &coord, &[], if dim == 3 { None } else { cl }), + } + }; + let rb: Vec = r.iter().map(|&v| self.bits(v)).collect(); + let n = if gather { 4 } else { comps.len() }; + let sel: Vec = (0..n).map(|k| if gather { k } else { comps[k] as usize }).collect(); + let vals: Vec = sel + .iter() + .map(|&c| { + if d16 { + // f32tof16(asfloat(e)) + self.s.f32_to_f16(r[c]) + } else { + rb[c] + } + }) + .collect(); + return self.image_result(vdata, &vals, d16, act); + } + + if base == "get_lod" { + if !self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) { + return err(d, "image_get_lod outside PS"); + } + if self.static_samplers.contains_key(&d.pc) { + return err(d, "image_get_lod with a static sampler"); + } + let coords: Vec = (0..body as usize).map(|k| compf(self, i_body + k)).collect(); + let spatial: Vec = match dim { + 3 => self.cube_dir(coords[0], coords[1], coords[2]).to_vec(), + _ => coords[..kind.grads().min(coords.len())].to_vec(), + }; + let s3 = self.sreg(ssamp + 3); + let tex = self.s.heap_texture(tw0, kind, false, CompType::F32, 4, true); + let si = self.andc(s3, 0xFFF); + let smp = self.s.heap_sampler(si, false, true); + let a = self.s.calculate_lod(tex, smp, &spatial, true); + let b = self.s.calculate_lod(tex, smp, &spatial, false); + let z = self.c(0); + let r = [self.bits(a), self.bits(b), z, z]; + let vals: Vec = comps.iter().map(|&c| if d16 { + let f = self.f(r[c as usize]); + self.s.f32_to_f16(f) + } else { + r[c as usize] + }).collect(); + return self.image_result(vdata, &vals, d16, act); + } + + if base == "get_resinfo" { + let mipv = compu(self, 0); + let tex = self.s.heap_texture(tw0, kind, false, CompType::F32, 4, true); + let dims = self.s.get_dimensions(tex.handle, Some(mipv)); + let one = self.c(1); + let e = |lw: &mut Lw, i: u32| lw.s.m.extract(dims, i); + // HLSL GetDimensions outputs per dim; missing ones are 1 + let (w, hh, dd, n) = match dim { + 0 => (e(self, 0), one, one, e(self, 3)), + 1 => (e(self, 0), e(self, 1), one, e(self, 3)), + // a cube array: its layers are faces, 6 per cube + 3 => { + let n = e(self, 2); + { + let k = self.c(6); + (e(self, 0), e(self, 1), self.mul(n, k), e(self, 3)) + } + } + 2 | 5 => (e(self, 0), e(self, 1), e(self, 2), e(self, 3)), + _ => (e(self, 0), one, e(self, 1), e(self, 3)), + }; + let r = [w, hh, dd, n]; + let vals: Vec = comps.iter().map(|&c| r[c as usize]).collect(); + return self.image_result(vdata, &vals, false, act); + } + + let ic: Vec = (0..body as usize).map(|k| compu(self, i_body + k)).collect(); + let mip = i_extra.map(|i| compu(self, i)).unwrap_or_else(|| self.c(0)); + if dim == 3 && base.starts_with("load") { + return err(d, "image_load cube"); + } + let lkind = if dim == 3 { TexKind::D2Array } else { kind }; + // class of the T# format: 1 uint, 2 sint, 0 float + let fmt = self.lshrc(tw1, 20); + let fmt = self.andc(fmt, 0x1FF); + let cls = self.img_cls(fmt); + match base { + "load" | "load_mip" => { + let tmps = [self.tmp_var(), self.tmp_var(), self.tmp_var(), self.tmp_var()]; + let z = self.c(0); + for &t in &tmps { + self.wr(t, z); + } + for (cv, ct) in [(1u32, CompType::U32), (2, CompType::I32), (0, CompType::F32)] { + let is = self.cmpc(Pred::Eq, cls, cv); + self.guarded(is, &mut |lw| { + let tex: Texture = lw.s.heap_texture(tw0, lkind, false, ct, 4, true); + let r = lw.s.texture_load(tex, Some(mip), &ic, &[]); + for k in 0..4 { + let b = lw.bits(r[k]); + lw.wr(tmps[k], b); + } + Ok(()) + })?; + } + let r: Vec = tmps.iter().map(|&t| self.rd(t)).collect(); + let vals: Vec = if d16 { + // float: f32tof16, else the low 16 bits + comps + .iter() + .map(|&c| { + let x = r[c as usize]; + 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 { + comps.iter().map(|&c| r[c as usize]).collect() + }; + self.image_result(vdata, &vals, d16, act) + } + "store" => { + let z = self.c(0); + let mut vals = [z; 4]; + for c in 0..4u64 { + if let Some(k) = comps.iter().position(|&x| x == c) { + vals[c as usize] = if d16 { + let v = self.vreg(vdata + k as u64 / 2); + let hp = self.lshrc(v, 16 * (k as u32 % 2)); + let hp = self.andc(hp, 0xFFFF); + let fh = self.s.f16_to_f32(hp); + let fb = self.bits(fh); + let fl = self.cmpc(Pred::Eq, cls, 0); + self.sel(fl, fb, hp) + } else { + self.vreg(vdata + k as u64) + }; + } + } + let ui = self.addc(tw0, 1); + for (cv, ct) in [(1u32, CompType::U32), (2, CompType::I32), (0, CompType::F32)] { + let is = self.cmpc(Pred::Eq, cls, cv); + let c = self.land(act, is); + self.guarded(c, &mut |lw| { + let tex = lw.s.heap_texture(ui, lkind, true, ct, 4, true); + let v4 = if ct == CompType::F32 { vals.map(|v| lw.f(v)) } else { vals }; + lw.s.texture_store(tex, &ic, v4); + Ok(()) + })?; + } + Ok(()) + } + _ if base.starts_with("atomic_") => { + let opn = &base[7..]; + let (v, cmpv) = (self.vreg(vdata), self.vreg(vdata + 1)); + let glc = f("GLC") == 1; + let ui = self.addc(tw0, 1); + let signed = opn == "smin" || opn == "smax"; + let ct = if signed { CompType::I32 } else { CompType::U32 }; + let aop = match opn { + "add" => Some(AtomicOp::Add), + "smin" => Some(AtomicOp::IMin), + "umin" => Some(AtomicOp::UMin), + "smax" => Some(AtomicOp::IMax), + "umax" => Some(AtomicOp::UMax), + "and" => Some(AtomicOp::And), + "or" => Some(AtomicOp::Or), + "xor" => Some(AtomicOp::Xor), + "swap" => Some(AtomicOp::Exchange), + "cmpswap" | "fcmpswap" | "sub" | "inc" | "dec" | "fmin" | "fmax" => None, + _ => return err(d, "image_atomic"), + }; + let tmp = self.tmp_var(); + let z = self.c(0); + self.wr(tmp, z); + let opn = opn.to_string(); + let ic2 = ic.clone(); + self.guarded(act, &mut |lw| { + let tex = lw.s.heap_texture(ui, lkind, true, ct, 1, true); + let old = match aop { + Some(o) => lw.s.atomic_binop(tex.handle, o, &ic2, v), + None if opn == "cmpswap" || opn == "fcmpswap" => lw.s.atomic_cmpxchg(tex.handle, &ic2, cmpv, v), + None => lw.texel_cas(tex.handle, &ic2, &opn, v), + }; + lw.wr(tmp, old); + Ok(()) + })?; + if glc { + let old = self.rd(tmp); + let a = self.act(); + let cur = self.vreg(vdata); + let nv = self.sel(a, old, cur); + self.wr(VAR_VGPR + vdata as u32, nv); + } + Ok(()) + } + _ => err(d, "MIMG"), + } + } + + /// 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 + let z = self.c(0); + let init = self.s.atomic_binop(h, AtomicOp::Or, ic, z); + let pre = self.cur(); + let lp = self.block(Some(2)); + let ex = self.block(Some(1)); + self.br(lp); + self.s.m.set_block(lp); + let i32 = self.s.m.i32(); + let c = self.s.m.phi(i32); + let i = self.s.m.phi(i32); + self.s.m.add_incoming(c, init, pre); + self.s.m.add_incoming(i, z, pre); + let n = match opn { + "sub" => self.sub(c, v), + "inc" => { + let ge = self.cmp(Pred::UGe, c, v); + let c1 = self.addc(c, 1); + self.selc(ge, 0, c1) + } + "dec" => { + let cz = self.cmpc(Pred::Eq, c, 0); + let gt = self.cmp(Pred::UGt, c, v); + let w = self.lor(cz, gt); + let one = self.c(1); + let c1 = self.sub(c, one); + self.sel(w, v, c1) + } + _ => { + let (x, y) = (self.f(c), self.f(v)); + let r = if opn == "fmin" { self.fmin(x, y) } else { self.fmax(x, y) }; + self.bits(r) + } + }; + let p = self.s.atomic_cmpxchg(h, ic, c, n); + let ok = self.cmp(Pred::Eq, p, c); + let i1 = self.addc(i, 1); + let out = self.cmpc(Pred::UGe, i1, 4096); + let stop = self.lor(ok, out); + let me = self.cur(); + self.s.m.add_incoming(c, p, me); + self.s.m.add_incoming(i, i1, me); + self.cond_br(stop, ex, lp); + self.s.m.set_block(ex); + p + } + + /// `img_cls`: 1 uint, 2 sint, 0 float (by the buffer-format table's numeric type). + fn img_cls(&mut self, fmt: Value) -> Value { + let info = self.fmt_info(fmt); + let ty = self.lshrc(info, 3); + let ty = self.andc(ty, 7); + let big = self.cmpc(Pred::UGt, fmt, 77); + let k6 = self.c(6); + let ty = self.sel(big, k6, ty); + let t4 = self.cmpc(Pred::Eq, ty, 4); + let t5 = self.cmpc(Pred::Eq, ty, 5); + let two = self.c(2); + let z = self.c(0); + let r = self.sel(t5, two, z); + self.selc(t4, 1, r) + } + + /// Writes result components to VDATA (D16: two halves per VGPR) in active lanes. + fn image_result(&mut self, vdata: u64, vals: &[Value], d16: bool, act: Value) -> LResult<()> { + let mut out = Vec::new(); + if d16 { + for k in (0..vals.len()).step_by(2) { + let lo = self.andc(vals[k], 0xFFFF); + let hi = if k + 1 < vals.len() { vals[k + 1] } else { self.c(0) }; + let hi = self.shlc(hi, 16); + out.push(self.or(lo, hi)); + } + } else { + out = vals.to_vec(); + } + for (k, v) in out.into_iter().enumerate() { + let old = self.vreg(vdata + k as u64); + let nv = self.sel(act, v, old); + self.wr(VAR_VGPR + (vdata + k as u64) as u32, nv); + } + Ok(()) + } +} diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs new file mode 100644 index 000000000..9b80d1222 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -0,0 +1,1945 @@ +//! Memory lowering: scalar loads, buffer / typed buffer, flat / global, LDS, +//! atomics and kernel exports on the kernel ABI's flat `mem` window (port of +//! `recomp/emit.rs` `smem` / `mubuf` / `flat` / `ds` / `export` and +//! `PRELUDE_MEM`). Accesses of disabled lanes are real branches. + +use super::lower::{err, Dst, LResult, Lw, VAR_VGPR}; +use super::module::{BinOp, Pred, RmwOp, Value}; +use super::ops::AtomicOp; +use super::shader::RawUav; +use crate::gpu::rdna2::{self, Decoded}; +use crate::gpu::recomp::emit::buf_format_info; +use crate::gpu::recomp::{KERNEL_EXPORTS, KERNEL_LANES}; + +/// Temporary SSA variables (merged across guarded blocks, never loaded / stored). +pub const VAR_TMP: u32 = 1024; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum BufKind { + Load, + Store, + FormatLoad, + FormatStore, +} + +fn buffer_op(name: &str) -> Option<(BufKind, u64)> { + let n = |suffix: &str| -> Option { + Some(match suffix { + "dword" | "x" => 1, + "dwordx2" | "xy" => 2, + "dwordx3" | "xyz" => 3, + "dwordx4" | "xyzw" => 4, + _ => return None, + }) + }; + if let Some(r) = name.strip_prefix("buffer_load_format_").or_else(|| name.strip_prefix("tbuffer_load_format_")) { + return Some((BufKind::FormatLoad, n(r)?)); + } + if let Some(r) = name.strip_prefix("buffer_store_format_").or_else(|| name.strip_prefix("tbuffer_store_format_")) { + return Some((BufKind::FormatStore, n(r)?)); + } + if let Some(r) = name.strip_prefix("buffer_load_") { + return Some((BufKind::Load, n(r)?)); + } + if let Some(r) = name.strip_prefix("buffer_store_") { + return Some((BufKind::Store, n(r)?)); + } + None +} + +fn buffer_format_d16(name: &str) -> Option<(BufKind, u64, bool)> { + let (kind, r) = if let Some(r) = name.strip_prefix("buffer_load_format_d16_").or_else(|| name.strip_prefix("tbuffer_load_format_d16_")) { + (BufKind::FormatLoad, r) + } else if let Some(r) = name.strip_prefix("buffer_store_format_d16_").or_else(|| name.strip_prefix("tbuffer_store_format_d16_")) { + (BufKind::FormatStore, r) + } else { + return None; + }; + let (components, high) = match r { + "x" => (1, false), + "xy" => (2, false), + "xyz" => (3, false), + "xyzw" => (4, false), + "hi_x" => (1, true), + _ => return None, + }; + Some((kind, components, high)) +} + +fn d16_small(op: &str) -> Option<(u32, bool, bool, u32)> { + Some(match op { + "load_ubyte_d16" => (1, false, false, 0), + "load_ubyte_d16_hi" => (1, false, false, 1), + "load_sbyte_d16" => (1, true, false, 0), + "load_sbyte_d16_hi" => (1, true, false, 1), + "load_short_d16" => (2, false, false, 0), + "load_short_d16_hi" => (2, false, false, 1), + "store_byte_d16_hi" => (1, false, true, 1), + "store_short_d16_hi" => (2, false, true, 1), + _ => return None, + }) +} + +fn flat_small(op: &str) -> Option<(u32, bool, bool, u32)> { + Some(match op { + "load_ubyte" => (1, false, false, 2), + "load_sbyte" => (1, true, false, 2), + "load_ushort" => (2, false, false, 2), + "load_sshort" => (2, true, false, 2), + "store_byte" => (1, false, true, 2), + "store_short" => (2, false, true, 2), + _ => return d16_small(op), + }) +} + +fn ds_d16(name: &str) -> Option<(u32, bool, bool, u32)> { + Some(match name { + "ds_read_u8_d16" => (8, false, false, 0), + "ds_read_u8_d16_hi" => (8, false, false, 1), + "ds_read_i8_d16" => (8, true, false, 0), + "ds_read_i8_d16_hi" => (8, true, false, 1), + "ds_read_u16_d16" => (16, false, false, 0), + "ds_read_u16_d16_hi" => (16, false, false, 1), + "ds_write_b8_d16_hi" => (8, false, true, 1), + "ds_write_b16_d16_hi" => (16, false, true, 1), + _ => return None, + }) +} + +/// Where a 32-bit atomic works. +#[derive(Clone, Copy)] +enum At { + Mem(Value), + Lds(Value), +} + +impl Lw { + /// Runs `f` on the memory window the last `window` selected (`mem`, `mem1`.. at u2..): + /// a switch over the windows when the program may address several, as the HLSL kernel's + /// `xcl_m*` accessors; returns `f`'s value (i32 or i64). + fn with_mem(&mut self, f: &mut dyn FnMut(&mut Lw, RawUav) -> Option) -> Option { + if self.mems.len() <= 1 { + let m = self.mems[0]; + return f(self, m); + } + let w = self.rd(super::lower::VAR_WIN); + let (tl, th) = (self.tmp_var(), self.tmp_var()); + let z = self.c(0); + self.wr(tl, z); + self.wr(th, z); + let mut kind = 0u8; // 0 none, 1 i32, 2 i64 + let mems = self.mems.clone(); + for (k, &m) in mems.iter().enumerate() { + // window 0 is the default (`switch` default: any value but 1..) + let is = if k == 0 { + let mut any = self.b(false); + for j in 1..mems.len() as u32 { + let e = self.cmpc(Pred::Eq, w, j); + any = self.lor(any, e); + } + self.lnot(any) + } else { + self.cmpc(Pred::Eq, w, k as u32) + }; + let _ = self.guarded(is, &mut |lw| { + if let Some(v) = f(lw, m) { + let t = lw.s.m.type_of(v); + if t == lw.s.m.i64() { + let (l, h) = lw.unpack64(v); + lw.wr(tl, l); + lw.wr(th, h); + kind = 2; + } else { + lw.wr(tl, v); + kind = 1; + } + } + Ok(()) + }); + } + match kind { + 0 => None, + 1 => Some(self.rd(tl)), + _ => { + let (l, h) = (self.rd(tl), self.rd(th)); + Some(self.pack64(l, h)) + } + } + } + /// `xcl_w = hi & 3` (several memory windows only). + pub fn window(&mut self, hi: Value) { + if self.mems.len() > 1 { + let v = self.andc(hi, 3); + self.wr(super::lower::VAR_WIN, v); + } + } + fn mraw_atomic(&mut self, op: AtomicOp, a: Value, v: Value) -> Value { + self.with_mem(&mut |lw, m| Some(lw.s.raw_atomic(m, op, a, v))).expect("atomic value") + } + fn mraw_cmpxchg(&mut self, a: Value, c: Value, n: Value) -> Value { + self.with_mem(&mut |lw, m| Some(lw.s.raw_cmpxchg(m, a, c, n))).expect("cmpxchg value") + } + /// `mem.Load(a & ~3)` + pub fn mem_ld(&mut self, a: Value) -> Value { + let a = self.andc(a, !3); + self.with_mem(&mut |lw, m| Some(lw.s.raw_load(m, a, 1)[0])).expect("load value") + } + /// `mem.Store(a & ~3, v)` + pub fn mem_st(&mut self, a: Value, v: Value) { + let a = self.andc(a, !3); + self.with_mem(&mut |lw, m| { + lw.s.raw_store(m, a, &[v]); + None + }); + } + + /// `ld_raw`: four dwords from an unaligned byte address. + fn ld_raw(&mut self, a: Value) -> [Value; 4] { + let b = self.andc(a, !3); + let s = self.andc(a, 3); + let s = self.shlc(s, 3); + let mut w = Vec::new(); + for k in 0..5 { + let at = self.addc(b, 4 * k); + w.push(self.mem_ld(at)); + } + let k32 = self.c(32); + let inv = self.sub(k32, s); + let inv = self.andc(inv, 31); + let sz = self.cmpc(Pred::Eq, s, 0); + let mut r = [w[0]; 4]; + for i in 0..4 { + let lo = self.bin(BinOp::LShr, w[i], s); + let hi = self.bin(BinOp::Shl, w[i + 1], inv); + let x = self.or(lo, hi); + r[i] = self.sel(sz, w[i], x); + } + r + } + /// `st_part`: atomically replace the bits `m` of the dword at `b` by `v`. + fn st_part(&mut self, b: Value, m: Value, v: Value) { + let nm = self.not(m); + self.mraw_atomic(AtomicOp::And, b, nm); + let vm = self.and(v, m); + self.mraw_atomic(AtomicOp::Or, b, vm); + } + /// `st_bytes`: store the low `n` bytes of `r` at byte address `a` (n ≤ 16; partial + /// dwords through atomics so neighbours stay intact). + fn st_bytes(&mut self, a: Value, r: [Value; 4], n: Value) -> LResult<()> { + let s = self.andc(a, 3); + let s = self.shlc(s, 3); + let b = self.andc(a, !3); + let sz = self.cmpc(Pred::Eq, s, 0); + let n3 = self.andc(n, 3); + let nz3 = self.cmpc(Pred::Eq, n3, 0); + let whole = self.land(sz, nz3); + self.guarded(whole, &mut |lw| { + for k in 0..4u32 { + let has = lw.cmpc(Pred::UGt, n, k * 4); + let at = lw.addc(b, 4 * k); + let v = r[k as usize]; + lw.guarded(has, &mut |lw| { + lw.mem_st(at, v); + Ok(()) + })?; + } + Ok(()) + })?; + let part = self.lnot(whole); + self.guarded(part, &mut |lw| { + let big = lw.cmpc(Pred::UGe, n, 4); + let n8 = lw.shlc(n, 3); + let n8 = lw.andc(n8, 31); + let one = lw.c(1); + let m = lw.bin(BinOp::Shl, one, n8); + let m = lw.sub(m, one); + let all = lw.c(u32::MAX); + let m = lw.sel(big, all, m); + let ms = lw.bin(BinOp::Shl, m, s); + let vs = lw.bin(BinOp::Shl, r[0], s); + lw.st_part(b, ms, vs); + let snz = lw.cmpc(Pred::Ne, s, 0); + let top = lw.add(s, n8); + // s + 8n with n = 4 gives s + 32 (n8 above is masked to 31) + let is4 = lw.cmpc(Pred::UGe, n, 4); + let k = lw.c(32); + let z = lw.c(0); + let t = lw.sel(is4, k, z); + let top = lw.add(top, t); + let over = lw.cmpc(Pred::UGt, top, 32); + let spill = lw.land(snz, over); + lw.guarded(spill, &mut |lw| { + let b4 = lw.addc(b, 4); + let k32 = lw.c(32); + let inv = lw.sub(k32, s); + let inv = lw.andc(inv, 31); + let m2 = lw.bin(BinOp::LShr, m, inv); + let v2 = lw.bin(BinOp::LShr, r[0], inv); + lw.st_part(b4, m2, v2); + Ok(()) + }) + }) + } + + // ------------------------------------------------------------ formats + + /// `FMT_INFO[min(fmt, 77)]` (a constant table) for a dynamic format. + pub(crate) fn fmt_info(&mut self, fmt: Value) -> Value { + let i32 = self.s.m.i32(); + let g = match self.fmt_table { + Some(g) => g, + None => { + let vals: Vec = (0..78).map(|i| self.s.m.i32c(buf_format_info(i))).collect(); + let at = self.s.m.array(78, i32); + let init = self.s.m.aggregate(at, &vals); + let g = self.s.m.global("xcl_fmt_info", at, 0, Some(init), true, 4); + self.fmt_table = Some(g); + g + } + }; + let k = self.c(77); + let i = self.umin(fmt, k); + let z = self.c(0); + let p = self.s.m.gep(g, &[z, i]); + self.s.m.load(p, 4) + } + fn fmt_bytes(&mut self, info: Value) -> Value { + let mut t = self.c(0); + for sh in [8, 14, 20, 26] { + let w = self.lshrc(info, sh); + let w = self.andc(w, 63); + t = self.add(t, w); + } + self.lshrc(t, 3) + } + /// `r[i]` for a dynamic i (0..3) + fn pick4(&mut self, r: &[Value; 4], i: Value) -> Value { + let mut v = r[3]; + for k in (0..3).rev() { + let is = self.cmpc(Pred::Eq, i, k); + v = self.sel(is, r[k as usize], v); + } + v + } + fn bits_at(&mut self, r: &[Value; 4], off: Value, w: Value) -> Value { + let i = self.lshrc(off, 5); + let s = self.andc(off, 31); + let lo = self.pick4(r, i); + let i1 = self.addc(i, 1); + let k3 = self.c(3); + let i1 = self.umin(i1, k3); + let hi = self.pick4(r, i1); + let in3 = self.cmpc(Pred::ULt, i, 3); + let hi = { + let z = self.c(0); + let t = self.lnot(in3); + self.sel(t, z, hi) + }; + let a = self.bin(BinOp::LShr, lo, s); + let k32 = self.c(32); + let inv = self.sub(k32, s); + let inv = self.andc(inv, 31); + let b = self.bin(BinOp::Shl, hi, inv); + let x = self.or(a, b); + let sz = self.cmpc(Pred::Eq, s, 0); + let v = self.sel(sz, lo, x); + let w31 = self.andc(w, 31); + let one = self.c(1); + let m = self.bin(BinOp::Shl, one, w31); + let m = self.sub(m, one); + let vm = self.and(v, m); + let big = self.cmpc(Pred::UGe, w, 32); + self.sel(big, v, vm) + } + fn exp2f(&mut self, x: Value) -> Value { + self.un(super::ops_core::op::EXP, x) + } + fn uf_small(&mut self, v: Value, mb: Value) -> Value { + let e = self.bin(BinOp::LShr, v, mb); + let one = self.c(1); + let p = self.bin(BinOp::Shl, one, mb); + let pm = self.sub(p, one); + let m = self.and(v, pm); + let fm = self.uitof(m); + let fp = self.uitof(p); + let fm = self.fdiv(fm, fp); + let mnz = self.nz(m); + let qn = self.s.m.f32c(0x7FC0_0000); + let inf = self.s.m.f32c(0x7F80_0000); + let special = self.sel(mnz, qn, inf); + let m14 = self.fc(-14.0); + let p14 = self.exp2f(m14); + let den = self.fmul(fm, p14); + let ef = self.uitof(e); + let k15 = self.fc(15.0); + let eb = self.fsub(ef, k15); + let pe = self.exp2f(eb); + let one_f = self.fc(1.0); + let mant = self.fadd(one_f, fm); + let norm = self.fmul(pe, mant); + let e0 = self.cmpc(Pred::Eq, e, 0); + let r = self.sel(e0, den, norm); + let e31 = self.cmpc(Pred::Eq, e, 31); + self.sel(e31, special, r) + } + fn fmt_comp(&mut self, r: &[Value; 4], info: Value, c: u32) -> Value { + let n = self.andc(info, 7); + let ty = self.lshrc(info, 3); + let ty = self.andc(ty, 7); + let t4 = self.cmpc(Pred::Eq, ty, 4); + let t5 = self.cmpc(Pred::Eq, ty, 5); + let isint = self.lor(t4, t5); + let mut off = self.c(0); + for k in 0..c { + let w = self.lshrc(info, 8 + 6 * k); + let w = self.andc(w, 63); + off = self.add(off, w); + } + let w = self.lshrc(info, (8 + 6 * c) & 31); + let w = self.andc(w, 63); + let v = self.bits_at(r, off, w); + let k32 = self.c(32); + let sh = self.sub(k32, w); + let sh = self.andc(sh, 31); + let x = self.bin(BinOp::Shl, v, sh); + let x = self.bin(BinOp::AShr, x, sh); + let big = self.cmpc(Pred::UGe, w, 32); + let sv = self.sel(big, v, x); + let w31 = self.andc(w, 31); + let one = self.c(1); + let mu = self.bin(BinOp::Shl, one, w31); + let mu = self.sub(mu, one); + let maxu = self.uitof(mu); + let fmaxu = self.fc(4294967295.0); + let maxu = self.sel(big, fmaxu, maxu); + let wm1 = self.sub(w, one); + let wm1 = self.andc(wm1, 31); + let ms = self.bin(BinOp::Shl, one, wm1); + let ms = self.sub(ms, one); + let maxs = self.uitof(ms); + let fmaxs = self.fc(2147483647.0); + let maxs = self.sel(big, fmaxs, maxs); + let fv = self.uitof(v); + let fsv = self.sitof(sv); + let zf = self.fc(0.0); + let onef = self.fc(1.0); + let vz = self.cmpc(Pred::Eq, v, 0); + let ge = self.fcmp(Pred::FOGe, fv, maxu); + let q = self.fdiv(fv, maxu); + let un = self.sel(ge, onef, q); + let un = self.sel(vz, zf, un); + let f_un = self.bits(un); + let svz = self.cmpc(Pred::Eq, sv, 0); + let ges = self.fcmp(Pred::FOGe, fsv, maxs); + let qs = self.fdiv(fsv, maxs); + let m1 = self.fc(-1.0); + let qs = self.fmax(qs, m1); + let sn = self.sel(ges, onef, qs); + let sn = self.sel(svz, zf, sn); + let f_sn = self.bits(sn); + let h = self.s.f16_to_f32(v); + let hb = self.bits(h); + let w11 = self.cmpc(Pred::Eq, w, 11); + let k6 = self.c(6); + let k5 = self.c(5); + let mb = self.sel(w11, k6, k5); + let uf = self.uf_small(v, mb); + let ufb = self.bits(uf); + let w16 = self.cmpc(Pred::Eq, w, 16); + let w32 = self.cmpc(Pred::Eq, w, 32); + let flt = self.sel(w16, hb, ufb); + let flt = self.sel(w32, v, flt); + let fvb = self.bits(fv); + let fsvb = self.bits(fsv); + let mut res = flt; + for (k, val) in [(5u32, sv), (4, v), (3, fsvb), (2, fvb), (1, f_sn), (0, f_un)] { + let is = self.cmpc(Pred::Eq, ty, k); + res = self.sel(is, val, res); + } + let cge = self.cmpc(Pred::ULe, n, c); + let dflt = if c == 3 { + let a = self.c(1); + let b = self.c(0x3F80_0000); + self.sel(isint, a, b) + } else { + self.c(0) + }; + self.sel(cge, dflt, res) + } + fn dst_sel(&mut self, c: &[Value; 4], sel: Value, isint: Value) -> Value { + let k4 = self.c(4); + let i = self.sub(sel, k4); + let i = self.andc(i, 3); + let v = self.pick4(c, i); + let one = self.c(1); + let onef = self.c(0x3F80_0000); + let o = self.sel(isint, one, onef); + let s1 = self.cmpc(Pred::Eq, sel, 1); + let v = self.sel(s1, o, v); + let s0 = self.cmpc(Pred::Eq, sel, 0); + self.selc(s0, 0, v) + } + fn fmt_encode(&mut self, x: Value, info: Value, c: u32) -> Value { + let ty = self.lshrc(info, 3); + let ty = self.andc(ty, 7); + let w = self.lshrc(info, 8 + 6 * c); + let w = self.andc(w, 63); + let f = self.f(x); + let big = self.cmpc(Pred::UGe, w, 32); + let one = self.c(1); + let w31 = self.andc(w, 31); + let mu = self.bin(BinOp::Shl, one, w31); + let mu = self.sub(mu, one); + let maxu = self.uitof(mu); + let fmaxu = self.fc(4294967295.0); + let maxu = self.sel(big, fmaxu, maxu); + let wm1 = self.sub(w, one); + let wm1 = self.andc(wm1, 31); + let ms = self.bin(BinOp::Shl, one, wm1); + let ms = self.sub(ms, one); + let maxs = self.uitof(ms); + let fmaxs = self.fc(2147483647.0); + let maxs = self.sel(big, fmaxs, maxs); + // ty 0: (uint)round(saturate(f) * maxu) + let sat = self.un(super::ops_core::op::SATURATE, f); + let u0 = self.fmul(sat, maxu); + let u0 = self.un(super::ops_core::op::ROUND_NE, u0); + let e0 = self.ftoui(u0); + // ty 1: (uint)(int)round((isnan(f) ? 0 : clamp(f, -1, 1)) * maxs) + let n = self.isnan(f); + let z = self.fc(0.0); + let m1 = self.fc(-1.0); + let p1 = self.fc(1.0); + let cl = self.fmax(f, m1); + let cl = self.fmin(cl, p1); + let cl = self.sel(n, z, cl); + let s1 = self.fmul(cl, maxs); + let s1 = self.un(super::ops_core::op::ROUND_NE, s1); + let e1 = self.ftosi(s1); + let e2 = self.ftoui(f); + let e3 = self.ftosi(f); + // floats + let h = self.s.f32_to_f16(f); + let w11 = self.cmpc(Pred::Eq, w, 11); + let k3f0 = self.c(0x3F0); + let nanv = self.selc(w11, 0x7E0, k3f0); + let h4 = self.lshrc(h, 4); + let h4 = self.andc(h4, 0x7FF); + let h5 = self.lshrc(h, 5); + let h5 = self.andc(h5, 0x3FF); + let small = self.sel(w11, h4, h5); + let le0 = self.fcmp(Pred::FOLe, f, z); + let small = self.selc(le0, 0, small); + let small = self.sel(n, nanv, small); + let w16 = self.cmpc(Pred::Eq, w, 16); + let fl = self.sel(w16, h, small); + let t4 = self.cmpc(Pred::Eq, ty, 4); + let t5 = self.cmpc(Pred::Eq, ty, 5); + let w32 = self.cmpc(Pred::Eq, w, 32); + let raw = self.lor(t4, t5); + let raw = self.lor(raw, w32); + let r = self.sel(raw, x, fl); + let mut res = r; + for (k, val) in [(3u32, e3), (2, e2), (1, e1), (0, e0)] { + let is = self.cmpc(Pred::Eq, ty, k); + res = self.sel(is, val, res); + } + res + } + fn fmt_pack(&mut self, v: [Value; 4], info: Value) -> [Value; 4] { + let z = self.c(0); + let mut r = [z; 4]; + let n = self.andc(info, 7); + let mut off = self.c(0); + for c in 0..4u32 { + let active = self.cmpc(Pred::UGt, n, c); + let w = self.lshrc(info, 8 + 6 * c); + let w = self.andc(w, 63); + let e = self.fmt_encode(v[c as usize], info, c); + // put_bits(r, off, w, e) + let big = self.cmpc(Pred::UGe, w, 32); + let one = self.c(1); + let w31 = self.andc(w, 31); + let m = self.bin(BinOp::Shl, one, w31); + let m = self.sub(m, one); + let all = self.c(u32::MAX); + let m = self.sel(big, all, m); + let e = self.and(e, m); + let e = self.sel(active, e, z); + let i = self.lshrc(off, 5); + let s = self.andc(off, 31); + let lo = self.bin(BinOp::Shl, e, s); + let k32 = self.c(32); + let inv = self.sub(k32, s); + let inv = self.andc(inv, 31); + let hi = self.bin(BinOp::LShr, e, inv); + let snz = self.cmpc(Pred::Ne, s, 0); + let sw = self.add(s, w); + let over = self.cmpc(Pred::UGt, sw, 32); + let spill = self.land(snz, over); + let i3 = self.cmpc(Pred::ULt, i, 3); + let spill = self.land(spill, i3); + for j in 0..4u32 { + let at = self.cmpc(Pred::Eq, i, j); + let x = self.sel(at, lo, z); + let mut nv = self.or(r[j as usize], x); + if j > 0 { + let at1 = self.cmpc(Pred::Eq, i, j - 1); + let sp = self.land(at1, spill); + let y = self.sel(sp, hi, z); + nv = self.or(nv, y); + } + r[j as usize] = nv; + } + let wa = self.sel(active, w, z); + off = self.add(off, wa); + } + r + } + + // ------------------------------------------------------------ d16 + + fn d16_data(&mut self, v: Value, half: u32) -> Value { + if half == 1 { + self.lshrc(v, 16) + } else { + v + } + } + fn d16_merge(&mut self, v: Value, raw: Value, n: u32, signed: bool, half: u32) -> Value { + let bits = 8 * n; + let val = if signed { + let x = self.shlc(raw, 32 - bits); + self.ashrc(x, 32 - bits) + } else { + self.andc(raw, ((1u64 << bits) - 1) as u32) + }; + match half { + 0 => { + let a = self.andc(v, 0xFFFF_0000); + let b = self.andc(val, 0xFFFF); + self.or(a, b) + } + 1 => { + let a = self.andc(v, 0xFFFF); + let b = self.shlc(val, 16); + self.or(a, b) + } + _ => val, + } + } + + /// Writes VGPR `n` in a block where this lane is known active. + fn vset(&mut self, n: u64, v: Value) { + self.wr(VAR_VGPR + n as u32, v); + } + + // ------------------------------------------------------------ SMEM + + pub fn smem(&mut self, d: &Decoded, name: &str) -> LResult<()> { + if name == "s_memtime" || name == "s_memrealtime" { + let sdata = Self::field(d, "SDATA"); + let z = self.c(0); + self.write64(&Dst::S(sdata), z, z); + return Ok(()); + } + let count = match name.trim_start_matches("s_buffer_load_").trim_start_matches("s_load_") { + "dword" => 1, + "dwordx2" => 2, + "dwordx4" => 4, + "dwordx8" => 8, + "dwordx16" => 16, + _ => return err(d, "SMEM"), + }; + let sdata = Self::field(d, "SDATA"); + let sbase = Self::field(d, "SBASE"); + let imm = Self::fv(d, "OFFSET") as u32; + let soff = rdna2::field_value(d.enc, &d.words, "SOFFSET").unwrap_or(125); + let soff = if soff == 125 { self.c(0) } else { self.code32(soff, None, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))? }; + let mut vals = Vec::new(); + if name.starts_with("s_buffer_load") { + let (d0, d1, d2) = (self.sreg(sbase), self.sreg(sbase + 1), self.sreg(sbase + 2)); + self.window(d1); + let k = self.c(imm); + let off = self.add(k, soff); + let st = self.lshrc(d1, 16); + let st = self.andc(st, 0x3FFF); + let sz = self.cmpc(Pred::Eq, st, 0); + let lim = self.mul(d2, st); + let lim = self.sel(sz, d2, lim); + for i in 0..count { + let o = self.addc(off, 4 * i); + let ok = self.cmp(Pred::ULt, o, lim); + let a = self.add(d0, o); + let v = self.mem_ld(a); + let z = self.c(0); + vals.push(self.sel(ok, v, z)); + } + } else { + let imm = ((imm << 11) as i32 >> 11) as u32; + let b = self.sreg(sbase); + let hi = self.sreg(sbase + 1); + self.window(hi); + let k = self.c(imm); + let a = self.add(b, k); + let a = self.add(a, soff); + for i in 0..count { + let at = self.addc(a, 4 * i); + vals.push(self.mem_ld(at)); + } + } + let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)); + if self.split && coherent { + // both halves take the lower half's values + let other = self.exchange_n(&vals); + let up = self.upper; + for (v, o) in vals.iter_mut().zip(other) { + *v = self.sel(up, o, *v); + } + } + for (i, v) in vals.into_iter().enumerate() { + self.write32(&Dst::S(sdata + i as u64), v); + } + Ok(()) + } + + // ------------------------------------------------------------ MUBUF / MTBUF + + pub fn mubuf(&mut self, d: &Decoded, name: &str) -> LResult<()> { + if name.starts_with("buffer_atomic_") { + return self.buffer_atomic(d, name); + } + let small = match name { + "buffer_load_ubyte" => Some((1u32, false, false)), + "buffer_load_sbyte" => Some((1, true, false)), + "buffer_load_ushort" => Some((2, false, false)), + "buffer_load_sshort" => Some((2, true, false)), + "buffer_store_byte" => Some((1, false, true)), + "buffer_store_short" => Some((2, false, true)), + _ => None, + }; + let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); + let d16s = d16_small(name.trim_start_matches("buffer_")); + let d16_format = buffer_format_d16(name); + let (kind, count) = match (small, d16_format) { + (Some(_), _) => (BufKind::Load, 1), + (None, Some((kind, components, _))) => (kind, (components + 1) / 2), + (None, None) if d16s.is_some() => (BufKind::Load, 1), + (None, None) => buffer_op(name).ok_or_else(|| format!("{}: MUBUF", rdna2::format(d)))?, + }; + if f("LDS") != 0 || f("TFE") != 0 { + return err(d, "MUBUF lds/tfe"); + } + let (vdata, vaddr, srsrc) = (f("VDATA"), f("VADDR"), Self::field(d, "SRSRC")); + let soff = self.code32(f("SOFFSET"), None, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + let (offen, idxen) = (f("OFFEN") != 0, f("IDXEN") != 0); + let (d0, d1, d2, d3) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2), self.sreg(srsrc + 3)); + self.window(d1); + let index = if idxen { self.vreg(vaddr) } else { self.c(0) }; + let voff = if offen { self.vreg(vaddr + idxen as u64) } else { self.c(0) }; + let stride = self.lshrc(d1, 16); + let stride = self.andc(stride, 0x3FFF); + let off = self.addc(voff, f("OFFSET") as u32); + let a = self.add(d0, soff); + let a = self.add(a, off); + let si = self.mul(stride, index); + let a = self.add(a, si); + let act = self.act(); + let szero = self.cmpc(Pred::Eq, stride, 0); + let idx_ok = self.cmp(Pred::ULt, index, d2); + let in_range = |lw: &mut Lw, bytes: Value| -> Value { + let e = lw.add(off, bytes); + let ok = lw.cmp(Pred::ULe, e, d2); + lw.sel(szero, ok, idx_ok) + }; + if let Some((n, signed, store, half)) = d16s { + let nb = self.c(n); + let ok = in_range(self, nb); + let v = self.vreg(vdata); + if store { + let data = self.d16_data(v, half); + let c = self.land(act, ok); + let z = self.c(0); + let nv = self.c(n); + return self.guarded(c, &mut |lw| lw.st_bytes(a, [data, z, z, z], nv)); + } + return self.guarded(act, &mut |lw| { + let r = lw.ld_raw(a); + let z = lw.c(0); + let raw = lw.sel(ok, r[0], z); + let nv = lw.d16_merge(v, raw, n, signed, half); + lw.vset(vdata, nv); + Ok(()) + }); + } + if let Some((n, signed, store)) = small { + let nb = self.c(n); + let ok = in_range(self, nb); + let v = self.vreg(vdata); + if store { + let c = self.land(act, ok); + let z = self.c(0); + let nv = self.c(n); + return self.guarded(c, &mut |lw| lw.st_bytes(a, [v, z, z, z], nv)); + } + return self.guarded(act, &mut |lw| { + let r = lw.ld_raw(a); + let bits = 8 * n; + let val = if signed { + let x = lw.shlc(r[0], 32 - bits); + lw.ashrc(x, 32 - bits) + } else { + lw.andc(r[0], ((1u64 << bits) - 1) as u32) + }; + let z = lw.c(0); + let val = lw.sel(ok, val, z); + lw.vset(vdata, val); + Ok(()) + }); + } + match kind { + BufKind::Load => { + let oks: Vec = (0..count).map(|i| { + let b = self.c(4 * i as u32 + 4); + in_range(self, b) + }).collect(); + self.guarded(act, &mut |lw| { + for i in 0..count { + let at = lw.addc(a, 4 * i as u32); + let v = lw.mem_ld(at); + let z = lw.c(0); + let v = lw.sel(oks[i as usize], v, z); + lw.vset(vdata + i, v); + } + Ok(()) + }) + } + BufKind::Store => { + let vals: Vec = (0..count).map(|i| self.vreg(vdata + i)).collect(); + let oks: Vec = (0..count).map(|i| { + let b = self.c(4 * i as u32 + 4); + in_range(self, b) + }).collect(); + self.guarded(act, &mut |lw| { + for i in 0..count as usize { + let at = lw.addc(a, 4 * i as u32); + let v = vals[i]; + lw.guarded(oks[i], &mut |lw| { + lw.mem_st(at, v); + Ok(()) + })?; + } + Ok(()) + }) + } + BufKind::FormatLoad => { + let fmt = if d.enc.name == "ENC_MTBUF" { + self.c(f("FORMAT") as u32) + } else { + let x = self.lshrc(d3, 12); + self.andc(x, 0x7F) + }; + let info = self.fmt_info(fmt); + let ty = self.lshrc(info, 3); + let ty = self.andc(ty, 7); + let t4 = self.cmpc(Pred::Eq, ty, 4); + let t5 = self.cmpc(Pred::Eq, ty, 5); + let isint = self.lor(t4, t5); + let nb = self.fmt_bytes(info); + let rng = in_range(self, nb); + let n7 = self.andc(info, 7); + let has = self.nz(n7); + let ok = self.land(has, rng); + let cur: Vec = (0..count).map(|i| self.vreg(vdata + i)).collect(); + self.guarded(act, &mut |lw| { + let r = lw.ld_raw(a); + let c = [lw.fmt_comp(&r, info, 0), lw.fmt_comp(&r, info, 1), lw.fmt_comp(&r, info, 2), lw.fmt_comp(&r, info, 3)]; + let z = lw.c(0); + if let Some((_, components, high)) = d16_format { + let half = |lw: &mut Lw, comp: u64| -> Value { + let sel = lw.lshrc(d3, 3 * comp as u32); + let sel = lw.andc(sel, 7); + let s = lw.dst_sel(&c, sel, isint); + let lo = lw.andc(s, 0xFFFF); + let sf = lw.f(s); + let h = lw.s.f32_to_f16(sf); + lw.sel(isint, lo, h) + }; + if high { + let h = half(lw, 0); + let h = lw.shlc(h, 16); + let h = lw.sel(ok, h, z); + let l = lw.andc(cur[0], 0xFFFF); + let v = lw.or(l, h); + lw.vset(vdata, v); + } else { + for i in 0..count { + let lo = half(lw, 2 * i); + let hi = if 2 * i + 1 < components { half(lw, 2 * i + 1) } else { z }; + let hi = lw.shlc(hi, 16); + let v = lw.or(lo, hi); + let v = lw.sel(ok, v, z); + lw.vset(vdata + i, v); + } + } + return Ok(()); + } + for i in 0..count { + let sel = lw.lshrc(d3, 3 * i as u32); + let sel = lw.andc(sel, 7); + let s = lw.dst_sel(&c, sel, isint); + let v = lw.sel(ok, s, z); + lw.vset(vdata + i, v); + } + Ok(()) + }) + } + BufKind::FormatStore => { + let fmt = if d.enc.name == "ENC_MTBUF" { + self.c(f("FORMAT") as u32) + } else { + let x = self.lshrc(d3, 12); + self.andc(x, 0x7F) + }; + let info = self.fmt_info(fmt); + let nb = self.fmt_bytes(info); + let rng = in_range(self, nb); + let n7 = self.andc(info, 7); + let has = self.nz(n7); + let ok = self.land(has, rng); + let z = self.c(0); + let vals: [Value; 4] = if let Some((_, components, high)) = d16_format { + let ty = self.lshrc(info, 3); + let ty = self.andc(ty, 7); + let mut out = [z; 4]; + for (i, slot) in out.iter_mut().enumerate() { + if (i as u64) >= components { + continue; + } + let v = self.vreg(vdata + if high { 0 } else { i as u64 / 2 }); + let hsh = if high || i & 1 != 0 { self.lshrc(v, 16) } else { v }; + let h = self.andc(hsh, 0xFFFF); + let sx = self.sx16(h); + let fh = self.s.f16_to_f32(h); + let fb = self.bits(fh); + let t5 = self.cmpc(Pred::Eq, ty, 5); + let t4 = self.cmpc(Pred::Eq, ty, 4); + let x = self.sel(t5, sx, fb); + *slot = self.sel(t4, h, x); + } + out + } else { + let mut out = [z; 4]; + for (i, slot) in out.iter_mut().enumerate().take(count as usize) { + *slot = self.vreg(vdata + i as u64); + } + out + }; + let c = self.land(act, ok); + self.guarded(c, &mut |lw| { + let packed = lw.fmt_pack(vals, info); + lw.st_bytes(a, packed, nb) + }) + } + } + } + + // ------------------------------------------------------------ atomics + + /// A 32-bit atomic; returns the old value (valid in the guarded block it runs in). + fn rmw32(&mut self, d: &Decoded, op: &str, at: At, v: Value, v2: Value) -> LResult { + let direct = |lw: &mut Lw, o: AtomicOp, rm: RmwOp, val: Value| -> Value { + match at { + At::Mem(a) => { + lw.mraw_atomic(o, a, val) + } + At::Lds(i) => { + let g = lw.lds.expect("lds"); + lw.s.gs_atomic(rm, g, i, val) + } + } + }; + let z = self.c(0); + Ok(match op { + "add" | "add_u32" => direct(self, AtomicOp::Add, RmwOp::Add, v), + "sub" | "sub_u32" => { + let n = self.sub(z, v); + direct(self, AtomicOp::Add, RmwOp::Add, n) + } + "and" | "and_b32" => direct(self, AtomicOp::And, RmwOp::And, v), + "or" | "or_b32" => direct(self, AtomicOp::Or, RmwOp::Or, v), + "xor" | "xor_b32" => direct(self, AtomicOp::Xor, RmwOp::Xor, v), + "swap" | "wrxchg_b32" => direct(self, AtomicOp::Exchange, RmwOp::Xchg, v), + "umin" | "min_u32" => direct(self, AtomicOp::UMin, RmwOp::UMin, v), + "umax" | "max_u32" => direct(self, AtomicOp::UMax, RmwOp::UMax, v), + "smin" | "min_i32" => direct(self, AtomicOp::IMin, RmwOp::Min, v), + "smax" | "max_i32" => direct(self, AtomicOp::IMax, RmwOp::Max, v), + "cmpswap" | "fcmpswap" | "cmpst_b32" | "cmpst_f32" => self.cmpxchg(at, v2, v), + "fmin" | "fmax" | "min_f32" | "max_f32" => { + let min = op == "fmin" || op == "min_f32"; + match at { + At::Mem(a) => self.float_minmax_mem(min, a, v)?, + At::Lds(_) => self.cas(at, &mut |lw, c| { + let (x, y) = (lw.f(c), lw.f(v)); + let r = if min { lw.fmin(x, y) } else { lw.fmax(x, y) }; + lw.bits(r) + }), + } + } + "rsub" | "rsub_u32" => self.cas(at, &mut |lw, c| lw.sub(v, c)), + "inc" | "inc_u32" => self.cas(at, &mut |lw, c| { + let ge = lw.cmp(Pred::UGe, c, v); + let c1 = lw.addc(c, 1); + lw.selc(ge, 0, c1) + }), + "dec" | "dec_u32" => self.cas(at, &mut |lw, c| { + let z = lw.cmpc(Pred::Eq, c, 0); + let gt = lw.cmp(Pred::UGt, c, v); + let w = lw.lor(z, gt); + let one = lw.c(1); + let c1 = lw.sub(c, one); + lw.sel(w, v, c1) + }), + "csub" => self.cas(at, &mut |lw, c| { + let ge = lw.cmp(Pred::UGe, c, v); + let s = lw.sub(c, v); + let z = lw.c(0); + lw.sel(ge, s, z) + }), + "add_f32" => self.cas(at, &mut |lw, c| { + let (x, y) = (lw.f(c), lw.f(v)); + let r = lw.fadd(x, y); + lw.bits(r) + }), + "mskor_b32" => self.cas(at, &mut |lw, c| { + let n = lw.not(v); + let x = lw.and(c, n); + lw.or(x, v2) + }), + _ => return err(d, "atomic"), + }) + } + + fn cmpxchg(&mut self, at: At, cmp: Value, new: Value) -> Value { + match at { + At::Mem(a) => { + self.mraw_cmpxchg(a, cmp, new) + } + At::Lds(i) => { + let g = self.lds.expect("lds"); + self.s.gs_cmpxchg(g, i, cmp, new) + } + } + } + + /// A compare-exchange loop (at most 4096 rounds) computing `new(old)`; returns the old value. + fn cas(&mut self, at: At, new: &mut dyn FnMut(&mut Lw, Value) -> Value) -> Value { + let init = match at { + At::Mem(a) => self.mem_ld(a), + At::Lds(i) => { + let g = self.lds.expect("lds"); + self.s.gs_load(g, i) + } + }; + let pre = self.cur(); + let lp = self.block(Some(2)); + let ex = self.block(Some(1)); + self.br(lp); + self.s.m.set_block(lp); + let i32 = self.s.m.i32(); + let c = self.s.m.phi(i32); + let i = self.s.m.phi(i32); + self.s.m.add_incoming(c, init, pre); + let z = self.c(0); + self.s.m.add_incoming(i, z, pre); + let n = new(self, c); + let p = self.cmpxchg(at, c, n); + let ok = self.cmp(Pred::Eq, p, c); + let i1 = self.addc(i, 1); + let out = self.cmpc(Pred::UGe, i1, 4096); + let stop = self.lor(ok, out); + let me = self.cur(); + self.s.m.add_incoming(c, p, me); + self.s.m.add_incoming(i, i1, me); + self.cond_br(stop, ex, lp); + self.s.m.set_block(ex); + p + } + + /// Float min / max on `mem` as one integer atomic (the recompiler's `float_minmax_mem`). + fn float_minmax_mem(&mut self, min: bool, a: Value, v: Value) -> LResult { + let (pos, neg) = if min { (AtomicOp::IMin, AtomicOp::UMax) } else { (AtomicOp::IMax, AtomicOp::UMin) }; + let tmp = self.tmp_var(); + let z = self.c(0); + self.wr(tmp, z); + let pp = self.cmpc(Pred::ULe, v, 0x7F80_0000); + self.guarded(pp, &mut |lw| { + let o = lw.mraw_atomic(pos, a, v); + lw.wr(tmp, o); + Ok(()) + })?; + let np = self.lnot(pp); + self.guarded(np, &mut |lw| { + let o = lw.mraw_atomic(neg, a, v); + lw.wr(tmp, o); + Ok(()) + })?; + Ok(self.rd(tmp)) + } + + pub fn tmp_var(&mut self) -> u32 { + self.ntmp += 1; + VAR_TMP + self.ntmp + } + + /// 64-bit atomic at `a`; data at VGPRs `data`/+1, compare at `cmp`/+1; old → `dst` (GLC). + #[allow(clippy::too_many_arguments)] + fn atomic64(&mut self, d: &Decoded, op: &str, a: Value, data: u64, cmp: u64, glc: bool, dst: u64, active: Value) -> LResult<()> { + let (lo, hi) = (self.vreg(data), self.vreg(data + 1)); + let (clo, chi) = (self.vreg(cmp), self.vreg(cmp + 1)); + let v = self.pack64(lo, hi); + let cv = self.pack64(clo, chi); + let ops = op.to_string(); + let mut failed = None; + self.guarded(active, &mut |lw| { + let z64 = lw.c64(0); + let old = match ops.as_str() { + "add" => lw.mraw_atomic(AtomicOp::Add, a, v), + "sub" => { + let n = lw.sub(z64, v); + lw.mraw_atomic(AtomicOp::Add, a, n) + } + "and" => lw.mraw_atomic(AtomicOp::And, a, v), + "or" => lw.mraw_atomic(AtomicOp::Or, a, v), + "xor" => lw.mraw_atomic(AtomicOp::Xor, a, v), + "swap" => lw.mraw_atomic(AtomicOp::Exchange, a, v), + "umin" => lw.mraw_atomic(AtomicOp::UMin, a, v), + "umax" => lw.mraw_atomic(AtomicOp::UMax, a, v), + "smin" => lw.mraw_atomic(AtomicOp::IMin, a, v), + "smax" => lw.mraw_atomic(AtomicOp::IMax, a, v), + "cmpswap" | "fcmpswap" => lw.mraw_cmpxchg(a, cv, v), + "fmin" | "fmax" => { + let min = ops == "fmin"; + let (pos, neg) = if min { (AtomicOp::IMin, AtomicOp::UMax) } else { (AtomicOp::IMax, AtomicOp::UMin) }; + let (tl, th) = (lw.tmp_var(), lw.tmp_var()); + let z = lw.c(0); + lw.wr(tl, z); + lw.wr(th, z); + let lim = lw.c64(0x7FF0_0000_0000_0000); + let pp = lw.cmp(Pred::ULe, v, lim); + for (cond, o) in [(pp, pos), (lw.lnot(pp), neg)] { + lw.guarded(cond, &mut |lw| { + let r = lw.mraw_atomic(o, a, v); + let (l, h) = lw.unpack64(r); + lw.wr(tl, l); + lw.wr(th, h); + Ok(()) + })?; + } + let (l, h) = (lw.rd(tl), lw.rd(th)); + lw.pack64(l, h) + } + "inc" | "dec" => { + let inc = ops == "inc"; + let l0 = lw.mem_ld(a); + let a4 = lw.addc(a, 4); + let h0 = lw.mem_ld(a4); + let init = lw.pack64(l0, h0); + let pre = lw.cur(); + let lp = lw.block(Some(2)); + let ex = lw.block(Some(1)); + lw.br(lp); + lw.s.m.set_block(lp); + let i64t = lw.i64(); + let i32 = lw.s.m.i32(); + let c = lw.s.m.phi(i64t); + let i = lw.s.m.phi(i32); + lw.s.m.add_incoming(c, init, pre); + let z = lw.c(0); + lw.s.m.add_incoming(i, z, pre); + let one = lw.c64(1); + let n = if inc { + let ge = lw.cmp(Pred::UGe, c, v); + let c1 = lw.add(c, one); + lw.sel(ge, z64, c1) + } else { + let cz = lw.cmp(Pred::Eq, c, z64); + let gt = lw.cmp(Pred::UGt, c, v); + let w = lw.lor(cz, gt); + let c1 = lw.sub(c, one); + lw.sel(w, v, c1) + }; + let p = lw.mraw_cmpxchg(a, c, n); + let ok = lw.cmp(Pred::Eq, p, c); + let i1 = lw.addc(i, 1); + let out = lw.cmpc(Pred::UGe, i1, 4096); + let stop = lw.lor(ok, out); + let me = lw.cur(); + lw.s.m.add_incoming(c, p, me); + lw.s.m.add_incoming(i, i1, me); + lw.cond_br(stop, ex, lp); + lw.s.m.set_block(ex); + p + } + _ => { + failed = Some("atomic 64"); + return Ok(()); + } + }; + if glc { + let (l, h) = lw.unpack64(old); + lw.vset(dst, l); + lw.vset(dst + 1, h); + } + Ok(()) + })?; + if let Some(why) = failed { + return err(d, why); + } + Ok(()) + } + + fn buffer_atomic(&mut self, d: &Decoded, name: &str) -> LResult<()> { + let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); + let op = name.trim_start_matches("buffer_atomic_"); + let (vdata, vaddr, srsrc) = (f("VDATA"), f("VADDR"), Self::field(d, "SRSRC")); + let soff = self.code32(f("SOFFSET"), None, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + let (offen, idxen) = (f("OFFEN") != 0, f("IDXEN") != 0); + let (d0, d1, d2) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2)); + self.window(d1); + let index = if idxen { self.vreg(vaddr) } else { self.c(0) }; + let voff = if offen { self.vreg(vaddr + idxen as u64) } else { self.c(0) }; + let x2 = op.ends_with("_x2"); + let op = op.trim_end_matches("_x2"); + let bytes = if x2 { 8 } else { 4 }; + let stride = self.lshrc(d1, 16); + let stride = self.andc(stride, 0x3FFF); + let off = self.addc(voff, f("OFFSET") as u32); + let a = self.add(d0, soff); + let a = self.add(a, off); + let si = self.mul(stride, index); + let a = self.add(a, si); + let a = self.andc(a, !(bytes - 1)); + let szero = self.cmpc(Pred::Eq, stride, 0); + let e = self.addc(off, bytes); + let r1 = self.cmp(Pred::ULe, e, d2); + let r2 = self.cmp(Pred::ULt, index, d2); + let ok = self.sel(szero, r1, r2); + let act = self.act(); + let active = self.land(act, ok); + if x2 { + return self.atomic64(d, op, a, vdata, vdata + 2, f("GLC") == 1, vdata, active); + } + let (v, cmp) = (self.vreg(vdata), self.vreg(vdata + 1)); + let glc = f("GLC") == 1; + let ops = op.to_string(); + let tmp = self.tmp_var(); + let z = self.c(0); + self.wr(tmp, z); + let mut e = None; + self.guarded(active, &mut |lw| { + match lw.rmw32(d, &ops, At::Mem(a), v, cmp) { + Ok(o) => lw.wr(tmp, o), + Err(x) => e = Some(x), + } + Ok(()) + })?; + if let Some(x) = e { + return Err(x); + } + if glc { + // select(act, select(ok, old, 0), v) + let old = self.rd(tmp); + let z = self.c(0); + let r = self.sel(ok, old, z); + let r = self.sel(act, r, v); + self.vset(vdata, r); + } + Ok(()) + } + + // ------------------------------------------------------------ FLAT / global + + fn flat_base(&mut self, d: &Decoded) -> (Value, bool) { + let global = d.enc.name == "ENC_FLAT_GLBL"; + let addr = self.vreg(Self::fv(d, "ADDR")); + let saddr = Self::fv(d, "SADDR"); + self.flat_window(d); + let base = if global && saddr != 0x7D && saddr != 0x7F { + let s = self.sreg(saddr); + self.add(s, addr) + } else { + addr + }; + let raw = Self::fv(d, "OFFSET") as u32; + let off = if global { (((raw << 20) as i32) >> 20) as u32 } else { raw }; + (self.addc(base, off), global) + } + + /// `flat_window`: the window of a FLAT / global address (SADDR pair or the 64-bit VGPR address). + fn flat_window(&mut self, d: &Decoded) { + if self.mems.len() > 1 { + let global = d.enc.name == "ENC_FLAT_GLBL"; + let saddr = Self::fv(d, "SADDR"); + let hi = if global && saddr != 0x7D && saddr != 0x7F { self.sreg(saddr + 1) } else { self.vreg(Self::fv(d, "ADDR") + 1) }; + self.window(hi); + } + } + + pub fn flat(&mut self, d: &Decoded, name: &str) -> LResult<()> { + let op = name.trim_start_matches("global_").trim_start_matches("flat_").trim_start_matches("scratch_"); + if d.enc.name == "ENC_FLAT_SCRATCH" { + return self.scratch(d, op); + } + if let Some(a) = op.strip_prefix("atomic_") { + return self.flat_atomic(d, a); + } + let act = self.act(); + if let Some((n, signed, store, half)) = flat_small(op) { + let (a, _) = self.flat_base(d); + if store { + let v = self.vreg(Self::fv(d, "DATA")); + let data = self.d16_data(v, half); + let z = self.c(0); + let nv = self.c(n); + return self.guarded(act, &mut |lw| lw.st_bytes(a, [data, z, z, z], nv)); + } + let vd = Self::fv(d, "VDST"); + let v = self.vreg(vd); + return self.guarded(act, &mut |lw| { + let r = lw.ld_raw(a); + let nv = lw.d16_merge(v, r[0], n, signed, half); + lw.vset(vd, nv); + Ok(()) + }); + } + let (store, count) = match op { + "load_dword" | "load_dword_addtid" => (false, 1), + "load_dwordx2" => (false, 2), + "load_dwordx3" => (false, 3), + "load_dwordx4" => (false, 4), + "store_dword" | "store_dword_addtid" => (true, 1), + "store_dwordx2" => (true, 2), + "store_dwordx3" => (true, 3), + "store_dwordx4" => (true, 4), + _ => return err(d, "FLAT"), + }; + let a = if op.ends_with("_addtid") { + self.flat_window(d); + let saddr = Self::fv(d, "SADDR"); + let lane = self.lane; + let l4 = self.shlc(lane, 2); + let base = match saddr { + 0x7D | 0x7F => l4, + _ => { + let s = self.sreg(saddr); + self.add(s, l4) + } + }; + let raw = Self::fv(d, "OFFSET") as u32; + let off = if d.enc.name == "ENC_FLAT_GLBL" { (((raw << 20) as i32) >> 20) as u32 } else { raw }; + self.addc(base, off) + } else { + self.flat_base(d).0 + }; + if store { + let vals: Vec = (0..count).map(|i| self.vreg(Self::fv(d, "DATA") + i)).collect(); + self.guarded(act, &mut |lw| { + for (i, &v) in vals.iter().enumerate() { + let at = lw.addc(a, 4 * i as u32); + lw.mem_st(at, v); + } + Ok(()) + }) + } else { + let vd = Self::fv(d, "VDST"); + self.guarded(act, &mut |lw| { + for i in 0..count { + let at = lw.addc(a, 4 * i as u32); + let v = lw.mem_ld(at); + lw.vset(vd + i, v); + } + Ok(()) + }) + } + } + + fn flat_atomic(&mut self, d: &Decoded, op: &str) -> LResult<()> { + let (a, _) = self.flat_base(d); + let x2 = op.ends_with("_x2"); + let op = op.trim_end_matches("_x2"); + let a = self.andc(a, if x2 { !7 } else { !3 }); + let act = self.act(); + let glc = Self::fv(d, "GLC") == 1; + let data = Self::fv(d, "DATA"); + if x2 { + return self.atomic64(d, op, a, data, data + 2, glc, Self::fv(d, "VDST"), act); + } + let v = self.vreg(data); + let cmpv = self.vreg(data + 1); + let vd = Self::fv(d, "VDST"); + let ops = op.to_string(); + let mut e = None; + self.guarded(act, &mut |lw| { + match lw.rmw32(d, &ops, At::Mem(a), v, cmpv) { + Ok(o) => { + if glc { + lw.vset(vd, o); + } + } + Err(x) => e = Some(x), + } + Ok(()) + })?; + match e { + Some(x) => Err(x), + None => Ok(()), + } + } + + // ------------------------------------------------------------ LDS / DS + + /// LDS dword index of byte address `at` (`(at >> 2) & 8191`, below the exchange words + /// in the split form). + fn lds_index(&mut self, at: Value) -> Value { + let i = self.lshrc(at, 2); + let i = self.andc(i, 8191); + if self.split { + let k = self.c(self.lds_top); + self.umin(i, k) + } else { + i + } + } + fn lds_ld(&mut self, at: Value) -> Value { + let i = self.lds_index(at); + let g = self.lds.expect("lds"); + self.s.gs_load(g, i) + } + fn lds_st(&mut self, at: Value, v: Value) { + let i = self.lds_index(at); + let g = self.lds.expect("lds"); + self.s.gs_store(g, i, v); + } + + pub fn ds(&mut self, d: &Decoded, name: &str) -> LResult<()> { + let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); + let (o0, o1) = (f("OFFSET0"), f("OFFSET1")); + let off16 = (o0 | o1 << 8) as u32; + match name { + "ds_swizzle_b32" => { + let a = self.vreg(f("ADDR")); + let l = self.swizzle_lane(off16 as u64); + let (el, eh) = self.exec_mask(); + let v = self.read_lane_half(a, l); + let on = self.lanebit_at(el, eh, l); + let z = self.c(0); + let t = self.sel(on, v, z); + self.write32(&Dst::V(f("VDST")), t); + return Ok(()); + } + "ds_bpermute_b32" => { + let (a, v) = (self.vreg(f("ADDR")), self.vreg(f("DATA0"))); + let m = if self.wave64 { 63 } else { 31 }; + let (el, eh) = self.exec_mask(); + let x = self.addc(a, off16); + let x = self.lshrc(x, 2); + let l = self.andc(x, m); + let r = self.read_lane_any(v, l); + let on = self.lanebit_at(el, eh, l); + let z = self.c(0); + let t = self.sel(on, r, z); + self.write32(&Dst::V(f("VDST")), t); + return Ok(()); + } + _ => {} + } + if f("GDS") != 0 { + return err(d, "GDS"); + } + let act = self.act(); + if matches!(name, "ds_write_addtid_b32" | "ds_read_addtid_b32") { + let m0 = self.sreg(124); + let base = self.andc(m0, 0xFFFF); + let base = self.addc(base, off16); + let lane = self.lane; + let l4 = self.shlc(lane, 2); + let at = self.add(base, l4); + if name == "ds_write_addtid_b32" { + let src = self.vreg(f("DATA0")); + return self.guarded(act, &mut |lw| { + lw.lds_st(at, src); + Ok(()) + }); + } + let vd = f("VDST"); + return self.guarded(act, &mut |lw| { + let v = lw.lds_ld(at); + lw.vset(vd, v); + Ok(()) + }); + } + let a = self.vreg(f("ADDR")); + if let Some((bits, signed, write, half)) = ds_d16(name) { + let at = self.addc(a, off16); + let sh = self.andc(at, 3); + let sh = self.shlc(sh, 3); + let mask = ((1u64 << bits) - 1) as u32; + if write { + let v = self.vreg(f("DATA0")); + let v = self.d16_data(v, half); + return self.guarded(act, &mut |lw| lw.lds_bits_store(at, sh, mask, v)); + } + let vd = f("VDST"); + let v = self.vreg(vd); + return self.guarded(act, &mut |lw| { + let w = lw.lds_ld(at); + let raw = lw.bin(BinOp::LShr, w, sh); + let nv = lw.d16_merge(v, raw, bits / 8, signed, half); + lw.vset(vd, nv); + Ok(()) + }); + } + let small = match name { + "ds_write_b8" => Some((8u32, false, true)), + "ds_write_b16" => Some((16, false, true)), + "ds_read_u8" => Some((8, false, false)), + "ds_read_i8" => Some((8, true, false)), + "ds_read_u16" => Some((16, false, false)), + "ds_read_i16" => Some((16, true, false)), + _ => None, + }; + if let Some((bits, signed, write)) = small { + let at = self.addc(a, off16); + let sh = self.andc(at, 3); + let sh = self.shlc(sh, 3); + let mask = ((1u64 << bits) - 1) as u32; + if write { + let v = self.vreg(f("DATA0")); + return self.guarded(act, &mut |lw| lw.lds_bits_store(at, sh, mask, v)); + } + let vd = f("VDST"); + return self.guarded(act, &mut |lw| { + let w = lw.lds_ld(at); + let x = lw.bin(BinOp::LShr, w, sh); + let x = lw.andc(x, mask); + let val = if signed { + let y = lw.shlc(x, 32 - bits); + lw.ashrc(y, 32 - bits) + } else { + x + }; + lw.vset(vd, val); + Ok(()) + }); + } + let rw = match name { + "ds_read_b32" => Some((false, 1, 1, false)), + "ds_read_b64" => Some((false, 2, 1, false)), + "ds_read_b96" => Some((false, 3, 1, false)), + "ds_read_b128" => Some((false, 4, 1, false)), + "ds_write_b32" => Some((true, 1, 1, false)), + "ds_write_b64" => Some((true, 2, 1, false)), + "ds_write_b96" => Some((true, 3, 1, false)), + "ds_write_b128" => Some((true, 4, 1, false)), + "ds_read2_b32" => Some((false, 1, 4, true)), + "ds_read2_b64" => Some((false, 2, 8, true)), + "ds_read2st64_b32" => Some((false, 1, 256, true)), + "ds_read2st64_b64" => Some((false, 2, 512, true)), + "ds_write2_b32" => Some((true, 1, 4, true)), + "ds_write2_b64" => Some((true, 2, 8, true)), + "ds_write2st64_b32" => Some((true, 1, 256, true)), + "ds_write2st64_b64" => Some((true, 2, 512, true)), + _ => None, + }; + if let Some((write, n, stride, two)) = rw { + let addrs: Vec = if two { + vec![self.addc(a, (o0 * stride) as u32), self.addc(a, (o1 * stride) as u32)] + } else { + vec![self.addc(a, off16)] + }; + let (vd, d0, d1) = (f("VDST"), f("DATA0"), f("DATA1")); + let srcs: Vec> = if write { + (0..addrs.len()).map(|e| (0..n).map(|k| self.vreg(if e == 0 { d0 } else { d1 } + k)).collect()).collect() + } else { + Vec::new() + }; + return self.guarded(act, &mut |lw| { + for (e, &at) in addrs.iter().enumerate() { + for k in 0..n { + let slot = lw.addc(at, 4 * k as u32); + if write { + lw.lds_st(slot, srcs[e][k as usize]); + } else { + let v = lw.lds_ld(slot); + lw.vset(vd + e as u64 * n + k, v); + } + } + } + Ok(()) + }); + } + let (op, rtn) = match name.strip_prefix("ds_") { + Some(r) if r.contains("_rtn_") => (r.replacen("_rtn", "", 1), true), + Some(r) => (r.to_string(), false), + None => return err(d, "DS"), + }; + if op == "wrxchg2_b32" || op == "wrxchg2st64_b32" { + let stride = if op == "wrxchg2_b32" { 4 } else { 256 }; + let (a0, a1) = (self.addc(a, (o0 * stride) as u32), self.addc(a, (o1 * stride) as u32)); + let (v0, v1) = (self.vreg(f("DATA0")), self.vreg(f("DATA1"))); + let vd = f("VDST"); + return self.guarded(act, &mut |lw| { + let g = lw.lds.expect("lds"); + let i0 = lw.lds_index(a0); + let r0 = lw.s.gs_atomic(RmwOp::Xchg, g, i0, v0); + let i1 = lw.lds_index(a1); + let r1 = lw.s.gs_atomic(RmwOp::Xchg, g, i1, v1); + if rtn { + lw.vset(vd, r0); + lw.vset(vd + 1, r1); + } + Ok(()) + }); + } + let (d0, d1) = (self.vreg(f("DATA0")), self.vreg(f("DATA1"))); + let (v, v2) = if op.starts_with("cmpst_") { (d1, d0) } else { (d0, d1) }; + let at = self.addc(a, off16); + let vd = f("VDST"); + let mut e = None; + self.guarded(act, &mut |lw| { + let i = lw.lds_index(at); + match lw.rmw32(d, &op, At::Lds(i), v, v2) { + Ok(o) => { + if rtn { + lw.vset(vd, o); + } + } + Err(x) => e = Some(x), + } + Ok(()) + })?; + match e { + Some(x) => Err(x), + None => Ok(()), + } + } + + /// `InterlockedAnd(slot, ~(mask << sh)); InterlockedOr(slot, (v & mask) << sh)` + fn lds_bits_store(&mut self, at: Value, sh: Value, mask: u32, v: Value) -> LResult<()> { + let g = self.lds.expect("lds"); + let i = self.lds_index(at); + let k = self.c(mask); + let m = self.bin(BinOp::Shl, k, sh); + let nm = self.not(m); + self.s.gs_atomic(RmwOp::And, g, i, nm); + let vm = self.andc(v, mask); + let vs = self.bin(BinOp::Shl, vm, sh); + self.s.gs_atomic(RmwOp::Or, g, i, vs); + Ok(()) + } + + /// `ds_swizzle_b32`'s source lane of this lane (`emit::swizzle_lane`; the upper + /// 32 lanes of a wave64 swizzle among themselves). + fn swizzle_lane(&mut self, offset: u64) -> Value { + let l = self.lane; + if offset >= 0xC000 { + // a permutation table: select chain over the 32 lanes + let mut v = self.c(0); + let l31 = self.andc(l, 0x1F); + for i in 0..32u32 { + let src = crate::gpu::recomp::emit::swizzle_lane(offset, i); + let is = self.cmpc(Pred::Eq, l31, i); + let k = self.c(src); + v = self.sel(is, k, v); + } + let up = self.andc(l, 0x20); + return self.or(up, v); + } + if offset & 0x8000 != 0 { + let a = self.andc(l, !3); + let q = self.andc(l, 3); + let sh = self.shlc(q, 1); + let k = self.c(offset as u32); + let s = self.bin(BinOp::LShr, k, sh); + let s = self.andc(s, 3); + return self.or(a, s); + } + let (and, or, xor) = ((offset & 0x1F) as u32, ((offset >> 5) & 0x1F) as u32, ((offset >> 10) & 0x1F) as u32); + let up = self.andc(l, 0x20); + let x = self.andc(l, 0x1F); + let x = self.andc(x, and); + let x = self.orc(x, or); + let k = self.c(xor); + let x = self.xor(x, k); + self.or(up, x) + } + + // ------------------------------------------------------------ scratch + + /// The lane's private memory (`xcl_scratch`, 1024 dwords), allocated in the entry block. + fn scratch_ptr(&mut self, i: Value) -> Value { + let arr = match self.scratch { + Some(a) => a, + None => { + let cur = self.cur(); + self.s.m.set_block(self.init.entry); + let i32 = self.s.m.i32(); + let t = self.s.m.array(1024, i32); + let a = self.s.m.alloca(t, 4); + self.s.m.set_block(cur); + self.scratch = Some(a); + a + } + }; + let z = self.c(0); + self.s.m.gep(arr, &[z, i]) + } + fn scr_slot(&mut self, a: Value) -> Value { + let b = self.lshrc(a, 2); + self.andc(b, 1023) + } + fn scr_ld(&mut self, a: Value) -> Value { + let b = self.scr_slot(a); + let s = self.andc(a, 3); + let s = self.shlc(s, 3); + let p = self.scratch_ptr(b); + let lo = self.s.m.load(p, 4); + let b1 = self.addc(b, 1); + let b1 = self.andc(b1, 1023); + let p1 = self.scratch_ptr(b1); + let hi = self.s.m.load(p1, 4); + let x = self.bin(BinOp::LShr, lo, s); + let k32 = self.c(32); + let inv = self.sub(k32, s); + let inv = self.andc(inv, 31); + let y = self.bin(BinOp::Shl, hi, inv); + let xy = self.or(x, y); + let sz = self.cmpc(Pred::Eq, s, 0); + self.sel(sz, lo, xy) + } + fn scr_st(&mut self, a: Value, v: Value, n: u32) -> LResult<()> { + let b = self.scr_slot(a); + let s = self.andc(a, 3); + let s = self.shlc(s, 3); + let m = if n >= 4 { self.c(u32::MAX) } else { self.c((1u32 << (8 * n)) - 1) }; + let p = self.scratch_ptr(b); + let old = self.s.m.load(p, 4); + let ms = self.bin(BinOp::Shl, m, s); + let nm = self.not(ms); + let keep = self.and(old, nm); + let vm = self.and(v, m); + let vs = self.bin(BinOp::Shl, vm, s); + let nv = self.or(keep, vs); + self.s.m.store(p, nv, 4); + let snz = self.cmpc(Pred::Ne, s, 0); + let top = self.addc(s, 8 * n); + let over = self.cmpc(Pred::UGt, top, 32); + let spill = self.land(snz, over); + self.guarded(spill, &mut |lw| { + let b2 = lw.addc(b, 1); + let b2 = lw.andc(b2, 1023); + let p2 = lw.scratch_ptr(b2); + let old = lw.s.m.load(p2, 4); + let k32 = lw.c(32); + let inv = lw.sub(k32, s); + let inv = lw.andc(inv, 31); + let m2 = lw.bin(BinOp::LShr, m, inv); + let nm2 = lw.not(m2); + let keep = lw.and(old, nm2); + let vm = lw.and(v, m); + let v2 = lw.bin(BinOp::LShr, vm, inv); + let nv = lw.or(keep, v2); + lw.s.m.store(p2, nv, 4); + Ok(()) + }) + } + + fn scratch(&mut self, d: &Decoded, op: &str) -> LResult<()> { + let saddr = Self::fv(d, "SADDR"); + let base = if saddr != 0x7D && saddr != 0x7F { self.sreg(saddr) } else { self.vreg(Self::fv(d, "ADDR")) }; + let raw = Self::fv(d, "OFFSET") as u32; + let off = (((raw << 20) as i32) >> 20) as u32; + let a = self.addc(base, off); + let act = self.act(); + if let Some((n, signed, store, half)) = flat_small(op) { + if store { + let v = self.vreg(Self::fv(d, "DATA")); + let data = self.d16_data(v, half); + return self.guarded(act, &mut |lw| lw.scr_st(a, data, n)); + } + let vd = Self::fv(d, "VDST"); + let v = self.vreg(vd); + return self.guarded(act, &mut |lw| { + let raw = lw.scr_ld(a); + let nv = lw.d16_merge(v, raw, n, signed, half); + lw.vset(vd, nv); + Ok(()) + }); + } + let (store, count) = match op { + "load_dword" => (false, 1), + "load_dwordx2" => (false, 2), + "load_dwordx3" => (false, 3), + "load_dwordx4" => (false, 4), + "store_dword" => (true, 1), + "store_dwordx2" => (true, 2), + "store_dwordx3" => (true, 3), + "store_dwordx4" => (true, 4), + _ => return err(d, "SCRATCH"), + }; + let vals: Vec = if store { (0..count).map(|i| self.vreg(Self::fv(d, "DATA") + i)).collect() } else { Vec::new() }; + let vd = Self::fv(d, "VDST"); + self.guarded(act, &mut |lw| { + for i in 0..count { + let at = lw.addc(a, 4 * i as u32); + let slot = lw.scr_slot(at); + let p = lw.scratch_ptr(slot); + if store { + lw.s.m.store(p, vals[i as usize], 4); + } else { + let v = lw.s.m.load(p, 4); + lw.vset(vd + i, v); + } + } + Ok(()) + }) + } + + // ------------------------------------------------------------ exports + + /// Mesh mode `s_sendmsg`: GS_ALLOC_REQ (M0 = primitives << 12 | vertices) into the + /// record header by lane 0 of each wave. + pub fn mesh_sendmsg(&mut self, d: &Decoded) -> LResult<()> { + if Self::fv(d, "SIMM16") & 0xF != 9 { + return Ok(()); + } + let m0 = self.sreg(124); + let rec = self.mesh.as_ref().expect("mesh").rec; + let res = self.res.expect("res"); + let lane = self.lane; + let first = self.cmpc(Pred::Eq, lane, 0); + self.guarded(first, &mut |lw| { + let v = lw.andc(m0, 0x3FF); + let p = lw.lshrc(m0, 12); + let p = lw.andc(p, 0x7FF); + let a = lw.shlc(rec, 2); + lw.s.raw_store(res, a, &[v]); + let a4 = lw.addc(a, 4); + lw.s.raw_store(res, a4, &[p]); + Ok(()) + }) + } + + /// Mesh mode exports: position / params into this thread's vertex slot, `prim` into its + /// primitive slot. + fn mesh_export(&mut self, d: &Decoded, en: u64, tgt: u64, compr: bool, srcs: &[Value]) -> LResult<()> { + let comp = |lw: &mut Lw, c: usize| -> Value { + if compr { + let r = srcs[c / 2]; + if c % 2 == 0 { + lw.andc(r, 0xFFFF) + } else { + lw.lshrc(r, 16) + } + } else { + srcs[c] + } + }; + let enabled = |c: usize| if compr { en >> (c / 2 * 2) & 3 != 0 } else { en >> c & 1 == 1 }; + let (vtx, prm) = { + let m = self.mesh.as_ref().expect("mesh"); + (m.vtx, m.prm) + }; + // (dword index in res, value) + let mut st: Vec<(Value, Value)> = Vec::new(); + match tgt { + 12 => { + for c in 0..4 { + if enabled(c) { + let at = self.addc(vtx, c as u32); + let v = comp(self, c); + st.push((at, v)); + } + } + } + 13..=15 | 9 => {} + 32..=63 => { + let k = (tgt - 32) as usize; + let outputs = self.mesh.as_ref().expect("mesh").outputs.clone(); + let at = crate::gpu::recomp::param_registers(&outputs, true).get(k).map(|&r| crate::gpu::recomp::elements_at(&outputs, true, r)).unwrap_or_default(); + for j in at { + for c in 0..4 { + if enabled(c) { + let a = self.addc(vtx, (4 * (j + 1) + c) as u32); + let v = comp(self, c); + st.push((a, v)); + } + } + } + } + 20 => st.push((prm, srcs[0])), + _ => return err(d, "export target"), + } + if st.is_empty() { + return Ok(()); + } + let res = self.res.expect("res"); + let act = self.act(); + self.guarded(act, &mut |lw| { + for &(at, v) in &st { + let off = lw.shlc(at, 2); + lw.s.raw_store(res, off, &[v]); + } + Ok(()) + }) + } + + pub fn export(&mut self, d: &Decoded) -> LResult<()> { + let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); + let (en, tgt, compr) = (f("EN"), f("TGT"), f("COMPR") != 0); + let srcs: Vec = (0..4).map(|i| self.vreg(f(&format!("VSRC{i}")))).collect(); + if self.mesh.is_some() { + return self.mesh_export(d, en, tgt, compr, &srcs); + } + if self.gfx.is_some() { + return self.export_gfx(d, en, tgt, compr, &srcs); + } + let act = self.act(); + let mut st = Vec::new(); + for c in 0..4u64 { + let val = if compr { + let r = srcs[(c / 2) as usize]; + if c % 2 == 0 { + self.andc(r, 0xFFFF) + } else { + self.lshrc(r, 16) + } + } else { + srcs[c as usize] + }; + let bit = if compr { 1 << (c / 2 * 2) | 2 << (c / 2 * 2) } else { 1 << c }; + if en & bit == 0 { + continue; + } + st.push((c, val)); + } + if st.is_empty() { + return Ok(()); + } + let res = self.res.expect("res"); + let lane = self.lane; + self.guarded(act, &mut |lw| { + for &(c, val) in &st { + // (KERNEL_EXPORTS + ((tgt * 64 + lane) * 4 + c)) * 4 + let k = lw.c((tgt as usize * KERNEL_LANES) as u32); + let x = lw.add(k, lane); + let x = lw.shlc(x, 2); + let x = lw.addc(x, (KERNEL_EXPORTS as u64 + c) as u32); + let off = lw.shlc(x, 2); + lw.s.raw_store(res, off, &[val]); + } + Ok(()) + }) + } +} diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs new file mode 100644 index 000000000..0313539e4 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -0,0 +1,1232 @@ +//! Vector ALU lowering: 32-bit integer and float operations, compares, +//! source / output modifiers, SDWA and DPP (port of `recomp/emit.rs` `valu`). + +use super::lower::{err, ext_encoding, Dst, LResult, Lw, Mods, VAR_VGPR}; +use super::module::{BinOp, Pred, Value}; +use super::ops_core::op; +use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; + +/// A source operand: one dword, or a mask pair (SGPR pair / VCC). +#[derive(Clone, Copy)] +pub enum Src { + W(Value), + Pair(Value, Value), +} + +impl Src { + pub fn w(self) -> Value { + match self { + Src::W(v) => v, + Src::Pair(l, _) => l, + } + } +} + +impl Lw { + pub fn mods(d: &Decoded) -> Mods { + let fv = |e: &Encoding, n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + let bit = |e: &Encoding, n: &str| fv(e, n) == 1; + match d.variant { + Variant::Sdwa => match ext_encoding(d) { + Some(e) => Mods { + abs: [bit(e, "SRC0_ABS"), bit(e, "SRC1_ABS"), false], + neg: [bit(e, "SRC0_NEG"), bit(e, "SRC1_NEG"), false], + omod: fv(e, "OMOD"), + clamp: bit(e, "CLAMP"), + opsel: 0, + }, + None => Mods::default(), + }, + Variant::Dpp16 => match ext_encoding(d) { + Some(e) => Mods { + abs: [bit(e, "SRC0_ABS"), bit(e, "SRC1_ABS"), false], + neg: [bit(e, "SRC0_NEG"), bit(e, "SRC1_NEG"), false], + ..Default::default() + }, + None => Mods::default(), + }, + Variant::Dpp8 => Mods::default(), + Variant::Plain => { + let e = d.enc; + let (abs, neg) = (fv(e, "ABS"), fv(e, "NEG")); + Mods { + abs: [abs & 1 == 1, abs >> 1 & 1 == 1, abs >> 2 & 1 == 1], + neg: [neg & 1 == 1, neg >> 1 & 1 == 1, neg >> 2 & 1 == 1], + omod: fv(e, "OMOD"), + clamp: bit(e, "CLAMP"), + opsel: fv(e, "OP_SEL"), + } + } + } + } + + /// Float view of a dword with abs / neg of source `i`. + pub fn fsrc(&mut self, m: &Mods, i: usize, u: Value) -> Value { + let mut s = self.f(u); + if m.abs[i] { + s = self.fabs(s); + } + if m.neg[i] { + s = self.fneg(s); + } + s + } + + /// Float result with output modifiers, as dword bits. + pub fn fres(&mut self, m: &Mods, e: Value) -> Value { + let mut s = match m.omod { + 1 => { + let k = self.fc(2.0); + self.fmul(e, k) + } + 2 => { + let k = self.fc(4.0); + self.fmul(e, k) + } + 3 => { + let k = self.fc(0.5); + self.fmul(e, k) + } + _ => e, + }; + if m.clamp { + s = self.un(op::SATURATE, s); + } + self.bits(s) + } + + /// DPP16 source lane (i32, −1 = none) of lane `lane`. + fn dpp16_src(&mut self, ctrl: u64) -> Option { + let n = (ctrl & 15) as u32; + let l = self.lane; + Some(match ctrl { + 0x000..=0x0FF => { + let a = self.andc(l, !3); + let q = self.andc(l, 3); + let sh = self.shlc(q, 1); + let k = self.c(ctrl as u32); + let s = self.bin(BinOp::LShr, k, sh); + let s = self.andc(s, 3); + self.or(a, s) + } + 0x101..=0x10F => { + let r = self.andc(l, 15); + let r = self.addc(r, n); + let ok = self.cmpc(Pred::ULt, r, 16); + let t = self.addc(l, n); + let m1 = self.c(u32::MAX); + self.sel(ok, t, m1) + } + 0x111..=0x11F => { + let r = self.andc(l, 15); + let ok = self.cmpc(Pred::UGe, r, n); + let k = self.c(n); + let t = self.sub(l, k); + let m1 = self.c(u32::MAX); + self.sel(ok, t, m1) + } + 0x121..=0x12F => { + let a = self.andc(l, !15); + let r = self.andc(l, 15); + let k = self.c(n); + let r = self.sub(r, k); + let r = self.andc(r, 15); + self.or(a, r) + } + 0x140 => { + let a = self.andc(l, !15); + let r = self.andc(l, 15); + let k = self.c(15); + let r = self.sub(k, r); + self.or(a, r) + } + 0x141 => { + let a = self.andc(l, !15); + let b8 = self.andc(l, 8); + let r = self.andc(l, 7); + let k = self.c(7); + let r = self.sub(k, r); + let x = self.or(a, b8); + self.or(x, r) + } + 0x150..=0x15F => { + let a = self.andc(l, !15); + let k = self.c(n); + self.or(a, k) + } + 0x160..=0x16F => { + let k = self.c(n); + self.xor(l, k) + } + _ => return None, + }) + } + + /// Source dwords in operand order; SGPR-pair masks as `Src::Pair`. SDWA + /// selects / extends its two sources, DPP reads src0 from another lane. + pub fn sources(&mut self, d: &Decoded, ins: &[&Operand], src_f16: bool) -> LResult> { + let mut u = Vec::new(); + for o in ins { + if d.variant != Variant::Plain && o.field == Some("SRC0") { + u.push(Src::W(self.c(0))); + continue; + } + match o.ty { + "OPR_SREG" | "OPR_VCC" if o.size == 64 => { + let (l, h) = self.read64(d, o, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + u.push(Src::Pair(l, h)); + } + _ if o.size == 64 => return err(d, "operand 64-bit"), + _ => u.push(Src::W(self.read(d, o, src_f16).ok_or_else(|| format!("{}: op", rdna2::format(d)))?)), + } + } + match d.variant { + Variant::Plain => {} + Variant::Sdwa => { + let e = ext_encoding(d).ok_or_else(|| format!("{}: SDWA", rdna2::format(d)))?; + let fv = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + let s0 = if fv("S0") == 1 { self.code32(fv("VSRC0"), None, src_f16).ok_or("op")? } else { self.vreg(fv("VSRC0")) }; + if !u.is_empty() { + u[0] = Src::W(self.sdwa_sel(s0, fv("SRC0_SEL") as u32, fv("SRC0_SEXT") == 1)); + } + if e.field("VSRC1").is_some() && u.len() > 1 { + let v1 = fv("VSRC1"); + let s1 = if fv("S1") == 1 { self.code32(v1, None, src_f16).ok_or("op")? } else { self.vreg(v1) }; + u[1] = Src::W(self.sdwa_sel(s1, fv("SRC1_SEL") as u32, fv("SRC1_SEXT") == 1)); + } + } + Variant::Dpp16 | Variant::Dpp8 => { + let e = ext_encoding(d).ok_or_else(|| format!("{}: DPP", rdna2::format(d)))?; + let fv = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); + let v = self.vreg(fv("VSRC0")); + let (el, eh) = self.exec_mask(); + let t; + if d.variant == Variant::Dpp16 { + let ctrl = fv("DPP_CTRL"); + let (fi, bound) = (fv("FI") == 1, fv("BOUND_CTRL") == 1); + let l = self.dpp16_src(ctrl).ok_or_else(|| format!("{}: DPP_CTRL", rdna2::format(d)))?; + let z = self.c(0); + let valid = self.cmp(Pred::SGe, l, z); + let lc = self.imax(l, z); + let on = self.lanebit_at(el, eh, lc); + let fib = self.b(fi); + let ok0 = self.lor(fib, on); + let ok = self.land(valid, ok0); + let r = self.read_lane_half(v, lc); + let (rm, bm) = (fv("ROW_MASK") as u32, fv("BANK_MASK") as u32); + let lane = self.lane; + let row = self.lshrc(lane, 4); + let k = self.c(rm); + let rb = self.bin(BinOp::LShr, k, row); + let rb = self.andc(rb, 1); + let rok = self.nz(rb); + let bank = self.lshrc(lane, 2); + let bank = self.andc(bank, 3); + let k = self.c(bm); + let bb = self.bin(BinOp::LShr, k, bank); + let bb = self.andc(bb, 1); + let bok = self.nz(bb); + let mut en = self.land(rok, bok); + if bound { + t = self.sel(ok, r, z); + } else { + en = self.land(en, ok); + t = r; + } + self.dpp_enable = Some(en); + } else { + let sel: u64 = (0..8).map(|i| fv(&format!("LANE_SEL_{i}")) << (3 * i)).sum(); + let fi = rdna2::field_value(d.enc, &d.words, "SRC0").unwrap_or(0) == 0xEA; + let lane = self.lane; + let a = self.andc(lane, !7); + let q = self.andc(lane, 7); + let k3 = self.c(3); + let sh = self.mul(q, k3); + let k = self.c(sel as u32); + let s = self.bin(BinOp::LShr, k, sh); + let s = self.andc(s, 7); + let l = self.or(a, s); + let r = self.read_lane_half(v, l); + t = if !fi { + let on = self.lanebit_at(el, eh, l); + let z = self.c(0); + self.sel(on, r, z) + } else { + r + }; + } + if !u.is_empty() { + u[0] = Src::W(t); + } + } + } + Ok(u) + } + + pub fn sdwa_sel(&mut self, x: Value, sel: u32, sext: bool) -> Value { + if sel >= 6 { + return x; + } + let (sh, w) = if sel < 4 { (8 * sel, 8) } else { (16 * (sel - 4), 16) }; + let v = self.lshrc(x, sh); + let v = self.andc(v, (1u32 << w) - 1); + if sext { + let s = self.shlc(v, 32 - w); + self.ashrc(s, 32 - w) + } else { + v + } + } + + fn sdwa_dst(&mut self, r: Value, old: Value, sel: u32, unused: u32) -> Value { + if sel >= 6 { + return r; + } + let (sh, w) = if sel < 4 { (8 * sel, 8u32) } else { (16 * (sel - 4), 16u32) }; + let m = (((1u64 << w) - 1) as u32) << sh; + let s = self.shlc(r, sh); + let v = self.andc(s, m); + match unused { + 2 => { + let o = self.andc(old, !m); + self.or(o, v) + } + 1 => { + let top = sh + w; + if top >= 32 { + return v; + } + let b = self.lshrc(r, w - 1); + let b = self.andc(b, 1); + let neg = self.nz(b); + let z = self.c(0); + let ext = self.c(u32::MAX << top); + let e = self.sel(neg, ext, z); + self.or(v, e) + } + _ => v, + } + } + + /// Writes a VALU result, honouring SDWA dst_sel / dst_unused and DPP write enables. + pub fn vwrite(&mut self, d: &Decoded, dst: &Dst, val: Value) { + let mut val = val; + if d.variant == Variant::Sdwa { + if let (Some(e), Dst::V(n)) = (ext_encoding(d), dst) { + let fv = |k: &str| rdna2::field_value(e, &d.words, k).unwrap_or(0); + if e.field("DST_SEL").is_some() { + let cur = self.vreg(*n); + val = self.sdwa_dst(val, cur, fv("DST_SEL") as u32, fv("DST_UNUSED") as u32); + } + } + } + match (self.dpp_enable.take(), dst) { + (Some(en), Dst::V(n)) => { + let old = self.vreg(*n); + let a = self.act(); + let c = self.land(a, en); + let v = self.sel(c, val, old); + self.wr(VAR_VGPR + *n as u32, v); + } + _ => self.write32(dst, val), + } + } + + pub fn valu(&mut self, d: &Decoded, name: &str) -> LResult<()> { + if name.starts_with("v_interp_") { + return self.interp_gfx(d, name); + } + let (outs, ins) = Self::ops(d); + const WIDE16: &[&str] = &[ + "v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32", "v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16", "v_cvt_pk_u16_u32", + "v_cvt_pk_i16_i32", "v_mad_u32_u16", "v_mad_i32_i16", "v_sad_u16", "v_sat_pk_u8_i16", + ]; + let f16 = (name.contains("f16") || name.contains("_i16") || name.contains("_u16") || name.contains("_b16")) && !WIDE16.contains(&name); + let cmp = name.starts_with("v_cmp"); + let src_f16 = matches!(name, "v_cvt_f32_f16" | "v_pack_b32_f16" | "v_cvt_pknorm_i16_f16" | "v_cvt_pknorm_u16_f16") || (cmp && name.ends_with("_f16")); + let mix = name.starts_with("v_fma_mix"); + if name.starts_with("v_pk_") || name.starts_with("v_dot") { + return self.valu_pk(d, name); + } + if name.starts_with("v_movrel") { + return self.movrel(d, name); + } + if name == "v_swaprel_b32" { + return self.swaprel(d); + } + if name == "v_swap_b32" && d.variant == Variant::Plain { + let s0 = Self::fv(d, "SRC0"); + if s0 < 256 { + return err(d, "v_swap_b32: SRC0 is not a VGPR"); + } + let (xn, yn) = (Self::fv(d, "VDST"), s0 - 256); + let (x, y) = (self.vreg(xn), self.vreg(yn)); + let a = self.act(); + let nx = self.sel(a, y, x); + let ny = self.sel(a, x, y); + self.wr(VAR_VGPR + xn as u32, nx); + self.wr(VAR_VGPR + yn as u32, ny); + return Ok(()); + } + if d.enc.name == "ENC_VOP3P" && !mix { + return err(d, "VOP3P"); + } + if d.variant != Variant::Plain && ext_encoding(d).is_none() { + return err(d, "SDWA/DPP in this encoding"); + } + self.dpp_enable = None; + if name.contains("f64") || name.contains("_i64") || name.contains("_u64") || name.contains("_b64") { + return self.valu64(d, name); + } + if f16 && !mix && !cmp && !matches!(name, "v_cvt_f32_f16" | "v_cvt_f16_f32" | "v_cvt_pkrtz_f16_f32" | "v_pack_b32_f16") { + return self.valu16(d, name); + } + let m = Self::mods(d); + let u = self.sources(d, &ins, src_f16)?; + if let Some(rest) = name.strip_prefix("v_cmpx_").or_else(|| name.strip_prefix("v_cmp_")) { + return self.vopc(d, rest, name.starts_with("v_cmpx_"), &outs, &u, &m); + } + let dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + let z = self.c(0); + let cur = match &dst { + Dst::V(n) => self.vreg(*n), + _ => z, + }; + let a = u.first().map(|s| s.w()).unwrap_or(z); + let b = u.get(1).map(|s| s.w()).unwrap_or(z); + let c = u.get(2).map(|s| s.w()).unwrap_or(z); + let wmask = if self.wave64 { 63 } else { 31 }; + macro_rules! fs { + ($i:expr) => {{ + let x = u.get($i).map(|s| s.w()).unwrap_or(z); + self.fsrc(&m, $i, x) + }}; + } + macro_rules! fr { + ($e:expr) => {{ + let e = $e; + self.fres(&m, e) + }}; + } + let res: Value = match name { + "v_mov_b32" | "v_mov_fed_b32" => a, + "v_not_b32" => self.not(a), + "v_bfrev_b32" => self.reversebits(a), + "v_ffbh_u32" => self.lzcnt(a), + "v_ffbl_b32" => self.firstbitlow(a), + "v_ffbh_i32" => self.ffbh_i(a), + "v_cvt_f32_i32" => fr!(self.sitof(a)), + "v_cvt_f32_u32" => fr!(self.uitof(a)), + "v_cvt_u32_f32" => { + let x = fs!(0); + self.cvt_u32(x) + } + "v_cvt_i32_f32" => { + let x = fs!(0); + self.cvt_i32(x) + } + "v_cvt_rpi_i32_f32" => { + let x = fs!(0); + let h = self.fc(0.5); + let x = self.fadd(x, h); + let x = self.un(op::ROUND_NI, x); + self.cvt_i32(x) + } + "v_cvt_flr_i32_f32" => { + let x = fs!(0); + let x = self.un(op::ROUND_NI, x); + self.cvt_i32(x) + } + "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { + let k = (name.as_bytes()[name.len() - 1] - b'0') as u32; + let x = self.lshrc(a, 8 * k); + let x = self.andc(x, 0xFF); + fr!(self.uitof(x)) + } + "v_cvt_f32_f16" => { + let h = if m.opsel & 1 == 1 { self.lshrc(a, 16) } else { self.andc(a, 0xFFFF) }; + fr!(self.s.f16_to_f32(h)) + } + "v_cvt_f16_f32" => { + let x = fs!(0); + // output modifier and clamp in f32, before the conversion + let x = if m.omod != 0 || m.clamp { + let b = self.fres(&m, x); + self.f(b) + } else { + x + }; + let h = self.to_f16(x); + if m.opsel >> 3 & 1 == 1 { + let l = self.andc(cur, 0xFFFF); + let hh = self.shlc(h, 16); + self.or(l, hh) + } else if d.variant == Variant::Sdwa { + h + } else { + let hi = self.andc(cur, 0xFFFF_0000); + self.or(hi, h) + } + } + "v_cvt_pkrtz_f16_f32" => { + let (x, y) = (fs!(0), fs!(1)); + let l = self.f16_rtz(x); + let h = self.f16_rtz(y); + let h = self.shlc(h, 16); + self.or(l, h) + } + "v_pack_b32_f16" => { + let lo = if m.opsel & 1 == 1 { self.lshrc(a, 16) } else { self.andc(a, 0xFFFF) }; + let hi = if m.opsel & 2 == 2 { self.lshrc(b, 16) } else { self.andc(b, 0xFFFF) }; + let hi = self.shlc(hi, 16); + self.or(lo, hi) + } + "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { + let fv = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); + let (sel, hi2) = (fv("OP_SEL"), fv("OP_SEL_HI") | fv("OP_SEL_HI_2") << 2); + let (neg, abs) = (fv("NEG"), fv("NEG_HI")); + let mut srcs = Vec::new(); + for i in 0..3 { + let raw = u.get(i).map(|s| s.w()).unwrap_or(z); + let mut s = if hi2 >> i & 1 == 1 { + let h = if sel >> i & 1 == 1 { self.lshrc(raw, 16) } else { self.andc(raw, 0xFFFF) }; + self.s.f16_to_f32(h) + } else { + self.f(raw) + }; + if abs >> i & 1 == 1 { + s = self.fabs(s); + } + if neg >> i & 1 == 1 { + s = self.fneg(s); + } + srcs.push(s); + } + let mut e = self.fmad(srcs[0], srcs[1], srcs[2]); + if fv("CLAMP") == 1 { + e = self.un(op::SATURATE, e); + } + match name { + "v_fma_mix_f32" => self.bits(e), + "v_fma_mixlo_f16" => { + let h = self.to_f16(e); + let hi = self.andc(cur, 0xFFFF_0000); + self.or(hi, h) + } + _ => { + let h = self.to_f16(e); + let h = self.shlc(h, 16); + let lo = self.andc(cur, 0xFFFF); + self.or(lo, h) + } + } + } + "v_rcp_f32" | "v_rcp_iflag_f32" => { + let x = fs!(0); + let one = self.fc(1.0); + fr!(self.fdiv(one, x)) + } + "v_rsq_f32" => fr!({ + let x = fs!(0); + self.un(op::RSQRT, x) + }), + "v_sqrt_f32" => fr!({ + let x = fs!(0); + self.un(op::SQRT, x) + }), + "v_exp_f32" => fr!({ + let x = fs!(0); + self.un(op::EXP, x) + }), + "v_log_f32" => fr!({ + let x = fs!(0); + self.un(op::LOG, x) + }), + "v_sin_f32" | "v_cos_f32" => { + let x = fs!(0); + let k = self.fc(6.283_185_3); + let x = self.fmul(x, k); + fr!(self.un(if name == "v_sin_f32" { op::SIN } else { op::COS }, x)) + } + "v_fract_f32" => { + let x = fs!(0); + fr!(self.fract_f(x)) + } + "v_trunc_f32" => fr!({ + let x = fs!(0); + self.un(op::ROUND_Z, x) + }), + "v_floor_f32" => fr!({ + let x = fs!(0); + self.un(op::ROUND_NI, x) + }), + "v_ceil_f32" => fr!({ + let x = fs!(0); + self.un(op::ROUND_PI, x) + }), + "v_rndne_f32" => fr!({ + let x = fs!(0); + self.un(op::ROUND_NE, x) + }), + "v_frexp_mant_f32" => { + let x = fs!(0); + fr!(self.frexp_mant(x)) + } + "v_frexp_exp_i32_f32" => { + let x = fs!(0); + self.frexp_exp(x) + } + "v_ldexp_f32" => { + let x = fs!(0); + fr!(self.ldexp_f(x, b)) + } + "v_add_f32" => { + let (x, y) = (fs!(0), fs!(1)); + fr!(self.fadd(x, y)) + } + "v_sub_f32" => { + let (x, y) = (fs!(0), fs!(1)); + fr!(self.fsub(x, y)) + } + "v_subrev_f32" => { + let (x, y) = (fs!(0), fs!(1)); + fr!(self.fsub(y, x)) + } + "v_mul_f32" => { + let (x, y) = (fs!(0), fs!(1)); + fr!(self.fmul(x, y)) + } + "v_mul_legacy_f32" => { + let (x, y) = (fs!(0), fs!(1)); + fr!(self.mul_legacy(x, y)) + } + "v_min_f32" => { + let (x, y) = (fs!(0), fs!(1)); + fr!(self.fmin(x, y)) + } + "v_max_f32" => { + let (x, y) = (fs!(0), fs!(1)); + fr!(self.fmax(x, y)) + } + "v_fmac_f32" | "v_mac_f32" | "v_fmac_legacy_f32" => { + let (x, y) = (fs!(0), fs!(1)); + let cf = self.f(cur); + fr!(match name { + "v_fmac_f32" => self.fmad(x, y, cf), + "v_mac_f32" => self.mad_nf(x, y, cf), + _ => self.fma_legacy(x, y, cf), + }) + } + "v_fma_f32" | "v_mad_f32" | "v_fma_legacy_f32" | "v_div_fmas_f32" => { + let (x, y, w) = (fs!(0), fs!(1), fs!(2)); + fr!(match name { + "v_fma_f32" | "v_div_fmas_f32" => self.fmad(x, y, w), + "v_mad_f32" => self.mad_nf(x, y, w), + _ => self.fma_legacy(x, y, w), + }) + } + "v_fmamk_f32" | "v_madmk_f32" => { + let (x, w) = (fs!(0), fs!(2)); + let k = self.f(b); + fr!(if name == "v_fmamk_f32" { self.fmad(x, k, w) } else { self.mad_nf(x, k, w) }) + } + "v_fmaak_f32" | "v_madak_f32" => { + let (x, y) = (fs!(0), fs!(1)); + let k = self.f(c); + fr!(if name == "v_fmaak_f32" { self.fmad(x, y, k) } else { self.mad_nf(x, y, k) }) + } + "v_min3_f32" => { + let (x, y, w) = (fs!(0), fs!(1), fs!(2)); + let t = self.fmin(x, y); + fr!(self.fmin(t, w)) + } + "v_max3_f32" => { + let (x, y, w) = (fs!(0), fs!(1), fs!(2)); + let t = self.fmax(x, y); + fr!(self.fmax(t, w)) + } + "v_med3_f32" => { + let (x, y, w) = (fs!(0), fs!(1), fs!(2)); + fr!(self.med3f(x, y, w)) + } + "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => { + let (x, y, w) = (fs!(0), fs!(1), fs!(2)); + fr!(self.cube(name, x, y, w)) + } + "v_div_fixup_f32" => { + let (q, dd, nn) = (fs!(0), fs!(1), fs!(2)); + fr!(self.div_fixup(q, dd, nn)) + } + // clamp: unsigned saturation + "v_add_nc_u32" | "v_add3_u32" if m.clamp => { + let t = self.add(a, b); + let over = self.cmp(Pred::ULt, t, a); + let (t, over) = if name == "v_add3_u32" { + let u = self.add(t, c); + let o2 = self.cmp(Pred::ULt, u, t); + (u, self.lor(over, o2)) + } else { + (t, over) + }; + let m1 = self.c(u32::MAX); + self.sel(over, m1, t) + } + "v_sub_nc_u32" | "v_subrev_nc_u32" if m.clamp => { + let (x, y) = if name == "v_sub_nc_u32" { (a, b) } else { (b, a) }; + let under = self.cmp(Pred::ULt, x, y); + let t = self.sub(x, y); + let z = self.c(0); + self.sel(under, z, t) + } + "v_add_nc_u32" => self.add(a, b), + "v_sub_nc_u32" => self.sub(a, b), + "v_subrev_nc_u32" => self.sub(b, a), + "v_mul_lo_u32" => self.mul(a, b), + "v_mul_hi_u32" => self.mul_hi(a, b, false), + "v_mul_hi_i32" => self.mul_hi(a, b, true), + "v_mul_u32_u24" => { + let (x, y) = (self.andc(a, 0xFF_FFFF), self.andc(b, 0xFF_FFFF)); + self.mul(x, y) + } + "v_mul_hi_u32_u24" => { + let (x, y) = (self.andc(a, 0xFF_FFFF), self.andc(b, 0xFF_FFFF)); + self.mul_hi(x, y, false) + } + "v_mul_i32_i24" => { + let (x, y) = (self.i24(a), self.i24(b)); + self.mul(x, y) + } + "v_mul_hi_i32_i24" => { + let (x, y) = (self.i24(a), self.i24(b)); + self.mul_hi(x, y, true) + } + "v_mad_u32_u24" => { + let (x, y) = (self.andc(a, 0xFF_FFFF), self.andc(b, 0xFF_FFFF)); + let p = self.mul(x, y); + self.add(p, c) + } + "v_mad_i32_i24" => { + let (x, y) = (self.i24(a), self.i24(b)); + let p = self.mul(x, y); + self.add(p, c) + } + "v_and_b32" => self.and(a, b), + "v_or_b32" => self.or(a, b), + "v_xor_b32" => self.xor(a, b), + "v_xnor_b32" => { + let x = self.xor(a, b); + self.not(x) + } + "v_lshlrev_b32" => self.shl(b, a), + "v_lshrrev_b32" => self.lshr(b, a), + "v_ashrrev_i32" => self.ashr(b, a), + "v_lshl_add_u32" => { + let x = self.shl(a, b); + self.add(x, c) + } + "v_add_lshl_u32" => { + let x = self.add(a, b); + self.shl(x, c) + } + "v_lshl_or_b32" => { + let x = self.shl(a, b); + self.or(x, c) + } + "v_and_or_b32" => { + let x = self.and(a, b); + self.or(x, c) + } + "v_or3_b32" => { + let x = self.or(a, b); + self.or(x, c) + } + "v_xor3_b32" => { + let x = self.xor(a, b); + self.xor(x, c) + } + "v_add3_u32" => { + let x = self.add(a, b); + self.add(x, c) + } + "v_xad_u32" => { + let x = self.xor(a, b); + self.add(x, c) + } + "v_bfe_u32" => self.bfe_u(a, b, c), + "v_bfe_i32" => self.bfe_i(a, b, c), + "v_bfi_b32" => { + let x = self.and(a, b); + let n = self.not(a); + let y = self.and(n, c); + self.or(x, y) + } + "v_bfm_b32" => self.bfm(a, b), + "v_bcnt_u32_b32" => { + let n = self.countbits(a); + self.add(n, b) + } + "v_perm_b32" => self.perm_b32(a, b, c), + "v_alignbit_b32" => self.alignbit(a, b, c), + "v_alignbyte_b32" => { + let s = self.andc(c, 3); + let s = self.shlc(s, 3); + self.alignbit(a, b, s) + } + "v_min_u32" => self.umin(a, b), + "v_max_u32" => self.umax(a, b), + "v_min_i32" => self.imin(a, b), + "v_max_i32" => self.imax(a, b), + "v_min3_u32" => { + let t = self.umin(a, b); + self.umin(t, c) + } + "v_max3_u32" => { + let t = self.umax(a, b); + self.umax(t, c) + } + "v_med3_u32" => { + let (x, y) = (self.umin(a, b), self.umax(a, b)); + let y = self.umin(y, c); + self.umax(x, y) + } + "v_min3_i32" => { + let t = self.imin(a, b); + self.imin(t, c) + } + "v_max3_i32" => { + let t = self.imax(a, b); + self.imax(t, c) + } + "v_med3_i32" => { + let (x, y) = (self.imin(a, b), self.imax(a, b)); + let y = self.imin(y, c); + self.imax(x, y) + } + "v_sad_u32" => { + let (x, y) = (self.umax(a, b), self.umin(a, b)); + let t = self.sub(x, y); + self.add(t, c) + } + "v_sad_u8" | "v_sad_hi_u8" => { + let s = self.sad_u8(a, b); + let s = if name == "v_sad_hi_u8" { self.shlc(s, 16) } else { s }; + self.add(s, c) + } + "v_sad_u16" => { + let x = self.absd(a, b, 0, 0xFFFF); + let y = self.absd(a, b, 16, 0xFFFF); + let t = self.add(x, y); + self.add(t, c) + } + "v_msad_u8" => { + let s = self.msad_u8(a, b); + self.add(s, c) + } + "v_lerp_u8" => self.lerp_u8(a, b, c), + "v_add_nc_i32" | "v_sub_nc_i32" if m.clamp => { + let (x, y) = (self.sext64(a), self.sext64(b)); + let r = if name == "v_add_nc_i32" { self.add(x, y) } else { self.sub(x, y) }; + self.sat_i32(r) + } + "v_add_nc_i32" => self.add(a, b), + "v_sub_nc_i32" => self.sub(a, b), + "v_mad_u32_u16" => { + let x = self.lshrc(a, 16 * (m.opsel & 1) as u32); + let x = self.andc(x, 0xFFFF); + let y = self.lshrc(b, 8 * (m.opsel & 2) as u32); + let y = self.andc(y, 0xFFFF); + let p = self.mul(x, y); + self.add(p, c) + } + "v_mad_i32_i16" => { + let x = self.lshrc(a, 16 * (m.opsel & 1) as u32); + let x = self.shlc(x, 16); + let x = self.ashrc(x, 16); + let y = self.lshrc(b, 8 * (m.opsel & 2) as u32); + let y = self.shlc(y, 16); + let y = self.ashrc(y, 16); + let p = self.mul(x, y); + self.add(p, c) + } + "v_cvt_pk_u16_u32" => { + let k = self.c(0xFFFF); + let x = self.umin(a, k); + let y = self.umin(b, k); + let y = self.shlc(y, 16); + self.or(x, y) + } + "v_cvt_pk_i16_i32" => { + let (lo, hi) = (self.c(-32768i32 as u32), self.c(32767)); + let x = self.imax(a, lo); + let x = self.imin(x, hi); + let x = self.andc(x, 0xFFFF); + let y = self.imax(b, lo); + let y = self.imin(y, hi); + let y = self.andc(y, 0xFFFF); + let y = self.shlc(y, 16); + self.or(x, y) + } + "v_cvt_pknorm_i16_f32" => { + let (x, y) = (fs!(0), fs!(1)); + let l = self.cvt_norm_i16_f32(x); + let h = self.cvt_norm_i16_f32(y); + let h = self.shlc(h, 16); + self.or(l, h) + } + "v_cvt_pknorm_u16_f32" => { + let (x, y) = (fs!(0), fs!(1)); + let l = self.cvt_norm_u16_f32(x); + let h = self.cvt_norm_u16_f32(y); + let h = self.shlc(h, 16); + self.or(l, h) + } + "v_cvt_pknorm_i16_f16" | "v_cvt_pknorm_u16_f16" => { + let mut hb = [z, z]; + for (i, slot) in hb.iter_mut().enumerate() { + let s = u.get(i).map(|s| s.w()).unwrap_or(z); + let mut s = if m.opsel >> i & 1 == 1 { self.lshrc(s, 16) } else { self.andc(s, 0xFFFF) }; + if m.abs[i] { + s = self.andc(s, 0x7FFF); + } + if m.neg[i] { + let k = self.c(0x8000); + s = self.xor(s, k); + } + *slot = s; + } + let (l, h) = if name == "v_cvt_pknorm_i16_f16" { + (self.cvt_norm_i16_f16(hb[0]), self.cvt_norm_i16_f16(hb[1])) + } else { + (self.cvt_norm_u16_f16(hb[0]), self.cvt_norm_u16_f16(hb[1])) + }; + let h = self.shlc(h, 16); + self.or(l, h) + } + "v_sat_pk_u8_i16" => { + let (lo, hi) = (self.c(0), self.c(255)); + let x = self.shlc(a, 16); + let x = self.ashrc(x, 16); + let x = self.imax(x, lo); + let x = self.imin(x, hi); + let y = self.ashrc(a, 16); + let y = self.imax(y, lo); + let y = self.imin(y, hi); + let y = self.shlc(y, 8); + self.or(x, y) + } + "v_cvt_pk_u8_f32" => { + let x = fs!(0); + let r = self.un(op::ROUND_NE, x); + let (lo, hi) = (self.fc(0.0), self.fc(255.0)); + let r = self.fmax(r, lo); + let r = self.fmin(r, hi); + let v = self.ftoui(r); + let sel = self.andc(b, 3); + let sh = self.shlc(sel, 3); + let k = self.c(0xFF); + let msk = self.shl(k, sh); + let nm = self.not(msk); + let keep = self.and(c, nm); + let v = self.shl(v, sh); + self.or(keep, v) + } + "v_mbcnt_lo_u32_b32" => { + let m = self.lanemask_lt(false); + let x = self.and(a, m); + let n = self.countbits(x); + self.add(n, b) + } + "v_mbcnt_hi_u32_b32" => { + let m = self.lanemask_lt(true); + let x = self.and(a, m); + let n = self.countbits(x); + self.add(n, b) + } + "v_cndmask_b32" => { + let Some(Src::Pair(l, h)) = u.get(2).copied() else { return err(d, "mask") }; + let bit = self.lane_of(l, h); + self.sel(bit, b, a) + } + "v_permlane16_b32" | "v_permlanex16_b32" => { + let (fi, bound) = (m.opsel & 1 == 1, m.opsel & 2 == 2); + let lane = self.lane; + let r = self.andc(lane, 15); + let lo8 = self.cmpc(Pred::ULt, r, 8); + let w = self.sel(lo8, b, c); + let q = self.andc(lane, 7); + let sh = self.shlc(q, 2); + let nsel = self.bin(BinOp::LShr, w, sh); + let nsel = self.andc(nsel, 15); + let base = self.andc(lane, !31); + let row = self.andc(lane, 16); + let row = if name == "v_permlanex16_b32" { + let k = self.c(16); + let x = self.xor(row, k); + self.andc(x, 16) + } else { + row + }; + let l = self.or(base, row); + let l = self.or(l, nsel); + let (el, eh) = self.exec_mask(); + let on = self.lanebit_at(el, eh, l); + let fib = self.b(fi); + let ok = self.lor(fib, on); + let v = self.read_lane_half(a, l); + if bound { + self.sel(ok, v, z) + } else { + self.sel(ok, v, cur) + } + } + "v_readfirstlane_b32" => { + let (el, eh) = self.exec_mask(); + let l = self.first_lane(el, eh); + let t = self.read_lane_uniform(a, l); + self.write32(&dst, t); + return Ok(()); + } + "v_readlane_b32" => { + let l = self.andc(b, wmask); + let t = self.read_lane_uniform(a, l); + self.write32(&dst, t); + return Ok(()); + } + "v_writelane_b32" => { + if let Dst::V(n) = dst { + let l = self.andc(b, wmask); + let lane = self.lane; + let me = self.cmp(Pred::Eq, lane, l); + let v = self.sel(me, a, cur); + self.wr(VAR_VGPR + n as u32, v); + } + return Ok(()); + } + "v_div_scale_f32" => { + let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); + let f = self.b(false); + self.write_mask(&sdst, f); + let x = fs!(0); + let r = self.bits(x); + self.vwrite(d, &dst, r); + return Ok(()); + } + "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" => { + let (x, y) = if name == "v_subrev_co_u32" { (b, a) } else { (a, b) }; + let (t, carry) = if name == "v_add_co_u32" { + let t = self.add(x, y); + (t, self.cmp(Pred::ULt, t, x)) + } else { + let t = self.sub(x, y); + (t, self.cmp(Pred::UGt, y, x)) + }; + let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); + self.write_mask(&sdst, carry); + self.vwrite(d, &dst, t); + return Ok(()); + } + "v_add_co_ci_u32" | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => { + let Some(Src::Pair(l, h)) = u.get(2).copied() else { return err(d, "mask") }; + let cb = self.lane_of(l, h); + let cin = self.u(cb); + let (x, y) = if name == "v_subrev_co_ci_u32" { (b, a) } else { (a, b) }; + let (x6, y6, c6) = (self.zext64(x), self.zext64(y), self.zext64(cin)); + let w = if name == "v_add_co_ci_u32" { + let s = self.add(x6, y6); + self.add(s, c6) + } else { + let s = self.sub(x6, y6); + self.sub(s, c6) + }; + let (t, hi) = self.unpack64(w); + let carry = self.nz(hi); + let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); + self.write_mask(&sdst, carry); + self.vwrite(d, &dst, t); + return Ok(()); + } + _ => return err(d, "VALU"), + }; + self.vwrite(d, &dst, res); + Ok(()) + } + + 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 { + return err(d, "VOPC"); + } + let (mut ua, mut ub) = (u[0].w(), u[1].w()); + let half = |s: &mut Self, i: u64, v: Value| if m.opsel >> i & 1 == 1 { s.lshrc(v, 16) } else { s.andc(v, 0xFFFF) }; + let ty = match ty { + "f16" => { + if opn == "class" { + let mut h = half(self, 0, ua); + if m.abs[0] { + h = self.andc(h, 0x7FFF); + } + if m.neg[0] { + let k = self.c(0x8000); + h = self.xor(h, k); + } + let cls = self.fclass16(h); + let s = self.bin(BinOp::LShr, ub, cls); + let s = self.andc(s, 1); + let cond = self.nz(s); + return self.vopc_write(d, cmpx, outs, cond); + } + let ha = half(self, 0, ua); + let fa = self.s.f16_to_f32(ha); + ua = self.bits(fa); + let hb = half(self, 1, ub); + let fb = self.s.f16_to_f32(hb); + ub = self.bits(fb); + "f32" + } + "u16" => { + ua = half(self, 0, ua); + ub = half(self, 1, ub); + "u32" + } + "i16" => { + let x = half(self, 0, ua); + let x = self.shlc(x, 16); + ua = self.ashrc(x, 16); + let y = half(self, 1, ub); + let y = self.shlc(y, 16); + ub = self.ashrc(y, 16); + "i32" + } + t => t, + }; + let cond = match ty { + "f32" => { + let a = self.fsrc(m, 0, ua); + if opn == "class" { + let cls = self.fclass(a); + let s = self.bin(BinOp::LShr, ub, cls); + let s = self.andc(s, 1); + self.nz(s) + } else { + let b = self.fsrc(m, 1, ub); + self.float_compare(opn, a, b).ok_or_else(|| format!("{}: VOPC f32", rdna2::format(d)))? + } + } + "i32" | "u32" => { + let s = ty == "i32"; + match opn { + "f" => self.b(false), + "t" | "tru" => self.b(true), + "lt" => self.cmp(if s { Pred::SLt } else { Pred::ULt }, ua, ub), + "eq" => self.cmp(Pred::Eq, ua, ub), + "le" => self.cmp(if s { Pred::SLe } else { Pred::ULe }, ua, ub), + "gt" => self.cmp(if s { Pred::SGt } else { Pred::UGt }, ua, ub), + "ne" | "lg" => self.cmp(Pred::Ne, ua, ub), + "ge" => self.cmp(if s { Pred::SGe } else { Pred::UGe }, ua, ub), + _ => return err(d, "VOPC int"), + } + } + _ => return err(d, "VOPC type"), + }; + self.vopc_write(d, cmpx, outs, cond) + } + + /// The recompiler's `float_compare`: NaN tested explicitly. + pub fn float_compare(&mut self, opn: &str, a: Value, b: Value) -> Option { + let rel = |s: &mut Self, r: &str| -> Option { + Some(match r { + "lt" => s.fcmp(Pred::FOLt, a, b), + "eq" => s.fcmp(Pred::FOEq, a, b), + "le" => s.fcmp(Pred::FOLe, a, b), + "gt" => s.fcmp(Pred::FOGt, a, b), + "ge" => s.fcmp(Pred::FOGe, a, b), + "lg" => { + let x = s.fcmp(Pred::FOLt, a, b); + let y = s.fcmp(Pred::FOGt, a, b); + s.lor(x, y) + } + _ => return None, + }) + }; + let nan = |s: &mut Self| { + let x = s.isnan_any(a); + let y = s.isnan_any(b); + s.lor(x, y) + }; + Some(match opn { + "f" => self.b(false), + "t" | "tru" => self.b(true), + "o" => { + let n = nan(self); + self.lnot(n) + } + "u" => nan(self), + _ => match opn.strip_prefix('n').filter(|r| matches!(*r, "lt" | "eq" | "le" | "gt" | "ge" | "lg")) { + Some(r) => { + let n = nan(self); + let x = rel(self, r)?; + let nx = self.lnot(x); + self.lor(n, nx) + } + None => { + let n = nan(self); + let nn = self.lnot(n); + let x = rel(self, opn)?; + self.land(nn, x) + } + }, + }) + } + + /// IsNaN of a float or double (doubles from their bits: DXC narrows `isnan`). + pub fn isnan_any(&mut self, x: Value) -> Value { + let t = self.s.m.type_of(x); + if t == self.s.m.f64() { + self.isnan_d(x) + } else { + self.isnan(x) + } + } + + pub fn vopc_write(&mut self, d: &Decoded, cmpx: bool, outs: &[&Operand], cond: Value) -> LResult<()> { + let mut dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); + if d.variant == Variant::Sdwa { + if let Some(e) = ext_encoding(d) { + if rdna2::field_value(e, &d.words, "SD") == Some(1) { + let sd = rdna2::field_value(e, &d.words, "SDST").unwrap_or(106); + dst = if sd == 125 { Dst::Null } else { Dst::S(sd) }; + } + } + } + if cmpx { + dst = Dst::S(126); + } + self.write_mask(&dst, cond); + Ok(()) + } + + /// lanemask_lt_lo / _hi words for this lane. + pub fn lanemask_lt(&mut self, hi: bool) -> Value { + let l = self.lane; + let all = self.c(u32::MAX); + if !hi { + // lane >= 32 ? ~0 : (lane == 0 ? 0 : ~0 >> (32 - lane)) + let k = self.c(32); + let s = self.sub(k, l); + let s = self.andc(s, 31); + let m = self.bin(BinOp::LShr, all, s); + let z = self.cmpc(Pred::Eq, l, 0); + let m = self.selc(z, 0, m); + let up = self.cmpc(Pred::UGe, l, 32); + self.sel(up, all, m) + } else { + // lane <= 32 ? 0 : ~0 >> (64 - lane) + let k = self.c(64); + let s = self.sub(k, l); + let s = self.andc(s, 31); + let m = self.bin(BinOp::LShr, all, s); + let le = self.cmpc(Pred::ULe, l, 32); + self.selc(le, 0, m) + } + } +} diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs new file mode 100644 index 000000000..c6ec5c5b0 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -0,0 +1,1251 @@ +//! VALU lowering of 16-bit, 64-bit and packed operations and relative moves +//! (port of `recomp/emit.rs` `valu16` / `valu64` / `valu_pk` / `movrel`). + +use super::lower::{err, Dst, LResult, Lw, VAR_VGPR}; +use super::lower_valu::Src; +use super::module::{BinOp, CastOp, Pred, Value}; +use super::ops::{Binary, FUnary, Tertiary}; +use super::ops_core::op; +use super::shader::Feature; +use crate::gpu::rdna2::{self, Decoded, Variant}; + +impl Lw { + fn hsel(&mut self, s: Value, hi: bool) -> Value { + if hi { + self.lshrc(s, 16) + } else { + self.andc(s, 0xFFFF) + } + } + /// sign-extended 16-bit value + pub fn sx16(&mut self, h: Value) -> Value { + let x = self.shlc(h, 16); + self.ashrc(x, 16) + } + + pub fn valu_pk(&mut self, d: &Decoded, name: &str) -> LResult<()> { + if d.variant != Variant::Plain { + return err(d, "VOP3P SDWA/DPP"); + } + let (outs, ins) = Self::ops(d); + let vop3p = d.enc.name == "ENC_VOP3P"; + let fv = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); + let (sel, sel_hi) = if vop3p { (fv("OP_SEL"), fv("OP_SEL_HI") | fv("OP_SEL_HI_2") << 2) } else { (0, 0b111) }; + let (neg, neg_hi) = if vop3p { (fv("NEG"), fv("NEG_HI")) } else { (0, 0) }; + let clamp = vop3p && fv("CLAMP") == 1; + let u: Vec = self.sources(d, &ins, name.ends_with("_f16"))?.into_iter().map(Src::w).collect(); + let dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + let z = self.c(0); + let cur = match &dst { + Dst::V(n) => self.vreg(*n), + _ => z, + }; + let src = |i: usize| u.get(i).copied().unwrap_or(z); + let h = |s: &mut Self, i: usize, hi: bool| -> Value { + let x = src(i); + let pick = (if hi { sel_hi } else { sel }) >> i & 1 == 1; + s.hsel(x, pick) + }; + let fh = |s: &mut Self, i: usize, hi: bool| -> Value { + let x = h(s, i, hi); + let v = s.s.f16_to_f32(x); + if (if hi { neg_hi } else { neg }) >> i & 1 == 1 { + s.fneg(v) + } else { + v + } + }; + let si = |s: &mut Self, i: usize, hi: bool| { + let x = h(s, i, hi); + s.sx16(x) + }; + let fr = |s: &mut Self, e: Value| { + let e = if clamp { s.un(op::SATURATE, e) } else { e }; + s.to_f16(e) + }; + let dot: Option = match name { + "v_dot2_f32_f16" | "v_dot2c_f32_f16" => { + let c = if name == "v_dot2_f32_f16" { + let c = self.f(src(2)); + if neg >> 2 & 1 == 1 { + self.fneg(c) + } else { + c + } + } else { + self.f(cur) + }; + let (a0, b0) = (fh(self, 0, false), fh(self, 1, false)); + let inner = self.fmad(a0, b0, c); + let (a1, b1) = (fh(self, 0, true), fh(self, 1, true)); + let e = self.fmad(a1, b1, inner); + let e = if clamp && name == "v_dot2_f32_f16" { self.un(op::SATURATE, e) } else { e }; + Some(self.bits(e)) + } + "v_dot4c_i32_i8" => Some(self.dot_n(src(0), src(1), cur, 8, true, false)), + "v_dot2_i32_i16" => { + let (a0, b0, a1, b1) = (si(self, 0, false), si(self, 1, false), si(self, 0, true), si(self, 1, true)); + let p = self.mul(a0, b0); + let q = self.mul(a1, b1); + Some(self.dot_sum(&[p, q], src(2), true, clamp)) + } + "v_dot2_u32_u16" => { + let (a0, b0, a1, b1) = (h(self, 0, false), h(self, 1, false), h(self, 0, true), h(self, 1, true)); + let p = self.mul(a0, b0); + let q = self.mul(a1, b1); + Some(self.dot_sum(&[p, q], src(2), false, clamp)) + } + "v_dot4_u32_u8" => Some(self.dot_n(src(0), src(1), src(2), 8, false, clamp)), + "v_dot4_i32_i8" => Some(self.dot_n(src(0), src(1), src(2), 8, true, clamp)), + "v_dot8_u32_u4" => Some(self.dot_n(src(0), src(1), src(2), 4, false, clamp)), + "v_dot8_i32_i4" => Some(self.dot_n(src(0), src(1), src(2), 4, true, clamp)), + _ => None, + }; + if let Some(e) = dot { + self.write32(&dst, e); + return Ok(()); + } + let mut halves = [z, z]; + for (k, hi) in [false, true].into_iter().enumerate() { + let (a, b, c) = (h(self, 0, hi), h(self, 1, hi), h(self, 2, hi)); + let v = match name { + "v_pk_add_f16" | "v_pk_mul_f16" | "v_pk_min_f16" | "v_pk_max_f16" => { + let (x, y) = (fh(self, 0, hi), fh(self, 1, hi)); + let e = match name { + "v_pk_add_f16" => self.fadd(x, y), + "v_pk_mul_f16" => self.fmul(x, y), + "v_pk_min_f16" => self.fmin(x, y), + _ => self.fmax(x, y), + }; + fr(self, e) + } + "v_pk_fma_f16" => { + let (x, y, w) = (fh(self, 0, hi), fh(self, 1, hi), fh(self, 2, hi)); + let e = self.fmad(x, y, w); + fr(self, e) + } + "v_pk_fmac_f16" => { + let (x, y) = (fh(self, 0, hi), fh(self, 1, hi)); + let ch = self.hsel(cur, hi); + let w = self.s.f16_to_f32(ch); + let e = self.fmad(x, y, w); + fr(self, e) + } + // clamp: saturate to the 16-bit range (computed exactly in 32 bits) + "v_pk_add_u16" | "v_pk_sub_u16" | "v_pk_mad_u16" if clamp => { + let t = match name { + "v_pk_add_u16" => self.add(a, b), + "v_pk_sub_u16" => self.sub(a, b), + _ => { + let t = self.mul(a, b); + self.add(t, c) + } + }; + let t = if name == "v_pk_sub_u16" { + let under = self.cmp(Pred::ULt, a, b); + self.selc(under, 0, t) + } else { + t + }; + let k = self.c(0xFFFF); + self.umin(t, k) + } + "v_pk_add_i16" | "v_pk_sub_i16" | "v_pk_mad_i16" if clamp => { + let (x, y) = (si(self, 0, hi), si(self, 1, hi)); + let t = match name { + "v_pk_add_i16" => self.add(x, y), + "v_pk_sub_i16" => self.sub(x, y), + _ => { + let w = si(self, 2, hi); + let t = self.mul(x, y); + self.add(t, w) + } + }; + let (lo, hi) = (self.c(0xFFFF_8000), self.c(0x7FFF)); + let t = self.imin(t, hi); + let t = self.imax(t, lo); + self.andc(t, 0xFFFF) + } + "v_pk_add_u16" | "v_pk_add_i16" => { + let t = self.add(a, b); + self.andc(t, 0xFFFF) + } + "v_pk_sub_u16" | "v_pk_sub_i16" => { + let t = self.sub(a, b); + self.andc(t, 0xFFFF) + } + "v_pk_mul_lo_u16" => { + let t = self.mul(a, b); + self.andc(t, 0xFFFF) + } + "v_pk_mad_u16" | "v_pk_mad_i16" => { + let t = self.mul(a, b); + let t = self.add(t, c); + self.andc(t, 0xFFFF) + } + "v_pk_lshlrev_b16" => { + let s = self.andc(a, 15); + let t = self.bin(BinOp::Shl, b, s); + self.andc(t, 0xFFFF) + } + "v_pk_lshrrev_b16" => { + let s = self.andc(a, 15); + self.bin(BinOp::LShr, b, s) + } + "v_pk_ashrrev_i16" => { + let x = si(self, 1, hi); + let s = self.andc(a, 15); + let t = self.bin(BinOp::AShr, x, s); + self.andc(t, 0xFFFF) + } + "v_pk_max_u16" => self.umax(a, b), + "v_pk_min_u16" => self.umin(a, b), + "v_pk_max_i16" | "v_pk_min_i16" => { + let (x, y) = (si(self, 0, hi), si(self, 1, hi)); + let t = if name == "v_pk_max_i16" { self.imax(x, y) } else { self.imin(x, y) }; + self.andc(t, 0xFFFF) + } + _ => return err(d, "VOP3P"), + }; + halves[k] = v; + } + let hi = self.shlc(halves[1], 16); + let r = self.or(halves[0], hi); + self.write32(&dst, r); + Ok(()) + } + + /// dot4_u8 / dot4_i8 / dot8_u4 / dot8_i4: c + Σ a[i]·b[i] over `bits`-wide fields. + /// `clamp`: the sum saturates to the 32-bit range. + fn dot_n(&mut self, a: Value, b: Value, c: Value, bits: u32, signed: bool, clamp: bool) -> Value { + let mut prods = Vec::new(); + let mut i = 0; + while i < 32 { + let (x, y) = if signed { + let x = self.shlc(a, 32 - bits - i); + let x = self.ashrc(x, 32 - bits); + let y = self.shlc(b, 32 - bits - i); + let y = self.ashrc(y, 32 - bits); + (x, y) + } else { + let x = self.lshrc(a, i); + let x = self.andc(x, (1 << bits) - 1); + let y = self.lshrc(b, i); + let y = self.andc(y, (1 << bits) - 1); + (x, y) + }; + prods.push(self.mul(x, y)); + i += bits; + } + self.dot_sum(&prods, c, signed, clamp) + } + + /// c + Σ products (each exact in 32 bits); `clamp`: in 64 bits, saturated to 32. + fn dot_sum(&mut self, prods: &[Value], c: Value, signed: bool, clamp: bool) -> Value { + if !clamp { + return prods.iter().fold(c, |r, &p| self.add(r, p)); + } + let ext = |s: &mut Self, v: Value| if signed { s.sext64(v) } else { s.zext64(v) }; + let mut r = ext(self, c); + for &p in prods { + let p = ext(self, p); + r = self.add(r, p); + } + if signed { + self.sat_i32(r) + } else { + let k = self.c64(0xFFFF_FFFF); + let r = self.umin(r, k); + self.trunc32(r) + } + } + + /// The highest VGPR the program names (relative moves index up to it). + fn top_vgpr(&self) -> u64 { + self.init.touched.iter().filter(|&&v| (VAR_VGPR..VAR_VGPR + 256).contains(&v)).map(|&v| (v - VAR_VGPR) as u64).max().unwrap_or(0) + } + + pub fn movrel(&mut self, d: &Decoded, name: &str) -> LResult<()> { + if d.variant != Variant::Plain { + return err(d, "movrel SDWA/DPP"); + } + let src_code = Self::fv(d, "SRC0"); + let vdst = Self::fv(d, "VDST"); + let m0 = self.sreg(124); + let top = self.top_vgpr().max(vdst).max(src_code.saturating_sub(256)); + let (rd_idx, wr_idx) = match name { + "v_movrels_b32" => (Some(m0), None), + "v_movreld_b32" => (None, Some(m0)), + "v_movrelsd_b32" => (Some(m0), Some(m0)), + "v_movrelsd_2_b32" => { + let r = self.andc(m0, 0x3FF); + let w = self.lshrc(m0, 16); + let w = self.andc(w, 0x3FF); + (Some(r), Some(w)) + } + _ => return err(d, "movrel"), + }; + let value = match rd_idx { + Some(idx) => { + if src_code < 256 { + return err(d, "movrels: the source is not a VGPR"); + } + let base = src_code - 256; + let mut v = self.c(0); + for k in 0..=top.saturating_sub(base) { + let r = self.vreg(base + k); + let is = self.cmpc(Pred::Eq, idx, k as u32); + v = self.sel(is, r, v); + } + v + } + None => self.code32(src_code, d.literal, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?, + }; + let a = self.act(); + match wr_idx { + Some(idx) => { + for k in 0..=top.saturating_sub(vdst) { + let is = self.cmpc(Pred::Eq, idx, k as u32); + let c = self.land(a, is); + let old = self.vreg(vdst + k); + let v = self.sel(c, value, old); + self.wr(VAR_VGPR + (vdst + k) as u32, v); + } + } + None => { + let old = self.vreg(vdst); + let v = self.sel(a, value, old); + self.wr(VAR_VGPR + vdst as u32, v); + } + } + Ok(()) + } + + pub fn swaprel(&mut self, d: &Decoded) -> LResult<()> { + if d.variant != Variant::Plain { + return err(d, "swaprel SDWA/DPP"); + } + let vdst = Self::fv(d, "VDST"); + let src_code = Self::fv(d, "SRC0"); + if src_code < 256 { + return err(d, "swaprel: the source is not a VGPR"); + } + let base = src_code - 256; + let top = self.top_vgpr().max(vdst).max(base); + let m0 = self.sreg(124); + let a = self.act(); + let td = self.vreg(vdst); + let mut ts = self.c(0); + for k in 0..=top.saturating_sub(base) { + let r = self.vreg(base + k); + let is = self.cmpc(Pred::Eq, m0, k as u32); + ts = self.sel(is, r, ts); + } + let nv = self.sel(a, ts, td); + self.wr(VAR_VGPR + vdst as u32, nv); + for k in 0..=top.saturating_sub(base) { + let is = self.cmpc(Pred::Eq, m0, k as u32); + let c = self.land(a, is); + let old = self.vreg(base + k); + let v = self.sel(c, td, old); + self.wr(VAR_VGPR + (base + k) as u32, v); + } + Ok(()) + } + + pub fn valu16(&mut self, d: &Decoded, name: &str) -> LResult<()> { + let (outs, ins) = Self::ops(d); + let m = Self::mods(d); + let u: Vec = self.sources(d, &ins, name.contains("f16"))?.into_iter().map(Src::w).collect(); + let plain = d.variant == Variant::Plain; + let z = self.c(0); + let half = |s: &mut Self, i: usize| -> Value { + let x = u.get(i).copied().unwrap_or(z); + s.hsel(x, plain && m.opsel >> i & 1 == 1) + }; + let fh = |s: &mut Self, i: usize| -> Value { + let x = half(s, i); + let mut v = s.s.f16_to_f32(x); + if m.abs[i.min(2)] { + v = s.fabs(v); + } + if m.neg[i.min(2)] { + v = s.fneg(v); + } + v + }; + let hb = |s: &mut Self, i: usize| -> Value { + let mut x = half(s, i); + if m.abs[i.min(2)] { + x = s.andc(x, 0x7FFF); + } + if m.neg[i.min(2)] { + let k = s.c(0x8000); + x = s.xor(x, k); + } + x + }; + let si = |s: &mut Self, i: usize| { + let x = half(s, i); + s.sx16(x) + }; + let fr = |s: &mut Self, e: Value| -> Value { + let mut v = match m.omod { + 1 => { + let k = s.fc(2.0); + s.fmul(e, k) + } + 2 => { + let k = s.fc(4.0); + s.fmul(e, k) + } + 3 => { + let k = s.fc(0.5); + s.fmul(e, k) + } + _ => e, + }; + if m.clamp { + v = s.un(op::SATURATE, v); + } + s.to_f16(v) + }; + let dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + let cur = match &dst { + Dst::V(n) => self.vreg(*n), + _ => z, + }; + let curh = self.hsel(cur, plain && m.opsel >> 3 & 1 == 1); + let (a, b, c) = (half(self, 0), half(self, 1), half(self, 2)); + macro_rules! f1 { + ($f:expr) => {{ + let x = fh(self, 0); + let e = $f(self, x); + fr(self, e) + }}; + } + macro_rules! f2 { + ($f:expr) => {{ + let x = fh(self, 0); + let y = fh(self, 1); + let e = $f(self, x, y); + fr(self, e) + }}; + } + macro_rules! f3 { + ($f:expr) => {{ + let x = fh(self, 0); + let y = fh(self, 1); + let w = fh(self, 2); + let e = $f(self, x, y, w); + fr(self, e) + }}; + } + let r: Value = match name { + "v_add_f16" => f2!(|s: &mut Self, x, y| s.fadd(x, y)), + "v_sub_f16" => f2!(|s: &mut Self, x, y| s.fsub(x, y)), + "v_subrev_f16" => f2!(|s: &mut Self, x, y| s.fsub(y, x)), + "v_mul_f16" => f2!(|s: &mut Self, x, y| s.fmul(x, y)), + "v_min_f16" => f2!(|s: &mut Self, x, y| s.fmin(x, y)), + "v_max_f16" => f2!(|s: &mut Self, x, y| s.fmax(x, y)), + "v_fma_f16" => f3!(|s: &mut Self, x, y, w| s.fmad(x, y, w)), + "v_med3_f16" => f3!(|s: &mut Self, x, y, w| s.med3f(x, y, w)), + "v_min3_f16" => f3!(|s: &mut Self, x, y, w| { + let t = s.fmin(x, y); + s.fmin(t, w) + }), + "v_max3_f16" => f3!(|s: &mut Self, x, y, w| { + let t = s.fmax(x, y); + s.fmax(t, w) + }), + "v_med3_u16" => { + let (x, y) = (self.umin(a, b), self.umax(a, b)); + let y = self.umin(y, c); + self.umax(x, y) + } + "v_min3_u16" => { + let t = self.umin(a, b); + self.umin(t, c) + } + "v_max3_u16" => { + let t = self.umax(a, b); + self.umax(t, c) + } + "v_med3_i16" | "v_min3_i16" | "v_max3_i16" => { + let (x, y, w) = (si(self, 0), si(self, 1), si(self, 2)); + let t = match name { + "v_med3_i16" => { + let (p, q) = (self.imin(x, y), self.imax(x, y)); + let q = self.imin(q, w); + self.imax(p, q) + } + "v_min3_i16" => { + let t = self.imin(x, y); + self.imin(t, w) + } + _ => { + let t = self.imax(x, y); + self.imax(t, w) + } + }; + self.andc(t, 0xFFFF) + } + "v_frexp_mant_f16" => f1!(|s: &mut Self, x| s.frexp_mant(x)), + "v_frexp_exp_i16_f16" => { + let x = fh(self, 0); + let e = self.frexp_exp(x); + self.andc(e, 0xFFFF) + } + "v_mad_f16" => { + let (x, y, w) = (fh(self, 0), fh(self, 1), fh(self, 2)); + let p = self.fmul(x, y); + let ph = if self.dyn_rm { + let rm = self.rd(super::lower::VAR_FP16_RM); + self.f32_to_f16_rm(p, rm) + } else { + self.f32_to_f16_rne(p) + }; + let p16 = self.s.f16_to_f32(ph); + let e = self.fadd(p16, w); + fr(self, e) + } + "v_fmac_f16" => { + let (x, y) = (fh(self, 0), fh(self, 1)); + let w = self.s.f16_to_f32(curh); + let e = self.fmad(x, y, w); + fr(self, e) + } + "v_fmamk_f16" => { + let (x, w) = (fh(self, 0), fh(self, 2)); + let k = self.andc(u[1], 0xFFFF); + let k = self.s.f16_to_f32(k); + let e = self.fmad(x, k, w); + fr(self, e) + } + "v_fmaak_f16" => { + let (x, y) = (fh(self, 0), fh(self, 1)); + let k = self.andc(u[2], 0xFFFF); + let k = self.s.f16_to_f32(k); + let e = self.fmad(x, y, k); + fr(self, e) + } + "v_ldexp_f16" => { + let x = fh(self, 0); + let n = si(self, 1); + let nf = self.sitof(n); + let p = self.un(op::EXP, nf); + let e = self.fmul(x, p); + fr(self, e) + } + "v_rcp_f16" => f1!(|s: &mut Self, x| { + let one = s.fc(1.0); + s.fdiv(one, x) + }), + "v_rsq_f16" => f1!(|s: &mut Self, x| s.un(op::RSQRT, x)), + "v_sqrt_f16" => f1!(|s: &mut Self, x| s.un(op::SQRT, x)), + "v_log_f16" => f1!(|s: &mut Self, x| s.un(op::LOG, x)), + "v_exp_f16" => f1!(|s: &mut Self, x| s.un(op::EXP, x)), + "v_sin_f16" | "v_cos_f16" => { + let x = fh(self, 0); + let k = self.fc(6.283_185_3); + let x = self.fmul(x, k); + let e = self.un(if name == "v_sin_f16" { op::SIN } else { op::COS }, x); + fr(self, e) + } + "v_fract_f16" => f1!(|s: &mut Self, x| s.fract_f(x)), + "v_floor_f16" => f1!(|s: &mut Self, x| s.un(op::ROUND_NI, x)), + "v_ceil_f16" => f1!(|s: &mut Self, x| s.un(op::ROUND_PI, x)), + "v_trunc_f16" => f1!(|s: &mut Self, x| s.un(op::ROUND_Z, x)), + "v_rndne_f16" => f1!(|s: &mut Self, x| s.un(op::ROUND_NE, x)), + "v_cvt_f16_u16" => { + let e = self.uitof(a); + fr(self, e) + } + "v_cvt_f16_i16" => { + let x = si(self, 0); + let e = self.sitof(x); + fr(self, e) + } + "v_cvt_u16_f16" => { + let x = fh(self, 0); + let v = self.cvt_u32(x); + let big = self.cmpc(Pred::UGt, v, 0xFFFF); + self.selc(big, 0xFFFF, v) + } + "v_cvt_i16_f16" => { + let x = fh(self, 0); + let v = self.cvt_i32(x); + let lo = self.c(-32768i32 as u32); + let hi = self.c(32767); + let v = self.imax(v, lo); + let v = self.imin(v, hi); + self.andc(v, 0xFFFF) + } + "v_cvt_norm_u16_f16" => { + let x = hb(self, 0); + self.cvt_norm_u16_f16(x) + } + "v_cvt_norm_i16_f16" => { + let x = hb(self, 0); + self.cvt_norm_i16_f16(x) + } + "v_add_nc_u16" | "v_add_u16" | "v_add_nc_i16" => { + let t = self.add(a, b); + self.andc(t, 0xFFFF) + } + "v_sub_nc_u16" | "v_sub_u16" | "v_sub_nc_i16" => { + let t = self.sub(a, b); + self.andc(t, 0xFFFF) + } + "v_subrev_nc_u16" | "v_subrev_u16" => { + let t = self.sub(b, a); + self.andc(t, 0xFFFF) + } + "v_mul_lo_u16" => { + let t = self.mul(a, b); + self.andc(t, 0xFFFF) + } + "v_lshlrev_b16" => { + let s = self.andc(a, 15); + let t = self.bin(BinOp::Shl, b, s); + self.andc(t, 0xFFFF) + } + "v_lshrrev_b16" => { + let s = self.andc(a, 15); + self.bin(BinOp::LShr, b, s) + } + "v_ashrrev_i16" => { + let x = si(self, 1); + let s = self.andc(a, 15); + let t = self.bin(BinOp::AShr, x, s); + self.andc(t, 0xFFFF) + } + "v_max_u16" => self.umax(a, b), + "v_min_u16" => self.umin(a, b), + "v_max_i16" | "v_min_i16" => { + let (x, y) = (si(self, 0), si(self, 1)); + let t = if name == "v_max_i16" { self.imax(x, y) } else { self.imin(x, y) }; + self.andc(t, 0xFFFF) + } + "v_mad_u16" | "v_mad_i16" => { + let t = self.mul(a, b); + let t = self.add(t, c); + self.andc(t, 0xFFFF) + } + _ => return err(d, "VALU 16-bit"), + }; + if d.variant == Variant::Sdwa { + self.vwrite(d, &dst, r); + } else { + let merged = if m.opsel >> 3 & 1 == 1 { + let l = self.andc(cur, 0xFFFF); + let h = self.shlc(r, 16); + self.or(l, h) + } else { + let h = self.andc(cur, 0xFFFF_0000); + self.or(h, r) + }; + self.vwrite(d, &dst, merged); + } + Ok(()) + } + + /// `f32_to_f16_rm(f, 0)`: binary32 → binary16, round to nearest even (software). + pub fn f32_to_f16_rne(&mut self, f: Value) -> Value { + let z = self.c(0); + self.f32_to_f16_rm(f, z) + } + + /// `f32_to_f16_rm`: binary32 → binary16 under MODE[3:2] `rm` (0 RNE, 1 +inf, 2 -inf, 3 RTZ). + pub fn f32_to_f16_rm(&mut self, f: Value, rm: Value) -> Value { + let x = self.bits(f); + let sign = self.lshrc(x, 16); + let sign = self.andc(sign, 0x8000); + let ax = self.andc(x, 0x7FFF_FFFF); + let isinfnan = self.cmpc(Pred::UGe, ax, 0x7F80_0000); + let isinf = self.cmpc(Pred::Eq, ax, 0x7F80_0000); + let pl = self.lshrc(ax, 13); + let pl = self.andc(pl, 0x1FF); + let nanv = self.orc(pl, 0x7E00); + let infnan = self.selc(isinf, 0x7C00, nanv); + let infnan = self.or(sign, infnan); + let zero = self.cmpc(Pred::Eq, ax, 0); + let rne = self.cmpc(Pred::Eq, rm, 0); + let pos = self.cmpc(Pred::Eq, sign, 0); + let neg = self.lnot(pos); + let up = self.cmpc(Pred::Eq, rm, 1); + let down = self.cmpc(Pred::Eq, rm, 2); + let dir_up = self.land(up, pos); + let dir_dn = self.land(down, neg); + let dir = self.lor(dir_up, dir_dn); + let away = self.lor(rne, dir); + let ovf = self.cmpc(Pred::UGe, ax, 0x4780_0000); + let k7bff = self.c(0x7BFF); + let ovm = self.selc(away, 0x7C00, k7bff); + let ovfv = self.or(sign, ovm); + let tiny = self.cmpc(Pred::ULt, ax, 0x3380_0000); + let half_t = self.cmpc(Pred::UGt, ax, 0x3300_0000); + let inc_t = self.sel(rne, half_t, dir); + let inc_t = self.u(inc_t); + let tinyv = self.or(sign, inc_t); + let normal = self.cmpc(Pred::UGe, ax, 0x3880_0000); + let e = self.lshrc(ax, 23); + let k112 = self.c(112); + let e = self.sub(e, k112); + let e = self.shlc(e, 10); + let mm = self.lshrc(ax, 13); + let mm = self.andc(mm, 0x3FF); + let hn = self.or(e, mm); + let remn = self.andc(ax, 0x1FFF); + let halfn = self.c(0x1000); + let k126 = self.c(126); + let ex = self.lshrc(ax, 23); + let sh = self.sub(k126, ex); + let sh = self.andc(sh, 31); + let sig = self.andc(ax, 0x7F_FFFF); + let sig = self.orc(sig, 0x80_0000); + let hs = self.bin(BinOp::LShr, sig, sh); + let one = self.c(1); + let shm = self.sub(sh, one); + let shm = self.andc(shm, 31); + let halfs = self.bin(BinOp::Shl, one, shm); + let full = self.bin(BinOp::Shl, one, sh); + let msk = self.sub(full, one); + let rems = self.and(sig, msk); + let h = self.sel(normal, hn, hs); + let rem = self.sel(normal, remn, rems); + let hb = self.sel(normal, halfn, halfs); + let gt = self.cmp(Pred::UGt, rem, hb); + let eq = self.cmp(Pred::Eq, rem, hb); + let odd = self.andc(h, 1); + let odd = self.nz(odd); + let tie = self.land(eq, odd); + let rne_inc = self.lor(gt, tie); + let rnz = self.nz(rem); + let dir_inc = self.land(rnz, dir); + let inc = self.sel(rne, rne_inc, dir_inc); + let inc = self.u(inc); + let r = self.add(h, inc); + let r = self.or(sign, r); + let r = self.sel(tiny, tinyv, r); + let r = self.sel(ovf, ovfv, r); + let r = self.sel(zero, sign, r); + self.sel(isinfnan, infnan, r) + } + + // ------------------------------------------------------------ 64-bit + + pub fn f64ty(&mut self) -> super::module::Ty { + self.s.require(Feature::Doubles); + self.s.m.f64() + } + pub fn dc(&mut self, x: f64) -> Value { + let t = self.f64ty(); + self.s.m.const_float(t, x.to_bits()) + } + pub fn dbits(&mut self, lo: u32, hi: u32) -> Value { + let t = self.f64ty(); + self.s.m.const_float(t, (hi as u64) << 32 | lo as u64) + } + pub fn mkd(&mut self, lo: Value, hi: Value) -> Value { + self.s.make_double(lo, hi) + } + + pub fn valu64(&mut self, d: &Decoded, name: &str) -> LResult<()> { + let (outs, ins) = Self::ops(d); + let m = Self::mods(d); + if d.variant != Variant::Plain { + return err(d, "64-bit SDWA/DPP"); + } + let src_f64 = name.ends_with("_f64"); + let mut lh: Vec<(Value, Value)> = Vec::new(); + for o in &ins { + if o.size == 64 { + lh.push(self.read64(d, o, src_f64).ok_or_else(|| format!("{}: op", rdna2::format(d)))?); + } else { + let v = self.read(d, o, false).ok_or_else(|| format!("{}: op", rdna2::format(d)))?; + let z = self.c(0); + lh.push((v, z)); + } + } + let u64v = |s: &mut Self, i: usize| s.pack64(lh[i].0, lh[i].1); + let f64v = |s: &mut Self, i: usize| { + let mut hi = lh[i].1; + if m.abs[i.min(2)] { + hi = s.andc(hi, 0x7FFF_FFFF); + } + if m.neg[i.min(2)] { + let k = s.c(0x8000_0000); + hi = s.xor(hi, k); + } + s.mkd(lh[i].0, hi) + }; + let dst = outs.first().map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + if let Some(rest) = name.strip_prefix("v_cmpx_").or_else(|| name.strip_prefix("v_cmp_")) { + let (opn, ty) = rest.rsplit_once('_').ok_or_else(|| format!("{}: VOPC", rdna2::format(d)))?; + let dst = if name.starts_with("v_cmpx_") { Dst::S(126) } else { dst }; + if opn == "class" && ty == "f64" { + let x = f64v(self, 0); + let cls = self.fclass64(x); + let s = self.bin(BinOp::LShr, lh[1].0, cls); + let s = self.andc(s, 1); + let cond = self.nz(s); + self.write_mask(&dst, cond); + return Ok(()); + } + let cond = match ty { + "f64" => { + let (a, b) = (f64v(self, 0), f64v(self, 1)); + self.float_compare(opn, a, b).ok_or_else(|| format!("{}: VOPC 64", rdna2::format(d)))? + } + "u64" | "i64" => { + let (a, b) = (u64v(self, 0), u64v(self, 1)); + let sg = ty == "i64"; + match opn { + "f" => self.b(false), + "t" | "tru" => self.b(true), + "lt" => self.cmp(if sg { Pred::SLt } else { Pred::ULt }, a, b), + "eq" => self.cmp(Pred::Eq, a, b), + "le" => self.cmp(if sg { Pred::SLe } else { Pred::ULe }, a, b), + "gt" => self.cmp(if sg { Pred::SGt } else { Pred::UGt }, a, b), + "ne" | "lg" => self.cmp(Pred::Ne, a, b), + "ge" => self.cmp(if sg { Pred::SGe } else { Pred::UGe }, a, b), + _ => return err(d, "VOPC 64"), + } + } + _ => return err(d, "VOPC 64"), + }; + self.write_mask(&dst, cond); + return Ok(()); + } + let r64: Value = match name { + "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => { + let v = u64v(self, 1); + let s = self.andc(lh[0].0, 63); + let s = self.zext64(s); + match name { + "v_lshlrev_b64" => self.bin(BinOp::Shl, v, s), + "v_lshrrev_b64" => self.bin(BinOp::LShr, v, s), + _ => self.bin(BinOp::AShr, v, s), + } + } + "v_mad_u64_u32" | "v_mad_i64_i32" => { + let p = if name == "v_mad_u64_u32" { + let (x, y) = (self.zext64(lh[0].0), self.zext64(lh[1].0)); + self.mul(x, y) + } else { + let (x, y) = (self.sext64(lh[0].0), self.sext64(lh[1].0)); + self.mul(x, y) + }; + let c = u64v(self, 2); + let w = self.add(p, c); + let carry = self.cmp(Pred::ULt, w, c); + let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::Null); + self.write_mask(&sdst, carry); + let (lo, hi) = self.unpack64(w); + self.write64(&dst, lo, hi); + return Ok(()); + } + _ => { + let e = match name { + "v_add_f64" | "v_mul_f64" | "v_min_f64" | "v_max_f64" => { + let (a, b) = (f64v(self, 0), f64v(self, 1)); + match name { + "v_add_f64" => self.fadd(a, b), + "v_mul_f64" => self.fmul(a, b), + "v_min_f64" => self.s.binary(Binary::FMin, a, b), + _ => self.s.binary(Binary::FMax, a, b), + } + } + "v_fma_f64" => { + let (a, b, c) = (f64v(self, 0), f64v(self, 1), f64v(self, 2)); + self.s.tertiary(Tertiary::Fma, a, b, c) + } + "v_rcp_f64" => { + let a = f64v(self, 0); + let one = self.dc(1.0); + self.ddiv(one, a) + } + "v_cvt_f64_f32" => { + let t = self.f64ty(); + let x = self.f(lh[0].0); + self.s.m.cast(CastOp::FPExt, x, t) + } + "v_cvt_f64_i32" => { + self.s.require(Feature::DoubleExtensions); + let t = self.f64ty(); + self.s.m.cast(CastOp::SIToFP, lh[0].0, t) + } + "v_cvt_f64_u32" => { + self.s.require(Feature::DoubleExtensions); + let t = self.f64ty(); + self.s.m.cast(CastOp::UIToFP, lh[0].0, t) + } + "v_floor_f64" => { + let a = f64v(self, 0); + self.floor_d(a) + } + "v_ceil_f64" => { + let a = f64v(self, 0); + self.ceil_d(a) + } + "v_fract_f64" => { + let a = f64v(self, 0); + self.fract_d(a) + } + "v_rndne_f64" => { + let a = f64v(self, 0); + self.round_ne_d(a) + } + "v_frexp_mant_f64" => { + let a = f64v(self, 0); + self.frexp_mant_d(a) + } + "v_sqrt_f64" => { + let a = f64v(self, 0); + self.sqrt_d(a) + } + "v_rsq_f64" => { + let a = f64v(self, 0); + let r = self.sqrt_d(a); + let one = self.dc(1.0); + self.ddiv(one, r) + } + "v_trunc_f64" => { + let a = f64v(self, 0); + self.trunc_d(a) + } + "v_ldexp_f64" => { + let a = f64v(self, 0); + self.ldexp_d(a, lh[1].0) + } + "v_cvt_f32_f64" => { + let a = f64v(self, 0); + let t = self.s.m.f32(); + let f = self.s.m.cast(CastOp::FPTrunc, a, t); + let f = match m.omod { + 1..=3 => { + let k = self.fc([2.0, 4.0, 0.5][m.omod as usize - 1]); + self.fmul(f, k) + } + _ => f, + }; + let f = if m.clamp { self.s.funary(FUnary::Saturate, f) } else { f }; + let b = self.bits(f); + self.write32(&dst, b); + return Ok(()); + } + "v_cvt_i32_f64" | "v_cvt_u32_f64" => { + let a = f64v(self, 0); + let n = self.isnan_d(a); + let (lo, hi) = if name == "v_cvt_i32_f64" { (self.dc(-2147483648.0), self.dc(2147483647.0)) } else { (self.dc(0.0), self.dc(4294967295.0)) }; + let x = self.s.binary(Binary::FMax, a, lo); + let x = self.s.binary(Binary::FMin, x, hi); + let i32 = self.s.m.i32(); + self.s.require(Feature::DoubleExtensions); + let v = self.s.m.cast(if name == "v_cvt_i32_f64" { CastOp::FPToSI } else { CastOp::FPToUI }, x, i32); + let r = self.selc(n, 0, v); + self.write32(&dst, r); + return Ok(()); + } + "v_frexp_exp_i32_f64" => { + let a = f64v(self, 0); + let r = self.frexp_exp_d(a); + self.write32(&dst, r); + return Ok(()); + } + _ => return err(d, "VALU 64-bit"), + }; + // output modifier, then clamp (as the f32 path) + let e = match m.omod { + 1..=3 => { + let k = self.dc([2.0, 4.0, 0.5][m.omod as usize - 1]); + self.fmul(e, k) + } + _ => e, + }; + let e = if m.clamp { self.s.funary(FUnary::Saturate, e) } else { e }; + let (lo, hi) = self.s.split_double(e); + self.write64(&dst, lo, hi); + return Ok(()); + } + }; + let (lo, hi) = self.unpack64(r64); + self.write64(&dst, lo, hi); + Ok(()) + } + + /// Double division (D3D11.1 double extensions). + pub fn ddiv(&mut self, a: Value, b: Value) -> Value { + self.s.require(Feature::DoubleExtensions); + self.fdiv(a, b) + } + + pub fn trunc_d(&mut self, x: Value) -> Value { + let (l, h) = self.s.split_double(x); + let e = self.lshrc(h, 20); + let e = self.andc(e, 0x7FF); + let big = self.cmpc(Pred::UGe, e, 1075); + let small = self.cmpc(Pred::ULt, e, 1023); + let sgn = self.andc(h, 0x8000_0000); + let z = self.c(0); + let zero = self.mkd(z, sgn); + let k = self.c(1075); + let s = self.sub(k, e); + let s = self.andc(s, 63); + let s64 = self.zext64(s); + let one = self.c64(1); + let m = self.bin(BinOp::Shl, one, s64); + let m = self.sub(m, one); + let m = self.not(m); + let bits = self.pack64(l, h); + let bits = self.and(bits, m); + let (bl, bh) = self.unpack64(bits); + let r = self.mkd(bl, bh); + let r = self.sel(small, zero, r); + self.sel(big, x, r) + } + pub fn floor_d(&mut self, x: Value) -> Value { + let t = self.trunc_d(x); + let gt = self.fcmp(Pred::FOGt, t, x); + let one = self.dc(1.0); + let t1 = self.fsub(t, one); + self.sel(gt, t1, t) + } + pub fn ceil_d(&mut self, x: Value) -> Value { + let t = self.trunc_d(x); + let lt = self.fcmp(Pred::FOLt, t, x); + let one = self.dc(1.0); + let t1 = self.fadd(t, one); + self.sel(lt, t1, t) + } + pub fn fract_d(&mut self, x: Value) -> Value { + let n = self.isnan_d(x); + let i = self.isinf_d(x); + let fl = self.floor_d(x); + let f = self.fsub(x, fl); + let z = self.dc(0.0); + let iz = self.fcmp(Pred::FOEq, f, z); + let lim = self.dbits(0xFFFF_FFFF, 0x3FEF_FFFF); + let mn = self.s.binary(Binary::FMin, f, lim); + let r = self.sel(iz, z, mn); + let qnan = self.dbits(0, 0x7FF8_0000); + let r = self.sel(i, qnan, r); + self.sel(n, x, r) + } + pub fn round_ne_d(&mut self, x: Value) -> Value { + let (l, h) = self.s.split_double(x); + let sign = self.andc(h, 0x8000_0000); + let e = self.lshrc(h, 20); + let e = self.andc(e, 0x7FF); + let hm = self.andc(h, 0x7FFF_FFFF); + let mag = self.pack64(l, hm); + let keep = { + let a = self.cmpc(Pred::Eq, e, 0x7FF); + let b = self.cmpc(Pred::UGe, e, 1075); + self.lor(a, b) + }; + let z = self.c(0); + let szero = self.mkd(z, sign); + let tiny = self.cmpc(Pred::ULt, e, 1022); + let is1022 = self.cmpc(Pred::Eq, e, 1022); + let fm = self.c64(0x000F_FFFF_FFFF_FFFF); + let fr = self.and(mag, fm); + let z64 = self.c64(0); + let above = self.cmp(Pred::Ne, fr, z64); + let so = self.orc(sign, 0x3FF0_0000); + let sone = self.mkd(z, so); + let half_r = self.sel(above, sone, szero); + let k = self.c(1075); + let sh = self.sub(k, e); + let sh = self.andc(sh, 63); + let sh64 = self.zext64(sh); + let one = self.c64(1); + let unit = self.bin(BinOp::Shl, one, sh64); + let mask = self.sub(unit, one); + let k1 = self.c(1); + let shm = self.sub(sh, k1); + let shm = self.andc(shm, 63); + let shm64 = self.zext64(shm); + let half = self.bin(BinOp::Shl, one, shm64); + let fraction = self.and(mag, mask); + let nmask = self.not(mask); + let whole = self.and(mag, nmask); + let gt = self.cmp(Pred::UGt, fraction, half); + let eq = self.cmp(Pred::Eq, fraction, half); + let wb = self.bin(BinOp::LShr, whole, sh64); + let wb = self.and(wb, one); + let odd = self.cmp(Pred::Ne, wb, z64); + let tie = self.land(eq, odd); + let up = self.lor(gt, tie); + let wu = self.add(whole, unit); + let whole = self.sel(up, wu, whole); + let (wl, wh) = self.unpack64(whole); + let wh = self.or(sign, wh); + let r = self.mkd(wl, wh); + let r = self.sel(is1022, half_r, r); + let r = self.sel(tiny, szero, r); + self.sel(keep, x, r) + } + /// position of the top set bit of the 52-bit fraction (m:l) + fn top52(&mut self, m: Value, l: Value) -> Value { + let a = self.firstbithigh(m); + let a = self.addc(a, 32); + let b = self.firstbithigh(l); + let mnz = self.nz(m); + self.sel(mnz, a, b) + } + pub fn frexp_mant_d(&mut self, x: Value) -> Value { + let (l, h) = self.s.split_double(x); + let e = self.lshrc(h, 20); + let e = self.andc(e, 0x7FF); + let m = self.andc(h, 0xF_FFFF); + let s = self.andc(h, 0x8000_0000); + let special = self.cmpc(Pred::Eq, e, 0x7FF); + let ez = self.cmpc(Pred::Eq, e, 0); + let ml = self.or(m, l); + let mz = self.cmpc(Pred::Eq, ml, 0); + let zero = self.land(ez, mz); + let keep = self.lor(special, zero); + let nh = self.or(s, m); + let nh = self.orc(nh, 0x3FE0_0000); + let normal = self.mkd(l, nh); + let top = self.top52(m, l); + let f = self.pack64(l, m); + let k = self.c(52); + let sh = self.sub(k, top); + let sh = self.andc(sh, 63); + let sh = self.zext64(sh); + let ff = self.bin(BinOp::Shl, f, sh); + let fm = self.c64(0x000F_FFFF_FFFF_FFFF); + let ff = self.and(ff, fm); + let (fl, fh) = self.unpack64(ff); + let dh = self.orc(s, 0x3FE0_0000); + let dh = self.or(dh, fh); + let den = self.mkd(fl, dh); + let r = self.sel(ez, den, normal); + self.sel(keep, x, r) + } + pub fn frexp_exp_d(&mut self, x: Value) -> Value { + let (l, h) = self.s.split_double(x); + let e = self.lshrc(h, 20); + let e = self.andc(e, 0x7FF); + let m = self.andc(h, 0xF_FFFF); + let special = self.cmpc(Pred::Eq, e, 0x7FF); + let ez = self.cmpc(Pred::Eq, e, 0); + let ml = self.or(m, l); + let mz = self.cmpc(Pred::Eq, ml, 0); + let zero = self.land(ez, mz); + let keep = self.lor(special, zero); + let k = self.c(1022); + let norm = self.sub(e, k); + let top = self.top52(m, l); + let k = self.c(1073); + let den = self.sub(top, k); + let r = self.sel(ez, den, norm); + self.selc(keep, 0, r) + } + /// `ldexp_d`: x · 2^n rounded once (scaling steps that stay normal). + pub fn ldexp_d(&mut self, x: Value, n: Value) -> Value { + let n0 = self.isnan_d(x); + let i0 = self.isinf_d(x); + let z = self.dc(0.0); + let x0 = self.fcmp(Pred::FOEq, x, z); + let keep = self.lor(n0, i0); + let keep = self.lor(keep, x0); + let lo = self.c(-2200i32 as u32); + let hi = self.c(2200); + let n = self.imax(n, lo); + let n = self.imin(n, hi); + let up = self.dbits(0, 0x7FE0_0000); + let down = self.dbits(0, 0x0360_0000); + let k1023 = self.c(1023); + let k969 = self.c(969); + // first step + let big = self.cmpc(Pred::SGt, n, 1023); + let small = self.cmpc(Pred::SLt, n, -1022i32 as u32); + let ru = self.fmul(x, up); + let rd = self.fmul(x, down); + let r1 = self.sel(small, rd, x); + let r1 = self.sel(big, ru, r1); + let nu = self.sub(n, k1023); + let nd = self.add(n, k969); + let n1 = self.sel(small, nd, n); + let n1 = self.sel(big, nu, n1); + // second step + let big2 = self.cmpc(Pred::SGt, n1, 1023); + let small2 = self.cmpc(Pred::SLt, n1, -1022i32 as u32); + let big2 = self.land(big, big2); + let small2 = self.land(small, small2); + let ru2 = self.fmul(r1, up); + let rd2 = self.fmul(r1, down); + let r2 = self.sel(small2, rd2, r1); + let r2 = self.sel(big2, ru2, r2); + let nu2 = self.sub(n1, k1023); + let nu2 = self.imin(nu2, k1023); + let nd2 = self.add(n1, k969); + let km = self.c(-1022i32 as u32); + let nd2 = self.imax(nd2, km); + let n2 = self.sel(small2, nd2, n1); + let n2 = self.sel(big2, nu2, n2); + // last step + let e = self.add(n2, k1023); + let e = self.shlc(e, 20); + let zz = self.c(0); + let p = self.mkd(zz, e); + let r = self.fmul(r2, p); + self.sel(keep, x, r) + } + /// `sqrt_d`: f32 root refined by two Newton steps in f64. + pub fn sqrt_d(&mut self, x: Value) -> Value { + let n = self.isnan_d(x); + let z = self.dc(0.0); + let zero = self.fcmp(Pred::FOEq, x, z); + let inf = self.isinf_d(x); + let pos = self.fcmp(Pred::FOGt, x, z); + let pinf = self.land(inf, pos); + let keep = self.lor(n, zero); + let keep = self.lor(keep, pinf); + let neg = self.fcmp(Pred::FOLt, x, z); + let fe = self.frexp_exp_d(x); + let k = self.ashrc(fe, 1); + let zz = self.c(0); + let k2 = self.sub(zz, k); + let k2 = self.shlc(k2, 1); + let s = self.ldexp_d(x, k2); + let f32 = self.s.m.f32(); + let sf = self.s.m.cast(CastOp::FPTrunc, s, f32); + let rf = self.un(op::SQRT, sf); + let f64 = self.f64ty(); + let y = self.s.m.cast(CastOp::FPExt, rf, f64); + // y = y + (s - y*y) / (y + y) + let yy = self.fmul(y, y); + let num = self.fsub(s, yy); + let den = self.fadd(y, y); + let q = self.ddiv(num, den); + let y = self.fadd(y, q); + // y = y + fma(-y, y, s) / (y + y) + let ny = self.fneg(y); + let res = self.s.tertiary(Tertiary::Fma, ny, y, s); + let den = self.fadd(y, y); + let q = self.ddiv(res, den); + let y = self.fadd(y, q); + let r = self.ldexp_d(y, k); + let qnan = self.dbits(0, 0x7FF8_0000); + let r = self.sel(neg, qnan, r); + self.sel(keep, x, r) + } + pub fn fclass64(&mut self, f: Value) -> Value { + let (l, h) = self.s.split_double(f); + let e = self.lshrc(h, 20); + let e = self.andc(e, 0x7FF); + let m = self.andc(h, 0xF_FFFF); + let m = self.or(m, l); + let n = self.lshrc(h, 31); + let q = self.andc(h, 0x8_0000); + let qn = self.nz(q); + let mnz = self.nz(m); + let nn = self.nz(n); + self.fclass_bits(e, 0x7FF, mnz, qn, nn) + } +} diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs new file mode 100644 index 000000000..64cb15668 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -0,0 +1,44 @@ +//! Direct DXIL emission: console GPU code → DXIL containers without HLSL or +//! DXC. Design and roadmap: `docs/specs/2026-11-24-direct-dxil.md`. +//! +//! Layers, bottom up: +//! * [`bitstream`] — LLVM bitstream writer (unabbreviated records only); +//! * [`module`] — an LLVM 3.7 module (types, constants, one entry function, +//! metadata) and its bitcode; +//! * [`shader`] — DXIL on top: `dx.op` intrinsics, resource handles, +//! entry-point metadata, shader flags; +//! * [`container`] — the DXBC container (`SFI0`, signatures, `PSV0`, +//! `DXIL`) and its digest, so no SDK DLL is needed at run time; +//! * [`validate`] — `dxil.dll` validator and DXC disassembler as test oracles. + +pub mod bitstream; +pub mod cfg; +pub mod container; +pub mod coverage; +pub mod graphics; +pub mod kernel; +mod lanes; +pub mod lower; +mod lower_gfx; +mod lower_image; +mod lower_mem; +mod lower_valu; +mod lower_wide; +pub mod module; +pub mod ops; +pub mod ops_core; +mod prelude; +pub mod shader; +pub mod ssa; +pub mod validate; + +#[cfg(test)] +mod core_tests; +#[cfg(test)] +mod tests; +#[cfg(test)] +mod ops_tests; +#[cfg(test)] +mod bitreader_tests; +#[cfg(test)] +mod robustness_tests; diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs new file mode 100644 index 000000000..3462ca361 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -0,0 +1,1461 @@ +//! A DXIL module in memory (an LLVM 3.7 module restricted to what DXIL uses) +//! and its serialisation to bitcode. +//! +//! The module holds one defined function (the entry point) plus declarations +//! (`dx.op.*` intrinsics). Values are symbolic while the module is built +//! ([`Value`]) and numbered when written, in LLVM's order: global variables, +//! functions, module-level constants, then the entry's instruction results. +//! All constants live at module level, which LLVM permits and keeps function +//! bodies simple. +//! +//! Record layouts follow LLVM 3.7's `LLVMBitCodes.h` / `BitcodeWriter.cpp` +//! (University of Illinois/NCSA licence), checked against DXC's own output. + +use std::collections::HashMap; + +use super::bitstream::{signed, BitWriter}; + +mod opt; + +// ---------------------------------------------------------------- types + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Ty(u32); + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum TypeDef { + Void, + Label, + Metadata, + Half, + Float, + Double, + Int(u32), + Ptr(Ty, u32), + Struct(Option, Vec), + Array(u64, Ty), + Func(Ty, Vec), +} + +// --------------------------------------------------------------- values + +/// A value: global variable, function, module constant or instruction result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Value { + Global(u32), + Func(u32), + Const(u32), + Inst(u32), +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum ConstDef { + /// Sign-extended to 64 bits from the type's width. + Int(Ty, i64), + /// Raw IEEE bits of the type's width. + Float(Ty, u64), + Undef(Ty), + Null(Ty), + Aggregate(Ty, Vec), +} + +struct FuncDecl { + name: String, + ty: Ty, + attrs: FnAttrs, + defined: bool, +} + +/// Function attribute sets DXIL intrinsics use. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum FnAttrs { + None, + /// `nounwind readnone` + ReadNone, + /// `nounwind readonly` + ReadOnly, + /// `nounwind` + NoUnwind, + /// `noduplicate nounwind` (barriers) + NoDuplicate, +} + +impl FnAttrs { + /// Index into the PARAMATTR table (+1; 0 = none). + fn index(self) -> u64 { + match self { + FnAttrs::None => 0, + FnAttrs::ReadNone => 1, + FnAttrs::ReadOnly => 2, + FnAttrs::NoUnwind => 3, + FnAttrs::NoDuplicate => 4, + } + } +} + +struct GlobalDef { + name: String, + /// Value type (the global itself is a pointer to it). + ty: Ty, + ptr: Ty, + addrspace: u32, + init: Option, + constant: bool, + align: u32, +} + +// --------------------------------------------------------- instructions + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Block(pub u32); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BinOp { + Add = 0, + Sub = 1, + Mul = 2, + UDiv = 3, + SDiv = 4, + URem = 5, + SRem = 6, + Shl = 7, + LShr = 8, + AShr = 9, + And = 10, + Or = 11, + Xor = 12, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum CastOp { + Trunc = 0, + ZExt = 1, + SExt = 2, + FPToUI = 3, + FPToSI = 4, + UIToFP = 5, + SIToFP = 6, + FPTrunc = 7, + FPExt = 8, + BitCast = 11, +} + +/// Comparison predicates (LLVM `CmpInst::Predicate`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Pred { + FFalse = 0, + FOEq = 1, + FOGt = 2, + FOGe = 3, + FOLt = 4, + FOLe = 5, + FONe = 6, + FOrd = 7, + FUno = 8, + FUEq = 9, + FUGt = 10, + FUGe = 11, + FULt = 12, + FULe = 13, + FUNe = 14, + FTrue = 15, + Eq = 32, + Ne = 33, + UGt = 34, + UGe = 35, + ULt = 36, + ULe = 37, + SGt = 38, + SGe = 39, + SLt = 40, + SLe = 41, +} + +/// LLVM atomicrmw operations. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum RmwOp { + Xchg = 0, + Add = 1, + Sub = 2, + And = 3, + Nand = 4, + Or = 5, + Xor = 6, + Max = 7, + Min = 8, + UMax = 9, + UMin = 10, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Op { + Bin(BinOp, Value, Value, u64), + Cast(CastOp, Value, Ty), + Cmp(Pred, Value, Value), + Select(Value, Value, Value), + Extract(Value, u32), + Call(u32, Vec), + Phi(Vec<(Value, Block)>), + Load(Value, u32), + Store(Value, Value, u32), + Gep(Value, Vec), + AtomicRmw(RmwOp, Value, Value), + CmpXchg(Value, Value, Value), + /// allocated type, array size (an i32 constant), alignment + Alloca(Ty, Value, u32), + Br(Block), + CondBr(Value, Block, Block), + Switch(Value, Block, Vec<(Value, Block)>), + Ret, + Unreachable, +} + +struct InstDef { + op: Op, + ty: Ty, +} + +// ------------------------------------------------------------- metadata + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Md(u32); + +enum MdDef { + Str(String), + Val(Ty, Value), + Node(Vec>), +} + +// --------------------------------------------------------------- module + +/// Fast-math flags (LLVM 3.7 bitcode encoding). +pub mod fmf { + pub const NONE: u64 = 0; + pub const UNSAFE_ALGEBRA: u64 = 1; + pub const NO_NANS: u64 = 2; + pub const NO_INFS: u64 = 4; + pub const NO_SIGNED_ZEROS: u64 = 8; + pub const ALLOW_RECIPROCAL: u64 = 16; + /// HLSL's default (`fast`). + pub const FAST: u64 = 31; +} + +pub struct Module { + types: Vec, + type_ids: HashMap, + consts: Vec, + const_ids: HashMap, + funcs: Vec, + func_ids: HashMap, + globals: Vec, + insts: Vec, + blocks: Vec>, + cur: Block, + md: Vec, + named_md: Vec<(String, Vec)>, + md_strings: HashMap, + /// The first misuse of the builder (see [`Module::error`]); later ones are dropped. + error: std::cell::RefCell>, +} + +impl Default for Module { + fn default() -> Self { + Self::new() + } +} + +impl Module { + pub fn new() -> Self { + Module { + types: Vec::new(), + type_ids: HashMap::new(), + consts: Vec::new(), + const_ids: HashMap::new(), + funcs: Vec::new(), + func_ids: HashMap::new(), + globals: Vec::new(), + insts: Vec::new(), + blocks: vec![Vec::new()], + cur: Block(0), + md: Vec::new(), + named_md: Vec::new(), + md_strings: HashMap::new(), + error: std::cell::RefCell::new(None), + } + } + + // ---- errors + + /// Records a misuse of the builder (the first one is kept). The builder carries on with a + /// placeholder so callers need no error paths; [`Module::try_to_bitcode`] (and the + /// `Shader::try_finish*` methods) then fail with this message instead of emitting. + pub fn fail(&self, msg: impl Into) { + let mut e = self.error.borrow_mut(); + if e.is_none() { + *e = Some(msg.into()); + } + } + /// The first recorded builder error, if any. + pub fn error(&self) -> Option { + self.error.borrow().clone() + } + + // ---- types + + fn ty(&mut self, t: TypeDef) -> Ty { + if let Some(&id) = self.type_ids.get(&t) { + return id; + } + let id = Ty(self.types.len() as u32); + self.types.push(t.clone()); + self.type_ids.insert(t, id); + id + } + pub fn void(&mut self) -> Ty { + self.ty(TypeDef::Void) + } + pub fn label(&mut self) -> Ty { + self.ty(TypeDef::Label) + } + pub fn metadata(&mut self) -> Ty { + self.ty(TypeDef::Metadata) + } + pub fn int(&mut self, bits: u32) -> Ty { + self.ty(TypeDef::Int(bits)) + } + pub fn i1(&mut self) -> Ty { + self.int(1) + } + pub fn i8(&mut self) -> Ty { + self.int(8) + } + pub fn i32(&mut self) -> Ty { + self.int(32) + } + pub fn i64(&mut self) -> Ty { + self.int(64) + } + pub fn f16(&mut self) -> Ty { + self.ty(TypeDef::Half) + } + pub fn f32(&mut self) -> Ty { + self.ty(TypeDef::Float) + } + pub fn f64(&mut self) -> Ty { + self.ty(TypeDef::Double) + } + pub fn ptr(&mut self, pointee: Ty, addrspace: u32) -> Ty { + self.ty(TypeDef::Ptr(pointee, addrspace)) + } + pub fn array(&mut self, n: u64, elem: Ty) -> Ty { + self.ty(TypeDef::Array(n, elem)) + } + pub fn named_struct(&mut self, name: &str, elems: &[Ty]) -> Ty { + self.ty(TypeDef::Struct(Some(name.to_string()), elems.to_vec())) + } + pub fn func_ty(&mut self, ret: Ty, params: &[Ty]) -> Ty { + self.ty(TypeDef::Func(ret, params.to_vec())) + } + + pub fn is_float(&self, t: Ty) -> bool { + matches!(self.types[t.0 as usize], TypeDef::Half | TypeDef::Float | TypeDef::Double) + } + pub fn int_width(&self, t: Ty) -> Option { + match self.types[t.0 as usize] { + TypeDef::Int(w) => Some(w), + _ => None, + } + } + fn struct_elem(&mut self, t: Ty, i: u32) -> Ty { + let r = match &self.types[t.0 as usize] { + TypeDef::Struct(_, e) => e.get(i as usize).copied(), + TypeDef::Array(_, e) => Some(*e), + _ => None, + }; + r.unwrap_or_else(|| { + self.fail(format!("extractvalue {i} from {:?}", self.types[t.0 as usize])); + self.i32() + }) + } + fn pointee_of(&self, t: Ty) -> Option<(Ty, u32)> { + match self.types[t.0 as usize] { + TypeDef::Ptr(p, a) => Some((p, a)), + _ => None, + } + } + fn pointee(&mut self, t: Ty) -> (Ty, u32) { + self.pointee_of(t).unwrap_or_else(|| { + self.fail(format!("not a pointer: {:?}", self.types[t.0 as usize])); + (self.i32(), 0) + }) + } + + // ---- constants + + fn constant(&mut self, c: ConstDef) -> Value { + if let Some(&id) = self.const_ids.get(&c) { + return Value::Const(id); + } + let id = self.consts.len() as u32; + self.consts.push(c.clone()); + self.const_ids.insert(c, id); + Value::Const(id) + } + /// An integer constant; `v` is truncated / sign-extended to the type's width. + pub fn const_int(&mut self, ty: Ty, v: u64) -> Value { + let w = self.int_width(ty).unwrap_or_else(|| { + self.fail(format!("const_int of {:?}", self.types[ty.0 as usize])); + 64 + }); + let sext = if w >= 64 { v as i64 } else { ((v << (64 - w)) as i64) >> (64 - w) }; + self.constant(ConstDef::Int(ty, sext)) + } + pub fn i32c(&mut self, v: u32) -> Value { + let t = self.i32(); + self.const_int(t, v as u64) + } + pub fn i8c(&mut self, v: u8) -> Value { + let t = self.i8(); + self.const_int(t, v as u64) + } + pub fn i1c(&mut self, v: bool) -> Value { + let t = self.i1(); + self.const_int(t, v as u64) + } + pub fn f32c(&mut self, bits: u32) -> Value { + let t = self.f32(); + self.constant(ConstDef::Float(t, bits as u64)) + } + /// A floating-point constant of a half / float / double type from raw bits. + /// Bits above the type's width are ignored (as LLVM's reader truncates + /// them), so equal constants intern to one value. + pub fn const_float(&mut self, ty: Ty, bits: u64) -> Value { + let bits = match self.types[ty.0 as usize] { + TypeDef::Half => bits & 0xFFFF, + TypeDef::Float => bits & 0xFFFF_FFFF, + TypeDef::Double => bits, + ref other => { + self.fail(format!("const_float of {other:?}")); + bits + } + }; + self.constant(ConstDef::Float(ty, bits)) + } + pub fn undef(&mut self, ty: Ty) -> Value { + self.constant(ConstDef::Undef(ty)) + } + pub fn null(&mut self, ty: Ty) -> Value { + self.constant(ConstDef::Null(ty)) + } + pub fn aggregate(&mut self, ty: Ty, elems: &[Value]) -> Value { + self.constant(ConstDef::Aggregate(ty, elems.to_vec())) + } + + // ---- functions and globals + + /// Declares (or finds) a function by name. + pub fn declare(&mut self, name: &str, ty: Ty, attrs: FnAttrs) -> u32 { + if let Some(&f) = self.func_ids.get(name) { + if self.funcs[f as usize].ty != ty { + self.fail(format!("function {name} redeclared with another type")); + } + return f; + } + let f = self.funcs.len() as u32; + self.funcs.push(FuncDecl { name: name.to_string(), ty, attrs, defined: false }); + self.func_ids.insert(name.to_string(), f); + f + } + + /// Declares the entry point `void name()`; its body is built with the + /// instruction methods. + pub fn define_entry(&mut self, name: &str) -> u32 { + let v = self.void(); + let ty = self.func_ty(v, &[]); + let f = self.declare(name, ty, FnAttrs::None); + if self.funcs.iter().any(|f| f.defined) { + self.fail(format!("a second defined function ({name})")); + } + self.funcs[f as usize].defined = true; + f + } + + pub fn func_value(&self, f: u32) -> Value { + Value::Func(f) + } + + /// A global variable (e.g. thread-group shared memory in address space 3). + pub fn global(&mut self, name: &str, ty: Ty, addrspace: u32, init: Option, constant: bool, align: u32) -> Value { + let ptr = self.ptr(ty, addrspace); + let id = self.globals.len() as u32; + self.globals.push(GlobalDef { name: name.to_string(), ty, ptr, addrspace, init, constant, align }); + Value::Global(id) + } + + pub fn type_of(&mut self, v: Value) -> Ty { + match v { + Value::Global(g) => self.globals[g as usize].ptr, + Value::Func(f) => { + let t = self.funcs[f as usize].ty; + self.ptr(t, 0) + } + Value::Const(c) => match &self.consts[c as usize] { + ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + }, + Value::Inst(i) => self.insts[i as usize].ty, + } + } + + // ---- blocks + + pub fn new_block(&mut self) -> Block { + self.blocks.push(Vec::new()); + Block(self.blocks.len() as u32 - 1) + } + pub fn entry_block(&self) -> Block { + Block(0) + } + pub fn set_block(&mut self, b: Block) { + self.cur = b; + } + pub fn current_block(&self) -> Block { + self.cur + } + /// Whether the current block already ends in a terminator. + pub fn terminated(&self) -> bool { + self.blocks[self.cur.0 as usize].last().is_some_and(|&i| { + matches!(self.insts[i as usize].op, Op::Br(_) | Op::CondBr(..) | Op::Switch(..) | Op::Ret | Op::Unreachable) + }) + } + + fn push(&mut self, op: Op, ty: Ty) -> Value { + if self.terminated() { + self.fail(format!("instruction after a terminator in block {:?}", self.cur)); + } + let id = self.insts.len() as u32; + self.insts.push(InstDef { op, ty }); + self.blocks[self.cur.0 as usize].push(id); + Value::Inst(id) + } + + // ---- instructions + + pub fn bin(&mut self, op: BinOp, a: Value, b: Value) -> Value { + let t = self.type_of(a); + debug_assert_eq!(t, self.type_of(b), "binop operand types differ"); + self.push(Op::Bin(op, a, b, 0), t) + } + /// Floating-point binop (`Add` = fadd, `Sub` = fsub, `Mul` = fmul, + /// `SDiv` = fdiv, `SRem` = frem — the bitcode reader rejects `UDiv` / + /// `URem` on floats) with fast-math flags. + pub fn fbin(&mut self, op: BinOp, a: Value, b: Value, flags: u64) -> Value { + let t = self.type_of(a); + debug_assert!(self.is_float(t)); + self.push(Op::Bin(op, a, b, flags), t) + } + /// Integer binop with `nuw` (1) / `nsw` (2) / `exact` (1) flags. + pub fn bin_flags(&mut self, op: BinOp, a: Value, b: Value, flags: u64) -> Value { + let t = self.type_of(a); + self.push(Op::Bin(op, a, b, flags), t) + } + pub fn cast(&mut self, op: CastOp, v: Value, to: Ty) -> Value { + self.push(Op::Cast(op, v, to), to) + } + pub fn bitcast(&mut self, v: Value, to: Ty) -> Value { + if self.type_of(v) == to { + return v; + } + self.cast(CastOp::BitCast, v, to) + } + pub fn cmp(&mut self, p: Pred, a: Value, b: Value) -> Value { + let t = self.i1(); + self.push(Op::Cmp(p, a, b), t) + } + pub fn select(&mut self, c: Value, t: Value, f: Value) -> Value { + let ty = self.type_of(t); + self.push(Op::Select(c, t, f), ty) + } + pub fn extract(&mut self, agg: Value, idx: u32) -> Value { + let at = self.type_of(agg); + let t = self.struct_elem(at, idx); + self.push(Op::Extract(agg, idx), t) + } + pub fn call(&mut self, f: u32, args: &[Value]) -> Value { + let ret = match &self.types[self.funcs[f as usize].ty.0 as usize] { + TypeDef::Func(r, p) => { + let r = *r; + if p.len() != args.len() { + self.fail(format!("call to {} with {} arguments", self.funcs[f as usize].name, args.len())); + } + r + } + _ => { + self.fail(format!("call to {}, not a function type", self.funcs[f as usize].name)); + self.void() + } + }; + self.push(Op::Call(f, args.to_vec()), ret) + } + /// A phi of type `ty`; incoming edges are added with [`Module::add_incoming`]. + pub fn phi(&mut self, ty: Ty) -> Value { + // Phis must lead their block. + debug_assert!(self.blocks[self.cur.0 as usize].iter().all(|&i| matches!(self.insts[i as usize].op, Op::Phi(_)))); + self.push(Op::Phi(Vec::new()), ty) + } + /// A phi of type `ty` placed after the existing phis of block `b`, whatever + /// the current block is and whether `b` already holds other instructions + /// (on-the-fly SSA construction creates phis in blocks already filled). + pub fn phi_at(&mut self, b: Block, ty: Ty) -> Value { + let id = self.insts.len() as u32; + self.insts.push(InstDef { op: Op::Phi(Vec::new()), ty }); + let list = &mut self.blocks[b.0 as usize]; + let at = list.iter().position(|&i| !matches!(self.insts[i as usize].op, Op::Phi(_))).unwrap_or(list.len()); + list.insert(at, id); + Value::Inst(id) + } + /// A phi of type `ty` not yet in any block (place it with [`Module::place_phi`]; + /// one never placed is simply not written). + pub fn detached_phi(&mut self, ty: Ty) -> Value { + let id = self.insts.len() as u32; + self.insts.push(InstDef { op: Op::Phi(Vec::new()), ty }); + Value::Inst(id) + } + /// Puts a [`Module::detached_phi`] after the existing phis of block `b`. + pub fn place_phi(&mut self, b: Block, phi: Value) { + let Value::Inst(id) = phi else { panic!("not a phi") }; + let list = &mut self.blocks[b.0 as usize]; + let at = list.iter().position(|&i| !matches!(self.insts[i as usize].op, Op::Phi(_))).unwrap_or(list.len()); + list.insert(at, id); + } + /// Number of incoming edges a phi has so far. + pub fn phi_incoming(&self, phi: Value) -> Vec<(Value, Block)> { + let Value::Inst(i) = phi else { return Vec::new() }; + match &self.insts[i as usize].op { + Op::Phi(list) => list.clone(), + _ => Vec::new(), + } + } + pub fn add_incoming(&mut self, phi: Value, v: Value, from: Block) { + if let Value::Inst(i) = phi { + if let Op::Phi(list) = &mut self.insts[i as usize].op { + list.push((v, from)); + return; + } + } + self.fail(format!("add_incoming to a non-phi {phi:?}")); + } + pub fn load(&mut self, ptr: Value, align: u32) -> Value { + let pt = self.type_of(ptr); + let (t, _) = self.pointee(pt); + self.push(Op::Load(ptr, align), t) + } + pub fn store(&mut self, ptr: Value, v: Value, align: u32) { + let t = self.void(); + self.push(Op::Store(ptr, v, align), t); + } + /// `getelementptr inbounds` with constant / variable indices. + pub fn gep(&mut self, ptr: Value, idx: &[Value]) -> Value { + let pt = self.type_of(ptr); + let (mut t, space) = self.pointee(pt); + for _ in 1..idx.len() { + t = match &self.types[t.0 as usize] { + TypeDef::Array(_, e) => *e, + other => { + self.fail(format!("gep into {other:?}")); + break; + } + }; + } + let rt = self.ptr(t, space); + self.push(Op::Gep(ptr, idx.to_vec()), rt) + } + pub fn atomic_rmw(&mut self, op: RmwOp, ptr: Value, v: Value) -> Value { + let t = self.type_of(v); + self.push(Op::AtomicRmw(op, ptr, v), t) + } + /// `cmpxchg` returning the old value (`{ T, i1 }` extracted at index 0). + pub fn cmpxchg(&mut self, ptr: Value, cmp: Value, new: Value) -> Value { + let t = self.type_of(cmp); + let b = self.i1(); + let st = self.ty(TypeDef::Struct(None, vec![t, b])); + let pair = self.push(Op::CmpXchg(ptr, cmp, new), st); + self.extract(pair, 0) + } + /// `alloca , align ` (a function-local variable, e.g. an indexable array; + /// emit it in the entry block). + pub fn alloca(&mut self, ty: Ty, align: u32) -> Value { + let one = self.i32c(1); + let p = self.ptr(ty, 0); + self.push(Op::Alloca(ty, one, align), p) + } + pub fn br(&mut self, to: Block) { + let t = self.void(); + self.push(Op::Br(to), t); + } + pub fn cond_br(&mut self, c: Value, t: Block, f: Block) { + let v = self.void(); + self.push(Op::CondBr(c, t, f), v); + } + pub fn switch(&mut self, v: Value, default: Block, cases: &[(Value, Block)]) { + let t = self.void(); + self.push(Op::Switch(v, default, cases.to_vec()), t); + } + pub fn ret(&mut self) { + let t = self.void(); + self.push(Op::Ret, t); + } + pub fn unreachable(&mut self) { + let t = self.void(); + self.push(Op::Unreachable, t); + } + + // ---- metadata + + pub fn md_str(&mut self, s: &str) -> Md { + if let Some(&m) = self.md_strings.get(s) { + return m; + } + let m = Md(self.md.len() as u32); + self.md.push(MdDef::Str(s.to_string())); + self.md_strings.insert(s.to_string(), m); + m + } + pub fn md_value(&mut self, v: Value) -> Md { + let t = self.type_of(v); + let m = Md(self.md.len() as u32); + self.md.push(MdDef::Val(t, v)); + m + } + pub fn md_i32(&mut self, v: u32) -> Md { + let c = self.i32c(v); + self.md_value(c) + } + pub fn md_i64(&mut self, v: u64) -> Md { + let t = self.i64(); + let c = self.const_int(t, v); + self.md_value(c) + } + pub fn md_i1(&mut self, v: bool) -> Md { + let c = self.i1c(v); + self.md_value(c) + } + pub fn md_node(&mut self, elems: &[Option]) -> Md { + let m = Md(self.md.len() as u32); + self.md.push(MdDef::Node(elems.to_vec())); + m + } + pub fn named_md(&mut self, name: &str, nodes: &[Md]) { + self.named_md.push((name.to_string(), nodes.to_vec())); + } + + // ---------------------------------------------------- serialisation + + /// [`Module::to_bitcode`], or the first builder error (recorded while building or + /// found while writing, e.g. a forward reference outside a phi). + pub fn try_to_bitcode(&mut self, triple: &str, datalayout: &str) -> Result, String> { + if let Some(e) = self.error() { + return Err(e); + } + let b = self.write_bitcode(triple, datalayout); + match self.error() { + Some(e) => Err(e), + None => Ok(b), + } + } + + /// The module as LLVM 3.7 bitcode (`BC\xC0\xDE` …). Panics on a builder error + /// (recorded or found while writing); [`Module::try_to_bitcode`] reports it instead. + pub fn to_bitcode(&mut self, triple: &str, datalayout: &str) -> Vec { + self.try_to_bitcode(triple, datalayout).unwrap_or_else(|e| panic!("DXIL builder: {e}")) + } + + fn write_bitcode(&mut self, triple: &str, datalayout: &str) -> Vec { + // Every type the writer references must exist before the type table: + // pointers to the declared functions (call / metadata operands). + for f in 0..self.funcs.len() { + self.type_of(Value::Func(f as u32)); + } + + // Blocks are written in reverse post-order of the entry's CFG (entry + // first), so a lowering may create blocks in any order; unreachable blocks + // are dropped. Value numbering follows that order. + let (order, pos) = self.block_layout(); + + // Global variables nothing references (e.g. an exchange array the code never + // needed) are left out: the validator rejects unused internal declarations. + // Likewise declarations of functions no longer called (after `optimize`). + let mut gused = vec![false; self.globals.len()]; + let mut fused: Vec = self.funcs.iter().map(|f| f.defined).collect(); + { + let mut mark = |v: Value| match v { + Value::Global(g) => gused[g as usize] = true, + Value::Func(f) => fused[f as usize] = true, + _ => {} + }; + for &b in &order { + for &i in &self.blocks[b] { + let op = &self.insts[i as usize].op; + if let Op::Call(f, _) = op { + mark(Value::Func(*f)); + } + op.for_each_operand(&mut mark); + } + } + for c in &self.consts { + if let ConstDef::Aggregate(_, e) = c { + e.iter().copied().for_each(&mut mark); + } + } + for m in &self.md { + if let MdDef::Val(_, v) = m { + mark(*v); + } + } + } + let mut gmap: Vec> = vec![None; self.globals.len()]; + let mut n_globals = 0u64; + for (g, used) in gused.iter().enumerate() { + if *used { + gmap[g] = Some(n_globals); + n_globals += 1; + } + } + let gmap = &gmap; + let mut fmap: Vec> = vec![None; self.funcs.len()]; + let mut n_funcs = 0u64; + for (f, used) in fused.iter().enumerate() { + if *used { + fmap[f] = Some(n_funcs); + n_funcs += 1; + } + } + let fmap = &fmap; + let n_consts = self.consts.len() as u64; + let const_base = n_globals + n_funcs; + let inst_base = const_base + n_consts; + + // Absolute value ids of instruction results. + let mut inst_ids: Vec> = vec![None; self.insts.len()]; + { + let mut next = inst_base; + for &b in &order { + for &i in &self.blocks[b] { + if !self.is_void(self.insts[i as usize].ty) { + inst_ids[i as usize] = Some(next); + next += 1; + } + } + } + } + let abs = |v: Value| -> u64 { + match v { + Value::Global(g) => gmap[g as usize].expect("use of a dropped global"), + Value::Func(f) => n_globals + fmap[f as usize].expect("use of a dropped function"), + Value::Const(c) => const_base + c as u64, + Value::Inst(i) => inst_ids[i as usize].unwrap_or_else(|| { + self.fail(format!("use of a void instruction %{i}")); + 0 + }), + } + }; + + let mut w = BitWriter::new(); + for b in [b'B', b'C', 0xC0, 0xDE] { + w.emit(b as u64, 8); + } + w.enter_block(BLOCK_MODULE); + w.record(MODULE_CODE_VERSION, &[1]); + + // Attribute groups: 1 = nounwind readnone, 2 = nounwind readonly, + // 3 = nounwind, 4 = noduplicate nounwind. + w.enter_block(BLOCK_PARAMATTR_GROUP); + const FN: u64 = 0xFFFF_FFFF; + w.record(PARAMATTR_GRP_CODE_ENTRY, &[1, FN, 0, ATTR_NOUNWIND, 0, ATTR_READNONE]); + w.record(PARAMATTR_GRP_CODE_ENTRY, &[2, FN, 0, ATTR_NOUNWIND, 0, ATTR_READONLY]); + w.record(PARAMATTR_GRP_CODE_ENTRY, &[3, FN, 0, ATTR_NOUNWIND]); + w.record(PARAMATTR_GRP_CODE_ENTRY, &[4, FN, 0, ATTR_NODUPLICATE, 0, ATTR_NOUNWIND]); + w.end_block(); + w.enter_block(BLOCK_PARAMATTR); + for g in 1..=4 { + w.record(PARAMATTR_CODE_ENTRY, &[g]); + } + w.end_block(); + + self.write_types(&mut w); + w.record_str(MODULE_CODE_TRIPLE, &[], triple); + w.record_str(MODULE_CODE_DATALAYOUT, &[], datalayout); + + for g in self.globals.iter().enumerate().filter(|(i, _)| gused[*i]).map(|x| x.1) { + // [valty, addrspace<<2 | explicit_type<<1 | isconst, initid+1, linkage, align, section, + // visibility, tls, unnamed_addr, externally_initialized, dllstorage, comdat] + let init = g.init.map_or(0, |v| abs(v) + 1); + let linkage = if g.init.is_some() { LINKAGE_INTERNAL } else { LINKAGE_EXTERNAL }; + let align = if g.align == 0 { 0 } else { g.align.trailing_zeros() as u64 + 1 }; + w.record( + MODULE_CODE_GLOBALVAR, + &[g.ty.0 as u64, ((g.addrspace as u64) << 2) | 2 | g.constant as u64, init, linkage, align, 0, 0, 0, 0, 0, 0, 0], + ); + } + for f in self.funcs.iter().enumerate().filter(|(i, _)| fused[*i]).map(|x| x.1) { + // [type, cc, isproto, linkage, paramattr, align, section, visibility, + // gc, unnamed_addr, prologue, dllstorage, comdat, prefix, personality] + w.record( + MODULE_CODE_FUNCTION, + &[f.ty.0 as u64, 0, (!f.defined) as u64, LINKAGE_EXTERNAL, f.attrs.index(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ); + } + + // Module-level constants. + if !self.consts.is_empty() { + w.enter_block(BLOCK_CONSTANTS); + let mut cur_ty = None; + for c in &self.consts { + let t = match c { + ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + }; + if cur_ty != Some(t) { + w.record(CST_CODE_SETTYPE, &[t.0 as u64]); + cur_ty = Some(t); + } + match c { + ConstDef::Int(_, v) => w.record(CST_CODE_INTEGER, &[signed(*v)]), + ConstDef::Float(_, bits) => w.record(CST_CODE_FLOAT, &[*bits]), + ConstDef::Undef(_) => w.record(CST_CODE_UNDEF, &[]), + ConstDef::Null(_) => w.record(CST_CODE_NULL, &[]), + ConstDef::Aggregate(_, e) => { + let ops: Vec = e.iter().map(|&v| abs(v)).collect(); + w.record(CST_CODE_AGGREGATE, &ops) + } + } + } + w.end_block(); + } + + // Metadata. + if !self.md.is_empty() || !self.named_md.is_empty() { + w.enter_block(BLOCK_METADATA); + for m in &self.md { + match m { + MdDef::Str(s) => w.record_str(METADATA_STRING, &[], s), + MdDef::Val(t, v) => w.record(METADATA_VALUE, &[t.0 as u64, abs(*v)]), + MdDef::Node(e) => { + let ops: Vec = e.iter().map(|m| m.map_or(0, |m| m.0 as u64 + 1)).collect(); + w.record(METADATA_NODE, &ops) + } + } + } + for (name, nodes) in &self.named_md { + w.record_str(METADATA_NAME, &[], name); + let ops: Vec = nodes.iter().map(|m| m.0 as u64).collect(); + w.record(METADATA_NAMED_NODE, &ops); + } + w.end_block(); + } + + // Module value symbol table: names of globals and functions. + w.enter_block(BLOCK_VALUE_SYMTAB); + for (i, g) in self.globals.iter().enumerate() { + if let Some(k) = gmap[i] { + w.record_str(VST_CODE_ENTRY, &[k], &g.name); + } + } + for (i, f) in self.funcs.iter().enumerate() { + if let Some(k) = fmap[i] { + w.record_str(VST_CODE_ENTRY, &[n_globals + k], &f.name); + } + } + w.end_block(); + + // The entry's body. + w.enter_block(BLOCK_FUNCTION); + w.record(FUNC_CODE_DECLAREBLOCKS, &[order.len() as u64]); + let mut inst_id = inst_base; + for &b in &order { + for k in 0..self.blocks[b].len() { + let i = self.blocks[b][k] as usize; + self.write_inst(&mut w, i, inst_id, &abs, &pos); + if !self.is_void(self.insts[i].ty) { + inst_id += 1; + } + } + } + w.end_block(); + + w.end_block(); // module + w.finish() + } + + fn is_void(&self, t: Ty) -> bool { + matches!(self.types[t.0 as usize], TypeDef::Void) + } + + fn write_types(&self, w: &mut BitWriter) { + w.enter_block(BLOCK_TYPE); + w.record(TYPE_CODE_NUMENTRY, &[self.types.len() as u64]); + for t in &self.types { + match t { + TypeDef::Void => w.record(TYPE_CODE_VOID, &[]), + TypeDef::Label => w.record(TYPE_CODE_LABEL, &[]), + TypeDef::Metadata => w.record(TYPE_CODE_METADATA, &[]), + TypeDef::Half => w.record(TYPE_CODE_HALF, &[]), + TypeDef::Float => w.record(TYPE_CODE_FLOAT, &[]), + TypeDef::Double => w.record(TYPE_CODE_DOUBLE, &[]), + TypeDef::Int(n) => w.record(TYPE_CODE_INTEGER, &[*n as u64]), + TypeDef::Ptr(p, a) => w.record(TYPE_CODE_POINTER, &[p.0 as u64, *a as u64]), + TypeDef::Array(n, e) => w.record(TYPE_CODE_ARRAY, &[*n, e.0 as u64]), + TypeDef::Func(r, p) => { + let mut ops = vec![0, r.0 as u64]; + ops.extend(p.iter().map(|t| t.0 as u64)); + w.record(TYPE_CODE_FUNCTION, &ops) + } + TypeDef::Struct(name, e) => { + let mut ops = vec![0]; + ops.extend(e.iter().map(|t| t.0 as u64)); + match name { + Some(n) => { + w.record_str(TYPE_CODE_STRUCT_NAME, &[], n); + w.record(TYPE_CODE_STRUCT_NAMED, &ops) + } + None => w.record(TYPE_CODE_STRUCT_ANON, &ops), + } + } + } + } + w.end_block(); + } + + /// Successor blocks of block `b` (from its terminator, if any). + fn successors(&self, b: usize) -> Vec { + match self.blocks[b].last().map(|&i| &self.insts[i as usize].op) { + Some(Op::Br(t)) => vec![*t], + Some(Op::CondBr(_, t, f)) => vec![*t, *f], + Some(Op::Switch(_, d, cases)) => std::iter::once(*d).chain(cases.iter().map(|c| c.1)).collect(), + _ => Vec::new(), + } + } + + /// The written block order (reverse post-order from the entry block, which + /// keeps the creation order where that is already a valid layout) and each + /// block's position in it (`None`: unreachable, not written). + fn block_layout(&self) -> (Vec, Vec>) { + let n = self.blocks.len(); + let mut seen = vec![false; n]; + let mut post = Vec::with_capacity(n); + // Iterative DFS; successors pushed so that earlier-created ones are visited + // last, which makes the reverse post-order prefer creation order. + let mut stack: Vec<(usize, Vec)> = vec![(0, { + let mut s = self.successors(0); + s.sort_by_key(|b| std::cmp::Reverse(b.0)); + s + })]; + seen[0] = true; + while let Some((b, succ)) = stack.last_mut() { + match succ.pop() { + Some(t) => { + let t = t.0 as usize; + if t < n && !seen[t] { + seen[t] = true; + let mut s = self.successors(t); + s.sort_by_key(|b| std::cmp::Reverse(b.0)); + stack.push((t, s)); + } + } + None => { + post.push(*b); + stack.pop(); + } + } + } + post.reverse(); + let mut pos = vec![None; n]; + for (k, &b) in post.iter().enumerate() { + pos[b] = Some(k as u32); + } + (post, pos) + } + + /// Replaces every use of `old` by `new` in the entry's instructions and in + /// metadata (e.g. to drop a trivial phi). `old` itself stays in its block. + pub fn replace_all_uses(&mut self, old: Value, new: Value) { + let r = |v: &mut Value| { + if *v == old { + *v = new; + } + }; + for inst in &mut self.insts { + match &mut inst.op { + Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::Store(a, b, _) | Op::AtomicRmw(_, a, b) => { + r(a); + r(b) + } + Op::Cast(_, a, _) | Op::Extract(a, _) | Op::Load(a, _) | Op::CondBr(a, _, _) | Op::Alloca(_, a, _) => r(a), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + r(a); + r(b); + r(c) + } + Op::Call(_, args) => args.iter_mut().for_each(r), + Op::Phi(inc) => inc.iter_mut().for_each(|(v, _)| r(v)), + Op::Gep(p, idx) => { + r(p); + idx.iter_mut().for_each(r) + } + Op::Switch(v, _, cases) => { + r(v); + cases.iter_mut().for_each(|(c, _)| r(c)) + } + Op::Br(_) | Op::Ret | Op::Unreachable => {} + } + } + for m in &mut self.md { + if let MdDef::Val(_, v) = m { + r(v); + } + } + } + + fn write_inst(&self, w: &mut BitWriter, i: usize, inst_id: u64, abs: &dyn Fn(Value) -> u64, pos: &[Option]) { + // Relative operand; forward references are only legal in phis. + let rel = |v: Value| -> u64 { + let a = abs(v); + if a >= inst_id { + self.fail(format!("forward reference to value {a} at instruction {inst_id} (blocks must be in dominance order)")); + return 1; + } + inst_id - a + }; + let bb = |b: Block| match pos.get(b.0 as usize).copied().flatten() { + Some(p) => p as u64, + None => { + self.fail(format!("branch to missing block {}", b.0)); + 0 + } + }; + match &self.insts[i].op { + Op::Bin(op, a, b, flags) => { + let mut ops = vec![rel(*a), rel(*b), *op as u64]; + if *flags != 0 { + ops.push(*flags); + } + w.record(FUNC_CODE_INST_BINOP, &ops) + } + Op::Cast(op, v, t) => w.record(FUNC_CODE_INST_CAST, &[rel(*v), t.0 as u64, *op as u64]), + Op::Cmp(p, a, b) => w.record(FUNC_CODE_INST_CMP2, &[rel(*a), rel(*b), *p as u64]), + Op::Select(c, t, f) => w.record(FUNC_CODE_INST_VSELECT, &[rel(*t), rel(*f), rel(*c)]), + Op::Extract(a, idx) => w.record(FUNC_CODE_INST_EXTRACTVAL, &[rel(*a), *idx as u64]), + Op::Call(f, args) => { + let fd = &self.funcs[*f as usize]; + let mut ops = vec![0, 1 << 15, fd.ty.0 as u64, rel(Value::Func(*f))]; + ops.extend(args.iter().map(|&a| rel(a))); + w.record(FUNC_CODE_INST_CALL, &ops) + } + Op::Phi(inc) => { + let mut ops = vec![self.insts[i].ty.0 as u64]; + // incoming edges from unreachable (unwritten) blocks are dropped + for &(v, b) in inc.iter().filter(|(_, b)| pos.get(b.0 as usize).copied().flatten().is_some()) { + ops.push(signed(inst_id as i64 - abs(v) as i64)); + ops.push(bb(b)); + } + w.record(FUNC_CODE_INST_PHI, &ops) + } + Op::Load(p, align) => { + let a = if *align == 0 { 0 } else { align.trailing_zeros() as u64 + 1 }; + w.record(FUNC_CODE_INST_LOAD, &[rel(*p), self.insts[i].ty.0 as u64, a, 0]) + } + Op::Store(p, v, align) => { + let a = if *align == 0 { 0 } else { align.trailing_zeros() as u64 + 1 }; + w.record(FUNC_CODE_INST_STORE, &[rel(*p), rel(*v), a, 0]) + } + Op::Gep(p, idx) => { + let pt = self.value_ty(*p); + let (src, _) = self.pointee_of(pt).unwrap_or((pt, 0)); + let mut ops = vec![1, src.0 as u64, rel(*p)]; + ops.extend(idx.iter().map(|&v| rel(v))); + w.record(FUNC_CODE_INST_GEP, &ops) + } + Op::AtomicRmw(op, p, v) => { + // [ptr, val, op, vol, ordering, synchscope (crossthread = 1)] + w.record(FUNC_CODE_INST_ATOMICRMW, &[rel(*p), rel(*v), *op as u64, 0, ORDERING_SEQCST, 1]) + } + Op::CmpXchg(p, c, n) => { + // [ptr, cmp, new, vol, success ordering, synchscope, failure ordering, weak] + w.record(FUNC_CODE_INST_CMPXCHG, &[rel(*p), rel(*c), rel(*n), 0, ORDERING_SEQCST, 1, ORDERING_SEQCST, 0]) + } + Op::Alloca(t, n, align) => { + // [instty, opty, size (absolute value id), align record (log2 + 1 | explicit type)] + let i32t = self.value_ty(*n); + let a = align.trailing_zeros() as u64 + 1; + w.record(FUNC_CODE_INST_ALLOCA, &[t.0 as u64, i32t.0 as u64, abs(*n), a | 1 << 6]) + } + Op::Br(b) => w.record(FUNC_CODE_INST_BR, &[bb(*b)]), + Op::CondBr(c, t, f) => w.record(FUNC_CODE_INST_BR, &[bb(*t), bb(*f), rel(*c)]), + Op::Switch(v, d, cases) => { + let mut ops = vec![self.value_ty(*v).0 as u64, rel(*v), bb(*d)]; + for &(c, b) in cases { + ops.push(abs(c)); + ops.push(bb(b)); + } + w.record(FUNC_CODE_INST_SWITCH, &ops) + } + Op::Ret => w.record(FUNC_CODE_INST_RET, &[]), + Op::Unreachable => w.record(FUNC_CODE_INST_UNREACHABLE, &[]), + } + } + + /// `type_of` without interning (writer side; pointer types already exist). + fn value_ty(&self, v: Value) -> Ty { + match v { + Value::Global(g) => self.globals[g as usize].ptr, + Value::Func(f) => self.type_ids[&TypeDef::Ptr(self.funcs[f as usize].ty, 0)], + Value::Const(c) => match &self.consts[c as usize] { + ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + }, + Value::Inst(i) => self.insts[i as usize].ty, + } + } +} + +// LLVMBitCodes.h (3.7) +const BLOCK_MODULE: u32 = 8; +const BLOCK_PARAMATTR: u32 = 9; +const BLOCK_PARAMATTR_GROUP: u32 = 10; +const BLOCK_CONSTANTS: u32 = 11; +const BLOCK_FUNCTION: u32 = 12; +const BLOCK_VALUE_SYMTAB: u32 = 14; +const BLOCK_METADATA: u32 = 15; +const BLOCK_TYPE: u32 = 17; + +const MODULE_CODE_VERSION: u32 = 1; +const MODULE_CODE_TRIPLE: u32 = 2; +const MODULE_CODE_DATALAYOUT: u32 = 3; +const MODULE_CODE_GLOBALVAR: u32 = 7; +const MODULE_CODE_FUNCTION: u32 = 8; + +const PARAMATTR_CODE_ENTRY: u32 = 2; +const PARAMATTR_GRP_CODE_ENTRY: u32 = 3; +const ATTR_NODUPLICATE: u64 = 12; +const ATTR_NOUNWIND: u64 = 18; +const ATTR_READNONE: u64 = 20; +const ATTR_READONLY: u64 = 21; + +/// `bitc::ORDERING_SEQCST`: the bitcode code, not the in-memory +/// `AtomicOrdering::SequentiallyConsistent` (7), which LLVM's reader only +/// accepts because it maps unknown codes to seq_cst. +const ORDERING_SEQCST: u64 = 6; + +const LINKAGE_EXTERNAL: u64 = 0; +const LINKAGE_INTERNAL: u64 = 3; + +const TYPE_CODE_NUMENTRY: u32 = 1; +const TYPE_CODE_VOID: u32 = 2; +const TYPE_CODE_FLOAT: u32 = 3; +const TYPE_CODE_DOUBLE: u32 = 4; +const TYPE_CODE_LABEL: u32 = 5; +const TYPE_CODE_INTEGER: u32 = 7; +const TYPE_CODE_POINTER: u32 = 8; +const TYPE_CODE_HALF: u32 = 10; +const TYPE_CODE_ARRAY: u32 = 11; +const TYPE_CODE_METADATA: u32 = 16; +const TYPE_CODE_STRUCT_ANON: u32 = 18; +const TYPE_CODE_STRUCT_NAME: u32 = 19; +const TYPE_CODE_STRUCT_NAMED: u32 = 20; +const TYPE_CODE_FUNCTION: u32 = 21; + +const CST_CODE_SETTYPE: u32 = 1; +const CST_CODE_NULL: u32 = 2; +const CST_CODE_UNDEF: u32 = 3; +const CST_CODE_INTEGER: u32 = 4; +const CST_CODE_FLOAT: u32 = 6; +const CST_CODE_AGGREGATE: u32 = 7; + +const METADATA_STRING: u32 = 1; +const METADATA_VALUE: u32 = 2; +const METADATA_NODE: u32 = 3; +const METADATA_NAME: u32 = 4; +const METADATA_NAMED_NODE: u32 = 10; + +const VST_CODE_ENTRY: u32 = 1; + +const FUNC_CODE_DECLAREBLOCKS: u32 = 1; +const FUNC_CODE_INST_BINOP: u32 = 2; +const FUNC_CODE_INST_CAST: u32 = 3; +const FUNC_CODE_INST_RET: u32 = 10; +const FUNC_CODE_INST_BR: u32 = 11; +const FUNC_CODE_INST_SWITCH: u32 = 12; +const FUNC_CODE_INST_UNREACHABLE: u32 = 15; +const FUNC_CODE_INST_PHI: u32 = 16; +const FUNC_CODE_INST_ALLOCA: u32 = 19; +const FUNC_CODE_INST_LOAD: u32 = 20; +const FUNC_CODE_INST_EXTRACTVAL: u32 = 26; +const FUNC_CODE_INST_CMP2: u32 = 28; +const FUNC_CODE_INST_VSELECT: u32 = 29; +const FUNC_CODE_INST_CALL: u32 = 34; +const FUNC_CODE_INST_ATOMICRMW: u32 = 38; +const FUNC_CODE_INST_GEP: u32 = 43; +const FUNC_CODE_INST_STORE: u32 = 44; +const FUNC_CODE_INST_CMPXCHG: u32 = 46; + +// ------------------------------------------------------- introspection + +/// What an instruction is, for analyses over the built function (e.g. the +/// signature dependency tables PSV0 carries). +#[derive(Debug, Clone)] +pub enum InstInfo<'a> { + /// A call: callee name and arguments. + Call(&'a str, &'a [Value]), + Phi(&'a [(Value, Block)]), + Load(Value), + Store(Value, Value), + /// Any other value-producing instruction with its value operands. + Other(Vec), + /// A terminator: condition operand (if any) and successors. + Term(Option, Vec), +} + +impl Module { + pub fn block_count(&self) -> usize { + self.blocks.len() + } + pub fn block_insts(&self, b: Block) -> &[u32] { + &self.blocks[b.0 as usize] + } + pub fn inst_info(&self, i: u32) -> InstInfo<'_> { + match &self.insts[i as usize].op { + Op::Call(f, args) => InstInfo::Call(&self.funcs[*f as usize].name, args), + Op::Phi(list) => InstInfo::Phi(list), + Op::Load(p, _) => InstInfo::Load(*p), + Op::Store(p, v, _) => InstInfo::Store(*p, *v), + Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) => InstInfo::Other(vec![*a, *b]), + Op::Cast(_, v, _) | Op::Extract(v, _) => InstInfo::Other(vec![*v]), + Op::Select(c, t, f) => InstInfo::Other(vec![*c, *t, *f]), + Op::Gep(p, idx) => InstInfo::Other(std::iter::once(*p).chain(idx.iter().copied()).collect()), + Op::AtomicRmw(_, p, v) => InstInfo::Other(vec![*p, *v]), + Op::CmpXchg(p, c, n) => InstInfo::Other(vec![*p, *c, *n]), + Op::Alloca(..) => InstInfo::Other(Vec::new()), + Op::Br(b) => InstInfo::Term(None, vec![*b]), + Op::CondBr(c, t, f) => InstInfo::Term(Some(*c), vec![*t, *f]), + Op::Switch(v, d, cases) => InstInfo::Term(Some(*v), std::iter::once(*d).chain(cases.iter().map(|c| c.1)).collect()), + Op::Ret | Op::Unreachable => InstInfo::Term(None, Vec::new()), + } + } + /// Whether an instruction of the entry function produces or consumes a + /// value of type `t` (the shader-flag rules key off instruction types). + /// The 64-bit integer and double types, if already interned (lookup + /// without adding them to the type table). + pub fn existing_i64_f64(&self) -> (Option, Option) { + (self.type_ids.get(&TypeDef::Int(64)).copied(), self.type_ids.get(&TypeDef::Double).copied()) + } + /// Whether the entry uses a D3D11.1 double extension through plain + /// instructions: double `fdiv`, or conversions between double and + /// integers (DXC's shader-flag rules; `Fma` is flagged by its helper). + pub fn uses_double_extensions(&self) -> bool { + let Some(f64) = self.type_ids.get(&TypeDef::Double).copied() else { return false }; + self.insts.iter().any(|d| match &d.op { + Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, + Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, + Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, + _ => false, + }) + } + pub fn insts_use_type(&self, t: Ty) -> bool { + self.blocks.iter().flatten().any(|&i| { + let d = &self.insts[i as usize]; + if d.ty == t { + return true; + } + let ops: Vec = match self.inst_info(i) { + InstInfo::Call(_, a) => a.to_vec(), + InstInfo::Phi(l) => l.iter().map(|p| p.0).collect(), + InstInfo::Load(p) => vec![p], + InstInfo::Store(p, v) => vec![p, v], + InstInfo::Other(v) => v, + InstInfo::Term(c, _) => c.into_iter().collect(), + }; + ops.into_iter().any(|v| self.value_ty(v) == t) + }) + } + /// The integer value of a constant (zero-extended from its width). + pub fn const_u64(&self, v: Value) -> Option { + match v { + Value::Const(c) => match &self.consts[c as usize] { + ConstDef::Int(t, x) => { + let w = self.int_width(*t)?; + Some(if w >= 64 { *x as u64 } else { (*x as u64) & ((1u64 << w) - 1) }) + } + _ => None, + }, + _ => None, + } + } +} + +impl Module { + /// `getelementptr inbounds` through arrays and structs (struct indices + /// must be constants). + pub fn gep_fields(&mut self, ptr: Value, idx: &[Value]) -> Value { + let pt = self.type_of(ptr); + let (mut t, space) = self.pointee(pt); + for &i in &idx[1..] { + let next = match &self.types[t.0 as usize] { + TypeDef::Array(_, e) => Ok(*e), + TypeDef::Struct(_, f) => self + .const_u64(i) + .and_then(|k| f.get(k as usize).copied()) + .ok_or_else(|| format!("gep: struct field {i:?} of {:?}", self.types[t.0 as usize])), + other => Err(format!("gep into {other:?}")), + }; + match next { + Ok(n) => t = n, + Err(e) => { + self.fail(e); + break; + } + } + } + let rt = self.ptr(t, space); + self.push(Op::Gep(ptr, idx.to_vec()), rt) + } + + /// Allocation size of a type under the DXIL data layout (scalars below + /// 32 bits are 32-bit aligned). + pub fn alloc_size(&self, t: Ty) -> u64 { + self.size_align(t, false).0 + } + /// Allocation size under the native 16-bit data layout (`i8:8`, + /// `i16:16`, `f16:16`) when `native16`, else the 32-bit-aligned one. + pub fn alloc_size_layout(&self, t: Ty, native16: bool) -> u64 { + self.size_align(t, native16).0 + } + fn size_align(&self, t: Ty, native16: bool) -> (u64, u64) { + match &self.types[t.0 as usize] { + TypeDef::Int(w) if *w > 32 => (8, 8), + TypeDef::Int(8) if native16 => (1, 1), + TypeDef::Int(16) | TypeDef::Half if native16 => (2, 2), + TypeDef::Double => (8, 8), + TypeDef::Int(_) | TypeDef::Half | TypeDef::Float | TypeDef::Ptr(..) => (4, 4), + TypeDef::Array(n, e) => { + let (s, a) = self.size_align(*e, native16); + (n * s, a) + } + TypeDef::Struct(_, f) => { + let (mut off, mut al) = (0u64, 1u64); + for &x in f { + let (s, a) = self.size_align(x, native16); + off = off.div_ceil(a) * a + s; + al = al.max(a); + } + (off.div_ceil(al) * al, al) + } + _ => (0, 1), + } + } + /// Total allocation size of the global variables in `addrspace` + /// (3: thread-group shared memory). + pub fn global_bytes(&self, addrspace: u32) -> u64 { + self.global_bytes_layout(addrspace, false) + } + /// [`Module::global_bytes`] under the native 16-bit layout when `native16`. + pub fn global_bytes_layout(&self, addrspace: u32, native16: bool) -> u64 { + self.globals.iter().filter(|g| g.addrspace == addrspace).map(|g| self.alloc_size_layout(g.ty, native16)).sum() + } +} diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs new file mode 100644 index 000000000..74153ff4a --- /dev/null +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -0,0 +1,383 @@ +//! Cheap cleanup of the entry function before it is written: unreachable +//! blocks emptied, trivial phis replaced by their single value, common +//! subexpressions merged (pure instructions along the dominator tree, wave +//! intrinsics within a block), dead instructions removed. +//! +//! The translator emits each guest instruction's per-lane expansion as is +//! (repeated lane-bit / ballot / extract sequences, operands of discarded +//! results); this pass removes the redundancy without changing what any +//! remaining instruction computes. + +use std::collections::HashMap; + +use super::{FnAttrs, Module, Op, Ty, Value}; + +impl Op { + /// Calls `f` on every value operand. + pub(super) fn for_each_operand(&self, mut f: impl FnMut(Value)) { + match self { + Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::Store(a, b, _) | Op::AtomicRmw(_, a, b) => { + f(*a); + f(*b) + } + Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => f(*v), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + f(*a); + f(*b); + f(*c) + } + Op::Call(_, args) => args.iter().copied().for_each(f), + Op::Phi(inc) => inc.iter().for_each(|p| f(p.0)), + Op::Gep(p, idx) => { + f(*p); + idx.iter().copied().for_each(f) + } + Op::Switch(v, _, cases) => { + f(*v); + cases.iter().for_each(|c| f(c.0)) + } + Op::Br(_) | Op::Ret | Op::Unreachable => {} + } + } + + /// Rewrites every value operand through `f`. + fn map_operands(&mut self, mut f: impl FnMut(Value) -> Value) { + match self { + Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::Store(a, b, _) | Op::AtomicRmw(_, a, b) => { + *a = f(*a); + *b = f(*b) + } + Op::Cast(_, v, _) | Op::Extract(v, _) | Op::Load(v, _) | Op::Alloca(_, v, _) | Op::CondBr(v, ..) => *v = f(*v), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + *a = f(*a); + *b = f(*b); + *c = f(*c) + } + Op::Call(_, args) => args.iter_mut().for_each(|a| *a = f(*a)), + Op::Phi(inc) => inc.iter_mut().for_each(|p| p.0 = f(p.0)), + Op::Gep(p, idx) => { + *p = f(*p); + idx.iter_mut().for_each(|v| *v = f(*v)) + } + Op::Switch(v, _, cases) => { + *v = f(*v); + cases.iter_mut().for_each(|c| c.0 = f(c.0)) + } + Op::Br(_) | Op::Ret | Op::Unreachable => {} + } + } +} + +/// How an instruction may be merged with an identical one. +#[derive(PartialEq)] +enum Cse { + No, + /// pure: any dominating copy will do + Dom, + /// a wave intrinsic: same result only under the same active lanes (same block) + Block, +} + +impl Module { + fn wave_call(&self, f: u32) -> bool { + let n = &self.funcs[f as usize].name; + n.starts_with("dx.op.wave") || n.starts_with("dx.op.quad") + } + + fn cse_kind(&self, op: &Op) -> Cse { + match op { + Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Gep(..) => Cse::Dom, + Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => Cse::Dom, + Op::Call(f, _) if self.wave_call(*f) && !self.funcs[*f as usize].name.starts_with("dx.op.waveIsFirstLane") => Cse::Block, + _ => Cse::No, + } + } + + /// Whether an unused instruction can go. 64-bit values stay: helpers already set + /// the Int64Ops / Doubles / DoubleExtensions flags for them. + fn removable(&self, op: &Op, ty: Ty, wide: &[Ty]) -> bool { + if wide.contains(&ty) { + return false; + } + let mut w = false; + op.for_each_operand(|v| w |= wide.contains(&self.value_ty(v))); + if w { + return false; + } + match op { + Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Gep(..) | Op::Phi(_) | Op::Load(..) | Op::Alloca(..) => true, + // only calls whose presence sets no shader flag (the flags are collected while + // building and must match the code: no wave ops, f64 math, typed / raw loads) + Op::Call(f, _) => { + let d = &self.funcs[*f as usize]; + matches!(d.attrs, FnAttrs::ReadNone | FnAttrs::ReadOnly) + && !d.name.ends_with(".f64") + && ["dx.op.unary.", "dx.op.binary.", "dx.op.tertiary.", "dx.op.loadInput.", "dx.op.annotateHandle", "dx.op.createHandleFromBinding", "dx.op.cbufferLoadLegacy."] + .iter() + .any(|p| d.name.starts_with(p)) + } + _ => false, + } + } + + /// Whether every non-phi operand of the reachable instructions is written before its + /// use and has a value (what the writer checks). + fn uses_well_formed(&self, order: &[u32]) -> bool { + let mut at = vec![usize::MAX; self.insts.len()]; + let mut k = 0; + for &b in order { + for &i in &self.blocks[b as usize] { + at[i as usize] = k; + k += 1; + } + } + let mut ok = true; + for &b in order { + for &i in &self.blocks[b as usize] { + let op = &self.insts[i as usize].op; + if matches!(op, Op::Phi(_)) { + continue; + } + op.for_each_operand(|v| { + if let Value::Inst(j) = v { + ok &= at[j as usize] < at[i as usize] && !matches!(self.types[self.insts[j as usize].ty.0 as usize], super::TypeDef::Void); + } + }); + } + } + ok + } + + /// Immediate dominators of the blocks in `order` (reverse postorder), by + /// Cooper, Harvey and Kennedy's iteration ("A Simple, Fast Dominance Algorithm"). + fn idoms(&self, order: &[u32]) -> Vec> { + let n = self.blocks.len(); + let mut rpo = vec![usize::MAX; n]; + for (k, &b) in order.iter().enumerate() { + rpo[b as usize] = k; + } + let mut preds: Vec> = vec![Vec::new(); n]; + for &b in order { + for s in self.successors(b as usize) { + preds[s.0 as usize].push(b as usize); + } + } + let mut idom: Vec> = vec![None; n]; + idom[0] = Some(0); + let mut changed = true; + while changed { + changed = false; + for &b in order.iter().skip(1) { + let b = b as usize; + let mut new: Option = None; + for &p in &preds[b] { + if idom[p].is_none() { + continue; + } + new = Some(match new { + None => p, + Some(mut x) => { + let mut y = p; + while x != y { + while rpo[x] > rpo[y] { + x = idom[x].unwrap(); + } + while rpo[y] > rpo[x] { + y = idom[y].unwrap(); + } + } + x + } + }); + } + if new.is_some() && idom[b] != new { + idom[b] = new; + changed = true; + } + } + } + idom + } + + /// Cleans up the entry function (see the module docs of `opt`). Values + /// keep their identities; replaced ones simply lose their uses. + /// + /// `XCL_DXIL_NO_OPT=phi,cse,dce` (any subset, or `all`) skips passes, for bisecting. + pub fn optimize(&mut self) { + let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); + let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); + let order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + // malformed IR (a use before its definition or of a void result) is left for the + // writer to report, not cleaned away + if !self.uses_well_formed(&order) { + return; + } + // unreachable blocks: emptied (the writer drops them) + let mut reach = vec![false; self.blocks.len()]; + for &b in &order { + reach[b as usize] = true; + } + for (b, r) in reach.iter().enumerate() { + if !r { + self.blocks[b].clear(); + } + } + for &b in &order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + if let Op::Phi(inc) = &mut self.insts[i].op { + inc.retain(|p| reach[p.1 .0 as usize]); + } + } + } + + let mut repl: Vec> = vec![None; self.insts.len()]; + + // trivial phis (all incoming values the phi itself or one value), to a fixed point + while !skip("phi") { + let mut changed = false; + for &b in &order { + for &i in &self.blocks[b as usize] { + let i = i as usize; + if repl[i].is_some() { + continue; + } + let Op::Phi(inc) = &self.insts[i].op else { break }; + let me = Value::Inst(i as u32); + let mut same: Option = None; + let mut trivial = true; + for &(v, _) in inc { + let v = resolve(&mut repl, v); + if v == me || Some(v) == same { + continue; + } + if same.is_some() { + trivial = false; + break; + } + same = Some(v); + } + if let (true, Some(v)) = (trivial, same) { + repl[i] = Some(v); + changed = true; + } + } + } + if !changed { + break; + } + } + + // CSE along the dominator tree (preorder walk with a scoped table) + let idom = self.idoms(&order); + let mut kids: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in order.iter().skip(1) { + if let Some(d) = idom[b as usize] { + kids[d].push(b as usize); + } + } + let mut table: HashMap<(Op, Ty), Value> = HashMap::new(); + // (block, undo log length) frames; undo log holds keys to remove / restore + let mut undo: Vec<((Op, Ty), Option)> = Vec::new(); + enum Step { + Enter(usize), + Leave(usize), + } + let mut stack = if skip("cse") { Vec::new() } else { vec![Step::Enter(0)] }; + while let Some(step) = stack.pop() { + let b = match step { + Step::Leave(mark) => { + while undo.len() > mark { + let (k, old) = undo.pop().unwrap(); + match old { + Some(v) => table.insert(k, v), + None => table.remove(&k), + }; + } + continue; + } + Step::Enter(b) => b, + }; + stack.push(Step::Leave(undo.len())); + let mut local: HashMap<(Op, Ty), Value> = HashMap::new(); + for k in 0..self.blocks[b].len() { + let i = self.blocks[b][k] as usize; + let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); + op.map_operands(|v| resolve(&mut repl, v)); + let kind = self.cse_kind(&op); + if repl[i].is_none() && kind != Cse::No { + let key = (op.clone(), self.insts[i].ty); + let t = if kind == Cse::Dom { &mut table } else { &mut local }; + if let Some(&v) = t.get(&key) { + repl[i] = Some(v); + } else { + let old = t.insert(key.clone(), Value::Inst(i as u32)); + if kind == Cse::Dom { + undo.push((key, old)); + } + } + } + self.insts[i].op = op; + } + for &c in kids[b].iter().rev() { + stack.push(Step::Enter(c)); + } + } + // phis may name values defined later (back edges): resolve once more + for &b in &order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); + } + } + + // dead instructions: live = side effects, terminators and their operands, transitively + let (i64t, f64t) = self.existing_i64_f64(); + let wide: Vec = i64t.into_iter().chain(f64t).collect(); + let mut live = vec![false; self.insts.len()]; + let mut work: Vec = Vec::new(); + for &b in &order { + for &i in &self.blocks[b as usize] { + if repl[i as usize].is_none() && (skip("dce") || !self.removable(&self.insts[i as usize].op, self.insts[i as usize].ty, &wide)) { + live[i as usize] = true; + work.push(i); + } + } + } + while let Some(i) = work.pop() { + self.insts[i as usize].op.for_each_operand(|v| { + if let Value::Inst(j) = v { + if !live[j as usize] { + live[j as usize] = true; + work.push(j); + } + } + }); + } + for b in &mut self.blocks { + b.retain(|&i| live[i as usize]); + } + } +} + +/// The value `v` stands for after replacements (path-compressing the chain). +fn resolve(repl: &mut [Option], v: Value) -> Value { + let mut r = v; + while let Value::Inst(i) = r { + match repl[i as usize] { + Some(n) => r = n, + None => break, + } + } + let mut c = v; + while let Value::Inst(i) = c { + match repl[i as usize] { + Some(n) if n != r => { + repl[i as usize] = Some(r); + c = n; + } + _ => break, + } + } + r +} diff --git a/crates/xcl/src/gpu/dxil/ops.rs b/crates/xcl/src/gpu/dxil/ops.rs new file mode 100644 index 000000000..e0d4e71d6 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/ops.rs @@ -0,0 +1,1083 @@ +//! Typed helpers for the DXIL operation (`dx.op.*`) library on top of +//! [`Shader::op`]: math, memory (group-shared, typed / structured / raw +//! buffers, atomics, barriers), textures and samplers, wave and quad +//! operations, derivatives. +//! +//! Opcode numbers, overload classes, argument layouts and function attributes +//! follow DXC's `docs/DXIL.rst` and DXC 1.9's output for small HLSL programs +//! (NCSA licence); each helper is covered by a validator test below, most by +//! a GPU execution test against a CPU reference. +//! +//! # Exactness +//! +//! None of the helpers add fast-math flags. Per the D3D functional spec and +//! `DXIL.rst`, these DXIL operations are **exact** (bit-exact up to the +//! denorm mode — 32-bit float denormals may be flushed unless the shader +//! runs with preserved denormals): `FAbs`, `Saturate`, `FMax`/`FMin` +//! (IEEE-754-2008 `maxNum`/`minNum`: a NaN operand yields the other operand), +//! `Round_*`, `Frc` (`x - floor(x)`), all integer ops (`IMax`…`Bfi`, +//! `IMul`/`UMul`/`UDiv`, bit counts), `IsNaN`/`IsInf`/`IsFinite`, +//! `MakeDouble`/`SplitDouble`, `Fma` (fused, f64), and double `FMax`/`FMin`. +//! `LegacyF32ToF16`'s rounding is implementation-defined: the RTX 4090 +//! rounds towards zero (others round to nearest even); `LegacyF16ToF32` is +//! exact. +//! +//! **Approximate** (implementation-defined within D3D tolerances): +//! `Cos`/`Sin` (absolute error ≤ 0.0008 on [-100π, 100π]), `Exp`/`Log` +//! (base 2, ≈ 3 ULP / absolute 2⁻²¹ near 1), `Sqrt` (≈ 1 ULP… drivers may +//! be less precise than correctly rounded), `Rsqrt` (≈ 2 ULP), the +//! hyperbolic / inverse trig ops, and float division (2.5 ULP). +//! `FMad` may or may not be fused: do not rely on either rounding. + +use super::module::{BinOp, CastOp, FnAttrs, RmwOp, Ty, Value}; +use super::shader::{kind, Feature, RawUav, ResClass, Shader}; + +// ------------------------------------------------------------------ enums + +/// `dx.op.unary` floating-point operations (overloads f16 / f32; f64 only +/// for those in [`DOUBLE_UNARY`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FUnary { + FAbs = 6, + Saturate = 7, + Cos = 12, + Sin = 13, + Tan = 14, + Acos = 15, + Asin = 16, + Atan = 17, + Hcos = 18, + Hsin = 19, + Htan = 20, + /// 2^x + Exp = 21, + /// `x - floor(x)` + Frc = 22, + /// log2(x) + Log = 23, + Sqrt = 24, + Rsqrt = 25, + /// Round to nearest even. + RoundNe = 26, + /// Round towards -inf (floor). + RoundNi = 27, + /// Round towards +inf (ceil). + RoundPi = 28, + /// Round towards zero (trunc). + RoundZ = 29, +} + +/// `dx.op.isSpecialFloat` tests (result i1). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FClass { + IsNaN = 8, + IsInf = 9, + IsFinite = 10, + IsNormal = 11, +} + +/// Bit-counting operations (`unaryBits`, result i32 for every overload). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BitCount { + /// Population count. + Countbits = 31, + /// Index of the lowest set bit, or -1. + FirstbitLo = 32, + /// Index of the highest set bit **counted from the MSB**, or -1 + /// (HLSL's `firstbithigh` is `31 - this` for non-zero inputs). + FirstbitHi = 33, + /// Like `FirstbitHi` on the first bit differing from the sign bit. + FirstbitSHi = 34, +} + +/// `dx.op.binary` operations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Binary { + FMax = 35, + FMin = 36, + IMax = 37, + IMin = 38, + UMax = 39, + UMin = 40, +} + +/// `dx.op.tertiary` operations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tertiary { + /// a*b+c, fusion unspecified (f16/f32/f64). + FMad = 46, + /// Fused a*b+c (f64 only; needs `DoubleExtensions`). + Fma = 47, + IMad = 48, + UMad = 49, + /// `Ibfe(width, offset, value)` (i32): signed bitfield extract; width and + /// offset use their low 5 bits. + Ibfe = 51, + /// `Ubfe(width, offset, value)` (i32). + Ubfe = 52, +} + +/// Atomic operations of `AtomicBinOp` (op 78). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AtomicOp { + Add = 0, + And = 1, + Or = 2, + Xor = 3, + IMin = 4, + IMax = 5, + UMin = 6, + UMax = 7, + Exchange = 8, +} + +/// `Barrier` mode flags (op 80), combined with `|`. +pub mod barrier { + /// Execution barrier: wait for every thread of the group. + pub const SYNC_THREAD_GROUP: u32 = 1; + /// Device-memory (global UAV) fence. + pub const UAV_FENCE_GLOBAL: u32 = 2; + /// Group-scoped UAV fence. + pub const UAV_FENCE_THREAD_GROUP: u32 = 4; + /// Group-shared memory fence. + pub const TGSM_FENCE: u32 = 8; + /// `GroupMemoryBarrierWithGroupSync()` + pub const GROUP_SYNC: u32 = SYNC_THREAD_GROUP | TGSM_FENCE; + /// `AllMemoryBarrierWithGroupSync()` + pub const ALL_SYNC: u32 = SYNC_THREAD_GROUP | TGSM_FENCE | UAV_FENCE_GLOBAL; +} + +/// `DXIL::ComponentType` of typed resource elements. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CompType { + I32 = 4, + U32 = 5, + I64 = 6, + U64 = 7, + F16 = 8, + F32 = 9, + F64 = 10, + SNormF32 = 13, + UNormF32 = 14, +} + +impl CompType { + fn is_float(self) -> bool { + matches!(self, CompType::F16 | CompType::F32 | CompType::F64 | CompType::SNormF32 | CompType::UNormF32) + } +} + +/// Texture shapes (`DXIL::ResourceKind`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TexKind { + D1 = 1, + D2 = 2, + D3 = 4, + Cube = 5, + D1Array = 6, + D2Array = 7, + CubeArray = 9, +} + +impl TexKind { + /// Coordinates used to address a texel / sample (array slice included). + pub fn coords(self) -> usize { + match self { + TexKind::D1 => 1, + TexKind::D2 | TexKind::D1Array => 2, + TexKind::D3 | TexKind::D2Array | TexKind::Cube => 3, + TexKind::CubeArray => 4, + } + } + /// Texel-offset components (none for cubes). + pub fn offsets(self) -> usize { + match self { + TexKind::D1 | TexKind::D1Array => 1, + TexKind::D2 | TexKind::D2Array => 2, + TexKind::D3 => 3, + TexKind::Cube | TexKind::CubeArray => 0, + } + } + /// Gradient components for `SampleGrad` (spatial dimensions). + pub fn grads(self) -> usize { + match self { + TexKind::D1 | TexKind::D1Array => 1, + TexKind::D2 | TexKind::D2Array => 2, + TexKind::D3 | TexKind::Cube | TexKind::CubeArray => 3, + } + } +} + +/// A texture handle (heap SRV or UAV) with its element type. +#[derive(Debug, Clone, Copy)] +pub struct Texture { + pub handle: Value, + pub kind: TexKind, + pub uav: bool, + pub comp: CompType, +} + +/// A sampler handle. +#[derive(Debug, Clone, Copy)] +pub struct Sampler { + pub handle: Value, + pub comparison: bool, +} + +/// A constant buffer handle. +#[derive(Debug, Clone, Copy)] +pub struct Cbv { + pub handle: Value, +} + +/// A typed buffer (`Buffer` / `RWBuffer`). +#[derive(Debug, Clone, Copy)] +pub struct TypedBuffer { + pub handle: Value, + pub comp: CompType, + binding: Option, +} + +/// Wave reduction / prefix operations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WaveOp { + Sum = 0, + Product = 1, + Min = 2, + Max = 3, +} + +/// Wave bitwise reductions. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WaveBit { + And = 0, + Or = 1, + Xor = 2, +} + +/// `QuadOp` directions. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QuadDir { + ReadAcrossX = 0, + ReadAcrossY = 1, + ReadAcrossDiagonal = 2, +} + +/// Derivative operations (`dx.op.unary`, f16/f32). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Deriv { + CoarseX = 83, + CoarseY = 84, + FineX = 85, + FineY = 86, +} + +/// Typed-buffer / texture resource properties word 1: component type and +/// count (`comp | ncomp << 8`). +fn typed_props(comp: CompType, ncomp: u32) -> u32 { + comp as u32 | (ncomp << 8) +} + +// ------------------------------------------------------------------- math + +impl Shader { + fn is_i64(&mut self, v: Value) -> bool { + let t = self.m.type_of(v); + t == self.m.i64() + } + fn is_f64(&mut self, v: Value) -> bool { + let t = self.m.type_of(v); + t == self.m.f64() + } + + /// A float unary op on `v` (f16 / f32; f64 only where DXIL allows). + pub fn funary(&mut self, op: FUnary, v: Value) -> Value { + let t = self.m.type_of(v); + if self.is_f64(v) { + self.require(Feature::Doubles); + } + self.op(op as u32, "unary", Some(t), t, &[v], FnAttrs::ReadNone) + } + + /// `IsNaN` / `IsInf` / `IsFinite` / `IsNormal` → i1 (f32; the f16 + /// overload needs SM 6.9). + pub fn fclass(&mut self, op: FClass, v: Value) -> Value { + let t = self.m.type_of(v); + let i1 = self.m.i1(); + self.op(op as u32, "isSpecialFloat", Some(t), i1, &[v], FnAttrs::ReadNone) + } + + /// `Bfrev` (bit reverse; i16 / i32 / i64). + pub fn bfrev(&mut self, v: Value) -> Value { + let t = self.m.type_of(v); + if self.is_i64(v) { + // AMD's driver (amdxc64, RDNA3/4) gets `Bfrev.i64` wrong (it + // writes the reversed low half into both halves), so reverse + // each 32-bit half and swap them. + self.require(Feature::Int64Ops); + let i32 = self.m.i32(); + let lo = self.m.cast(CastOp::Trunc, v, i32); + let c32 = self.m.const_int(t, 32); + let hi = self.m.bin(BinOp::LShr, v, c32); + let hi = self.m.cast(CastOp::Trunc, hi, i32); + let rlo = self.op(30, "unary", Some(i32), i32, &[lo], FnAttrs::ReadNone); + let rhi = self.op(30, "unary", Some(i32), i32, &[hi], FnAttrs::ReadNone); + let rlo = self.m.cast(CastOp::ZExt, rlo, t); + let rlo = self.m.bin(BinOp::Shl, rlo, c32); + let rhi = self.m.cast(CastOp::ZExt, rhi, t); + return self.m.bin(BinOp::Or, rlo, rhi); + } + self.op(30, "unary", Some(t), t, &[v], FnAttrs::ReadNone) + } + + /// Bit counts (i16 / i32 / i64 input) → i32. + pub fn bit_count(&mut self, op: BitCount, v: Value) -> Value { + let t = self.m.type_of(v); + let i32 = self.m.i32(); + if self.is_i64(v) { + self.require(Feature::Int64Ops); + if matches!(op, BitCount::Countbits) { + // Count each 32-bit half: AMD's driver (amdxc64, RDNA4) gets + // i64 bit ops wrong (see `bfrev`); fuzz seed 1599 reads a wrong + // value downstream of `Countbits.i64(i64 2)` there only. + let lo = self.m.cast(CastOp::Trunc, v, i32); + let c32 = self.m.const_int(t, 32); + let hi = self.m.bin(BinOp::LShr, v, c32); + let hi = self.m.cast(CastOp::Trunc, hi, i32); + let a = self.op(op as u32, "unaryBits", Some(i32), i32, &[lo], FnAttrs::ReadNone); + let b = self.op(op as u32, "unaryBits", Some(i32), i32, &[hi], FnAttrs::ReadNone); + return self.m.bin(BinOp::Add, a, b); + } + } + self.op(op as u32, "unaryBits", Some(t), i32, &[v], FnAttrs::ReadNone) + } + + /// `FMax`…`UMin` on two values of the same type. + pub fn binary(&mut self, op: Binary, a: Value, b: Value) -> Value { + let t = self.m.type_of(a); + if self.is_f64(a) { + self.require(Feature::Doubles); + } + if self.is_i64(a) { + self.require(Feature::Int64Ops); + } + self.op(op as u32, "binary", Some(t), t, &[a, b], FnAttrs::ReadNone) + } + + /// `FMad`, `Fma`, `IMad`, `UMad`, `Ibfe`, `Ubfe`. + pub fn tertiary(&mut self, op: Tertiary, a: Value, b: Value, c: Value) -> Value { + let t = self.m.type_of(a); + if self.is_f64(a) { + self.require(Feature::Doubles); + } + if op == Tertiary::Fma { + self.require(Feature::DoubleExtensions); + } + if self.is_i64(a) { + self.require(Feature::Int64Ops); + } + self.op(op as u32, "tertiary", Some(t), t, &[a, b, c], FnAttrs::ReadNone) + } + + /// `Bfi(width, offset, value, replaced)` (i32): inserts the low `width` + /// bits of `value` into `replaced` at `offset`. + pub fn bfi(&mut self, width: Value, offset: Value, value: Value, replaced: Value) -> Value { + let t = self.m.type_of(value); + self.op(53, "quaternary", Some(t), t, &[width, offset, value, replaced], FnAttrs::ReadNone) + } + + fn two_outs(&mut self, op: u32, a: Value, b: Value) -> (Value, Value) { + let i32 = self.m.i32(); + let st = self.m.named_struct("dx.types.twoi32", &[i32, i32]); + let r = self.op(op, "binaryWithTwoOuts", Some(i32), st, &[a, b], FnAttrs::ReadNone); + (self.m.extract(r, 0), self.m.extract(r, 1)) + } + /// Full 64-bit product of two signed i32 → `(hi, lo)`. + pub fn imul_wide(&mut self, a: Value, b: Value) -> (Value, Value) { + self.two_outs(41, a, b) + } + /// Full 64-bit product of two unsigned i32 → `(hi, lo)`. + pub fn umul_wide(&mut self, a: Value, b: Value) -> (Value, Value) { + self.two_outs(42, a, b) + } + /// Unsigned divide → `(quotient, remainder)` (division by zero gives all ones). + pub fn udiv_rem(&mut self, a: Value, b: Value) -> (Value, Value) { + self.two_outs(43, a, b) + } + fn carry(&mut self, op: u32, a: Value, b: Value) -> (Value, Value) { + let i32 = self.m.i32(); + let i1 = self.m.i1(); + let st = self.m.named_struct("dx.types.i32c", &[i32, i1]); + let r = self.op(op, "binaryWithCarryOrBorrow", Some(i32), st, &[a, b], FnAttrs::ReadNone); + (self.m.extract(r, 0), self.m.extract(r, 1)) + } + /// `UAddc`: `(a + b, carry)`. + pub fn uaddc(&mut self, a: Value, b: Value) -> (Value, Value) { + self.carry(44, a, b) + } + /// `USubb`: `(a - b, borrow)`. + pub fn usubb(&mut self, a: Value, b: Value) -> (Value, Value) { + self.carry(45, a, b) + } + + /// `MakeDouble(lo, hi)`. + pub fn make_double(&mut self, lo: Value, hi: Value) -> Value { + self.require(Feature::Doubles); + let f64 = self.m.f64(); + self.op(101, "makeDouble", Some(f64), f64, &[lo, hi], FnAttrs::ReadNone) + } + /// `SplitDouble(d)` → `(lo, hi)`. + pub fn split_double(&mut self, d: Value) -> (Value, Value) { + self.require(Feature::Doubles); + let (f64, i32) = (self.m.f64(), self.m.i32()); + let st = self.m.named_struct("dx.types.splitdouble", &[i32, i32]); + let r = self.op(102, "splitDouble", Some(f64), st, &[d], FnAttrs::ReadNone); + (self.m.extract(r, 0), self.m.extract(r, 1)) + } + /// `f32tof16`: half bits in the low 16 bits of an i32. + pub fn f32_to_f16(&mut self, f: Value) -> Value { + let i32 = self.m.i32(); + self.op(130, "legacyF32ToF16", None, i32, &[f], FnAttrs::ReadNone) + } + /// `f16tof32` of the low 16 bits of an i32. + pub fn f16_to_f32(&mut self, h: Value) -> Value { + let f32 = self.m.f32(); + self.op(131, "legacyF16ToF32", None, f32, &[h], FnAttrs::ReadNone) + } +} + +// ----------------------------------------------------------------- memory + +/// A group-shared array (`groupshared T name[n]`, address space 3). +#[derive(Debug, Clone, Copy)] +pub struct GroupShared { + pub global: Value, + pub elem: Ty, +} + +impl Shader { + /// Declares `groupshared name[n]`. + pub fn groupshared(&mut self, name: &str, elem: Ty, n: u64) -> GroupShared { + let arr = self.m.array(n, elem); + let align = if elem == self.m.i64() || elem == self.m.f64() { 8 } else { 4 }; + let global = self.m.global(name, arr, 3, None, false, align); + GroupShared { global, elem } + } + /// Pointer to element `idx` (i32). + pub fn gs_ptr(&mut self, g: GroupShared, idx: Value) -> Value { + let zero = self.m.i32c(0); + self.m.gep(g.global, &[zero, idx]) + } + fn elem_align(&mut self, t: Ty) -> u32 { + if t == self.m.i64() || t == self.m.f64() { + 8 + } else { + 4 + } + } + pub fn gs_load(&mut self, g: GroupShared, idx: Value) -> Value { + let p = self.gs_ptr(g, idx); + let a = self.elem_align(g.elem); + self.m.load(p, a) + } + pub fn gs_store(&mut self, g: GroupShared, idx: Value, v: Value) { + let p = self.gs_ptr(g, idx); + let a = self.elem_align(g.elem); + self.m.store(p, v, a); + } + /// `atomicrmw` on a group-shared element; returns the old value. + pub fn gs_atomic(&mut self, op: RmwOp, g: GroupShared, idx: Value, v: Value) -> Value { + if self.is_i64(v) { + self.require(Feature::Int64Ops); + self.require(Feature::AtomicInt64GroupShared); + } + let p = self.gs_ptr(g, idx); + self.m.atomic_rmw(op, p, v) + } + /// `cmpxchg` on a group-shared element; returns the old value. + pub fn gs_cmpxchg(&mut self, g: GroupShared, idx: Value, cmp: Value, new: Value) -> Value { + if self.is_i64(cmp) { + self.require(Feature::Int64Ops); + self.require(Feature::AtomicInt64GroupShared); + } + let p = self.gs_ptr(g, idx); + self.m.cmpxchg(p, cmp, new) + } + + /// `Barrier(mode)` — see [`barrier`] for the flags. + pub fn barrier(&mut self, mode: u32) { + let void = self.m.void(); + let mk = self.m.i32c(mode); + self.op(80, "barrier", None, void, &[mk], FnAttrs::NoDuplicate); + } + + // ---- typed and structured buffers + + /// Declares `RWBuffer` at `u, space`. + pub fn typed_uav(&mut self, lower: u32, space: u32, comp: CompType) -> TypedBuffer { + let id = self.bindings.len(); + self.bindings.push(super::shader::Binding { comp_type: comp as u32, ..super::shader::Binding::new(ResClass::Uav, space, lower, kind::TYPED_BUFFER) }); + let h = self.handle_from_binding(ResClass::Uav, lower, lower, space, lower); + let handle = self.annotate(h, kind::TYPED_BUFFER | 0x1000, typed_props(comp, 1)); + TypedBuffer { handle, comp, binding: Some(id) } + } + /// `Buffer` / `RWBuffer` from the descriptor heap. + pub fn heap_typed_buffer(&mut self, index: Value, uav: bool, comp: CompType, nonuniform: bool) -> TypedBuffer { + let h = self.handle_from_heap(index, false, nonuniform); + let handle = self.annotate(h, kind::TYPED_BUFFER | if uav { 0x1000 } else { 0 }, typed_props(comp, 1)); + TypedBuffer { handle, comp, binding: None } + } + fn comp_ty(&mut self, c: CompType) -> Ty { + match c { + CompType::F16 => self.m.f16(), + CompType::F64 => self.m.f64(), + c if c.is_float() => self.m.f32(), + CompType::I64 | CompType::U64 => self.m.i64(), + _ => self.m.i32(), + } + } + /// `BufferLoad` (op 68) of element `index` → four components. + pub fn buffer_load(&mut self, buf: TypedBuffer, index: Value) -> [Value; 4] { + let t = self.comp_ty(buf.comp); + let rt = self.res_ret(t); + let i32 = self.m.i32(); + let undef = self.m.undef(i32); + let r = self.op(68, "bufferLoad", Some(t), rt, &[buf.handle, index, undef], FnAttrs::ReadOnly); + [0, 1, 2, 3].map(|c| self.m.extract(r, c)) + } + /// `BufferStore` (op 69) of up to four components (DXIL requires the + /// full mask the format has; pass all components of the element). + pub fn buffer_store(&mut self, buf: TypedBuffer, index: Value, vals: &[Value]) { + assert!((1..=4).contains(&vals.len())); + let t = self.m.type_of(vals[0]); + let void = self.m.void(); + let i32 = self.m.i32(); + let undef = self.m.undef(i32); + let mut v = [vals[0]; 4]; + v[..vals.len()].copy_from_slice(vals); + let mk = self.m.i8c(0xf); + self.op(69, "bufferStore", Some(t), void, &[buf.handle, index, undef, v[0], v[1], v[2], v[3], mk], FnAttrs::NoUnwind); + } + + /// Declares `Buffer` at `t, space`. + pub fn srv_typed(&mut self, lower: u32, space: u32, comp: CompType, ncomp: u32) -> TypedBuffer { + let id = self.bindings.len(); + self.bindings.push(super::shader::Binding { comp_type: comp as u32, ..super::shader::Binding::new(ResClass::Srv, space, lower, kind::TYPED_BUFFER) }); + let h = self.handle_from_binding(ResClass::Srv, lower, lower, space, lower); + let handle = self.annotate(h, kind::TYPED_BUFFER, typed_props(comp, ncomp)); + TypedBuffer { handle, comp, binding: Some(id) } + } + /// Declares `ByteAddressBuffer` at `t, space`. + pub fn srv_raw(&mut self, lower: u32, space: u32) -> RawUav { + self.require(Feature::RawAndStructuredBuffers); + let id = self.bindings.len(); + self.bindings.push(super::shader::Binding::new(ResClass::Srv, space, lower, kind::RAW_BUFFER)); + let h = self.handle_from_binding(ResClass::Srv, lower, lower, space, lower); + let handle = self.annotate(h, kind::RAW_BUFFER, 0); + RawUav { handle, binding: Some(id) } + } + /// Declares `StructuredBuffer` with `stride` bytes at `t, space`. + pub fn srv_structured(&mut self, lower: u32, space: u32, stride: u32) -> RawUav { + self.require(Feature::RawAndStructuredBuffers); + let id = self.bindings.len(); + self.bindings.push(super::shader::Binding { stride, ..super::shader::Binding::new(ResClass::Srv, space, lower, kind::STRUCTURED_BUFFER) }); + let h = self.handle_from_binding(ResClass::Srv, lower, lower, space, lower); + let handle = self.annotate(h, kind::STRUCTURED_BUFFER, stride); + RawUav { handle, binding: Some(id) } + } + /// Declares a texture SRV (`Texture2D` = `(D2, F32, 4)`) at `t, space`. + pub fn srv_texture(&mut self, lower: u32, space: u32, kind: TexKind, comp: CompType, ncomp: u32) -> Texture { + self.bindings.push(super::shader::Binding { comp_type: comp as u32, ..super::shader::Binding::new(ResClass::Srv, space, lower, kind as u32) }); + let h = self.handle_from_binding(ResClass::Srv, lower, lower, space, lower); + let handle = self.annotate(h, kind as u32, typed_props(comp, ncomp)); + Texture { handle, kind, uav: false, comp } + } + /// Declares a cbuffer of `size` bytes at `b, space` (a + /// root-constant block is the same: a small cbuffer). + pub fn cbv(&mut self, lower: u32, space: u32, size: u32) -> Cbv { + self.bindings.push(super::shader::Binding { size, ..super::shader::Binding::new(ResClass::Cbv, space, lower, kind::CBUFFER) }); + let h = self.handle_from_binding(ResClass::Cbv, lower, lower, space, lower); + let handle = self.annotate(h, kind::CBUFFER, size); + Cbv { handle } + } + /// A cbuffer from `ResourceDescriptorHeap[index]` of `size` bytes. + pub fn heap_cbv(&mut self, index: Value, size: u32, nonuniform: bool) -> Cbv { + let h = self.handle_from_heap(index, false, nonuniform); + let handle = self.annotate(h, kind::CBUFFER, size); + Cbv { handle } + } + /// `CBufferLoadLegacy` (op 59): the 16-byte row `row` as four `ty` + /// values (i32/f32; i64/f64 rows have two components, i16/f16 eight — + /// only the 32-bit forms are exposed here). + pub fn cbuffer_load_legacy(&mut self, cb: Cbv, row: Value, ty: Ty) -> [Value; 4] { + let name = format!("dx.types.CBufRet.{}", self.type_suffix(ty)); + let rt = self.m.named_struct(&name, &[ty, ty, ty, ty]); + let r = self.op(59, "cbufferLoadLegacy", Some(ty), rt, &[cb.handle, row], FnAttrs::ReadOnly); + [0, 1, 2, 3].map(|c| self.m.extract(r, c)) + } + /// Declares a sampler (`SamplerComparisonState` if `comparison`) at `s, space`. + pub fn sampler(&mut self, lower: u32, space: u32, comparison: bool) -> Sampler { + self.bindings.push(super::shader::Binding { comparison, ..super::shader::Binding::new(ResClass::Sampler, space, lower, kind::SAMPLER) }); + let h = self.handle_from_binding(ResClass::Sampler, lower, lower, space, lower); + let handle = self.annotate(h, kind::SAMPLER | if comparison { 0x8000 } else { 0 }, 0); + Sampler { handle, comparison } + } + + /// Declares `RWStructuredBuffer` with `stride` bytes at `u, space`. + pub fn structured_uav(&mut self, lower: u32, space: u32, stride: u32) -> RawUav { + self.require(Feature::RawAndStructuredBuffers); + let id = self.bindings.len(); + self.bindings.push(super::shader::Binding { stride, ..super::shader::Binding::new(ResClass::Uav, space, lower, kind::STRUCTURED_BUFFER) }); + let h = self.handle_from_binding(ResClass::Uav, lower, lower, space, lower); + let handle = self.annotate(h, kind::STRUCTURED_BUFFER | 0x1000, stride); + RawUav { handle, binding: Some(id) } + } + /// A structured buffer from the heap. + pub fn heap_structured_buffer(&mut self, index: Value, uav: bool, stride: u32, nonuniform: bool) -> RawUav { + self.require(Feature::RawAndStructuredBuffers); + let h = self.handle_from_heap(index, false, nonuniform); + let handle = self.annotate(h, kind::STRUCTURED_BUFFER | if uav { 0x1000 } else { 0 }, stride); + RawUav { handle, binding: None } + } + /// Structured load of `mask` consecutive i32s of element `index` at byte `offset`. + pub fn structured_load(&mut self, buf: RawUav, index: Value, offset: u32, mask: u8) -> Vec { + let i32 = self.m.i32(); + let rt = self.res_ret(i32); + let (off, mk, al) = (self.m.i32c(offset), self.m.i8c(mask), self.m.i32c(4)); + let r = self.op(139, "rawBufferLoad", Some(i32), rt, &[buf.handle, index, off, mk, al], FnAttrs::ReadOnly); + (0..4).filter(|c| mask & (1 << c) != 0).map(|c| self.m.extract(r, c)).collect() + } + /// Structured store of up to four i32s to element `index` at byte `offset`. + pub fn structured_store(&mut self, buf: RawUav, index: Value, offset: u32, vals: &[Value]) { + assert!((1..=4).contains(&vals.len())); + let (i32, void) = (self.m.i32(), self.m.void()); + let undef = self.m.undef(i32); + let mut v = [undef; 4]; + v[..vals.len()].copy_from_slice(vals); + let mask = (1u8 << vals.len()) - 1; + let (off, mk, al) = (self.m.i32c(offset), self.m.i8c(mask), self.m.i32c(4)); + self.op(140, "rawBufferStore", Some(i32), void, &[buf.handle, index, off, v[0], v[1], v[2], v[3], mk, al], FnAttrs::NoUnwind); + } + + // ---- resource atomics + + /// 64-bit resource atomics: `Int64Ops`; typed resources also need + /// `AtomicInt64Typed`, heap resources `AtomicInt64Heap`, and static + /// bindings carry the metadata tag (as DXC sets them). + fn note_atomic64(&mut self, v: Value, binding: Option, typed: bool) { + if self.is_i64(v) { + self.require(Feature::Int64Ops); + if typed { + self.require(Feature::AtomicInt64Typed); + } + match binding { + Some(b) => self.bindings[b].atomic64 = true, + None => self.require(Feature::AtomicInt64Heap), + } + } + } + /// Declares the features of a 64-bit atomic on a heap texture/typed + /// buffer handle used with [`Shader::atomic_binop`] / [`Shader::atomic_cmpxchg`]. + pub fn heap_typed_atomic64(&mut self) { + self.require(Feature::Int64Ops); + self.require(Feature::AtomicInt64Typed); + self.require(Feature::AtomicInt64Heap); + } + fn atomic_coords(&mut self, c: &[Value]) -> [Value; 3] { + assert!((1..=3).contains(&c.len())); + let i32 = self.m.i32(); + let u = self.m.undef(i32); + let mut out = [u; 3]; + out[..c.len()].copy_from_slice(c); + out + } + /// `AtomicBinOp` (op 78) on a raw buffer at byte `offset` (i32 or i64 value); + /// returns the old value. + pub fn raw_atomic(&mut self, buf: RawUav, op: AtomicOp, offset: Value, v: Value) -> Value { + self.note_atomic64(v, buf.binding, false); + self.atomic_binop(buf.handle, op, &[offset], v) + } + /// `AtomicBinOp` on a structured buffer element `index` at byte `offset`. + pub fn structured_atomic(&mut self, buf: RawUav, op: AtomicOp, index: Value, offset: u32, v: Value) -> Value { + self.note_atomic64(v, buf.binding, false); + let off = self.m.i32c(offset); + self.atomic_binop(buf.handle, op, &[index, off], v) + } + /// `AtomicBinOp` on a typed buffer element. + pub fn typed_atomic(&mut self, buf: TypedBuffer, op: AtomicOp, index: Value, v: Value) -> Value { + self.note_atomic64(v, buf.binding, true); + self.atomic_binop(buf.handle, op, &[index], v) + } + /// Raw `AtomicBinOp` with up to three coordinates (typed UAV textures: + /// texel coordinates). Callers handle 64-bit feature flags. + pub fn atomic_binop(&mut self, handle: Value, op: AtomicOp, coords: &[Value], v: Value) -> Value { + let t = self.m.type_of(v); + let c = self.atomic_coords(coords); + let o = self.m.i32c(op as u32); + self.op(78, "atomicBinOp", Some(t), t, &[handle, o, c[0], c[1], c[2], v], FnAttrs::NoUnwind) + } + /// `AtomicCompareExchange` (op 79) on a raw buffer; returns the old value. + pub fn raw_cmpxchg(&mut self, buf: RawUav, offset: Value, cmp: Value, new: Value) -> Value { + self.note_atomic64(cmp, buf.binding, false); + self.atomic_cmpxchg(buf.handle, &[offset], cmp, new) + } + /// `AtomicCompareExchange` with up to three coordinates. + pub fn atomic_cmpxchg(&mut self, handle: Value, coords: &[Value], cmp: Value, new: Value) -> Value { + let t = self.m.type_of(cmp); + let c = self.atomic_coords(coords); + self.op(79, "atomicCompareExchange", Some(t), t, &[handle, c[0], c[1], c[2], cmp, new], FnAttrs::NoUnwind) + } +} + +// --------------------------------------------------------------- textures + +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 { + 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 } + } + /// A sampler from `SamplerDescriptorHeap[index]`. + pub fn heap_sampler(&mut self, index: Value, comparison: bool, nonuniform: bool) -> Sampler { + let h = self.handle_from_heap(index, true, nonuniform); + let handle = self.annotate(h, 14 | if comparison { 0x8000 } else { 0 }, 0); + Sampler { handle, comparison } + } + + fn tex_ty(&mut self, t: Texture) -> Ty { + self.comp_ty(t.comp) + } + fn ret4(&mut self, r: Value) -> [Value; 4] { + [0, 1, 2, 3].map(|c| self.m.extract(r, c)) + } + fn padded(&mut self, vals: &[Value], n: usize, ty: Ty) -> Vec { + assert!(vals.len() <= n, "too many coordinates"); + let u = self.m.undef(ty); + let mut v = vals.to_vec(); + v.resize(n, u); + v + } + /// Offsets: given ones as constants, missing ones 0 for the kind's + /// dimensions (as DXC emits) and undef past them. + fn offsets(&mut self, kind: TexKind, offs: &[i32], n: usize) -> Vec { + let i32 = self.m.i32(); + let u = self.m.undef(i32); + (0..n) + .map(|i| if i < kind.offsets() { self.m.i32c(offs.get(i).copied().unwrap_or(0) as u32) } else { u }) + .collect() + } + fn coords_f(&mut self, coords: &[Value]) -> Vec { + let f32 = self.m.f32(); + self.padded(coords, 4, f32) + } + + /// `TextureLoad` (op 66): integer texel coordinates (array slice + /// included), `mip` for SRVs (`None` on UAVs), immediate offsets. + pub fn texture_load(&mut self, tex: Texture, mip: Option, coords: &[Value], offs: &[i32]) -> [Value; 4] { + let t = self.tex_ty(tex); + let rt = self.res_ret(t); + let i32 = self.m.i32(); + let mip = mip.unwrap_or_else(|| self.m.undef(i32)); + let c = self.padded(coords, 3, i32); + let o = if offs.is_empty() { self.padded(&[], 3, i32) } else { self.offsets(tex.kind, offs, 3) }; + if tex.uav && tex.comp != CompType::U32 && tex.comp != CompType::I32 && tex.comp != CompType::F32 { + self.require(Feature::TypedUavLoadAdditionalFormats); + } + let mut args = vec![tex.handle, mip]; + args.extend(c); + args.extend(o); + let r = self.op(66, "textureLoad", Some(t), rt, &args, FnAttrs::ReadOnly); + self.ret4(r) + } + /// `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) { + self.require(Feature::TypedUavLoadAdditionalFormats); + } + /// `TextureStore` (op 67) of four components (the full mask) to a UAV texture. + pub fn texture_store(&mut self, tex: Texture, coords: &[Value], vals: [Value; 4]) { + let i32 = self.m.i32(); + let void = self.m.void(); + let t = self.m.type_of(vals[0]); + let c = self.padded(coords, 3, i32); + let mk = self.m.i8c(0xf); + let mut args = vec![tex.handle]; + args.extend(c); + args.extend(vals); + args.push(mk); + let t = if t == self.m.f64() { panic!("no f64 texture stores") } else { t }; + self.op(67, "textureStore", Some(t), void, &args, FnAttrs::NoUnwind); + } + + fn sample_common(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32]) -> Vec { + let mut args = vec![tex.handle, s.handle]; + let c = self.coords_f(coords); + args.extend(c); + let o = self.offsets(tex.kind, offs, 3); + args.extend(o); + args + } + fn clamp_arg(&mut self, clamp: Option) -> Value { + match clamp { + Some(c) => { + self.require(Feature::TiledResources); + c + } + None => { + let f32 = self.m.f32(); + self.m.undef(f32) + } + } + } + /// `Sample` (op 60; implicit derivatives: pixel shaders, or compute with + /// quad-shaped thread groups in SM 6.6). `clamp` = min LOD. + pub fn sample(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32], clamp: Option) -> [Value; 4] { + let t = self.tex_ty(tex); + let rt = self.res_ret(t); + let mut args = self.sample_common(tex, s, coords, offs); + let c = self.clamp_arg(clamp); + args.push(c); + let r = self.op(60, "sample", Some(t), rt, &args, FnAttrs::ReadOnly); + self.ret4(r) + } + /// `SampleBias` (op 61). + pub fn sample_bias(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32], bias: Value, clamp: Option) -> [Value; 4] { + let t = self.tex_ty(tex); + let rt = self.res_ret(t); + let mut args = self.sample_common(tex, s, coords, offs); + let c = self.clamp_arg(clamp); + args.extend([bias, c]); + let r = self.op(61, "sampleBias", Some(t), rt, &args, FnAttrs::ReadOnly); + self.ret4(r) + } + /// `SampleLevel` (op 62): explicit LOD, legal in every stage. + pub fn sample_level(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32], lod: Value) -> [Value; 4] { + let t = self.tex_ty(tex); + let rt = self.res_ret(t); + let mut args = self.sample_common(tex, s, coords, offs); + args.push(lod); + let r = self.op(62, "sampleLevel", Some(t), rt, &args, FnAttrs::ReadOnly); + self.ret4(r) + } + /// `SampleGrad` (op 63) with explicit gradients (`kind.grads()` each). + pub fn sample_grad(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32], ddx: &[Value], ddy: &[Value], clamp: Option) -> [Value; 4] { + let t = self.tex_ty(tex); + let rt = self.res_ret(t); + let f32 = self.m.f32(); + let mut args = self.sample_common(tex, s, coords, offs); + let dx = self.padded(ddx, 3, f32); + let dy = self.padded(ddy, 3, f32); + args.extend(dx); + args.extend(dy); + let c = self.clamp_arg(clamp); + args.push(c); + let r = self.op(63, "sampleGrad", Some(t), rt, &args, FnAttrs::ReadOnly); + self.ret4(r) + } + /// `SampleCmp` (op 64; implicit derivatives like `Sample`). + pub fn sample_cmp(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32], cmp: Value, clamp: Option) -> [Value; 4] { + let t = self.tex_ty(tex); + let rt = self.res_ret(t); + let mut args = self.sample_common(tex, s, coords, offs); + let c = self.clamp_arg(clamp); + args.extend([cmp, c]); + let r = self.op(64, "sampleCmp", Some(t), rt, &args, FnAttrs::ReadOnly); + self.ret4(r) + } + /// `SampleCmpLevelZero` (op 65). + pub fn sample_cmp_level_zero(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32], cmp: Value) -> [Value; 4] { + let t = self.tex_ty(tex); + let rt = self.res_ret(t); + let mut args = self.sample_common(tex, s, coords, offs); + args.push(cmp); + let r = self.op(65, "sampleCmpLevelZero", Some(t), rt, &args, FnAttrs::ReadOnly); + self.ret4(r) + } + fn gather_args(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32], channel: u32) -> Vec { + let mut args = vec![tex.handle, s.handle]; + let c = self.coords_f(coords); + args.extend(c); + let o = self.offsets(tex.kind, offs, 2); + args.extend(o); + let ch = self.m.i32c(channel); + args.push(ch); + args + } + /// `TextureGather` (op 73) of `channel` (0 = red … 3 = alpha); the result + /// holds the texels in D3D order (-u+v, +u+v, +u-v, -u-v). + pub fn gather(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32], channel: u32) -> [Value; 4] { + let t = self.tex_ty(tex); + let rt = self.res_ret(t); + let args = self.gather_args(tex, s, coords, offs, channel); + let r = self.op(73, "textureGather", Some(t), rt, &args, FnAttrs::ReadOnly); + self.ret4(r) + } + /// `TextureGatherCmp` (op 74). + pub fn gather_cmp(&mut self, tex: Texture, s: Sampler, coords: &[Value], offs: &[i32], channel: u32, cmp: Value) -> [Value; 4] { + let t = self.tex_ty(tex); + let rt = self.res_ret(t); + let mut args = self.gather_args(tex, s, coords, offs, channel); + args.push(cmp); + let r = self.op(74, "textureGatherCmp", Some(t), rt, &args, FnAttrs::ReadOnly); + self.ret4(r) + } + /// `GetDimensions` (op 72): a `dx.types.Dimensions` struct of i32 + /// `{width, height, depth / array size, mip levels}`; extract only the + /// 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. + 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]); + let mip = mip.unwrap_or_else(|| self.m.undef(i32)); + self.op(72, "getDimensions", None, st, &[handle, mip], FnAttrs::ReadOnly) + } + /// `CalculateLOD` (op 81): clamped or unclamped LOD for `coords` (spatial only). + pub fn calculate_lod(&mut self, tex: Texture, s: Sampler, coords: &[Value], clamped: bool) -> Value { + let f32 = self.m.f32(); + let c = self.padded(coords, 3, f32); + let cl = self.m.i1c(clamped); + self.op(81, "calculateLOD", Some(f32), f32, &[tex.handle, s.handle, c[0], c[1], c[2], cl], FnAttrs::ReadOnly) + } +} + +// ------------------------------------------------------------------- wave + +impl Shader { + pub fn wave_is_first_lane(&mut self) -> Value { + self.require(Feature::WaveOps); + let i1 = self.m.i1(); + self.op(110, "waveIsFirstLane", None, i1, &[], FnAttrs::NoUnwind) + } + pub fn wave_lane_count(&mut self) -> Value { + self.require(Feature::WaveOps); + let i32 = self.m.i32(); + self.op(112, "waveGetLaneCount", None, i32, &[], FnAttrs::ReadNone) + } + /// `WaveActiveAnyTrue(cond)`. + pub fn wave_any_true(&mut self, cond: Value) -> Value { + self.require(Feature::WaveOps); + let i1 = self.m.i1(); + self.op(113, "waveAnyTrue", None, i1, &[cond], FnAttrs::NoUnwind) + } + /// `WaveActiveAllTrue(cond)`. + pub fn wave_all_true(&mut self, cond: Value) -> Value { + self.require(Feature::WaveOps); + let i1 = self.m.i1(); + self.op(114, "waveAllTrue", None, i1, &[cond], FnAttrs::NoUnwind) + } + pub fn wave_all_equal(&mut self, v: Value) -> Value { + self.require(Feature::WaveOps); + let t = self.m.type_of(v); + let i1 = self.m.i1(); + self.op(115, "waveActiveAllEqual", Some(t), i1, &[v], FnAttrs::NoUnwind) + } + fn wave_int64(&mut self, v: Value) { + self.require(Feature::WaveOps); + if self.is_i64(v) { + self.require(Feature::Int64Ops); + } + if self.is_f64(v) { + self.require(Feature::Doubles); + } + } + /// `WaveActiveOp` (op 119); `unsigned` selects unsigned integer min/max + /// (and is ignored for sum/product bits but kept as DXC emits it). + pub fn wave_active_op(&mut self, v: Value, op: WaveOp, unsigned: bool) -> Value { + self.wave_int64(v); + let t = self.m.type_of(v); + let (o, s) = (self.m.i8c(op as u8), self.m.i8c(unsigned as u8)); + self.op(119, "waveActiveOp", Some(t), t, &[v, o, s], FnAttrs::NoUnwind) + } + /// `WaveActiveBitAnd/Or/Xor` (op 120; integers). + pub fn wave_active_bit(&mut self, v: Value, op: WaveBit) -> Value { + self.wave_int64(v); + let t = self.m.type_of(v); + let o = self.m.i8c(op as u8); + self.op(120, "waveActiveBit", Some(t), t, &[v, o], FnAttrs::NoUnwind) + } + /// `WavePrefixSum/Product` (op 121; exclusive). DXIL only defines sum + /// and product prefixes. + pub fn wave_prefix_op(&mut self, v: Value, op: WaveOp, unsigned: bool) -> Value { + assert!(matches!(op, WaveOp::Sum | WaveOp::Product), "WavePrefixOp only sums and multiplies"); + self.wave_int64(v); + let t = self.m.type_of(v); + let (o, s) = (self.m.i8c(op as u8), self.m.i8c(unsigned as u8)); + self.op(121, "wavePrefixOp", Some(t), t, &[v, o, s], FnAttrs::NoUnwind) + } + /// `WaveActiveCountBits(cond)` (op 135). + pub fn wave_all_bit_count(&mut self, cond: Value) -> Value { + self.require(Feature::WaveOps); + let i32 = self.m.i32(); + self.op(135, "waveAllOp", None, i32, &[cond], FnAttrs::NoUnwind) + } + /// `WavePrefixCountBits(cond)` (op 136; exclusive). + pub fn wave_prefix_bit_count(&mut self, cond: Value) -> Value { + self.require(Feature::WaveOps); + let i32 = self.m.i32(); + self.op(136, "wavePrefixOp", None, i32, &[cond], FnAttrs::NoUnwind) + } + /// `QuadReadLaneAt(v, lane)` (op 122; lane 0..3, uniform). + pub fn quad_read_lane_at(&mut self, v: Value, lane: Value) -> Value { + self.wave_int64(v); + let t = self.m.type_of(v); + self.op(122, "quadReadLaneAt", Some(t), t, &[v, lane], FnAttrs::NoUnwind) + } + /// `QuadReadAcrossX/Y/Diagonal` (op 123). + pub fn quad_op(&mut self, v: Value, dir: QuadDir) -> Value { + self.wave_int64(v); + let t = self.m.type_of(v); + let d = self.m.i8c(dir as u8); + self.op(123, "quadOp", Some(t), t, &[v, d], FnAttrs::NoUnwind) + } + /// `WaveMatch(v)` (op 165, SM 6.5) → lane mask words. + pub fn wave_match(&mut self, v: Value) -> [Value; 4] { + self.wave_int64(v); + let t = self.m.type_of(v); + let i32 = self.m.i32(); + let fr = self.m.named_struct("dx.types.fouri32", &[i32, i32, i32, i32]); + let r = self.op(165, "waveMatch", Some(t), fr, &[v], FnAttrs::NoUnwind); + self.ret4(r) + } + /// `WaveMultiPrefixOp` (op 166, SM 6.5): exclusive prefix over the lanes + /// of `mask` with a [`multi_prefix`] operation. + pub fn wave_multi_prefix_op(&mut self, v: Value, mask: [Value; 4], op: u8, unsigned: bool) -> Value { + self.wave_int64(v); + let t = self.m.type_of(v); + // DXC always marks the bitwise ops signed; AMD's compiler removes + // the device on `WaveMultiPrefixBitXor` with sop = unsigned. + let unsigned = unsigned && !matches!(op, multi_prefix::AND | multi_prefix::OR | multi_prefix::XOR); + let (o, s) = (self.m.i8c(op), self.m.i8c(unsigned as u8)); + self.op(166, "waveMultiPrefixOp", Some(t), t, &[v, mask[0], mask[1], mask[2], mask[3], o, s], FnAttrs::NoUnwind) + } + /// `WaveMultiPrefixCountBits` (op 167, SM 6.5). + pub fn wave_multi_prefix_bit_count(&mut self, cond: Value, mask: [Value; 4]) -> Value { + self.require(Feature::WaveOps); + let i32 = self.m.i32(); + self.op(167, "waveMultiPrefixBitCount", None, i32, &[cond, mask[0], mask[1], mask[2], mask[3]], FnAttrs::NoUnwind) + } + + // ---- derivatives + + /// `ddx`/`ddy` (coarse or fine). Pixel shaders, or (SM 6.6) compute / + /// mesh / amplification shaders whose thread groups form quads. + pub fn deriv(&mut self, op: Deriv, v: Value) -> Value { + let t = self.m.type_of(v); + self.op(op as u32, "unary", Some(t), t, &[v], FnAttrs::ReadNone) + } +} + +/// `WaveMultiPrefixOp` operation codes (`DXIL::WaveMultiPrefixOpKind`). +pub mod multi_prefix { + pub const SUM: u8 = 0; + pub const AND: u8 = 1; + pub const OR: u8 = 2; + pub const XOR: u8 = 3; + pub const PRODUCT: u8 = 4; +} + +/// Float unary operations with an f64 overload (checked against the +/// validator in the tests); the others are f16 / f32 only. +pub const DOUBLE_UNARY: [FUnary; 2] = [FUnary::FAbs, FUnary::Saturate]; diff --git a/crates/xcl/src/gpu/dxil/ops_core.rs b/crates/xcl/src/gpu/dxil/ops_core.rs new file mode 100644 index 000000000..aa631ab53 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/ops_core.rs @@ -0,0 +1,19 @@ +//! Short names for the `dx.op` operations the direct compute translator uses +//! (the helpers themselves are [`super::ops`]). + +/// Float unary operations by their DXIL names. +pub mod op { + pub use super::super::ops::FUnary; + pub const SATURATE: FUnary = FUnary::Saturate; + pub const COS: FUnary = FUnary::Cos; + pub const SIN: FUnary = FUnary::Sin; + pub const EXP: FUnary = FUnary::Exp; + pub const FRC: FUnary = FUnary::Frc; + pub const LOG: FUnary = FUnary::Log; + pub const SQRT: FUnary = FUnary::Sqrt; + pub const RSQRT: FUnary = FUnary::Rsqrt; + pub const ROUND_NE: FUnary = FUnary::RoundNe; + pub const ROUND_NI: FUnary = FUnary::RoundNi; + pub const ROUND_PI: FUnary = FUnary::RoundPi; + pub const ROUND_Z: FUnary = FUnary::RoundZ; +} diff --git a/crates/xcl/src/gpu/dxil/ops_tests.rs b/crates/xcl/src/gpu/dxil/ops_tests.rs new file mode 100644 index 000000000..33965aaf3 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/ops_tests.rs @@ -0,0 +1,1114 @@ +//! Tests of the `dx.op` helpers in [`super::ops`]: every emitted kernel must +//! pass DXC's validator; where the runner can bind the resources, the kernel +//! also runs on the GPU (wave32, 32 threads) and is compared with a CPU +//! reference. Inputs come from `u2` (memory), results go to `u1` (`res`): +//! value `k` of lane `l` at dword `64·k + l`. + +use super::container::Stage; +use super::module::{BinOp, CastOp, Pred, RmwOp, Value}; +use super::ops::*; +use super::shader::{RawUav, Shader}; +use super::validate; +use crate::gpu::recomp::runner; + +struct K { + s: Shader, + lane: Value, + res: RawUav, + mem: RawUav, +} + +fn kernel() -> K { + 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(); + K { s, lane, res, mem } +} + +impl K { + 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) + } + /// mem[64k + lane] as i32. + fn input(&mut self, k: u32) -> Value { + let off = self.slot(k); + self.s.raw_load(self.mem, off, 1)[0] + } + fn input_f(&mut self, k: u32) -> Value { + let v = self.input(k); + let f = self.s.m.f32(); + self.s.m.bitcast(v, f) + } + /// res[64k + lane] = v (f32 bitcast, i1 zero-extended). + fn out(&mut self, k: u32, v: Value) { + let i32 = self.s.m.i32(); + let t = self.s.m.type_of(v); + let v = if t == self.s.m.i1() { + self.s.m.cast(CastOp::ZExt, v, i32) + } else if t == self.s.m.f32() { + self.s.m.bitcast(v, i32) + } else { + v + }; + let off = self.slot(k); + self.s.raw_store(self.res, off, &[v]); + } + fn finish(self, nt: [u32; 3]) -> Vec { + let c = self.s.finish(nt, Some(32)); + check(&c); + c + } +} + +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 kernel:\n{e}\n--- disassembly ---\n{dis}"); + } +} + +/// Runs a validated kernel; `None` when there is no wave32 GPU. +fn gpu(c: &[u8], mem: &[u32], tex: &[runner::TestTexture], smp: &[runner::TestSampler]) -> Option { + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => { + runner::skip_test("no wave32"); + return None; + } + Err(e) => { + runner::skip_test(&e); + return None; + } + } + Some(runner::run_with(c, &runner::KernelState::default(), mem, tex, smp).expect("GPU run")) +} + +fn outv(r: &runner::KernelResult, k: usize) -> &[u32] { + &r.raw[64 * k..64 * k + 32] +} + +fn mem_of(inputs: &[Vec]) -> Vec { + let mut m = vec![0u32; 64 * inputs.len().max(1)]; + for (k, v) in inputs.iter().enumerate() { + m[64 * k..64 * k + v.len()].copy_from_slice(v); + } + m +} + +// ------------------------------------------------------------------- math + +const FVALS: [f32; 32] = [ + 0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 1.5, -1.5, 2.5, -2.5, 0.25, 3.75, -3.75, 100.3, -100.7, 1e-3, 7.0, 0.9999, 1e10, -1e10, 0.1, 2.0, 4.0, 9.0, + f32::INFINITY, f32::NEG_INFINITY, f32::NAN, 1.25, 33.5, -0.75, 1e-30, 6.5, +]; +const UVALS: [u32; 32] = [ + 0, 1, 2, 3, 0xffff_ffff, 0x8000_0000, 0x7fff_ffff, 0x1234_5678, 0xdead_beef, 0x0f0f_0f0f, 16, 255, 256, 0x10000, 0xfffe, 7, 1000, 12345, 0xffff_0000, 0x8000_0001, 5, 6, 9, + 100, 0x4000_0000, 0x0000_ffff, 31, 32, 33, 0xc000_0000, 0x5555_5555, 0xaaaa_aaaa, +]; + +fn uvals2() -> Vec { + UVALS.iter().map(|&v| v.rotate_left(7) ^ 0x9e37_79b9).collect() +} + +#[test] +fn exact_float_unary_ops_match_cpu() { + let ops = [FUnary::FAbs, FUnary::Saturate, FUnary::Frc, FUnary::RoundNe, FUnary::RoundNi, FUnary::RoundPi, FUnary::RoundZ]; + let mut k = kernel(); + let f = k.input_f(0); + for (i, &op) in ops.iter().enumerate() { + let r = k.s.funary(op, f); + k.out(i as u32, r); + } + let n = ops.len() as u32; + for (j, c) in [FClass::IsNaN, FClass::IsInf, FClass::IsFinite].into_iter().enumerate() { + let r = k.s.fclass(c, f); + k.out(n + j as u32, r); + } + let c = k.finish([32, 1, 1]); + let fin: Vec = FVALS.iter().map(|f| f.to_bits()).collect(); + let Some(r) = gpu(&c, &mem_of(&[fin]), &[], &[]) else { return }; + let cpu: [fn(f32) -> f32; 7] = [f32::abs, |x| if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }, |x| x - x.floor(), f32::round_ties_even, f32::floor, f32::ceil, f32::trunc]; + for (i, f) in cpu.iter().enumerate() { + for (l, &x) in FVALS.iter().enumerate() { + let want = f(x); + let got = f32::from_bits(outv(&r, i)[l]); + // Denormals may flush; Frc(±inf) is NaN; compare NaN-ness then bits. + let ok = (want.is_nan() && got.is_nan()) || want.to_bits() == got.to_bits() || (want == 0.0 && got == 0.0 && i == 2); + assert!(ok || (x.abs() < 1e-20), "op {:?} of {x}: got {got}, want {want}", ops[i]); + } + } + for (l, &x) in FVALS.iter().enumerate() { + assert_eq!(outv(&r, 7)[l], x.is_nan() as u32, "isnan {x}"); + assert_eq!(outv(&r, 8)[l], x.is_infinite() as u32, "isinf {x}"); + assert_eq!(outv(&r, 9)[l], x.is_finite() as u32, "isfinite {x}"); + } +} + +#[test] +fn approximate_float_unary_ops_are_within_tolerance() { + let ops = [FUnary::Cos, FUnary::Sin, FUnary::Exp, FUnary::Log, FUnary::Sqrt, FUnary::Rsqrt]; + let mut k = kernel(); + let f = k.input_f(0); + for (i, &op) in ops.iter().enumerate() { + let r = k.s.funary(op, f); + k.out(i as u32, r); + } + let c = k.finish([32, 1, 1]); + let xs: Vec = (0..32).map(|l| 0.05 + l as f32 * 0.37).collect(); + let Some(r) = gpu(&c, &mem_of(&[xs.iter().map(|x| x.to_bits()).collect()]), &[], &[]) else { return }; + let cpu: [fn(f32) -> f32; 6] = [f32::cos, f32::sin, f32::exp2, f32::log2, f32::sqrt, |x| 1.0 / x.sqrt()]; + for (i, f) in cpu.iter().enumerate() { + for (l, &x) in xs.iter().enumerate() { + let (want, got) = (f(x), f32::from_bits(outv(&r, i)[l])); + let tol = 1e-3f32.max(want.abs() * 1e-5); + assert!((want - got).abs() <= tol, "{:?}({x}) = {got}, want {want}", ops[i]); + } + } +} + +#[test] +fn integer_ops_match_cpu() { + let mut k = kernel(); + let a = k.input(0); + let b = k.input(1); + let mut outs = Vec::new(); + outs.push(k.s.bfrev(a)); + for op in [BitCount::Countbits, BitCount::FirstbitLo, BitCount::FirstbitHi, BitCount::FirstbitSHi] { + outs.push(k.s.bit_count(op, a)); + } + for op in [Binary::IMax, Binary::IMin, Binary::UMax, Binary::UMin] { + outs.push(k.s.binary(op, a, b)); + } + outs.push(k.s.tertiary(Tertiary::IMad, a, b, a)); + outs.push(k.s.tertiary(Tertiary::UMad, a, b, b)); + let (w, o) = { + let m31 = k.s.m.i32c(31); + let w = k.s.m.bin(BinOp::And, b, m31); + let o = { let c = k.s.m.i32c(5); k.s.m.bin(BinOp::LShr, b, c) }; + let o = k.s.m.bin(BinOp::And, o, m31); + (w, o) + }; + outs.push(k.s.tertiary(Tertiary::Ibfe, w, o, a)); + outs.push(k.s.tertiary(Tertiary::Ubfe, w, o, a)); + outs.push(k.s.bfi(w, o, a, b)); + let (hi, lo) = k.s.umul_wide(a, b); + outs.extend([hi, lo]); + let (hi, lo) = k.s.imul_wide(a, b); + outs.extend([hi, lo]); + let (q, rm) = k.s.udiv_rem(a, b); + outs.extend([q, rm]); + for (i, &v) in outs.iter().enumerate() { + k.out(i as u32, v); + } + let c = k.finish([32, 1, 1]); + let bs = uvals2(); + let Some(r) = gpu(&c, &mem_of(&[UVALS.to_vec(), bs.clone()]), &[], &[]) else { return }; + let fhi = |x: u32| if x == 0 { u32::MAX } else { x.leading_zeros() }; + let bfe = |w: u32, o: u32, v: u32, signed: bool| -> u32 { + if w == 0 { + 0 + } else if w + o < 32 { + let s = v << (32 - w - o); + if signed { ((s as i32) >> (32 - w)) as u32 } else { s >> (32 - w) } + } else if signed { + ((v as i32) >> o) as u32 + } else { + v >> o + } + }; + for l in 0..32 { + let (a, b) = (UVALS[l], bs[l]); + let (w, o) = (b & 31, (b >> 5) & 31); + let bfi = { let m = ((1u64 << w) - 1) as u32; let m = m << o; ((a << o) & m) | (b & !m) }; + let um = a as u64 * b as u64; + let im = (a as i32 as i64 * b as i32 as i64) as u64; + let want = [ + a.reverse_bits(), + a.count_ones(), + if a == 0 { u32::MAX } else { a.trailing_zeros() }, + fhi(a), + fhi(if (a as i32) < 0 { !a } else { a }), + (a as i32).max(b as i32) as u32, + (a as i32).min(b as i32) as u32, + a.max(b), + a.min(b), + a.wrapping_mul(b).wrapping_add(a), + a.wrapping_mul(b).wrapping_add(b), + bfe(w, o, a, true), + bfe(w, o, a, false), + bfi, + (um >> 32) as u32, + um as u32, + (im >> 32) as u32, + im as u32, + a.checked_div(b).unwrap_or(u32::MAX), + a.checked_rem(b).unwrap_or(u32::MAX), + ]; + for (i, &wv) in want.iter().enumerate() { + assert_eq!(outv(&r, i)[l], wv, "int op #{i} lane {l}: a={a:#x} b={b:#x}"); + } + } +} + +#[test] +fn float_binary_tertiary_and_half_conversions_match_cpu() { + let mut k = kernel(); + let a = k.input_f(0); + let b = k.input_f(1); + let bits = k.input(0); + let mx = k.s.binary(Binary::FMax, a, b); + let mn = k.s.binary(Binary::FMin, a, b); + let h = k.s.f32_to_f16(a); + let back = k.s.f16_to_f32(bits); + let mad = k.s.tertiary(Tertiary::FMad, a, b, a); + for (i, v) in [mx, mn, h, back, mad].into_iter().enumerate() { + k.out(i as u32, v); + } + let c = k.finish([32, 1, 1]); + let bv: Vec = FVALS.iter().rev().copied().collect(); + let Some(r) = gpu(&c, &mem_of(&[FVALS.iter().map(|f| f.to_bits()).collect(), bv.iter().map(|f| f.to_bits()).collect()]), &[], &[]) else { return }; + for l in 0..32 { + let (x, y) = (FVALS[l], bv[l]); + let fl = |v: f32| if v.abs() < 1e-37 { 0.0 } else { v }; + assert_eq!(fl(f32::from_bits(outv(&r, 0)[l])).to_bits(), fl(x.max(y)).to_bits(), "fmax {x} {y}"); + assert_eq!(fl(f32::from_bits(outv(&r, 1)[l])).to_bits(), fl(x.min(y)).to_bits(), "fmin {x} {y}"); + if !x.is_nan() { + // Rounding is implementation-defined: nearest-even or towards zero + // (the RTX 4090 truncates). + let got = outv(&r, 2)[l]; + assert!(got == f32_to_f16(x, false) as u32 || got == f32_to_f16(x, true) as u32, "f32tof16 {x}: {got:#x}"); + } + let hb = (x.to_bits() & 0xffff) as u16; + let hf = f16_to_f32(hb); + if !hf.is_nan() { + assert_eq!(outv(&r, 3)[l], hf.to_bits(), "f16tof32 {hb:#x}"); + } + let m = f32::from_bits(outv(&r, 4)[l]); + let w = x * y + x; + assert!((m.is_nan() && w.is_nan()) || m == w || (m - w).abs() <= w.abs() * 1e-6, "fmad {x} {y}: {m} vs {w}"); + } +} + +#[test] +fn uaddc_and_usubb_match_cpu() { + // HLSL never emits UAddc/USubb, but DXC 1.9's validator accepts them in cs_6_6. + let mut k = kernel(); + let a = k.input(0); + let b = k.input(1); + let (sum, carry) = k.s.uaddc(a, b); + let (diff, borrow) = k.s.usubb(a, b); + for (i, v) in [sum, carry, diff, borrow].into_iter().enumerate() { + k.out(i as u32, v); + } + let c = k.finish([32, 1, 1]); + let bs = uvals2(); + let Some(r) = gpu(&c, &mem_of(&[UVALS.to_vec(), bs.clone()]), &[], &[]) else { return }; + for l in 0..32 { + let (a, b) = (UVALS[l], bs[l]); + let (s, c) = a.overflowing_add(b); + let (d, w) = a.overflowing_sub(b); + assert_eq!([outv(&r, 0)[l], outv(&r, 1)[l], outv(&r, 2)[l], outv(&r, 3)[l]], [s, c as u32, d, w as u32], "lane {l}: {a:#x} {b:#x}"); + } +} + +#[test] +fn doubles_match_cpu() { + let mut k = kernel(); + let lo = k.input(0); + let hi = k.input(1); + let d = k.s.make_double(lo, hi); + let two = { let f64 = k.s.m.f64(); k.s.m.const_float(f64, 2.0f64.to_bits()) }; + let one = { let f64 = k.s.m.f64(); k.s.m.const_float(f64, 0.1f64.to_bits()) }; + let f = k.s.tertiary(Tertiary::Fma, d, two, one); + let mx = k.s.binary(Binary::FMax, f, d); + let (l0, h0) = k.s.split_double(f); + let (l1, h1) = k.s.split_double(mx); + for (i, v) in [l0, h0, l1, h1].into_iter().enumerate() { + k.out(i as u32, v); + } + let c = k.finish([32, 1, 1]); + let ds: Vec = (0..32).map(|l| (l as f64 - 15.5) * 1.000_000_000_1).collect(); + let Some(r) = gpu(&c, &mem_of(&[ds.iter().map(|d| d.to_bits() as u32).collect(), ds.iter().map(|d| (d.to_bits() >> 32) as u32).collect()]), &[], &[]) else { return }; + for (l, &x) in ds.iter().enumerate() { + let f = x.mul_add(2.0, 0.1); + let got = |i: usize| (outv(&r, i)[l] as u64) | ((outv(&r, i + 1)[l] as u64) << 32); + assert_eq!(got(0), f.to_bits(), "fma({x})"); + assert_eq!(got(2), f.max(x).to_bits(), "max({x})"); + } +} + +// ----------------------------------------------------------------- memory + +#[test] +fn groupshared_barrier_and_atomics_run() { + let mut k = kernel(); + let i32 = k.s.m.i32(); + let i64 = k.s.m.i64(); + let gs = k.s.groupshared("gs", i32, 32); + let acc = k.s.groupshared("acc", i32, 2); + let acc64 = k.s.groupshared("acc64", i64, 1); + let v = k.input(0); + let zero = k.s.m.i32c(0); + let one = k.s.m.i32c(1); + // Lane 0 clears the accumulators. + let is0 = k.s.m.cmp(Pred::Eq, k.lane, zero); + let init = k.s.m.new_block(); + let join = k.s.m.new_block(); + k.s.m.cond_br(is0, init, join); + k.s.m.set_block(init); + k.s.gs_store(acc, zero, zero); + k.s.gs_store(acc, one, zero); + let z64 = k.s.m.const_int(i64, 0); + k.s.gs_store(acc64, zero, z64); + k.s.m.br(join); + k.s.m.set_block(join); + k.s.gs_store(gs, k.lane, v); + k.s.barrier(barrier::GROUP_SYNC); + let m31 = k.s.m.i32c(31); + let rev = k.s.m.bin(BinOp::Sub, m31, k.lane); + let other = k.s.gs_load(gs, rev); + k.s.gs_atomic(RmwOp::Add, acc, zero, v); + k.s.gs_atomic(RmwOp::UMax, acc, one, v); + let v64 = k.s.m.cast(CastOp::ZExt, v, i64); + k.s.gs_atomic(RmwOp::Add, acc64, zero, v64); + // cmpxchg: only the lane that sees 0 in gs[0] after barrier... use a + // deterministic one: every lane tries gs[lane] == v → v + 1. + let vp1 = k.s.m.bin(BinOp::Add, v, one); + let old = k.s.gs_cmpxchg(gs, k.lane, v, vp1); + k.s.barrier(barrier::GROUP_SYNC); + let sum = k.s.gs_load(acc, zero); + let max = k.s.gs_load(acc, one); + let s64 = k.s.gs_load(acc64, zero); + let s64hi = { let c = k.s.m.const_int(i64, 32); k.s.m.bin(BinOp::LShr, s64, c) }; + let s64hi = k.s.m.cast(CastOp::Trunc, s64hi, i32); + let after = k.s.gs_load(gs, k.lane); + for (i, x) in [other, sum, max, s64hi, old, after].into_iter().enumerate() { + k.out(i as u32, x); + } + let c = k.finish([32, 1, 1]); + let vals: Vec = (0..32).map(|l| 0x9000_0000u32.wrapping_add(l * 0x0100_0001)).collect(); + let Some(r) = gpu(&c, &mem_of(&[vals.clone()]), &[], &[]) else { return }; + let sum: u32 = vals.iter().fold(0u32, |a, &b| a.wrapping_add(b)); + let s64: u64 = vals.iter().map(|&v| v as u64).sum(); + for l in 0..32 { + assert_eq!(outv(&r, 0)[l], vals[31 - l]); + assert_eq!(outv(&r, 1)[l], sum); + assert_eq!(outv(&r, 2)[l], *vals.iter().max().unwrap()); + assert_eq!(outv(&r, 3)[l], (s64 >> 32) as u32); + assert_eq!(outv(&r, 4)[l], vals[l]); + assert_eq!(outv(&r, 5)[l], vals[l] + 1); + } +} + +#[test] +fn raw_and_structured_buffer_atomics_run() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let sb = s.structured_uav(1, 0, 4); + let mem = s.raw_uav(2, 0); + let lane = s.flattened_thread_id_in_group(); + let i32 = s.m.i32(); + let i64 = s.m.i64(); + let off = { let c = s.m.i32c(2); s.m.bin(BinOp::Shl, lane, c) }; + let v = s.raw_load(mem, off, 1)[0]; + // mem[64..]: accumulators (dword 64 add, 65 or, 66 umax; 68..69 i64 add; 70 cmpxchg target). + let c256 = s.m.i32c(256); + let o_add = s.raw_atomic(mem, AtomicOp::Add, c256, v); + let c260 = s.m.i32c(260); + s.raw_atomic(mem, AtomicOp::Or, c260, v); + let c264 = s.m.i32c(264); + s.raw_atomic(mem, AtomicOp::UMax, c264, v); + let c272 = s.m.i32c(272); + let v64 = s.m.cast(CastOp::ZExt, v, i64); + let sh = s.m.const_int(i64, 20); + let v64 = s.m.bin(BinOp::Shl, v64, sh); + s.raw_atomic(mem, AtomicOp::Add, c272, v64); + // Lane-ordered cmpxchg: exactly one lane (the one whose value is 0) wins first. + let c280 = s.m.i32c(280); + let zero = s.m.i32c(0); + let won = s.raw_cmpxchg(mem, c280, zero, v); + // structured: sb[lane] = v; sb[32] += 1 for each lane (structured atomic). + s.structured_store(sb, lane, 0, &[v]); + let c32 = s.m.i32c(32); + let one = s.m.i32c(1); + s.structured_atomic(sb, AtomicOp::Add, c32, 0, one); + let c33 = s.m.i32c(33); + let o = s.m.bin(BinOp::Add, lane, c33); + let _ = (o_add, i32); + s.structured_store(sb, o, 0, &[won]); + let c = s.finish([32, 1, 1], Some(32)); + check(&c); + let dis = validate::disassemble(&c).unwrap(); + assert!(dis.contains("@dx.op.atomicBinOp.i64(i32 78"), "{dis}"); + let vals: Vec = (0..32).map(|l| (l * 37 + 11) & 0xff).collect(); + let mut m = vals.clone(); + m.resize(128, 0); + m[70] = 0; + let Some(r) = gpu(&c, &m, &[], &[]) else { return }; + let sum: u32 = vals.iter().sum(); + let or = vals.iter().fold(0, |a, b| a | b); + let s64: u64 = vals.iter().map(|&v| (v as u64) << 20).sum(); + assert_eq!(r.mem[64], sum); + assert_eq!(r.mem[65], or); + assert_eq!(r.mem[66], *vals.iter().max().unwrap()); + assert_eq!(r.mem[68] as u64 | ((r.mem[69] as u64) << 32), s64); + assert!(vals.contains(&r.mem[70])); + assert_eq!(&r.raw[..32], &vals[..]); + assert_eq!(r.raw[32], 32); + // every lane but the first swapper sees the winner's value + // No input is 0: exactly one lane swapped (saw 0), the others saw the winner. + let olds = &r.raw[33..65]; + assert_eq!(olds.iter().filter(|&&o| o == 0).count(), 1); + assert!(olds.iter().all(|&o| o == 0 || o == r.mem[70])); +} + +#[test] +fn typed_buffer_ops_validate() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let tb = s.typed_uav(3, 0, CompType::U32); + let lane = s.flattened_thread_id_in_group(); + let v = s.buffer_load(tb, lane); + let one = s.m.i32c(1); + let x = s.m.bin(BinOp::Add, v[0], one); + let n = s.m.bin(BinOp::Add, lane, one); + s.buffer_store(tb, n, &[x, x, x, x]); + s.typed_atomic(tb, AtomicOp::Add, lane, one); + let i64 = s.m.i64(); + let tb64 = { + let idx = s.m.i32c(3); + s.heap_typed_buffer(idx, true, CompType::U64, false) + }; + let big = s.m.const_int(i64, 1 << 40); + s.typed_atomic(tb64, AtomicOp::Or, lane, big); + let d = s.get_dimensions(tb.handle, None); + let n = s.m.extract(d, 0); + s.buffer_store(tb, n, &[x, x, x, x]); + let c = s.finish([32, 1, 1], None); + check(&c); + let dis = validate::disassemble(&c).unwrap(); + for needle in ["@dx.op.bufferLoad.i32(i32 68", "@dx.op.bufferStore.i32(i32 69", "@dx.op.atomicBinOp.i64(i32 78", "RWTypedBuffer"] { + assert!(dis.contains(needle), "missing {needle}:\n{dis}"); + } +} + +/// Typed buffers on the GPU: heap 0 `Buffer` (SRV, R32_UINT, 32 +/// elements), heap 3 `RWBuffer` (UAV, R32_UINT, 64 elements). +/// `uav[l] = srv[l] * 3 + uav[l]`; `InterlockedAdd(uav[32 + (l & 3)], l)` +/// returns the old value; `res0 = srv[31 - l]`. +#[test] +fn typed_buffer_ops_run() { + use windows::Win32::Graphics::Dxgi::Common::*; + let mut k = kernel(); + let (i0, i3) = (k.s.m.i32c(0), k.s.m.i32c(3)); + let srv = k.s.heap_typed_buffer(i0, false, CompType::U32, false); + let uav = k.s.heap_typed_buffer(i3, true, CompType::U32, false); + let lane = k.lane; + let a = k.s.buffer_load(srv, lane)[0]; + let b = k.s.buffer_load(uav, lane)[0]; + let three = k.s.m.i32c(3); + let a3 = k.s.m.bin(BinOp::Mul, a, three); + let v = k.s.m.bin(BinOp::Add, a3, b); + k.s.buffer_store(uav, lane, &[v, v, v, v]); + let c32 = k.s.m.i32c(32); + let q = k.s.m.bin(BinOp::And, lane, three); + let slot = k.s.m.bin(BinOp::Add, c32, q); + let old = k.s.typed_atomic(uav, AtomicOp::Add, slot, lane); + let c31 = k.s.m.i32c(31); + let r = k.s.m.bin(BinOp::Sub, c31, lane); + let rv = k.s.buffer_load(srv, r)[0]; + k.out(0, rv); + k.out(1, old); + let c = k.finish([32, 1, 1]); + let srv_data: Vec = (0..32).map(|i| i * 7 + 1).collect(); + let uav_data: Vec = (0..64).map(|i| 1000 + i).collect(); + let buf = |data: &[u32], uav: bool| runner::TestTexture { + dim: runner::TexDim::Buffer, + format: DXGI_FORMAT_R32_UINT, + width: data.len() as u32, + height: 1, + depth: 1, + texel_bytes: 4, + data: data.iter().flat_map(|x| x.to_le_bytes()).collect(), + uav, + }; + let Some(r) = gpu(&c, &[], &[buf(&srv_data, false), buf(&uav_data, true)], &[]) else { return }; + let want: Vec = (0..32).map(|l| srv_data[31 - l]).collect(); + assert_eq!(outv(&r, 0), &want[..]); + let out: Vec = r.textures[0].chunks(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect(); + for l in 0..32 { + assert_eq!(out[l], srv_data[l] * 3 + uav_data[l], "uav[{l}]"); + } + for q in 0..4u32 { + let sum: u32 = (0..32).filter(|l| l & 3 == q).sum(); + assert_eq!(out[32 + q as usize], uav_data[32 + q as usize] + sum, "atomic slot {q}"); + } + // Old values: each lane saw a partial sum of its slot. + for l in 0..32usize { + let o = outv(&r, 1)[l]; + let base = uav_data[32 + (l & 3)]; + let total: u32 = (0..32u32).filter(|x| (x & 3) as usize == l & 3).sum(); + assert!(o >= base && o - base <= total, "old value of lane {l}: {o}"); + } +} + +// --------------------------------------------------------------- textures + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +fn tex_data(w: u32, h: u32, d: u32) -> Vec { + (0..w * h * d).map(|i| i as f32 * 0.25 + 1.0).collect() +} + +fn ftex(dim: runner::TexDim, w: u32, h: u32, d: u32) -> runner::TestTexture { + runner::TestTexture { + dim, + format: DXGI_FORMAT_R32_FLOAT, + width: w, + height: h, + depth: d, + texel_bytes: 4, + data: tex_data(w, h, d).iter().flat_map(|f| f.to_le_bytes()).collect(), + uav: false, + } +} + +/// Textures: t0 2D 8×8, t1 2D-array 8×8×2, t2 3D 4×4×4, t3 cube 4×4, t4 UAV +/// 2D R32_UINT 8×4 (heap 9); samplers: s0 point clamp, s1 point clamp +/// comparison LESS_EQUAL. +fn textures() -> (Vec, Vec) { + let mut u = ftex(runner::TexDim::D2, 8, 4, 1); + u.format = DXGI_FORMAT_R32_UINT; + u.uav = true; + u.data = vec![0; 8 * 4 * 4]; + ( + vec![ftex(runner::TexDim::D2, 8, 8, 1), ftex(runner::TexDim::D2Array, 8, 8, 2), ftex(runner::TexDim::D3, 4, 4, 4), ftex(runner::TexDim::Cube, 4, 4, 6), u], + vec![ + runner::TestSampler { filter: D3D12_FILTER_MIN_MAG_MIP_POINT, address: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, comparison: None }, + runner::TestSampler { filter: D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT, address: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, comparison: Some(D3D12_COMPARISON_FUNC_LESS_EQUAL) }, + ], + ) +} + +#[test] +fn texture_ops_run() { + let mut k = kernel(); + let x = k.s.thread_id_in_group(0); + let y = k.s.thread_id_in_group(1); + let f32 = k.s.m.f32(); + let i32 = k.s.m.i32(); + let idx = |k: &mut K, i: u32| k.s.m.i32c(i); + let i0 = idx(&mut k, 0); + let t2 = k.s.heap_texture(i0, TexKind::D2, false, CompType::F32, 1, false); + let i2 = idx(&mut k, 2); + let ta = k.s.heap_texture(i2, TexKind::D2Array, false, CompType::F32, 1, false); + let i4 = idx(&mut k, 4); + let t3 = k.s.heap_texture(i4, TexKind::D3, false, CompType::F32, 1, false); + let i6 = idx(&mut k, 6); + let tc = k.s.heap_texture(i6, TexKind::Cube, false, CompType::F32, 1, false); + let i9 = idx(&mut k, 9); + let uv = k.s.heap_texture(i9, TexKind::D2, true, CompType::U32, 1, false); + let s0 = k.s.heap_sampler(i0, false, false); + let one = idx(&mut k, 1); + let sc = k.s.heap_sampler(one, true, false); + // uv = (x + 0.5) / 8, (y + 0.5) / 8 → texel (x, y) of an 8×8 texture + let fx = k.s.m.cast(CastOp::UIToFP, x, f32); + let fy = k.s.m.cast(CastOp::UIToFP, y, f32); + let half = k.s.m.f32c(0.5f32.to_bits()); + let eighth = k.s.m.f32c(0.125f32.to_bits()); + let u = k.s.m.fbin(BinOp::Add, fx, half, 0); + let u = k.s.m.fbin(BinOp::Mul, u, eighth, 0); + let v = k.s.m.fbin(BinOp::Add, fy, half, 0); + let v = k.s.m.fbin(BinOp::Mul, v, eighth, 0); + let zero = k.s.m.i32c(0); + let fzero = k.s.m.f32c(0); + let fone = k.s.m.f32c(1.0f32.to_bits()); + let ld = k.s.texture_load(t2, Some(zero), &[x, y], &[]); + let ldo = k.s.texture_load(t2, Some(zero), &[x, y], &[1, 0]); + let smp = k.s.sample(t2, s0, &[u, v], &[], None); + let sl = k.s.sample_level(t2, s0, &[u, v], &[], fzero); + let sg = k.s.sample_grad(t2, s0, &[u, v], &[], &[fzero, fzero], &[fzero, fzero], None); + let sb = k.s.sample_bias(t2, s0, &[u, v], &[], fzero, None); + let g = k.s.gather(t2, s0, &[u, v], &[], 0); + // ref value 10: texels ≤ 10 compare → 1.0 (LESS_EQUAL: ref <= texel) + let refv = k.s.m.f32c(10.0f32.to_bits()); + let cmp = k.s.sample_cmp(t2, sc, &[u, v], &[], refv, None); + let cmpz = k.s.sample_cmp_level_zero(t2, sc, &[u, v], &[], refv); + let gc = k.s.gather_cmp(t2, sc, &[u, v], &[], 0, refv); + let sa = k.s.sample_level(ta, s0, &[u, v, fone], &[], fzero); + let s3 = k.s.sample_level(t3, s0, &[u, v, half], &[], fzero); + let cube_dir = [fone, fzero, fzero]; + let scube = k.s.sample_level(tc, s0, &cube_dir, &[], fzero); + let lod = k.s.calculate_lod(t2, s0, &[u, v], true); + let d = k.s.get_dimensions(t2.handle, Some(zero)); + let dims = [0, 1, 2, 3].map(|i| if i == 2 { d } else { k.s.m.extract(d, i) }); + let d = k.s.get_dimensions(uv.handle, None); + let udims = [0, 1].map(|i| k.s.m.extract(d, i)); + let bits = k.s.m.bitcast(ld[0], i32); + k.s.texture_store(uv, &[x, y], [bits, bits, bits, bits]); + let outs = [ld[0], ldo[0], smp[0], sl[0], sg[0], sb[0], g[0], g[1], g[2], g[3], cmp[0], cmpz[0], gc[0], sa[0], s3[0], scube[0], lod, dims[0], dims[1], dims[3], udims[0], udims[1]]; + for (i, &o) in outs.iter().enumerate() { + k.out(i as u32, o); + } + let c = k.finish([8, 4, 1]); + let (tex, smp) = textures(); + let Some(r) = gpu(&c, &[0; 64], &tex, &smp) else { return }; + let t2d = tex_data(8, 8, 1); + let at = |x: usize, y: usize| t2d[y.min(7) * 8 + x.min(7)]; + let lane_xy = |l: usize| (l % 8, l / 8); + let f = |i: usize, l: usize| f32::from_bits(outv(&r, i)[l]); + for l in 0..32 { + let (x, y) = lane_xy(l); + let t = at(x, y); + assert_eq!(f(0, l), t, "load lane {l}"); + assert_eq!(f(1, l), if x < 7 { at(x + 1, y) } else { 0.0 }, "load+offset lane {l} (out of bounds → 0)"); + for i in 2..6 { + assert_eq!(f(i, l), t, "sample variant {i} lane {l}"); + } + // gather at the texel centre: lower-right quad (x..x+1, y..y+1) in + // (-u+v, +u+v, +u-v, -u-v) order — point at centre picks (x-0.5..): the + // 2×2 footprint around (x+0.5, y+0.5) is texels x..x+1 with coords floored at x+0.5-0.5. + let gw = [at(x, y + 1), at(x + 1, y + 1), at(x + 1, y), at(x, y)]; + for j in 0..4 { + assert_eq!(f(6 + j, l), gw[j], "gather[{j}] lane {l}"); + } + let c1 = |v: f32| if 10.0 <= v { 1.0 } else { 0.0 }; + assert_eq!(f(10, l), c1(t), "samplecmp lane {l}"); + assert_eq!(f(11, l), c1(t), "samplecmplevelzero lane {l}"); + assert_eq!(f(12, l), c1(gw[0]), "gathercmp lane {l}"); + assert_eq!(f(13, l), tex_data(8, 8, 2)[64 + y * 8 + x], "array slice 1 lane {l}"); + let (x3, y3) = (x * 4 / 8, y * 4 / 8); + assert_eq!(f(14, l), tex_data(4, 4, 4)[2 * 16 + y3 * 4 + x3], "3D lane {l}"); + // +X face (face 0) centre → texel (2, 2) or nearby of face 0. + let fc = f(15, l); + assert!((0..16).any(|i| tex_data(4, 4, 6)[i] == fc), "cube +X lane {l}: {fc}"); + assert_eq!(f(16, l), 0.0, "lod lane {l}"); + assert_eq!(&[outv(&r, 17)[l], outv(&r, 18)[l], outv(&r, 19)[l], outv(&r, 20)[l], outv(&r, 21)[l]], &[8, 8, 1, 8, 4], "dims lane {l}"); + } + let stored: Vec = r.textures[0].chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + for l in 0..32 { + let (x, y) = lane_xy(l); + assert_eq!(stored[y * 8 + x], at(x, y).to_bits(), "texture store {x},{y}"); + } +} + +#[test] +fn texture_variants_validate() { + // Offsets, clamp (tiled resources), typed UAV loads of float4, texture + // atomics, unclamped LOD, 3D / array UAV stores. + let mut s = Shader::new(Stage::Compute, (6, 6)); + let x = s.thread_id_in_group(0); + let f = s.m.f32c(0.5f32.to_bits()); + let i0 = s.m.i32c(0); + let t = s.heap_texture(i0, TexKind::D2, false, CompType::F32, 4, false); + let smp = s.heap_sampler(i0, false, false); + let r1 = s.sample(t, smp, &[f, f], &[1, -1], Some(f)); + let r2 = s.sample_bias(t, smp, &[f, f], &[0, 1], f, Some(f)); + let _ = s.calculate_lod(t, smp, &[f, f], false); + let i9 = s.m.i32c(9); + let u4 = s.heap_texture(i9, TexKind::D2, true, CompType::F32, 4, false); + s.typed_uav_load_additional_formats(); + let l = s.texture_load(u4, None, &[x, x], &[]); + let a = s.m.fbin(BinOp::Add, l[1], r1[2], 0); + let a = s.m.fbin(BinOp::Add, a, r2[3], 0); + s.texture_store(u4, &[x, x], [a, a, a, a]); + let i11 = s.m.i32c(11); + let ua = s.heap_texture(i11, TexKind::D2Array, true, CompType::U32, 1, false); + let one = s.m.i32c(1); + let old = s.atomic_binop(ua.handle, AtomicOp::Add, &[x, x, one], one); + let cx = s.atomic_cmpxchg(ua.handle, &[x, x, i0], old, one); + s.texture_store(ua, &[x, x, one], [cx, cx, cx, cx]); + let i13 = s.m.i32c(13); + let u3 = s.heap_texture(i13, TexKind::D3, true, CompType::F32, 1, false); + s.texture_store(u3, &[x, x, one], [a, a, a, a]); + let c = s.finish([8, 4, 1], None); + check(&c); +} + +// ------------------------------------------------------------------- wave + +/// `WaveGetLaneIndex` is declared as DXC 1.9 declares it. +#[test] +fn wave_lane_index_is_declared_readonly() { + let mut k = kernel(); + let lane = k.s.wave_lane_index(); + k.out(0, lane); + let dis = validate::disassemble(&k.finish([32, 1, 1])).expect("disassembly"); + let at = dis.lines().position(|l| l.starts_with("declare i32 @dx.op.waveGetLaneIndex(")).expect("the declaration"); + assert_eq!(dis.lines().nth(at - 1), Some("; Function Attrs: nounwind readonly"), "{dis}"); +} + +#[test] +fn wave_ops_match_cpu() { + let mut k = kernel(); + let u = k.input(0); + let fv = k.input_f(1); + let i64 = k.s.m.i64(); + let three = k.s.m.i32c(3); + let gt3 = k.s.m.cmp(Pred::UGt, u, three); + let mut o = vec![ + k.s.wave_is_first_lane(), + k.s.wave_lane_count(), + k.s.wave_all_true(gt3), + k.s.wave_any_true(gt3), + k.s.wave_all_equal(u), + ]; + for (op, uns) in [(WaveOp::Sum, true), (WaveOp::Product, true), (WaveOp::Min, true), (WaveOp::Max, true), (WaveOp::Min, false), (WaveOp::Max, false)] { + o.push(k.s.wave_active_op(u, op, uns)); + } + for b in [WaveBit::And, WaveBit::Or, WaveBit::Xor] { + o.push(k.s.wave_active_bit(u, b)); + } + o.push(k.s.wave_prefix_op(u, WaveOp::Sum, true)); + o.push(k.s.wave_prefix_op(u, WaveOp::Product, false)); + o.push(k.s.wave_all_bit_count(gt3)); + o.push(k.s.wave_prefix_bit_count(gt3)); + let two = k.s.m.i32c(2); + o.push(k.s.quad_read_lane_at(u, two)); + for d in [QuadDir::ReadAcrossX, QuadDir::ReadAcrossY, QuadDir::ReadAcrossDiagonal] { + o.push(k.s.quad_op(u, d)); + } + let m7 = k.s.m.i32c(7); + let key = k.s.m.bin(BinOp::And, u, m7); + let mask = k.s.wave_match(key); + o.push(mask[0]); + o.push(k.s.wave_multi_prefix_op(u, mask, multi_prefix::SUM, true)); + o.push(k.s.wave_multi_prefix_op(u, mask, multi_prefix::XOR, false)); + o.push(k.s.wave_multi_prefix_bit_count(gt3, mask)); + let u64v = k.s.m.cast(CastOp::ZExt, u, i64); + let sh = k.s.m.const_int(i64, 8); + let u64v = k.s.m.bin(BinOp::Shl, u64v, sh); + let s64 = k.s.wave_active_op(u64v, WaveOp::Sum, true); + let s64 = { let c = k.s.m.const_int(i64, 32); k.s.m.bin(BinOp::LShr, s64, c) }; + let i32 = k.s.m.i32(); + o.push(k.s.m.cast(CastOp::Trunc, s64, i32)); + o.push(k.s.wave_active_op(fv, WaveOp::Sum, false)); + o.push(k.s.wave_active_op(fv, WaveOp::Max, false)); + o.push(k.s.wave_prefix_op(fv, WaveOp::Sum, false)); + for (i, &v) in o.iter().enumerate() { + k.out(i as u32, v); + } + let c = k.finish([32, 1, 1]); + let us: Vec = (0..32u32).map(|l| l.wrapping_mul(2_654_435_761u32) >> 24 | 1).collect(); + let fs: Vec = (0..32).map(|l| l as f32 * 0.5 + 1.0).collect(); + let Some(r) = gpu(&c, &mem_of(&[us.clone(), fs.iter().map(|f| f.to_bits()).collect()]), &[], &[]) else { return }; + let sum = us.iter().fold(0u32, |a, &b| a.wrapping_add(b)); + let prod = us.iter().fold(1u32, |a, &b| a.wrapping_mul(b)); + let all = us.iter().all(|&v| v > 3) as u32; + let any = us.iter().any(|&v| v > 3) as u32; + let cnt = us.iter().filter(|&&v| v > 3).count() as u32; + let s64: u64 = us.iter().map(|&v| (v as u64) << 8).sum(); + for l in 0..32 { + let q = l & !3; + let key = us[l] & 7; + let grp: Vec = (0..32).filter(|&j| us[j] & 7 == key).collect(); + let mmask = grp.iter().fold(0u32, |a, &j| a | (1 << j)); + let before: Vec = grp.iter().copied().filter(|&j| j < l).collect(); + let want = [ + (l == 0) as u32, + 32, + all, + any, + us.iter().all(|&v| v == us[0]) as u32, + sum, + prod, + *us.iter().min().unwrap(), + *us.iter().max().unwrap(), + *us.iter().min().unwrap(), + *us.iter().max().unwrap(), + us.iter().fold(!0, |a, &b| a & b), + us.iter().fold(0, |a, &b| a | b), + us.iter().fold(0, |a, &b| a ^ b), + us[..l].iter().fold(0u32, |a, &b| a.wrapping_add(b)), + us[..l].iter().fold(1u32, |a, &b| a.wrapping_mul(b)), + cnt, + us[..l].iter().filter(|&&v| v > 3).count() as u32, + us[q + 2], + us[l ^ 1], + us[l ^ 2], + us[l ^ 3], + mmask, + before.iter().fold(0u32, |a, &j| a.wrapping_add(us[j])), + before.iter().fold(0u32, |a, &j| a ^ us[j]), + before.iter().filter(|&&j| us[j] > 3).count() as u32, + (s64 >> 32) as u32, + ]; + for (i, &w) in want.iter().enumerate() { + assert_eq!(outv(&r, i)[l], w, "wave op #{i} lane {l}"); + } + let n = want.len(); + let fsum: f32 = fs.iter().sum(); + assert!((f32::from_bits(outv(&r, n)[l]) - fsum).abs() < 1e-3, "float sum"); + assert_eq!(f32::from_bits(outv(&r, n + 1)[l]), 16.5, "float max"); + let fp: f32 = fs[..l].iter().sum(); + assert!((f32::from_bits(outv(&r, n + 2)[l]) - fp).abs() < 1e-3, "float prefix lane {l}"); + } +} + +// ------------------------------------------------------------ derivatives + +#[test] +fn derivatives_in_compute_run() { + // SM 6.6 compute derivatives: with numthreads (8, 4, 1) quads are 2×2 + // blocks in thread-ID space. + let mut k = kernel(); + let x = k.s.thread_id_in_group(0); + let y = k.s.thread_id_in_group(1); + let f32 = k.s.m.f32(); + let fx = k.s.m.cast(CastOp::UIToFP, x, f32); + let fy = k.s.m.cast(CastOp::UIToFP, y, f32); + // f = x*x + 10*y*x + let xx = k.s.m.fbin(BinOp::Mul, fx, fx, 0); + let ten = k.s.m.f32c(10.0f32.to_bits()); + let ty = k.s.m.fbin(BinOp::Mul, fy, ten, 0); + let txy = k.s.m.fbin(BinOp::Mul, ty, fx, 0); + let f = k.s.m.fbin(BinOp::Add, xx, txy, 0); + for (i, d) in [Deriv::CoarseX, Deriv::CoarseY, Deriv::FineX, Deriv::FineY].into_iter().enumerate() { + let v = k.s.deriv(d, f); + k.out(i as u32, v); + } + let c = k.finish([8, 4, 1]); + let Some(r) = gpu(&c, &[0; 64], &[], &[]) else { return }; + let fv = |x: usize, y: usize| (x * x + 10 * y * x) as f32; + for l in 0..32 { + let (x, y) = (l % 8, l / 8); + let (qx, qy) = (x & !1, y & !1); + let fine_x = fv(qx + 1, y) - fv(qx, y); + let fine_y = fv(x, qy + 1) - fv(x, qy); + let got = |i: usize| f32::from_bits(outv(&r, i)[l]); + assert_eq!(got(2), fine_x, "ddx_fine lane {l}"); + assert_eq!(got(3), fine_y, "ddy_fine lane {l}"); + // coarse: any row / column of the quad (implementation-defined) + assert!([fv(qx + 1, qy) - fv(qx, qy), fv(qx + 1, qy + 1) - fv(qx, qy + 1)].contains(&got(0)), "ddx_coarse lane {l}"); + assert!([fv(qx, qy + 1) - fv(qx, qy), fv(qx + 1, qy + 1) - fv(qx + 1, qy)].contains(&got(1)), "ddy_coarse lane {l}"); + } +} + +fn f16_to_f32(h: u16) -> f32 { + let (s, e, m) = ((h >> 15) as u32, ((h >> 10) & 31) as i32, (h & 0x3ff) as u32); + let mag = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 => if m == 0 { f32::INFINITY } else { f32::NAN }, + _ => (1.0 + m as f32 / 1024.0) * 2f32.powi(e - 15), + }; + if s == 1 { -mag } else { mag } +} + +/// f32 → f16 bits, rounding to nearest even or towards zero (NaN not handled). +fn f32_to_f16(x: f32, rtz: bool) -> u16 { + let sign = if x.is_sign_negative() { 0x8000u16 } else { 0 }; + let a = x.abs(); + if a.is_infinite() || a >= 65520.0 || (!rtz && a >= 65520.0) { + return sign | if rtz && a.is_finite() { 0x7bff } else { 0x7c00 }; + } + // Scale to units of the result's ULP and round half to even. + let e = if a < 2f32.powi(-14) { -14 } else { a.log2().floor() as i32 }; + let ulp = 2f64.powi(e - 10); + let q = if rtz { (a as f64 / ulp).floor() } else { (a as f64 / ulp).round_ties_even() } as u32; + let (e, q) = if q >= 2048 { (e + 1, q / 2) } else { (e, q) }; + if q < 1024 { + sign | q as u16 // subnormal (e == -14) + } else { + sign | (((e + 15) as u16) << 10) | (q as u16 & 0x3ff) + } +} + +#[test] +fn double_unary_legality_matches_dxil_tables() { + if !validate::validator_supported() { + return validate::skip_validation(); + } + // Which float unary ops take an f64 overload (DXIL.rst: FAbs, Saturate only). + let all = [ + FUnary::FAbs, FUnary::Saturate, FUnary::Cos, FUnary::Sin, FUnary::Exp, FUnary::Frc, FUnary::Log, FUnary::Sqrt, FUnary::Rsqrt, FUnary::RoundNe, + FUnary::RoundNi, FUnary::RoundPi, FUnary::RoundZ, + ]; + let mut legal = Vec::new(); + for op in all { + let mut k = kernel(); + let lo = k.input(0); + let d = k.s.make_double(lo, lo); + let r = k.s.funary(op, d); + let (a, _) = k.s.split_double(r); + k.out(0, a); + if validate::validate(&k.s.finish([32, 1, 1], Some(32))).is_ok() { + legal.push(op); + } + } + assert_eq!(legal, DOUBLE_UNARY); +} + +#[test] +fn int64_bit_ops_match_cpu() { + let mut k = kernel(); + let lo = k.input(0); + let hi = k.input(1); + let i64 = k.s.m.i64(); + let i32 = k.s.m.i32(); + let l64 = k.s.m.cast(CastOp::ZExt, lo, i64); + let h64 = k.s.m.cast(CastOp::ZExt, hi, i64); + let sh = k.s.m.const_int(i64, 32); + let h64 = k.s.m.bin(BinOp::Shl, h64, sh); + let v = k.s.m.bin(BinOp::Or, h64, l64); + let mut outs = vec![]; + for op in [BitCount::Countbits, BitCount::FirstbitLo, BitCount::FirstbitHi] { + outs.push(k.s.bit_count(op, v)); + } + let rev = k.s.bfrev(v); + outs.push(k.s.m.cast(CastOp::Trunc, rev, i32)); + let mx = k.s.binary(Binary::UMax, v, h64); + let mx = { let c = k.s.m.const_int(i64, 32); k.s.m.bin(BinOp::LShr, mx, c) }; + outs.push(k.s.m.cast(CastOp::Trunc, mx, i32)); + for (i, &o) in outs.iter().enumerate() { + k.out(i as u32, o); + } + let c = k.finish([32, 1, 1]); + let his: Vec = UVALS.iter().map(|v| v.rotate_right(9) & 0x00ff_ffff).collect(); + let Some(r) = gpu(&c, &mem_of(&[UVALS.to_vec(), his.clone()]), &[], &[]) else { return }; + for l in 0..32 { + let v = UVALS[l] as u64 | (his[l] as u64) << 32; + let want = [ + v.count_ones(), + if v == 0 { u32::MAX } else { v.trailing_zeros() }, + if v == 0 { u32::MAX } else { v.leading_zeros() }, + v.reverse_bits() as u32, + his[l], + ]; + for (i, &w) in want.iter().enumerate() { + assert_eq!(outv(&r, i)[l], w, "i64 op #{i} of {v:#x}"); + } + } +} + +#[test] +fn uav_array_3d_stores_loads_and_texture_atomics_run() { + // u: heap 3 = RWTexture2DArray 4×4×2, heap 5 = RWTexture3D 4×4×2. + let mut k = kernel(); + let i1 = k.s.m.i32c(3); + let i3 = k.s.m.i32c(5); + let ua = k.s.heap_texture(i1, TexKind::D2Array, true, CompType::U32, 1, false); + let u3 = k.s.heap_texture(i3, TexKind::D3, true, CompType::F32, 1, false); + let lane = k.lane; + let c3 = k.s.m.i32c(3); + let c2 = k.s.m.i32c(2); + let x = k.s.m.bin(BinOp::And, lane, c3); + let y = k.s.m.bin(BinOp::LShr, lane, c2); + let y = k.s.m.bin(BinOp::And, y, c3); + let z = { let c = k.s.m.i32c(4); k.s.m.bin(BinOp::LShr, lane, c) }; + let old = k.s.texture_load(ua, None, &[x, y, z], &[])[0]; + k.s.texture_store(ua, &[x, y, z], [lane, lane, lane, lane]); + let f32 = k.s.m.f32(); + let fl = k.s.m.cast(CastOp::UIToFP, lane, f32); + k.s.texture_store(u3, &[x, y, z], [fl, fl, fl, fl]); + k.s.barrier(barrier::UAV_FENCE_THREAD_GROUP | barrier::SYNC_THREAD_GROUP); + // Every lane adds 1 to texel (0, 0, 1) and swaps texel (1, 0, 1) if it holds 17. + let zero = k.s.m.i32c(0); + let one = k.s.m.i32c(1); + let before = k.s.atomic_binop(ua.handle, AtomicOp::Add, &[zero, zero, one], one); + let c17 = k.s.m.i32c(17); + let c99 = k.s.m.i32c(99); + let cx = k.s.atomic_cmpxchg(ua.handle, &[one, zero, one], c17, c99); + k.out(0, old); + k.out(1, before); + k.out(2, cx); + let c = k.finish([32, 1, 1]); + let mk = |dim, format, data: Vec| runner::TestTexture { dim, format, width: 4, height: 4, depth: 2, texel_bytes: 4, data, uav: true }; + let init: Vec = (0..32).map(|i| 1000 + i).collect(); + let tex = [ + ftex(runner::TexDim::D2, 1, 1, 1), + mk(runner::TexDim::D2Array, DXGI_FORMAT_R32_UINT, init.iter().flat_map(|v| v.to_le_bytes()).collect()), + mk(runner::TexDim::D3, DXGI_FORMAT_R32_FLOAT, vec![0; 128]), + ]; + let Some(r) = gpu(&c, &[0; 64], &tex, &[]) else { return }; + assert_eq!(outv(&r, 0), &init[..], "loads before stores"); + let mut before: Vec = outv(&r, 1).to_vec(); + before.sort(); + assert_eq!(before, (16..48).collect::>(), "atomic add sees 16, 17, … in some order"); + let arr: Vec = r.textures[0].chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + assert_eq!(arr[16], 16 + 32); + assert_eq!(arr[17], 99); + assert_eq!(outv(&r, 2).iter().filter(|&&v| v == 17).count(), 1); + let vol: Vec = r.textures[1].chunks(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect(); + assert_eq!(vol, (0..32).map(|i| i as f32).collect::>()); +} + +#[test] +fn half_precision_overloads_run() { + // Native 16-bit floats (SM 6.2+ `-enable-16bit-types`). + let mut k = kernel(); + k.s.require(super::shader::Feature::NativeLowPrecision); + let a = k.input_f(0); + let b = k.input_f(1); + let f16 = k.s.m.f16(); + let f32 = k.s.m.f32(); + let ha = k.s.m.cast(CastOp::FPTrunc, a, f16); + let hb = k.s.m.cast(CastOp::FPTrunc, b, f16); + let mx = k.s.binary(Binary::FMax, ha, hb); + let fl = k.s.funary(FUnary::RoundNi, ha); + let ab = k.s.funary(FUnary::FAbs, hb); + let mad = k.s.tertiary(Tertiary::FMad, ha, hb, ab); + // (f16 isSpecialFloat needs SM 6.9.) + let nan = k.s.fclass(FClass::IsNaN, a); + // Reduce `ha`, not `ab`: AMD's driver (RDNA4, 32.0.3xxxx) drops an + // `FAbs.f16` feeding `WaveActiveMax.f16` (it returns max(y), 5.0, for + // max(|y|), 10.5); DXC's own DXIL for the HLSL does the same. `ab` is + // checked on its own above. + let sum = k.s.wave_active_op(ha, WaveOp::Max, false); + for (i, v) in [mx, fl, ab, mad, sum].into_iter().enumerate() { + let e = k.s.m.cast(CastOp::FPExt, v, f32); + k.out(i as u32, e); + } + k.out(5, nan); + let c = k.finish([32, 1, 1]); + let xs: Vec = (0..32).map(|l| l as f32 * 0.75 - 9.0).collect(); + let ys: Vec = (0..32).map(|l| 5.0 - l as f32 * 0.5).collect(); + let Some(r) = gpu(&c, &mem_of(&[xs.iter().map(|f| f.to_bits()).collect(), ys.iter().map(|f| f.to_bits()).collect()]), &[], &[]) else { return }; + let xmax = xs.iter().fold(f32::MIN, |m, &x| m.max(x)); + for l in 0..32 { + let (x, y) = (xs[l], ys[l]); // all exactly representable in f16 + let got = |i: usize| f32::from_bits(outv(&r, i)[l]); + assert_eq!(got(0), x.max(y)); + assert_eq!(got(1), x.floor()); + assert_eq!(got(2), y.abs()); + assert!((got(3) - (x * y + y.abs())).abs() <= 0.05, "half mad {x} {y}: {}", got(3)); + assert_eq!(got(4), xmax, "half wave max"); + assert_eq!(outv(&r, 5)[l], 0); + } +} + +/// Every literal `op(, "", .., FnAttrs::)` in the backend +/// declares the attributes DXC uses for that opcode (table in +/// `shader::dxc_fn_attrs`, from DXC 1.9 `-Fc` listings). +#[test] +fn dx_op_attrs_match_dxc() { + use super::module::FnAttrs; + let srcs = [include_str!("ops.rs"), include_str!("graphics.rs"), include_str!("lower_image.rs"), include_str!("shader.rs")]; + let mut n = 0; + for src in srcs { + for (i, _) in src.match_indices("op(") { + let rest = &src[i + 3..]; + let Some((num, rest)) = rest.split_once(", \"") else { continue }; + let Ok(op) = num.trim().parse::() else { continue }; + let Some(end) = rest.find(')') .and_then(|_| rest.find("FnAttrs::")) else { continue }; + if rest[..end].contains(';') { + continue; + } + let a = &rest[end + 9..]; + let a: String = a.chars().take_while(|c| c.is_alphanumeric()).collect(); + let got = match a.as_str() { + "ReadNone" => FnAttrs::ReadNone, + "ReadOnly" => FnAttrs::ReadOnly, + "NoUnwind" => FnAttrs::NoUnwind, + "NoDuplicate" => FnAttrs::NoDuplicate, + _ => FnAttrs::None, + }; + let want = super::shader::dxc_fn_attrs(op).unwrap_or_else(|| panic!("opcode {op} missing from dxc_fn_attrs")); + assert_eq!(got, want, "opcode {op}: {}", &rest[..rest.find('"').unwrap_or(0)]); + n += 1; + } + } + assert!(n > 50, "only {n} declarations found"); +} diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs new file mode 100644 index 000000000..a171fd099 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -0,0 +1,488 @@ +//! The recompiler's HLSL helper functions (`recomp/emit.rs` `PRELUDE`) as +//! DXIL builders, operation for operation (the HLSL intrinsics as DXC lowers +//! them), so both backends compute the same bits. + +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use super::ops_core::op; + +impl Lw { + /// `cvt_u32`: NaN / ≤ 0 → 0, ≥ 2^32 → 0xFFFFFFFF. + pub fn cvt_u32(&mut self, f: Value) -> Value { + let n = self.isnan(f); + let z = self.fc(0.0); + let le = self.fcmp(Pred::FOLe, f, z); + let low = self.lor(n, le); + let big = self.fc(4294967296.0); + let ge = self.fcmp(Pred::FOGe, f, big); + let v = self.ftoui(f); + let v = self.selc(ge, u32::MAX, v); + self.selc(low, 0, v) + } + /// `cvt_i32`: NaN → 0, saturating. + pub fn cvt_i32(&mut self, f: Value) -> Value { + let n = self.isnan(f); + let lo = self.fc(-2147483648.0); + let hi = self.fc(2147483648.0); + let le = self.fcmp(Pred::FOLe, f, lo); + let ge = self.fcmp(Pred::FOGe, f, hi); + let v = self.ftosi(f); + let v = self.selc(ge, 0x7FFF_FFFF, v); + let v = self.selc(le, 0x8000_0000, v); + self.selc(n, 0, v) + } + /// `f32tof16(e) & 0xFFFF` + /// The recompiler's `to_f16_expr`: `f32tof16(e) & 0xFFFF`, or under a program-set + /// MODE[3:2] the software conversion with the current mode. + pub fn to_f16(&mut self, e: Value) -> Value { + if self.dyn_rm { + let rm = self.rd(super::lower::VAR_FP16_RM); + return self.f32_to_f16_rm(e, rm); + } + let h = self.s.f32_to_f16(e); + self.andc(h, 0xFFFF) + } + /// `f16_rtz`: binary16 rounded toward zero. + pub fn f16_rtz(&mut self, f: Value) -> Value { + let h = self.s.f32_to_f16(f); + let h = self.andc(h, 0xFFFF); + let n = self.isnan(f); + let nn = self.lnot(n); + let mag = self.andc(h, 0x7FFF); + let nz = self.nz(mag); + let back = self.s.f16_to_f32(h); + let ab = self.fabs(back); + let af = self.fabs(f); + let gt = self.fcmp(Pred::FOGt, ab, af); + let c = self.land(nn, nz); + let c = self.land(c, gt); + let one = self.u(c); + self.sub(h, one) + } + /// `fract_f`: x - floor(x), below 1.0. + pub fn fract_f(&mut self, x: Value) -> Value { + let fl = self.un(op::ROUND_NI, x); + let r = self.fsub(x, fl); + let one = self.fc(1.0); + let ge = self.fcmp(Pred::FOGe, r, one); + let k = self.s.m.f32c(0x3F7F_FFFF); + self.sel(ge, k, r) + } + /// HLSL `frexp` as DXC lowers it: (mantissa, exponent as float). + fn frexp_dxc(&mut self, x: Value) -> (Value, Value) { + let i = self.bits(x); + let e = self.andc(i, 0x7F80_0000); + let mant = self.andc(i, 0x007F_FFFF); // DXC drops the sign + let e = self.addc(e, (-0x3F00_0000i32) as u32); + let e = self.ashrc(e, 23); + let mant = self.orc(mant, 0x3F00_0000); + let z = self.fc(0.0); + let nz = self.fcmp(Pred::FUNe, x, z); + let ef = self.sitof(e); + let ef = self.sel(nz, ef, z); + let mf = self.f(mant); + let mf = self.sel(nz, mf, z); + (mf, ef) + } + pub fn frexp_mant(&mut self, x: Value) -> Value { + let (m, _) = self.frexp_dxc(x); + let a = self.isinf(x); + let b = self.isnan(x); + let s = self.lor(a, b); + self.sel(s, x, m) + } + pub fn frexp_exp(&mut self, x: Value) -> Value { + let (_, e) = self.frexp_dxc(x); + let a = self.isinf(x); + let b = self.isnan(x); + let s = self.lor(a, b); + let ei = self.ftosi(e); + self.selc(s, 0, ei) + } + /// `ldexp_f`: exact x · 2^n on the bits. + pub fn ldexp_f(&mut self, x: Value, n: Value) -> Value { + let u = self.bits(x); + let sign = self.andc(u, 0x8000_0000); + let e8 = self.lshrc(u, 23); + let exp = self.andc(e8, 0xFF); + let mant = self.andc(u, 0x7F_FFFF); + // exp == 0xFF or (exp == 0 and mant == 0): x + let special = self.cmpc(Pred::Eq, exp, 0xFF); + let ez = self.cmpc(Pred::Eq, exp, 0); + let mz = self.cmpc(Pred::Eq, mant, 0); + let zero = self.land(ez, mz); + let keep = self.lor(special, zero); + // denormal: normalise + let top = self.firstbithigh(mant); + let k23 = self.c(23); + let sh = self.sub(k23, top); + let nm = self.shl(mant, sh); + let nm = self.andc(nm, 0x7F_FFFF); + let k22 = self.c(22); + let ne = self.sub(top, k22); + let mant = self.sel(ez, nm, mant); + let e = self.sel(ez, ne, exp); + let lo = self.c(-500i32 as u32); + let hi = self.c(500); + let nc = self.imax(n, lo); + let nc = self.imin(nc, hi); + let eo = self.add(e, nc); + // eo >= 255: inf + let inf = self.cmpc(Pred::SGe, eo, 255); + let infv = self.orc(sign, 0x7F80_0000); + // eo >= 1: normal + let norm = self.cmpc(Pred::SGe, eo, 1); + let eb = self.shlc(eo, 23); + let nv = self.or(sign, eb); + let nv = self.or(nv, mant); + // denormal result + let one = self.c(1); + let shd = self.sub(one, eo); + let tiny = self.cmpc(Pred::UGt, shd, 24); + let sig = self.orc(mant, 0x80_0000); + let shc = { let k = self.c(31); self.umin(shd, k) }; + let q = self.bin(BinOp::LShr, sig, shc); + let shm1 = self.sub(shc, one); + let shm1 = self.andc(shm1, 31); + let half = self.bin(BinOp::Shl, one, shm1); + let full = self.bin(BinOp::Shl, one, shc); + let rm = self.sub(full, one); + let rem = self.and(sig, rm); + let gt = self.cmp(Pred::UGt, rem, half); + let eqh = self.cmp(Pred::Eq, rem, half); + let odd = self.andc(q, 1); + let odd = self.nz(odd); + let tie = self.land(eqh, odd); + let inc = self.lor(gt, tie); + let incv = self.u(inc); + let qd = self.add(q, incv); + let dv = self.or(sign, qd); + let dv = self.sel(tiny, sign, dv); + let r = self.sel(norm, nv, dv); + let r = self.sel(inf, infv, r); + let r = self.sel(keep, u, r); + self.f(r) + } + /// `mul_legacy`: 0 · anything = 0. + pub fn mul_legacy(&mut self, a: Value, b: Value) -> Value { + let z = self.fc(0.0); + let az = self.fcmp(Pred::FOEq, a, z); + let bz = self.fcmp(Pred::FOEq, b, z); + let c = self.lor(az, bz); + let p = self.fmul(a, b); + self.sel(c, z, p) + } + /// `mad_nf`: separately rounded multiply and add (`precise`). + pub fn mad_nf(&mut self, a: Value, b: Value, c: Value) -> Value { + let p = self.fmul(a, b); + self.fadd(p, c) + } + /// `fma_legacy`: (a == 0 || b == 0) ? c : mad(a, b, c). + pub fn fma_legacy(&mut self, a: Value, b: Value, c: Value) -> Value { + let z = self.fc(0.0); + let az = self.fcmp(Pred::FOEq, a, z); + let bz = self.fcmp(Pred::FOEq, b, z); + let cnd = self.lor(az, bz); + let m = self.fmad(a, b, c); + self.sel(cnd, c, m) + } + pub fn med3f(&mut self, a: Value, b: Value, c: Value) -> Value { + let x = self.fmin(a, b); + let y = self.fmax(a, b); + let y = self.fmin(y, c); + self.fmax(x, y) + } + /// `div_fixup` + pub fn div_fixup(&mut self, q: Value, d: Value, n: Value) -> Value { + let a = self.isnan(d); + let b = self.isnan(n); + let z = self.fc(0.0); + let dz = self.fcmp(Pred::FOEq, d, z); + let di = self.isinf(d); + let ni = self.isinf(n); + let x = self.lor(a, b); + let y = self.lor(di, ni); + let y = self.lor(dz, y); + let c = self.lor(x, y); + let r = self.fdiv(n, d); + self.sel(c, r, q) + } + /// cube_id / cube_sc / cube_tc / cube_ma + pub fn cube(&mut self, name: &str, x: Value, y: Value, z: Value) -> Value { + let (ax, ay, az) = (self.fabs(x), self.fabs(y), self.fabs(z)); + let zx = self.fcmp(Pred::FOGe, az, ax); + let zy = self.fcmp(Pred::FOGe, az, ay); + let zmaj = self.land(zx, zy); + let ymaj = self.fcmp(Pred::FOGe, ay, ax); + let zero = self.fc(0.0); + let zneg = self.fcmp(Pred::FOLt, z, zero); + let yneg = self.fcmp(Pred::FOLt, y, zero); + let xneg = self.fcmp(Pred::FOLt, x, zero); + let (zr, yr, xr) = match name { + "v_cubeid_f32" => { + let (f5, f4, f3, f2, f1, f0) = (self.fc(5.0), self.fc(4.0), self.fc(3.0), self.fc(2.0), self.fc(1.0), self.fc(0.0)); + (self.sel(zneg, f5, f4), self.sel(yneg, f3, f2), self.sel(xneg, f1, f0)) + } + "v_cubesc_f32" => { + let nx = self.fneg(x); + let nz = self.fneg(z); + (self.sel(zneg, nx, x), x, self.sel(xneg, z, nz)) + } + "v_cubetc_f32" => { + let ny = self.fneg(y); + let nz = self.fneg(z); + (ny, self.sel(yneg, nz, z), ny) + } + _ => { + let two = self.fc(2.0); + (self.fmul(two, z), self.fmul(two, y), self.fmul(two, x)) + } + }; + let r = self.sel(ymaj, yr, xr); + self.sel(zmaj, zr, r) + } + /// `i24`: sign-extended low 24 bits. + pub fn i24(&mut self, v: Value) -> Value { + let s = self.shlc(v, 8); + self.ashrc(s, 8) + } + pub fn alignbit(&mut self, s0: Value, s1: Value, s: Value) -> Value { + let s = self.andc(s, 31); + let a = self.bin(BinOp::LShr, s1, s); + let k = self.c(32); + let t = self.sub(k, s); + let t = self.andc(t, 31); + let b = self.bin(BinOp::Shl, s0, t); + let r = self.or(a, b); + let z = self.cmpc(Pred::Eq, s, 0); + self.sel(z, s1, r) + } + pub fn perm_b32(&mut self, s0: Value, s1: Value, sel: Value) -> Value { + let mut r = self.c(0); + for i in 0..4u32 { + let k = self.lshrc(sel, 8 * i); + let k = self.andc(k, 0xFF); + // bytes 0..7: s1 bytes 0..3 then s0 bytes 0..3 + let lo4 = self.cmpc(Pred::ULt, k, 4); + let k3 = self.andc(k, 3); + let sh = self.shlc(k3, 3); + let w = self.sel(lo4, s1, s0); + let byte = self.bin(BinOp::LShr, w, sh); + let byte = self.andc(byte, 0xFF); + // 8..11: sign of s1 bit 15 / 31, s0 bit 15 / 31 + let b15 = self.lshrc(s1, 15); + let b31 = self.lshrc(s1, 31); + let c15 = self.lshrc(s0, 15); + let c31 = self.lshrc(s0, 31); + let is8 = self.cmpc(Pred::Eq, k, 8); + let is9 = self.cmpc(Pred::Eq, k, 9); + let is10 = self.cmpc(Pred::Eq, k, 10); + let t = self.sel(is10, c15, c31); + let t = self.sel(is9, b31, t); + let t = self.sel(is8, b15, t); + let t = self.andc(t, 1); + let tn = self.nz(t); + let ff = self.c(0xFF); + let z = self.c(0); + let sgn = self.sel(tn, ff, z); + let ge8 = self.cmpc(Pred::UGe, k, 8); + let b = self.sel(ge8, sgn, byte); + let is12 = self.cmpc(Pred::Eq, k, 12); + let b = self.sel(is12, z, b); + let ge13 = self.cmpc(Pred::UGe, k, 13); + let b = self.sel(ge13, ff, b); + let b = self.shlc(b, 8 * i); + r = self.or(r, b); + } + r + } + /// |a[k..] - b[k..]| of one byte / half (`absd8` / `absd16`). + pub fn absd(&mut self, a: Value, b: Value, k: u32, mask: u32) -> Value { + let x = self.lshrc(a, k); + let x = self.andc(x, mask); + let y = self.lshrc(b, k); + let y = self.andc(y, mask); + let hi = self.umax(x, y); + let lo = self.umin(x, y); + self.sub(hi, lo) + } + pub fn sad_u8(&mut self, a: Value, b: Value) -> Value { + let mut r = self.absd(a, b, 0, 0xFF); + for k in [8, 16, 24] { + let x = self.absd(a, b, k, 0xFF); + r = self.add(r, x); + } + r + } + pub fn msad_u8(&mut self, a: Value, b: Value) -> Value { + let mut r = self.c(0); + for k in [0, 8, 16, 24] { + let x = self.absd(a, b, k, 0xFF); + let bb = self.lshrc(b, k); + let bb = self.andc(bb, 0xFF); + let nz = self.nz(bb); + let z = self.c(0); + let x = self.sel(nz, x, z); + r = self.add(r, x); + } + r + } + pub fn lerp_u8(&mut self, a: Value, b: Value, c: Value) -> Value { + let mut r = self.c(0); + for k in [0, 8, 16, 24] { + let x = self.lshrc(a, k); + let x = self.andc(x, 0xFF); + let y = self.lshrc(b, k); + let y = self.andc(y, 0xFF); + let z = self.lshrc(c, k); + let z = self.andc(z, 1); + let s = self.add(x, y); + let s = self.add(s, z); + let s = self.lshrc(s, 1); + let s = self.shlc(s, k); + r = self.or(r, s); + } + r + } + /// `sat_i32` of an i64. + pub fn sat_i32(&mut self, r: Value) -> Value { + let hi = self.c64(0x7FFF_FFFF); + let lo = self.c64(0xFFFF_FFFF_8000_0000); + let over = self.cmp(Pred::SGt, r, hi); + let under = self.cmp(Pred::SLt, r, lo); + let t = self.trunc32(r); + let t = self.selc(under, 0x8000_0000, t); + self.selc(over, 0x7FFF_FFFF, t) + } + /// `cvt_norm_i16_f32`: round(clamp(nan ? 0 : f, -1, 1) * 32767) & 0xFFFF. + pub fn cvt_norm_i16_f32(&mut self, f: Value) -> Value { + let n = self.isnan(f); + let z = self.fc(0.0); + let x = self.sel(n, z, f); + let (lo, hi) = (self.fc(-1.0), self.fc(1.0)); + let x = self.fmax(x, lo); + let x = self.fmin(x, hi); + let k = self.fc(32767.0); + let x = self.fmul(x, k); + let x = self.un(op::ROUND_NE, x); + let i = self.ftosi(x); + self.andc(i, 0xFFFF) + } + /// `(uint)round(saturate(f) * 65535.0f)` + pub fn cvt_norm_u16_f32(&mut self, f: Value) -> Value { + let x = self.un(op::SATURATE, f); + let k = self.fc(65535.0); + let x = self.fmul(x, k); + let x = self.un(op::ROUND_NE, x); + self.ftoui(x) + } + /// `cvt_norm_f16`: exact binary16 → unorm / snorm magnitude. + fn cvt_norm_f16(&mut self, h: Value, scale: u32) -> Value { + let mag = self.andc(h, 0x7FFF); + let nan = self.cmpc(Pred::UGt, mag, 0x7C00); + let e = self.lshrc(h, 10); + let exp = self.andc(e, 0x1F); + let frac = self.andc(h, 0x3FF); + let big = self.cmpc(Pred::UGe, exp, 15); + let ez = self.cmpc(Pred::Eq, exp, 0); + let im = self.orc(frac, 1024); + let m = self.sel(ez, frac, im); + let k25 = self.c(25); + let s1 = self.sub(k25, exp); + let s = self.selc(ez, 24, s1); + let s = self.andc(s, 31); + let k = self.c(scale); + let prod = self.mul(m, k); + let q = self.bin(BinOp::LShr, prod, s); + let one = self.c(1); + let full = self.bin(BinOp::Shl, one, s); + let msk = self.sub(full, one); + let rem = self.and(prod, msk); + let sm1 = self.sub(s, one); + let sm1 = self.andc(sm1, 31); + let half = self.bin(BinOp::Shl, one, sm1); + let gt = self.cmp(Pred::UGt, rem, half); + let eq = self.cmp(Pred::Eq, rem, half); + let odd = self.andc(q, 1); + let odd = self.nz(odd); + let tie = self.land(eq, odd); + let inc = self.lor(gt, tie); + let inc = self.u(inc); + let r = self.add(q, inc); + let r = self.selc(big, scale, r); + self.selc(nan, 0, r) + } + pub fn cvt_norm_u16_f16(&mut self, h: Value) -> Value { + let r = self.cvt_norm_f16(h, 65535); + let s = self.andc(h, 0x8000); + let neg = self.nz(s); + self.selc(neg, 0, r) + } + pub fn cvt_norm_i16_f16(&mut self, h: Value) -> Value { + let r = self.cvt_norm_f16(h, 32767); + let s = self.andc(h, 0x8000); + let neg = self.nz(s); + let z = self.c(0); + let n = self.sub(z, r); + let v = self.sel(neg, n, r); + self.andc(v, 0xFFFF) + } + /// `fclass16`: the class bit index of a binary16 value. + pub fn fclass16(&mut self, h: Value) -> Value { + let e = self.lshrc(h, 10); + let e = self.andc(e, 0x1F); + let m = self.andc(h, 0x3FF); + let s = self.andc(h, 0x8000); + self.fclass_parts(e, 0x1F, m, 0x200, s) + } + /// `fclass`: the class bit index of a binary32 value. + pub fn fclass(&mut self, f: Value) -> Value { + let u = self.bits(f); + let e = self.lshrc(u, 23); + let e = self.andc(e, 0xFF); + let m = self.andc(u, 0x7F_FFFF); + let s = self.lshrc(u, 31); + self.fclass_parts(e, 0xFF, m, 0x40_0000, s) + } + /// class bit index from the exponent field, its all-ones value, mantissa != 0, + /// the quiet bit and the sign + pub fn fclass_bits(&mut self, e: Value, emax: u32, mnz: Value, qn: Value, n: Value) -> Value { + let (c0, c1, c2, c3, c4, c5, c6, c7, c8, c9) = (self.c(0), self.c(1), self.c(2), self.c(3), self.c(4), self.c(5), self.c(6), self.c(7), self.c(8), self.c(9)); + let nanc = self.sel(qn, c1, c0); + let infc = self.sel(n, c2, c9); + let special = self.sel(mnz, nanc, infc); + let zc = self.sel(n, c5, c6); + let dc = self.sel(n, c4, c7); + let zero = self.sel(mnz, dc, zc); + let normal = self.sel(n, c3, c8); + let ez = self.cmpc(Pred::Eq, e, 0); + let emx = self.cmpc(Pred::Eq, e, emax); + let r = self.sel(ez, zero, normal); + self.sel(emx, special, r) + } + fn fclass_parts(&mut self, e: Value, emax: u32, m: Value, quiet: u32, sign: Value) -> Value { + let n = self.nz(sign); + let mnz = self.nz(m); + let q = self.andc(m, quiet); + let qn = self.nz(q); + self.fclass_bits(e, emax, mnz, qn, n) + } + /// `isnan_d` from the bits. + pub fn isnan_d(&mut self, x: Value) -> Value { + let (l, h) = self.s.split_double(x); + let h = self.andc(h, 0x7FFF_FFFF); + let gt = self.cmpc(Pred::UGt, h, 0x7FF0_0000); + let eq = self.cmpc(Pred::Eq, h, 0x7FF0_0000); + let lnz = self.nz(l); + let e = self.land(eq, lnz); + self.lor(gt, e) + } + /// `isinf_d` from the bits. + pub fn isinf_d(&mut self, x: Value) -> Value { + let (l, h) = self.s.split_double(x); + let h = self.andc(h, 0x7FFF_FFFF); + let eq = self.cmpc(Pred::Eq, h, 0x7FF0_0000); + let lz = self.cmpc(Pred::Eq, l, 0); + self.land(eq, lz) + } +} diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs new file mode 100644 index 000000000..46a06c63d --- /dev/null +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -0,0 +1,233 @@ +//! Determinism of the direct translator (same input → byte-identical containers, in +//! separate translator instances and threads) and builder misuse reported as errors. + +use super::kernel::{self, KernelOptions}; +use crate::gpu::dxbc::SigElement as S; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::{CsInterface, PsInterface, VsInterface}; + +fn prog(list: &[(&str, &str, &[(&str, u64)], Option)]) -> Vec { + let mut v = Vec::new(); + for (n, e, f, l) in list { + v.extend(encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))); + } + v.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + v +} + +fn el(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> S { + S { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } +} + +/// Programs touching many registers (hash-map keyed state), branches, guarded memory, +/// LDS, cross-lane reads, and VS / PS signatures. +fn translate_all() -> Vec> { + const V: u64 = 256; + let branchy = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 138)], None), + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)], None), + ("S_SUB_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 0)], None), + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)], None), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 106)], None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 8)], None), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 5), ("VSRC1", 2)], None), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 30), ("SRC0", V + 10), ("SRC1", 129)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 20)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", 30)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", 31)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 14), ("SRC0", 32)], None), + ]); + let vs_code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ("EXP", "ENC_EXP", &[("TGT", 32), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 9), ("VSRC2", 10), ("VSRC3", 11)], None), + ("EXP", "ENC_EXP", &[("TGT", 33), ("EN", 0x3), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 0), ("VSRC3", 0)], None), + ]); + let vsi = VsInterface { + inputs: vec![el("POSITION", 0, 0, 3, 0, 3), el("COLOR", 0, 0, 3, 1, 0xF)], + outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF), el("TEXCOORD", 3, 0, 3, 2, 0x3)], + attr_base: 4, + params: None, + }; + let ps_code = prog(&[ + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 4), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 0)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 5), ("VSRC", 1), ("ATTR", 0), ("ATTRCHAN", 1)], None), + ("V_INTERP_P2_F32", "ENC_VINTRP", &[("VDST", 6), ("VSRC", 1), ("ATTR", 1), ("ATTRCHAN", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None), + ]); + let psi = PsInterface { + inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("COLOR", 0, 0, 3, 1, 0xF), el("TEXCOORD", 3, 0, 3, 2, 0x3)], + outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: None, + }; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let mut out = Vec::new(); + for (w, s) in [(false, false), (true, true), (true, false)] { + out.push(kernel::translate(&branchy, o(w, s)).expect("kernel")); + out.push(kernel::translate_compute(&branchy, o(w, s), &cs).expect("compute").dxil); + } + out.push(kernel::translate_vertex(&vs_code, o(true, false), &vsi).expect("vs").dxil); + out.push(kernel::translate_pixel(&ps_code, o(true, false), &psi).expect("ps").dxil); + out +} + +#[test] +fn translation_is_byte_identical_across_runs_and_threads() { + let first = translate_all(); + for _ in 0..3 { + assert!(translate_all() == first, "a second translation differs"); + } + let threads: Vec<_> = (0..4).map(|_| std::thread::Builder::new().stack_size(64 << 20).spawn(translate_all).unwrap()).collect(); + for t in threads { + assert!(t.join().unwrap() == first, "a translation on another thread differs"); + } +} + +// ---- builder misuse: recorded as the first error, finish fails instead of panicking + +use super::container::Stage; +use super::module::{BinOp, FnAttrs, Module}; +use super::shader::Shader; + +/// A compute shader with `misuse` applied fails to finish with an error containing `want`. +fn finish_fails(want: &str, misuse: impl FnOnce(&mut Shader)) { + let mut s = Shader::new(Stage::Compute, (6, 6)); + misuse(&mut s); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| s.try_finish([1, 1, 1], None))); + let e = r.expect("try_finish panicked").expect_err("misuse was not reported"); + assert!(e.contains(want), "error {e:?} does not name {want:?}"); +} + +#[test] +fn forward_reference_outside_a_phi_is_an_error() { + finish_fails("forward reference", |s| { + let later = s.m.new_block(); + let entry = s.m.current_block(); + s.m.set_block(later); + let one = s.m.i32c(1); + let two = s.m.i32c(2); + let v = s.m.bin(BinOp::Add, one, two); + s.m.ret(); + s.m.set_block(entry); + let _ = s.m.bin(BinOp::Add, v, one); + s.m.br(later); + }); +} + +#[test] +fn instruction_after_a_terminator_is_an_error() { + finish_fails("after a terminator", |s| { + s.m.ret(); + let one = s.m.i32c(1); + let _ = s.m.bin(BinOp::Add, one, one); + }); +} + +#[test] +fn unknown_overload_suffix_is_an_error() { + finish_fails("overload suffix", |s| { + let i32 = s.m.i32(); + let arr = s.m.array(4, i32); + let _ = s.type_suffix(arr); + }); +} + +#[test] +fn gep_and_extractvalue_into_wrong_types_are_errors() { + finish_fails("gep into", |s| { + let i32 = s.m.i32(); + let g = s.m.global("g", i32, 3, None, false, 4); + let z = s.m.i32c(0); + let _ = s.m.gep(g, &[z, z]); + }); + finish_fails("gep: struct field", |s| { + let i32 = s.m.i32(); + let st = s.m.named_struct("S", &[i32]); + let g = s.m.global("g", st, 3, None, false, 4); + let z = s.m.i32c(0); + let k = s.m.i32c(5); + let _ = s.m.gep_fields(g, &[z, k]); + }); + finish_fails("not a pointer", |s| { + let one = s.m.i32c(1); + let _ = s.m.load(one, 4); + }); + finish_fails("extractvalue", |s| { + let one = s.m.i32c(1); + let _ = s.m.extract(one, 0); + }); +} + +#[test] +fn redeclared_function_and_bad_calls_are_errors() { + finish_fails("redeclared", |s| { + let v = s.m.void(); + let i32 = s.m.i32(); + let a = s.m.func_ty(v, &[]); + let b = s.m.func_ty(v, &[i32]); + s.m.declare("f", a, FnAttrs::None); + s.m.declare("f", b, FnAttrs::None); + }); + finish_fails("arguments", |s| { + let v = s.m.void(); + let t = s.m.func_ty(v, &[]); + let f = s.m.declare("f", t, FnAttrs::None); + let one = s.m.i32c(1); + s.m.call(f, &[one]); + }); + finish_fails("second defined function", |s| { + s.m.define_entry("other"); + }); +} + +#[test] +fn bad_constants_phis_and_stores_are_errors() { + finish_fails("const_int", |s| { + let f = s.m.f32(); + s.m.const_int(f, 1); + }); + finish_fails("const_float", |s| { + let i = s.m.i32(); + s.m.const_float(i, 1); + }); + finish_fails("non-phi", |s| { + let one = s.m.i32c(1); + let v = s.m.bin(BinOp::Add, one, one); + let b = s.m.current_block(); + s.m.add_incoming(v, one, b); + }); + finish_fails("rawBufferStore of 5", |s| { + let u = s.raw_uav(0, 0); + let z = s.m.i32c(0); + s.raw_store(u, z, &[z; 5]); + }); +} + +#[test] +fn use_of_a_void_value_and_wrong_finish_are_errors() { + finish_fails("void instruction", |s| { + let u = s.raw_uav(0, 0); + let z = s.m.i32c(0); + s.raw_store(u, z, &[z]); + // the store's (void) result as an operand + let st = super::module::Value::Inst(s.m.block_insts(s.m.current_block()).last().copied().unwrap()); + let i32 = s.m.i32(); + let _ = s.m.cast(super::module::CastOp::BitCast, st, i32); + }); + let s = Shader::new(Stage::Pixel, (6, 6)); + assert!(s.try_finish([1, 1, 1], None).is_err()); + let mut m = Module::new(); + m.ret(); + m.ret(); + assert!(m.try_to_bitcode("dxil-ms-dx", "").is_err()); +} diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs new file mode 100644 index 000000000..19118e387 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -0,0 +1,577 @@ +//! A DXIL shader under construction: the [`Module`] plus what DXIL adds on +//! top of LLVM — `dx.op` intrinsics, resource handles, entry-point metadata, +//! shader flags, PSV0 — and the finished, signed container. +//! +//! Operation numbers and signatures follow DXC's `DxilOperations` tables and +//! `docs/DXIL.rst` (NCSA licence); each helper is checked against DXC output +//! and the validator in the tests. + +use std::collections::BTreeSet; + +use super::container::{self, Psv, PsvResType, PsvResource, Stage}; +use super::module::{FnAttrs, Md, Module, Ty, Value}; + +pub const TRIPLE: &str = "dxil-ms-dx"; +pub const DATALAYOUT: &str = "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64"; + +/// Optional features a shader uses; each sets a metadata shader flag and, +/// for most, a container feature bit (`SFI0`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Feature { + Doubles, + RawAndStructuredBuffers, + WaveOps, + Int64Ops, + NativeLowPrecision, + ResourceHeapIndexing, + SamplerHeapIndexing, + AtomicInt64Typed, + AtomicInt64GroupShared, + AtomicInt64Heap, + /// `fma`, double division / reciprocal (D3D11.1 double extensions). + DoubleExtensions, + /// Sample/gather with a `clamp` operand (min-LOD), CheckAccessFullyMapped. + TiledResources, + /// Typed UAV loads of multi-component / non-32-bit formats. + TypedUavLoadAdditionalFormats, +} + +impl Feature { + /// `DxilShaderFlags` bit (entry-point metadata tag 0). + pub(super) fn metadata_bit(self) -> u64 { + if self == Feature::NativeLowPrecision { + // UseNativeLowPrecision | LowPrecisionPresent + return (1 << 23) | (1 << 5); + } + 1u64 << match self { + Feature::Doubles => 2, + Feature::RawAndStructuredBuffers => 4, + Feature::WaveOps => 19, + Feature::Int64Ops => 20, + Feature::NativeLowPrecision => 23, + Feature::AtomicInt64Typed => 27, + Feature::AtomicInt64GroupShared => 28, + Feature::ResourceHeapIndexing => 30, + Feature::SamplerHeapIndexing => 31, + Feature::AtomicInt64Heap => 32, + Feature::DoubleExtensions => 6, + Feature::TiledResources => 12, + Feature::TypedUavLoadAdditionalFormats => 13, + } + } + /// `D3D_SHADER_REQUIRES_*` container feature bit. + pub(super) fn container_bit(self) -> u64 { + match self { + Feature::Doubles => 0x1, + Feature::RawAndStructuredBuffers => 0, + Feature::WaveOps => 0x4000, + Feature::Int64Ops => 0x8000, + Feature::NativeLowPrecision => 0x40000, + Feature::AtomicInt64Typed => 0x40_0000, + Feature::AtomicInt64GroupShared => 0x80_0000, + Feature::ResourceHeapIndexing => 0x200_0000, + Feature::SamplerHeapIndexing => 0x400_0000, + Feature::AtomicInt64Heap => 0x1000_0000, + Feature::DoubleExtensions => 0x20, + Feature::TiledResources => 0x100, + Feature::TypedUavLoadAdditionalFormats => 0x800, + } + } +} + +/// Resource classes (`DXIL::ResourceClass`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResClass { + Srv = 0, + Uav = 1, + Cbv = 2, + Sampler = 3, +} + +/// A statically bound resource range. +#[derive(Debug, Clone)] +pub(super) struct Binding { + pub(super) class: ResClass, + pub(super) space: u32, + pub(super) lower: u32, + /// `DXIL::ResourceKind`. + pub(super) kind: u32, + /// Structured stride (0 otherwise). + pub(super) stride: u32, + /// Typed resources: `DXIL::ComponentType` of the elements (0 otherwise). + pub(super) comp_type: u32, + /// 64-bit atomics are used on the resource (metadata tag 3). + pub(super) atomic64: bool, + /// CBVs: size in bytes. + pub(super) size: u32, + /// Samplers: `SamplerComparisonState`. + pub(super) comparison: bool, + /// UAVs: `globallycoherent` + pub(super) coherent: bool, +} + +impl Binding { + pub(super) fn new(class: ResClass, space: u32, lower: u32, kind: u32) -> Binding { + Binding { class, space, lower, kind, stride: 0, comp_type: 0, atomic64: false, size: 0, comparison: false, coherent: false } + } +} + +/// `DXIL::ResourceKind` values used here. +pub mod kind { + pub const TEXTURE2D: u32 = 2; + pub const CBUFFER: u32 = 13; + pub const SAMPLER: u32 = 14; + pub const TYPED_BUFFER: u32 = 10; + pub const RAW_BUFFER: u32 = 11; + pub const STRUCTURED_BUFFER: u32 = 12; +} + +pub struct Shader { + pub m: Module, + pub stage: Stage, + pub(super) sm: (u32, u32), + pub(super) entry: u32, + pub(super) features: BTreeSet, + pub(super) bindings: Vec, + pub(super) handle_ty: Ty, + props_ty: Ty, +} + +/// A raw (byte-address) UAV bound at `u, space`. +#[derive(Debug, Clone, Copy)] +pub struct RawUav { + pub(super) handle: Value, + /// Index into the static bindings (`None` for heap handles). + pub(super) binding: Option, +} + +impl Shader { + pub fn new(stage: Stage, sm: (u32, u32)) -> Shader { + let mut m = Module::new(); + let entry = m.define_entry("main"); + let i8 = m.i8(); + let p8 = m.ptr(i8, 0); + let handle_ty = m.named_struct("dx.types.Handle", &[p8]); + let i32 = m.i32(); + let props_ty = m.named_struct("dx.types.ResourceProperties", &[i32, i32]); + Shader { m, stage, sm, entry, features: BTreeSet::new(), bindings: Vec::new(), handle_ty, props_ty } + } + + pub fn require(&mut self, f: Feature) { + self.features.insert(f); + } + + /// Calls `dx.op.[.]` with opcode `op` and the given arguments. + pub fn op(&mut self, op: u32, name: &str, overload: Option, ret: Ty, args: &[Value], attrs: FnAttrs) -> Value { + let full = match overload { + Some(t) => format!("dx.op.{name}.{}", self.type_suffix(t)), + None => format!("dx.op.{name}"), + }; + let i32 = self.m.i32(); + let mut params = vec![i32]; + for &a in args { + params.push(self.m.type_of(a)); + } + if let Some(want) = dxc_fn_attrs(op) { + debug_assert_eq!(attrs, want, "dx.op {op} ({name}) attributes differ from DXC's"); + } + let fty = self.m.func_ty(ret, ¶ms); + let f = self.m.declare(&full, fty, attrs); + let opc = self.m.i32c(op); + let mut all = vec![opc]; + all.extend_from_slice(args); + self.m.call(f, &all) + } + + pub(super) fn type_suffix(&mut self, t: Ty) -> &'static str { + if t == self.m.f16() { + "f16" + } else if t == self.m.f32() { + "f32" + } else if t == self.m.f64() { + "f64" + } else if t == self.m.i1() { + "i1" + } else if t == self.m.int(16) { + "i16" + } else if t == self.m.i32() { + "i32" + } else if t == self.m.i64() { + "i64" + } else if t == self.m.i8() { + "i8" + } else { + self.m.fail(format!("no dx.op overload suffix for type {t:?}")); + "i32" + } + } + + // ---- system values + + /// `SV_GroupThreadID` component. + pub fn thread_id_in_group(&mut self, comp: u32) -> Value { + let i32 = self.m.i32(); + let c = self.m.i32c(comp); + self.op(95, "threadIdInGroup", Some(i32), i32, &[c], FnAttrs::ReadNone) + } + /// `SV_DispatchThreadID` component. + pub fn thread_id(&mut self, comp: u32) -> Value { + let i32 = self.m.i32(); + let c = self.m.i32c(comp); + self.op(93, "threadId", Some(i32), i32, &[c], FnAttrs::ReadNone) + } + /// `SV_GroupID` component. + pub fn group_id(&mut self, comp: u32) -> Value { + let i32 = self.m.i32(); + let c = self.m.i32c(comp); + self.op(94, "groupId", Some(i32), i32, &[c], FnAttrs::ReadNone) + } + /// `SV_GroupIndex`. + pub fn flattened_thread_id_in_group(&mut self) -> Value { + let i32 = self.m.i32(); + self.op(96, "flattenedThreadIdInGroup", Some(i32), i32, &[], FnAttrs::ReadNone) + } + + // ---- resources + + /// Declares a raw UAV at `u, space` and creates its handle + /// in the entry block (call before emitting other code in that block). + pub fn raw_uav(&mut self, lower: u32, space: u32) -> RawUav { + self.require(Feature::RawAndStructuredBuffers); + let id = self.bindings.len(); + self.bindings.push(Binding::new(ResClass::Uav, space, lower, kind::RAW_BUFFER)); + let h = self.handle_from_binding(ResClass::Uav, lower, lower, space, lower); + let handle = self.annotate(h, kind::RAW_BUFFER | 0x1000, 0); + RawUav { handle, binding: Some(id) } + } + + /// `globallycoherent RWByteAddressBuffer` at `u, space`. + pub fn raw_uav_coherent(&mut self, lower: u32, space: u32) -> RawUav { + self.require(Feature::RawAndStructuredBuffers); + let id = self.bindings.len(); + self.bindings.push(Binding { coherent: true, ..Binding::new(ResClass::Uav, space, lower, kind::RAW_BUFFER) }); + let h = self.handle_from_binding(ResClass::Uav, lower, lower, space, lower); + // resource properties: IsUAV (bit 12) | IsGloballyCoherent (bit 14) + let handle = self.annotate(h, kind::RAW_BUFFER | 0x1000 | 0x4000, 0); + RawUav { handle, binding: Some(id) } + } + + pub(super) fn handle_from_binding(&mut self, class: ResClass, lower: u32, upper: u32, space: u32, index: u32) -> Value { + let i32 = self.m.i32(); + let i8 = self.m.i8(); + let bind_ty = self.m.named_struct("dx.types.ResBind", &[i32, i32, i32, i8]); + let (lo, hi, sp, cl) = (self.m.i32c(lower), self.m.i32c(upper), self.m.i32c(space), self.m.i8c(class as u8)); + let bind = self.m.aggregate(bind_ty, &[lo, hi, sp, cl]); + let idx = self.m.i32c(index); + let nonuniform = self.m.i1c(false); + let ht = self.handle_ty; + self.op(217, "createHandleFromBinding", None, ht, &[bind, idx, nonuniform], FnAttrs::ReadNone) + } + + /// A handle to `ResourceDescriptorHeap[index]` (or the sampler heap). + pub fn handle_from_heap(&mut self, index: Value, sampler: bool, nonuniform: bool) -> Value { + self.require(if sampler { Feature::SamplerHeapIndexing } else { Feature::ResourceHeapIndexing }); + let (s, n) = (self.m.i1c(sampler), self.m.i1c(nonuniform)); + let ht = self.handle_ty; + self.op(218, "createHandleFromHeap", None, ht, &[index, s, n], FnAttrs::ReadNone) + } + + /// `annotateHandle` with resource properties (`{kind | uav<<12 | ..., stride/format}`). + pub fn annotate(&mut self, h: Value, props0: u32, props1: u32) -> Value { + let (a, b) = (self.m.i32c(props0), self.m.i32c(props1)); + let pt = self.props_ty; + let props = self.m.aggregate(pt, &[a, b]); + let ht = self.handle_ty; + self.op(216, "annotateHandle", None, ht, &[h, props], FnAttrs::ReadNone) + } + + /// A raw-buffer handle from the descriptor heap (`RWByteAddressBuffer` if `uav`). + pub fn heap_raw_buffer(&mut self, index: Value, uav: bool, nonuniform: bool) -> RawUav { + let h = self.handle_from_heap(index, false, nonuniform); + let handle = self.annotate(h, kind::RAW_BUFFER | if uav { 0x1000 } else { 0 }, 0); + RawUav { handle, binding: None } + } + + pub(super) fn res_ret(&mut self, t: Ty) -> Ty { + let name = format!("dx.types.ResRet.{}", self.type_suffix(t)); + let i32 = self.m.i32(); + self.m.named_struct(&name, &[t, t, t, t, i32]) + } + + /// `rawBufferLoad` of `mask` (1..15) consecutive 32-bit values at byte `offset`. + pub fn raw_load(&mut self, buf: RawUav, offset: Value, mask: u8) -> Vec { + let i32 = self.m.i32(); + let rt = self.res_ret(i32); + let undef = self.m.undef(i32); + let (mk, al) = (self.m.i8c(mask), self.m.i32c(4)); + let r = self.op(139, "rawBufferLoad", Some(i32), rt, &[buf.handle, offset, undef, mk, al], FnAttrs::ReadOnly); + (0..4).filter(|c| mask & (1 << c) != 0).map(|c| self.m.extract(r, c)).collect() + } + + /// `rawBufferStore` of up to four 32-bit values at byte `offset`. + pub fn raw_store(&mut self, buf: RawUav, offset: Value, vals: &[Value]) { + if !(1..=4).contains(&vals.len()) { + return self.m.fail(format!("rawBufferStore of {} values", vals.len())); + } + let i32 = self.m.i32(); + let void = self.m.void(); + let undef = self.m.undef(i32); + let mut v = [undef; 4]; + v[..vals.len()].copy_from_slice(vals); + let mask = (1u8 << vals.len()) - 1; + let (mk, al) = (self.m.i8c(mask), self.m.i32c(4)); + self.op(140, "rawBufferStore", Some(i32), void, &[buf.handle, offset, undef, v[0], v[1], v[2], v[3], mk, al], FnAttrs::NoUnwind); + } + + // ---- wave operations + + pub fn wave_read_lane_at(&mut self, v: Value, lane: Value) -> Value { + self.require(Feature::WaveOps); + let t = self.m.type_of(v); + self.op(117, "waveReadLaneAt", Some(t), t, &[v, lane], FnAttrs::NoUnwind) + } + pub fn wave_read_lane_first(&mut self, v: Value) -> Value { + self.require(Feature::WaveOps); + let t = self.m.type_of(v); + self.op(118, "waveReadLaneFirst", Some(t), t, &[v], FnAttrs::NoUnwind) + } + pub fn wave_lane_index(&mut self) -> Value { + self.require(Feature::WaveOps); + let i32 = self.m.i32(); + self.op(111, "waveGetLaneIndex", None, i32, &[], FnAttrs::ReadOnly) + } + /// `WaveActiveBallot` → four i32 words (lanes 0-31, 32-63, …). + pub fn wave_ballot(&mut self, cond: Value) -> [Value; 4] { + self.require(Feature::WaveOps); + let i32 = self.m.i32(); + let fr = self.m.named_struct("dx.types.fouri32", &[i32, i32, i32, i32]); + let r = self.op(116, "waveActiveBallot", None, fr, &[cond], FnAttrs::NoUnwind); + [0, 1, 2, 3].map(|i| self.m.extract(r, i)) + } + + // ---- finishing + + /// The `dx.resources` node (`!{srvs, uavs, cbvs, samplers}`, also the + /// entry's resource field) and the PSV0 resource entries for the + /// statically bound resources; `None` when nothing is bound. Record ids + /// count per class in declaration order; PSV0 lists CBVs, samplers, + /// SRVs, then UAVs (as DXC does). + pub(super) fn resource_metadata(&mut self) -> (Option, Vec) { + let bindings = self.bindings.clone(); + let m = &mut self.m; + let mut lists: [Vec>; 4] = Default::default(); + let mut psv: [Vec; 4] = Default::default(); + for b in &bindings { + let ci = b.class as usize; + let i32 = m.i32(); + let sname = match (b.class, b.kind) { + (ResClass::Uav, kind::RAW_BUFFER) => "struct.RWByteAddressBuffer", + (ResClass::Uav, kind::TYPED_BUFFER) => "class.RWBuffer", + (ResClass::Uav, kind::STRUCTURED_BUFFER) => "struct.RWStructuredBuffer", + (ResClass::Uav, _) => "class.RWTexture", + (ResClass::Srv, kind::RAW_BUFFER) => "struct.ByteAddressBuffer", + (ResClass::Srv, kind::TYPED_BUFFER) => "class.Buffer", + (ResClass::Srv, kind::STRUCTURED_BUFFER) => "class.StructuredBuffer", + (ResClass::Srv, _) => "class.Texture", + (ResClass::Cbv, _) => "CB", + (ResClass::Sampler, _) if b.comparison => "struct.SamplerComparisonState", + (ResClass::Sampler, _) => "struct.SamplerState", + }; + let st = if b.class == ResClass::Cbv { + // Register-sized struct of the cbuffer's bytes. + let a = m.array(b.size.div_ceil(4).max(1) as u64, i32); + let name = format!("CB.{}.{}", b.space, b.lower); + m.named_struct(&name, &[a]) + } else { + m.named_struct(sname, &[i32]) + }; + let pst = m.ptr(st, 0); + let undef = m.undef(pst); + let id = m.md_i32(lists[ci].len() as u32); + let var = m.md_value(undef); + let name = m.md_str(""); + let space = m.md_i32(b.space); + let lower = m.md_i32(b.lower); + let range = m.md_i32(1); + let mut node = vec![Some(id), Some(var), Some(name), Some(space), Some(lower), Some(range)]; + // Extended properties: tag 0 element type, 1 stride, 3 64-bit atomics. + let mut ext: Vec> = Vec::new(); + if b.comp_type != 0 { + ext.extend([Some(m.md_i32(0)), Some(m.md_i32(b.comp_type))]); + } + if b.stride != 0 { + ext.extend([Some(m.md_i32(1)), Some(m.md_i32(b.stride))]); + } + if b.atomic64 { + ext.extend([Some(m.md_i32(3)), Some(m.md_i32(1))]); + } + let extra = if ext.is_empty() { None } else { Some(m.md_node(&ext)) }; + match b.class { + ResClass::Uav => { + let (k, f, gc) = (m.md_i32(b.kind), m.md_i1(false), m.md_i1(b.coherent)); + // globallycoherent, hasCounter, rasterizerOrdered. + node.extend([Some(k), Some(gc), Some(f), Some(f), extra]); + } + ResClass::Srv => { + let (k, samples) = (m.md_i32(b.kind), m.md_i32(0)); + node.extend([Some(k), Some(samples), extra]); + } + ResClass::Cbv => node.extend([Some(m.md_i32(b.size)), None]), + ResClass::Sampler => node.extend([Some(m.md_i32(b.comparison as u32)), None]), + } + lists[ci].push(Some(m.md_node(&node))); + let res_type = match (b.class, b.kind) { + (ResClass::Cbv, _) => PsvResType::Cbv, + (ResClass::Sampler, _) => PsvResType::Sampler, + (ResClass::Srv, kind::RAW_BUFFER) => PsvResType::SrvRaw, + (ResClass::Srv, kind::STRUCTURED_BUFFER) => PsvResType::SrvStructured, + (ResClass::Srv, _) => PsvResType::SrvTyped, + (ResClass::Uav, kind::RAW_BUFFER) => PsvResType::UavRaw, + (ResClass::Uav, kind::STRUCTURED_BUFFER) => PsvResType::UavStructured, + (ResClass::Uav, _) => PsvResType::UavTyped, + }; + // PSVResourceFlags::UsedByAtomic64 + psv[ci].push(PsvResource { res_type, space: b.space, lower: b.lower, upper: b.lower, kind: b.kind, flags: b.atomic64 as u32 }); + } + if lists.iter().all(|l| l.is_empty()) { + return (None, Vec::new()); + } + let parts: Vec> = lists.iter().map(|l| if l.is_empty() { None } else { Some(m.md_node(l)) }).collect(); + let node = m.md_node(&parts); + let [srv, uav, cbv, smp] = psv; + (Some(node), [cbv, smp, srv, uav].concat()) + } + + /// Requires the features implied by instruction types alone (`Int64Ops` + /// for any i64, `Doubles` for any double, `DoubleExtensions` for double + /// division and int ↔ double conversions), which the validator derives + /// from the code and demands in the flags even when the IR was built + /// with [`Module`] methods directly rather than the [`Shader`] helpers. + pub(super) fn infer_type_features(&mut self) { + let (i64, f64) = self.m.existing_i64_f64(); + if i64.is_some_and(|t| self.m.insts_use_type(t)) { + self.require(Feature::Int64Ops); + } + if f64.is_some_and(|t| self.m.insts_use_type(t)) { + self.require(Feature::Doubles); + } + if self.m.uses_double_extensions() { + self.require(Feature::DoubleExtensions); + } + } + + /// Writes metadata, bitcode and the signed container (panics on a builder error: tests; + /// translators use [`Shader::try_finish`]). + pub fn finish(self, numthreads: [u32; 3], wave_size: Option) -> Vec { + self.try_finish(numthreads, wave_size).unwrap_or_else(|e| panic!("DXIL builder: {e}")) + } + + /// [`Shader::finish`], or the first builder error. + pub fn try_finish(mut self, numthreads: [u32; 3], wave_size: Option) -> Result, String> { + if self.stage != Stage::Compute { + return Err(format!("finish of a {:?} entry (only compute; graphics use finish_graphics)", self.stage)); + } + if !self.m.terminated() { + self.m.ret(); + } + self.m.optimize(); + self.infer_type_features(); + let flags: u64 = self.features.iter().map(|f| f.metadata_bit()).fold(0, |a, b| a | b); + let sfi0: u64 = self.features.iter().map(|f| f.container_bit()).fold(0, |a, b| a | b); + + let m = &mut self.m; + let one = m.md_i32(1); + let ver = m.md_i32(self.sm.1); + let dx_version = m.md_node(&[Some(one), Some(ver)]); + let valver = m.md_i32(super::validate::VALVER.1); + let dx_valver = m.md_node(&[Some(one), Some(valver)]); + let prefix = m.md_str(self.stage.profile_prefix()); + let smaj = m.md_i32(self.sm.0); + let shader_model = m.md_node(&[Some(prefix), Some(smaj), Some(ver)]); + + let (resources, psv_res) = self.resource_metadata(); + let m = &mut self.m; + + // Entry properties. + let mut props: Vec> = Vec::new(); + if flags != 0 { + let tag = m.md_i32(0); + let v = m.md_i64(flags); + props.extend([Some(tag), Some(v)]); + } + let tag = m.md_i32(4); + let nt: Vec> = numthreads.iter().map(|&n| Some(m.md_i32(n))).collect(); + let ntn = m.md_node(&nt); + props.extend([Some(tag), Some(ntn)]); + if let Some(w) = wave_size { + let tag = m.md_i32(11); + let wv = m.md_i32(w); + let wn = m.md_node(&[Some(wv)]); + props.extend([Some(tag), Some(wn)]); + } + let props_node = m.md_node(&props); + let fv = m.func_value(self.entry); + let fmd = m.md_value(fv); + let name = m.md_str("main"); + let entry = m.md_node(&[Some(fmd), Some(name), None, resources, Some(props_node)]); + + // `!llvm.ident`, as DXC writes first: AMD's driver compiler (amdxc64) crashes at + // PSO creation on modules without it. + let ident = m.md_str("xcl"); + let ident = m.md_node(&[Some(ident)]); + m.named_md("llvm.ident", &[ident]); + m.named_md("dx.version", &[dx_version]); + m.named_md("dx.valver", &[dx_valver]); + m.named_md("dx.shaderModel", &[shader_model]); + if let Some(r) = resources { + m.named_md("dx.resources", &[r]); + } + m.named_md("dx.entryPoints", &[entry]); + + let bitcode = m.try_to_bitcode(TRIPLE, DATALAYOUT)?; + let (min_wave, max_wave) = wave_size.map_or((0, u32::MAX), |w| (w, w)); + let psv = Psv { stage: self.stage, min_wave, max_wave, numthreads, resources: psv_res, entry: "main".into() }; + Ok(container::container(self.stage, self.sm, &bitcode, sfi0, &psv)) + } +} + +/// The function attributes DXC gives each `dx.op` declaration (DXC 1.9 +/// `DxilOperations.cpp`, checked against `dxc -Fc` listings). AMD's compiler +/// is sensitive to them (e.g. `waveGetLaneIndex` must be `readonly`), so +/// [`Shader::op`] checks every declaration against this table in debug +/// builds. `None` for opcodes not listed. +pub fn dxc_fn_attrs(op: u32) -> Option { + use FnAttrs::*; + Some(match op { + 4 => ReadNone, // loadInput + 5 => NoUnwind, // storeOutput + 6..=56 => ReadNone, // unary/binary/tertiary/quaternary/dot + 57..=66 => ReadOnly, // createHandle, cbuffer loads, samples, textureLoad + 67 => NoUnwind, // textureStore + 68 => ReadOnly, // bufferLoad + 69 | 70 => NoUnwind, // bufferStore, bufferUpdateCounter + 71..=77 => ReadOnly, // checkAccess, getDimensions, gathers, sample positions + 78 | 79 => NoUnwind, // atomics + 80 => NoDuplicate, // barrier + 81 => ReadOnly, // calculateLOD + 82 => NoUnwind, // discard + 83..=96 => ReadNone, // derivatives, eval*, sampleIndex, coverage, ids + 97..=99 => NoUnwind, // emitStream, cutStream, emitThenCutStream + 100..=102 => ReadNone, // gsInstanceID, makeDouble, splitDouble + 110 => NoUnwind, // waveIsFirstLane + 111 => ReadOnly, // waveGetLaneIndex + 112 => ReadNone, // waveGetLaneCount + 113..=123 => NoUnwind, // wave / quad ops + 124..=132 => ReadNone, // bitcasts, legacy conversions + 135 | 136 => NoUnwind, // waveAllOp, wavePrefixBitCount + 137 | 138 => ReadNone, // attributeAtVertex, viewID + 139 => ReadOnly, // rawBufferLoad + 140 => NoUnwind, // rawBufferStore + 165..=169 => NoUnwind, // waveMatch, waveMultiPrefix*, mesh outputs + 170 => ReadOnly, // getMeshPayload + 171 | 172 => NoUnwind, // storeVertexOutput, storePrimitiveOutput + 216..=218 => ReadNone, // annotateHandle, createHandleFromBinding/Heap + 221 => ReadOnly, // isHelperLane + _ => return Option::None, + }) +} diff --git a/crates/xcl/src/gpu/dxil/ssa.rs b/crates/xcl/src/gpu/dxil/ssa.rs new file mode 100644 index 000000000..2ebd42fb9 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/ssa.rs @@ -0,0 +1,245 @@ +//! On-the-fly SSA construction (Braun, Buchwald, Hack, Leißa, Mallon, Zwinkau: +//! "Simple and Efficient Construction of Static Single Assignment Form", CC 2013) +//! over the module's basic blocks. Variables are register dwords (SGPRs, SCC, +//! VCC, M0, EXEC, VGPRs) numbered by the translator. +//! +//! Blocks are registered as they are created; predecessors are added as the +//! branches are emitted. A block whose predecessors are not all known yet is +//! *unsealed*: reads there create incomplete phis, completed on [`Ssa::seal`]. +//! A read that reaches a block without predecessors asks the caller for the +//! variable's initial value (the kernel loads it from `io` in the entry block). + +use std::collections::HashMap; + +use super::module::{Block, Ty, Value}; +use super::shader::Shader; + +/// Multiplicative hash for the small integer keys of the definition maps (SipHash +/// dominated the reads of long programs). +#[derive(Default, Clone, Copy)] +struct VarHasher(u64); + +impl std::hash::Hasher for VarHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.0 = (self.0.rotate_left(5) ^ b as u64).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95); + } + } + fn write_u32(&mut self, v: u32) { + self.0 = (self.0.rotate_left(5) ^ v as u64).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95); + } +} + +type VarMap = HashMap>; + +#[derive(Default)] +struct SBlock { + defs: VarMap, + preds: Vec, + sealed: bool, + /// predecessors to wait for before sealing automatically (None: sealed explicitly) + expect: Option, + incomplete: Vec<(u32, Value)>, + /// a region join ([`Ssa::seal_region_join`]): the region's last block and the + /// variables it writes + region: Option<(Block, Vec)>, +} + +pub struct Ssa { + blocks: Vec, + ty: Ty, + /// (block, variable) of the sealed joins whose operands are being read, with the + /// phi created if a read came back around to the join (a loop) + visiting: HashMap<(u32, u32), Option>, + /// open write logs (innermost last) + logs: Vec>, +} + +impl Ssa { + /// All variables have type `ty`. + pub fn new(ty: Ty) -> Ssa { + Ssa { blocks: Vec::new(), ty, visiting: HashMap::new(), logs: Vec::new() } + } + + fn at(&mut self, b: Block) -> &mut SBlock { + let i = b.0 as usize; + if self.blocks.len() <= i { + self.blocks.resize_with(i + 1, SBlock::default); + } + &mut self.blocks[i] + } + + /// `b` seals itself once `n` predecessors have been added. + pub fn expect_preds(&mut self, s: &mut Shader, b: Block, n: usize, init: &mut dyn FnMut(&mut Shader, u32) -> Value) { + self.at(b).expect = Some(n); + if self.at(b).preds.len() >= n && !self.at(b).sealed { + self.seal(s, b, init); + } + } + + pub fn add_pred(&mut self, s: &mut Shader, b: Block, p: Block, init: &mut dyn FnMut(&mut Shader, u32) -> Value) { + let sb = self.at(b); + assert!(!sb.sealed, "edge into the sealed block {b:?}"); + sb.preds.push(p); + if let Some(n) = sb.expect { + if sb.preds.len() >= n { + self.seal(s, b, init); + } + } + } + + pub fn is_sealed(&mut self, b: Block) -> bool { + self.at(b).sealed + } + + pub fn preds(&mut self, b: Block) -> Vec { + self.at(b).preds.clone() + } + + /// A definition by the program (logged for an open [`Ssa::begin_log`]). + pub fn write(&mut self, b: Block, var: u32, v: Value) { + if let Some(log) = self.logs.last_mut() { + log.push(var); + } + self.at(b).defs.insert(var, v); + } + + /// A read's result remembered in `b` (not a definition). + fn cache(&mut self, b: Block, var: u32, v: Value) { + self.at(b).defs.insert(var, v); + } + + /// Starts logging the variables written (e.g. in a guarded region). + pub fn begin_log(&mut self) { + self.logs.push(Vec::new()); + } + + /// Ends the innermost log: the variables written since `begin_log` (also + /// counted in the enclosing log). + pub fn end_log(&mut self) -> Vec { + let mut log = self.logs.pop().expect("begin_log"); + log.sort_unstable(); + log.dedup(); + if let Some(outer) = self.logs.last_mut() { + outer.extend_from_slice(&log); + } + log + } + + /// Seals the join `j` of a region `cond → (then … end) → j` / `cond → j` whose + /// only writes are `written` (sorted): a written variable merges over both edges, + /// every other one reads through `cond` directly, as if `cond` were `j`'s only + /// predecessor. Reads then skip the region instead of walking both edges of every + /// guard (guarded memory accesses make thousands of such joins). + pub fn seal_region_join(&mut self, j: Block, cond: Block, end: Block, written: Vec) { + let sb = self.at(j); + assert!(!sb.sealed && sb.incomplete.is_empty(), "region join already read"); + sb.preds = vec![cond]; + sb.sealed = true; + if !written.is_empty() { + sb.region = Some((end, written)); + } + } + + /// The predecessors a read of `var` in `b` merges over. + fn preds_of(&mut self, b: Block, var: u32) -> Vec { + let sb = self.at(b); + match &sb.region { + Some((end, w)) if w.binary_search(&var).is_ok() => vec![sb.preds[0], *end], + _ => sb.preds.clone(), + } + } + + /// The definition of `var` reaching the current end of block `b`. + pub fn read(&mut self, s: &mut Shader, b: Block, var: u32, init: &mut dyn FnMut(&mut Shader, u32) -> Value) -> Value { + if let Some(&v) = self.at(b).defs.get(&var) { + return v; + } + // chains of sealed single-predecessor blocks (guarded memory accesses make long ones) + // are walked iteratively, not recursively + let mut chain = Vec::new(); + let mut b = b; + loop { + let sb = self.at(b); + if !sb.sealed || sb.preds.len() != 1 || sb.region.as_ref().is_some_and(|(_, w)| w.binary_search(&var).is_ok()) { + break; + } + chain.push(b); + b = sb.preds[0]; + if let Some(&v) = self.at(b).defs.get(&var) { + for c in chain { + self.cache(c, var, v); + } + return v; + } + } + if !chain.is_empty() { + let v = self.read(s, b, var, init); + for c in chain { + self.cache(c, var, v); + } + return v; + } + let v = if !self.at(b).sealed { + let ty = self.ty; + let phi = s.m.phi_at(b, ty); + self.at(b).incomplete.push((var, phi)); + phi + } else { + let preds = self.preds_of(b, var); + match preds.len() { + 0 => init(s, var), + 1 => self.read(s, preds[0], var, init), + _ => { + // the operands first, without a phi: most joins a read walks through + // (guarded accesses make thousands) see one value from every edge + // (Braun et al.'s trivial phi) and need none. A read that comes back + // here around a loop gets a phi, which then stays. + let key = (b.0, var); + if let Some(slot) = self.visiting.get(&key).copied() { + let phi = slot.unwrap_or_else(|| s.m.detached_phi(self.ty)); + self.visiting.insert(key, Some(phi)); + return phi; + } + self.visiting.insert(key, None); + let vals: Vec = preds.iter().map(|&p| self.read(s, p, var, init)).collect(); + let marker = self.visiting.remove(&key).flatten(); + if marker.is_none() && vals.iter().all(|&v| v == vals[0]) { + vals[0] + } else { + let phi = marker.unwrap_or_else(|| s.m.detached_phi(self.ty)); + for (&v, &p) in vals.iter().zip(&preds) { + s.m.add_incoming(phi, v, p); + } + s.m.place_phi(b, phi); + phi + } + } + } + }; + self.cache(b, var, v); + v + } + + fn add_operands(&mut self, s: &mut Shader, phi: Value, preds: &[Block], var: u32, init: &mut dyn FnMut(&mut Shader, u32) -> Value) { + for &p in preds { + let v = self.read(s, p, var, init); + s.m.add_incoming(phi, v, p); + } + } + + pub fn seal(&mut self, s: &mut Shader, b: Block, init: &mut dyn FnMut(&mut Shader, u32) -> Value) { + if self.at(b).sealed { + return; + } + let preds = self.at(b).preds.clone(); + let inc = std::mem::take(&mut self.at(b).incomplete); + for (var, phi) in inc { + self.add_operands(s, phi, &preds, var, init); + } + self.at(b).sealed = true; + } +} diff --git a/crates/xcl/src/gpu/dxil/tests.rs b/crates/xcl/src/gpu/dxil/tests.rs new file mode 100644 index 000000000..67e6baf0d --- /dev/null +++ b/crates/xcl/src/gpu/dxil/tests.rs @@ -0,0 +1,179 @@ +//! End-to-end checks of emitted DXIL: the SDK validator accepts it, DXC +//! disassembles it, and D3D12 runs it on the GPU with the recompiler's +//! kernel ABI (u0 `io`, u1 `res` root UAVs). + +use super::container::Stage; +use super::module::{BinOp, CastOp, Pred}; +use super::shader::Shader; +use super::validate; +use crate::gpu::recomp::runner; + +/// The program of `tests/data/dxil/dxc_cs_raw_uav.hlsl`, emitted directly: +/// `a = io[lane]; f = asfloat(a) * 2 + 1; if (a > 5) f = -f; +/// res[lane] = asuint(f) + WaveReadLaneAt(a, 3)` — with a real branch and phi +/// rather than a select, to exercise control flow. +fn sample_kernel(wave: u32) -> Vec { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let io = s.raw_uav(0, 0); + let res = s.raw_uav(1, 0); + let lane = s.thread_id_in_group(0); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, lane, two); + let a = s.raw_load(io, off, 1)[0]; + let f32 = s.m.f32(); + let i32 = s.m.i32(); + let fa = s.m.bitcast(a, f32); + let c2 = s.m.f32c(2.0f32.to_bits()); + let c1 = s.m.f32c(1.0f32.to_bits()); + let mul = s.m.fbin(BinOp::Mul, fa, c2, 0); + let f = s.m.fbin(BinOp::Add, mul, c1, 0); + let five = s.m.i32c(5); + let big = s.m.cmp(Pred::UGt, a, five); + let three = s.m.i32c(3); + let other = s.wave_read_lane_at(a, three); + + let entry = s.m.current_block(); + let neg_b = s.m.new_block(); + let join = s.m.new_block(); + s.m.cond_br(big, neg_b, join); + s.m.set_block(neg_b); + let nz = s.m.f32c(0x8000_0000); + let neg = s.m.fbin(BinOp::Sub, nz, f, 0); + s.m.br(join); + s.m.set_block(join); + let phi = s.m.phi(f32); + s.m.add_incoming(phi, f, entry); + s.m.add_incoming(phi, neg, neg_b); + let bits = s.m.cast(CastOp::BitCast, phi, i32); + let sum = s.m.bin(BinOp::Add, bits, other); + s.raw_store(res, off, &[sum]); + s.finish([64, 1, 1], Some(wave)) +} + +fn expected(io: &[u32], wave: usize) -> Vec { + (0..64) + .map(|l| { + let a = io[l]; + let mut f = f32::from_bits(a) * 2.0 + 1.0; + if a > 5 { + f = -f; + } + f.to_bits().wrapping_add(io[l / wave * wave + 3]) + }) + .collect() +} + +#[test] +fn emitted_kernel_passes_the_sdk_validator() { + let c = sample_kernel(64); + if let Err(e) = validate::validate(&c) { + let dis = validate::disassemble(&c).unwrap_or_else(|d| d); + panic!("validator rejected the emitted kernel:\n{e}\n--- disassembly ---\n{dis}"); + } +} + +#[test] +fn emitted_kernel_disassembles_like_dxc_output() { + let dis = validate::disassemble(&sample_kernel(64)).expect("disassembly"); + for needle in [ + "@dx.op.createHandleFromBinding(i32 217", + "@dx.op.rawBufferLoad.i32(i32 139", + "@dx.op.waveReadLaneAt.i32(i32 117", + "phi float", + "!{i32 64, i32 1, i32 1}", + ] { + assert!(dis.contains(needle), "missing `{needle}` in:\n{dis}"); + } +} + +#[test] +fn emitted_kernel_runs_on_the_gpu() { + let wave = match (runner::wave64_supported(), runner::wave32_supported()) { + (Ok(true), _) => 64, + (_, Ok(true)) => 32, + (Err(e), _) => return runner::skip_test(&e), + _ => return runner::skip_test("neither wave64 nor wave32 support"), + }; + let c = sample_kernel(wave); + validate::validate(&c).expect("valid DXIL"); + // io dwords 0..64 are the SGPR slots the runner uploads first. + let mut sgpr = vec![0u32; 128]; + for (l, v) in sgpr.iter_mut().take(64).enumerate() { + *v = match l % 4 { + 0 => l as u32, // small integers (≤ 5 stay positive) + 1 => (l as f32 * 0.5).to_bits(), // floats, all > 5 as integers → negated + 2 => 3, + _ => (-(l as f32)).to_bits(), + }; + } + let state = runner::KernelState { sgpr: sgpr.clone(), vgpr: vec![vec![0; 256]; 64], scc: 0 }; + let r = runner::run(&c, &state, &[]).expect("GPU run"); + assert_eq!(&r.raw[..64], &expected(&sgpr, wave as usize)[..]); +} + +/// Blocks created out of dominance order (a block used as a branch target +/// before the block that dominates it exists), an unreachable block feeding a +/// phi, and `replace_all_uses` on a trivial phi: the writer lays blocks out in +/// reverse post-order, drops the unreachable one and its phi edge, and the +/// result validates and runs (res[lane] = (lane << 2) + 7 + io[lane]). +fn out_of_order_kernel() -> Vec { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let io = s.raw_uav(0, 0); + let res = s.raw_uav(1, 0); + let lane = s.thread_id_in_group(0); + let two = s.m.i32c(2); + let off = s.m.bin(BinOp::Shl, lane, two); + let entry = s.m.current_block(); + // created first, reached last + let tail = s.m.new_block(); + let dead = s.m.new_block(); + let mid = s.m.new_block(); + s.m.br(mid); + + s.m.set_block(mid); + let seven = s.m.i32c(7); + let v = s.m.bin(BinOp::Add, off, seven); + let x = s.raw_load(io, off, 1)[0]; + s.m.br(tail); + + s.m.set_block(dead); + let junk = s.m.i32c(0xdead); + s.m.br(tail); + + s.m.set_block(tail); + let i32 = s.m.i32(); + let trivial = s.m.phi(i32); // only ever `v`: replaced below + s.m.add_incoming(trivial, v, mid); + let p = s.m.phi(i32); + s.m.add_incoming(p, x, mid); + s.m.add_incoming(p, junk, dead); + let sum = s.m.bin(BinOp::Add, trivial, p); + s.raw_store(res, off, &[sum]); + s.m.replace_all_uses(trivial, v); + let _ = entry; + s.finish([64, 1, 1], None) +} + +#[test] +fn blocks_are_written_in_reverse_post_order() { + let c = out_of_order_kernel(); + if let Err(e) = validate::validate(&c) { + let dis = validate::disassemble(&c).unwrap_or_else(|d| d); + panic!("validator rejected the out-of-order kernel:\n{e}\n--- disassembly ---\n{dis}"); + } + let dis = validate::disassemble(&c).expect("disassembly"); + assert!(!dis.contains("57005"), "the unreachable block's constant must be gone:\n{dis}"); + match runner::wave32_supported().or_else(|_| runner::wave64_supported()) { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32 / wave64"), + Err(e) => return runner::skip_test(&e), + } + let mut sgpr = vec![0u32; 128]; + for (l, v) in sgpr.iter_mut().take(64).enumerate() { + *v = 1000 + l as u32 * 3; + } + let state = runner::KernelState { sgpr: sgpr.clone(), vgpr: vec![vec![0; 256]; 64], scc: 0 }; + let r = runner::run(&c, &state, &[]).expect("GPU run"); + let want: Vec = (0..64).map(|l| ((l as u32) << 2) + 7 + sgpr[l]).collect(); + assert_eq!(&r.raw[..64], &want[..]); +} diff --git a/crates/xcl/src/gpu/dxil/validate.rs b/crates/xcl/src/gpu/dxil/validate.rs new file mode 100644 index 000000000..7ba10b203 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/validate.rs @@ -0,0 +1,169 @@ +//! Test and diagnostic oracles from the Windows SDK: DXC's validator +//! (`IDxcValidator` from `dxcompiler.dll`, which carries the internal +//! validator since DXC 1.8 — the SDK's `dxil.dll` copies may be older) and +//! its disassembler. Emitted shaders do +//! not need either: their container digest is computed by +//! [`super::container::hash`]. + +use std::ffi::c_void; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D::Dxc::*; + +type CreateInstance = unsafe extern "system" fn(*const windows::core::GUID, *const windows::core::GUID, *mut *mut c_void) -> windows::core::HRESULT; + +fn compiler_create() -> Result { + let f = crate::gpu::recomp::dxc::create_instance().ok_or("dxcompiler.dll not found")?; + Ok(unsafe { std::mem::transmute::(f) }) +} + +fn instance(create: CreateInstance, clsid: &windows::core::GUID) -> Result { + let mut p = std::ptr::null_mut(); + let hr = unsafe { create(clsid, &T::IID, &mut p) }; + if hr.is_err() || p.is_null() { + return Err(format!("DxcCreateInstance: {hr:?}")); + } + Ok(unsafe { T::from_raw(p) }) +} + +fn blob_text(b: &IDxcBlob) -> String { + unsafe { + let (p, n) = (b.GetBufferPointer() as *const u8, b.GetBufferSize()); + // An empty blob may have a null buffer, which `from_raw_parts` forbids. + if p.is_null() || n == 0 { + return String::new(); + } + String::from_utf8_lossy(std::slice::from_raw_parts(p, n)).trim_end_matches('\0').to_string() + } +} + +/// The text of an operation's error buffer (empty if there is none). +fn error_text(e: windows::core::Result) -> String { + e.ok().and_then(|e| e.cast::().ok()).map(|b| blob_text(&b)).unwrap_or_default() +} + +fn blob(bytes: &[u8]) -> Result { + let utils: IDxcUtils = instance(compiler_create()?, &CLSID_DxcUtils)?; + unsafe { + let len = u32::try_from(bytes.len()).map_err(|_| "blob larger than 4 GiB".to_string())?; + let b = utils.CreateBlob(bytes.as_ptr() as *const c_void, len, DXC_CP_ACP).map_err(|e| format!("CreateBlob: {e}"))?; + b.cast::().map_err(|e| format!("{e}")) + } +} + +/// The validator version our metadata declares (`dx.valver`). It stays 1.8 rather than +/// 1.7: the PSV0 part carries `PSVRuntimeInfo3` (the entry name), which validator 1.8 +/// introduced, so a 1.7 validator would reject the container anyway. +pub const VALVER: (u32, u32) = (1, 8); + +/// The loaded validator's version (`IDxcVersionInfo`), queried once. +pub fn validator_version() -> Result<(u32, u32), String> { + static V: std::sync::OnceLock> = std::sync::OnceLock::new(); + V.get_or_init(|| { + let v: IDxcValidator = instance(compiler_create()?, &CLSID_DxcValidator)?; + let info: IDxcVersionInfo = v.cast().map_err(|e| format!("IDxcVersionInfo: {e}"))?; + let (mut major, mut minor) = (0, 0); + unsafe { info.GetVersion(&mut major, &mut minor) }.map_err(|e| format!("GetVersion: {e}"))?; + Ok((major, minor)) + }) + .clone() +} + +/// Whether the loaded validator can check our containers (version >= [`VALVER`]). The +/// Windows SDK's DXC 1.7, for one, cannot: it rejects `dx.valver` 1.8 before anything else. +pub fn validator_supported() -> bool { + validator_version().is_ok_and(|v| v >= VALVER) +} + +/// Validates a container with DXC's validator; `Err` carries the validator's messages. +/// +/// With a validator older than [`VALVER`] the check is skipped (`Ok`, and under test a +/// `SKIPPED : validator < 1.8` line once per test): emitted shaders do not need +/// the validator at run time, and the GPU tests still run. Malformed containers still fail. +pub fn validate(container: &[u8]) -> Result<(), String> { + header_fits(container)?; + let v: IDxcValidator = instance(compiler_create()?, &CLSID_DxcValidator)?; + let b = blob(container)?; + unsafe { + let r = v.Validate(&b, DxcValidatorFlags_Default).map_err(|e| format!("Validate: {e}"))?; + let status = r.GetStatus().map_err(|e| format!("{e}"))?; + if status.is_ok() { + return Ok(()); + } + let msg = error_text(r.GetErrorBuffer()); + if !validator_supported() && msg.contains("Validator version in metadata") { + skip_validation(); + return Ok(()); + } + Err(if msg.is_empty() { format!("validation failed: {status:?}") } else { msg }) + } +} + +/// Reports (once per test thread, under test) that validation was skipped for an old validator. +pub fn skip_validation() { + if !cfg!(test) { + return; + } + use std::io::Write; + let thread = std::thread::current(); + // Only test threads (`module::test`), not e.g. the translator's worker threads. + if !thread.name().is_some_and(|n| n.contains("::")) { + return; + } + thread_local!(static REPORTED: std::cell::Cell = const { std::cell::Cell::new(false) }); + if REPORTED.with(|r| r.replace(true)) { + return; + } + let (major, minor) = validator_version().unwrap_or_default(); + let _ = writeln!(std::io::stderr(), "SKIPPED {}: validator {major}.{minor} < {}.{} (validation step only)", thread.name().unwrap_or("?"), VALVER.0, VALVER.1); +} + +/// Refuses input shorter than a container header (32 bytes) before DXC sees it: DXC 1.8's +/// validator (dxcompiler 1.8.2502.11, the Windows SDK's) reads the whole header of a blob +/// that starts with `DXBC`, past the end of a shorter one (`b"DXBC"` faults in it). +fn header_fits(container: &[u8]) -> Result<(), String> { + if container.len() < 32 { + return Err(format!("not a DXIL container: {} bytes, shorter than its 32-byte header", container.len())); + } + Ok(()) +} + +/// DXC's textual disassembly of a container (for diagnostics and tests). +pub fn disassemble(container: &[u8]) -> Result { + header_fits(container)?; + let c: IDxcCompiler3 = instance(compiler_create()?, &CLSID_DxcCompiler)?; + let buf = DxcBuffer { Ptr: container.as_ptr() as *const c_void, Size: container.len(), Encoding: 0 }; + unsafe { + let r: IDxcResult = c.Disassemble(&buf).map_err(|e| format!("Disassemble: {e}"))?; + let status = r.GetStatus().map_err(|e| format!("{e}"))?; + if status.is_err() { + let msg = error_text(r.GetErrorBuffer()); + return Err(format!("disassembly failed: {msg}")); + } + let out: IDxcBlob = r.GetResult().map_err(|e| format!("{e}"))?; + Ok(blob_text(&out)) + } +} + +#[cfg(test)] +mod tests { + /// Malformed input must come back as `Err`, never as a panic or UB in the + /// FFI glue (empty error blobs may carry a null buffer pointer). + #[test] + fn malformed_containers_are_errors() { + let s = super::super::shader::Shader::new(super::super::container::Stage::Compute, (6, 6)); + let good = s.finish([1, 1, 1], None); + assert_eq!(super::validate(&good), Ok(())); + // Garbage and truncations. (A wrong digest is *not* an error here: + // the validator re-signs rather than checks it; D3D12 does check it, + // which the GPU tests cover.) + let inputs: [&[u8]; 5] = [&[], b"DXBC", &[0u8; 64], &good[..good.len() / 2], &good[..good.len() - 4]]; + for c in inputs { + if crate::gpu::recomp::dxc::create_instance().is_none() { + return crate::gpu::recomp::runner::skip_test("no dxcompiler.dll"); + } + assert!(super::validate(c).is_err(), "accepted {} bytes", c.len()); + let _ = super::disassemble(c); + } + } +} diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index 06ebeedc0..d95af42f7 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -6,6 +6,7 @@ pub mod agility; pub mod bvh; pub mod desc; pub mod dxbc; +pub mod dxil; pub(crate) mod fence; pub mod pack; pub mod rdna2; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 82876f01d..c56279aad 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1331,7 +1331,7 @@ fn scalar_constant(d: &Decoded, code: u64) -> Option { /// S# built from constants in the code – how the console compiler places the static /// samplers of a root signature: for each MIMG instruction whose four sampler SGPRs were all /// set by s_mov / s_movk with constants earlier in its block, those words. -fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> BTreeMap { +pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> BTreeMap { let mut known: std::collections::HashMap = std::collections::HashMap::new(); let mut out = BTreeMap::new(); for d in insts { diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index c63f8be85..46e237b2c 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -156,6 +156,8 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa split_wave64, cache_dir: dxc::cache_dir(), }; + // with `XCL_DIRECT_DXIL` the disk entries live under their own identity (backend tag, + // direct translator version, routing mode): never mixed with the HLSL path's entries let from_disk = || translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one); cached_shader(cache, key, blob, from_disk).map(|shader| shader.as_ref().clone()) } @@ -185,6 +187,46 @@ mod translated { h | 1 } + /// The backend producing an entry: the HLSL path, or `XCL_DIRECT_DXIL` routing (whose + /// results may also be HLSL fallbacks, so its identity extends the HLSL one). + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + pub(super) enum Backend { + Hlsl, + /// direct DXIL for compute + the mesh pass (`=1`) + DirectCompute, + /// direct DXIL for VS / PS too (`=all`) + DirectAll, + } + + impl Backend { + pub(super) fn current() -> Self { + match (crate::gpu::dxil::kernel::enabled(), crate::gpu::dxil::kernel::enabled_graphics()) { + (_, true) => Backend::DirectAll, + (true, false) => Backend::DirectCompute, + _ => Backend::Hlsl, + } + } + } + + /// `identity_for` of `backend`: unchanged for the HLSL path (its entries stay valid), + /// tagged with the direct translator's version and routing mode otherwise. + pub(super) fn identity_with(source: &str, toolchain: &str, backend: Backend, direct_version: u32) -> u64 { + let base = identity_for(source, toolchain); + let tag = match backend { + Backend::Hlsl => return base, + Backend::DirectCompute => "compute", + Backend::DirectAll => "all", + }; + let mut h = base; + for part in ["xcl-direct-dxil", tag, &direct_version.to_string()] { + for byte in part.bytes().chain([0]) { + h ^= byte as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + } + h | 1 + } + /// Translation semantics and the DXC DLLs, independent of link metadata and build profile. /// Zero means the disk cache is disabled. fn identity() -> u64 { @@ -193,7 +235,12 @@ mod translated { if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { return 0; } - identity_for(env!("XCL_TRANSLATOR_SOURCE_ID"), super::dxc::toolchain_identity()) + identity_with( + env!("XCL_TRANSLATOR_SOURCE_ID"), + super::dxc::toolchain_identity(), + Backend::current(), + crate::gpu::dxil::kernel::TRANSLATOR_VERSION, + ) }) } @@ -295,6 +342,29 @@ mod translated { // Changes here, in `fspx`, or in `console_translation` that alter the cached result must bump // `TRANSLATION_GLUE_REVISION` in build.rs; cache serialization changes need not bump it. fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result { + // `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path + // for what it cannot translate yet + if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() { + match direct_compute(blob, sampler_base, windows, split_wave64) { + Ok(c) => { + crate::gpu::dxil::coverage::record_translated("CS"); + return Ok(c); + } + Err(e) => direct_fallback("CS", &e), + } + } + // `XCL_DIRECT_DXIL=all`: vertex / pixel shaders too (not with the PS debug hooks below) + let ps_debug = stage == Stage::Pixel + && (debug_color(blob).is_some() || ["XCL_DEBUG_LOD0", "XCL_DEBUG_PS_SUB", "XCL_DEBUG_PS_EXPR"].iter().any(|v| std::env::var_os(v).is_some())); + if stage != Stage::Compute && !ps_debug && crate::gpu::dxil::kernel::enabled_graphics() { + match direct_graphics(blob, stage, sampler_base, windows) { + Ok(c) => { + crate::gpu::dxil::coverage::record_translated(if stage == Stage::Vertex { "VS" } else { "PS" }); + return Ok(c); + } + Err(e) => direct_fallback(if stage == Stage::Vertex { "VS" } else { "PS" }, &e), + } + } let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?; if let Some([r, g, b]) = (stage == Stage::Pixel).then(|| debug_color(blob)).flatten() { t.hlsl = t.hlsl.replacen(" return xo;\n}", &format!(" xo.t0 = float4({r:.3}, {g:.3}, {b:.3}, 1.0);\n return xo;\n}}"), 1); @@ -511,6 +581,64 @@ pub fn compute_user_sgprs(blob: &[u8]) -> Option { } } +/// A direct DXIL translation that fell back to the HLSL path: one structured log line +/// (`stage=… reason=…`, the reason with operands stripped) and the live summary counter +/// (`XCL_DIRECT_DXIL_STATS=1`, `gpu::dxil::coverage`). +fn direct_fallback(stage: &str, err: &str) { + let reason = crate::gpu::dxil::coverage::record_fallback(stage, err); + crate::xlog_info!("[SHADER] direct DXIL fallback stage={stage} reason=\"{reason}\" detail=\"{}\" – HLSL path", err.lines().next().unwrap_or("")); +} + +/// A console compute shader through the direct DXIL translator (`gpu::dxil::kernel`). +/// FSPX (driver) containers are left to the HLSL path. +fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result { + let sh = xbox::parse(blob).ok_or("not a console shader container")?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?; + let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; + let p = f.programs.first().ok_or("FSSM without a program")?; + let code = &f.data[p.offset..p.offset + p.len]; + let wave64 = super::detect_wave64(code); + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base }; + let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?; + dump_direct(blob, &k.dxil); + Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }) +} + +/// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's +/// DXIL to `%TEMP%\xcl-dxil-dump\.dxil` (with `XCL_TRANSLATED_CACHE=0`, so cached +/// translations are redone). +fn dump_direct(blob: &[u8], dxil: &[u8]) { + let Ok(want) = std::env::var("XCL_DXIL_DUMP") else { return }; + let h = crate::gpu::shader::fnv64(blob); + if want == "all" || want.split(',').filter_map(|v| u64::from_str_radix(v.trim(), 16).ok()).any(|v| v == h) { + let dir = std::env::temp_dir().join("xcl-dxil-dump"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join(format!("{h:016x}.dxil")); + match std::fs::write(&path, dxil) { + Ok(()) => crate::xlog_info!("[SHADER] direct DXIL of {h:016x} ({} B) written to {}", dxil.len(), path.display()), + Err(e) => crate::xlog_warn!("[SHADER] XCL_DXIL_DUMP {}: {e}", path.display()), + } + } +} + +/// A console vertex / pixel shader through the direct DXIL translator. +fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) -> Result { + let sh = xbox::parse(blob).ok_or("not a console shader container")?; + let want = if stage == Stage::Vertex { 4 } else { 5 }; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == want)).ok_or("no hardware variant")?; + let mode = interface(blob, &sh, f).ok_or("unknown shader interface")?; + let p = f.programs.first().ok_or("FSSM without a program")?; + let code = &f.data[p.offset..p.offset + p.len]; + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: super::detect_wave64(code), split: false, mem_windows: windows, sampler_base }; + let k = match (&mode, stage) { + (Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::translate_vertex(code, o, vs)?, + (Mode::Pixel(ps), Stage::Pixel) => crate::gpu::dxil::kernel::translate_pixel(code, o, ps)?, + _ => return Err("the shader stage does not match its slot in the PSO".into()), + }; + dump_direct(blob, &k.dxil); + Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }) +} + fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(super::Translation, &'static str), String> { if let Some(f) = fspx(blob) { if stage != Stage::Compute { @@ -591,7 +719,22 @@ pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Resul let record = ms.clone(); let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - finish_two_pass(super::translate_mesh(code, ms.clone(), super::detect_wave64(code), split_wave64, mem_windows())?, record, ps) + let wave64 = super::detect_wave64(code); + // `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, split: wave64 && split_wave64, mem_windows: mem_windows(), sampler_base: 0 }; + match crate::gpu::dxil::kernel::translate_mesh(code, o, ms) { + Ok(k) => { + crate::gpu::dxil::coverage::record_translated("MS"); + 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("MS", &e), + } + } + finish_two_pass(super::translate_mesh(code, ms.clone(), wave64, split_wave64, mem_windows())?, record, ps) } /// Whether the adapter runs only 32-lane waves (its wave range lacks 64): wave64 compute, @@ -804,6 +947,61 @@ mod shader_cache_tests { let _ = std::fs::remove_dir_all(&dir); } + /// Direct DXIL entries have their own identity per routing mode and translator version; + /// the HLSL identity is the pre-direct one (its entries stay valid). + #[test] + fn direct_dxil_identity_never_collides_with_hlsl() { + use translated::{identity_for, identity_with, Backend}; + let hlsl = identity_with("s", "t", Backend::Hlsl, 1); + assert_eq!(hlsl, identity_for("s", "t")); + assert_eq!(hlsl, identity_with("s", "t", Backend::Hlsl, 2), "the direct version does not touch HLSL entries"); + let ids = [ + hlsl, + identity_with("s", "t", Backend::DirectCompute, 1), + identity_with("s", "t", Backend::DirectAll, 1), + identity_with("s", "t", Backend::DirectCompute, 2), + identity_with("s2", "t", Backend::DirectCompute, 1), + identity_with("s", "t2", Backend::DirectCompute, 1), + ]; + assert!(ids.iter().all(|&i| i != 0)); + assert_eq!(ids.iter().collect::>().len(), ids.len()); + } + + /// Hit / miss through a temp cache dir: a direct entry is reused by the same identity and + /// is a miss for the HLSL identity (and the other way round) for the same request. + #[test] + fn direct_and_hlsl_disk_entries_are_separate() { + use translated::{cached_in, identity_with, Backend}; + let dir = std::env::temp_dir().join(format!("xcl-translated-direct-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let blob = b"console-direct"; + let hlsl = identity_with("s", "t", Backend::Hlsl, 1); + let direct = identity_with("s", "t", Backend::DirectCompute, 1); + let go = |ident, marker: u8, calls: &mut u32| { + cached_in(&dir, ident, blob, Stage::Compute, 0, 1, true, || { + *calls += 1; + Ok(compiled(marker)) + }) + .unwrap() + .dxil[0] + }; + let mut calls = 0; + assert_eq!(go(direct, 1, &mut calls), 1); + assert_eq!(go(direct, 9, &mut calls), 1, "direct hit"); + assert_eq!(calls, 1); + assert_eq!(go(hlsl, 2, &mut calls), 2, "HLSL misses the direct entry"); + assert_eq!(calls, 2); + assert_eq!(go(hlsl, 9, &mut calls), 2, "HLSL hit"); + assert_eq!(go(direct, 9, &mut calls), 1, "direct entry not overwritten"); + assert_eq!(calls, 2); + let v2 = identity_with("s", "t", Backend::DirectCompute, 2); + assert_eq!(go(v2, 3, &mut calls), 3, "a version bump misses"); + // another split_wave64 / sampler base is another entry + let other = cached_in(&dir, direct, blob, Stage::Compute, 0, 1, false, || Ok(compiled(4))).unwrap(); + assert_eq!(other.dxil[0], 4); + let _ = std::fs::remove_dir_all(&dir); + } + fn key(hash: u64) -> ShaderKey { ShaderKey { hash, diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 2327e0794..f647dbd2c 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -134,6 +134,8 @@ pub enum TexDim { D2Array, D3, Cube, + /// Typed buffer (test only): `width` elements of `format`, `height` = `depth` = 1. + Buffer, } /// A texture for kernel tests: SRV at heap index 2·i, UAV (if `uav`) at 2·i + 1. @@ -211,7 +213,19 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t TexDim::D3 => (D3D12_RESOURCE_DIMENSION_TEXTURE3D, t.depth), _ => (D3D12_RESOURCE_DIMENSION_TEXTURE2D, t.depth), }; - let rd = D3D12_RESOURCE_DESC { + let rd = if t.dim == TexDim::Buffer { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (t.width * t.texel_bytes) as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if t.uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + } + } else { D3D12_RESOURCE_DESC { Dimension: dim, Width: t.width as u64, Height: t.height, @@ -221,7 +235,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Flags: if t.uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, ..Default::default() - }; + } }; let subs = if t.dim == TexDim::D3 { 1 } else { t.depth }; let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); subs as usize]; let mut size = 0u64; @@ -256,7 +270,10 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t 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)?; let r = r.ok_or("texture")?; - for (k, fp) in fps.iter().enumerate() { + if t.dim == TexDim::Buffer { + list.CopyBufferRegion(&r, 0, upload.as_ref().unwrap(), fps[0].Offset, rd.Width); + } + for (k, fp) in fps.iter().enumerate().filter(|_| t.dim != TexDim::Buffer) { let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(upload.as_ref().unwrap()), @@ -294,6 +311,12 @@ 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::Buffer => { + sv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + sv.Anonymous.Buffer = D3D12_BUFFER_SRV { NumElements: t.width, ..Default::default() }; + uv.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uv.Anonymous.Buffer = D3D12_BUFFER_UAV { NumElements: t.width, ..Default::default() }; + } } if !t.uav { dev.CreateShaderResourceView(&r, Some(&sv), at(&heap, 2 * i, inc)); @@ -359,6 +382,13 @@ pub fn wave64_supported() -> Result { gpu.as_ref().map(|x| x.wave64).map_err(|x| x.clone()) } +/// Whether the adapter runs 32-lane waves (`[WaveSize(32)]`). +pub fn wave32_supported() -> Result { + let mut g = GPU.lock().unwrap(); + let gpu = g.get_or_insert_with(init); + gpu.as_ref().map(|x| x.wave32).map_err(|x| x.clone()) +} + /// Whether wave64 programs need the split form here (`Options::split_wave64`): the /// adapter runs only 32-lane waves. False without a usable GPU. pub fn split_wave64() -> bool { @@ -527,7 +557,10 @@ pub fn run_with_statics( let (r, fps, size) = &bound.textures[i]; let rb = buffer(dev, *size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?; list.ResourceBarrier(&[transition(r, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - for (k, fp) in fps.iter().enumerate() { + if t.dim == TexDim::Buffer { + list.CopyBufferRegion(&rb, fps[0].Offset, r, 0, (t.width * t.texel_bytes) as u64); + } + for (k, fp) in fps.iter().enumerate().filter(|_| t.dim != TexDim::Buffer) { let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); @@ -588,8 +621,29 @@ pub fn run_program(code: &[u8], state: &KernelState, extra: &[u32]) -> Result<(K Ok((run_code(code, state, &mem)?, at)) } +/// `XCL_DIRECT_DXIL=1`: kernels are translated by the direct DXIL backend (`gpu::dxil::kernel`) +/// instead of HLSL + DXC; an unsupported instruction is an error (no fallback). +pub fn direct_dxil() -> bool { + crate::gpu::dxil::kernel::enabled() +} + +/// A kernel through the direct DXIL backend: a wave64 program in the split form where this +/// adapter needs it, as `options` does for the HLSL path. +pub fn direct_kernel(code: &[u8], wave64: bool) -> Result, String> { + direct_kernel_full(code, wave64).map(|k| k.dxil) +} + +/// `direct_kernel` with the static samplers the kernel's root signature needs. +pub fn direct_kernel_full(code: &[u8], wave64: bool) -> Result { + crate::gpu::dxil::kernel::translate_full(code, crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64(), mem_windows: 1, sampler_base: 0 }) +} + /// Translate + compile + run RDNA2 code as a kernel, with test textures and samplers. pub fn run_code_with(code: &[u8], state: &KernelState, mem: &[u32], textures: &[TestTexture], samplers: &[TestSampler]) -> Result { + if direct_dxil() { + let k = direct_kernel_full(code, true)?; + return run_with_statics(&k.dxil, state, mem, textures, samplers, &k.static_samplers); + } let t = super::translate(code, &options(super::Mode::Kernel))?; if !t.complete() { return Err(format!("unsupported instructions: {:?}", t.unsupported)); @@ -600,6 +654,10 @@ pub fn run_code_with(code: &[u8], state: &KernelState, mem: &[u32], textures: &[ /// Translate + compile + run RDNA2 code as a kernel. pub fn run_code(code: &[u8], state: &KernelState, mem: &[u32]) -> Result { + if direct_dxil() { + let k = direct_kernel_full(code, true)?; + return run_with_statics(&k.dxil, state, mem, &[], &[], &k.static_samplers); + } let opt = options(super::Mode::Kernel); let t = super::translate(code, &opt)?; if !t.complete() { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 56d71f0d1..0705c4593 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -60,12 +60,42 @@ fn gpu_waves() -> Vec { /// A kernel compiled as a wave64 or wave32 program, and the code as memory from address 0, /// where `runner::run_program` puts it. fn kernel_wave(code: &[u8], wave64: bool) -> (Vec, Vec) { + let mem = code.chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + if runner::direct_dxil() { + return (runner::direct_kernel(code, wave64).unwrap(), mem); + } let t = translate(code, &Options { wave64, ..Default::default() }).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); (dxil, code.chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect()) } +/// `XCL_DIRECT_DXIL=1`: the direct DXIL translator's kernel for a kernel-mode program with +/// one memory window (else `hlsl`, the HLSL path's container). +fn direct_or(code: &[u8], opt: &Options, hlsl: Vec) -> Vec { + use crate::gpu::dxil::kernel::{translate, translate_compute, KernelOptions}; + let windows = opt.mem_windows <= 4 && (opt.hw_wave == 0 || (opt.hw_wave == 32 && !opt.wave64)); + if !runner::direct_dxil() || !windows { + return hlsl; + } + let split = opt.wave64 && (opt.split_wave64 || runner::split_wave64()); + let o = KernelOptions { wave64: opt.wave64, split, mem_windows: opt.mem_windows, sampler_base: opt.static_sampler_base }; + match &opt.mode { + Mode::Kernel => translate(code, o).unwrap_or_else(|e| panic!("direct DXIL: {e}")), + Mode::Compute(cs) => translate_compute(code, o, cs).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, + Mode::Mesh(ms) => crate::gpu::dxil::kernel::translate_mesh(code, o, ms).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, + Mode::Vertex(vs) => crate::gpu::dxil::kernel::translate_vertex(code, o, vs).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, + Mode::Pixel(ps) => crate::gpu::dxil::kernel::translate_pixel(code, o, ps).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, + _ => hlsl, + } +} + +/// `XCL_DIRECT_DXIL=1`: a kernel-mode program the HLSL path only compiles must also go +/// through the direct DXIL translator (and its validator check). +fn direct_check(code: &[u8], opt: &Options) { + let _ = direct_or(code, opt, Vec::new()); +} + /// `runner::run_program` as a wave64 or wave32 program, with the number of lanes that ran. fn run_wave(code: &[u8], st: &KernelState, wave64: bool) -> (runner::KernelResult, usize) { let (dxil, mem) = kernel_wave(code, wave64); @@ -196,6 +226,7 @@ fn scalar_bfe_64_handles_unsigned_signed_and_zero_width() { assert!(t.hlsl.contains("& (0xFFFFFFFFFFFFFFFFull >> (64u -") && t.hlsl.contains("(int64_t)(t") && t.hlsl.contains("== 0u) ? 0ull"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -211,6 +242,7 @@ fn scalar_bitcmp_64_selects_the_indexed_half() { assert!(t.hlsl.contains("scc = (uint)(") && t.hlsl.contains("== 0u);"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -229,6 +261,7 @@ fn scalar_64_bit_count_scan_and_set_cluster() { assert!(t.hlsl.contains("31u - firstbithigh(s5)") && t.hlsl.contains("s7 | select((s10 & 32u) != 0u") && t.hlsl.contains("s6 & ~select((s11 & 32u) == 0u"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -246,6 +279,7 @@ fn scalar_signed_leading_bit_scans() { assert!(t.hlsl.contains("31u - firstbithigh(") && t.hlsl.contains("63u - firstbithigh(") && t.hlsl.contains("0xFFFFFFFFu"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -263,6 +297,7 @@ fn scalar_relative_move_cluster() { assert!(t.hlsl.contains("switch (m0)") && t.hlsl.contains("switch ((m0 & 0x3FFu))") && t.hlsl.contains("switch (((m0 >> 16) & 0x3FFu))"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -302,6 +337,7 @@ fn v_swaprel_b32_uses_the_m0_relative_switch() { assert!(t.hlsl.contains("if (lanebit(exec_lo, exec_hi)) { v5 = t2; switch (m0) { case 0u: v10 = t1; break; default: break; } }"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -431,6 +467,7 @@ fn atomic_fmin_fmax_x2_are_native_64_bit_atomics() { if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); super::dxc::compile(&w.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", w.hlsl)); + direct_check(&code, &Options { mem_windows: 2, ..Default::default() }); } } @@ -455,6 +492,7 @@ fn unary_f64_math_vop1_and_vop3() { assert_eq!(t.hlsl.matches("(double)1 / sqrt_d(").count(), 2, "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -655,6 +693,7 @@ fn frexp_f64_instructions() { assert!(t.hlsl.contains("frexp_mant_d(asdouble(0x00000000u, 0xBFF00000u))"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -670,6 +709,7 @@ fn rndne_f64_instructions() { assert!(t.hlsl.contains("round_ne_d(asdouble(v10, (v11 ^ 0x80000000u)))"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -1487,6 +1527,7 @@ fn buffer_format_d16_packs_and_unpacks_halves() { assert!(t.hlsl.contains("f16tof32(((v16 >> 16) & 0xFFFFu))"), "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -1619,11 +1660,12 @@ fn gpu_graphics_vs_ps_draw() { input_ena: 0x302, attrs: None, }; - let vt = translate(&vs_code, &Options { mode: Mode::Vertex(vsi), wave64: true, ..Default::default() }).unwrap(); - let pt = translate(&ps_code, &Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }).unwrap(); + let (vo, po) = (Options { mode: Mode::Vertex(vsi), wave64: true, ..Default::default() }, Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }); + let vt = translate(&vs_code, &vo).unwrap(); + let pt = translate(&ps_code, &po).unwrap(); assert!(vt.complete() && pt.complete(), "{:?} {:?}", vt.unsupported, pt.unsupported); - let vs = super::dxc::compile(&vt.hlsl, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", vt.hlsl)); - let ps = super::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + let vs = direct_or(&vs_code, &vo, super::dxc::compile(&vt.hlsl, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", vt.hlsl))); + let ps = direct_or(&ps_code, &po, super::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl))); let c = [0.8f32, 0.6, 0.4, 1.0]; let verts: Vec = [[-1.0f32, -1.0], [-1.0, 3.0], [3.0, -1.0]].iter().flat_map(|p| [p[0], p[1], c[0], c[1], c[2], c[3]]).collect(); let layout = [ @@ -2603,6 +2645,7 @@ fn global_dword_addtid_address_is_saddr_plus_4_per_lane() { assert_eq!(t.hlsl.matches("_a = ").count(), 2, "{}", t.hlsl); if super::dxc::location().is_ok() { super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); } } @@ -2853,9 +2896,10 @@ fn gpu_mesh_mode_two_passes() { list.push(exp(20, 1, [21, 0, 0, 0], 1)); let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let code = prog(&refs); - let t = translate(&code, &on_gpu(Options { mode: Mode::Mesh(ms.clone()), wave64: true, ..Default::default() })).unwrap(); + let opt = on_gpu(Options { mode: Mode::Mesh(ms.clone()), wave64: true, ..Default::default() }); + let t = translate(&code, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - let cs = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let cs = direct_or(&code, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap()); let pass = mesh_passthrough(&ms); let msb = dxc::compile(&pass, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass}")); let ps_src = "struct V { float4 pos : SV_Position; float4 p0 : TEXCOORD0; };\nfloat4 main(V v) : SV_Target0 { return v.p0; }\n"; @@ -3102,7 +3146,7 @@ fn gpu_unified_memory_arena() { ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 2), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), ]); let t = translate(&p, &on_gpu(Options::default())).unwrap(); - let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil = direct_or(&p, &on_gpu(Options::default()), super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap()); let hi = (va >> 32) as u32; let mut st = KernelState::default(); st.sgpr[2..4].copy_from_slice(&[(va + 0x1000) as u32, hi]); @@ -3228,7 +3272,9 @@ fn memory_windows_above_4_gib(heap: bool) { assert!(t.hlsl.contains("RWByteAddressBuffer mem1 : register(u3)")); assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap, "heap windows: no switch over windows"); assert_eq!(t.hlsl.contains("ResourceDescriptorHeap[NonUniformResourceIndex(0u + xcl_w)]"), heap); - let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + let hlsl_dxil = || super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + // the direct translator binds windows as root UAVs only (no heap windows yet) + let dxil = if heap { hlsl_dxil() } else { direct_or(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() }), hlsl_dxil()) }; let hi = |a: u64| (a >> 32) as u32; let mut st = KernelState::default(); st.sgpr[2..4].copy_from_slice(&[(w1 + 0x1000) as u32, hi(w1)]); @@ -3468,8 +3514,9 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 2), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), ]); let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 6, ..Default::default() }; - let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), mem_windows: 4, ..Default::default() })).unwrap(); - let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + let opt = on_gpu(Options { mode: Mode::Compute(cs), mem_windows: 4, ..Default::default() }); + let t = translate(&p, &opt).unwrap(); + let dxil = direct_or(&p, &opt, super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap()); // Execute on the real D3D12.X device + queue (goes through q_execute_command_lists -> sparse::before_execute) unsafe { @@ -4124,9 +4171,10 @@ fn gpu_compute_mode_dispatch_abi() { ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 128)], None), ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 9), ("DATA", 11), ("SADDR", 0x7D)], None), ]); - let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() })).unwrap(); + let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); + let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); let (w, h, base) = (32usize, 24usize, 0x100usize); let mut io = vec![0u32; 128]; io[0] = base as u32; @@ -4160,7 +4208,7 @@ fn gpu_wave32_program_in_wave64_hardware() { ]); let t = translate(&p, &Options { mode: Mode::Kernel, wave64: false, hw_wave: 64, ..Default::default() }).unwrap(); assert!(t.hlsl.contains("[WaveSize(64)]") && t.hlsl.contains("xcl_half"), "{}", t.hlsl); - let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil = direct_or(&p, &Options { mode: Mode::Kernel, wave64: false, hw_wave: 64, ..Default::default() }, super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap()); let mut st = KernelState::default(); st.sgpr[126] = u32::MAX; // exec of each half for (l, r) in st.vgpr.iter_mut().enumerate() { @@ -4416,7 +4464,7 @@ fn gpu_bvh64_intersect_ray_across_memory_windows_and_grazing() { code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let t = translate(&code, &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap(); - let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + let dxil = direct_or(&code, &on_gpu(Options { mem_windows: 2, ..Default::default() }), super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap()); let mut st = KernelState::default(); st.sgpr[8..12].copy_from_slice(&crate::gpu::desc::bvh_words(0, true)); @@ -5968,13 +6016,14 @@ fn gpu_split_wave64_local_and_exchanged_masks_in_diverging_waves() { for dims in [[256u32, 1, 1], [8, 8, 4]] { let threads = dims.iter().product::(); let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; - let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() })).unwrap(); + let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); + let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); if runner::split_wave64() { assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 1, "the v_cmp: read whole by the odd waves"); assert_eq!(t.hlsl.matches("= xcl_x_ballot_local(and(").count(), 2, "the carries"); } - let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); let base = 0x100usize; let mut io = vec![0u32; 128]; io[0] = base as u32; @@ -6046,12 +6095,13 @@ fn gpu_split_wave64_waves_diverge() { for dims in [[256u32, 1, 1], [64, 1, 1], [8, 8, 4], [16, 4, 1]] { let threads = dims.iter().product::(); let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; - let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() })).unwrap(); + let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); + let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); if runner::split_wave64() && std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0") { assert!(t.hlsl.contains("[WaveSize(32)]") && t.hlsl.contains("#define XCL_X_SPIN 1"), "{dims:?}"); } - let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); let base = 0x100usize; let mut io = vec![0u32; 128]; io[0] = base as u32; @@ -6123,12 +6173,13 @@ fn bench_split_wave64() { let mut exchanges = 0; for wave64 in [false, true] { let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; - let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() })).unwrap(); + let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() }); + let t = translate(&p, &opt).unwrap(); // the loop's exchanges: masks read whole (`x64_masks`: not the v_cndmask // selector, unless `XCL_X64_ALL_MASKS`) and the readfirstlane exchanges = t.hlsl.matches("= xcl_x_ballot(and(").count() + t.hlsl.matches("xcl_x_rla_uniform(").count().saturating_sub(1); assert!(t.complete(), "{:?}", t.unsupported_why); - let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); let groups = (1u32 << 18) / threads; let mut io = vec![0u32; 128]; io[0] = 0; @@ -6702,7 +6753,7 @@ fn gpu_nonfused_mad_and_mac_prevent_fma_contraction() { let opt = Options { wave64: false, hw_wave: 32, ..Options::default() }; let t = translate(&code, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil = direct_or(&code, &opt, super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap()); let mut st = KernelState::default(); st.sgpr[127] = 0; @@ -6818,7 +6869,7 @@ fn gpu_s_round_mode_controls_f16_rounding_across_modes() { let opt = Options { wave64: false, hw_wave: 32, ..Options::default() }; let t = translate(&code, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil = direct_or(&code, &opt, super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap()); // (f32 bits, RNE, RTZ, +inf, -inf) let cases: &[(u32, u16, u16, u16, u16)] = &[ @@ -6965,7 +7016,7 @@ fn gpu_ds_swizzle_and_bpermute_zero_inactive_lanes() { let code = prog(&insns); let t = translate(&code, &Options { wave64, split_wave64, ..Default::default() }).unwrap(); assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); - let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let dxil = direct_or(&code, &Options { wave64, split_wave64, ..Default::default() }, super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl))); let mut st = KernelState::default(); let lanes = if wave64 { 64 } else { 32 }; for (l, r) in st.vgpr.iter_mut().take(lanes).enumerate() { diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 83ed10292..bb6c3e921 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -34,6 +34,9 @@ Usage: for the recompiler). RPF9 packages are scanned for shader records. --recomp: translates every RDNA2 program → HLSL and shows what is missing; --compile N: additionally compiles N complete translations with DXC. + --direct [--sample N] [--seed S] [--validate] [--compare]: direct DXIL translator + coverage over a seeded sample (default 200 programs, 0 = all); also + --timeout, --max-bytes, --threads, --json, --hash H, --dump DIR. xcl rpf [--top N] [--find NAME] [--extract NAME --out DIR] Lists or extracts readable inline records. Archives larger than 1 GB use a bounded-memory header probe; --probe requests it explicitly and --full overrides it. diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index d54f98b78..45b886e10 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -171,6 +171,8 @@ fn lock_within(m: &Mutex, wait: Duration) -> Option> { pub fn write_final(crash: Option) { // the process ends: a cursor held in the XCL window is let go crate::hle::kbm::release(); + // `XCL_DIRECT_DXIL_STATS=1`: the direct DXIL translator's live fallback summary + crate::gpu::dxil::coverage::dump_fallbacks(); // a crash is kept even while another thread writes the report, and is written once that // thread is done – the process ends right after (#106); other calls give way at once let wait = if crash.is_some() { Duration::from_secs(2) } else { Duration::ZERO }; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index a2ee0de96..057801827 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -720,6 +720,9 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let windows = if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows }; return precompile(&input, opt("--limit").unwrap_or(usize::MAX), windows, opt("--split").map(|v| v != 0), only.as_deref(), pipelines, t0); } + if args.iter().any(|a| a == "--direct") { + return direct_sweep(&input, args, top, json, t0); + } let agg = analyze(&input, recomp_on, compile, iface_on); drop(input); print(path, &what, agg, top, json, t0, compile) @@ -1322,3 +1325,130 @@ fn name_hash(name: &str) -> u64 { } h } + +/// `--direct [--sample N] [--seed S] [--validate] [--compare] [--split 0|1] [--windows W]`: +/// every program of a seeded sample of N records (default 200 programs' worth; `--sample 0` = +/// all) through the direct DXIL translator; per-stage outcomes, a ranked histogram of what it +/// cannot translate, translation times and (`--compare`) DXIL size vs HLSL + DXC. +fn direct_sweep(input: &Input, args: &[String], top: usize, json: bool, t0: std::time::Instant) -> i32 { + use crate::gpu::dxil::coverage::{self, Report, Sample}; + let opt = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).and_then(|v| v.parse::().ok()); + let want = opt("--sample").map(|v| v as usize).unwrap_or(200); + let want = if want == 0 { usize::MAX } else { want }; + let seed = opt("--seed").unwrap_or(1); + let validate = args.iter().any(|a| a == "--validate"); + let compare = args.iter().any(|a| a == "--compare"); + let windows = opt("--windows").unwrap_or(4) as u32; + let split = opt("--split").map(|v| v != 0).unwrap_or(true); + // records hold one or more programs: sample records, stop at `want` programs + let order = coverage::sample_indices(input.len(), want, seed); + let next = AtomicUsize::new(0); + let taken = AtomicUsize::new(0); + let threads = opt("--threads").map(|v| v.max(1) as usize).unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).min(8)); + let trace = args.iter().any(|a| a == "--trace"); + // big programs translate slowly (SSA over every guarded access): skip above the cap, + // give up on one after the timeout (its thread is left to finish; the process ends soon) + let max_bytes = opt("--max-bytes").map(|v| v as usize).unwrap_or(16384); + let timeout = std::time::Duration::from_secs(opt("--timeout").unwrap_or(10)); + let skipped = AtomicUsize::new(0); + // `--hash H`: only the container whose `[SHADER]` hash (FNV-64 of the container) is H, every + // record searched; `--dump DIR`: write each program's direct DXIL (and with `--compare` the + // HLSL path's source and DXIL) to DIR, for diffing the two (`dxc -dumpbin`) + let only_hash = args.iter().position(|a| a == "--hash").and_then(|i| args.get(i + 1)).and_then(|v| u64::from_str_radix(v.trim_start_matches("0x"), 16).ok()); + let dump_dir = args.iter().position(|a| a == "--dump").and_then(|i| args.get(i + 1)).map(std::path::PathBuf::from); + if let Some(d) = &dump_dir { + let _ = std::fs::create_dir_all(d); + } + let (order, want, max_bytes) = if only_hash.is_some() { ((0..input.len()).collect(), usize::MAX, 0) } else { (order, want, max_bytes) }; + // translator panics are counted, not printed (`--trace` keeps the messages) + if !trace { + std::panic::set_hook(Box::new(|_| {})); + } + let results: Mutex> = Mutex::new(Vec::new()); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(&ri) = order.get(i) else { break }; + if taken.load(Ordering::Relaxed) >= want { + break; + } + let (name, Some(blob)) = input.get(ri) else { continue }; + let blob_hash = crate::gpu::shader::fnv64(&blob); + if only_hash.is_some_and(|h| h != blob_hash) { + continue; + } + let Some(sh) = xbox::parse(&blob) else { continue }; + for (fi, f) in sh.fssm.iter().enumerate() { + let Some(mode) = recomp::interface(&blob, &sh, f) else { continue }; + for p in &f.programs { + if taken.fetch_add(1, Ordering::Relaxed) >= want { + return; + } + let code = &f.data[p.offset..p.offset + p.len]; + if max_bytes > 0 && code.len() > max_bytes { + skipped.fetch_add(1, Ordering::Relaxed); + continue; + } + let wave64 = recomp::detect_wave64(code); + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split, mem_windows: windows, sampler_base: 0 }; + if trace { + eprintln!("direct: {name} FSSM#{fi} ({} B, {})", code.len(), coverage::stage_name(&mode)); + } + let t = std::time::Instant::now(); + let r = { + let (tx, rx) = std::sync::mpsc::channel(); + let (c, m) = (code.to_vec(), mode.clone()); + std::thread::spawn(move || { + let _ = tx.send(coverage::translate_mode(&c, &m, o, validate)); + }); + rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) + }; + let time = t.elapsed(); + let dump = |suffix: &str, bytes: &[u8]| { + if let Some(d) = &dump_dir { + let _ = std::fs::write(d.join(format!("{blob_hash:016x}_f{fi}_{:x}.{suffix}", p.offset)), bytes); + } + }; + dump("guest.bin", code); + match &r { + Ok(dxil) => dump("direct.dxil", dxil), + Err(e) => dump("direct.err.txt", e.as_bytes()), + } + let hlsl_size = (compare && r.is_ok()) + .then(|| { + let profile = match mode { + recomp::Mode::Vertex(_) => "vs_6_6", + recomp::Mode::Pixel(_) => "ps_6_6", + _ => "cs_6_6", + }; + let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: wave64 && split, mem_windows: windows, ..Default::default() }; + let t = recomp::translate(code, &opt).ok().filter(|t| t.complete())?; + dump("hlsl", t.hlsl.as_bytes()); + let d = recomp::dxc::compile(&t.hlsl, "main", profile, &[]).ok()?; + dump("hlsl.dxil", &d); + Some(d.len()) + }) + .flatten(); + let sample = Sample { stage: coverage::stage_name(&mode), result: r.map(|d| d.len()), time, hlsl_size }; + results.lock().unwrap().push((format!("{name} FSSM#{fi}"), sample)); + } + } + }); + } + }); + let mut results = results.into_inner().unwrap(); + results.sort_by(|a, b| a.0.cmp(&b.0)); + let mut rep = Report::default(); + for (name, s) in &results { + rep.add(name, s); + } + if json { + println!("{}", rep.json(top)); + } else { + println!("{} programs from {} sampled records (seed {seed}; {} over {max_bytes} B skipped){}{}", results.len(), order.len().min(input.len()), skipped.load(Ordering::Relaxed), if validate { ", validated" } else { "" }, if compare { ", compared with HLSL+DXC" } else { "" }); + print!("{}", rep.text(top)); + println!("time {:.1} s", t0.elapsed().as_secs_f64()); + } + 0 +} diff --git a/docs/specs/2026-11-24-direct-dxil.md b/docs/specs/2026-11-24-direct-dxil.md new file mode 100644 index 000000000..8abb51389 --- /dev/null +++ b/docs/specs/2026-11-24-direct-dxil.md @@ -0,0 +1,118 @@ +# Direct DXIL backend — design and roadmap (2026-11-24) + +Branch `shaders/direct-dxil`, code in `crates/xcl/src/gpu/dxil/`. + +## Goal + +Translate console RDNA2 programs straight to signed DXIL containers, with no +HLSL text and no DXC at run time, while keeping the HLSL → DXC path as a +per-shader fallback until the direct path matches its 100 % corpus coverage. + +Why: compile latency on cache misses (DXC takes from hundreds of ms to +seconds, and gigabytes, on large translated programs), no dependency on the +Windows SDK's `dxcompiler.dll`/`dxil.dll`, exact control over float +semantics (no implicit fast-math), and much smaller intermediate output. + +## Provenance and licensing + +XCL is GPL-2.0-only. References used: + +- LLVM 3.7 bitcode format and DXC (`DxilOperations`, `DXIL.rst`, the + container hash) — University of Illinois/NCSA, GPL-compatible. +- DXC's *output* for small HLSL test programs (`tests/data/dxil/`), dumped with a + local bitstream reader, as the layout oracle. +- Mesa `src/microsoft/compiler` (MIT) may be ported with a provenance note. + +**Not used:** the VIctory project (GPL-3.0-or-later, incompatible). Its +public architecture description informed the approach below; no code was +read for porting or copied. + +## Layers (done) + +| Module | Role | +|---|---| +| `bitstream` | LLVM bitstream writer: fixed/VBR fields, blocks with back-patched lengths, unabbreviated records | +| `module` | LLVM 3.7 module: interned types, module-level constants, function declarations, one defined entry, instructions (binop, cast, cmp, select, extractvalue, call, phi, load/store/GEP, atomicrmw/cmpxchg, br/switch/ret), metadata; bitcode writer with relative operand numbering | +| `shader` | DXIL layer: `dx.op` calls, `createHandleFromBinding`/`FromHeap` + `annotateHandle`, raw buffer load/store, wave ops, system values, entry metadata, shader flags ↔ `SFI0` bits | +| `container` | DXBC container: `SFI0`, `ISG1`/`OSG1`, `PSV0` (RuntimeInfo3), `DXIL` program header, retail digest (verified against DXC byte for byte) | +| `validate` | DXC 1.9's internal validator and disassembler as test oracles | + +Verified: the emitted sample kernel (branch + phi, raw UAV load/store, wave +read-lane, WaveSize) passes the validator, disassembles as expected, and runs +on the GPU with the recompiler's kernel ABI, matching a CPU reference. + +## Translator architecture (to build) + +The HLSL backend emulates the wave: a uniform `switch (pc)` dispatcher over +register arrays, EXEC as an explicit mask. That form is exact but leans on +DXC's optimiser. Emitting it unoptimised as DXIL would leave register arrays +in scratch memory. The direct backend therefore uses a per-lane model: + +1. **SSA construction** (`dxil/ssa.rs`). Build a CFG from the decoded program + (reuse `rdna2` decode and `recomp` analysis). Each register dword is a + variable, with SSA built by the Braun et al. on-the-fly algorithm (no + dominance frontiers needed). SCC, VCC, M0 and EXEC are explicit operands. + A VGPR write also reads the old value, because disabled lanes keep it. +2. **Lane-mask lowering** (`dxil/lanes.rs`). Lane masks become per-lane + booleans (this lane's bit of EXEC/VCC/compare results), represented as a + small hash-consed boolean DAG. Branches on wave-uniform tests of masks + (`s_cbranch_execz`, `vccz`, SCC of `s_and_saveexec`) become per-lane + branches. A path-sensitive dataflow proves where this lane's EXEC bit is + set; vector instructions not proven keep a per-lane guard. Values that + really are wave-wide (`s_bcnt1` of a mask, `v_readlane`, ballots) are + rebuilt with `WaveActiveBallot`/`WaveReadLaneAt`/`WaveActiveCountBits`. +3. **Whole-wave regions.** Code between `s_or_saveexec -1` and the restore + (DPP/permlane reductions and prefix sums the console compiler expands) is + evaluated symbolically over the console's lanes. The result is + classified as a reduction or prefix of a known associative operation and + emitted as the DXIL wave op. This makes wave64 reduction code correct on + wave32 hosts. Anything unrecognised falls back to the HLSL path. +4. **Control flow.** DXIL needs a reducible CFG. Console code is reducible in + practice; irreducible input falls back. Blocks are emitted in reverse + post-order so non-phi operands never forward-reference. +5. **Lowering** (`dxil/lower.rs`). One machine instruction → DXIL + instructions, sharing the semantic tables the HLSL emitter already + encodes (float compare classes, DPP/SDWA selects, buffer formats, + denorm/rounding modes). Exactness rules: no fast-math flags; explicit + NaN/denorm handling where RDNA and DXIL differ (`V_FRACT_F32(+inf)`, + min/max NaN rules, `v_rcp` precision). +6. **Resources.** Descriptor addresses are traced to their root/user-data + sources (reuse the recompiler's T#/V#/S# analysis) and mapped to SM 6.6 + heap indexing or root descriptors, matching `pso.rs`'s ABI. +7. **Light optimisation passes** on the SSA (constant folding, dead code, + copy propagation, guard merging) before emission. Drivers do the heavy + optimisation. + +## Testing strategy + +- Validator + disassembly on every emitted shader in tests. +- **Differential GPU testing:** the existing `recomp/tests.rs` instruction + tests (≈6k lines, `runner::run`) take DXIL bytes. Every test runs the same + RDNA program through both backends, which must give identical final + registers and memory. +- Corpus sweep: translate the bounded validation corpus (9,282 programs) + and record per-program direct/fallback status and validator results, on + small samples per the project's time constraints. +- Live: route compute first, behind `XCL_DIRECT_DXIL=1`, with the HLSL path as + fallback on any unsupported construct. + +## Roadmap + +| Phase | Content | Exit criterion | +|---|---|---| +| 0 ✅ | Bitstream, module, DXIL layer, container + hash, validator oracle, GPU smoke test | Emitted kernel validates and runs | +| 1 ✅ | SSA + per-lane model for straight-line and branchy **compute kernels in the test ABI**; SALU/VALU integer + float ALU | Differential tests pass for ALU instruction tests | +| 2 ✅ | Memory: `buffer_*`/`tbuffer_*`/`s_load`/`s_buffer_load`/flat/global, LDS (`ds_*` → groupshared), atomics | Memory instruction tests pass | +| 3 ✅ | Cross-lane: DPP16/DPP8, `v_readlane`/`v_writelane`, permlane, whole-wave regions | Cross-lane tests pass, wave64 on wave32 | +| 4 (partial) | Real compute shaders: resource tracing → heap/root bindings; `XCL_DIRECT_DXIL=1` live routing with fallback | Corpus CS coverage measured, live title runs | +| 5 (partial) | Graphics: VS/PS signatures (`ISG1`/`OSG1`/PSV elements), interpolation, exports, images/samplers | VS/PS tests and live draws | +| 6 (partial) | Mesh/two-pass pipelines, mesh output metadata | Mesh tests | +| 7 | Default-on for covered shaders, cache keying on backend version | Parity with the HLSL path | + +Status (main-based port, 2026-11-24): phases 1–3 done; 4–6 partial — live routing +behind `XCL_DIRECT_DXIL=1` (compute + mesh compute pass) / `=all` (VS/PS) with a +logged HLSL fallback is in, corpus coverage and live-title runs are not measured +yet. Model: a faithful EXEC/ballot model (EXEC and VCC as wave masks, lanes +predicated per instruction over a structured block CFG); per-lane +structurization (real divergent control flow instead of predication) is future +work. Coverage: `xcl shaders --direct`. diff --git a/tests/data/dxil/dxc_cs_raw_uav.dxil b/tests/data/dxil/dxc_cs_raw_uav.dxil new file mode 100644 index 000000000..1cf128bef Binary files /dev/null and b/tests/data/dxil/dxc_cs_raw_uav.dxil differ diff --git a/tests/data/dxil/dxc_cs_raw_uav.hlsl b/tests/data/dxil/dxc_cs_raw_uav.hlsl new file mode 100644 index 000000000..937b6dd32 --- /dev/null +++ b/tests/data/dxil/dxc_cs_raw_uav.hlsl @@ -0,0 +1,10 @@ +RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer res : register(u1); +[WaveSize(64)] +[numthreads(64,1,1)] +void main(uint3 id : SV_GroupThreadID) { + uint a = io.Load(id.x*4); + float f = asfloat(a) * 2.0f + 1.0f; + if (a > 5) f = -f; + res.Store(id.x*4, asuint(f) + WaveReadLaneAt(a, 3)); +} diff --git a/tests/data/dxil/dxc_cs_resources.dxil b/tests/data/dxil/dxc_cs_resources.dxil new file mode 100644 index 000000000..8f9c15ed7 Binary files /dev/null and b/tests/data/dxil/dxc_cs_resources.dxil differ diff --git a/tests/data/dxil/dxc_cs_resources.hlsl b/tests/data/dxil/dxc_cs_resources.hlsl new file mode 100644 index 000000000..8abb276a1 --- /dev/null +++ b/tests/data/dxil/dxc_cs_resources.hlsl @@ -0,0 +1,14 @@ +ByteAddressBuffer rawb : register(t0); +StructuredBuffer sb : register(t1); +Buffer tb : register(t2); +Texture2D tex : register(t3, space1); +cbuffer CB : register(b0) { uint4 a; uint4 b; }; +SamplerState smp : register(s0); +SamplerComparisonState cmp : register(s1); +RWByteAddressBuffer res : register(u1); +[numthreads(32,1,1)] +void main(uint id : SV_GroupIndex) { + uint v = rawb.Load(id*4) + sb[id].y + asuint(tb[id].x) + b.y; + float f = tex.SampleLevel(smp, float2(0.5,0.5), 0).x + tex.SampleCmpLevelZero(cmp, float2(0.5,0.5), 0.5); + res.Store(id*4, v + asuint(f)); +} diff --git a/tests/data/dxil/dxc_ms_basic.dxil b/tests/data/dxil/dxc_ms_basic.dxil new file mode 100644 index 000000000..7d5ffb7f9 Binary files /dev/null and b/tests/data/dxil/dxc_ms_basic.dxil differ diff --git a/tests/data/dxil/dxc_ms_basic.hlsl b/tests/data/dxil/dxc_ms_basic.hlsl new file mode 100644 index 000000000..fbd374285 --- /dev/null +++ b/tests/data/dxil/dxc_ms_basic.hlsl @@ -0,0 +1,10 @@ +struct V { float4 pos : SV_Position; float4 color : COLOR0; }; +struct P { uint id : SV_PrimitiveID; nointerpolation float2 extra : EXTRA; }; +struct Pay { uint x; }; +[outputtopology("triangle")] +[numthreads(32, 1, 1)] +void main(uint tid : SV_GroupThreadID, out vertices V verts[3], out indices uint3 tris[1], out primitives P prims[1]) { + SetMeshOutputCounts(3, 1); + if (tid < 3) { V v; v.pos = float4(tid, 0, 0, 1); v.color = float4(1,0,0,1); verts[tid] = v; } + if (tid == 0) { tris[0] = uint3(0,1,2); P p; p.id = 7; p.extra = float2(1,2); prims[0] = p; } +} diff --git a/tests/data/dxil/dxc_ms_payload.dxil b/tests/data/dxil/dxc_ms_payload.dxil new file mode 100644 index 000000000..1ba8e7052 Binary files /dev/null and b/tests/data/dxil/dxc_ms_payload.dxil differ diff --git a/tests/data/dxil/dxc_ms_payload.hlsl b/tests/data/dxil/dxc_ms_payload.hlsl new file mode 100644 index 000000000..d29e7b9c7 --- /dev/null +++ b/tests/data/dxil/dxc_ms_payload.hlsl @@ -0,0 +1,13 @@ +struct V { float4 pos : SV_Position; }; +struct P { nointerpolation uint k : PRIMK; bool cull : SV_CullPrimitive; uint rt : SV_RenderTargetArrayIndex; }; +struct Pay { uint a; float b[3]; }; +groupshared uint gs[16]; +[outputtopology("line")] +[numthreads(16, 2, 1)] +void main(uint tid : SV_GroupIndex, in payload Pay pay, out vertices V verts[4], out indices uint2 lines[2], out primitives P prims[2]) { + gs[tid % 16] = pay.a; + GroupMemoryBarrierWithGroupSync(); + SetMeshOutputCounts(4, 2); + if (tid < 4) { verts[tid].pos = float4(gs[(tid + 1) % 16], pay.b[tid % 3], 0, 1); } + if (tid < 2) { lines[tid] = uint2(tid, tid + 1); prims[tid].k = tid; prims[tid].cull = false; prims[tid].rt = 1; } +} diff --git a/tests/data/dxil/dxc_ps_basic.dxil b/tests/data/dxil/dxc_ps_basic.dxil new file mode 100644 index 000000000..0498f8fe9 Binary files /dev/null and b/tests/data/dxil/dxc_ps_basic.dxil differ diff --git a/tests/data/dxil/dxc_ps_basic.hlsl b/tests/data/dxil/dxc_ps_basic.hlsl new file mode 100644 index 000000000..56c207222 --- /dev/null +++ b/tests/data/dxil/dxc_ps_basic.hlsl @@ -0,0 +1 @@ +float4 main(float4 pos : SV_Position, float4 color : COLOR0, float2 uv : TEXCOORD1) : SV_Target { return color + uv.xyxy; } diff --git a/tests/data/dxil/dxc_ps_early.dxil b/tests/data/dxil/dxc_ps_early.dxil new file mode 100644 index 000000000..b73ca0622 Binary files /dev/null and b/tests/data/dxil/dxc_ps_early.dxil differ diff --git a/tests/data/dxil/dxc_ps_early.hlsl b/tests/data/dxil/dxc_ps_early.hlsl new file mode 100644 index 000000000..0c4b129a0 --- /dev/null +++ b/tests/data/dxil/dxc_ps_early.hlsl @@ -0,0 +1 @@ +[earlydepthstencil] float4 main(float4 p : SV_Position) : SV_Target { return p; } diff --git a/tests/data/dxil/dxc_ps_min16.dxil b/tests/data/dxil/dxc_ps_min16.dxil new file mode 100644 index 000000000..b48e6c6df Binary files /dev/null and b/tests/data/dxil/dxc_ps_min16.dxil differ diff --git a/tests/data/dxil/dxc_ps_min16.hlsl b/tests/data/dxil/dxc_ps_min16.hlsl new file mode 100644 index 000000000..29c53e31d --- /dev/null +++ b/tests/data/dxil/dxc_ps_min16.hlsl @@ -0,0 +1 @@ +min16float4 main(min16float2 a : A, min16uint b : B) : SV_Target { return min16float4(a, b, 1); } diff --git a/tests/data/dxil/dxc_ps_modes.dxil b/tests/data/dxil/dxc_ps_modes.dxil new file mode 100644 index 000000000..4427561af Binary files /dev/null and b/tests/data/dxil/dxc_ps_modes.dxil differ diff --git a/tests/data/dxil/dxc_ps_modes.hlsl b/tests/data/dxil/dxc_ps_modes.hlsl new file mode 100644 index 000000000..a339a321d --- /dev/null +++ b/tests/data/dxil/dxc_ps_modes.hlsl @@ -0,0 +1,3 @@ +struct O { float4 a : SV_Target0; float4 b : SV_Target1; float d : SV_Depth; }; +O main(float4 pos : SV_Position, nointerpolation uint m : MODE, centroid float2 c : TEXCOORD0, noperspective float t : TEXCOORD1, sample float3 s : TEXCOORD2, bool ff : SV_IsFrontFace, uint pid : SV_PrimitiveID, uint cov : SV_Coverage, linear centroid noperspective float q : Q) { + O o; if (m == 3) discard; o.a = float4(c, t, s.x); o.b = float4(s.yz, ff ? 1 : 0, pid + cov + q); o.d = pos.z; return o; } diff --git a/tests/data/dxil/dxc_ps_native16.dxil b/tests/data/dxil/dxc_ps_native16.dxil new file mode 100644 index 000000000..9d536eccd Binary files /dev/null and b/tests/data/dxil/dxc_ps_native16.dxil differ diff --git a/tests/data/dxil/dxc_ps_native16.hlsl b/tests/data/dxil/dxc_ps_native16.hlsl new file mode 100644 index 000000000..c0b398ae9 --- /dev/null +++ b/tests/data/dxil/dxc_ps_native16.hlsl @@ -0,0 +1 @@ +half4 main(half2 a : A, uint16_t b : B) : SV_Target { return half4(a, b, 1); } diff --git a/tests/data/dxil/dxc_ps_outputs.dxil b/tests/data/dxil/dxc_ps_outputs.dxil new file mode 100644 index 000000000..761c197fc Binary files /dev/null and b/tests/data/dxil/dxc_ps_outputs.dxil differ diff --git a/tests/data/dxil/dxc_ps_outputs.hlsl b/tests/data/dxil/dxc_ps_outputs.hlsl new file mode 100644 index 000000000..893c30f18 --- /dev/null +++ b/tests/data/dxil/dxc_ps_outputs.hlsl @@ -0,0 +1,2 @@ +struct O { float4 c : SV_Target2; uint cov : SV_Coverage; float d : SV_DepthGreaterEqual; uint s : SV_StencilRef; }; +O main(noperspective centroid float4 p : SV_Position, nointerpolation uint k : PRIMK, uint rt : SV_RenderTargetArrayIndex) { O o; o.c = float4(k, rt, 0, 1); if (p.x > 4) o.c.z = 2; o.cov = 1; o.d = 0.5; o.s = k; return o; } diff --git a/tests/data/dxil/dxc_ps_packing.dxil b/tests/data/dxil/dxc_ps_packing.dxil new file mode 100644 index 000000000..b8fe01646 Binary files /dev/null and b/tests/data/dxil/dxc_ps_packing.dxil differ diff --git a/tests/data/dxil/dxc_ps_packing.hlsl b/tests/data/dxil/dxc_ps_packing.hlsl new file mode 100644 index 000000000..fa44f0af1 --- /dev/null +++ b/tests/data/dxil/dxc_ps_packing.hlsl @@ -0,0 +1 @@ +float4 main(nointerpolation uint a : A, bool ff : SV_IsFrontFace, nointerpolation uint b : B, float c : C, float2 d : D, nointerpolation float e : E, uint si : SV_SampleIndex, float4 p : SV_Position, nointerpolation int h : H, uint4 rest : REST) : SV_Target { return a + ff + b + c + d.x + e + si + p.x + h; } diff --git a/tests/data/dxil/dxc_ps_resources.dxil b/tests/data/dxil/dxc_ps_resources.dxil new file mode 100644 index 000000000..1b16dea2c Binary files /dev/null and b/tests/data/dxil/dxc_ps_resources.dxil differ diff --git a/tests/data/dxil/dxc_ps_resources.hlsl b/tests/data/dxil/dxc_ps_resources.hlsl new file mode 100644 index 000000000..bd85721a2 --- /dev/null +++ b/tests/data/dxil/dxc_ps_resources.hlsl @@ -0,0 +1,4 @@ +cbuffer RC : register(b2, space1) { uint k; float scale; }; +Texture2D tex : register(t0); +SamplerState smp : register(s3); +float4 main(float4 p : SV_Position) : SV_Target { return tex.Sample(smp, p.xy * scale) + (float)k; } diff --git a/tests/data/dxil/dxc_vs_basic.dxil b/tests/data/dxil/dxc_vs_basic.dxil new file mode 100644 index 000000000..6a8fe9c38 Binary files /dev/null and b/tests/data/dxil/dxc_vs_basic.dxil differ diff --git a/tests/data/dxil/dxc_vs_basic.hlsl b/tests/data/dxil/dxc_vs_basic.hlsl new file mode 100644 index 000000000..0a53439f1 --- /dev/null +++ b/tests/data/dxil/dxc_vs_basic.hlsl @@ -0,0 +1,3 @@ +struct VSOut { float4 pos : SV_Position; float4 color : COLOR0; float2 uv : TEXCOORD1; }; +VSOut main(float3 p : POSITION, float4 c : COLOR, uint vid : SV_VertexID) { + VSOut o; o.pos = float4(p, 1); o.color = c; o.uv = float2(vid, 0); return o; } diff --git a/tests/data/dxil/dxc_vs_clip.dxil b/tests/data/dxil/dxc_vs_clip.dxil new file mode 100644 index 000000000..235f6e40f Binary files /dev/null and b/tests/data/dxil/dxc_vs_clip.dxil differ diff --git a/tests/data/dxil/dxc_vs_clip.hlsl b/tests/data/dxil/dxc_vs_clip.hlsl new file mode 100644 index 000000000..7059266f2 --- /dev/null +++ b/tests/data/dxil/dxc_vs_clip.hlsl @@ -0,0 +1,2 @@ +struct VSOut { float4 pos : SV_Position; float2 a : A; float3 clip : SV_ClipDistance0; float c : C; float2 cull : SV_CullDistance0; float clip1 : SV_ClipDistance1; nointerpolation uint vp : SV_ViewportArrayIndex; }; +VSOut main(float4 p : POSITION) { VSOut o; o.pos = p; o.a = p.xy; o.clip = p.xyz; o.c = p.w; o.cull = p.zw; o.clip1 = p.x; o.vp = 1; return o; } diff --git a/tests/data/dxil/dxc_vs_clip_rows.dxil b/tests/data/dxil/dxc_vs_clip_rows.dxil new file mode 100644 index 000000000..addbd3493 Binary files /dev/null and b/tests/data/dxil/dxc_vs_clip_rows.dxil differ diff --git a/tests/data/dxil/dxc_vs_clip_rows.hlsl b/tests/data/dxil/dxc_vs_clip_rows.hlsl new file mode 100644 index 000000000..9f4913672 --- /dev/null +++ b/tests/data/dxil/dxc_vs_clip_rows.hlsl @@ -0,0 +1,2 @@ +struct VSOut { float4 pos : SV_Position; float a : A; float clip : SV_ClipDistance0; float b : B; float cull : SV_CullDistance0; float c : C; float2 d : D; }; +VSOut main(float4 p : POSITION) { VSOut o; o.pos = p; o.a = p.x; o.clip = p.y; o.b = p.z; o.cull = p.w; o.c = 1; o.d = 2; return o; } diff --git a/tests/data/dxil/dxc_vs_control.dxil b/tests/data/dxil/dxc_vs_control.dxil new file mode 100644 index 000000000..7ed6002bc Binary files /dev/null and b/tests/data/dxil/dxc_vs_control.dxil differ diff --git a/tests/data/dxil/dxc_vs_control.hlsl b/tests/data/dxil/dxc_vs_control.hlsl new file mode 100644 index 000000000..7ca1a3f22 --- /dev/null +++ b/tests/data/dxil/dxc_vs_control.hlsl @@ -0,0 +1,6 @@ +struct VSOut { float4 pos : SV_Position; float a : A; float b : B; }; +VSOut main(float4 p : POSITION, float c : C, uint iid : SV_InstanceID) { + VSOut o; o.pos = p; o.a = 0; o.b = 1; + [branch] if (c > 0.5) { o.a = p.x * 2; } + [loop] for (uint i = 0; i < iid; i++) { o.b += p.y; } + return o; } diff --git a/tests/data/dxil/dxc_vs_packing.dxil b/tests/data/dxil/dxc_vs_packing.dxil new file mode 100644 index 000000000..f3029d7e0 Binary files /dev/null and b/tests/data/dxil/dxc_vs_packing.dxil differ diff --git a/tests/data/dxil/dxc_vs_packing.hlsl b/tests/data/dxil/dxc_vs_packing.hlsl new file mode 100644 index 000000000..8e1eae62b --- /dev/null +++ b/tests/data/dxil/dxc_vs_packing.hlsl @@ -0,0 +1,3 @@ +struct VSOut { float2 a : A; float2 b : B; float c : C; nointerpolation uint d : D; float4 pos : SV_Position; float e : E; nointerpolation uint rt : SV_RenderTargetArrayIndex; nointerpolation uint2 f : F; float3 g : G; float2x2 m : M; uint i : I; }; +VSOut main(uint vid : SV_VertexID, uint iid : SV_InstanceID) { + VSOut o; o.a = vid; o.b = 1; o.c = 2; o.d = iid; o.pos = 0; o.e = 3; o.rt = vid; o.f = iid; o.g = 4; o.m = float2x2(1,2,3,vid); o.i = 5; return o; } diff --git a/tests/data/dxil/dxc_vs_uav.dxil b/tests/data/dxil/dxc_vs_uav.dxil new file mode 100644 index 000000000..a4b43e522 Binary files /dev/null and b/tests/data/dxil/dxc_vs_uav.dxil differ diff --git a/tests/data/dxil/dxc_vs_uav.hlsl b/tests/data/dxil/dxc_vs_uav.hlsl new file mode 100644 index 000000000..87b7ea076 --- /dev/null +++ b/tests/data/dxil/dxc_vs_uav.hlsl @@ -0,0 +1,2 @@ +RWByteAddressBuffer mem : register(u2); +float4 main(uint vid : SV_VertexID) : SV_Position { return asfloat(mem.Load4(vid * 16)); }