Run Grand Theft Auto VI from first boot into the world
The title now boots through every first-boot and menu screen at its own 30 fps, drawing with translated shaders, with input, sound, saves and loading served; it reaches the world, where the host GPU path still fails (see "Not working yet"). Loader and runtime - Crash reports unwind properly, name C++ throws and host GPU failures, carry the title's last debug lines and are appended to crashes.log. - Thread notices on our own threads, reentrant late DLL loading, exit in the console's order, relaunch on a launch-new-game request. - Offline guard: the title cannot reach the network (sockets, name lookups, WinHTTP, the media source resolver); by-name lookups and loads follow the import rules. - Every runtime area the title calls is served (networking hint, packages, store, saves, display, UI, speech stubs, user, async pool). Saves persist; an update is one rename and survives a kill at any step. - DirectStorage reads for real: shared worker pool, priorities, zlib and BCPack. BCPack is our own decoder; the format's constant tables ship in crates/victory-formats/src/bcpack-tables.bin (the asset policy's one exception, see docs/asset-policy.md). - GameInput from XInput pads and the keyboard, with a keyboard stand-in pad; console timers (1 ms) for the whole process. - Audio: XMA2 decoding on the emulated contexts, Opus on the decoder queues, the DSP interface as a stub; title memory placed below 2^40. - Console texture layouts (sizes, tiling, detiling) and the layout library's imports. GPU - Draws, mesh dispatches and compute dispatches run on the host with shaders translated at first use and cached on disk; descriptor heaps, views, root signatures, barriers and host texture states; rectangle lists; comparison samplers. - Title memory reaches the host through persistent mirrors that copy only pages written since the last copy; shader-written buffers are copied back. - Presentation with frame pacing per event kind; framerate in the window caption. Shaders - DXIL emission for vertex, pixel, compute and mesh programs from the console's native code, with a differential test suite against the PC compile. World set: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539; utility set complete. Build - Debugging aids (debug logs, frame capture, stack dumps, scripted keys, the host debug layer, the software adapter) exist only with the `diagnostics` feature; `[profile.diag]` keeps that build apart. Not working yet - In the world the host device is removed within seconds (descriptor handling fixes are in, unproven by a surviving run) and frames present black. - 64-bit image atomics, merged geometry stages and the BVH builder's own shaders do not translate; reverb is silent. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
bc3070991a
commit
2849477415
107 files changed
+42526
-868
No files matched your search
@@ -0,0 +1,986 @@
|
||||
//! A DXIL module and its LLVM 3.7 bitcode, written with unabbreviated
|
||||
//! records only (the format DXIL fixes; codes from LLVM's `LLVMBitCodes.h`).
|
||||
//!
|
||||
//! Values are symbolic while the module is built ([`V`]) and numbered when
|
||||
//! it is written: functions, then constants (all at module level), then the
|
||||
//! instructions of `main` in block order.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub(crate) struct Ty(u32);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
enum TypeDef {
|
||||
Void,
|
||||
Int(u32),
|
||||
Float,
|
||||
/// Pointee and address space.
|
||||
Ptr(Ty, u32),
|
||||
Struct(Option<String>, Vec<Ty>),
|
||||
Array(u32, Ty),
|
||||
Func(Ty, Vec<Ty>),
|
||||
}
|
||||
|
||||
/// A value: a global variable, a function, a module constant, or an
|
||||
/// instruction result.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub(crate) enum V {
|
||||
Global(u32),
|
||||
Func(u32),
|
||||
Const(u32),
|
||||
Inst(u32),
|
||||
}
|
||||
|
||||
/// A global variable declaration (thread-group shared memory).
|
||||
struct Global {
|
||||
name: String,
|
||||
ty: Ty,
|
||||
/// Its pointer type.
|
||||
ptr: Ty,
|
||||
space: u32,
|
||||
/// An internal constant with this initialiser (a constant table).
|
||||
init: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
enum Const {
|
||||
Int(i64),
|
||||
Float(u32),
|
||||
Undef,
|
||||
Aggregate(Vec<u32>),
|
||||
}
|
||||
|
||||
/// LLVM binary opcodes (the same codes serve the float forms).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Bin {
|
||||
Add = 0,
|
||||
Sub = 1,
|
||||
Mul = 2,
|
||||
UDiv = 3,
|
||||
SDiv = 4,
|
||||
URem = 5,
|
||||
Shl = 7,
|
||||
LShr = 8,
|
||||
AShr = 9,
|
||||
And = 10,
|
||||
Or = 11,
|
||||
Xor = 12,
|
||||
}
|
||||
|
||||
/// `atomicrmw` operations.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Rmw {
|
||||
Xchg = 0,
|
||||
Add = 1,
|
||||
Sub = 2,
|
||||
And = 3,
|
||||
Or = 5,
|
||||
Xor = 6,
|
||||
Max = 7,
|
||||
Min = 8,
|
||||
UMax = 9,
|
||||
UMin = 10,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Cast {
|
||||
Trunc = 0,
|
||||
ZExt = 1,
|
||||
SExt = 2,
|
||||
FpToUi = 3,
|
||||
FpToSi = 4,
|
||||
UiToFp = 5,
|
||||
SiToFp = 6,
|
||||
Bitcast = 11,
|
||||
}
|
||||
|
||||
/// Compare predicates: floats 0-15, integers 32-41.
|
||||
pub(crate) mod pred {
|
||||
pub const FALSE: u8 = 0;
|
||||
pub const OEQ: u8 = 1;
|
||||
pub const OGT: u8 = 2;
|
||||
pub const OGE: u8 = 3;
|
||||
pub const OLT: u8 = 4;
|
||||
pub const OLE: u8 = 5;
|
||||
pub const ONE: u8 = 6;
|
||||
pub const ORD: u8 = 7;
|
||||
pub const UNO: u8 = 8;
|
||||
pub const UEQ: u8 = 9;
|
||||
pub const UGT: u8 = 10;
|
||||
pub const UGE: u8 = 11;
|
||||
pub const ULT: u8 = 12;
|
||||
pub const ULE: u8 = 13;
|
||||
pub const UNE: u8 = 14;
|
||||
pub const TRUE: u8 = 15;
|
||||
pub const EQ: u8 = 32;
|
||||
pub const NE: u8 = 33;
|
||||
pub const IUGT: u8 = 34;
|
||||
pub const IUGE: u8 = 35;
|
||||
pub const IULT: u8 = 36;
|
||||
pub const IULE: u8 = 37;
|
||||
pub const SGT: u8 = 38;
|
||||
pub const SGE: u8 = 39;
|
||||
pub const SLT: u8 = 40;
|
||||
pub const SLE: u8 = 41;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum Op {
|
||||
Bin(Bin, V, V),
|
||||
Cast(Cast, V),
|
||||
Cmp(u8, V, V),
|
||||
Select(V, V, V),
|
||||
Extract(V, u32),
|
||||
Call(u32, Vec<V>),
|
||||
/// Filled in later: (value, block).
|
||||
Phi(Vec<(V, usize)>),
|
||||
/// `getelementptr` over the pointee type, from a pointer.
|
||||
Gep(Ty, V, Vec<V>),
|
||||
Load(V),
|
||||
/// Pointer, value.
|
||||
Store(V, V),
|
||||
AtomicRmw(Rmw, V, V),
|
||||
/// Pointer, expected, new; returns `{i32, i1}`.
|
||||
CmpXchg(V, V, V),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Inst {
|
||||
ty: Ty,
|
||||
op: Op,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum Term {
|
||||
Br(usize),
|
||||
CondBr(V, usize, usize),
|
||||
Ret,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct Block {
|
||||
phis: Vec<u32>,
|
||||
body: Vec<u32>,
|
||||
term: Option<Term>,
|
||||
}
|
||||
|
||||
/// Function attributes of a `dx.op` declaration.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Attr {
|
||||
ReadNone = 1,
|
||||
NoUnwind = 2,
|
||||
ReadOnly = 3,
|
||||
/// Barriers.
|
||||
NoDuplicate = 4,
|
||||
}
|
||||
|
||||
struct Func {
|
||||
name: String,
|
||||
ty: Ty,
|
||||
attr: Option<Attr>,
|
||||
body: bool,
|
||||
}
|
||||
|
||||
/// A metadata node operand.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct Md(u32);
|
||||
|
||||
enum MdDef {
|
||||
Str(String),
|
||||
Value(Ty, V),
|
||||
Node(Vec<Option<Md>>),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Module {
|
||||
types: Vec<TypeDef>,
|
||||
type_ids: HashMap<TypeDef, u32>,
|
||||
consts: Vec<(Ty, Const)>,
|
||||
const_ids: HashMap<(Ty, Const), u32>,
|
||||
globals: Vec<Global>,
|
||||
funcs: Vec<Func>,
|
||||
func_ids: HashMap<String, u32>,
|
||||
insts: Vec<Inst>,
|
||||
blocks: Vec<Block>,
|
||||
mds: Vec<MdDef>,
|
||||
named: Vec<(String, Vec<Md>)>,
|
||||
}
|
||||
|
||||
impl Module {
|
||||
fn ty(&mut self, def: TypeDef) -> Ty {
|
||||
if let Some(&t) = self.type_ids.get(&def) {
|
||||
return Ty(t);
|
||||
}
|
||||
let t = self.types.len() as u32;
|
||||
self.types.push(def.clone());
|
||||
self.type_ids.insert(def, t);
|
||||
Ty(t)
|
||||
}
|
||||
|
||||
pub fn void(&mut self) -> Ty {
|
||||
self.ty(TypeDef::Void)
|
||||
}
|
||||
pub fn int(&mut self, bits: u32) -> Ty {
|
||||
self.ty(TypeDef::Int(bits))
|
||||
}
|
||||
pub fn float(&mut self) -> Ty {
|
||||
self.ty(TypeDef::Float)
|
||||
}
|
||||
pub fn ptr(&mut self, to: Ty) -> Ty {
|
||||
self.ty(TypeDef::Ptr(to, 0))
|
||||
}
|
||||
pub fn ptr_in(&mut self, to: Ty, space: u32) -> Ty {
|
||||
self.ty(TypeDef::Ptr(to, space))
|
||||
}
|
||||
pub fn array(&mut self, n: u32, of: Ty) -> Ty {
|
||||
self.ty(TypeDef::Array(n, of))
|
||||
}
|
||||
pub fn named_struct(&mut self, name: &str, fields: Vec<Ty>) -> Ty {
|
||||
self.ty(TypeDef::Struct(Some(name.into()), fields))
|
||||
}
|
||||
pub fn func_ty(&mut self, ret: Ty, params: Vec<Ty>) -> Ty {
|
||||
self.ty(TypeDef::Func(ret, params))
|
||||
}
|
||||
|
||||
fn is_void(&self, t: Ty) -> bool {
|
||||
self.types[t.0 as usize] == TypeDef::Void
|
||||
}
|
||||
|
||||
fn constant(&mut self, ty: Ty, c: Const) -> V {
|
||||
if let Some(&i) = self.const_ids.get(&(ty, c.clone())) {
|
||||
return V::Const(i);
|
||||
}
|
||||
let i = self.consts.len() as u32;
|
||||
self.consts.push((ty, c.clone()));
|
||||
self.const_ids.insert((ty, c), i);
|
||||
V::Const(i)
|
||||
}
|
||||
|
||||
pub fn int_const(&mut self, ty: Ty, v: i64) -> V {
|
||||
self.constant(ty, Const::Int(v))
|
||||
}
|
||||
pub fn i32(&mut self, v: u32) -> V {
|
||||
let t = self.int(32);
|
||||
self.int_const(t, i64::from(v as i32))
|
||||
}
|
||||
pub fn i8(&mut self, v: u8) -> V {
|
||||
let t = self.int(8);
|
||||
self.int_const(t, i64::from(v as i8))
|
||||
}
|
||||
pub fn bool(&mut self, v: bool) -> V {
|
||||
let t = self.int(1);
|
||||
self.int_const(t, -i64::from(v))
|
||||
}
|
||||
pub fn f32(&mut self, bits: u32) -> V {
|
||||
let t = self.float();
|
||||
self.constant(t, Const::Float(bits))
|
||||
}
|
||||
pub fn undef(&mut self, ty: Ty) -> V {
|
||||
self.constant(ty, Const::Undef)
|
||||
}
|
||||
/// A constant struct or array of constants.
|
||||
pub fn aggregate(&mut self, ty: Ty, fields: &[V]) -> V {
|
||||
let ids = fields
|
||||
.iter()
|
||||
.map(|f| match f {
|
||||
V::Const(i) => *i,
|
||||
_ => panic!("aggregate of a non-constant"),
|
||||
})
|
||||
.collect();
|
||||
self.constant(ty, Const::Aggregate(ids))
|
||||
}
|
||||
|
||||
/// Gives constant `old` the content of `new` (both stay valid).
|
||||
pub fn replace_const(&mut self, old: V, new: V) {
|
||||
if let (V::Const(o), V::Const(n)) = (old, new) {
|
||||
self.consts[o as usize] = self.consts[n as usize].clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// A function declaration (or `main` with `body`), found by name.
|
||||
pub fn function(&mut self, name: &str, ty: Ty, attr: Option<Attr>, body: bool) -> V {
|
||||
if let Some(&i) = self.func_ids.get(name) {
|
||||
return V::Func(i);
|
||||
}
|
||||
let i = self.funcs.len() as u32;
|
||||
self.funcs.push(Func {
|
||||
name: name.into(),
|
||||
ty,
|
||||
attr,
|
||||
body,
|
||||
});
|
||||
self.func_ids.insert(name.into(), i);
|
||||
V::Func(i)
|
||||
}
|
||||
|
||||
/// An external global of type `ty` in address space `space` (DXIL
|
||||
/// declares thread-group shared memory this way).
|
||||
pub fn global(&mut self, name: &str, ty: Ty, space: u32) -> V {
|
||||
let ptr = self.ptr_in(ty, space);
|
||||
self.globals.push(Global {
|
||||
name: name.into(),
|
||||
ty,
|
||||
ptr,
|
||||
space,
|
||||
init: None,
|
||||
});
|
||||
V::Global(self.globals.len() as u32 - 1)
|
||||
}
|
||||
|
||||
/// An internal constant global initialised with the constant `init`.
|
||||
pub fn constant_global(&mut self, name: &str, init: V) -> V {
|
||||
let V::Const(i) = init else {
|
||||
panic!("a global initialised with a non-constant")
|
||||
};
|
||||
let ty = self.consts[i as usize].0;
|
||||
let g = self.global(name, ty, 0);
|
||||
if let V::Global(n) = g {
|
||||
self.globals[n as usize].init = Some(i);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
pub fn new_block(&mut self) -> usize {
|
||||
self.blocks.push(Block::default());
|
||||
self.blocks.len() - 1
|
||||
}
|
||||
|
||||
pub fn type_of(&self, v: V) -> Ty {
|
||||
match v {
|
||||
V::Global(i) => self.globals[i as usize].ptr,
|
||||
V::Const(i) => self.consts[i as usize].0,
|
||||
V::Inst(i) => self.insts[i as usize].ty,
|
||||
V::Func(i) => {
|
||||
let t = self.funcs[i as usize].ty;
|
||||
*self
|
||||
.type_ids
|
||||
.get(&TypeDef::Ptr(t, 0))
|
||||
.map(|t| Ty(*t))
|
||||
.as_ref()
|
||||
.expect("function pointer type")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, block: usize, ty: Ty, op: Op) -> V {
|
||||
let i = self.insts.len() as u32;
|
||||
self.insts.push(Inst { ty, op });
|
||||
// Terminators are kept apart, so a block can still grow at its end.
|
||||
self.blocks[block].body.push(i);
|
||||
V::Inst(i)
|
||||
}
|
||||
|
||||
pub fn bin(&mut self, block: usize, op: Bin, a: V, b: V) -> V {
|
||||
let ty = self.type_of(a);
|
||||
self.push(block, ty, Op::Bin(op, a, b))
|
||||
}
|
||||
pub fn cast(&mut self, block: usize, op: Cast, v: V, to: Ty) -> V {
|
||||
self.push(block, to, Op::Cast(op, v))
|
||||
}
|
||||
pub fn cmp(&mut self, block: usize, pred: u8, a: V, b: V) -> V {
|
||||
let t = self.int(1);
|
||||
self.push(block, t, Op::Cmp(pred, a, b))
|
||||
}
|
||||
pub fn select(&mut self, block: usize, c: V, t: V, f: V) -> V {
|
||||
let ty = self.type_of(t);
|
||||
self.push(block, ty, Op::Select(c, t, f))
|
||||
}
|
||||
pub fn extract(&mut self, block: usize, agg: V, index: u32) -> V {
|
||||
let ty = match &self.types[self.type_of(agg).0 as usize] {
|
||||
TypeDef::Struct(_, f) => f[index as usize],
|
||||
TypeDef::Array(_, t) => *t,
|
||||
t => panic!("extractvalue from {t:?}"),
|
||||
};
|
||||
self.push(block, ty, Op::Extract(agg, index))
|
||||
}
|
||||
pub fn call(&mut self, block: usize, f: V, args: Vec<V>) -> V {
|
||||
let V::Func(i) = f else {
|
||||
panic!("call of a non-function")
|
||||
};
|
||||
let TypeDef::Func(ret, _) = self.types[self.funcs[i as usize].ty.0 as usize] else {
|
||||
unreachable!()
|
||||
};
|
||||
self.push(block, ret, Op::Call(i, args))
|
||||
}
|
||||
/// A phi at the top of `block`; incoming values come with [`Module::set_phi`].
|
||||
pub fn phi(&mut self, block: usize, ty: Ty) -> V {
|
||||
let i = self.insts.len() as u32;
|
||||
self.insts.push(Inst {
|
||||
ty,
|
||||
op: Op::Phi(Vec::new()),
|
||||
});
|
||||
self.blocks[block].phis.push(i);
|
||||
V::Inst(i)
|
||||
}
|
||||
/// The address of element `index` of the array `ptr` points to.
|
||||
pub fn element(&mut self, block: usize, ptr: V, index: V) -> V {
|
||||
let TypeDef::Ptr(arr, space) = self.types[self.type_of(ptr).0 as usize] else {
|
||||
panic!("element of a non-pointer")
|
||||
};
|
||||
let TypeDef::Array(_, elem) = self.types[arr.0 as usize] else {
|
||||
panic!("element of a non-array")
|
||||
};
|
||||
let ty = self.ptr_in(elem, space);
|
||||
let zero = self.i32(0);
|
||||
self.push(block, ty, Op::Gep(arr, ptr, vec![zero, index]))
|
||||
}
|
||||
pub fn load(&mut self, block: usize, ptr: V) -> V {
|
||||
let TypeDef::Ptr(ty, _) = self.types[self.type_of(ptr).0 as usize] else {
|
||||
panic!("load from a non-pointer")
|
||||
};
|
||||
self.push(block, ty, Op::Load(ptr))
|
||||
}
|
||||
pub fn store(&mut self, block: usize, ptr: V, value: V) {
|
||||
let void = self.void();
|
||||
self.push(block, void, Op::Store(ptr, value));
|
||||
}
|
||||
pub fn atomic(&mut self, block: usize, op: Rmw, ptr: V, value: V) -> V {
|
||||
let ty = self.type_of(value);
|
||||
self.push(block, ty, Op::AtomicRmw(op, ptr, value))
|
||||
}
|
||||
/// The old value of a compare-exchange.
|
||||
pub fn cmpxchg(&mut self, block: usize, ptr: V, expected: V, new: V) -> V {
|
||||
let (i32t, i1) = (self.type_of(new), self.int(1));
|
||||
let pair = self.ty(TypeDef::Struct(None, vec![i32t, i1]));
|
||||
let r = self.push(block, pair, Op::CmpXchg(ptr, expected, new));
|
||||
self.extract(block, r, 0)
|
||||
}
|
||||
|
||||
pub fn set_phi(&mut self, phi: V, incoming: Vec<(V, usize)>) {
|
||||
let V::Inst(i) = phi else { panic!() };
|
||||
self.insts[i as usize].op = Op::Phi(incoming);
|
||||
}
|
||||
pub fn terminate(&mut self, block: usize, t: Term) {
|
||||
self.blocks[block].term = Some(t);
|
||||
}
|
||||
|
||||
pub fn md_str(&mut self, s: &str) -> Md {
|
||||
self.mds.push(MdDef::Str(s.into()));
|
||||
Md(self.mds.len() as u32 - 1)
|
||||
}
|
||||
pub fn md_value(&mut self, v: V) -> Md {
|
||||
let ty = self.type_of(v);
|
||||
self.mds.push(MdDef::Value(ty, v));
|
||||
Md(self.mds.len() as u32 - 1)
|
||||
}
|
||||
pub fn md_node(&mut self, ops: Vec<Option<Md>>) -> Md {
|
||||
self.mds.push(MdDef::Node(ops));
|
||||
Md(self.mds.len() as u32 - 1)
|
||||
}
|
||||
pub fn named_md(&mut self, name: &str, nodes: Vec<Md>) {
|
||||
self.named.push((name.into(), nodes));
|
||||
}
|
||||
|
||||
/// The module as bitcode.
|
||||
pub fn write(&self) -> Vec<u8> {
|
||||
let mut w = Writer::default();
|
||||
w.bytes(b"BC\xC0\xDE");
|
||||
w.enter(MODULE_BLOCK, 3);
|
||||
w.record(1, &[1]); // VERSION: relative value ids
|
||||
|
||||
// Attribute groups 1-4 and one list per group.
|
||||
w.enter(PARAMATTR_GROUP_BLOCK, 3);
|
||||
for (id, kinds) in [
|
||||
(1, &[18u64, 20][..]),
|
||||
(2, &[18]),
|
||||
(3, &[18, 21]),
|
||||
(4, &[12, 18]),
|
||||
] {
|
||||
let mut r = vec![id, 0xFFFF_FFFF];
|
||||
for &k in kinds {
|
||||
r.extend([0, k]);
|
||||
}
|
||||
w.record(3, &r);
|
||||
}
|
||||
w.exit();
|
||||
w.enter(PARAMATTR_BLOCK, 3);
|
||||
for id in 1..=4 {
|
||||
w.record(2, &[id]);
|
||||
}
|
||||
w.exit();
|
||||
|
||||
w.enter(TYPE_BLOCK, 4);
|
||||
w.record(1, &[self.types.len() as u64]);
|
||||
for t in &self.types {
|
||||
match t {
|
||||
TypeDef::Void => w.record(2, &[]),
|
||||
TypeDef::Float => w.record(3, &[]),
|
||||
TypeDef::Int(b) => w.record(7, &[u64::from(*b)]),
|
||||
TypeDef::Ptr(p, space) => w.record(8, &[u64::from(p.0), u64::from(*space)]),
|
||||
TypeDef::Array(n, e) => w.record(11, &[u64::from(*n), u64::from(e.0)]),
|
||||
TypeDef::Struct(name, fields) => {
|
||||
let mut r = vec![0];
|
||||
r.extend(fields.iter().map(|f| u64::from(f.0)));
|
||||
match name {
|
||||
Some(n) => {
|
||||
w.record(19, &chars(n));
|
||||
w.record(20, &r);
|
||||
}
|
||||
None => w.record(18, &r),
|
||||
}
|
||||
}
|
||||
TypeDef::Func(ret, params) => {
|
||||
let mut r = vec![0, u64::from(ret.0)];
|
||||
r.extend(params.iter().map(|p| u64::from(p.0)));
|
||||
w.record(21, &r);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.exit();
|
||||
|
||||
w.record(2, &chars("dxil-ms-dx"));
|
||||
w.record(
|
||||
3,
|
||||
&chars(
|
||||
"e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64",
|
||||
),
|
||||
);
|
||||
let first_const = (self.globals.len() + self.funcs.len()) as u64;
|
||||
for g in &self.globals {
|
||||
// [type, address space << 2 | explicit type | constant, init id
|
||||
// + 1, linkage (external 0, internal 3), log2 alignment + 1,
|
||||
// section]
|
||||
let (constant, init, linkage) = match g.init {
|
||||
Some(i) => (1, first_const + u64::from(i) + 1, 3),
|
||||
None => (0, 0, 0),
|
||||
};
|
||||
w.record(
|
||||
7,
|
||||
&[
|
||||
u64::from(g.ty.0),
|
||||
u64::from(g.space) << 2 | 2 | constant,
|
||||
init,
|
||||
linkage,
|
||||
3,
|
||||
0,
|
||||
],
|
||||
);
|
||||
}
|
||||
for f in &self.funcs {
|
||||
// [type, cc, isproto, linkage, paramattr, align, section,
|
||||
// visibility, gc, unnamed_addr, prologue, dllstorage, comdat, prefix]
|
||||
let attr = f.attr.map_or(0, |a| a as u64);
|
||||
w.record(
|
||||
8,
|
||||
&[
|
||||
u64::from(f.ty.0),
|
||||
0,
|
||||
u64::from(!f.body),
|
||||
0,
|
||||
attr,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Value ids: globals, functions, constants, instructions.
|
||||
let globals = self.globals.len() as u32;
|
||||
let funcs = globals + self.funcs.len() as u32;
|
||||
let const_id = |i: u32| u64::from(funcs + i);
|
||||
w.enter(CONSTANTS_BLOCK, 4);
|
||||
let mut current = None;
|
||||
for (ty, c) in &self.consts {
|
||||
if current != Some(*ty) {
|
||||
w.record(1, &[u64::from(ty.0)]);
|
||||
current = Some(*ty);
|
||||
}
|
||||
match c {
|
||||
Const::Undef => w.record(3, &[]),
|
||||
Const::Int(v) => w.record(4, &[signed(*v)]),
|
||||
Const::Float(bits) => w.record(6, &[u64::from(*bits)]),
|
||||
Const::Aggregate(ids) => {
|
||||
let r: Vec<u64> = ids.iter().map(|&i| const_id(i)).collect();
|
||||
w.record(7, &r);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.exit();
|
||||
|
||||
// Phis nothing reads are left out (one register per phi makes many).
|
||||
let mut live = vec![false; self.insts.len()];
|
||||
let mark = |live: &mut Vec<bool>, v: V| {
|
||||
if let V::Inst(i) = v
|
||||
&& !live[i as usize]
|
||||
{
|
||||
live[i as usize] = true;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
};
|
||||
let operands = |op: &Op| -> Vec<V> {
|
||||
match op {
|
||||
Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => {
|
||||
vec![*a, *b]
|
||||
}
|
||||
Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => vec![*v],
|
||||
Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => vec![*a, *b, *c],
|
||||
Op::Call(_, args) => args.clone(),
|
||||
Op::Phi(inc) => inc.iter().map(|x| x.0).collect(),
|
||||
Op::Gep(_, p, idx) => std::iter::once(*p).chain(idx.iter().copied()).collect(),
|
||||
}
|
||||
};
|
||||
for b in &self.blocks {
|
||||
for &i in &b.body {
|
||||
live[i as usize] = true;
|
||||
}
|
||||
if let Some(Term::CondBr(c, ..)) = b.term {
|
||||
mark(&mut live, c);
|
||||
}
|
||||
}
|
||||
let mut changed = true;
|
||||
while changed {
|
||||
changed = false;
|
||||
for (i, inst) in self.insts.iter().enumerate() {
|
||||
if live[i] {
|
||||
for v in operands(&inst.op) {
|
||||
changed |= mark(&mut live, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Blocks are laid out in reverse postorder, so every block follows
|
||||
// its forward predecessors (drivers take a branch to an earlier
|
||||
// block for a loop's back edge).
|
||||
let succs = |b: usize| match self.blocks[b].term {
|
||||
Some(Term::Br(t)) => vec![t],
|
||||
Some(Term::CondBr(_, t, f)) => vec![t, f],
|
||||
_ => vec![],
|
||||
};
|
||||
let mut seen = vec![false; self.blocks.len()];
|
||||
let mut post = Vec::new();
|
||||
let mut stack = vec![(0usize, 0usize)];
|
||||
seen[0] = true;
|
||||
while let Some(top) = stack.last_mut() {
|
||||
let (b, k) = *top;
|
||||
top.1 += 1;
|
||||
match succs(b).get(k) {
|
||||
Some(&s) if !seen[s] => {
|
||||
seen[s] = true;
|
||||
stack.push((s, 0));
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
post.push(b);
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
post.reverse();
|
||||
let mut pos = vec![u64::MAX; self.blocks.len()];
|
||||
for (n, &b) in post.iter().enumerate() {
|
||||
pos[b] = n as u64;
|
||||
}
|
||||
// An empty latch (only a branch back to its loop header) is folded
|
||||
// into its one predecessor, so the exiting block is the latch as in
|
||||
// DXC's loops; the AMD driver hangs on divergent loops otherwise.
|
||||
let mut preds = vec![Vec::new(); self.blocks.len()];
|
||||
for &b in &post {
|
||||
for s in succs(b) {
|
||||
preds[s].push(b);
|
||||
}
|
||||
}
|
||||
let mut fold = vec![None; self.blocks.len()];
|
||||
for &b in &post {
|
||||
let blk = &self.blocks[b];
|
||||
if let (Some(Term::Br(h)), true, [p]) = (
|
||||
blk.term,
|
||||
blk.phis.is_empty() && blk.body.is_empty(),
|
||||
&preds[b][..],
|
||||
) && pos[h] < pos[b]
|
||||
&& !succs(*p).contains(&h)
|
||||
{
|
||||
fold[b] = Some((*p, h));
|
||||
}
|
||||
}
|
||||
let layout: Vec<usize> = post.into_iter().filter(|&b| fold[b].is_none()).collect();
|
||||
let mut pos = vec![u64::MAX; self.blocks.len()];
|
||||
for (n, &b) in layout.iter().enumerate() {
|
||||
pos[b] = n as u64;
|
||||
}
|
||||
// Branch targets and phi blocks through folded latches.
|
||||
let target = |t: usize| fold[t].map_or(pos[t], |(_, h)| pos[h]);
|
||||
let from = |b: usize| fold[b].map_or(pos[b], |(p, _)| pos[p]);
|
||||
|
||||
// Instruction value ids, in layout order.
|
||||
let base = funcs + self.consts.len() as u32;
|
||||
let mut ids = vec![u32::MAX; self.insts.len()];
|
||||
let mut next = base;
|
||||
for b in layout.iter().map(|&b| &self.blocks[b]) {
|
||||
for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) {
|
||||
if !self.is_void(self.insts[i as usize].ty) {
|
||||
ids[i as usize] = next;
|
||||
next += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let abs = |v: V| -> u32 {
|
||||
match v {
|
||||
V::Global(i) => i,
|
||||
V::Func(i) => globals + i,
|
||||
V::Const(i) => funcs + i,
|
||||
V::Inst(i) => {
|
||||
let id = ids[i as usize];
|
||||
assert_ne!(id, u32::MAX, "use of a void value");
|
||||
id
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
w.enter(METADATA_BLOCK, 3);
|
||||
for m in &self.mds {
|
||||
match m {
|
||||
MdDef::Str(s) => w.record(1, &chars(s)),
|
||||
MdDef::Value(ty, v) => w.record(2, &[u64::from(ty.0), u64::from(abs(*v))]),
|
||||
MdDef::Node(ops) => {
|
||||
let r: Vec<u64> = ops
|
||||
.iter()
|
||||
.map(|o| o.map_or(0, |m| u64::from(m.0) + 1))
|
||||
.collect();
|
||||
w.record(3, &r);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, nodes) in &self.named {
|
||||
w.record(4, &chars(name));
|
||||
let r: Vec<u64> = nodes.iter().map(|m| u64::from(m.0)).collect();
|
||||
w.record(10, &r);
|
||||
}
|
||||
w.exit();
|
||||
// The metadata kinds an LLVM 3.7 module declares, as DXC writes them.
|
||||
w.enter(METADATA_BLOCK, 3);
|
||||
for (id, kind) in [
|
||||
"dbg",
|
||||
"tbaa",
|
||||
"prof",
|
||||
"fpmath",
|
||||
"range",
|
||||
"tbaa.struct",
|
||||
"invariant.load",
|
||||
"alias.scope",
|
||||
"noalias",
|
||||
"nontemporal",
|
||||
"llvm.mem.parallel_loop_access",
|
||||
"nonnull",
|
||||
"dereferenceable",
|
||||
"dereferenceable_or_null",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let mut r = vec![id as u64];
|
||||
r.extend(chars(kind));
|
||||
w.record(6, &r);
|
||||
}
|
||||
w.exit();
|
||||
|
||||
w.enter(VALUE_SYMTAB_BLOCK, 4);
|
||||
let names = self.globals.iter().map(|g| &g.name);
|
||||
for (i, name) in names.chain(self.funcs.iter().map(|f| &f.name)).enumerate() {
|
||||
let mut r = vec![i as u64];
|
||||
r.extend(chars(name));
|
||||
w.record(1, &r);
|
||||
}
|
||||
w.exit();
|
||||
|
||||
w.enter(FUNCTION_BLOCK, 4);
|
||||
w.record(1, &[layout.len() as u64]);
|
||||
let mut inst_id = base;
|
||||
for b in layout.iter().map(|&b| &self.blocks[b]) {
|
||||
for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) {
|
||||
let inst = &self.insts[i as usize];
|
||||
let rel = |v: V| {
|
||||
let a = abs(v);
|
||||
assert!(a < inst_id, "forward reference outside a phi");
|
||||
u64::from(inst_id - a)
|
||||
};
|
||||
match &inst.op {
|
||||
Op::Bin(op, a, b) => w.record(2, &[rel(*a), rel(*b), *op as u64]),
|
||||
Op::Cast(op, v) => w.record(3, &[rel(*v), u64::from(inst.ty.0), *op as u64]),
|
||||
Op::Cmp(p, a, b) => w.record(28, &[rel(*a), rel(*b), u64::from(*p)]),
|
||||
Op::Select(c, t, f) => w.record(29, &[rel(*t), rel(*f), rel(*c)]),
|
||||
Op::Extract(a, idx) => w.record(26, &[rel(*a), u64::from(*idx)]),
|
||||
Op::Call(f, args) => {
|
||||
let mut r = vec![0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)];
|
||||
r.push(rel(V::Func(*f)));
|
||||
r.extend(args.iter().map(|&a| rel(a)));
|
||||
w.record(34, &r);
|
||||
}
|
||||
Op::Phi(incoming) => {
|
||||
let mut r = vec![u64::from(inst.ty.0)];
|
||||
for &(v, b) in incoming {
|
||||
r.push(signed(i64::from(inst_id) - i64::from(abs(v))));
|
||||
r.push(from(b));
|
||||
}
|
||||
w.record(16, &r);
|
||||
}
|
||||
Op::Gep(ty, p, idx) => {
|
||||
let mut r = vec![0, u64::from(ty.0), rel(*p)];
|
||||
r.extend(idx.iter().map(|&i| rel(i)));
|
||||
w.record(43, &r);
|
||||
}
|
||||
// Alignment 4 (log2 + 1), not volatile.
|
||||
Op::Load(p) => w.record(20, &[rel(*p), u64::from(inst.ty.0), 3, 0]),
|
||||
Op::Store(p, v) => w.record(44, &[rel(*p), rel(*v), 3, 0]),
|
||||
// Sequentially consistent, across threads.
|
||||
Op::AtomicRmw(op, p, v) => {
|
||||
w.record(38, &[rel(*p), rel(*v), *op as u64, 0, 6, 1])
|
||||
}
|
||||
Op::CmpXchg(p, c, n) => {
|
||||
w.record(46, &[rel(*p), rel(*c), rel(*n), 0, 6, 1, 6, 0]);
|
||||
}
|
||||
}
|
||||
if !self.is_void(inst.ty) {
|
||||
inst_id += 1;
|
||||
}
|
||||
}
|
||||
match b.term.expect("unterminated block") {
|
||||
Term::Ret => w.record(10, &[]),
|
||||
Term::Br(t) => w.record(11, &[target(t)]),
|
||||
Term::CondBr(c, t, f) => {
|
||||
let a = abs(c);
|
||||
assert!(a < inst_id);
|
||||
w.record(11, &[target(t), target(f), u64::from(inst_id - a)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.exit();
|
||||
w.exit();
|
||||
w.finish()
|
||||
}
|
||||
}
|
||||
|
||||
const MODULE_BLOCK: u64 = 8;
|
||||
const PARAMATTR_BLOCK: u64 = 9;
|
||||
const PARAMATTR_GROUP_BLOCK: u64 = 10;
|
||||
const CONSTANTS_BLOCK: u64 = 11;
|
||||
const FUNCTION_BLOCK: u64 = 12;
|
||||
const VALUE_SYMTAB_BLOCK: u64 = 14;
|
||||
const METADATA_BLOCK: u64 = 15;
|
||||
const TYPE_BLOCK: u64 = 17;
|
||||
|
||||
fn chars(s: &str) -> Vec<u64> {
|
||||
s.bytes().map(u64::from).collect()
|
||||
}
|
||||
|
||||
/// LLVM's signed VBR operand: magnitude shifted left, sign in bit 0.
|
||||
fn signed(v: i64) -> u64 {
|
||||
if v >= 0 {
|
||||
(v as u64) << 1
|
||||
} else {
|
||||
(v.unsigned_abs() << 1) | 1
|
||||
}
|
||||
}
|
||||
|
||||
/// The bitstream: little-endian 32-bit words filled from bit 0.
|
||||
#[derive(Default)]
|
||||
struct Writer {
|
||||
words: Vec<u32>,
|
||||
cur: u64,
|
||||
bits: u32,
|
||||
/// Per open block: abbreviation width, index of its length word.
|
||||
stack: Vec<(u32, usize)>,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
fn width(&self) -> u32 {
|
||||
self.stack.last().map_or(2, |b| b.0)
|
||||
}
|
||||
|
||||
fn emit(&mut self, v: u64, width: u32) {
|
||||
debug_assert!(width == 64 || v >> width == 0);
|
||||
self.cur |= v << self.bits;
|
||||
self.bits += width;
|
||||
while self.bits >= 32 {
|
||||
self.words.push(self.cur as u32);
|
||||
self.cur >>= 32;
|
||||
self.bits -= 32;
|
||||
}
|
||||
}
|
||||
|
||||
fn vbr(&mut self, mut v: u64, width: u32) {
|
||||
let hi = 1u64 << (width - 1);
|
||||
while v >= hi {
|
||||
self.emit(v & (hi - 1) | hi, width);
|
||||
v >>= width - 1;
|
||||
}
|
||||
self.emit(v, width);
|
||||
}
|
||||
|
||||
fn align(&mut self) {
|
||||
if self.bits > 0 {
|
||||
self.words.push(self.cur as u32);
|
||||
self.cur = 0;
|
||||
self.bits = 0;
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes(&mut self, b: &[u8]) {
|
||||
for &x in b {
|
||||
self.emit(u64::from(x), 8);
|
||||
}
|
||||
}
|
||||
|
||||
fn enter(&mut self, id: u64, width: u32) {
|
||||
self.emit(1, self.width()); // ENTER_SUBBLOCK
|
||||
self.vbr(id, 8);
|
||||
self.vbr(u64::from(width), 4);
|
||||
self.align();
|
||||
self.words.push(0);
|
||||
self.stack.push((width, self.words.len()));
|
||||
}
|
||||
|
||||
fn exit(&mut self) {
|
||||
self.emit(0, self.width()); // END_BLOCK
|
||||
self.align();
|
||||
let (_, start) = self.stack.pop().expect("open block");
|
||||
self.words[start - 1] = (self.words.len() - start) as u32;
|
||||
}
|
||||
|
||||
/// An unabbreviated record.
|
||||
fn record(&mut self, code: u64, ops: &[u64]) {
|
||||
self.emit(3, self.width());
|
||||
self.vbr(code, 6);
|
||||
self.vbr(ops.len() as u64, 6);
|
||||
for &o in ops {
|
||||
self.vbr(o, 6);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Vec<u8> {
|
||||
self.align();
|
||||
self.words.iter().flat_map(|w| w.to_le_bytes()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn vbr_and_blocks() {
|
||||
let mut w = Writer::default();
|
||||
w.vbr(5, 6);
|
||||
w.vbr(100, 6); // two chunks: 100 = 0b1100100 -> 0b100100 | 32, then 3
|
||||
assert_eq!(w.cur, 5 | (0b10_0100 << 6) | (3 << 12));
|
||||
let mut w = Writer::default();
|
||||
w.enter(8, 3);
|
||||
w.record(1, &[1]);
|
||||
w.exit();
|
||||
let bytes = w.finish();
|
||||
// header word, length word, one record word, end word.
|
||||
assert_eq!(bytes.len() % 4, 0);
|
||||
assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 1);
|
||||
assert_eq!(signed(-3), 7);
|
||||
assert_eq!(signed(2), 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
//! The PC container around emitted DXIL: feature flags (`SFI0`), the
|
||||
//! signatures (`ISG1`, `OSG1`), pipeline state validation (`PSV0`) and the
|
||||
//! program (`DXIL`), laid out as validator version 1.6 lays them out, plus
|
||||
//! the container hash that D3D12 checks.
|
||||
|
||||
/// One signature element: one row (D3D12 links stages by semantic).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct SigElement {
|
||||
pub name: String,
|
||||
pub index: u32,
|
||||
/// DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...).
|
||||
pub kind: u8,
|
||||
/// DXIL component type (4 i32, 5 u32, 9 f32, 1 i1).
|
||||
pub comp: u8,
|
||||
/// DXIL interpolation mode (0 for none).
|
||||
pub interp: u8,
|
||||
/// Start row, if the element has a register.
|
||||
pub row: Option<u32>,
|
||||
pub col: u8,
|
||||
pub cols: u8,
|
||||
/// Components read (inputs) or written (outputs), relative to `col`.
|
||||
pub usage: u8,
|
||||
/// 16-bit on the console (declared 32-bit here).
|
||||
pub half: bool,
|
||||
}
|
||||
|
||||
impl SigElement {
|
||||
fn system_value(&self) -> u32 {
|
||||
match self.kind {
|
||||
1 => 6, // vertex id
|
||||
2 => 8, // instance id
|
||||
3 => 1, // position
|
||||
4 => 4, // render target array index
|
||||
5 => 5, // viewport array index
|
||||
6 => 2, // clip distance
|
||||
7 => 3, // cull distance
|
||||
10 => 7, // primitive id
|
||||
12 => 10,
|
||||
13 => 9, // front face
|
||||
14 => 66,
|
||||
15 => 70,
|
||||
16 => 64, // target
|
||||
17 => 65, // depth
|
||||
18 => 68,
|
||||
19 => 67,
|
||||
20 => 69,
|
||||
30 => 25, // cull primitive
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn sig_comp(&self) -> u32 {
|
||||
match self.comp {
|
||||
1 | 5 => 1, // bool and u32
|
||||
4 => 2,
|
||||
9 => 3,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn mask(&self) -> u8 {
|
||||
((1u8 << self.cols) - 1) << self.col
|
||||
}
|
||||
}
|
||||
|
||||
/// `ISG1`/`OSG1`: 32-byte rows, then the names.
|
||||
pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend((elements.len() as u32).to_le_bytes());
|
||||
out.extend(8u32.to_le_bytes());
|
||||
// Validator 1.6 writes one name per element in element order, repeats
|
||||
// included, except that system values share theirs (it keys names by
|
||||
// the semantic's string, which is one static string per system value);
|
||||
// the rows sorted by register (unallocated last).
|
||||
let mut offsets: Vec<u32> = Vec::new();
|
||||
let mut next = 8 + 32 * elements.len() as u32;
|
||||
let mut names = Vec::new();
|
||||
for (i, e) in elements.iter().enumerate() {
|
||||
let shared = (e.kind != 0)
|
||||
.then(|| (0..i).find(|&j| elements[j].kind == e.kind))
|
||||
.flatten();
|
||||
match shared {
|
||||
Some(j) => offsets.push(offsets[j]),
|
||||
None => {
|
||||
offsets.push(next);
|
||||
next += e.name.len() as u32 + 1;
|
||||
names.push(&e.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut order: Vec<usize> = (0..elements.len()).collect();
|
||||
order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col));
|
||||
for i in order {
|
||||
let (e, offset) = (&elements[i], offsets[i]);
|
||||
let used = e.usage << e.col;
|
||||
let rw = if input { used } else { !used & 0xf };
|
||||
for v in [
|
||||
0,
|
||||
offset,
|
||||
e.index,
|
||||
e.system_value(),
|
||||
e.sig_comp(),
|
||||
e.row.unwrap_or(u32::MAX),
|
||||
] {
|
||||
out.extend(v.to_le_bytes());
|
||||
}
|
||||
out.extend([e.mask(), rw, 0, 0]);
|
||||
out.extend(0u32.to_le_bytes());
|
||||
}
|
||||
for name in names {
|
||||
out.extend(name.as_bytes());
|
||||
out.push(0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A resource bound by register, as `PSV0` lists it.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Binding {
|
||||
/// PSV resource type: 1 sampler, 2 CBV.
|
||||
pub kind: u32,
|
||||
pub space: u32,
|
||||
pub register: u32,
|
||||
/// DXIL resource kind (13 cbuffer, 14 sampler).
|
||||
pub dxil_kind: u32,
|
||||
}
|
||||
|
||||
pub(crate) struct Psv<'a> {
|
||||
/// PSV shader kind: 0 pixel, 1 vertex, 5 compute.
|
||||
pub stage: u8,
|
||||
/// Vertex: writes `SV_Position`. Pixel: writes depth.
|
||||
pub flag: bool,
|
||||
pub inputs: &'a [SigElement],
|
||||
pub outputs: &'a [SigElement],
|
||||
/// Mesh: per-primitive outputs.
|
||||
pub prims: &'a [SigElement],
|
||||
/// Mesh: its state and the group-shared bytes it declares.
|
||||
pub mesh: Option<(super::shader::Mesh, u32)>,
|
||||
pub bindings: &'a [Binding],
|
||||
/// Compute: thread-group size and required wave size.
|
||||
pub threads: [u32; 3],
|
||||
pub wave_size: Option<u32>,
|
||||
}
|
||||
|
||||
/// `PSV0` with runtime info version 2 (validator 1.6).
|
||||
pub(crate) fn psv(p: &Psv) -> Vec<u8> {
|
||||
let vectors = |els: &[SigElement]| {
|
||||
els.iter()
|
||||
.filter_map(|e| e.row)
|
||||
.map(|r| r + 1)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (in_vectors, out_vectors) = (vectors(p.inputs), vectors(p.outputs));
|
||||
let mut out = Vec::new();
|
||||
let u32s = |out: &mut Vec<u8>, vs: &[u32]| {
|
||||
for v in vs {
|
||||
out.extend(v.to_le_bytes());
|
||||
}
|
||||
};
|
||||
u32s(&mut out, &[48]);
|
||||
let mut info = [0u8; 48];
|
||||
info[0] = u8::from(p.flag);
|
||||
let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n));
|
||||
info[16..20].copy_from_slice(&min.to_le_bytes());
|
||||
info[20..24].copy_from_slice(&max.to_le_bytes());
|
||||
info[24] = p.stage;
|
||||
for (k, n) in p.threads.into_iter().enumerate() {
|
||||
info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes());
|
||||
}
|
||||
info[28] = p.inputs.len() as u8;
|
||||
info[29] = p.outputs.len() as u8;
|
||||
info[31] = in_vectors as u8;
|
||||
info[32] = out_vectors as u8;
|
||||
if let Some((mesh, shared)) = p.mesh {
|
||||
info[0..4].copy_from_slice(&shared.to_le_bytes());
|
||||
info[12..14].copy_from_slice(&(mesh.max_vertices as u16).to_le_bytes());
|
||||
info[14..16].copy_from_slice(&(mesh.max_primitives as u16).to_le_bytes());
|
||||
info[26] = vectors(p.prims) as u8;
|
||||
info[27] = mesh.topology;
|
||||
info[30] = p.prims.len() as u8;
|
||||
}
|
||||
out.extend(info);
|
||||
u32s(&mut out, &[p.bindings.len() as u32]);
|
||||
if !p.bindings.is_empty() {
|
||||
u32s(&mut out, &[24]);
|
||||
for b in p.bindings {
|
||||
u32s(
|
||||
&mut out,
|
||||
&[b.kind, b.space, b.register, b.register, b.dxil_kind, 0],
|
||||
);
|
||||
}
|
||||
}
|
||||
// Names of arbitrary semantics (system values use ""), then indices.
|
||||
let mut strings = vec![0u8];
|
||||
let mut indices: Vec<u32> = Vec::new();
|
||||
let mut elements = Vec::new();
|
||||
for e in p.inputs.iter().chain(p.outputs).chain(p.prims) {
|
||||
let name = if e.kind == 0 {
|
||||
let needle: Vec<u8> = e.name.bytes().chain([0]).collect();
|
||||
match find(&strings, &needle) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
strings.extend(&needle);
|
||||
strings.len() - needle.len()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let index = match indices.iter().position(|&i| i == e.index) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
indices.push(e.index);
|
||||
indices.len() - 1
|
||||
}
|
||||
};
|
||||
let (start, alloc) = match e.row {
|
||||
Some(r) => (r as u8, 0x40 | (e.col << 4)),
|
||||
None => (0, 0),
|
||||
};
|
||||
elements.push((name as u32, index as u32, start, e.cols | alloc, e));
|
||||
}
|
||||
strings.resize(strings.len().next_multiple_of(4), 0);
|
||||
u32s(&mut out, &[strings.len() as u32]);
|
||||
out.extend(&strings);
|
||||
u32s(&mut out, &[indices.len() as u32]);
|
||||
u32s(&mut out, &indices);
|
||||
if !elements.is_empty() {
|
||||
u32s(&mut out, &[16]);
|
||||
for (name, index, start, cols, e) in elements {
|
||||
u32s(&mut out, &[name, index]);
|
||||
out.extend([1, start, cols, e.kind, e.sig_comp() as u8, e.interp, 0, 0]);
|
||||
}
|
||||
}
|
||||
// Input-to-output dependencies, as the view-id state declares them:
|
||||
// every output scalar on every input scalar.
|
||||
if in_vectors > 0 && out_vectors > 0 {
|
||||
let scalars = |els: &[SigElement]| {
|
||||
els.iter()
|
||||
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (ni, no) = (scalars(p.inputs), scalars(p.outputs));
|
||||
let per = (out_vectors * 4).div_ceil(32);
|
||||
for i in 0..in_vectors * 4 {
|
||||
for k in 0..per {
|
||||
let bits = if i < ni {
|
||||
no.saturating_sub(32 * k).min(32)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mask = if bits == 32 {
|
||||
u32::MAX
|
||||
} else {
|
||||
(1u32 << bits) - 1
|
||||
};
|
||||
u32s(&mut out, &[mask]);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
hay.windows(needle.len()).position(|w| w == needle)
|
||||
}
|
||||
|
||||
/// The container: parts in order, hashed.
|
||||
pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
|
||||
let table = 0x20 + 4 * parts.len();
|
||||
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
|
||||
let mut out = Vec::with_capacity(total);
|
||||
out.extend(b"DXBC");
|
||||
out.extend([0; 16]);
|
||||
out.extend(1u16.to_le_bytes());
|
||||
out.extend(0u16.to_le_bytes());
|
||||
out.extend((total as u32).to_le_bytes());
|
||||
out.extend((parts.len() as u32).to_le_bytes());
|
||||
let mut offset = table;
|
||||
for (_, d) in parts {
|
||||
out.extend((offset as u32).to_le_bytes());
|
||||
offset += 8 + d.len();
|
||||
}
|
||||
for (fourcc, d) in parts {
|
||||
out.extend(*fourcc);
|
||||
out.extend((d.len() as u32).to_le_bytes());
|
||||
out.extend(*d);
|
||||
}
|
||||
let digest = hash(&out[20..]);
|
||||
out[4..20].copy_from_slice(&digest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The container hash D3D12 checks: MD5 whose last block carries the bit
|
||||
/// count first and `2 × bytes + 1` last instead of standard padding.
|
||||
pub(crate) fn hash(data: &[u8]) -> [u8; 16] {
|
||||
let len = data.len();
|
||||
let left = len % 64;
|
||||
let mut tail = Vec::with_capacity(128);
|
||||
if left < 56 {
|
||||
tail.extend(((len as u32) << 3).to_le_bytes());
|
||||
tail.extend(&data[len - left..]);
|
||||
tail.push(0x80);
|
||||
tail.resize(60, 0);
|
||||
} else {
|
||||
tail.extend(&data[len - left..]);
|
||||
tail.push(0x80);
|
||||
tail.resize(64, 0);
|
||||
tail.extend(((len as u32) << 3).to_le_bytes());
|
||||
tail.resize(124, 0);
|
||||
}
|
||||
tail.extend(((len as u32) << 1 | 1).to_le_bytes());
|
||||
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
|
||||
for block in data[..len - left]
|
||||
.as_chunks::<64>()
|
||||
.0
|
||||
.iter()
|
||||
.chain(tail.as_chunks::<64>().0)
|
||||
{
|
||||
md5_block(&mut state, block);
|
||||
}
|
||||
let mut out = [0; 16];
|
||||
for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(state) {
|
||||
o.copy_from_slice(&s.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) {
|
||||
const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
|
||||
let x: Vec<u32> = block
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| u32::from_le_bytes(*c))
|
||||
.collect();
|
||||
let [mut a, mut b, mut c, mut d] = *state;
|
||||
for i in 0..64 {
|
||||
let (f, g) = match i / 16 {
|
||||
0 => ((b & c) | (!b & d), i),
|
||||
1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
|
||||
2 => (b ^ c ^ d, (3 * i + 5) % 16),
|
||||
_ => (c ^ (b | !d), (7 * i) % 16),
|
||||
};
|
||||
let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32;
|
||||
let rotated = a
|
||||
.wrapping_add(f)
|
||||
.wrapping_add(k)
|
||||
.wrapping_add(x[g])
|
||||
.rotate_left(S[(i / 16) * 4 + i % 4]);
|
||||
(a, b, c, d) = (d, b.wrapping_add(rotated), b, c);
|
||||
}
|
||||
for (s, v) in state.iter_mut().zip([a, b, c, d]) {
|
||||
*s = s.wrapping_add(v);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn md5_core_matches_the_standard() {
|
||||
// Standard MD5 of "abc" with standard padding, through md5_block.
|
||||
let mut block = b"abc".to_vec();
|
||||
block.push(0x80);
|
||||
block.resize(56, 0);
|
||||
block.extend(24u64.to_le_bytes());
|
||||
let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
|
||||
md5_block(&mut state, block.as_slice().try_into().unwrap());
|
||||
let hex: String = state
|
||||
.iter()
|
||||
.flat_map(|s| s.to_le_bytes())
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect();
|
||||
assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,452 @@
|
||||
//! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute
|
||||
//! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts.
|
||||
//! Compute shaders keep the console's thread-group size; one that depends
|
||||
//! on the lane layout (cross-lane operations) declares the console's wave
|
||||
//! size (`WaveSize`), so the host device must support it.
|
||||
//!
|
||||
//! What the host binds for a translated shader ([`HostShader`]):
|
||||
//!
|
||||
//! * **User data** at `b0, space 0` (32-bit root constants or a constant
|
||||
//! buffer, per stage): dword `index` holds a root parameter's value, as
|
||||
//! [`UserData`] lists. A root-constant dword is the constant. A
|
||||
//! descriptor table is the byte offset of its first descriptor in its
|
||||
//! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16
|
||||
//! for sampler tables (the console's descriptor sizes; the code adds
|
||||
//! offsets in those units). The heap bases of dynamic resources are 0
|
||||
//! and not listed.
|
||||
//! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and
|
||||
//! `SamplerDescriptorHeap[]`, at the index the console address gives, so
|
||||
//! the host heaps keep the title's descriptor order. The root signature
|
||||
//! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and
|
||||
//! `SAMPLER_HEAP_DIRECTLY_INDEXED`.
|
||||
//! * **Immediate samplers** as static samplers `s<n>, space 0`, `n` the
|
||||
//! position in [`HostShader::samplers`] (the console sampler words) and
|
||||
//! [`HostShader::static_samplers`] (the same decoded into a D3D12 static
|
||||
//! sampler description). Comparison sampling (added 2026-11-23): an
|
||||
//! immediate sampler it uses has a comparison filter there (bit 0x80);
|
||||
//! a heap sampler it uses must be a comparison sampler on the host.
|
||||
//! * **Root CBVs and root SRVs** (raw buffers) as root descriptors
|
||||
//! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter
|
||||
//! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the
|
||||
//! address the title sets is the buffer's.
|
||||
//! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and
|
||||
//! vertex programs fetch vertices themselves with typed-format loads
|
||||
//! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm,
|
||||
//! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the
|
||||
//! instruction, so the translation reads raw bytes and converts them
|
||||
//! itself. Their descriptors are built around a root SRV (stride 1, no
|
||||
//! record limit): the host binds the root SRV `t<slot>` above with the
|
||||
//! address the title sets, nothing more. The vertex index, the stride
|
||||
//! and the attribute offset are the shader's own arithmetic on data in
|
||||
//! that buffer (per-stream headers), not descriptor fields.
|
||||
//! * **Buffer views in the heap** are declared by how the shader reads
|
||||
//! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and
|
||||
//! typed-format loads without an index; structured with the used-resource
|
||||
//! entry's stride when indexed; typed with four 32-bit float channels for
|
||||
//! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at
|
||||
//! that index must be of that kind and start at the console descriptor's
|
||||
//! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the
|
||||
//! title's view description says. Typed-format loads from heap
|
||||
//! descriptors (1,024 world compute programs, ray-tracing material
|
||||
//! resolves) read raw views this way.
|
||||
//!
|
||||
//! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses
|
||||
//! atomically is declared a 32-bit unsigned single-channel view; the
|
||||
//! host's view at that index must be an R32 integer view (64-bit atomics
|
||||
//! stop the translation). Global loads from a root SRV read it raw.
|
||||
//!
|
||||
//! Entry points: [`translate`] (container bytes as the title passes them
|
||||
//! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
|
||||
//! earlier stages already run). The root constants of each stage must
|
||||
//! cover [`HostShader::user_data_dwords`]. Stability: these types and the
|
||||
//! binding scheme are what pipeline creation builds on; changes are
|
||||
//! announced.
|
||||
//! * **Signatures** as the console container has them (same semantics,
|
||||
//! registers and masks), so the input layout and stage linking are the
|
||||
//! title's; pixel outputs are plain 32-bit values.
|
||||
//! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and
|
||||
//! descriptors as above (the root constants visible to the mesh stage);
|
||||
//! the pipeline is a mesh pipeline (pipeline-state stream, no input
|
||||
//! layout) with the title's pixel shader. The thread group is the
|
||||
//! console's in lanes (`[numthreads]` in the DXIL), the vertex and
|
||||
//! primitive maxima its own, triangles only, no wave size required. The
|
||||
//! console numbers groups in x only: the draw path passes the title's
|
||||
//! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
|
||||
//! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
|
||||
//! console never exports them).
|
||||
|
||||
mod bitcode;
|
||||
mod container;
|
||||
#[cfg(all(test, windows))]
|
||||
mod diff_tests;
|
||||
#[cfg(all(windows, any(test, feature = "host")))]
|
||||
pub mod host;
|
||||
mod lower;
|
||||
mod sampler;
|
||||
mod shader;
|
||||
#[cfg(windows)]
|
||||
pub mod validator;
|
||||
mod wave;
|
||||
|
||||
use crate::dxbc::{Container, FourCC};
|
||||
use crate::native::{HwStage, NativeProgram, RootType};
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
pub use sampler::StaticSampler;
|
||||
pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
|
||||
|
||||
/// A translated shader and what the host binds for it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HostShader {
|
||||
pub stage: HwStage,
|
||||
/// The DXIL container, hashed as D3D12 expects.
|
||||
pub dxil: Vec<u8>,
|
||||
/// The user-data dwords the shader reads.
|
||||
pub user_data: Vec<UserData>,
|
||||
/// Immediate samplers: the four sampler words of `s<n>`.
|
||||
pub samplers: Vec<[u32; 4]>,
|
||||
/// The same samplers decoded, `s<n>` at position n: the static sampler
|
||||
/// descriptions the host's root signature declares.
|
||||
pub static_samplers: Vec<StaticSampler>,
|
||||
/// Root CBVs the shader reads: root parameter indices, each bound as
|
||||
/// `b<index>` in [`ROOT_CBV_SPACE`].
|
||||
pub root_cbvs: Vec<u8>,
|
||||
/// Root SRVs (raw buffers) the shader reads: `t<index>` in
|
||||
/// [`ROOT_CBV_SPACE`].
|
||||
pub root_srvs: Vec<u8>,
|
||||
}
|
||||
|
||||
impl HostShader {
|
||||
/// Size of the user-data buffer the shader declares, in dwords (a
|
||||
/// multiple of 4; 0 when it reads none). Root constants must cover it.
|
||||
pub fn user_data_dwords(&self) -> u32 {
|
||||
let n = self
|
||||
.user_data
|
||||
.iter()
|
||||
.map(|u| u.index + 1)
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
n.next_multiple_of(4)
|
||||
}
|
||||
}
|
||||
|
||||
/// One dword of user data and the root parameter that fills it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct UserData {
|
||||
/// Dword in the user-data buffer (the console's user-data index).
|
||||
pub index: u32,
|
||||
/// Root parameter index in the title's root signature.
|
||||
pub slot: u8,
|
||||
/// `Constants` or `Table` (see the module notes for the value).
|
||||
pub root: RootType,
|
||||
/// Dword within the parameter.
|
||||
pub dword: u32,
|
||||
}
|
||||
|
||||
/// Translates the vertex, pixel, compute or mesh program of a console
|
||||
/// shader container.
|
||||
pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
|
||||
let c = Container::parse(container)?;
|
||||
let dxil = c
|
||||
.part(FourCC::DXIL)
|
||||
.ok_or(ShaderError::Malformed("no DXIL part"))?;
|
||||
let native = crate::native_programs(dxil.data)?
|
||||
.into_iter()
|
||||
.find(|p| {
|
||||
matches!(
|
||||
p.stage,
|
||||
HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms
|
||||
)
|
||||
})
|
||||
.ok_or(ShaderError::Unsupported {
|
||||
offset: 0,
|
||||
what: "a container without a vertex, pixel, compute or mesh program",
|
||||
})?;
|
||||
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
let res = resource::track(&p, &native.layout, native.stage)?;
|
||||
let io = io::raise(&p, &native)?;
|
||||
let st = structure::structure(&p)?;
|
||||
emit(&c, &native, &p, &st, &io, &res)
|
||||
}
|
||||
|
||||
/// Emits a program whose earlier stages already ran.
|
||||
pub fn emit(
|
||||
c: &Container,
|
||||
native: &NativeProgram,
|
||||
p: &ir::Program,
|
||||
st: &structure::Structured,
|
||||
io: &io::Io,
|
||||
res: &resource::Resources,
|
||||
) -> Result<HostShader, ShaderError> {
|
||||
let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
|
||||
match c.part(fourcc) {
|
||||
Some(part) => signature(part.data),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
};
|
||||
let pixel = native.stage == HwStage::Ps;
|
||||
let mut inputs = sig(FourCC::ISG1)?;
|
||||
let mut outputs = sig(FourCC::OSG1)?;
|
||||
// Interpolation as DXC declares it by default; pixel inputs that are
|
||||
// read get the mode their barycentrics say.
|
||||
let interpolated = if pixel { &mut inputs } else { &mut outputs };
|
||||
for e in interpolated {
|
||||
e.interp = match (e.kind, e.comp) {
|
||||
(3, _) => 4,
|
||||
// Constant, as DXC declares it (the AMD compiler crashed on a
|
||||
// front face without a mode).
|
||||
(13, _) => 1,
|
||||
(0 | 6 | 7, 9) => 2,
|
||||
(0, _) => 1,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
// Per-primitive outputs are constant. The console never exports a
|
||||
// primitive id or cull flag a mesh shader writes (it culls with the
|
||||
// primitive export), so those rows are left out.
|
||||
let mut prims = sig(FourCC::PSG1)?;
|
||||
prims.retain(|e| !matches!(e.kind, 10 | 30));
|
||||
for e in &mut prims {
|
||||
e.interp = 1;
|
||||
}
|
||||
// A mesh group's id arrives multiplied by max(threads, vertices,
|
||||
// primitives) (the code divides by that); the thread count is in PSV0
|
||||
// from runtime info version 2 on.
|
||||
// shortcut: older containers fall back to the group's lane count, right
|
||||
// when the HLSL group fills its waves (Grand Theft Auto VI's do).
|
||||
let mesh_stride = match &native.io {
|
||||
crate::native::StageIo::Ms(ms) => {
|
||||
let psv = c.part(FourCC::PSV0).map(|p| p.data);
|
||||
let threads = psv
|
||||
.filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48))
|
||||
.and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok());
|
||||
threads.map_or(ms.threads, |t| {
|
||||
t.max(ms.max_vertices).max(ms.max_primitives)
|
||||
})
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
let l = lower::lower(&lower::Parts {
|
||||
native,
|
||||
p,
|
||||
st,
|
||||
io,
|
||||
res,
|
||||
inputs,
|
||||
outputs,
|
||||
prims,
|
||||
mesh_stride,
|
||||
})?;
|
||||
Ok(HostShader {
|
||||
stage: native.stage,
|
||||
dxil: l.dxil,
|
||||
user_data: l.user_data,
|
||||
static_samplers: l
|
||||
.samplers
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(n, &w)| {
|
||||
let mut s = StaticSampler::from_words(w);
|
||||
if l.cmp_samplers >> n & 1 != 0 {
|
||||
s.filter |= 0x80;
|
||||
}
|
||||
s
|
||||
})
|
||||
.collect(),
|
||||
samplers: l.samplers,
|
||||
root_cbvs: l.root_cbvs,
|
||||
root_srvs: l.root_srvs,
|
||||
})
|
||||
}
|
||||
|
||||
/// The rows of an `ISG1`/`OSG1` part.
|
||||
fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
|
||||
use crate::dxbc::u32_at;
|
||||
let count = u32_at(part, 0)? as usize;
|
||||
let base = u32_at(part, 4)? as usize;
|
||||
let mut out = Vec::with_capacity(count);
|
||||
for i in 0..count {
|
||||
let at = base + 32 * i;
|
||||
let name_at = u32_at(part, at + 4)? as usize;
|
||||
let name = part
|
||||
.get(name_at..)
|
||||
.and_then(|s| s.split(|&b| b == 0).next())
|
||||
.ok_or(ShaderError::Malformed("signature name out of bounds"))?;
|
||||
let mask = *part
|
||||
.get(at + 24)
|
||||
.ok_or(ShaderError::Malformed("truncated"))?;
|
||||
if u32_at(part, at + 28)? != 0 {
|
||||
return Err(ShaderError::Unsupported {
|
||||
offset: 0,
|
||||
what: "a minimum-precision signature element",
|
||||
});
|
||||
}
|
||||
if u32_at(part, at)? != 0 {
|
||||
return Err(ShaderError::Unsupported {
|
||||
offset: 0,
|
||||
what: "a signature element of another stream",
|
||||
});
|
||||
}
|
||||
let kind = match u32_at(part, at + 12)? {
|
||||
0 => 0,
|
||||
1 => 3,
|
||||
2 => 6,
|
||||
3 => 7,
|
||||
4 => 4,
|
||||
5 => 5,
|
||||
6 => 1,
|
||||
7 => 10,
|
||||
8 => 2,
|
||||
9 => 13,
|
||||
10 => 12,
|
||||
64 => 16,
|
||||
65 => 17,
|
||||
66 => 14,
|
||||
67 => 19,
|
||||
68 => 18,
|
||||
69 => 20,
|
||||
70 => 15,
|
||||
25 => 30, // cull primitive
|
||||
_ => {
|
||||
return Err(ShaderError::Unsupported {
|
||||
offset: 0,
|
||||
what: "a system value in the signature",
|
||||
});
|
||||
}
|
||||
};
|
||||
// 16-bit elements are declared 32-bit; reading or writing one
|
||||
// converts (16-bit values travel packed on the console).
|
||||
let raw = u32_at(part, at + 16)?;
|
||||
let comp = match (kind, raw) {
|
||||
// DXIL declares the front face a uint (the validator insists).
|
||||
(13, _) => 5,
|
||||
(_, 1 | 4) => 5,
|
||||
(_, 2 | 5) => 4,
|
||||
(_, 3 | 6) => 9,
|
||||
(_, c) => {
|
||||
return Err(ShaderError::Unsupported {
|
||||
offset: 0,
|
||||
what: match c {
|
||||
0 => "a signature element of unknown type",
|
||||
_ => "a 64-bit signature element",
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
let register = u32_at(part, at + 20)?;
|
||||
out.push(container::SigElement {
|
||||
name: String::from_utf8_lossy(name).into_owned(),
|
||||
index: u32_at(part, at + 8)?,
|
||||
kind,
|
||||
comp,
|
||||
interp: 0,
|
||||
row: (register != u32::MAX).then_some(register),
|
||||
col: mask.trailing_zeros().min(3) as u8,
|
||||
cols: mask.count_ones().max(1) as u8,
|
||||
usage: 0,
|
||||
half: (4..=6).contains(&raw),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::bitcode::Attr;
|
||||
use super::container::SigElement;
|
||||
use super::shader::Shader;
|
||||
|
||||
/// A pixel shader writing a constant colour.
|
||||
fn constant_color() -> Vec<u8> {
|
||||
let mut s = Shader::new(true);
|
||||
s.outputs.push(SigElement {
|
||||
name: "SV_Target".into(),
|
||||
index: 0,
|
||||
kind: 16,
|
||||
comp: 9,
|
||||
interp: 0,
|
||||
row: Some(0),
|
||||
col: 0,
|
||||
cols: 4,
|
||||
usage: 15,
|
||||
half: false,
|
||||
});
|
||||
let b = s.entry;
|
||||
for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() {
|
||||
let args = [
|
||||
s.m.i32(0),
|
||||
s.m.i32(0),
|
||||
s.m.i8(c as u8),
|
||||
s.m.f32(v.to_bits()),
|
||||
];
|
||||
s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
|
||||
}
|
||||
s.m.terminate(b, super::bitcode::Term::Ret);
|
||||
s.finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn stub_pipeline_is_created() {
|
||||
let Ok(host) = super::host::Host::new(false) else {
|
||||
eprintln!("no SM 6.6 device; skipped");
|
||||
return;
|
||||
};
|
||||
let ps = super::HostShader {
|
||||
stage: crate::HwStage::Ps,
|
||||
dxil: constant_color(),
|
||||
user_data: Vec::new(),
|
||||
samplers: Vec::new(),
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
};
|
||||
let file = |var: &str, stage| {
|
||||
std::env::var(var).ok().map(|p| super::HostShader {
|
||||
stage,
|
||||
dxil: std::fs::read(p).unwrap(),
|
||||
user_data: Vec::new(),
|
||||
samplers: Vec::new(),
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
})
|
||||
};
|
||||
let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
|
||||
let vs = file("VICTORY_REF_VS", crate::HwStage::Vs)
|
||||
.unwrap_or_else(|| super::host::stub_vs(&ps).unwrap());
|
||||
if let Ok(mut v) = super::validator::Validator::load(
|
||||
super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut vs.dxil.clone()).unwrap();
|
||||
}
|
||||
host.pipeline(&vs, &ps).unwrap();
|
||||
// The runtime checks the container hash: no hash or a wrong one is
|
||||
// refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass
|
||||
// value; ours works with older ones too.)
|
||||
let mut wrong = ps.dxil[4..20].to_vec();
|
||||
wrong[0] ^= 1;
|
||||
for digest in [&[0u8; 16][..], &wrong] {
|
||||
let mut other = ps.clone();
|
||||
other.dxil[4..20].copy_from_slice(digest);
|
||||
assert!(
|
||||
host.pipeline(&vs, &other).is_err(),
|
||||
"digest {digest:02x?} accepted"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn constant_color_validates() {
|
||||
let mut c = constant_color();
|
||||
let path = super::validator::Validator::default_path();
|
||||
let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else {
|
||||
eprintln!("no dxil.dll; skipped");
|
||||
return;
|
||||
};
|
||||
let ours = c[4..20].to_vec();
|
||||
v.validate(&mut c).unwrap();
|
||||
assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Immediate samplers: the console's four sampler words (the GPU's public
|
||||
//! `SQ_IMG_SAMP_WORD0-3` layout) as a D3D12 static sampler.
|
||||
//!
|
||||
//! Word 0: address modes x, y, z (bits 0-8, 3 each), log2 of the maximum
|
||||
//! anisotropy (9-11), comparison function (12-14), reduction (29-30: 0
|
||||
//! filtering, 1 minimum, 2 maximum). Word 1: minimum and maximum LOD
|
||||
//! (0-11, 12-23, unsigned 4.8). Word 2: LOD bias (0-13, signed 5.8),
|
||||
//! magnification and minification filters (20-21, 22-23: point, linear,
|
||||
//! anisotropic point, anisotropic linear), mip filter (26-27: none, point,
|
||||
//! linear). Word 3: border colour (30-31: transparent black, opaque black,
|
||||
//! opaque white, custom).
|
||||
//!
|
||||
//! Comparison is the sampling instruction's, not the sampler's: the console
|
||||
//! encodes a comparison function in every sampler (D3D's default, less or
|
||||
//! equal, when unused).
|
||||
|
||||
/// A static sampler in D3D12 terms; the integers are the `D3D12_FILTER`,
|
||||
/// `D3D12_TEXTURE_ADDRESS_MODE`, `D3D12_COMPARISON_FUNC` and
|
||||
/// `D3D12_STATIC_BORDER_COLOR` values.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct StaticSampler {
|
||||
pub filter: u32,
|
||||
/// U, V, W.
|
||||
pub address: [u32; 3],
|
||||
pub mip_lod_bias: f32,
|
||||
pub max_anisotropy: u32,
|
||||
pub comparison: u32,
|
||||
pub border: u32,
|
||||
pub min_lod: f32,
|
||||
pub max_lod: f32,
|
||||
}
|
||||
|
||||
// The floats come from fixed-point fields: never NaN.
|
||||
impl Eq for StaticSampler {}
|
||||
|
||||
impl StaticSampler {
|
||||
/// Decodes the four sampler words.
|
||||
pub fn from_words(w: [u32; 4]) -> Self {
|
||||
let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1);
|
||||
// wrap, mirror, clamp, mirror once; the half-border modes have no
|
||||
// D3D form and become their nearest.
|
||||
let address = |m: u32| [1, 2, 3, 5, 3, 5, 4, 5][m as usize];
|
||||
let (mag, min, mip) = (bits(w[2], 20, 2), bits(w[2], 22, 2), bits(w[2], 26, 2));
|
||||
let reduction = match bits(w[0], 29, 2) {
|
||||
1 => 2,
|
||||
2 => 3,
|
||||
_ => 0,
|
||||
};
|
||||
let filter = if mag >= 2 || min >= 2 {
|
||||
0x55 | reduction << 7
|
||||
} else {
|
||||
(min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7
|
||||
};
|
||||
let lod = |v: u32| v as f32 / 256.0;
|
||||
// Without a mip filter the base level is sampled.
|
||||
let (min_lod, max_lod) = if mip == 0 {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
(lod(bits(w[1], 0, 12)), lod(bits(w[1], 12, 12)))
|
||||
};
|
||||
StaticSampler {
|
||||
filter,
|
||||
address: [0, 3, 6].map(|at| address(bits(w[0], at, 3))),
|
||||
mip_lod_bias: ((bits(w[2], 0, 14) << 18) as i32 >> 18) as f32 / 256.0,
|
||||
max_anisotropy: 1 << bits(w[0], 9, 3).min(4),
|
||||
comparison: bits(w[0], 12, 3) + 1,
|
||||
// shortcut: a custom border colour (type 3, a table entry) becomes
|
||||
// transparent black; upgrade when a title uses one.
|
||||
border: bits(w[3], 30, 2) % 3,
|
||||
min_lod,
|
||||
max_lod,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn console_compiled_samplers_decode() {
|
||||
// Words the console compiler wrote for static samplers of known
|
||||
// descriptions.
|
||||
let point = StaticSampler::from_words([0x3088, 0x0054_0100, 0x1400_0080, 0x8000_0000]);
|
||||
assert_eq!(
|
||||
point,
|
||||
StaticSampler {
|
||||
filter: 0,
|
||||
address: [1, 2, 3],
|
||||
mip_lod_bias: 0.5,
|
||||
max_anisotropy: 1,
|
||||
comparison: 4,
|
||||
border: 2,
|
||||
min_lod: 1.0,
|
||||
max_lod: 5.25,
|
||||
}
|
||||
);
|
||||
let aniso = StaticSampler::from_words([0x369E, 0x00FF_F000, 0x18F0_3E00, 0x8000_0000]);
|
||||
assert_eq!(
|
||||
(aniso.filter, aniso.address, aniso.max_anisotropy),
|
||||
(0x55, [4, 5, 3], 8)
|
||||
);
|
||||
assert_eq!((aniso.mip_lod_bias, aniso.max_lod), (-2.0, 4095.0 / 256.0));
|
||||
let compare = StaticSampler::from_words([0x3006, 0x00FF_F000, 0x1450_0000, 0x4000_0000]);
|
||||
assert_eq!(
|
||||
(compare.filter, compare.address, compare.border),
|
||||
(0x14, [4, 1, 1], 1)
|
||||
);
|
||||
let minimum =
|
||||
StaticSampler::from_words([0x2000_3003, 0x00FF_F000, 0x1850_0000, 0x8000_0000]);
|
||||
assert_eq!((minimum.filter, minimum.address[0]), (0x115, 5));
|
||||
let mag_mip = StaticSampler::from_words([0x3002, 0, 0x1810_0000, 0x8000_0000]);
|
||||
assert_eq!((mag_mip.filter, mag_mip.max_lod), (0x05, 0.0));
|
||||
let max_aniso =
|
||||
StaticSampler::from_words([0x4000_3800, 0x00FF_F000, 0x18F0_0F00, 0x8000_0000]);
|
||||
assert_eq!(
|
||||
(
|
||||
max_aniso.filter,
|
||||
max_aniso.max_anisotropy,
|
||||
max_aniso.mip_lod_bias
|
||||
),
|
||||
(0x1D5, 16, 15.0)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
//! A DXIL vertex, pixel, compute or mesh shader under construction: the module,
|
||||
//! the `dx.op` declarations it calls, its signatures and bound resources,
|
||||
//! and the metadata and container that wrap it up (SM 6.6, validator 1.6).
|
||||
|
||||
use super::bitcode::{Attr, Md, Module, Ty, V};
|
||||
use super::container::{self, Binding, Psv, SigElement};
|
||||
|
||||
/// Where the shader reads its user data: `b0` in this space.
|
||||
pub const USER_DATA_SPACE: u32 = 0;
|
||||
/// Where immediate samplers are bound: `s<n>` in this space.
|
||||
pub const SAMPLER_SPACE: u32 = 0;
|
||||
/// Where root CBVs and SRVs are bound: `b<root parameter index>` and
|
||||
/// `t<root parameter index>` in this space.
|
||||
pub const ROOT_CBV_SPACE: u32 = 1;
|
||||
|
||||
/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits.
|
||||
pub(crate) mod flags {
|
||||
pub const RAW_BUFFERS: u64 = 1 << 4;
|
||||
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
|
||||
pub const WAVE_OPS: u64 = 1 << 19;
|
||||
pub const INT64: u64 = 1 << 20;
|
||||
pub const RESOURCE_HEAP: u64 = 1 << 30;
|
||||
pub const SAMPLER_HEAP: u64 = 1 << 31;
|
||||
}
|
||||
|
||||
pub(crate) struct Types {
|
||||
pub void: Ty,
|
||||
pub i1: Ty,
|
||||
pub i32: Ty,
|
||||
pub f32: Ty,
|
||||
pub handle: Ty,
|
||||
pub props: Ty,
|
||||
pub bind: Ty,
|
||||
pub cbuf_ret: Ty,
|
||||
pub res_ret: Ty,
|
||||
}
|
||||
|
||||
/// What a mesh shader declares beyond its thread-group size.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Mesh {
|
||||
pub max_vertices: u32,
|
||||
pub max_primitives: u32,
|
||||
/// 1 lines, 2 triangles.
|
||||
pub topology: u8,
|
||||
}
|
||||
|
||||
pub(crate) struct Shader {
|
||||
pub m: Module,
|
||||
pub t: Types,
|
||||
pub pixel: bool,
|
||||
pub inputs: Vec<SigElement>,
|
||||
pub outputs: Vec<SigElement>,
|
||||
/// A mesh shader's per-primitive outputs.
|
||||
pub prims: Vec<SigElement>,
|
||||
/// A mesh shader (`threads` is its thread-group size).
|
||||
pub mesh: Option<Mesh>,
|
||||
/// Dwords of user data the shader reads (0: no user-data buffer).
|
||||
pub user_data: u32,
|
||||
/// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`].
|
||||
pub samplers: u32,
|
||||
/// Bit n: immediate sampler n is a comparison sampler.
|
||||
pub cmp_samplers: u64,
|
||||
/// Root CBVs read, by root parameter index, with their handles.
|
||||
pub root_cbvs: Vec<(u8, V)>,
|
||||
/// Root SRVs (raw buffers) read, likewise.
|
||||
pub root_srvs: Vec<(u8, V)>,
|
||||
pub flags: u64,
|
||||
/// A compute shader with this thread-group size.
|
||||
pub threads: Option<[u32; 3]>,
|
||||
/// The wave size a compute shader requires (`WaveSize`).
|
||||
pub wave_size: Option<u32>,
|
||||
/// Thread-group shared memory, in dwords.
|
||||
pub lds_dwords: u32,
|
||||
lds: Option<V>,
|
||||
main: V,
|
||||
pub entry: usize,
|
||||
}
|
||||
|
||||
impl Shader {
|
||||
pub fn new(pixel: bool) -> Self {
|
||||
let mut m = Module::default();
|
||||
let void = m.void();
|
||||
let i1 = m.int(1);
|
||||
let i8 = m.int(8);
|
||||
let i32 = m.int(32);
|
||||
let f32 = m.float();
|
||||
let i8p = m.ptr(i8);
|
||||
let handle = m.named_struct("dx.types.Handle", vec![i8p]);
|
||||
let props = m.named_struct("dx.types.ResourceProperties", vec![i32, i32]);
|
||||
let bind = m.named_struct("dx.types.ResBind", vec![i32, i32, i32, i8]);
|
||||
let cbuf_ret = m.named_struct("dx.types.CBufRet.i32", vec![i32, i32, i32, i32]);
|
||||
let res_ret = m.named_struct("dx.types.ResRet.f32", vec![f32, f32, f32, f32, i32]);
|
||||
let main_ty = m.func_ty(void, vec![]);
|
||||
m.ptr(main_ty);
|
||||
let main = m.function("main", main_ty, None, true);
|
||||
let entry = m.new_block();
|
||||
Shader {
|
||||
m,
|
||||
t: Types {
|
||||
void,
|
||||
i1,
|
||||
i32,
|
||||
f32,
|
||||
handle,
|
||||
props,
|
||||
bind,
|
||||
cbuf_ret,
|
||||
res_ret,
|
||||
},
|
||||
pixel,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh: None,
|
||||
user_data: 0,
|
||||
samplers: 0,
|
||||
cmp_samplers: 0,
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
flags: 0,
|
||||
threads: None,
|
||||
wave_size: None,
|
||||
lds_dwords: 0,
|
||||
lds: None,
|
||||
main,
|
||||
entry,
|
||||
}
|
||||
}
|
||||
|
||||
/// The thread-group shared memory: `[lds_dwords x i32]` in address
|
||||
/// space 3.
|
||||
pub fn lds(&mut self) -> V {
|
||||
if let Some(g) = self.lds {
|
||||
return g;
|
||||
}
|
||||
let arr = self.m.array(self.lds_dwords, self.t.i32);
|
||||
let g = self.m.global("lds", arr, 3);
|
||||
self.lds = Some(g);
|
||||
g
|
||||
}
|
||||
|
||||
/// Calls `dx.op.<name>` (class and overload) with `opcode` and `args`.
|
||||
pub fn op(
|
||||
&mut self,
|
||||
block: usize,
|
||||
name: &str,
|
||||
attr: Attr,
|
||||
ret: Ty,
|
||||
opcode: u32,
|
||||
args: &[V],
|
||||
) -> V {
|
||||
let mut params = vec![self.t.i32];
|
||||
params.extend(args.iter().map(|&a| self.m.type_of(a)));
|
||||
let fty = self.m.func_ty(ret, params);
|
||||
self.m.ptr(fty);
|
||||
let f = self
|
||||
.m
|
||||
.function(&format!("dx.op.{name}"), fty, Some(attr), false);
|
||||
let mut all = vec![self.m.i32(opcode)];
|
||||
all.extend(args);
|
||||
self.m.call(block, f, all)
|
||||
}
|
||||
|
||||
/// The handle of the user-data constant buffer, made in the entry block.
|
||||
pub fn user_data_handle(&mut self) -> V {
|
||||
let bind = [
|
||||
self.m.i32(0),
|
||||
self.m.i32(0),
|
||||
self.m.i32(USER_DATA_SPACE),
|
||||
self.m.i8(2), // CBV
|
||||
];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let block = self.entry;
|
||||
let (i, f) = (self.m.i32(0), self.m.bool(false));
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, i, f],
|
||||
);
|
||||
// The size is known in `finish`, which fixes this placeholder.
|
||||
self.annotate(block, h, 13, u32::MAX)
|
||||
}
|
||||
|
||||
/// The handle of the root CBV of root parameter `slot`, made in the
|
||||
/// entry block.
|
||||
pub fn root_cbv_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 13, 65536);
|
||||
self.root_cbvs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of the root SRV (a raw buffer) of root parameter `slot`.
|
||||
pub fn root_srv_handle(&mut self, slot: u8) -> V {
|
||||
if let Some(&(_, h)) = self.root_srvs.iter().find(|r| r.0 == slot) {
|
||||
return h;
|
||||
}
|
||||
let r = self.m.i32(u32::from(slot));
|
||||
let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(0)];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let f = self.m.bool(false);
|
||||
let block = self.entry;
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, r, f],
|
||||
);
|
||||
let h = self.annotate(block, h, 11, 0);
|
||||
self.flags |= flags::RAW_BUFFERS;
|
||||
self.root_srvs.push((slot, h));
|
||||
h
|
||||
}
|
||||
|
||||
/// The handle of immediate sampler `n` (a comparison sampler when its
|
||||
/// bit in `cmp_samplers` is set).
|
||||
pub fn sampler_handle(&mut self, block: usize, n: u32) -> V {
|
||||
let bind = [
|
||||
self.m.i32(n),
|
||||
self.m.i32(n),
|
||||
self.m.i32(SAMPLER_SPACE),
|
||||
self.m.i8(3), // sampler
|
||||
];
|
||||
let bind = self.m.aggregate(self.t.bind, &bind);
|
||||
let (i, f) = (self.m.i32(n), self.m.bool(false));
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromBinding",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
217,
|
||||
&[bind, i, f],
|
||||
);
|
||||
let cmp = if self.cmp_samplers >> n & 1 != 0 {
|
||||
0x8000
|
||||
} else {
|
||||
0
|
||||
};
|
||||
self.annotate(block, h, 14 | cmp, 0)
|
||||
}
|
||||
|
||||
pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V {
|
||||
let p = [self.m.i32(props0), self.m.i32(props1)];
|
||||
let p = self.m.aggregate(self.t.props, &p);
|
||||
self.op(
|
||||
block,
|
||||
"annotateHandle",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
216,
|
||||
&[h, p],
|
||||
)
|
||||
}
|
||||
|
||||
/// A descriptor heap handle, annotated with `props`.
|
||||
pub fn heap_handle(&mut self, block: usize, index: V, sampler: bool, props: (u32, u32)) -> V {
|
||||
self.flags |= if sampler {
|
||||
flags::SAMPLER_HEAP
|
||||
} else {
|
||||
flags::RESOURCE_HEAP
|
||||
};
|
||||
let (s, n) = (self.m.bool(sampler), self.m.bool(false));
|
||||
let h = self.op(
|
||||
block,
|
||||
"createHandleFromHeap",
|
||||
Attr::ReadNone,
|
||||
self.t.handle,
|
||||
218,
|
||||
&[index, s, n],
|
||||
);
|
||||
self.annotate(block, h, props.0, props.1)
|
||||
}
|
||||
|
||||
/// The finished container.
|
||||
pub fn finish(mut self) -> Vec<u8> {
|
||||
let ud_size = (self.user_data * 4).next_multiple_of(16);
|
||||
self.fix_user_data_size(ud_size);
|
||||
let mut resources = None;
|
||||
let mut bindings = Vec::new();
|
||||
let i32c = |s: &mut Self, v: u32| {
|
||||
let c = s.m.i32(v);
|
||||
s.m.md_value(c)
|
||||
};
|
||||
if self.user_data > 0
|
||||
|| self.samplers > 0
|
||||
|| !self.root_cbvs.is_empty()
|
||||
|| !self.root_srvs.is_empty()
|
||||
{
|
||||
let empty = self.m.md_str("");
|
||||
let mut cbvs = None;
|
||||
let mut cbv_list = Vec::new();
|
||||
if self.user_data > 0 {
|
||||
let arr = self.m.array(self.user_data.next_multiple_of(4), self.t.i32);
|
||||
let ty = self.m.named_struct("UserData", vec![arr]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, 0)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, USER_DATA_SPACE)),
|
||||
Some(i32c(&mut self, 0)),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, ud_size)),
|
||||
None,
|
||||
];
|
||||
cbv_list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 2,
|
||||
space: USER_DATA_SPACE,
|
||||
register: 0,
|
||||
dxil_kind: 13,
|
||||
});
|
||||
}
|
||||
let blob = self.m.array(16384, self.t.i32);
|
||||
let ty = self.m.named_struct("RootCbv", vec![blob]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
for (slot, _) in self.root_cbvs.clone() {
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, cbv_list.len() as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 65536)),
|
||||
None,
|
||||
];
|
||||
cbv_list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 2,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 13,
|
||||
});
|
||||
}
|
||||
if !cbv_list.is_empty() {
|
||||
cbvs = Some(self.m.md_node(cbv_list));
|
||||
}
|
||||
let mut srvs = None;
|
||||
if !self.root_srvs.is_empty() {
|
||||
let ty = self
|
||||
.m
|
||||
.named_struct("struct.ByteAddressBuffer", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let mut list = Vec::new();
|
||||
for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() {
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n as u32)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, ROOT_CBV_SPACE)),
|
||||
Some(i32c(&mut self, u32::from(slot))),
|
||||
Some(i32c(&mut self, 1)),
|
||||
Some(i32c(&mut self, 11)),
|
||||
Some(i32c(&mut self, 0)),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 4,
|
||||
space: ROOT_CBV_SPACE,
|
||||
register: u32::from(slot),
|
||||
dxil_kind: 11,
|
||||
});
|
||||
}
|
||||
srvs = Some(self.m.md_node(list));
|
||||
}
|
||||
let mut samplers = None;
|
||||
if self.samplers > 0 {
|
||||
let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]);
|
||||
let p = self.m.ptr(ty);
|
||||
let u = self.m.undef(p);
|
||||
let mut list = Vec::new();
|
||||
for n in 0..self.samplers {
|
||||
let kind = (self.cmp_samplers >> n & 1) as u32;
|
||||
let ops = vec![
|
||||
Some(i32c(&mut self, n)),
|
||||
Some(self.m.md_value(u)),
|
||||
Some(empty),
|
||||
Some(i32c(&mut self, SAMPLER_SPACE)),
|
||||
Some(i32c(&mut self, n)),
|
||||
Some(i32c(&mut self, 1)),
|
||||
// Sampler kind: 1 comparison.
|
||||
Some(i32c(&mut self, kind)),
|
||||
None,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
bindings.push(Binding {
|
||||
kind: 1,
|
||||
space: SAMPLER_SPACE,
|
||||
register: n,
|
||||
dxil_kind: 14,
|
||||
});
|
||||
}
|
||||
samplers = Some(self.m.md_node(list));
|
||||
}
|
||||
resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers]));
|
||||
// PSV0 lists them as the module does: CBVs, samplers, SRVs.
|
||||
bindings.sort_by_key(|b| match b.kind {
|
||||
2 => 0,
|
||||
1 => 1,
|
||||
_ => 2,
|
||||
});
|
||||
}
|
||||
if let Some(r) = resources {
|
||||
self.m.named_md("dx.resources", vec![r]);
|
||||
}
|
||||
|
||||
let graphics = self.threads.is_none() || self.mesh.is_some();
|
||||
if graphics {
|
||||
// shortcut: every output is declared to depend on every input; the
|
||||
// exact sets need a dependence pass. Drivers read this state.
|
||||
let scalars = |els: &[SigElement]| {
|
||||
els.iter()
|
||||
.filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let (ni, no) = (scalars(&self.inputs), scalars(&self.outputs));
|
||||
let mut view = vec![ni, no];
|
||||
// Mesh shaders have no inputs: then the primitive outputs' count.
|
||||
if self.mesh.is_some() {
|
||||
view.push(scalars(&self.prims));
|
||||
}
|
||||
for _ in 0..ni {
|
||||
for k in 0..no.div_ceil(32) {
|
||||
let bits = (no - 32 * k).min(32);
|
||||
view.push(if bits == 32 {
|
||||
u32::MAX
|
||||
} else {
|
||||
(1 << bits) - 1
|
||||
});
|
||||
}
|
||||
}
|
||||
let arr = self.m.array(view.len() as u32, self.t.i32);
|
||||
let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect();
|
||||
let arr = self.m.aggregate(arr, &elems);
|
||||
let arr = self.m.md_value(arr);
|
||||
let view_node = self.m.md_node(vec![Some(arr)]);
|
||||
self.m.named_md("dx.viewIdState", vec![view_node]);
|
||||
}
|
||||
|
||||
let sigs = if graphics {
|
||||
let ins = self.signature_md(self.inputs.clone());
|
||||
let outs = self.signature_md(self.outputs.clone());
|
||||
let prims = self.signature_md(self.prims.clone());
|
||||
Some(self.m.md_node(vec![ins, outs, prims]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Entry properties: shader flags (tag 0), thread-group size (4),
|
||||
// wave size (11).
|
||||
let mut props = Vec::new();
|
||||
if self.flags != 0 {
|
||||
props.push(i32c(&mut self, 0));
|
||||
let i64t = self.m.int(64);
|
||||
let f = self.m.int_const(i64t, self.flags as i64);
|
||||
props.push(self.m.md_value(f));
|
||||
}
|
||||
if let Some(threads) = self.threads {
|
||||
let t = threads.map(|n| Some(i32c(&mut self, n)));
|
||||
let t = self.m.md_node(t.to_vec());
|
||||
match self.mesh {
|
||||
// Mesh state (tag 9): threads, maximum vertices and
|
||||
// primitives, topology, payload bytes.
|
||||
Some(mesh) => {
|
||||
props.push(i32c(&mut self, 9));
|
||||
let state = [
|
||||
mesh.max_vertices,
|
||||
mesh.max_primitives,
|
||||
mesh.topology.into(),
|
||||
0,
|
||||
]
|
||||
.map(|n| Some(i32c(&mut self, n)));
|
||||
let mut node = vec![Some(t)];
|
||||
node.extend(state);
|
||||
props.push(self.m.md_node(node));
|
||||
}
|
||||
None => {
|
||||
props.push(i32c(&mut self, 4));
|
||||
props.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(n) = self.wave_size {
|
||||
props.push(i32c(&mut self, 11));
|
||||
let n = Some(i32c(&mut self, n));
|
||||
props.push(self.m.md_node(vec![n]));
|
||||
}
|
||||
let props =
|
||||
(!props.is_empty()).then(|| self.m.md_node(props.into_iter().map(Some).collect()));
|
||||
let main = self.m.md_value(self.main);
|
||||
let name = self.m.md_str("main");
|
||||
let entry = self
|
||||
.m
|
||||
.md_node(vec![Some(main), Some(name), sigs, resources, props]);
|
||||
|
||||
let ident = self.m.md_str("victory");
|
||||
let ident = self.m.md_node(vec![Some(ident)]);
|
||||
self.m.named_md("llvm.ident", vec![ident]);
|
||||
let one = i32c(&mut self, 1);
|
||||
let six = i32c(&mut self, 6);
|
||||
let version = self.m.md_node(vec![Some(one), Some(six)]);
|
||||
self.m.named_md("dx.version", vec![version]);
|
||||
self.m.named_md("dx.valver", vec![version]);
|
||||
// Program kinds: 0 pixel, 1 vertex, 5 compute, 13 mesh.
|
||||
let (name, kind) = match (self.threads, self.pixel) {
|
||||
_ if self.mesh.is_some() => ("ms", 13u32),
|
||||
(Some(_), _) => ("cs", 5u32),
|
||||
(None, true) => ("ps", 0),
|
||||
(None, false) => ("vs", 1),
|
||||
};
|
||||
let name = self.m.md_str(name);
|
||||
let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]);
|
||||
self.m.named_md("dx.shaderModel", vec![sm]);
|
||||
self.m.named_md("dx.entryPoints", vec![entry]);
|
||||
|
||||
let bitcode = self.m.write();
|
||||
let mut dxil = Vec::with_capacity(24 + bitcode.len());
|
||||
dxil.extend((kind << 16 | 0x66).to_le_bytes());
|
||||
dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes());
|
||||
dxil.extend(b"DXIL");
|
||||
dxil.extend(0x106u32.to_le_bytes());
|
||||
dxil.extend(16u32.to_le_bytes());
|
||||
dxil.extend((bitcode.len() as u32).to_le_bytes());
|
||||
dxil.extend(&bitcode);
|
||||
|
||||
let mut features = 0u64;
|
||||
if self.flags & flags::TYPED_UAV_LOADS != 0 {
|
||||
features |= 0x800;
|
||||
}
|
||||
if self.flags & flags::WAVE_OPS != 0 {
|
||||
features |= 0x4000;
|
||||
}
|
||||
if self.flags & flags::INT64 != 0 {
|
||||
features |= 0x8000;
|
||||
}
|
||||
if self.flags & flags::RESOURCE_HEAP != 0 {
|
||||
features |= 0x200_0000;
|
||||
}
|
||||
if self.flags & flags::SAMPLER_HEAP != 0 {
|
||||
features |= 0x400_0000;
|
||||
}
|
||||
let sfi0 = features.to_le_bytes();
|
||||
let isg1 = container::signature(&self.inputs, true);
|
||||
let osg1 = container::signature(&self.outputs, false);
|
||||
let flag = if self.pixel {
|
||||
self.outputs.iter().any(|o| (17..=19).contains(&o.kind))
|
||||
} else {
|
||||
self.outputs.iter().any(|o| o.kind == 3)
|
||||
};
|
||||
let psv0 = container::psv(&Psv {
|
||||
stage: kind as u8,
|
||||
flag: flag && self.threads.is_none(),
|
||||
inputs: &self.inputs,
|
||||
outputs: &self.outputs,
|
||||
prims: &self.prims,
|
||||
mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)),
|
||||
bindings: &bindings,
|
||||
threads: self.threads.unwrap_or_default(),
|
||||
wave_size: self.wave_size,
|
||||
});
|
||||
let hash = [0u8; 20];
|
||||
let psg1 = container::signature(&self.prims, false);
|
||||
let mut parts: Vec<(&[u8; 4], &[u8])> =
|
||||
vec![(b"SFI0", &sfi0), (b"ISG1", &isg1), (b"OSG1", &osg1)];
|
||||
if self.mesh.is_some() {
|
||||
parts.push((b"PSG1", &psg1));
|
||||
}
|
||||
parts.extend([(b"PSV0", &psv0[..]), (b"HASH", &hash), (b"DXIL", &dxil)]);
|
||||
container::build(&parts)
|
||||
}
|
||||
|
||||
/// The user-data buffer's annotation carries its size, known only now.
|
||||
fn fix_user_data_size(&mut self, size: u32) {
|
||||
let old = [self.m.i32(13), self.m.i32(u32::MAX)];
|
||||
let old = self.m.aggregate(self.t.props, &old);
|
||||
let new = [self.m.i32(13), self.m.i32(size)];
|
||||
let new = self.m.aggregate(self.t.props, &new);
|
||||
self.m.replace_const(old, new);
|
||||
}
|
||||
|
||||
fn signature_md(&mut self, elements: Vec<SigElement>) -> Option<Md> {
|
||||
if elements.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut list = Vec::new();
|
||||
for (id, e) in elements.iter().enumerate() {
|
||||
let c32 = |s: &mut Self, v: u32| {
|
||||
let c = s.m.i32(v);
|
||||
Some(s.m.md_value(c))
|
||||
};
|
||||
let c8 = |s: &mut Self, v: u8| {
|
||||
let c = s.m.i8(v);
|
||||
Some(s.m.md_value(c))
|
||||
};
|
||||
let idx = c32(self, e.index);
|
||||
let indices = Some(self.m.md_node(vec![idx]));
|
||||
let usage = if e.usage != 0 {
|
||||
let (tag, mask) = (c32(self, 3), c32(self, u32::from(e.usage)));
|
||||
Some(self.m.md_node(vec![tag, mask]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ops = vec![
|
||||
c32(self, id as u32),
|
||||
Some(self.m.md_str(&e.name)),
|
||||
c8(self, e.comp),
|
||||
c8(self, e.kind),
|
||||
indices,
|
||||
c8(self, e.interp),
|
||||
c32(self, 1),
|
||||
c8(self, e.cols),
|
||||
c32(self, e.row.unwrap_or(u32::MAX)),
|
||||
c8(self, if e.row.is_some() { e.col } else { u8::MAX }),
|
||||
usage,
|
||||
];
|
||||
list.push(Some(self.m.md_node(ops)));
|
||||
}
|
||||
Some(self.m.md_node(list))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the
|
||||
//! offline batch. Translated shaders do not need it: they carry the
|
||||
//! container hash we compute ([`super::container::hash`]).
|
||||
//!
|
||||
//! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's
|
||||
//! `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
|
||||
|
||||
type Hresult = i32;
|
||||
|
||||
#[repr(C)]
|
||||
struct Guid(u32, u16, u16, [u8; 8]);
|
||||
|
||||
const CLSID_DXC_VALIDATOR: Guid = Guid(
|
||||
0x8ca3_e215,
|
||||
0xf728,
|
||||
0x4cf3,
|
||||
[0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1],
|
||||
);
|
||||
const IID_IDXC_VALIDATOR: Guid = Guid(
|
||||
0xa6e8_2bd2,
|
||||
0x1fd7,
|
||||
0x4826,
|
||||
[0x98, 0x11, 0x28, 0x57, 0xe7, 0x97, 0xf4, 0x9a],
|
||||
);
|
||||
/// `DxcValidatorFlags_InPlaceEdit`: sign the container we pass.
|
||||
const IN_PLACE_EDIT: u32 = 1;
|
||||
|
||||
type CreateInstance =
|
||||
unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult;
|
||||
|
||||
/// COM object: a pointer to a table of method pointers.
|
||||
type Object = *mut *const usize;
|
||||
|
||||
unsafe fn method<F: Copy>(obj: Object, slot: usize) -> F {
|
||||
// SAFETY: the caller names a slot of the object's interface.
|
||||
unsafe { std::mem::transmute_copy(&*(*obj).add(slot)) }
|
||||
}
|
||||
|
||||
unsafe fn release(obj: Object) {
|
||||
if !obj.is_null() {
|
||||
// SAFETY: slot 2 of every COM interface is Release.
|
||||
unsafe { method::<unsafe extern "system" fn(Object) -> u32>(obj, 2)(obj) };
|
||||
}
|
||||
}
|
||||
|
||||
/// An `IDxcBlob` over our bytes: QueryInterface, AddRef, Release,
|
||||
/// GetBufferPointer, GetBufferSize. Lives on the caller's stack.
|
||||
#[repr(C)]
|
||||
struct Blob {
|
||||
vtable: *const BlobVtable,
|
||||
data: *mut u8,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
/// IUnknown and IDxcBlob, as raw GUID bytes.
|
||||
const IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
|
||||
const IDXC_BLOB: [u8; 16] = [
|
||||
0x08, 0xfb, 0xa5, 0x8b, 0x95, 0x51, 0xe2, 0x40, 0xac, 0x58, 0x0d, 0x98, 0x9c, 0x3a, 0x01, 0x02,
|
||||
];
|
||||
|
||||
unsafe extern "system" fn blob_qi(
|
||||
this: *mut Blob,
|
||||
iid: *const [u8; 16],
|
||||
out: *mut *mut c_void,
|
||||
) -> Hresult {
|
||||
// SAFETY: the validator passes valid pointers.
|
||||
unsafe {
|
||||
if *iid == IUNKNOWN || *iid == IDXC_BLOB {
|
||||
*out = this.cast();
|
||||
0
|
||||
} else {
|
||||
*out = std::ptr::null_mut();
|
||||
0x8000_4002_u32 as i32 // E_NOINTERFACE
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe extern "system" fn blob_ref(_: *mut Blob) -> u32 {
|
||||
1
|
||||
}
|
||||
unsafe extern "system" fn blob_ptr(this: *mut Blob) -> *mut u8 {
|
||||
// SAFETY: `this` is our blob.
|
||||
unsafe { (*this).data }
|
||||
}
|
||||
unsafe extern "system" fn blob_len(this: *mut Blob) -> usize {
|
||||
// SAFETY: `this` is our blob.
|
||||
unsafe { (*this).len }
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct BlobVtable {
|
||||
qi: unsafe extern "system" fn(*mut Blob, *const [u8; 16], *mut *mut c_void) -> Hresult,
|
||||
add_ref: unsafe extern "system" fn(*mut Blob) -> u32,
|
||||
release: unsafe extern "system" fn(*mut Blob) -> u32,
|
||||
ptr: unsafe extern "system" fn(*mut Blob) -> *mut u8,
|
||||
len: unsafe extern "system" fn(*mut Blob) -> usize,
|
||||
}
|
||||
|
||||
static BLOB_VTABLE: BlobVtable = BlobVtable {
|
||||
qi: blob_qi,
|
||||
add_ref: blob_ref,
|
||||
release: blob_ref,
|
||||
ptr: blob_ptr,
|
||||
len: blob_len,
|
||||
};
|
||||
|
||||
pub struct Validator {
|
||||
object: Object,
|
||||
}
|
||||
|
||||
// SAFETY: the validator object is free-threaded (DXC's validator has no
|
||||
// thread affinity); calls are serialised by `&mut self`.
|
||||
unsafe impl Send for Validator {}
|
||||
|
||||
impl Validator {
|
||||
/// Where `dxil.dll` is looked for.
|
||||
pub fn default_path() -> Option<PathBuf> {
|
||||
if let Some(p) = std::env::var_os("VICTORY_DXIL") {
|
||||
return Some(p.into());
|
||||
}
|
||||
let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin");
|
||||
let mut versions: Vec<PathBuf> = std::fs::read_dir(&kits)
|
||||
.ok()?
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.path().join(r"x64\dxil.dll"))
|
||||
.filter(|p| p.exists())
|
||||
.collect();
|
||||
versions.sort();
|
||||
versions.pop()
|
||||
}
|
||||
|
||||
/// Loads `path`'s validator (or `dxil.dll` from the DLL search path).
|
||||
pub fn load(path: Option<&std::path::Path>) -> Result<Self, String> {
|
||||
let name: Vec<u16> = path
|
||||
.map_or_else(|| "dxil.dll".into(), |p| p.as_os_str().to_owned())
|
||||
.to_string_lossy()
|
||||
.encode_utf16()
|
||||
.chain([0])
|
||||
.collect();
|
||||
// SAFETY: plain Win32 calls with a NUL-terminated name.
|
||||
unsafe {
|
||||
let module = LoadLibraryW(name.as_ptr());
|
||||
if module.is_null() {
|
||||
return Err(format!("cannot load {}", String::from_utf16_lossy(&name)));
|
||||
}
|
||||
let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast())
|
||||
.ok_or("dxil.dll lacks DxcCreateInstance")?;
|
||||
let create: CreateInstance = std::mem::transmute(create);
|
||||
let mut object = std::ptr::null_mut();
|
||||
let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object);
|
||||
if hr < 0 || object.is_null() {
|
||||
return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}"));
|
||||
}
|
||||
Ok(Validator {
|
||||
object: object.cast(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates `container` and signs it in place; the error text if it
|
||||
/// is rejected.
|
||||
pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> {
|
||||
let mut blob = Blob {
|
||||
vtable: &BLOB_VTABLE,
|
||||
data: container.as_mut_ptr(),
|
||||
len: container.len(),
|
||||
};
|
||||
// SAFETY: IDxcValidator::Validate (slot 3) with our blob; then
|
||||
// IDxcOperationResult GetStatus (3) and GetErrorBuffer (5), and
|
||||
// IDxcBlob GetBufferPointer (3) / GetBufferSize (4).
|
||||
unsafe {
|
||||
let mut result: Object = std::ptr::null_mut();
|
||||
let validate: unsafe extern "system" fn(
|
||||
Object,
|
||||
*mut Blob,
|
||||
u32,
|
||||
*mut Object,
|
||||
) -> Hresult = method(self.object, 3);
|
||||
let hr = validate(self.object, &mut blob, IN_PLACE_EDIT, &mut result);
|
||||
if hr < 0 || result.is_null() {
|
||||
return Err(format!("Validate failed: {hr:#x}"));
|
||||
}
|
||||
let mut status = 0;
|
||||
let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult =
|
||||
method(result, 3);
|
||||
get_status(result, &mut status);
|
||||
let mut text = String::new();
|
||||
if status < 0 {
|
||||
let mut errors: Object = std::ptr::null_mut();
|
||||
let get_errors: unsafe extern "system" fn(Object, *mut Object) -> Hresult =
|
||||
method(result, 5);
|
||||
if get_errors(result, &mut errors) >= 0 && !errors.is_null() {
|
||||
let ptr: unsafe extern "system" fn(Object) -> *const u8 = method(errors, 3);
|
||||
let len: unsafe extern "system" fn(Object) -> usize = method(errors, 4);
|
||||
let bytes = std::slice::from_raw_parts(ptr(errors), len(errors));
|
||||
text = String::from_utf8_lossy(bytes)
|
||||
.trim_end_matches('\0')
|
||||
.trim()
|
||||
.into();
|
||||
release(errors);
|
||||
}
|
||||
if text.is_empty() {
|
||||
text = format!("rejected ({status:#x})");
|
||||
}
|
||||
}
|
||||
release(result);
|
||||
if status < 0 { Err(text) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Validator {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: we own one reference.
|
||||
unsafe { release(self.object) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,679 @@
|
||||
//! Whole-wave sections (decision 0003): code between `s_or_saveexec -1`
|
||||
//! (or `s_nand_saveexec 0`) and the restore of the saved mask runs in every lane of the console's
|
||||
//! wave, the inactive ones included, which is how the compiler expands
|
||||
//! HLSL wave reductions and prefix sums (an identity put into the inactive
|
||||
//! lanes with `v_cndmask`, then DPP, `v_permlanex16` and `v_readlane`
|
||||
//! steps). A host lane that is elsewhere cannot run that code, so each
|
||||
//! section is simulated on the console's lanes with symbolic values, and a
|
||||
//! value it leaves is lowered by what it turned out to be: the reduction or
|
||||
//! prefix of one operation over the lanes' (masked) inputs, which DXIL's
|
||||
//! wave operations compute over the host's active lanes. No instruction
|
||||
//! sequence is matched; any step the simulation does not model leaves the
|
||||
//! values it writes unknown.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::gfx10::{Dpp, Fields, NULL, Operand};
|
||||
use crate::ir::{EXEC, Inst, Program, Reg, Value};
|
||||
|
||||
/// An associative operation and its identity.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Op {
|
||||
AddU,
|
||||
AddF,
|
||||
MinU,
|
||||
MaxU,
|
||||
MinI,
|
||||
MaxI,
|
||||
MinF,
|
||||
MaxF,
|
||||
Or,
|
||||
And,
|
||||
Xor,
|
||||
}
|
||||
|
||||
impl Op {
|
||||
fn of(name: &str) -> Option<Op> {
|
||||
Some(match name {
|
||||
"v_add_nc_u32" => Op::AddU,
|
||||
"v_add_f32" => Op::AddF,
|
||||
"v_min_u32" => Op::MinU,
|
||||
"v_max_u32" => Op::MaxU,
|
||||
"v_min_i32" => Op::MinI,
|
||||
"v_max_i32" => Op::MaxI,
|
||||
"v_min_f32" => Op::MinF,
|
||||
"v_max_f32" => Op::MaxF,
|
||||
"v_or_b32" => Op::Or,
|
||||
"v_and_b32" => Op::And,
|
||||
"v_xor_b32" => Op::Xor,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `k` leaves the other operand unchanged.
|
||||
fn identity(self, k: u32) -> bool {
|
||||
match self {
|
||||
Op::AddU | Op::Or | Op::Xor | Op::MaxU => k == 0,
|
||||
Op::AddF => k == 0 || k == 0x8000_0000,
|
||||
Op::MinU | Op::And => k == u32::MAX,
|
||||
Op::MinI => k == 0x7FFF_FFFF,
|
||||
Op::MaxI => k == 0x8000_0000,
|
||||
Op::MinF => k == 0x7F80_0000,
|
||||
Op::MaxF => k == 0xFF80_0000,
|
||||
}
|
||||
}
|
||||
|
||||
/// Counting a lane twice changes the result.
|
||||
fn counts(self) -> bool {
|
||||
matches!(self, Op::AddU | Op::AddF | Op::Xor)
|
||||
}
|
||||
}
|
||||
|
||||
/// A lane's value inside a section.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Sym {
|
||||
Unknown,
|
||||
K(u32),
|
||||
/// The lane's own value of a VGPR value from before the section.
|
||||
Own(Value),
|
||||
/// A uniform value from before the section.
|
||||
Uni(Value),
|
||||
/// `op` over `lanes` of `mask ? src : ident` (`op` none: one lane).
|
||||
Red {
|
||||
op: Option<Op>,
|
||||
src: Value,
|
||||
mask: Value,
|
||||
ident: u32,
|
||||
lanes: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// What a value a section leaves holds in every lane.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Shape {
|
||||
K(u32),
|
||||
Value(Value),
|
||||
/// The lane's own `mask ? src : ident`.
|
||||
Masked(Value, Value, u32),
|
||||
/// `op` over every lane.
|
||||
Active(Op, Value, Value, u32),
|
||||
/// `op` over the lanes below (`inclusive`: and including) each lane.
|
||||
Prefix(Op, Value, Value, u32, bool),
|
||||
}
|
||||
|
||||
/// The section starting at instruction `start` of a block: its restore
|
||||
/// index and the shapes of the values it writes.
|
||||
pub(crate) struct Section {
|
||||
pub end: usize,
|
||||
pub shapes: HashMap<Value, Shape>,
|
||||
}
|
||||
|
||||
/// Every whole-wave section of `block`, by start index.
|
||||
pub(crate) fn sections(p: &Program, block: usize) -> HashMap<usize, Section> {
|
||||
let insts = &p.blocks[block].insts;
|
||||
let wave: u32 = if p.wave64 { 64 } else { 32 };
|
||||
let mut out = HashMap::new();
|
||||
let mut i = 0;
|
||||
while i < insts.len() {
|
||||
let inst = &insts[i];
|
||||
// EXEC becomes every lane: `s_or_saveexec -1` or `s_nand_saveexec 0`.
|
||||
let all = match inst.name() {
|
||||
"s_or_saveexec_b64" | "s_or_saveexec_b32" => Some(Operand::Const(193)),
|
||||
"s_nand_saveexec_b64" | "s_nand_saveexec_b32" => Some(Operand::Const(128)),
|
||||
_ => None,
|
||||
};
|
||||
let start = all.is_some_and(
|
||||
|k| matches!(&inst.fields, Fields::Sop { src, .. } if src.first() == Some(&k)),
|
||||
);
|
||||
let saved = match &inst.fields {
|
||||
Fields::Sop {
|
||||
dst: Some(Operand::Scalar { code, .. }),
|
||||
..
|
||||
} if start => inst.write(Reg::S(*code)),
|
||||
_ => None,
|
||||
};
|
||||
let Some(saved) = saved else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
let end = (i + 1..insts.len()).find(|&j| {
|
||||
insts[j].write(Reg::S(EXEC)).is_some()
|
||||
&& insts[j].read(Reg::S(saved_code(inst))) == Some(saved)
|
||||
});
|
||||
let Some(end) = end else {
|
||||
break;
|
||||
};
|
||||
let shapes = simulate(&insts[i + 1..end], wave, saved);
|
||||
out.insert(i, Section { end, shapes });
|
||||
i = end + 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn saved_code(inst: &Inst) -> u8 {
|
||||
match &inst.fields {
|
||||
Fields::Sop {
|
||||
dst: Some(Operand::Scalar { code, .. }),
|
||||
..
|
||||
} => *code,
|
||||
_ => NULL,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lane `l` reads with DPP, whether it reads 0 instead, and whether it
|
||||
/// writes; `None` for patterns not modelled.
|
||||
fn dpp_lane(d: Dpp, l: u32) -> Option<(u32, bool, bool)> {
|
||||
match d {
|
||||
Dpp::Lanes { sel, .. } => Some(((l & !7) | (sel >> (3 * (l & 7)) & 7), false, true)),
|
||||
Dpp::Row {
|
||||
ctrl,
|
||||
row_mask,
|
||||
bank_mask,
|
||||
bound_ctrl,
|
||||
..
|
||||
} => {
|
||||
let (row, pos, n) = (l & !15, l & 15, u32::from(ctrl & 15));
|
||||
let enabled = row_mask >> (l >> 4 & 3) & 1 != 0 && bank_mask >> (l >> 2 & 3) & 1 != 0;
|
||||
let (src, inside) = match ctrl {
|
||||
0..=0xFF => ((l & !3) | (u32::from(ctrl) >> (2 * (l & 3)) & 3), true),
|
||||
0x101..=0x10F => (l + n, pos + n < 16),
|
||||
0x111..=0x11F => (l.wrapping_sub(n), pos >= n),
|
||||
0x121..=0x12F => (row | (pos.wrapping_sub(n) & 15), true),
|
||||
0x140 => (l ^ 15, true),
|
||||
0x141 => (l ^ 7, true),
|
||||
0x150..=0x15F => (row | n, true),
|
||||
0x160..=0x16F => (l ^ n, true),
|
||||
_ => return None,
|
||||
};
|
||||
match (inside, bound_ctrl) {
|
||||
(true, _) => Some((src, false, enabled)),
|
||||
(false, true) => Some((l, true, enabled)),
|
||||
(false, false) => Some((l, false, false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn combine(op: Op, a: Sym, b: Sym) -> Sym {
|
||||
match (a, b) {
|
||||
(Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) => x,
|
||||
(
|
||||
Sym::Red {
|
||||
op: oa,
|
||||
src,
|
||||
mask,
|
||||
ident,
|
||||
lanes: la,
|
||||
},
|
||||
Sym::Red {
|
||||
op: ob,
|
||||
src: sb,
|
||||
mask: mb,
|
||||
ident: ib,
|
||||
lanes: lb,
|
||||
},
|
||||
) if (src, mask, ident) == (sb, mb, ib)
|
||||
&& op.identity(ident)
|
||||
&& oa.is_none_or(|o| o == op)
|
||||
&& ob.is_none_or(|o| o == op)
|
||||
&& (!op.counts() || la & lb == 0) =>
|
||||
{
|
||||
Sym::Red {
|
||||
op: Some(op),
|
||||
src,
|
||||
mask,
|
||||
ident,
|
||||
lanes: la | lb,
|
||||
}
|
||||
}
|
||||
_ => Sym::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
let all = if wave == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
u64::from(u32::MAX)
|
||||
};
|
||||
let mut exec = all;
|
||||
let mut vec: HashMap<Value, Vec<Sym>> = HashMap::new();
|
||||
let mut uni: HashMap<Value, Sym> = HashMap::new();
|
||||
// Masks the section derives from the saved EXEC (`s_and` with it).
|
||||
let mut masked = vec![saved];
|
||||
for inst in insts {
|
||||
let name = inst.name();
|
||||
if inst.write(Reg::S(EXEC)).is_some() {
|
||||
// Constant lane sets (prefix sums); anything else ends what
|
||||
// the simulation can follow.
|
||||
let lo = name
|
||||
.starts_with("s_mov_b")
|
||||
.then(|| constant(inst))
|
||||
.flatten();
|
||||
let Some(k) = lo else {
|
||||
return shapes(vec, uni, wave);
|
||||
};
|
||||
exec = if name == "s_mov_b64" {
|
||||
k
|
||||
} else {
|
||||
exec & !0xFFFF_FFFF | k & 0xFFFF_FFFF
|
||||
};
|
||||
continue;
|
||||
}
|
||||
if inst.write(Reg::S(EXEC + 1)).is_some() {
|
||||
let Some(k) = name
|
||||
.starts_with("s_mov_b")
|
||||
.then(|| constant(inst))
|
||||
.flatten()
|
||||
else {
|
||||
return shapes(vec, uni, wave);
|
||||
};
|
||||
exec = exec & 0xFFFF_FFFF | k << 32;
|
||||
continue;
|
||||
}
|
||||
if let Fields::Sop { src, .. } = &inst.fields {
|
||||
if name.starts_with("s_and_b")
|
||||
&& src.iter().any(|o| matches!(*o, Operand::Scalar { code, .. } if inst.read(Reg::S(code)).is_some_and(|v| masked.contains(&v))))
|
||||
&& let Some(&(_, w)) = inst.writes.iter().find(|w| matches!(w.0, Reg::S(_)))
|
||||
{
|
||||
masked.push(w);
|
||||
}
|
||||
for &(_, w) in &inst.writes {
|
||||
uni.entry(w).or_insert(Sym::Unknown);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Fields::Valu(v) = &inst.fields else {
|
||||
for &(_, w) in &inst.writes {
|
||||
vec.insert(w, vec![Sym::Unknown; wave as usize]);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let lanes = |op: &Operand,
|
||||
vec: &HashMap<Value, Vec<Sym>>,
|
||||
uni: &HashMap<Value, Sym>|
|
||||
-> Vec<Sym> {
|
||||
let one = |s: Sym| vec![s; wave as usize];
|
||||
match *op {
|
||||
Operand::Vector { reg, .. } => match inst.read(Reg::V(reg)) {
|
||||
Some(x) => vec
|
||||
.get(&x)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| (0..wave).map(|_| Sym::Own(x)).collect()),
|
||||
None => one(Sym::Unknown),
|
||||
},
|
||||
Operand::Scalar { code, .. } if code != NULL => match inst.read(Reg::S(code)) {
|
||||
Some(x) => one(uni.get(&x).copied().unwrap_or(Sym::Uni(x))),
|
||||
None => one(Sym::Unknown),
|
||||
},
|
||||
Operand::Const(c) => one(crate::resource::inline(c).map_or(Sym::Unknown, Sym::K)),
|
||||
Operand::Literal(x) => one(Sym::K(x)),
|
||||
_ => one(Sym::Unknown),
|
||||
}
|
||||
};
|
||||
let modifiers = v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some();
|
||||
if name == "v_readlane_b32" {
|
||||
let (Some(Operand::Scalar { code, .. }), Some(src), Some(lane)) =
|
||||
(v.dst, v.src.first(), v.src.get(1))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let l = match *lane {
|
||||
Operand::Const(c) => crate::resource::inline(c),
|
||||
Operand::Literal(x) => Some(x),
|
||||
_ => None,
|
||||
};
|
||||
let x = lanes(src, &vec, &uni);
|
||||
if let Some(w) = inst.write(Reg::S(code)) {
|
||||
let s = l
|
||||
.and_then(|l| x.get(l as usize).copied())
|
||||
.unwrap_or(Sym::Unknown);
|
||||
uni.insert(w, s);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(Operand::Vector { reg: dreg, .. }) = v.dst else {
|
||||
for &(_, w) in &inst.writes {
|
||||
uni.insert(w, Sym::Unknown);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let Some(dst) = inst.write(Reg::V(dreg)) else {
|
||||
continue;
|
||||
};
|
||||
let old = lanes(
|
||||
&Operand::Vector {
|
||||
reg: dreg,
|
||||
dwords: 1,
|
||||
},
|
||||
&vec,
|
||||
&uni,
|
||||
);
|
||||
// src0 as each lane fetches it (DPP), with the lanes that write.
|
||||
let src0 = v.src.first().map(|o| lanes(o, &vec, &uni));
|
||||
let mut writes = exec;
|
||||
let fetched: Option<Vec<Sym>> = match (v.dpp, &src0) {
|
||||
(Some(d), Some(s)) => {
|
||||
if exec != all {
|
||||
vec.insert(dst, vec![Sym::Unknown; wave as usize]);
|
||||
continue;
|
||||
}
|
||||
let mut f = Vec::with_capacity(wave as usize);
|
||||
let mut ok = true;
|
||||
for l in 0..wave {
|
||||
match dpp_lane(d, l) {
|
||||
Some((src, zero, on)) if src < wave => {
|
||||
f.push(if zero { Sym::K(0) } else { s[src as usize] });
|
||||
if !on {
|
||||
writes &= !(1u64 << l);
|
||||
}
|
||||
}
|
||||
_ => ok = false,
|
||||
}
|
||||
}
|
||||
ok.then_some(f)
|
||||
}
|
||||
(None, Some(s)) => Some(s.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let src = |k: usize| v.src.get(k).map(|o| lanes(o, &vec, &uni));
|
||||
let result: Vec<Sym> = match (name, fetched) {
|
||||
_ if modifiers => vec![Sym::Unknown; wave as usize],
|
||||
("v_mov_b32", Some(a)) => a,
|
||||
("v_bfrev_b32", Some(a)) => a
|
||||
.into_iter()
|
||||
.map(|s| match s {
|
||||
Sym::K(k) => Sym::K(k.reverse_bits()),
|
||||
_ => Sym::Unknown,
|
||||
})
|
||||
.collect(),
|
||||
("v_cndmask_b32", Some(a)) => {
|
||||
let mask = match v.src.get(2) {
|
||||
Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)),
|
||||
_ => None,
|
||||
};
|
||||
let b = src(1).unwrap_or_default();
|
||||
(0..wave as usize)
|
||||
.map(|l| match (a[l], b.get(l).copied(), mask) {
|
||||
(Sym::K(ident), Some(Sym::Own(x)), Some(m)) if masked.contains(&m) => {
|
||||
Sym::Red {
|
||||
op: None,
|
||||
src: x,
|
||||
mask: m,
|
||||
ident,
|
||||
lanes: 1 << l,
|
||||
}
|
||||
}
|
||||
_ => Sym::Unknown,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
("v_permlanex16_b32", Some(a)) => {
|
||||
// Lanes of each row read the other row of their half; lane
|
||||
// i's pick is nibble i of {src2, src1}.
|
||||
let sel = |k: usize| match v.src.get(k) {
|
||||
Some(&Operand::Const(c)) => crate::resource::inline(c),
|
||||
Some(&Operand::Literal(x)) => Some(x),
|
||||
_ => None,
|
||||
};
|
||||
match (sel(1), sel(2)) {
|
||||
(Some(s1), Some(s2)) => {
|
||||
let s = u64::from(s1) | u64::from(s2) << 32;
|
||||
(0..wave)
|
||||
.map(|l| {
|
||||
let other = (l & !31) | ((l & 16) ^ 16);
|
||||
let pick = (s >> (4 * (l & 15)) & 15) as u32;
|
||||
a[(other | pick) as usize]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
_ => vec![Sym::Unknown; wave as usize],
|
||||
}
|
||||
}
|
||||
("v_sub_nc_u32", Some(a)) => {
|
||||
// A prefix sum less the lane's own term: the exclusive one.
|
||||
let b = src(1).unwrap_or_default();
|
||||
(0..wave as usize)
|
||||
.map(|l| match (a[l], b.get(l).copied()) {
|
||||
(
|
||||
Sym::Red {
|
||||
op: None | Some(Op::AddU),
|
||||
src,
|
||||
mask,
|
||||
ident: 0,
|
||||
lanes,
|
||||
},
|
||||
Some(Sym::Red {
|
||||
op: None | Some(Op::AddU),
|
||||
src: s2,
|
||||
mask: m2,
|
||||
ident: 0,
|
||||
lanes: l2,
|
||||
}),
|
||||
) if (src, mask) == (s2, m2) && lanes & l2 == l2 => {
|
||||
let rest = lanes & !l2;
|
||||
if rest == 0 {
|
||||
Sym::K(0)
|
||||
} else {
|
||||
Sym::Red {
|
||||
op: Some(Op::AddU),
|
||||
src,
|
||||
mask,
|
||||
ident: 0,
|
||||
lanes: rest,
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Sym::Unknown,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
(n, Some(a)) => match (Op::of(n), src(1)) {
|
||||
(Some(op), Some(b)) => (0..wave as usize)
|
||||
.map(|l| combine(op, a[l], b[l]))
|
||||
.collect(),
|
||||
_ => vec![Sym::Unknown; wave as usize],
|
||||
},
|
||||
_ => vec![Sym::Unknown; wave as usize],
|
||||
};
|
||||
let merged = (0..wave as usize)
|
||||
.map(|l| {
|
||||
if writes >> l & 1 != 0 {
|
||||
result[l]
|
||||
} else {
|
||||
old[l]
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
vec.insert(dst, merged);
|
||||
}
|
||||
shapes(vec, uni, wave)
|
||||
}
|
||||
|
||||
fn constant(inst: &Inst) -> Option<u64> {
|
||||
let Fields::Sop { src, .. } = &inst.fields else {
|
||||
return None;
|
||||
};
|
||||
match *src.first()? {
|
||||
Operand::Const(c) => {
|
||||
let x = crate::resource::inline(c)?;
|
||||
Some(if (x as i32) < 0 {
|
||||
u64::MAX
|
||||
} else {
|
||||
u64::from(x)
|
||||
})
|
||||
}
|
||||
Operand::Literal(x) => Some(u64::from(x)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape of each value, where every lane agrees on one.
|
||||
fn shapes(
|
||||
vec: HashMap<Value, Vec<Sym>>,
|
||||
uni: HashMap<Value, Sym>,
|
||||
wave: u32,
|
||||
) -> HashMap<Value, Shape> {
|
||||
let all = if wave == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
u64::from(u32::MAX)
|
||||
};
|
||||
let mut out = HashMap::new();
|
||||
let single = |s: Sym| match s {
|
||||
Sym::K(k) => Some(Shape::K(k)),
|
||||
Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)),
|
||||
Sym::Red {
|
||||
op: Some(op),
|
||||
src,
|
||||
mask,
|
||||
ident,
|
||||
lanes,
|
||||
} if lanes == all => Some(Shape::Active(op, src, mask, ident)),
|
||||
_ => None,
|
||||
};
|
||||
for (v, s) in uni {
|
||||
if let Some(sh) = single(s) {
|
||||
out.insert(v, sh);
|
||||
}
|
||||
}
|
||||
for (v, lanes) in vec {
|
||||
if let Some(sh) = per_lane(&lanes, all) {
|
||||
out.insert(v, sh);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
|
||||
let first = lanes[0];
|
||||
let own = |l: usize, s: Sym| match s {
|
||||
Sym::Red {
|
||||
op: None,
|
||||
src,
|
||||
mask,
|
||||
ident,
|
||||
lanes,
|
||||
} if lanes == 1 << l => Some((src, mask, ident)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(m) = own(0, first)
|
||||
&& lanes.iter().enumerate().all(|(l, &s)| own(l, s) == Some(m))
|
||||
{
|
||||
return Some(Shape::Masked(m.0, m.1, m.2));
|
||||
}
|
||||
if lanes.iter().all(|&s| s == first) {
|
||||
return match first {
|
||||
Sym::K(k) => Some(Shape::K(k)),
|
||||
Sym::Uni(x) | Sym::Own(x) => Some(Shape::Value(x)),
|
||||
Sym::Red {
|
||||
op: Some(op),
|
||||
src,
|
||||
mask,
|
||||
ident,
|
||||
lanes,
|
||||
} if lanes == all => Some(Shape::Active(op, src, mask, ident)),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
// Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive).
|
||||
let mut found: Option<(Op, Value, Value, u32, bool)> = None;
|
||||
for (l, &s) in lanes.iter().enumerate() {
|
||||
let below = (1u64 << l) - 1;
|
||||
let (op, src, mask, ident, set) = match s {
|
||||
Sym::Red {
|
||||
op,
|
||||
src,
|
||||
mask,
|
||||
ident,
|
||||
lanes,
|
||||
} => (op, src, mask, ident, lanes),
|
||||
// Lane 0 of an exclusive prefix holds the identity.
|
||||
Sym::K(_) if l == 0 => continue,
|
||||
_ => return None,
|
||||
};
|
||||
let inclusive = set == below | 1 << l;
|
||||
if !inclusive && set != below {
|
||||
return None;
|
||||
}
|
||||
let op = match (op, found) {
|
||||
(Some(o), _) => o,
|
||||
(None, Some(f)) => f.0,
|
||||
(None, None) => continue,
|
||||
};
|
||||
let me = (op, src, mask, ident, inclusive);
|
||||
match found {
|
||||
None => found = Some(me),
|
||||
Some(f) if f == me => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
let (op, src, mask, ident, inclusive) = found?;
|
||||
if let Sym::K(k) = lanes[0]
|
||||
&& (inclusive || k != ident)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(Shape::Prefix(op, src, mask, ident, inclusive))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dpp_lanes_follow_the_isa() {
|
||||
// row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16.
|
||||
let shr = Dpp::Row {
|
||||
ctrl: 0x111,
|
||||
row_mask: 0xF,
|
||||
bank_mask: 0xF,
|
||||
bound_ctrl: true,
|
||||
fi: false,
|
||||
};
|
||||
assert_eq!(dpp_lane(shr, 16), Some((16, true, true)));
|
||||
assert_eq!(dpp_lane(shr, 17), Some((16, false, true)));
|
||||
// row_mirror: lane 3 reads lane 12.
|
||||
let mirror = Dpp::Row {
|
||||
ctrl: 0x140,
|
||||
row_mask: 0xF,
|
||||
bank_mask: 0xF,
|
||||
bound_ctrl: true,
|
||||
fi: false,
|
||||
};
|
||||
assert_eq!(dpp_lane(mirror, 3), Some((12, false, true)));
|
||||
// dpp8 [1,0,3,2,5,4,7,6] swaps neighbours.
|
||||
let swap = Dpp::Lanes {
|
||||
sel: 1 | 3 << 6 | 2 << 9 | 5 << 12 | 4 << 15 | 7 << 18 | 6 << 21,
|
||||
fi: false,
|
||||
};
|
||||
assert_eq!(dpp_lane(swap, 8), Some((9, false, true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefixes_are_recognised() {
|
||||
let (x, m) = (Value(1), Value(2));
|
||||
let red = |lanes: u64| Sym::Red {
|
||||
op: Some(Op::AddU),
|
||||
src: x,
|
||||
mask: m,
|
||||
ident: 0,
|
||||
lanes,
|
||||
};
|
||||
let inclusive: Vec<Sym> = (0..64).map(|l| red(u64::MAX >> (63 - l))).collect();
|
||||
assert_eq!(
|
||||
per_lane(&inclusive, u64::MAX),
|
||||
Some(Shape::Prefix(Op::AddU, x, m, 0, true))
|
||||
);
|
||||
let mut exclusive: Vec<Sym> = (0..64).map(|l| red((1u64 << l) - 1)).collect();
|
||||
exclusive[0] = Sym::K(0);
|
||||
assert_eq!(
|
||||
per_lane(&exclusive, u64::MAX),
|
||||
Some(Shape::Prefix(Op::AddU, x, m, 0, false))
|
||||
);
|
||||
assert_eq!(
|
||||
per_lane(&vec![red(u64::MAX); 64], u64::MAX),
|
||||
Some(Shape::Active(Op::AddU, x, m, 0))
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user