From 852bb2de707efab2910f4d2bfc7bb37cc2a428bf Mon Sep 17 00:00:00 2001 From: SombraSoft Date: Tue, 24 Nov 2026 16:30:15 -0300 Subject: [PATCH 1/3] Shaders: read DXIL bitcode with abbreviations and BLOCKINFO A compile-cost report needs to read the DXIL that DXC emits, and the only reader in the tree (bitreader_tests.rs) handles the unabbreviated records our own writer produces. DXC's LLVM 3.7 writer uses abbreviations defined in BLOCKINFO and locally, char6 arrays and blobs. BitReader walks the bitstream one entry at a time (enter block, end block, record) with the block stack on the heap, so nesting depth costs no recursion. BLOCKINFO is consumed internally; skip_block jumps over blocks a caller does not need. Every count read from the stream (operands, array elements, blob bytes, block lengths) is checked against the bits left in its block before anything is read or allocated, and bitcode that is not whole 32-bit words is refused, so corrupt input is an Err, not a panic or a large allocation. Tested: a hand-assembled stream with a BLOCKINFO abbreviation (literal code, fixed, VBR, char6 array) and a local one (fixed code, blob) decodes to the expected records; every prefix and every single-bit flip of it reads without a panic. --- crates/xcl/src/gpu/dxil/bitreader.rs | 436 +++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/mod.rs | 4 +- 2 files changed, 439 insertions(+), 1 deletion(-) create mode 100644 crates/xcl/src/gpu/dxil/bitreader.rs diff --git a/crates/xcl/src/gpu/dxil/bitreader.rs b/crates/xcl/src/gpu/dxil/bitreader.rs new file mode 100644 index 0000000000..5d0290f3e9 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/bitreader.rs @@ -0,0 +1,436 @@ +//! LLVM bitstream reader: fixed, VBR and char6 fields, nested blocks, +//! abbreviation definitions (local and from `BLOCKINFO`), abbreviated and +//! unabbreviated records, arrays and blobs — everything DXC's LLVM 3.7 writer +//! emits. Iterative: [`BitReader::next_entry`] yields one entry at a time and the +//! block stack lives on the heap, so nesting depth costs no recursion. +//! +//! Malformed input is an `Err`, never a panic: every length field is checked +//! against the bits left in its block before anything is read or allocated. + +use std::collections::BTreeMap; + +/// One step of the stream. `BLOCKINFO` blocks are consumed by the reader. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Entry { + /// A sub-block starts (its id); [`BitReader::skip_block`] skips it. + Enter(u32), + /// The current block ends (its id). + End(u32), + /// A record (its code); operands in [`BitReader::ops`], blob in [`BitReader::blob`]. + Record(u32), +} + +#[derive(Debug, Clone, Copy)] +enum Op { + Literal(u64), + Fixed(u32), + Vbr(u32), + Array, + Char6, + Blob, +} + +struct Frame { + id: u32, + width: u32, + /// Bit position of the block's end (the stream's end for the top level). + end: usize, + /// How many `BLOCKINFO` abbreviations of this block id existed on entry. + inherited: usize, + local: Vec>, +} + +pub struct BitReader<'a> { + data: &'a [u8], + pos: usize, + len: usize, + stack: Vec, + blockinfo: BTreeMap>>, + /// The block a `BLOCKINFO` `SETBID` record selected. + info_target: Option, + ops: Vec, + blob: Option<(usize, usize)>, +} + +const MAGIC: &[u8; 4] = b"BC\xC0\xDE"; +const WRAPPER_MAGIC: u32 = 0x0B17_C0DE; +const BLOCKINFO: u32 = 0; +const BLOCKINFO_SETBID: u32 = 1; + +/// The bitcode inside an optional `0x0B17C0DE` wrapper header. +pub fn unwrap_bitcode(buf: &[u8]) -> Result<&[u8], String> { + let word = |i: usize| buf.get(i * 4..i * 4 + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap()) as usize); + if word(0) == Some(WRAPPER_MAGIC as usize) { + let (off, size) = (word(2).ok_or("truncated bitcode wrapper")?, word(3).ok_or("truncated bitcode wrapper")?); + return off.checked_add(size).and_then(|e| buf.get(off..e)).ok_or_else(|| "bitcode wrapper points past its buffer".to_string()); + } + Ok(buf) +} + +impl<'a> BitReader<'a> { + /// A reader over bitcode that starts with the `BC\xC0\xDE` magic. + pub fn new(bitcode: &'a [u8]) -> Result { + if bitcode.len() < 4 || &bitcode[..4] != MAGIC { + return Err("not LLVM bitcode (no BC 0xC0DE magic)".into()); + } + if !bitcode.len().is_multiple_of(4) { + return Err(format!("bitcode of {} bytes, not whole 32-bit words", bitcode.len())); + } + let len = bitcode.len() * 8; + let top = Frame { id: u32::MAX, width: 2, end: len, inherited: 0, local: Vec::new() }; + Ok(BitReader { data: bitcode, pos: 32, len, stack: vec![top], blockinfo: BTreeMap::new(), info_target: None, ops: Vec::new(), blob: None }) + } + + /// The operands of the last record (without its code or blob bytes). + pub fn ops(&self) -> &[u64] { + &self.ops + } + + /// The blob of the last record, if its abbreviation has one. + pub fn blob(&self) -> Option<&'a [u8]> { + self.blob.map(|(at, n)| &self.data[at..at + n]) + } + + fn word(&self, byte: usize) -> u64 { + match self.data.get(byte..byte + 8) { + Some(b) => u64::from_le_bytes(b.try_into().unwrap()), + None => self.data.get(byte..).unwrap_or(&[]).iter().rev().fold(0, |v, &b| v << 8 | b as u64), + } + } + + fn fixed(&mut self, w: u32) -> Result { + if w > 56 { + let lo = self.fixed(32)?; + return Ok(lo | self.fixed(w - 32)? << 32); + } + if self.len.saturating_sub(self.pos) < w as usize { + return Err(format!("bitcode ends inside a field at bit {}", self.pos)); + } + let v = (self.word(self.pos / 8) >> (self.pos % 8)) & ((1u64 << w) - 1); + self.pos += w as usize; + Ok(v) + } + + fn vbr(&mut self, w: u32) -> Result { + let hi = 1u64 << (w - 1); + let (mut v, mut shift) = (0u64, 0u32); + loop { + let c = self.fixed(w)?; + if shift >= 64 || (c & (hi - 1)) << shift >> shift != c & (hi - 1) { + return Err(format!("VBR value over 64 bits at bit {}", self.pos)); + } + v |= (c & (hi - 1)) << shift; + if c & hi == 0 { + return Ok(v); + } + shift += w - 1; + } + } + + fn align32(&mut self) { + self.pos = self.pos.div_ceil(32) * 32; + } + + fn left(&self) -> usize { + self.stack.last().map_or(0, |f| f.end).saturating_sub(self.pos) + } + + fn abbrev(&self, id: u64) -> Option<&[Op]> { + let f = self.stack.last()?; + let k = usize::try_from(id - 4).ok()?; + if k < f.inherited { + return self.blockinfo.get(&f.id).map(|v| &v[k][..]); + } + f.local.get(k - f.inherited).map(|v| &v[..]) + } + + /// The next entry, `None` at the end of the stream. + pub fn next_entry(&mut self) -> Result, String> { + loop { + let e = match self.step()? { + Some(e) => e, + None => return Ok(None), + }; + // The block holding this entry (for `Enter`, the one around the new block). + let depth = self.stack.len() - matches!(e, Entry::Enter(_)) as usize; + let in_info = depth >= 1 && self.stack[depth - 1].id == BLOCKINFO; + match e { + Entry::Enter(BLOCKINFO) => self.info_target = None, + Entry::Enter(_) if in_info => self.skip_block()?, + Entry::End(BLOCKINFO) => {} + Entry::Record(c) if in_info => { + if c == BLOCKINFO_SETBID { + let id = self.ops.first().ok_or("SETBID without a block id")?; + self.info_target = Some(u32::try_from(*id).map_err(|_| "SETBID block id over 32 bits")?); + } + } + e => return Ok(Some(e)), + } + } + } + + /// Skips the rest of the block just entered (or the current one). + pub fn skip_block(&mut self) -> Result<(), String> { + if self.stack.len() < 2 { + return Err("skip_block outside a block".into()); + } + let f = self.stack.pop().unwrap(); + self.pos = f.end; + Ok(()) + } + + fn step(&mut self) -> Result, String> { + loop { + let width = self.stack.last().unwrap().width; + let top = self.stack.len() == 1; + if top && self.len.saturating_sub(self.pos) < 32 { + return Ok(None); + } + if self.left() < width as usize { + return Err(format!("block runs past its end at bit {}", self.pos)); + } + let id = self.fixed(width)?; + match id { + 0 if top => return Ok(None), + 0 => { + self.align32(); + let f = self.stack.pop().unwrap(); + if self.pos != f.end { + return Err(format!("block {} ends at bit {}, its length says {}", f.id, self.pos, f.end)); + } + return Ok(Some(Entry::End(f.id))); + } + 1 => { + let bid = u32::try_from(self.vbr(8)?).map_err(|_| "block id over 32 bits")?; + let w = self.vbr(4)?; + if w > 32 { + return Err(format!("abbreviation width {w} in block {bid}")); + } + self.align32(); + let words = self.fixed(32)? as usize; + if words * 32 > self.left() { + return Err(format!("block {bid} ({words} words) runs past its parent")); + } + let inherited = self.blockinfo.get(&bid).map_or(0, Vec::len); + self.stack.push(Frame { id: bid, width: w as u32, end: self.pos + words * 32, inherited, local: Vec::new() }); + return Ok(Some(Entry::Enter(bid))); + } + 2 if !top => { + let a = self.define_abbrev()?; + let f = self.stack.last_mut().unwrap(); + if f.id == BLOCKINFO { + let t = self.info_target.ok_or("BLOCKINFO abbreviation before SETBID")?; + self.blockinfo.entry(t).or_default().push(a); + } else { + f.local.push(a); + } + } + 3 if !top => { + let code = self.vbr(6)?; + let n = self.vbr(6)? as usize; + if n > self.left() / 6 { + return Err(format!("record with {n} operands runs past its block")); + } + self.ops.clear(); + self.blob = None; + for _ in 0..n { + let v = self.vbr(6)?; + self.ops.push(v); + } + return Ok(Some(Entry::Record(u32::try_from(code).map_err(|_| "record code over 32 bits")?))); + } + _ if !top => return self.abbreviated(id).map(Some), + _ => return Err(format!("abbreviation id {id} at the top level")), + } + } + } + + fn define_abbrev(&mut self) -> Result, String> { + let n = self.vbr(5)? as usize; + if n == 0 || n > self.left() / 4 { + return Err(format!("abbreviation with {n} operands")); + } + let mut a = Vec::with_capacity(n); + for _ in 0..n { + let op = if self.fixed(1)? == 1 { + Op::Literal(self.vbr(8)?) + } else { + match self.fixed(3)? { + e @ (1 | 2) => match (e, self.vbr(5)?) { + (_, 0) => Op::Literal(0), + (1, w) if w <= 64 => Op::Fixed(w as u32), + (2, w) if (2..=32).contains(&w) => Op::Vbr(w as u32), + (_, w) => return Err(format!("abbreviation field width {w}")), + }, + 3 => Op::Array, + 4 => Op::Char6, + 5 => Op::Blob, + e => return Err(format!("abbreviation encoding {e}")), + } + }; + a.push(op); + } + // An array is followed by its element (a scalar, last); a blob comes last. + for (i, op) in a.iter().enumerate() { + let ok = match op { + Op::Array => i + 2 == a.len() && matches!(a[i + 1], Op::Fixed(_) | Op::Vbr(_) | Op::Char6), + Op::Blob => i + 1 == a.len(), + _ => true, + }; + if !ok || (i == 0 && matches!(op, Op::Array | Op::Blob)) { + return Err("malformed array or blob in an abbreviation".into()); + } + } + Ok(a) + } + + fn scalar(&mut self, op: Op) -> Result { + match op { + Op::Literal(v) => Ok(v), + Op::Fixed(w) => self.fixed(w), + Op::Vbr(w) => self.vbr(w), + Op::Char6 => Ok(b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._"[self.fixed(6)? as usize] as u64), + Op::Array | Op::Blob => Err("array or blob where a scalar belongs".into()), + } + } + + fn abbreviated(&mut self, id: u64) -> Result { + let a = self.abbrev(id).ok_or_else(|| format!("undefined abbreviation {id} at bit {}", self.pos))?; + // Abbreviations are small; a copy frees `self` for reading. + let mut buf = [Op::Literal(0); 16]; + let heap; + let a: &[Op] = if a.len() <= buf.len() { + buf[..a.len()].copy_from_slice(a); + &buf[..a.len()] + } else { + heap = a.to_vec(); + &heap + }; + let code = self.scalar(a[0])?; + self.ops.clear(); + self.blob = None; + let mut i = 1; + while i < a.len() { + match a[i] { + Op::Array => { + let n = self.vbr(6)? as usize; + if n > self.left() { + return Err(format!("array of {n} elements runs past its block")); + } + for _ in 0..n { + let v = self.scalar(a[i + 1])?; + self.ops.push(v); + } + i += 1; + } + Op::Blob => { + let n = self.vbr(6)? as usize; + self.align32(); + if n > self.left() / 8 { + return Err(format!("blob of {n} bytes runs past its block")); + } + self.blob = Some((self.pos / 8, n)); + self.pos += n * 8; + self.align32(); + } + op => { + let v = self.scalar(op)?; + self.ops.push(v); + } + } + i += 1; + } + Ok(Entry::Record(u32::try_from(code).map_err(|_| "record code over 32 bits")?)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::dxil::bitstream::BitWriter; + + /// A stream with a `BLOCKINFO` abbreviation (literal code, fixed, VBR and a + /// char6 array) and a local one (fixed code, blob), as DXC's writer uses them. + fn abbreviated_stream() -> Vec { + let mut w = BitWriter::new(); + for b in *b"BC\xC0\xDE" { + w.emit(b as u64, 8); + } + let abbrev = |w: &mut BitWriter, ops: &[(u64, u64)]| { + // (encoding, value): encoding 0 is a literal + w.emit(2, 3); + w.vbr(ops.len() as u64, 5); + for &(e, v) in ops { + w.emit((e == 0) as u64, 1); + match e { + 0 => w.vbr(v, 8), + 1 | 2 => { + w.emit(e, 3); + w.vbr(v, 5) + } + _ => w.emit(e, 3), + } + } + }; + w.enter_block(0); + w.record(1, &[9]); // SETBID 9 + abbrev(&mut w, &[(0, 7), (1, 3), (2, 4), (3, 0), (4, 0)]); + w.end_block(); + w.enter_block(9); + abbrev(&mut w, &[(1, 8), (5, 0)]); + w.emit(4, 3); // abbreviation 4: code 7, fixed 5, vbr 100, "dx." + w.emit(5, 3); + w.vbr(100, 4); + w.vbr(3, 6); + for c in [3, 23, 62] { + w.emit(c, 6); + } + w.emit(5, 3); // abbreviation 5: code 42, blob "hi!" + w.emit(42, 8); + w.vbr(3, 6); + w.align32(); + for &b in b"hi!" { + w.emit(b as u64, 8); + } + w.align32(); + w.record(3, &[1, 2]); + w.end_block(); + w.finish() + } + + #[test] + fn reader_decodes_abbreviations_from_blockinfo_and_blobs() { + let bc = abbreviated_stream(); + let mut r = BitReader::new(&bc).unwrap(); + assert_eq!(r.next_entry(), Ok(Some(Entry::Enter(9)))); + assert_eq!(r.next_entry(), Ok(Some(Entry::Record(7)))); + assert_eq!(r.ops(), &[5, 100, b'd' as u64, b'x' as u64, b'.' as u64]); + assert_eq!(r.next_entry(), Ok(Some(Entry::Record(42)))); + assert_eq!((r.ops(), r.blob()), (&[][..], Some(&b"hi!"[..]))); + assert_eq!(r.next_entry(), Ok(Some(Entry::Record(3)))); + assert_eq!(r.ops(), &[1, 2]); + assert_eq!(r.next_entry(), Ok(Some(Entry::End(9)))); + assert_eq!(r.next_entry(), Ok(None)); + } + + #[test] + fn truncated_or_bit_flipped_streams_are_errors_not_panics() { + let bc = abbreviated_stream(); + let drain = |b: &[u8]| -> Result<(), String> { + let mut r = BitReader::new(b)?; + while r.next_entry()?.is_some() {} + Ok(()) + }; + assert_eq!(drain(&bc), Ok(())); + // A prefix reads only if it ends between top-level blocks (a word boundary). + for n in 0..bc.len() { + assert!(drain(&bc[..n]).is_err() || n % 4 == 0, "prefix of {n} bytes"); + } + assert!(drain(&bc[..bc.len() - 4]).is_err()); + for bit in 32..bc.len() * 8 { + let mut v = bc.clone(); + v[bit / 8] ^= 1 << (bit % 8); + let _ = drain(&v); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index 6fe75d575f..d20636c802 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -9,8 +9,10 @@ //! 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. +//! * [`validate`] — `dxil.dll` validator and DXC disassembler as test oracles; +//! * [`bitreader`] — reading DXIL bitcode back (abbreviations included). +pub mod bitreader; pub mod bitstream; pub mod cfg; pub mod container; From e7097e2b25b0cdaff15987e1562e3261f98d960c Mon Sep 17 00:00:00 2001 From: SombraSoft Date: Tue, 24 Nov 2026 16:32:29 -0300 Subject: [PATCH 2/3] Shaders: DXIL structure statistics for compile-cost reports To explain why a shader is expensive for the driver's compiler, a report needs the shape of its DXIL: functions and declarations, basic blocks, instructions and SSA values, phis and their incoming edges, branches, switches and back edges, selects, memory operations, and calls per callee (dx.op.* name). container_stats reads the DXIL part of a DXBC container, bitcode_stats raw bitcode (optionally in the 0x0B17C0DE wrapper). One pass over the bitstream: the type table, global, function and constant records give the module-level value ids; function arguments, function constants and value-producing instructions continue them per body, so the relative callee operand of a call resolves to its function and name. A call produces a value when its function type (explicit in the call or the callee's) returns non-void. Metadata, attributes, use lists and function symbol tables are skipped by block length. Output maps are BTreeMaps, so identical input gives identical stats and JSON. Tested: - two modules built with our writer (branches, a loop with a forward- referencing phi, select, calls to a value and a void dx.op; a switch, global, alloca, gep, load, stores) give exactly the expected stats; - three DXC 1.8.2502.11 compute shaders (a loop, nested branches with a three-way phi, a switch with buffer loads/stores) match counts read from DXC's disassembly: functions, declarations, blocks, instructions, values, phis, phi edges, br/cond br, switch cases, back edges, select, loads, stores, allocas, calls per callee; - every prefix and 3000 byte-flipped copies of a DXC bitcode, its container and a writer module return Ok or Err without a panic; - release build: 20.6 MB of writer bitcode (3M instructions) reads in 86 ms; a 1.5 KB DXC module 10000 times in 97 ms. --- crates/xcl/src/gpu/dxil/mod.rs | 6 +- crates/xcl/src/gpu/dxil/stats.rs | 415 +++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/stats_tests.rs | 273 ++++++++++++++++ 3 files changed, 693 insertions(+), 1 deletion(-) create mode 100644 crates/xcl/src/gpu/dxil/stats.rs create mode 100644 crates/xcl/src/gpu/dxil/stats_tests.rs diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index d20636c802..c7819f60fe 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -10,7 +10,8 @@ //! * [`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; -//! * [`bitreader`] — reading DXIL bitcode back (abbreviations included). +//! * [`bitreader`], [`stats`] — reading DXIL bitcode back (abbreviations +//! included) and its structure statistics, for compile-cost reports. pub mod bitreader; pub mod bitstream; @@ -35,6 +36,7 @@ pub mod ops_core; mod prelude; pub mod shader; pub mod ssa; +pub mod stats; pub mod validate; #[cfg(test)] @@ -55,3 +57,5 @@ mod msaa_tests; mod round_tests; #[cfg(test)] mod geometry_tests; +#[cfg(test)] +mod stats_tests; diff --git a/crates/xcl/src/gpu/dxil/stats.rs b/crates/xcl/src/gpu/dxil/stats.rs new file mode 100644 index 0000000000..b240dbdc87 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/stats.rs @@ -0,0 +1,415 @@ +//! Structure statistics of a DXIL module (blocks, phis, branches, calls by +//! callee, …), read from the bitcode DXC emits: the numbers that explain why +//! a shader is expensive for the driver's compiler. +//! +//! One pass over the bitstream ([`super::bitreader`]). Value ids are tracked +//! exactly (globals, functions, constants, arguments, value-producing +//! instructions) so that relative operands — the callee of a call — resolve. +//! Metadata, attributes and function symbol tables are skipped unread. + +use std::collections::BTreeMap; + +use super::bitreader::{unwrap_bitcode, BitReader, Entry}; + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct DxilStats { + /// The whole input. + pub container_bytes: u64, + /// The LLVM bitcode inside the `DXIL` part. + pub bitcode_bytes: u64, + /// Functions with bodies. + pub functions: u32, + /// Declared-only functions (`dx.op.*` and the like). + pub declarations: u32, + /// Basic blocks over all function bodies. + pub blocks: u32, + pub instructions: u32, + /// Instructions that produce a value (SSA values). + pub values: u32, + pub phis: u32, + /// Incoming edges over all phis. + pub phi_incoming: u64, + pub max_phi_incoming: u32, + /// Unconditional `br`. + pub branches: u32, + pub cond_branches: u32, + pub switches: u32, + pub switch_cases: u64, + /// `br` / `switch` edges to a block at or before their own (loop back + /// edges in DXC's block layout). + pub backward_branches: u32, + pub selects: u32, + pub loads: u32, + pub stores: u32, + pub allocas: u32, + pub calls: u32, + /// Constants (module and function constant blocks). + pub constants: u32, + pub globals: u32, + /// Instruction kind (`binop`, `phi`, `call`, …) → count. + pub opcodes: BTreeMap<&'static str, u32>, + /// Called function name (`dx.op.bufferLoad.i32`) → calls. + pub callees: BTreeMap, +} + +impl DxilStats { + pub fn to_json(&self) -> serde_json::Value { + serde_json::json!({ + "container_bytes": self.container_bytes, + "bitcode_bytes": self.bitcode_bytes, + "functions": self.functions, + "declarations": self.declarations, + "blocks": self.blocks, + "instructions": self.instructions, + "values": self.values, + "phis": self.phis, + "phi_incoming": self.phi_incoming, + "max_phi_incoming": self.max_phi_incoming, + "branches": self.branches, + "cond_branches": self.cond_branches, + "switches": self.switches, + "switch_cases": self.switch_cases, + "backward_branches": self.backward_branches, + "selects": self.selects, + "loads": self.loads, + "stores": self.stores, + "allocas": self.allocas, + "calls": self.calls, + "constants": self.constants, + "globals": self.globals, + "opcodes": self.opcodes, + "callees": self.callees, + }) + } +} + +/// Statistics of the program in a DXBC container's `DXIL` part. +pub fn container_stats(container: &[u8]) -> Result { + let mut s = module_stats(dxil_bitcode(container)?)?; + s.container_bytes = container.len() as u64; + Ok(s) +} + +/// Statistics of raw bitcode (`BC\xC0\xDE`, optionally in a `0x0B17C0DE` wrapper). +pub fn bitcode_stats(bitcode: &[u8]) -> Result { + let mut s = module_stats(unwrap_bitcode(bitcode)?)?; + s.container_bytes = bitcode.len() as u64; + Ok(s) +} + +/// The bitcode of a container's `DXIL` part (program header, bitcode header, bitcode). +pub fn dxil_bitcode(c: &[u8]) -> Result<&[u8], String> { + let at = |b: &[u8], o: usize| { + let word = b.get(o..o + 4).ok_or_else(|| "truncated DXBC container".to_string())?; + Ok::<_, String>(u32::from_le_bytes(word.try_into().unwrap()) as usize) + }; + if c.get(..4) != Some(b"DXBC") { + return Err("not a DXBC container".into()); + } + for i in 0..at(c, 28)? { + let off = at(c, 32 + 4 * i)?; + if c.get(off..off + 4) == Some(b"DXIL") { + let part = c.get(off + 8..off + 8 + at(c, off + 4)?).ok_or("DXIL part runs past the container")?; + if part.get(8..12) != Some(b"DXIL") { + return Err("DXIL part without a bitcode header".into()); + } + let (start, len) = (8 + at(part, 16)?, at(part, 20)?); + return part.get(start..start + len).ok_or_else(|| "bitcode runs past the DXIL part".into()); + } + } + Err("no DXIL part in the container".into()) +} + +// LLVMBitCodes.h (3.7) +const BLOCK_MODULE: u32 = 8; +const BLOCK_CONSTANTS: u32 = 11; +const BLOCK_FUNCTION: u32 = 12; +const BLOCK_VALUE_SYMTAB: u32 = 14; +const BLOCK_TYPE: u32 = 17; + +#[derive(Debug, Clone, Copy)] +enum Type { + Void, + Func { ret: u32, params: u32 }, + Ptr(u32), + Other, +} + +#[derive(Default)] +struct Walk { + s: DxilStats, + types: Vec, + /// Module-level values in id order: a function's type, `None` for the rest. + values: Vec>, + /// Value ids of the functions with bodies, in body order. + bodies: Vec, + bodies_seen: usize, + relative: bool, + names: BTreeMap, + callee_ids: BTreeMap, + next_value: u32, + cur_block: u32, +} + +fn u32_of(v: u64) -> Result { + u32::try_from(v).map_err(|_| format!("operand {v} over 32 bits")) +} + +fn module_stats(bc: &[u8]) -> Result { + let mut r = BitReader::new(bc)?; + let mut w = Walk::default(); + w.s.bitcode_bytes = bc.len() as u64; + let mut ctx: Vec = Vec::new(); + let mut modules = 0; + while let Some(e) = r.next_entry()? { + match e { + Entry::Enter(id) => { + let keep = match (ctx.as_slice(), id) { + ([], BLOCK_MODULE) => { + modules += 1; + true + } + ([BLOCK_MODULE], BLOCK_TYPE | BLOCK_CONSTANTS | BLOCK_VALUE_SYMTAB) => true, + ([BLOCK_MODULE], BLOCK_FUNCTION) => { + w.enter_function()?; + true + } + ([BLOCK_MODULE, BLOCK_FUNCTION], BLOCK_CONSTANTS) => true, + _ => false, + }; + if keep { + ctx.push(id); + } else { + r.skip_block()?; + } + } + Entry::End(_) => { + ctx.pop(); + } + Entry::Record(code) => { + let ops = r.ops(); + match ctx.as_slice() { + [BLOCK_MODULE] => w.module_record(code, ops)?, + [BLOCK_MODULE, BLOCK_TYPE] => w.type_record(code, ops)?, + [BLOCK_MODULE, BLOCK_VALUE_SYMTAB] => w.symbol(code, ops), + [BLOCK_MODULE, BLOCK_FUNCTION] => w.inst(code, ops)?, + [BLOCK_MODULE, .., BLOCK_CONSTANTS] if code != 1 => { + // Every record but SETTYPE defines one constant. + w.s.constants += 1; + if ctx.len() == 2 { + w.values.push(None); + } else { + w.next_value = w.next_value.wrapping_add(1); + } + } + _ => {} + } + } + } + } + if !ctx.is_empty() || modules != 1 { + return Err(format!("bitcode with {modules} module blocks")); + } + for (id, n) in w.callee_ids { + let name = w.names.get(&id).cloned().unwrap_or_else(|| format!("#{id}")); + *w.s.callees.entry(name).or_default() += n; + } + Ok(w.s) +} + +impl Walk { + /// The function type behind a type id (through a pointer): (return type, parameters). + fn fn_type(&self, t: u64) -> Result<(u32, u32), String> { + let ty = |t: u64| self.types.get(t as usize).copied().ok_or_else(|| format!("type {t} out of range")); + let resolved = match ty(t)? { + Type::Ptr(p) => ty(p as u64)?, + other => other, + }; + match resolved { + Type::Func { ret, params } if (ret as usize) < self.types.len() => Ok((ret, params)), + _ => Err(format!("type {t} is not a function type")), + } + } + + fn type_record(&mut self, code: u32, ops: &[u64]) -> Result<(), String> { + let t = match (code, ops) { + (1 | 19, _) => return Ok(()), // NUMENTRY, STRUCT_NAME + (2, _) => Type::Void, + (8, [p, ..]) => Type::Ptr(u32_of(*p)?), + (21, [_, ret, params @ ..]) => Type::Func { ret: u32_of(*ret)?, params: params.len() as u32 }, + (9, [_, _, ret, params @ ..]) => Type::Func { ret: u32_of(*ret)?, params: params.len() as u32 }, + (8 | 9 | 21, _) => return Err(format!("type record {code} with {} operands", ops.len())), + _ => Type::Other, + }; + self.types.push(t); + Ok(()) + } + + fn module_record(&mut self, code: u32, ops: &[u64]) -> Result<(), String> { + match code { + 1 => self.relative = ops.first().is_some_and(|&v| v >= 1), // VERSION + 7 => { + self.s.globals += 1; + self.values.push(None); + } + 8 => { + // [type, cc, isproto, ...] + let [ty, _, proto, ..] = *ops else { return Err("short FUNCTION record".into()) }; + self.fn_type(ty)?; + let ty = match self.types[ty as usize] { + Type::Ptr(p) => p, + _ => ty as u32, + }; + if proto == 0 { + self.s.functions += 1; + self.bodies.push(self.values.len() as u32); + } else { + self.s.declarations += 1; + } + self.values.push(Some(ty)); + } + 9 | 14 => self.values.push(None), // aliases + _ => {} + } + Ok(()) + } + + /// Module symbol table: ENTRY [valueid, name...], FNENTRY [valueid, offset, name...]. + fn symbol(&mut self, code: u32, ops: &[u64]) { + let (id, name) = match (code, ops) { + (1, [id, name @ ..]) | (3, [id, _, name @ ..]) => (*id, name), + _ => return, + }; + if self.values.get(id as usize).is_some_and(Option::is_some) { + let bytes: Vec = name.iter().map(|&c| c as u8).collect(); + self.names.insert(id as u32, String::from_utf8_lossy(&bytes).into_owned()); + } + } + + fn enter_function(&mut self) -> Result<(), String> { + let f = *self.bodies.get(self.bodies_seen).ok_or("more function bodies than defined functions")?; + self.bodies_seen += 1; + let ty = self.values[f as usize].unwrap(); + let (_, params) = self.fn_type(ty as u64)?; + self.next_value = (self.values.len() as u32).checked_add(params).ok_or("value ids over 32 bits")?; + self.cur_block = 0; + Ok(()) + } + + fn edge(&mut self, target: u64) { + if target <= self.cur_block as u64 { + self.s.backward_branches += 1; + } + } + + fn inst(&mut self, code: u32, ops: &[u64]) -> Result<(), String> { + let op = |i: usize| ops.get(i).copied().ok_or_else(|| format!("instruction record {code} with {} operands", ops.len())); + // (kind, produces a value, ends a block) + let (kind, value, term) = match code { + 1 => { + self.s.blocks = self.s.blocks.checked_add(u32_of(op(0)?)?).ok_or("block count over 32 bits")?; + return Ok(()); + } + 33 | 35 => return Ok(()), // debug locations + 2 => ("binop", true, false), + 3 => ("cast", true, false), + 4 | 30 | 43 => ("gep", true, false), + 5 | 29 => { + self.s.selects += 1; + ("select", true, false) + } + 6 => ("extractelt", true, false), + 7 => ("insertelt", true, false), + 8 => ("shufflevec", true, false), + 9 | 28 => ("cmp", true, false), + 10 => ("ret", false, true), + 11 => { + // [bb] or [truebb, falsebb, cond] + self.edge(op(0)?); + if ops.len() >= 3 { + self.s.cond_branches += 1; + self.edge(op(1)?); + } else { + self.s.branches += 1; + } + ("br", false, true) + } + 12 => { + // [opty, cond, defaultbb, (caseval, bb)*]; the case-range + // format (magic in operand 0) is counted without its cases. + self.s.switches += 1; + self.edge(op(2)?); + if op(0)? >> 16 != 0x4B5 { + let cases = ops.len().saturating_sub(3) / 2; + self.s.switch_cases += cases as u64; + for k in 0..cases { + self.edge(ops[4 + 2 * k]); + } + } + ("switch", false, true) + } + 15 => ("unreachable", false, true), + 16 => { + // [ty, (val, bb)*] + let n = (ops.len().max(1) - 1) / 2; + self.s.phis += 1; + self.s.phi_incoming += n as u64; + self.s.max_phi_incoming = self.s.max_phi_incoming.max(n as u32); + ("phi", true, false) + } + 19 => { + self.s.allocas += 1; + ("alloca", true, false) + } + 20 | 41 => { + self.s.loads += 1; + ("load", true, false) + } + 23 => ("vaarg", true, false), + 24 | 42 | 44 | 45 => { + self.s.stores += 1; + ("store", false, false) + } + 26 => ("extractval", true, false), + 27 => ("insertval", true, false), + 31 => ("indirectbr", false, true), + 34 => { + // [paramattrs, cc, fmf if cc bit 17, fnty if cc bit 15, callee, args...] + let cc = op(1)?; + let mut i = 2 + (cc >> 17 & 1) as usize; + let explicit = if cc >> 15 & 1 == 1 { + i += 1; + Some(op(i - 1)?) + } else { + None + }; + let rel = u32_of(op(i)?)?; + let callee = if self.relative { self.next_value.wrapping_sub(rel) } else { rel }; + let fty = match explicit { + Some(t) => t, + None => self.values.get(callee as usize).copied().flatten().ok_or("call through a value of unknown type")? as u64, + }; + let (ret, _) = self.fn_type(fty)?; + self.s.calls += 1; + *self.callee_ids.entry(callee).or_default() += 1; + ("call", !matches!(self.types[ret as usize], Type::Void), false) + } + 36 => ("fence", false, false), + 37 | 46 => ("cmpxchg", true, false), + 38 => ("atomicrmw", true, false), + 39 => ("resume", false, true), + 40 | 47 => ("landingpad", true, false), + _ => return Err(format!("unsupported instruction record {code}")), + }; + self.s.instructions += 1; + *self.s.opcodes.entry(kind).or_default() += 1; + if value { + self.s.values += 1; + self.next_value = self.next_value.wrapping_add(1); + } + if term { + self.cur_block += 1; + } + Ok(()) + } +} diff --git a/crates/xcl/src/gpu/dxil/stats_tests.rs b/crates/xcl/src/gpu/dxil/stats_tests.rs new file mode 100644 index 0000000000..5902e165d6 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/stats_tests.rs @@ -0,0 +1,273 @@ +//! [`super::stats`] against the writer's modules (known shapes), DXC's +//! disassembly (an independent reading of the same bitcode), and corrupted input. + +use super::module::{BinOp, FnAttrs, Module, Pred}; +use super::stats::{bitcode_stats, container_stats, dxil_bitcode}; + +const LOOP_CS: &str = r" +RWByteAddressBuffer io : register(u0); +[numthreads(64, 1, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + uint n = io.Load(tid.x * 4); + uint acc = 0; + for (uint i = 0; i < n; i++) { + acc += io.Load(i * 4) * i; + if (acc > 1000) break; + } + io.Store(tid.x * 4, acc); +}"; + +const BRANCH_CS: &str = r" +RWStructuredBuffer b : register(u0); +[numthreads(64, 1, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + float v = b[tid.x]; + float r; + if (v > 0) { + r = sqrt(v); + if (v > 10) r = r * b[tid.x + 1]; + } else { + r = -v * b[0]; + } + b[tid.x] = (tid.x & 1) ? r : r * 2; +}"; + +const SWITCH_CS: &str = r" +Buffer src : register(t0); +RWBuffer dst : register(u0); +[numthreads(64, 1, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + uint v = src[tid.x]; + uint r; + switch (v & 7) { + case 0: r = src[v]; break; + case 1: r = src[v * 3] + 1; break; + case 3: r = src[v + 1] ^ v; break; + case 5: dst[v] = 7; r = 9; break; + default: r = v; + } + dst[tid.x] = r; +}"; + +fn dxc(src: &str) -> Option> { + if crate::gpu::recomp::dxc::create_instance().is_none() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return None; + } + Some(crate::gpu::recomp::dxc::compile(src, "main", "cs_6_6", &[]).expect("DXC compile")) +} + +/// `entry: a = test(1, 2); c = a == 0; br c, b1, b2`, `b1: x = a + 1`, +/// `b2: y = select c, a, 5`, `join: p = phi [x, b1], [y, b2]`, then a loop +/// `q = phi [p, join], [q2, loop]; q2 = q + 1; sink(q2); br q2 < 10, loop, exit`. +fn branchy_module() -> Vec { + let mut m = Module::new(); + m.define_entry("main"); + let (i32, void) = (m.i32(), m.void()); + let fty = m.func_ty(i32, &[i32, i32]); + let test = m.declare("dx.op.test.i32", fty, FnAttrs::ReadNone); + let sty = m.func_ty(void, &[i32]); + let sink = m.declare("dx.op.sink", sty, FnAttrs::NoUnwind); + let (b1, b2, join, lp, exit) = (m.new_block(), m.new_block(), m.new_block(), m.new_block(), m.new_block()); + let (one, two, zero, five, ten) = (m.i32c(1), m.i32c(2), m.i32c(0), m.i32c(5), m.i32c(10)); + let a = m.call(test, &[one, two]); + let c = m.cmp(Pred::Eq, a, zero); + m.cond_br(c, b1, b2); + m.set_block(b1); + let x = m.bin(BinOp::Add, a, one); + m.br(join); + m.set_block(b2); + let y = m.select(c, a, five); + m.br(join); + m.set_block(join); + let p = m.phi(i32); + m.add_incoming(p, x, b1); + m.add_incoming(p, y, b2); + m.br(lp); + m.set_block(lp); + let q = m.phi(i32); + let q2 = m.bin(BinOp::Add, q, one); + m.add_incoming(q, p, join); + m.add_incoming(q, q2, lp); + m.call(sink, &[q2]); + let more = m.cmp(Pred::ULt, q2, ten); + m.cond_br(more, lp, exit); + m.set_block(exit); + m.ret(); + m.to_bitcode("dxil-ms-dx", "") +} + +#[test] +fn writer_module_stats_are_exact() { + let bc = branchy_module(); + let s = bitcode_stats(&bc).unwrap(); + let ops = [("binop", 2), ("br", 5), ("call", 2), ("cmp", 2), ("phi", 2), ("ret", 1), ("select", 1)]; + let want = super::stats::DxilStats { + container_bytes: bc.len() as u64, + bitcode_bytes: bc.len() as u64, + functions: 1, + declarations: 2, + blocks: 6, + instructions: 15, + values: 8, // the call to sink is void + phis: 2, + phi_incoming: 4, + max_phi_incoming: 2, + branches: 3, + cond_branches: 2, + backward_branches: 1, + selects: 1, + calls: 2, + constants: 5, + opcodes: ops.into_iter().collect(), + callees: [("dx.op.sink".to_string(), 1), ("dx.op.test.i32".to_string(), 1)].into_iter().collect(), + ..Default::default() + }; + assert_eq!(s, want); + assert_eq!(s.to_json()["callees"]["dx.op.sink"], 1); +} + +#[test] +fn writer_switch_and_memory_stats_are_exact() { + 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 (c1, c2, c3) = (m.i32c(1), m.i32c(2), m.i32c(3)); + let _ = m.alloca(i32, 4); + let zero = m.i32c(0); + let p = m.gep(g, &[zero, zero]); + let a = m.load(p, 4); + let (b1, b2, b3, exit) = (m.new_block(), m.new_block(), m.new_block(), m.new_block()); + m.switch(a, exit, &[(c1, b1), (c2, b2), (c3, b3)]); + for (b, v) in [(b1, c1), (b2, c2), (b3, c3)] { + m.set_block(b); + m.store(p, v, 4); + m.br(exit); + } + m.set_block(exit); + m.ret(); + let s = bitcode_stats(&m.to_bitcode("dxil-ms-dx", "")).unwrap(); + let got = (s.functions, s.declarations, s.globals, s.blocks, s.instructions, s.values, s.constants); + assert_eq!(got, (1, 0, 1, 5, 11, 3, 4)); + let got = (s.switches, s.switch_cases, s.branches, s.backward_branches, s.loads, s.stores, s.allocas, s.opcodes["gep"]); + assert_eq!(got, (1, 3, 3, 0, 1, 3, 1, 1)); +} + +/// Counts read from DXC's disassembly of a container: an independent reading +/// of the same bitcode. Fields the text does not show stay at their default. +fn stats_from_disassembly(dis: &str) -> super::stats::DxilStats { + let mut s = super::stats::DxilStats::default(); + let (mut in_fn, mut in_switch) = (false, false); + // per function: block labels in order, and (source block, target label) edges + let (mut labels, mut edges): (Vec, Vec<(usize, String)>) = (Vec::new(), Vec::new()); + for line in dis.lines() { + let t = line.split(" ;").next().unwrap().trim(); + if t.starts_with("declare ") { + s.declarations += 1; + } else if t.starts_with("define ") { + (in_fn, labels, edges) = (true, vec!["0".into()], Vec::new()); + s.functions += 1; + } else if !in_fn || t.is_empty() { + } else if t == "}" { + in_fn = false; + s.blocks += labels.len() as u32; + s.backward_branches += edges.iter().filter(|(src, l)| labels.iter().position(|x| x == l).unwrap() <= *src).count() as u32; + } else if let Some(l) = t.strip_prefix(";