Only changed dwords go back into title memory; cheap safe copies; title's own arguments; more shader forms

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 20:28:42 -06:00
1 parent d9a31188be
commit 7fa012814f
16 files changed
+973 -29

No files matched your search

+2
View File
@@ -17,6 +17,8 @@ pub struct FourCC(pub [u8; 4]);
impl FourCC {
pub const DXIL: FourCC = FourCC(*b"DXIL");
/// Native code another compiler made, in place of `DXIL` (VIctory upstream 0b35b7f).
pub const ACCC: FourCC = FourCC(*b"ACCC");
pub const STAT: FourCC = FourCC(*b"STAT");
pub const RTS0: FourCC = FourCC(*b"RTS0");
pub const PSV0: FourCC = FourCC(*b"PSV0");
+93 -3
View File
@@ -3110,6 +3110,12 @@ impl<'a> Lower<'a> {
let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
self.i32_of(v)
}
// src_scc: SCC as 0 or 1 (VIctory upstream 0b35b7f, as the dot
// products and packed multiply-adds below).
Operand::Const(253) => {
let bit = self.scc_in(inst)?;
Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32))
}
Operand::Const(c) => crate::resource::inline(c)
.map(|x| self.s.m.i32(x))
.ok_or("a special operand (vccz, execz, scc, lds_direct)"),
@@ -6955,6 +6961,61 @@ impl<'a> Lower<'a> {
.op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
int(self, r)
}
"v_dot4c_i32_i8" => {
// D += the dot product of four signed bytes, wrapping: DXIL's
// Dot4AddI8Packed.
let (a, bb) = (s(self, 0)?, s(self, 1)?);
let Some(Operand::Vector { reg, .. }) = v.dst else {
return Err("an accumulator");
};
let acc = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
let i32_ty = self.s.t.i32;
let r = self.s.op(
c,
"dot4AddPacked.i32",
Attr::ReadNone,
i32_ty,
163,
&[acc, a, bb],
);
int(self, r)
}
"v_dot4_i32_i8" => {
// VOP3P: op_sel picks the half each multiplicand's low half
// reads, op_sel_hi its high half's; the accumulator is read
// whole (as AMD's compilers fold constants into it).
if v.clamp || v.neg_hi != 0 {
return Err("a saturating or negated dot product");
}
let mut xs = Vec::new();
for k in 0..2 {
let x = s(self, k)?;
let (lo, hi) = (v.opsel >> k & 1 != 0, v.opsel_hi >> k & 1 != 0);
if (lo, hi) == (false, true) {
xs.push(x);
continue;
}
let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
let top = self.s.m.bin(c, Bin::LShr, x, k16);
let bottom = self.s.m.bin(c, Bin::And, x, low);
let hi = self
.s
.m
.bin(c, Bin::Shl, if hi { top } else { bottom }, k16);
xs.push(self.s.m.bin(c, Bin::Or, if lo { top } else { bottom }, hi));
}
let acc = s(self, 2)?;
let i32_ty = self.s.t.i32;
let r = self.s.op(
c,
"dot4AddPacked.i32",
Attr::ReadNone,
i32_ty,
163,
&[acc, xs[0], xs[1]],
);
int(self, r)
}
"v_mov_b32" => {
if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
let a = f(self, 0)?;
@@ -8411,6 +8472,30 @@ impl<'a> Lower<'a> {
Ok(self.s.m.bin(c, Bin::And, x, m))
}
/// Half `high` of source `k` of `v_pk_fmac_f16`, in the low 16 bits: a
/// VOP2 operation (no op_sel) whose third source is its destination.
fn fmac_half(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
let Fields::Valu(v) = &inst.fields else {
unreachable!()
};
let op = if k == 2 { v.dst } else { v.src.get(k).copied() };
let op = op.ok_or("a missing operand")?;
if matches!(op, Operand::Const(_) | Operand::Literal(_)) {
// shortcut: no constant operand seen; its high half is not known.
return Err("a constant operand of v_pk_fmac_f16");
}
let x = self.operand(inst, &op)?;
let c = self.cur;
let x = if high {
let k16 = self.s.m.i32(16);
self.s.m.bin(c, Bin::LShr, x, k16)
} else {
x
};
let m = self.s.m.i32(0xFFFF);
Ok(self.s.m.bin(c, Bin::And, x, m))
}
/// Packed 16-bit operations (`v_pk_*`): each half computed as the
/// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
@@ -8419,7 +8504,7 @@ impl<'a> Lower<'a> {
};
let float = op.ends_with("_f16");
let n = match op {
"fma_f16" | "mad_u16" | "mad_i16" => 3,
"fma_f16" | "fmac_f16" | "mad_u16" | "mad_i16" => 3,
"add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
| "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
| "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
@@ -8434,7 +8519,11 @@ impl<'a> Lower<'a> {
for high in [false, true] {
let mut xs = Vec::new();
for k in 0..n {
let h = self.packed_src(inst, k, high, float)?;
let h = if op == "fmac_f16" {
self.fmac_half(inst, k, high)?
} else {
self.packed_src(inst, k, high, float)?
};
if float {
let mut f = self
.s
@@ -9480,7 +9569,8 @@ impl<'a> Lower<'a> {
let Fields::Image { cache, .. } = &inst.fields else {
unreachable!()
};
if *d16 || *a16 {
// 16-bit coordinates (a16) are read as `addr_val` reads them.
if *d16 {
return Err("a 16-bit image atomic");
}
// Compare-exchange consumes a replacement followed by a comparand.
+1
View File
@@ -284,6 +284,7 @@ pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
let c = Container::parse(container)?;
let dxil = c
.part(FourCC::DXIL)
.or(c.part(FourCC::ACCC))
.ok_or(ShaderError::Malformed("no DXIL part"))?;
let native = crate::native_programs(dxil.data)?
.into_iter()
+140 -1
View File
@@ -120,6 +120,18 @@ const CS_THREADS: usize = 0x28;
const RECORD_LDS: usize = 0x4c;
const MS_CLIP_CNTL: usize = 0x194;
const MS_INFO: usize = 0x448;
const FSPX_VERSION: u32 = 1;
const FSPX_HEADER: usize = 0x10;
const FSPX_PACKET: u32 = 0;
const FSPX_CODE: u32 = 6;
const FSPX_METADATA: u32 = 7;
const PACKET_THREADS: usize = 0x0c;
const PACKET_FLAGS: usize = 0x12;
const PACKET_WAVE32: u16 = 1 << 4;
const PACKET_RSRC1: usize = 0x14;
const PACKET_RSRC2: usize = 0x18;
const FSPX_RECORDS: usize = 0x18;
const FSPX_RECORD: usize = 32;
/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes.
const MAX_UNPACKED: u64 = 16 << 20;
@@ -409,8 +421,12 @@ pub struct UsedResource {
pub slot: u8,
}
/// The native programs in a `DXIL` part's data; empty for the PC layout.
/// The native programs in a `DXIL` part's data, or in an `ACCC` part's
/// ([`fspx_program`]); empty for the PC layout.
pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
if part.starts_with(b"FSPX") {
return Ok(vec![fspx_program(part)?]);
}
if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") {
return Ok(Vec::new());
}
@@ -432,6 +448,129 @@ pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
Ok(out)
}
/// The compute program of an `ACCC` part, which a container carries in place
/// of `DXIL` when another compiler made the native code (the AMD
/// FidelityFX upscaler's shaders). Layout as observed (offsets from "FSPX"):
///
/// ```text
/// +0x00 "FSPX" u32 version (1), u32 entry count, u32 size; entries of 16 B
/// from +0x10: u32 kind, u32 offset, u32 size, u32 0
/// kind 0 pipeline registers, 0x1c B: +0x0c u16 x3 thread-group size,
/// +0x12 u16 flags (bit 4 wave32), +0x14 COMPUTE_PGM_RSRC1,
/// +0x18 COMPUTE_PGM_RSRC2
/// kind 1 pipeline metadata (a hash); kind 6 the GFX10 code
/// kind 7 program metadata: u32 0x403, u32 size - 0x14, u32 code dwords,
/// u64 0, u8 0x40, u8 first user-data dword, u8 count of 0x41
/// records, u8 0; then 32-byte records from +0x18, each a u32 tag:
/// 0x41 a resource the code reads: u8 resource type (as FSSM's used
/// entries), u8 root type, u16 0, u32 table offset (dwords), u32
/// register, u32 view dimension (1 buffer, 4 2D, 0 root view),
/// u8 descriptor dwords, u8 user-data dword, u8 root slot, u8 0,
/// u32 -1, u32 0
/// 0x42 a view declaration: u32 0, u8 1, u8 class (0 SRV, 1 UAV),
/// u8 resource kind (DXIL's), u8 0, u32 register
/// 0x43 the shader hash (16 B); the last record
/// ```
pub fn fspx_program(part: &[u8]) -> Result<NativeProgram, ShaderError> {
if u32_at(part, 4)? != FSPX_VERSION {
return Err(Malformed("unknown FSPX version"));
}
let count = u32_at(part, 8)? as usize;
if count > MAX_XDAT_ENTRIES {
return Err(Malformed("implausible FSPX entry count"));
}
let entry = |kind: u32| -> Result<&[u8], ShaderError> {
for i in 0..count {
let at = FSPX_HEADER + 16 * i;
if u32_at(part, at)? == kind {
let (offset, size) = (u32_at(part, at + 4)?, u32_at(part, at + 8)?);
return bytes(part, offset.into(), size.into())
.ok_or(Malformed("FSPX entry out of bounds"));
}
}
Err(Malformed("FSPX entry missing"))
};
let packet = entry(FSPX_PACKET)?;
let code = entry(FSPX_CODE)?;
let meta = entry(FSPX_METADATA)?;
if u32_at(meta, 8)? as usize * 4 != code.len() {
return Err(Malformed("FSPX code size disagrees"));
}
let wave64 = u16_at(packet, PACKET_FLAGS)? & PACKET_WAVE32 == 0;
// VGPRs in granules of 4 (wave64) or 8 (wave32).
let granules = (u32_at(packet, PACKET_RSRC1)? & 0x3F) + 1;
let vgprs = (granules * if wave64 { 4 } else { 8 }).min(256) as u16;
let threads = |i: usize| u16_at(packet, PACKET_THREADS + 2 * i).map(u32::from);
let mut layout: Vec<RootParam> = Vec::new();
let mut used = Vec::new();
for e in meta
.get(FSPX_RECORDS..)
.unwrap_or(&[])
.as_chunks::<FSPX_RECORD>()
.0
{
match e[0] {
0x41 => {}
0x42 => continue,
0x43 => break,
_ => return Err(Malformed("unknown FSPX metadata record")),
}
let root = RootType::from_raw(e[5].into());
let u = UsedResource {
kind: match e[4] {
0 => ResourceType::Srv,
1 => ResourceType::Sampler,
2 => ResourceType::Cbv,
3 => ResourceType::Uav,
n => ResourceType::Other(n),
},
root,
table_offset_dwords: le32(e, 8),
lower_bound: le32(e, 12),
stride: 0,
dwords: e[20],
user_data: e[21],
slot: e[22],
};
let sgprs = match root {
RootType::Table => 1,
RootType::Descriptor => 2,
// The code holds its words; no user data.
RootType::ImmediateSampler => 0,
_ => return Err(Malformed("an FSPX resource of an unknown root type")),
};
if sgprs > 0 && !layout.iter().any(|p| p.slot == u.slot) {
layout.push(RootParam {
root,
table_offset_dwords: 0,
sgprs,
base_register: u.lower_bound,
user_data: u.user_data,
slot: u.slot,
});
}
used.push(u);
}
Ok(NativeProgram {
stage: HwStage::Cs,
wave64,
vgprs,
layout,
used,
io: StageIo::Cs(ComputeIo {
rsrc2: u32_at(packet, PACKET_RSRC2)?,
threads: [threads(0)?, threads(1)?, threads(2)?],
}),
code: code.to_vec(),
})
}
fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
data.get(at..at + 2)
.map(|b| u16::from_le_bytes([b[0], b[1]]))
.ok_or(Malformed("FSPX data out of bounds"))
}
fn unpack(blob: &[u8]) -> Result<Vec<u8>, ShaderError> {
if blob.get(0..4) != Some(b"XBCH") {
return Err(Malformed("native blob lacks XBCH magic"));
+129 -1
View File
@@ -1118,10 +1118,17 @@ impl<'a> Tracer<'a> {
let Operand::Scalar { code, dwords } = *op else {
return Err("a descriptor not in SGPRs");
};
let words = (0..dwords)
let mut words = (0..dwords)
.map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v)))
.collect::<Option<Vec<_>>>()
.ok_or("a descriptor not in SGPRs")?;
// A byte access through a buffer descriptor made raw reads what the
// descriptor's view does with a raw host view (VIctory upstream 0b35b7f).
if !inst.name().contains("format")
&& let Some(raw) = self.made_raw(&words)
{
words = raw.to_vec();
}
// Only the lanes that reach the access read the descriptor.
let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true)));
self.classify(&words, &mut Vec::new(), &mut known)
@@ -1462,6 +1469,46 @@ impl<'a> Tracer<'a> {
}
}
/// The words of a buffer descriptor that `words` makes raw, as the
/// FidelityFX upscaler's compiler does before byte accesses: the stride
/// (dword 1 bits 16-29) cleared, the record count times max(stride, 1),
/// out-of-bounds checking by bytes (dword 3 bits 28-29 set). The bounds
/// are then the view's size in bytes either way.
fn made_raw(&self, words: &[Term]) -> Option<[Term; 4]> {
let [w0, Term::Value(w1), Term::Value(w2), Term::Value(w3)] = *words else {
return None;
};
// `x op c` with `c` either side.
let with = |v: Value, name: &str, c: u32| match self.sop2(v, &[name])?.1 {
[x, Term::Const(k)] | [Term::Const(k), x] if k == c => Some(x),
_ => None,
};
let d1 = with(w1, "s_and_b32", 0xC000_FFFF)?;
let Term::Value(m3) = with(w3, "s_or_b32", 0x3000_0000)? else {
return None;
};
let d3 = with(m3, "s_and_b32", 0xCFFF_FFFF)?;
let [a, b] = self.sop2(w2, &["s_mul_i32"])?.1;
let max = |t: Term| match t {
Term::Value(s) => with(s, "s_max_u32", 1),
Term::Const(_) => None,
};
let (d2, field) = match (max(a), max(b)) {
(_, Some(f)) => (a, f),
(Some(f), None) => (b, f),
(None, None) => return None,
};
let Term::Value(field) = field else {
return None;
};
// s_bfe_u32: offset 16, width 14.
let (_, [x, Term::Const(0x000E_0010)]) = self.sop2(field, &["s_bfe_u32"])? else {
return None;
};
(x == d1).then_some([w0, d1, d2, d3])
}
/// For a `v_readfirstlane_b32` result: the VGPR value it reads.
fn first_lane_source(&self, v: Value) -> Option<Value> {
let inst = self.def(v)?;
@@ -2331,6 +2378,12 @@ fn copy_source(inst: &Inst, k: usize) -> Option<Moved> {
if inst.name() == "s_movk_i32" {
return Some(Moved::Const(i32::from((*imm)? as i16) as u32));
}
// A mask of S0 bits from bit S1, as the upscaler's compiler makes an
// immediate sampler's word.
if let ("s_bfm_b32", 0, [Operand::Const(w), Operand::Const(at)]) = (inst.name(), k, &src[..]) {
let (w, at) = (inline(*w)? & 31, inline(*at)? & 31);
return Some(Moved::Const(((1u32 << w) - 1) << at));
}
let src = src.first()?;
match (inst.name(), *src) {
("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => {
@@ -2343,6 +2396,11 @@ fn copy_source(inst: &Inst, k: usize) -> Option<Moved> {
// that has no inline form; fold more if descriptors need it.
("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())),
("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)),
// shortcut: a literal below 2^31, whose high dword is 0 whether the
// hardware extends it with zeros or with its sign.
("s_mov_b64", Operand::Literal(x)) if x >> 31 == 0 => {
Some(Moved::Const(if k == 0 { x } else { 0 }))
}
// 64-bit inline integers are sign-extended.
("s_mov_b64", Operand::Const(c @ 128..=208)) => {
let low = inline(c)?;
@@ -2763,6 +2821,76 @@ pub(crate) mod tests {
assert_eq!(r.scalar, [((0, 2), at(0, 0)), ((0, 3), at(0, 0x10))]);
}
/// The FidelityFX upscaler's byte accesses make a loaded buffer
/// descriptor raw first (stride cleared, records times stride, bounds
/// in bytes): the access reads the loaded descriptor. Any other change
/// still fails.
#[test]
fn a_descriptor_made_raw_is_the_loaded_one() {
let words = |mask: u32| -> Vec<u8> {
[
0xBE88_0304, // s_mov_b32 s8, s4
0xBE89_0380, // s_mov_b32 s9, 0
0xF408_0204,
0xFA00_0160, // s_load_dwordx4 s[8:11], s[8:9], 0x160
0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
0x938C_FF09,
0x000E_0010, // s_bfe_u32 s12, s9, 0x000e0010
0x848C_810C, // s_max_u32 s12, s12, 1
0x8709_FF09,
mask, // s_and_b32 s9, s9, mask
0x870B_FF0B,
0xCFFF_FFFF, // s_and_b32 s11, s11, 0xcfffffff
0x930A_0C0A, // s_mul_i32 s10, s10, s12
0x880B_FF0B,
0x3000_0000, // s_or_b32 s11, s11, 0x30000000
0xE078_1000,
0x8002_0007, // buffer_store_dwordx4 v[0:3], v7, s[8:11], 0 offen
S_ENDPGM,
]
.iter()
.flat_map(|w: &u32| w.to_le_bytes())
.collect()
};
let run = |mask| {
let p = crate::ir::build(&words(mask), false, 256).unwrap();
track(&p, &[param(Table, 4, 1)], HwStage::Cs, lanes(&p).as_ref())
};
assert!(run(0xC000_FFFF).is_ok());
assert_eq!(
run(0xC000_FFFE).unwrap_err(),
ShaderError::Unsupported {
offset: 0x3c,
what: "a descriptor changed after loading"
}
);
}
/// Immediate sampler words the upscaler's compiler makes with a bit
/// mask and a 64-bit move of a literal.
#[test]
fn sampler_words_from_bit_masks_and_wide_literals_are_constants() {
let code: Vec<u8> = [
0xB010_3092, // s_movk_i32 s16, 0x3092
0x9211_8C8C, // s_bfm_b32 s17, 12, 12
0xBE92_04FF,
0x1850_0000, // s_mov_b64 s[18:19], 0x18500000
S_ENDPGM,
]
.iter()
.flat_map(|w: &u32| w.to_le_bytes())
.collect();
let p = crate::ir::build(&code, false, 256).unwrap();
let layout = [param(Table, 4, 1)];
let t = Tracer::new(&p, &layout, HwStage::Cs, None).unwrap();
let block = &p.blocks[0];
let value = |n: usize, k: usize| t.origin(block.insts[n].writes[k].1);
assert_eq!(value(1, 0), Term::Const(0x00FF_F000));
assert_eq!(value(2, 0), Term::Const(0x1850_0000));
assert_eq!(value(2, 1), Term::Const(0));
}
#[test]
fn a_selection_that_mixes_two_descriptors_fails() {
// The high half picked from the first load whatever SCC is: when