mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 02:21:11 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4fb9ae030 | ||
|
|
1d363c3c34 | ||
|
|
d04954e7a5 | ||
|
|
e74ebbe30b | ||
|
|
26eba92b87 | ||
|
|
05143d6295 | ||
|
|
d6a65b2940 | ||
|
|
1cc7f01fec | ||
|
|
6a4fc7cce1 | ||
|
|
b5b24347e9 | ||
|
|
f8eb976102 | ||
|
|
bbb59324c0 | ||
|
|
34b16ca65c | ||
|
|
fd0e427c7b | ||
|
|
314d1f5874 | ||
|
|
7adb978683 | ||
|
|
9d5de05055 | ||
|
|
3348d34e6f | ||
|
|
8e9ec8b9d1 | ||
|
|
b54f5ef0aa | ||
|
|
4d5207afd8 | ||
|
|
131c8669cf | ||
|
|
de71515d76 |
No files matched your search
@@ -10,12 +10,17 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- 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
|
||||
- Added an isolated experiment under `experiments/audio-dsp` with a bounded PCM mixer and opt-in native CoreAudio output. It runs outside the Xenora runtime, with measurements limited to one local machine.
|
||||
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
|
||||
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
|
||||
- Added decoding and Metal shader translation for the sixteen Wave32 VOPC 64-bit integer compares (#215). They read VGPR pairs, known even-aligned SGPR pairs or sign-extended inline integers and write the Wave32 VCC mask. The guide-derived oracle passes on native Metal (4,640 cases in 3,818 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added XADD and CMPXCHG for 8- to 64-bit register and memory destinations, and the LOCK prefix on their memory forms (#198). LOCK anywhere else, CMPXCHG8B and CMPXCHG16B stay rejected. Both engines run the new forms on the shared semantics, one instruction at a time, so a locked instruction is indivisible today and LOCK changes no result; `docs/cpu/instruction-registry.md` states the ordering, alignment, compare-failure and fault rules a guest scheduler must preserve. A failed compare still writes the destination, so it faults on memory that cannot be written. Nothing is lowered to ARM64 atomic instructions, and no multi-thread behaviour is established. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, with 62 LLVM-assembled fixtures and five new tests in `x86_atomic.rs`; not compared with x86 hardware and awaiting independent review.
|
||||
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
|
||||
|
||||
+29
-56
@@ -5,17 +5,17 @@ use std::fmt;
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
|
||||
VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, VectorSwapOp, VectorUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, VectorSwapOp,
|
||||
VectorUnaryOp,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
use xenora_isa::semantics::{FORM_IDS, OperandRule};
|
||||
pub use xenora_isa::semantics::{VectorBinary, VectorUnary};
|
||||
pub use xenora_isa::semantics::{VectorBinary, VectorLowering, VectorUnary, VectorVcc};
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination: the hand-written forms below followed by every form of
|
||||
@@ -40,17 +40,11 @@ const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
|
||||
}
|
||||
|
||||
/// Decoded forms not yet described by the semantic registry.
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 16] = [
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 10] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
@@ -396,34 +390,25 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediateCompare { op, src, simm16 }, 4));
|
||||
}
|
||||
if S_BRANCH.matches(first) {
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
if let Some(op) = SoppControlOp::from_word(first) {
|
||||
let immediate = first as u16;
|
||||
if op
|
||||
.required_immediate()
|
||||
.is_some_and(|exact| immediate != exact)
|
||||
{
|
||||
let detail = if op == SoppControlOp::EndProgram {
|
||||
"expected zero immediate"
|
||||
} else {
|
||||
"expected vmcnt(0) alone"
|
||||
};
|
||||
return Err(unsupported(op.mnemonic(), detail));
|
||||
}
|
||||
let instruction = op.decode(|| branch_target(immediate, offset, op.mnemonic()))?;
|
||||
return Ok((instruction, 4));
|
||||
}
|
||||
if let Some(op) = ScalarAluOp::from_word(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
if S_CBRANCH_SCC0.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_scc0")?;
|
||||
return Ok((
|
||||
Instruction::BranchSccZero { target },
|
||||
S_CBRANCH_SCC0.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_EXECZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_execz")?;
|
||||
return Ok((
|
||||
Instruction::BranchExecZero { target },
|
||||
S_CBRANCH_EXECZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_VCCZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_vccz")?;
|
||||
return Ok((
|
||||
Instruction::BranchVccZero { target },
|
||||
S_CBRANCH_VCCZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if let Some(op) = VectorAluOp::from_word(first) {
|
||||
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
|
||||
let dst = ((first >> 17) & 0xff) as u8;
|
||||
@@ -434,7 +419,10 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let (_, src0, _) = vop2_registers(first, op.assembly_name())?;
|
||||
(VectorSource::Register(src0), 4)
|
||||
}
|
||||
_ => vector_src0(first, bytes, op.assembly_name())?,
|
||||
OperandRule::Vop2Vgpr | OperandRule::Vop2Vcc => {
|
||||
vector_src0(first, bytes, op.assembly_name())?
|
||||
}
|
||||
_ => unreachable!("non-VOP2 operand rule for VOP2 instruction"),
|
||||
};
|
||||
return Ok((
|
||||
Instruction::VectorAlu {
|
||||
@@ -460,15 +448,6 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
V_MUL_F32.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_WAITCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_WAITCNT.byte_len(),
|
||||
0xbf8c_3f70,
|
||||
Instruction::WaitLoad,
|
||||
"expected vmcnt(0) alone",
|
||||
);
|
||||
}
|
||||
if S_WAITCNT_VSCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
@@ -478,15 +457,6 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
"expected null, 0",
|
||||
);
|
||||
}
|
||||
if S_ENDPGM.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_ENDPGM.byte_len(),
|
||||
0xbf81_0000,
|
||||
Instruction::EndProgram,
|
||||
"expected zero immediate",
|
||||
);
|
||||
}
|
||||
|
||||
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
|
||||
}
|
||||
@@ -543,11 +513,11 @@ fn scalar_source(
|
||||
}
|
||||
|
||||
fn branch_target(
|
||||
first: u32,
|
||||
immediate: u16,
|
||||
offset: usize,
|
||||
mnemonic: &'static str,
|
||||
) -> Result<usize, DecodeErrorKind> {
|
||||
let displacement = first as u16 as i16;
|
||||
let displacement = immediate as i16;
|
||||
let words = usize::try_from(displacement)
|
||||
.map_err(|_| unsupported(mnemonic, "expected a forward branch"))?;
|
||||
offset
|
||||
@@ -686,6 +656,9 @@ fn vector_compare(
|
||||
return Err(unsupported(mnemonic, "invalid 64-bit compare source"));
|
||||
}
|
||||
}
|
||||
if op.semantics().width == 16 && first & 0x1ff == 255 {
|
||||
return Err(unsupported(mnemonic, "literal in 16-bit compare"));
|
||||
}
|
||||
let (src0, len) = vector_src0(first, bytes, mnemonic)?;
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ use xenora_decoder::{
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarImmediate, ScalarUnary,
|
||||
Source, VectorAlu, VectorInteger, VectorUnary,
|
||||
BranchCondition, CompareSource, CompareWidth, Comparison, Op, ScalarAlu, ScalarImmediate,
|
||||
ScalarUnary, Source, VectorAlu, VectorInteger, VectorUnary,
|
||||
};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
@@ -505,8 +505,8 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
panic!("compute reference matrix received a graphics/image instruction")
|
||||
}
|
||||
|
||||
Instruction::VectorCompare { op, src0, src1 } => Op::Compare(
|
||||
Comparison {
|
||||
Instruction::VectorCompare { op, src0, src1 } => {
|
||||
let comparison = Comparison {
|
||||
offset: match op.relation() {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
@@ -518,14 +518,19 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
CompareRelation::True => 7,
|
||||
},
|
||||
signed: op.signed(),
|
||||
},
|
||||
match src0 {
|
||||
};
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
src1,
|
||||
),
|
||||
};
|
||||
match op.semantics().width {
|
||||
16 => Op::WideCompare(comparison, CompareWidth::Half, src0, src1),
|
||||
32 => Op::Compare(comparison, src0, src1),
|
||||
64 => Op::WideCompare(comparison, CompareWidth::Double, src0, src1),
|
||||
width => panic!("unexpected VOPC operand width {width}"),
|
||||
}
|
||||
}
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
@@ -533,6 +538,10 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
match op {
|
||||
VectorAluOp::CndmaskB32 => VectorInteger::Select,
|
||||
VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry,
|
||||
VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false },
|
||||
VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true },
|
||||
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
|
||||
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
|
||||
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
|
||||
@@ -582,15 +591,17 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-vcc.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-16.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 126, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 142, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -887,7 +898,7 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
let target = next_offset + displacement * 4;
|
||||
format!("{mnemonic} -> 0x{target:04x}")
|
||||
}
|
||||
// VOPC and the registry VOP2 forms print SRC0 (the second operand) as bits.
|
||||
// VOPC and registry VOP2 forms print SRC0 as bits.
|
||||
mnemonic
|
||||
if mnemonic.starts_with("v_cmp_")
|
||||
|| VectorAluOp::ALL
|
||||
@@ -895,10 +906,11 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
.any(|op| op.assembly_name() == mnemonic) =>
|
||||
{
|
||||
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
|
||||
parts[1] = match literal_bits(&parts[1]) {
|
||||
let src = if parts.len() == 5 { 2 } else { 1 };
|
||||
parts[src] = match literal_bits(&parts[src]) {
|
||||
Some(bits) => format!("0x{bits:x}"),
|
||||
None => parts[1].parse::<i32>().map_or_else(
|
||||
|_| parts[1].clone(),
|
||||
None => parts[src].parse::<i32>().map_or_else(
|
||||
|_| parts[src].clone(),
|
||||
|value| format!("0x{:x}", value as u32),
|
||||
),
|
||||
};
|
||||
|
||||
@@ -49,7 +49,20 @@ VARIANT_KEYS = {"of", "family", "opcode", "operands", "spec", "verify"}
|
||||
# The assembler suffix LLVM prints for a variant's encoding family.
|
||||
ASSEMBLY_SUFFIX = {"VOP3": "_e64"}
|
||||
|
||||
# Control effects select an existing typed instruction and its operand contract.
|
||||
# The XML records SCC as a separate implicit input. VCC and EXEC predicates
|
||||
# have fieldless mask inputs instead.
|
||||
CONTROL_OPERATIONS = {
|
||||
"end_program": ("EndProgram", "sopp_end", None),
|
||||
"branch": ("Branch", "sopp_branch", None),
|
||||
"branch_scc_zero": ("BranchSccZero", "sopp_branch", None),
|
||||
"branch_vcc_zero": ("BranchVccZero", "sopp_branch", "OPR_VCC"),
|
||||
"branch_exec_zero": ("BranchExecZero", "sopp_branch", "OPR_SDST_EXEC"),
|
||||
"wait_load": ("WaitLoad", "sopp_wait", None),
|
||||
}
|
||||
|
||||
OPERATIONS = {
|
||||
**{name: variant for name, (variant, _, _) in CONTROL_OPERATIONS.items()},
|
||||
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
|
||||
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
|
||||
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
|
||||
@@ -78,7 +91,11 @@ RELATIONS = {
|
||||
VECTOR_ONLY_RELATIONS = {"f", "t"}
|
||||
# Guide 12.9 Tables 59 and 61: integer VOPC opcodes are the group base
|
||||
# for the operand width and signedness plus the relation offset.
|
||||
VOPC_INTEGER_BASES = {32: {"signed": 128, "unsigned": 192}, 64: {"signed": 160, "unsigned": 224}}
|
||||
VOPC_INTEGER_BASES = {
|
||||
16: {"signed": 136, "unsigned": 168},
|
||||
32: {"signed": 128, "unsigned": 192},
|
||||
64: {"signed": 160, "unsigned": 224},
|
||||
}
|
||||
VOPC_RELATION_OFFSETS = {"f": 0, "lt": 1, "eq": 2, "le": 3, "gt": 4, "lg": 5, "ge": 6, "t": 7}
|
||||
# (relation, signedness) -> primitive. Equality does not depend on signedness,
|
||||
# so both declared signednesses of EQ and LG share one primitive.
|
||||
@@ -123,7 +140,7 @@ SHIFT_AMOUNTS = {1, 2, 3, 4}
|
||||
SOURCE_ORDER_KEY = "source_order"
|
||||
SOURCE_ORDERS = {"reversed"}
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc", "vcc": "Vcc"}
|
||||
SCC = {
|
||||
"unchanged": "Unchanged",
|
||||
"carry_out": "CarryOut",
|
||||
@@ -133,16 +150,18 @@ SCC = {
|
||||
"relation": "Relation",
|
||||
"selected_src0": "SelectedSrc0",
|
||||
}
|
||||
# lane_mask: the Wave32 VOPC result written to VCC_LO (vcc only; EXEC writes
|
||||
# such as v_cmpx have no contract yet, so exec must stay unchanged).
|
||||
# lane_mask: the Wave32 compare or carry result written to VCC_LO.
|
||||
# EXEC writes such as v_cmpx have no contract, so exec must stay unchanged.
|
||||
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
# Which wave declaration each operand-rule kind must make. The decoder has no
|
||||
# wave-size input, so "wave32" is only true where the caller's ABI fixes the
|
||||
# wave size: the lane-mask compares, whose one entry point is the Wave32
|
||||
# compute fixture ABI (docs/shaders/vector-compare.md section 2). Every other
|
||||
# kind must be "any".
|
||||
WAVE_BY_KIND = {"vector_compare": "wave32", "vector_unary": "wave32", "vector_swap": "wave32"}
|
||||
# The synthetic compute fixture ABI fixes the wave size for these operand-rule
|
||||
# kinds and for the VCC-reading VOP2 rule. Other forms declare "any".
|
||||
WAVE_BY_KIND = {"control": "wave32", "vector_compare": "wave32", "vector_unary": "wave32", "vector_swap": "wave32"}
|
||||
VCC_VECTOR_PRIMITIVES = {
|
||||
("cselect", "bitwise"): "Select",
|
||||
("add", "unsigned"): "AddCarry",
|
||||
("sub", "unsigned"): "SubtractBorrow",
|
||||
}
|
||||
EVIDENCE = {
|
||||
"reference": "Reference",
|
||||
"independent": "Independent",
|
||||
@@ -266,6 +285,28 @@ VECTOR_UNARY_PRIMITIVES = {
|
||||
}
|
||||
|
||||
OPERAND_RULES = {
|
||||
"sopp_end": {
|
||||
"rust": "SoppEnd",
|
||||
"enum": "SoppControlOp",
|
||||
"shape": {"family": "SOPP", "src": [], "max_literals": 0, "immediate": 0},
|
||||
"unsupported": set(),
|
||||
"kind": "control",
|
||||
},
|
||||
"sopp_branch": {
|
||||
"rust": "SoppBranch",
|
||||
"enum": "SoppControlOp",
|
||||
"shape": {"family": "SOPP", "src": [{"field": "SIMM16", "class": "label"}], "max_literals": 0},
|
||||
"unsupported": set(),
|
||||
"kind": "control",
|
||||
},
|
||||
"sopp_wait": {
|
||||
"rust": "SoppWait",
|
||||
"enum": "SoppControlOp",
|
||||
"shape": {"family": "SOPP", "src": [{"field": "SIMM16", "class": "waitcnt"}],
|
||||
"max_literals": 0, "immediate": 0x3f70},
|
||||
"unsupported": set(),
|
||||
"kind": "control",
|
||||
},
|
||||
"vop1_vgpr": {
|
||||
"rust": "Vop1Vgpr",
|
||||
"enum": "VectorUnaryOp",
|
||||
@@ -399,6 +440,26 @@ OPERAND_RULES = {
|
||||
},
|
||||
"kind": "vector_compare",
|
||||
},
|
||||
"vopc_vcc_half": {
|
||||
"rust": "VopcVccHalf",
|
||||
"enum": "VectorCompareOp",
|
||||
"shape": {
|
||||
"family": "VOPC",
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
},
|
||||
# The destination is implicitly vcc_lo; the decoder rejects these SRC0
|
||||
# selectors (the same vector_source as VOP2).
|
||||
"unsupported": {
|
||||
"src_literal", "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector_compare",
|
||||
"width": 16,
|
||||
},
|
||||
"vopc_vcc_pair": {
|
||||
"rust": "VopcVccPair",
|
||||
"enum": "VectorCompareOp",
|
||||
@@ -464,6 +525,24 @@ OPERAND_RULES = {
|
||||
},
|
||||
"kind": "vector",
|
||||
},
|
||||
"vop2_vcc": {
|
||||
"rust": "Vop2Vcc",
|
||||
"enum": "VectorAluOp",
|
||||
"shape": {
|
||||
"family": "VOP2",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
"unsupported": {
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector",
|
||||
},
|
||||
"vop2_vgpr2": {
|
||||
"rust": "Vop2Vgpr2",
|
||||
"enum": "VectorAluOp",
|
||||
@@ -653,24 +732,35 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
operands = {}
|
||||
scc_in = scc_out = False
|
||||
implicit = set()
|
||||
vcc_writes = []
|
||||
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
|
||||
vcc_operands = []
|
||||
control_mask = CONTROL_OPERATIONS.get(form["operation"], (None, None, None))[2]
|
||||
mask_inputs = 0
|
||||
for field, data_format, kind, size, is_input, is_output, is_implicit, encoded in variant["operands"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
scc_out |= is_output
|
||||
elif control_mask and (field, kind, data_format, size, is_input, is_output, is_implicit, encoded) == (
|
||||
"", control_mask, "FMT_NUM_M64", 64, True, False, True, True
|
||||
):
|
||||
mask_inputs += 1
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
elif kind == "OPR_VCC":
|
||||
vcc_operands.append((is_input, is_output))
|
||||
else:
|
||||
implicit.add(kind)
|
||||
if kind == "OPR_VCC":
|
||||
vcc_writes.append((is_input, is_output))
|
||||
# The vocabulary states SCC effects and a lane-mask VCC write; any other
|
||||
# implicit XML operand (such as an EXEC write) is undeclared.
|
||||
if form["carry_in"] == "vcc":
|
||||
if vcc_operands.count((True, False)) != 1:
|
||||
errors.append(f"{label}: carry_in vcc requires one implicit XML VCC input")
|
||||
if (True, False) in vcc_operands:
|
||||
vcc_operands.remove((True, False))
|
||||
if form["vcc"] == "lane_mask":
|
||||
# Exactly one fieldless VCC operand, written and not read.
|
||||
if vcc_writes != [(False, True)]:
|
||||
if vcc_operands != [(False, True)]:
|
||||
errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output")
|
||||
implicit.discard("OPR_VCC")
|
||||
elif vcc_operands:
|
||||
implicit.add("OPR_VCC")
|
||||
if control_mask and mask_inputs != 1:
|
||||
errors.append(f"{label}: expected one implicit {control_mask} input in the XML")
|
||||
if implicit:
|
||||
errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared")
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
@@ -691,6 +781,14 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
if field == "SIMM16" and _rule_kind(form) == "control":
|
||||
expected_kind, expected_format = (
|
||||
("OPR_LABEL", "FMT_NUM_I16") if form["operands"] == "sopp_branch"
|
||||
else ("OPR_WAITCNT", "FMT_NUM_B16")
|
||||
)
|
||||
if [field, expected_format, expected_kind, 16, True, False, False, True] not in variant["operands"]:
|
||||
errors.append(f"{label}: SIMM16 is not an encoded {expected_kind} input")
|
||||
continue
|
||||
if field == "SIMM16":
|
||||
# The 16-bit immediate: signed forms read it as FMT_NUM_I16 (sign
|
||||
# extended), unsigned compares as FMT_NUM_U16 (zero extended).
|
||||
@@ -718,8 +816,8 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
if data_format != f"FMT_NUM_I{bits}":
|
||||
errors.append(f"{label}: {field} has XML format {data_format}, not FMT_NUM_I{bits}")
|
||||
elif is_source and data_format not in (
|
||||
{f"FMT_NUM_{'I' if form['signedness'] == 'signed' else 'U'}64"}
|
||||
if form["operands"] == "vopc_vcc_pair"
|
||||
{f"FMT_NUM_{'I' if form['signedness'] == 'signed' else 'U'}{form['width']}"}
|
||||
if form["operands"] in ("vopc_vcc_half", "vopc_vcc_pair")
|
||||
else SOURCE_FORMATS.get(form["signedness"], ())
|
||||
):
|
||||
errors.append(
|
||||
@@ -791,10 +889,13 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: variant {form['variant']!r} is reserved")
|
||||
if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid opcode")
|
||||
wave = WAVE_BY_KIND.get(_rule_kind(form), "any")
|
||||
reads_vcc = form["operands"] == "vop2_vcc"
|
||||
wave = "wave32" if reads_vcc else WAVE_BY_KIND.get(_rule_kind(form), "any")
|
||||
if (form["carry_in"] == "vcc") != reads_vcc:
|
||||
errors.append(f"{label}: implicit VCC input requires the vop2_vcc rule")
|
||||
if form["wave"] in WAVE and form["wave"] != wave:
|
||||
errors.append(f"{label}: wave {form['wave']} is not enforced for this rule (requires {wave})")
|
||||
lane_mask = _rule_kind(form) == "vector_compare"
|
||||
lane_mask = _rule_kind(form) == "vector_compare" or (reads_vcc and form["operation"] != "cselect")
|
||||
if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask:
|
||||
errors.append(
|
||||
f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} "
|
||||
@@ -843,7 +944,7 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: unknown {SOURCE_ORDER_KEY} {order!r}")
|
||||
elif _rule_kind(form) != "vector":
|
||||
errors.append(f"{label}: {SOURCE_ORDER_KEY} on a non-vector form")
|
||||
if form["operation"] in SCC_READERS and form["carry_in"] != "scc":
|
||||
if not reads_vcc and form["operation"] in SCC_READERS and form["carry_in"] != "scc":
|
||||
errors.append(f"{label}: operation {form['operation']} reads SCC (requires carry_in scc)")
|
||||
if form["operation"] == "sext":
|
||||
bits = form.get(SOURCE_BITS_KEY)
|
||||
@@ -883,12 +984,20 @@ def validate(registry, snapshot):
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = (scc, None, False)
|
||||
elif form["operation"] in CONTROL_OPERATIONS:
|
||||
variant, operand_rule, _ = CONTROL_OPERATIONS[form["operation"]]
|
||||
signedness = "signed" if operand_rule == "sopp_branch" else "bitwise"
|
||||
if (form["variant"], form["operands"], form["signedness"]) != (variant, operand_rule, signedness):
|
||||
errors.append(f"{label}: control operation requires {variant}, {operand_rule}, {signedness}")
|
||||
if RELATION_KEY in form or form["width"] != 32:
|
||||
errors.append(f"{label}: control operation requires width 32 and no relation")
|
||||
primitive = ("unchanged", None, form["operation"] == "branch_scc_zero")
|
||||
elif _rule_kind(form) in ("vector", "vector_unary", "vector_swap"):
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
key = (form["operation"], form["signedness"])
|
||||
table = {
|
||||
"vector": VECTOR_PRIMITIVES,
|
||||
"vector": VCC_VECTOR_PRIMITIVES if reads_vcc else VECTOR_PRIMITIVES,
|
||||
"vector_unary": VECTOR_UNARY_PRIMITIVES,
|
||||
"vector_swap": {("swap", "bitwise"): "Swap"},
|
||||
}[_rule_kind(form)]
|
||||
@@ -926,6 +1035,7 @@ def validate(registry, snapshot):
|
||||
form["operation"] == "mov" and form["family"] == "SOP1"
|
||||
)
|
||||
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
|
||||
else "control" if form["operation"] in CONTROL_OPERATIONS
|
||||
else "immediate" if _rule_kind(form) == "immediate"
|
||||
else "alu"
|
||||
):
|
||||
@@ -1112,7 +1222,7 @@ def render(registry, snapshot):
|
||||
"use crate::primitive;",
|
||||
"use crate::semantics::{",
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, VectorBinary, VectorUnary, Wave,",
|
||||
" Signedness, SpecRef, VectorBinary, VectorLowering, VectorUnary, VectorVcc, Wave,",
|
||||
"};",
|
||||
"use crate::CompareRelation;",
|
||||
"",
|
||||
@@ -1302,7 +1412,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
f"pub enum {enum} {{",
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
carry = {"scc": " plus SCC", "vcc": " with VCC input"}.get(form["carry_in"], "")
|
||||
what = f"compare {form[RELATION_KEY]}" if RELATION_KEY in form else form["operation"]
|
||||
effect = f"VCC = {form['vcc']}" if form["vcc"] != "unchanged" else f"SCC = {form['scc']}"
|
||||
out += [
|
||||
@@ -1359,6 +1469,42 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }]",
|
||||
" }",
|
||||
]
|
||||
if kind == "control":
|
||||
out += [
|
||||
"",
|
||||
" /// Exact SIMM16 required by the fixture, or None for a displacement.",
|
||||
" pub const fn required_immediate(self) -> Option<u16> {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
exact = OPERAND_RULES[form["operands"]]["shape"].get("immediate")
|
||||
value = "None" if exact is None else f"Some({exact:#x})"
|
||||
out.append(f" Self::{form['variant']} => {value},")
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Constructs the existing decoded instruction, resolving a target only for a branch.",
|
||||
" pub fn decode<E>(",
|
||||
" self,",
|
||||
" target: impl FnOnce() -> Result<usize, E>,",
|
||||
" ) -> Result<crate::Instruction, E> {",
|
||||
" Ok(match self {",
|
||||
]
|
||||
for form in forms:
|
||||
variant = form["variant"]
|
||||
fields = " { target: target()? }" if form["operands"] == "sopp_branch" else ""
|
||||
out.append(f" Self::{variant} => crate::Instruction::{variant}{fields},")
|
||||
out += [" })", " }", "}", "", "impl crate::Instruction {",
|
||||
" /// The registry operation corresponding to a decoded SOPP control.",
|
||||
f" pub const fn sopp_control(self) -> Option<{enum}> {{",
|
||||
" match self {"]
|
||||
for form in forms:
|
||||
variant = form["variant"]
|
||||
fields = " { .. }" if form["operands"] == "sopp_branch" else ""
|
||||
out.append(f" Self::{variant}{fields} => Some({enum}::{variant}),")
|
||||
out += [" _ => None,", " }", " }", "}"]
|
||||
return out
|
||||
if kind in ("vector_unary", "vector_swap"):
|
||||
out += [
|
||||
"",
|
||||
@@ -1526,14 +1672,16 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }",
|
||||
"",
|
||||
" /// The per-lane operation its MSL lowering uses.",
|
||||
" pub const fn lowering(self) -> VectorBinary {",
|
||||
" pub const fn lowering(self) -> VectorLowering {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => "
|
||||
f"VectorBinary::{VECTOR_PRIMITIVES[(form['operation'], form['signedness'])]},"
|
||||
for form in forms
|
||||
]
|
||||
for form in forms:
|
||||
key = (form["operation"], form["signedness"])
|
||||
if form["operands"] == "vop2_vcc":
|
||||
lowering = f"Vcc(VectorVcc::{VCC_VECTOR_PRIMITIVES[key]})"
|
||||
else:
|
||||
lowering = f"Binary(VectorBinary::{VECTOR_PRIMITIVES[key]})"
|
||||
out.append(f" Self::{form['variant']} => VectorLowering::{lowering},")
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
@@ -1612,9 +1760,14 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
out += [" match self {"]
|
||||
for form in forms:
|
||||
relation = form[RELATION_KEY]
|
||||
if form["width"] == 64 and relation not in VECTOR_ONLY_RELATIONS:
|
||||
if form["width"] in (16, 64) and relation not in VECTOR_ONLY_RELATIONS:
|
||||
symbol = {"lt": "<", "eq": "==", "le": "<=", "gt": ">", "lg": "!=", "ge": ">="}[relation]
|
||||
left, right = ("(src0 as i64)", "(src1 as i64)") if form["signedness"] == "signed" else ("src0", "src1")
|
||||
width = form["width"]
|
||||
if width == 64 and form["signedness"] == "unsigned":
|
||||
left, right = "src0", "src1"
|
||||
else:
|
||||
cast = f"{'i' if form['signedness'] == 'signed' else 'u'}{width}"
|
||||
left, right = f"(src0 as {cast})", f"(src1 as {cast})"
|
||||
expression = f"{left} {symbol} {right}"
|
||||
else:
|
||||
function = COMPARE_PRIMITIVES[(relation, form["signedness"])]
|
||||
|
||||
@@ -25,6 +25,7 @@ include = [
|
||||
"rdna2/vop2.toml",
|
||||
"rdna2/vopc.toml",
|
||||
"rdna2/vop3.toml",
|
||||
"rdna2/sopp.toml",
|
||||
]
|
||||
|
||||
# Named public documents that spec references point at.
|
||||
@@ -44,11 +45,11 @@ file = "amdgpu_isa_rdna2.xml"
|
||||
# variant Rust enum variant of the typed op
|
||||
# operation primitive (closed vocabulary in generate_semantics.py OPERATIONS)
|
||||
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
|
||||
# carry_in none | scc (scc for unsigned add/sub carry and the cselect condition)
|
||||
# carry_in none | scc | vcc (implicit scalar or per-lane condition or carry)
|
||||
# width operand and result width in bits
|
||||
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
|
||||
# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare)
|
||||
# wave any | wave32 (wave32 for VOPC compares and VOP1 integer forms)
|
||||
# vcc, exec unchanged (stated, not implied) | lane_mask (Wave32 VOPC compare or VOP2 carry output)
|
||||
# wave any | wave32 (wave32 for VOPC compares, VOP1 integer forms and VCC-reading VOP2 forms)
|
||||
# operands a key of [operand_rules]
|
||||
# spec references; at least one guide section with a page
|
||||
# verify evidence required before the form counts as verified
|
||||
@@ -0,0 +1,123 @@
|
||||
# Existing gfx1030 compute controls, AMD RDNA 2 ISA guide §12.5.
|
||||
|
||||
[operand_rules.sopp_end]
|
||||
family = "SOPP"
|
||||
src = []
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
immediate = 0
|
||||
|
||||
[operand_rules.sopp_branch]
|
||||
family = "SOPP"
|
||||
src = [{ field = "SIMM16", class = "label" }]
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
|
||||
[operand_rules.sopp_wait]
|
||||
family = "SOPP"
|
||||
src = [{ field = "SIMM16", class = "waitcnt" }]
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
immediate = 0x3f70
|
||||
|
||||
[[form]]
|
||||
name = "S_ENDPGM"
|
||||
family = "SOPP"
|
||||
opcode = 1
|
||||
variant = "EndProgram"
|
||||
operation = "end_program"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_end"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BRANCH"
|
||||
family = "SOPP"
|
||||
opcode = 2
|
||||
variant = "Branch"
|
||||
operation = "branch"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_SCC0"
|
||||
family = "SOPP"
|
||||
opcode = 4
|
||||
variant = "BranchSccZero"
|
||||
operation = "branch_scc_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_VCCZ"
|
||||
family = "SOPP"
|
||||
opcode = 6
|
||||
variant = "BranchVccZero"
|
||||
operation = "branch_vcc_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_EXECZ"
|
||||
family = "SOPP"
|
||||
opcode = 8
|
||||
variant = "BranchExecZero"
|
||||
operation = "branch_exec_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 125 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_WAITCNT"
|
||||
family = "SOPP"
|
||||
opcode = 12
|
||||
variant = "WaitLoad"
|
||||
operation = "wait_load"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_wait"
|
||||
spec = [{ document = "guide", section = "12.5", page = 125 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -348,3 +348,85 @@ wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[operand_rules.vop2_vcc]
|
||||
family = "VOP2"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CNDMASK_B32"
|
||||
family = "VOP2"
|
||||
opcode = 1
|
||||
variant = "CndmaskB32"
|
||||
operation = "cselect"
|
||||
signedness = "bitwise"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 131 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_ADD_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 40
|
||||
variant = "AddCoCiU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUB_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 41
|
||||
variant = "SubCoCiU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUBREV_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 42
|
||||
variant = "SubrevCoCiU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
source_order = "reversed"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -707,3 +707,268 @@ spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
# Wave32 16-bit integer compares (guide 12.9, Tables 59 and 61).
|
||||
[operand_rules.vopc_vcc_half]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# Guide 6.2, 6.2.5 and 6.8: read the low half of each source.
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_literal", "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I16"
|
||||
family = "VOPC"
|
||||
opcode = 137
|
||||
variant = "CmpLtI16"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_I16"
|
||||
family = "VOPC"
|
||||
opcode = 138
|
||||
variant = "CmpEqI16"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 139
|
||||
variant = "CmpLeI16"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_I16"
|
||||
family = "VOPC"
|
||||
opcode = 140
|
||||
variant = "CmpGtI16"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 141
|
||||
variant = "CmpNeI16"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 142
|
||||
variant = "CmpGeI16"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_U16"
|
||||
family = "VOPC"
|
||||
opcode = 169
|
||||
variant = "CmpLtU16"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_U16"
|
||||
family = "VOPC"
|
||||
opcode = 170
|
||||
variant = "CmpEqU16"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 171
|
||||
variant = "CmpLeU16"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_U16"
|
||||
family = "VOPC"
|
||||
opcode = 172
|
||||
variant = "CmpGtU16"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 173
|
||||
variant = "CmpNeU16"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 174
|
||||
variant = "CmpGeU16"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+26
-3
@@ -20,9 +20,21 @@ pub use rdna2::{
|
||||
};
|
||||
pub use semantics_gen::{
|
||||
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
|
||||
VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp,
|
||||
};
|
||||
|
||||
impl VectorAluOp {
|
||||
/// Whether this encoding takes a per-lane VCC_LO bit.
|
||||
pub fn reads_vcc(self) -> bool {
|
||||
self.semantics().carry_in == semantics::CarryIn::Vcc
|
||||
}
|
||||
|
||||
/// Whether this encoding replaces the Wave32 VCC_LO mask.
|
||||
pub fn writes_vcc(self) -> bool {
|
||||
self.semantics().vcc == semantics::MaskEffect::LaneMask
|
||||
}
|
||||
}
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
|
||||
@@ -382,9 +394,20 @@ impl fmt::Display for Instruction {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
Self::VectorAlu {
|
||||
dst, src0, src1, ..
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => {
|
||||
write!(formatter, " v{dst}, {src0}, v{src1}")
|
||||
write!(formatter, " v{dst}, ")?;
|
||||
if op.writes_vcc() {
|
||||
write!(formatter, "vcc_lo, ")?;
|
||||
}
|
||||
write!(formatter, "{src0}, v{src1}")?;
|
||||
if op.reads_vcc() {
|
||||
write!(formatter, ", vcc_lo")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::Branch { target }
|
||||
| Self::BranchSccZero { target }
|
||||
|
||||
@@ -94,6 +94,18 @@ pub enum Operation {
|
||||
Move,
|
||||
/// SOPK: SDST receives the sign-extended SIMM16 when SCC is set.
|
||||
ConditionalMove,
|
||||
/// Terminate the program.
|
||||
EndProgram,
|
||||
/// Unconditional PC-relative branch.
|
||||
Branch,
|
||||
/// Branch when SCC is clear.
|
||||
BranchSccZero,
|
||||
/// Branch when VCC is zero.
|
||||
BranchVccZero,
|
||||
/// Branch when EXEC is zero.
|
||||
BranchExecZero,
|
||||
/// Complete an outstanding vector load.
|
||||
WaitLoad,
|
||||
/// Swap the two old per-lane VGPR values (guide 12.8).
|
||||
Swap,
|
||||
}
|
||||
@@ -165,13 +177,35 @@ pub enum Signedness {
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC.
|
||||
/// Per-lane VOP2 operation selected by the semantic registry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorLowering {
|
||||
/// Two explicit operands, with no implicit lane input.
|
||||
Binary(VectorBinary),
|
||||
/// Two explicit operands and the lane's VCC bit.
|
||||
Vcc(VectorVcc),
|
||||
}
|
||||
|
||||
/// VOP2 primitives with an implicit per-lane VCC input.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorVcc {
|
||||
/// Choose S1 when the VCC bit is set, otherwise S0.
|
||||
Select,
|
||||
/// Unsigned addition with carry-in and carry-out.
|
||||
AddCarry,
|
||||
/// Unsigned subtraction with borrow-in and borrow-out.
|
||||
SubtractBorrow,
|
||||
}
|
||||
|
||||
/// Implicit condition or carry input.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// SCC is not read.
|
||||
/// No implicit condition or carry input.
|
||||
None,
|
||||
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
|
||||
Scc,
|
||||
/// Per-lane Wave32 VCC_LO bit.
|
||||
Vcc,
|
||||
}
|
||||
|
||||
/// What a form writes to SCC.
|
||||
@@ -235,6 +269,12 @@ pub enum OperandRule {
|
||||
/// SOPK integer compare: SDST (s0-s105) is the left operand, SIMM16 the right
|
||||
/// (sign-extended for `_i32`, zero-extended for `_u32`); only SCC is written.
|
||||
SopkCompare,
|
||||
/// SOPP termination with zero in the reserved immediate field.
|
||||
SoppEnd,
|
||||
/// SOPP branch with a signed dword displacement from the next instruction.
|
||||
SoppBranch,
|
||||
/// SOPP wait with exactly vmcnt(0) and the other counters disabled.
|
||||
SoppWait,
|
||||
/// VOPC vector compare: the destination is `vcc_lo` (Wave32); SRC0 is a VGPR,
|
||||
/// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a
|
||||
/// VGPR. Everything else is rejected as unsupported.
|
||||
@@ -242,6 +282,8 @@ pub enum OperandRule {
|
||||
/// Wave32 VOPC with a VGPR pair, even normal SGPR pair or inline integer
|
||||
/// as SRC0 and a VGPR pair as VSRC1. The destination is `vcc_lo`.
|
||||
VopcVccPair,
|
||||
/// VOPC with low-half operands and no literal selector.
|
||||
VopcVccHalf,
|
||||
/// VOP3 encoding of a VOP2 vector form: VDST is v0-v255, SRC0 and SRC1 are
|
||||
/// VGPRs, no input or output modifiers, SRC2 unused. Everything else is
|
||||
/// rejected as unsupported.
|
||||
@@ -250,6 +292,8 @@ pub enum OperandRule {
|
||||
/// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is
|
||||
/// rejected as unsupported.
|
||||
Vop2Vgpr,
|
||||
/// VOP2 general SRC0 and VGPR VSRC1 with an implicit VCC_LO input.
|
||||
Vop2Vcc,
|
||||
/// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs.
|
||||
/// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported.
|
||||
Vop2Vgpr2,
|
||||
|
||||
+939
-75
File diff suppressed because it is too large.
Load diff
@@ -168,6 +168,14 @@ fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
|
||||
|
||||
#[test]
|
||||
fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
const OPERANDS16: [u64; 6] = [
|
||||
0xaaaa_0000,
|
||||
0x5555_0001,
|
||||
0xdead_7fff,
|
||||
0x8000,
|
||||
0xfffe,
|
||||
0xffff,
|
||||
];
|
||||
const OPERANDS32: [u64; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff];
|
||||
const OPERANDS64: [u64; 6] = [0, 1, u64::MAX >> 1, 1 << 63, u64::MAX - 1, u64::MAX];
|
||||
for op in VectorCompareOp::ALL {
|
||||
@@ -188,14 +196,20 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
);
|
||||
// The per-lane test is the declared relation over the declared
|
||||
// signedness, with SRC0 on the left.
|
||||
let operands = if row.width == 64 {
|
||||
OPERANDS64
|
||||
} else {
|
||||
OPERANDS32
|
||||
let operands = match row.width {
|
||||
16 => OPERANDS16,
|
||||
64 => OPERANDS64,
|
||||
_ => OPERANDS32,
|
||||
};
|
||||
for src0 in operands {
|
||||
for src1 in operands {
|
||||
let ordering = if op.signed() && row.width == 64 {
|
||||
let ordering = if row.width == 16 {
|
||||
if op.signed() {
|
||||
(src0 as i16).cmp(&(src1 as i16))
|
||||
} else {
|
||||
(src0 as u16).cmp(&(src1 as u16))
|
||||
}
|
||||
} else if op.signed() && row.width == 64 {
|
||||
(src0 as i64).cmp(&(src1 as i64))
|
||||
} else if op.signed() {
|
||||
(src0 as i32).cmp(&(src1 as i32))
|
||||
@@ -221,7 +235,7 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// v_cmpx and the 16-bit and float compares must not be dispatched.
|
||||
// v_cmpx and the float compares must not be dispatched.
|
||||
dispatch_selects_exactly(EncodingFamily::Vopc, |word| {
|
||||
VectorCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
|
||||
@@ -40,6 +40,7 @@ SRCS = {"": 0, "b": 1, "w": 2, "d": 4, "q": 8, "x": 16}
|
||||
# encoding -> (Rust variant, has ModRM, required immediates)
|
||||
ENCS = {
|
||||
"none": ("None", False, {""}),
|
||||
"string": ("String", False, {""}),
|
||||
"rm_reg": ("RmReg", True, {""}),
|
||||
"reg_rm": ("RegRm", True, {""}),
|
||||
"reg_rm_imm": ("RegRmImm", True, {"ib", "iz"}),
|
||||
|
||||
@@ -97,6 +97,8 @@ pub struct CpuState {
|
||||
/// XMM0-XMM15, lane 0 in the low bits.
|
||||
pub xmm: [u128; 16],
|
||||
pub mxcsr: Mxcsr,
|
||||
/// Direction flag: string instructions step RSI and RDI down when set.
|
||||
pub df: bool,
|
||||
}
|
||||
|
||||
impl CpuState {
|
||||
@@ -111,6 +113,7 @@ impl CpuState {
|
||||
fs_base: 0,
|
||||
xmm: [0; 16],
|
||||
mxcsr: Mxcsr::default(),
|
||||
df: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,8 @@ pub enum Entry {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Encoding {
|
||||
None,
|
||||
/// A string instruction: source `[RSI]`, destination `[RDI]`, REP allowed.
|
||||
String,
|
||||
RmReg,
|
||||
RegRm,
|
||||
RegRmImm,
|
||||
@@ -172,6 +174,8 @@ pub struct Insn {
|
||||
/// Carries a LOCK prefix. Set only for a lockable form with a memory
|
||||
/// destination.
|
||||
pub lock: bool,
|
||||
/// A string instruction carrying a REP prefix.
|
||||
pub rep: bool,
|
||||
}
|
||||
|
||||
impl Insn {
|
||||
@@ -310,8 +314,12 @@ pub fn decode<E>(
|
||||
let opcode = if two_byte { cursor.u8()? } else { byte };
|
||||
let slot = usize::from(opcode);
|
||||
let table = if !two_byte {
|
||||
// Only PAUSE (F3 90) has a meaning here for F3 on a one-byte opcode.
|
||||
if repne || (rep && opcode != 0x90) {
|
||||
// On a one-byte opcode F3 is PAUSE (F3 90) or REP on a string form.
|
||||
let string = matches!(
|
||||
ONE_BYTE[slot],
|
||||
Entry::Form(index) if FORMS[usize::from(index)].encoding == Encoding::String
|
||||
);
|
||||
if repne || (rep && opcode != 0x90 && !string) {
|
||||
return Err(DecodeError::Unsupported(if rep { 0xF3 } else { 0xF2 }));
|
||||
}
|
||||
&ONE_BYTE
|
||||
@@ -424,6 +432,15 @@ pub fn decode<E>(
|
||||
}
|
||||
} else if matches!(form.encoding, Encoding::OpReg | Encoding::OpRegImm) {
|
||||
reg = register(opcode & 7, rex_b, size);
|
||||
} else if form.encoding == Encoding::String {
|
||||
// The source is DS:[RSI], which FS or GS may override. The destination
|
||||
// ES:[RDI] takes no override.
|
||||
rm = Some(RmOperand::Mem(MemOperand {
|
||||
base: Some(6),
|
||||
index: None,
|
||||
disp: 0,
|
||||
segment,
|
||||
}));
|
||||
}
|
||||
// LOCK is an invalid opcode unless the instruction is lockable and its
|
||||
// destination is memory (Intel SDM Vol. 2, "LOCK").
|
||||
@@ -467,6 +484,7 @@ pub fn decode<E>(
|
||||
imm,
|
||||
condition: opcode & 0xF,
|
||||
lock,
|
||||
rep: rep && form.encoding == Encoding::String,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ const RDX: usize = Register::Rdx as usize;
|
||||
const RBX: usize = Register::Rbx as usize;
|
||||
const RSP: usize = Register::Rsp as usize;
|
||||
const RBP: usize = Register::Rbp as usize;
|
||||
const RSI: usize = Register::Rsi as usize;
|
||||
const RDI: usize = Register::Rdi as usize;
|
||||
|
||||
/// Value mask of an operand of `size` bytes.
|
||||
fn mask(size: u8) -> u64 {
|
||||
@@ -582,6 +584,37 @@ pub fn execute(
|
||||
cpu.gpr[register] = u64::from(value);
|
||||
}
|
||||
}
|
||||
Op::Movs | Op::Stos => {
|
||||
// One element per execution. A REP form with elements left keeps
|
||||
// RIP on itself, so every element is a step of its own: it counts
|
||||
// against the step budget, and a fault keeps the elements already
|
||||
// done, with RSI, RDI and RCX at the element that faulted.
|
||||
if !(insn.rep && cpu.gpr[RCX] == 0) {
|
||||
let value = if insn.op == Op::Movs {
|
||||
read_rm(cpu, memory, insn)?
|
||||
} else {
|
||||
cpu.gpr[RAX] & mask(size)
|
||||
};
|
||||
write_mem(memory, cpu.gpr[RDI], size, value)?;
|
||||
let step = if cpu.df {
|
||||
u64::from(size).wrapping_neg()
|
||||
} else {
|
||||
u64::from(size)
|
||||
};
|
||||
if insn.op == Op::Movs {
|
||||
cpu.gpr[RSI] = cpu.gpr[RSI].wrapping_add(step);
|
||||
}
|
||||
cpu.gpr[RDI] = cpu.gpr[RDI].wrapping_add(step);
|
||||
if insn.rep {
|
||||
cpu.gpr[RCX] -= 1;
|
||||
if cpu.gpr[RCX] != 0 {
|
||||
next = insn.rip;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::Cld => cpu.df = false,
|
||||
Op::Std => cpu.df = true,
|
||||
Op::Clc => cpu.flags.cf = false,
|
||||
Op::Stc => cpu.flags.cf = true,
|
||||
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
|
||||
|
||||
+149
-107
@@ -67,6 +67,10 @@ pub enum Op {
|
||||
Stc,
|
||||
Cmc,
|
||||
Cpuid,
|
||||
Cld,
|
||||
Std,
|
||||
Movs,
|
||||
Stos,
|
||||
Movaps,
|
||||
Movups,
|
||||
Movdqa,
|
||||
@@ -205,7 +209,7 @@ pub enum Op {
|
||||
}
|
||||
|
||||
impl Op {
|
||||
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
|
||||
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
|
||||
|
||||
/// Lower-case mnemonic stem.
|
||||
pub const fn name(self) -> &'static str {
|
||||
@@ -269,6 +273,10 @@ impl Op {
|
||||
Op::Stc => "stc",
|
||||
Op::Cmc => "cmc",
|
||||
Op::Cpuid => "cpuid",
|
||||
Op::Cld => "cld",
|
||||
Op::Std => "std",
|
||||
Op::Movs => "movs",
|
||||
Op::Stos => "stos",
|
||||
Op::Movaps => "movaps",
|
||||
Op::Movups => "movups",
|
||||
Op::Movdqa => "movdqa",
|
||||
@@ -469,6 +477,10 @@ impl Op {
|
||||
Op::Stc => 0,
|
||||
Op::Cmc => 1,
|
||||
Op::Cpuid => 0,
|
||||
Op::Cld => 0,
|
||||
Op::Std => 0,
|
||||
Op::Movs => 0,
|
||||
Op::Stos => 0,
|
||||
Op::Movaps => 0,
|
||||
Op::Movups => 0,
|
||||
Op::Movdqa => 0,
|
||||
@@ -669,6 +681,10 @@ impl Op {
|
||||
Op::Stc => 1,
|
||||
Op::Cmc => 1,
|
||||
Op::Cpuid => 0,
|
||||
Op::Cld => 0,
|
||||
Op::Std => 0,
|
||||
Op::Movs => 0,
|
||||
Op::Stos => 0,
|
||||
Op::Movaps => 0,
|
||||
Op::Movups => 0,
|
||||
Op::Movdqa => 0,
|
||||
@@ -869,6 +885,10 @@ impl Op {
|
||||
Op::Stc => 1,
|
||||
Op::Cmc => 1,
|
||||
Op::Cpuid => 0,
|
||||
Op::Cld => 0,
|
||||
Op::Std => 0,
|
||||
Op::Movs => 0,
|
||||
Op::Stos => 0,
|
||||
Op::Movaps => 0,
|
||||
Op::Movups => 0,
|
||||
Op::Movdqa => 0,
|
||||
@@ -1069,6 +1089,10 @@ impl Op {
|
||||
Op::Stc => 0,
|
||||
Op::Cmc => 0,
|
||||
Op::Cpuid => 0,
|
||||
Op::Cld => 0,
|
||||
Op::Std => 0,
|
||||
Op::Movs => 0,
|
||||
Op::Stos => 0,
|
||||
Op::Movaps => 0,
|
||||
Op::Movups => 0,
|
||||
Op::Movdqa => 0,
|
||||
@@ -1269,6 +1293,10 @@ impl Op {
|
||||
Op::Stc => false,
|
||||
Op::Cmc => false,
|
||||
Op::Cpuid => false,
|
||||
Op::Cld => false,
|
||||
Op::Std => false,
|
||||
Op::Movs => true,
|
||||
Op::Stos => true,
|
||||
Op::Movaps => false,
|
||||
Op::Movups => false,
|
||||
Op::Movdqa => false,
|
||||
@@ -1469,6 +1497,10 @@ impl Op {
|
||||
Op::Stc => false,
|
||||
Op::Cmc => false,
|
||||
Op::Cpuid => false,
|
||||
Op::Cld => false,
|
||||
Op::Std => false,
|
||||
Op::Movs => false,
|
||||
Op::Stos => false,
|
||||
Op::Movaps => false,
|
||||
Op::Movups => false,
|
||||
Op::Movdqa => false,
|
||||
@@ -1669,6 +1701,10 @@ impl Op {
|
||||
Op::Stc => false,
|
||||
Op::Cmc => false,
|
||||
Op::Cpuid => false,
|
||||
Op::Cld => false,
|
||||
Op::Std => false,
|
||||
Op::Movs => false,
|
||||
Op::Stos => false,
|
||||
Op::Movaps => true,
|
||||
Op::Movups => true,
|
||||
Op::Movdqa => true,
|
||||
@@ -1808,7 +1844,7 @@ impl Op {
|
||||
}
|
||||
}
|
||||
|
||||
pub static FORMS: [Form; 363] = [
|
||||
pub static FORMS: [Form; 369] = [
|
||||
Form { op: Op::Movsxd, encoding: Encoding::RegRm, size: OperandSize::Wide, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Push, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Pop, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
@@ -1858,6 +1894,12 @@ pub static FORMS: [Form; 363] = [
|
||||
Form { op: Op::Stc, encoding: Encoding::None, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Syscall, encoding: Encoding::None, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Cpuid, encoding: Encoding::None, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movs, encoding: Encoding::String, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movs, encoding: Encoding::String, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Stos, encoding: Encoding::String, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Stos, encoding: Encoding::String, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Cld, encoding: Encoding::None, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Std, encoding: Encoding::None, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movzx, encoding: Encoding::RegRm, size: OperandSize::Variable, immediate: Immediate::None, source: 1, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movzx, encoding: Encoding::RegRm, size: OperandSize::Variable, immediate: Immediate::None, source: 2, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movsx, encoding: Encoding::RegRm, size: OperandSize::Variable, immediate: Immediate::None, source: 1, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
@@ -2176,47 +2218,47 @@ pub static FORMS: [Form; 363] = [
|
||||
|
||||
/// Form per ModRM digit; 65535 marks an unsupported digit.
|
||||
pub static GROUPS: [[u16; 8]; 22] = [
|
||||
[247, 256, 265, 274, 283, 292, 301, 310],
|
||||
[248, 257, 266, 275, 284, 293, 302, 311],
|
||||
[249, 258, 267, 276, 285, 294, 303, 312],
|
||||
[253, 262, 271, 280, 289, 298, 307, 316],
|
||||
[254, 263, 272, 281, 290, 299, 308, 317],
|
||||
[255, 264, 273, 282, 291, 300, 309, 318],
|
||||
[6, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[333, 334, 65535, 65535, 335, 336, 65535, 337],
|
||||
[338, 339, 65535, 65535, 340, 341, 65535, 342],
|
||||
[339, 340, 65535, 65535, 341, 342, 65535, 343],
|
||||
[344, 345, 65535, 65535, 346, 347, 65535, 348],
|
||||
[33, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[34, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[343, 344, 65535, 65535, 345, 346, 65535, 347],
|
||||
[348, 349, 65535, 65535, 350, 351, 65535, 352],
|
||||
[353, 354, 65535, 65535, 355, 356, 65535, 357],
|
||||
[358, 359, 65535, 65535, 360, 361, 65535, 362],
|
||||
[18, 65535, 317, 318, 319, 320, 321, 322],
|
||||
[19, 65535, 323, 324, 325, 326, 327, 328],
|
||||
[329, 330, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[331, 332, 41, 65535, 42, 65535, 5, 65535],
|
||||
[349, 350, 65535, 65535, 351, 352, 65535, 353],
|
||||
[354, 355, 65535, 65535, 356, 357, 65535, 358],
|
||||
[359, 360, 65535, 65535, 361, 362, 65535, 363],
|
||||
[364, 365, 65535, 65535, 366, 367, 65535, 368],
|
||||
[18, 65535, 323, 324, 325, 326, 327, 328],
|
||||
[19, 65535, 329, 330, 331, 332, 333, 334],
|
||||
[335, 336, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[337, 338, 41, 65535, 42, 65535, 5, 65535],
|
||||
[28, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[65535, 65535, 187, 188, 65535, 65535, 65535, 65535],
|
||||
[65535, 65535, 65535, 65535, 313, 314, 315, 316],
|
||||
[65535, 65535, 159, 65535, 161, 65535, 163, 65535],
|
||||
[65535, 65535, 193, 194, 65535, 65535, 65535, 65535],
|
||||
[65535, 65535, 65535, 65535, 319, 320, 321, 322],
|
||||
[65535, 65535, 165, 65535, 167, 65535, 169, 65535],
|
||||
[65535, 65535, 171, 174, 65535, 65535, 173, 175],
|
||||
[65535, 65535, 171, 65535, 173, 65535, 175, 65535],
|
||||
[65535, 65535, 177, 180, 65535, 65535, 179, 181],
|
||||
];
|
||||
|
||||
pub static ONE_BYTE: [Entry; 256] = [
|
||||
Entry::Form(241), Entry::Form(242), Entry::Form(243), Entry::Form(244),
|
||||
Entry::Form(245), Entry::Form(246), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(250), Entry::Form(251), Entry::Form(252), Entry::Form(253),
|
||||
Entry::Form(254), Entry::Form(255), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(259), Entry::Form(260), Entry::Form(261), Entry::Form(262),
|
||||
Entry::Form(263), Entry::Form(264), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(268), Entry::Form(269), Entry::Form(270), Entry::Form(271),
|
||||
Entry::Form(272), Entry::Form(273), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(277), Entry::Form(278), Entry::Form(279), Entry::Form(280),
|
||||
Entry::Form(281), Entry::Form(282), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(286), Entry::Form(287), Entry::Form(288), Entry::Form(289),
|
||||
Entry::Form(290), Entry::Form(291), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(295), Entry::Form(296), Entry::Form(297), Entry::Form(298),
|
||||
Entry::Form(299), Entry::Form(300), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(304), Entry::Form(305), Entry::Form(306), Entry::Form(307),
|
||||
Entry::Form(308), Entry::Form(309), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(247), Entry::Form(248), Entry::Form(249), Entry::Form(250),
|
||||
Entry::Form(251), Entry::Form(252), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(256), Entry::Form(257), Entry::Form(258), Entry::Form(259),
|
||||
Entry::Form(260), Entry::Form(261), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(265), Entry::Form(266), Entry::Form(267), Entry::Form(268),
|
||||
Entry::Form(269), Entry::Form(270), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(274), Entry::Form(275), Entry::Form(276), Entry::Form(277),
|
||||
Entry::Form(278), Entry::Form(279), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(283), Entry::Form(284), Entry::Form(285), Entry::Form(286),
|
||||
Entry::Form(287), Entry::Form(288), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(292), Entry::Form(293), Entry::Form(294), Entry::Form(295),
|
||||
Entry::Form(296), Entry::Form(297), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(301), Entry::Form(302), Entry::Form(303), Entry::Form(304),
|
||||
Entry::Form(305), Entry::Form(306), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(310), Entry::Form(311), Entry::Form(312), Entry::Form(313),
|
||||
Entry::Form(314), Entry::Form(315), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2242,8 +2284,8 @@ pub static ONE_BYTE: [Entry; 256] = [
|
||||
Entry::Form(29), Entry::Form(30), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(16), Entry::Form(17), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(49), Entry::Form(50), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(16), Entry::Form(17), Entry::Form(51), Entry::Form(52),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(31), Entry::Form(31), Entry::Form(31), Entry::Form(31),
|
||||
Entry::Form(31), Entry::Form(31), Entry::Form(31), Entry::Form(31),
|
||||
@@ -2264,7 +2306,7 @@ pub static ONE_BYTE: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(43), Entry::Form(44), Entry::Group(12), Entry::Group(13),
|
||||
Entry::Form(45), Entry::Form(46), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Group(14), Entry::Group(15),
|
||||
Entry::Form(53), Entry::Form(54), Entry::Group(14), Entry::Group(15),
|
||||
];
|
||||
|
||||
pub static TWO_BYTE: [Entry; 256] = [
|
||||
@@ -2272,14 +2314,14 @@ pub static TWO_BYTE: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Form(47), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(71), Entry::Form(72), Entry::Form(90), Entry::Form(92),
|
||||
Entry::Form(181), Entry::Form(183), Entry::Form(94), Entry::Form(96),
|
||||
Entry::Form(77), Entry::Form(78), Entry::Form(96), Entry::Form(98),
|
||||
Entry::Form(187), Entry::Form(189), Entry::Form(100), Entry::Form(102),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Group(16),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(67), Entry::Form(68), Entry::Unsupported, Entry::Form(80),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(221), Entry::Form(222),
|
||||
Entry::Form(73), Entry::Form(74), Entry::Unsupported, Entry::Form(86),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(227), Entry::Form(228),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2288,10 +2330,10 @@ pub static TWO_BYTE: [Entry; 256] = [
|
||||
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
|
||||
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
|
||||
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
|
||||
Entry::Form(98), Entry::Form(189), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(102), Entry::Form(105), Entry::Form(108), Entry::Form(111),
|
||||
Entry::Form(193), Entry::Form(197), Entry::Form(225), Entry::Form(229),
|
||||
Entry::Form(201), Entry::Form(205), Entry::Form(209), Entry::Form(213),
|
||||
Entry::Form(104), Entry::Form(195), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(108), Entry::Form(111), Entry::Form(114), Entry::Form(117),
|
||||
Entry::Form(199), Entry::Form(203), Entry::Form(231), Entry::Form(235),
|
||||
Entry::Form(207), Entry::Form(211), Entry::Form(215), Entry::Form(219),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2308,18 +2350,18 @@ pub static TWO_BYTE: [Entry; 256] = [
|
||||
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
|
||||
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
|
||||
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(48), Entry::Form(59),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(48), Entry::Form(65),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(60),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(66),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Group(17), Entry::Form(9),
|
||||
Entry::Form(63), Entry::Form(64), Entry::Unsupported, Entry::Form(61),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(49), Entry::Form(50),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Group(18), Entry::Form(62),
|
||||
Entry::Form(54), Entry::Form(55), Entry::Form(51), Entry::Form(52),
|
||||
Entry::Form(65), Entry::Form(66), Entry::Form(217), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(179), Entry::Unsupported,
|
||||
Entry::Form(53), Entry::Form(53), Entry::Form(53), Entry::Form(53),
|
||||
Entry::Form(53), Entry::Form(53), Entry::Form(53), Entry::Form(53),
|
||||
Entry::Form(69), Entry::Form(70), Entry::Unsupported, Entry::Form(67),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(55), Entry::Form(56),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Group(18), Entry::Form(68),
|
||||
Entry::Form(60), Entry::Form(61), Entry::Form(57), Entry::Form(58),
|
||||
Entry::Form(71), Entry::Form(72), Entry::Form(223), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(185), Entry::Unsupported,
|
||||
Entry::Form(59), Entry::Form(59), Entry::Form(59), Entry::Form(59),
|
||||
Entry::Form(59), Entry::Form(59), Entry::Form(59), Entry::Form(59),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2339,14 +2381,14 @@ pub static TWO_BYTE_66: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(73), Entry::Form(74), Entry::Form(91), Entry::Form(93),
|
||||
Entry::Form(182), Entry::Form(184), Entry::Form(95), Entry::Form(97),
|
||||
Entry::Form(79), Entry::Form(80), Entry::Form(97), Entry::Form(99),
|
||||
Entry::Form(188), Entry::Form(190), Entry::Form(101), Entry::Form(103),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(69), Entry::Form(70), Entry::Unsupported, Entry::Form(81),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(223), Entry::Form(224),
|
||||
Entry::Form(75), Entry::Form(76), Entry::Unsupported, Entry::Form(87),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(229), Entry::Form(230),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2355,18 +2397,18 @@ pub static TWO_BYTE_66: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(99), Entry::Form(190), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(103), Entry::Form(106), Entry::Form(109), Entry::Form(112),
|
||||
Entry::Form(194), Entry::Form(198), Entry::Form(226), Entry::Form(230),
|
||||
Entry::Form(202), Entry::Form(206), Entry::Form(210), Entry::Form(214),
|
||||
Entry::Form(113), Entry::Form(114), Entry::Form(115), Entry::Form(116),
|
||||
Entry::Form(117), Entry::Form(118), Entry::Form(119), Entry::Form(120),
|
||||
Entry::Form(121), Entry::Form(122), Entry::Form(123), Entry::Form(124),
|
||||
Entry::Form(125), Entry::Form(126), Entry::Form(88), Entry::Form(75),
|
||||
Entry::Form(176), Entry::Group(19), Entry::Group(20), Entry::Group(21),
|
||||
Entry::Form(127), Entry::Form(128), Entry::Form(129), Entry::Unsupported,
|
||||
Entry::Form(105), Entry::Form(196), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(109), Entry::Form(112), Entry::Form(115), Entry::Form(118),
|
||||
Entry::Form(200), Entry::Form(204), Entry::Form(232), Entry::Form(236),
|
||||
Entry::Form(208), Entry::Form(212), Entry::Form(216), Entry::Form(220),
|
||||
Entry::Form(119), Entry::Form(120), Entry::Form(121), Entry::Form(122),
|
||||
Entry::Form(123), Entry::Form(124), Entry::Form(125), Entry::Form(126),
|
||||
Entry::Form(127), Entry::Form(128), Entry::Form(129), Entry::Form(130),
|
||||
Entry::Form(131), Entry::Form(132), Entry::Form(94), Entry::Form(81),
|
||||
Entry::Form(182), Entry::Group(19), Entry::Group(20), Entry::Group(21),
|
||||
Entry::Form(133), Entry::Form(134), Entry::Form(135), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(89), Entry::Form(76),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(95), Entry::Form(82),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2383,22 +2425,22 @@ pub static TWO_BYTE_66: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(218), Entry::Unsupported,
|
||||
Entry::Form(185), Entry::Form(186), Entry::Form(180), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(224), Entry::Unsupported,
|
||||
Entry::Form(191), Entry::Form(192), Entry::Form(186), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(158), Entry::Form(164), Entry::Form(170),
|
||||
Entry::Form(130), Entry::Form(131), Entry::Form(87), Entry::Form(100),
|
||||
Entry::Form(132), Entry::Form(133), Entry::Form(134), Entry::Form(101),
|
||||
Entry::Form(135), Entry::Form(136), Entry::Form(137), Entry::Form(104),
|
||||
Entry::Form(138), Entry::Form(160), Entry::Form(166), Entry::Form(139),
|
||||
Entry::Form(140), Entry::Form(141), Entry::Form(232), Entry::Form(79),
|
||||
Entry::Form(142), Entry::Form(143), Entry::Form(144), Entry::Form(107),
|
||||
Entry::Form(145), Entry::Form(146), Entry::Form(147), Entry::Form(110),
|
||||
Entry::Unsupported, Entry::Form(162), Entry::Form(168), Entry::Form(172),
|
||||
Entry::Form(148), Entry::Form(149), Entry::Form(150), Entry::Unsupported,
|
||||
Entry::Form(151), Entry::Form(152), Entry::Form(153), Entry::Form(154),
|
||||
Entry::Form(155), Entry::Form(156), Entry::Form(157), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(164), Entry::Form(170), Entry::Form(176),
|
||||
Entry::Form(136), Entry::Form(137), Entry::Form(93), Entry::Form(106),
|
||||
Entry::Form(138), Entry::Form(139), Entry::Form(140), Entry::Form(107),
|
||||
Entry::Form(141), Entry::Form(142), Entry::Form(143), Entry::Form(110),
|
||||
Entry::Form(144), Entry::Form(166), Entry::Form(172), Entry::Form(145),
|
||||
Entry::Form(146), Entry::Form(147), Entry::Form(238), Entry::Form(85),
|
||||
Entry::Form(148), Entry::Form(149), Entry::Form(150), Entry::Form(113),
|
||||
Entry::Form(151), Entry::Form(152), Entry::Form(153), Entry::Form(116),
|
||||
Entry::Unsupported, Entry::Form(168), Entry::Form(174), Entry::Form(178),
|
||||
Entry::Form(154), Entry::Form(155), Entry::Form(156), Entry::Unsupported,
|
||||
Entry::Form(157), Entry::Form(158), Entry::Form(159), Entry::Form(160),
|
||||
Entry::Form(161), Entry::Form(162), Entry::Form(163), Entry::Unsupported,
|
||||
];
|
||||
|
||||
pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
@@ -2406,14 +2448,14 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(82), Entry::Form(83), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(88), Entry::Form(89), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(235), Entry::Unsupported,
|
||||
Entry::Form(236), Entry::Form(237), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(241), Entry::Unsupported,
|
||||
Entry::Form(242), Entry::Form(243), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2422,18 +2464,18 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(191), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(197), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(195), Entry::Form(199), Entry::Form(227), Entry::Form(231),
|
||||
Entry::Form(203), Entry::Form(207), Entry::Form(211), Entry::Form(215),
|
||||
Entry::Form(201), Entry::Form(205), Entry::Form(233), Entry::Form(237),
|
||||
Entry::Form(209), Entry::Form(213), Entry::Form(217), Entry::Form(221),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(77),
|
||||
Entry::Form(177), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(83),
|
||||
Entry::Form(183), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(86), Entry::Form(78),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(92), Entry::Form(84),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2448,9 +2490,9 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(56), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(57), Entry::Form(58), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(219), Entry::Unsupported,
|
||||
Entry::Form(62), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(63), Entry::Form(64), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(225), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2459,7 +2501,7 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(233), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(239), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2473,14 +2515,14 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(84), Entry::Form(85), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(90), Entry::Form(91), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(238), Entry::Unsupported,
|
||||
Entry::Form(239), Entry::Form(240), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(244), Entry::Unsupported,
|
||||
Entry::Form(245), Entry::Form(246), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2489,15 +2531,15 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(192), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(198), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(196), Entry::Form(200), Entry::Form(228), Entry::Unsupported,
|
||||
Entry::Form(204), Entry::Form(208), Entry::Form(212), Entry::Form(216),
|
||||
Entry::Form(202), Entry::Form(206), Entry::Form(234), Entry::Unsupported,
|
||||
Entry::Form(210), Entry::Form(214), Entry::Form(218), Entry::Form(222),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(178), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(184), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2517,7 +2559,7 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(220), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(226), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2526,7 +2568,7 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(234), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(240), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
|
||||
@@ -2666,7 +2666,7 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("bt_memory_register_offset_can_fault", 0),
|
||||
("btr16_memory_negative_16bit_offset", 0),
|
||||
("bts_memory_negative_offset", 0),
|
||||
("cmpsb_is_rsi_minus_rdi", 0),
|
||||
("cmpsb_is_rsi_minus_rdi", 1),
|
||||
("cmpxchg16b_equal", 0),
|
||||
("cmpxchg16b_equal_without_lock", 0),
|
||||
("cmpxchg16b_not_equal", 0),
|
||||
@@ -2681,8 +2681,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("enter_leave_round_trip", 0),
|
||||
("fifteen_byte_instruction_executes", 0),
|
||||
("fs_addr32_truncates_before_adding_base", 0),
|
||||
("fs_rep_movsb_overrides_source_only", 0),
|
||||
("fs_rep_movsb_overrides_source_only_df_clear", 0),
|
||||
("haddps_hsubpd_addsubps", 0),
|
||||
("insertps_zero_mask", 0),
|
||||
("jecxz_tests_low_32_bits", 1),
|
||||
@@ -2691,9 +2689,9 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("lahf_zero", 0),
|
||||
("lea64_addr32_truncates_effective_address", 0),
|
||||
("lock_btc_memory", 0),
|
||||
("lodsd_zero_extends", 0),
|
||||
("lodsd_zero_extends", 1),
|
||||
("lodsd_zero_extends_df_clear", 0),
|
||||
("lodsw_preserves_upper48", 0),
|
||||
("lodsw_preserves_upper48", 1),
|
||||
("loop_decrements_rcx_without_flags", 1),
|
||||
("loopne_stops_on_zero_flag", 1),
|
||||
("maskmovdqu_selects_bytes", 0),
|
||||
@@ -2701,7 +2699,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("mov_moffs8_store", 0),
|
||||
("movddup_movsldup_movshdup", 0),
|
||||
("movdqa_movaps_aligned_store_and_load", 3),
|
||||
("movsb_forward", 0),
|
||||
("mpsadbw", 0),
|
||||
("pabs_min_is_unchanged", 0),
|
||||
("packusdw", 0),
|
||||
@@ -2739,27 +2736,16 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("rcr8_by10_is_by_one_mod_9", 0),
|
||||
("rcr8_by1_clear_carry_in", 0),
|
||||
("rcr8_by1_set_carry_in", 0),
|
||||
("rep_lodsb_source_fault", 0),
|
||||
("rep_movs_zero_count_touches_nothing", 0),
|
||||
("rep_movsb_addr32_uses_32bit_registers", 0),
|
||||
("rep_movsb_fault_df_clear", 0),
|
||||
("rep_movsb_fault_stops_at_failing_iteration", 0),
|
||||
("rep_movsb_overlap_propagates_df_clear", 0),
|
||||
("rep_movsq_overlap_propagates", 0),
|
||||
("rep_movsq_zero_count_df_clear", 0),
|
||||
("rep_movsw_backward", 0),
|
||||
("rep_stosd_df_clear", 0),
|
||||
("rep_stosd_forward", 0),
|
||||
("rep_stosq_fault_df_clear", 0),
|
||||
("rep_stosq_fault_stops_at_failing_iteration", 0),
|
||||
("repe_cmpsb_fault_restores_flags", 0),
|
||||
("rep_lodsb_source_fault", 1),
|
||||
("rep_movsb_addr32_uses_32bit_registers", 1),
|
||||
("repe_cmpsb_fault_restores_flags", 1),
|
||||
("repe_cmpsb_fault_restores_flags_df_clear", 0),
|
||||
("repe_cmpsb_stops_at_difference", 0),
|
||||
("repe_cmpsb_stops_at_difference", 1),
|
||||
("repe_cmpsb_stops_at_difference_df_clear", 0),
|
||||
("repe_cmpsb_zero_count_keeps_flags", 0),
|
||||
("repne_scasb_finds_byte", 0),
|
||||
("repe_cmpsb_zero_count_keeps_flags", 1),
|
||||
("repne_scasb_finds_byte", 1),
|
||||
("repne_scasb_finds_byte_df_clear", 0),
|
||||
("repne_scasd_exhausts_count", 0),
|
||||
("repne_scasd_exhausts_count", 1),
|
||||
("rex_not_adjacent_to_opcode_is_ignored", 0),
|
||||
("roundps_uses_mxcsr_rc", 0),
|
||||
("roundsd_suppress_precision", 0),
|
||||
@@ -3613,6 +3599,7 @@ fn dbt_route_of_every_case_is_recorded() {
|
||||
let memory = start.image.load(&case.code);
|
||||
let text: Vec<&str> = case.asm.split(';').map(str::trim).collect();
|
||||
let mut routes = Vec::new();
|
||||
let mut repeats = false;
|
||||
for (index, &offset) in case.offsets.iter().enumerate() {
|
||||
let Ok(insn) = decode(CODE + offset as u64, |at| memory.fetch_instruction_byte(at))
|
||||
else {
|
||||
@@ -3620,6 +3607,7 @@ fn dbt_route_of_every_case_is_recorded() {
|
||||
};
|
||||
let name = text.get(index).copied().unwrap_or(case.asm);
|
||||
routes.push(is_native(&insn));
|
||||
repeats |= insn.rep;
|
||||
if is_native(&insn) {
|
||||
native.insert(name);
|
||||
} else {
|
||||
@@ -3634,13 +3622,13 @@ fn dbt_route_of_every_case_is_recorded() {
|
||||
};
|
||||
counts.entry(group).or_default()[kind] += 1;
|
||||
// Straight-line cases run each instruction once, so the counter must equal
|
||||
// the number of helper instructions.
|
||||
// the number of helper instructions. A REP form runs once per element.
|
||||
let labelled = text.iter().any(|piece| {
|
||||
piece
|
||||
.split_once(':')
|
||||
.is_some_and(|(label, _)| label.parse::<u8>().is_ok())
|
||||
});
|
||||
if !labelled && case.fault.is_empty() && routes.len() == case.offsets.len() {
|
||||
if !labelled && !repeats && case.fault.is_empty() && routes.len() == case.offsets.len() {
|
||||
let mut dbt = new_dbt();
|
||||
let mut memory = memory.clone();
|
||||
run_dbt(&mut dbt, &start.cpu, &mut memory, BUDGET);
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! MOVS, STOS, REP and the direction flag (issue #129).
|
||||
//!
|
||||
//! Expected results come from a byte-array model written from the operation
|
||||
//! sections of the Intel SDM Vol. 2 for MOVS, STOS, REP, CLD and STD. The
|
||||
//! model never decodes or calls the production semantics. Encodings were
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
//! Nothing was compared with x86 hardware.
|
||||
//!
|
||||
//! A REP form runs one element per step and stays on the instruction until RCX
|
||||
//! is zero. The tests check that rule through the step counts, so a repeat can
|
||||
//! never outrun the step budget.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
use xenora_loader::x86_table::{FORMS, Op};
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
/// One writable page with nothing mapped on either side.
|
||||
const DATA: u64 = 0x8000;
|
||||
const PAGE: usize = 0x1000;
|
||||
const END: u64 = DATA + PAGE as u64;
|
||||
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RSI: usize = 6;
|
||||
const RDI: usize = 7;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Kind {
|
||||
Movs,
|
||||
Stos,
|
||||
}
|
||||
|
||||
/// `[rep] movs/stos` for an element of `size` bytes, in the assembler's order.
|
||||
fn encode(kind: Kind, size: u64, rep: bool) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
if rep {
|
||||
code.push(0xF3);
|
||||
}
|
||||
match size {
|
||||
2 => code.push(0x66),
|
||||
8 => code.push(0x48),
|
||||
_ => {}
|
||||
}
|
||||
code.push(match (kind, size) {
|
||||
(Kind::Movs, 1) => 0xA4,
|
||||
(Kind::Movs, _) => 0xA5,
|
||||
(Kind::Stos, 1) => 0xAA,
|
||||
(Kind::Stos, _) => 0xAB,
|
||||
});
|
||||
code
|
||||
}
|
||||
|
||||
fn image(code: &[u8], data: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(DATA, PAGE, MemoryPermissions::READ_WRITE, data)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn bytes(memory: &GuestMemory) -> Vec<u8> {
|
||||
let mut out = vec![0; PAGE];
|
||||
memory.read_bytes(DATA, &mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
struct Run {
|
||||
name: &'static str,
|
||||
result: ExecutionResult,
|
||||
memory: GuestMemory,
|
||||
/// Instructions the DBT ran on the shared semantics.
|
||||
helpers: usize,
|
||||
}
|
||||
|
||||
/// The interpreter and the DBT, each from its own copy of the state.
|
||||
fn both(cpu: &CpuState, memory: &GuestMemory, budget: usize) -> [Run; 2] {
|
||||
let mut interpreted = memory.clone();
|
||||
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
|
||||
let mut translated = memory.clone();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let mut state = cpu.clone();
|
||||
let native = engine.run(&mut state, &mut translated, budget);
|
||||
[
|
||||
Run {
|
||||
name: "interpreter",
|
||||
result,
|
||||
memory: interpreted,
|
||||
helpers: 0,
|
||||
},
|
||||
Run {
|
||||
name: "DBT",
|
||||
result: native,
|
||||
memory: translated,
|
||||
helpers: engine.metrics.interpreter_fallbacks,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Deterministic generator (xorshift64*).
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
}
|
||||
|
||||
/// The architectural effect of `count` elements on a byte array: each element
|
||||
/// is read whole, then written, then the pointers move by its size.
|
||||
fn model(
|
||||
kind: Kind,
|
||||
size: u64,
|
||||
backward: bool,
|
||||
count: u64,
|
||||
data: &mut [u8],
|
||||
rax: u64,
|
||||
(mut rsi, mut rdi): (u64, u64),
|
||||
) -> (u64, u64) {
|
||||
let size_bytes = size as usize;
|
||||
for _ in 0..count {
|
||||
let element: Vec<u8> = match kind {
|
||||
Kind::Movs => {
|
||||
let from = (rsi - DATA) as usize;
|
||||
data[from..from + size_bytes].to_vec()
|
||||
}
|
||||
Kind::Stos => rax.to_le_bytes()[..size_bytes].to_vec(),
|
||||
};
|
||||
let to = (rdi - DATA) as usize;
|
||||
data[to..to + size_bytes].copy_from_slice(&element);
|
||||
if kind == Kind::Movs {
|
||||
rsi = if backward { rsi - size } else { rsi + size };
|
||||
}
|
||||
rdi = if backward { rdi - size } else { rdi + size };
|
||||
}
|
||||
(rsi, rdi)
|
||||
}
|
||||
|
||||
const FLAGS: RFlags = RFlags {
|
||||
cf: true,
|
||||
zf: false,
|
||||
sf: true,
|
||||
of: false,
|
||||
pf: true,
|
||||
af: false,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn every_form_matches_a_byte_array_model_and_counts_one_step_per_element() {
|
||||
let mut random = Random(0x1234_5678_9ABC_DEF1);
|
||||
for kind in [Kind::Movs, Kind::Stos] {
|
||||
for size in [1, 2, 4, 8] {
|
||||
for rep in [false, true] {
|
||||
for backward in [false, true] {
|
||||
for round in 0..40 {
|
||||
// Counts 0 to 9. Source and destination start within 24
|
||||
// bytes of each other, so the ranges often overlap.
|
||||
let count = round % 10;
|
||||
let rsi = DATA + 0x400 + random.next() % 0x100;
|
||||
let rdi = rsi + random.next() % 49 - 24;
|
||||
let rax = random.next();
|
||||
let data: Vec<u8> = (0..PAGE).map(|_| random.next() as u8).collect();
|
||||
|
||||
let mut code = encode(kind, size, rep);
|
||||
code.push(0xF4); // hlt
|
||||
let memory = image(&code, &data);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
for register in &mut cpu.gpr {
|
||||
*register = random.next();
|
||||
}
|
||||
cpu.gpr[RAX] = rax;
|
||||
cpu.gpr[RCX] = count;
|
||||
cpu.gpr[RSI] = rsi;
|
||||
cpu.gpr[RDI] = rdi;
|
||||
cpu.df = backward;
|
||||
cpu.flags = FLAGS;
|
||||
|
||||
// Without REP exactly one element moves and RCX is not
|
||||
// read or written.
|
||||
let elements = if rep { count } else { 1 };
|
||||
let mut wanted_data = data.clone();
|
||||
let (wanted_rsi, wanted_rdi) = model(
|
||||
kind,
|
||||
size,
|
||||
backward,
|
||||
elements,
|
||||
&mut wanted_data,
|
||||
rax,
|
||||
(rsi, rdi),
|
||||
);
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.rip = ENTRY + code.len() as u64;
|
||||
wanted.gpr[RSI] = wanted_rsi;
|
||||
wanted.gpr[RDI] = wanted_rdi;
|
||||
if rep {
|
||||
wanted.gpr[RCX] = 0;
|
||||
}
|
||||
// One step per element, one for a REP with a zero
|
||||
// count, and one for the HLT.
|
||||
let steps = elements.max(1) as usize + 1;
|
||||
|
||||
for run in both(&cpu, &memory, 64) {
|
||||
let what = format!(
|
||||
"{kind:?} size {size} rep={rep} backward={backward} count={count} \
|
||||
on the {}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(run.result.exit_reason, ExitReason::Halt, "{what}");
|
||||
assert_eq!(run.result.final_state, wanted, "{what}");
|
||||
assert!(bytes(&run.memory) == wanted_data, "{what}: memory");
|
||||
assert_eq!(run.result.instructions_executed, steps, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn step_budget_stops_a_repeat_part_way_and_it_resumes() {
|
||||
// rep stosb; hlt
|
||||
let code = [0xF3, 0xAA, 0xF4];
|
||||
let memory = image(&code, &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x5A;
|
||||
cpu.gpr[RCX] = 100;
|
||||
cpu.gpr[RDI] = DATA + 0x200;
|
||||
for run in both(&cpu, &memory, 10) {
|
||||
// Ten steps store ten bytes and leave RIP on the instruction.
|
||||
assert_eq!(
|
||||
run.result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(run.result.instructions_executed, 10, "{}", run.name);
|
||||
let state = &run.result.final_state;
|
||||
assert_eq!(
|
||||
(state.rip, state.gpr[RCX], state.gpr[RDI]),
|
||||
(ENTRY, 90, DATA + 0x20A),
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
let written = bytes(&run.memory);
|
||||
assert_eq!(written[0x200..0x20A], [0x5A; 10], "{}", run.name);
|
||||
assert_eq!(written[0x20A..0x264], [0; 90], "{}", run.name);
|
||||
if run.name == "DBT" {
|
||||
assert_eq!(run.helpers, 10);
|
||||
}
|
||||
|
||||
// Resuming from that state finishes the remaining ninety and halts.
|
||||
let [rest, _] = both(state, &run.memory, 1000);
|
||||
assert_eq!(rest.result.exit_reason, ExitReason::Halt, "{}", run.name);
|
||||
assert_eq!(rest.result.instructions_executed, 91, "{}", run.name);
|
||||
assert_eq!(rest.result.final_state.gpr[RCX], 0, "{}", run.name);
|
||||
assert_eq!(
|
||||
bytes(&rest.memory)[0x200..0x264],
|
||||
[0x5A; 100],
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_is_all_of_rcx() {
|
||||
// rep stosb with a count above 32 bits: two steps take exactly two off it.
|
||||
let memory = image(&[0xF3, 0xAA, 0xF4], &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = 0x0000_0001_0000_0001;
|
||||
cpu.gpr[RDI] = DATA;
|
||||
for run in both(&cpu, &memory, 2) {
|
||||
assert_eq!(
|
||||
run.result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(
|
||||
run.result.final_state.gpr[RCX], 0x0000_0000_FFFF_FFFF,
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(run.result.final_state.rip, ENTRY, "{}", run.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_keeps_the_elements_already_done() {
|
||||
// (code, RSI, RDI, backward, elements that complete before the fault)
|
||||
let cases: &[(&[u8], u64, u64, bool, u64)] = &[
|
||||
// rep movsq up to the end of the page: 19 bytes hold two elements, and
|
||||
// the third would end past the page.
|
||||
(&[0xF3, 0x48, 0xA5], DATA, END - 19, false, 2),
|
||||
// rep stosd down to the start of the page: elements at offsets 5 and 1
|
||||
// fit, the next would start before the page.
|
||||
(&[0xF3, 0xAB], 0, DATA + 5, true, 2),
|
||||
// rep movsw from a source that ends: three elements can be read.
|
||||
(&[0xF3, 0x66, 0xA5], END - 6, DATA + 0x100, false, 3),
|
||||
// rep movsb with no readable source at all.
|
||||
(&[0xF3, 0xA4], END, DATA + 0x100, false, 0),
|
||||
];
|
||||
let mut random = Random(77);
|
||||
for &(code, rsi, rdi, backward, done) in cases {
|
||||
let data: Vec<u8> = (0..PAGE).map(|_| random.next() as u8).collect();
|
||||
let memory = image(code, &data);
|
||||
let insn = decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap();
|
||||
let (kind, size) = (
|
||||
if insn.op == Op::Movs {
|
||||
Kind::Movs
|
||||
} else {
|
||||
Kind::Stos
|
||||
},
|
||||
u64::from(insn.size),
|
||||
);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x1122_3344_5566_7788;
|
||||
cpu.gpr[RCX] = 9;
|
||||
cpu.gpr[RSI] = rsi;
|
||||
cpu.gpr[RDI] = rdi;
|
||||
cpu.df = backward;
|
||||
cpu.flags = FLAGS;
|
||||
|
||||
// The completed elements took effect. The faulting one changed
|
||||
// nothing, and RIP stays on the instruction so it can be restarted.
|
||||
let mut wanted_data = data.clone();
|
||||
let (wanted_rsi, wanted_rdi) = model(
|
||||
kind,
|
||||
size,
|
||||
backward,
|
||||
done,
|
||||
&mut wanted_data,
|
||||
cpu.gpr[RAX],
|
||||
(rsi, rdi),
|
||||
);
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.gpr[RCX] = 9 - done;
|
||||
wanted.gpr[RSI] = wanted_rsi;
|
||||
wanted.gpr[RDI] = wanted_rdi;
|
||||
|
||||
for run in both(&cpu, &memory, 64) {
|
||||
let what = format!("{code:02X?} on the {}", run.name);
|
||||
assert!(
|
||||
matches!(run.result.exit_reason, ExitReason::MemoryFault(_)),
|
||||
"{what}: {:?}",
|
||||
run.result.exit_reason
|
||||
);
|
||||
assert_eq!(run.result.final_state, wanted, "{what}");
|
||||
assert!(bytes(&run.memory) == wanted_data, "{what}: memory");
|
||||
assert_eq!(run.result.instructions_executed, done as usize, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direction_flag_is_set_by_std_and_cleared_by_cld() {
|
||||
// std; stosb; cld; stosb; hlt
|
||||
let code = [0xFD, 0xAA, 0xFC, 0xAA, 0xF4];
|
||||
let memory = image(&code, &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0xC3;
|
||||
cpu.gpr[RDI] = DATA + 0x80;
|
||||
cpu.flags = FLAGS;
|
||||
for run in both(&cpu, &memory, 16) {
|
||||
assert_eq!(run.result.exit_reason, ExitReason::Halt, "{}", run.name);
|
||||
// The first store steps down to 0x7F, the second back up to 0x80.
|
||||
assert_eq!(run.result.final_state.gpr[RDI], DATA + 0x80, "{}", run.name);
|
||||
let written = bytes(&run.memory);
|
||||
assert_eq!(written[0x7F..0x81], [0xC3, 0xC3], "{}", run.name);
|
||||
assert!(!run.result.final_state.df, "{}", run.name);
|
||||
// Neither instruction touches a status flag.
|
||||
assert_eq!(run.result.final_state.flags, FLAGS, "{}", run.name);
|
||||
}
|
||||
// The flag outlives the run that set it.
|
||||
for run in both(&cpu, &image(&[0xFD, 0xF4], &[0; PAGE]), 4) {
|
||||
assert!(run.result.final_state.df, "{}", run.name);
|
||||
assert_eq!(run.result.final_state.flags, FLAGS, "{}", run.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_override_moves_the_source_only() {
|
||||
const BASE: u64 = 0x300;
|
||||
let mut data = vec![0u8; PAGE];
|
||||
data[0x10] = 0x11; // DATA + 0x10, what [RSI] names without a base
|
||||
data[0x310] = 0x22; // DATA + 0x10 + BASE, the same RSI under the FS or GS base
|
||||
for (code, uses_base) in [
|
||||
(&[0xA4][..], false), // movsb
|
||||
(&[0x64, 0xA4][..], true), // movsb with the source under FS
|
||||
(&[0x65, 0xA4][..], true), // movsb with the source under GS
|
||||
] {
|
||||
let memory = image(code, &data);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.fs_base = BASE;
|
||||
cpu.gs_base = BASE;
|
||||
cpu.gpr[RSI] = DATA + 0x10;
|
||||
cpu.gpr[RDI] = DATA + 0x800;
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let what = format!("{code:02X?} on the {}", run.name);
|
||||
// The destination is [RDI] with no base either way.
|
||||
let wanted = if uses_base { 0x22 } else { 0x11 };
|
||||
assert_eq!(bytes(&run.memory)[0x800], wanted, "{what}");
|
||||
assert_eq!(
|
||||
run.result.final_state.gpr[RSI],
|
||||
DATA + 0x11,
|
||||
"{what}: RSI moves by the element, not by the base"
|
||||
);
|
||||
}
|
||||
}
|
||||
// STOS has no source, and its destination takes no override.
|
||||
let memory = image(&[0x64, 0xAA], &data);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.fs_base = BASE;
|
||||
cpu.gpr[RAX] = 0x77;
|
||||
cpu.gpr[RDI] = DATA + 0x800;
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let written = bytes(&run.memory);
|
||||
assert_eq!((written[0x800], written[0xB00]), (0x77, 0), "{}", run.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_the_declared_string_forms_decode() {
|
||||
let decode_bytes = |code: &[u8]| {
|
||||
decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
for kind in [Kind::Movs, Kind::Stos] {
|
||||
for size in [1, 2, 4, 8] {
|
||||
for rep in [false, true] {
|
||||
let code = encode(kind, size, rep);
|
||||
let insn =
|
||||
decode_bytes(&code).unwrap_or_else(|error| panic!("{code:02X?}: {error:?}"));
|
||||
assert_eq!(usize::from(insn.len), code.len(), "{code:02X?}");
|
||||
assert_eq!((u64::from(insn.size), insn.rep), (size, rep), "{code:02X?}");
|
||||
assert!(!is_native(&insn), "{code:02X?}");
|
||||
seen.insert(usize::from(insn.form));
|
||||
}
|
||||
}
|
||||
}
|
||||
for code in [[0xFC], [0xFD]] {
|
||||
seen.insert(usize::from(decode_bytes(&code).unwrap().form));
|
||||
}
|
||||
// Every declared form of these operations was reached above.
|
||||
for (index, form) in FORMS.iter().enumerate() {
|
||||
if matches!(form.op, Op::Movs | Op::Stos | Op::Cld | Op::Std) {
|
||||
assert!(seen.contains(&index), "{:?} {:?}", form.op, form.size);
|
||||
}
|
||||
}
|
||||
|
||||
let rejected: &[&[u8]] = &[
|
||||
&[0xF2, 0xA4], // repne movsb
|
||||
&[0xF2, 0xAB], // repne stosd
|
||||
&[0xF3, 0xF2, 0xA4], // both repeat prefixes
|
||||
&[0x67, 0xF3, 0xA4], // rep movsb with 32-bit addresses
|
||||
&[0xF0, 0xF3, 0xAA], // lock rep stosb
|
||||
&[0xF3, 0xFC], // rep cld
|
||||
&[0xA6], // cmpsb
|
||||
&[0xF3, 0xA6], // repe cmpsb
|
||||
&[0xAC], // lodsb
|
||||
&[0xAE], // scasb
|
||||
&[0xF2, 0xAE], // repne scasb
|
||||
];
|
||||
for code in rejected {
|
||||
let mut padded = code.to_vec();
|
||||
padded.extend([0x90; 8]);
|
||||
let memory = image(&padded, &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = 3;
|
||||
cpu.gpr[RSI] = DATA;
|
||||
cpu.gpr[RDI] = DATA + 0x100;
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert!(
|
||||
matches!(run.result.exit_reason, ExitReason::IllegalInstruction(_)),
|
||||
"{code:02X?} on the {}: {:?}",
|
||||
run.name,
|
||||
run.result.exit_reason
|
||||
);
|
||||
assert_eq!(run.result.final_state, cpu, "{code:02X?}");
|
||||
assert!(bytes(&run.memory) == vec![0; PAGE], "{code:02X?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -977,7 +977,9 @@ fn every_declared_form_is_executed_by_a_fixture() {
|
||||
.unwrap_or_else(|error| panic!("{line}: {error:?}"));
|
||||
seen.insert(usize::from(insn.form));
|
||||
}
|
||||
// Control flow and exits are covered by the tests below.
|
||||
// Control flow and exits are covered by the tests below. String
|
||||
// instructions and the direction flag need their own memory layout and
|
||||
// are covered form by form in `tests/cpu_rep.rs`.
|
||||
let separate = [
|
||||
Op::Ldmxcsr,
|
||||
Op::Jcc,
|
||||
@@ -986,6 +988,10 @@ fn every_declared_form_is_executed_by_a_fixture() {
|
||||
Op::Ret,
|
||||
Op::Hlt,
|
||||
Op::Syscall,
|
||||
Op::Movs,
|
||||
Op::Stos,
|
||||
Op::Cld,
|
||||
Op::Std,
|
||||
];
|
||||
let mut missing: BTreeMap<&str, Vec<String>> = BTreeMap::new();
|
||||
for (index, form) in FORMS.iter().enumerate() {
|
||||
@@ -1208,7 +1214,8 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
|
||||
&[0xF0, 0x01, 0x0E], // lock add [rsi], ecx
|
||||
&[0xF2, 0x90], // repne nop
|
||||
&[0xF3, 0xC3], // rep ret
|
||||
&[0xF3, 0xA4], // rep movsb
|
||||
&[0xF2, 0xA4], // repne movsb
|
||||
&[0xF3, 0xA6], // repe cmpsb
|
||||
&[0x67, 0x8B, 0x06], // address-size override
|
||||
&[0x64, 0x2E, 0x8B, 0x06], // CS after FS
|
||||
&[0x66, 0x50], // push ax
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
# decodable; a form counts as implemented only once its operation has semantics
|
||||
# and independent tests. Forms not listed here are rejected.
|
||||
#
|
||||
# enc = "string" is a string instruction: its source is [RSI], which FS or GS
|
||||
# may override, its destination is [RDI], and it accepts the REP prefix (F3).
|
||||
#
|
||||
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
|
||||
# Every other use of LOCK is rejected, as the architecture's #UD.
|
||||
#
|
||||
@@ -91,6 +94,11 @@ clc = { writes = "cf", ref = "sdm CLC" }
|
||||
stc = { writes = "cf", ref = "sdm STC" }
|
||||
cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
|
||||
cpuid = { ref = "sdm CPUID" }
|
||||
cld = { ref = "sdm CLD" }
|
||||
std = { ref = "sdm STD" }
|
||||
# A REP form repeats by leaving RIP on itself, so these end a translated block.
|
||||
movs = { terminator = true, ref = "sdm MOVS/MOVSB/MOVSW/MOVSD/MOVSQ" }
|
||||
stos = { terminator = true, ref = "sdm STOS/STOSB/STOSW/STOSD/STOSQ" }
|
||||
|
||||
# SSE and SSE2 moves and packed integer operations. None reads or writes RFLAGS.
|
||||
movaps = { ref = "sdm MOVAPS" }
|
||||
@@ -575,6 +583,42 @@ opcode = 0xA2
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "movs"
|
||||
opcode = 0xA4
|
||||
enc = "string"
|
||||
size = "b"
|
||||
|
||||
[[form]]
|
||||
op = "movs"
|
||||
opcode = 0xA5
|
||||
enc = "string"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "stos"
|
||||
opcode = 0xAA
|
||||
enc = "string"
|
||||
size = "b"
|
||||
|
||||
[[form]]
|
||||
op = "stos"
|
||||
opcode = 0xAB
|
||||
enc = "string"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "cld"
|
||||
opcode = 0xFC
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "std"
|
||||
opcode = 0xFD
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "movzx"
|
||||
map = "0f"
|
||||
|
||||
+64
-2
@@ -76,7 +76,7 @@ pub enum Op {
|
||||
},
|
||||
Vector(VectorAlu, u8, u8, u8),
|
||||
/// VOP2 32-bit integer form: VDST, SRC0 (VGPR, SGPR, `vcc_lo`, inline
|
||||
/// integer or literal) and VSRC1. Writes neither VCC nor SCC.
|
||||
/// integer or literal) and VSRC1, with implicit VCC for select/carry forms.
|
||||
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.
|
||||
@@ -317,6 +317,12 @@ pub enum VectorAlu {
|
||||
/// section 12.7). None has a carry-in or carry-out.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorInteger {
|
||||
/// 1: select S1 when the lane's VCC bit is set.
|
||||
Select,
|
||||
/// 40: unsigned add with carry input and output.
|
||||
AddCarry,
|
||||
/// 41 / 42: unsigned subtract with borrow input and output.
|
||||
SubtractBorrow { reversed: bool },
|
||||
/// 9 / 11: D = low 32 bits of S0[23:0] * S1[23:0], sign-extended from
|
||||
/// bit 23 when `signed`.
|
||||
Multiply24 { signed: bool },
|
||||
@@ -340,6 +346,11 @@ impl VectorInteger {
|
||||
/// Opcode bits 30-25 of the VOP2 word.
|
||||
fn from_opcode(opcode: u8) -> Option<Self> {
|
||||
Some(match opcode {
|
||||
1 => Self::Select,
|
||||
40 => Self::AddCarry,
|
||||
41 | 42 => Self::SubtractBorrow {
|
||||
reversed: opcode == 42,
|
||||
},
|
||||
9 => Self::Multiply24 { signed: true },
|
||||
10 => Self::MultiplyHigh24 { signed: true },
|
||||
11 => Self::Multiply24 { signed: false },
|
||||
@@ -356,6 +367,34 @@ impl VectorInteger {
|
||||
})
|
||||
}
|
||||
|
||||
fn reads_vcc(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Select | Self::AddCarry | Self::SubtractBorrow { .. }
|
||||
)
|
||||
}
|
||||
|
||||
fn writes_vcc(self) -> bool {
|
||||
matches!(self, Self::AddCarry | Self::SubtractBorrow { .. })
|
||||
}
|
||||
|
||||
// Guide 12.7: carry/borrow is determined from the exact mathematical result.
|
||||
fn apply_vcc(self, a: u32, b: u32, bit: u32) -> (u32, bool) {
|
||||
match self {
|
||||
Self::Select => (if bit == 0 { a } else { b }, false),
|
||||
Self::AddCarry => {
|
||||
let exact = u64::from(a) + u64::from(b) + u64::from(bit);
|
||||
(exact as u32, exact > u64::from(u32::MAX))
|
||||
}
|
||||
Self::SubtractBorrow { reversed } => {
|
||||
let (minuend, subtrahend) = if reversed { (b, a) } else { (a, b) };
|
||||
let exact = i64::from(minuend) - i64::from(subtrahend) - i64::from(bit);
|
||||
(exact as u32, exact < 0)
|
||||
}
|
||||
_ => unreachable!("VOP2 operation does not read VCC"),
|
||||
}
|
||||
}
|
||||
|
||||
/// D for S0 = `a`, S1 = `b`, from exact i64 arithmetic reduced modulo 2^32.
|
||||
fn apply(self, a: u32, b: u32) -> u32 {
|
||||
let field = |bits: u32, signed: bool| {
|
||||
@@ -393,6 +432,9 @@ impl VectorInteger {
|
||||
Self::Add => a.wrapping_add(b),
|
||||
Self::Subtract => a.wrapping_sub(b),
|
||||
Self::SubtractReverse => b.wrapping_sub(a),
|
||||
Self::Select | Self::AddCarry | Self::SubtractBorrow { .. } => {
|
||||
unreachable!("VOP2 operation requires VCC")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1087,13 +1129,33 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
}
|
||||
check(src1)?;
|
||||
}
|
||||
let incoming = if exec != 0 && kind.reads_vcc() {
|
||||
read_scalar(Source::Register(VCC_LO as u8))?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut outgoing = 0;
|
||||
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, read(lane, src1)?)));
|
||||
let s1 = read(lane, src1)?;
|
||||
let value = if kind.reads_vcc() {
|
||||
let (value, carry) = kind.apply_vcc(s0, s1, (incoming >> lane) & 1);
|
||||
outgoing |= u32::from(carry) << lane;
|
||||
value
|
||||
} else {
|
||||
kind.apply(s0, s1)
|
||||
};
|
||||
results[lane] = Some((dst, value));
|
||||
}
|
||||
// Guide 3.9: only executing lanes can contribute a carry.
|
||||
if kind.writes_vcc() {
|
||||
scalars[VCC_LO] = Some(outgoing);
|
||||
scalars[VCC_HI] = None;
|
||||
lane_derived_vcc = exec != 0;
|
||||
}
|
||||
}
|
||||
Op::VectorUnary(kind, dst, src0) => {
|
||||
|
||||
+245
-102
@@ -8,9 +8,11 @@ mod graphics;
|
||||
pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
pub use xenora_decoder::Architecture;
|
||||
use xenora_decoder::SoppControlOp;
|
||||
use xenora_decoder::{
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, ScalarUnaryOp, VectorAluOp,
|
||||
VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorSource, VectorUnary,
|
||||
VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorLowering, VectorSource, VectorUnary,
|
||||
VectorVcc,
|
||||
};
|
||||
|
||||
/// SGPR index of `vcc_lo`.
|
||||
@@ -99,6 +101,17 @@ enum Op {
|
||||
inactive: Value,
|
||||
},
|
||||
Store(Value),
|
||||
VccArithmetic {
|
||||
primitive: VectorVcc,
|
||||
left: Value,
|
||||
right: Value,
|
||||
mask: Value,
|
||||
flag: bool,
|
||||
},
|
||||
CarryMask {
|
||||
flag: Value,
|
||||
exec: u32,
|
||||
},
|
||||
ScalarBranch {
|
||||
target: usize,
|
||||
taken: bool,
|
||||
@@ -146,6 +159,10 @@ impl Op {
|
||||
operands
|
||||
}
|
||||
Self::RuntimeBranch { mask, .. } => vec![mask],
|
||||
Self::VccArithmetic {
|
||||
left, right, mask, ..
|
||||
} => vec![left, right, mask],
|
||||
Self::CarryMask { flag, .. } => vec![flag],
|
||||
Self::JoinVccz {
|
||||
mask,
|
||||
fallthrough,
|
||||
@@ -204,8 +221,32 @@ impl Op {
|
||||
name(fallthrough),
|
||||
name(taken)
|
||||
),
|
||||
Self::VccArithmetic {
|
||||
primitive,
|
||||
left,
|
||||
right,
|
||||
mask,
|
||||
flag,
|
||||
} => {
|
||||
let (left, right) = (name(left), name(right));
|
||||
let bit = format!("(({} >> {lane}) & 1u)", name(mask));
|
||||
// Guide 12.7: widen the carry/borrow check before adding the input bit.
|
||||
match (primitive, flag) {
|
||||
(VectorVcc::Select, false) => format!("{bit} != 0u ? {right} : {left}"),
|
||||
(VectorVcc::AddCarry, false) => format!("{left} + {right} + {bit}"),
|
||||
(VectorVcc::AddCarry, true) => {
|
||||
format!("uint((ulong({left}) + ulong({right}) + {bit}) >> 32u)")
|
||||
}
|
||||
(VectorVcc::SubtractBorrow, false) => format!("{left} - {right} - {bit}"),
|
||||
(VectorVcc::SubtractBorrow, true) => {
|
||||
format!("uint(ulong({right}) + {bit} > ulong({left}))")
|
||||
}
|
||||
_ => unreachable!("not a VCC arithmetic operation"),
|
||||
}
|
||||
}
|
||||
Self::Store(_)
|
||||
| Self::ScalarBranch { .. }
|
||||
| Self::CarryMask { .. }
|
||||
| Self::LaneMask { .. }
|
||||
| Self::RuntimeBranch { .. } => unreachable!("not a per-thread expression"),
|
||||
}
|
||||
@@ -225,7 +266,17 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
|
||||
CompareRelation::False => return "false".to_owned(),
|
||||
CompareRelation::True => return "true".to_owned(),
|
||||
};
|
||||
if op.signed() && op.semantics().width == 64 {
|
||||
if op.semantics().width == 16 {
|
||||
// Guide §§6.2, 6.2.5 and 6.8: the e32 form reads the low half.
|
||||
let half = |value| {
|
||||
if op.signed() {
|
||||
format!("as_type<short>(ushort({value}))")
|
||||
} else {
|
||||
format!("ushort({value})")
|
||||
}
|
||||
};
|
||||
format!("{} {symbol} {}", half(left), half(right))
|
||||
} else if op.signed() && op.semantics().width == 64 {
|
||||
format!("as_type<long>({left}) {symbol} as_type<long>({right})")
|
||||
} else if op.signed() {
|
||||
format!("as_type<int>({left}) {symbol} as_type<int>({right})")
|
||||
@@ -429,7 +480,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
let mut ir = String::new();
|
||||
let has_mask = operations
|
||||
.iter()
|
||||
.any(|(_, operation)| matches!(operation, Op::LaneMask { .. }));
|
||||
.any(|(_, operation)| matches!(operation, Op::LaneMask { .. } | Op::CarryMask { .. }));
|
||||
let grid = if has_mask {
|
||||
",\n uint grid [[threads_per_grid]]"
|
||||
} else {
|
||||
@@ -451,8 +502,8 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
for (index, &(offset, operation)) in operations.iter().enumerate() {
|
||||
let dest = Value(index);
|
||||
uniform.push(match operation {
|
||||
Op::Constant(_) | Op::LaneMask { .. } => true,
|
||||
Op::Load | Op::MergeLanes { .. } => false,
|
||||
Op::Constant(_) | Op::LaneMask { .. } | Op::CarryMask { .. } => true,
|
||||
Op::Load | Op::MergeLanes { .. } | Op::VccArithmetic { .. } => false,
|
||||
_ => operation.operands().iter().all(|value| uniform[value.0]),
|
||||
});
|
||||
let thread = |value: Value| value.to_string();
|
||||
@@ -515,6 +566,38 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
format!("{dest} = join.vccz {mask}, {fallthrough}, {taken}"),
|
||||
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
|
||||
),
|
||||
Op::VccArithmetic {
|
||||
primitive,
|
||||
left,
|
||||
right,
|
||||
mask,
|
||||
flag,
|
||||
} => (
|
||||
format!(
|
||||
"{dest} = vcc.{primitive:?}{suffix} {left}, {right}, {mask}",
|
||||
suffix = if flag { ".flag" } else { "" }
|
||||
),
|
||||
format!(
|
||||
"uint {dest} = {};",
|
||||
operation.expression(&thread, "", "(index & 31u)")
|
||||
),
|
||||
),
|
||||
Op::CarryMask { flag, exec } => {
|
||||
let _ = writeln!(
|
||||
ir,
|
||||
"{offset:04x}: {dest} = wave.carry {flag} exec=0x{exec:08x}"
|
||||
);
|
||||
emit_lane_mask(
|
||||
&mut msl,
|
||||
&operations,
|
||||
&uniform,
|
||||
index,
|
||||
exec,
|
||||
vec![flag],
|
||||
|name| name(flag),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Op::LaneMask {
|
||||
op,
|
||||
src0,
|
||||
@@ -532,7 +615,33 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
"{offset:04x}: {dest} = wave.mask {} {left}, {right} exec=0x{exec:08x}",
|
||||
op.assembly_name()
|
||||
);
|
||||
emit_lane_mask(&mut msl, &operations, &uniform, index, operation);
|
||||
let inputs = if matches!(
|
||||
op.relation(),
|
||||
xenora_decoder::CompareRelation::False | xenora_decoder::CompareRelation::True
|
||||
) {
|
||||
Vec::new()
|
||||
} else {
|
||||
operation.operands()
|
||||
};
|
||||
emit_lane_mask(
|
||||
&mut msl,
|
||||
&operations,
|
||||
&uniform,
|
||||
index,
|
||||
exec,
|
||||
inputs,
|
||||
|name| {
|
||||
let (left, right) = if let Some((hi0, hi1)) = high {
|
||||
let pair = |lo, hi| {
|
||||
format!("((ulong({}) << 32u) | ulong({}))", name(hi), name(lo))
|
||||
};
|
||||
(pair(src0, hi0), pair(src1, hi1))
|
||||
} else {
|
||||
(name(src0), name(src1))
|
||||
};
|
||||
format!("({}) ? 1u : 0u", compare_expression(op, &left, &right))
|
||||
},
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Op::Store(value) => (
|
||||
@@ -552,7 +661,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
})
|
||||
}
|
||||
|
||||
/// Emit a Wave32 compare mask without any cross-thread operation: the thread
|
||||
/// Emit a Wave32 predicate mask without any cross-thread operation: the thread
|
||||
/// recomputes the lane-dependent operands of each lane of its own RDNA wave
|
||||
/// (dispatch indices `(index & ~31) + n`) from those lanes' input words.
|
||||
/// Absent lanes of a final partial wave contribute 0.
|
||||
@@ -561,28 +670,11 @@ fn emit_lane_mask(
|
||||
operations: &[(usize, Op)],
|
||||
uniform: &[bool],
|
||||
index: usize,
|
||||
operation: Op,
|
||||
exec: u32,
|
||||
mut pending: Vec<Value>,
|
||||
predicate: impl FnOnce(&dyn Fn(Value) -> String) -> String,
|
||||
) {
|
||||
let Op::LaneMask {
|
||||
op,
|
||||
src0,
|
||||
src1,
|
||||
high,
|
||||
exec,
|
||||
} = operation
|
||||
else {
|
||||
unreachable!("expected a lane mask")
|
||||
};
|
||||
let mut cone = vec![false; index];
|
||||
// F and T do not depend on the operands, so their lanes compute none.
|
||||
let mut pending = if matches!(
|
||||
op.relation(),
|
||||
xenora_decoder::CompareRelation::False | xenora_decoder::CompareRelation::True
|
||||
) {
|
||||
Vec::new()
|
||||
} else {
|
||||
operation.operands()
|
||||
};
|
||||
while let Some(value) = pending.pop() {
|
||||
if uniform[value.0] || cone[value.0] {
|
||||
continue;
|
||||
@@ -612,16 +704,10 @@ fn emit_lane_mask(
|
||||
);
|
||||
}
|
||||
}
|
||||
let (left, right) = if let Some((hi0, hi1)) = high {
|
||||
let pair = |lo, hi| format!("((ulong({}) << 32u) | ulong({}))", name(hi), name(lo));
|
||||
(pair(src0, hi0), pair(src1, hi1))
|
||||
} else {
|
||||
(name(src0), name(src1))
|
||||
};
|
||||
let _ = writeln!(
|
||||
msl,
|
||||
" uint pass = ({}) ? 1u : 0u;\n {dest} |= ((0x{exec:08x}u >> lane) & pass) << lane;\n }}",
|
||||
compare_expression(op, &left, &right)
|
||||
" uint pass = {};\n {dest} |= ((0x{exec:08x}u >> lane) & pass) << lane;\n }}",
|
||||
predicate(&name)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -656,18 +742,18 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
// contract, even when a known branch skips it.
|
||||
for (index, instruction) in decoded.iter().enumerate() {
|
||||
let offset = instruction.offset;
|
||||
if let Some(target) = instruction.branch_target()
|
||||
&& (target <= offset
|
||||
|| decoded
|
||||
.binary_search_by_key(&target, |instruction| instruction.offset)
|
||||
.is_err())
|
||||
{
|
||||
return Err(CompileError::Verify {
|
||||
offset,
|
||||
reason: "branch target must be a forward instruction boundary",
|
||||
});
|
||||
}
|
||||
let reason = match instruction.instruction {
|
||||
Instruction::Branch { target }
|
||||
| Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target }
|
||||
if target <= offset
|
||||
|| decoded
|
||||
.binary_search_by_key(&target, |instruction| instruction.offset)
|
||||
.is_err() =>
|
||||
{
|
||||
"branch target must be a forward instruction boundary"
|
||||
}
|
||||
Instruction::BufferLoadDword {
|
||||
index, resource, ..
|
||||
} if (index, resource) != (0, 0) => "unsupported resource or buffer index",
|
||||
@@ -807,6 +893,13 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
// Scalar instructions and waits still execute when all lanes are inactive.
|
||||
if exec == 0 {
|
||||
match instruction.instruction {
|
||||
Instruction::VectorAlu { op, .. } if op.writes_vcc() => {
|
||||
// Guide 3.9: inactive lanes contribute zero to carry-out.
|
||||
lane_vcc = None;
|
||||
scalars[VCC_LO] = Some(0);
|
||||
scalars[VCC_HI] = None;
|
||||
continue;
|
||||
}
|
||||
Instruction::MoveB32 { .. }
|
||||
| Instruction::VectorAluVop3 { .. }
|
||||
| Instruction::VectorAddF32 { .. }
|
||||
@@ -846,12 +939,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
store_pending = true;
|
||||
(None, Op::Store(read(data)?))
|
||||
}
|
||||
Instruction::WaitLoad => {
|
||||
if let Some((register, value)) = pending_load.take() {
|
||||
registers[register] = Some(value);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::WaitStore => {
|
||||
store_pending = false;
|
||||
continue;
|
||||
@@ -923,10 +1010,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
} else {
|
||||
(read(src0)?, read(src1)?)
|
||||
};
|
||||
(
|
||||
Some(dst),
|
||||
Op::Binary(Binary::Vector(op.lowering()), left, right),
|
||||
)
|
||||
let VectorLowering::Binary(binary) = op.lowering() else {
|
||||
return Err(error("VOP3 with a lane condition is unsupported"));
|
||||
};
|
||||
(Some(dst), Op::Binary(Binary::Vector(binary), left, right))
|
||||
}
|
||||
Instruction::ScalarUnary {
|
||||
op: op @ ScalarUnaryOp::MovB32,
|
||||
@@ -1091,43 +1178,66 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
lane_vcc = Some(mask);
|
||||
continue;
|
||||
}
|
||||
Instruction::BranchVccZero { target } if let Some(mask) = lane_vcc => {
|
||||
if pending_load.is_some() {
|
||||
return Err(error(
|
||||
"a runtime s_cbranch_vccz requires no outstanding vector load",
|
||||
));
|
||||
}
|
||||
region = Some((target, mask, registers));
|
||||
(None, Op::RuntimeBranch { mask, target })
|
||||
}
|
||||
Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target } => {
|
||||
let taken = match instruction.instruction {
|
||||
Instruction::BranchSccZero { .. } => {
|
||||
!scc.ok_or_else(|| error("conditional branch reads uninitialized SCC"))?
|
||||
Instruction::Branch { .. }
|
||||
| Instruction::BranchSccZero { .. }
|
||||
| Instruction::BranchExecZero { .. }
|
||||
| Instruction::BranchVccZero { .. }
|
||||
| Instruction::WaitLoad
|
||||
| Instruction::EndProgram => {
|
||||
match instruction
|
||||
.instruction
|
||||
.sopp_control()
|
||||
.expect("decoded SOPP control")
|
||||
{
|
||||
SoppControlOp::WaitLoad => {
|
||||
if let Some((register, value)) = pending_load.take() {
|
||||
registers[register] = Some(value);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::BranchVccZero { .. } => {
|
||||
scalars[106]
|
||||
.ok_or_else(|| error("conditional branch reads uninitialized VCC_LO"))?
|
||||
== 0
|
||||
SoppControlOp::EndProgram => {
|
||||
if !stored || store_pending || pending_load.is_some() {
|
||||
return Err(error(
|
||||
"termination requires one completed store and no pending loads",
|
||||
));
|
||||
}
|
||||
return Ok(operations);
|
||||
}
|
||||
op => {
|
||||
let target = instruction.branch_target().expect("decoded SOPP branch");
|
||||
if op == SoppControlOp::BranchVccZero
|
||||
&& let Some(mask) = lane_vcc
|
||||
{
|
||||
if pending_load.is_some() {
|
||||
return Err(error(
|
||||
"a runtime s_cbranch_vccz requires no outstanding vector load",
|
||||
));
|
||||
}
|
||||
region = Some((target, mask, registers));
|
||||
(None, Op::RuntimeBranch { mask, target })
|
||||
} else {
|
||||
let taken = match op {
|
||||
SoppControlOp::Branch => true,
|
||||
SoppControlOp::BranchSccZero => !scc.ok_or_else(|| {
|
||||
error("conditional branch reads uninitialized SCC")
|
||||
})?,
|
||||
SoppControlOp::BranchVccZero => {
|
||||
scalars[106].ok_or_else(|| {
|
||||
error("conditional branch reads uninitialized VCC_LO")
|
||||
})? == 0
|
||||
}
|
||||
SoppControlOp::BranchExecZero => exec == 0,
|
||||
SoppControlOp::WaitLoad | SoppControlOp::EndProgram => {
|
||||
unreachable!()
|
||||
}
|
||||
};
|
||||
if taken {
|
||||
skip_before = target;
|
||||
}
|
||||
(None, Op::ScalarBranch { target, taken })
|
||||
}
|
||||
}
|
||||
_ => exec == 0,
|
||||
};
|
||||
if taken {
|
||||
skip_before = target;
|
||||
}
|
||||
(None, Op::ScalarBranch { target, taken })
|
||||
}
|
||||
Instruction::Branch { target } => {
|
||||
skip_before = target;
|
||||
(
|
||||
None,
|
||||
Op::ScalarBranch {
|
||||
target,
|
||||
taken: true,
|
||||
},
|
||||
)
|
||||
}
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
@@ -1142,10 +1252,51 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
} else {
|
||||
(src0, src1)
|
||||
};
|
||||
(
|
||||
Some(dst),
|
||||
Op::Binary(Binary::Vector(op.lowering()), left, right),
|
||||
)
|
||||
match op.lowering() {
|
||||
VectorLowering::Binary(binary) => {
|
||||
(Some(dst), Op::Binary(Binary::Vector(binary), left, right))
|
||||
}
|
||||
VectorLowering::Vcc(primitive) => {
|
||||
let mask = match (lane_vcc, scalars[VCC_LO]) {
|
||||
(Some(mask), _) => mask,
|
||||
(None, Some(bits)) => {
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
(None, None) => {
|
||||
return Err(error("vector ALU reads uninitialized VCC_LO"));
|
||||
}
|
||||
};
|
||||
if op.writes_vcc() {
|
||||
let flag = Value(operations.len());
|
||||
operations.push((
|
||||
offset,
|
||||
Op::VccArithmetic {
|
||||
primitive,
|
||||
left,
|
||||
right,
|
||||
mask,
|
||||
flag: true,
|
||||
},
|
||||
));
|
||||
facts.push(KnownBits::UNKNOWN);
|
||||
lane_vcc = Some(Value(operations.len()));
|
||||
operations.push((offset, Op::CarryMask { flag, exec }));
|
||||
facts.push(KnownBits::UNKNOWN);
|
||||
scalars[VCC_LO] = None;
|
||||
scalars[VCC_HI] = None;
|
||||
}
|
||||
(
|
||||
Some(dst),
|
||||
Op::VccArithmetic {
|
||||
primitive,
|
||||
left,
|
||||
right,
|
||||
mask,
|
||||
flag: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Instruction::VectorUnary { op, dst, src } => {
|
||||
let source = read_vector(src, &mut operations, &mut facts)?;
|
||||
@@ -1191,14 +1342,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
"graphics instruction is unsupported in a compute fixture",
|
||||
));
|
||||
}
|
||||
Instruction::EndProgram => {
|
||||
if !stored || store_pending || pending_load.is_some() {
|
||||
return Err(error(
|
||||
"termination requires one completed store and no pending loads",
|
||||
));
|
||||
}
|
||||
return Ok(operations);
|
||||
}
|
||||
};
|
||||
let value_bits = match operation {
|
||||
Op::Constant(bits) => KnownBits::constant(bits),
|
||||
|
||||
@@ -392,6 +392,20 @@ fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_vcc_fixture_matches_ir_and_msl_goldens() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-vcc.bin");
|
||||
let result = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
result.ir,
|
||||
include_str!("../../../fixtures/golden/vector-vcc.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
result.msl,
|
||||
include_str!("../../../fixtures/golden/vector-vcc.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop1_integer_fixture_lowers_unary_and_masked_swap() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-unary.bin");
|
||||
|
||||
@@ -26,6 +26,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
|
||||
- [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule.
|
||||
- [VOP1 vector unary and swap](shaders/vector-unary.md) — Wave32 integer bit operations, register exchange, and operand limits.
|
||||
- [VOP2 select and carry](shaders/vector-vcc.md) — Wave32 lane selection, carry and borrow through the vector condition code.
|
||||
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
|
||||
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
|
||||
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
|
||||
<title id="title">Xenora · recorded progress</title>
|
||||
<desc id="description">Decoded gfx1030 forms: 142 of 142. Accepted Metal forms · Apple M5: 18 of 142. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<desc id="description">Decoded gfx1030 forms: 158 of 158. Accepted Metal forms · Apple M5: 18 of 158. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
|
||||
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
|
||||
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
|
||||
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">142 / 142</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">158 / 158</text>
|
||||
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 142</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 158</text>
|
||||
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="103" width="62.11" height="4" rx="2" fill="#88c6bd"/>
|
||||
<rect x="20" y="103" width="55.82" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
|
||||
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
|
||||
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -59,6 +59,18 @@ These rules hold for both engines and are what a guest scheduler has to preserve
|
||||
|
||||
The SDM cases for these forms in `tests/cpu_known_answers.rs` were written before this implementation, by another contributor. `tests/x86_atomic.rs` adds the LOCK rules, both compare outcomes at every width, unaligned operands and faults. None of it has been compared with x86 hardware, and nothing here establishes multi-thread behaviour.
|
||||
|
||||
## String instructions
|
||||
|
||||
MOVS and STOS exist for 8-, 16-, 32- and 64-bit elements, alone and with REP (F3), together with the direction flag and CLD and STD. `CpuState::df` holds the flag. It is not one of the six status flags the registry tracks.
|
||||
|
||||
- **One element per step.** A REP form moves one element, decrements RCX and, while RCX is not zero, leaves RIP on the instruction. Each element is a step of its own in both engines and counts against the step budget, so a repeat cannot outrun the budget and can stop part-way and resume. A zero count touches no memory and no register. Without REP, RCX is not read. Step counts therefore count elements, not instructions, for a REP form.
|
||||
- **Direction.** RSI and RDI move up by the element size when the flag is clear and down when it is set. Each element is read whole and then written, so overlapping ranges behave as that order dictates.
|
||||
- **Faults.** An element completes or changes nothing. A fault keeps the elements already done, leaves RSI, RDI and RCX at the element that faulted, and leaves RIP on the instruction.
|
||||
- **Segments.** An FS or GS override applies to the MOVS source. The destination, and STOS as a whole, take no override.
|
||||
- **Lowering.** The DBT runs these forms on the shared semantics, one helper call per element, and a string instruction ends its translated block. There is no bulk-copy path, so large copies are slow.
|
||||
|
||||
The SDM cases for these forms in `tests/cpu_known_answers.rs` were written before this implementation, by another contributor. `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count, the step accounting, faults and the segment rule. None of it has been compared with x86 hardware.
|
||||
|
||||
## Guest CPUID
|
||||
|
||||
CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a synthetic processor: the vendor string is `Xenora guest`, not Intel's or AMD's, and leaf 1 reports no family, model or stepping.
|
||||
@@ -83,4 +95,4 @@ A feature bit is set only when every instruction of that feature is implemented.
|
||||
|
||||
## Rejected on purpose
|
||||
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
|
||||
@@ -14,12 +14,12 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| Form | Operands | Size or word | Recognized | Decoded | LLVM | Lowering | Reference | CPU | GPU |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `buffer_load_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL load | implemented | fixture verified | fixture verified |
|
||||
| `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified |
|
||||
| `s_waitcnt vmcnt(0)` | SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values (semantic registry) | 4 B | yes | yes | three-way passed | verified load wait | implemented | fixture verified | fixture verified |
|
||||
| `v_mov_b32_e32` | VOP1, VGPR destination, VGPR, normal SGPR (wave-uniform, known during translation), vcc_lo (known or a compare mask) or inline integer or literal source, plus the inline bit pattern for +1.0f | 4 or 8 B | yes | yes | three-way passed | constant or register value | implemented | fixture verified | fixture verified |
|
||||
| `v_add_nc_u32_e64` | VOP3, VGPR destination and two VGPR inputs, modifier fields clear, third source field encoded as inline zero | 8 B | yes | yes | three-way passed | MSL unsigned add | implemented | fixture verified | fixture verified |
|
||||
| `buffer_store_dword` | MUBUF, VGPR data/index, four normal SGPRs, `idxen`, zero offsets and remaining flags | 8 B | yes | yes | three-way passed | MSL store | implemented | fixture verified | fixture verified |
|
||||
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
|
||||
| `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
|
||||
| `s_endpgm` | SOPP, zero immediate (semantic registry) | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
|
||||
| `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified |
|
||||
| `s_not_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0 | `BE890708` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_brev_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged | `BE8A0B08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -109,6 +109,18 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_cmp_t_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D0E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_f_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written | `7D800501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_t_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D8E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 < S1), fully written | `7D120702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 == S1), fully written | `7D140702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 <= S1), fully written | `7D160702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 > S1), fully written | `7D180702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 != S1), fully written | `7D1A0702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_i16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 >= S1), fully written | `7D1C0702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 < S1), fully written | `7D520702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 == S1), fully written | `7D540702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 <= S1), fully written | `7D560702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_gt_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 > S1), fully written | `7D580702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 != S1), fully written | `7D5A0702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_u16_e32` | VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 >= S1), fully written | `7D5C0702` | yes | yes | three-way passed | per-thread Wave32 mask with low-half operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_f_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (false), fully written | `7D400902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 < S1), fully written | `7D420902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_i64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 == S1), fully written | `7D440902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -125,8 +137,8 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_cmp_ne_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 != S1), fully written | `7DCA0902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (S0 >= S1), fully written | `7DCC0902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_t_u64_e32` | VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; unsigned 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (true), fully written | `7DCE0902` | yes | yes | assembled fixture matched | per-thread Wave32 mask with 64-bit operands | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_scc0` | Nonnegative signed dword displacement | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified |
|
||||
| `s_branch` | Nonnegative signed dword displacement | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified |
|
||||
| `s_cbranch_scc0` | Nonnegative signed dword displacement (semantic registry) | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified |
|
||||
| `s_branch` | Nonnegative signed dword displacement (semantic registry) | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified |
|
||||
| `v_and_b32_e32` | Two VGPR sources and one VGPR destination | `36020702` | yes | yes | three-way passed | MSL bitwise AND | implemented | fixture verified | fixture verified |
|
||||
| `v_xor_b32_e32` | Two VGPR sources and one VGPR destination | `3A020702` | yes | yes | three-way passed | MSL bitwise XOR | implemented | fixture verified | fixture verified |
|
||||
| `v_add_f32_e32` | Two VGPR sources and one VGPR destination | `06020702` | yes | yes | three-way passed | MSL FP32 add | implemented | fixture verified | fixture verified |
|
||||
@@ -135,8 +147,8 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_lshlrev_b32_e32` | Two VGPR sources and one VGPR destination | `34020501` | yes | yes | three-way passed | MSL logical left shift with a five-bit count | implemented | fixture verified | fixture verified on Apple M5 |
|
||||
| `v_lshrrev_b32_e32` | Two VGPR sources and one VGPR destination | `2DFFFF01` | yes | yes | three-way passed | MSL logical right shift with a five-bit count | implemented | fixture verified | fixture verified on Apple M5 |
|
||||
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_execz` | Nonnegative signed dword displacement (semantic registry) | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_vccz` | Nonnegative signed dword displacement (semantic registry) | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_not_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement | `7E046F01` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_bfrev_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order | `7E067101` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_ffbh_u32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero | `7E087302` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -155,16 +167,20 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_add_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 + S1, no carry | `4A160F06` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_sub_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 - S1, no carry | `4C181308` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_subrev_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S1 - S0, no carry | `4E1A170A` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cndmask_b32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; select S1 when the VCC_LO lane bit is set, otherwise S0 | `020402C1` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_add_co_ci_u32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned addition with carry input and output | `50040481` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_sub_co_ci_u32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S0 minus S1 with borrow input and output | `52060480` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_subrev_co_ci_u32_e32` | VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S1 minus S0 with borrow input and output | `540606C2` | yes | yes | three-way passed | per-thread integer expression with EXEC masking | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
<!-- status:instructions:end -->
|
||||
|
||||
## Automated three-way comparison
|
||||
|
||||
LLVM 23.1.6, the production decoder and the independent reference decoder
|
||||
matched 650 instructions across ten streams: the eight synthetic fixtures,
|
||||
matched 1,088 instructions across 18 streams: 16 synthetic fixtures,
|
||||
a high-register sequence and an operand matrix assembled by LLVM.
|
||||
The harness checks byte offsets, widths, encoded bytes from LLVM, mnemonic
|
||||
and operands, and the typed reference operation against the production
|
||||
operation. It covers all 42 compute forms in this document.
|
||||
operation. It covers 124 instruction forms.
|
||||
|
||||
The matrix checks the 81 inline integer selectors in VOP1, SOP1, SOPC and
|
||||
SOP2, forced literals that could otherwise be inline, literal selection in
|
||||
@@ -174,7 +190,7 @@ operands, and zero and nonzero forward branch displacements. The decoder
|
||||
trace exposes MUBUF operands independently of the synthetic execution ABI,
|
||||
which still requires the original index and resource bindings.
|
||||
|
||||
Five malformed LLVM probes produced diagnostics, and 25 valid encodings
|
||||
Five malformed LLVM probes produced diagnostics, and 27 valid encodings
|
||||
or disassemblable branch sequences were deliberately rejected by both Xenora
|
||||
decoders. Both Xenora decoders also reject all 37 interior truncation offsets
|
||||
in the add fixture and every case in the unsupported-encoding list.
|
||||
|
||||
@@ -28,15 +28,15 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 0 | 0 | 12 |
|
||||
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
|
||||
| SOPK | 27 | 17 | 16 | 17 | 17 | 17 | 1 | 1 | 5 |
|
||||
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
|
||||
| SOPP | 36 | 6 | 6 | 6 | 6 | 6 | 4 | 4 | 0 |
|
||||
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP1 | 81 | 7 | 6 | 7 | 7 | 7 | 1 | 1 | 11 |
|
||||
| VOP2 | 47 | 20 | 18 | 20 | 20 | 20 | 7 | 7 | 11 |
|
||||
| VOP2 | 47 | 24 | 22 | 24 | 24 | 24 | 7 | 7 | 11 |
|
||||
| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 |
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 16 | 32 | 32 | 32 | 32 | 0 | 0 | 9 |
|
||||
| **Total** | 1465 | 126 | 130 | 146 | 142 | 142 | 18 | 18 | 78 |
|
||||
| VOPC | 190 | 28 | 44 | 44 | 44 | 44 | 0 | 0 | 9 |
|
||||
| **Total** | 1465 | 142 | 152 | 162 | 158 | 158 | 18 | 18 | 78 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
@@ -50,10 +50,15 @@ The table counts distinct variant names per family across registry operand rules
|
||||
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| SOPK | `sopk_compare` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
|
||||
| SOPK | `sopk_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
|
||||
| SOPP | `sopp_branch` | None listed |
|
||||
| SOPP | `sopp_end` | None listed |
|
||||
| SOPP | `sopp_wait` | None listed |
|
||||
| VOP1 | `vop1_swap` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| VOP1 | `vop1_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOP2 | `vop2_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOPC | `vopc_vcc_half` | `src_exec`, `src_float_inline`, `src_literal`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOPC | `vopc_vcc_pair` | `src_exec`, `src_float_inline`, `src_literal`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
@@ -111,16 +111,16 @@ error.
|
||||
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `mov` (SOP1 and SOPK), `cmov` (SOPK only), `compare` and the SOP1 unaries |
|
||||
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
|
||||
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
|
||||
| `width` | Operand and result width in bits (operand width for compares) | `32`, or `64` with `vopc_vcc_pair` |
|
||||
| `carry_in` | Implicit carry, borrow or select input | `none`, `scc` for unsigned scalar `add` and `sub` and required for scalar `cselect`, `vcc` for the Wave32 VOP2 select and carry forms |
|
||||
| `width` | Operand and result width in bits (operand width for compares) | `32`, `16` with `vopc_vcc_half`, or `64` with `vopc_vcc_pair` |
|
||||
| `source_bits` | Sign extension only: the low bits of S0 that are read. The XML must list S0 with that size and format (`FMT_NUM_I8` or `FMT_NUM_I16`) | `8`, `16`; required for `sext`, rejected elsewhere |
|
||||
| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere |
|
||||
| `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` |
|
||||
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
|
||||
| `shift_count_bits` | Shifts only: the low bits of the count source used as the count: S1, or S0 for a vector form with `source_order = "reversed"`. Scalar forms mask it in the generated evaluation, vector forms in their MSL template; the XML must list the count source as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC and SOPK compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
|
||||
| `vcc`, `exec` | Implicit effect on VCC and EXEC | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (explicit destinations are covered by the operand rule) |
|
||||
| `wave` | Wave sizes the form is valid in | `wave32` for VOPC compares and VOP1 integer forms in the Wave32 compute fixture ABI, `any` for other registry forms |
|
||||
| `vcc`, `exec` | Implicit effect on VCC and EXEC | `vcc` is `lane_mask` for [VOPC compares](vector-compare.md) and the three [VOP2 carry forms](vector-vcc.md). These write all of VCC_LO, zero inactive lane bits and leave VCC_HI unknown. Other forms declare `vcc` as `unchanged`. All forms declare `exec` as `unchanged`. Operand rules cover explicit destinations. |
|
||||
| `wave` | Wave sizes the form is valid in | `wave32` for SOPP controls, VOPC compares, VOP1 integer forms and VCC-reading VOP2 forms in the Wave32 compute fixture ABI, `any` for other registry forms |
|
||||
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
|
||||
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
|
||||
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
|
||||
@@ -162,11 +162,11 @@ and one literal dword. The move copies the source and leaves SCC unchanged.
|
||||
The destination vocabulary preserves the original decoder subset of the
|
||||
RDNA 2 guide sections 5.3 and 12.3.
|
||||
|
||||
Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
|
||||
Binary vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
|
||||
generate the one `VectorAluOp` enum, whose `operand_rule()` tells the decoder
|
||||
which rule a form uses) use a separate table:
|
||||
the pair picks the per-lane `VectorBinary` the MSL lowering uses, and `scc`
|
||||
must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
|
||||
must be `unchanged` (these binary forms write no SCC, VCC or EXEC):
|
||||
|
||||
| `operation` / `signedness` | `VectorBinary` |
|
||||
| --- | --- |
|
||||
@@ -177,6 +177,12 @@ must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
|
||||
| `and`, `or`, `xor` / `bitwise` | `And`, `Or`, `Xor` |
|
||||
| `lshl`, `lshr` / `bitwise`, `ashr` / `signed` (with `shift_count_bits = 5`) | `ShiftLeft`, `ShiftRight`, `ArithmeticShiftRight` |
|
||||
|
||||
The [Wave32 VOP2 select and carry forms](vector-vcc.md) use `vop2_vcc` with
|
||||
the general SRC0 domain and an implicit VCC input. The generator checks the
|
||||
direction of each fieldless VCC operand in the pinned XML. The three arithmetic
|
||||
forms also declare a lane-mask output and use the same reverse-source mechanism
|
||||
as the no-carry subtraction.
|
||||
|
||||
`vop2_vgpr2` is the VGPR-only subset (SRC0 256-511) that the hand-written decoder
|
||||
accepted for `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`
|
||||
and `v_ashrrev_i32` before they moved into the registry (#215 M27); widening them
|
||||
@@ -185,9 +191,11 @@ shifts declare `source_order = "reversed"` (D = S1 shifted by S0[4:0]), so the
|
||||
generator checks the XML's unsigned count format on SRC0, not VSRC1.
|
||||
|
||||
VOPC compares (kind `vector_compare`) write `vcc_lo`. The 32-bit rule
|
||||
`vopc_vcc` accepts a `vector_source` as for VOP2 and a VGPR. The 64-bit rule
|
||||
`vopc_vcc` accepts a `vector_source` as for VOP2 and a VGPR. The 16-bit rule
|
||||
`vopc_vcc_half` reads the low half of the same source types and rejects
|
||||
literals (guide sections 6.2, 6.2.5 and 6.8). The 64-bit rule
|
||||
`vopc_vcc_pair` accepts a VGPR pair, an even normal SGPR pair or an inline
|
||||
integer as SRC0 and a VGPR pair as VSRC1. Both declare a `relation`,
|
||||
integer as SRC0 and a VGPR pair as VSRC1. All three declare a `relation`,
|
||||
`scc = "unchanged"`, `vcc = "lane_mask"` and `wave = "wave32"`. The XML's implicit
|
||||
64-bit VCC output must be present and is accounted for by `lane_mask`. Signedness
|
||||
still matters for `eq` and `lg`, because the MSL lowering casts signed operands.
|
||||
@@ -211,6 +219,17 @@ The XML must give SIMM16 as 16-bit `FMT_NUM_I16` (`FMT_NUM_U16` for `unsigned`).
|
||||
The word never takes a literal dword. The details are in
|
||||
[scalar-immediate.md](scalar-immediate.md).
|
||||
|
||||
The SOPP control rules (AMD RDNA 2 ISA guide §§12.5 and 13.1.5) generate
|
||||
`SoppControlOp` for the existing Wave32 compute subset. `sopp_end` accepts
|
||||
`s_endpgm` with zero in SIMM16. `sopp_wait` accepts only `s_waitcnt vmcnt(0)`
|
||||
(`0x3f70`), completing a pending vector load. `sopp_branch` accepts
|
||||
`s_branch`, `s_cbranch_scc0`, `s_cbranch_vccz` and `s_cbranch_execz` with a
|
||||
nonnegative signed SIMM16 displacement in dwords from the next instruction.
|
||||
The decoder and compiler require a valid target boundary. The conditional
|
||||
branches read SCC, VCC_LO or EXEC_LO without writing those registers.
|
||||
Other SOPP forms, including `s_nop`, the nonzero branches, `s_sendmsg`,
|
||||
`s_trap`, `s_sethalt` and `s_setprio`, remain unsupported.
|
||||
|
||||
Behaviour is chosen only from these declared fields, never from the mnemonic.
|
||||
|
||||
## What the validator checks
|
||||
@@ -221,7 +240,8 @@ vocabularies above, it rejects:
|
||||
- contradictions: a declared `scc` or `carry_in` that the primitive does not
|
||||
have, `bitwise` on an arithmetic operation or the reverse;
|
||||
- VOPC compares whose opcode is not the group base (128 and 192 for signed and
|
||||
unsigned 32-bit forms, 160 and 224 for their 64-bit counterparts) plus the relation's offset in guide Table 59 (F 0, LT 1,
|
||||
unsigned 32-bit forms, 136 and 168 for 16-bit forms, 160 and 224 for 64-bit
|
||||
forms) plus the relation's offset in guide Table 59 (F 0, LT 1,
|
||||
EQ 2, LE 3, GT 4, LG/NE 5, GE 6, T 7), and a `lane_mask` form whose XML
|
||||
does not have exactly one implicit VCC operand that is written and not read;
|
||||
- duplicates: the same `name`, the same `(family, opcode)`, or the same
|
||||
|
||||
@@ -77,16 +77,16 @@ using this ABI; there is no Wave64 entry point to reject.
|
||||
|
||||
### 2a. 16-bit and 64-bit compares
|
||||
|
||||
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
|
||||
translator support the 64-bit forms through the `vopc_vcc_pair` operand rule.
|
||||
The 16-bit forms are available only in the interpreters.
|
||||
The decoder, translator and both reference interpreters 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 registry
|
||||
uses `vopc_vcc_half` for the 16-bit forms and `vopc_vcc_pair` for the 64-bit
|
||||
forms.
|
||||
|
||||
- 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.
|
||||
SRC0 accepts a VGPR, a known SGPR, `vcc_lo` or an inline integer
|
||||
(for example, −1 supplies `0xffff`). VSRC1 is a VGPR. Literals are rejected.
|
||||
- 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
|
||||
@@ -254,13 +254,14 @@ run in `vopc_f_t_match_the_guide_on_native_metal`.
|
||||
|
||||
The 16-bit and 64-bit oracle (`tests/validation/tests/vopc_wide.rs`) checks
|
||||
6,212 cases on both reference interpreters, plus 1,208 rejections and 13
|
||||
neighbouring opcodes. CPU tests check compilation of the 4,640 64-bit cases
|
||||
and rejection of out-of-contract 64-bit operands and all 12 16-bit forms.
|
||||
The LLVM-assembled `fixtures/rdna2/vector-compare-64.s` covers all sixteen
|
||||
64-bit opcodes in the decoder's fixture inventory.
|
||||
`scripts/test-gpu.sh` includes `vopc64_match_the_guide_on_native_metal` and
|
||||
skips `vopc16_match_the_guide_on_native_metal`. On a local Apple M5 under API and
|
||||
shader validation, all 4,640 64-bit cases (3,818 programs) agree; acceptance is pending. Deliberately broken copies of both
|
||||
neighbouring opcodes. CPU tests check compilation of 1,572 16-bit and 4,640
|
||||
64-bit cases, plus compiler rejection of out-of-contract programs. LLVM
|
||||
assembled `vector-compare-16.s` and `vector-compare-64.s` cover all 28 opcodes
|
||||
in the decoder's fixture inventory. The native Metal gate runs both
|
||||
`vopc16_match_the_guide_on_native_metal` and
|
||||
`vopc64_match_the_guide_on_native_metal`. On a local Apple M5 with API and
|
||||
shader validation, all 4,640 64-bit cases (3,818 programs) agree with the
|
||||
oracle. On a local Apple M5 under API and shader validation, all 1,572 16-bit cases (1,420 programs) agree; independent acceptance is pending. 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.
|
||||
@@ -274,13 +275,12 @@ swapped signedness, without the EXEC mask, without the absent-lane bound
|
||||
(shader validation aborts on the out-of-range read) or with an inverted join.
|
||||
|
||||
The 32-bit readback evidence is local agreement with a specification-derived
|
||||
reference on Apple M5 Pro. The 64-bit compiler evidence is CPU-only.
|
||||
reference on Apple M5 Pro. The 16-bit compiler evidence is CPU-only.
|
||||
There is no RDNA 2 or Xbox hardware evidence.
|
||||
|
||||
## 10. Limitations
|
||||
|
||||
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP or float compares. The 16-bit
|
||||
compares are available only in the reference interpreters (2a).
|
||||
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP or float compares.
|
||||
- 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
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Wave32 vector select, carry and borrow
|
||||
|
||||
The gfx1030 compute fixture ABI supports four 32-bit vector two-operand
|
||||
instruction (VOP2) forms that read the vector condition code (VCC).
|
||||
In Wave32, bit `n` of `VCC_LO` supplies lane `n`'s input `c`.
|
||||
The AMD RDNA 2 guide describes the operations in section 12.7, the VOP2 word
|
||||
in section 13.3.1, and the execution and condition masks in sections 3.3 and 3.9.
|
||||
|
||||
| Instruction | Active lane destination | Active lane VCC output |
|
||||
| --- | --- | --- |
|
||||
| `v_cndmask_b32_e32` | S1 if c is set, S0 otherwise | Preserved |
|
||||
| `v_add_co_ci_u32_e32` | Low 32 bits of S0 + S1 + c | Exact sum reaches 2³² |
|
||||
| `v_sub_co_ci_u32_e32` | Low 32 bits of S0 − S1 − c | S1 + c exceeds S0 |
|
||||
| `v_subrev_co_ci_u32_e32` | Low 32 bits of S1 − S0 − c | S0 + c exceeds S1 |
|
||||
|
||||
Section 12.7 prints a reverse-subtract flag expression that conflicts with its
|
||||
prose and destination equation. Xenora uses unsigned borrow from the stated
|
||||
reverse subtraction, consistent with section 12.12's `v_subrev_co_u32` when
|
||||
the incoming borrow is zero.
|
||||
|
||||
Inactive lanes retain the old vector destination (VDST). Section 3.9
|
||||
describes a fully written VCC mask and defines carry-out in terms of executing
|
||||
lanes. Under that reading, inactive lanes contribute zero to a carry or borrow
|
||||
output. Section 3.3 says scalar-register-writing vector ALU instructions
|
||||
still execute under empty EXEC, so the carry output is a zero mask.
|
||||
The synthetic ABI also zeros
|
||||
absent lanes in a final short wave when it constructs a new mask.
|
||||
The scalar condition code (SCC) and EXEC are preserved by these forms.
|
||||
|
||||
The general SRC0 subset includes vector general-purpose registers (VGPRs),
|
||||
scalar registers s0–s105, `vcc_lo`, inline integers and one literal word.
|
||||
VSRC1 and VDST are VGPRs. Translated scalar sources must be known or supplied
|
||||
by a translated VCC result. The pinned XML lists the VCC input on all four
|
||||
forms and an additional VCC output on the three arithmetic forms. VOP3
|
||||
encodings with explicit scalar conditions and VOP3B carry-out-only forms
|
||||
are outside this subset.
|
||||
|
||||
The Metal lowering reuses the compare mask's replay of the current wave's
|
||||
input lanes to form carry and borrow masks. The original `vector-vcc.s`
|
||||
fixture chains all four operations. LLVM checks encoding, and the guide-derived
|
||||
oracle checks both CPU interpreters. `vop2_vcc_matches_guide_on_native_metal` passes on a local
|
||||
Apple M5 under API and shader validation; independent acceptance is pending. The expectations are derived from the public AMD specification (class B).
|
||||
+198
-6
@@ -53,7 +53,7 @@ llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_waitcnt vmcnt(0)"
|
||||
encoding = "SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values"
|
||||
encoding = "SOPP, exact immediate `0x3f70`; other counters disabled by their maximum values (semantic registry)"
|
||||
representation = "4 B"
|
||||
lowering = "verified load wait"
|
||||
reference = "implemented"
|
||||
@@ -113,7 +113,7 @@ llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_endpgm"
|
||||
encoding = "SOPP, zero immediate"
|
||||
encoding = "SOPP, zero immediate (semantic registry)"
|
||||
representation = "4 B"
|
||||
lowering = "verified termination"
|
||||
reference = "implemented"
|
||||
@@ -1190,6 +1190,150 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_lt_i16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 < S1), fully written"
|
||||
representation = "`7D120702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_eq_i16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 == S1), fully written"
|
||||
representation = "`7D140702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_le_i16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 <= S1), fully written"
|
||||
representation = "`7D160702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_gt_i16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 > S1), fully written"
|
||||
representation = "`7D180702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_ne_i16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 != S1), fully written"
|
||||
representation = "`7D1A0702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_ge_i16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; signed low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 >= S1), fully written"
|
||||
representation = "`7D1C0702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_lt_u16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 < S1), fully written"
|
||||
representation = "`7D520702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_eq_u16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 == S1), fully written"
|
||||
representation = "`7D540702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_le_u16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 <= S1), fully written"
|
||||
representation = "`7D560702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_gt_u16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 > S1), fully written"
|
||||
representation = "`7D580702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_ne_u16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 != S1), fully written"
|
||||
representation = "`7D5A0702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_ge_u16_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, known SGPR, VCC_LO or inline integer SRC0; VGPR VSRC1; unsigned low 16 bits; VCC_LO[n] = EXEC_LO[n] & (S0 >= S1), fully written"
|
||||
representation = "`7D5C0702`"
|
||||
lowering = "per-thread Wave32 mask with low-half operands"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_f_i64_e32"
|
||||
encoding = "VOPC, Wave32; VGPR pair, known even SGPR pair or sign-extended inline integer SRC0; VGPR pair VSRC1; signed 64-bit operands; VCC_LO[n] = EXEC_LO[n] & (false), fully written"
|
||||
@@ -1384,7 +1528,7 @@ llvm = "assembled fixture matched"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cbranch_scc0"
|
||||
encoding = "Nonnegative signed dword displacement"
|
||||
encoding = "Nonnegative signed dword displacement (semantic registry)"
|
||||
representation = "`BF840002`"
|
||||
lowering = "resolved conditional branch"
|
||||
reference = "implemented"
|
||||
@@ -1396,7 +1540,7 @@ llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_branch"
|
||||
encoding = "Nonnegative signed dword displacement"
|
||||
encoding = "Nonnegative signed dword displacement (semantic registry)"
|
||||
representation = "`BF820001`"
|
||||
lowering = "resolved branch"
|
||||
reference = "implemented"
|
||||
@@ -1504,7 +1648,7 @@ llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cbranch_execz"
|
||||
encoding = "Nonnegative signed dword displacement"
|
||||
encoding = "Nonnegative signed dword displacement (semantic registry)"
|
||||
representation = "`BF880001`"
|
||||
lowering = "resolved Wave32 EXEC_LO zero check"
|
||||
reference = "implemented"
|
||||
@@ -1516,7 +1660,7 @@ llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cbranch_vccz"
|
||||
encoding = "Nonnegative signed dword displacement"
|
||||
encoding = "Nonnegative signed dword displacement (semantic registry)"
|
||||
representation = "`BF860001`"
|
||||
lowering = "resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare"
|
||||
reference = "implemented"
|
||||
@@ -1742,6 +1886,54 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cndmask_b32_e32"
|
||||
encoding = "VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; select S1 when the VCC_LO lane bit is set, otherwise S0"
|
||||
representation = "`020402C1`"
|
||||
lowering = "per-thread integer expression with EXEC masking"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_add_co_ci_u32_e32"
|
||||
encoding = "VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned addition with carry input and output"
|
||||
representation = "`50040481`"
|
||||
lowering = "per-thread integer expression with EXEC masking"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_sub_co_ci_u32_e32"
|
||||
encoding = "VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S0 minus S1 with borrow input and output"
|
||||
representation = "`52060480`"
|
||||
lowering = "per-thread integer expression with EXEC masking"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_subrev_co_ci_u32_e32"
|
||||
encoding = "VOP2, Wave32; VCC_LO lane input; general SRC0, VGPR VSRC1 and VDST; unsigned S1 minus S0 with borrow input and output"
|
||||
representation = "`540606C2`"
|
||||
lowering = "per-thread integer expression with EXEC masking"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[guest_milestones]
|
||||
X1 = "accepted"
|
||||
X2 = "accepted"
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
/target/
|
||||
@@ -0,0 +1,30 @@
|
||||
# Audio API coverage
|
||||
|
||||
Proprietary Xbox audio DSP APIs are unsupported; this experiment defines only its own fixture services below.
|
||||
|
||||
## Original Xenora fixture services
|
||||
|
||||
These Win64 calls are defined only for this experiment under
|
||||
`xenora_audio_fixture.dll`. The host registers them for a single DSP session
|
||||
and provides a stream handle to trusted synthetic guest code.
|
||||
|
||||
| Import | Arguments |
|
||||
| --- | --- |
|
||||
| `SubmitPcm` | RCX stream handle, RDX guest PCM address, R8 byte length, R9D encoding (1 for S16LE, 2 for F32LE) |
|
||||
| `ScheduleStart` | RCX stream handle, RDX absolute DSP output-frame clock position |
|
||||
|
||||
The result in RAX is 0 for accepted, 1 for an invalid handle, 2 for invalid
|
||||
input, 3 for exhausted capacity or 4 for session failure. An invalid guest
|
||||
memory range raises Xenora's checked memory fault. PCM must use complete frames,
|
||||
be appropriately aligned and fit the configured transfer limit. Acceptance
|
||||
places a command into the FIFO and does not report completed playback.
|
||||
|
||||
## Public references
|
||||
|
||||
- [Microsoft GDK overview](https://learn.microsoft.com/en-us/gaming/gdk/_content/gc/intro/overviews/introduction)
|
||||
- [Microsoft XAudio2 introduction](https://learn.microsoft.com/en-us/windows/win32/xaudio2/xaudio2-introduction)
|
||||
- [Microsoft WAVEFORMATEX frame alignment](https://learn.microsoft.com/en-us/windows/win32/api/mmreg/ns-mmreg-waveformatex)
|
||||
- [Microsoft x64 calling convention](https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention)
|
||||
- [Apple Audio Queue Services](https://developer.apple.com/documentation/audiotoolbox/audio-queue-services)
|
||||
- [Apple AudioQueueNewOutput](https://developer.apple.com/documentation/audiotoolbox/audioqueuenewoutput)
|
||||
- [Apple AudioQueueGetCurrentTime](https://developer.apple.com/documentation/audiotoolbox/audioqueuegetcurrenttime)
|
||||
@@ -0,0 +1,72 @@
|
||||
# Architecture
|
||||
|
||||
```text
|
||||
Host PCM ───────────────┐
|
||||
Gate 6 AudioSubsystem ──┼─> Session staging ─> FIFO commands ─> per-stream PCM
|
||||
Synthetic guest ABI ────┘ │
|
||||
v
|
||||
rate conversion, gain, mix
|
||||
│
|
||||
v
|
||||
offline read or Audio Queue worker
|
||||
```
|
||||
|
||||
A clone of a `Session` shares one bounded state and output clock. The host opens
|
||||
streams using validated channel layouts and rates. Handles contain a slot and a
|
||||
generation unique within the process. Session ownership is enforced by exact
|
||||
matches in the session's tables. Slots allocated again get new handles. A staged
|
||||
PCM buffer belongs to one stream. Successful submission makes the buffer
|
||||
in-flight until the renderer transfers its samples into that stream's queue and
|
||||
retires the handle. The renderer applies pending commands in ticket order at
|
||||
the beginning of each block. Closing a stream retires its staged buffers and
|
||||
drops its pending commands. Closing a session invalidates all handles.
|
||||
|
||||
There is one active renderer per session. Relative to its clock, a stream can
|
||||
start or resume at an exact output frame and can be paused without consuming
|
||||
source samples. Gains apply per output channel. Mono duplicates into stereo.
|
||||
Stereo downmix is the arithmetic mean. The mixer accumulates in FP64 and clips
|
||||
once to normalized FP32. Linear interpolation tracks input phase as an integer
|
||||
ratio of rates across input and output boundaries. On shortage it inserts
|
||||
silence and holds the remaining source state. Pause and future starts do not
|
||||
count as underruns. The renderer never waits for input.
|
||||
|
||||
Hard limits bound the stream, source-frame, buffer and command counts per
|
||||
session. PCM allocations and destination capacity are checked before admission.
|
||||
A failed admission leaves existing audio in place. The DSP serializes its
|
||||
state with a mutex. Decoding, copying and retiring PCM can allocate on producer
|
||||
or worker threads. The CoreAudio callback only identifies a reclaimed buffer
|
||||
and updates atomics. The worker refills three platform-owned buffers and uses
|
||||
synchronous queue disposal off the callback thread. If disposal fails, it
|
||||
returns the status and retains callback context for potential late callbacks.
|
||||
|
||||
Audio Queue startup queries hardware support through the system framework at
|
||||
runtime. If the default device cannot open or start at the requested format,
|
||||
the call returns the platform error. The worker starts with three silence
|
||||
buffers so startup can fail without consuming source PCM. It currently polls
|
||||
at 1 ms and requires at least four milliseconds of audio per buffer. Timing
|
||||
metrics include observed buffer returns, periodic queue-clock samples and
|
||||
discontinuities. A discontinuity invalidates the queue lead estimate for
|
||||
that playback session. Stopping flushes the device queue. A device error after
|
||||
rendering has begun can discard an already mixed block.
|
||||
|
||||
## Integration boundary
|
||||
|
||||
The optional adapter uses Xenora's existing typed argument reader, import
|
||||
registry and checked guest memory. The Gate 6 bridge preserves its producer,
|
||||
PCM storage and existing format IDs. It submits through the same host API as
|
||||
other PCM clients. It handles a finite batch based on capacity and preserves
|
||||
source bytes when a submission fails. It does not implicitly replace the
|
||||
existing application audio path.
|
||||
|
||||
## Current limits
|
||||
|
||||
- Interleaved S16LE and normalized finite F32LE input. Interleaved FP32 output.
|
||||
- Mono and stereo at 8 through 192 kHz. No surround, effects graph, codecs,
|
||||
device selection, hot-plug recovery or drift compensation.
|
||||
- The linear resampler does not implement anti-alias filtering for downsampling.
|
||||
- Native output was tested on one M5 Pro. Other Apple Silicon devices depend on
|
||||
runtime Audio Queue support and remain unmeasured in this experiment.
|
||||
- The standalone crate does not add shared app, runtime or FFI changes. Wiring
|
||||
the bridge into Gate 6's app session and native device lifetime requires
|
||||
coordination with the Gate 6 and runtime owners. Xenora #284 and #293 identify
|
||||
the overlapping FFI work.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Added a standalone bounded PCM mixer with generation-tracked handles,
|
||||
ordered commands, synchronized stream starts and deterministic offline output.
|
||||
- Added opt-in native ARM64 CoreAudio output and diagnostics.
|
||||
- Added a Gate 6 PCM bridge and typed services for original synthetic Xenora
|
||||
fixtures.
|
||||
Generated
+207
@@ -0,0 +1,207 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dispatch2"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
|
||||
dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-foundation"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"dispatch2",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-encode"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-metal"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"objc2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "xenora-audio-dsp"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-ffi",
|
||||
"xenora-loader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-decoder"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-isa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-ffi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-isa"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "xenora-loader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-metal"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
"objc2-metal",
|
||||
"xenora-texture",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-shader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-texture"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "xenora-audio-dsp"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.100"
|
||||
license = "GPL-3.0-or-later"
|
||||
description = "Bounded PCM mixer and native macOS audio output experiment"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[features]
|
||||
xenora = ["dep:xenora-loader", "dep:xenora-ffi"]
|
||||
|
||||
[dependencies]
|
||||
xenora-loader = { path = "../../crates/loader", optional = true }
|
||||
xenora-ffi = { path = "../../crates/ffi", optional = true }
|
||||
|
||||
[lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
@@ -0,0 +1,75 @@
|
||||
# Native audio DSP experiment
|
||||
|
||||
This Rust library mixes bounded PCM streams to deterministic offline output or the
|
||||
default CoreAudio playback queue on Apple Silicon. The optional `xenora` feature
|
||||
exposes the mixer through two original synthetic runtime services and can ingest
|
||||
PCM from the existing Gate 6 queue.
|
||||
|
||||
## Build and test
|
||||
|
||||
Run from this directory with Rust 1.100 or later on Apple Silicon macOS.
|
||||
|
||||
```sh
|
||||
cargo test --locked --target aarch64-apple-darwin --all-features
|
||||
cargo clippy --locked --target aarch64-apple-darwin --all-features --all-targets -- -D warnings
|
||||
cargo fmt --check
|
||||
cargo run --locked --release --target aarch64-apple-darwin --example measure
|
||||
```
|
||||
|
||||
The offline benchmark submits and mixes eight stereo PCM streams. Pass
|
||||
`-- --play` to the same example for a brief, quiet tone on the default CoreAudio
|
||||
output, with queue timing and underrun counters. Normal tests stay silent.
|
||||
|
||||
## Offline rendering
|
||||
|
||||
```rust
|
||||
use xenora_audio_dsp::{Channels, Encoding, Format, Limits, Session};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let output = Format::new(48_000, Channels::Stereo)?;
|
||||
let source = Format::new(48_000, Channels::Mono)?;
|
||||
let session = Session::new(output, Limits::default())?;
|
||||
let stream = session.open_stream(source)?;
|
||||
session.submit_pcm(stream, Encoding::S16Le, &[0, 0x40, 0, 0xc0])?;
|
||||
let mut pcm = [0.0; 4];
|
||||
session.renderer()?.render(&mut pcm)?;
|
||||
assert_eq!(pcm, [0.5, 0.5, -0.5, -0.5]);
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
To ingest Gate 6 audio, make a DSP stream with the same rate and channel count
|
||||
and call `xenora::transfer_gate6(&mut gate6_audio, &session, stream, 256)`.
|
||||
That function only drains frames after the DSP accepts them. Call it again
|
||||
after rendering if the destination has no free frames.
|
||||
|
||||
An original trusted guest fixture can call
|
||||
`xenora::register_fixture_services(&mut registry, &session)` from its host
|
||||
setup. The host supplies the guest with the raw handle for the fixture's
|
||||
stream. The [API coverage report](API-COVERAGE.md) describes the exact
|
||||
synthetic call contract.
|
||||
|
||||
## Local verification
|
||||
|
||||
The standalone experiment was checked on Apple M5 Pro, macOS 27.2.1,
|
||||
Rust 1.100.0 and Xcode 27.2. The release example was a native arm64 Mach-O
|
||||
linked to AudioToolbox and libSystem.
|
||||
|
||||
| Check | Observed result |
|
||||
| --- | --- |
|
||||
| ARM64 DSP and adapter tests | 15 passed, including 100 session lifecycle cycles |
|
||||
| Existing ARM64 Xenora workspace tests | 486 passed, 22 ignored |
|
||||
| Eight streams, 48 kHz, 256-frame blocks | 9.13 µs median and 9.42 µs p95 to submit and mix; 3.63 µs median for mixing and command retirement alone |
|
||||
| Process memory in the offline benchmark | 6,471,680 bytes maximum resident set, with 278,528 bytes reserved for PCM at a fully staged block |
|
||||
| Default CoreAudio output, 48 kHz, 256-frame buffers | 47 buffer returns, 12,032 DSP frames submitted, zero DSP underrun frames or queue timeline discontinuities |
|
||||
| Timing on that CoreAudio run | 83.11 ms to first worker-observed buffer return from the start call, and a sampled queue lead of 1,622 frames (33.8 ms) |
|
||||
|
||||
The device measurement includes startup and worker scheduling. Queue lead is
|
||||
an estimate on the CoreAudio sample timeline. Neither value measures acoustic
|
||||
latency. Three buffers carry 768 initial silence frames (16 ms at 48 kHz) so
|
||||
device startup failure leaves the DSP timeline and PCM unchanged.
|
||||
|
||||
See the [architecture](ARCHITECTURE.md) for ownership, limits, scheduling and
|
||||
remaining work. This is a local AI-assisted experiment with independent
|
||||
agent review of the resampling expectations and Audio Queue ownership.
|
||||
Maintainer ownership review and human acceptance remain pending.
|
||||
@@ -0,0 +1,111 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
use xenora_audio_dsp::{Channels, Encoding, Format, Limits, Session};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
match std::env::args().nth(1).as_deref() {
|
||||
None => offline(),
|
||||
Some("--play") => native(),
|
||||
_ => Err("usage: measure [--play]".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn offline() -> Result<(), Box<dyn std::error::Error>> {
|
||||
const BLOCK: usize = 256;
|
||||
const VOICES: usize = 8;
|
||||
const ITERATIONS: usize = 1500;
|
||||
let format = Format::new(48_000, Channels::Stereo)?;
|
||||
let session = Session::new(format, Limits::default())?;
|
||||
let inputs = (0..VOICES)
|
||||
.map(|_| session.open_stream(format))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut renderer = session.renderer()?;
|
||||
let pcm = [0x00, 0x04, 0x00, 0xfc].repeat(BLOCK);
|
||||
let mut output = [0.0; 2 * BLOCK];
|
||||
let mut times = Vec::with_capacity(ITERATIONS);
|
||||
let mut mix_times = Vec::with_capacity(ITERATIONS);
|
||||
let mut peak_bytes = 0;
|
||||
for _ in 0..100 {
|
||||
for &stream in &inputs {
|
||||
session.submit_pcm(stream, Encoding::S16Le, &pcm)?;
|
||||
}
|
||||
renderer.render(black_box(&mut output))?;
|
||||
}
|
||||
for _ in 0..ITERATIONS {
|
||||
let start = Instant::now();
|
||||
for &stream in &inputs {
|
||||
session.submit_pcm(stream, Encoding::S16Le, &pcm)?;
|
||||
}
|
||||
let staged_at = Instant::now();
|
||||
renderer.render(black_box(&mut output))?;
|
||||
mix_times.push(staged_at.elapsed().as_nanos());
|
||||
times.push(start.elapsed().as_nanos());
|
||||
}
|
||||
for &stream in &inputs {
|
||||
session.submit_pcm(stream, Encoding::S16Le, &pcm)?;
|
||||
}
|
||||
peak_bytes = peak_bytes.max(session.metrics()?.reserved_sample_bytes);
|
||||
renderer.render(&mut output)?;
|
||||
let metrics = session.metrics()?;
|
||||
times.sort_unstable();
|
||||
mix_times.sort_unstable();
|
||||
assert_eq!((output[0], output[1]), (0.25, -0.25));
|
||||
assert_eq!(metrics.underrun_stream_frames, 0);
|
||||
println!("Offline: {ITERATIONS} × {BLOCK} frames, {VOICES} stereo streams, 48000 Hz");
|
||||
println!(
|
||||
"submit+mix p50={} ns p95={} ns; mix p50={} ns p95={} ns",
|
||||
times[ITERATIONS / 2],
|
||||
times[ITERATIONS * 95 / 100],
|
||||
mix_times[ITERATIONS / 2],
|
||||
mix_times[ITERATIONS * 95 / 100]
|
||||
);
|
||||
println!(
|
||||
"Reserved PCM payload at one fully staged block: {peak_bytes} bytes; staging high-water={} source frames",
|
||||
metrics.peak_staging_frames
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
|
||||
fn native() -> Result<(), Box<dyn std::error::Error>> {
|
||||
use std::time::Duration;
|
||||
use xenora_audio_dsp::coreaudio::Playback;
|
||||
|
||||
let format = Format::new(48_000, Channels::Stereo)?;
|
||||
let limits = Limits {
|
||||
frames_per_stream: 24_000,
|
||||
staging_frames: 24_000,
|
||||
..Limits::default()
|
||||
};
|
||||
let session = Session::new(format, limits)?;
|
||||
let stream = session.open_stream(format)?;
|
||||
let pcm = (0..20_000)
|
||||
.flat_map(|frame| {
|
||||
let envelope = (frame as f32 / 500.0)
|
||||
.min(1.0)
|
||||
.min((19_999 - frame) as f32 / 500.0);
|
||||
let sample =
|
||||
(frame as f32 * 220.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.015 * envelope;
|
||||
[sample.to_le_bytes(); 2].into_iter().flatten()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
session.submit_pcm(stream, Encoding::F32Le, &pcm)?;
|
||||
let playback = Playback::start(&session, 256)?;
|
||||
std::thread::sleep(Duration::from_millis(260));
|
||||
let measured = playback.stop()?;
|
||||
let metrics = session.metrics()?;
|
||||
assert!(measured.buffer_callbacks > 0);
|
||||
assert!(measured.queue_clock_frames.is_some_and(|frames| frames > 0));
|
||||
assert_eq!(metrics.underrun_stream_frames, 0);
|
||||
assert_eq!(metrics.output_frames, measured.submitted_frames);
|
||||
println!("Native playback: {measured:?}");
|
||||
println!("Session: {metrics:?}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
|
||||
fn native() -> Result<(), Box<dyn std::error::Error>> {
|
||||
Err("native playback requires Apple Silicon macOS".into())
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Native ARM64 Audio Queue output. Only the worker calls into the DSP.
|
||||
|
||||
use crate::{AudioError, Format, Renderer, Session};
|
||||
use std::ffi::c_void;
|
||||
use std::fmt;
|
||||
use std::ptr::{self, NonNull};
|
||||
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const BUFFER_COUNT: usize = 3;
|
||||
const UNAVAILABLE: u64 = u64::MAX;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PlaybackError {
|
||||
Dsp(AudioError),
|
||||
CoreAudio {
|
||||
operation: &'static str,
|
||||
status: i32,
|
||||
},
|
||||
InvalidBuffer,
|
||||
InvalidBlockSize,
|
||||
Thread(std::io::Error),
|
||||
WorkerStopped,
|
||||
}
|
||||
|
||||
impl fmt::Display for PlaybackError {
|
||||
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Dsp(err) => write!(out, "DSP playback: {err}"),
|
||||
Self::CoreAudio { operation, status } => {
|
||||
write!(out, "{operation} failed (OSStatus {status})")
|
||||
}
|
||||
Self::InvalidBuffer => out.write_str("CoreAudio returned an invalid PCM buffer"),
|
||||
Self::InvalidBlockSize => out.write_str("invalid CoreAudio block size"),
|
||||
Self::Thread(err) => write!(out, "could not start the audio worker: {err}"),
|
||||
Self::WorkerStopped => out.write_str("audio worker stopped unexpectedly"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PlaybackError {}
|
||||
impl From<AudioError> for PlaybackError {
|
||||
fn from(error: AudioError) -> Self {
|
||||
Self::Dsp(error)
|
||||
}
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, PlaybackError>;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct PlaybackMetrics {
|
||||
pub buffer_callbacks: u64,
|
||||
pub submitted_frames: u64,
|
||||
pub priming_frames: u64,
|
||||
pub queue_clock_frames: Option<u64>,
|
||||
pub queued_lead_estimate_frames: Option<u64>,
|
||||
pub time_to_first_return_observed: Option<Duration>,
|
||||
pub timeline_discontinuities: u64,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
stop: AtomicBool,
|
||||
buffers: [AtomicPtr<QueueBuffer>; BUFFER_COUNT],
|
||||
returned: AtomicU32,
|
||||
callbacks: AtomicU64,
|
||||
submitted: AtomicU64,
|
||||
priming: AtomicU64,
|
||||
queue_clock: AtomicU64,
|
||||
lead: AtomicU64,
|
||||
first_return: AtomicU64,
|
||||
discontinuities: AtomicU64,
|
||||
}
|
||||
|
||||
impl Default for Shared {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
stop: AtomicBool::new(false),
|
||||
buffers: std::array::from_fn(|_| AtomicPtr::new(ptr::null_mut())),
|
||||
returned: AtomicU32::new(0),
|
||||
callbacks: AtomicU64::new(0),
|
||||
submitted: AtomicU64::new(0),
|
||||
priming: AtomicU64::new(0),
|
||||
queue_clock: AtomicU64::new(UNAVAILABLE),
|
||||
lead: AtomicU64::new(UNAVAILABLE),
|
||||
first_return: AtomicU64::new(UNAVAILABLE),
|
||||
discontinuities: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn metrics(&self) -> PlaybackMetrics {
|
||||
let read = |value: &AtomicU64| value.load(Ordering::Relaxed);
|
||||
let clock = read(&self.queue_clock);
|
||||
let first = read(&self.first_return);
|
||||
let lead = read(&self.lead);
|
||||
let submitted = read(&self.submitted);
|
||||
PlaybackMetrics {
|
||||
buffer_callbacks: read(&self.callbacks),
|
||||
submitted_frames: submitted,
|
||||
priming_frames: read(&self.priming),
|
||||
queue_clock_frames: (clock != UNAVAILABLE).then_some(clock),
|
||||
queued_lead_estimate_frames: (lead != UNAVAILABLE).then_some(lead),
|
||||
time_to_first_return_observed: (first != UNAVAILABLE)
|
||||
.then(|| Duration::from_nanos(first)),
|
||||
timeline_discontinuities: read(&self.discontinuities),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A native output queue opened at runtime with the session's format on the default device.
|
||||
pub struct Playback {
|
||||
shared: Arc<Shared>,
|
||||
worker: Option<JoinHandle<Result<()>>>,
|
||||
}
|
||||
|
||||
impl Playback {
|
||||
pub fn start(session: &Session, frames_per_buffer: usize) -> Result<Self> {
|
||||
let format = session.output_format()?;
|
||||
let min = (format.rate() as usize).div_ceil(250); // Four milliseconds per buffer.
|
||||
let max = session.live()?.limits.render_frames.min(4096);
|
||||
if !(min..=max).contains(&frames_per_buffer) {
|
||||
return Err(PlaybackError::InvalidBlockSize);
|
||||
}
|
||||
let renderer = session.renderer()?;
|
||||
let shared = Arc::new(Shared::default());
|
||||
let worker_shared = Arc::clone(&shared);
|
||||
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
|
||||
let worker = thread::Builder::new()
|
||||
.name("xenora-audio".into())
|
||||
.spawn(move || {
|
||||
play(
|
||||
renderer,
|
||||
format,
|
||||
frames_per_buffer,
|
||||
&worker_shared,
|
||||
ready_tx,
|
||||
)
|
||||
})
|
||||
.map_err(PlaybackError::Thread)?;
|
||||
if ready_rx.recv().is_err() {
|
||||
worker.join().map_err(|_| PlaybackError::WorkerStopped)??;
|
||||
return Err(PlaybackError::WorkerStopped);
|
||||
}
|
||||
Ok(Self {
|
||||
shared,
|
||||
worker: Some(worker),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn metrics(&self) -> PlaybackMetrics {
|
||||
self.shared.metrics()
|
||||
}
|
||||
|
||||
pub fn stop(mut self) -> Result<PlaybackMetrics> {
|
||||
self.finish()?;
|
||||
Ok(self.metrics())
|
||||
}
|
||||
|
||||
fn finish(&mut self) -> Result<()> {
|
||||
self.shared.stop.store(true, Ordering::Release);
|
||||
match self.worker.take() {
|
||||
Some(worker) => worker.join().map_err(|_| PlaybackError::WorkerStopped)?,
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Playback {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.finish();
|
||||
}
|
||||
}
|
||||
|
||||
fn play(
|
||||
mut renderer: Renderer,
|
||||
format: Format,
|
||||
frames: usize,
|
||||
shared: &Arc<Shared>,
|
||||
ready: mpsc::SyncSender<()>,
|
||||
) -> Result<()> {
|
||||
let bytes_per_frame = (format.channels().count() * size_of::<f32>()) as u32;
|
||||
let description = StreamDescription {
|
||||
sample_rate: f64::from(format.rate()),
|
||||
format: u32::from_be_bytes(*b"lpcm"),
|
||||
flags: 1 | (1 << 3), // kLinearPCMFormatFlagIsFloat | kLinearPCMFormatFlagIsPacked
|
||||
bytes_per_packet: bytes_per_frame,
|
||||
frames_per_packet: 1,
|
||||
bytes_per_frame,
|
||||
channels_per_frame: format.channels().count() as u32,
|
||||
bits_per_channel: 32,
|
||||
reserved: 0,
|
||||
};
|
||||
let byte_count = frames as u32 * bytes_per_frame;
|
||||
let mut queue = NativeQueue::new(&description, shared)?;
|
||||
let mut buffers = [None; BUFFER_COUNT];
|
||||
let result = (|| {
|
||||
for (index, slot) in buffers.iter_mut().enumerate() {
|
||||
let buffer = queue.allocate(byte_count)?;
|
||||
shared.buffers[index].store(buffer.as_ptr(), Ordering::Release);
|
||||
*slot = Some(buffer);
|
||||
}
|
||||
// A failed allocation, enqueue or start must leave the source and DSP clock intact.
|
||||
for buffer in buffers.into_iter().flatten() {
|
||||
queue.enqueue(buffer, byte_count, None)?;
|
||||
shared.priming.fetch_add(frames as u64, Ordering::Relaxed);
|
||||
}
|
||||
let clock_start = Instant::now();
|
||||
status("AudioQueueStart", unsafe {
|
||||
AudioQueueStart(queue.raw(), ptr::null())
|
||||
})?;
|
||||
if ready.send(()).is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut next_clock_read = clock_start;
|
||||
while !shared.stop.load(Ordering::Acquire) {
|
||||
let returned = shared.returned.swap(0, Ordering::Acquire);
|
||||
if returned != 0 {
|
||||
let elapsed = clock_start
|
||||
.elapsed()
|
||||
.as_nanos()
|
||||
.min(u128::from(UNAVAILABLE - 1)) as u64;
|
||||
let _ = shared.first_return.compare_exchange(
|
||||
UNAVAILABLE,
|
||||
elapsed,
|
||||
Ordering::Relaxed,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
for (index, slot) in buffers.iter().enumerate() {
|
||||
if returned & (1 << index) != 0 {
|
||||
queue.enqueue(
|
||||
slot.ok_or(PlaybackError::InvalidBuffer)?,
|
||||
byte_count,
|
||||
Some(&mut renderer),
|
||||
)?;
|
||||
shared.submitted.fetch_add(frames as u64, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
let now = Instant::now();
|
||||
if now >= next_clock_read {
|
||||
queue.observe_clock(shared);
|
||||
next_clock_read = now + Duration::from_millis(10);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
shared.stop.store(true, Ordering::Release);
|
||||
let disposal = queue.dispose();
|
||||
result.and(disposal)
|
||||
}
|
||||
|
||||
struct NativeQueue {
|
||||
queue: Option<NonNull<c_void>>,
|
||||
callback_context: *const Shared,
|
||||
timeline: *mut c_void,
|
||||
}
|
||||
|
||||
impl NativeQueue {
|
||||
fn new(description: &StreamDescription, shared: &Arc<Shared>) -> Result<Self> {
|
||||
let context = Arc::into_raw(Arc::clone(shared));
|
||||
let mut queue = ptr::null_mut();
|
||||
// SAFETY: matching C ABI. The separately retained context survives until synchronous disposal.
|
||||
let result = unsafe {
|
||||
AudioQueueNewOutput(
|
||||
description,
|
||||
returned_buffer,
|
||||
context.cast_mut().cast(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
0,
|
||||
&mut queue,
|
||||
)
|
||||
};
|
||||
let Some(queue) = NonNull::new(queue) else {
|
||||
// With no queue there is no callback registration to retire.
|
||||
unsafe { drop(Arc::from_raw(context)) };
|
||||
return status("AudioQueueNewOutput", result).and(Err(PlaybackError::InvalidBuffer));
|
||||
};
|
||||
let mut native = Self {
|
||||
queue: Some(queue),
|
||||
callback_context: context,
|
||||
timeline: ptr::null_mut(),
|
||||
};
|
||||
status("AudioQueueNewOutput", result)?;
|
||||
status("AudioQueueCreateTimeline", unsafe {
|
||||
AudioQueueCreateTimeline(native.raw(), &mut native.timeline)
|
||||
})?;
|
||||
if native.timeline.is_null() {
|
||||
return Err(PlaybackError::InvalidBuffer);
|
||||
}
|
||||
Ok(native)
|
||||
}
|
||||
|
||||
fn raw(&self) -> *mut c_void {
|
||||
self.queue.unwrap().as_ptr()
|
||||
}
|
||||
|
||||
fn allocate(&self, byte_count: u32) -> Result<NonNull<QueueBuffer>> {
|
||||
let mut out = ptr::null_mut();
|
||||
status("AudioQueueAllocateBuffer", unsafe {
|
||||
AudioQueueAllocateBuffer(self.raw(), byte_count, &mut out)
|
||||
})?;
|
||||
NonNull::new(out).ok_or(PlaybackError::InvalidBuffer)
|
||||
}
|
||||
|
||||
fn enqueue(
|
||||
&self,
|
||||
mut buffer: NonNull<QueueBuffer>,
|
||||
byte_count: u32,
|
||||
renderer: Option<&mut Renderer>,
|
||||
) -> Result<()> {
|
||||
// SAFETY: the worker owns a fresh buffer or has acquired a completion signal.
|
||||
let storage = unsafe { buffer.as_mut() };
|
||||
let data = storage.data.cast::<f32>();
|
||||
if storage.capacity < byte_count || data.is_null() || !data.is_aligned() {
|
||||
return Err(PlaybackError::InvalidBuffer);
|
||||
}
|
||||
let sample_count = byte_count as usize / size_of::<f32>();
|
||||
// SAFETY: retained queue buffer with checked alignment and complete interleaved frames.
|
||||
// Initialize storage before creating the Rust f32 slice.
|
||||
let samples = unsafe {
|
||||
data.write_bytes(0, sample_count);
|
||||
std::slice::from_raw_parts_mut(data, sample_count)
|
||||
};
|
||||
if let Some(renderer) = renderer {
|
||||
renderer.render(samples)?;
|
||||
}
|
||||
storage.byte_count = byte_count;
|
||||
status("AudioQueueEnqueueBuffer", unsafe {
|
||||
AudioQueueEnqueueBuffer(self.raw(), buffer.as_ptr(), 0, ptr::null())
|
||||
})
|
||||
}
|
||||
|
||||
fn observe_clock(&self, shared: &Shared) {
|
||||
let mut stamp = TimeStamp::default();
|
||||
let mut discontinuity = 0;
|
||||
let status = unsafe {
|
||||
AudioQueueGetCurrentTime(self.raw(), self.timeline, &mut stamp, &mut discontinuity)
|
||||
};
|
||||
if discontinuity != 0 {
|
||||
shared.discontinuities.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
let clock = if status == 0
|
||||
&& discontinuity == 0
|
||||
&& stamp.flags & 1 != 0
|
||||
&& stamp.sample_time.is_finite()
|
||||
&& stamp.sample_time >= 0.0
|
||||
{
|
||||
stamp.sample_time as u64
|
||||
} else {
|
||||
UNAVAILABLE
|
||||
};
|
||||
shared.queue_clock.store(clock, Ordering::Relaxed);
|
||||
// Sample lead on the worker using the submission count from this observation.
|
||||
// After a discontinuity the original submission epoch is no longer reliable.
|
||||
let lead = if clock != UNAVAILABLE && shared.discontinuities.load(Ordering::Relaxed) == 0 {
|
||||
let submitted = shared
|
||||
.submitted
|
||||
.load(Ordering::Relaxed)
|
||||
.saturating_add(shared.priming.load(Ordering::Relaxed));
|
||||
submitted.saturating_sub(clock)
|
||||
} else {
|
||||
UNAVAILABLE
|
||||
};
|
||||
shared.lead.store(lead, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn dispose(&mut self) -> Result<()> {
|
||||
let Some(queue) = self.queue.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
// SAFETY: called off the callback thread with no locks. On success no more callbacks run.
|
||||
let result = unsafe { AudioQueueDispose(queue.as_ptr(), 1) };
|
||||
if result == 0 {
|
||||
unsafe { drop(Arc::from_raw(self.callback_context)) };
|
||||
}
|
||||
// If disposal fails the callback registration may still be live, so retain the context.
|
||||
status("AudioQueueDispose", result)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NativeQueue {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn returned_buffer(
|
||||
context: *mut c_void,
|
||||
_: *mut c_void,
|
||||
buffer: *mut QueueBuffer,
|
||||
) {
|
||||
// SAFETY: Audio Queue holds the explicitly retained Arc pointer until synchronous disposal.
|
||||
let shared = unsafe { &*context.cast::<Shared>() };
|
||||
if shared.stop.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
for (index, slot) in shared.buffers.iter().enumerate() {
|
||||
if slot.load(Ordering::Acquire) == buffer {
|
||||
shared.callbacks.fetch_add(1, Ordering::Relaxed);
|
||||
shared.returned.fetch_or(1 << index, Ordering::Release);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn status(operation: &'static str, code: i32) -> Result<()> {
|
||||
if code == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PlaybackError::CoreAudio {
|
||||
operation,
|
||||
status: code,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct StreamDescription {
|
||||
sample_rate: f64,
|
||||
format: u32,
|
||||
flags: u32,
|
||||
bytes_per_packet: u32,
|
||||
frames_per_packet: u32,
|
||||
bytes_per_frame: u32,
|
||||
channels_per_frame: u32,
|
||||
bits_per_channel: u32,
|
||||
reserved: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct QueueBuffer {
|
||||
capacity: u32,
|
||||
data: *mut c_void,
|
||||
byte_count: u32,
|
||||
user_data: *mut c_void,
|
||||
packet_capacity: u32,
|
||||
packets: *mut c_void,
|
||||
packet_count: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct TimeStamp {
|
||||
sample_time: f64,
|
||||
host_time: u64,
|
||||
rate_scalar: f64,
|
||||
word_clock: u64,
|
||||
smpte: [u32; 6],
|
||||
flags: u32,
|
||||
reserved: u32,
|
||||
}
|
||||
|
||||
#[link(name = "AudioToolbox", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn AudioQueueNewOutput(
|
||||
description: *const StreamDescription,
|
||||
callback: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut QueueBuffer),
|
||||
context: *mut c_void,
|
||||
run_loop: *const c_void,
|
||||
mode: *const c_void,
|
||||
flags: u32,
|
||||
out: *mut *mut c_void,
|
||||
) -> i32;
|
||||
fn AudioQueueAllocateBuffer(queue: *mut c_void, size: u32, out: *mut *mut QueueBuffer) -> i32;
|
||||
fn AudioQueueEnqueueBuffer(
|
||||
queue: *mut c_void,
|
||||
buffer: *mut QueueBuffer,
|
||||
packet_count: u32,
|
||||
descriptions: *const c_void,
|
||||
) -> i32;
|
||||
fn AudioQueueStart(queue: *mut c_void, at: *const TimeStamp) -> i32;
|
||||
fn AudioQueueCreateTimeline(queue: *mut c_void, timeline: *mut *mut c_void) -> i32;
|
||||
fn AudioQueueGetCurrentTime(
|
||||
queue: *mut c_void,
|
||||
timeline: *mut c_void,
|
||||
stamp: *mut TimeStamp,
|
||||
discontinuity: *mut u8,
|
||||
) -> i32;
|
||||
fn AudioQueueDispose(queue: *mut c_void, immediate: u8) -> i32;
|
||||
}
|
||||
@@ -0,0 +1,709 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Bounded interleaved PCM mixing, independent of the guest and output device.
|
||||
|
||||
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
|
||||
pub mod coreaudio;
|
||||
#[cfg(feature = "xenora")]
|
||||
pub mod xenora;
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::fmt;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
type Frame = [f32; 2];
|
||||
type Result<T> = std::result::Result<T, AudioError>;
|
||||
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AudioError {
|
||||
InvalidFormat,
|
||||
InvalidLength,
|
||||
InvalidSample,
|
||||
InvalidGain,
|
||||
InvalidLimits,
|
||||
InvalidHandle,
|
||||
WrongStream,
|
||||
Closed,
|
||||
RendererBusy,
|
||||
QueueFull,
|
||||
BufferBudget,
|
||||
StreamLimit,
|
||||
BufferInFlight,
|
||||
ClockOverflow,
|
||||
Poisoned,
|
||||
}
|
||||
|
||||
impl fmt::Display for AudioError {
|
||||
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let detail = match self {
|
||||
Self::InvalidFormat => "unsupported PCM format",
|
||||
Self::InvalidLength => "invalid PCM or render length",
|
||||
Self::InvalidSample => "PCM sample is not finite or is outside the normalized range",
|
||||
Self::InvalidGain => "invalid channel gain",
|
||||
Self::InvalidLimits => "invalid DSP resource limits",
|
||||
Self::InvalidHandle => "invalid, stale, or foreign audio handle",
|
||||
Self::WrongStream => "audio buffer belongs to a different stream",
|
||||
Self::Closed => "audio session is closed",
|
||||
Self::RendererBusy => "audio session already has a renderer",
|
||||
Self::QueueFull => "audio command queue is full",
|
||||
Self::BufferBudget => "audio buffer budget exhausted",
|
||||
Self::StreamLimit => "audio session stream limit reached",
|
||||
Self::BufferInFlight => "audio buffer is queued for consumption",
|
||||
Self::ClockOverflow => "audio timeline or handle generation exhausted",
|
||||
Self::Poisoned => "audio session lock is poisoned",
|
||||
};
|
||||
out.write_str(detail)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AudioError {}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Channels {
|
||||
Mono = 1,
|
||||
Stereo = 2,
|
||||
}
|
||||
|
||||
impl Channels {
|
||||
pub const fn count(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Format {
|
||||
rate: u32,
|
||||
channels: Channels,
|
||||
}
|
||||
|
||||
impl Format {
|
||||
pub fn new(rate: u32, channels: Channels) -> Result<Self> {
|
||||
if !(8_000..=192_000).contains(&rate) {
|
||||
return Err(AudioError::InvalidFormat);
|
||||
}
|
||||
Ok(Self { rate, channels })
|
||||
}
|
||||
|
||||
pub const fn rate(self) -> u32 {
|
||||
self.rate
|
||||
}
|
||||
|
||||
pub const fn channels(self) -> Channels {
|
||||
self.channels
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Encoding {
|
||||
S16Le,
|
||||
F32Le,
|
||||
}
|
||||
|
||||
impl Encoding {
|
||||
pub const fn frame_bytes(self, channels: Channels) -> usize {
|
||||
let sample_bytes = match self {
|
||||
Self::S16Le => 2,
|
||||
Self::F32Le => 4,
|
||||
};
|
||||
sample_bytes * channels.count()
|
||||
}
|
||||
|
||||
fn frames(self, channels: Channels, bytes: &[u8]) -> impl Iterator<Item = Result<Frame>> {
|
||||
bytes
|
||||
.chunks_exact(self.frame_bytes(channels))
|
||||
.map(move |chunk| {
|
||||
let sample = |index: usize| match self {
|
||||
Self::S16Le => {
|
||||
let offset = index * 2;
|
||||
Ok(
|
||||
f32::from(i16::from_le_bytes([chunk[offset], chunk[offset + 1]]))
|
||||
/ 32768.0,
|
||||
)
|
||||
}
|
||||
Self::F32Le => {
|
||||
let offset = index * 4;
|
||||
let value =
|
||||
f32::from_le_bytes(chunk[offset..offset + 4].try_into().unwrap());
|
||||
if (-1.0..=1.0).contains(&value) {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(AudioError::InvalidSample)
|
||||
}
|
||||
}
|
||||
};
|
||||
let left = sample(0)?;
|
||||
let right = if channels == Channels::Stereo {
|
||||
sample(1)?
|
||||
} else {
|
||||
left
|
||||
};
|
||||
Ok([left, right])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Limits {
|
||||
pub streams: usize,
|
||||
pub frames_per_stream: usize,
|
||||
pub buffers: usize,
|
||||
pub staging_frames: usize,
|
||||
pub commands: usize,
|
||||
pub render_frames: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
streams: 8,
|
||||
frames_per_stream: 4096,
|
||||
buffers: 32,
|
||||
staging_frames: 8192,
|
||||
commands: 64,
|
||||
render_frames: 4096,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
fn check(self) -> Result<()> {
|
||||
let valid = (1..=64).contains(&self.streams)
|
||||
&& (1..=65_536).contains(&self.frames_per_stream)
|
||||
&& self.streams * self.frames_per_stream <= 262_144
|
||||
&& (1..=256).contains(&self.buffers)
|
||||
&& (1..=262_144).contains(&self.staging_frames)
|
||||
&& (1..=4096).contains(&self.commands)
|
||||
&& (1..=8192).contains(&self.render_frames);
|
||||
valid.then_some(()).ok_or(AudioError::InvalidLimits)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StreamHandle(u64);
|
||||
impl StreamHandle {
|
||||
pub const fn raw(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
pub const fn from_raw(value: u64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BufferHandle(u64);
|
||||
|
||||
struct Pool<T, const TAG: u64>(Vec<Option<(u64, T)>>);
|
||||
|
||||
impl<T, const TAG: u64> Pool<T, TAG> {
|
||||
fn new(capacity: usize) -> Self {
|
||||
Self(std::iter::repeat_with(|| None).take(capacity).collect())
|
||||
}
|
||||
|
||||
fn insert(&mut self, value: T, full: AudioError) -> Result<u64> {
|
||||
let index = self.0.iter().position(Option::is_none).ok_or(full)?;
|
||||
let generation = NEXT_GENERATION
|
||||
.try_update(Ordering::Relaxed, Ordering::Relaxed, |generation| {
|
||||
(generation <= (u64::MAX >> 9)).then_some(generation + 1)
|
||||
})
|
||||
.map_err(|_| AudioError::ClockOverflow)?;
|
||||
let handle = (generation << 9) | TAG | index as u64;
|
||||
self.0[index] = Some((handle, value));
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
fn entry(&mut self, handle: u64) -> Result<&mut Option<(u64, T)>> {
|
||||
self.0
|
||||
.get_mut((handle & 255) as usize)
|
||||
.filter(|entry| entry.as_ref().is_some_and(|(id, _)| *id == handle))
|
||||
.ok_or(AudioError::InvalidHandle)
|
||||
}
|
||||
|
||||
fn get(&mut self, handle: u64) -> Result<&mut T> {
|
||||
Ok(&mut self.entry(handle)?.as_mut().unwrap().1)
|
||||
}
|
||||
|
||||
fn take(&mut self, handle: u64) -> Result<T> {
|
||||
Ok(self.entry(handle)?.take().unwrap().1)
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.0.fill_with(|| None);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Control {
|
||||
Gain([f32; 2]),
|
||||
Mute(bool),
|
||||
/// Start or resume when the output clock is at least this frame.
|
||||
StartAt(u64),
|
||||
Pause,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Metrics {
|
||||
pub output_frames: u64,
|
||||
pub commands_applied: u64,
|
||||
pub commands_cancelled: u64,
|
||||
pub command_overruns: u64,
|
||||
pub buffer_overruns: u64,
|
||||
pub underrun_stream_frames: u64,
|
||||
pub last_applied: Option<u64>,
|
||||
pub live_streams: usize,
|
||||
pub live_buffers: usize,
|
||||
pub pending_commands: usize,
|
||||
pub buffered_source_frames: usize,
|
||||
pub reserved_sample_bytes: usize,
|
||||
pub peak_staging_frames: usize,
|
||||
}
|
||||
|
||||
struct Stream {
|
||||
format: Format,
|
||||
samples: VecDeque<Frame>,
|
||||
reserved: usize,
|
||||
phase: u32,
|
||||
gain: Frame,
|
||||
muted: bool,
|
||||
start_at: Option<u64>,
|
||||
}
|
||||
|
||||
impl Stream {
|
||||
fn next(&mut self, output_rate: u32) -> Option<Frame> {
|
||||
self.consume_whole_frames(output_rate);
|
||||
let first = *self.samples.front()?;
|
||||
let frame = if self.phase == 0 {
|
||||
first
|
||||
} else {
|
||||
let second = self.samples.get(1)?;
|
||||
let t = self.phase as f32 / output_rate as f32;
|
||||
std::array::from_fn(|channel| first[channel] + (second[channel] - first[channel]) * t)
|
||||
};
|
||||
self.phase += self.format.rate;
|
||||
self.consume_whole_frames(output_rate);
|
||||
Some(frame)
|
||||
}
|
||||
|
||||
fn consume_whole_frames(&mut self, output_rate: u32) {
|
||||
let count = ((self.phase / output_rate) as usize).min(self.samples.len());
|
||||
if count > 0 {
|
||||
self.samples.drain(..count);
|
||||
self.phase -= count as u32 * output_rate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Buffer {
|
||||
owner: StreamHandle,
|
||||
frames: Vec<Frame>,
|
||||
queued: bool,
|
||||
}
|
||||
|
||||
enum Command {
|
||||
Control(Control),
|
||||
Buffer(BufferHandle),
|
||||
}
|
||||
|
||||
struct Pending {
|
||||
ticket: u64,
|
||||
stream: StreamHandle,
|
||||
command: Command,
|
||||
}
|
||||
|
||||
struct State {
|
||||
closed: bool,
|
||||
renderer: bool,
|
||||
output: Format,
|
||||
limits: Limits,
|
||||
streams: Pool<Stream, 0>,
|
||||
buffers: Pool<Buffer, 256>,
|
||||
staging_frames: usize,
|
||||
commands: VecDeque<Pending>,
|
||||
next_ticket: u64,
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn reserve_command(&mut self) -> Result<u64> {
|
||||
if self.commands.len() == self.limits.commands {
|
||||
self.metrics.command_overruns = self.metrics.command_overruns.saturating_add(1);
|
||||
return Err(AudioError::QueueFull);
|
||||
}
|
||||
let ticket = self.next_ticket;
|
||||
self.next_ticket = ticket.checked_add(1).ok_or(AudioError::ClockOverflow)?;
|
||||
Ok(ticket)
|
||||
}
|
||||
|
||||
fn take_buffer(&mut self, handle: BufferHandle) -> Result<Buffer> {
|
||||
let buffer = self.buffers.take(handle.0)?;
|
||||
self.staging_frames -= buffer.frames.len();
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
fn apply_commands(&mut self) -> Result<()> {
|
||||
while let Some(pending) = self.commands.pop_front() {
|
||||
match pending.command {
|
||||
Command::Control(control) => {
|
||||
let stream = self.streams.get(pending.stream.0)?;
|
||||
match control {
|
||||
Control::Gain(gain) => stream.gain = gain,
|
||||
Control::Mute(muted) => stream.muted = muted,
|
||||
Control::StartAt(frame) => stream.start_at = Some(frame),
|
||||
Control::Pause => stream.start_at = None,
|
||||
}
|
||||
}
|
||||
Command::Buffer(handle) => {
|
||||
let buffer = self.take_buffer(handle)?;
|
||||
let stream = self.streams.get(pending.stream.0)?;
|
||||
stream.reserved -= buffer.frames.len();
|
||||
stream.samples.extend(buffer.frames);
|
||||
}
|
||||
}
|
||||
self.metrics.commands_applied = self.metrics.commands_applied.saturating_add(1);
|
||||
self.metrics.last_applied = Some(pending.ticket);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A session has one output clock and up to one active renderer.
|
||||
#[derive(Clone)]
|
||||
pub struct Session(Arc<Mutex<State>>);
|
||||
|
||||
impl Session {
|
||||
pub fn new(output: Format, limits: Limits) -> Result<Self> {
|
||||
limits.check()?;
|
||||
Ok(Self(Arc::new(Mutex::new(State {
|
||||
closed: false,
|
||||
renderer: false,
|
||||
output,
|
||||
limits,
|
||||
streams: Pool::new(limits.streams),
|
||||
buffers: Pool::new(limits.buffers),
|
||||
staging_frames: 0,
|
||||
commands: VecDeque::with_capacity(limits.commands),
|
||||
next_ticket: 0,
|
||||
metrics: Metrics::default(),
|
||||
}))))
|
||||
}
|
||||
|
||||
fn lock(&self) -> Result<MutexGuard<'_, State>> {
|
||||
self.0.lock().map_err(|_| AudioError::Poisoned)
|
||||
}
|
||||
|
||||
fn live(&self) -> Result<MutexGuard<'_, State>> {
|
||||
let state = self.lock()?;
|
||||
if state.closed {
|
||||
Err(AudioError::Closed)
|
||||
} else {
|
||||
Ok(state)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn output_format(&self) -> Result<Format> {
|
||||
Ok(self.live()?.output)
|
||||
}
|
||||
|
||||
pub fn stream_format(&self, stream: StreamHandle) -> Result<Format> {
|
||||
Ok(self.live()?.streams.get(stream.0)?.format)
|
||||
}
|
||||
|
||||
/// An upper bound for validation before guest memory is copied.
|
||||
pub fn max_pcm_bytes(&self, stream: StreamHandle, encoding: Encoding) -> Result<usize> {
|
||||
let mut state = self.live()?;
|
||||
let frames = state
|
||||
.limits
|
||||
.frames_per_stream
|
||||
.min(state.limits.staging_frames);
|
||||
let format = state.streams.get(stream.0)?.format;
|
||||
Ok(frames * encoding.frame_bytes(format.channels))
|
||||
}
|
||||
|
||||
/// Available source frames at the time of the call. Other producers can consume this capacity.
|
||||
pub fn available_pcm_frames(&self, stream: StreamHandle) -> Result<usize> {
|
||||
let mut state = self.live()?;
|
||||
let staging = state.limits.staging_frames - state.staging_frames;
|
||||
let capacity = state.limits.frames_per_stream;
|
||||
let stream = state.streams.get(stream.0)?;
|
||||
Ok(staging.min(capacity - stream.samples.len() - stream.reserved))
|
||||
}
|
||||
|
||||
pub fn open_stream(&self, format: Format) -> Result<StreamHandle> {
|
||||
let mut state = self.live()?;
|
||||
let capacity = state.limits.frames_per_stream;
|
||||
if capacity < 2 && !format.rate.is_multiple_of(state.output.rate) {
|
||||
return Err(AudioError::InvalidLimits);
|
||||
}
|
||||
if state.streams.0.iter().all(Option::is_some) {
|
||||
return Err(AudioError::StreamLimit);
|
||||
}
|
||||
state
|
||||
.streams
|
||||
.insert(
|
||||
Stream {
|
||||
format,
|
||||
samples: VecDeque::with_capacity(capacity),
|
||||
reserved: 0,
|
||||
phase: 0,
|
||||
gain: [1.0; 2],
|
||||
muted: false,
|
||||
start_at: Some(0),
|
||||
},
|
||||
AudioError::StreamLimit,
|
||||
)
|
||||
.map(StreamHandle)
|
||||
}
|
||||
|
||||
/// Cancel queued commands and retire every buffer owned by this stream.
|
||||
pub fn close_stream(&self, stream: StreamHandle) -> Result<()> {
|
||||
let mut state = self.live()?;
|
||||
state.streams.take(stream.0)?;
|
||||
let before = state.commands.len();
|
||||
state.commands.retain(|pending| pending.stream != stream);
|
||||
let cancelled = before - state.commands.len();
|
||||
state.metrics.commands_cancelled = state
|
||||
.metrics
|
||||
.commands_cancelled
|
||||
.saturating_add(cancelled as u64);
|
||||
let mut released = 0;
|
||||
for slot in &mut state.buffers.0 {
|
||||
if slot
|
||||
.as_ref()
|
||||
.is_some_and(|(_, buffer)| buffer.owner == stream)
|
||||
{
|
||||
released += slot.take().unwrap().1.frames.len();
|
||||
}
|
||||
}
|
||||
state.staging_frames -= released;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn close(&self) -> Result<()> {
|
||||
let mut state = self.lock()?;
|
||||
state.closed = true;
|
||||
state.metrics.commands_cancelled = state
|
||||
.metrics
|
||||
.commands_cancelled
|
||||
.saturating_add(state.commands.len() as u64);
|
||||
state.commands.clear();
|
||||
state.streams.clear();
|
||||
state.buffers.clear();
|
||||
state.staging_frames = 0;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn allocate_pcm(
|
||||
&self,
|
||||
stream: StreamHandle,
|
||||
encoding: Encoding,
|
||||
bytes: &[u8],
|
||||
) -> Result<BufferHandle> {
|
||||
let mut state = self.live()?;
|
||||
let channels = state.streams.get(stream.0)?.format.channels;
|
||||
let stride = encoding.frame_bytes(channels);
|
||||
if bytes.is_empty() || !bytes.len().is_multiple_of(stride) {
|
||||
return Err(AudioError::InvalidLength);
|
||||
}
|
||||
let count = bytes.len() / stride;
|
||||
if count > state.limits.frames_per_stream
|
||||
|| count > state.limits.staging_frames - state.staging_frames
|
||||
|| state.buffers.0.iter().all(Option::is_some)
|
||||
{
|
||||
state.metrics.buffer_overruns = state.metrics.buffer_overruns.saturating_add(1);
|
||||
return Err(AudioError::BufferBudget);
|
||||
}
|
||||
let frames = encoding
|
||||
.frames(channels, bytes)
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let handle = state.buffers.insert(
|
||||
Buffer {
|
||||
owner: stream,
|
||||
frames,
|
||||
queued: false,
|
||||
},
|
||||
AudioError::BufferBudget,
|
||||
)?;
|
||||
state.staging_frames += count;
|
||||
state.metrics.peak_staging_frames =
|
||||
state.metrics.peak_staging_frames.max(state.staging_frames);
|
||||
Ok(BufferHandle(handle))
|
||||
}
|
||||
|
||||
pub fn retire_buffer(&self, buffer: BufferHandle) -> Result<()> {
|
||||
let mut state = self.live()?;
|
||||
if state.buffers.get(buffer.0)?.queued {
|
||||
return Err(AudioError::BufferInFlight);
|
||||
}
|
||||
state.take_buffer(buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Transfer a staged PCM buffer to the queue. The next render retires the handle.
|
||||
pub fn submit_buffer(&self, stream: StreamHandle, buffer: BufferHandle) -> Result<u64> {
|
||||
let mut state = self.live()?;
|
||||
let buffer_slot = state.buffers.get(buffer.0)?;
|
||||
if buffer_slot.owner != stream {
|
||||
return Err(AudioError::WrongStream);
|
||||
}
|
||||
if buffer_slot.queued {
|
||||
return Err(AudioError::BufferInFlight);
|
||||
}
|
||||
let count = buffer_slot.frames.len();
|
||||
let limit = state.limits.frames_per_stream;
|
||||
let dest = state.streams.get(stream.0)?;
|
||||
if count > limit - dest.samples.len() - dest.reserved {
|
||||
state.metrics.buffer_overruns = state.metrics.buffer_overruns.saturating_add(1);
|
||||
return Err(AudioError::BufferBudget);
|
||||
}
|
||||
let ticket = state.reserve_command()?;
|
||||
state.streams.get(stream.0)?.reserved += count;
|
||||
state.buffers.get(buffer.0)?.queued = true;
|
||||
state.commands.push_back(Pending {
|
||||
ticket,
|
||||
stream,
|
||||
command: Command::Buffer(buffer),
|
||||
});
|
||||
Ok(ticket)
|
||||
}
|
||||
|
||||
pub fn submit_pcm(
|
||||
&self,
|
||||
stream: StreamHandle,
|
||||
encoding: Encoding,
|
||||
bytes: &[u8],
|
||||
) -> Result<u64> {
|
||||
let handle = self.allocate_pcm(stream, encoding, bytes)?;
|
||||
let result = self.submit_buffer(stream, handle);
|
||||
if result.is_err() {
|
||||
// A concurrent close may already have retired the allocation.
|
||||
let _ = self.retire_buffer(handle);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn control(&self, stream: StreamHandle, control: Control) -> Result<u64> {
|
||||
if let Control::Gain(gain) = control
|
||||
&& !gain.into_iter().all(|gain| (0.0..=4.0).contains(&gain))
|
||||
{
|
||||
return Err(AudioError::InvalidGain);
|
||||
}
|
||||
let mut state = self.live()?;
|
||||
state.streams.get(stream.0)?;
|
||||
let ticket = state.reserve_command()?;
|
||||
state.commands.push_back(Pending {
|
||||
ticket,
|
||||
stream,
|
||||
command: Command::Control(control),
|
||||
});
|
||||
Ok(ticket)
|
||||
}
|
||||
|
||||
pub fn renderer(&self) -> Result<Renderer> {
|
||||
let mut state = self.live()?;
|
||||
if state.renderer {
|
||||
return Err(AudioError::RendererBusy);
|
||||
}
|
||||
state.renderer = true;
|
||||
Ok(Renderer(self.clone()))
|
||||
}
|
||||
|
||||
pub fn metrics(&self) -> Result<Metrics> {
|
||||
let state = self.lock()?;
|
||||
let mut metrics = state.metrics;
|
||||
metrics.live_streams = state.streams.0.iter().flatten().count();
|
||||
metrics.live_buffers = state.buffers.0.iter().flatten().count();
|
||||
metrics.pending_commands = state.commands.len();
|
||||
metrics.buffered_source_frames = state.staging_frames
|
||||
+ state
|
||||
.streams
|
||||
.0
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|(_, stream)| stream.samples.len())
|
||||
.sum::<usize>();
|
||||
metrics.reserved_sample_bytes = std::mem::size_of::<Frame>()
|
||||
* (state
|
||||
.streams
|
||||
.0
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|(_, stream)| stream.samples.capacity())
|
||||
.sum::<usize>()
|
||||
+ state
|
||||
.buffers
|
||||
.0
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|(_, buffer)| buffer.frames.capacity())
|
||||
.sum::<usize>());
|
||||
Ok(metrics)
|
||||
}
|
||||
}
|
||||
|
||||
/// Exclusive sink for deterministic offline output or native playback.
|
||||
pub struct Renderer(Session);
|
||||
|
||||
impl Renderer {
|
||||
/// Apply pending commands in ticket order, then render consecutive interleaved FP32 frames.
|
||||
pub fn render(&mut self, out: &mut [f32]) -> Result<()> {
|
||||
let mut state = self.0.live()?;
|
||||
let output = state.output;
|
||||
let channels = output.channels.count();
|
||||
if out.is_empty()
|
||||
|| !out.len().is_multiple_of(channels)
|
||||
|| out.len() / channels > state.limits.render_frames
|
||||
{
|
||||
return Err(AudioError::InvalidLength);
|
||||
}
|
||||
let start = state.metrics.output_frames;
|
||||
let end = start
|
||||
.checked_add((out.len() / channels) as u64)
|
||||
.ok_or(AudioError::ClockOverflow)?;
|
||||
state.apply_commands()?;
|
||||
let mut underruns = 0;
|
||||
for (clock, dest) in (start..end).zip(out.chunks_exact_mut(channels)) {
|
||||
let mut mixed = [0.0f64; 2];
|
||||
for (_, stream) in state.streams.0.iter_mut().flatten() {
|
||||
if stream.start_at.is_none_or(|frame| frame > clock) {
|
||||
continue;
|
||||
}
|
||||
let Some(frame) = stream.next(output.rate) else {
|
||||
underruns += 1;
|
||||
continue;
|
||||
};
|
||||
if stream.muted {
|
||||
continue;
|
||||
}
|
||||
if channels == 1 {
|
||||
mixed[0] += (f64::from(frame[0]) + f64::from(frame[1]))
|
||||
* 0.5
|
||||
* f64::from(stream.gain[0]);
|
||||
} else {
|
||||
for channel in 0..2 {
|
||||
mixed[channel] +=
|
||||
f64::from(frame[channel]) * f64::from(stream.gain[channel]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (dest, value) in dest.iter_mut().zip(mixed) {
|
||||
*dest = value.clamp(-1.0, 1.0) as f32;
|
||||
}
|
||||
}
|
||||
state.metrics.output_frames = end;
|
||||
state.metrics.underrun_stream_frames = state
|
||||
.metrics
|
||||
.underrun_stream_frames
|
||||
.saturating_add(underruns);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Renderer {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(mut state) = self.0.lock() {
|
||||
state.renderer = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Adapters for explicitly authored Xenora workloads and the Gate 6 PCM queue.
|
||||
//! Retail guest imports remain outside this module.
|
||||
|
||||
use crate::{AudioError, Channels, Control, Encoding, Format, Session, StreamHandle};
|
||||
use xenora_ffi::{AudioSubsystem, XENORA_AUDIO_FORMAT_PCM_F32LE, XENORA_AUDIO_FORMAT_PCM_S16LE};
|
||||
use xenora_loader::cpu::ExitReason;
|
||||
use xenora_loader::import_table::ImportName;
|
||||
use xenora_loader::imports::{ImportRegistry, RegistryError, ServiceStatus};
|
||||
use xenora_loader::runtime::Call;
|
||||
|
||||
pub const MODULE: &str = "xenora_audio_fixture.dll";
|
||||
pub const SUBMIT_PCM: &str = "SubmitPcm";
|
||||
pub const SCHEDULE_START: &str = "ScheduleStart";
|
||||
pub const OK: u64 = 0;
|
||||
pub const INVALID_HANDLE: u64 = 1;
|
||||
pub const INVALID_DATA: u64 = 2;
|
||||
pub const RESOURCE_EXHAUSTED: u64 = 3;
|
||||
pub const SESSION_ERROR: u64 = 4;
|
||||
|
||||
/// Transfer whole Gate 6 frames using its existing PCM storage and format.
|
||||
pub fn transfer_gate6(
|
||||
audio: &mut AudioSubsystem,
|
||||
session: &Session,
|
||||
stream: StreamHandle,
|
||||
frame_limit: usize,
|
||||
) -> crate::Result<usize> {
|
||||
let channels = match audio.channels {
|
||||
1 => Channels::Mono,
|
||||
2 => Channels::Stereo,
|
||||
_ => return Err(AudioError::InvalidFormat),
|
||||
};
|
||||
let format = Format::new(audio.sample_rate, channels)?;
|
||||
if format != session.stream_format(stream)? {
|
||||
return Err(AudioError::InvalidFormat);
|
||||
}
|
||||
let encoding = match audio.format {
|
||||
XENORA_AUDIO_FORMAT_PCM_S16LE => Encoding::S16Le,
|
||||
XENORA_AUDIO_FORMAT_PCM_F32LE => Encoding::F32Le,
|
||||
_ => return Err(AudioError::InvalidFormat),
|
||||
};
|
||||
let stride = encoding.frame_bytes(channels);
|
||||
if !audio.queue.len().is_multiple_of(stride) {
|
||||
return Err(AudioError::InvalidLength);
|
||||
}
|
||||
let count = frame_limit
|
||||
.min(audio.queue.len() / stride)
|
||||
.min(session.available_pcm_frames(stream)?);
|
||||
if count != 0 {
|
||||
let bytes = count * stride;
|
||||
session.submit_pcm(stream, encoding, &audio.queue.make_contiguous()[..bytes])?;
|
||||
audio.queue.drain(..bytes);
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// Register the documented Xenora synthetic ABI for a single session.
|
||||
/// Existing handlers are never replaced.
|
||||
pub fn register_fixture_services(
|
||||
registry: &mut ImportRegistry,
|
||||
session: &Session,
|
||||
) -> Result<(), RegistryError> {
|
||||
for symbol in [SUBMIT_PCM, SCHEDULE_START] {
|
||||
if registry.has_binding(MODULE, symbol) {
|
||||
return Err(RegistryError::Duplicate {
|
||||
module: MODULE.into(),
|
||||
symbol: symbol.into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let output = session.clone();
|
||||
registry.try_register(
|
||||
MODULE,
|
||||
ImportName::Name(SUBMIT_PCM.into()),
|
||||
ServiceStatus::Implemented,
|
||||
Box::new(move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let stream = StreamHandle::from_raw(call.u64(0)?);
|
||||
let address = call.u64(1)?;
|
||||
let length = call.u64(2)? as usize;
|
||||
let encoding = match call.u32(3)? {
|
||||
1 => Encoding::S16Le,
|
||||
2 => Encoding::F32Le,
|
||||
_ => return Ok(INVALID_DATA),
|
||||
};
|
||||
let limit = match output.max_pcm_bytes(stream, encoding) {
|
||||
Ok(limit) => limit,
|
||||
Err(err) => return Ok(error_status(err)),
|
||||
};
|
||||
let format = match output.stream_format(stream) {
|
||||
Ok(format) => format,
|
||||
Err(err) => return Ok(error_status(err)),
|
||||
};
|
||||
let alignment = match encoding {
|
||||
Encoding::S16Le => 2,
|
||||
Encoding::F32Le => 4,
|
||||
};
|
||||
if address == 0
|
||||
|| !address.is_multiple_of(alignment)
|
||||
|| length == 0
|
||||
|| !length.is_multiple_of(encoding.frame_bytes(format.channels()))
|
||||
|| length > limit
|
||||
{
|
||||
return Ok(INVALID_DATA);
|
||||
}
|
||||
let mut bytes = vec![0; length];
|
||||
memory
|
||||
.read_bytes(address, &mut bytes)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
Ok(output
|
||||
.submit_pcm(stream, encoding, &bytes)
|
||||
.map_or_else(error_status, |_| OK))
|
||||
}),
|
||||
)?;
|
||||
|
||||
let output = session.clone();
|
||||
registry.try_register(
|
||||
MODULE,
|
||||
ImportName::Name(SCHEDULE_START.into()),
|
||||
ServiceStatus::Implemented,
|
||||
Box::new(move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let stream = StreamHandle::from_raw(call.u64(0)?);
|
||||
let frame = call.u64(1)?;
|
||||
Ok(output
|
||||
.control(stream, Control::StartAt(frame))
|
||||
.map_or_else(error_status, |_| OK))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn error_status(error: AudioError) -> u64 {
|
||||
match error {
|
||||
AudioError::InvalidHandle | AudioError::WrongStream => INVALID_HANDLE,
|
||||
AudioError::InvalidFormat
|
||||
| AudioError::InvalidLength
|
||||
| AudioError::InvalidSample
|
||||
| AudioError::InvalidGain
|
||||
| AudioError::InvalidLimits => INVALID_DATA,
|
||||
AudioError::QueueFull | AudioError::BufferBudget | AudioError::StreamLimit => {
|
||||
RESOURCE_EXHAUSTED
|
||||
}
|
||||
_ => SESSION_ERROR,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::thread;
|
||||
use xenora_audio_dsp::{AudioError, Channels::*, Control, Encoding::*, Format, Limits, Session};
|
||||
|
||||
fn s16(samples: &[i16]) -> Vec<u8> {
|
||||
samples
|
||||
.iter()
|
||||
.flat_map(|sample| sample.to_le_bytes())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fp(samples: &[f32]) -> Vec<u8> {
|
||||
samples
|
||||
.iter()
|
||||
.flat_map(|sample| sample.to_le_bytes())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pcm_value(sample: i16) -> f32 {
|
||||
f32::from(sample) / 32768.0
|
||||
}
|
||||
|
||||
fn verify_s16(actual: &[f32], expected: &[i16]) {
|
||||
assert_eq!(actual.len(), expected.len());
|
||||
for (&actual, &expected) in actual.iter().zip(expected) {
|
||||
assert!(
|
||||
(actual - pcm_value(expected)).abs() < 0.000_002,
|
||||
"{actual} != {expected}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixer_clips_after_accumulation_and_downmixes_stereo() {
|
||||
let out = Format::new(48_000, Mono).unwrap();
|
||||
let dsp = Session::new(out, Limits::default()).unwrap();
|
||||
let a = dsp.open_stream(out).unwrap();
|
||||
let b = dsp.open_stream(out).unwrap();
|
||||
let c = dsp
|
||||
.open_stream(Format::new(48_000, Stereo).unwrap())
|
||||
.unwrap();
|
||||
dsp.submit_pcm(a, S16Le, &s16(&[30000, -30000, 30000, 30000]))
|
||||
.unwrap();
|
||||
dsp.submit_pcm(b, S16Le, &s16(&[10000, -10000, 30000, 0]))
|
||||
.unwrap();
|
||||
dsp.submit_pcm(c, S16Le, &s16(&[0, 0, 0, 0, -30000, -30000, 32767, -32767]))
|
||||
.unwrap();
|
||||
let mut result = [0.0; 4];
|
||||
dsp.renderer().unwrap().render(&mut result).unwrap();
|
||||
assert_eq!(result[0], 1.0);
|
||||
verify_s16(&result[1..], &[-32768, 30000, 30000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rational_resampler_continues_across_chunks_and_releases_the_last_frame() {
|
||||
let dsp = Session::new(Format::new(48_000, Stereo).unwrap(), Limits::default()).unwrap();
|
||||
let stream = dsp.open_stream(Format::new(32_000, Mono).unwrap()).unwrap();
|
||||
dsp.submit_pcm(stream, S16Le, &s16(&[0, 3000])).unwrap();
|
||||
let mut render = dsp.renderer().unwrap();
|
||||
let mut first = [0.0; 4];
|
||||
render.render(&mut first).unwrap();
|
||||
dsp.submit_pcm(stream, S16Le, &s16(&[6000, 9000, 12000]))
|
||||
.unwrap();
|
||||
let mut second = [0.0; 10];
|
||||
render.render(&mut second).unwrap();
|
||||
verify_s16(&first, &[0, 0, 2000, 2000]);
|
||||
verify_s16(
|
||||
&second,
|
||||
&[
|
||||
4000, 4000, 6000, 6000, 8000, 8000, 10000, 10000, 12000, 12000,
|
||||
],
|
||||
);
|
||||
let mut silence = [1.0; 2];
|
||||
render.render(&mut silence).unwrap();
|
||||
assert_eq!(silence, [0.0; 2]);
|
||||
assert_eq!(dsp.metrics().unwrap().underrun_stream_frames, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stereo_downsampling_keeps_channels_independent() {
|
||||
let dsp = Session::new(Format::new(32_000, Stereo).unwrap(), Limits::default()).unwrap();
|
||||
let stream = dsp
|
||||
.open_stream(Format::new(48_000, Stereo).unwrap())
|
||||
.unwrap();
|
||||
dsp.submit_pcm(
|
||||
stream,
|
||||
S16Le,
|
||||
&s16(&[
|
||||
0, 12000, 2000, 8000, 4000, 4000, 6000, 0, 8000, -4000, 10000, -8000, 12000, -12000,
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let mut result = [0.0; 10];
|
||||
dsp.renderer().unwrap().render(&mut result).unwrap();
|
||||
verify_s16(
|
||||
&result,
|
||||
&[0, 12000, 3000, 6000, 6000, 0, 9000, -6000, 12000, -12000],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_partition_does_not_change_the_offline_output() {
|
||||
let input = s16(&(0..1024).collect::<Vec<_>>());
|
||||
let capture = |blocks: &[usize]| {
|
||||
let dsp = Session::new(Format::new(48_000, Mono).unwrap(), Limits::default()).unwrap();
|
||||
let stream = dsp.open_stream(Format::new(44_100, Mono).unwrap()).unwrap();
|
||||
dsp.submit_pcm(stream, S16Le, &input).unwrap();
|
||||
let mut render = dsp.renderer().unwrap();
|
||||
let mut output = vec![0.0; blocks.iter().sum()];
|
||||
let mut at = 0;
|
||||
for &size in blocks {
|
||||
render.render(&mut output[at..at + size]).unwrap();
|
||||
at += size;
|
||||
}
|
||||
output
|
||||
};
|
||||
let output = capture(&[1000]);
|
||||
assert_eq!(output, capture(&[37, 128, 3, 789, 43]));
|
||||
for k in 0..=6 {
|
||||
assert_eq!(output[k * 160], pcm_value((k * 147) as i16));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_streams_start_on_the_same_clock() {
|
||||
let format = Format::new(48_000, Mono).unwrap();
|
||||
let dsp = Session::new(format, Limits::default()).unwrap();
|
||||
for (start, samples) in [(1, &[1000, 2000][..]), (2, &[4000, 8000]), (6, &[16000])] {
|
||||
let stream = dsp.open_stream(format).unwrap();
|
||||
dsp.control(stream, Control::StartAt(start)).unwrap();
|
||||
dsp.submit_pcm(stream, S16Le, &s16(samples)).unwrap();
|
||||
}
|
||||
let mut output = [0.0; 8];
|
||||
dsp.renderer().unwrap().render(&mut output).unwrap();
|
||||
verify_s16(&output, &[0, 1000, 6000, 8000, 0, 0, 16000, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_controls_apply_before_the_block_and_pause_holds_samples() {
|
||||
let format = Format::new(48_000, Stereo).unwrap();
|
||||
let dsp = Session::new(format, Limits::default()).unwrap();
|
||||
let stream = dsp.open_stream(format).unwrap();
|
||||
assert_eq!(dsp.control(stream, Control::Mute(true)), Ok(0));
|
||||
assert_eq!(dsp.control(stream, Control::Pause), Ok(1));
|
||||
assert_eq!(
|
||||
dsp.submit_pcm(stream, F32Le, &fp(&[0.75, -0.5, 0.5, 0.25])),
|
||||
Ok(2)
|
||||
);
|
||||
let mut render = dsp.renderer().unwrap();
|
||||
let mut out = [90.0; 2];
|
||||
render.render(&mut out).unwrap();
|
||||
assert_eq!(out, [0.0; 2]);
|
||||
assert_eq!(dsp.metrics().unwrap().buffered_source_frames, 2);
|
||||
dsp.control(stream, Control::Mute(false)).unwrap();
|
||||
dsp.control(stream, Control::Gain([0.5, 0.25])).unwrap();
|
||||
dsp.control(stream, Control::StartAt(1)).unwrap();
|
||||
render.render(&mut out).unwrap();
|
||||
assert_eq!(out, [0.375, -0.125]);
|
||||
assert_eq!(dsp.metrics().unwrap().last_applied, Some(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_foreign_and_wrong_stream_handles_are_rejected() {
|
||||
let format = Format::new(48_000, Mono).unwrap();
|
||||
let dsp = Session::new(format, Limits::default()).unwrap();
|
||||
let other = Session::new(format, Limits::default()).unwrap();
|
||||
let stream = dsp.open_stream(format).unwrap();
|
||||
let peer = dsp.open_stream(format).unwrap();
|
||||
let outside = other.open_stream(format).unwrap();
|
||||
let buffer = dsp.allocate_pcm(stream, S16Le, &s16(&[1])).unwrap();
|
||||
assert_eq!(
|
||||
dsp.submit_buffer(peer, buffer),
|
||||
Err(AudioError::WrongStream)
|
||||
);
|
||||
assert_eq!(
|
||||
dsp.control(outside, Control::Pause),
|
||||
Err(AudioError::InvalidHandle)
|
||||
);
|
||||
dsp.submit_buffer(stream, buffer).unwrap();
|
||||
assert_eq!(dsp.retire_buffer(buffer), Err(AudioError::BufferInFlight));
|
||||
dsp.renderer().unwrap().render(&mut [0.0]).unwrap();
|
||||
assert_eq!(dsp.retire_buffer(buffer), Err(AudioError::InvalidHandle));
|
||||
dsp.close_stream(stream).unwrap();
|
||||
let replacement = dsp.open_stream(format).unwrap();
|
||||
assert_ne!(stream, replacement);
|
||||
assert_eq!(dsp.stream_format(stream), Err(AudioError::InvalidHandle));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_frames_and_overruns_leave_existing_audio_intact() {
|
||||
let format = Format::new(48_000, Mono).unwrap();
|
||||
let limits = Limits {
|
||||
streams: 1,
|
||||
frames_per_stream: 2,
|
||||
commands: 1,
|
||||
..Limits::default()
|
||||
};
|
||||
let dsp = Session::new(format, limits).unwrap();
|
||||
let stream = dsp.open_stream(format).unwrap();
|
||||
assert_eq!(dsp.open_stream(format), Err(AudioError::StreamLimit));
|
||||
assert_eq!(
|
||||
dsp.submit_pcm(stream, S16Le, &[1]),
|
||||
Err(AudioError::InvalidLength)
|
||||
);
|
||||
assert_eq!(
|
||||
dsp.submit_pcm(stream, F32Le, &fp(&[f32::NAN])),
|
||||
Err(AudioError::InvalidSample)
|
||||
);
|
||||
dsp.submit_pcm(stream, S16Le, &s16(&[1000])).unwrap();
|
||||
assert_eq!(
|
||||
dsp.submit_pcm(stream, S16Le, &s16(&[2000])),
|
||||
Err(AudioError::QueueFull)
|
||||
);
|
||||
assert_eq!(
|
||||
dsp.submit_pcm(stream, S16Le, &s16(&[3000, 4000])),
|
||||
Err(AudioError::BufferBudget)
|
||||
);
|
||||
let mut out = [0.0; 2];
|
||||
dsp.renderer().unwrap().render(&mut out).unwrap();
|
||||
verify_s16(&out, &[1000, 0]);
|
||||
let metrics = dsp.metrics().unwrap();
|
||||
assert_eq!(metrics.command_overruns, 1);
|
||||
assert_eq!(metrics.buffer_overruns, 1);
|
||||
assert_eq!(metrics.underrun_stream_frames, 1);
|
||||
assert_eq!(metrics.live_buffers, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_producers_render_in_ticket_order() {
|
||||
let format = Format::new(48_000, Mono).unwrap();
|
||||
let dsp = Session::new(format, Limits::default()).unwrap();
|
||||
let stream = dsp.open_stream(format).unwrap();
|
||||
let mut receipts = thread::scope(|scope| {
|
||||
(1..=16)
|
||||
.map(|sample| {
|
||||
let dsp = &dsp;
|
||||
scope.spawn(move || {
|
||||
(
|
||||
dsp.submit_pcm(stream, S16Le, &s16(&[sample])).unwrap(),
|
||||
sample,
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
.map(|thread| thread.join().unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
receipts.sort_unstable();
|
||||
let expected = receipts
|
||||
.into_iter()
|
||||
.map(|(_, sample)| sample)
|
||||
.collect::<Vec<_>>();
|
||||
let mut output = [0.0; 16];
|
||||
dsp.renderer().unwrap().render(&mut output).unwrap();
|
||||
verify_s16(&output, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_releases_reservations_in_one_hundred_cycles() {
|
||||
let format = Format::new(48_000, Mono).unwrap();
|
||||
for _ in 0..100 {
|
||||
let dsp = Session::new(format, Limits::default()).unwrap();
|
||||
let stream = dsp.open_stream(format).unwrap();
|
||||
let staged = dsp.allocate_pcm(stream, S16Le, &s16(&[1, 2])).unwrap();
|
||||
dsp.submit_pcm(stream, S16Le, &s16(&[3])).unwrap();
|
||||
let mut render = dsp.renderer().unwrap();
|
||||
assert!(matches!(dsp.renderer(), Err(AudioError::RendererBusy)));
|
||||
dsp.close_stream(stream).unwrap();
|
||||
assert_eq!(dsp.retire_buffer(staged), Err(AudioError::InvalidHandle));
|
||||
assert_eq!(dsp.metrics().unwrap().commands_cancelled, 1);
|
||||
dsp.close().unwrap();
|
||||
dsp.close().unwrap();
|
||||
assert_eq!(render.render(&mut [0.0]), Err(AudioError::Closed));
|
||||
let metrics = dsp.metrics().unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
metrics.live_streams,
|
||||
metrics.live_buffers,
|
||||
metrics.pending_commands,
|
||||
metrics.reserved_sample_bytes,
|
||||
metrics.buffered_source_frames
|
||||
),
|
||||
(0, 0, 0, 0, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fractional_resampling_refuses_a_one_frame_capacity() {
|
||||
let output = Format::new(48_000, Mono).unwrap();
|
||||
let limits = Limits {
|
||||
frames_per_stream: 1,
|
||||
..Limits::default()
|
||||
};
|
||||
let dsp = Session::new(output, limits).unwrap();
|
||||
assert_eq!(
|
||||
dsp.open_stream(Format::new(32_000, Mono).unwrap()),
|
||||
Err(AudioError::InvalidLimits)
|
||||
);
|
||||
assert_eq!(
|
||||
dsp.open_stream(Format::new(72_000, Mono).unwrap()),
|
||||
Err(AudioError::InvalidLimits)
|
||||
);
|
||||
let matching = dsp.open_stream(output).unwrap();
|
||||
dsp.submit_pcm(matching, S16Le, &s16(&[1000])).unwrap();
|
||||
let mut result = [0.0];
|
||||
dsp.renderer().unwrap().render(&mut result).unwrap();
|
||||
verify_s16(&result, &[1000]);
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
|
||||
#[test]
|
||||
fn coreaudio_rejects_a_short_block_before_touching_the_dsp() {
|
||||
use xenora_audio_dsp::coreaudio::{Playback, PlaybackError};
|
||||
let output = Format::new(192_000, Stereo).unwrap();
|
||||
let dsp = Session::new(output, Limits::default()).unwrap();
|
||||
let stream = dsp.open_stream(output).unwrap();
|
||||
dsp.submit_pcm(stream, S16Le, &s16(&[1000, 2000])).unwrap();
|
||||
assert!(matches!(
|
||||
Playback::start(&dsp, 64),
|
||||
Err(PlaybackError::InvalidBlockSize)
|
||||
));
|
||||
assert_eq!(dsp.metrics().unwrap().output_frames, 0);
|
||||
let mut samples = [0.0; 2];
|
||||
dsp.renderer().unwrap().render(&mut samples).unwrap();
|
||||
verify_s16(&samples, &[1000, 2000]);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#![cfg(feature = "xenora")]
|
||||
|
||||
use xenora_audio_dsp::{Channels, Format, Limits, Session, xenora::*};
|
||||
use xenora_ffi::{AudioSubsystem, XENORA_AUDIO_FORMAT_PCM_S16LE};
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::imports::{ImportRegistry, Win64Args};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
#[test]
|
||||
fn guest_registry_checks_ranges_handles_and_frame_atomicity() {
|
||||
let format = Format::new(48_000, Channels::Stereo).unwrap();
|
||||
let dsp = Session::new(format, Limits::default()).unwrap();
|
||||
let stream = dsp.open_stream(format).unwrap();
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_fixture_services(&mut registry, &dsp).unwrap();
|
||||
assert!(register_fixture_services(&mut registry, &dsp).is_err());
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
0x1000,
|
||||
4096,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&[0, 0x80, 0xff, 0x7f],
|
||||
)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::default();
|
||||
cpu.set(Register::Rcx, stream.raw());
|
||||
cpu.set(Register::Rdx, 0x1000);
|
||||
cpu.set(Register::R8, 3);
|
||||
cpu.set(Register::R9, 1);
|
||||
let submit = registry.binding(MODULE, SUBMIT_PCM).unwrap();
|
||||
assert_eq!(
|
||||
(submit.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory),
|
||||
Ok(INVALID_DATA)
|
||||
);
|
||||
cpu.set(Register::R8, 4);
|
||||
cpu.set(Register::Rdx, 0x1ffe);
|
||||
assert!(matches!(
|
||||
(submit.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory),
|
||||
Err(ExitReason::MemoryFault(_))
|
||||
));
|
||||
assert_eq!(dsp.metrics().unwrap().pending_commands, 0);
|
||||
cpu.set(Register::Rdx, 0x1000);
|
||||
assert_eq!(
|
||||
(submit.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory),
|
||||
Ok(OK)
|
||||
);
|
||||
let mut pcm = [0.0; 2];
|
||||
dsp.renderer().unwrap().render(&mut pcm).unwrap();
|
||||
assert_eq!(pcm, [-1.0, 32767.0 / 32768.0]);
|
||||
dsp.close_stream(stream).unwrap();
|
||||
assert_eq!(
|
||||
(submit.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory),
|
||||
Ok(INVALID_HANDLE)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gate6_transfer_reuses_processed_pcm_and_preserves_failed_submission() {
|
||||
let format = Format::new(48_000, Channels::Mono).unwrap();
|
||||
let dsp = Session::new(
|
||||
format,
|
||||
Limits {
|
||||
commands: 1,
|
||||
..Limits::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let stream = dsp.open_stream(format).unwrap();
|
||||
let mut gate = AudioSubsystem {
|
||||
channels: 1,
|
||||
volume: 0.5,
|
||||
format: XENORA_AUDIO_FORMAT_PCM_S16LE,
|
||||
..AudioSubsystem::default()
|
||||
};
|
||||
gate.submit(&[0, 0x40, 0, 0xc0]);
|
||||
assert_eq!(transfer_gate6(&mut gate, &dsp, stream, 1), Ok(1));
|
||||
assert!(transfer_gate6(&mut gate, &dsp, stream, 1).is_err());
|
||||
assert_eq!(gate.queue.len(), 2);
|
||||
let mut render = dsp.renderer().unwrap();
|
||||
let mut output = [0.0];
|
||||
render.render(&mut output).unwrap();
|
||||
assert_eq!(output, [0.25]);
|
||||
assert_eq!(transfer_gate6(&mut gate, &dsp, stream, 1), Ok(1));
|
||||
render.render(&mut output).unwrap();
|
||||
assert_eq!(output, [-0.25]);
|
||||
assert!(gate.queue.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gate6_transfer_makes_progress_with_a_held_interpolation_frame() {
|
||||
let output = Format::new(48_000, Channels::Mono).unwrap();
|
||||
let limits = Limits {
|
||||
frames_per_stream: 2,
|
||||
..Limits::default()
|
||||
};
|
||||
let dsp = Session::new(output, limits).unwrap();
|
||||
let stream = dsp
|
||||
.open_stream(Format::new(32_000, Channels::Mono).unwrap())
|
||||
.unwrap();
|
||||
let mut gate = AudioSubsystem {
|
||||
channels: 1,
|
||||
sample_rate: 32_000,
|
||||
..AudioSubsystem::default()
|
||||
};
|
||||
gate.submit(&[0, 0, 0, 0x30, 0, 0x60]);
|
||||
assert_eq!(transfer_gate6(&mut gate, &dsp, stream, 1), Ok(1));
|
||||
let mut render = dsp.renderer().unwrap();
|
||||
let mut output = [1.0];
|
||||
render.render(&mut output).unwrap();
|
||||
assert_eq!(output, [0.0]);
|
||||
assert_eq!(transfer_gate6(&mut gate, &dsp, stream, 2), Ok(1));
|
||||
render.render(&mut output).unwrap();
|
||||
assert_eq!(output, [0.25]);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x00000000
|
||||
000c: t2 = wave.mask v_cmp_eq_u32_e32 t1, t0 exec=0xffffffff
|
||||
0010: t3 = const.u32 0xffffffff
|
||||
0010: t4 = vcc.Select t3, t0, t2
|
||||
0014: t5 = const.u32 0x00000001
|
||||
0014: t6 = vcc.AddCarry.flag t5, t4, t2
|
||||
0014: t7 = wave.carry t6 exec=0xffffffff
|
||||
0014: t8 = vcc.AddCarry t5, t4, t2
|
||||
0018: t9 = const.u32 0x00000000
|
||||
0018: t10 = vcc.SubtractBorrow.flag t9, t8, t7
|
||||
0018: t11 = wave.carry t10 exec=0xffffffff
|
||||
0018: t12 = vcc.SubtractBorrow t9, t8, t7
|
||||
001c: t13 = const.u32 0xfffffffe
|
||||
001c: t14 = vcc.SubtractBorrow.flag t12, t13, t11
|
||||
001c: t15 = wave.carry t14 exec=0xffffffff
|
||||
001c: t16 = vcc.SubtractBorrow t12, t13, t11
|
||||
0024: store.u32 output[index], t15
|
||||
@@ -0,0 +1,63 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]],
|
||||
uint grid [[threads_per_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t1 = 0x00000000u;
|
||||
uint t2 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint pass = (t1 == l0) ? 1u : 0u;
|
||||
t2 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t3 = 0xffffffffu;
|
||||
uint t4 = ((t2 >> (index & 31u)) & 1u) != 0u ? t0 : t3;
|
||||
uint t5 = 0x00000001u;
|
||||
uint t6 = uint((ulong(t5) + ulong(t4) + ((t2 >> (index & 31u)) & 1u)) >> 32u);
|
||||
uint t7 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint l4 = ((t2 >> lane) & 1u) != 0u ? l0 : t3;
|
||||
uint l6 = uint((ulong(t5) + ulong(l4) + ((t2 >> lane) & 1u)) >> 32u);
|
||||
uint pass = l6;
|
||||
t7 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t8 = t5 + t4 + ((t2 >> (index & 31u)) & 1u);
|
||||
uint t9 = 0x00000000u;
|
||||
uint t10 = uint(ulong(t8) + ((t7 >> (index & 31u)) & 1u) > ulong(t9));
|
||||
uint t11 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint l4 = ((t2 >> lane) & 1u) != 0u ? l0 : t3;
|
||||
uint l8 = t5 + l4 + ((t2 >> lane) & 1u);
|
||||
uint l10 = uint(ulong(l8) + ((t7 >> lane) & 1u) > ulong(t9));
|
||||
uint pass = l10;
|
||||
t11 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t12 = t9 - t8 - ((t7 >> (index & 31u)) & 1u);
|
||||
uint t13 = 0xfffffffeu;
|
||||
uint t14 = uint(ulong(t13) + ((t11 >> (index & 31u)) & 1u) > ulong(t12));
|
||||
uint t15 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint l0 = input[lane_index];
|
||||
uint l4 = ((t2 >> lane) & 1u) != 0u ? l0 : t3;
|
||||
uint l8 = t5 + l4 + ((t2 >> lane) & 1u);
|
||||
uint l12 = t9 - l8 - ((t7 >> lane) & 1u);
|
||||
uint l14 = uint(ulong(t13) + ((t11 >> lane) & 1u) > ulong(l12));
|
||||
uint pass = l14;
|
||||
t15 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t16 = t12 - t13 - ((t11 >> (index & 31u)) & 1u);
|
||||
output[index] = t15;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Encoding inventory for Wave32 16-bit VOPC compares (guide Table 61).
|
||||
// Operand and execution cases are in tests/validation/tests/vopc_wide.rs.
|
||||
.text
|
||||
buffer_load_dword v2, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
v_mov_b32_e32 v3, 7
|
||||
v_cmp_lt_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_eq_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_le_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_gt_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_ne_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_ge_i16_e32 vcc_lo, v2, v3
|
||||
v_cmp_lt_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_eq_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_le_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_gt_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_ne_u16_e32 vcc_lo, v2, v3
|
||||
v_cmp_ge_u16_e32 vcc_lo, v2, v3
|
||||
v_mov_b32_e32 v2, vcc_lo
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original Wave32 example. The compare derives VCC from the input, then each
|
||||
// carry/borrow feeds the next operation. Before reverse subtract, v3 is
|
||||
// 0xfffffffe for a zero input and 0xffffffff otherwise, with borrow-in 1.
|
||||
// Subtracting 0xfffffffe and the borrow-in sets the final VCC bit for zero inputs.
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
v_cmp_eq_u32_e32 vcc_lo, 0, v1
|
||||
v_cndmask_b32_e32 v2, -1, v1, vcc_lo
|
||||
v_add_co_ci_u32_e32 v2, vcc_lo, 1, v2, vcc_lo
|
||||
v_sub_co_ci_u32_e32 v3, vcc_lo, 0, v2, vcc_lo
|
||||
v_subrev_co_ci_u32_e32 v3, vcc_lo, -2, v3, vcc_lo
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
buffer_store_dword v4, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
@@ -12,7 +12,7 @@ case "${1:-}" in
|
||||
esac
|
||||
|
||||
for name in add bitwise-branch float-exact or shifts ashr \
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-unary vector-compare-64; do
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-vcc vector-unary vector-compare-64 vector-compare-16; do
|
||||
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
|
||||
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
|
||||
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
|
||||
|
||||
+1
-4
@@ -53,7 +53,4 @@ 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
|
||||
# Oracles whose translator side has not landed are skipped by name until it does
|
||||
# (#215: the PR that translates the forms removes its skip).
|
||||
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1 \
|
||||
--skip vopc16_match_the_guide_on_native_metal
|
||||
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
|
||||
@@ -771,12 +771,21 @@ class Validate(unittest.TestCase):
|
||||
text = gen.render(vectors(), snapshot())
|
||||
self.assertIn("pub enum VectorAluOp {", text)
|
||||
self.assertIn("if word & 0x8000_0000 != 0x0000_0000 {", text)
|
||||
self.assertIn("Self::MulI32I24 => VectorBinary::Mul24Signed,", text)
|
||||
self.assertIn("Self::SubrevNcU32 => VectorBinary::Sub,", text)
|
||||
self.assertIn("Self::MulI32I24 => VectorLowering::Binary(VectorBinary::Mul24Signed),", text)
|
||||
self.assertIn("Self::SubrevNcU32 => VectorLowering::Binary(VectorBinary::Sub),", text)
|
||||
self.assertIn("Self::SubrevNcU32 => true,", text.split("fn swaps_sources", 1)[1])
|
||||
self.assertIn('Self::AddU32 => "v_min_i32_e32",', text)
|
||||
self.assertIn("swap_sources: true,", text)
|
||||
|
||||
def test_vop2_vcc_requires_the_xml_input_and_output(self):
|
||||
reg = gen.load_registry()
|
||||
snap = gen.load_snapshot()
|
||||
operands = snap["variants"][("V_ADD_CO_CI_U32", "ENC_VOP2")]["operands"]
|
||||
operands[:] = [op for op in operands if not (op[2] == "OPR_VCC" and op[4])]
|
||||
self.rejects(reg, "V_ADD_CO_CI_U32: carry_in vcc requires one implicit XML VCC input", snap)
|
||||
form(reg, "V_CNDMASK_B32")["vcc"] = "lane_mask"
|
||||
self.rejects(reg, "V_CNDMASK_B32: vcc lane_mask contradicts rule vop2_vcc", snap)
|
||||
|
||||
def test_accepts_compares(self):
|
||||
self.assertEqual(self.errors(compares()), [])
|
||||
|
||||
@@ -1140,7 +1149,7 @@ class Validate(unittest.TestCase):
|
||||
|
||||
def test_rejects_unknown_signedness_carry_in_exec_and_wave(self):
|
||||
for key, value in (
|
||||
("signedness", "float"), ("carry_in", "vcc"), ("exec", "written"), ("wave", "wave64"),
|
||||
("signedness", "float"), ("carry_in", "exec"), ("exec", "written"), ("wave", "wave64"),
|
||||
):
|
||||
with self.subTest(key=key):
|
||||
reg = registry()
|
||||
|
||||
@@ -99,6 +99,7 @@ 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),
|
||||
VIntVcc(u32, u8, CmpSrc, u8),
|
||||
/// VOP1 integer opcode 55-59: VDST, SRC0.
|
||||
VUnary(u32, u8, CmpSrc),
|
||||
/// `v_swap_b32 vD, vS` (VOP1 opcode 101).
|
||||
@@ -232,6 +233,26 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
None
|
||||
})
|
||||
}
|
||||
Insn::VIntVcc(opcode, dst, src0, src1) => {
|
||||
if let Some(error) = first_error(&lanes) {
|
||||
return Err(error);
|
||||
}
|
||||
vector_vcc(
|
||||
&mut lanes,
|
||||
&sgpr,
|
||||
execution_mask,
|
||||
(opcode, dst, src0, src1),
|
||||
offset,
|
||||
)
|
||||
.map(|mask| {
|
||||
if opcode != 1 {
|
||||
sgpr[106] = Some(mask);
|
||||
sgpr[107] = None;
|
||||
vcc_lane_derived = execution_mask != 0;
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
Insn::SUnary(opcode, dst, src) => {
|
||||
if dst < 8 {
|
||||
Err(format!("{offset:#x}: write to a resource SGPR"))
|
||||
@@ -325,6 +346,60 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
Err(first_error(&lanes).unwrap_or_else(|| "stream ended without s_endpgm".to_string()))
|
||||
}
|
||||
|
||||
/// Guide 12.7 vector select and carry/borrow, with the Wave32 mask from 3.9.
|
||||
fn vector_vcc(
|
||||
lanes: &mut [Lane],
|
||||
sgpr: &[Option<u32>; 128],
|
||||
exec: u32,
|
||||
(opcode, dst, src0, src1): (u32, u8, CmpSrc, u8),
|
||||
offset: usize,
|
||||
) -> Result<u32, String> {
|
||||
if exec == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let incoming = sgpr[106].ok_or_else(|| format!("{offset:#x}: uninitialized vcc_lo"))?;
|
||||
let mut mask = 0;
|
||||
for (index, lane) in lanes.iter_mut().enumerate() {
|
||||
if exec != u32::MAX && lane.vgpr[usize::from(dst)].is_none() {
|
||||
return Err(format!("{offset:#x}: partial EXEC on uninitialized VGPR"));
|
||||
}
|
||||
let a = match src0 {
|
||||
CmpSrc::Sgpr(reg) => sgpr[usize::from(reg)]
|
||||
.ok_or_else(|| format!("{offset:#x}: uninitialized s{reg}"))?,
|
||||
CmpSrc::Vcc => incoming,
|
||||
CmpSrc::Imm(value) => value,
|
||||
CmpSrc::Vgpr(reg) => read_vgpr(lane, reg, offset)?,
|
||||
};
|
||||
let b = read_vgpr(lane, src1, offset)?;
|
||||
let lane_bit = 2_u32.pow(index as u32);
|
||||
if exec & lane_bit == 0 {
|
||||
continue;
|
||||
}
|
||||
check_destination(dst, lane.pending_read, offset)?;
|
||||
let bit = incoming / lane_bit % 2;
|
||||
let (value, flag) = match opcode {
|
||||
1 => (if bit == 1 { b } else { a }, false),
|
||||
40 => {
|
||||
let (sum, overflow) = a.overflowing_add(b);
|
||||
let (value, carry) = sum.overflowing_add(bit);
|
||||
(value, overflow || carry)
|
||||
}
|
||||
41 | 42 => {
|
||||
let (lhs, rhs) = if opcode == 42 { (b, a) } else { (a, b) };
|
||||
let (difference, underflow) = lhs.overflowing_sub(rhs);
|
||||
let (value, borrow) = difference.overflowing_sub(bit);
|
||||
(value, underflow || borrow)
|
||||
}
|
||||
_ => unreachable!("not a VCC-reading VOP2 opcode"),
|
||||
};
|
||||
lane.vgpr[usize::from(dst)] = Some(value);
|
||||
if flag {
|
||||
mask |= lane_bit;
|
||||
}
|
||||
}
|
||||
Ok(mask)
|
||||
}
|
||||
|
||||
/// One SOPK instruction, per the operation text of guide 12.2. SDST names
|
||||
/// the destination and, for every form but the two moves, the first source.
|
||||
fn scalar_immediate(
|
||||
@@ -1250,6 +1325,13 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
}
|
||||
// VOP2 integer forms: bit 31 = 0, OP 30:25, VDST 24:17, VSRC1 16:9, SRC0 8:0.
|
||||
let vop2_op = (first >> 25) & 0x3f;
|
||||
if first >> 31 == 0 && matches!(vop2_op, 1 | 40..=42) {
|
||||
let (src0, len) = vector_src0(code, offset, first, "VOP2")?;
|
||||
return Ok((
|
||||
Insn::VIntVcc(vop2_op, (first >> 17) as u8, src0, (first >> 9) as u8),
|
||||
len,
|
||||
));
|
||||
}
|
||||
if first >> 31 == 0 && matches!(vop2_op, 9..=12 | 17..=20 | 30 | 37..=39) {
|
||||
let (src0, len) = vector_src0(code, offset, first, "VOP2")?;
|
||||
let insn = Insn::VInt(vop2_op, (first >> 17) as u8, src0, (first >> 9) as u8);
|
||||
|
||||
@@ -784,6 +784,27 @@ mod review {
|
||||
const SCALAR_ARITH_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-arith.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-arith.s from the guide's 12.1 pseudocode.
|
||||
const SCALAR_ARITH_KEY: u32 = 0x8115_7dfe;
|
||||
#[test]
|
||||
fn vector_vcc_chain_returns_the_zero_input_mask() {
|
||||
let code = include_bytes!("../../fixtures/rdna2/vector-vcc.bin");
|
||||
let input: Vec<_> = [0, 1, u32::MAX, 5, 0, 7]
|
||||
.into_iter()
|
||||
.cycle()
|
||||
.take(67)
|
||||
.collect();
|
||||
let expected: Vec<_> = input
|
||||
.chunks(32)
|
||||
.flat_map(|wave| {
|
||||
let mask = wave
|
||||
.iter()
|
||||
.enumerate()
|
||||
.fold(0, |mask, (lane, &x)| mask | (u32::from(x == 0) << lane));
|
||||
std::iter::repeat_n(mask, wave.len())
|
||||
})
|
||||
.collect();
|
||||
verify(code, &input, Some(&expected));
|
||||
}
|
||||
|
||||
const VECTOR_INTEGER_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-integer.bin");
|
||||
|
||||
/// fixtures/rdna2/vector-integer.s for one lane input `x`, written from the
|
||||
|
||||
@@ -745,9 +745,9 @@ fn unsupported_vop2_integer_encodings_are_rejected() {
|
||||
fn other_vop2_opcodes_stay_unsupported() {
|
||||
// Every VOP2 opcode (0-61; 62 and 63 are the VOPC and VOP1 encodings)
|
||||
// except the forms supported before this set (V_ADD_F32 3, V_MUL_F32 8,
|
||||
// the shifts 22, 24, 26 and AND, OR, XOR 27-29) and these twelve. VDST is
|
||||
// the shifts 22, 24, 26 and AND, OR, XOR 27-29) and the registered integer forms. VDST is
|
||||
// initialized, so a form that also reads it fails only on the opcode.
|
||||
let earlier = [3, 8, 22, 24, 26, 27, 28, 29];
|
||||
let earlier = [1, 3, 8, 22, 24, 26, 27, 28, 29, 40, 41, 42];
|
||||
let supported: Vec<u32> = FORMS
|
||||
.iter()
|
||||
.map(|&(form, _)| form as u32)
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Wave32 VOP2 select and carry/borrow oracle from AMD RDNA 2 ISA guide
|
||||
//! sections 3.3, 3.9, 12.7 and 13.3.1.
|
||||
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use xenora_shader::{Architecture, CompileError, compile};
|
||||
|
||||
const FORMS: [u32; 4] = [1, 40, 41, 42];
|
||||
const EXEC_PATTERNS: [u32; 3] = [u32::MAX, 0xaaaa_aaab, 0];
|
||||
const INITIAL_DST: u32 = 0x1234_5678;
|
||||
const SCALAR_VCC: u32 = 0x8000_0005;
|
||||
|
||||
fn words(code: &[u32]) -> Vec<u8> {
|
||||
code.iter().flat_map(|word| word.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
fn vop2(op: u32, dst: u32, src0: u32, src1: u32) -> u32 {
|
||||
op << 25 | dst << 17 | src1 << 9 | src0
|
||||
}
|
||||
|
||||
fn program(body: &[u32], output: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
code.extend(body);
|
||||
code.extend([
|
||||
0xe070_2000,
|
||||
0x8001_0000 | output << 8,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn input() -> Vec<u32> {
|
||||
[0, 1, 2, u32::MAX, u32::MAX - 1, 0x8000_0000, 0, 31]
|
||||
.into_iter()
|
||||
.cycle()
|
||||
.take(67)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Guide 12.7 gives the unbounded result and the 32-bit destination.
|
||||
/// For SUBREV the prose and D equation reverse the operands. The printed
|
||||
/// borrow formula repeats SUB's order, inconsistent with that subtraction.
|
||||
fn expected(op: u32, a: u32, b: u32, bit: u32) -> (u32, bool) {
|
||||
let (a, b, bit) = (i128::from(a), i128::from(b), i128::from(bit));
|
||||
let exact = match op {
|
||||
1 => return (if bit == 0 { a } else { b } as u32, false),
|
||||
40 => a + b + bit,
|
||||
41 => a - b - bit,
|
||||
42 => b - a - bit,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let modulus = 1_i128 << 32;
|
||||
(
|
||||
exact.rem_euclid(modulus) as u32,
|
||||
!(0..modulus).contains(&exact),
|
||||
)
|
||||
}
|
||||
|
||||
fn cases() -> Vec<(Vec<u8>, Vec<u32>)> {
|
||||
let input = input();
|
||||
let mut cases = Vec::new();
|
||||
for op in FORMS {
|
||||
for exec in EXEC_PATTERNS {
|
||||
for (selector, extension, src0) in [
|
||||
(129, None, 1),
|
||||
(193, None, u32::MAX),
|
||||
(8, None, 0x8000_0000),
|
||||
(255, Some(u32::MAX - 1), u32::MAX - 1),
|
||||
(259, None, INITIAL_DST),
|
||||
(106, None, 0),
|
||||
] {
|
||||
for from_compare in [false, true] {
|
||||
let mut body = vec![0x7e06_02ff, INITIAL_DST, 0xbe88_03ff, 0x8000_0000];
|
||||
if from_compare {
|
||||
body.push(0x7d84_0280); // v_cmp_eq_u32_e32 vcc_lo, 0, v1
|
||||
} else {
|
||||
body.extend([0xbeea_03ff, SCALAR_VCC]); // s_mov_b32 vcc_lo, literal
|
||||
}
|
||||
body.extend([0xbefe_03ff, exec]);
|
||||
body.push(vop2(op, 3, selector, 1));
|
||||
body.extend(extension);
|
||||
body.push(0xbefe_03c1); // restore full EXEC for the store
|
||||
|
||||
let mut values = Vec::new();
|
||||
let mut masks = Vec::new();
|
||||
for wave in input.chunks(32) {
|
||||
let incoming = if from_compare {
|
||||
wave.iter()
|
||||
.enumerate()
|
||||
.fold(0, |mask, (lane, &x)| mask | (u32::from(x == 0) << lane))
|
||||
} else {
|
||||
SCALAR_VCC
|
||||
};
|
||||
let mut mask = if op == 1 { incoming } else { 0 };
|
||||
for (lane, &x) in wave.iter().enumerate() {
|
||||
if exec & (1 << lane) == 0 {
|
||||
values.push(INITIAL_DST);
|
||||
} else {
|
||||
let a = if selector == 106 { incoming } else { src0 };
|
||||
let (value, flag) = expected(op, a, x, (incoming >> lane) & 1);
|
||||
values.push(value);
|
||||
mask |= u32::from(flag) << lane;
|
||||
}
|
||||
}
|
||||
masks.extend(std::iter::repeat_n(mask, wave.len()));
|
||||
}
|
||||
cases.push((program(&body, 3), values));
|
||||
body.push(0x7e08_026a); // v_mov_b32_e32 v4, vcc_lo
|
||||
cases.push((program(&body, 4), masks));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop2_vcc_matches_guide_on_both_interpreters() {
|
||||
let input = input();
|
||||
for (index, (code, expected)) in cases().into_iter().enumerate() {
|
||||
compile(Architecture::Gfx1030, &code).unwrap();
|
||||
assert_eq!(
|
||||
xenora_ref::execute(&code, &input).unwrap(),
|
||||
expected,
|
||||
"reference case {index}"
|
||||
);
|
||||
assert_eq!(
|
||||
independent_ref::execute(&code, &input).unwrap(),
|
||||
expected,
|
||||
"independent case {index}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop2_vcc_rejects_unsupported_operands_and_uninitialized_state() {
|
||||
let mut cases = Vec::new();
|
||||
for op in FORMS {
|
||||
cases.push((program(&[vop2(op, 2, 129, 1)], 2), 12));
|
||||
for selector in [107, 124, 126, 128 + 112, 249, 250] {
|
||||
cases.push((program(&[vop2(op, 2, selector, 1), 0], 2), 12));
|
||||
}
|
||||
let fixture = words(&[vop2(op, 2, 255, 1)]);
|
||||
assert!(matches!(
|
||||
compile(Architecture::Gfx1030, &fixture),
|
||||
Err(CompileError::Decode(_))
|
||||
));
|
||||
assert!(xenora_ref::execute(&fixture, &[1]).is_err());
|
||||
assert!(independent_ref::execute(&fixture, &[1]).is_err());
|
||||
cases.push((
|
||||
program(&[0xbeea_03c1, 0xbefe_0381, vop2(op, 2, 129, 1)], 2),
|
||||
20,
|
||||
));
|
||||
}
|
||||
// LLVM-assembled e64 forms with an explicit scalar condition operand.
|
||||
for first in [0xd501_0002, 0xd528_0902, 0xd529_0902, 0xd52a_0902] {
|
||||
cases.push((program(&[first, 0x0022_0303], 2), 12));
|
||||
}
|
||||
for (code, offset) in cases {
|
||||
let result = compile(Architecture::Gfx1030, &code);
|
||||
let got = match result {
|
||||
Err(CompileError::Decode(error)) => error.offset,
|
||||
Err(CompileError::Verify { offset, .. }) => offset,
|
||||
other => panic!("expected rejection at {offset:#x}: {other:?}"),
|
||||
};
|
||||
assert_eq!(got, offset);
|
||||
assert_eq!(
|
||||
xenora_ref::execute(&code, &[1, 2]).unwrap_err().offset,
|
||||
offset
|
||||
);
|
||||
assert!(
|
||||
independent_ref::execute(&code, &[1, 2])
|
||||
.unwrap_err()
|
||||
.starts_with(&format!("{offset:#x}:"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn vop2_vcc_matches_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"));
|
||||
let metal = xenora_metal::NativeCompute::new().unwrap();
|
||||
let input = input();
|
||||
let fixture = include_bytes!("../../../fixtures/rdna2/vector-vcc.bin");
|
||||
let fixture_expected = input
|
||||
.chunks(32)
|
||||
.flat_map(|wave| {
|
||||
let mask = wave
|
||||
.iter()
|
||||
.enumerate()
|
||||
.fold(0, |mask, (lane, &x)| mask | (u32::from(x == 0) << lane));
|
||||
std::iter::repeat_n(mask, wave.len())
|
||||
})
|
||||
.collect();
|
||||
for (index, (code, expected)) in cases()
|
||||
.into_iter()
|
||||
.chain([(fixture.to_vec(), fixture_expected)])
|
||||
.enumerate()
|
||||
{
|
||||
let shader = compile(Architecture::Gfx1030, &code).unwrap();
|
||||
assert_eq!(
|
||||
metal
|
||||
.run_words(&shader.msl, xenora_shader::ENTRY_POINT, &input)
|
||||
.unwrap(),
|
||||
expected,
|
||||
"Metal case {index}",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,7 @@
|
||||
//! 6.2 (Table 20 and 6.2.1), 6.2.5, 6.8 and 9.1. 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 native Metal gate includes the 64-bit
|
||||
//! cases. The 16-bit Metal cases remain skipped while the compiler rejects
|
||||
//! those forms.
|
||||
//! interpreter `independent_ref`. The native Metal gate includes both widths.
|
||||
//!
|
||||
//! Readings of the guide (not hardware evidence):
|
||||
//! - Table 59: offsets F 0, LT 1, EQ 2, LE 3, GT 4, LG/NE 5, GE 6, TRU 7 with
|
||||
@@ -1169,10 +1167,34 @@ fn vopc_wide_outside_the_contract_are_rejected() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_compiler_still_rejects_the_16_bit_compares() {
|
||||
for form in forms().into_iter().filter(|form| form.bits == 16) {
|
||||
let (code, offset) = program(&vmov(3, 7), None, &[vopc(form.op, vgpr(1), 3)], &[]);
|
||||
assert_compiler_rejected_at(form.name, &code, offset);
|
||||
fn production_compiler_lowers_the_16_bit_compares() {
|
||||
let cases = cases_at_width(16);
|
||||
harness::check_reference(&cases).assert_none("16-bit compare compilation and reference");
|
||||
check_compiler_rejections(16);
|
||||
eprintln!("vopc16: {} compiler acceptance cases", cases.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_compiler_emits_signed_and_unsigned_low_half_relations() {
|
||||
for (name, signed) in [("v_cmp_lt_i16", true), ("v_cmp_lt_u16", false)] {
|
||||
let code = code(&vmov(3, 7), None, &[vopc(form(name).op, 193, 3)]);
|
||||
let shader = compile(Architecture::Gfx1030, &code).unwrap();
|
||||
let predicate = shader
|
||||
.msl
|
||||
.lines()
|
||||
.find(|line| line.contains("uint pass = ("))
|
||||
.unwrap();
|
||||
let cast = if signed {
|
||||
"as_type<short>(ushort("
|
||||
} else {
|
||||
"ushort("
|
||||
};
|
||||
assert_eq!(predicate.matches(cast).count(), 2, "{name}: {predicate}");
|
||||
assert!(!predicate.contains(">>"), "{name}: {predicate}");
|
||||
assert_eq!(
|
||||
predicate.matches("as_type<short>(").count(),
|
||||
if signed { 2 } else { 0 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1268,7 +1290,7 @@ fn vopc64_match_the_guide_on_native_metal() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires the translator's 16-bit forms and native Metal validation"]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn vopc16_match_the_guide_on_native_metal() {
|
||||
check_compiler_rejections(16);
|
||||
check_native_metal(16);
|
||||
|
||||
@@ -79,6 +79,12 @@ class GenerateX86(unittest.TestCase):
|
||||
_, forms = generate_x86.load(REGISTRY)
|
||||
self.assertEqual({form["op"] for form in forms if form.get("lock")}, {"cmpxchg", "xadd"})
|
||||
|
||||
def test_string_forms_are_movs_and_stos_without_operands(self):
|
||||
_, forms = generate_x86.load(REGISTRY)
|
||||
self.assertEqual({form["op"] for form in forms if form["enc"] == "string"}, {"movs", "stos"})
|
||||
self.rejects(self.form('op = "movs"\nopcode = 0xD7\nenc = "string"\nsize = "b"\nimm = "ib"'), "not valid for string")
|
||||
self.rejects(self.form('op = "movs"\nopcode = 0xD7\nenc = "string"\nsize = "b"\nlock = true'), "LOCK needs a memory destination")
|
||||
|
||||
def test_unknown_vocabulary_is_rejected(self):
|
||||
self.rejects(self.form('op = "frob"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "unknown op")
|
||||
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "z"'), "unknown size")
|
||||
|
||||
Reference in new issue
Block a user