GFX10 operand fields and SP3 text; FSSM wave size

Decode the operand fields of every GFX10 encoding (Instruction::fields)
and print them in SP3 syntax (Instruction::text, shader-info --disasm).
Read the wave size from the FSSM stage record flags.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MarvisandClaude Opus 5.5 committed 2026-11-23 01:43:34 +01:00
1 parent f4504f6413
commit 12caefe804
5 files changed
+1626 -10

No files matched your search

+7 -5
View File
@@ -76,7 +76,9 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
*t.unnamed.entry(key).or_default() += 1;
}
if disasm {
listing.extend(insts.iter().map(format_instruction));
listing.extend(
insts.iter().map(|i| format_instruction(i, n.wave64)),
);
}
}
Err(e) => {
@@ -166,11 +168,11 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
Ok(())
}
fn format_instruction(i: &Instruction) -> String {
fn format_instruction(i: &Instruction, wave64: bool) -> String {
let words: Vec<_> = i.words.iter().map(|w| format!("{w:08X}")).collect();
let name = match i.name() {
Some(n) => n.to_owned(),
let text = match i.name() {
Some(_) => i.text(wave64),
None => format!("<{:?} {:#x}>", i.encoding, i.opcode),
};
format!(" {:06x}: {:<44} {name}", i.offset, words.join(" "))
format!(" {:06x}: {:<44} {text}", i.offset, words.join(" "))
}
+813
View File
@@ -0,0 +1,813 @@
//! Operand fields of GFX10 instructions, by encoding.
//!
//! Layouts follow AMD's RDNA ISA reference. Register ranges carry their size
//! in dwords, which depends on the opcode (read from its name) and, for lane
//! masks (VCC, EXEC, compare results), on the wave size.
use super::{Encoding, Instruction};
/// A source or destination of an instruction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operand {
/// Scalar registers by operand code: 0-105 `s0`-`s105`, 106/107
/// `vcc_lo`/`vcc_hi`, 108-123 `ttmp0`-`ttmp15`, 124 `m0`, 125 `null`,
/// 126/127 `exec_lo`/`exec_hi`.
Scalar {
code: u8,
dwords: u8,
},
Vector {
reg: u8,
dwords: u8,
},
/// Inline constant or read-only special source, by operand code
/// (128-192: 0-64, 193-208: -1 to -16, 240-248: floats, 251-254: vccz,
/// execz, scc, lds_direct).
Const(u8),
/// The 32-bit literal that follows the instruction.
Literal(u32),
/// Interpolation attribute and channel (0-3 = x-w); `high` selects the
/// upper f16 half.
Attr {
index: u8,
chan: u8,
high: bool,
},
}
/// Operand code of `null` (no register; reads as 0).
pub const NULL: u8 = 125;
const VCC: u8 = 106;
const EXEC: u8 = 126;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Cache {
pub glc: bool,
pub slc: bool,
pub dlc: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Fields {
/// SOP1, SOP2, SOPC, SOPK; `imm` is SOPK's 16-bit immediate.
Sop {
dst: Option<Operand>,
src: Vec<Operand>,
imm: Option<u16>,
},
/// The 16-bit immediate: branch offset in dwords, wait counts, message...
Sopp {
imm: u16,
},
Smem {
data: Option<Operand>,
base: Operand,
/// Signed byte offset, added to `soffset`.
offset: i32,
soffset: Operand,
cache: Cache,
},
Valu(Valu),
Vintrp {
dst: Operand,
/// The i/j VGPR, or for `v_interp_mov_f32` the parameter (0 `p10`,
/// 1 `p20`, 2 `p0`) as [`Operand::Const`].
src: Operand,
attr: Operand,
},
Ds {
dst: Option<Operand>,
addr: Option<Operand>,
data: Vec<Operand>,
offset0: u8,
offset1: u8,
gds: bool,
},
/// MUBUF, and MTBUF with `format` set.
Buffer {
/// Loaded, stored, or the atomic operand (and result with `glc`).
data: Option<Operand>,
addr: Operand,
rsrc: Operand,
soffset: Operand,
offset: u16,
offen: bool,
idxen: bool,
format: Option<u8>,
lds: bool,
tfe: bool,
cache: Cache,
},
Image {
data: Operand,
/// One range, or one VGPR per address with the NSA form.
addr: Vec<Operand>,
rsrc: Operand,
sampler: Option<Operand>,
dmask: u8,
dim: u8,
unorm: bool,
r128: bool,
a16: bool,
d16: bool,
tfe: bool,
lwe: bool,
cache: Cache,
},
/// FLAT, GLOBAL and SCRATCH.
Flat {
dst: Option<Operand>,
addr: Option<Operand>,
data: Option<Operand>,
saddr: Option<Operand>,
offset: i16,
lds: bool,
cache: Cache,
},
Exp {
target: u8,
/// Per channel; `None` when disabled.
src: [Option<Operand>; 4],
compr: bool,
done: bool,
vm: bool,
},
}
/// VOP1, VOP2, VOPC, VOP3 and VOP3P, with their SDWA and DPP forms.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Valu {
/// A VGPR range, an SGPR (`v_readlane_b32`...) or a lane mask (compares).
pub dst: Option<Operand>,
/// Carry-out or the second result of VOP3B (`v_add_co_u32`, `v_div_scale_f32`...).
pub carry: Option<Operand>,
/// In operand order, including the implicit VCC of VOP2 `v_cndmask_b32`
/// and carry-in, and the literal of `v_madmk`/`v_madak` forms.
pub src: Vec<Operand>,
/// Bit i applies to `src[i]`. For VOP3P, `neg` is the low half's.
pub neg: u8,
pub abs: u8,
/// VOP3P: negate the high half (`v_fma_mix*`: absolute value).
pub neg_hi: u8,
/// VOP3: bit 3 is the destination. VOP3P with `opsel_hi`: the halves used.
pub opsel: u8,
pub opsel_hi: u8,
pub clamp: bool,
/// Output modifier: 1 ×2, 2 ×4, 3 ÷2.
pub omod: u8,
pub sdwa: Option<Sdwa>,
pub dpp: Option<Dpp>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sdwa {
/// Selects: 0-3 byte, 4-5 word, 6 dword. Compares have no `dst_sel`.
pub dst_sel: u8,
/// 0 pad with zeros, 1 sign-extend, 2 preserve.
pub dst_unused: u8,
pub src_sel: [u8; 2],
/// Bit i sign-extends `src[i]`.
pub sext: u8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dpp {
/// DPP16: `ctrl` is the 9-bit permutation (quad_perm, row shifts...).
Row {
ctrl: u16,
row_mask: u8,
bank_mask: u8,
bound_ctrl: bool,
fi: bool,
},
/// DPP8: eight 3-bit lane selects.
Lanes { sel: u32, fi: bool },
}
impl Instruction {
/// Decodes the operand fields. `wave64` sizes lane masks.
pub fn fields(&self, wave64: bool) -> Fields {
let name = self.name().unwrap_or("");
let w = |i: usize| self.words.get(i).copied().unwrap_or(0);
let (w0, w1) = (w(0), w(1));
let bit = |word: u32, n: u32| word >> n & 1 != 0;
let cache = |glc, slc, dlc| Cache { glc, slc, dlc };
match self.encoding {
Encoding::Sop2 | Encoding::Sop1 | Encoding::Sopc => {
let (dst, src0, src1) = salu_dwords(name);
let sdst = scalar((w0 >> 16 & 0x7F) as u8, dst);
let ssrc = |shift: u32, dwords| source(w0 >> shift & 0xFF, dwords, w1);
let (dst, src) = match self.encoding {
Encoding::Sop2 => (Some(sdst), vec![ssrc(0, src0), ssrc(8, src1)]),
Encoding::Sopc => (None, vec![ssrc(0, src0), ssrc(8, src1)]),
_ => match name {
"s_getpc_b64" => (Some(sdst), vec![]),
"s_setpc_b64" | "s_rfe_b64" => (None, vec![ssrc(0, src0)]),
_ => (Some(sdst), vec![ssrc(0, src0)]),
},
};
Fields::Sop {
dst,
src,
imm: None,
}
}
Encoding::Sopk => {
let sdst = scalar((w0 >> 16 & 0x7F) as u8, 1 + u8::from(name == "s_call_b64"));
let (dst, src) = match name {
"s_setreg_imm32_b32" => (None, vec![Operand::Literal(w1)]),
"s_version" => (None, vec![]),
n if n.starts_with("s_cmpk_")
|| n.starts_with("s_waitcnt_")
|| n == "s_setreg_b32" =>
{
(None, vec![sdst])
}
_ => (Some(sdst), vec![]),
};
Fields::Sop {
dst,
src,
imm: Some(w0 as u16),
}
}
Encoding::Sopp => Fields::Sopp { imm: w0 as u16 },
Encoding::Smem => {
let data = match name {
"s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => None,
n if n.starts_with("s_dcache_discard") => None,
"s_memtime" | "s_memrealtime" => Some(2),
_ => Some(data_dwords(name)),
};
let base = 2 + 2 * u8::from(name.starts_with("s_buffer_"));
Fields::Smem {
data: data.map(|d| scalar((w0 >> 6 & 0x7F) as u8, d)),
base: scalar(((w0 & 0x3F) << 1) as u8, base),
offset: (w1 << 11) as i32 >> 11,
soffset: scalar((w1 >> 25) as u8, 1),
cache: cache(bit(w0, 16), false, bit(w0, 14)),
}
}
Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc | Encoding::Vop3 | Encoding::Vop3p => {
Fields::Valu(self.valu(name, if wave64 { 2 } else { 1 }))
}
Encoding::Vintrp => {
let vsrc = (w0 & 0xFF) as u8;
Fields::Vintrp {
dst: vector(w0 >> 18, 1),
src: if name == "v_interp_mov_f32" {
Operand::Const(vsrc)
} else {
vector(vsrc.into(), 1)
},
attr: Operand::Attr {
index: (w0 >> 10 & 0x3F) as u8,
chan: (w0 >> 8 & 3) as u8,
high: false,
},
}
}
Encoding::Ds => {
let ty = data_dwords(name);
let pair = ds_pair(name);
let returns = name.contains("read")
|| name.contains("_rtn")
|| matches!(
name,
"ds_swizzle_b32"
| "ds_permute_b32"
| "ds_bpermute_b32"
| "ds_append"
| "ds_consume"
| "ds_ordered_count"
);
let no_addr = name.starts_with("ds_gws")
|| name.contains("addtid")
|| matches!(name, "ds_nop" | "ds_append" | "ds_consume");
let data = if name.contains("read")
|| name.contains("src2")
|| matches!(
name,
"ds_swizzle_b32"
| "ds_nop"
| "ds_append"
| "ds_consume"
| "ds_ordered_count"
| "ds_gws_sema_v"
| "ds_gws_sema_p"
| "ds_gws_sema_release_all"
) {
0
} else if pair || name.contains("cmpst") || name.contains("mskor") {
2
} else {
1
};
Fields::Ds {
dst: returns.then(|| vector(w1 >> 24, ty * (1 + u8::from(pair)))),
addr: (!no_addr).then(|| vector(w1 & 0xFF, 1)),
data: (0..data)
.map(|i| vector(w1 >> (8 + 8 * i) & 0xFF, ty))
.collect(),
offset0: w0 as u8,
offset1: (w0 >> 8) as u8,
gds: bit(w0, 17),
}
}
Encoding::Mubuf | Encoding::Mtbuf => {
let (offen, idxen, tfe) = (bit(w0, 12), bit(w0, 13), bit(w1, 23));
let mtbuf = self.encoding == Encoding::Mtbuf;
Fields::Buffer {
data: (!name.ends_with("_inv"))
.then(|| vector(w1 >> 8 & 0xFF, data_dwords(name) + u8::from(tfe))),
addr: vector(w1 & 0xFF, 1 + u8::from(offen && idxen)),
rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, 4),
soffset: source(w1 >> 24, 1, 0),
offset: (w0 & 0xFFF) as u16,
offen,
idxen,
format: mtbuf.then_some((w0 >> 19 & 0x7F) as u8),
lds: !mtbuf && bit(w0, 16),
tfe,
cache: cache(bit(w0, 14), bit(w1, 22), bit(w0, 15)),
}
}
Encoding::Mimg => {
let (dim, dmask, a16, d16) = (
(w0 >> 3 & 7) as u8,
(w0 >> 8 & 0xF) as u8,
bit(w1, 30),
bit(w1, 31),
);
let (r128, tfe, lwe) = (bit(w0, 15), bit(w0, 16), bit(w0, 17));
let mut data = if name.starts_with("image_gather4") {
4
} else {
dmask.count_ones().max(1) as u8
};
if d16 {
data = data.div_ceil(2);
}
let count = image_addr_dwords(name, dim, a16);
let addr = if w0 >> 1 & 3 == 0 {
vec![vector(w1 & 0xFF, count)]
} else {
// NSA: one VGPR per address, the first in dword 1, the rest
// in the extra dwords.
(0..usize::from(count))
.map(|i| match i {
0 => vector(w1 & 0xFF, 1),
i => vector(w(2 + (i - 1) / 4) >> (8 * ((i - 1) % 4)) & 0xFF, 1),
})
.collect()
};
let sampled = ["image_sample", "image_gather4", "image_get_lod"]
.iter()
.any(|p| name.starts_with(p));
Fields::Image {
data: vector(w1 >> 8 & 0xFF, data + u8::from(tfe || lwe)),
addr,
rsrc: scalar(((w1 >> 16 & 0x1F) << 2) as u8, if r128 { 4 } else { 8 }),
sampler: sampled.then(|| scalar(((w1 >> 21 & 0x1F) << 2) as u8, 4)),
dmask,
dim,
unorm: bit(w0, 12),
r128,
a16,
d16,
tfe,
lwe,
cache: cache(bit(w0, 13), bit(w0, 25), bit(w0, 7)),
}
}
Encoding::Flat | Encoding::Global | Encoding::Scratch => {
let saddr = (w1 >> 16 & 0x7F) as u8;
let glc = bit(w0, 16);
let n = data_dwords(name);
let (load, atomic) = (name.contains("_load_"), name.contains("_atomic_"));
let addr = match self.encoding {
Encoding::Flat => Some(vector(w1 & 0xFF, 2)),
Encoding::Global => Some(vector(w1 & 0xFF, 1 + u8::from(saddr == NULL))),
// With an SGPR base, scratch takes no VGPR.
_ => (saddr == NULL).then(|| vector(w1 & 0xFF, 1)),
};
let ret = if atomic && name.contains("cmpswap") {
n / 2
} else {
n
};
Fields::Flat {
dst: (load || atomic && glc).then(|| vector(w1 >> 24, ret)),
addr,
data: (!load).then(|| vector(w1 >> 8 & 0xFF, n)),
saddr: (self.encoding != Encoding::Flat)
.then(|| scalar(saddr, 1 + u8::from(self.encoding == Encoding::Global))),
offset: match self.encoding {
Encoding::Flat => (w0 & 0x7FF) as i16,
_ => ((w0 << 4) as i16) >> 4,
},
lds: bit(w0, 13),
cache: cache(glc, bit(w0, 17), bit(w0, 12)),
}
}
Encoding::Exp => {
let compr = bit(w0, 10);
Fields::Exp {
target: (w0 >> 4 & 0x3F) as u8,
src: std::array::from_fn(|i| {
let slot = if compr { i / 2 } else { i };
bit(w0, i as u32).then(|| vector(w1 >> (8 * slot) & 0xFF, 1))
}),
compr,
done: bit(w0, 11),
vm: bit(w0, 12),
}
}
}
}
fn valu(&self, name: &str, lanes: u8) -> Valu {
// No operands; the console compiler stores a shader hash in their fields.
if matches!(name, "v_nop" | "v_pipeflush" | "v_clrexcp") {
return Valu::default();
}
let w = |i: usize| self.words.get(i).copied().unwrap_or(0);
let w0 = w(0);
let (dst_n, src_n) = valu_dwords(name);
let compare = match self.encoding {
Encoding::Vopc => true,
Encoding::Vop3 => self.opcode < 0x100,
_ => false,
};
let vop3b = VOP3B.contains(&name);
let carry_in = name.ends_with("_co_ci_u32") || name == "v_cndmask_b32";
let mut v = Valu::default();
match self.encoding {
Encoding::Vop1 | Encoding::Vop2 | Encoding::Vopc => {
let ext = w(1);
let mut src0 = w0 & 0x1FF;
let vsrc1 = 256 + (w0 >> 9 & 0xFF);
let mut src1 = vsrc1;
match src0 {
0xF9 => {
let sdwa = Sdwa {
dst_sel: (ext >> 8 & 7) as u8,
dst_unused: (ext >> 11 & 3) as u8,
src_sel: [(ext >> 16 & 7) as u8, (ext >> 24 & 7) as u8],
sext: (ext >> 19 & 1 | ext >> 26 & 2) as u8,
};
// The s0/s1 bits select an SGPR or constant instead of a VGPR.
src0 = (ext & 0xFF) | if ext >> 23 & 1 == 0 { 256 } else { 0 };
if ext >> 31 == 1 {
src1 = vsrc1 - 256;
}
v.neg = (ext >> 20 & 1 | ext >> 27 & 2) as u8;
v.abs = (ext >> 21 & 1 | ext >> 28 & 2) as u8;
if compare {
if ext >> 15 & 1 == 1 {
v.dst = Some(scalar((ext >> 8 & 0x7F) as u8, lanes));
}
v.sdwa = Some(Sdwa {
dst_sel: 6,
dst_unused: 0,
..sdwa
});
} else {
v.clamp = ext >> 13 & 1 == 1;
v.omod = (ext >> 14 & 3) as u8;
v.sdwa = Some(sdwa);
}
}
0xFA => {
src0 = 256 + (ext & 0xFF);
v.neg = (ext >> 20 & 1 | ext >> 21 & 2) as u8;
v.abs = (ext >> 21 & 1 | ext >> 22 & 2) as u8;
v.dpp = Some(Dpp::Row {
ctrl: (ext >> 8 & 0x1FF) as u16,
row_mask: (ext >> 28) as u8,
bank_mask: (ext >> 24 & 0xF) as u8,
bound_ctrl: ext >> 19 & 1 == 1,
fi: ext >> 18 & 1 == 1,
});
}
0xE9 | 0xEA => {
v.dpp = Some(Dpp::Lanes {
sel: ext >> 8,
fi: src0 == 0xEA,
});
src0 = 256 + (ext & 0xFF);
}
_ => {}
}
let op0 = source(src0, src_n[0], ext);
let op1 = source(src1, src_n[1], ext);
match self.encoding {
Encoding::Vopc => {
let mask = if name.starts_with("v_cmpx") {
EXEC
} else {
VCC
};
v.dst = v.dst.or(Some(scalar(mask, lanes)));
v.src = vec![op0, op1];
}
Encoding::Vop1 => {
v.dst = Some(valu_dst(name, w0 >> 17 & 0xFF, dst_n));
v.src = vec![op0];
}
_ => {
v.dst = Some(vector(w0 >> 17 & 0xFF, dst_n));
v.src = match name {
n if n.ends_with("mk_f32") || n.ends_with("mk_f16") => {
vec![op0, Operand::Literal(ext), op1]
}
n if n.ends_with("ak_f32") || n.ends_with("ak_f16") => {
vec![op0, op1, Operand::Literal(ext)]
}
_ => vec![op0, op1],
};
if carry_in {
v.src.push(scalar(VCC, lanes));
}
if name.ends_with("_co_ci_u32") {
v.carry = Some(scalar(VCC, lanes));
}
}
}
}
Encoding::Vop3 | Encoding::Vop3p => {
let w1 = w(1);
let field = |i: u32| w1 >> (9 * i) & 0x1FF;
let count = match self.opcode {
_ if self.encoding == Encoding::Vop3p => {
if name.starts_with("v_pk_")
&& !name.contains("_fma_")
&& !name.contains("_mad_")
{
2
} else {
3
}
}
0x000..0x100 => 2,
0x100..0x140 => 2 + usize::from(carry_in),
0x180..0x200 => 1,
_ if VOP3_TWO_SOURCES.contains(&name) => 2,
_ => 3,
};
v.src = (0..count)
.map(|i| {
let code = field(i as u32);
if i == 0 && name.starts_with("v_interp_") {
Operand::Attr {
index: (code & 0x3F) as u8,
chan: (code >> 6 & 3) as u8,
high: code >> 8 & 1 == 1,
}
} else if i == 2 && carry_in {
source(code, lanes, w(2))
} else {
source(code, src_n[i], w(2))
}
})
.collect();
v.clamp = w0 >> 15 & 1 == 1;
v.neg = (w1 >> 29) as u8;
if self.encoding == Encoding::Vop3p {
v.neg_hi = (w0 >> 8 & 7) as u8;
v.opsel = (w0 >> 11 & 7) as u8;
v.opsel_hi = (w1 >> 27 & 3 | w0 >> 12 & 4) as u8;
} else {
v.omod = (w1 >> 27 & 3) as u8;
if vop3b {
v.carry = Some(scalar((w0 >> 8 & 0x7F) as u8, lanes));
} else {
v.abs = (w0 >> 8 & 7) as u8;
v.opsel = (w0 >> 11 & 0xF) as u8;
}
}
let vdst = w0 & 0xFF;
v.dst = Some(if compare {
scalar(vdst as u8, lanes)
} else {
valu_dst(name, vdst, dst_n)
});
}
_ => unreachable!("not a VALU encoding"),
}
v
}
}
/// VOP3-only opcodes that take two sources (the rest take three).
const VOP3_TWO_SOURCES: &[&str] = &[
"v_add_f64",
"v_mul_f64",
"v_min_f64",
"v_max_f64",
"v_ldexp_f64",
"v_mul_lo_u32",
"v_mul_hi_u32",
"v_mul_lo_i32",
"v_mul_hi_i32",
"v_trig_preop_f64",
"v_lshlrev_b64",
"v_lshrrev_b64",
"v_ashrrev_i64",
"v_add_nc_u16",
"v_sub_nc_u16",
"v_mul_lo_u16",
"v_lshrrev_b16",
"v_ashrrev_i16",
"v_max_u16",
"v_max_i16",
"v_min_u16",
"v_min_i16",
"v_add_nc_i16",
"v_sub_nc_i16",
"v_add_co_u32",
"v_sub_co_u32",
"v_subrev_co_u32",
"v_pack_b32_f16",
"v_cvt_pknorm_i16_f16",
"v_cvt_pknorm_u16_f16",
"v_lshlrev_b16",
"v_interp_p1ll_f16",
"v_readlane_b32",
"v_writelane_b32",
"v_ldexp_f32",
"v_bfm_b32",
"v_bcnt_u32_b32",
"v_mbcnt_lo_u32_b32",
"v_mbcnt_hi_u32_b32",
"v_cvt_pknorm_i16_f32",
"v_cvt_pknorm_u16_f32",
"v_cvt_pk_u16_u32",
"v_cvt_pk_i16_i32",
"v_sub_nc_i32",
"v_add_nc_i32",
];
/// VOP3 opcodes whose bits 14:8 hold a scalar destination instead of `abs`/`opsel`.
const VOP3B: &[&str] = &[
"v_add_co_u32",
"v_sub_co_u32",
"v_subrev_co_u32",
"v_add_co_ci_u32",
"v_sub_co_ci_u32",
"v_subrev_co_ci_u32",
"v_div_scale_f32",
"v_div_scale_f64",
"v_mad_u64_u32",
"v_mad_i64_i32",
];
fn scalar(code: u8, dwords: u8) -> Operand {
Operand::Scalar { code, dwords }
}
fn vector(reg: u32, dwords: u8) -> Operand {
Operand::Vector {
reg: reg as u8,
dwords,
}
}
/// A 9-bit source field (8-bit scalar fields are the same codes below 256).
fn source(code: u32, dwords: u8, literal: u32) -> Operand {
match code {
0..=127 => scalar(code as u8, dwords),
255 => Operand::Literal(literal),
256.. => vector(code - 256, dwords),
_ => Operand::Const(code as u8),
}
}
/// VALU destinations that are SGPRs.
fn valu_dst(name: &str, field: u32, dwords: u8) -> Operand {
match name {
"v_readlane_b32" | "v_readfirstlane_b32" => scalar(field as u8, 1),
_ => vector(field, dwords),
}
}
/// LDS opcodes on two addresses (`ds_read2_b32`...), with `offset0`/`offset1`.
pub(super) fn ds_pair(name: &str) -> bool {
name.split('_').any(|t| {
["read2", "write2", "wrxchg2"]
.iter()
.any(|p| t.starts_with(p))
})
}
/// Dwords of a type suffix such as `b64` or `f32`.
fn type_dwords(token: &str) -> u8 {
match token {
"b64" | "u64" | "i64" | "f64" => 2,
_ => 1,
}
}
/// (sdst, ssrc0, ssrc1) dwords of a scalar ALU opcode.
fn salu_dwords(name: &str) -> (u8, u8, u8) {
match name {
"s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" | "s_bfe_u64" | "s_bfe_i64"
| "s_bitcmp0_b64" | "s_bitcmp1_b64" => (2, 2, 1),
"s_bfm_b64" | "s_bitset0_b64" | "s_bitset1_b64" | "s_bitreplicate_b64_b32" => (2, 1, 1),
"s_bcnt0_i32_b64" | "s_bcnt1_i32_b64" | "s_ff0_i32_b64" | "s_ff1_i32_b64"
| "s_flbit_i32_b64" | "s_flbit_i32_i64" => (1, 2, 2),
_ => {
let n = type_dwords(name.rsplit('_').next().unwrap_or(""));
(n, n, n)
}
}
}
/// (vdst, [src0, src1, src2]) dwords of a VALU opcode.
fn valu_dwords(name: &str) -> (u8, [u8; 3]) {
let parts: Vec<&str> = name.split('_').collect();
match name {
"v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => (2, [1, 2, 2]),
"v_ldexp_f64" | "v_trig_preop_f64" | "v_cmp_class_f64" | "v_cmpx_class_f64" => {
(2, [2, 1, 2])
}
"v_mad_u64_u32" | "v_mad_i64_i32" => (2, [1, 1, 2]),
"v_qsad_pk_u16_u8" | "v_mqsad_pk_u16_u8" => (2, [2, 1, 2]),
"v_mqsad_u32_u8" => (4, [2, 1, 4]),
"v_frexp_exp_i32_f64" => (1, [2; 3]),
_ if parts.len() == 4 && parts[1] == "cvt" => {
(type_dwords(parts[2]), [type_dwords(parts[3]); 3])
}
_ => {
let n = type_dwords(parts.last().copied().unwrap_or(""));
(n, [n; 3])
}
}
}
/// Dwords of loaded, stored or atomic data, from the opcode name.
fn data_dwords(name: &str) -> u8 {
let mut n: u8 = 1;
for token in name.split('_') {
n = match token {
"dwordx2" | "x2" | "xy" | "b64" | "u64" | "i64" | "f64" => 2,
"dwordx3" | "xyz" | "b96" => 3,
"dwordx4" | "xyzw" | "b128" => 4,
"dwordx8" => 8,
"dwordx16" => 16,
_ => n,
};
}
if name.contains("cmpswap") {
n *= 2;
}
if name.contains("format_d16") {
n = n.div_ceil(2);
}
n
}
/// Address dwords of an image opcode: offset, bias, compare, derivatives,
/// coordinates, then LOD/clamp/mip, packed in pairs with `a16`.
fn image_addr_dwords(name: &str, dim: u8, a16: bool) -> u8 {
// (coordinates, derivatives per direction) for 1D 2D 3D CUBE 1D_ARRAY
// 2D_ARRAY 2D_MSAA 2D_MSAA_ARRAY.
const DIMS: [(u8, u8); 8] = [
(1, 1),
(2, 2),
(3, 3),
(3, 2),
(2, 1),
(3, 2),
(3, 2),
(4, 2),
];
let (coords, grads) = DIMS[usize::from(dim & 7)];
match name {
"image_bvh_intersect_ray" => return if a16 { 8 } else { 11 },
"image_bvh64_intersect_ray" => return if a16 { 9 } else { 12 },
"image_get_resinfo" => return 1,
_ => {}
}
let (mut whole, mut derivs, mut packed): (u8, u8, u8) = (0, 0, coords);
if let Some(rest) = name
.strip_prefix("image_sample")
.or_else(|| name.strip_prefix("image_gather4"))
{
for token in rest.split('_') {
match token {
"o" | "b" | "c" => whole += 1,
"d" | "cd" => derivs = grads,
"l" | "cl" => packed += 1,
_ => {}
}
}
} else if name.contains("_mip") {
packed += 1;
}
if a16 {
whole + 2 * derivs.div_ceil(2) + packed.div_ceil(2)
} else {
whole + 2 * derivs + packed
}
}
+6 -2
View File
@@ -2,8 +2,8 @@
//!
//! Instructions are found by following control flow from offset 0, not by a
//! linear sweep: compilers place data (constant tables) in the code region
//! after the end of the program. Operand fields are not decoded yet; each
//! instruction keeps its raw dwords.
//! after the end of the program. [`Instruction::fields`] decodes the operand
//! fields and [`Instruction::text`] prints them in AMD's SP3 syntax.
//!
//! Encodings by the top bits of the first dword:
//!
@@ -14,7 +14,11 @@
//! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP
//! ```
mod fields;
mod opcodes;
mod sp3;
pub use fields::{Cache, Dpp, Fields, Operand, Sdwa, Valu};
use std::collections::BTreeMap;
+784
View File
@@ -0,0 +1,784 @@
//! Instruction text in AMD's SP3 assembly syntax.
use std::fmt::{self, Display, Write};
use super::fields::{Cache, Dpp, Fields, NULL, Operand, Valu};
use super::{Encoding, Instruction};
impl Instruction {
/// The instruction in SP3 syntax, e.g. `v_add_f32 v1, 0.5, v8`.
/// Branch targets are written `label_<byte offset>`.
pub fn text(&self, wave64: bool) -> String {
let name = self.name().unwrap_or("?");
let ops = operands(self, name, &self.fields(wave64));
if ops.is_empty() {
name.to_owned()
} else {
format!("{name} {ops}")
}
}
}
impl Display for Operand {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Operand::Scalar { code, dwords: 1 } => f.write_str(&scalar_name(code)),
Operand::Scalar {
code: 106,
dwords: 2,
} => f.write_str("vcc"),
Operand::Scalar {
code: 126,
dwords: 2,
} => f.write_str("exec"),
Operand::Scalar { code, dwords } if code < 106 => {
write!(f, "s[{code}:{}]", code + dwords - 1)
}
Operand::Scalar { code, dwords } if (108..124).contains(&code) => {
write!(f, "ttmp[{}:{}]", code - 108, code - 108 + dwords - 1)
}
Operand::Scalar { code, .. } => f.write_str(&scalar_name(code)),
Operand::Vector { reg, dwords: 1 } => write!(f, "v{reg}"),
Operand::Vector { reg, dwords } => {
write!(f, "v[{reg}:{}]", reg as u32 + dwords as u32 - 1)
}
Operand::Const(code) => f.write_str(&const_name(code)),
Operand::Literal(value) => write!(f, "lit(0x{value:08x})"),
Operand::Attr { index, chan, .. } => write!(
f,
"attr{index}.{}",
['x', 'y', 'z', 'w'][usize::from(chan & 3)]
),
}
}
}
fn scalar_name(code: u8) -> String {
match code {
0..=105 => format!("s{code}"),
106 => "vcc_lo".into(),
107 => "vcc_hi".into(),
108..=123 => format!("ttmp{}", code - 108),
124 => "m0".into(),
125 => "null".into(),
126 => "exec_lo".into(),
_ => "exec_hi".into(),
}
}
fn const_name(code: u8) -> String {
match code {
128..=192 => (i32::from(code) - 128).to_string(),
193..=208 => (192 - i32::from(code)).to_string(),
240 => "0.5".into(),
241 => "-0.5".into(),
242 => "1.0".into(),
243 => "-1.0".into(),
244 => "2.0".into(),
245 => "-2.0".into(),
246 => "4.0".into(),
247 => "-4.0".into(),
248 => "0.15915494".into(),
235 => "src_shared_base".into(),
236 => "src_shared_limit".into(),
237 => "src_private_base".into(),
238 => "src_private_limit".into(),
239 => "src_pops_exiting_wave_id".into(),
251 => "src_vccz".into(),
252 => "src_execz".into(),
253 => "src_scc".into(),
254 => "src_lds_direct".into(),
_ => format!("<src {code}>"),
}
}
fn join(ops: impl IntoIterator<Item = String>) -> String {
ops.into_iter().collect::<Vec<_>>().join(", ")
}
fn operands(inst: &Instruction, name: &str, fields: &Fields) -> String {
let mut out = String::new();
match fields {
Fields::Sop { dst, src, imm } => {
let regs = join(dst.iter().chain(src).map(|o| o.to_string()));
out = match (name, imm) {
("s_getreg_b32", Some(imm)) => format!("{regs}, {}", hwreg(*imm)),
("s_setreg_b32" | "s_setreg_imm32_b32", Some(imm)) => {
format!("{}, {regs}", hwreg(*imm))
}
("s_call_b64", Some(imm)) => format!("{regs}, {}", label(inst, *imm)),
(_, Some(imm)) if regs.is_empty() => format!("0x{imm:04x}"),
(_, Some(imm)) => format!("{regs}, 0x{imm:04x}"),
(_, None) => regs,
};
}
Fields::Sopp { imm } => {
out = match name {
"s_endpgm"
| "s_barrier"
| "s_code_end"
| "s_endpgm_saved"
| "s_endpgm_ordered_ps_done"
| "s_wakeup"
| "s_icache_inv"
| "s_ttracedata" => String::new(),
"s_branch" => label(inst, *imm),
n if n.starts_with("s_cbranch_") => label(inst, *imm),
"s_waitcnt" => waitcnt(*imm),
"s_sendmsg" | "s_sendmsghalt" => sendmsg(*imm),
_ => format!("0x{imm:04x}"),
};
}
Fields::Smem {
data,
base,
offset,
soffset,
cache,
} => {
if let Some(data) = data {
let off = match (soffset, offset) {
(Operand::Scalar { code: NULL, .. }, 0) => soffset.to_string(),
(Operand::Scalar { code: NULL, .. }, _) => {
format!("0x{:06x}", offset & 0x1F_FFFF)
}
(_, 0) => soffset.to_string(),
_ => format!("{soffset} offset:0x{:06x}", offset & 0x1F_FFFF),
};
out = format!("{data}, {base}, {off}");
}
flags(&mut out, cache, false);
}
Fields::Valu(v) => out = valu(name, v, inst.encoding),
Fields::Vintrp { dst, src, attr } => {
let src = match (name, src) {
("v_interp_mov_f32", Operand::Const(p)) => ["p10", "p20", "p0"]
.get(usize::from(*p))
.map_or("p?".into(), |p| p.to_string()),
_ => src.to_string(),
};
out = format!("{dst}, {src}, {attr}");
}
Fields::Ds {
dst,
addr,
data,
offset0,
offset1,
gds,
} => {
out = join(dst.iter().chain(addr).chain(data).map(|o| o.to_string()));
if super::fields::ds_pair(name) {
if *offset0 != 0 {
let _ = write!(out, " offset0:{offset0}");
}
if *offset1 != 0 {
let _ = write!(out, " offset1:{offset1}");
}
} else {
let offset = u16::from(*offset1) << 8 | u16::from(*offset0);
if offset != 0 {
let _ = write!(out, " offset:{offset}");
}
}
if *gds {
out.push_str(" gds");
}
}
Fields::Buffer {
data,
addr,
rsrc,
soffset,
offset,
offen,
idxen,
format,
lds,
tfe,
cache,
} => {
if let Some(data) = data {
out = format!("{data}, {addr}, {rsrc}, {soffset}");
if *idxen {
out.push_str(" idxen");
}
if *offen {
out.push_str(" offen");
}
if *offset != 0 {
let _ = write!(out, " offset:{offset}");
}
if let Some(format) = format {
let _ = write!(out, " format:[{}]", buffer_format(*format));
}
}
flags(&mut out, cache, false);
if *lds {
out.push_str(" lds");
}
if *tfe {
out.push_str(" tfe");
}
}
Fields::Image {
data,
addr,
rsrc,
sampler,
dmask,
dim,
unorm,
r128,
a16,
d16,
tfe,
lwe,
cache,
} => {
let addr = match addr.as_slice() {
[one] => one.to_string(),
many => format!(
"[{}]",
many.iter()
.map(|o| o.to_string())
.collect::<Vec<_>>()
.join(",")
),
};
out = join(
[data.to_string(), addr, rsrc.to_string()]
.into_iter()
.chain(sampler.map(|s| s.to_string())),
);
if *dmask != 1 {
let _ = write!(out, " dmask:0x{dmask:x}");
}
let dims = [
"1D",
"2D",
"3D",
"CUBE",
"1D_ARRAY",
"2D_ARRAY",
"2D_MSAA",
"2D_MSAA_ARRAY",
];
let _ = write!(out, " dim:SQ_RSRC_IMG_{}", dims[usize::from(*dim & 7)]);
for (on, text) in [(*r128, "r128"), (*unorm, "unorm")] {
if on {
out.push(' ');
out.push_str(text);
}
}
flags(&mut out, cache, true);
for (on, text) in [(*a16, "a16"), (*d16, "d16"), (*tfe, "tfe"), (*lwe, "lwe")] {
if on {
out.push(' ');
out.push_str(text);
}
}
}
Fields::Flat {
dst,
addr,
data,
saddr,
offset,
lds,
cache,
} => {
let addr = addr.map_or("off".into(), |a| a.to_string());
out = join(
dst.iter()
.map(|o| o.to_string())
.chain([addr])
.chain(data.iter().chain(saddr).map(|o| o.to_string())),
);
if *offset != 0 {
let _ = write!(out, " inst_offset:{offset}");
}
flags(&mut out, cache, false);
if *lds {
out.push_str(" lds");
}
}
Fields::Exp {
target,
src,
compr,
done,
vm,
} => {
let target = match *target {
0..=7 => format!("mrt{target}"),
8 => "mrtz".into(),
9 => "null".into(),
12..=15 => format!("pos{}", target - 12),
20 => "prim".into(),
32..=63 => format!("param{}", target - 32),
_ => format!("<target {target}>"),
};
out = join(
[target].into_iter().chain(
src.iter()
.map(|s| s.map_or("off".into(), |o| o.to_string())),
),
);
for (on, text) in [(*done, " done"), (*compr, " compr"), (*vm, " vm")] {
if on {
out.push_str(text);
}
}
}
}
out
}
/// Cache flags; images write `dlc` first.
fn flags(out: &mut String, cache: &Cache, dlc_first: bool) {
let dlc = (cache.dlc, " dlc");
let (first, last) = if dlc_first {
(dlc, (false, ""))
} else {
((false, ""), dlc)
};
for (on, text) in [first, (cache.glc, " glc"), (cache.slc, " slc"), last] {
if on {
out.push_str(text);
}
}
if out.starts_with(' ') {
out.remove(0);
}
}
fn label(inst: &Instruction, imm: u16) -> String {
let target = inst.offset as i64 + 4 * inst.words.len() as i64 + 4 * i64::from(imm as i16);
format!("label_{target:04X}")
}
fn hwreg(imm: u16) -> String {
let (id, offset, size) = (imm & 0x3F, imm >> 6 & 0x1F, (imm >> 11 & 0x1F) + 1);
let name = match id {
1 => "HW_REG_MODE".into(),
20 => "HW_REG_SHADER_FLAT_SCRATCH_LO".into(),
21 => "HW_REG_SHADER_FLAT_SCRATCH_HI".into(),
25 => "HW_REG_POPS_PACKER".into(),
_ => id.to_string(),
};
if offset == 0 && size == 32 {
format!("hwreg({name})")
} else {
format!("hwreg({name}, {offset}, {size})")
}
}
fn waitcnt(imm: u16) -> String {
let vm = imm & 0xF | (imm >> 14) << 4;
let exp = imm >> 4 & 7;
let lgkm = imm >> 8 & 0x3F;
let mut parts = Vec::new();
if vm != 0x3F {
parts.push(format!("vmcnt({vm})"));
}
if exp != 7 {
parts.push(format!("expcnt({exp})"));
}
if lgkm != 0x3F {
parts.push(format!("lgkmcnt({lgkm})"));
}
if matches!(parts.len(), 0 | 3) {
return format!("0x{imm:04x}");
}
parts.join(" & ")
}
fn sendmsg(imm: u16) -> String {
let (msg, op, stream) = (imm & 0xF, imm >> 4 & 7, imm >> 8 & 3);
let msg_name = match msg {
2 => "MSG_GS".into(),
3 => "MSG_GS_DONE".into(),
7 => "MSG_ORDERED_PS_DONE".into(),
9 => "MSG_GS_ALLOC_REQ".into(),
_ => msg.to_string(),
};
let op_name = ["GS_OP_NOP", "GS_OP_CUT", "GS_OP_EMIT", "GS_OP_EMIT_CUT"]
.get(usize::from(op))
.map_or(op.to_string(), |s| s.to_string());
if msg == 3 && op == 0 {
format!("sendmsg({msg_name}, {op_name})")
} else {
format!("sendmsg({msg_name}, {op_name}, {stream})")
}
}
fn buffer_format(format: u8) -> String {
const NAMES: [&str; 78] = [
"INVALID",
"8_UNORM",
"8_SNORM",
"8_USCALED",
"8_SSCALED",
"8_UINT",
"8_SINT",
"16_UNORM",
"16_SNORM",
"16_USCALED",
"16_SSCALED",
"16_UINT",
"16_SINT",
"16_FLOAT",
"8_8_UNORM",
"8_8_SNORM",
"8_8_USCALED",
"8_8_SSCALED",
"8_8_UINT",
"8_8_SINT",
"32_UINT",
"32_SINT",
"32_FLOAT",
"16_16_UNORM",
"16_16_SNORM",
"16_16_USCALED",
"16_16_SSCALED",
"16_16_UINT",
"16_16_SINT",
"16_16_FLOAT",
"10_11_11_UNORM",
"10_11_11_SNORM",
"10_11_11_USCALED",
"10_11_11_SSCALED",
"10_11_11_UINT",
"10_11_11_SINT",
"10_11_11_FLOAT",
"11_11_10_UNORM",
"11_11_10_SNORM",
"11_11_10_USCALED",
"11_11_10_SSCALED",
"11_11_10_UINT",
"11_11_10_SINT",
"11_11_10_FLOAT",
"10_10_10_2_UNORM",
"10_10_10_2_SNORM",
"10_10_10_2_USCALED",
"10_10_10_2_SSCALED",
"10_10_10_2_UINT",
"10_10_10_2_SINT",
"2_10_10_10_UNORM",
"2_10_10_10_SNORM",
"2_10_10_10_USCALED",
"2_10_10_10_SSCALED",
"2_10_10_10_UINT",
"2_10_10_10_SINT",
"8_8_8_8_UNORM",
"8_8_8_8_SNORM",
"8_8_8_8_USCALED",
"8_8_8_8_SSCALED",
"8_8_8_8_UINT",
"8_8_8_8_SINT",
"32_32_UINT",
"32_32_SINT",
"32_32_FLOAT",
"16_16_16_16_UNORM",
"16_16_16_16_SNORM",
"16_16_16_16_USCALED",
"16_16_16_16_SSCALED",
"16_16_16_16_UINT",
"16_16_16_16_SINT",
"16_16_16_16_FLOAT",
"32_32_32_UINT",
"32_32_32_SINT",
"32_32_32_FLOAT",
"32_32_32_32_UINT",
"32_32_32_32_SINT",
"32_32_32_32_FLOAT",
];
NAMES
.get(usize::from(format))
.map_or(format!("{format}"), |n| format!("BUF_FMT_{n}"))
}
fn valu(name: &str, v: &Valu, encoding: Encoding) -> String {
let bit = |mask: u8, i: usize| mask >> i & 1 != 0;
let mix = name.starts_with("v_fma_mix");
let src = |i: usize| {
let o = v.src[i];
let mut s = o.to_string();
if let Some(sdwa) = v.sdwa
&& bit(sdwa.sext, i)
{
s = format!("sext({s})");
}
if encoding == Encoding::Vop3p {
if mix {
if bit(v.opsel_hi, i) {
s = format!("{}({s})", if bit(v.opsel, i) { "sel_hi" } else { "sel_lo" });
}
if bit(v.neg_hi, i) {
s = format!("abs({s})");
}
if bit(v.neg, i) {
s = format!("-{s}");
}
} else {
if bit(v.neg, i) && bit(v.neg_hi, i) {
s = format!("-{s}");
}
match (bit(v.opsel, i), bit(v.opsel_hi, i)) {
(false, true) => {}
(false, false) => s = format!("sel_lo({s})"),
(true, true) => s = format!("sel_hi({s})"),
(true, false) => s = format!("sel_hi_lo({s})"),
}
}
} else {
if bit(v.abs, i) {
s = format!("abs({s})");
}
if bit(v.neg, i) {
s = format!("-{s}");
}
// v_permlane*: the opsel bits are fi and bound_ctrl.
if bit(v.opsel, i) && !name.starts_with("v_permlane") {
s = format!("sel_hi({s})");
}
}
s
};
let mut ops: Vec<String> = v
.dst
.iter()
.chain(&v.carry)
.map(|o| o.to_string())
.collect();
let mut order: Vec<usize> = (0..v.src.len()).collect();
if name.starts_with("v_interp_") && order.len() > 1 {
// dst, i/j, attribute, then the p1 result for p2.
order.swap(0, 1);
}
ops.extend(order.into_iter().map(src));
let mut out = ops.join(", ");
let mut suffix = |s: &str| {
out.push(' ');
out.push_str(s);
};
if let Some(Operand::Attr { high: true, .. }) = v.src.first() {
suffix("high");
}
let omod = ["", "mul:2", "mul:4", "div:2"][usize::from(v.omod & 3)];
if name.starts_with("v_permlane") {
if v.opsel & 1 != 0 {
suffix("fi:1");
}
if v.opsel & 2 != 0 {
suffix("bound_ctrl:1");
}
}
if let Some(sdwa) = v.sdwa {
if v.clamp {
suffix("clamp");
}
if !omod.is_empty() {
suffix(omod);
}
let sel = [
"BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD", "?",
];
if sdwa.dst_sel != 6 {
suffix(&format!("dst_sel:{}", sel[usize::from(sdwa.dst_sel & 7)]));
}
if sdwa.dst_unused != 0 {
let unused = ["UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE", "?"];
suffix(&format!(
"dst_unused:{}",
unused[usize::from(sdwa.dst_unused & 3)]
));
}
for (i, s) in sdwa.src_sel.iter().enumerate() {
if *s != 6 {
suffix(&format!("src{i}_sel:{}", sel[usize::from(s & 7)]));
}
}
} else {
if !omod.is_empty() {
suffix(omod);
}
if v.clamp {
suffix("clamp");
}
}
match v.dpp {
Some(Dpp::Row {
ctrl,
row_mask,
bank_mask,
bound_ctrl,
fi,
}) => {
suffix(&match ctrl {
0x000..=0x0FF => format!(
"quad_perm:[{},{},{},{}]",
ctrl & 3,
ctrl >> 2 & 3,
ctrl >> 4 & 3,
ctrl >> 6 & 3
),
0x101..=0x10F => format!("row_shl:{}", ctrl & 0xF),
0x111..=0x11F => format!("row_shr:{}", ctrl & 0xF),
0x121..=0x12F => format!("row_ror:{}", ctrl & 0xF),
0x140 => "row_mirror".into(),
0x141 => "row_half_mirror".into(),
0x150..=0x15F => format!("row_share:{}", ctrl & 0xF),
0x160..=0x16F => format!("row_xmask:{}", ctrl & 0xF),
_ => format!("dpp_ctrl:0x{ctrl:x}"),
});
if row_mask != 0xF {
suffix(&format!("row_mask:0x{row_mask:x}"));
}
if bank_mask != 0xF {
suffix(&format!("bank_mask:0x{bank_mask:x}"));
}
if bound_ctrl {
suffix("bound_ctrl:1");
}
if fi {
suffix("fi:1");
}
}
Some(Dpp::Lanes { sel, fi }) => {
let lanes: Vec<String> = (0..8).map(|i| (sel >> (3 * i) & 7).to_string()).collect();
suffix(&format!("dpp8:[{}]", lanes.join(",")));
if fi {
suffix("fi:1");
}
}
None => {}
}
out
}
#[cfg(test)]
mod tests {
use crate::gfx10::{Fields, Operand, decode};
/// Text of each instruction in `words` (a straight-line program).
fn texts(words: &[u32], wave64: bool) -> Vec<String> {
let mut code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
code.extend(0xBF81_0000u32.to_le_bytes()); // s_endpgm
let insts = decode(&code).unwrap();
insts[..insts.len() - 1]
.iter()
.map(|i| i.text(wave64))
.collect()
}
fn one(words: &[u32], wave64: bool) -> String {
let t = texts(words, wave64);
assert_eq!(t.len(), 1, "{t:?}");
t[0].clone()
}
#[test]
fn scalar() {
assert_eq!(
texts(&[0xBF88_0001, 0xBF8C_0070, 0xBE80_03FF, 0x1234_5678], true),
[
"s_cbranch_execz label_0008",
"s_waitcnt vmcnt(0) & lgkmcnt(0)",
"s_mov_b32 s0, lit(0x12345678)",
]
);
assert_eq!(one(&[0x8782_027E], true), "s_and_b64 s[2:3], exec, s[2:3]");
assert_eq!(
one(&[0xF408_0501, 0xFA00_0040], true),
"s_load_dwordx4 s[20:23], s[2:3], 0x000040"
);
assert_eq!(
one(&[0xF420_0144, 0x0400_0000], true),
"s_buffer_load_dword s5, s[8:11], s2"
);
}
#[test]
fn lane_masks_follow_the_wave_size() {
let cmp = [0x7C08_06F0]; // v_cmp_gt_f32 with 0.5 and v3
assert_eq!(one(&cmp, false), "v_cmp_gt_f32 vcc_lo, 0.5, v3");
assert_eq!(one(&cmp, true), "v_cmp_gt_f32 vcc, 0.5, v3");
let vop3 = [0xD401_0106, 0x0001_E501]; // v_cmp_lt_f32 to s6, |v1| < 1.0
assert_eq!(one(&vop3, false), "v_cmp_lt_f32 s6, abs(v1), 1.0");
assert_eq!(one(&vop3, true), "v_cmp_lt_f32 s[6:7], abs(v1), 1.0");
assert_eq!(
one(&[0x0202_0480], false),
"v_cndmask_b32 v1, 0, v2, vcc_lo"
);
assert_eq!(
one(&[0x5006_0801], true),
"v_add_co_ci_u32 v3, vcc, s1, v4, vcc"
);
}
#[test]
fn vector_modifiers() {
assert_eq!(
one(&[0x1004_0AFF, 0x3F00_0001], true),
"v_mul_f32 v2, lit(0x3f000001), v5"
);
assert_eq!(
one(&[0xD54B_8004, 0x2BC0_0501], true),
"v_fma_f32 v4, -v1, s2, 0.5 mul:2 clamp"
);
assert_eq!(
one(&[0x7E02_16F9, 0x0605_0602], true),
"v_cvt_f32_f16 v1, v2 src0_sel:WORD_1"
);
assert_eq!(
one(&[0x7E06_02E9, 0x0539_7701], true),
"v_mov_b32 v3, v1 dpp8:[7,6,5,4,3,2,1,0]"
);
assert_eq!(
one(&[0x7E0A_02FA, 0xFF08_B106], true),
"v_mov_b32 v5, v6 quad_perm:[1,0,3,2] bound_ctrl:1"
);
assert_eq!(
one(&[0xCC20_0C01, 0x2C10_0702], true),
"v_fma_mix_f32 v1, -sel_hi(v2), s3, abs(v4)"
);
}
#[test]
fn memory_and_export() {
assert_eq!(
one(&[0xE034_7010, 0x0102_0402], true),
"buffer_load_dwordx2 v[4:5], v[2:3], s[8:11], s1 idxen offen offset:16 glc"
);
assert_eq!(
one(&[0xD8DC_0302, 0x0600_0001], true),
"ds_read2_b32 v[6:7], v1 offset0:2 offset1:3"
);
assert_eq!(
one(&[0xF800_1C0F, 0x0000_0302], true),
"exp mrt0, v2, v2, v3, v3 done compr vm"
);
}
#[test]
fn image_d16_data_is_packed() {
// Three f16 channels occupy two VGPRs; NSA lists the addresses.
let words = [0xF09C_070A, 0x8024_0801, 0x0000_0005];
assert_eq!(
one(&words, true),
"image_sample_lz v[8:9], [v1,v5], s[16:23], s[4:7] dmask:0x7 dim:SQ_RSRC_IMG_2D d16"
);
let code: Vec<u8> = words
.iter()
.chain(&[0xBF81_0000])
.flat_map(|w| w.to_le_bytes())
.collect();
let Fields::Image { data, addr, .. } = decode(&code).unwrap()[0].fields(true) else {
panic!("not an image instruction");
};
assert_eq!(data, Operand::Vector { reg: 8, dwords: 2 });
assert_eq!(addr.len(), 2);
}
}
+16 -3
View File
@@ -15,7 +15,8 @@
//! payload +0x00 u64 graphics slot count (6)
//! +0x08 u64 record offsets: LS HS ES GS VS PS (0x08..0x30),
//! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF
//! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative)
//! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative),
//! +0x14 u32 flags: bit 5 wave32 (else wave64)
//! ```
//!
//! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped),
@@ -46,6 +47,9 @@ const SLOTS: [(HwStage, usize); 8] = [
(HwStage::Cs, 0x60),
];
const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF;
const RECORD_SIZE: u64 = 0x18;
const RECORD_FLAGS: usize = 0x14;
const FLAG_WAVE32: u32 = 1 << 5;
/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes.
const MAX_UNPACKED: u64 = 16 << 20;
@@ -66,6 +70,8 @@ pub enum HwStage {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeProgram {
pub stage: HwStage,
/// Runs as 64 lanes per wave (else 32); sizes lane masks.
pub wave64: bool,
/// GFX10 machine code.
pub code: Vec<u8>,
}
@@ -135,11 +141,13 @@ fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
if record == ABSENT {
continue;
}
let record = bytes(payload, record, 16).ok_or(Malformed("FSSM record out of bounds"))?;
let record =
bytes(payload, record, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?;
let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?)
.ok_or(Malformed("native code out of bounds"))?;
out.push(NativeProgram {
stage,
wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0,
code: code.to_vec(),
});
}
@@ -174,8 +182,11 @@ mod tests {
let slot = slot(stage);
let record = payload.len() as u64;
payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes());
payload.extend_from_slice(&(record + 16).to_le_bytes());
payload.extend_from_slice(&(record + RECORD_SIZE).to_le_bytes());
payload.extend_from_slice(&(code.len() as u64).to_le_bytes());
let flags = if stage == HwStage::Ps { FLAG_WAVE32 } else { 0 };
payload.extend_from_slice(&[0; 4]);
payload.extend_from_slice(&flags.to_le_bytes());
payload.extend_from_slice(code);
}
let mut out = b"FSSM".to_vec();
@@ -224,10 +235,12 @@ mod tests {
[
NativeProgram {
stage: HwStage::Vs,
wave64: true,
code: VS_CODE.to_vec()
},
NativeProgram {
stage: HwStage::Ps,
wave64: false,
code: PS_CODE.to_vec()
},
]