Merge upstream main 0a722d2 into system runtime branch

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
Adeeb Rahman committed 2026-11-24 10:02:59 -05:00
commit eabab264ea
8 files changed
+2562 -65

No files matched your search

+1 -6
View File
@@ -15,12 +15,7 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- The experimental CLI can run the embedded runtime-services fixture, which round-trips the guest last-error value through two kernel32 imports before drawing a verified Metal frame.
- Import manifests now report emitted adapters, stubs, and existing runtime bindings separately from catalog classifications.
- Generated import conformance tests now execute emitted service handlers and verify unsupported stubs.
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215.
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
+247 -26
View File
@@ -57,6 +57,10 @@ pub enum Op {
MoveScalar(u8, u8),
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
Compare(Comparison, CompareSource, u8),
/// VOPC 16- or 64-bit integer compare writing the Wave32 mask to
/// `vcc_lo`. For 64-bit forms a `Vector` or `Scalar` source and VSRC1 name
/// the low register of a pair.
WideCompare(Comparison, CompareWidth, CompareSource, u8),
/// SOP2 operation writing an SGPR and SCC.
Scalar(ScalarAlu, u8, Source, Source),
/// SOPC `s_cmp_eq_{i32,u32}` (opcodes 0 and 6, identical per guide 12.4).
@@ -72,6 +76,11 @@ pub enum Op {
/// VOP2 32-bit integer form: VDST, SRC0 (VGPR, SGPR, `vcc_lo`, inline
/// integer or literal) and VSRC1. Writes neither VCC nor SCC.
VectorInteger(VectorInteger, u8, CompareSource, u8),
/// VOP1 32-bit integer or bit form: VDST and SRC0 (VGPR, SGPR, `vcc_lo`,
/// inline integer or literal). Writes neither VCC nor SCC.
VectorUnary(VectorUnary, u8, CompareSource),
/// VOP1 `v_swap_b32` (opcode 101): exchanges VDST and the SRC0 VGPR.
Swap(u8, u8),
End,
}
@@ -89,18 +98,27 @@ pub struct Comparison {
}
impl Comparison {
/// The per-lane result, from an exact comparison of the widened operands.
/// The per-lane result for 32-bit operands.
fn holds(self, s0: u32, s1: u32) -> bool {
let widen = |bits: u32| {
if self.signed {
i64::from(bits as i32)
} else {
i64::from(bits)
self.holds_at(CompareWidth::Word, u64::from(s0), u64::from(s1))
}
/// The per-lane result, from an exact comparison of the operands widened
/// from their low `width` bits; higher bits are ignored.
fn holds_at(self, width: CompareWidth, s0: u64, s1: u64) -> bool {
let widen = |bits: u64| -> i128 {
match (width, self.signed) {
(CompareWidth::Half, true) => i128::from(bits as u16 as i16),
(CompareWidth::Half, false) => i128::from(bits as u16),
(CompareWidth::Word, true) => i128::from(bits as u32 as i32),
(CompareWidth::Word, false) => i128::from(bits as u32),
(CompareWidth::Double, true) => i128::from(bits as i64),
(CompareWidth::Double, false) => i128::from(bits),
}
};
let (s0, s1) = (widen(s0), widen(s1));
match self.offset {
// Table 61: V_CMP_F_{I,U}32 `D[threadId] = 0`.
// Table 61: V_CMP_F_{I,U}{32,64} `D[threadId] = 0`.
0 => false,
1 => s0 < s1,
2 => s0 == s1,
@@ -108,12 +126,45 @@ impl Comparison {
4 => s0 > s1,
5 => s0 != s1,
6 => s0 >= s1,
// Table 61: V_CMP_T_{I,U}32 `D[threadId] = 1`.
// Table 61: V_CMP_T_{I,U}{32,64} `D[threadId] = 1`.
_ => true,
}
}
}
/// Operand width of a VOPC integer compare (guide 6.2: the data size is the
/// one named by the instruction).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareWidth {
/// `_I16`/`_U16`: bits 15:0 of each 32-bit source (6.2.5 and 6.8: VOPC
/// selects another half only through SDWA, which is not accepted).
Half,
/// `_I32`/`_U32`.
Word,
/// `_I64`/`_U64`: register pairs with the low dword in the lower register
/// (3.6.3 for SGPRs; for VGPRs the guide states it for 64-bit addresses,
/// 9.1: "ADDR has the LSBs, and ADDR+1 has the MSBs").
Double,
}
impl CompareWidth {
/// Guide 12.9 Tables 59-61: the base opcode of each accepted group plus
/// the relation offset; 16-bit groups have no F (offset 0) or T (7).
fn from_opcode(opcode: u16) -> Option<(Comparison, Self)> {
let (base, signed, width) = match opcode {
128..=135 => (128, true, Self::Word),
192..=199 => (192, false, Self::Word),
137..=142 => (136, true, Self::Half),
169..=174 => (168, false, Self::Half),
160..=167 => (160, true, Self::Double),
224..=231 => (224, false, Self::Double),
_ => return None,
};
let offset = (opcode - base) as u8;
Some((Comparison { offset, signed }, width))
}
}
/// First source of a VOPC compare or a VOP2 integer form.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareSource {
@@ -327,6 +378,54 @@ impl VectorInteger {
}
}
/// VOP1 32-bit integer and bit forms with a general SRC0 (AMD RDNA 2 ISA
/// guide section 12.8). None writes VCC or SCC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorUnary {
/// 55: D = ~S0.
Not,
/// 56: D[31:0] = S0[0:31].
ReverseBits,
/// 57: zeros before the first one from the MSB, -1 if none.
FindFirstOneFromMsb,
/// 58: position of the first one from the LSB, -1 if none.
FindFirstOneFromLsb,
/// 59: bits after the sign bit that equal it, from the MSB; -1 if all
/// 32 bits are equal.
FindSignChange,
}
impl VectorUnary {
/// Opcode bits 16-9 of the VOP1 word.
fn from_opcode(opcode: u8) -> Option<Self> {
Some(match opcode {
55 => Self::Not,
56 => Self::ReverseBits,
57 => Self::FindFirstOneFromMsb,
58 => Self::FindFirstOneFromLsb,
59 => Self::FindSignChange,
_ => return None,
})
}
fn apply(self, s0: u32) -> u32 {
// -1 (all ones) when the scan finds nothing.
let found = |index: u32| if index == 32 { u32::MAX } else { index };
match self {
Self::Not => !s0,
Self::ReverseBits => s0.reverse_bits(),
Self::FindFirstOneFromMsb => found(s0.leading_zeros()),
Self::FindFirstOneFromLsb => found(s0.trailing_zeros()),
Self::FindSignChange => {
// Normalize to a non-negative word: the run after the sign bit
// is then a run of zeros.
let positive = if (s0 as i32) < 0 { !s0 } else { s0 };
found(positive.leading_zeros())
}
}
}
}
/// Execute original little-endian gfx1030 bytes with the synthetic binding ABI.
///
/// Each dispatched lane reads the corresponding input word and may write only
@@ -581,20 +680,38 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
}
// VOPC (bits 31-25 = 0b0111110): SRC0 bits 0-8, VSRC1 bits 9-16, OP bits 17-24.
[lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..]
if matches!(
if CompareWidth::from_opcode(
(u16::from(*tag & 1) << 7) | u16::from(*upper >> 1),
128..=135 | 192..=199
) =>
)
.is_some() =>
{
let opcode = (u16::from(*tag & 1) << 7) | u16::from(*upper >> 1);
let comparison = Comparison {
offset: (opcode & 0x3f) as u8,
signed: opcode < 192,
};
let (comparison, width) = CompareWidth::from_opcode(opcode).unwrap();
let vsrc1 = (packed >> 1) | ((upper & 1) << 7);
let selector = u16::from(*lo) | (u16::from(packed & 1) << 8);
// docs/shaders/vector-compare.md subset: no literal for 16-bit;
// 64-bit takes v[n:n+1] (n <= 254), s[2k:2k+1] (k <= 52) or
// an inline integer, with VSRC1 v[m:m+1] (m <= 254).
let accepted = match width {
CompareWidth::Half => selector != 255,
CompareWidth::Word => true,
CompareWidth::Double => {
vsrc1 != 255
&& matches!(selector, 0..=104 | 128..=208 | 256..=510)
&& (selector >= 128 || selector % 2 == 0)
}
};
if !accepted {
return Err(error(offset, "unsupported VOPC source"));
}
let (src0, length) =
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOPC source")?;
(Op::Compare(comparison, src0, vsrc1), length)
let op = if width == CompareWidth::Word {
Op::Compare(comparison, src0, vsrc1)
} else {
Op::WideCompare(comparison, width, src0, vsrc1)
};
(op, length)
}
// VOP2 integer forms (bit 31 = 0): OP bits 25-30, VDST 17-24,
// VSRC1 9-16, SRC0 0-8.
@@ -608,6 +725,26 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOP2 source")?;
(Op::VectorInteger(kind, dst, src0, vsrc1), length)
}
// VOP1 integer forms (bits 31-25 = 0b0111111): VDST bits 17-24,
// OP 9-16, SRC0 0-8.
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
if VectorUnary::from_opcode((packed >> 1) | ((upper & 1) << 7)).is_some() =>
{
let kind = VectorUnary::from_opcode((packed >> 1) | ((upper & 1) << 7)).unwrap();
let dst = (upper >> 1) | ((tag & 1) << 7);
let (src0, length) =
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOP1 source")?;
(Op::VectorUnary(kind, dst, src0), length)
}
// v_swap_b32: SRC0 must be a VGPR (256-511), since it is written.
[lo, packed, upper, tag @ 0x7e..=0x7f, ..]
if (packed >> 1) | ((upper & 1) << 7) == 101 =>
{
if packed & 1 == 0 {
return Err(error(offset, "v_swap_b32 SRC0 is not a VGPR"));
}
(Op::Swap((upper >> 1) | ((tag & 1) << 7), *lo), 4)
}
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
if packed & 0xfe == 2 && upper & 1 == 0 =>
{
@@ -811,7 +948,9 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
| Op::MoveScalar(dst, _)
| Op::Add(dst, ..)
| Op::Vector(_, dst, ..)
| Op::VectorInteger(_, dst, ..) => {
| Op::VectorInteger(_, dst, ..)
| Op::VectorUnary(_, dst, _)
| Op::Swap(dst, _) => {
if exec != 0
&& registers
.iter()
@@ -918,6 +1057,49 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
results[lane] = Some((dst, kind.apply(s0, read(lane, src1)?)));
}
}
Op::VectorUnary(kind, dst, src0) => {
if exec != 0 {
// Sources are checked once for the wave, as for VOP2.
match src0 {
CompareSource::Vector(register) => {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))?
}
CompareSource::Scalar(register) => {
read_scalar(Source::Register(register))?;
}
CompareSource::Immediate(_) => {}
}
}
for lane in (0..lanes).filter(|&lane| executes(lane)) {
let s0 = match src0 {
CompareSource::Vector(register) => read(lane, register)?,
CompareSource::Scalar(register) => read_scalar(Source::Register(register))?,
CompareSource::Immediate(bits) => bits,
};
results[lane] = Some((dst, kind.apply(s0)));
}
}
// Guide 12.8: tmp = D; D = S0; S0 = tmp, in each active lane.
Op::Swap(dst, src0) => {
if exec != 0 {
for register in [dst, src0] {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))?;
}
}
let mut swapped = Vec::new();
for lane in (0..lanes).filter(|&lane| executes(lane)) {
swapped.push((lane, read(lane, dst)?, read(lane, src0)?));
}
if !swapped.is_empty()
&& pending_read.is_some_and(|register| register == dst || register == src0)
{
return Err(error(offset, "write to immutable or pending VGPR"));
}
for (lane, old_dst, old_src0) in swapped {
registers[lane][usize::from(dst)] = Some(old_src0);
registers[lane][usize::from(src0)] = Some(old_dst);
}
}
Op::ScalarMove(dst, src) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
@@ -1109,30 +1291,69 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
}
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
Op::Compare(comparison, src0, src1) => {
Op::Compare(..) | Op::WideCompare(..) => {
let (comparison, width, src0, src1) = match op {
Op::Compare(comparison, src0, src1) => {
(comparison, CompareWidth::Word, src0, src1)
}
Op::WideCompare(comparison, width, src0, src1) => {
(comparison, width, src0, src1)
}
_ => unreachable!(),
};
let mut mask = 0u32;
if exec != 0 {
// The registers each source occupies: a pair for 64-bit forms.
let span = |register: u8| {
if width == CompareWidth::Double {
vec![register, register + 1]
} else {
vec![register]
}
};
// Sources are checked once for the wave, even if no present lane is active.
let check = |register: u8| {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))
span(register).into_iter().try_for_each(|register| {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))
})
};
let join = |values: Vec<u32>| {
values
.iter()
.rev()
.fold(0u64, |acc, &value| (acc << 32) | u64::from(value))
};
let read_pair = |lane: usize, register: u8| {
span(register)
.into_iter()
.map(|register| read(lane, register))
.collect::<Result<Vec<_>, _>>()
.map(join)
};
let read_scalar_pair = |register: u8| {
span(register)
.into_iter()
.map(|register| read_scalar(Source::Register(register)))
.collect::<Result<Vec<_>, _>>()
.map(join)
};
match src0 {
CompareSource::Vector(register) => check(register)?,
CompareSource::Scalar(register) => {
read_scalar(Source::Register(register))?;
read_scalar_pair(register)?;
}
CompareSource::Immediate(_) => {}
}
check(src1)?;
for lane in (0..lanes).filter(|&lane| executes(lane)) {
let s0 = match src0 {
CompareSource::Vector(register) => read(lane, register)?,
CompareSource::Scalar(register) => {
read_scalar(Source::Register(register))?
}
CompareSource::Immediate(bits) => bits,
CompareSource::Vector(register) => read_pair(lane, register)?,
CompareSource::Scalar(register) => read_scalar_pair(register)?,
// Table 20: an inline integer is the value 0..64 or
// -1..-16 at the operand's width (sign extended).
CompareSource::Immediate(bits) => bits as i32 as i64 as u64,
};
if comparison.holds(s0, read(lane, src1)?) {
if comparison.holds_at(width, s0, read_pair(lane, src1)?) {
mask |= 1 << lane;
}
}
+40 -3
View File
@@ -75,6 +75,29 @@ stream carries no wave-size declaration (the VOPC word has no wave-size field),
so every caller of the translator and the reference establishes Wave32 by
using this ABI; there is no Wave64 entry point to reject.
### 2a. 16-bit and 64-bit compares (reference interpreters only)
The reference (`crates/ref`) and the second interpreter
(`tests/validation/independent_ref.rs`) also accept the `_e32` forms
`v_cmp_{lt,eq,le,gt,ne,ge}_{i16,u16}` (opcodes 137-142, 169-174) and
`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i64,u64}` (160-167, 224-231). The decoder and
the translator still reject them (section 4); these forms have an oracle
but no translation yet.
- 16-bit forms read bits 15:0 of each 32-bit source and ignore bits 31:16
(an inference from guide 6.2, 6.2.5 and 6.8: only SDWA selects a half).
There is no literal source.
- 64-bit forms read a pair: v[n:n+1] with n <= 254, an even-aligned
s[2k:2k+1] with k <= 52 (3.6.3), or an inline integer, which is
sign-extended to 64 bits (-1 is all ones, also for `_u64`; a reading of
Table 20). VSRC1 is v[m:m+1] with m <= 254. Literals and VCC as a 64-bit
source are rejected.
- The result, EXEC masking, VCCZ and the empty-EXEC rule are those of
sections 3 and 5.
The expectations and the guide readings are in
`tests/validation/tests/vopc_wide.rs`.
## 3. Semantics of one supported compare, Wave32
Let E = EXEC_LO before the instruction and A = the set of lanes that exist in
@@ -100,7 +123,9 @@ this wave (all 32 except in a final partial wave, see 7). As an unsigned
- V_CMPX_* (writes EXEC: divergent execution; needs its own contract).
- The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers).
- SDWA and DPP forms; 16-bit, 64-bit and float compares; v_cmp_class.
- SDWA and DPP forms; float compares; v_cmp_class.
- 16-bit and 64-bit compares in the decoder and translator (the reference
interpreters accept the subset in 2a).
- SRC0 inline float constants (240-248), SGPRs other than s0-s106, TTMPs,
M0, EXEC_LO/HI, VCC_HI, SCC/VCCZ/EXECZ selectors, LDS direct.
- A normal-SGPR SRC0 without a known value, when EXEC_LO != 0.
@@ -226,7 +251,17 @@ programs, plus 2 mask-chain programs (252 in all), and the F/T fixture (253) mat
(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`). The F/T oracle's own native Metal cases
run in `vopc_f_t_match_the_guide_on_native_metal`.
A deliberately broken copy of each implementation fails these tests: the
The 16-bit and 64-bit oracle (`tests/validation/tests/vopc_wide.rs`) checks
6,212 lane cases on both reference interpreters, plus 1,208 rejections and the
13 neighbouring opcodes, and that the production compiler still rejects all 28
forms. Its native Metal test stays ignored (and skipped by `scripts/test-gpu.sh`)
until the translator implements these forms. Deliberately broken copies of both
interpreters (16-bit reads of 32 bits, swapped pair halves, zero-extended
inline integers, flipped signedness, reads under empty EXEC and others) each
fail it.
For the 32-bit forms, a deliberately broken copy of each implementation fails
the tests above: the
reference with unsigned-only compares or with the EXEC test removed; the
second interpreter with unsigned-only compares or with no empty-EXEC rule;
the translator with a stale VCC under empty EXEC (CPU), and, on Metal, with
@@ -238,7 +273,9 @@ locally on Apple M5 Pro. It is not agreement with RDNA 2 or Xbox hardware.
## 10. Limitations
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP, 16-bit, 64-bit or float compares.
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP or float compares. 16-bit and
64-bit compares exist only in the reference interpreters (2a); native Metal
agreement for them is not shown.
- A lane-derived VCC_LO cannot reach EXEC or any scalar instruction, so there
is no divergent execution. That needs its own contract.
- The skipped region of a runtime `s_cbranch_vccz` holds only integer vector
+3 -1
View File
@@ -53,4 +53,6 @@ timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test audio_
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
# and VOPC compares.
cargo test --locked -p xenora-semantic-review --no-run
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
# Oracles whose translator side has not landed are skipped by name until it does.
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1 \
--skip vopc_wide_match_the_guide_on_native_metal
+151 -23
View File
@@ -15,7 +15,9 @@
//! and XOR, the stage C forms ANDN2, ORN2, NAND, NOR, XNOR, LSHL, LSHR and
//! ASHR (32-bit), the 32-bit integer forms MIN/MAX (I32, U32), CSELECT, BFM,
//! MUL_I32, BFE (U32, I32), ABSDIFF, LSHL1-4_ADD and MUL_HI (U32, I32), VOP1 move
//! (including from an SGPR),
//! (including from an SGPR), the VOP1 integer forms NOT, BFREV, FFBH_U32,
//! FFBL_B32 and FFBH_I32 (any SRC0 a VOPC compare takes; bit scans as the
//! guide's loops over bits from integer division) and SWAP_B32 (VGPR SRC0),
//! VOP2 bitwise, shift, arithmetic-shift and float, the VOP2 integer forms
//! MUL_I32_I24, MUL_HI_I32_I24, MUL_U32_U24, MUL_HI_U32_U24, MIN/MAX (I32,
//! U32), XNOR and ADD/SUB/SUBREV_NC_U32 (any SRC0 a VOPC compare takes; a
@@ -27,8 +29,10 @@
//! production operator. SOP2 arithmetic runs through a bit-serial ripple
//! adder (subtraction as addition of the complement), not host integer ops.
//!
//! Wave32 VOPC integer compares (`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i32,u32}_e32`,
//! contract `docs/shaders/vector-compare.md`) need all lanes of a wave, so execution
//! Wave32 VOPC integer compares
//! (`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i32,u32,i64,u64}_e32` and
//! `v_cmp_{lt,eq,le,gt,ne,ge}_{i16,u16}_e32`, contract
//! `docs/shaders/vector-compare.md`) need all lanes of a wave, so execution
//! runs lockstep waves of 32 consecutive dispatch indices with wave-uniform
//! scalar state and per-lane vector state. A lane-local failure stops only that
//! lane and the lowest-index error is reported, so programs without compares
@@ -76,9 +80,11 @@ enum Insn {
/// `v_mov_b32_e32 vD, vcc_lo`.
VMovFromVcc(u8),
/// VOPC compare into VCC_LO: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t.
/// `bits` is 16, 32 or 64; 64-bit register operands name the low register of a pair.
VCmp {
relation: u8,
signed: bool,
bits: u32,
src0: CmpSrc,
src1: u8,
},
@@ -91,6 +97,10 @@ enum Insn {
VXor(u8, u8, u8),
/// VOP2 integer opcode 9-12, 17-20, 30 or 37-39: VDST, SRC0, VSRC1.
VInt(u32, u8, CmpSrc, u8),
/// VOP1 integer opcode 55-59: VDST, SRC0.
VUnary(u32, u8, CmpSrc),
/// `v_swap_b32 vD, vS` (VOP1 opcode 101).
VSwap(u8, u8),
VAddF(u8, u8, u8),
VMulF(u8, u8, u8),
Load(u8),
@@ -196,6 +206,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
Insn::VCmp {
relation,
signed,
bits,
src0,
src1,
} => {
@@ -208,7 +219,7 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
&lanes,
&sgpr,
execution_mask,
(relation, signed, src0, src1),
(relation, signed, bits, src0, src1),
offset,
)
.map(|mask| {
@@ -545,29 +556,58 @@ fn compare(
lanes: &[Lane],
sgpr: &[Option<u32>; 128],
execution_mask: u32,
(relation, signed, src0, src1): (u8, bool, CmpSrc, u8),
(relation, signed, bits, src0, src1): (u8, bool, u32, CmpSrc, u8),
offset: usize,
) -> Result<u32, String> {
if execution_mask == 0 {
// Encoding already validated; nothing is read (contract 5).
return Ok(0);
}
let scalar_src0 = match src0 {
CmpSrc::Sgpr(reg) => {
Some(sgpr[reg as usize].ok_or_else(|| format!("{offset:#x}: uninitialized s{reg}"))?)
// Registers per operand: a 64-bit operand is {reg (bits 31:0), reg+1 (63:32)}.
let count: u8 = if bits == 64 { 2 } else { 1 };
let read_s = |reg: u8| -> Result<u64, String> {
let mut value = 0u64;
for half in (0..count).rev() {
let r = reg + half;
let word =
sgpr[r as usize].ok_or_else(|| format!("{offset:#x}: uninitialized s{r}"))?;
value = value * (1 << 32) + u64::from(word);
}
CmpSrc::Vcc => Some(sgpr[106].ok_or_else(|| format!("{offset:#x}: uninitialized vcc_lo"))?),
CmpSrc::Imm(value) => Some(value),
Ok(value)
};
let read_v = |lane: &Lane, reg: u8| -> Result<u64, String> {
let mut value = 0u64;
for half in (0..count).rev() {
value = value * (1 << 32) + u64::from(read_vgpr(lane, reg + half, offset)?);
}
Ok(value)
};
let scalar_src0 = match src0 {
CmpSrc::Sgpr(reg) => Some(read_s(reg)?),
CmpSrc::Vcc => {
Some(u64::from(sgpr[106].ok_or_else(|| {
format!("{offset:#x}: uninitialized vcc_lo")
})?))
}
// Inline integers -16..64 keep their value at every width; a
// 32-bit literal (32-bit forms only) is used as its 32 bits.
CmpSrc::Imm(value) if bits == 64 && value >= 0x8000_0000 => {
Some(u64::from(value) + 0xffff_ffff_0000_0000)
}
CmpSrc::Imm(value) => Some(u64::from(value)),
CmpSrc::Vgpr(_) => None,
};
// VGPR readiness is wave-uniform; validate it on every existing lane so
// acceptance does not depend on which lanes are active.
for lane in lanes {
if let CmpSrc::Vgpr(reg) = src0 {
read_vgpr(lane, reg, offset)?;
read_v(lane, reg)?;
}
read_vgpr(lane, src1, offset)?;
read_v(lane, src1)?;
}
// Only the low `bits` bits take part (16-bit forms ignore bits 31:16).
let keep = u64::MAX >> (64 - bits);
let sign = 1u64 << (bits - 1);
let mut mask = 0u32;
for (n, lane) in lanes.iter().enumerate() {
if (execution_mask >> n) & 1 == 0 {
@@ -575,16 +615,13 @@ fn compare(
}
let a = match (scalar_src0, src0) {
(Some(value), _) => value,
(None, CmpSrc::Vgpr(reg)) => read_vgpr(lane, reg, offset)?,
(None, CmpSrc::Vgpr(reg)) => read_v(lane, reg)?,
(None, _) => unreachable!(),
};
let b = read_vgpr(lane, src1, offset)?;
let b = read_v(lane, src1)?;
let (a, b) = (a & keep, b & keep);
// Signed order equals unsigned order after flipping the sign bit.
let (a, b) = if signed {
(a ^ 0x8000_0000, b ^ 0x8000_0000)
} else {
(a, b)
};
let (a, b) = if signed { (a ^ sign, b ^ sign) } else { (a, b) };
// Guide 12.9 Table 59 offsets; F (0) and T (7) ignore the operand
// values but still read them (contract 5: sources are validated).
let pass = match relation {
@@ -689,6 +726,8 @@ fn lane_step(
| Insn::VShiftRight(dst, ..)
| Insn::VShiftRightArithmetic(dst, ..)
| Insn::VInt(_, dst, ..)
| Insn::VUnary(_, dst, _)
| Insn::VSwap(dst, _)
| Insn::VAddF(dst, ..)
| Insn::VMulF(dst, ..) => {
if execution_mask != 0 && lane.vgpr[usize::from(dst)].is_none() {
@@ -718,6 +757,22 @@ fn lane_step(
}
read_vgpr(lane, src1, offset)?;
}
Insn::VUnary(_, _, src0) => match src0 {
CmpSrc::Sgpr(reg) => {
read_s(reg)?;
}
CmpSrc::Vcc => {
read_vcc()?;
}
CmpSrc::Vgpr(reg) => {
read_vgpr(lane, reg, offset)?;
}
CmpSrc::Imm(_) => {}
},
Insn::VSwap(dst, src0) => {
read_vgpr(lane, dst, offset)?;
read_vgpr(lane, src0, offset)?;
}
_ => {}
}
}
@@ -823,6 +878,25 @@ fn lane_step(
};
(dst, vector_integer(opcode, a, read_v(src1)?))
}
Insn::VUnary(opcode, dst, src0) => {
check_destination(dst, pending_read, offset)?;
let a = match src0 {
CmpSrc::Sgpr(reg) => read_s(reg)?,
CmpSrc::Vcc => read_vcc()?,
CmpSrc::Imm(value) => value,
CmpSrc::Vgpr(reg) => read_v(reg)?,
};
(dst, vector_unary(opcode, a))
}
// Guide 12.8: tmp = D; D = S0; S0 = tmp. Both are VGPR writes.
Insn::VSwap(dst, src0) => {
let (old_dst, old_src0) = (read_v(dst)?, read_v(src0)?);
check_destination(dst, pending_read, offset)?;
check_destination(src0, pending_read, offset)?;
lane.vgpr[dst as usize] = Some(old_src0);
lane.vgpr[src0 as usize] = Some(old_dst);
return Ok(());
}
Insn::VAddF(dst, a, b) => {
check_destination(dst, pending_read, offset)?;
(dst, exact_float(true, read_v(a)?, read_v(b)?, offset)?)
@@ -837,6 +911,22 @@ fn lane_step(
Ok(())
}
/// D of VOP1 integer opcode `opcode` (guide 12.8 pseudocode) for S0 = `value`.
fn vector_unary(opcode: u32, value: u32) -> u32 {
// Bit i of S0, by integer division rather than a host shift.
let bit = |i: u32| (value / 2_u32.pow(i)) % 2 == 1;
// D = -1 unless the loop finds a position.
let found = |position: Option<u32>| position.unwrap_or(u32::MAX);
match opcode {
55 => u32::MAX - value,
// D[31:0] = S0[0:31]: S0 bit 0 becomes D bit 31.
56 => (0..32).fold(0, |word, i| word * 2 + u32::from(bit(i))),
57 => found((0..32).find(|&i| bit(31 - i))),
58 => found((0..32).find(|&i| bit(i))),
_ => found((1..32).find(|&i| bit(31 - i) != bit(31))),
}
}
/// D of VOP2 integer opcode `opcode` (guide 12.7) for S0 = `a`, S1 = `b`.
fn vector_integer(opcode: u32, a: u32, b: u32) -> u32 {
// Signed order equals unsigned order after flipping the sign bit.
@@ -1039,20 +1129,58 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
};
return Ok((Insn::VMov(dst, src), len));
}
// VOP1 integer forms: bits 31:25 = 0b0111111, VDST 24:17, OP 16:9, SRC0 8:0.
if first >> 25 == 0b011_1111 {
let dst = (first >> 17) as u8;
match (first >> 9) & 0xff {
opcode @ 55..=59 => {
let (src0, len) = vector_src0(code, offset, first, "VOP1")?;
return Ok((Insn::VUnary(opcode, dst, src0), len));
}
// SRC0 is written back, so only a VGPR is meaningful.
101 => {
return match vector_src0(code, offset, first, "VOP1")? {
(CmpSrc::Vgpr(src0), _) => Ok((Insn::VSwap(dst, src0), 4)),
_ => Err(fail("v_swap_b32 needs a VGPR SRC0")),
};
}
_ => {}
}
}
// VOPC: bits 31:25 = 0b0111110, OP 24:17, VSRC1 16:9, SRC0 8:0.
if first >> 25 == 0b011_1110 {
let opcode = (first >> 17) & 0xff;
let (signed, relation) = match opcode {
128..=135 => (true, opcode - 128),
192..=199 => (false, opcode - 192),
// Guide 12.9 Table 61 opcode groups (16-bit groups lack F and T).
let (signed, bits, relation) = match opcode {
128..=135 => (true, 32, opcode - 128),
192..=199 => (false, 32, opcode - 192),
137..=142 => (true, 16, opcode - 136),
169..=174 => (false, 16, opcode - 168),
160..=167 => (true, 64, opcode - 160),
224..=231 => (false, 64, opcode - 224),
_ => return Err(fail("unsupported VOPC opcode")),
};
let (src0, len) = vector_src0(code, offset, first, "VOPC")?;
let src1 = (first >> 9) as u8;
// Accepted subset: no literal for 16-bit forms; 64-bit forms take an
// even SGPR pair below VCC, a VGPR pair below v255 or an inline integer.
let allowed = match (bits, src0) {
(16 | 64, CmpSrc::Imm(_)) if len == 8 => false,
(64, CmpSrc::Vcc) => false,
(64, CmpSrc::Sgpr(reg)) => reg % 2 == 0 && src1 != 255,
(64, CmpSrc::Vgpr(reg)) => reg != 255 && src1 != 255,
(64, _) => src1 != 255,
_ => true,
};
if !allowed {
return Err(fail("unsupported VOPC operand"));
}
let insn = Insn::VCmp {
relation: relation as u8,
signed,
bits,
src0,
src1: (first >> 9) as u8,
src1,
};
return Ok((insn, len));
}
+867
View File
@@ -0,0 +1,867 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent per-lane expected values for six 32-bit VOP1 integer and bit
//! forms (#215): `v_not_b32`, `v_bfrev_b32`, `v_ffbh_u32`, `v_ffbl_b32`,
//! `v_ffbh_i32` and `v_swap_b32`, all `_e32`.
//!
//! The expectations are written below from the public AMD "RDNA 2" Instruction
//! Set Architecture Reference Guide only: section 12.8 "VOP1 Instructions"
//! (pseudocode, descriptions and functional examples), section 13.3.2 for the
//! VOP1 word and the vector operand table for SRC0 (SGPRs, `vcc_lo`, inline
//! integers, the literal, VGPRs). Nothing here comes from the ISA crate, the
//! semantic registry, the decoder or the shader compiler. Every case runs on
//! the reference interpreter `xenora_ref` and on the second interpreter
//! `independent_ref`; the ignored test also runs the translated MSL on native
//! Metal.
//!
//! Readings of the guide (not hardware evidence):
//! - The bit scans return -1 (all ones) when the loop finds nothing, as the
//! pseudocode's `D.i = -1` initial value says; V_FFBH_I32 starts at bit 30,
//! so 0 and -1 both give -1 (the guide's own examples).
//! - V_SWAP_B32 is `tmp = D; D = S0; S0 = tmp`, so SRC0 must be a VGPR; with
//! VDST = SRC0 the register keeps its value.
//! - None of the six writes VCC or SCC (no carry or compare output is listed).
//! - A lane whose EXEC bit is clear keeps its old VGPRs (guide section 3.3).
//!
//! Left out on purpose: float ops and conversions (they wait for the float
//! contract), V_READFIRSTLANE_B32 (lane-crossing, SGPR result), the
//! M0-relative moves (V_MOVREL*, V_SWAPREL_B32), V_NOP, V_PIPEFLUSH and
//! V_CLREXCP (no integer result), and V_SAT_PK_U8_I16, whose guide entry
//! calls it a "saturating add" and does not define `sat8`.
#[path = "operand_domains/harness.rs"]
#[allow(dead_code)]
mod harness;
#[path = "../independent_ref.rs"]
mod independent_ref;
use std::collections::BTreeMap;
use harness::{Case, words};
use xenora_shader::{Architecture, CompileError, compile};
/// The five one-source forms with their ENC_VOP1 opcodes (guide 12.8).
#[derive(Clone, Copy, Debug, PartialEq)]
enum Form {
Not = 55,
Bfrev = 56,
FfbhU32 = 57,
FfblB32 = 58,
FfbhI32 = 59,
}
const FORMS: [(Form, &str); 5] = [
(Form::Not, "v_not_b32"),
(Form::Bfrev, "v_bfrev_b32"),
(Form::FfbhU32, "v_ffbh_u32"),
(Form::FfblB32, "v_ffbl_b32"),
(Form::FfbhI32, "v_ffbh_i32"),
];
const SWAP: u32 = 101;
const SWAP_NAME: &str = "v_swap_b32";
/// S0 bit `i` (0 = LSB).
fn bit(s: u32, i: u32) -> u32 {
(s >> i) & 1
}
/// D for S0 = `s`, transcribed from the guide 12.8 pseudocode.
fn expect(form: Form, s: u32) -> u32 {
match form {
// D.u = ~S0.u.
Form::Not => s ^ 0xffff_ffff,
// D.u[31:0] = S0.u[0:31].
Form::Bfrev => {
let mut d = 0;
for i in 0..32 {
d |= bit(s, i) << (31 - i);
}
d
}
// for i in 0..31: if S0.u[31 - i] == 1 then D.i = i.
Form::FfbhU32 => {
for i in 0..32 {
if bit(s, 31 - i) == 1 {
return i;
}
}
u32::MAX
}
// for i in 0..31: if S0.u[i] == 1 then D.i = i.
Form::FfblB32 => {
for i in 0..32 {
if bit(s, i) == 1 {
return i;
}
}
u32::MAX
}
// for i in 1..31: if S0.i[31 - i] != S0.i[31] then D.i = i.
Form::FfbhI32 => {
for i in 1..32 {
if bit(s, 31 - i) != bit(s, 31) {
return i;
}
}
u32::MAX
}
}
}
/// The guide's functional examples for the three bit scans (12.8).
const GUIDE_EXAMPLES: [(Form, u32, u32); 17] = [
(Form::FfbhU32, 0x0000_0000, 0xffff_ffff),
(Form::FfbhU32, 0x8000_00ff, 0),
(Form::FfbhU32, 0x1000_00ff, 3),
(Form::FfbhU32, 0x0000_ffff, 16),
(Form::FfbhU32, 0x0000_0001, 31),
(Form::FfblB32, 0x0000_0000, 0xffff_ffff),
(Form::FfblB32, 0xff00_0001, 0),
(Form::FfblB32, 0xff00_0008, 3),
(Form::FfblB32, 0xffff_0000, 16),
(Form::FfblB32, 0x8000_0000, 31),
(Form::FfbhI32, 0x0000_0000, 0xffff_ffff),
(Form::FfbhI32, 0x4000_0000, 1),
(Form::FfbhI32, 0x8000_0000, 1),
(Form::FfbhI32, 0x0fff_ffff, 4),
(Form::FfbhI32, 0xffff_0000, 16),
(Form::FfbhI32, 0xffff_fffe, 31),
(Form::FfbhI32, 0xffff_ffff, 0xffff_ffff),
];
const VALUES: [u32; 18] = [
0x0000_0000,
0x0000_0001,
0x0000_0002,
0x007f_ffff,
0x0080_0000,
0x0080_0001,
0x00ff_ffff,
0x0100_0000,
0x1234_5678,
0x5555_5555,
0x7fff_ffff,
0x8000_0000,
0x8000_0001,
0xaaaa_aaaa,
0xff00_0001,
0xff80_0000,
0xffff_fffe,
0xffff_ffff,
];
/// The other 14 lane inputs, so all 32 lanes differ.
const MORE_LANES: [u32; 14] = [
0x007f_fffe,
0x00ff_fffe,
0x0100_0001,
0x00c0_0000,
0xff7f_ffff,
0xff80_0001,
0xffff_0000,
0x0000_ffff,
0x4000_0000,
0xc000_0000,
0x8765_4321,
0x0f0f_0f0f,
0x7fff_fffe,
0x1fff_ffff,
];
const LITERALS: [u32; 9] = [
0,
1,
0x7fff_ffff,
0x8000_0000,
u32::MAX,
0x00ff_ffff,
0x0080_0000,
0xff80_0000,
0x0100_0001,
];
const SGPR_VALUES: [u32; 3] = [0x8000_0000, 0x00ff_ffff, 0xff80_0001];
/// XORed with v1 to make a second per-lane VGPR that differs from v1.
const PAIR_KEYS: [u32; 5] = [0x00ff_ffff, 0x8000_0000, u32::MAX, 0x0080_0001, 0x5555_5555];
/// The last one is set explicitly, as a full EXEC written by `s_mov_b32`.
const EXEC_MASKS: [u32; 7] = [
0,
0x5555_5555,
0xaaaa_aaaa,
0x8000_0001,
0x0000_ffff,
0x7fff_fffe,
u32::MAX,
];
/// XORed with v1 to give every lane its own old VGPR before a masked write.
const OLD: u32 = 0x0bad_f00d;
const COUNTS: [(&str, usize); 17] = [
("vop1 domain", 5 * (1 + 18)),
("vop1 bit positions", 5 * 4),
("vop1 aliasing", 5),
("vop1 inline integer", 5 * 81),
("vop1 literal", 5 * 9),
("vop1 sgpr source", 5 * 2 * 3),
("vop1 vcc_lo source", 5 * 3),
("vop1 max register", 5 * 2),
("vop1 exec", 5 * (7 + 3)),
("vop1 partial wave", 5 * 3),
("vop1 no vcc or scc write", 5 * 5),
("swap lane pairs", 5 * 2),
("swap same register", 1),
("swap max register", 4),
("swap exec", 7 * 2),
("swap partial wave", 3),
("swap no vcc or scc write", 5),
];
/// Per one-source form: a missing literal and every SRC0 selector outside the
/// supported subset (107-127 and 209-254, with the SDWA and DPP extension
/// dword where one belongs); for V_SWAP_B32 every selector 0-255; and for
/// all six a read of and a write to a VGPR with a load outstanding.
const REJECTIONS: usize = 5 * (1 + 21 + 46) + 256 + 2 + 6 * 2;
const LITERAL: u32 = 255;
const VCC_LO: u32 = 106;
/// ENCODING 0b0111111 in bits 25-31, VDST 17-24, OP 9-16, SRC0 0-8 (guide
/// 13.3.2); SRC0 256 + n is VGPR n.
fn vop1(op: u32, dst: u32, src0: u32) -> u32 {
0x7e00_0000 | dst << 17 | op << 9 | src0
}
const fn vgpr(n: u32) -> u32 {
256 + n
}
/// `v_mov_b32 v<reg>, literal` (VOP1 opcode 1).
fn vmov(reg: u32, value: u32) -> [u32; 2] {
[0x7e00_02ff | reg << 17, value]
}
/// `s_mov_b32 s<reg>, literal` (SOP1 opcode 3).
fn smov(reg: u32, value: u32) -> [u32; 2] {
[0xbe80_03ff | reg << 16, value]
}
/// `v_xor_b32 v<dst>, v<a>, v<b>` (VOP2 opcode 29, supported before this set).
fn vxor(dst: u32, a: u32, b: u32) -> u32 {
29 << 25 | dst << 17 | b << 9 | vgpr(a)
}
/// `s_mov_b32 exec_lo, -1`.
const FULL_EXEC: u32 = 0xbefe_03c1;
/// `s_cmp_eq_u32 0, 0` (SCC = 1) and `s_cmp_eq_u32 0, 1` (SCC = 0).
const SCC_SET: u32 = 0xbf06_8080;
const SCC_CLEAR: u32 = 0xbf06_8180;
/// v6 = vcc_lo; v2 ^= v6; `s_cbranch_scc0` over v2 ^= v1.
const FLAG_TAIL: [u32; 4] = [0x7e0c_026a, 0x3a04_0506, 0xbf84_0001, 0x3a04_0501];
/// Load v1 = lane input, then `setup`, the ALU words, `after`, then
/// v2 = v<result> (unless it is v2) and store v2.
fn program(setup: &[u32], alu: &[u32], after: &[u32], result: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
code.extend(setup);
code.extend(alu);
code.extend(after);
if result != 2 {
code.push(0x7e04_0300 | result);
}
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
/// The ALU word's byte offset in `program` with `setup`.
fn alu_offset(setup: &[u32]) -> usize {
12 + 4 * setup.len()
}
fn lanes() -> Vec<u32> {
VALUES.iter().chain(&MORE_LANES).copied().collect()
}
/// A case whose lane `n` (dispatch index) with input `x` expects `lane(n, x)`.
fn case(
name: &'static str,
family: &'static str,
label: String,
code: Vec<u8>,
input: Vec<u32>,
lane: impl Fn(usize, u32) -> u32,
) -> Case {
let expected = input.iter().enumerate().map(|(n, &x)| lane(n, x)).collect();
Case {
form: name,
family,
label: format!("{name} {label}"),
code,
input,
expected,
}
}
/// D where the lane is active under `exec` (bit `n % 32`), else the old value.
fn masked(exec: u32, n: usize, d: u32, old: u32) -> u32 {
if exec >> (n % 32) & 1 == 1 { d } else { old }
}
fn inline_integer(selector: u32) -> u32 {
match selector {
128..=192 => selector - 128,
193..=208 => (-((selector - 192) as i32)) as u32,
_ => unreachable!("not an integer inline constant"),
}
}
/// Lane `n`'s input in a bit-position case.
type Pattern = fn(usize) -> u32;
/// 45 lanes: one full wave and a final wave of 13.
fn long_lanes() -> Vec<u32> {
lanes()
.into_iter()
.chain(MORE_LANES.into_iter().take(13))
.collect()
}
fn unary_cases(cases: &mut Vec<Case>) {
for (form, name) in FORMS {
let op = form as u32;
let f = move |s| expect(form, s);
// The 32 lane inputs directly, then each boundary value from a VGPR.
let code = program(&[], &[vop1(op, 2, vgpr(1))], &[], 2);
cases.push(case(
name,
"vop1 domain",
"v1".into(),
code,
lanes(),
|_, x| f(x),
));
for b in VALUES {
let code = program(&vmov(3, b), &[vop1(op, 2, vgpr(3))], &[], 2);
let label = format!("v3 = {b:#x}");
cases.push(case(name, "vop1 domain", label, code, lanes(), |_, _| f(b)));
}
// Every single-bit position, every single zero, and every run of ones
// from the MSB and from the LSB: lane n gets the shifted pattern.
let patterns: [(&str, Pattern); 4] = [
("1 << n", |n| 1 << n),
("!(1 << n)", |n| !(1 << n)),
("-1 << n", |n| u32::MAX << n),
("-1 >> n", |n| u32::MAX >> n),
];
for (label, pattern) in patterns {
let input = (0..32).map(pattern).collect();
let code = program(&[], &[vop1(op, 2, vgpr(1))], &[], 2);
let family = "vop1 bit positions";
cases.push(case(name, family, label.into(), code, input, |_, x| f(x)));
}
// VDST equal to SRC0.
let code = program(&[], &[vop1(op, 1, vgpr(1))], &[], 1);
let family = "vop1 aliasing";
cases.push(case(
name,
family,
"v1 = v1".into(),
code,
lanes(),
|_, x| f(x),
));
// Every integer inline constant (-16..64) as SRC0.
for selector in 128..=208 {
let value = inline_integer(selector);
let code = program(&[], &[vop1(op, 2, selector)], &[], 2);
let label = format!("inline {selector} ({value:#x})");
let family = "vop1 inline integer";
cases.push(case(name, family, label, code, lanes(), |_, _| f(value)));
}
// One literal dword after the VOP1 word as SRC0.
for literal in LITERALS {
let code = program(&[], &[vop1(op, 2, LITERAL), literal], &[], 2);
let label = format!("literal {literal:#x}");
let family = "vop1 literal";
cases.push(case(name, family, label, code, lanes(), |_, _| f(literal)));
}
// SGPR SRC0: s8 and s105, the highest SGPR (guide 5.2), and vcc_lo.
for (reg, family) in [
(8, "vop1 sgpr source"),
(105, "vop1 sgpr source"),
(VCC_LO, "vop1 vcc_lo source"),
] {
for value in SGPR_VALUES {
let code = program(&smov(reg, value), &[vop1(op, 2, reg)], &[], 2);
let label = format!("s{reg} = {value:#x}");
cases.push(case(name, family, label, code, lanes(), |_, _| f(value)));
}
}
// v255, the highest VGPR, as VDST and as SRC0.
let family = "vop1 max register";
let code = program(&[], &[vop1(op, 255, vgpr(1))], &[], 255);
cases.push(case(
name,
family,
"v255 = v1".into(),
code,
lanes(),
|_, x| f(x),
));
let b = 0x8000_0001;
let code = program(&vmov(255, b), &[vop1(op, 2, vgpr(255))], &[], 2);
cases.push(case(
name,
family,
"v2 = v255".into(),
code,
lanes(),
|_, _| f(b),
));
// EXEC around the ALU word: v2 = v1 ^ OLD before it, so each inactive
// lane must keep its own old value; EXEC is -1 again for the store.
let mut setup = vmov(5, OLD).to_vec();
setup.push(vxor(2, 5, 1));
let family = "vop1 exec";
for exec in EXEC_MASKS {
let mut before = setup.clone();
before.extend(smov(126, exec));
let code = program(&before, &[vop1(op, 2, vgpr(1))], &[FULL_EXEC], 2);
let label = format!("exec {exec:#x}, v1");
cases.push(case(name, family, label, code, lanes(), |n, x| {
masked(exec, n, f(x), x ^ OLD)
}));
}
// Partial EXEC with a scalar SRC0 (s8), and a literal also under
// empty EXEC: its dword is still consumed.
let exec = 0x0f0f_0f0f;
let value = 0xff80_0003;
let mut before = setup.clone();
before.extend(smov(8, value));
before.extend(smov(126, exec));
let code = program(&before, &[vop1(op, 2, 8)], &[FULL_EXEC], 2);
let label = format!("exec {exec:#x}, s8 = {value:#x}");
cases.push(case(name, family, label, code, lanes(), |n, x| {
masked(exec, n, f(value), x ^ OLD)
}));
for exec in [exec, 0] {
let mut before = setup.clone();
before.extend(smov(126, exec));
let alu = [vop1(op, 2, LITERAL), value];
let code = program(&before, &alu, &[FULL_EXEC], 2);
let label = format!("exec {exec:#x}, literal {value:#x}");
cases.push(case(name, family, label, code, lanes(), |n, x| {
masked(exec, n, f(value), x ^ OLD)
}));
}
// A final wave with absent lanes: 7 lanes, and 45 lanes, also with
// partial EXEC in both waves.
let family = "vop1 partial wave";
let code = program(&setup, &[vop1(op, 2, vgpr(1))], &[], 2);
let short = lanes()[..7].to_vec();
let label = "7 lanes".into();
cases.push(case(name, family, label, code.clone(), short, |_, x| f(x)));
let label = "45 lanes".into();
cases.push(case(name, family, label, code, long_lanes(), |_, x| f(x)));
let exec = 0x5555_5555;
let mut before = setup.clone();
before.extend(smov(126, exec));
let code = program(&before, &[vop1(op, 2, vgpr(1))], &[FULL_EXEC], 2);
let label = format!("45 lanes, exec {exec:#x}");
cases.push(case(name, family, label, code, long_lanes(), |n, x| {
masked(exec, n, f(x), x ^ OLD)
}));
// VCC_LO seeded to 0 or -1 and SCC to 0 or 1 before the ALU word.
// Afterwards each lane outputs D ^ VCC_LO, XORed with its input when
// SCC is set, so any VCC or SCC write changes the output.
let family = "vop1 no vcc or scc write";
for vcc in [0, u32::MAX] {
for scc in [false, true] {
let mut setup = smov(VCC_LO, vcc).to_vec();
setup.push(if scc { SCC_SET } else { SCC_CLEAR });
let code = program(&setup, &[vop1(op, 2, vgpr(1))], &FLAG_TAIL, 2);
let label = format!("vcc_lo {vcc:#x}, scc {scc}");
cases.push(case(name, family, label, code, lanes(), |_, x| {
f(x) ^ vcc ^ if scc { x } else { 0 }
}));
}
}
// The same under partial EXEC with SCC = 1 and VCC_LO bits both inside
// and outside EXEC, so a VCC write limited to active lanes also shows.
let (exec, vcc) = (0x0f0f_0f0f, 0x0000_00f3);
let mut before = setup.clone();
before.extend(smov(VCC_LO, vcc));
before.push(SCC_SET);
before.extend(smov(126, exec));
let mut after = vec![FULL_EXEC];
after.extend(FLAG_TAIL);
let code = program(&before, &[vop1(op, 2, vgpr(1))], &after, 2);
let label = format!("exec {exec:#x}, vcc_lo {vcc:#x}, scc true");
cases.push(case(name, family, label, code, lanes(), |n, x| {
masked(exec, n, f(x), x ^ OLD) ^ vcc ^ x
}));
}
}
fn swap_cases(cases: &mut Vec<Case>) {
let name = SWAP_NAME;
// v4 = v1 ^ key, then swap v4 (VDST) with v1 (SRC0); either register is
// stored, so both writes are checked.
for key in [PAIR_KEYS[0], PAIR_KEYS[2], PAIR_KEYS[4]]
.into_iter()
.chain([0x1234_5678, 0x8000_0001])
{
let mut setup = vmov(3, key).to_vec();
setup.push(vxor(4, 3, 1));
let alu = [vop1(SWAP, 4, vgpr(1))];
let family = "swap lane pairs";
let code = program(&setup, &alu, &[], 4);
let label = format!("v4 = v1 ^ {key:#x}, read v4");
cases.push(case(name, family, label, code, lanes(), |_, x| x));
let code = program(&setup, &alu, &[], 1);
let label = format!("v4 = v1 ^ {key:#x}, read v1");
cases.push(case(name, family, label, code, lanes(), |_, x| x ^ key));
}
let code = program(&[], &[vop1(SWAP, 1, vgpr(1))], &[], 1);
let family = "swap same register";
cases.push(case(name, family, "v1, v1".into(), code, lanes(), |_, x| x));
// v255, the highest VGPR, as VDST and as SRC0, with v255 = b.
let b = 0x8000_0001;
let family = "swap max register";
let code = program(&vmov(255, b), &[vop1(SWAP, 255, vgpr(1))], &[], 1);
cases.push(case(
name,
family,
"v255, v1".into(),
code,
lanes(),
|_, _| b,
));
let code = program(&vmov(255, b), &[vop1(SWAP, 1, vgpr(255))], &[], 255);
cases.push(case(
name,
family,
"v1, v255".into(),
code,
lanes(),
|_, x| x,
));
// The other register of each pair, so both writes are seen.
let code = program(&vmov(255, b), &[vop1(SWAP, 255, vgpr(1))], &[], 255);
let label = "v255, v1, read v255".into();
cases.push(case(name, family, label, code, lanes(), |_, x| x));
let code = program(&vmov(255, b), &[vop1(SWAP, 1, vgpr(255))], &[], 1);
let label = "v1, v255, read v1".into();
cases.push(case(name, family, label, code, lanes(), |_, _| b));
// EXEC: v4 = v1 ^ OLD; active lanes exchange, inactive lanes keep both.
let mut setup = vmov(5, OLD).to_vec();
setup.push(vxor(4, 5, 1));
let family = "swap exec";
for exec in EXEC_MASKS {
let mut before = setup.clone();
before.extend(smov(126, exec));
let alu = [vop1(SWAP, 4, vgpr(1))];
let code = program(&before, &alu, &[FULL_EXEC], 4);
let label = format!("exec {exec:#x}, read v4");
cases.push(case(name, family, label, code, lanes(), |n, x| {
masked(exec, n, x, x ^ OLD)
}));
let code = program(&before, &alu, &[FULL_EXEC], 1);
let label = format!("exec {exec:#x}, read v1");
cases.push(case(name, family, label, code, lanes(), |n, x| {
masked(exec, n, x ^ OLD, x)
}));
}
let family = "swap partial wave";
let alu = [vop1(SWAP, 4, vgpr(1))];
let code = program(&setup, &alu, &[], 4);
let short = lanes()[..7].to_vec();
cases.push(case(
name,
family,
"7 lanes".into(),
code.clone(),
short,
|_, x| x,
));
cases.push(case(
name,
family,
"45 lanes".into(),
code,
long_lanes(),
|_, x| x,
));
let exec = 0x5555_5555;
let mut before = setup.clone();
before.extend(smov(126, exec));
let code = program(&before, &alu, &[FULL_EXEC], 1);
let label = format!("45 lanes, exec {exec:#x}, read v1");
cases.push(case(name, family, label, code, long_lanes(), |n, x| {
masked(exec, n, x ^ OLD, x)
}));
// Output v4 (= x after the swap) ^ VCC_LO, XORed with v1 (= x ^ OLD after
// the swap) when SCC is set.
let family = "swap no vcc or scc write";
for vcc in [0, u32::MAX] {
for scc in [false, true] {
let mut before = setup.clone();
before.extend(smov(VCC_LO, vcc));
before.push(if scc { SCC_SET } else { SCC_CLEAR });
let mut after = vec![0x7e04_0304]; // v2 = v4
after.extend(FLAG_TAIL);
let code = program(&before, &alu, &after, 2);
let label = format!("vcc_lo {vcc:#x}, scc {scc}");
cases.push(case(name, family, label, code, lanes(), |_, x| {
x ^ vcc ^ if scc { x ^ OLD } else { 0 }
}));
}
}
// Partial EXEC with VCC_LO bits inside and outside EXEC, so a VCC write
// limited to active lanes, or one derived from the swapped data, shows.
let (exec, vcc) = (0x0f0f_0f0f, 0x0000_00f3);
let mut before = setup.clone();
before.extend(smov(VCC_LO, vcc));
before.push(SCC_SET);
before.extend(smov(126, exec));
let mut after = vec![FULL_EXEC, 0x7e04_0304]; // v2 = v4
after.extend(FLAG_TAIL);
let code = program(&before, &alu, &after, 2);
let label = format!("exec {exec:#x}, vcc_lo {vcc:#x}, scc true");
cases.push(case(name, family, label, code, lanes(), |n, x| {
masked(exec, n, x, x ^ OLD) ^ vcc ^ masked(exec, n, x ^ OLD, x)
}));
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
unary_cases(&mut cases);
swap_cases(&mut cases);
cases
}
/// Programs both interpreters must refuse at the ALU word, with that offset.
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
let setup = vmov(3, 7);
let offset = alu_offset(&setup);
let mut all = Vec::new();
// SDWA (249) with SRC0 v1 and DWORD selects, DPP16 (250) with the
// identity quad_perm, DPP8 (233) and DPP8FI (234) with the identity lane
// selects; other selectors get no extension dword.
let extension = |src0: u32| match src0 {
249 => vec![0x0606_0601],
250 => vec![0xff00_e401],
233 | 234 => vec![0xfac6_8801],
_ => vec![],
};
for (form, name) in FORMS {
let op = form as u32;
// A literal SRC0 with no literal dword: the program ends at the word.
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
code.extend(setup);
code.push(vop1(op, 2, LITERAL));
all.push((format!("{name} missing literal"), words(&code), offset));
// Outside the accepted subset (project policy, not a guide limit):
// VCC_HI, TTMPs, M0, NULL, EXEC, the reserved and float inline
// selectors, DPP8, VCCZ, EXECZ, SCC, SDWA, DPP16 and 254 (LDS direct
// in Table 20, reserved in Table 77).
for src0 in (107..=127).chain(209..=254) {
let mut alu = vec![vop1(op, 2, src0)];
alu.extend(extension(src0));
let code = program(&setup, &alu, &[], 2);
all.push((format!("{name} src0 {src0}"), code, offset));
}
}
// V_SWAP_B32 writes SRC0, so every non-VGPR selector is refused; VDST v2
// is initialized, so only the selector can fail.
let mut swap_setup = setup.to_vec();
swap_setup.extend(vmov(2, 5));
let swap_offset = alu_offset(&swap_setup);
for src0 in 0..=255 {
let mut alu = vec![vop1(SWAP, 2, src0)];
alu.extend(extension(src0));
if src0 == LITERAL {
alu.push(7);
}
let code = program(&swap_setup, &alu, &[], 2);
all.push((format!("{SWAP_NAME} src0 {src0}"), code, swap_offset));
}
// V_SWAP_B32 also writes v0 (the dispatch index) through either operand:
// v0 as SRC0 and v0 as VDST, under full EXEC.
for (dst, src0, what) in [(2, 0, "SRC0"), (0, 2, "VDST")] {
let code = program(&swap_setup, &[vop1(SWAP, dst, vgpr(src0))], &[], 2);
all.push((format!("{SWAP_NAME} v0 as {what}"), code, swap_offset));
}
// v3 with a load into it outstanding (no wait): read as SRC0, then
// written as VDST. The swap reads its VDST first, so for it the second
// case is also a read; no supported form writes v3 without reading it.
let mut pending = swap_setup.clone();
pending.extend(PENDING_LOAD_V3);
let pending_offset = alu_offset(&pending);
let ops = FORMS.iter().map(|&(form, name)| (form as u32, name));
for (op, name) in ops.chain([(SWAP, SWAP_NAME)]) {
for (dst, src0, what) in [(2, 3, "read"), (3, if op == SWAP { 2 } else { 1 }, "write")] {
let code = program(&pending, &[vop1(op, dst, vgpr(src0))], &[], 2);
let what = if op == SWAP && what == "write" {
"VDST read"
} else {
what
};
let label = format!("{name} {what} of v3 with its load outstanding");
all.push((label, code, pending_offset));
}
}
all
}
/// `buffer_load_dword v3, v0, s[0:3], 0 idxen` without the wait.
const PENDING_LOAD_V3: [u32; 2] = [0xe030_2000, 0x8000_0300];
fn assert_rejected_at(label: &str, code: &[u8], offset: usize, input: &[u32]) {
match xenora_ref::execute(code, input) {
Ok(_) => panic!("reference accepted {label}"),
Err(error) => assert_eq!(
error.offset, offset,
"reference rejected {label} elsewhere: {error:?}"
),
}
match independent_ref::execute(code, input) {
Ok(_) => panic!("independent accepted {label}"),
Err(error) => assert!(
error.starts_with(&format!("{offset:#x}:")),
"independent rejected {label} elsewhere: {error}"
),
}
}
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
let mut counts = BTreeMap::new();
for case in cases {
*counts.entry(key(case)).or_default() += 1;
}
counts
}
/// Runs `execute` on every case and returns one line per failing family: the
/// number of failures and the first one.
fn failures(
cases: &[Case],
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
) -> Vec<String> {
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
for case in cases {
let output = execute(&case.code, &case.input);
if output.as_deref().ok() != Some(case.expected.as_slice()) {
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
failed.entry(case.family).or_insert((0, first)).0 += 1;
}
}
failed
.into_iter()
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
.collect()
}
fn checked_cases() -> Vec<Case> {
let cases = cases();
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
cases
}
#[test]
fn expectations_reproduce_the_worked_examples() {
for (form, s0, d) in GUIDE_EXAMPLES {
assert_eq!(expect(form, s0), d, "{form:?}({s0:#x})");
}
}
#[test]
fn vop1_integer_forms_match_the_guide_on_the_reference() {
let cases = checked_cases();
let failed = failures(&cases, |code, input| {
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
});
assert!(
failed.is_empty(),
"reference disagrees with the guide:\n{}",
failed.join("\n")
);
eprintln!("vop1_integer: {} reference cases", cases.len());
for (form, n) in tally(&cases, |case| case.form) {
eprintln!(" form {form}: {n}");
}
}
#[test]
fn vop1_integer_forms_match_the_guide_on_the_independent_interpreter() {
let cases = checked_cases();
let failed = failures(&cases, independent_ref::execute);
assert!(
failed.is_empty(),
"independent interpreter disagrees with the guide:\n{}",
failed.join("\n")
);
eprintln!(
"vop1_integer: {} independent-interpreter cases",
cases.len()
);
}
#[test]
fn unsupported_vop1_integer_encodings_are_rejected() {
let rejections = rejections();
assert_eq!(rejections.len(), REJECTIONS);
for (label, code, offset) in &rejections {
assert_rejected_at(label, code, *offset, &lanes());
}
eprintln!("vop1_integer: {} rejections", rejections.len());
}
#[test]
fn swap_scalar_sources_fail_to_decode() {
// The SRC0 refusal is a decode error, not a failed read of an
// uninitialized SGPR or VCC_LO at run time.
for src0 in 0..=255 {
let code = words(&[vop1(SWAP, 2, src0), 7, 0xbf81_0000]);
match xenora_ref::decode(&code) {
Err(error) => assert_eq!(error.offset, 0, "src0 {src0}: {error:?}"),
Ok(program) => panic!("reference decoded v_swap_b32 src0 {src0}: {program:?}"),
}
}
}
#[test]
fn other_vop1_opcodes_stay_unsupported() {
// Every VOP1 opcode (0-255) except V_MOV_B32 (1, supported before this
// set) and these six must be refused at the ALU word. VDST and SRC0 are
// initialized, so a form that reads only those cannot fail on them; other
// prerequisites (M0 for the relative moves) are not set up, and the offset
// alone does not say why a form was refused.
let supported = [1, 55, 56, 57, 58, 59, SWAP];
let mut setup = vmov(3, 7).to_vec();
setup.extend(vmov(2, 5));
for op in (0..=255).filter(|op| !supported.contains(op)) {
let code = program(&setup, &[vop1(op, 2, vgpr(3))], &[], 2);
assert_rejected_at(&format!("opcode {op}"), &code, alu_offset(&setup), &lanes());
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation, and the translator's VOP1 integer forms (skipped by scripts/test-gpu.sh until then)"]
fn vop1_integer_forms_match_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
for (label, code, offset) in rejections() {
// Refused at the same word as by the interpreters, so a later failure
// cannot stand in.
let at = match compile(Architecture::Gfx1030, &code) {
Err(CompileError::Decode(error)) => error.offset,
Err(CompileError::Verify { offset, .. }) => offset,
other => panic!("compiler did not reject {label}: {other:?}"),
};
assert_eq!(at, offset, "compiler rejected {label} elsewhere");
}
let cases = checked_cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"vop1_integer: {} Metal cases in {programs} programs",
cases.len()
);
}
+4 -6
View File
@@ -666,16 +666,14 @@ fn vopc_f_t_outside_the_contract_are_rejected() {
#[test]
fn other_constant_compares_stay_unsupported() {
// F and T/TRU of the float, 64-bit and v_cmpx groups (Table 61):
// F and T/TRU of the float and v_cmpx groups (Table 61):
// V_CMP_F_F32 0, V_CMP_TRU_F32 15, V_CMPX_F_F32 16, V_CMPX_TRU_F32 31,
// V_CMP_F_I64 160, V_CMP_T_I64 167, V_CMPX_F_I64 176, V_CMPX_T_I64 183,
// V_CMP_F_U64 224, V_CMP_T_U64 231, V_CMPX_F_U64 240, V_CMPX_T_U64 247.
// V_CMPX_F_I64 176, V_CMPX_T_I64 183, V_CMPX_F_U64 240, V_CMPX_T_U64 247.
// The 64-bit V_CMP_F/T (160, 167, 224, 231) are covered by vopc_wide.rs.
let setup = vmov(3, 7);
// Also the neighbours of the two 32-bit integer groups: 127 and 191 (not
// in Table 61), 136 V_CMP_CLASS_F32 and 200 V_CMP_F_F16.
for op in [
0, 15, 16, 31, 127, 136, 160, 167, 176, 183, 191, 200, 224, 231, 240, 247,
] {
for op in [0, 15, 16, 31, 127, 136, 176, 183, 191, 200, 240, 247] {
let (code, offset) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &[]);
assert_rejected_at(&format!("opcode {op}"), &code, offset, &lanes());
}
File diff suppressed because it is too large. Load diff