diff --git a/crates/xcl/src/gpu/dxil/bitreader_tests.rs b/crates/xcl/src/gpu/dxil/bitreader_tests.rs index b3a7b3dd41..81823c4386 100644 --- a/crates/xcl/src/gpu/dxil/bitreader_tests.rs +++ b/crates/xcl/src/gpu/dxil/bitreader_tests.rs @@ -1,7 +1,7 @@ //! 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). +//! produces (both unabbreviated records and `DEFINE_ABBREV` abbreviated records), +//! 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}; @@ -12,6 +12,15 @@ pub(super) struct Block { pub blocks: Vec, } +#[derive(Clone, Debug)] +enum AbOp { + Literal(u64), + Fixed(u32), + Vbr(u32), + ArrayFixed(u32), + ArrayVbr(u32), +} + impl Block { /// Depth-first search for the first block with `id`. pub fn find(&self, id: u32) -> Option<&Block> { @@ -57,6 +66,7 @@ impl Reader<'_> { } fn block(&mut self, id: u32, width: u32, end_bit: Option) -> Block { let mut blk = Block { id, ..Default::default() }; + let mut abbrevs: Vec> = Vec::new(); loop { if end_bit.is_none() && self.pos + width as usize > self.b.len() * 8 { return blk; @@ -77,13 +87,70 @@ impl Reader<'_> { let end = self.pos + words * 32; blk.blocks.push(self.block(sub, w, Some(end))); } + 2 => { + let n = self.vbr(5); + let mut ops = Vec::new(); + let mut i = 0; + while i < n { + if self.fixed(1) == 1 { + ops.push(AbOp::Literal(self.vbr(8))); + i += 1; + } else { + match self.fixed(3) { + 1 => { + ops.push(AbOp::Fixed(self.vbr(5) as u32)); + i += 1; + } + 2 => { + ops.push(AbOp::Vbr(self.vbr(5) as u32)); + i += 1; + } + 3 => { + assert_eq!(self.fixed(1), 0, "array element must be encoded"); + match self.fixed(3) { + 1 => ops.push(AbOp::ArrayFixed(self.vbr(5) as u32)), + 2 => ops.push(AbOp::ArrayVbr(self.vbr(5) as u32)), + e => panic!("unsupported array elem encoding {e}"), + } + i += 2; + } + e => panic!("unsupported abbrev encoding {e}"), + } + } + } + abbrevs.push(ops); + } 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}"), + a => { + let ab = abbrevs.get((a - 4) as usize).unwrap_or_else(|| panic!("unknown abbreviation id {a}")); + let mut vals = Vec::new(); + for op in ab { + match *op { + AbOp::Literal(v) => vals.push(v), + AbOp::Fixed(w) => vals.push(self.fixed(w)), + AbOp::Vbr(w) => vals.push(self.vbr(w)), + AbOp::ArrayFixed(w) => { + let len = self.vbr(6); + for _ in 0..len { + vals.push(self.fixed(w)); + } + } + AbOp::ArrayVbr(w) => { + let len = self.vbr(6); + for _ in 0..len { + vals.push(self.vbr(w)); + } + } + } + } + let code = vals[0] as u32; + blk.records.push((code, vals[1..].to_vec())); + } } } } @@ -143,6 +210,64 @@ fn a_shorter_binop_record_has_only_its_own_operands() { assert_eq!(records, [&[1, 1, BinOp::Add as u64, 3][..], &[1, 2, BinOp::Xor as u64][..]]); } +/// The abbreviated records decode to the operands the unabbreviated ones had, and a table +/// of words is one `CST_CODE_DATA` record. +#[test] +fn abbreviated_records_decode_to_the_plain_layout() { + use super::module::Pred; + const BLOCK_CONSTANTS: u32 = 11; + const CST_CODE_DATA: u32 = 22; + const FUNC_CODE_INST_BR: u32 = 11; + const FUNC_CODE_INST_PHI: u32 = 16; + const FUNC_CODE_INST_LOAD: u32 = 20; + const FUNC_CODE_INST_GEP: u32 = 43; + const FUNC_CODE_INST_STORE: u32 = 44; + let words = [7, 0xDEAD_BEEF, 0, u32::MAX]; + let mut m = Module::new(); + m.define_entry("main"); + let i32 = m.i32(); + let arr = m.array(words.len() as u64, i32); + let init = m.const_data_i32(&words); + let table = m.global("table", arr, 0, Some(init), true, 4); + let lds = m.global("lds", arr, 3, None, false, 4); + let (zero, one) = (m.i32c(0), m.i32c(1)); + let entry = m.entry_block(); + let at = m.gep(table, &[zero, one]); + let v = m.load(at, 4); + let c = m.cmp(Pred::Eq, v, zero); + let (then, join) = (m.new_block(), m.new_block()); + m.cond_br(c, then, join); + m.set_block(then); + m.br(join); + m.set_block(join); + let p = m.phi(i32); + m.add_incoming(p, v, entry); + m.add_incoming(p, one, then); + let to = m.gep(lds, &[zero, zero]); + m.store(to, p, 4); + m.ret(); + + let root = parse(&m.to_bitcode("dxil-ms-dx", "")); + let consts = root.find(BLOCK_CONSTANTS).unwrap(); + assert_eq!(consts.records_with(CST_CODE_DATA), [&words.map(u64::from)[..]]); + let f = root.find(BLOCK_FUNCTION).unwrap(); + let geps = f.records_with(FUNC_CODE_INST_GEP); + assert_eq!(geps.len(), 2); + // [inbounds, source type, pointer, indices...] + assert!(geps.iter().all(|r| r.len() == 5 && r[0] == 1), "{geps:?}"); + // [pointer, type, align log2 + 1, volatile] + let loads = f.records_with(FUNC_CODE_INST_LOAD); + assert!(loads.len() == 1 && loads[0].len() == 4 && loads[0][2..] == [3, 0], "{loads:?}"); + let stores = f.records_with(FUNC_CODE_INST_STORE); + assert!(stores.len() == 1 && stores[0].len() == 4 && stores[0][2..] == [3, 0], "{stores:?}"); + let mut br_lens: Vec = f.records_with(FUNC_CODE_INST_BR).iter().map(|r| r.len()).collect(); + br_lens.sort_unstable(); + assert_eq!(br_lens, [1, 3]); + // [type, (signed relative value, block) per incoming edge] + let phis = f.records_with(FUNC_CODE_INST_PHI); + assert!(phis.len() == 1 && phis[0].len() == 5 && phis[0][2] == 0, "{phis:?}"); +} + #[test] fn atomics_use_bitcode_ordering_codes() { let root = parse(&atomic_module()); diff --git a/crates/xcl/src/gpu/dxil/bitstream.rs b/crates/xcl/src/gpu/dxil/bitstream.rs index 70757093f1..6b23eedd51 100644 --- a/crates/xcl/src/gpu/dxil/bitstream.rs +++ b/crates/xcl/src/gpu/dxil/bitstream.rs @@ -1,21 +1,30 @@ //! 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). +//! back-patched lengths, unabbreviated records, and LLVM `DEFINE_ABBREV` +//! abbreviations for compact DXIL encoding. /// 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)>, + /// Open blocks: (byte offset of the length word, outer abbreviation width, next abbrev id). + blocks: Vec<(usize, u32, u32)>, width: u32, } -/// Abbreviation width used for every block we open (IDs 0..3 need 2 bits). +/// Abbreviation operand encoding for LLVM `DEFINE_ABBREV` records. +#[derive(Clone, Copy, Debug)] +pub enum AbbrevOp { + Literal(u64), + Fixed(u32), + Vbr(u32), + /// Trailing array of fixed-width operands (LLVM `Array` + `Fixed(w)` pair). + ArrayFixed(u32), + /// Trailing array of VBR-encoded operands (LLVM `Array` + `VBR(w)` pair). + ArrayVbr(u32), +} + +/// Abbreviation width used for every block opened via [`BitWriter::enter_block`] (IDs 0..7). pub const ABBREV_WIDTH: u32 = 3; impl Default for BitWriter { @@ -31,7 +40,7 @@ impl BitWriter { 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"); + debug_assert!(width == 64 || width == 32 || value >> width == 0, "value {value:#x} does not fit {width} bits"); self.acc |= value << self.nbits; self.nbits += width; while self.nbits >= 8 { @@ -60,25 +69,114 @@ impl BitWriter { } pub fn enter_block(&mut self, id: u32) { + self.enter_block_with_width(id, ABBREV_WIDTH); + } + + pub fn enter_block_with_width(&mut self, id: u32, abbrev_width: u32) { self.emit(1, self.width); // ENTER_SUBBLOCK self.vbr(id as u64, 8); - self.vbr(ABBREV_WIDTH as u64, 4); + 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; + self.blocks.push((at, self.width, 4)); + 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 (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; } + /// Define a block-local abbreviation (`DEFINE_ABBREV = 2`) and return its ID (`>= 4`). + pub fn define_abbrev(&mut self, ops: &[AbbrevOp]) -> u32 { + let id = { + let top = self.blocks.last_mut().expect("define_abbrev outside block"); + let id = top.2; + top.2 += 1; + id + }; + debug_assert!((id as u64) < (1u64 << self.width), "abbrev id {id} exceeds width {}", self.width); + let num_ops: u64 = ops.iter().map(|o| if matches!(o, AbbrevOp::ArrayFixed(_) | AbbrevOp::ArrayVbr(_)) { 2 } else { 1 }).sum(); + self.emit(2, self.width); // DEFINE_ABBREV + self.vbr(num_ops, 5); + for &op in ops { + match op { + AbbrevOp::Literal(v) => { + self.emit(1, 1); + self.vbr(v, 8); + } + AbbrevOp::Fixed(w) => { + self.emit(0, 1); + self.emit(1, 3); + self.vbr(w as u64, 5); + } + AbbrevOp::Vbr(w) => { + self.emit(0, 1); + self.emit(2, 3); + self.vbr(w as u64, 5); + } + AbbrevOp::ArrayFixed(w) => { + self.emit(0, 1); + self.emit(3, 3); // Array + self.emit(0, 1); + self.emit(1, 3); // Fixed element + self.vbr(w as u64, 5); + } + AbbrevOp::ArrayVbr(w) => { + self.emit(0, 1); + self.emit(3, 3); // Array + self.emit(0, 1); + self.emit(2, 3); // VBR element + self.vbr(w as u64, 5); + } + } + } + id + } + + /// Emit an abbreviated record defined by [`Self::define_abbrev`]. `values` supplies only the + /// non-literal operands in order; if `ops` ends with `ArrayFixed`/`ArrayVbr`, remaining items + /// in `values` form the array payload. + pub fn emit_abbrev(&mut self, id: u32, ops: &[AbbrevOp], values: &[u64]) { + self.emit(id as u64, self.width); + let mut idx = 0usize; + for &op in ops { + match op { + AbbrevOp::Literal(_) => {} + AbbrevOp::Fixed(w) => { + self.emit(values[idx], w); + idx += 1; + } + AbbrevOp::Vbr(w) => { + self.vbr(values[idx], w); + idx += 1; + } + AbbrevOp::ArrayFixed(w) => { + let rest = &values[idx..]; + self.vbr(rest.len() as u64, 6); + for &v in rest { + self.emit(v, w); + } + idx = values.len(); + } + AbbrevOp::ArrayVbr(w) => { + let rest = &values[idx..]; + self.vbr(rest.len() as u64, 6); + for &v in rest { + self.vbr(v, w); + } + idx = values.len(); + } + } + } + debug_assert_eq!(idx, values.len()); + } + /// An unabbreviated record. pub fn record(&mut self, code: u32, ops: &[u64]) { self.emit(3, self.width); // UNABBREV_RECORD @@ -152,4 +250,21 @@ mod tests { assert_eq!(signed(-3), 7); assert_eq!(signed(i64::MIN), 1); } + + #[test] + fn define_abbrev_round_trips_fixed_vbr_and_arrays() { + const AB: &[AbbrevOp] = &[AbbrevOp::Literal(22), AbbrevOp::ArrayFixed(32)]; + let mut w = BitWriter::new(); + for b in [b'B', b'C', 0xC0, 0xDE] { + w.emit(b as u64, 8); + } + w.enter_block_with_width(11, 3); + let id = w.define_abbrev(AB); + assert_eq!(id, 4); + w.emit_abbrev(id, AB, &[0x1234_5678, 0xDEAD_BEEF]); + w.end_block(); + let bc = w.finish(); + assert_eq!(&bc[..4], b"BC\xC0\xDE"); + assert_eq!(bc.len() % 4, 0); + } } diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index c8bfab774b..81ce01bb0d 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -1,14 +1,204 @@ //! The compact form: each distinct block of a program lowered once, in a loop over a table. use super::cfg::{Cfg, Term}; -use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET}; +use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET, VAR_SCC}; use super::lower_mem::VAR_TMP; use super::module::{Block, Pred, Value}; use std::collections::{BTreeSet, HashMap}; +const ALL_SGPRS_MASK: u128 = (1u128 << 106) - 1; +const SCC_LIVE_BIT: u128 = 1u128 << VAR_SCC; + +fn is_pure_nop(name: &str) -> bool { + matches!( + name, + "S_NOP" + | "V_NOP" + | "S_WAITCNT" + | "S_WAITCNT_VSCNT" + | "S_WAITCNT_VMCNT" + | "S_WAITCNT_LGKMCNT" + | "S_WAITCNT_EXPCNT" + | "S_WAITCNT_DEPCTR" + | "S_INST_PREFETCH" + | "S_CLAUSE" + ) +} + +/// Conservative `(use_mask, def_mask)` over `s0..s105` (bits `0..106`) and `SCC` (bit `VAR_SCC`). +/// Any register not provably unconditionally overwritten is omitted from `def_mask`; any unknown +/// or indexed SGPR read sets all bits in `use_mask`. +fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded, wave64: bool) -> (u128, u128) { + use crate::gpu::rdna2::{field_value, register_scale, Variant}; + if d.inst.name.starts_with("S_MOVREL") { + return (ALL_SGPRS_MASK, 0); + } + let cond_write = d.inst.name.starts_with("S_CMOV"); + let rmw_dst = matches!( + d.inst.name, + "S_ADDK_I32" | "S_MULK_I32" | "S_BITSET0_B32" | "S_BITSET1_B32" | "S_BITSET0_B64" | "S_BITSET1_B64" + ); + let (mut u, mut def) = (0u128, 0u128); + for o in d.ienc.operands { + if o.ty == "OPR_SSRC_SPECIAL_SCC" { + if o.input { + u |= SCC_LIVE_BIT; + } + if o.output { + def |= SCC_LIVE_BIT; + } + continue; + } + let Some(f) = o.field else { continue }; + if f == "LITERAL" || o.implicit { + continue; + } + if !["SREG", "SSRC", "SDST", "OPR_SRC", "SMEM_OFFSET"].iter().any(|k| o.ty.contains(k)) { + continue; + } + // SDWA / DPP sources are read from the extension word below + if f == "SRC0" && d.variant != Variant::Plain { + continue; + } + let Some(raw) = field_value(d.enc, &d.words, f) else { continue }; + let v = raw * register_scale(f); + if v == 253 && o.input { + u |= SCC_LIVE_BIT; + continue; + } + if v >= 106 { + continue; + } + let n = (o.size as u64).div_ceil(32).max(1); + // Wave32 VALU mask writers (V_CMP_*, V_ADD_CO_*, etc.) only write the low SGPR; do not + // mark s[v + 1] as killed. + let def_n = if !wave64 && o.output && o.size == 64 && !d.inst.name.starts_with("S_") { 1 } else { n }; + for r in v..(v + n).min(106) { + if o.input || (o.output && (cond_write || rmw_dst)) { + u |= 1u128 << r; + } + } + if o.output && !cond_write { + for r in v..(v + def_n).min(106) { + def |= 1u128 << r; + } + } + } + // SDWA: either source is an SGPR (or SCC) when its S bit is set, as `Lw::sources` reads them + if let Some(e) = ext_encoding(d).filter(|_| d.variant == Variant::Sdwa) { + let fv = |n: &str| field_value(e, &d.words, n).unwrap_or(0); + for (s, src) in [("S0", "VSRC0"), ("S1", "VSRC1")] { + if e.field(src).is_some() && fv(s) == 1 { + match fv(src) { + code @ 0..=105 => u |= 1u128 << code, + 253 => u |= SCC_LIVE_BIT, + _ => {} + } + } + } + } + (u, def) +} + +fn compute_live_out(cfg: &Cfg, mblocks: &[MicroBlock], end_live: u128, wave64: bool) -> Vec { + let n = mblocks.len(); + let mut b_use = vec![0u128; n]; + let mut b_def = vec![0u128; n]; + for (idx, blk) in mblocks.iter().enumerate() { + let (mut u, mut d) = (0u128, 0u128); + for &i in &blk.insts { + let (iu, id) = inst_sreg_scc_use_def(&cfg.insts[i], wave64); + u |= iu & !d; + d |= id; + } + if let Term::Cond(ci, ..) = blk.term { + let (iu, _) = inst_sreg_scc_use_def(&cfg.insts[ci], wave64); + u |= iu & !d; + } + b_use[idx] = u; + b_def[idx] = d; + } + let mut live_in = vec![0u128; n]; + let mut live_out = vec![0u128; n]; + loop { + let mut changed = false; + for idx in (0..n).rev() { + let out = match mblocks[idx].term { + Term::End => end_live, + Term::Jump(t) => if t < n { live_in[t] } else { end_live }, + Term::Cond(_, t, f) => { + let lt = if t < n { live_in[t] } else { end_live }; + let lf = if f < n { live_in[f] } else { end_live }; + lt | lf + } + }; + let inp = b_use[idx] | (out & !b_def[idx]); + if out != live_out[idx] || inp != live_in[idx] { + live_out[idx] = out; + live_in[idx] = inp; + changed = true; + } + } + if !changed { + break; + } + } + live_out +} + +/// If `blk` ends with a 3-instruction far-jump address computation (`s_getpc_b64 s[r:r+1]`, +/// `s_{add,sub}_u32 s[r]`, `s_{addc,subb}_u32 s[r+1]`) feeding a resolved `s_setpc_b64`, +/// return the destination SGPR base `r` (`< 105`) so dead far-jump veneers can be stripped. +fn resolved_far_jump_reg(cfg: &Cfg, blk: &MicroBlock) -> Option { + if !matches!(blk.term, Term::Jump(_)) || blk.insts.len() < 3 { + return None; + } + let len = blk.insts.len(); + let (i0, i1, i2) = (blk.insts[len - 3], blk.insts[len - 2], blk.insts[len - 1]); + if i1 != i0 + 1 || i2 != i1 + 1 { + return None; + } + let set = cfg.insts.get(i2 + 1)?; + if set.inst.name != "S_SETPC_B64" || set.far_target.is_none() { + return None; + } + let (get, lo, hi) = (&cfg.insts[i0], &cfg.insts[i1], &cfg.insts[i2]); + if get.inst.name != "S_GETPC_B64" { + return None; + } + if !matches!((lo.inst.name, hi.inst.name), ("S_ADD_U32", "S_ADDC_U32") | ("S_SUB_U32", "S_SUBB_U32")) { + return None; + } + let r = crate::gpu::rdna2::field_value(get.enc, &get.words, "SDST")?; + (r < 105).then_some(r) +} + +/// One virtual basic block in a compact plan (either a whole guest block or a split micro-block +/// isolating a repeated heavy memory instruction so its lowering is emitted once instead of once +/// per surrounding ALU context). +pub struct MicroBlock { + pub pc: u64, + pub insts: Vec, + pub term: Term, + pub is_header: bool, +} + +/// How the compact table encodes each micro-block's successor target(s). +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum NextEnc { + /// Pair of relative `(taken_off, not_taken_off)` indexed in `xcl_steps`. + Steps, + /// `not_taken = b + 1`; `field` holds the absolute `taken` block number directly. + Inline, + /// `not_taken = b + 1`; `field == 0` means `taken = b + 1`, else `xcl_targets[field - 1]`. + TargetPool, +} + pub struct Plan { - /// the reachable blocks in address order: the loop's block numbers + /// the reachable blocks in address order (same length as `mblocks`) pub order: Vec, + /// virtual blocks executed by the compact loop (targets in `term` are indices into `mblocks`) + pub mblocks: Vec, /// the class of each pub class: Vec, /// a block of each class (a block number) @@ -17,23 +207,45 @@ pub struct Plan { pub next: Vec<(u32, u32)>, /// the distinct pairs of offsets from a block to its two successors, sorted pub steps: Vec<(u32, u32)>, - /// an entry holds the block's taken successor itself; the other one is the next block + /// unique non-fallthrough taken targets for `NextEnc::TargetPool` + pub targets: Vec, + /// successor table encoding mode + pub next_enc: NextEnc, + /// an entry holds the block's taken successor itself (true for `Inline` and `TargetPool`) pub inline: bool, + /// per-block parameterized 32-bit literal when the block has exactly one parameterizable literal + pub blk_lit: Vec>, + /// whether `blk_lit` parameterization is enabled for this plan + pub use_lit: bool, + /// whether `S_GETPC_B64` block-PC parameterization is enabled for this plan + pub use_pc: bool, + /// union of live-out `(s0..s105 | SCC)` bitmasks across all micro-blocks in each class + pub class_live_out: Vec, } /// Most 32-bit words of tables a program may need to take the form by itself. -const MAX_TABLE_WORDS: usize = 12288; +const MAX_TABLE_WORDS: usize = 32768; impl Plan { /// Bits of a table entry: the class, and the taken successor or the index of the pair of offsets. fn widths(&self) -> (u32, u32) { - (bits(self.rep.len()), if self.inline { bits(self.order.len()) } else { bits(self.steps.len()) }) + let pb = match self.next_enc { + NextEnc::Steps => bits(self.steps.len()), + NextEnc::Inline => bits(self.mblocks.len()), + NextEnc::TargetPool => bits(self.targets.len() + 1), + }; + (bits(self.rep.len()), pb) } /// 32-bit words of the tables. pub fn words(&self) -> usize { let (cb, pb) = self.widths(); - (self.order.len() * (cb + pb) as usize).div_ceil(32) + 1 + if self.inline { 0 } else { self.steps.len() * 2 } + let extra = match self.next_enc { + NextEnc::Steps => self.steps.len() * 2, + NextEnc::Inline => 0, + NextEnc::TargetPool => self.targets.len(), + }; + (self.mblocks.len() * (cb + pb) as usize).div_ceil(32) + 1 + extra } } @@ -51,73 +263,397 @@ pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option { if !large && !(split_compute && atomic_candidate(cfg)) { return None; } let p = plan(cfg, lw)?; if p.words() > MAX_TABLE_WORDS { return None; } - let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); - let all: usize = (0..p.order.len()).map(insts).sum(); + let insts = |n: usize| p.mblocks[n].insts.len(); + let all: usize = (0..p.mblocks.len()).map(insts).sum(); let once: usize = p.rep.iter().map(|&n| insts(n)).sum(); let repeated = if large { once * 10 < all * 3 } else { p.rep.len() * 4 <= p.order.len() }; repeated.then_some(p) } -/// Whether to consider compaction based on instruction count alone. +/// Reachable non-terminator instruction count threshold for trying the compact form. +const LARGE_INSTS: usize = 10_000; +/// Reachable basic-block count threshold for trying the compact form: branch-heavy +/// unrolled programs with thousands of small blocks (even below `LARGE_INSTS` +/// non-terminator instructions) expand into tens of thousands of DXIL blocks and PHIs +/// in plain form, causing excessive driver-compiler memory commit spikes. +const LARGE_BLOCKS: usize = 2_000; + +/// Whether to consider compaction based on the reachable instruction and block counts. pub fn large(cfg: &Cfg) -> bool { - cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= 20_000 + cfg.rpo.len() >= LARGE_BLOCKS + || cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= LARGE_INSTS } pub const END: u32 = u32::MAX; +fn is_heavy_mem(d: &crate::gpu::rdna2::Decoded) -> bool { + matches!( + d.enc.name, + "ENC_MUBUF" | "ENC_MTBUF" | "ENC_SMEM" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" + ) && !matches!( + d.inst.name, + "S_DCACHE_INV" + | "S_DCACHE_WB" + | "S_DCACHE_DISCARD" + | "S_DCACHE_DISCARD_X2" + | "S_GL1_INV" + | "S_MEMTIME" + | "S_MEMREALTIME" + ) +} + +/// Whether a micro-block has exactly one parameterizable 32-bit literal instruction. +fn single_param_lit(cfg: &Cfg, blk: &MicroBlock) -> Option { + let mut found = None; + for &i in &blk.insts { + let d = &cfg.insts[i]; + if let Some(lit) = d.literal { + if d.inst.name == "S_SETREG_IMM32_B32" || d.enc.name == "ENC_MIMG" || found.is_some() { + return None; + } + found = Some(lit); + } + } + found +} + /// Sorts the reachable blocks into classes the lowering would emit the same for. +/// On large shaders, repeated heavy memory instructions (appearing `>= 4` times) are split +/// into standalone micro-blocks so each unique buffer/SMEM/image lowering is emitted once +/// instead of once per surrounding ALU context. pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { - let mut order = cfg.rpo.clone(); - order.sort_by_key(|&b| (cfg.blocks[b].pc, b)); - let mut number = vec![END; cfg.blocks.len()]; - for (n, &b) in order.iter().enumerate() { - number[b] = n as u32; + let mut orig_order = cfg.rpo.clone(); + orig_order.sort_by_key(|&b| (cfg.blocks[b].pc, b)); + + // Count exact heavy-memory instruction occurrences across reachable blocks. + let mut mem_counts: HashMap<(Vec, Option, Option<[u32; 4]>), usize> = HashMap::new(); + let allow_split = orig_order.len() >= 64; + if allow_split { + for &b in &orig_order { + for &i in &cfg.blocks[b].insts { + let d = &cfg.insts[i]; + if is_heavy_mem(d) { + let sampler = lw.static_samplers.get(&d.pc).copied(); + *mem_counts.entry((d.words.clone(), d.literal, sampler)).or_insert(0) += 1; + } + } + } } - let mut ids: HashMap<(Vec, &'static str), u32> = HashMap::new(); - let (mut class, mut rep, mut next) = (Vec::new(), Vec::new(), Vec::new()); - let mut falls = true; - for (n, &b) in order.iter().enumerate() { + + // Pass 1: split blocks around repeated heavy memory ops (`>= 4` occurrences). + let mut segs_per_orig: Vec<(usize, Vec>)> = Vec::with_capacity(orig_order.len()); + let mut orig_to_mb = vec![END; cfg.blocks.len()]; + let mut mb_cursor = 0u32; + for &b in &orig_order { let blk = &cfg.blocks[b]; - let mut key = vec![cfg.headers.contains(&b) as u64]; - for &i in &blk.insts { - let d = &cfg.insts[i]; - key.push(d.words.len() as u64); - key.extend(d.words.iter().map(|&w| w as u64)); - key.push(d.literal.map_or(u64::MAX, |l| l as u64)); - let sampler = lw.static_samplers.get(&d.pc); - key.push(sampler.is_some() as u64); - key.extend(sampler.into_iter().flatten().map(|&w| w as u64)); - // what `Lw::write_mask` asks of this address, for any register a mask can go to - if let Some(&l) = lw.whole_live.get(&d.pc) { - let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST")); - let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa); - key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3)); + let mut segs: Vec> = Vec::new(); + if allow_split && blk.insts.len() > 1 { + let mut cur: Vec = Vec::new(); + for &i in &blk.insts { + let d = &cfg.insts[i]; + let isolate = is_heavy_mem(d) + && mem_counts + .get(&(d.words.clone(), d.literal, lw.static_samplers.get(&d.pc).copied())) + .copied() + .unwrap_or(0) + >= 2; + if isolate { + if !cur.is_empty() { + segs.push(std::mem::take(&mut cur)); + } + segs.push(vec![i]); + } else { + cur.push(i); + } } - if d.inst.name == "S_GETPC_B64" { - key.push(d.pc); + if !cur.is_empty() { + segs.push(cur); } } - let (end, to) = match blk.term { - Term::End => ("end", (END, END)), - Term::Jump(t) => ("jump", (number[t], number[t])), - Term::Cond(i, t, f) => { - falls &= number[f] == n as u32 + 1; - (cfg.insts[i].inst.name, (number[t], number[f])) + if segs.is_empty() { + segs.push(blk.insts.clone()); + } + orig_to_mb[b] = mb_cursor; + mb_cursor += segs.len() as u32; + segs_per_orig.push((b, segs)); + } + + // Pass 2: materialize micro-blocks with remapped successor targets (stripping pure no-ops). + let mut order: Vec = Vec::with_capacity(mb_cursor as usize); + let mut mblocks: Vec = Vec::with_capacity(mb_cursor as usize); + for (orig_b, segs) in segs_per_orig { + let blk = &cfg.blocks[orig_b]; + let is_hdr = cfg.headers.contains(&orig_b); + let n_segs = segs.len(); + for (s, raw_insts) in segs.into_iter().enumerate() { + let my_id = mblocks.len(); + let pc = raw_insts.first().map_or(blk.pc, |&i| cfg.insts[i].pc); + let insts = if allow_split { + raw_insts.into_iter().filter(|&i| !is_pure_nop(cfg.insts[i].inst.name)).collect() + } else { + raw_insts + }; + let term = if s + 1 < n_segs { + Term::Jump(my_id + 1) + } else { + match blk.term { + Term::End => Term::End, + Term::Jump(t) => Term::Jump(orig_to_mb[t] as usize), + Term::Cond(ci, t, f) => Term::Cond(ci, orig_to_mb[t] as usize, orig_to_mb[f] as usize), + } + }; + order.push(orig_b); + mblocks.push(MicroBlock { pc, insts, term, is_header: s == 0 && is_hdr }); + } + } + + // Pass 3 (large shaders): strip dead far-jump veneers (`s_getpc_b64 + s_add_u32 + s_addc_u32` + // feeding a resolved `s_setpc_b64` when `s[r:r+1]` and `SCC` are dead at the jump target) and + // bypass empty non-header jump blocks so neither `xcl_blocks` nor `FUNCTION` pays for them. + let end_live = if lw.res.is_some() { ALL_SGPRS_MASK | SCC_LIVE_BIT } else { 0 }; + if allow_split { + let live_out = compute_live_out(cfg, &mblocks, end_live, lw.wave64); + for (idx, blk) in mblocks.iter_mut().enumerate() { + if let Some(r) = resolved_far_jump_reg(cfg, blk) { + let clobber = (1u128 << r) | (1u128 << (r + 1)) | SCC_LIVE_BIT; + if (live_out[idx] & clobber) == 0 { + let new_len = blk.insts.len() - 3; + blk.insts.truncate(new_len); + } } - }; - let fresh = ids.len() as u32; - let c = *ids.entry((key, end)).or_insert(fresh); - if c == fresh { - rep.push(n); } - class.push(c); - next.push(to); + // Bypass empty non-header jump micro-blocks (entry 0 stays pinned at 0). + // Preserve `falls` (`Term::Cond` fallthrough `f == idx + 1`) by not bypassing a + // fallthrough block whose jump goes anywhere other than `cur + 1`. + let n_mb = mblocks.len(); + let mut is_fallthrough = vec![false; n_mb]; + for (idx, blk) in mblocks.iter().enumerate() { + if let Term::Cond(_, _, f) = blk.term { + if f == idx + 1 && f < n_mb { + is_fallthrough[f] = true; + } + } + } + let mut redir: Vec = (0..n_mb).collect(); + for start in 1..n_mb { + let mut cur = start; + let mut ft = is_fallthrough[start]; + for _ in 0..64 { + if cur == 0 || mblocks[cur].is_header || !mblocks[cur].insts.is_empty() { + break; + } + match mblocks[cur].term { + Term::Jump(t) if t < n_mb && t != cur => { + if ft && t != cur + 1 { + break; + } + cur = t; + ft |= is_fallthrough[cur]; + } + _ => break, + } + } + redir[start] = cur; + } + for blk in &mut mblocks { + match &mut blk.term { + Term::Jump(t) if *t < n_mb => *t = redir[*t], + Term::Cond(_, t, f) => { + if *t < n_mb { + *t = redir[*t]; + } + if *f < n_mb { + *f = redir[*f]; + } + } + _ => {} + } + if let Term::Cond(_, t, f) = blk.term { + if t == f { + blk.term = Term::Jump(t); + } + } + } + // Compact out bypassed/unreachable micro-blocks. + let mut reach = vec![false; n_mb]; + let mut stack = vec![0usize]; + reach[0] = true; + while let Some(u) = stack.pop() { + match mblocks[u].term { + Term::Jump(t) if t < n_mb && !reach[t] => { + reach[t] = true; + stack.push(t); + } + Term::Cond(_, t, f) => { + if t < n_mb && !reach[t] { + reach[t] = true; + stack.push(t); + } + if f < n_mb && !reach[f] { + reach[f] = true; + stack.push(f); + } + } + _ => {} + } + } + let mut remap = vec![END as usize; n_mb]; + let mut new_order = Vec::with_capacity(n_mb); + let mut new_mblocks = Vec::with_capacity(n_mb); + for (i, (orig_b, blk)) in order.into_iter().zip(mblocks.into_iter()).enumerate() { + if reach[i] { + remap[i] = new_mblocks.len(); + new_order.push(orig_b); + new_mblocks.push(blk); + } + } + for blk in &mut new_mblocks { + match &mut blk.term { + Term::Jump(t) if *t < n_mb => *t = remap[*t], + Term::Cond(_, t, f) => { + if *t < n_mb { + *t = remap[*t]; + } + if *f < n_mb { + *f = remap[*f]; + } + } + _ => {} + } + } + order = new_order; + mblocks = new_mblocks; + } + + let final_live_out = if allow_split { + compute_live_out(cfg, &mblocks, end_live, lw.wave64) + } else { + vec![ALL_SGPRS_MASK | SCC_LIVE_BIT; mblocks.len()] + }; + + let build = |param_lit: bool, param_pc: bool| { + let mut ids: HashMap<(Vec, &'static str), u32> = HashMap::new(); + let (mut class, mut rep, mut next, mut blk_lit) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut falls = true; + for (n, blk) in mblocks.iter().enumerate() { + let p_lit = if param_lit { single_param_lit(cfg, blk) } else { None }; + blk_lit.push(p_lit); + let mut key = vec![blk.is_header as u64, p_lit.is_some() as u64]; + for &i in &blk.insts { + let d = &cfg.insts[i]; + let mask_lit = p_lit.is_some() && d.literal.is_some(); + let words = if mask_lit { &d.words[..d.words.len() - 1] } else { &d.words[..] }; + key.push(d.words.len() as u64); + key.extend(words.iter().map(|&w| w as u64)); + if mask_lit { + key.push(u64::MAX - 1); + } else { + key.push(d.literal.map_or(u64::MAX, |l| l as u64)); + } + let sampler = lw.static_samplers.get(&d.pc); + key.push(sampler.is_some() as u64); + key.extend(sampler.into_iter().flatten().map(|&w| w as u64)); + // what `Lw::write_mask` asks of this address, for any register a mask can go to + if let Some(&l) = lw.whole_live.get(&d.pc) { + let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST")); + let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa); + key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3)); + } + if d.inst.name == "S_GETPC_B64" { + key.push(if param_pc { d.pc.wrapping_sub(blk.pc) } else { d.pc }); + } + } + let (end, to) = match blk.term { + Term::End => ("end", (END, END)), + Term::Jump(t) => ("jump", (t as u32, t as u32)), + Term::Cond(i, t, f) => { + falls &= f == n + 1; + (cfg.insts[i].inst.name, (t as u32, f as u32)) + } + }; + let fresh = ids.len() as u32; + let c = *ids.entry((key, end)).or_insert(fresh); + if c == fresh { + rep.push(n); + } + class.push(c); + next.push(to); + } + (class, rep, next, blk_lit, falls) + }; + let base = build(false, false); + let has_getpc = allow_split && mblocks.iter().any(|blk| blk.insts.iter().any(|&i| cfg.insts[i].inst.name == "S_GETPC_B64")); + // Parameterize single-literal blocks (and S_GETPC_B64 when present) on large shaders only + // when the collapsed switch arms outweigh the packed lookup tables (`~2 B/block` per table). + let (use_lit, use_pc, (class, rep, next, blk_lit, falls)) = if allow_split { + let cand = build(true, has_getpc); + let saved_both = base.1.len().saturating_sub(cand.1.len()); + let table_cost = mblocks.len() * if has_getpc { 4 } else { 2 }; + if saved_both >= 64 && saved_both * 60 > table_cost { + let only_lit = if has_getpc { build(true, false) } else { cand.clone() }; + let saved_pc = only_lit.1.len().saturating_sub(cand.1.len()); + if has_getpc && saved_pc >= 64 && saved_pc * 60 > mblocks.len() * 2 { + (true, true, cand) + } else if base.1.len().saturating_sub(only_lit.1.len()) >= 64 + && base.1.len().saturating_sub(only_lit.1.len()) * 60 > mblocks.len() * 2 + { + (true, false, only_lit) + } else { + (false, false, base) + } + } else { + (false, false, base) + } + } else { + (false, false, base) + }; + let mut class_live_out = vec![0u128; rep.len()]; + for (mb_idx, &c) in class.iter().enumerate() { + class_live_out[c as usize] |= final_live_out[mb_idx]; } let steps: BTreeSet<(u32, u32)> = next.iter().enumerate().map(|(b, &to)| offsets(b, to)).collect(); - let mut p = Plan { order, class, rep, next, steps: steps.into_iter().collect(), inline: false }; - let pairs = p.words(); - p.inline = falls; - p.inline = falls && p.words() < pairs; + let targets: Vec = if falls { + let set: BTreeSet = next + .iter() + .enumerate() + .filter_map(|(b, &(t, _))| (t != END && t != b as u32 + 1).then_some(t)) + .collect(); + set.into_iter().collect() + } else { + Vec::new() + }; + let mut p = Plan { + order, + mblocks, + class, + rep, + next, + steps: steps.into_iter().collect(), + targets, + next_enc: NextEnc::Steps, + inline: false, + blk_lit, + use_lit, + use_pc, + class_live_out, + }; + let mut best_enc = NextEnc::Steps; + let mut best_words = p.words(); + if falls { + for cand_enc in [NextEnc::Inline, NextEnc::TargetPool] { + if cand_enc == NextEnc::TargetPool && p.targets.is_empty() { + continue; + } + p.next_enc = cand_enc; + let (cb, pb) = p.widths(); + if cb + pb <= 32 && p.words() < best_words { + best_words = p.words(); + best_enc = cand_enc; + } + } + } + p.next_enc = best_enc; + p.inline = matches!(best_enc, NextEnc::Inline | NextEnc::TargetPool); let (cb, pb) = p.widths(); (cb + pb <= 32).then_some(p) } @@ -131,12 +667,12 @@ fn bits(n: usize) -> u32 { (usize::BITS - n.saturating_sub(1).leading_zeros()).max(1) } -/// A constant table of 32-bit words. +/// A constant table of 32-bit words (emitted via LLVM `CST_CODE_DATA` without interning +/// each element as an individual `CST_CODE_INTEGER` constant). fn table(lw: &mut Lw, name: &str, words: &[u32]) -> Value { - let vals: Vec = words.iter().map(|&w| lw.c(w)).collect(); let i32 = lw.s.m.i32(); let at = lw.s.m.array(words.len() as u64, i32); - let init = lw.s.m.aggregate(at, &vals); + let init = lw.s.m.const_data_i32(words); lw.s.m.global(name, at, 0, Some(init), true, 4) } @@ -220,10 +756,13 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let width = cb + pb; let mut packed = vec![0u32; (n * width as usize).div_ceil(32) + 1]; for (b, &to) in p.next.iter().enumerate() { - let field = match (p.inline, to.0) { - (true, END) => 0, - (true, t) => t, - _ => p.steps.binary_search(&offsets(b, to)).expect("a pair of the plan") as u32, + let field = match (p.next_enc, to.0) { + (NextEnc::Inline, END) => 0, + (NextEnc::Inline, t) => t, + (NextEnc::TargetPool, END) => 0, + (NextEnc::TargetPool, t) if t == b as u32 + 1 => 0, + (NextEnc::TargetPool, t) => p.targets.binary_search(&t).expect("target in pool") as u32 + 1, + (NextEnc::Steps, _) => p.steps.binary_search(&offsets(b, to)).expect("a pair of the plan") as u32, }; let e = (p.class[b] | field << cb) as u64; let at = b * width as usize; @@ -232,7 +771,44 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block } let blocks = table(lw, "xcl_blocks", &packed); let steps: Vec = p.steps.iter().flat_map(|&(t, f)| [t, f]).collect(); - let steps = (!p.inline).then(|| table(lw, "xcl_steps", &steps)); + let steps = (p.next_enc == NextEnc::Steps).then(|| table(lw, "xcl_steps", &steps)); + let target_pool = (p.next_enc == NextEnc::TargetPool).then(|| table(lw, "xcl_targets", &p.targets)); + let pc_table = p.use_pc.then(|| { + let max_pc_dw = p.mblocks.iter().map(|blk| (blk.pc >> 2) as usize).max().unwrap_or(0); + let pc_w = bits(max_pc_dw + 1).min(32); + let mut pc_packed = vec![0u32; (n * pc_w as usize).div_ceil(32) + 1]; + for (b, blk) in p.mblocks.iter().enumerate() { + let v = (blk.pc >> 2) as u64; + let at = b * pc_w as usize; + pc_packed[at / 32] |= (v << (at % 32)) as u32; + pc_packed[at / 32 + 1] |= (v << (at % 32) >> 32) as u32; + } + (table(lw, "xcl_pc", &pc_packed), pc_w) + }); + let lit_table = p.use_lit.then(|| { + // Deduplicate unique 32-bit literals into a pool and bit-pack pool indices per block. + let mut pool: Vec = vec![0]; + let mut idx_map: HashMap = HashMap::from([(0, 0)]); + let mut blk_idx: Vec = Vec::with_capacity(n); + for &opt in &p.blk_lit { + let val = opt.unwrap_or(0); + let idx = *idx_map.entry(val).or_insert_with(|| { + let id = pool.len() as u32; + pool.push(val); + id + }); + blk_idx.push(idx); + } + let lit_w = bits(pool.len()).min(32); + let mut idx_packed = vec![0u32; (n * lit_w as usize).div_ceil(32) + 1]; + for (b, &id) in blk_idx.iter().enumerate() { + let v = id as u64; + let at = b * lit_w as usize; + idx_packed[at / 32] |= (v << (at % 32)) as u32; + idx_packed[at / 32 + 1] |= (v << (at % 32) >> 32) as u32; + } + (table(lw, "xcl_lit_idx", &idx_packed), table(lw, "xcl_lit_pool", &pool), lit_w) + }); let (at, to) = (lw.tmp_var(), lw.tmp_var()); let (at, to, budget) = (slot(lw, at), slot(lw, to), slot(lw, VAR_BUDGET)); @@ -254,12 +830,61 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let class = lw.andc(e, (1u32 << cb) - 1); let field = lw.lshrc(e, cb); let field = lw.andc(field, (1u32 << pb) - 1); + let blk_pc = pc_table.map(|(pc_tbl, pc_w)| { + let pm = if pc_w == 32 { + word(lw, pc_tbl, b) + } else { + let pw = lw.c(pc_w); + let pbit = lw.mul(b, pw); + let pi = lw.lshrc(pbit, 5); + let psh = lw.andc(pbit, 31); + let plo = word(lw, pc_tbl, pi); + let pi1 = lw.addc(pi, 1); + let phi = word(lw, pc_tbl, pi1); + let plo = lw.lshr(plo, psh); + let phi = lw.shlc(phi, 1); + let pup = lw.sub(k31, psh); + let phi = lw.shl(phi, pup); + let pe = lw.or(plo, phi); + lw.andc(pe, (1u32 << pc_w) - 1) + }; + lw.shlc(pm, 2) + }); + let blk_lit_val = lit_table.map(|(idx_tbl, pool_tbl, lit_w)| { + let id = if lit_w == 32 { + word(lw, idx_tbl, b) + } else { + let lw_c = lw.c(lit_w); + let lbit = lw.mul(b, lw_c); + let li = lw.lshrc(lbit, 5); + let lsh = lw.andc(lbit, 31); + let llo = word(lw, idx_tbl, li); + let li1 = lw.addc(li, 1); + let lhi = word(lw, idx_tbl, li1); + let llo = lw.lshr(llo, lsh); + let lhi = lw.shlc(lhi, 1); + let lup = lw.sub(k31, lsh); + let lhi = lw.shl(lhi, lup); + let le = lw.or(llo, lhi); + lw.andc(le, (1u32 << lit_w) - 1) + }; + word(lw, pool_tbl, id) + }); let (taken, not_taken) = if let Some(steps) = steps { let pi = lw.shlc(field, 1); let step_t = word(lw, steps, pi); let pi1 = lw.addc(pi, 1); let step_f = word(lw, steps, pi1); (lw.add(b, step_t), lw.add(b, step_f)) + } else if let Some(target_tbl) = target_pool { + let next_b = lw.addc(b, 1); + let is_fall = lw.cmpc(Pred::Eq, field, 0); + let one = lw.c(1); + let tidx = lw.sub(field, one); + let z = lw.c(0); + let safe_tidx = lw.sel(is_fall, z, tidx); + let pooled = word(lw, target_tbl, safe_tidx); + (lw.sel(is_fall, next_b, pooled), next_b) } else { (field, lw.addc(b, 1)) }; @@ -296,8 +921,8 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block lw.s.m.set_block(c); lw.init.mem = Some(c); lw.ssa.begin_log(); - let blk = &cfg.blocks[p.order[r]]; - if cfg.headers.contains(&p.order[r]) { + let blk = &p.mblocks[r]; + if blk.is_header { // a loop head spends the loop budget let left = lw.s.m.load(budget, 4); let none = lw.cmpc(Pred::Eq, left, 0); @@ -312,9 +937,13 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let l = lw.sub(left, one); lw.s.m.store(budget, l, 4); } + lw.compact_blk_pc = blk_pc.map(|v| (v, blk.pc)); + lw.compact_lit = if p.blk_lit[r].is_some() { blk_lit_val } else { None }; for &i in &blk.insts { lw.inst(&cfg.insts[i])?; } + lw.compact_blk_pc = None; + lw.compact_lit = None; let next = match blk.term { Term::End => lw.c(END), Term::Jump(_) => taken, @@ -323,7 +952,11 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block lw.sel(c, taken, not_taken) } }; + let live_out = p.class_live_out[k]; for var in lw.ssa.end_log().into_iter().filter(|&v| v < VAR_TMP) { + if (var < 106 || var == VAR_SCC) && (live_out & (1u128 << var)) == 0 { + continue; + } let (v, p) = (lw.rd(var), slot(lw, var)); lw.s.m.store(p, v, 4); } @@ -362,3 +995,66 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block } Ok(()) } + +#[cfg(test)] +mod liveness_tests { + use super::*; + use crate::gpu::rdna2; + + fn dec(name: &str, enc: &str, fields: &[(&str, u64)]) -> rdna2::Decoded { + let bytes = rdna2::encode(name, enc, fields, None).unwrap(); + rdna2::decode(&bytes, 0).unwrap() + } + + #[test] + fn cmov_and_rmw_salu_read_sdst_and_wave32_valu_keeps_hi_sgpr() { + // S_CMOV_B32 / S_CMOV_B64: conditional write reads SDST and must not kill it. + let cmov32 = dec("S_CMOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 2)]); + let (u, d) = inst_sreg_scc_use_def(&cmov32, true); + assert_ne!(u & (1u128 << 4), 0, "S_CMOV_B32 must use SDST"); + assert_eq!(d & (1u128 << 4), 0, "S_CMOV_B32 must not kill SDST"); + + let cmov64 = dec("S_CMOV_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 2)]); + let (u, d) = inst_sreg_scc_use_def(&cmov64, true); + assert_eq!(u & ((1u128 << 6) | (1u128 << 7)), (1u128 << 6) | (1u128 << 7)); + assert_eq!(d & ((1u128 << 6) | (1u128 << 7)), 0); + + // RMW SALU ops (S_ADDK_I32, S_MULK_I32, S_BITSET0_B32, S_BITSET1_B64): both use and def SDST. + for (name, enc, fields, width) in [ + ("S_ADDK_I32", "ENC_SOPK", &[("SDST", 8), ("SIMM16", 1)][..], 1u64), + ("S_MULK_I32", "ENC_SOPK", &[("SDST", 9), ("SIMM16", 3)][..], 1u64), + ("S_BITSET0_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)][..], 1u64), + ("S_BITSET1_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)][..], 2u64), + ] { + let inst = dec(name, enc, fields); + let (u, d) = inst_sreg_scc_use_def(&inst, true); + let base = fields[0].1; + let mask = if width == 2 { (1u128 << base) | (1u128 << (base + 1)) } else { 1u128 << base }; + assert_eq!(u & mask, mask, "{name} must use SDST"); + assert_eq!(d & mask, mask, "{name} must def SDST"); + } + + // Wave32 VALU mask writer (V_CMP_EQ_U32 VOP3) writes only s4, leaving s5 live. + let vcmp = dec("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 256), ("SRC1", 257)]); + let (_, d32) = inst_sreg_scc_use_def(&vcmp, false); + assert_ne!(d32 & (1u128 << 4), 0, "Wave32 V_CMP must def s4"); + assert_eq!(d32 & (1u128 << 5), 0, "Wave32 V_CMP must not kill s5"); + let (_, d64) = inst_sreg_scc_use_def(&vcmp, true); + assert_eq!(d64 & ((1u128 << 4) | (1u128 << 5)), (1u128 << 4) | (1u128 << 5)); + } + + /// An SDWA source with its S bit set is an SGPR the instruction reads (`Lw::sources`): the + /// liveness keeps it, or the block before would leave its store out. + #[test] + fn sdwa_sgpr_sources_are_uses() { + let s1 = dec("V_ADD_NC_U32", "VOP2_VOP_SDWA", &[("VDST", 9), ("SRC0", 0xF9), ("VSRC0", 0), ("VSRC1", 20), ("S1", 1), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6)]); + let (u, _) = inst_sreg_scc_use_def(&s1, false); + assert_ne!(u & (1u128 << 20), 0, "SDWA S1 source s20 must be a use"); + let s0 = dec("V_ADD_F16", "VOP2_VOP_SDWA", &[("VDST", 10), ("SRC0", 0xF9), ("VSRC0", 7), ("S0", 1), ("VSRC1", 1), ("SRC0_SEL", 6), ("SRC1_SEL", 5), ("DST_SEL", 6)]); + let (u, _) = inst_sreg_scc_use_def(&s0, false); + assert_ne!(u & (1u128 << 7), 0, "SDWA S0 source s7 must be a use"); + assert_eq!(u & (1u128 << 1), 0, "VSRC1 without S1 is v1, not s1"); + let vgprs = dec("V_ADD_NC_U32", "VOP2_VOP_SDWA", &[("VDST", 9), ("SRC0", 0xF9), ("VSRC0", 3), ("VSRC1", 4), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("DST_SEL", 6)]); + assert_eq!(inst_sreg_scc_use_def(&vgprs, false).0, 0); + } +} diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 86d41bfd68..cf56c97c85 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -61,7 +61,11 @@ fn a_large_program_that_repeats_itself_takes_the_compact_form() { return; } let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; - for (copies, compact) in [(2500, true), (2000, false)] { + // `repeated(copies)` has 4 basic blocks and 9 non-terminator instructions per copy: + // - 2500 copies (10k blocks, 22.5k insts) and 500 copies (2k blocks, 4.5k insts) cross + // the compact threshold and take the compact form; + // - 400 copies (1.6k blocks, 3.6k insts) stay below both thresholds and keep plain form. + for (copies, compact) in [(2500, true), (500, true), (400, false)] { assert_eq!(translate_full(&repeated(copies), o).unwrap().dxil.len(), size(copies, o, compact), "{copies} copies"); } } @@ -127,6 +131,60 @@ fn early_outs(copies: usize) -> Vec { v } +/// Copies of one block that differ only in a literal, each after the same scalar load and a +/// no-op, each with an early out to the end: the load becomes a micro-block of its own, the +/// no-op goes, and the literal is read from a table. +fn loads_and_literals(copies: usize) -> Vec { + let i = |n: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(n, e, f, lit).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut v = Vec::new(); + for k in 0..copies { + v.extend(i("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 1), ("OFFSET", 0), ("SOFFSET", 125)], None)); + v.extend(i("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)], None)); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 8)], None)); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 255)], Some(1000 + k as u32))); + v.extend(i("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 4)], None)); + // to the s_mov after the last copy: 8 dwords per copy (the load and the literal take 2) + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", ((copies - 1 - k) * 8) as u64)], None)); + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 129)], None)); + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + v +} + +#[test] +fn repeated_loads_split_into_micro_blocks_and_literals_into_a_table() { + let code = loads_and_literals(200); + let cfg = super::cfg::Cfg::build(&code).unwrap(); + let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); + let p = super::compact::plan(&cfg, &lw).unwrap(); + assert!(p.mblocks.len() > cfg.rpo.len(), "{} micro-blocks of {} blocks", p.mblocks.len(), cfg.rpo.len()); + assert!(p.mblocks.iter().all(|b| b.insts.iter().all(|&i| cfg.insts[i].inst.name != "S_WAITCNT"))); + assert!(p.use_lit && p.inline, "literal table {}, inline successors {}", p.use_lit, p.inline); + assert!(p.rep.len() < 8, "{} classes", p.rep.len()); +} + +#[test] +fn gpu_compact_form_with_micro_blocks_and_literal_table_runs_as_the_plain_form() { + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let mut st = KernelState::default(); + // s[2:3] = 0: the loads read mem[0]; the early out is taken in the 10th copy + st.sgpr[4] = 50; + let code = loads_and_literals(200); + let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let run = |compact: bool| { + let k = translate_full_as(&code, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + runner::run_with_statics(&k.dxil, &st, &[5, 0, 0, 0], &[], &[], &k.static_samplers).expect("GPU run") + }; + let (c, p) = (run(true), run(false)); + assert_eq!((c.sgpr[0], c.sgpr[1], c.sgpr[5], c.sgpr[8]), (50, (1000..1010).sum::(), 1, 5)); + assert_eq!((c.sgpr, c.vgpr, c.scc), (p.sgpr, p.vgpr, p.scc)); +} + #[test] fn branches_to_many_places_keep_their_target_in_the_entry() { let code = early_outs(1000); @@ -213,7 +271,7 @@ fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); let p = super::compact::automatic_plan(&cfg, &lw, false).unwrap(); - assert!(p.inline && p.words() > 8192 && p.words() <= 12288); + assert!(p.inline && p.order.len() > 16384 && p.words() <= 12288); let k = translate_full(&code, o).unwrap(); for initial in [0u32, u32::MAX - 1, 0u32.wrapping_sub(COPIES as u32), 0u32.wrapping_sub((2 * COPIES) as u32), 0u32.wrapping_sub(COPIES as u32 + 1)] { let mut st = KernelState::default(); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 89eeaf1d8d..20fce94bc9 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -683,6 +683,8 @@ impl Lw { has_f64_round_op: false, img_writes: crate::gpu::recomp::emit::image_write_srsrcs(insts), exec_cache: HashMap::new(), + compact_blk_pc: None, + compact_lit: None, xs: None, xw: None, xc: None, diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index d2dd21d95d..eeeecb3dbb 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -282,6 +282,10 @@ pub struct Lw { pub static_used: Vec<([u32; 4], bool, super::ops::Sampler)>, pub sampler_base: u32, pub exec_cache: HashMap<(Block, Value, Value), Value>, + /// dynamic block-start PC `(blk_pc_val, rep_blk_pc)` when lowering compact `S_GETPC_B64` blocks + pub compact_blk_pc: Option<(Value, u64)>, + /// dynamic 32-bit literal value when lowering a single-literal parameterized compact block + pub compact_lit: Option, /// 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)>, @@ -756,6 +760,10 @@ impl Lw { } /// 32-bit value of a scalar source code (0..255) or VALU source (256+ = VGPR). + fn lit_c(&mut self, lit: u32) -> Value { + self.compact_lit.unwrap_or_else(|| self.c(lit)) + } + pub fn code32(&mut self, code: u64, lit: Option, f16: bool) -> Option { Some(match code { 0..=124 | 126 | 127 => self.sreg(code), @@ -779,7 +787,7 @@ impl Lw { self.u(z) } 253 => self.scc(), - 255 => self.c(lit?), + 255 => self.lit_c(lit?), 256..=511 => self.vreg(code - 256), 235..=238 => self.c(0), 239 => self.c(0x7FFF_FFFF), @@ -803,9 +811,9 @@ impl Lw { 251 | 252 | 253 => (self.code32(code, None, false)?, self.c(0)), 255 => { if f64 { - (self.c(0), self.c(lit?)) + (self.c(0), self.lit_c(lit?)) } else { - (self.c(lit?), self.c(0)) + (self.lit_c(lit?), self.c(0)) } } 256..=510 => (self.vreg(code - 256), self.vreg(code - 255)), @@ -822,7 +830,7 @@ impl Lw { pub fn read(&mut self, d: &Decoded, o: &Operand, f16: bool) -> Option { match o.field { - Some("LITERAL") => Some(self.c(d.literal?)), + Some("LITERAL") => Some(self.lit_c(d.literal?)), Some(f) => { let v = Self::field(d, f); let width = d.enc.field_width(f); @@ -831,7 +839,7 @@ impl Lw { } match o.ty { "OPR_SIMM16" => Some(self.c(v as u32)), - "OPR_SIMM32" => Some(self.c(d.literal?)), + "OPR_SIMM32" => Some(self.lit_c(d.literal?)), _ => self.code32(v, d.literal, f16), } } @@ -1392,9 +1400,15 @@ impl Lw { if name == "s_getpc_b64" { // the code region is addressed from 0 – with constant data after the program and // several memory windows, above them all (`rodata_loads`), as the HLSL kernel - let pc = d.pc + d.len as u64; + let lo = match self.compact_blk_pc { + Some((blk_pc, rep_blk_pc)) => { + let rel = (d.pc + d.len as u64).wrapping_sub(rep_blk_pc) as u32; + if rel == 0 { blk_pc } else { self.addc(blk_pc, rel) } + } + None => self.c((d.pc + d.len as u64) as u32), + }; let code_hi = if self.rodata.is_empty() || !self.windowed() { 0 } else { crate::gpu::recomp::CODE_ADDRESS_HI }; - let (lo, hi) = (self.c(pc as u32), self.c(code_hi)); + let hi = self.c(code_hi); self.write64(&dst, lo, hi); return Ok(()); } diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index a9601ad981..394c976eb6 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; -use super::bitstream::{signed, BitWriter}; +use super::bitstream::{signed, AbbrevOp, BitWriter}; mod opt; #[cfg(test)] @@ -60,6 +60,9 @@ enum ConstDef { Undef(Ty), Null(Ty), Aggregate(Ty, Vec), + /// Packed `i32` constant array (`CST_CODE_DATA = 22`), avoiding per-element `CST_CODE_INTEGER` + /// interning for large lookup tables (e.g. `compact.rs`). + DataI32(Ty, Vec), } #[derive(Clone)] @@ -462,6 +465,16 @@ impl Module { self.constant(ConstDef::Aggregate(ty, elems.to_vec())) } + /// Packed `[N x i32]` constant data array (`CST_CODE_DATA`), avoiding interning each element. + pub fn const_data_i32(&mut self, words: &[u32]) -> Value { + let i32 = self.i32(); + let at = self.array(words.len() as u64, i32); + if words.is_empty() { + return self.null(at); + } + self.constant(ConstDef::DataI32(at, words.to_vec())) + } + // ---- functions and globals /// Declares (or finds) a function by name. @@ -511,7 +524,12 @@ impl Module { 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, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }, Value::Inst(i) => self.insts[i as usize].ty, } @@ -964,18 +982,30 @@ impl Module { // Module-level constants. if n_consts > 0 { + const ABBREV_CST_INT: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_INTEGER as u64), AbbrevOp::Vbr(6)]; + const ABBREV_CST_F32: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_FLOAT as u64), AbbrevOp::Fixed(32)]; + const ABBREV_CST_DATA: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_DATA as u64), AbbrevOp::ArrayFixed(32)]; w.enter_block(BLOCK_CONSTANTS); + let ab_int = w.define_abbrev(ABBREV_CST_INT); + let ab_f32 = w.define_abbrev(ABBREV_CST_F32); + let ab_data = w.define_abbrev(ABBREV_CST_DATA); let mut cur_ty = None; for c in self.consts.iter().enumerate().filter(|(i, _)| cused[*i]).map(|x| x.1) { let t = match c { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(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::Int(_, v) => w.emit_abbrev(ab_int, ABBREV_CST_INT, &[signed(*v)]), + ConstDef::Float(_, bits) if *bits <= u32::MAX as u64 => w.emit_abbrev(ab_f32, ABBREV_CST_F32, &[*bits]), ConstDef::Float(_, bits) => w.record(CST_CODE_FLOAT, &[*bits]), ConstDef::Undef(_) => w.record(CST_CODE_UNDEF, &[]), ConstDef::Null(_) => w.record(CST_CODE_NULL, &[]), @@ -983,6 +1013,10 @@ impl Module { let ops: Vec = e.iter().map(|&v| abs(v)).collect(); w.record(CST_CODE_AGGREGATE, &ops) } + ConstDef::DataI32(_, words) => { + let ops: Vec = words.iter().map(|&x| x as u64).collect(); + w.emit_abbrev(ab_data, ABBREV_CST_DATA, &ops); + } } } w.end_block(); @@ -1023,15 +1057,16 @@ impl Module { } w.end_block(); - // The entry's body. - w.enter_block(BLOCK_FUNCTION); + // The entry's body (abbrev width 4 -> 12 user abbreviations for hot DXIL opcodes). + w.enter_block_with_width(BLOCK_FUNCTION, 4); + let ab = FuncAbbrevs::define(&mut w); w.record(FUNC_CODE_DECLAREBLOCKS, &[order.len() as u64]); let mut inst_id = inst_base; let mut operands = Vec::new(); 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, &mut operands); + self.write_inst(&mut w, &ab, i, inst_id, &abs, &pos, &mut operands); if !self.is_void(self.insts[i].ty) { inst_id += 1; } @@ -1230,6 +1265,7 @@ impl Module { fn write_inst( &self, w: &mut BitWriter, + ab: &FuncAbbrevs, i: usize, inst_id: u64, abs: &dyn Fn(Value) -> u64, @@ -1255,21 +1291,22 @@ impl Module { ops.clear(); match &self.insts[i].op { Op::Bin(op, a, b, flags) => { - ops.extend_from_slice(&[rel(*a), rel(*b), *op as u64]); - if *flags != 0 { - ops.push(*flags); + if *flags == 0 { + w.emit_abbrev(ab.binop, ABBREV_BINOP, &[rel(*a), rel(*b), *op as u64]); + } else { + ops.extend_from_slice(&[rel(*a), rel(*b), *op as u64, *flags]); + w.record(FUNC_CODE_INST_BINOP, ops); } - 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::Cast(op, v, t) => w.emit_abbrev(ab.cast, ABBREV_CAST, &[rel(*v), t.0 as u64, *op as u64]), + Op::Cmp(p, a, b) => w.emit_abbrev(ab.cmp2, ABBREV_CMP2, &[rel(*a), rel(*b), *p as u64]), + Op::Select(c, t, f) => w.emit_abbrev(ab.vselect, ABBREV_VSELECT, &[rel(*t), rel(*f), rel(*c)]), + Op::Extract(a, idx) => w.emit_abbrev(ab.extract, ABBREV_EXTRACT, &[rel(*a), *idx as u64]), Op::Call(f, args) => { let fd = &self.funcs[*f as usize]; - ops.extend_from_slice(&[0, 1 << 15, fd.ty.0 as u64, rel(Value::Func(*f))]); + ops.extend_from_slice(&[fd.ty.0 as u64, rel(Value::Func(*f))]); ops.extend(args.iter().map(|&a| rel(a))); - w.record(FUNC_CODE_INST_CALL, ops) + w.emit_abbrev(ab.call, ABBREV_CALL, ops); } Op::Phi(inc) => { ops.push(self.insts[i].ty.0 as u64); @@ -1278,22 +1315,30 @@ impl Module { ops.push(signed(inst_id as i64 - abs(v) as i64)); ops.push(bb(b)); } - w.record(FUNC_CODE_INST_PHI, ops) + w.emit_abbrev(ab.phi, ABBREV_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]) + if a == 3 { + w.emit_abbrev(ab.load, ABBREV_LOAD, &[rel(*p), self.insts[i].ty.0 as u64]); + } else { + 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]) + if a == 3 { + w.emit_abbrev(ab.store, ABBREV_STORE, &[rel(*p), rel(*v)]); + } else { + 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)); - ops.extend_from_slice(&[1, src.0 as u64, rel(*p)]); + ops.extend_from_slice(&[src.0 as u64, rel(*p)]); ops.extend(idx.iter().map(|&v| rel(v))); - w.record(FUNC_CODE_INST_GEP, ops) + w.emit_abbrev(ab.gep, ABBREV_GEP, ops); } Op::AtomicRmw(op, p, v) => { // [ptr, val, op, vol, ordering, synchscope (crossthread = 1)] @@ -1309,8 +1354,8 @@ impl Module { 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::Br(b) => w.emit_abbrev(ab.br, ABBREV_BR, &[bb(*b)]), + Op::CondBr(c, t, f) => w.emit_abbrev(ab.condbr, ABBREV_CONDBR, &[bb(*t), bb(*f), rel(*c)]), Op::Switch(v, d, cases) => { ops.extend_from_slice(&[self.value_ty(*v).0 as u64, rel(*v), bb(*d)]); for &(c, b) in cases { @@ -1330,7 +1375,12 @@ impl Module { 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, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }, Value::Inst(i) => self.insts[i as usize].ty, } @@ -1389,6 +1439,7 @@ 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 CST_CODE_DATA: u32 = 22; const METADATA_STRING: u32 = 1; const METADATA_VALUE: u32 = 2; @@ -1417,6 +1468,66 @@ const FUNC_CODE_INST_GEP: u32 = 43; const FUNC_CODE_INST_STORE: u32 = 44; const FUNC_CODE_INST_CMPXCHG: u32 = 46; +const ABBREV_BINOP: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BINOP as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(4)]; +const ABBREV_CAST: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_CAST as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(4)]; +const ABBREV_CMP2: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_CMP2 as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(6)]; +const ABBREV_VSELECT: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_VSELECT as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5)]; +const ABBREV_EXTRACT: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_EXTRACTVAL as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(4)]; +const ABBREV_LOAD: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_LOAD as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5), AbbrevOp::Literal(3), AbbrevOp::Literal(0)]; +const ABBREV_STORE: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_STORE as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5), AbbrevOp::Literal(3), AbbrevOp::Literal(0)]; +const ABBREV_BR: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BR as u64), AbbrevOp::Vbr(6)]; +const ABBREV_CONDBR: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BR as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5)]; +const ABBREV_CALL: &[AbbrevOp] = &[ + AbbrevOp::Literal(FUNC_CODE_INST_CALL as u64), + AbbrevOp::Literal(0), + AbbrevOp::Literal(1 << 15), + AbbrevOp::Vbr(5), + AbbrevOp::Vbr(6), + AbbrevOp::ArrayVbr(5), +]; +const ABBREV_PHI: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_PHI as u64), AbbrevOp::Vbr(5), AbbrevOp::ArrayVbr(6)]; +const ABBREV_GEP: &[AbbrevOp] = &[ + AbbrevOp::Literal(FUNC_CODE_INST_GEP as u64), + AbbrevOp::Literal(1), + AbbrevOp::Vbr(5), + AbbrevOp::Vbr(5), + AbbrevOp::ArrayVbr(5), +]; + +struct FuncAbbrevs { + binop: u32, + cast: u32, + cmp2: u32, + vselect: u32, + extract: u32, + load: u32, + store: u32, + br: u32, + condbr: u32, + call: u32, + phi: u32, + gep: u32, +} + +impl FuncAbbrevs { + fn define(w: &mut BitWriter) -> Self { + Self { + binop: w.define_abbrev(ABBREV_BINOP), + cast: w.define_abbrev(ABBREV_CAST), + cmp2: w.define_abbrev(ABBREV_CMP2), + vselect: w.define_abbrev(ABBREV_VSELECT), + extract: w.define_abbrev(ABBREV_EXTRACT), + load: w.define_abbrev(ABBREV_LOAD), + store: w.define_abbrev(ABBREV_STORE), + br: w.define_abbrev(ABBREV_BR), + condbr: w.define_abbrev(ABBREV_CONDBR), + call: w.define_abbrev(ABBREV_CALL), + phi: w.define_abbrev(ABBREV_PHI), + gep: w.define_abbrev(ABBREV_GEP), + } + } +} + // ------------------------------------------------------- introspection /// What an instruction is, for analyses over the built function (e.g. the @@ -1628,25 +1739,14 @@ mod tests { } fn symtab_names(bc: &[u8]) -> Vec { - assert!(bc.starts_with(&[b'B', b'C', 0xC0, 0xDE])); - let (mut bit, mut w, mut blk, mut stack, mut out) = (32usize, 2u32, 0u32, Vec::new(), Vec::new()); - let bits = |bit: &mut usize, n: u32| (0..n).fold(0u64, |v, k| { let b = (bc[*bit / 8] >> (*bit % 8)) & 1; *bit += 1; v | ((b as u64) << k) }); - let vbr = |bit: &mut usize, n: u32| { - let (mut o, mut s, hi) = (0u64, 0u32, 1u64 << (n - 1)); - loop { let c = bits(bit, n); o |= (c & (hi - 1)) << s; if c & hi == 0 { return o; } s += n - 1; } - }; - while bit + w as usize <= bc.len() * 8 { - match bits(&mut bit, w) { - 0 => { bit = (bit + 31) & !31; if let Some((pw, pb)) = stack.pop() { w = pw; blk = pb; } else { break; } } - 1 => { let (id, nw) = (vbr(&mut bit, 8) as u32, vbr(&mut bit, 4) as u32); bit = ((bit + 31) & !31) + 32; stack.push((w, blk)); w = nw; blk = id; } - 3 => { - let (code, n) = (vbr(&mut bit, 6) as u32, vbr(&mut bit, 6) as usize); - let ops: Vec = (0..n).map(|_| vbr(&mut bit, 6)).collect(); - if blk == BLOCK_VALUE_SYMTAB && code == VST_CODE_ENTRY { out.push(String::from_utf8(ops[1..].iter().map(|&x| x as u8).collect()).unwrap()); } - } - other => panic!("unexpected abbrev {other}"), + fn walk(b: &super::super::bitreader_tests::Block, out: &mut Vec) { + if b.id == BLOCK_VALUE_SYMTAB { + out.extend(b.records_with(VST_CODE_ENTRY).iter().map(|ops| String::from_utf8(ops[1..].iter().map(|&x| x as u8).collect()).unwrap())); } + b.blocks.iter().for_each(|c| walk(c, out)); } + let mut out = Vec::new(); + walk(&super::super::bitreader_tests::parse(bc), &mut out); out }