Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
a8569bf
gpu: direct DXIL emitter (bitcode, container, op library, graphics st…
bmjask Nov 24, 2026
cbde110
dxil: encode atomic orderings with bitcode codes (seq_cst = 6, not 7)
bmjask Nov 24, 2026
2815b2a
dxil: derive Int64Ops / Doubles / DoubleExtensions from instruction t…
bmjask Nov 24, 2026
9230fbc
dxil: randomised differential tests of the emitter
bmjask Nov 24, 2026
7c672cd
dxil: validate.rs FFI hardening
bmjask Nov 24, 2026
6b1170b
dxil: mask float constant bits to the type width
bmjask Nov 24, 2026
746f7dd
gpu/dxil: direct RDNA2 -> DXIL translator and XCL_DIRECT_DXIL routing
bmjask Nov 24, 2026
065aef3
docs: direct DXIL main-based port status
bmjask Nov 24, 2026
97d5259
dxil: disk-cache direct DXIL translations under their own identity
bmjask Nov 24, 2026
b45a6c9
dxil: test byte-identical translation across runs and threads
bmjask Nov 24, 2026
86ab4cd
gpu/dxil: lower an instruction under a caller-chosen guard (Lw::inst_…
bmjask Nov 24, 2026
942b6c7
dxil: builder misuse recorded as an error instead of panicking
bmjask Nov 24, 2026
02ec584
dxil: move DXC reference containers to tests/data/dxil
bmjask Nov 24, 2026
3c01233
dxil tests: skip runner draws where wave64 programs cannot run
bmjask Nov 24, 2026
55e9c3b
dxil fuzz: emit atomicrmw sub as add of the negation
bmjask Nov 24, 2026
ac9328f
dxil: emit !llvm.ident like DXC
bmjask Nov 24, 2026
b6239db
dxil validate: skip the validation step with a validator older than 1.8
bmjask Nov 24, 2026
bc93a3a
Merge branch 'dxil/cache-errors' into shaders/direct-dxil-main
bmjask Nov 24, 2026
34acfbf
Recompiler: direct DXIL stages may branch before their exports
Kalmarv Nov 24, 2026
f372cfb
Recompiler: direct DXIL declares waveGetLaneIndex readonly
Kalmarv Nov 24, 2026
469d8b4
Recompiler: direct DXIL translator version 2
Kalmarv Nov 24, 2026
7d24e97
gpu/dxil: write blocks in reverse post-order; Module::replace_all_uses
bmjask Nov 24, 2026
564c72e
Shaders: expose DXIL module IR internals and fix f64 extension scan
Roroca-1 Nov 24, 2026
32facfe
Shaders: add DXIL CFG, PHI, DCE, compaction, and feature-sync passes
Roroca-1 Nov 24, 2026
f3ee243
Shaders: add DXIL InstCombine constant folding and dominator CSE
Roroca-1 Nov 24, 2026
f349ef0
Shaders: run DXIL IR optimization pass in direct translator
Roroca-1 Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 155 additions & 0 deletions crates/xcl/src/gpu/dxil/bitreader_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
//! A test-only reader for the bitstream [`super::bitstream::BitWriter`]
//! produces (unabbreviated records only), used to check record layouts
//! that the validator and disassembler do not distinguish (e.g. atomic
//! ordering codes the LLVM reader maps leniently).

use super::module::{BinOp, Module, RmwOp};

#[derive(Debug, Default)]
pub(super) struct Block {
pub id: u32,
pub records: Vec<(u32, Vec<u64>)>,
pub blocks: Vec<Block>,
}

impl Block {
/// Depth-first search for the first block with `id`.
pub fn find(&self, id: u32) -> Option<&Block> {
if self.id == id {
return Some(self);
}
self.blocks.iter().find_map(|b| b.find(id))
}
pub fn records_with(&self, code: u32) -> Vec<&[u64]> {
self.records.iter().filter(|r| r.0 == code).map(|r| &r.1[..]).collect()
}
}

struct Reader<'a> {
b: &'a [u8],
pos: usize, // bit position
}

impl Reader<'_> {
fn fixed(&mut self, w: u32) -> u64 {
let mut v = 0u64;
for i in 0..w {
let bit = (self.b[self.pos / 8] >> (self.pos % 8)) & 1;
v |= (bit as u64) << i;
self.pos += 1;
}
v
}
fn vbr(&mut self, w: u32) -> u64 {
let hi = 1u64 << (w - 1);
let (mut v, mut shift) = (0u64, 0);
loop {
let c = self.fixed(w);
v |= (c & (hi - 1)) << shift;
shift += w - 1;
if c & hi == 0 {
return v;
}
}
}
fn align32(&mut self) {
self.pos = self.pos.div_ceil(32) * 32;
}
fn block(&mut self, id: u32, width: u32, end_bit: Option<usize>) -> Block {
let mut blk = Block { id, ..Default::default() };
loop {
if end_bit.is_none() && self.pos + width as usize > self.b.len() * 8 {
return blk;
}
match self.fixed(width) {
0 => {
self.align32();
if let Some(e) = end_bit {
assert_eq!(self.pos, e, "block length mismatch for block {id}");
}
return blk;
}
1 => {
let sub = self.vbr(8) as u32;
let w = self.vbr(4) as u32;
self.align32();
let words = self.fixed(32) as usize;
let end = self.pos + words * 32;
blk.blocks.push(self.block(sub, w, Some(end)));
}
3 => {
let code = self.vbr(6) as u32;
let n = self.vbr(6);
let ops = (0..n).map(|_| self.vbr(6)).collect();
blk.records.push((code, ops));
}
a => panic!("unexpected abbreviation id {a}"),
}
}
}
}

/// Parses bitcode (with the `BC\xC0\xDE` magic) into its block tree; the
/// root is a pseudo block with id `u32::MAX`.
pub(super) fn parse(bc: &[u8]) -> Block {
assert_eq!(&bc[..4], b"BC\xC0\xDE");
let mut r = Reader { b: &bc[4..], pos: 0 };
r.block(u32::MAX, 2, None)
}

const BLOCK_FUNCTION: u32 = 12;
const FUNC_CODE_INST_ATOMICRMW: u32 = 38;
const FUNC_CODE_INST_CMPXCHG: u32 = 46;
/// `bitc::ORDERING_SEQCST` (the in-memory `AtomicOrdering` value is 7, the
/// bitcode code is 6).
const ORDERING_SEQCST: u64 = 6;

fn atomic_module() -> Vec<u8> {
let mut m = Module::new();
m.define_entry("main");
let i32 = m.i32();
let arr = m.array(4, i32);
let g = m.global("g", arr, 3, None, false, 4);
let zero = m.i32c(0);
let p = m.gep(g, &[zero, zero]);
let one = m.i32c(1);
let a = m.atomic_rmw(RmwOp::Add, p, one);
let b = m.cmpxchg(p, a, one);
let _ = m.bin(BinOp::Add, a, b);
m.ret();
m.to_bitcode("dxil-ms-dx", "")
}

#[test]
fn reader_round_trips_block_structure() {
let bc = atomic_module();
let root = parse(&bc);
assert!(root.find(8).is_some(), "module block");
assert!(root.find(BLOCK_FUNCTION).is_some(), "function block");
}

#[test]
fn atomics_use_bitcode_ordering_codes() {
let root = parse(&atomic_module());
let f = root.find(BLOCK_FUNCTION).unwrap();
let rmw = f.records_with(FUNC_CODE_INST_ATOMICRMW);
assert_eq!(rmw.len(), 1);
// [ptr, val, op, vol, ordering, synchscope]
assert_eq!(rmw[0][4], ORDERING_SEQCST, "atomicrmw ordering: {:?}", rmw[0]);
assert_eq!(rmw[0][5], 1, "crossthread synch scope");
let cx = f.records_with(FUNC_CODE_INST_CMPXCHG);
assert_eq!(cx.len(), 1);
// [ptr, cmp, new, vol, success, synchscope, failure, weak]
assert_eq!(cx[0][4], ORDERING_SEQCST, "cmpxchg success ordering: {:?}", cx[0]);
assert_eq!(cx[0][6], ORDERING_SEQCST, "cmpxchg failure ordering: {:?}", cx[0]);
}

#[test]
fn float_constants_ignore_bits_above_their_width() {
let mut m = Module::new();
let (f16, f32) = (m.f16(), m.f32());
let one = m.f32c(1.0f32.to_bits());
assert_eq!(m.const_float(f32, 0xFFFF_0000_0000_0000 | 1.0f32.to_bits() as u64), one);
let h = m.const_float(f16, 0x3C00);
assert_eq!(m.const_float(f16, 0x1_3C00), h);
}
155 changes: 155 additions & 0 deletions crates/xcl/src/gpu/dxil/bitstream.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
//! LLVM bitstream writer: fixed and VBR fields, nested blocks with
//! back-patched lengths, and unabbreviated records.
//!
//! DXIL accepts the plain bitstream container without any abbreviations,
//! which keeps the writer small; size is not a concern for shader modules
//! (the driver re-encodes them anyway).

/// Bit-level writer, little-endian within 32-bit words as LLVM defines.
pub struct BitWriter {
out: Vec<u8>,
acc: u64,
nbits: u32,
/// Open blocks: (byte offset of the length word, outer abbreviation width).
blocks: Vec<(usize, u32)>,
width: u32,
}

/// Abbreviation width used for every block we open (IDs 0..3 need 2 bits).
pub const ABBREV_WIDTH: u32 = 3;

impl Default for BitWriter {
fn default() -> Self {
Self::new()
}
}

impl BitWriter {
pub fn new() -> Self {
BitWriter { out: Vec::new(), acc: 0, nbits: 0, blocks: Vec::new(), width: 2 }
}

pub fn emit(&mut self, value: u64, width: u32) {
debug_assert!(width <= 32);
debug_assert!(width == 64 || value >> width == 0, "value {value:#x} does not fit {width} bits");
self.acc |= value << self.nbits;
self.nbits += width;
while self.nbits >= 8 {
self.out.push(self.acc as u8);
self.acc >>= 8;
self.nbits -= 8;
}
}

pub fn vbr(&mut self, mut value: u64, width: u32) {
let hi = 1u64 << (width - 1);
while value >= hi {
self.emit((value & (hi - 1)) | hi, width);
value >>= width - 1;
}
self.emit(value, width);
}

pub fn align32(&mut self) {
if self.nbits > 0 {
self.emit(0, 8 - self.nbits);
}
while self.out.len() % 4 != 0 {
self.out.push(0);
}
}

pub fn enter_block(&mut self, id: u32) {
self.emit(1, self.width); // ENTER_SUBBLOCK
self.vbr(id as u64, 8);
self.vbr(ABBREV_WIDTH as u64, 4);
self.align32();
let at = self.out.len();
self.out.extend_from_slice(&[0; 4]);
self.blocks.push((at, self.width));
self.width = ABBREV_WIDTH;
}

pub fn end_block(&mut self) {
self.emit(0, self.width); // END_BLOCK
self.align32();
let (at, outer) = self.blocks.pop().expect("end_block without enter_block");
let words = ((self.out.len() - at - 4) / 4) as u32;
self.out[at..at + 4].copy_from_slice(&words.to_le_bytes());
self.width = outer;
}

/// An unabbreviated record.
pub fn record(&mut self, code: u32, ops: &[u64]) {
self.emit(3, self.width); // UNABBREV_RECORD
self.vbr(code as u64, 6);
self.vbr(ops.len() as u64, 6);
for &op in ops {
self.vbr(op, 6);
}
}

/// A record whose operands are the bytes of a string.
pub fn record_str(&mut self, code: u32, prefix: &[u64], s: &str) {
let mut ops = prefix.to_vec();
ops.extend(s.bytes().map(u64::from));
self.record(code, &ops);
}

pub fn finish(mut self) -> Vec<u8> {
assert!(self.blocks.is_empty(), "unterminated bitstream block");
self.align32();
self.out
}
}

/// LLVM's signed VBR operand encoding: sign in bit 0.
pub fn signed(v: i64) -> u64 {
if v >= 0 {
(v as u64) << 1
} else if v == i64::MIN {
1 // "-0": LLVM's encoding of INT64_MIN
} else {
((v.unsigned_abs()) << 1) | 1
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn vbr_and_fixed_fields_pack_little_endian() {
let mut w = BitWriter::new();
w.emit(0b10, 2);
w.vbr(5, 3); // 0b101 needs continuation in 3-bit VBR: chunks 01|1, 01|0... check value round trip below
w.align32();
let bytes = w.finish();
assert_eq!(bytes.len(), 4);
// Decode back: 2 bits, then VBR3.
let word = u32::from_le_bytes(bytes[..4].try_into().unwrap());
assert_eq!(word & 3, 0b10);
let (c0, c1) = ((word >> 2) & 7, (word >> 5) & 7);
assert_eq!(c0, 0b101); // low 2 bits of 5 = 01, continuation bit set
assert_eq!(c1, 0b001); // remaining 1, no continuation
}

#[test]
fn block_lengths_are_back_patched_in_words() {
let mut w = BitWriter::new();
w.enter_block(8);
w.record(1, &[1]);
w.end_block();
let b = w.finish();
let len = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize;
assert_eq!(b.len(), 8 + len * 4);
}

#[test]
fn signed_vbr_operands() {
assert_eq!(signed(0), 0);
assert_eq!(signed(3), 6);
assert_eq!(signed(-3), 7);
assert_eq!(signed(i64::MIN), 1);
}
}
Loading
Loading