mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 00:51:11 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3bbc955bc |
No files matched your search
+1
-5
@@ -13,10 +13,6 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Added
|
||||
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
|
||||
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
|
||||
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
|
||||
|
||||
- Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`.
|
||||
- Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet.
|
||||
- Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware.
|
||||
@@ -31,7 +27,6 @@ remains unsupported.
|
||||
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
|
||||
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
|
||||
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
|
||||
- Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported.
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
- Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`.
|
||||
- Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`.
|
||||
@@ -201,6 +196,7 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed the intermittent failure of the frame-loop memory-footprint test (#290). Each frame-loop session opened its own Metal command queue. The first command buffer on a queue makes the GPU driver allocate a working set for it (about 45 MiB on an Apple M5 with Metal validation), and the driver frees it asynchronously 10–50 ms after the queue is released, so the process footprint read right after a session ended depended on how far that release had got. Measured immediately after each of 50 destroys, it ranged from 45 to 96 MiB; the unchanged test failed 5 times in 30 runs, with up to 26 MiB of apparent growth. There was no leak: one second after each destroy the footprint was back at the same floor every time. Frame-loop sessions now share one process-wide Metal device and command queue, so the working set is allocated once and kept: the same readings stay within 93–98 MiB across 50 sessions, and the unchanged test passed 30 runs in a row (largest growth 0.31 MiB). The cost is that the process keeps that GPU memory (about 50 MiB with validation, 58 MiB total footprint without) after its first frame loop. A new 50-session test (normal completion, pause and resume, destroy while running) checks the readings stay within 16 MiB; it fails without the fix.
|
||||
- Stop ignoring `fixtures/pe/trusted-runner.exe`. The runner embeds it with `include_bytes!`, so ignoring the file made a fresh checkout fail to compile.
|
||||
- Corrected the ARM64 STP pre-index encoder, which had a hardcoded -32-byte immediate and therefore adjusted the host stack by the wrong amount once the translator frame grew to 48 bytes. The wrong frame silently corrupted the caller's stack and caused SIGSEGV in every native translation test. Emitter encodings are now checked against LLVM's assembler, and a test asserts that each translated block opens and closes the same 48-byte frame.
|
||||
- Translated guest memory faults now stop the block before it commits further architectural effects. A faulting push, call or store leaves guest RSP and registers unchanged, the reported instruction count covers only completed work, and guest RIP identifies the faulting instruction. Previously the block continued after the helper recorded a fault, so later instructions and writes still took effect.
|
||||
|
||||
@@ -9,8 +9,10 @@ pub use xenora_isa::{
|
||||
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_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
@@ -40,7 +42,7 @@ 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); 24] = [
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
@@ -57,6 +59,18 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 24] = [
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_AND_B32", EncodingFamily::Vop2),
|
||||
("V_ASHRREV_I32", EncodingFamily::Vop2),
|
||||
("V_CMP_EQ_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_EQ_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_LT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_U32", EncodingFamily::Vopc),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
|
||||
("V_LSHLREV_B32", EncodingFamily::Vop2),
|
||||
@@ -324,8 +338,26 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
if V_MOV_B32.matches(first) {
|
||||
return move_b32(first, bytes);
|
||||
}
|
||||
if let Some(op) = VectorCompareOp::from_word(first) {
|
||||
return vector_compare(op, first, bytes);
|
||||
{
|
||||
use CompareRelation::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual};
|
||||
for (opcode, relation, signed) in [
|
||||
(V_CMP_LT_I32, Less, true),
|
||||
(V_CMP_EQ_I32, Equal, true),
|
||||
(V_CMP_LE_I32, LessOrEqual, true),
|
||||
(V_CMP_GT_I32, Greater, true),
|
||||
(V_CMP_NE_I32, NotEqual, true),
|
||||
(V_CMP_GE_I32, GreaterOrEqual, true),
|
||||
(V_CMP_LT_U32, Less, false),
|
||||
(V_CMP_EQ_U32, Equal, false),
|
||||
(V_CMP_LE_U32, LessOrEqual, false),
|
||||
(V_CMP_GT_U32, Greater, false),
|
||||
(V_CMP_NE_U32, NotEqual, false),
|
||||
(V_CMP_GE_U32, GreaterOrEqual, false),
|
||||
] {
|
||||
if opcode.matches(first) {
|
||||
return vector_compare(VectorCompareOp { relation, signed }, first, bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
if V_ADD_NC_U32.matches(first) {
|
||||
let len = V_ADD_NC_U32.byte_len();
|
||||
@@ -683,7 +715,7 @@ fn vector_compare(
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = vector_src0(first, bytes, op.assembly_name())?;
|
||||
let (src0, len) = vector_src0(first, bytes, op.mnemonic())?;
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
}
|
||||
|
||||
|
||||
@@ -454,17 +454,15 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
|
||||
Instruction::VectorCompare { op, src0, src1 } => Op::Compare(
|
||||
Comparison {
|
||||
offset: match op.relation() {
|
||||
offset: match op.relation {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
CompareRelation::False => 0,
|
||||
CompareRelation::True => 7,
|
||||
},
|
||||
signed: op.signed(),
|
||||
signed: op.signed,
|
||||
},
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
@@ -528,13 +526,12 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 104, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 100, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -599,7 +596,7 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
);
|
||||
// Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo,
|
||||
// inline integers at both ends, inline zero and a literal.
|
||||
for relation in ["f", "lt", "eq", "le", "gt", "ne", "ge", "t"] {
|
||||
for relation in ["lt", "eq", "le", "gt", "ne", "ge"] {
|
||||
for kind in ["i32", "u32"] {
|
||||
for src0 in [
|
||||
"v255",
|
||||
@@ -747,6 +744,8 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
|
||||
let outside_subset: &[&[u32]] = &[
|
||||
&[0x7e04_026b], // VOP1 VCC_HI source
|
||||
&[0x7da2_0501], // v_cmpx_eq_u32_e32
|
||||
&[0x7d00_0501], // v_cmp_f_i32_e32
|
||||
&[0x7d0e_0501], // v_cmp_t_i32_e32
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
|
||||
&[0x8788_0908], // s_and_b64
|
||||
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! the guest leaves its loop and halts.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
@@ -171,8 +171,8 @@ impl FrameLoop {
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)
|
||||
.map_err(|e| format!("shader translation: {e}"))?;
|
||||
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
|
||||
// The session's GPU resources live on the guest thread, where the import runs.
|
||||
let gpu = shared_gpu()?;
|
||||
// The import runs on the guest thread, so the session's shader lives there too.
|
||||
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
|
||||
|
||||
let shared = Arc::clone(self);
|
||||
@@ -268,7 +268,26 @@ impl FrameLoop {
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static GPU: RefCell<Option<(NativeCompute, String)>> = const { RefCell::new(None) };
|
||||
static GPU: RefCell<Option<(&'static NativeCompute, String)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// One Metal device and command queue shared by every frame-loop session (#290).
|
||||
///
|
||||
/// The first command buffer submitted on a queue makes the GPU driver allocate a
|
||||
/// working set for it (about 45 MiB on an Apple M5 with Metal validation), and the
|
||||
/// driver frees that memory asynchronously, 10–50 ms after the queue is released.
|
||||
/// A queue per session therefore allocated and freed it once per session, and the
|
||||
/// process footprint depended on how far that release had progressed. One queue
|
||||
/// for the process allocates the working set once and keeps it: bounded caching,
|
||||
/// not per-session churn. `NativeCompute` is `Send + Sync`, and rendering takes
|
||||
/// `&self`, so concurrent sessions can share it. A device that cannot be opened
|
||||
/// is reported to every session that asks.
|
||||
fn shared_gpu() -> Result<&'static NativeCompute, String> {
|
||||
static SHARED: OnceLock<Result<NativeCompute, String>> = OnceLock::new();
|
||||
SHARED
|
||||
.get_or_init(|| NativeCompute::new().map_err(|e| format!("Metal device: {e}")))
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
}
|
||||
|
||||
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
|
||||
|
||||
+139
-21
@@ -82,25 +82,6 @@ fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Statu
|
||||
}
|
||||
}
|
||||
|
||||
/// Footprint once it has stopped changing. After a session is destroyed, Metal gives
|
||||
/// back its memory asynchronously: measured on an Apple M5, a reading taken right after
|
||||
/// destroy was up to about 45 MiB above the floor it returned to within one second,
|
||||
/// every time. A single immediate reading therefore mixes in memory that is already on
|
||||
/// its way out. Read every 50 ms until two consecutive readings agree within 1 MiB
|
||||
/// (at most 5 s). A genuine leak still settles high, so it is still caught.
|
||||
fn settled_footprint() -> u64 {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let mut previous = footprint();
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let current = footprint();
|
||||
if current.abs_diff(previous) < 1 << 20 || Instant::now() >= deadline {
|
||||
return current;
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
|
||||
fn footprint() -> u64 {
|
||||
unsafe extern "C" {
|
||||
@@ -264,11 +245,11 @@ fn repeated_sessions_do_not_grow_the_memory_footprint() {
|
||||
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
|
||||
run();
|
||||
run();
|
||||
let baseline = settled_footprint();
|
||||
let baseline = footprint();
|
||||
for _ in 0..5 {
|
||||
run();
|
||||
}
|
||||
let after = settled_footprint();
|
||||
let after = footprint();
|
||||
let growth = after.saturating_sub(baseline);
|
||||
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
|
||||
assert!(
|
||||
@@ -276,3 +257,140 @@ fn repeated_sessions_do_not_grow_the_memory_footprint() {
|
||||
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression test for #290: the footprint read right after each destroy must stay
|
||||
/// flat across many sessions. Each session used to open its own Metal command queue,
|
||||
/// and the GPU driver frees a queue's working set (about 45 MiB on an Apple M5 with
|
||||
/// validation) asynchronously after release, so these readings swung by about 50 MiB
|
||||
/// from session to session. Sessions now share one queue. The mix of sessions covers
|
||||
/// normal completion, pause and resume, and destruction while running.
|
||||
#[test]
|
||||
fn fifty_sessions_keep_a_flat_footprint_after_each_destroy() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let one = |kind: usize| {
|
||||
let session = session();
|
||||
match kind {
|
||||
0 => {
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
|
||||
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
|
||||
}
|
||||
1 => {
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
|
||||
wait_until(session, "10 frames", |s| s.completed >= 10);
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
|
||||
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "a frame", |s| s.completed >= 1);
|
||||
}
|
||||
}
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
footprint()
|
||||
};
|
||||
one(0); // the first session allocates the shared queue's working set
|
||||
let readings: Vec<u64> = (0..50).map(|i| one(i % 3)).collect();
|
||||
let mib: Vec<u64> = readings.iter().map(|r| r >> 20).collect();
|
||||
println!("footprint after each destroy (MiB): {mib:?}");
|
||||
let median = |values: &[u64]| {
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_unstable();
|
||||
sorted[sorted.len() / 2]
|
||||
};
|
||||
// Sustained growth: the typical reading at the end against the start.
|
||||
let (start, end) = (median(&readings[..10]), median(&readings[40..]));
|
||||
assert!(
|
||||
end.saturating_sub(start) < 16 << 20,
|
||||
"footprint grew from {start} to {end} bytes (median of first and last ten sessions)"
|
||||
);
|
||||
// Per-session churn, the cause fixed in #290: with a queue per session, about half
|
||||
// of all readings sat some 45 MiB away from the median. With the shared queue,
|
||||
// a reading is still occasionally caught while the driver frees a batch of
|
||||
// per-frame render resources: graphics-tagged memory only, 16 to 44 MiB, gone
|
||||
// within about 100 ms, measured in 13 of 6,000 sessions (0.22%). Allowing two such
|
||||
// readings in 50 keeps a false failure near 1 in 5,000 runs while per-session
|
||||
// churn would exceed it every time.
|
||||
let centre = median(&readings);
|
||||
let outliers: Vec<u64> = readings
|
||||
.iter()
|
||||
.filter(|&&r| r.abs_diff(centre) >= 16 << 20)
|
||||
.map(|r| r >> 20)
|
||||
.collect();
|
||||
assert!(
|
||||
outliers.len() <= 2,
|
||||
"{} of 50 readings were 16 MiB or more from the median {} MiB: {outliers:?}",
|
||||
outliers.len(),
|
||||
centre >> 20
|
||||
);
|
||||
}
|
||||
|
||||
/// Two sessions render at the same time through the shared Metal queue (#290). Each
|
||||
/// must keep its own frame sequence and pixels, pausing one must not stop the other,
|
||||
/// and destroying one mid-run must not disturb the other.
|
||||
#[test]
|
||||
fn concurrent_sessions_share_the_queue_but_stay_isolated() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let (a, b) = (session(), session());
|
||||
assert_eq!(xenora_session_start_frame_loop(a, 400), XENORA_OK);
|
||||
assert_eq!(xenora_session_start_frame_loop(b, 250), XENORA_OK);
|
||||
wait_until(a, "session A started", |s| s.completed >= 5);
|
||||
wait_until(b, "session B started", |s| s.completed >= 5);
|
||||
|
||||
// Pausing A holds only A.
|
||||
assert_eq!(xenora_session_pause_frame_loop(a), XENORA_OK);
|
||||
let a_held = wait_until(a, "session A paused", |s| s.state == XENORA_LOOP_PAUSED);
|
||||
let b_before = status(b).completed;
|
||||
let b_moving = wait_until(b, "session B progress while A is paused", |s| {
|
||||
s.completed >= b_before + 20 || s.state != XENORA_LOOP_RUNNING
|
||||
});
|
||||
assert!(
|
||||
b_moving.completed > b_before,
|
||||
"B kept rendering while A was paused"
|
||||
);
|
||||
let a_still = status(a);
|
||||
assert_eq!(a_still.state, XENORA_LOOP_PAUSED);
|
||||
// At most the frame A was rendering when paused can still complete.
|
||||
assert!(a_still.completed <= a_held.completed + 1);
|
||||
assert_eq!(a_still.rgba.to_vec(), expected(a_still.frame_id));
|
||||
assert_eq!(xenora_session_resume_frame_loop(a), XENORA_OK);
|
||||
|
||||
// Both finish with their own counts and their own final frames.
|
||||
let a_done = wait_until(a, "session A finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
let b_done = wait_until(b, "session B finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(
|
||||
(a_done.state, a_done.completed, a_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 400, 399)
|
||||
);
|
||||
assert_eq!(
|
||||
(b_done.state, b_done.completed, b_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 250, 249)
|
||||
);
|
||||
assert_eq!(a_done.rgba.to_vec(), expected(399));
|
||||
assert_eq!(b_done.rgba.to_vec(), expected(249));
|
||||
assert_eq!(xenora_session_destroy(a), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(b), XENORA_OK);
|
||||
|
||||
// Destroying one running session leaves the other running to completion.
|
||||
let (c, d) = (session(), session());
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(c, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(xenora_session_start_frame_loop(d, 300), XENORA_OK);
|
||||
wait_until(c, "session C started", |s| s.completed >= 5);
|
||||
wait_until(d, "session D started", |s| s.completed >= 5);
|
||||
assert_eq!(xenora_session_destroy(c), XENORA_OK);
|
||||
let d_done = wait_until(d, "session D finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(
|
||||
(d_done.state, d_done.completed, d_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 300, 299)
|
||||
);
|
||||
assert_eq!(d_done.rgba.to_vec(), expected(299));
|
||||
assert_eq!(xenora_session_destroy(d), XENORA_OK);
|
||||
}
|
||||
@@ -60,15 +60,8 @@ SOURCE_BITS = {8, 16}
|
||||
RELATION_KEY = "relation"
|
||||
RELATIONS = {
|
||||
"eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual",
|
||||
"lt": "Less", "le": "LessOrEqual", "f": "False", "t": "True",
|
||||
"lt": "Less", "le": "LessOrEqual",
|
||||
}
|
||||
# F and T exist only as VOPC compares (guide Table 59 offsets 0 and 7).
|
||||
VECTOR_ONLY_RELATIONS = {"f", "t"}
|
||||
# Guide 12.9 Table 59 and Table 61: a 32-bit integer VOPC compare's opcode is
|
||||
# its group base (128 for _I32, 192 for _U32) plus its relation's offset. This
|
||||
# is the guide's opcode layout, not a reading of the mnemonic.
|
||||
VOPC_INTEGER_BASES = {"signed": 128, "unsigned": 192}
|
||||
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.
|
||||
COMPARE_PRIMITIVES = {
|
||||
@@ -78,8 +71,6 @@ COMPARE_PRIMITIVES = {
|
||||
("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32",
|
||||
("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32",
|
||||
("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32",
|
||||
("f", "signed"): "false_b32", ("f", "unsigned"): "false_b32",
|
||||
("t", "signed"): "true_b32", ("t", "unsigned"): "true_b32",
|
||||
}
|
||||
# Logical operations take untyped bits; arithmetic ones never do. Shifts take
|
||||
# the signedness their primitive names, and their S1 is an unsigned count.
|
||||
@@ -122,16 +113,11 @@ 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).
|
||||
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"}
|
||||
MASK = {"unchanged": "Unchanged"}
|
||||
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"}
|
||||
# The decoder has no wave-size input at the registry dispatch yet, so a Wave32
|
||||
# restriction could be declared but not enforced. Reject it until it can be.
|
||||
ENFORCED_WAVES = {"any"}
|
||||
EVIDENCE = {
|
||||
"reference": "Reference",
|
||||
"independent": "Independent",
|
||||
@@ -267,25 +253,6 @@ OPERAND_RULES = {
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
|
||||
"kind": "unary",
|
||||
},
|
||||
"vopc_vcc": {
|
||||
"rust": "VopcVcc",
|
||||
"enum": "VectorCompareOp",
|
||||
"shape": {
|
||||
"family": "VOPC",
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# The destination is implicitly vcc_lo; the decoder rejects these SRC0
|
||||
# selectors (the same vector_source as VOP2).
|
||||
"unsupported": {
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector_compare",
|
||||
},
|
||||
"vop2_vgpr": {
|
||||
"rust": "Vop2Vgpr",
|
||||
"enum": "VectorAluOp",
|
||||
@@ -389,7 +356,6 @@ 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"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
@@ -398,15 +364,8 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
operands[field] = (data_format, size, 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["vcc"] == "lane_mask":
|
||||
# Exactly one fieldless VCC operand, written and not read.
|
||||
if vcc_writes != [(False, True)]:
|
||||
errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output")
|
||||
implicit.discard("OPR_VCC")
|
||||
# The vocabulary can state only SCC effects (vcc and exec are "unchanged"),
|
||||
# so any other implicit XML operand, such as VCC, is undeclared.
|
||||
if implicit:
|
||||
errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared")
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
@@ -512,17 +471,8 @@ 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")
|
||||
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"
|
||||
if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask:
|
||||
errors.append(
|
||||
f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} "
|
||||
f"(requires {'lane_mask' if lane_mask else 'unchanged'})"
|
||||
)
|
||||
if form["exec"] != "unchanged":
|
||||
errors.append(f"{label}: exec {form['exec']} has no contract (requires unchanged)")
|
||||
if form["wave"] in WAVE and form["wave"] not in ENFORCED_WAVES:
|
||||
errors.append(f"{label}: wave {form['wave']} has no decoder enforcement yet")
|
||||
if type(form["width"]) is not int or form["width"] not in WIDTHS:
|
||||
errors.append(f"{label}: width {form['width']} is not supported")
|
||||
for key, value in (
|
||||
@@ -577,23 +527,11 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}")
|
||||
elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES:
|
||||
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
|
||||
elif relation in VECTOR_ONLY_RELATIONS and _rule_kind(form) != "vector_compare":
|
||||
errors.append(f"{label}: relation {relation} exists only for VOPC compares")
|
||||
elif _rule_kind(form) == "vector_compare":
|
||||
base = VOPC_INTEGER_BASES.get(form["signedness"])
|
||||
expected = None if base is None else base + VOPC_RELATION_OFFSETS[relation]
|
||||
if form["opcode"] != expected:
|
||||
errors.append(
|
||||
f"{label}: relation {relation}/{form['signedness']} has VOPC opcode "
|
||||
f"{expected} (guide Table 59), not {form['opcode']}"
|
||||
)
|
||||
# SOPC compares write SCC; VOPC compares write VCC and leave SCC.
|
||||
scc = "unchanged" if _rule_kind(form) == "vector_compare" else "relation"
|
||||
if form["scc"] != scc:
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts compare (requires {scc})")
|
||||
if form["scc"] != "relation":
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)")
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = (scc, None, False)
|
||||
primitive = ("relation", None, False)
|
||||
elif _rule_kind(form) == "vector":
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
@@ -620,8 +558,7 @@ def validate(registry, snapshot):
|
||||
elif rule.get("family") != form["family"]:
|
||||
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
|
||||
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
|
||||
("vector_compare" if _rule_kind(form) == "vector_compare" else "compare")
|
||||
if form["operation"] == "compare"
|
||||
"compare" if form["operation"] == "compare"
|
||||
else "unary" if form["operation"] in UNARY
|
||||
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
|
||||
else "alu"
|
||||
@@ -770,11 +707,10 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
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']}"
|
||||
what = f"compare {form[RELATION_KEY]}" if kind == "compare" else form["operation"]
|
||||
out += [
|
||||
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
|
||||
f"{form['signedness']} {what}{carry}, {effect}.",
|
||||
f"{form['signedness']} {what}{carry}, SCC = {form['scc']}.",
|
||||
f" {form['variant']},",
|
||||
]
|
||||
by_opcode = {form["opcode"]: form["variant"] for form in forms}
|
||||
@@ -898,29 +834,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "vector_compare":
|
||||
out += [
|
||||
"",
|
||||
" /// Assembler name of the 32-bit (VOPC) encoding, as LLVM prints it.",
|
||||
" pub const fn assembly_name(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}_e32\"," for form in forms]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operands compare as two's-complement values.",
|
||||
" pub const fn signed(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if form['signedness'] == 'signed' else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [" }", " }"]
|
||||
if kind in ("compare", "vector_compare"):
|
||||
result = "SCC" if kind == "compare" else "per-lane result"
|
||||
if kind == "compare":
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with S0 on the left.",
|
||||
@@ -935,7 +849,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
f" /// The {result}: whether the relation holds for S0 and S1.",
|
||||
" /// The new SCC: whether the relation holds for S0 and S1.",
|
||||
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
|
||||
@@ -54,8 +54,8 @@ unsupported = [
|
||||
# carry_in none | scc (scc for unsigned add/sub carry and the cselect condition)
|
||||
# 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 exactly for the VOPC lane-mask compares)
|
||||
# vcc, exec unchanged (stated, not implied)
|
||||
# wave any | wave32
|
||||
# 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
|
||||
@@ -1409,361 +1409,3 @@ wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ----
|
||||
# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold;
|
||||
# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's
|
||||
# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes),
|
||||
# the VOP3 encoding and Wave64 stay unsupported.
|
||||
[operand_rules.vopc_vcc]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2.
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I32"
|
||||
family = "VOPC"
|
||||
opcode = 129
|
||||
variant = "CmpLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 130
|
||||
variant = "CmpEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 131
|
||||
variant = "CmpLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 132
|
||||
variant = "CmpGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 133
|
||||
variant = "CmpNeI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 134
|
||||
variant = "CmpGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 193
|
||||
variant = "CmpLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 194
|
||||
variant = "CmpEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 195
|
||||
variant = "CmpLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 196
|
||||
variant = "CmpGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 197
|
||||
variant = "CmpNeU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 198
|
||||
variant = "CmpGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ----
|
||||
# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes
|
||||
# that exist. Sources are still decoded and checked as for the other compares
|
||||
# (docs/shaders/vector-compare.md section 5).
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_I32"
|
||||
family = "VOPC"
|
||||
opcode = 128
|
||||
variant = "CmpFI32"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_T_I32"
|
||||
family = "VOPC"
|
||||
opcode = 135
|
||||
variant = "CmpTI32"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_F_U32"
|
||||
family = "VOPC"
|
||||
opcode = 192
|
||||
variant = "CmpFU32"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_T_U32"
|
||||
family = "VOPC"
|
||||
opcode = 199
|
||||
variant = "CmpTU32"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+61
-10
@@ -18,9 +18,7 @@ pub use rdna2::{
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::{
|
||||
ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorCompareOp,
|
||||
};
|
||||
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
@@ -95,8 +93,7 @@ impl fmt::Display for ScalarSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Relation tested by a SOPC or VOPC integer compare; S0 (SSRC0 or SRC0) is on
|
||||
/// the left.
|
||||
/// Relation tested by a VOPC integer compare; S0 is SRC0 and S1 is VSRC1.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareRelation {
|
||||
/// S0 < S1 (opcode offset 1).
|
||||
@@ -111,10 +108,64 @@ pub enum CompareRelation {
|
||||
NotEqual,
|
||||
/// S0 >= S1 (offset 6).
|
||||
GreaterOrEqual,
|
||||
/// Never holds (VOPC F, offset 0).
|
||||
False,
|
||||
/// Always holds (VOPC T, offset 7).
|
||||
True,
|
||||
}
|
||||
|
||||
/// A 32-bit VOPC integer compare: one relation over signed or unsigned operands.
|
||||
///
|
||||
/// The per-lane test follows the RDNA 2 ISA guide, section 12.9 (Table 59) and
|
||||
/// the pinned XML descriptions. VCC and EXEC rules are in
|
||||
/// docs/shaders/vector-compare.md.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct VectorCompareOp {
|
||||
/// The tested relation.
|
||||
pub relation: CompareRelation,
|
||||
/// `_i32` (two's complement) when true, `_u32` when false.
|
||||
pub signed: bool,
|
||||
}
|
||||
|
||||
impl VectorCompareOp {
|
||||
/// Lower-case mnemonic of the 32-bit VOPC encoding.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
const SIGNED: [&str; 6] = [
|
||||
"v_cmp_lt_i32_e32",
|
||||
"v_cmp_eq_i32_e32",
|
||||
"v_cmp_le_i32_e32",
|
||||
"v_cmp_gt_i32_e32",
|
||||
"v_cmp_ne_i32_e32",
|
||||
"v_cmp_ge_i32_e32",
|
||||
];
|
||||
const UNSIGNED: [&str; 6] = [
|
||||
"v_cmp_lt_u32_e32",
|
||||
"v_cmp_eq_u32_e32",
|
||||
"v_cmp_le_u32_e32",
|
||||
"v_cmp_gt_u32_e32",
|
||||
"v_cmp_ne_u32_e32",
|
||||
"v_cmp_ge_u32_e32",
|
||||
];
|
||||
let index = self.relation as usize;
|
||||
if self.signed {
|
||||
SIGNED[index]
|
||||
} else {
|
||||
UNSIGNED[index]
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-lane test result for operand bits S0 and S1.
|
||||
pub fn test(self, src0: u32, src1: u32) -> bool {
|
||||
let ordering = if self.signed {
|
||||
(src0 as i32).cmp(&(src1 as i32))
|
||||
} else {
|
||||
src0.cmp(&src1)
|
||||
};
|
||||
match self.relation {
|
||||
CompareRelation::Less => ordering.is_lt(),
|
||||
CompareRelation::Equal => ordering.is_eq(),
|
||||
CompareRelation::LessOrEqual => ordering.is_le(),
|
||||
CompareRelation::Greater => ordering.is_gt(),
|
||||
CompareRelation::NotEqual => ordering.is_ne(),
|
||||
CompareRelation::GreaterOrEqual => ordering.is_ge(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Output targeted by a supported uncompressed four-component export.
|
||||
@@ -276,7 +327,7 @@ impl Instruction {
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.assembly_name(),
|
||||
Self::VectorCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorAlu { op, .. } => op.assembly_name(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
|
||||
@@ -99,16 +99,6 @@ pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// The VOPC F test: false for every operand pair.
|
||||
pub const fn false_b32(_a: u32, _b: u32) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The VOPC T test: true for every operand pair.
|
||||
pub const fn true_b32(_a: u32, _b: u32) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// `a == b` on the raw bits; signedness does not matter for equality.
|
||||
pub const fn eq_b32(a: u32, b: u32) -> bool {
|
||||
a == b
|
||||
|
||||
@@ -160,15 +160,11 @@ pub enum SccEffect {
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC.
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
Unchanged,
|
||||
/// Wave32 VOPC result (VCC only): `VCC_LO` bit n is EXEC[n] & (lane n
|
||||
/// exists) & test(lane n), fully written; `VCC_HI` has no known value after
|
||||
/// it (docs/shaders/vector-compare.md section 3).
|
||||
LaneMask,
|
||||
}
|
||||
|
||||
/// Wave-size restriction.
|
||||
@@ -192,10 +188,6 @@ pub enum OperandRule {
|
||||
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
|
||||
/// a literal word. Everything else is rejected as unsupported.
|
||||
Sop1Sgpr,
|
||||
/// 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.
|
||||
VopcVcc,
|
||||
/// VOP2 vector: VDST is v0-v255; 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.
|
||||
|
||||
@@ -1179,7 +1179,7 @@ impl ScalarCompareOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// The SCC: whether the relation holds for S0 and S1.
|
||||
/// The new SCC: whether the relation holds for S0 and S1.
|
||||
pub const fn test(self, src0: u32, src1: u32) -> bool {
|
||||
match self {
|
||||
Self::CmpEqI32 => primitive::eq_b32(src0, src1),
|
||||
@@ -1412,468 +1412,8 @@ impl VectorAluOp {
|
||||
}
|
||||
}
|
||||
|
||||
/// VOPC operations declared in the semantic registry (operand rule `vopc_vcc`).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorCompareOp {
|
||||
/// `v_cmp_lt_i32` (VOPC opcode 129): signed compare lt, VCC = lane_mask.
|
||||
CmpLtI32,
|
||||
/// `v_cmp_eq_i32` (VOPC opcode 130): signed compare eq, VCC = lane_mask.
|
||||
CmpEqI32,
|
||||
/// `v_cmp_le_i32` (VOPC opcode 131): signed compare le, VCC = lane_mask.
|
||||
CmpLeI32,
|
||||
/// `v_cmp_gt_i32` (VOPC opcode 132): signed compare gt, VCC = lane_mask.
|
||||
CmpGtI32,
|
||||
/// `v_cmp_ne_i32` (VOPC opcode 133): signed compare lg, VCC = lane_mask.
|
||||
CmpNeI32,
|
||||
/// `v_cmp_ge_i32` (VOPC opcode 134): signed compare ge, VCC = lane_mask.
|
||||
CmpGeI32,
|
||||
/// `v_cmp_lt_u32` (VOPC opcode 193): unsigned compare lt, VCC = lane_mask.
|
||||
CmpLtU32,
|
||||
/// `v_cmp_eq_u32` (VOPC opcode 194): unsigned compare eq, VCC = lane_mask.
|
||||
CmpEqU32,
|
||||
/// `v_cmp_le_u32` (VOPC opcode 195): unsigned compare le, VCC = lane_mask.
|
||||
CmpLeU32,
|
||||
/// `v_cmp_gt_u32` (VOPC opcode 196): unsigned compare gt, VCC = lane_mask.
|
||||
CmpGtU32,
|
||||
/// `v_cmp_ne_u32` (VOPC opcode 197): unsigned compare lg, VCC = lane_mask.
|
||||
CmpNeU32,
|
||||
/// `v_cmp_ge_u32` (VOPC opcode 198): unsigned compare ge, VCC = lane_mask.
|
||||
CmpGeU32,
|
||||
/// `v_cmp_f_i32` (VOPC opcode 128): signed compare f, VCC = lane_mask.
|
||||
CmpFI32,
|
||||
/// `v_cmp_t_i32` (VOPC opcode 135): signed compare t, VCC = lane_mask.
|
||||
CmpTI32,
|
||||
/// `v_cmp_f_u32` (VOPC opcode 192): unsigned compare f, VCC = lane_mask.
|
||||
CmpFU32,
|
||||
/// `v_cmp_t_u32` (VOPC opcode 199): unsigned compare t, VCC = lane_mask.
|
||||
CmpTU32,
|
||||
}
|
||||
|
||||
/// VectorCompareOp by VOPC OP field value; `None` for undeclared opcodes.
|
||||
const VECTOR_COMPARE_OP_BY_OPCODE: [Option<VectorCompareOp>; 256] = [
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(VectorCompareOp::CmpFI32),
|
||||
Some(VectorCompareOp::CmpLtI32),
|
||||
Some(VectorCompareOp::CmpEqI32),
|
||||
Some(VectorCompareOp::CmpLeI32),
|
||||
Some(VectorCompareOp::CmpGtI32),
|
||||
Some(VectorCompareOp::CmpNeI32),
|
||||
Some(VectorCompareOp::CmpGeI32),
|
||||
Some(VectorCompareOp::CmpTI32),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(VectorCompareOp::CmpFU32),
|
||||
Some(VectorCompareOp::CmpLtU32),
|
||||
Some(VectorCompareOp::CmpEqU32),
|
||||
Some(VectorCompareOp::CmpLeU32),
|
||||
Some(VectorCompareOp::CmpGtU32),
|
||||
Some(VectorCompareOp::CmpNeU32),
|
||||
Some(VectorCompareOp::CmpGeU32),
|
||||
Some(VectorCompareOp::CmpTU32),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
];
|
||||
|
||||
impl VectorCompareOp {
|
||||
/// Every operation, in registry order.
|
||||
pub const ALL: [Self; 16] = [
|
||||
Self::CmpLtI32,
|
||||
Self::CmpEqI32,
|
||||
Self::CmpLeI32,
|
||||
Self::CmpGtI32,
|
||||
Self::CmpNeI32,
|
||||
Self::CmpGeI32,
|
||||
Self::CmpLtU32,
|
||||
Self::CmpEqU32,
|
||||
Self::CmpLeU32,
|
||||
Self::CmpGtU32,
|
||||
Self::CmpNeU32,
|
||||
Self::CmpGeU32,
|
||||
Self::CmpFI32,
|
||||
Self::CmpTI32,
|
||||
Self::CmpFU32,
|
||||
Self::CmpTU32,
|
||||
];
|
||||
|
||||
/// Selects the operation from a first instruction word: the VOPC encoding
|
||||
/// bits (mask 0xfe00_0000) and then the OP field (bits 17-24).
|
||||
pub const fn from_word(word: u32) -> Option<Self> {
|
||||
if word & 0xfe00_0000 != 0x7c00_0000 {
|
||||
return None;
|
||||
}
|
||||
VECTOR_COMPARE_OP_BY_OPCODE[((word >> 17) & 0xff) as usize]
|
||||
}
|
||||
|
||||
/// Lower-case mnemonic.
|
||||
pub const fn mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Self::CmpLtI32 => "v_cmp_lt_i32",
|
||||
Self::CmpEqI32 => "v_cmp_eq_i32",
|
||||
Self::CmpLeI32 => "v_cmp_le_i32",
|
||||
Self::CmpGtI32 => "v_cmp_gt_i32",
|
||||
Self::CmpNeI32 => "v_cmp_ne_i32",
|
||||
Self::CmpGeI32 => "v_cmp_ge_i32",
|
||||
Self::CmpLtU32 => "v_cmp_lt_u32",
|
||||
Self::CmpEqU32 => "v_cmp_eq_u32",
|
||||
Self::CmpLeU32 => "v_cmp_le_u32",
|
||||
Self::CmpGtU32 => "v_cmp_gt_u32",
|
||||
Self::CmpNeU32 => "v_cmp_ne_u32",
|
||||
Self::CmpGeU32 => "v_cmp_ge_u32",
|
||||
Self::CmpFI32 => "v_cmp_f_i32",
|
||||
Self::CmpTI32 => "v_cmp_t_i32",
|
||||
Self::CmpFU32 => "v_cmp_f_u32",
|
||||
Self::CmpTU32 => "v_cmp_t_u32",
|
||||
}
|
||||
}
|
||||
|
||||
/// The validated registry row.
|
||||
pub fn semantics(self) -> &'static FormSemantics {
|
||||
&FORMS[match self {
|
||||
Self::CmpLtI32 => 68,
|
||||
Self::CmpEqI32 => 69,
|
||||
Self::CmpLeI32 => 70,
|
||||
Self::CmpGtI32 => 71,
|
||||
Self::CmpNeI32 => 72,
|
||||
Self::CmpGeI32 => 73,
|
||||
Self::CmpLtU32 => 74,
|
||||
Self::CmpEqU32 => 75,
|
||||
Self::CmpLeU32 => 76,
|
||||
Self::CmpGtU32 => 77,
|
||||
Self::CmpNeU32 => 78,
|
||||
Self::CmpGeU32 => 79,
|
||||
Self::CmpFI32 => 80,
|
||||
Self::CmpTI32 => 81,
|
||||
Self::CmpFU32 => 82,
|
||||
Self::CmpTU32 => 83,
|
||||
}]
|
||||
}
|
||||
|
||||
/// Assembler name of the 32-bit (VOPC) encoding, as LLVM prints it.
|
||||
pub const fn assembly_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::CmpLtI32 => "v_cmp_lt_i32_e32",
|
||||
Self::CmpEqI32 => "v_cmp_eq_i32_e32",
|
||||
Self::CmpLeI32 => "v_cmp_le_i32_e32",
|
||||
Self::CmpGtI32 => "v_cmp_gt_i32_e32",
|
||||
Self::CmpNeI32 => "v_cmp_ne_i32_e32",
|
||||
Self::CmpGeI32 => "v_cmp_ge_i32_e32",
|
||||
Self::CmpLtU32 => "v_cmp_lt_u32_e32",
|
||||
Self::CmpEqU32 => "v_cmp_eq_u32_e32",
|
||||
Self::CmpLeU32 => "v_cmp_le_u32_e32",
|
||||
Self::CmpGtU32 => "v_cmp_gt_u32_e32",
|
||||
Self::CmpNeU32 => "v_cmp_ne_u32_e32",
|
||||
Self::CmpGeU32 => "v_cmp_ge_u32_e32",
|
||||
Self::CmpFI32 => "v_cmp_f_i32_e32",
|
||||
Self::CmpTI32 => "v_cmp_t_i32_e32",
|
||||
Self::CmpFU32 => "v_cmp_f_u32_e32",
|
||||
Self::CmpTU32 => "v_cmp_t_u32_e32",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the operands compare as two's-complement values.
|
||||
pub const fn signed(self) -> bool {
|
||||
match self {
|
||||
Self::CmpLtI32 => true,
|
||||
Self::CmpEqI32 => true,
|
||||
Self::CmpLeI32 => true,
|
||||
Self::CmpGtI32 => true,
|
||||
Self::CmpNeI32 => true,
|
||||
Self::CmpGeI32 => true,
|
||||
Self::CmpLtU32 => false,
|
||||
Self::CmpEqU32 => false,
|
||||
Self::CmpLeU32 => false,
|
||||
Self::CmpGtU32 => false,
|
||||
Self::CmpNeU32 => false,
|
||||
Self::CmpGeU32 => false,
|
||||
Self::CmpFI32 => true,
|
||||
Self::CmpTI32 => true,
|
||||
Self::CmpFU32 => false,
|
||||
Self::CmpTU32 => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The relation tested, with S0 on the left.
|
||||
pub const fn relation(self) -> CompareRelation {
|
||||
match self {
|
||||
Self::CmpLtI32 => CompareRelation::Less,
|
||||
Self::CmpEqI32 => CompareRelation::Equal,
|
||||
Self::CmpLeI32 => CompareRelation::LessOrEqual,
|
||||
Self::CmpGtI32 => CompareRelation::Greater,
|
||||
Self::CmpNeI32 => CompareRelation::NotEqual,
|
||||
Self::CmpGeI32 => CompareRelation::GreaterOrEqual,
|
||||
Self::CmpLtU32 => CompareRelation::Less,
|
||||
Self::CmpEqU32 => CompareRelation::Equal,
|
||||
Self::CmpLeU32 => CompareRelation::LessOrEqual,
|
||||
Self::CmpGtU32 => CompareRelation::Greater,
|
||||
Self::CmpNeU32 => CompareRelation::NotEqual,
|
||||
Self::CmpGeU32 => CompareRelation::GreaterOrEqual,
|
||||
Self::CmpFI32 => CompareRelation::False,
|
||||
Self::CmpTI32 => CompareRelation::True,
|
||||
Self::CmpFU32 => CompareRelation::False,
|
||||
Self::CmpTU32 => CompareRelation::True,
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-lane result: whether the relation holds for S0 and S1.
|
||||
pub const fn test(self, src0: u32, src1: u32) -> bool {
|
||||
match self {
|
||||
Self::CmpLtI32 => primitive::lt_i32(src0, src1),
|
||||
Self::CmpEqI32 => primitive::eq_b32(src0, src1),
|
||||
Self::CmpLeI32 => primitive::le_i32(src0, src1),
|
||||
Self::CmpGtI32 => primitive::gt_i32(src0, src1),
|
||||
Self::CmpNeI32 => primitive::ne_b32(src0, src1),
|
||||
Self::CmpGeI32 => primitive::ge_i32(src0, src1),
|
||||
Self::CmpLtU32 => primitive::lt_u32(src0, src1),
|
||||
Self::CmpEqU32 => primitive::eq_b32(src0, src1),
|
||||
Self::CmpLeU32 => primitive::le_u32(src0, src1),
|
||||
Self::CmpGtU32 => primitive::gt_u32(src0, src1),
|
||||
Self::CmpNeU32 => primitive::ne_b32(src0, src1),
|
||||
Self::CmpGeU32 => primitive::ge_u32(src0, src1),
|
||||
Self::CmpFI32 => primitive::false_b32(src0, src1),
|
||||
Self::CmpTI32 => primitive::true_b32(src0, src1),
|
||||
Self::CmpFU32 => primitive::false_b32(src0, src1),
|
||||
Self::CmpTU32 => primitive::true_b32(src0, src1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity of every registry form, in registry order.
|
||||
pub const FORM_IDS: [(&str, EncodingFamily); 84] = [
|
||||
pub const FORM_IDS: [(&str, EncodingFamily); 68] = [
|
||||
("S_ADD_U32", EncodingFamily::Sop2),
|
||||
("S_SUB_U32", EncodingFamily::Sop2),
|
||||
("S_ADD_I32", EncodingFamily::Sop2),
|
||||
@@ -1942,26 +1482,10 @@ pub const FORM_IDS: [(&str, EncodingFamily); 84] = [
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop2),
|
||||
("V_SUB_NC_U32", EncodingFamily::Vop2),
|
||||
("V_SUBREV_NC_U32", EncodingFamily::Vop2),
|
||||
("V_CMP_LT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_EQ_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_EQ_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_F_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_T_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_F_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_T_U32", EncodingFamily::Vopc),
|
||||
];
|
||||
|
||||
/// One validated row per registry form, in registry order.
|
||||
pub static FORMS: [FormSemantics; 84] = [
|
||||
pub static FORMS: [FormSemantics; 68] = [
|
||||
FormSemantics {
|
||||
name: "S_ADD_U32",
|
||||
family: EncodingFamily::Sop2,
|
||||
@@ -3390,340 +2914,4 @@ pub static FORMS: [FormSemantics; 84] = [
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.7", page: 134 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_LT_I32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 129,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Less),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_EQ_I32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 130,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Equal),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_LE_I32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 131,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::LessOrEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_GT_I32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 132,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Greater),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_NE_I32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 133,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::NotEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_GE_I32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 134,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::GreaterOrEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_LT_U32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 193,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Less),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_EQ_U32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 194,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Equal),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_LE_U32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 195,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::LessOrEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_GT_U32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 196,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::Greater),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_NE_U32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 197,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::NotEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_GE_U32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 198,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::GreaterOrEqual),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_F_I32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 128,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::False),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_T_I32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 135,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Signed,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::True),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_F_U32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 192,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::False),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
FormSemantics {
|
||||
name: "V_CMP_T_U32",
|
||||
family: EncodingFamily::Vopc,
|
||||
opcode: 199,
|
||||
operation: Operation::Compare,
|
||||
signedness: Signedness::Unsigned,
|
||||
carry_in: CarryIn::None,
|
||||
width: 32,
|
||||
shift_count_bits: 0,
|
||||
shift_amount: 0,
|
||||
swap_sources: false,
|
||||
source_bits: 32,
|
||||
relation: Some(CompareRelation::True),
|
||||
scc: SccEffect::Unchanged,
|
||||
vcc: MaskEffect::LaneMask,
|
||||
exec: MaskEffect::Unchanged,
|
||||
wave: Wave::Wave32,
|
||||
operands: OperandRule::VopcVcc,
|
||||
spec: &[SpecRef { document: Document::Guide, section: "12.9", page: 150 }, SpecRef { document: Document::Guide, section: "3.9", page: 19 }],
|
||||
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
|
||||
},
|
||||
];
|
||||
@@ -1,12 +1,8 @@
|
||||
//! Ties the generated semantic registry tables to the independent XML metadata table.
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
|
||||
};
|
||||
use xenora_isa::{
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorCompareOp,
|
||||
};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
|
||||
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
@@ -107,56 +103,3 @@ fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
|
||||
VectorAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
const OPERANDS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff];
|
||||
for op in VectorCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Vopc);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
assert_eq!(op.signed(), row.signedness == Signedness::Signed);
|
||||
assert_eq!(
|
||||
(row.scc, row.vcc, row.exec, row.wave),
|
||||
(
|
||||
SccEffect::Unchanged,
|
||||
MaskEffect::LaneMask,
|
||||
MaskEffect::Unchanged,
|
||||
Wave::Wave32
|
||||
)
|
||||
);
|
||||
// The per-lane test is the declared relation over the declared
|
||||
// signedness, with SRC0 on the left.
|
||||
for src0 in OPERANDS {
|
||||
for src1 in OPERANDS {
|
||||
let ordering = if op.signed() {
|
||||
(src0 as i32).cmp(&(src1 as i32))
|
||||
} else {
|
||||
src0.cmp(&src1)
|
||||
};
|
||||
let expected = match op.relation() {
|
||||
CompareRelation::Less => ordering.is_lt(),
|
||||
CompareRelation::Equal => ordering.is_eq(),
|
||||
CompareRelation::LessOrEqual => ordering.is_le(),
|
||||
CompareRelation::Greater => ordering.is_gt(),
|
||||
CompareRelation::NotEqual => ordering.is_ne(),
|
||||
CompareRelation::GreaterOrEqual => ordering.is_ge(),
|
||||
CompareRelation::False => false,
|
||||
CompareRelation::True => true,
|
||||
};
|
||||
assert_eq!(
|
||||
op.test(src0, src1),
|
||||
expected,
|
||||
"{} {src0:#x} {src1:#x}",
|
||||
row.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// v_cmpx and the 16-, 64-bit and float compares must not be dispatched.
|
||||
dispatch_selects_exactly(EncodingFamily::Vopc, |word| {
|
||||
VectorCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
@@ -79,10 +79,10 @@ pub enum Op {
|
||||
///
|
||||
/// AMD RDNA 2 ISA guide section 12.9, Tables 59 and 61: opcode 128 + offset
|
||||
/// for signed and 192 + offset for unsigned 32-bit operands, with offsets
|
||||
/// F 0, LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6, T 7.
|
||||
/// LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Comparison {
|
||||
/// Opcode offset 0-7 within the 32-bit integer group.
|
||||
/// Opcode offset 1-6 within the 32-bit integer group.
|
||||
pub offset: u8,
|
||||
/// Whether the operands are two's-complement integers.
|
||||
pub signed: bool,
|
||||
@@ -100,16 +100,12 @@ impl Comparison {
|
||||
};
|
||||
let (s0, s1) = (widen(s0), widen(s1));
|
||||
match self.offset {
|
||||
// Table 61: V_CMP_F_{I,U}32 `D[threadId] = 0`.
|
||||
0 => false,
|
||||
1 => s0 < s1,
|
||||
2 => s0 == s1,
|
||||
3 => s0 <= s1,
|
||||
4 => s0 > s1,
|
||||
5 => s0 != s1,
|
||||
6 => s0 >= s1,
|
||||
// Table 61: V_CMP_T_{I,U}32 `D[threadId] = 1`.
|
||||
_ => true,
|
||||
_ => s0 >= s1,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -583,7 +579,7 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
[lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..]
|
||||
if matches!(
|
||||
(u16::from(*tag & 1) << 7) | u16::from(*upper >> 1),
|
||||
128..=135 | 192..=199
|
||||
129..=134 | 193..=198
|
||||
) =>
|
||||
{
|
||||
let opcode = (u16::from(*tag & 1) << 7) | u16::from(*upper >> 1);
|
||||
|
||||
@@ -195,18 +195,15 @@ impl Op {
|
||||
|
||||
fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
|
||||
use xenora_decoder::CompareRelation;
|
||||
let symbol = match op.relation() {
|
||||
let symbol = match op.relation {
|
||||
CompareRelation::Less => "<",
|
||||
CompareRelation::Equal => "==",
|
||||
CompareRelation::LessOrEqual => "<=",
|
||||
CompareRelation::Greater => ">",
|
||||
CompareRelation::NotEqual => "!=",
|
||||
CompareRelation::GreaterOrEqual => ">=",
|
||||
// F and T read no operand bits.
|
||||
CompareRelation::False => return "false".to_owned(),
|
||||
CompareRelation::True => return "true".to_owned(),
|
||||
};
|
||||
if op.signed() {
|
||||
if op.signed {
|
||||
format!("as_type<int>({left}) {symbol} as_type<int>({right})")
|
||||
} else {
|
||||
format!("{left} {symbol} {right}")
|
||||
@@ -488,7 +485,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
|
||||
let _ = writeln!(
|
||||
ir,
|
||||
"{offset:04x}: {dest} = wave.mask {} {src0}, {src1} exec=0x{exec:08x}",
|
||||
op.assembly_name()
|
||||
op.mnemonic()
|
||||
);
|
||||
emit_lane_mask(&mut msl, &operations, &uniform, index, op, src0, src1, exec);
|
||||
continue;
|
||||
@@ -526,15 +523,7 @@ fn emit_lane_mask(
|
||||
exec: u32,
|
||||
) {
|
||||
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 {
|
||||
vec![src0, src1]
|
||||
};
|
||||
let mut pending = vec![src0, src1];
|
||||
while let Some(value) = pending.pop() {
|
||||
if uniform[value.0] || cone[value.0] {
|
||||
continue;
|
||||
|
||||
@@ -350,20 +350,6 @@ fn vector_integer_forms_lower_to_per_lane_templates() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_f_and_t_compares_lower_to_operand_free_wave_masks() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin");
|
||||
let result = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
result.ir,
|
||||
include_str!("../../../fixtures/golden/vector-compare-ft.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
result.msl,
|
||||
include_str!("../../../fixtures/golden/vector-compare-ft.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
|
||||
|
||||
@@ -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: 104 of 104. Accepted Metal forms · Apple M5: 18 of 104. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<desc id="description">Decoded gfx1030 forms: 100 of 100. Accepted Metal forms · Apple M5: 18 of 100. 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">104 / 104</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">100 / 100</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 / 104</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 100</text>
|
||||
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="103" width="84.81" height="4" rx="2" fill="#88c6bd"/>
|
||||
<rect x="20" y="103" width="88.20" 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 |
@@ -89,10 +89,6 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_cmp_gt_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 > S1), fully written | `7D8802C0` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ne_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 != S1), fully written | `7D8A026A` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_ge_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 >= S1), fully written | `7D8C0D01` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_f_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] & false, fully written | `7D000501` | 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_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 |
|
||||
| `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 |
|
||||
| `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 |
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
| SOP1 `S_NOT_B32`, `S_BREV_B32`, `S_BCNT{0,1}_I32_B32`, `S_FF{0,1}_I32_B32`, `S_FLBIT_I32_B32`, `S_FLBIT_I32`, `S_SEXT_I32_I{8,16}`, `S_ABS_I32` | The guide's section 12.3 result; a search that finds nothing gives -1, and `S_ABS_I32` of 0x80000000 is 0x80000000. Only NOT, BCNT0, BCNT1 and ABS write SCC (= D != 0). Descriptor SGPRs are reserved. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_{EQ,LG,GT,GE,LT,LE}_{I32,U32}` | Copy 32 bits into a scalar register, or compare SSRC0 with SSRC1 (signed for `_I32` ordering, unsigned for `_U32`; EQ and LG on the raw bits) and set only SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32`, `S_ANDN2_B32`, `S_ORN2_B32`, `S_NAND_B32`, `S_NOR_B32`, `S_XNOR_B32`, `S_LSHL_B32`, `S_LSHR_B32`, `S_ASHR_I32` | Exact integer result reduced modulo 2^32; shifts use S1[4:0]; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero logical or shift result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| VOPC `V_CMP_{F,LT,EQ,LE,GT,NE,GE,T}_{I32,U32}` | Compare widened 64-bit values per active lane (F is false and T true for every lane). VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). |
|
||||
| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). |
|
||||
| SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. |
|
||||
| VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. |
|
||||
| VOP2 `V_MUL_{I32_I24,HI_I32_I24,U32_U24,HI_U32_U24}`, `V_MIN_{I32,U32}`, `V_MAX_{I32,U32}`, `V_XNOR_B32`, `V_ADD_NC_U32`, `V_SUB_NC_U32`, `V_SUBREV_NC_U32` | The guide's section 12.7 result per active lane, computed exactly: the 24-bit multiplies use S0[23:0] and S1[23:0] (sign-extended for I24) and keep bits 31:0 or 63:32; SUBREV gives S1 - S0. SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline integer or a literal. Inactive lanes keep VDST; no SCC or VCC write. |
|
||||
|
||||
@@ -35,8 +35,8 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 |
|
||||
| **Total** | 1465 | 104 | 84 | 108 | 104 | 104 | 18 | 18 | 44 |
|
||||
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
|
||||
| **Total** | 1465 | 100 | 68 | 104 | 100 | 100 | 18 | 18 | 37 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
@@ -48,4 +48,3 @@ The table counts distinct variant names per family across registry operand rules
|
||||
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
| VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
@@ -60,9 +60,9 @@ error.
|
||||
| `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 S1 used as the count. The generator masks S1 with it, and the XML must list S1 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 compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
|
||||
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `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` (no EXEC-writing contract yet) |
|
||||
| `wave` | Wave sizes the form is valid in | `wave32` exactly for the VOPC compares (their one entry point is the Wave32 compute fixture ABI, vector-compare.md section 2), `any` for everything else; the decoder has no wave-size input, so no other form may claim `wave32` |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
|
||||
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` |
|
||||
| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) |
|
||||
| `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` |
|
||||
@@ -105,15 +105,7 @@ must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
|
||||
| `min`, `max` / `signed` or `unsigned` | `MinSigned`, `MinUnsigned`, `MaxSigned`, `MaxUnsigned` |
|
||||
| `mul24`, `mul_hi24` / `signed` or `unsigned` | `Mul24Signed`, `Mul24Unsigned`, `MulHi24Signed`, `MulHi24Unsigned` |
|
||||
|
||||
VOPC compares (operand rule `vopc_vcc`, kind `vector_compare`: SRC0 a
|
||||
`vector_source` as for VOP2, VSRC1 a VGPR, destination implicitly `vcc_lo`)
|
||||
take the same `relation` and primitive as SOPC compares, but declare
|
||||
`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.
|
||||
`v_cmpx_*` (EXEC writes), the VOP3 encoding and Wave64 stay unsupported.
|
||||
|
||||
A SOPC compare must use an operand rule of the compare kind (`sopc_scalar`: two
|
||||
A compare must use an operand rule of the compare kind (`sopc_scalar`: two
|
||||
sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
|
||||
one source and an SGPR destination), and a two-source ALU operation
|
||||
`sop2_sgpr`.
|
||||
@@ -127,10 +119,6 @@ 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 for `signed`, 192
|
||||
for `unsigned`) 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
|
||||
`variant` twice in one generated enum;
|
||||
- XML disagreements: a family with no XML encoding, a form with no default XML
|
||||
|
||||
@@ -53,13 +53,8 @@ The 32-bit VOPC encoding (bits 31:25 = 0b0111110), no SDWA or DPP:
|
||||
| v_cmp_gt_i32 / v_cmp_gt_u32 | S0 > S1 |
|
||||
| v_cmp_ne_i32 / v_cmp_ne_u32 | S0 != S1 |
|
||||
| v_cmp_ge_i32 / v_cmp_ge_u32 | S0 >= S1 |
|
||||
| v_cmp_f_i32 / v_cmp_f_u32 | false (Table 59 offset 0) |
|
||||
| v_cmp_t_i32 / v_cmp_t_u32 | true (offset 7) |
|
||||
|
||||
`_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values.
|
||||
The forms are declared in the semantic registry
|
||||
(`crates/isa/semantics/rdna2.toml`, operand rule `vopc_vcc`); the decoder
|
||||
dispatches them from the generated `VectorCompareOp`.
|
||||
Operand order matters (S0 is SRC0): lt with swapped operands is gt.
|
||||
|
||||
SRC0 selectors, exhaustively: 0-105 (normal SGPR), 106 (VCC_LO, see 5),
|
||||
@@ -100,7 +95,7 @@ this wave (all 32 except in a final partial wave, see 7). As an unsigned
|
||||
|
||||
- V_CMPX_* (writes EXEC: divergent execution; needs its own contract).
|
||||
- The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers).
|
||||
- SDWA and DPP forms; 16-bit, 64-bit and float compares; v_cmp_class.
|
||||
- SDWA and DPP forms; F/T, 16-bit, 64-bit and float compares; v_cmp_class.
|
||||
- SRC0 inline float constants (240-248), SGPRs other than s0-s106, TTMPs,
|
||||
M0, EXEC_LO/HI, VCC_HI, SCC/VCCZ/EXECZ selectors, LDS direct.
|
||||
- A normal-SGPR SRC0 without a known value, when EXEC_LO != 0.
|
||||
@@ -199,7 +194,7 @@ instructions are pure 32-bit ALU and are evaluated unconditionally.
|
||||
## 9. Verification
|
||||
|
||||
`fixtures/rdna2/vector-compare.s` is an original program, assembled by LLVM.
|
||||
It uses the twelve relational forms with VGPR, SGPR, inline, literal and `vcc_lo`
|
||||
It uses all twelve forms with VGPR, SGPR, inline, literal and `vcc_lo`
|
||||
sources, a compare and a mask move under partial EXEC, a compare under empty
|
||||
EXEC that must clear a stale VCC, SCC kept across compares, and a runtime
|
||||
`s_cbranch_vccz`. Its expected output is written in
|
||||
@@ -207,13 +202,7 @@ EXEC that must clear a stale VCC, SCC kept across compares, and a runtime
|
||||
relation for each row. The test input has a wave whose branch is taken, one
|
||||
whose branch is not, and a final partial wave of 9 lanes.
|
||||
|
||||
`fixtures/rdna2/vector-compare-ft.s` does the same for the four F and T
|
||||
forms: an F that clears a stale VCC, T and F under partial EXEC, a T reading
|
||||
`vcc_lo`, and runtime `s_cbranch_vccz` on a T result (never taken) and an F
|
||||
result (always taken). The independent oracle for F and T is
|
||||
`tests/validation/tests/vopc_f_t.rs`.
|
||||
|
||||
`tests/validation/known_answers.rs` runs each relational form against 10 boundary values (0, 1, 0x7ffffffe,
|
||||
The same file runs each form against 10 boundary values (0, 1, 0x7ffffffe,
|
||||
0x7fffffff, 0x80000000, 0x80000001, 0xfffffff0, 0xfffffffe, 0xffffffff,
|
||||
0x0f0f0f0f), in both operand orders. That is 240 programs, checked against
|
||||
exact i128 differences. It also covers partial and empty EXEC with seeded
|
||||
@@ -221,10 +210,9 @@ destinations, both runtime branch edges in one dispatch, and 32 rejections
|
||||
pinned to their byte offset. The translator, the reference (lockstep waves,
|
||||
compares on widened i64 values) and the second interpreter (sign-bit flip,
|
||||
then an unsigned compare) must all agree. The 9 ordered compare slots in the
|
||||
relational fixture each change the result when their signedness is flipped. The same
|
||||
programs, plus 2 mask-chain programs (252 in all), and the F/T fixture (253) match on native Metal with API and shader validation
|
||||
(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`). The F/T oracle's own native Metal cases
|
||||
run in `vopc_f_t_match_the_guide_on_native_metal`.
|
||||
fixture each change the result when their signedness is flipped. The same
|
||||
programs, plus 2 mask-chain programs (252 in all), match on native Metal with API and shader validation
|
||||
(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`).
|
||||
|
||||
A deliberately broken copy of each implementation fails these tests: the
|
||||
reference with unsigned-only compares or with the EXEC test removed; the
|
||||
|
||||
@@ -950,54 +950,6 @@ gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
[[instruction]]
|
||||
form = "v_cmp_f_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written"
|
||||
representation = "`7D000501`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select"
|
||||
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_t_i32_e32"
|
||||
encoding = "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"
|
||||
representation = "`7D0E0501`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select"
|
||||
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_u32_e32"
|
||||
encoding = "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"
|
||||
representation = "`7D800501`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select"
|
||||
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_t_u32_e32"
|
||||
encoding = "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"
|
||||
representation = "`7D8E0501`"
|
||||
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select"
|
||||
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 = "s_cbranch_scc0"
|
||||
encoding = "Nonnegative signed dword displacement"
|
||||
|
||||
@@ -38,7 +38,6 @@ PYTHONPATH=scripts python3 -m qa rdna2 discrepancies
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 diff --before before.json --after after.json --compact
|
||||
PYTHONPATH=scripts python3 -m qa verify quick
|
||||
PYTHONPATH=scripts python3 -m qa cpu-coverage --blockers
|
||||
PYTHONPATH=scripts python3 -m qa cpu-inventory --compact
|
||||
PYTHONPATH=scripts python3 -m qa bench-compare --baseline b.json --current c.json
|
||||
PYTHONPATH=scripts python3 -m release readiness --revision HEAD --live --binary path --app path.app
|
||||
```
|
||||
@@ -47,12 +46,3 @@ RDNA2 planning is read-only over the AMD snapshot, semantic registry, decoder ta
|
||||
`docs/status.toml`. Candidates and manifests are never counted as implemented forms.
|
||||
Family claims exclude those families; path-only claims block candidates whose default
|
||||
permitted files overlap. Reconcile reports mismatches without adjusting planner counts.
|
||||
|
||||
## Phase III — compatibility intelligence
|
||||
|
||||
Checkpoint ledger: [phase3-compat-ledger.md](phase3-compat-ledger.md).
|
||||
|
||||
`cpu-inventory` consumes the x86 instruction registry (not heuristic opcode scans).
|
||||
Declared forms are decodable only; native vs shared-semantic partitions come from
|
||||
read-only `dbt.rs` analysis. Unsupported intentional rejections stay in a separate catalog.
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
# Phase III compatibility-intelligence checkpoint ledger
|
||||
|
||||
Branch: `feat/infra-phase3-compat`. Issue #277.
|
||||
Approved paths only. No push without separate authorization.
|
||||
|
||||
| Milestone | Status | Commit | Tests | Next |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| M1 CPU inventory | done | `b2a36e9` | test_cpu_inventory 5 OK; cpu-inventory compact | M2 runtime inventory |
|
||||
| M2 Runtime intelligence | done | `da92995` | test_runtime_inventory 2 OK; runtime-inventory compact | M3 compat gaps |
|
||||
| M3 Compat gaps | pending | — | — | — |
|
||||
| M4 Performance intel | pending | — | — | — |
|
||||
| M5 Regression detection | pending | — | — | — |
|
||||
| M6 Task planning | pending | — | — | — |
|
||||
| M7 Unified diagnostics | pending | — | — | — |
|
||||
| M8 Verify profiles | pending | — | — | — |
|
||||
|
||||
## Notes
|
||||
|
||||
- Do not inflate coverage. Declared ≠ implemented.
|
||||
- Prefer focused `tests/qa` unit tests between milestones.
|
||||
@@ -1,28 +0,0 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0014: t1 = const.u32 0x00000000
|
||||
0018: t2 = const.u32 0x00000001
|
||||
0020: t3 = wave.mask v_cmp_f_i32_e32 t0, t0 exec=0xffffffff
|
||||
0028: t4 = xor.b32 t1, t3
|
||||
002c: t5 = const.u32 0x12345678
|
||||
002c: t6 = wave.mask v_cmp_t_i32_e32 t5, t0 exec=0xffffffff
|
||||
0034: t7 = lshl.b32 t4, t2
|
||||
0038: t8 = xor.b32 t7, t6
|
||||
0044: t9 = const.u32 0xfffffff9
|
||||
0044: t10 = wave.mask v_cmp_t_u32_e32 t9, t0 exec=0x0f0f0f0f
|
||||
0050: t11 = lshl.b32 t8, t2
|
||||
0054: t12 = xor.b32 t11, t10
|
||||
0058: t13 = wave.mask v_cmp_t_i32_e32 t0, t0 exec=0xffffffff
|
||||
0064: t14 = const.u32 0xdeadbeef
|
||||
0064: t15 = wave.mask v_cmp_f_u32_e32 t14, t0 exec=0x3c3c3c3c
|
||||
0074: t16 = lshl.b32 t12, t2
|
||||
0078: t17 = xor.b32 t16, t15
|
||||
007c: t18 = wave.mask v_cmp_t_u32_e32 t15, t0 exec=0xffffffff
|
||||
0080: branch.vccz t18 -> 0x0088
|
||||
0084: t20 = xor.b32 t17, t0
|
||||
0088: t21 = join.vccz t18, t20, t17
|
||||
0088: t22 = const.u32 0x00000040
|
||||
0088: t23 = wave.mask v_cmp_f_i32_e32 t22, t0 exec=0xffffffff
|
||||
008c: branch.vccz t23 -> 0x0094
|
||||
0090: t25 = const.u32 0x00000000
|
||||
0094: t26 = join.vccz t23, t25, t21
|
||||
0094: store.u32 output[index], t26
|
||||
@@ -1,76 +0,0 @@
|
||||
#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 = 0x00000001u;
|
||||
uint t3 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (false) ? 1u : 0u;
|
||||
t3 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t4 = t1 ^ t3;
|
||||
uint t5 = 0x12345678u;
|
||||
uint t6 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (true) ? 1u : 0u;
|
||||
t6 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t7 = t4 << (t2 & 31u);
|
||||
uint t8 = t7 ^ t6;
|
||||
uint t9 = 0xfffffff9u;
|
||||
uint t10 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (true) ? 1u : 0u;
|
||||
t10 |= ((0x0f0f0f0fu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t11 = t8 << (t2 & 31u);
|
||||
uint t12 = t11 ^ t10;
|
||||
uint t13 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (true) ? 1u : 0u;
|
||||
t13 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t14 = 0xdeadbeefu;
|
||||
uint t15 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (false) ? 1u : 0u;
|
||||
t15 |= ((0x3c3c3c3cu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t16 = t12 << (t2 & 31u);
|
||||
uint t17 = t16 ^ t15;
|
||||
uint t18 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (true) ? 1u : 0u;
|
||||
t18 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t20 = t17 ^ t0;
|
||||
uint t21 = t18 != 0u ? t20 : t17;
|
||||
uint t22 = 0x00000040u;
|
||||
uint t23 = 0u;
|
||||
for (uint lane = 0u; lane < 32u; ++lane) {
|
||||
uint lane_index = (index & ~31u) + lane;
|
||||
if (lane_index >= grid) { break; }
|
||||
uint pass = (false) ? 1u : 0u;
|
||||
t23 |= ((0xffffffffu >> lane) & pass) << lane;
|
||||
}
|
||||
uint t25 = 0x00000000u;
|
||||
uint t26 = t23 != 0u ? t25 : t21;
|
||||
output[index] = t26;
|
||||
}
|
||||
Binary file not shown.
@@ -1,45 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original Wave32 VOPC vectors for the F and T compares: both signednesses
|
||||
// with VGPR, SGPR, inline, literal and vcc_lo sources; F clearing a stale
|
||||
// VCC; T and F under partial EXEC; and runtime s_cbranch_vccz on a T result
|
||||
// (never taken) and an F result (always taken). Each wave folds its masks
|
||||
// into v2 as v2 = (v2 << 1) ^ mask. Expected results come from exact
|
||||
// definitions in tests/validation/known_answers.rs, not from this file.
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, 0x12345678
|
||||
v_mov_b32_e32 v2, 0 // accumulator
|
||||
v_mov_b32_e32 v5, 1 // shift count
|
||||
s_mov_b32 vcc_lo, -1 // stale nonzero mask
|
||||
v_cmp_f_i32_e32 vcc_lo, v1, v1 // VCC_LO = 0
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_t_i32_e32 vcc_lo, s8, v1 // every lane of the wave
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
s_mov_b32 exec_lo, 0x0f0f0f0f
|
||||
v_cmp_t_u32_e32 vcc_lo, -7, v1 // only the EXEC lanes
|
||||
s_mov_b32 exec_lo, -1
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_t_i32_e32 vcc_lo, v1, v1 // nonzero again before the F
|
||||
s_mov_b32 exec_lo, 0x3c3c3c3c
|
||||
v_cmp_f_u32_e32 vcc_lo, 0xdeadbeef, v1 // 0 even in active lanes
|
||||
s_mov_b32 exec_lo, -1
|
||||
v_mov_b32_e32 v4, vcc_lo
|
||||
v_lshlrev_b32_e32 v2, v5, v2
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_cmp_t_u32_e32 vcc_lo, vcc_lo, v1 // reads the zero mask; T anyway
|
||||
s_cbranch_vccz .Lskip // runtime branch, never taken
|
||||
v_xor_b32_e32 v2, v2, v1
|
||||
.Lskip:
|
||||
v_cmp_f_i32_e32 vcc_lo, 64, v1
|
||||
s_cbranch_vccz .Ldone // runtime branch, always taken
|
||||
v_mov_b32_e32 v2, 0
|
||||
.Ldone:
|
||||
buffer_store_dword v2, 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 vector-integer vector-compare-ft; 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 vector-integer; 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"
|
||||
|
||||
+2
-74
@@ -53,17 +53,6 @@ from .rdna2_plan import (
|
||||
write_json,
|
||||
)
|
||||
from .coverage_history import historical_report, snapshot_inventory, write_snapshot
|
||||
from .cpu_inventory import (
|
||||
build_inventory as build_cpu_inventory,
|
||||
compact_inventory as compact_cpu_inventory,
|
||||
dumps_inventory as dumps_cpu_inventory,
|
||||
)
|
||||
from .runtime_inventory import (
|
||||
build_runtime_inventory,
|
||||
compact_runtime,
|
||||
dumps_runtime,
|
||||
)
|
||||
from .compat_gaps import analyze_gaps, compact_gaps, dumps_gaps, load_dependency_report
|
||||
from .stale_branch import classify_sync, format_sync_reports
|
||||
from .verify import dumps_evidence, evidence_is_stale, load_evidence, run_profile
|
||||
|
||||
@@ -112,7 +101,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
r = sub.add_parser("rdna2", help="read-only RDNA2 expansion planning")
|
||||
r.add_argument(
|
||||
"action",
|
||||
choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile", "rank"),
|
||||
choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile"),
|
||||
)
|
||||
r.add_argument("--limit", type=int, default=0)
|
||||
r.add_argument("--family", action="append", default=[], help="filter by encoding family")
|
||||
@@ -127,26 +116,11 @@ def main(argv: list[str] | None = None) -> int:
|
||||
r.add_argument("--out", default="", help="write full JSON under this path (prefer artifacts/)")
|
||||
r.add_argument("--before", default="", help="JSON inventory for diff")
|
||||
r.add_argument("--after", default="", help="JSON inventory for diff")
|
||||
r.add_argument("--no-float", action="store_true", help="rank: exclude floating-point groups")
|
||||
|
||||
cpu = sub.add_parser("cpu-coverage", help="legacy heuristic CPU/runtime coverage scan")
|
||||
cpu = sub.add_parser("cpu-coverage", help="read-only CPU/runtime coverage scan")
|
||||
cpu.add_argument("--blockers", action="store_true")
|
||||
cpu.add_argument("--compare", default="", help="previous JSON report path")
|
||||
|
||||
cinv = sub.add_parser("cpu-inventory", help="authoritative x86 inventory from instructions.toml")
|
||||
cinv.add_argument("--compact", action="store_true")
|
||||
cinv.add_argument("--forms", action="store_true", help="include expanded form records in JSON")
|
||||
cinv.add_argument("--out", default="", help="write JSON (prefer artifacts/)")
|
||||
|
||||
rinv = sub.add_parser("runtime-inventory", help="typed runtime services from services.txt")
|
||||
rinv.add_argument("--compact", action="store_true")
|
||||
rinv.add_argument("--out", default="")
|
||||
|
||||
gaps = sub.add_parser("compat-gaps", help="read-only dependency gap analysis (no binary exec)")
|
||||
gaps.add_argument("--deps", required=True, help="JSON dependency report path")
|
||||
gaps.add_argument("--compact", action="store_true")
|
||||
gaps.add_argument("--out", default="")
|
||||
|
||||
ver = sub.add_parser("verify", help="run a verification profile")
|
||||
ver.add_argument("profile", choices=("quick", "cpu", "gpu", "app", "full", "release"))
|
||||
ver.add_argument("--revision", default="")
|
||||
@@ -169,12 +143,6 @@ def main(argv: list[str] | None = None) -> int:
|
||||
br.add_argument("--behind", type=int, required=True)
|
||||
|
||||
args = p.parse_args(argv)
|
||||
if args.command == "rdna2" and args.action == "rank":
|
||||
from .rdna2_rank import run_rank
|
||||
|
||||
return run_rank(_root(), args)
|
||||
if args.command == "rdna2" and args.no_float:
|
||||
r.error("--no-float requires the rank action")
|
||||
root = _root()
|
||||
|
||||
if args.command == "orchestrate":
|
||||
@@ -352,46 +320,6 @@ def main(argv: list[str] | None = None) -> int:
|
||||
print(dumps_cpu(report), end="")
|
||||
return 0
|
||||
|
||||
if args.command == "cpu-inventory":
|
||||
inv = build_cpu_inventory(root)
|
||||
payload = inv.to_dict()
|
||||
if not args.forms:
|
||||
payload.pop("forms", None)
|
||||
if args.out:
|
||||
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.out).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
if args.compact or args.out:
|
||||
print(compact_cpu_inventory(inv), end="")
|
||||
else:
|
||||
print(dumps_cpu_inventory(inv, include_forms=args.forms), end="")
|
||||
return 0
|
||||
|
||||
if args.command == "runtime-inventory":
|
||||
inv = build_runtime_inventory(root)
|
||||
payload = inv.to_dict()
|
||||
if args.out:
|
||||
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.out).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
if args.compact or args.out:
|
||||
print(compact_runtime(inv), end="")
|
||||
else:
|
||||
print(dumps_runtime(inv), end="")
|
||||
return 0
|
||||
|
||||
if args.command == "compat-gaps":
|
||||
deps = load_dependency_report(Path(args.deps))
|
||||
rt = build_runtime_inventory(root)
|
||||
report = analyze_gaps(deps, implemented=rt.implemented, partial=rt.partial)
|
||||
payload = report.to_dict()
|
||||
if args.out:
|
||||
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.out).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
if args.compact or args.out:
|
||||
print(compact_gaps(report), end="")
|
||||
else:
|
||||
print(dumps_gaps(report), end="")
|
||||
return 0
|
||||
|
||||
if args.command == "verify":
|
||||
if args.check_stale:
|
||||
evidence = load_evidence(Path(args.check_stale).read_text(encoding="utf-8"))
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Compatibility gap analysis over read-only dependency reports.
|
||||
|
||||
Consumes JSON describing imports required by authorized workloads. Never
|
||||
executes input binaries. Groups missing symbols by reusable subsystem.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
|
||||
# Heuristic subsystem buckets for missing Win64/CRT symbols (planning only).
|
||||
SUBSYSTEM_RULES: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
("memory", ("VirtualAlloc", "VirtualFree", "HeapAlloc", "HeapFree", "LocalAlloc", "GlobalAlloc")),
|
||||
("threading", ("CreateThread", "OpenThread", "WaitFor", "Sleep", "Tls", "CriticalSection")),
|
||||
("process", ("GetCurrentProcess", "GetProcess", "TerminateProcess", "ExitProcess", "CreateProcess")),
|
||||
("error", ("GetLastError", "SetLastError", "FormatMessage")),
|
||||
("time", ("GetSystemTime", "QueryPerformance", "GetTickCount", "Sleep")),
|
||||
("crt-math", ("sqrt", "fabs", "sin", "cos", "pow", "exp", "log", "floor", "ceil")),
|
||||
("crt-string", ("strlen", "strcmp", "strcpy", "memcpy", "memmove", "memset", "sprintf", "snprintf")),
|
||||
("file-io", ("CreateFile", "ReadFile", "WriteFile", "CloseHandle", "GetFileSize")),
|
||||
("sync", ("WaitForSingleObject", "WaitForMultipleObjects", "CreateEvent", "CreateMutex", "ReleaseMutex")),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class GapItem:
|
||||
module: str
|
||||
symbol: str
|
||||
subsystem: str
|
||||
status: str # missing | partial | present
|
||||
note: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class GapReport:
|
||||
workload: str
|
||||
total_imports: int
|
||||
missing: list[dict[str, Any]] = field(default_factory=list)
|
||||
partial: list[dict[str, Any]] = field(default_factory=list)
|
||||
present: list[dict[str, Any]] = field(default_factory=list)
|
||||
by_subsystem: dict[str, list[str]] = field(default_factory=dict)
|
||||
shared_primitives: list[str] = field(default_factory=list)
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def classify_subsystem(symbol: str) -> str:
|
||||
for name, needles in SUBSYSTEM_RULES:
|
||||
for needle in needles:
|
||||
if needle.lower() in symbol.lower():
|
||||
return name
|
||||
return "other"
|
||||
|
||||
|
||||
def _normalize_imports(payload: dict[str, Any]) -> list[tuple[str, str]]:
|
||||
"""Accept {workload, imports:[{module,symbol}| "mod!sym"]} or flat list."""
|
||||
items = payload.get("imports", payload if isinstance(payload, list) else [])
|
||||
out: list[tuple[str, str]] = []
|
||||
for item in items:
|
||||
if isinstance(item, str):
|
||||
if "!" in item:
|
||||
mod, sym = item.split("!", 1)
|
||||
else:
|
||||
mod, sym = "unknown", item
|
||||
out.append((mod, sym))
|
||||
elif isinstance(item, dict):
|
||||
mod = str(item.get("module") or item.get("dll") or "unknown")
|
||||
sym = str(item.get("symbol") or item.get("name") or "")
|
||||
if sym:
|
||||
out.append((mod, sym))
|
||||
return out
|
||||
|
||||
|
||||
def analyze_gaps(
|
||||
dependency_report: dict[str, Any],
|
||||
*,
|
||||
implemented: Iterable[str],
|
||||
partial: Iterable[str],
|
||||
) -> GapReport:
|
||||
"""Compare required imports to runtime inventory keys (`dll!symbol`)."""
|
||||
impl = {k.lower() for k in implemented}
|
||||
part = {k.lower() for k in partial}
|
||||
workload = str(dependency_report.get("workload", "unspecified"))
|
||||
imports = _normalize_imports(dependency_report)
|
||||
missing: list[GapItem] = []
|
||||
partial_hits: list[GapItem] = []
|
||||
present: list[GapItem] = []
|
||||
for module, symbol in imports:
|
||||
key = f"{module}!{symbol}".lower()
|
||||
# Also try basename match on symbol alone against inventory keys.
|
||||
symbol_keys = {k for k in impl | part if k.endswith("!" + symbol.lower())}
|
||||
if key in impl or any(k in impl for k in symbol_keys):
|
||||
present.append(GapItem(module, symbol, classify_subsystem(symbol), "present"))
|
||||
elif key in part or any(k in part for k in symbol_keys):
|
||||
partial_hits.append(GapItem(module, symbol, classify_subsystem(symbol), "partial",
|
||||
"registry status is partial"))
|
||||
else:
|
||||
missing.append(GapItem(module, symbol, classify_subsystem(symbol), "missing"))
|
||||
|
||||
by_sub: dict[str, list[str]] = defaultdict(list)
|
||||
for item in missing + partial_hits:
|
||||
by_sub[item.subsystem].append(f"{item.module}!{item.symbol}")
|
||||
# Shared primitives: subsystems with more than one missing/partial entry.
|
||||
shared = sorted(sub for sub, items in by_sub.items() if len(items) > 1 and sub != "other")
|
||||
return GapReport(
|
||||
workload=workload,
|
||||
total_imports=len(imports),
|
||||
missing=[asdict(i) for i in missing],
|
||||
partial=[asdict(i) for i in partial_hits],
|
||||
present=[asdict(i) for i in present],
|
||||
by_subsystem={k: sorted(v) for k, v in sorted(by_sub.items())},
|
||||
shared_primitives=shared,
|
||||
notes=[
|
||||
"Read-only analysis of a dependency JSON report; binaries are not executed.",
|
||||
"Subsystem grouping is advisory for prioritising shared primitives.",
|
||||
"Does not claim Xbox or commercial workload compatibility.",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def load_dependency_report(path: Path) -> dict[str, Any]:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def compact_gaps(report: GapReport) -> str:
|
||||
return (
|
||||
f"workload={report.workload} imports={report.total_imports} "
|
||||
f"missing={len(report.missing)} partial={len(report.partial)} "
|
||||
f"present={len(report.present)} shared_subsystems={len(report.shared_primitives)}\n"
|
||||
)
|
||||
|
||||
|
||||
def dumps_gaps(report: GapReport) -> str:
|
||||
return json.dumps(report.to_dict(), indent=2, sort_keys=True) + "\n"
|
||||
@@ -1,258 +0,0 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Authoritative x86-64 inventory from the instruction registry.
|
||||
|
||||
Consumes `crates/loader/x86/instructions.toml` via `generate_x86.load`.
|
||||
Classifies native lowering from read-only `is_native`/`neon_operation` arms in
|
||||
`dbt.rs`. Does not modify CPU crates or invent support percentages.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import runpy
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
REGISTRY_REL = Path("crates/loader/x86/instructions.toml")
|
||||
GENERATOR_REL = Path("crates/loader/generate_x86.py")
|
||||
DBT_REL = Path("crates/loader/src/dbt.rs")
|
||||
FIXTURE_RELS = (
|
||||
Path("crates/loader/tests/x86/integer.txt"),
|
||||
Path("crates/loader/tests/x86/vector.txt"),
|
||||
Path("crates/loader/tests/x86/float.txt"),
|
||||
)
|
||||
|
||||
# Documented intentional rejections (docs/cpu/instruction-registry.md).
|
||||
# Not registry forms; tracked separately so they are never counted as declared.
|
||||
UNSUPPORTED_CATALOG = (
|
||||
"LOCK",
|
||||
"F2/F3-as-rep (except PAUSE / declared forms)",
|
||||
"F2+F3 combined",
|
||||
"address-size override",
|
||||
"ignored segment after FS/GS",
|
||||
"16-bit stack/branch",
|
||||
"16-bit BSWAP/MOVSXD",
|
||||
"BT memory by register index",
|
||||
"RCL/RCR/SHLD/SHRD",
|
||||
"string instructions",
|
||||
"MMX",
|
||||
"RCP/RSQRT approximations",
|
||||
"SSE3+",
|
||||
"VEX",
|
||||
"atomics/fences",
|
||||
"raw SYSCALL in DBT",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FormRecord:
|
||||
op: str
|
||||
map: str
|
||||
prefix: str
|
||||
opcode: int
|
||||
digit: int | None
|
||||
enc: str
|
||||
size: str
|
||||
imm: str
|
||||
src: str
|
||||
expanded_from_count: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class CpuInventory:
|
||||
schema: int
|
||||
architecture: str
|
||||
form_count: int
|
||||
operation_count: int
|
||||
by_map: dict[str, int] = field(default_factory=dict)
|
||||
by_prefix: dict[str, int] = field(default_factory=dict)
|
||||
by_size: dict[str, int] = field(default_factory=dict)
|
||||
by_enc: dict[str, int] = field(default_factory=dict)
|
||||
operations: list[str] = field(default_factory=list)
|
||||
native_ops: list[str] = field(default_factory=list)
|
||||
shared_semantic_ops: list[str] = field(default_factory=list)
|
||||
fixture_mnemonics: list[str] = field(default_factory=list)
|
||||
ops_missing_fixture_evidence: list[str] = field(default_factory=list)
|
||||
unsupported_catalog: list[str] = field(default_factory=list)
|
||||
forms: list[dict[str, Any]] = field(default_factory=list)
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _load_generator(root: Path):
|
||||
path = root / GENERATOR_REL
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"missing generator {path}")
|
||||
# Keep generate_x86 importable without installing the package.
|
||||
sys.path.insert(0, str(path.parent))
|
||||
try:
|
||||
return runpy.run_path(str(path))
|
||||
finally:
|
||||
if sys.path and sys.path[0] == str(path.parent):
|
||||
sys.path.pop(0)
|
||||
|
||||
|
||||
def expand_forms(raw_forms: list[dict[str, Any]]) -> list[FormRecord]:
|
||||
"""Expand count>1 encodings into per-opcode records (matches generator slots)."""
|
||||
out: list[FormRecord] = []
|
||||
for form in raw_forms:
|
||||
count = int(form.get("count", 1))
|
||||
base = int(form["opcode"])
|
||||
for offset in range(count):
|
||||
out.append(
|
||||
FormRecord(
|
||||
op=str(form["op"]),
|
||||
map=str(form.get("map", "1")),
|
||||
prefix=str(form.get("prefix", "") or ""),
|
||||
opcode=base + offset,
|
||||
digit=form.get("digit"),
|
||||
enc=str(form["enc"]),
|
||||
size=str(form["size"]),
|
||||
imm=str(form.get("imm", "") or ""),
|
||||
src=str(form.get("src", "") or ""),
|
||||
expanded_from_count=count > 1,
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def parse_native_ops(dbt_text: str) -> set[str]:
|
||||
"""Collect Op::* names that appear as unconditional native arms or NEON table keys.
|
||||
|
||||
Conditional native (wide-only, encoding-gated) still counts the op as having
|
||||
a native lowering path; shared-semantic remains available for other widths.
|
||||
"""
|
||||
native: set[str] = set()
|
||||
# Arms of is_native before the final `_ => false`
|
||||
fn = re.search(r"pub fn is_native\(.*?\{(.*?)\n\}", dbt_text, re.S)
|
||||
body = fn.group(1) if fn else dbt_text
|
||||
for match in re.finditer(r"Op::([A-Za-z0-9_]+)", body):
|
||||
# Stop once we hit neon_operation definition if we grabbed too much.
|
||||
native.add(_rust_op_to_registry(match.group(1)))
|
||||
neon = re.search(r"fn neon_operation\(.*?\{(.*?)\n\}", dbt_text, re.S)
|
||||
if neon:
|
||||
for match in re.finditer(r"Op::([A-Za-z0-9_]+)", neon.group(1)):
|
||||
native.add(_rust_op_to_registry(match.group(1)))
|
||||
native.discard("syscall") # is_translatable rejects; not a native lower
|
||||
return native
|
||||
|
||||
|
||||
def _rust_op_to_registry(name: str) -> str:
|
||||
# Op::Movsxd -> movsxd, Op::Add -> add
|
||||
out = []
|
||||
for i, ch in enumerate(name):
|
||||
if ch.isupper() and i:
|
||||
out.append("_")
|
||||
out.append(ch.lower())
|
||||
return "".join(out).replace("__", "_")
|
||||
|
||||
|
||||
def parse_fixture_mnemonics(texts: list[str]) -> set[str]:
|
||||
"""First token after `|` in `hex | asm` fixture lines."""
|
||||
found: set[str] = set()
|
||||
for text in texts:
|
||||
for line in text.splitlines():
|
||||
if " | " not in line:
|
||||
continue
|
||||
asm = line.split(" | ", 1)[1].strip()
|
||||
if not asm:
|
||||
continue
|
||||
token = asm.split()[0].lower()
|
||||
# strip width suffixes used in intel syntax occasionally
|
||||
found.add(token)
|
||||
return found
|
||||
|
||||
|
||||
def mnemonic_covers_op(mnemonic: str, op: str) -> bool:
|
||||
if mnemonic == op:
|
||||
return True
|
||||
# Common aliases: jcc conditions, cmovcc, setcc, imul2 -> imul
|
||||
if op == "jcc" and mnemonic.startswith("j") and mnemonic not in {"jmp", "jecxz", "jrcxz"}:
|
||||
return True
|
||||
if op == "cmov" and mnemonic.startswith("cmov"):
|
||||
return True
|
||||
if op == "setcc" and mnemonic.startswith("set"):
|
||||
return True
|
||||
if op == "imul2" and mnemonic == "imul":
|
||||
return True
|
||||
if op in {"cwde", "cdq"} and mnemonic in {"cwde", "cdqe", "cdq", "cqo", "cbw", "cwd"}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def build_inventory(root: Path) -> CpuInventory:
|
||||
gen = _load_generator(root)
|
||||
text = (root / REGISTRY_REL).read_text(encoding="utf-8")
|
||||
operations, forms = gen["load"](text)
|
||||
records = expand_forms(forms)
|
||||
by_map: dict[str, int] = defaultdict(int)
|
||||
by_prefix: dict[str, int] = defaultdict(int)
|
||||
by_size: dict[str, int] = defaultdict(int)
|
||||
by_enc: dict[str, int] = defaultdict(int)
|
||||
for rec in records:
|
||||
by_map[rec.map] += 1
|
||||
by_prefix[rec.prefix or "none"] += 1
|
||||
by_size[rec.size] += 1
|
||||
by_enc[rec.enc] += 1
|
||||
|
||||
dbt = (root / DBT_REL).read_text(encoding="utf-8") if (root / DBT_REL).is_file() else ""
|
||||
native_ops = sorted(parse_native_ops(dbt) & set(operations))
|
||||
shared = sorted(set(operations) - set(native_ops))
|
||||
|
||||
fixture_texts = []
|
||||
for rel in FIXTURE_RELS:
|
||||
path = root / rel
|
||||
if path.is_file():
|
||||
fixture_texts.append(path.read_text(encoding="utf-8"))
|
||||
mnemonics = parse_fixture_mnemonics(fixture_texts)
|
||||
missing = sorted(
|
||||
op for op in operations
|
||||
if not any(mnemonic_covers_op(m, op) for m in mnemonics)
|
||||
and op not in {"ldmxcsr", "stmxcsr", "jcc", "jmp", "call", "ret", "hlt", "syscall"}
|
||||
)
|
||||
|
||||
notes = [
|
||||
"Declared forms are decodable; support requires semantics + fixtures (docs/cpu/instruction-registry.md).",
|
||||
"Native ops are read from dbt.rs is_native/neon_operation; conditional width/encoding gates still use shared semantics for other cases.",
|
||||
"Unsupported catalog is documentation of intentional rejections, not missing registry rows.",
|
||||
"Does not inflate coverage: fixture evidence is mnemonic-level, not form-index proof.",
|
||||
]
|
||||
return CpuInventory(
|
||||
schema=1,
|
||||
architecture="x86-64",
|
||||
form_count=len(records),
|
||||
operation_count=len(operations),
|
||||
by_map=dict(sorted(by_map.items())),
|
||||
by_prefix=dict(sorted(by_prefix.items())),
|
||||
by_size=dict(sorted(by_size.items())),
|
||||
by_enc=dict(sorted(by_enc.items())),
|
||||
operations=sorted(operations),
|
||||
native_ops=native_ops,
|
||||
shared_semantic_ops=shared,
|
||||
fixture_mnemonics=sorted(mnemonics),
|
||||
ops_missing_fixture_evidence=missing,
|
||||
unsupported_catalog=list(UNSUPPORTED_CATALOG),
|
||||
forms=[asdict(r) for r in records],
|
||||
notes=notes,
|
||||
)
|
||||
|
||||
|
||||
def compact_inventory(inv: CpuInventory) -> str:
|
||||
return (
|
||||
f"forms={inv.form_count} ops={inv.operation_count} "
|
||||
f"native={len(inv.native_ops)} shared={len(inv.shared_semantic_ops)} "
|
||||
f"maps={inv.by_map} unsupported_catalog={len(inv.unsupported_catalog)}\n"
|
||||
)
|
||||
|
||||
|
||||
def dumps_inventory(inv: CpuInventory, *, include_forms: bool = False) -> str:
|
||||
data = inv.to_dict()
|
||||
if not include_forms:
|
||||
data.pop("forms", None)
|
||||
return json.dumps(data, indent=2, sort_keys=True) + "\n"
|
||||
@@ -1,135 +0,0 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Rank registry expansion by XML identity and operand shape."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import runpy
|
||||
from argparse import Namespace
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Sequence
|
||||
|
||||
from . import rdna2_plan
|
||||
|
||||
# Relative planning weights, not measurements of implementation effort.
|
||||
ENCODING_VARIANT_COST = 1
|
||||
OPERAND_RULE_COST = 2
|
||||
PRIMITIVE_COST = 4
|
||||
|
||||
FLOAT_FORMATS = {"FMT_NUM_F16", "FMT_NUM_F32", "FMT_NUM_F64"}
|
||||
DIRECTIONS = {(False, False): "none", (True, False): "in",
|
||||
(False, True): "out", (True, True): "inout"}
|
||||
|
||||
FormKey = tuple[str, str]
|
||||
Operand = tuple[str, str, str, int, bool, bool, bool, bool]
|
||||
Signature = tuple[tuple[str, str, int, str], ...]
|
||||
|
||||
|
||||
@dataclass
|
||||
class RankGroup:
|
||||
key: str
|
||||
kind: str
|
||||
family: str
|
||||
signature: Signature
|
||||
cost: int
|
||||
forms: list[dict[str, str | int]] = field(default_factory=list)
|
||||
float: bool = False
|
||||
blocked_by_claims: int = 0
|
||||
|
||||
def payload(self) -> dict[str, Any]:
|
||||
count = len(self.forms)
|
||||
return {**asdict(self), "count": count, "score": count / self.cost}
|
||||
|
||||
|
||||
def load_xml_operands(root: Path, identified: dict[FormKey, int]) -> dict[FormKey, list[Operand]]:
|
||||
# Use the same base-row selection as the planner, including literal-only
|
||||
# forms and relative moves with non-default conditions.
|
||||
metadata = runpy.run_path(str(root / "crates/isa/generate_rdna2_meta.py"))
|
||||
snapshot = (root / "crates/isa/data/rdna2.jsonl").read_text(encoding="utf-8")
|
||||
_, _, forms = metadata["forms_from_snapshot"](snapshot)
|
||||
return {
|
||||
key: form["operands"]
|
||||
for form in forms
|
||||
if (key := (form["encoding"].upper(), form["name"])) in identified
|
||||
}
|
||||
|
||||
|
||||
def rank_groups(
|
||||
data: dict[str, Any],
|
||||
operands: dict[FormKey, list[Operand]],
|
||||
*,
|
||||
families: Sequence[str] = (),
|
||||
claims: Sequence[rdna2_plan.ClaimScope] = (),
|
||||
no_float: bool = False,
|
||||
limit: int | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
identified = data["identified"]
|
||||
declared = set(data["declared"]) | {
|
||||
(variant["family"], variant["of"])
|
||||
for variant in data["registry"].get("encoding_variant", [])
|
||||
}
|
||||
signatures = {
|
||||
key: tuple((field, kind, size, DIRECTIONS[is_input, is_output])
|
||||
for field, _, kind, size, is_input, is_output, _, _ in rows)
|
||||
for key, rows in operands.items()
|
||||
}
|
||||
formats = {
|
||||
key: tuple((row[1], row[3]) for row in rows)
|
||||
for key, rows in operands.items()
|
||||
}
|
||||
# The planner validates each form's rule. Its XML signature supplies the
|
||||
# kinds, widths and directions that the registry's rule alone lacks.
|
||||
declared_names = {name for _, name in declared}
|
||||
rule_shapes = {(key[0], signatures[key]) for key in declared if key in identified}
|
||||
declared_formats = {formats[key] for key in declared if key in identified}
|
||||
|
||||
selected = {family.upper() for family in families}
|
||||
claimed_families = {family for scope in claims for family in scope.families}
|
||||
claimed_paths = {path for scope in claims if not scope.families for path in scope.paths}
|
||||
groups: dict[str, RankGroup] = {}
|
||||
for family, name in sorted(identified.keys() - declared):
|
||||
if selected and family not in selected:
|
||||
continue
|
||||
form = (family, name)
|
||||
signature = signatures[form]
|
||||
if name in declared_names:
|
||||
kind, cost = "encoding-variant", ENCODING_VARIANT_COST
|
||||
elif (family, signature) not in rule_shapes and formats[form] in declared_formats:
|
||||
kind, cost = "operand-rule", OPERAND_RULE_COST
|
||||
else:
|
||||
kind, cost = "primitive", PRIMITIVE_COST
|
||||
shape = ",".join(f"{field}/{kind}/{size}/{direction}" for field, kind, size, direction in signature)
|
||||
key = f"{kind}:{family}:{shape}"
|
||||
if key not in groups:
|
||||
groups[key] = RankGroup(key, kind, family, signature, cost)
|
||||
group = groups[key]
|
||||
group.float |= any(fmt in FLOAT_FORMATS for fmt, _ in formats[form])
|
||||
opcode = identified[form]
|
||||
candidate = rdna2_plan.Candidate(family, name, opcode, None, None, None)
|
||||
if family in claimed_families or rdna2_plan.claims_block_candidate(candidate, claimed_paths):
|
||||
group.blocked_by_claims += 1
|
||||
else:
|
||||
group.forms.append({"name": name, "opcode": opcode})
|
||||
|
||||
ranked = [group.payload() for group in groups.values()
|
||||
if group.forms and not (no_float and group.float)]
|
||||
ranked.sort(key=lambda group: (-group["score"], -group["count"], group["key"]))
|
||||
return ranked[:limit]
|
||||
|
||||
|
||||
def run_rank(root: Path, args: Namespace) -> int:
|
||||
data = rdna2_plan.load_inventories(root)
|
||||
operands = load_xml_operands(root, data["identified"])
|
||||
claims = rdna2_plan.load_claim_scopes(Path(args.claims)) if args.claims else []
|
||||
groups = rank_groups(data, operands, families=args.family, claims=claims,
|
||||
no_float=args.no_float, limit=args.limit or None)
|
||||
if args.out:
|
||||
rdna2_plan.write_json(Path(args.out), groups)
|
||||
if args.compact or args.out:
|
||||
for group in groups:
|
||||
print(f"{group['key']} count={group['count']} cost={group['cost']} "
|
||||
f"score={group['score']:g} float={str(group['float']).lower()} "
|
||||
f"blocked_by_claims={group['blocked_by_claims']}")
|
||||
else:
|
||||
print(json.dumps(groups, indent=2, sort_keys=True))
|
||||
return 0
|
||||
@@ -1,163 +0,0 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Typed runtime service inventory from crates/loader/runtime/services.txt.
|
||||
|
||||
Separates canonical services from API-set aliases. Does not execute guests or
|
||||
modify runtime crates.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
SERVICES_REL = Path("crates/loader/runtime/services.txt")
|
||||
STATUS_VALUES = frozenset({"implemented", "partial", "stub"})
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServiceRecord:
|
||||
library: str
|
||||
symbol: str
|
||||
signature: str
|
||||
handler: str
|
||||
status: str
|
||||
aliases: list[str] = field(default_factory=list)
|
||||
fails: str = ""
|
||||
ref: str = ""
|
||||
tests: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def key(self) -> str:
|
||||
return f"{self.library}!{self.symbol}"
|
||||
|
||||
|
||||
@dataclass
|
||||
class RuntimeInventory:
|
||||
service_count: int
|
||||
by_status: dict[str, int]
|
||||
implemented: list[str]
|
||||
partial: list[str]
|
||||
stub: list[str]
|
||||
independently_verified: list[str]
|
||||
aliases: list[dict[str, str]]
|
||||
alias_count: int
|
||||
libraries: dict[str, int]
|
||||
services: list[dict[str, Any]]
|
||||
notes: list[str]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
_SERVICE_HEAD = re.compile(
|
||||
r"^service\s+(\S+)\s+(\S+)\((.*)\)\s*->\s*(\S+)\s*$"
|
||||
)
|
||||
|
||||
|
||||
def parse_services_text(text: str) -> list[ServiceRecord]:
|
||||
services: list[ServiceRecord] = []
|
||||
current: ServiceRecord | None = None
|
||||
for raw in text.splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if line.startswith("service "):
|
||||
match = _SERVICE_HEAD.match(line)
|
||||
if not match:
|
||||
raise ValueError(f"bad service header: {line}")
|
||||
library, symbol, params, result = match.groups()
|
||||
current = ServiceRecord(
|
||||
library=library,
|
||||
symbol=symbol,
|
||||
signature=f"({params}) -> {result}",
|
||||
handler="",
|
||||
status="",
|
||||
)
|
||||
services.append(current)
|
||||
continue
|
||||
if current is None:
|
||||
raise ValueError(f"field outside service: {line}")
|
||||
if " " not in line:
|
||||
raise ValueError(f"missing field value: {line}")
|
||||
key, value = line.split(None, 1)
|
||||
if key == "handler":
|
||||
current.handler = value
|
||||
elif key == "status":
|
||||
if value not in STATUS_VALUES:
|
||||
raise ValueError(f"unknown status {value!r}")
|
||||
current.status = value
|
||||
elif key == "alias":
|
||||
current.aliases.append(value)
|
||||
elif key == "fails":
|
||||
current.fails = value
|
||||
elif key == "ref":
|
||||
current.ref = value
|
||||
elif key == "test":
|
||||
current.tests.append(value)
|
||||
else:
|
||||
raise ValueError(f"unknown field {key!r}")
|
||||
for svc in services:
|
||||
if not svc.handler or not svc.status:
|
||||
raise ValueError(f"incomplete service {svc.key}")
|
||||
return services
|
||||
|
||||
|
||||
def build_runtime_inventory(root: Path) -> RuntimeInventory:
|
||||
path = root / SERVICES_REL
|
||||
services = parse_services_text(path.read_text(encoding="utf-8"))
|
||||
by_status: dict[str, int] = defaultdict(int)
|
||||
libraries: dict[str, int] = defaultdict(int)
|
||||
aliases: list[dict[str, str]] = []
|
||||
for svc in services:
|
||||
by_status[svc.status] += 1
|
||||
libraries[svc.library] += 1
|
||||
for alias in svc.aliases:
|
||||
aliases.append({
|
||||
"alias": alias,
|
||||
"canonical": svc.key,
|
||||
"symbol": svc.symbol,
|
||||
})
|
||||
# Independently verified: registry documents zero acceptance unless a future
|
||||
# field appears; do not invent. Track explicit empty list.
|
||||
independently_verified: list[str] = []
|
||||
notes = [
|
||||
"Status values are registry contracts for synthetic guests, not Xbox compatibility.",
|
||||
"API-set aliases are counted separately from canonical services.",
|
||||
"Independently verified remains empty until an acceptance process records it; not inferred.",
|
||||
"docs/runtime/services.md counts are generated; this tool re-parses services.txt.",
|
||||
]
|
||||
return RuntimeInventory(
|
||||
service_count=len(services),
|
||||
by_status=dict(sorted(by_status.items())),
|
||||
implemented=sorted(s.key for s in services if s.status == "implemented"),
|
||||
partial=sorted(s.key for s in services if s.status == "partial"),
|
||||
stub=sorted(s.key for s in services if s.status == "stub"),
|
||||
independently_verified=independently_verified,
|
||||
aliases=sorted(aliases, key=lambda a: (a["alias"], a["canonical"])),
|
||||
alias_count=len(aliases),
|
||||
libraries=dict(sorted(libraries.items())),
|
||||
services=[asdict(s) for s in services],
|
||||
notes=notes,
|
||||
)
|
||||
|
||||
|
||||
def compact_runtime(inv: RuntimeInventory) -> str:
|
||||
return (
|
||||
f"services={inv.service_count} "
|
||||
f"implemented={inv.by_status.get('implemented', 0)} "
|
||||
f"partial={inv.by_status.get('partial', 0)} "
|
||||
f"stub={inv.by_status.get('stub', 0)} "
|
||||
f"aliases={inv.alias_count} "
|
||||
f"verified={len(inv.independently_verified)}\n"
|
||||
)
|
||||
|
||||
|
||||
def dumps_runtime(inv: RuntimeInventory, *, include_services: bool = True) -> str:
|
||||
data = inv.to_dict()
|
||||
if not include_services:
|
||||
data.pop("services", None)
|
||||
return json.dumps(data, indent=2, sort_keys=True) + "\n"
|
||||
@@ -1,39 +0,0 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import unittest
|
||||
|
||||
from qa.compat_gaps import analyze_gaps, classify_subsystem, compact_gaps
|
||||
|
||||
|
||||
class CompatGaps(unittest.TestCase):
|
||||
def test_groups_missing_by_subsystem(self):
|
||||
report = analyze_gaps(
|
||||
{
|
||||
"workload": "synthetic-a",
|
||||
"imports": [
|
||||
{"module": "kernel32.dll", "symbol": "VirtualAlloc"},
|
||||
{"module": "kernel32.dll", "symbol": "VirtualFree"},
|
||||
{"module": "kernel32.dll", "symbol": "GetCurrentProcess"},
|
||||
{"module": "ucrtbase.dll", "symbol": "sqrt"},
|
||||
{"module": "kernel32.dll", "symbol": "CreateFileW"},
|
||||
],
|
||||
},
|
||||
implemented=["kernel32.dll!GetCurrentProcess"],
|
||||
partial=["kernel32.dll!VirtualAlloc", "ucrtbase.dll!sqrt"],
|
||||
)
|
||||
self.assertEqual(report.workload, "synthetic-a")
|
||||
self.assertEqual(len(report.present), 1)
|
||||
self.assertEqual(len(report.partial), 2)
|
||||
self.assertEqual(len(report.missing), 2) # VirtualFree, CreateFileW
|
||||
self.assertIn("memory", report.by_subsystem)
|
||||
self.assertIn("memory", report.shared_primitives)
|
||||
self.assertIn("binaries are not executed", " ".join(report.notes).lower())
|
||||
self.assertIn("missing=2", compact_gaps(report))
|
||||
|
||||
def test_subsystem_rules(self):
|
||||
self.assertEqual(classify_subsystem("VirtualAlloc"), "memory")
|
||||
self.assertEqual(classify_subsystem("sqrtf"), "crt-math")
|
||||
self.assertEqual(classify_subsystem("NoSuchThing"), "other")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,71 +0,0 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from qa.cpu_inventory import (
|
||||
build_inventory,
|
||||
compact_inventory,
|
||||
expand_forms,
|
||||
mnemonic_covers_op,
|
||||
parse_fixture_mnemonics,
|
||||
parse_native_ops,
|
||||
)
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class CpuInventory(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.inv = build_inventory(ROOT)
|
||||
|
||||
def test_registry_forms_not_heuristic(self):
|
||||
self.assertEqual(self.inv.schema, 1)
|
||||
self.assertEqual(self.inv.architecture, "x86-64")
|
||||
self.assertGreater(self.inv.form_count, 200)
|
||||
self.assertGreater(self.inv.operation_count, 100)
|
||||
self.assertIn("1", self.inv.by_map)
|
||||
self.assertIn("0f", self.inv.by_map)
|
||||
self.assertEqual(
|
||||
self.inv.form_count,
|
||||
sum(self.inv.by_map.values()),
|
||||
)
|
||||
|
||||
def test_native_and_shared_partition(self):
|
||||
native = set(self.inv.native_ops)
|
||||
shared = set(self.inv.shared_semantic_ops)
|
||||
ops = set(self.inv.operations)
|
||||
self.assertTrue(native)
|
||||
self.assertTrue(shared)
|
||||
self.assertTrue(native.issubset(ops))
|
||||
self.assertTrue(shared.issubset(ops))
|
||||
self.assertEqual(native | shared, ops)
|
||||
self.assertEqual(native & shared, set())
|
||||
|
||||
def test_unsupported_catalog_separate(self):
|
||||
self.assertIn("MMX", self.inv.unsupported_catalog)
|
||||
for name in self.inv.unsupported_catalog:
|
||||
self.assertNotIn(name.lower(), self.inv.operations)
|
||||
|
||||
def test_expand_count_and_fixtures(self):
|
||||
expanded = expand_forms(
|
||||
[{"op": "push", "opcode": 0x50, "count": 8, "enc": "op_reg", "size": "q"}]
|
||||
)
|
||||
self.assertEqual(len(expanded), 8)
|
||||
self.assertEqual(expanded[0].opcode, 0x50)
|
||||
self.assertEqual(expanded[7].opcode, 0x57)
|
||||
mnems = parse_fixture_mnemonics(["00 cb | add bl, cl\n66 01 cb | add bx, cx\n"])
|
||||
self.assertEqual(mnems, {"add"})
|
||||
self.assertTrue(mnemonic_covers_op("je", "jcc"))
|
||||
self.assertTrue(mnemonic_covers_op("imul", "imul2"))
|
||||
|
||||
def test_compact_and_no_coverage_inflation(self):
|
||||
text = compact_inventory(self.inv)
|
||||
self.assertIn(f"forms={self.inv.form_count}", text)
|
||||
# Notes must deny inflation.
|
||||
joined = " ".join(self.inv.notes).lower()
|
||||
self.assertIn("does not inflate", joined)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,111 +0,0 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import io
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from qa.__main__ import main
|
||||
from qa.rdna2_plan import load_claim_scopes
|
||||
from qa.rdna2_rank import rank_groups
|
||||
|
||||
|
||||
def operand(field, kind, fmt="FMT_NUM_U32", *, output=False):
|
||||
return (field, fmt, kind, 32, not output, output, False, True)
|
||||
|
||||
|
||||
class Rdna2Rank(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.base = ("VOP2", "SYNTHETIC_ADD")
|
||||
self.variant = ("VOP3", "SYNTHETIC_ADD")
|
||||
self.rule = ("SOP2", "SYNTHETIC_OTHER")
|
||||
self.primitive = ("VOP2", "SYNTHETIC_NEW")
|
||||
self.floating = ("VOP2", "SYNTHETIC_FLOAT")
|
||||
self.data = {
|
||||
"identified": {self.primitive: 5, self.variant: 17, self.base: 2,
|
||||
self.floating: 4, self.rule: 11},
|
||||
"declared": {self.base},
|
||||
"registry": {},
|
||||
}
|
||||
dst = operand("VDST", "OPR_VGPR", output=True)
|
||||
src = operand("SRC0", "OPR_SRC")
|
||||
self.operands = {
|
||||
self.base: [dst, src],
|
||||
self.variant: [dst, operand("SRC0", "OPR_SRC_NOLDS")],
|
||||
self.rule: [operand("SDST", "OPR_SGPR", output=True), src],
|
||||
self.primitive: [dst, src],
|
||||
self.floating: [dst, operand("SRC0", "OPR_SRC", "FMT_NUM_F32")],
|
||||
}
|
||||
|
||||
def test_kinds_and_costs_determine_ranking(self):
|
||||
groups = rank_groups(self.data, self.operands)
|
||||
self.assertEqual(
|
||||
[(group["kind"], group["cost"], group["score"]) for group in groups],
|
||||
[("encoding-variant", 1, 1.0), ("primitive", 4, 0.5), ("operand-rule", 2, 0.5)],
|
||||
)
|
||||
self.assertEqual(groups[0]["family"], "VOP3")
|
||||
self.assertEqual(groups[0]["forms"], [{"name": "SYNTHETIC_ADD", "opcode": 17}])
|
||||
self.assertEqual(groups[0]["signature"], (
|
||||
("VDST", "OPR_VGPR", 32, "out"), ("SRC0", "OPR_SRC_NOLDS", 32, "in"),
|
||||
))
|
||||
|
||||
def test_declared_variant_is_not_ranked_and_supplies_a_rule_shape(self):
|
||||
self.data["registry"]["encoding_variant"] = [
|
||||
{"of": self.base[1], "family": "VOP3", "opcode": 17, "operands": "synthetic_rule"},
|
||||
]
|
||||
other = ("VOP3", "SYNTHETIC_OTHER")
|
||||
self.data["identified"][other] = 18
|
||||
self.operands[other] = self.operands[self.variant]
|
||||
groups = rank_groups(self.data, self.operands, families=["vop3"])
|
||||
self.assertEqual(len(groups), 1)
|
||||
self.assertEqual(groups[0]["kind"], "primitive")
|
||||
self.assertEqual(groups[0]["forms"], [{"name": other[1], "opcode": 18}])
|
||||
|
||||
def test_claim_file_family_and_path_scopes(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "claims.json"
|
||||
path.write_text(json.dumps({"claims": [
|
||||
{"families": ["vop3"], "paths": ["crates/isa/**"]},
|
||||
{"paths": ["unrelated/**"]},
|
||||
]}), encoding="utf-8")
|
||||
remaining = rank_groups(self.data, self.operands, claims=load_claim_scopes(path))
|
||||
self.assertEqual([group["family"] for group in remaining], ["VOP2", "SOP2"])
|
||||
path.write_text(json.dumps([{"paths": ["crates/isa/**"]}]), encoding="utf-8")
|
||||
self.assertEqual(rank_groups(self.data, self.operands, claims=load_claim_scopes(path)), [])
|
||||
|
||||
def test_partially_blocked_group_reports_dropped_form(self):
|
||||
with patch("qa.rdna2_plan.claims_block_candidate", side_effect=lambda cand, _: cand.name == self.primitive[1]):
|
||||
groups = rank_groups(self.data, self.operands, families=["VOP2"])
|
||||
self.assertEqual(groups[0]["blocked_by_claims"], 1)
|
||||
self.assertEqual(groups[0]["count"], 1)
|
||||
self.assertEqual(groups[0]["score"], 0.25)
|
||||
self.assertEqual(groups[0]["forms"], [{"name": self.floating[1], "opcode": 4}])
|
||||
|
||||
def test_float_marker_and_cli_filter(self):
|
||||
def invoke(*flags):
|
||||
stdout = io.StringIO()
|
||||
with redirect_stdout(stdout):
|
||||
self.assertEqual(main(["rdna2", "rank", *flags]), 0)
|
||||
return stdout.getvalue()
|
||||
|
||||
with (
|
||||
patch("qa.rdna2_plan.load_inventories", return_value=self.data),
|
||||
patch("qa.rdna2_rank.load_xml_operands", return_value=self.operands),
|
||||
):
|
||||
groups = json.loads(invoke())
|
||||
self.assertEqual([group["float"] for group in groups], [False, True, False])
|
||||
self.assertEqual(json.loads(invoke("--no-float")), [groups[0], groups[2]])
|
||||
self.assertEqual(json.loads(invoke("--family", "sop2", "--limit", "1")), [groups[2]])
|
||||
self.assertEqual(len(invoke("--no-float", "--compact").splitlines()), 2)
|
||||
|
||||
def test_deterministic_with_reordered_inventory_and_equal_scores(self):
|
||||
additional_rule = ("SOP1", "SYNTHETIC_OTHER")
|
||||
self.data["identified"][additional_rule] = 1
|
||||
self.operands[additional_rule] = self.operands[self.rule]
|
||||
first = rank_groups(self.data, self.operands)
|
||||
reordered = {**self.data, "identified": dict(reversed(list(self.data["identified"].items())))}
|
||||
second = rank_groups(reordered, dict(reversed(list(self.operands.items()))))
|
||||
self.assertEqual(first, second)
|
||||
self.assertEqual([group["family"] for group in first], ["VOP3", "VOP2", "SOP1", "SOP2"])
|
||||
@@ -1,56 +0,0 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from qa.runtime_inventory import build_runtime_inventory, compact_runtime, parse_services_text
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
SAMPLE = """
|
||||
# comment
|
||||
service kernel32.dll GetCurrentProcess() -> handle
|
||||
handler get_current_process
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentProcess
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service ucrtbase.dll sqrt(x: f64) -> f64
|
||||
handler crt_sqrt
|
||||
status partial
|
||||
fails NaN for a negative argument
|
||||
ref math.h sqrt
|
||||
test crt_math_guest_dispatch
|
||||
"""
|
||||
|
||||
|
||||
class RuntimeInventory(unittest.TestCase):
|
||||
def test_parse_separates_aliases(self):
|
||||
services = parse_services_text(SAMPLE)
|
||||
self.assertEqual(len(services), 2)
|
||||
self.assertEqual(services[0].status, "implemented")
|
||||
self.assertEqual(services[0].aliases, ["api-ms-win-core-processthreads-l1-1-0.dll"])
|
||||
self.assertEqual(services[1].library, "ucrtbase.dll")
|
||||
|
||||
def test_live_registry(self):
|
||||
inv = build_runtime_inventory(ROOT)
|
||||
self.assertGreaterEqual(inv.service_count, 20)
|
||||
self.assertEqual(
|
||||
inv.service_count,
|
||||
inv.by_status.get("implemented", 0)
|
||||
+ inv.by_status.get("partial", 0)
|
||||
+ inv.by_status.get("stub", 0),
|
||||
)
|
||||
self.assertEqual(inv.independently_verified, [])
|
||||
self.assertGreater(inv.alias_count, 0)
|
||||
# Aliases are separate records pointing at canonical services.
|
||||
self.assertTrue(all("canonical" in a and "alias" in a for a in inv.aliases))
|
||||
self.assertTrue(all("!" in a["canonical"] for a in inv.aliases))
|
||||
text = compact_runtime(inv)
|
||||
self.assertIn(f"services={inv.service_count}", text)
|
||||
self.assertIn("verified=0", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -144,34 +144,9 @@ def snapshot():
|
||||
"instruction": name, "encoding": "ENC_VOP2", "opcode": opcode,
|
||||
"operands": vector(data_format),
|
||||
}
|
||||
vopc = {
|
||||
"name": "ENC_VOPC",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SRC0", [[0, 9]]], ["VSRC1", [[9, 8]]], ["OP", [[17, 8]]], ["ENCODING", [[25, 7]]],
|
||||
],
|
||||
"identifier_mask": 0xFFFE0000,
|
||||
"identifiers": [0x7C000000 | (op << 17) for op in (129, 135, 192, 197)],
|
||||
}
|
||||
for name, opcode, data_format in (
|
||||
("V_CMP_LT_I32", 129, I32), ("V_CMP_T_I32", 135, I32), ("V_CMP_F_U32", 192, U32),
|
||||
("V_CMP_NE_U32", 197, U32),
|
||||
):
|
||||
variants[(name, "ENC_VOPC")] = {
|
||||
"instruction": name, "encoding": "ENC_VOPC", "opcode": opcode,
|
||||
# Values copied from the AMD XML snapshot: an implicit 64-bit VCC output.
|
||||
"operands": [
|
||||
["", "FMT_NUM_M64", "OPR_VCC", 64, False, True, False, False],
|
||||
["SRC0", data_format, "OPR_SRC", 32, True, False, False, True],
|
||||
["VSRC1", data_format, "OPR_VGPR", 32, True, False, False, True],
|
||||
],
|
||||
}
|
||||
return {
|
||||
"source": {"sha256": SHA},
|
||||
"encodings": {
|
||||
"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1, "ENC_VOP2": vop2,
|
||||
"ENC_VOPC": vopc,
|
||||
},
|
||||
"encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1, "ENC_VOP2": vop2},
|
||||
"variants": variants,
|
||||
}
|
||||
|
||||
@@ -242,29 +217,6 @@ def vectors():
|
||||
return reg
|
||||
|
||||
|
||||
def vector_compares():
|
||||
reg = registry()
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["vopc_vcc"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.OPERAND_RULES["vopc_vcc"]["unsupported"])
|
||||
reg["operand_rules"]["vopc_vcc"] = rule
|
||||
|
||||
def compare(name, opcode, variant, relation, signedness):
|
||||
form = _form(name, opcode, variant, "compare", signedness, "unchanged")
|
||||
form.update(
|
||||
family="VOPC", relation=relation, operands="vopc_vcc", vcc="lane_mask", wave="wave32"
|
||||
)
|
||||
return form
|
||||
|
||||
reg["form"] += [
|
||||
# The same variant name as a SOPC form: variants are per enum.
|
||||
compare("V_CMP_LT_I32", 129, "CmpLtI32", "lt", "signed"),
|
||||
compare("V_CMP_T_I32", 135, "CmpTI32", "t", "signed"),
|
||||
compare("V_CMP_F_U32", 192, "CmpFU32", "f", "unsigned"),
|
||||
compare("V_CMP_NE_U32", 197, "CmpNeU32", "lg", "unsigned"),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def compares():
|
||||
reg = registry()
|
||||
reg["form"] += [
|
||||
@@ -786,113 +738,7 @@ class Validate(unittest.TestCase):
|
||||
def test_rejects_an_unenforced_wave_restriction(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["wave"] = "wave32"
|
||||
self.rejects(reg, "S_ADD_U32: wave wave32 is not enforced for this rule (requires any)")
|
||||
|
||||
# ---- VOPC lane-mask compares ----
|
||||
|
||||
def test_accepts_vector_compares(self):
|
||||
self.assertEqual(self.errors(vector_compares()), [])
|
||||
|
||||
def test_rejects_a_vector_compare_declared_for_any_wave(self):
|
||||
reg = vector_compares()
|
||||
form(reg, "V_CMP_LT_I32")["wave"] = "any"
|
||||
self.rejects(reg, "V_CMP_LT_I32: wave any is not enforced for this rule (requires wave32)")
|
||||
|
||||
def test_rejects_a_vector_compare_without_its_vcc_write(self):
|
||||
reg = vector_compares()
|
||||
form(reg, "V_CMP_LT_I32")["vcc"] = "unchanged"
|
||||
self.rejects(reg, "V_CMP_LT_I32: vcc unchanged contradicts rule vopc_vcc (requires lane_mask)")
|
||||
# The XML VCC output is then undeclared as well.
|
||||
self.rejects(reg, "V_CMP_LT_I32: XML implicit operands ['OPR_VCC'] are not declared")
|
||||
|
||||
def test_rejects_a_lane_mask_outside_vopc(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["vcc"] = "lane_mask"
|
||||
self.rejects(reg, "S_ADD_U32: vcc lane_mask contradicts rule sop2_sgpr (requires unchanged)")
|
||||
self.rejects(reg, "S_ADD_U32: vcc lane_mask but the XML has no implicit VCC output")
|
||||
|
||||
def test_rejects_an_exec_write(self):
|
||||
reg = vector_compares()
|
||||
form(reg, "V_CMP_LT_I32")["exec"] = "lane_mask"
|
||||
self.rejects(reg, "V_CMP_LT_I32: exec lane_mask has no contract (requires unchanged)")
|
||||
|
||||
def test_rejects_a_vector_compare_that_writes_scc(self):
|
||||
reg = vector_compares()
|
||||
form(reg, "V_CMP_LT_I32")["scc"] = "relation"
|
||||
self.rejects(reg, "V_CMP_LT_I32: scc relation contradicts compare (requires unchanged)")
|
||||
|
||||
def test_rejects_a_vector_compare_without_a_relation(self):
|
||||
reg = vector_compares()
|
||||
del form(reg, "V_CMP_NE_U32")["relation"]
|
||||
self.rejects(reg, "V_CMP_NE_U32: unknown or missing relation None")
|
||||
|
||||
def test_rejects_a_vector_compare_under_a_scalar_rule(self):
|
||||
reg = vector_compares()
|
||||
form(reg, "V_CMP_LT_I32")["operands"] = "sopc_scalar"
|
||||
self.rejects(reg, "V_CMP_LT_I32: operand rule sopc_scalar is for SOPC")
|
||||
|
||||
def test_rejects_a_vector_compare_signedness_against_the_xml(self):
|
||||
reg = vector_compares()
|
||||
form(reg, "V_CMP_LT_I32")["signedness"] = "unsigned"
|
||||
self.rejects(reg, "V_CMP_LT_I32: signedness unsigned contradicts XML format FMT_NUM_I32")
|
||||
|
||||
def test_rejects_f_and_t_outside_vopc(self):
|
||||
for relation in ("f", "t"):
|
||||
with self.subTest(relation=relation):
|
||||
reg = compares()
|
||||
form(reg, "S_CMP_LT_I32")["relation"] = relation
|
||||
self.rejects(reg, f"S_CMP_LT_I32: relation {relation} exists only for VOPC compares")
|
||||
|
||||
def test_renders_f_and_t_primitives(self):
|
||||
reg = vector_compares()
|
||||
self.assertEqual(self.errors(reg), [])
|
||||
text = gen.render(reg, snapshot())
|
||||
self.assertIn("Self::CmpTI32 => primitive::true_b32(src0, src1),", text)
|
||||
self.assertIn("Self::CmpFU32 => CompareRelation::False,", text)
|
||||
|
||||
def test_rejects_a_vopc_relation_that_contradicts_the_opcode(self):
|
||||
for name, relation, expected in (
|
||||
("V_CMP_T_I32", "f", 128), ("V_CMP_LT_I32", "gt", 132), ("V_CMP_F_U32", "t", 199),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
reg = vector_compares()
|
||||
form(reg, name)["relation"] = relation
|
||||
signedness = form(reg, name)["signedness"]
|
||||
self.rejects(
|
||||
reg,
|
||||
f"{name}: relation {relation}/{signedness} has VOPC opcode {expected} "
|
||||
f"(guide Table 59), not {form(reg, name)['opcode']}",
|
||||
)
|
||||
|
||||
def test_rejects_an_implicit_vcc_read_as_a_lane_mask_write(self):
|
||||
for direction in ([True, False], [True, True]):
|
||||
with self.subTest(direction=direction):
|
||||
snap = snapshot()
|
||||
operands = snap["variants"][("V_CMP_T_I32", "ENC_VOPC")]["operands"]
|
||||
operands[0][4:6] = direction
|
||||
self.rejects(
|
||||
vector_compares(),
|
||||
"V_CMP_T_I32: vcc lane_mask but the XML has no implicit VCC output",
|
||||
snap,
|
||||
)
|
||||
|
||||
def test_rejects_a_second_implicit_vcc_operand(self):
|
||||
snap = snapshot()
|
||||
operands = snap["variants"][("V_CMP_T_I32", "ENC_VOPC")]["operands"]
|
||||
operands.append(["", "FMT_NUM_M64", "OPR_VCC", 64, True, False, False, False])
|
||||
self.rejects(
|
||||
vector_compares(), "V_CMP_T_I32: vcc lane_mask but the XML has no implicit VCC output", snap
|
||||
)
|
||||
|
||||
def test_renders_vector_compare_dispatch(self):
|
||||
text = gen.render(vector_compares(), snapshot())
|
||||
self.assertIn("pub enum VectorCompareOp {", text)
|
||||
self.assertIn("if word & 0xfe00_0000 != 0x7c00_0000 {", text)
|
||||
self.assertIn('Self::CmpNeU32 => "v_cmp_ne_u32_e32",', text)
|
||||
self.assertIn("Self::CmpLtI32 => true,", text.split("fn signed", 1)[1])
|
||||
self.assertIn("Self::CmpNeU32 => primitive::ne_b32(src0, src1),", text)
|
||||
self.assertIn("vcc: MaskEffect::LaneMask,", text)
|
||||
self.assertIn("wave: Wave::Wave32,", text)
|
||||
self.rejects(reg, "S_ADD_U32: wave wave32 has no decoder enforcement yet")
|
||||
|
||||
def test_rejects_a_reserved_variant(self):
|
||||
reg = registry()
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
//! production operator. SOP2 arithmetic runs through a bit-serial ripple
|
||||
//! adder (subtraction as addition of the complement), not host integer ops.
|
||||
//!
|
||||
//! Wave32 VOPC integer compares (`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i32,u32}_e32`,
|
||||
//! Wave32 VOPC integer compares (`v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`,
|
||||
//! contract `docs/shaders/vector-compare.md`) need all lanes of a wave, so execution
|
||||
//! runs lockstep waves of 32 consecutive dispatch indices with wave-uniform
|
||||
//! scalar state and per-lane vector state. A lane-local failure stops only that
|
||||
@@ -75,7 +75,7 @@ enum Insn {
|
||||
VMovFromSgpr(u8, u8),
|
||||
/// `v_mov_b32_e32 vD, vcc_lo`.
|
||||
VMovFromVcc(u8),
|
||||
/// VOPC compare into VCC_LO: relation 0 f, 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge, 7 t.
|
||||
/// VOPC compare into VCC_LO: relation 1 lt, 2 eq, 3 le, 4 gt, 5 ne, 6 ge.
|
||||
VCmp {
|
||||
relation: u8,
|
||||
signed: bool,
|
||||
@@ -585,17 +585,13 @@ fn compare(
|
||||
} else {
|
||||
(a, b)
|
||||
};
|
||||
// Guide 12.9 Table 59 offsets; F (0) and T (7) ignore the operand
|
||||
// values but still read them (contract 5: sources are validated).
|
||||
let pass = match relation {
|
||||
0 => false,
|
||||
1 => a < b,
|
||||
2 => a == b,
|
||||
3 => a <= b,
|
||||
4 => a > b,
|
||||
5 => a != b,
|
||||
6 => a >= b,
|
||||
_ => true,
|
||||
_ => a >= b,
|
||||
};
|
||||
mask |= u32::from(pass) << n;
|
||||
}
|
||||
@@ -1043,8 +1039,8 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
if first >> 25 == 0b011_1110 {
|
||||
let opcode = (first >> 17) & 0xff;
|
||||
let (signed, relation) = match opcode {
|
||||
128..=135 => (true, opcode - 128),
|
||||
192..=199 => (false, opcode - 192),
|
||||
129..=134 => (true, opcode - 128),
|
||||
193..=198 => (false, opcode - 192),
|
||||
_ => return Err(fail("unsupported VOPC opcode")),
|
||||
};
|
||||
let (src0, len) = vector_src0(code, offset, first, "VOPC")?;
|
||||
|
||||
@@ -1308,21 +1308,6 @@ mod review {
|
||||
// ---- VOPC integer compares (docs/shaders/vector-compare.md) ----
|
||||
|
||||
const COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-compare.bin");
|
||||
const COMPARE_FT_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-compare-ft.bin");
|
||||
|
||||
/// fixtures/rdna2/vector-compare-ft.s, from its listing and guide 12.9
|
||||
/// Table 61 (F: D = 0, T: D = 1) with VCC_LO[n] = EXEC_LO[n] & test: every
|
||||
/// F mask is 0 and every T mask is EXEC_LO & the lanes that exist, so the
|
||||
/// T branch is never taken and the F branch always is.
|
||||
fn compare_ft_expected(input: &[u32]) -> Vec<u32> {
|
||||
let mut output = Vec::new();
|
||||
for wave in input.chunks(32) {
|
||||
let exists = wave_mask(wave, u32::MAX, |_| true);
|
||||
let folded = ((exists << 1) ^ (exists & 0x0f0f_0f0f)) << 1;
|
||||
output.extend(wave.iter().map(|&x| folded ^ x));
|
||||
}
|
||||
output
|
||||
}
|
||||
const COMPARE_VALUES: [u32; 10] = [
|
||||
0,
|
||||
1,
|
||||
@@ -1427,30 +1412,6 @@ mod review {
|
||||
input
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_ft_fixture_matches_exact_definitions() {
|
||||
// A full wave and a final partial wave of 7 lanes.
|
||||
let mut input = compare_fixture_input()[..32].to_vec();
|
||||
input.extend([0, 1, u32::MAX, 0x8000_0000, 0x7fff_ffff, 64, 0x1234_5678]);
|
||||
let expected = compare_ft_expected(&input);
|
||||
verify(COMPARE_FT_FIXTURE, &input, Some(&expected));
|
||||
// The partial wave's T masks have only its 7 lanes.
|
||||
assert_eq!(expected[32], ((0x7f << 1) ^ 0x0f) << 1);
|
||||
let compiled = compile(Architecture::Gfx1030, COMPARE_FT_FIXTURE).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir.matches("wave.mask").count(),
|
||||
7,
|
||||
"{}",
|
||||
compiled.ir
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.ir.matches("join.vccz").count(),
|
||||
2,
|
||||
"{}",
|
||||
compiled.ir
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_fixture_matches_exact_definitions() {
|
||||
let input = compare_fixture_input();
|
||||
@@ -1841,10 +1802,12 @@ mod review {
|
||||
let mut code = base.clone();
|
||||
code[0x14..0x18].copy_from_slice(&vopc(129, 256 + 1, 9).to_le_bytes());
|
||||
rejected_at(&code, 0x14);
|
||||
// v_cmpx (writes EXEC) and the VOP3 encoding.
|
||||
let mut code = base.clone();
|
||||
code[0x14..0x18].copy_from_slice(&vopc(210, 257, 3).to_le_bytes());
|
||||
rejected_at(&code, 0x14);
|
||||
// v_cmpx (writes EXEC), F and T forms, and the VOP3 encoding.
|
||||
for word in [vopc(210, 257, 3), vopc(128, 257, 3), vopc(135, 257, 3)] {
|
||||
let mut code = base.clone();
|
||||
code[0x14..0x18].copy_from_slice(&word.to_le_bytes());
|
||||
rejected_at(&code, 0x14);
|
||||
}
|
||||
let mut e64 = base[..0x14].to_vec();
|
||||
e64.extend(words(&[0xd481_006a, 0x0002_0701]));
|
||||
e64.extend_from_slice(&base[0x18..]);
|
||||
@@ -1931,10 +1894,6 @@ mod review {
|
||||
assert_eq!(run(&join, &[1, 0, 5, 0]), [0b1010; 4]);
|
||||
assert_eq!(run(&join, &[0, 0, 0, 0]), [0; 4]);
|
||||
programs += 2;
|
||||
let mut input = compare_fixture_input()[..32].to_vec();
|
||||
input.extend([0, 1, u32::MAX, 0x8000_0000, 0x7fff_ffff, 64, 0x1234_5678]);
|
||||
assert_eq!(run(COMPARE_FT_FIXTURE, &input), compare_ft_expected(&input));
|
||||
programs += 1;
|
||||
eprintln!("{programs} VOPC programs matched on native Metal");
|
||||
}
|
||||
}
|
||||
@@ -1,704 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent per-lane expected values for the four constant Wave32 VOPC
|
||||
//! integer compares (#215): `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and
|
||||
//! `v_cmp_t_u32`, `_e32` only, under the contract in
|
||||
//! `docs/shaders/vector-compare.md` (sections 2-7).
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.9 "VOPC Instructions"
|
||||
//! (Table 59 "Eight Compare Operations" and Table 61 "VOPC Compare Opcodes"),
|
||||
//! section 3.9 "Vector Compares: VCC and VCCZ", and the VOPC word layout of
|
||||
//! section 13.3.3. Nothing here comes from the ISA crate, the semantic
|
||||
//! registry, the decoder or the shader compiler. Every case runs on the
|
||||
//! reference interpreter `xenora_ref` and on the second interpreter
|
||||
//! `independent_ref`; the ignored test also runs the translated MSL on native
|
||||
//! Metal.
|
||||
//!
|
||||
//! Readings of the guide (not hardware evidence):
|
||||
//! - Table 61: F is `D[threadId] = 0`, T is `D[threadId] = 1`, with "D = VCC in
|
||||
//! VOPC encoding"; Table 59 gives the same as offsets F 0 and TRU 7.
|
||||
//! - Section 3.9: `V_CMP_* => VCC[n] = EXEC[n] & (test passed for thread[n])`
|
||||
//! and "VCC is fully written; there are no partial mask updates". So T writes
|
||||
//! EXEC_LO masked to the lanes that exist, F writes 0 even for active lanes,
|
||||
//! and stale VCC bits never survive either.
|
||||
//! - Section 3.9: in wave32 only VCC_LO contributes to VCCZ, so
|
||||
//! `s_cbranch_vccz` after F is taken, after T with EXEC_LO != 0 it is not,
|
||||
//! and after T with EXEC_LO = 0 it is.
|
||||
//! - The guide does not say that F and T skip their sources. They keep the
|
||||
//! SRC0 allowlist and the contract section 5 rule: with EXEC_LO != 0 every
|
||||
//! source must be valid and initialized; with EXEC_LO = 0 the encoding is
|
||||
//! validated and no source is read. A lane-derived VCC_LO stays
|
||||
//! lane-derived even though F's value is always 0 (contract section 5).
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod harness;
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harness::{Case, words};
|
||||
use xenora_shader::{Architecture, CompileError, compile};
|
||||
|
||||
/// The four forms with their ENC_VOPC opcodes (guide 12.9, Table 61).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Form {
|
||||
FI32 = 128,
|
||||
TI32 = 135,
|
||||
FU32 = 192,
|
||||
TU32 = 199,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 4] = [
|
||||
(Form::FI32, "v_cmp_f_i32"),
|
||||
(Form::TI32, "v_cmp_t_i32"),
|
||||
(Form::FU32, "v_cmp_f_u32"),
|
||||
(Form::TU32, "v_cmp_t_u32"),
|
||||
];
|
||||
|
||||
/// The per-lane test. The operands are taken so every call site names them,
|
||||
/// but neither form depends on them.
|
||||
fn test(form: Form, _s0: u32, _s1: u32) -> bool {
|
||||
match form {
|
||||
// 128 V_CMP_F_I32 / 192 V_CMP_F_U32: D[threadId] = 0.
|
||||
Form::FI32 | Form::FU32 => false,
|
||||
// 135 V_CMP_T_I32 / 199 V_CMP_T_U32: D[threadId] = 1.
|
||||
Form::TI32 | Form::TU32 => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Section 3.9 and contract section 3: VCC_LO = OR over the lanes n that
|
||||
/// exist (`present`) of (EXEC[n] & test(n)) << n, with S0 and S1 of lane n
|
||||
/// from `operands(n)`.
|
||||
fn vcc(form: Form, exec: u32, present: u32, operands: impl Fn(usize) -> (u32, u32)) -> u32 {
|
||||
(0..32)
|
||||
.filter(|&n| (present & exec) >> n & 1 == 1)
|
||||
.filter(|&n| {
|
||||
let (s0, s1) = operands(n);
|
||||
test(form, s0, s1)
|
||||
})
|
||||
.fold(0, |mask, n| mask | 1 << n)
|
||||
}
|
||||
|
||||
/// Boundary operands.
|
||||
const VALUES: [u32; 8] = [
|
||||
0,
|
||||
1,
|
||||
0x1234_5678,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
];
|
||||
/// Per-lane inputs: the boundary values first, then 24 more, all different.
|
||||
const MORE_LANES: [u32; 24] = [
|
||||
2,
|
||||
0x0000_00ff,
|
||||
0x0000_ffff,
|
||||
0x00ff_ffff,
|
||||
0x0f0f_0f0f,
|
||||
0x4000_0000,
|
||||
0x5555_5555,
|
||||
0x7fff_fffe,
|
||||
0x8765_4321,
|
||||
0xaaaa_aaaa,
|
||||
0xc000_0000,
|
||||
0xf0f0_f0f0,
|
||||
0xff00_0000,
|
||||
0xffff_0000,
|
||||
0xffff_ff00,
|
||||
0xffff_fff0,
|
||||
3,
|
||||
16,
|
||||
64,
|
||||
65,
|
||||
0x0000_0100,
|
||||
0x00c0_ffee,
|
||||
0x1fff_ffff,
|
||||
0xdead_beef,
|
||||
];
|
||||
const LITERALS: [u32; 5] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX];
|
||||
const SGPR_VALUES: [u32; 3] = [0, 0x8000_0000, u32::MAX];
|
||||
/// The last one is set explicitly, as a full EXEC written by `s_mov_b32`.
|
||||
const EXEC_MASKS: [u32; 7] = [
|
||||
0,
|
||||
0x5555_5555,
|
||||
0xaaaa_aaaa,
|
||||
0x8000_0001,
|
||||
0x0000_ffff,
|
||||
0x7fff_fffe,
|
||||
u32::MAX,
|
||||
];
|
||||
/// VCC_LO before the compare in the EXEC cases: bits inside and outside every
|
||||
/// mask above, so a partial VCC update would show.
|
||||
const STALE_VCC: u32 = 0xa5a5_c33c;
|
||||
/// XORed with v1 to give every lane its own old v2 before a masked move.
|
||||
const OLD: u32 = 0x0bad_f00d;
|
||||
|
||||
const COUNTS: [(&str, usize); 12] = [
|
||||
("vopc domain", 4 * 8 * 2),
|
||||
("vopc aliasing", 4 * 2),
|
||||
("vopc inline integer", 4 * 81),
|
||||
("vopc literal", 4 * 5),
|
||||
("vopc sgpr source", 4 * 2 * 3),
|
||||
("vopc vcc_lo source", 4 * 4),
|
||||
("vopc max register", 4 * 3),
|
||||
("vopc exec", 4 * (7 + 2)),
|
||||
("vopc empty exec reads nothing", 4 * 3),
|
||||
("vopc partial wave", 4 * 3),
|
||||
("vopc vccz branch", 4 * 4),
|
||||
("vopc exec unchanged", 4 * 2),
|
||||
];
|
||||
/// Per form: 4 uninitialized sources, 2 sources with a load outstanding, a missing literal, 9 float inline
|
||||
/// constants, 9 other special SRC0 selectors, a float constant under empty
|
||||
/// EXEC, SDWA, DPP16 and two DPP8 forms, the VOP3 `_e64` form, the matching
|
||||
/// `v_cmpx`, and a lane-derived F result branching over a scalar instruction.
|
||||
const REJECTIONS: usize = 4 * (4 + 2 + 1 + 9 + 9 + 1 + 4 + 1 + 1 + 1);
|
||||
|
||||
const LITERAL: u32 = 255;
|
||||
const VCC_LO: u32 = 106;
|
||||
const EXEC_LO: u32 = 126;
|
||||
|
||||
/// ENCODING 0b0111110 in bits 25-31, OP 17-24, VSRC1 9-16, SRC0 0-8 (guide
|
||||
/// 13.3.3); SRC0 256 + n is VGPR n.
|
||||
fn vopc(op: u32, src0: u32, vsrc1: u32) -> u32 {
|
||||
0b011_1110 << 25 | op << 17 | vsrc1 << 9 | src0
|
||||
}
|
||||
|
||||
const fn vgpr(n: u32) -> u32 {
|
||||
256 + n
|
||||
}
|
||||
|
||||
/// `v_mov_b32 v<reg>, literal` (VOP1 opcode 1).
|
||||
fn vmov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0x7e00_02ff | reg << 17, value]
|
||||
}
|
||||
|
||||
/// `s_mov_b32 s<reg>, literal` (SOP1 opcode 3).
|
||||
fn smov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0xbe80_03ff | reg << 16, value]
|
||||
}
|
||||
|
||||
/// `s_mov_b32 exec_lo, -1`.
|
||||
const FULL_EXEC: u32 = 0xbefe_03c1;
|
||||
/// `v_mov_b32 v2, vcc_lo`.
|
||||
const READ_VCC: u32 = 0x7e04_026a;
|
||||
/// `v_cmp_lt_u32 vcc_lo, v1, v3`: a supported compare, so VCC_LO becomes
|
||||
/// lane-derived from v1 < v3.
|
||||
const LT_U32_V1_V3: u32 = 0x7d82_0701;
|
||||
/// `s_cbranch_vccz` over one word (SOPP opcode 6, SIMM16 = 1).
|
||||
const VCCZ_OVER_ONE: u32 = 0xbf86_0001;
|
||||
/// `v_xor_b32 v2, v1, v2` (VOP2 opcode 29), the skipped region.
|
||||
const XOR_V2_V1: u32 = 29 << 25 | 2 << 17 | 2 << 9 | (256 + 1);
|
||||
|
||||
const PREFIX: [u32; 3] = [0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
const STORE_V2: [u32; 4] = [0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000];
|
||||
|
||||
/// Load v1 = lane input, `setup`, EXEC_LO = `exec` (unless `None`), the compare
|
||||
/// words, EXEC_LO = -1 again, v2 = vcc_lo, `tail`, then store v2. Returns the
|
||||
/// program and the compare's byte offset.
|
||||
fn program(setup: &[u32], exec: Option<u32>, compare: &[u32], tail: &[u32]) -> (Vec<u8>, usize) {
|
||||
let mut code = PREFIX.to_vec();
|
||||
code.extend(setup);
|
||||
if let Some(exec) = exec {
|
||||
code.extend(smov(EXEC_LO, exec));
|
||||
}
|
||||
let offset = 4 * code.len();
|
||||
code.extend(compare);
|
||||
if exec.is_some() {
|
||||
code.push(FULL_EXEC);
|
||||
}
|
||||
code.push(READ_VCC);
|
||||
code.extend(tail);
|
||||
code.extend(STORE_V2);
|
||||
(words(&code), offset)
|
||||
}
|
||||
|
||||
fn lanes() -> Vec<u32> {
|
||||
VALUES.iter().chain(&MORE_LANES).copied().collect()
|
||||
}
|
||||
|
||||
/// The lanes of each wave of `input` that exist, as a mask per dispatch index.
|
||||
fn present(input: &[u32], n: usize) -> u32 {
|
||||
let in_wave = (input.len() - n / 32 * 32).min(32);
|
||||
if in_wave == 32 {
|
||||
u32::MAX
|
||||
} else {
|
||||
(1 << in_wave) - 1
|
||||
}
|
||||
}
|
||||
|
||||
/// A case whose lane `n` (dispatch index) of `input` expects
|
||||
/// `lane(n, x, present-lane mask of its wave)`.
|
||||
fn case(
|
||||
(_, name): (Form, &'static str),
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
input: Vec<u32>,
|
||||
lane: impl Fn(usize, u32, u32) -> u32,
|
||||
) -> Case {
|
||||
let expected = input
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(n, &x)| lane(n, x, present(&input, n)))
|
||||
.collect();
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label: format!("{name} {label}"),
|
||||
code,
|
||||
input,
|
||||
expected,
|
||||
}
|
||||
}
|
||||
|
||||
fn inline_integer(selector: u32) -> u32 {
|
||||
match selector {
|
||||
128..=192 => selector - 128,
|
||||
193..=208 => (-((selector - 192) as i32)) as u32,
|
||||
_ => unreachable!("not an integer inline constant"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The expected lane output under full EXEC: VCC_LO of the lane's wave.
|
||||
fn full(form: Form, operands: impl Fn(usize) -> (u32, u32)) -> impl Fn(usize, u32, u32) -> u32 {
|
||||
move |_, _, present| vcc(form, u32::MAX, present, &operands)
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
let input = lanes();
|
||||
// S0/S1 for lane n of a wave of `input`, with v1 = input.
|
||||
let v1 = |n: usize| input[n % 32];
|
||||
for entry @ (form, _) in FORMS {
|
||||
let op = form as u32;
|
||||
// Every boundary value against all 32 lane inputs, in each slot.
|
||||
for b in VALUES {
|
||||
let setup = vmov(3, b);
|
||||
let (code, _) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &[]);
|
||||
let label = format!("v1, {b:#x}");
|
||||
let f = full(form, |n| (v1(n), b));
|
||||
cases.push(case(entry, "vopc domain", label, code, lanes(), f));
|
||||
let (code, _) = program(&setup, None, &[vopc(op, vgpr(3), 1)], &[]);
|
||||
let label = format!("{b:#x}, v1");
|
||||
let f = full(form, |n| (b, v1(n)));
|
||||
cases.push(case(entry, "vopc domain", label, code, lanes(), f));
|
||||
}
|
||||
// Both sources the same register.
|
||||
let b = 0x8000_0000;
|
||||
let family = "vopc aliasing";
|
||||
let (code, _) = program(&vmov(3, b), None, &[vopc(op, vgpr(1), 1)], &[]);
|
||||
let f = full(form, |n| (v1(n), v1(n)));
|
||||
cases.push(case(entry, family, "v1, v1".into(), code, lanes(), f));
|
||||
let (code, _) = program(&vmov(3, b), None, &[vopc(op, vgpr(3), 3)], &[]);
|
||||
let f = full(form, |_| (b, b));
|
||||
cases.push(case(entry, family, "v3, v3".into(), code, lanes(), f));
|
||||
// Every integer inline constant (-16..64) as SRC0.
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
let (code, _) = program(&[], None, &[vopc(op, selector, 1)], &[]);
|
||||
let label = format!("inline {selector} ({value:#x}), v1");
|
||||
let f = full(form, |n| (value, v1(n)));
|
||||
cases.push(case(entry, "vopc inline integer", label, code, lanes(), f));
|
||||
}
|
||||
// One literal dword after the VOPC word as SRC0.
|
||||
for literal in LITERALS {
|
||||
let (code, _) = program(&[], None, &[vopc(op, LITERAL, 1), literal], &[]);
|
||||
let label = format!("literal {literal:#x}, v1");
|
||||
let f = full(form, |n| (literal, v1(n)));
|
||||
cases.push(case(entry, "vopc literal", label, code, lanes(), f));
|
||||
}
|
||||
// SGPR SRC0: s8 and s105, the highest SGPR.
|
||||
for reg in [8, 105] {
|
||||
for value in SGPR_VALUES {
|
||||
let (code, _) = program(&smov(reg, value), None, &[vopc(op, reg, 1)], &[]);
|
||||
let label = format!("s{reg} = {value:#x}, v1");
|
||||
let f = full(form, |n| (value, v1(n)));
|
||||
cases.push(case(entry, "vopc sgpr source", label, code, lanes(), f));
|
||||
}
|
||||
}
|
||||
// vcc_lo SRC0: known (three values), and lane-derived from a supported
|
||||
// compare; the old VCC_LO is read before the new value is written.
|
||||
let family = "vopc vcc_lo source";
|
||||
for value in SGPR_VALUES {
|
||||
let (code, _) = program(&smov(VCC_LO, value), None, &[vopc(op, VCC_LO, 1)], &[]);
|
||||
let label = format!("vcc_lo = {value:#x}, v1");
|
||||
let f = full(form, |n| (value, v1(n)));
|
||||
cases.push(case(entry, family, label, code, lanes(), f));
|
||||
}
|
||||
let b = 0x8000_0000;
|
||||
let mut setup = vmov(3, b).to_vec();
|
||||
setup.push(LT_U32_V1_V3);
|
||||
let (code, _) = program(&setup, None, &[vopc(op, VCC_LO, 1)], &[]);
|
||||
// The earlier v_cmp_lt_u32 result, from its own guide relation.
|
||||
let old = (0..32)
|
||||
.filter(|&n| v1(n) < b)
|
||||
.fold(0u32, |mask, n| mask | 1 << n);
|
||||
let f = full(form, |n| (old, v1(n)));
|
||||
let label = "vcc_lo lane-derived (v1 < 0x80000000), v1".into();
|
||||
cases.push(case(entry, family, label, code, lanes(), f));
|
||||
// v255, the highest VGPR, in each slot and both.
|
||||
let b = 0x7fff_ffff;
|
||||
let family = "vopc max register";
|
||||
let setup = vmov(255, b);
|
||||
for (src0, vsrc1, label) in [
|
||||
(vgpr(255), 1, "v255, v1"),
|
||||
(vgpr(1), 255, "v1, v255"),
|
||||
(vgpr(255), 255, "v255, v255"),
|
||||
] {
|
||||
let (code, _) = program(&setup, None, &[vopc(op, src0, vsrc1)], &[]);
|
||||
let f = full(form, |n| {
|
||||
let pick = |is_v255: bool| if is_v255 { b } else { v1(n) };
|
||||
(pick(src0 == vgpr(255)), pick(vsrc1 == 255))
|
||||
});
|
||||
cases.push(case(entry, family, label.into(), code, lanes(), f));
|
||||
}
|
||||
// EXEC around the compare, with a stale VCC_LO: inactive lanes' bits
|
||||
// are cleared, active lanes take the test.
|
||||
let family = "vopc exec";
|
||||
let b = 0x0f0f_0f0f;
|
||||
let mut setup = vmov(3, b).to_vec();
|
||||
setup.extend(smov(VCC_LO, STALE_VCC));
|
||||
for exec in EXEC_MASKS {
|
||||
let (code, _) = program(&setup, Some(exec), &[vopc(op, vgpr(1), 3)], &[]);
|
||||
let label = format!("exec {exec:#x}, vcc_lo was {STALE_VCC:#x}, v1, {b:#x}");
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, _, p| {
|
||||
vcc(form, exec, p, |n| (v1(n), b))
|
||||
}));
|
||||
}
|
||||
// A literal SRC0 under partial and empty EXEC: its dword is consumed.
|
||||
for exec in [0x00f0_0f00, 0] {
|
||||
let compare = [vopc(op, LITERAL, 3), 0x8000_0000];
|
||||
let (code, _) = program(&setup, Some(exec), &compare, &[]);
|
||||
let label = format!("exec {exec:#x}, literal 0x80000000, v3");
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, _, p| {
|
||||
vcc(form, exec, p, |_| (0x8000_0000, b))
|
||||
}));
|
||||
}
|
||||
// EXEC_LO = 0: no source is read, so uninitialized ones are accepted
|
||||
// (contract section 5) and VCC_LO becomes 0.
|
||||
let family = "vopc empty exec reads nothing";
|
||||
for (src0, vsrc1, label) in [
|
||||
(20, 1, "s20 (unknown), v1"),
|
||||
(VCC_LO, 1, "vcc_lo (uninitialized), v1"),
|
||||
(vgpr(9), 9, "v9, v9 (uninitialized)"),
|
||||
] {
|
||||
let (code, _) = program(&[], Some(0), &[vopc(op, src0, vsrc1)], &[]);
|
||||
let label = format!("exec 0, {label}");
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, _, p| {
|
||||
vcc(form, 0, p, |_| (0, 0))
|
||||
}));
|
||||
}
|
||||
// A final wave with absent lanes: 7 lanes, and 45 lanes (one full wave
|
||||
// and 13 lanes), also with partial EXEC in both waves.
|
||||
let family = "vopc partial wave";
|
||||
let long: Vec<u32> = lanes()
|
||||
.into_iter()
|
||||
.chain(lanes().into_iter().take(13))
|
||||
.collect();
|
||||
// Lane k of the wave holding dispatch index n; `vcc` asks only for
|
||||
// lanes that exist.
|
||||
let wave_lane = |input: &[u32], n: usize, k: usize| input[n / 32 * 32 + k];
|
||||
let short = lanes()[..7].to_vec();
|
||||
for (exec, input, label) in [
|
||||
(u32::MAX, short, "7 lanes".to_string()),
|
||||
(u32::MAX, long.clone(), "45 lanes".to_string()),
|
||||
(0x5555_5555, long, "45 lanes, exec 0x55555555".to_string()),
|
||||
] {
|
||||
let exec_word = (exec != u32::MAX).then_some(exec);
|
||||
let (code, _) = program(&vmov(3, 5), exec_word, &[vopc(op, vgpr(1), 3)], &[]);
|
||||
let copy = input.clone();
|
||||
cases.push(case(entry, family, label, code, input, |n, _, p| {
|
||||
vcc(form, exec, p, |k| (wave_lane(©, n, k), 5))
|
||||
}));
|
||||
}
|
||||
// s_cbranch_vccz after the compare (guide 3.9: VCCZ = VCC_LO == 0 in
|
||||
// wave32). Taken: v2 = VCC_LO (0). Not taken: v2 = VCC_LO ^ v1.
|
||||
let family = "vopc vccz branch";
|
||||
for exec in [u32::MAX, 0x0000_8000, 0] {
|
||||
let (code, _) = program(
|
||||
&vmov(3, 5),
|
||||
Some(exec),
|
||||
&[vopc(op, vgpr(1), 3)],
|
||||
&[VCCZ_OVER_ONE, XOR_V2_V1],
|
||||
);
|
||||
let label = format!("exec {exec:#x}, then s_cbranch_vccz");
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, x, p| {
|
||||
let mask = vcc(form, exec, p, |n| (v1(n), 5));
|
||||
if mask == 0 { 0 } else { mask ^ x }
|
||||
}));
|
||||
}
|
||||
// Under EXEC_LO = 0 the result is a known 0 (contract section 5), so
|
||||
// the branch is resolved statically and may skip a scalar
|
||||
// instruction (`s_mov_b32 s8, 0`); it is taken, v2 = 0.
|
||||
let tail = [VCCZ_OVER_ONE, 0xbe88_0380];
|
||||
let (code, _) = program(&vmov(3, 5), Some(0), &[vopc(op, vgpr(1), 3)], &tail);
|
||||
let label = "exec 0, then s_cbranch_vccz over s_mov".into();
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, _, _| 0));
|
||||
// EXEC_LO is unchanged by the compare (contract section 3): v2 =
|
||||
// vcc_lo runs under the compare's partial EXEC, so active lanes take
|
||||
// VCC_LO and inactive lanes keep their own old v2 = v1 ^ OLD.
|
||||
let family = "vopc exec unchanged";
|
||||
for exec in [0x5555_5555, 0x8000_0001] {
|
||||
let mut code = PREFIX.to_vec();
|
||||
code.extend(vmov(3, 5));
|
||||
code.extend(vmov(5, OLD));
|
||||
code.push(29 << 25 | 2 << 17 | 1 << 9 | vgpr(5)); // v_xor_b32 v2, v5, v1
|
||||
code.extend(smov(EXEC_LO, exec));
|
||||
code.extend([vopc(op, vgpr(1), 3), READ_VCC, FULL_EXEC]);
|
||||
code.extend(STORE_V2);
|
||||
let label = format!("exec {exec:#x}, v2 = vcc_lo before EXEC is restored");
|
||||
cases.push(case(
|
||||
entry,
|
||||
family,
|
||||
label,
|
||||
words(&code),
|
||||
lanes(),
|
||||
|n, x, p| {
|
||||
if exec >> (n % 32) & 1 == 1 {
|
||||
vcc(form, exec, p, |k| (v1(k), 5))
|
||||
} else {
|
||||
x ^ OLD
|
||||
}
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// Programs both interpreters must refuse, with the refusing byte offset.
|
||||
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
|
||||
let setup = vmov(3, 7);
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
let mut reject = |label: String, (code, offset): (Vec<u8>, usize)| {
|
||||
all.push((format!("{name} {label}"), code, offset));
|
||||
};
|
||||
// Uninitialized sources under nonzero EXEC (contract sections 4 and 5).
|
||||
for (src0, vsrc1, label) in [
|
||||
(20, 3, "s20 unknown"),
|
||||
(VCC_LO, 3, "vcc_lo uninitialized"),
|
||||
(vgpr(9), 3, "v9 uninitialized as SRC0"),
|
||||
(vgpr(1), 9, "v9 uninitialized as VSRC1"),
|
||||
] {
|
||||
reject(
|
||||
label.into(),
|
||||
program(&setup, None, &[vopc(op, src0, vsrc1)], &[]),
|
||||
);
|
||||
}
|
||||
// A source whose VGPR has a load outstanding (no wait after
|
||||
// `buffer_load_dword v3`): refused at the compare.
|
||||
for (src0, vsrc1, label) in [(vgpr(1), 3, "VSRC1"), (vgpr(3), 1, "SRC0")] {
|
||||
let mut code = PREFIX.to_vec();
|
||||
code.extend(setup);
|
||||
code.extend([0xe030_2000, 0x8000_0300]);
|
||||
let offset = 4 * code.len();
|
||||
code.push(vopc(op, src0, vsrc1));
|
||||
code.extend([READ_VCC, 0xbf8c_3f70]);
|
||||
code.extend(STORE_V2);
|
||||
let label = format!("v3 load outstanding as {label}");
|
||||
reject(label, (words(&code), offset));
|
||||
}
|
||||
// A literal SRC0 with no literal dword: the program ends at the word.
|
||||
let mut code = PREFIX.to_vec();
|
||||
code.extend(setup);
|
||||
let offset = 4 * code.len();
|
||||
code.push(vopc(op, LITERAL, 3));
|
||||
reject("missing literal".into(), (words(&code), offset));
|
||||
// Float inline constants 240-248, VCC_HI, TTMP-adjacent and special
|
||||
// selectors outside the allowlist (contract section 2).
|
||||
for src0 in (240..=248).chain([107, 124, 125, 126, 127, 251, 252, 253, 254]) {
|
||||
let label = format!("src0 {src0}");
|
||||
reject(label, program(&setup, None, &[vopc(op, src0, 3)], &[]));
|
||||
}
|
||||
// Rejected at decode independent of EXEC.
|
||||
let label = "src0 240 under empty exec".into();
|
||||
reject(label, program(&setup, Some(0), &[vopc(op, 240, 3)], &[]));
|
||||
// SDWA (249), DPP16 (250), DPP8 (233) and DPP8FI (234) with SRC0 v1.
|
||||
for (src0, extension) in [
|
||||
(249, 0x0606_0601),
|
||||
(250, 0xff00_e401),
|
||||
(233, 0xfac6_8801),
|
||||
(234, 0xfac6_8801),
|
||||
] {
|
||||
let label = format!("src0 {src0} extension");
|
||||
reject(
|
||||
label,
|
||||
program(&setup, None, &[vopc(op, src0, 3), extension], &[]),
|
||||
);
|
||||
}
|
||||
// The VOP3 `_e64` form (ENCODING 0b110101, OP = the VOPC opcode,
|
||||
// SDST vcc_lo): v_cmp vcc_lo, v1, v3.
|
||||
let vop3 = [0xd400_0000 | op << 16 | VCC_LO, vgpr(1) | vgpr(3) << 9];
|
||||
reject("_e64".into(), program(&setup, None, &vop3, &[]));
|
||||
// The matching v_cmpx (writes EXEC): opcode + 16 (Table 61: 144, 151,
|
||||
// 208, 215).
|
||||
let label = format!("v_cmpx opcode {}", op + 16);
|
||||
reject(
|
||||
label,
|
||||
program(&setup, None, &[vopc(op + 16, vgpr(1), 3)], &[]),
|
||||
);
|
||||
// F under nonzero EXEC is lane-derived even though its value is 0, so
|
||||
// a vccz branch over `s_mov_b32 s8, 0` is refused at that word.
|
||||
// Layout: compare, v2 = vcc_lo, branch, then the s_mov at +12.
|
||||
let tail = [VCCZ_OVER_ONE, 0xbe88_0380];
|
||||
let (code, compare) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &tail);
|
||||
reject("lane-derived vccz over s_mov".into(), (code, compare + 12));
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn assert_rejected_at(label: &str, code: &[u8], offset: usize, input: &[u32]) {
|
||||
match xenora_ref::execute(code, input) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(
|
||||
error.offset, offset,
|
||||
"reference rejected {label} elsewhere: {error:?}"
|
||||
),
|
||||
}
|
||||
match independent_ref::execute(code, input) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{offset:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:x?}, expected {:x?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expectations_follow_the_guide_examples() {
|
||||
// Worked by hand from section 3.9 and Table 61.
|
||||
for (form, exec, present, mask) in [
|
||||
(Form::TI32, u32::MAX, u32::MAX, u32::MAX),
|
||||
(Form::TU32, 0x5555_5555, u32::MAX, 0x5555_5555),
|
||||
(Form::TI32, u32::MAX, 0x7f, 0x7f),
|
||||
(Form::TU32, 0xf0f0_f0f0, 0x1fff, 0x10f0),
|
||||
(Form::TI32, 0, u32::MAX, 0),
|
||||
(Form::FI32, u32::MAX, u32::MAX, 0),
|
||||
(Form::FU32, 0x8000_0001, u32::MAX, 0),
|
||||
] {
|
||||
assert_eq!(
|
||||
vcc(form, exec, present, |_| (0, 0)),
|
||||
mask,
|
||||
"{form:?} {exec:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vopc_f_t_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, |code, input| {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
});
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("vopc_f_t: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vopc_f_t_match_the_guide_on_the_independent_interpreter() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, independent_ref::execute);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"independent interpreter disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("vopc_f_t: {} independent-interpreter cases", cases.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vopc_f_t_outside_the_contract_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code, offset) in &rejections {
|
||||
assert_rejected_at(label, code, *offset, &lanes());
|
||||
}
|
||||
eprintln!("vopc_f_t: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_constant_compares_stay_unsupported() {
|
||||
// F and T/TRU of the float, 64-bit and v_cmpx groups (Table 61):
|
||||
// V_CMP_F_F32 0, V_CMP_TRU_F32 15, V_CMPX_F_F32 16, V_CMPX_TRU_F32 31,
|
||||
// V_CMP_F_I64 160, V_CMP_T_I64 167, V_CMPX_F_I64 176, V_CMPX_T_I64 183,
|
||||
// V_CMP_F_U64 224, V_CMP_T_U64 231, V_CMPX_F_U64 240, V_CMPX_T_U64 247.
|
||||
let setup = vmov(3, 7);
|
||||
// Also the neighbours of the two 32-bit integer groups: 127 and 191 (not
|
||||
// in Table 61), 136 V_CMP_CLASS_F32 and 200 V_CMP_F_F16.
|
||||
for op in [
|
||||
0, 15, 16, 31, 127, 136, 160, 167, 176, 183, 191, 200, 224, 231, 240, 247,
|
||||
] {
|
||||
let (code, offset) = program(&setup, None, &[vopc(op, vgpr(1), 3)], &[]);
|
||||
assert_rejected_at(&format!("opcode {op}"), &code, offset, &lanes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation, and the translator's F/T forms"]
|
||||
fn vopc_f_t_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
for (label, code, offset) in rejections() {
|
||||
let at = match compile(Architecture::Gfx1030, &code) {
|
||||
Err(CompileError::Decode(error)) => error.offset,
|
||||
Err(CompileError::Verify { offset, .. }) => offset,
|
||||
other => panic!("compiler did not reject {label}: {other:?}"),
|
||||
};
|
||||
assert_eq!(at, offset, "compiler rejected {label} elsewhere");
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"vopc_f_t: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user