Compare commits

...
Author SHA1 Message Date
Ranveer Soni 0bfb12fd17 Merge branch 'main' into task/261-native-app-gate1 2026-11-24 15:45:49 +05:30
Swastick Chowdhury c6d0986da2 app: add native macOS shell and versioned C runtime interface (#261)
Add crates/ffi, a static library exposing a version 1 C interface with
opaque generation-checked session handles, stable status codes and
panic containment. It can create and destroy sessions and parse the
bundled trusted PE fixture; no guest code runs. Add a minimal SwiftUI
app (Swift Package Manager) that links it, and scripts/build-app.sh to
build an ad-hoc signed, arm64-only Xenora.app and run its smoke check.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:43:08 +05:30
Ranveer Soni 9a9422c7da Merge pull request #260 from elforeign/task/215-stage-c
isa: eight SOP2 logical and shift forms through the semantic registry (#215 stage C)
2026-11-24 15:41:50 +05:30
elforeign de00cb2bfd Merge remote-tracking branch 'origin/main' into task/215-stage-c 2026-11-24 04:08:15 -06:00
elforeign d8f9669280 semantics: require exact XML number formats and a sane count width (#215)
Review follow-up: a shift count must be FMT_NUM_U32 and other sources
must have the format their signedness implies, so a float format no
longer passes; a negative shift_count_bits is a diagnostic instead of a
crash. The stage C rows cite the guide pages where the forms are listed,
and the scalar ALU page names which suite covers which forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:08:15 -06:00
elforeign 19b2e9b5d5 semantics: dispatch through a generated OP-indexed table (#215)
With 17 forms the generated match on the masked word cost about 0.4 ns
(4 %) more per decoded SOP2 instruction than main. The generator now
emits a fixed-bits test plus a static table indexed by the OP field,
both derived from the XML snapshot and checked to select exactly the
same words; decoding is back to main's speed (10.05 ns).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:07:17 -06:00
Ranveer Soni bb6bc52c95 Merge pull request #258 from Swastickc/task/80-pe-mapping-limits
loader: bound total mapped PE image size before allocation (#80)
2026-11-24 15:37:11 +05:30
Ranveer Soni ba6bbb2e4a Merge pull request #259 from Swastickc/task/77-teb-startup-bounds
loader: validate startup stack and TEB layout before mapping (#77)
2026-11-24 15:36:51 +05:30
elforeign d3c1150854 changelog: stage C SOP2 forms through the registry (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:22 -06:00
elforeign a81d62ffe3 decoder: map the stage C SOP2 operations onto the reference in the consistency test (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:00 -06:00
elforeign 8d53d82981 Merge branch 'task/215-stage-c-oracle' into task/215-stage-c 2026-11-24 04:03:01 -06:00
elforeign ba2cfc2a00 validation: close two blind spots in the stage C cases (#215)
Review found that one register operand per inline constant hides some wrong
inline values (ANDN2 with s8 = 0x80000f0f cannot tell 16 from 0), and that the
odd-opcode check used a misaligned SGPR pair. Each inline now runs against a
word and its complement, and the 64-bit neighbours read aligned pairs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:02:10 -06:00
elforeign b13ab327f2 ref, validation: evaluate the stage C SOP2 forms in both interpreters (#215)
The reference interpreter and the second, independent interpreter now run
s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and s_ashr_i32 per the RDNA 2
guide: shifts use only S1[4:0] and every form sets SCC = (D != 0). The two use
different arithmetic (host bit ops vs per-bit and power-of-two evaluation),
so they cannot share a mistake with each other or with the expectations.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:00:28 -06:00
Swastick Chowdhury e7cb8db14f loader: bound total mapped PE image size before allocation (#80)
Sum max(VirtualSize, SizeOfRawData) over all sections and reject images
above a 256 MiB loader budget with SectionMappingError(AllocationFailed)
before any host allocation. Adds pe_mapping_limits tests.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:29:34 +05:30
elforeign e7795d0e5a validation: guide-derived expectations for the stage C SOP2 forms (#215)
Expected D and SCC for s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and
s_ashr_i32 are written from the RDNA 2 ISA guide (12.1, 5.3) before either
interpreter implements them, so the implementation cannot shape the oracle.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:57:55 -06:00
elforeign ff191d89bd isa: declare eight more SOP2 logical and shift forms in the registry (#215 stage C, WIP)
Adds andn2, orn2, nand, nor, xnor, lshl, lshr and ashr as registry
primitives with a declared shift-count width that the generator applies
as a mask and checks against the XML's unsigned count operand. The forms
reach the decoder and translator through the generated dispatch with no
per-form Rust. The independent oracle side lands separately.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:55:00 -06:00
35 changed files with 1938 additions and 58 deletions

No files matched your search

+3
View File
@@ -37,3 +37,6 @@ __pycache__/
*.pyc
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
# Native application build output
/app/.build/
+1
View File
@@ -11,6 +11,7 @@ remains unsupported.
### Added
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
Generated
+7
View File
@@ -179,6 +179,13 @@ dependencies = [
"xenora-ref",
]
[[package]]
name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
]
[[package]]
name = "xenora-import-gen"
version = "0.1.0"
+13
View File
@@ -0,0 +1,13 @@
// swift-tools-version: 6.0
// SPDX-License-Identifier: GPL-3.0-or-later
// Build with scripts/build-app.sh, which builds the Rust static library first.
import PackageDescription
let package = Package(
name: "Xenora",
platforms: [.macOS(.v14)],
targets: [
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
]
)
+5
View File
@@ -0,0 +1,5 @@
module CXenora [system] {
header "../../../crates/ffi/include/xenora.h"
link "xenora_ffi"
export *
}
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Gate 1 shell: proves the app links the Rust runtime through the versioned C
// interface. It inspects the bundled trusted fixture and executes no guest code.
import CXenora
import Foundation
import SwiftUI
struct RuntimeProbe {
var abiVersion: UInt32 = 0
var status: Int32 = -1
var sections: UInt32 = 0
var entryRVA: UInt32 = 0
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
static func run() -> RuntimeProbe {
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
var session: xenora_session = 0
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard probe.status == XENORA_OK else { return probe }
defer { _ = xenora_session_destroy(session) }
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
return probe
}
var summary: String {
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
}
}
struct ContentView: View {
let probe = RuntimeProbe.run()
var body: some View {
Form {
LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))")
LabeledContent("Interface version", value: "\(probe.abiVersion)")
LabeledContent("Trusted fixture sections", value: "\(probe.sections)")
LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA))
Text("Guest execution and live display are not available in this build.")
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.frame(minWidth: 420, minHeight: 240)
}
}
struct XenoraApp: App {
var body: some Scene {
WindowGroup("Xenora") { ContentView() }
}
}
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
if CommandLine.arguments.contains("--smoke") {
let probe = RuntimeProbe.run()
print(probe.summary)
exit(probe.connected ? 0 : 1)
}
XenoraApp.main()
+10 -1
View File
@@ -340,6 +340,14 @@ fn reference_op(instruction: Instruction) -> Op {
ScalarAluOp::AndB32 => ScalarAlu::And,
ScalarAluOp::OrB32 => ScalarAlu::Or,
ScalarAluOp::XorB32 => ScalarAlu::Xor,
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
ScalarAluOp::NandB32 => ScalarAlu::Nand,
ScalarAluOp::NorB32 => ScalarAlu::Nor,
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
},
dst,
reference_scalar(src0),
@@ -434,13 +442,14 @@ fn compares_fixture_instructions_against_llvm() {
SHIFT_FIXTURE,
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 42, "forms compared: {forms:?}");
assert_eq!(forms.len(), 50, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "xenora-ffi"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
description = "Versioned C interface between the native macOS application and the Xenora runtime"
[lib]
crate-type = ["staticlib", "rlib"]
[lints]
workspace = true
[dependencies]
xenora-loader = { path = "../loader" }
+47
View File
@@ -0,0 +1,47 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
* Xenora native application interface, version 1.
*
* Every function returns a xenora_status. Sessions are identified by opaque
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
* handle stays invalid even if its slot is reused. Output pointers are owned
* by the caller and are written only when the call returns XENORA_OK.
* All functions are thread-safe. No Rust panic crosses this boundary: one is
* reported as XENORA_INTERNAL_ERROR.
*/
#ifndef XENORA_H
#define XENORA_H
#include <stdint.h>
#define XENORA_ABI_VERSION 1u
typedef int32_t xenora_status;
enum {
XENORA_OK = 0,
XENORA_INVALID_ARGUMENT = 1,
XENORA_INVALID_HANDLE = 2,
XENORA_VERSION_MISMATCH = 3,
XENORA_INTERNAL_ERROR = 4,
XENORA_PE_ERROR = 5,
XENORA_LIMIT_EXCEEDED = 6,
};
typedef uint64_t xenora_session;
/* The interface version this library implements. */
uint32_t xenora_abi_version(void);
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
xenora_status xenora_session_destroy(xenora_session session);
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
xenora_status xenora_session_inspect_trusted_fixture(
xenora_session session,
uint32_t *out_section_count,
uint32_t *out_entry_rva);
#endif
+264
View File
@@ -0,0 +1,264 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Versioned C interface for the native macOS application (see `include/xenora.h`).
//!
//! Sessions are opaque 64-bit handles: the low 32 bits index a slot and the high
//! 32 bits hold that slot's generation, so a stale handle never reaches a reused slot.
//! Every exported function catches panics and reports them as `XENORA_INTERNAL_ERROR`.
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Mutex;
use xenora_loader::ParsedPe;
pub const XENORA_ABI_VERSION: u32 = 1;
pub const XENORA_OK: i32 = 0;
pub const XENORA_INVALID_ARGUMENT: i32 = 1;
pub const XENORA_INVALID_HANDLE: i32 = 2;
pub const XENORA_VERSION_MISMATCH: i32 = 3;
pub const XENORA_INTERNAL_ERROR: i32 = 4;
pub const XENORA_PE_ERROR: i32 = 5;
pub const XENORA_LIMIT_EXCEEDED: i32 = 6;
/// Upper bound on simultaneously live sessions.
const MAX_SESSIONS: usize = 64;
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
struct Slot {
/// Odd while live, even while free; starts at 0 so the first handle is never 0.
generation: u32,
}
static SESSIONS: Mutex<Vec<Slot>> = Mutex::new(Vec::new());
fn guarded(f: impl FnOnce() -> i32) -> i32 {
catch_unwind(AssertUnwindSafe(f)).unwrap_or(XENORA_INTERNAL_ERROR)
}
fn split(handle: u64) -> (usize, u32) {
((handle & 0xFFFF_FFFF) as usize, (handle >> 32) as u32)
}
fn is_live(slots: &[Slot], handle: u64) -> bool {
let (index, generation) = split(handle);
slots
.get(index)
.is_some_and(|slot| slot.generation == generation && generation % 2 == 1)
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_abi_version() -> u32 {
XENORA_ABI_VERSION
}
/// # Safety
/// `out_session` must be null or valid for one aligned `u64` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_create(abi_version: u32, out_session: *mut u64) -> i32 {
guarded(|| {
if out_session.is_null() {
return XENORA_INVALID_ARGUMENT;
}
if abi_version != XENORA_ABI_VERSION {
return XENORA_VERSION_MISMATCH;
}
let Ok(mut slots) = SESSIONS.lock() else {
return XENORA_INTERNAL_ERROR;
};
let index = match slots.iter().position(|slot| slot.generation % 2 == 0) {
Some(index) => index,
None if slots.len() < MAX_SESSIONS => {
slots.push(Slot { generation: 0 });
slots.len() - 1
}
None => return XENORA_LIMIT_EXCEEDED,
};
let slot = &mut slots[index];
// ponytail: a slot retires after 2^31 reuses instead of wrapping its generation.
let Some(generation) = slot.generation.checked_add(1) else {
return XENORA_LIMIT_EXCEEDED;
};
slot.generation = generation;
// SAFETY: checked non-null above; the caller guarantees validity.
unsafe { out_session.write((u64::from(generation) << 32) | index as u64) };
XENORA_OK
})
}
#[unsafe(no_mangle)]
pub extern "C" fn xenora_session_destroy(session: u64) -> i32 {
guarded(|| {
let Ok(mut slots) = SESSIONS.lock() else {
return XENORA_INTERNAL_ERROR;
};
if !is_live(&slots, session) {
return XENORA_INVALID_HANDLE;
}
slots[split(session).0].generation += 1;
XENORA_OK
})
}
/// # Safety
/// Each output pointer must be null or valid for one aligned `u32` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_session_inspect_trusted_fixture(
session: u64,
out_section_count: *mut u32,
out_entry_rva: *mut u32,
) -> i32 {
guarded(|| {
if out_section_count.is_null() || out_entry_rva.is_null() {
return XENORA_INVALID_ARGUMENT;
}
match SESSIONS.lock() {
Ok(slots) if is_live(&slots, session) => {}
Ok(_) => return XENORA_INVALID_HANDLE,
Err(_) => return XENORA_INTERNAL_ERROR,
}
let Ok(pe) = ParsedPe::parse(FIXTURE) else {
return XENORA_PE_ERROR;
};
// SAFETY: both checked non-null above; the caller guarantees validity.
unsafe {
out_section_count.write(u32::from(pe.number_of_sections));
out_entry_rva.write(pe.entry_point_rva);
}
XENORA_OK
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::ptr::null_mut;
/// The session table is process-global, so tests that fill or count it run one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
fn serial() -> std::sync::MutexGuard<'static, ()> {
SERIAL
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn create() -> u64 {
let mut handle = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
XENORA_OK
);
assert_ne!(handle, 0);
handle
}
fn inspect(handle: u64) -> (i32, u32, u32) {
let (mut sections, mut entry) = (u32::MAX, u32::MAX);
let status =
unsafe { xenora_session_inspect_trusted_fixture(handle, &mut sections, &mut entry) };
(status, sections, entry)
}
#[test]
fn header_and_rust_constants_agree() {
let header = include_str!("../include/xenora.h");
assert!(header.contains(&format!("#define XENORA_ABI_VERSION {XENORA_ABI_VERSION}u")));
for (name, value) in [
("XENORA_OK", XENORA_OK),
("XENORA_INVALID_ARGUMENT", XENORA_INVALID_ARGUMENT),
("XENORA_INVALID_HANDLE", XENORA_INVALID_HANDLE),
("XENORA_VERSION_MISMATCH", XENORA_VERSION_MISMATCH),
("XENORA_INTERNAL_ERROR", XENORA_INTERNAL_ERROR),
("XENORA_PE_ERROR", XENORA_PE_ERROR),
("XENORA_LIMIT_EXCEEDED", XENORA_LIMIT_EXCEEDED),
] {
assert!(header.contains(&format!("{name} = {value},")), "{name}");
}
}
#[test]
fn session_inspects_the_trusted_fixture() {
let _serial = serial();
let handle = create();
// Independent expectation: read straight from the fixture's COFF and optional headers.
let lfanew = u32::from_le_bytes(FIXTURE[0x3C..0x40].try_into().unwrap()) as usize;
let sections = u16::from_le_bytes(FIXTURE[lfanew + 6..lfanew + 8].try_into().unwrap());
let entry = u32::from_le_bytes(FIXTURE[lfanew + 40..lfanew + 44].try_into().unwrap());
assert_eq!(inspect(handle), (XENORA_OK, u32::from(sections), entry));
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
}
#[test]
fn version_mismatch_and_null_outputs_are_rejected() {
let _serial = serial();
let mut handle = 7;
assert_eq!(
unsafe { xenora_session_create(2, &mut handle) },
XENORA_VERSION_MISMATCH
);
assert_eq!(handle, 7, "output untouched on failure");
assert_eq!(
unsafe { xenora_session_create(1, null_mut()) },
XENORA_INVALID_ARGUMENT
);
let live = create();
let mut x = 0;
assert_eq!(
unsafe { xenora_session_inspect_trusted_fixture(live, null_mut(), &mut x) },
XENORA_INVALID_ARGUMENT
);
xenora_session_destroy(live);
}
#[test]
fn invalid_stale_and_double_destroyed_handles_are_rejected() {
let _serial = serial();
for bogus in [0, u64::MAX, 0xFFFF_FFFF, 1 << 32] {
assert_eq!(
xenora_session_destroy(bogus),
XENORA_INVALID_HANDLE,
"{bogus:#x}"
);
assert_eq!(inspect(bogus), (XENORA_INVALID_HANDLE, u32::MAX, u32::MAX));
}
let handle = create();
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
assert_eq!(xenora_session_destroy(handle), XENORA_INVALID_HANDLE);
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
// Reusing the slot must not revive the old handle.
let reused: Vec<u64> = (0..MAX_SESSIONS).map(|_| create()).collect();
assert!(!reused.contains(&handle));
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
for h in reused {
xenora_session_destroy(h);
}
}
#[test]
fn repeated_and_concurrent_lifecycles_do_not_leak_slots() {
let _serial = serial();
let threads: Vec<_> = (0..8)
.map(|_| {
std::thread::spawn(|| {
for _ in 0..500 {
let mut handle = 0;
let status = unsafe { xenora_session_create(1, &mut handle) };
assert_eq!(status, XENORA_OK);
assert_eq!(inspect(handle).0, XENORA_OK);
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
}
})
})
.collect();
for t in threads {
t.join().unwrap();
}
assert!(SESSIONS.lock().unwrap().len() <= MAX_SESSIONS);
}
#[test]
fn panics_do_not_cross_the_boundary() {
assert_eq!(guarded(|| panic!("injected")), XENORA_INTERNAL_ERROR);
}
}
+75 -13
View File
@@ -38,8 +38,24 @@ FORM_KEYS = {
}
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
OPERATIONS = {"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor"}
LOGICAL = {"and", "or", "xor"}
OPERATIONS = {
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
}
# Logical operations take untyped bits; arithmetic ones never do. Shifts take
# the signedness their primitive names, and their S1 is an unsigned count.
LOGICAL = {"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor"}
ARITHMETIC = {"add", "sub"}
SHIFTS = {"lshl", "lshr", "ashr"}
# XML number formats a source may have for each declared signedness.
SOURCE_FORMATS = {
"signed": {"FMT_NUM_I32"},
"unsigned": {"FMT_NUM_U32"},
"bitwise": {"FMT_NUM_U32", "FMT_NUM_B32"},
}
# Optional keys: required exactly when the condition holds.
SHIFT_KEY = "shift_count_bits"
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
CARRY_IN = {"none": "None", "scc": "Scc"}
SCC = {
@@ -86,6 +102,14 @@ PRIMITIVES = {
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
("andn2", "bitwise"): ("nonzero", "andn2_nonzero_b32", False),
("orn2", "bitwise"): ("nonzero", "orn2_nonzero_b32", False),
("nand", "bitwise"): ("nonzero", "nand_nonzero_b32", False),
("nor", "bitwise"): ("nonzero", "nor_nonzero_b32", False),
("xnor", "bitwise"): ("nonzero", "xnor_nonzero_b32", False),
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
}
# Operand rules the decoder implements, each exactly once. A registry rule must
@@ -205,6 +229,7 @@ def _check_xml(form, rule, snapshot, errors):
if rule is None:
return
fields = [(rule["dst"]["field"], False)] + [(src["field"], True) for src in rule["src"]]
count_field = rule["src"][1]["field"] if form["operation"] in SHIFTS else None
for field, is_source in fields:
if field not in operands:
errors.append(f"{label}: XML has no operand {field}")
@@ -214,8 +239,12 @@ def _check_xml(form, rule, snapshot, errors):
errors.append(f"{label}: {field} is {size} bits in the XML, declared {form['width']}")
if (is_input, is_output) != (is_source, not is_source):
errors.append(f"{label}: {field} direction disagrees with the XML")
signed_format = data_format.startswith("FMT_NUM_I")
if is_source and signed_format != (form["signedness"] == "signed"):
if field == count_field:
if data_format != "FMT_NUM_U32":
errors.append(
f"{label}: shift count {field} has XML format {data_format}, not FMT_NUM_U32"
)
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
errors.append(
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
)
@@ -261,7 +290,7 @@ def validate(registry, snapshot):
for index, form in enumerate(forms):
label = form.get("name", f"form #{index}")
missing = sorted(FORM_KEYS - set(form))
extra = sorted(set(form) - FORM_KEYS)
extra = sorted(set(form) - FORM_KEYS - {SHIFT_KEY})
if missing:
errors.append(f"{label}: incomplete, missing {missing}")
if extra:
@@ -294,10 +323,20 @@ def validate(registry, snapshot):
if value in seen[key]:
errors.append(f"{label}: duplicate {key} {value}")
seen[key].add(value)
if (form["signedness"] == "bitwise") != (form["operation"] in LOGICAL):
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
):
errors.append(
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
)
if form["operation"] in SHIFTS:
bits = form.get(SHIFT_KEY)
if type(bits) is not int or not 0 < bits < 32 or (1 << bits) != form["width"]:
errors.append(
f"{label}: {SHIFT_KEY} must be log2 of the width ({form['width']}), got {bits!r}"
)
elif SHIFT_KEY in form:
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
if primitive is None:
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
@@ -396,6 +435,7 @@ def render(registry, snapshot):
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
f" width: {form['width']},",
f" shift_count_bits: {form.get(SHIFT_KEY, 0)},",
f" scc: SccEffect::{SCC[form['scc']]},",
f" vcc: MaskEffect::{MASK[form['vcc']]},",
f" exec: MaskEffect::{MASK[form['exec']]},",
@@ -414,6 +454,16 @@ def _render_enum(rule_name, forms, snapshot, positions):
family = forms[0]["family"]
encoding = snapshot["encodings"][_family_encoding(family)]
mask = encoding["identifier_mask"]
(offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"]
op_mask = ((1 << size) - 1) << offset
fixed_mask = mask & ~op_mask
fixed_bits = encoding["identifiers"][0] & fixed_mask
# Every identifier of the family must share the fixed bits, or the split
# into an encoding test plus an OP match would change which words match.
if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]) or (
mask & op_mask != op_mask
):
raise ValueError(f"{family}: identifiers do not split into fixed bits and OP")
out = [
"",
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
@@ -427,9 +477,20 @@ def _render_enum(rule_name, forms, snapshot, positions):
f"{form['signedness']} {form['operation']}{carry}, SCC = {form['scc']}.",
f" {form['variant']},",
]
by_opcode = {form["opcode"]: form["variant"] for form in forms}
out += [
"}",
"",
f"/// {enum} by {family} OP field value; `None` for undeclared opcodes.",
f"const BY_OPCODE: [Option<{enum}>; {1 << size}] = [",
]
out += [
f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None,"
for opcode in range(1 << size)
]
out += [
"];",
"",
f"impl {enum} {{",
" /// Every operation, in registry order.",
f" pub const ALL: [Self; {len(forms)}] = [",
@@ -438,15 +499,13 @@ def _render_enum(rule_name, forms, snapshot, positions):
out += [
" ];",
"",
f" /// Selects the operation from a first instruction word (mask 0x{mask:09_x}).",
f" /// Selects the operation from a first instruction word: the {family} encoding",
f" /// bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits {offset}-{offset + size - 1}).",
" pub const fn from_word(word: u32) -> Option<Self> {",
f" match word & 0x{mask:09_x} {{",
]
for form in sorted(forms, key=lambda item: item["opcode"]):
out.append(f" 0x{_identifier(encoding, form['opcode']):09_x} => Some(Self::{form['variant']}),")
out += [
" _ => None,",
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
" return None;",
" }",
f" BY_OPCODE[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
" }",
"",
" /// Lower-case mnemonic.",
@@ -489,6 +548,9 @@ def _render_enum(rule_name, forms, snapshot, positions):
if takes_carry:
argument = "carry_in" if form["carry_in"] == "scc" else "false"
call = f"primitive::{function}(src0, src1, {argument})"
elif form["operation"] in SHIFTS:
mask = (1 << form[SHIFT_KEY]) - 1
call = f"primitive::{function}(src0, src1 & 0x{mask:x})"
else:
call = f"primitive::{function}(src0, src1)"
out.append(f" Self::{form['variant']} => {call},")
+142
View File
@@ -230,3 +230,145 @@ wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- Stage C: further SOP2 logical and shift forms (#215) ----
# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode).
[[form]]
name = "S_ANDN2_B32"
family = "SOP2"
opcode = 20
variant = "Andn2B32"
operation = "andn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ORN2_B32"
family = "SOP2"
opcode = 22
variant = "Orn2B32"
operation = "orn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NAND_B32"
family = "SOP2"
opcode = 24
variant = "NandB32"
operation = "nand"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NOR_B32"
family = "SOP2"
opcode = 26
variant = "NorB32"
operation = "nor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_XNOR_B32"
family = "SOP2"
opcode = 28
variant = "XnorB32"
operation = "xnor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL_B32"
family = "SOP2"
opcode = 30
variant = "LshlB32"
operation = "lshl"
signedness = "bitwise"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHR_B32"
family = "SOP2"
opcode = 32
variant = "LshrB32"
operation = "lshr"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ASHR_I32"
family = "SOP2"
opcode = 34
variant = "AshrI32"
operation = "ashr"
signedness = "signed"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+49
View File
@@ -49,3 +49,52 @@ pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a ^ b;
(value, value != 0)
}
/// Bitwise `a & !b` and whether the result is nonzero.
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a & !b;
(value, value != 0)
}
/// Bitwise `a | !b` and whether the result is nonzero.
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a | !b;
(value, value != 0)
}
/// Bitwise `!(a & b)` and whether the result is nonzero.
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a & b);
(value, value != 0)
}
/// Bitwise `!(a | b)` and whether the result is nonzero.
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a | b);
(value, value != 0)
}
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a ^ b);
(value, value != 0)
}
/// `a << count` and whether the result is nonzero. The caller masks the count
/// to the declared count width, so `count` is below 32.
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a << count;
(value, value != 0)
}
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a >> count;
(value, value != 0)
}
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
let value = ((a as i32) >> count) as u32;
(value, value != 0)
}
+18
View File
@@ -30,6 +30,22 @@ pub enum Operation {
Or,
/// Bitwise exclusive OR.
Xor,
/// Bitwise AND with the complement of S1.
AndNot,
/// Bitwise OR with the complement of S1.
OrNot,
/// Complement of bitwise AND.
Nand,
/// Complement of bitwise OR.
Nor,
/// Complement of bitwise exclusive OR.
Xnor,
/// Shift S0 left by the masked count in S1, filling with zeros.
ShiftLeft,
/// Shift S0 right by the masked count in S1, filling with zeros.
LogicalShiftRight,
/// Shift S0 right by the masked count in S1, filling with its sign bit.
ArithmeticShiftRight,
}
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
@@ -141,6 +157,8 @@ pub struct FormSemantics {
pub carry_in: CarryIn,
/// Operand and result width in bits.
pub width: u8,
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
pub shift_count_bits: u8,
/// SCC write.
pub scc: SccEffect,
/// VCC write.
+349 -15
View File
@@ -32,11 +32,159 @@ pub enum ScalarAluOp {
OrB32,
/// `s_xor_b32` (SOP2 opcode 18): bitwise xor, SCC = nonzero.
XorB32,
/// `s_andn2_b32` (SOP2 opcode 20): bitwise andn2, SCC = nonzero.
Andn2B32,
/// `s_orn2_b32` (SOP2 opcode 22): bitwise orn2, SCC = nonzero.
Orn2B32,
/// `s_nand_b32` (SOP2 opcode 24): bitwise nand, SCC = nonzero.
NandB32,
/// `s_nor_b32` (SOP2 opcode 26): bitwise nor, SCC = nonzero.
NorB32,
/// `s_xnor_b32` (SOP2 opcode 28): bitwise xnor, SCC = nonzero.
XnorB32,
/// `s_lshl_b32` (SOP2 opcode 30): bitwise lshl, SCC = nonzero.
LshlB32,
/// `s_lshr_b32` (SOP2 opcode 32): unsigned lshr, SCC = nonzero.
LshrB32,
/// `s_ashr_i32` (SOP2 opcode 34): signed ashr, SCC = nonzero.
AshrI32,
}
/// ScalarAluOp by SOP2 OP field value; `None` for undeclared opcodes.
const BY_OPCODE: [Option<ScalarAluOp>; 128] = [
Some(ScalarAluOp::AddU32),
Some(ScalarAluOp::SubU32),
Some(ScalarAluOp::AddI32),
Some(ScalarAluOp::SubI32),
Some(ScalarAluOp::AddcU32),
Some(ScalarAluOp::SubbU32),
None,
None,
None,
None,
None,
None,
None,
None,
Some(ScalarAluOp::AndB32),
None,
Some(ScalarAluOp::OrB32),
None,
Some(ScalarAluOp::XorB32),
None,
Some(ScalarAluOp::Andn2B32),
None,
Some(ScalarAluOp::Orn2B32),
None,
Some(ScalarAluOp::NandB32),
None,
Some(ScalarAluOp::NorB32),
None,
Some(ScalarAluOp::XnorB32),
None,
Some(ScalarAluOp::LshlB32),
None,
Some(ScalarAluOp::LshrB32),
None,
Some(ScalarAluOp::AshrI32),
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,
];
impl ScalarAluOp {
/// Every operation, in registry order.
pub const ALL: [Self; 9] = [
pub const ALL: [Self; 17] = [
Self::AddU32,
Self::SubU32,
Self::AddI32,
@@ -46,22 +194,23 @@ impl ScalarAluOp {
Self::AndB32,
Self::OrB32,
Self::XorB32,
Self::Andn2B32,
Self::Orn2B32,
Self::NandB32,
Self::NorB32,
Self::XnorB32,
Self::LshlB32,
Self::LshrB32,
Self::AshrI32,
];
/// Selects the operation from a first instruction word (mask 0xff80_0000).
/// Selects the operation from a first instruction word: the SOP2 encoding
/// bits (mask 0xc000_0000) and then the OP field (bits 23-29).
pub const fn from_word(word: u32) -> Option<Self> {
match word & 0xff80_0000 {
0x8000_0000 => Some(Self::AddU32),
0x8080_0000 => Some(Self::SubU32),
0x8100_0000 => Some(Self::AddI32),
0x8180_0000 => Some(Self::SubI32),
0x8200_0000 => Some(Self::AddcU32),
0x8280_0000 => Some(Self::SubbU32),
0x8700_0000 => Some(Self::AndB32),
0x8800_0000 => Some(Self::OrB32),
0x8900_0000 => Some(Self::XorB32),
_ => None,
if word & 0xc000_0000 != 0x8000_0000 {
return None;
}
BY_OPCODE[((word >> 23) & 0x7f) as usize]
}
/// Lower-case mnemonic.
@@ -76,6 +225,14 @@ impl ScalarAluOp {
Self::AndB32 => "s_and_b32",
Self::OrB32 => "s_or_b32",
Self::XorB32 => "s_xor_b32",
Self::Andn2B32 => "s_andn2_b32",
Self::Orn2B32 => "s_orn2_b32",
Self::NandB32 => "s_nand_b32",
Self::NorB32 => "s_nor_b32",
Self::XnorB32 => "s_xnor_b32",
Self::LshlB32 => "s_lshl_b32",
Self::LshrB32 => "s_lshr_b32",
Self::AshrI32 => "s_ashr_i32",
}
}
@@ -91,6 +248,14 @@ impl ScalarAluOp {
Self::AndB32 => false,
Self::OrB32 => false,
Self::XorB32 => false,
Self::Andn2B32 => false,
Self::Orn2B32 => false,
Self::NandB32 => false,
Self::NorB32 => false,
Self::XnorB32 => false,
Self::LshlB32 => false,
Self::LshrB32 => false,
Self::AshrI32 => false,
}
}
@@ -106,6 +271,14 @@ impl ScalarAluOp {
Self::AndB32 => 6,
Self::OrB32 => 7,
Self::XorB32 => 8,
Self::Andn2B32 => 9,
Self::Orn2B32 => 10,
Self::NandB32 => 11,
Self::NorB32 => 12,
Self::XnorB32 => 13,
Self::LshlB32 => 14,
Self::LshrB32 => 15,
Self::AshrI32 => 16,
}]
}
@@ -122,12 +295,20 @@ impl ScalarAluOp {
Self::AndB32 => primitive::and_nonzero_b32(src0, src1),
Self::OrB32 => primitive::or_nonzero_b32(src0, src1),
Self::XorB32 => primitive::xor_nonzero_b32(src0, src1),
Self::Andn2B32 => primitive::andn2_nonzero_b32(src0, src1),
Self::Orn2B32 => primitive::orn2_nonzero_b32(src0, src1),
Self::NandB32 => primitive::nand_nonzero_b32(src0, src1),
Self::NorB32 => primitive::nor_nonzero_b32(src0, src1),
Self::XnorB32 => primitive::xnor_nonzero_b32(src0, src1),
Self::LshlB32 => primitive::lshl_nonzero_b32(src0, src1 & 0x1f),
Self::LshrB32 => primitive::lshr_nonzero_b32(src0, src1 & 0x1f),
Self::AshrI32 => primitive::ashr_nonzero_i32(src0, src1 & 0x1f),
}
}
}
/// Identity of every registry form, in registry order.
pub const FORM_IDS: [(&str, EncodingFamily); 9] = [
pub const FORM_IDS: [(&str, EncodingFamily); 17] = [
("S_ADD_U32", EncodingFamily::Sop2),
("S_SUB_U32", EncodingFamily::Sop2),
("S_ADD_I32", EncodingFamily::Sop2),
@@ -137,10 +318,18 @@ pub const FORM_IDS: [(&str, EncodingFamily); 9] = [
("S_AND_B32", EncodingFamily::Sop2),
("S_OR_B32", EncodingFamily::Sop2),
("S_XOR_B32", EncodingFamily::Sop2),
("S_ANDN2_B32", EncodingFamily::Sop2),
("S_ORN2_B32", EncodingFamily::Sop2),
("S_NAND_B32", EncodingFamily::Sop2),
("S_NOR_B32", EncodingFamily::Sop2),
("S_XNOR_B32", EncodingFamily::Sop2),
("S_LSHL_B32", EncodingFamily::Sop2),
("S_LSHR_B32", EncodingFamily::Sop2),
("S_ASHR_I32", EncodingFamily::Sop2),
];
/// One validated row per registry form, in registry order.
pub static FORMS: [FormSemantics; 9] = [
pub static FORMS: [FormSemantics; 17] = [
FormSemantics {
name: "S_ADD_U32",
family: EncodingFamily::Sop2,
@@ -149,6 +338,7 @@ pub static FORMS: [FormSemantics; 9] = [
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::CarryOut,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
@@ -165,6 +355,7 @@ pub static FORMS: [FormSemantics; 9] = [
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Borrow,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
@@ -181,6 +372,7 @@ pub static FORMS: [FormSemantics; 9] = [
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::SignedOverflow,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
@@ -197,6 +389,7 @@ pub static FORMS: [FormSemantics; 9] = [
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::SignedOverflow,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
@@ -213,6 +406,7 @@ pub static FORMS: [FormSemantics; 9] = [
signedness: Signedness::Unsigned,
carry_in: CarryIn::Scc,
width: 32,
shift_count_bits: 0,
scc: SccEffect::CarryOut,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
@@ -229,6 +423,7 @@ pub static FORMS: [FormSemantics; 9] = [
signedness: Signedness::Unsigned,
carry_in: CarryIn::Scc,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Borrow,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
@@ -245,6 +440,7 @@ pub static FORMS: [FormSemantics; 9] = [
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
@@ -261,6 +457,7 @@ pub static FORMS: [FormSemantics; 9] = [
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
@@ -277,6 +474,7 @@ pub static FORMS: [FormSemantics; 9] = [
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
@@ -285,4 +483,140 @@ pub static FORMS: [FormSemantics; 9] = [
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_ANDN2_B32",
family: EncodingFamily::Sop2,
opcode: 20,
operation: Operation::AndNot,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 103 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_ORN2_B32",
family: EncodingFamily::Sop2,
opcode: 22,
operation: Operation::OrNot,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 103 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_NAND_B32",
family: EncodingFamily::Sop2,
opcode: 24,
operation: Operation::Nand,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_NOR_B32",
family: EncodingFamily::Sop2,
opcode: 26,
operation: Operation::Nor,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_XNOR_B32",
family: EncodingFamily::Sop2,
opcode: 28,
operation: Operation::Xnor,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 0,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_LSHL_B32",
family: EncodingFamily::Sop2,
opcode: 30,
operation: Operation::ShiftLeft,
signedness: Signedness::Bitwise,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 5,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_LSHR_B32",
family: EncodingFamily::Sop2,
opcode: 32,
operation: Operation::LogicalShiftRight,
signedness: Signedness::Unsigned,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 5,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
FormSemantics {
name: "S_ASHR_I32",
family: EncodingFamily::Sop2,
opcode: 34,
operation: Operation::ArithmeticShiftRight,
signedness: Signedness::Signed,
carry_in: CarryIn::None,
width: 32,
shift_count_bits: 5,
scc: SccEffect::Nonzero,
vcc: MaskEffect::Unchanged,
exec: MaskEffect::Unchanged,
wave: Wave::Any,
operands: OperandRule::Sop2Sgpr,
spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }],
verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding],
},
];
+14
View File
@@ -94,6 +94,9 @@ pub const PE32_PLUS_MAGIC: u16 = 0x020B;
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
const SECTION_HEADER_SIZE: usize = 40;
/// Host memory budget for all mapped sections of one image. This is a loader policy
/// limit, not a property of the PE format.
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
fn read_u16(bytes: &[u8], at: usize) -> u16 {
u16::from_le_bytes([bytes[at], bytes[at + 1]])
@@ -273,6 +276,17 @@ impl ParsedPe {
}
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
// Each section becomes a zero-filled host allocation, so bound the total before
// allocating anything. Sections may not overlap, so the sum is the mapped size.
let mapped: u64 = self
.sections
.iter()
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
.sum();
if mapped > MAX_MAPPED_IMAGE_BYTES {
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
}
let mut memory = GuestMemory::new();
for sec in &self.sections {
+96
View File
@@ -0,0 +1,96 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! PE image mapping budget tests (#80).
//!
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
//! backs it with zero-filled host memory, so a small file can request a large
//! allocation. The loader's documented budget is 256 MiB per image.
use xenora_loader::{MemoryError, ParsedPe, PeError};
const BUDGET: u32 = 256 * 1024 * 1024;
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
fn build(bss_sizes: &[u32]) -> Vec<u8> {
let mut pe = vec![0u8; 0x400];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&(1 + bss_sizes.len() as u16).to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&112u16.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
let h = opt + 112 + i * 40;
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
};
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
let mut va = 0x2000u32;
for (i, &size) in bss_sizes.iter().enumerate() {
section(i + 1, va, size, 0, 0xC000_0080);
va += size;
}
pe
}
fn over_budget() -> PeError {
PeError::SectionMappingError(MemoryError::AllocationFailed)
}
#[test]
fn small_image_loads() {
let bytes = build(&[0x1000]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn image_exactly_at_budget_loads() {
let bytes = build(&[BUDGET - 0x200]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn one_byte_over_budget_is_rejected() {
let bytes = build(&[BUDGET - 0x1FF]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn budget_counts_all_sections_together() {
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
let bytes = build(&[128 << 20; 3]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
let bytes = build(&[0xF000_0000]);
assert_eq!(bytes.len(), 0x400);
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn repository_fixture_is_within_budget() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/trusted-runner.exe"
);
let bytes = std::fs::read(path).unwrap();
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
+43 -3
View File
@@ -129,7 +129,7 @@ pub enum BranchCondition {
///
/// AMD RDNA 2 XML descriptions: additions store the carry-out in SCC,
/// subtractions the borrow; ADDC/SUBB add or subtract SCC; bitwise
/// operations set SCC iff the result is nonzero.
/// operations and shifts set SCC iff the result is nonzero.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarAlu {
Add,
@@ -142,6 +142,22 @@ pub enum ScalarAlu {
And,
Or,
Xor,
/// RDNA 2 ISA guide 12.1: D = S0 & ~S1, SCC = (D != 0).
AndNot,
/// D = S0 | ~S1, SCC = (D != 0).
OrNot,
/// D = ~(S0 & S1), SCC = (D != 0).
Nand,
/// D = ~(S0 | S1), SCC = (D != 0).
Nor,
/// D = ~(S0 ^ S1), SCC = (D != 0).
Xnor,
/// D = S0 << S1[4:0], SCC = (D != 0).
ShiftLeft,
/// D = S0 >> S1[4:0] (logical), SCC = (D != 0).
ShiftRight,
/// D = signext(S0) >> S1[4:0], SCC = (D != 0).
ArithmeticShiftRight,
}
/// VOP2 operations decoded by the reference interpreter.
@@ -287,7 +303,7 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
left,
right,
low,
high @ (0x80..=0x82 | 0x87 | 0x88 | 0x89),
high @ (0x80..=0x82 | 0x87..=0x91),
tail @ ..,
] if (*left, *right) != (255, 255)
&& low & 0x7f <= 105
@@ -302,7 +318,16 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
(0x82, _) => ScalarAlu::SubtractWithBorrow,
(0x87, _) => ScalarAlu::And,
(0x88, _) => ScalarAlu::Or,
_ => ScalarAlu::Xor,
(0x89, _) => ScalarAlu::Xor,
// Even opcodes 20-34 (bit 23 clear, checked above).
(0x8a, _) => ScalarAlu::AndNot,
(0x8b, _) => ScalarAlu::OrNot,
(0x8c, _) => ScalarAlu::Nand,
(0x8d, _) => ScalarAlu::Nor,
(0x8e, _) => ScalarAlu::Xnor,
(0x8f, _) => ScalarAlu::ShiftLeft,
(0x90, _) => ScalarAlu::ShiftRight,
_ => ScalarAlu::ArithmeticShiftRight,
};
let (left, left_length) = decode_scalar(*left, tail, offset)?;
let (right, right_length) = decode_scalar(*right, tail, offset)?;
@@ -694,6 +719,21 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
};
(bits, bits != 0)
}
// Guide 12.1: shifts use only S1[4:0]; all set SCC = (D != 0).
_ => {
let (a, b) = (lhs as u32, rhs as u32);
let bits = match kind {
ScalarAlu::AndNot => a & !b,
ScalarAlu::OrNot => a | !b,
ScalarAlu::Nand => !(a & b),
ScalarAlu::Nor => !(a | b),
ScalarAlu::Xnor => !(a ^ b),
ScalarAlu::ShiftLeft => a << (b & 0x1f),
ScalarAlu::ShiftRight => a >> (b & 0x1f),
_ => ((a as i32) >> (b & 0x1f)) as u32,
};
(i64::from(bits), bits != 0)
}
};
let value = exact.rem_euclid(1 << 32) as u32;
scalars[usize::from(dst)] = Some(value);
+14
View File
@@ -280,6 +280,20 @@ fn scalar_alu_results_reach_the_kernel_as_constants() {
);
}
#[test]
fn scalar_logic_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-logic.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-logic.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-logic.metal")
);
}
#[test]
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
+4 -4
View File
@@ -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: 42 of 42. Accepted Metal forms · Apple M5: 18 of 42. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 50 of 50. Accepted Metal forms · Apple M5: 18 of 50. 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">42 / 42</text>
<text x="510" y="58" font-size="13" text-anchor="end">50 / 50</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 / 42</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 50</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="210.00" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="176.40" 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

+8
View File
@@ -31,6 +31,14 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `s_and_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `870D090C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_or_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `880ED00D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_xor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `890C0A0B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_andn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0 | `8A09FF08 FF00FF00` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_orn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 \| ~S1; SCC = result != 0 | `8B0AC109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_nand_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0 | `8C0B0808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_nor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 \| S1); SCC = result != 0 | `8D0C090B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_xnor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0 | `8E0D080C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0 | `8F0EA40D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshr_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0 | `900FFF0E FFFFFFE1` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_ashr_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0 | `91109F0E` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_lt_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written | `7D020701` | 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_eq_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 == S1), fully written | `7D040280` | 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_le_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 <= S1), fully written | `7D060208` | 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 |
+23 -3
View File
@@ -1,6 +1,6 @@
# SOP2 scalar ALU subset
Xenora decodes and executes nine gfx1030 SOP2 forms. Each takes 32-bit
Xenora decodes and executes seventeen gfx1030 SOP2 forms. Each takes 32-bit
operands, writes a normal SGPR (s0-s105) and sets SCC.
| Form | D | SCC |
@@ -14,10 +14,23 @@ operands, writes a normal SGPR (s0-s105) and sets SCC.
| `s_and_b32` | S0 & S1 | D != 0 |
| `s_or_b32` | S0 \| S1 | D != 0 |
| `s_xor_b32` | S0 ^ S1 | D != 0 |
| `s_andn2_b32` | S0 & ~S1 | D != 0 |
| `s_orn2_b32` | S0 \| ~S1 | D != 0 |
| `s_nand_b32` | ~(S0 & S1) | D != 0 |
| `s_nor_b32` | ~(S0 \| S1) | D != 0 |
| `s_xnor_b32` | ~(S0 ^ S1) | D != 0 |
| `s_lshl_b32` | S0 << S1[4:0] | D != 0 |
| `s_lshr_b32` | S0 >> S1[4:0], zero fill | D != 0 |
| `s_ashr_i32` | S0 >> S1[4:0], sign fill | D != 0 |
The last eight were added through the semantic registry alone: one TOML entry
each, with no hand-written Rust per form. Shifts use only the low five bits of
S1 as the count, as the guide's pseudocode states (section 12.1); higher bits are
ignored.
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
These nine forms are declared as data in the semantic registry,
These forms are declared as data in the semantic registry,
`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in,
SCC effect, operand rule and guide references. `crates/isa/generate_semantics.py`
checks each declaration against the pinned AMD XML snapshot and rejects
@@ -85,7 +98,7 @@ literal operands, bitwise results that set and clear SCC, and an
Its expected output, input ^ 0x0000000e,
was derived by hand.
`tests/validation/known_answers.rs` runs every supported form over 10 boundary
`tests/validation/known_answers.rs` runs the first nine forms over 10 boundary
operands squared, with SCC clear and set. That is 1,800 programs. The same file
covers aliasing, inline and literal operands, and rejected forms. Expected
values come from exact integer definitions in the test. Three implementations
@@ -94,6 +107,13 @@ must agree with them:
- the reference interpreter (exact integers, reduced modulo 2^32);
- the independent interpreter (a bit-serial ripple-carry adder).
The eight logical and shift forms added through the registry have their own
suite, `tests/validation/tests/sop2_stage_c.rs`: 6,896 cases whose expected
values were derived from the guide separately from the registry, checked on
both CPU interpreters and, through the translator, on native Metal. The
LLVM-assembled `fixtures/rdna2/scalar-logic.s` (expected input ^ 0x887f00f8)
runs on all three and on native Metal.
`scalar_alu_native_metal_known_answers` runs the fixture, the 1,800 programs
and the aliasing and immediate cases on native Metal with API and shader
validation. `scripts/test-gpu.sh` runs it. This is local evidence from one
+2 -2
View File
@@ -25,7 +25,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SOP1 | 65 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOP2 | 51 | 9 | 9 | 9 | 9 | 9 | 0 | 0 | 12 |
| SOP2 | 51 | 17 | 17 | 17 | 17 | 17 | 0 | 0 | 12 |
| SOPC | 18 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
@@ -36,7 +36,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
| **Total** | 1465 | 42 | 9 | 46 | 42 | 42 | 18 | 18 | 12 |
| **Total** | 1465 | 50 | 17 | 54 | 50 | 50 | 18 | 18 | 12 |
## Unsupported operand variants
+7 -3
View File
@@ -51,10 +51,11 @@ error.
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
| `opcode` | Opcode; must match the XML | non-negative integer |
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor` |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (`bitwise` exactly for `and`, `or`, `xor`) |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr` |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, never for `add` and `sub`; shifts take their primitive's signedness) |
| `carry_in` | Whether the form reads SCC as carry-in or borrow-in | `none`, `scc` (`scc` only for unsigned `add` and `sub`) |
| `width` | Operand and result width in bits | `32` |
| `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`, `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) |
@@ -71,7 +72,10 @@ fixes the `scc` value:
| `sub` / `unsigned` | `borrow` | `sub_borrow_u32` | allowed |
| `add` / `signed` | `signed_overflow` | `add_overflow_i32` | no |
| `sub` / `signed` | `signed_overflow` | `sub_overflow_i32` | no |
| `and`, `or`, `xor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32` | no |
| `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32`, `andn2_nonzero_b32`, `orn2_nonzero_b32`, `nand_nonzero_b32`, `nor_nonzero_b32`, `xnor_nonzero_b32` | no |
| `lshl` / `bitwise` | `nonzero` | `lshl_nonzero_b32` | no |
| `lshr` / `unsigned` | `nonzero` | `lshr_nonzero_b32` | no |
| `ashr` / `signed` | `nonzero` | `ashr_nonzero_i32` | no |
Behaviour is chosen only from these declared fields, never from the mnemonic.
+96
View File
@@ -255,6 +255,102 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_andn2_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0"
representation = "`8A09FF08 FF00FF00`"
lowering = "resolved scalar state and SCC"
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_orn2_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 | ~S1; SCC = result != 0"
representation = "`8B0AC109`"
lowering = "resolved scalar state and SCC"
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_nand_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0"
representation = "`8C0B0808`"
lowering = "resolved scalar state and SCC"
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_nor_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 | S1); SCC = result != 0"
representation = "`8D0C090B`"
lowering = "resolved scalar state and SCC"
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_xnor_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0"
representation = "`8E0D080C`"
lowering = "resolved scalar state and SCC"
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_lshl_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0"
representation = "`8F0EA40D`"
lowering = "resolved scalar state and SCC"
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_lshr_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0"
representation = "`900FFF0E FFFFFFE1`"
lowering = "resolved scalar state and SCC"
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_ashr_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0"
representation = "`91109F0E`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_lt_i32_e32"
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written"
+13
View File
@@ -0,0 +1,13 @@
0000: t0 = load.u32 input[index]
0040: branch.uniform 0x004c taken=true
004c: t2 = const.u32 0xff0fffff
0050: t3 = const.u32 0x787ffff8
0054: t4 = xor.b32 t2, t3
0058: t5 = const.u32 0xffffffff
005c: t6 = xor.b32 t4, t5
0060: t7 = const.u32 0x00f00000
0064: t8 = xor.b32 t6, t7
0068: t9 = const.u32 0xf000ff00
006c: t10 = xor.b32 t8, t9
0070: t11 = xor.b32 t0, t10
0074: store.u32 output[index], t11
+19
View File
@@ -0,0 +1,19 @@
#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 t0 = input[index];
uint t2 = 0xff0fffffu;
uint t3 = 0x787ffff8u;
uint t4 = t2 ^ t3;
uint t5 = 0xffffffffu;
uint t6 = t4 ^ t5;
uint t7 = 0x00f00000u;
uint t8 = t6 ^ t7;
uint t9 = 0xf000ff00u;
uint t10 = t8 ^ t9;
uint t11 = t0 ^ t10;
output[index] = t11;
}
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOP2 vectors for the registry-declared logical and shift forms:
// ANDN2/ORN2 with a literal and an inline -1, NAND with aliased sources,
// NOR/XNOR chains, shift counts that use only S1[4:0] (36 -> 4, a literal
// 0xffffffe1 -> 1, 31), an arithmetic shift of a negative and a positive value,
// and an SCC branch on a zero shift result. SGPR results are moved into VGPRs.
// Expected: input ^ 0x887f00f8 (worked out by hand below).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, 0xf0f0ff00
s_andn2_b32 s9, s8, 0xff00ff00 // s9 = 0x00f00000, SCC = 1
s_orn2_b32 s10, s9, -1 // s10 = 0x00f00000, SCC = 1
s_nand_b32 s11, s8, s8 // s11 = 0x0f0f00ff, SCC = 1
s_nor_b32 s12, s11, s9 // s12 = 0xf000ff00, SCC = 1
s_xnor_b32 s13, s12, s8 // s13 = 0xff0fffff, SCC = 1
s_lshl_b32 s14, s13, 36 // s14 = 0xf0fffff0 (count 4), SCC = 1
s_lshr_b32 s15, s14, 0xffffffe1 // s15 = 0x787ffff8 (count 1), SCC = 1
s_ashr_i32 s16, s14, 31 // s16 = 0xffffffff, SCC = 1
s_ashr_i32 s17, s15, 31 // s17 = 0, SCC = 0
s_cbranch_scc0 .Lzero
v_mov_b32_e32 v2, 0
s_branch .Ldone
.Lzero:
v_mov_b32_e32 v2, s13
v_mov_b32_e32 v3, s15
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v4, s16
v_xor_b32_e32 v2, v2, v4
v_mov_b32_e32 v5, s10
v_xor_b32_e32 v2, v2, v5
v_mov_b32_e32 v6, s12
v_xor_b32_e32 v2, v2, v6 // 0xff0fffff ^ 0x787ffff8 ^ 0xffffffff ^ 0x00f00000 ^ 0xf000ff00
v_xor_b32_e32 v2, v1, v2
.Ldone:
buffer_store_dword v2, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
+1 -1
View File
@@ -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; do
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic; 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"
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Build Xenora.app (native ARM64) into build/Xenora.app and run its smoke check.
# Requires: macOS on Apple Silicon, Rust 1.100 (aarch64-apple-darwin), Swift 6 toolchain.
set -eu
cd "$(dirname "$0")/.."
root=$(pwd)
fail() { echo "build-app: $*" >&2; exit 1; }
[ "$(uname -s)" = Darwin ] || fail "macOS is required"
[ "$(uname -m)" = arm64 ] || fail "a native arm64 host is required"
[ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 0 ] || fail "running under Rosetta is not supported"
command -v cargo >/dev/null || fail "cargo not found; install Rust 1.100"
command -v swift >/dev/null || fail "swift not found; install the Xcode command line tools"
target=aarch64-apple-darwin
# Match the app's LSMinimumSystemVersion so the static library links cleanly.
MACOSX_DEPLOYMENT_TARGET=14.0 cargo build --locked --release -p xenora-ffi --target "$target"
swift build --package-path app -c release --arch arm64 \
-Xlinker -L -Xlinker "$root/target/$target/release"
bundle="$root/build/Xenora.app"
rm -rf "$bundle"
mkdir -p "$bundle/Contents/MacOS"
cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/Xenora" "$bundle/Contents/MacOS/Xenora"
cat > "$bundle/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key><string>Xenora</string>
<key>CFBundleIdentifier</key><string>local.xenora.Xenora</string>
<key>CFBundleName</key><string>Xenora</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>0.1.0</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST
# Ad-hoc signature for local development only. No entitlements are requested:
# this build executes no guest code, so it needs no JIT entitlement.
codesign --force --sign - "$bundle"
binary="$bundle/Contents/MacOS/Xenora"
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
"$binary" --smoke
echo "build-app: built $bundle"
@@ -32,11 +32,11 @@ U32 = "FMT_NUM_U32"
I32 = "FMT_NUM_I32"
def _operands(data_format, scc_in=False):
def _operands(data_format, scc_in=False, src1_format=None):
rows = [
["SDST", data_format, "OPR_SDST", 32, False, True, False, True],
["SSRC0", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
["SSRC1", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
["SSRC1", src1_format or data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True],
]
if scc_in:
@@ -54,7 +54,7 @@ def snapshot():
["OP", [[23, 7]]], ["ENCODING", [[30, 2]]],
],
"identifier_mask": 0xFF800000,
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14)],
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14, 34)],
}
variants = {}
for name, opcode, operands in (
@@ -62,6 +62,8 @@ def snapshot():
("S_ADD_I32", 2, _operands(I32)),
("S_ADDC_U32", 4, _operands(U32, scc_in=True)),
("S_AND_B32", 14, _operands(U32)),
# The XML gives S_ASHR_I32 a signed S0 and an unsigned shift count.
("S_ASHR_I32", 34, _operands(I32, src1_format=U32)),
):
variants[(name, "ENC_SOP2")] = {
"instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands,
@@ -94,6 +96,10 @@ def registry():
_form("S_ADD_I32", 2, "AddI32", "add", "signed", "signed_overflow"),
_form("S_ADDC_U32", 4, "AddcU32", "add", "unsigned", "carry_out", carry_in="scc"),
_form("S_AND_B32", 14, "AndB32", "and", "bitwise", "nonzero"),
dict(
_form("S_ASHR_I32", 34, "AshrI32", "ashr", "signed", "nonzero"),
shift_count_bits=5,
),
],
}
@@ -288,6 +294,54 @@ class Validate(unittest.TestCase):
reg["operand_rules"]["sop2_sgpr"]["max_literals"] = 2
self.rejects(reg, "operand rule sop2_sgpr: declaration differs")
def test_rejects_a_shift_without_a_count_width(self):
reg = registry()
del reg["form"][-1]["shift_count_bits"]
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got None")
def test_rejects_a_wrong_count_width(self):
reg = registry()
reg["form"][-1]["shift_count_bits"] = 6
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got 6")
def test_rejects_a_count_width_on_a_non_shift(self):
reg = registry()
reg["form"][0]["shift_count_bits"] = 5
self.rejects(reg, "S_ADD_U32: shift_count_bits on a non-shift operation")
def test_rejects_a_signed_shift_count_in_the_xml(self):
snap = snapshot()
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(I32)
self.rejects(registry(), "S_ASHR_I32: shift count SSRC1 has XML format FMT_NUM_I32", snap)
def test_rejects_a_float_shift_count_in_the_xml(self):
snap = snapshot()
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(
I32, src1_format="FMT_NUM_F32"
)
self.rejects(registry(), "S_ASHR_I32: shift count SSRC1 has XML format FMT_NUM_F32", snap)
def test_rejects_a_float_source_format(self):
snap = snapshot()
snap["variants"][("S_AND_B32", "ENC_SOP2")]["operands"] = _operands("FMT_NUM_F32")
self.rejects(registry(), "S_AND_B32: signedness bitwise contradicts XML format FMT_NUM_F32", snap)
def test_rejects_a_negative_count_width(self):
reg = registry()
reg["form"][-1]["shift_count_bits"] = -1
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got -1")
def test_rejects_an_unsigned_arithmetic_shift(self):
reg = registry()
reg["form"][-1]["signedness"] = "unsigned"
self.rejects(reg, "S_ASHR_I32: no primitive implements ashr/unsigned")
def test_renders_the_declared_count_mask(self):
self.assertIn(
"Self::AshrI32 => primitive::ashr_nonzero_i32(src0, src1 & 0x1f),",
gen.render(registry(), snapshot()),
)
def test_rejects_an_incomplete_unsupported_list(self):
reg = registry()
reg["operand_rules"]["sop2_sgpr"]["unsupported"].remove("two_literals")
@@ -424,14 +478,24 @@ class Render(unittest.TestCase):
self.assertNotEqual(list(reg["form"][0]), list(reordered["form"][0]))
self.assertEqual(gen.render(reg, snapshot()), gen.render(reordered, snapshot()))
def test_dispatch_is_sorted_by_opcode(self):
def test_dispatch_table_is_indexed_by_opcode(self):
reg = registry()
reg["form"].reverse()
text = gen.render(reg, snapshot())
body = text.split("match word & ", 1)[1].split("_ => None", 1)[0]
words = [line.split(" => ")[0].strip() for line in body.splitlines()[1:] if "=>" in line]
self.assertEqual(words, sorted(words))
self.assertEqual(len(words), 4)
body = text.split("const BY_OPCODE: [Option<ScalarAluOp>; 128] = [", 1)[1].split("];", 1)[0]
rows = [line.strip() for line in body.splitlines() if line.strip()]
self.assertEqual(len(rows), 128)
declared = {index: row for index, row in enumerate(rows) if row != "None,"}
self.assertEqual(sorted(declared), [0, 2, 4, 14, 34])
self.assertEqual(declared[34], "Some(ScalarAluOp::AshrI32),")
self.assertIn("if word & 0xc000_0000 != 0x8000_0000 {", text)
self.assertIn("BY_OPCODE[((word >> 23) & 0x7f) as usize]", text)
def test_rejects_identifiers_that_do_not_share_the_encoding_bits(self):
snap = snapshot()
snap["encodings"]["ENC_SOP2"]["identifiers"].append(0x40000000)
with self.assertRaisesRegex(ValueError, "do not split into fixed bits and OP"):
gen.render(registry(), snap)
def test_real_registry_renders_the_committed_file(self):
text = gen.render(gen.load_registry(), gen.load_snapshot())
+27 -4
View File
@@ -10,7 +10,8 @@
//!
//! Scope matches the demo fixtures: scalar move/compare/branch, SOP2 unsigned
//! and signed add and subtract, add-with-carry, subtract-with-borrow, AND, OR
//! and XOR, VOP1 move
//! and XOR, the stage C forms ANDN2, ORN2, NAND, NOR, XNOR, LSHL, LSHR and
//! ASHR (32-bit), VOP1 move
//! (including from an SGPR),
//! VOP2 bitwise, shift, arithmetic-shift and float, VOP3 add-no-carry, MUBUF
//! load/store and the two waits plus `s_endpgm`. Anything else is a controlled
@@ -50,7 +51,7 @@ enum CmpSrc {
#[derive(Clone, Copy, Debug)]
enum Insn {
SMov(u8, Src),
/// SOP2 opcode 0-5, 14, 16 or 18.
/// SOP2 opcode 0-5, 14, 16, 18 or an even opcode 20-34.
SAlu(u32, u8, Src, Src),
SCmpEq(Src, Src),
BranchScc0(usize),
@@ -320,6 +321,18 @@ fn scalar_alu(
let (value, carry) = ripple(a, !b, !borrow);
(value, !carry)
}
// RDNA 2 ISA guide 12.1: the shifts use only S1[4:0], taken here as
// the remainder modulo 32, and scale by a power of two in exact
// arithmetic; ASHR is floor division of the signed S0. SCC = D != 0.
30 | 32 | 34 => {
let scale = 1_i64 << (b % 32);
let value = match opcode {
30 => (i64::from(a) * scale).rem_euclid(1 << 32),
32 => i64::from(a) / scale,
_ => i64::from(a as i32).div_euclid(scale).rem_euclid(1 << 32),
} as u32;
(value, value != 0)
}
_ => {
let mut value = 0;
for bit in 0..32 {
@@ -327,7 +340,12 @@ fn scalar_alu(
let set = match opcode {
14 => x && y,
16 => x || y,
_ => x != y,
18 => x != y,
20 => x && !y,
22 => x || !y,
24 => !(x && y),
26 => !(x || y),
_ => x == y,
};
value |= u32::from(set) << bit;
}
@@ -795,7 +813,12 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
return Ok((Insn::SMov(dst, src), len));
}
// SOP2: ENCODING 0b10 in bits 30-31, OP in bits 23-29, SDST in 16-22.
if first >> 30 == 0b10 && matches!((first >> 23) & 0x7f, 0..=5 | 14 | 16 | 18) {
if first >> 30 == 0b10
&& matches!(
(first >> 23) & 0x7f,
0..=5 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34
)
{
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(fail("unsupported SOP2 destination"));
+24 -1
View File
@@ -768,6 +768,9 @@ mod review {
}
const SCALAR_ALU_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-alu.bin");
const SCALAR_LOGIC_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-logic.bin");
// Hand-derived in fixtures/rdna2/scalar-logic.s from the guide's 12.1 pseudocode.
const SCALAR_LOGIC_KEY: u32 = 0x887f_00f8;
// SOP2 opcodes of the supported subset (RDNA 2 XML opcode table).
const SOP2_OPCODES: [u32; 9] = [0, 1, 2, 3, 4, 5, 14, 16, 18];
const SCALAR_VALUES: [u32; 10] = [
@@ -869,6 +872,24 @@ mod review {
verify(&nonzero, &input, Some(&[0; 5]));
}
#[test]
fn scalar_logic_fixture_chains_registry_logical_and_shift_forms() {
let input = [0, 1, u32::MAX, SCALAR_LOGIC_KEY, 0x1234_5678];
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
verify(SCALAR_LOGIC_FIXTURE, &input, Some(&expected));
let compiled = compile(Architecture::Gfx1030, SCALAR_LOGIC_FIXTURE).unwrap();
assert!(compiled.disassembly.contains("s_ashr_i32 s17, s15, 31"));
// The SCC-zero edge is observable: with a shift count of 30 instead of
// 31, s17 = 0x787ffff8 >> 30 = 1, SCC = 1, and v2 = 0.
let mut nonzero = SCALAR_LOGIC_FIXTURE.to_vec();
let at = nonzero
.windows(4)
.position(|word| word == [0x0f, 0x9f, 0x11, 0x91])
.unwrap();
nonzero[at + 1] = 0x9e;
verify(&nonzero, &input, Some(&[0; 5]));
}
/// The translator's own folding: v2 = D as a constant, and the SCC-zero edge
/// is taken exactly when SCC is clear.
fn assert_translated(code: &[u8], expected: &[u32; 2]) {
@@ -1089,6 +1110,8 @@ mod review {
let input: Vec<u32> = (0..64).map(|lane| lane * 0x0101_0101).collect();
let expected: Vec<_> = input.iter().map(|word| word ^ 0x0000_000e).collect();
assert_eq!(run(SCALAR_ALU_FIXTURE, &input), expected);
let logic: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
assert_eq!(run(SCALAR_LOGIC_FIXTURE, &input), logic);
let mut vectors = sop2_vectors();
vectors.extend(sop2_operand_cases());
vectors.extend(signed_immediate_overflows());
@@ -1097,7 +1120,7 @@ mod review {
}
eprintln!(
"{} SOP2 programs matched on native Metal",
vectors.len() + 1
vectors.len() + 2
);
}
+328
View File
@@ -0,0 +1,328 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent expected values for the eight SOP2 forms added in #215 stage C:
//! `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`,
//! `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`.
//!
//! The expectations are written below from the public AMD "RDNA 2" Instruction
//! Set Architecture Reference Guide only: section 12.1 "SOP2 Instructions" for
//! D and SCC of each form, section 5.3 for the SCC rule of bit/logical
//! operations, and the scalar operand table (section 3) for inline integer
//! constants. 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.
#[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};
/// The eight stage C forms with their ENC_SOP2 opcodes (guide 12.1).
#[derive(Clone, Copy, Debug)]
enum Form {
Andn2 = 20,
Orn2 = 22,
Nand = 24,
Nor = 26,
Xnor = 28,
Lshl = 30,
Lshr = 32,
Ashr = 34,
}
const FORMS: [(Form, &str); 8] = [
(Form::Andn2, "s_andn2_b32"),
(Form::Orn2, "s_orn2_b32"),
(Form::Nand, "s_nand_b32"),
(Form::Nor, "s_nor_b32"),
(Form::Xnor, "s_xnor_b32"),
(Form::Lshl, "s_lshl_b32"),
(Form::Lshr, "s_lshr_b32"),
(Form::Ashr, "s_ashr_i32"),
];
/// The guide's D and SCC for `form` with S0 = `s0` and S1 = `s1`. None of
/// these forms reads SCC, so the value of SCC before the instruction is not an
/// input.
fn expect(form: Form, s0: u32, s1: u32) -> (u32, bool) {
let d = match form {
// 20 S_ANDN2_B32: D = S0 & ~S1; SCC = (D != 0).
Form::Andn2 => s0 & !s1,
// 22 S_ORN2_B32: D = S0 | ~S1; SCC = (D != 0).
Form::Orn2 => s0 | !s1,
// 24 S_NAND_B32: D = ~(S0 & S1); SCC = (D != 0).
Form::Nand => !(s0 & s1),
// 26 S_NOR_B32: D = ~(S0 | S1); SCC = (D != 0).
Form::Nor => !(s0 | s1),
// 28 S_XNOR_B32: D = ~(S0 ^ S1); SCC = (D != 0).
Form::Xnor => !(s0 ^ s1),
// 30 S_LSHL_B32: D.u = S0.u << S1.u[4:0]; SCC = (D.u != 0).
Form::Lshl => s0 << (s1 & 0x1f),
// 32 S_LSHR_B32: D.u = S0.u >> S1.u[4:0]; SCC = (D.u != 0).
Form::Lshr => s0 >> (s1 & 0x1f),
// 34 S_ASHR_I32: D.i = signext(S0.i) >> S1.u[4:0]; SCC = (D.i != 0).
// S1 is read as unsigned and only its low five bits count, so its
// sign never matters; the shift replicates S0's sign bit.
Form::Ashr => ((s0 as i32) >> (s1 & 0x1f)) as u32,
};
// Section 5.3: bit/logical operations set SCC = 1 iff the result is not zero.
(d, d != 0)
}
/// Guide section 3 scalar operand table: 128 is 0, 129-192 are 1 to 64 and
/// 193-208 are -1 to -16, as 32-bit words.
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"),
}
}
const LITERAL: u32 = 255;
/// Boundary operands and alternating bit patterns.
const VALUES: [u32; 8] = [
0,
1,
0x7fff_ffff,
0x8000_0000,
0xffff_ffff,
0xaaaa_aaaa,
0x5555_5555,
0x1234_5678,
];
/// Shift counts around the five-bit field, and one whose low bits are 1.
const SHIFTS: [u32; 7] = [0, 1, 31, 32, 33, 63, 0xffff_ffe1];
const INPUT: [u32; 2] = [0, u32::MAX];
const COUNTS: [(&str, usize); 5] = [
("stage c domain", 8 * 8 * 8 * 2),
("stage c shift count", 3 * 8 * 7 * 2),
("stage c aliasing", 8 * 2 * 5 * 2),
("stage c inline integer", 8 * 81 * 2 * 2 * 2),
("stage c literal", 8 * 6 * 2 * 2),
];
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7.
fn sop2(form: Form, dst: u32, src0: u32, src1: u32) -> u32 {
0x8000_0000 | (form as u32) << 23 | dst << 16 | src1 << 8 | src0
}
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
/// `scc` with `s_cmp_eq_u32`, run `alu`, then v2 = s<result>, XORed with v1
/// when SCC is set afterwards, and store v2. With the lane input [0, !0] the
/// output is [D, D] when SCC is clear and [D, !D] when it is set.
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
for &(reg, value) in init {
code.extend([0xbe80_03ff | reg << 16, value]);
}
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
code.extend(alu);
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn case(
name: &'static str,
family: &'static str,
label: String,
code: Vec<u8>,
out: (u32, bool),
) -> Case {
let (d, scc) = out;
Case {
form: name,
family,
label: format!("{name} {label}"),
code,
input: INPUT.to_vec(),
expected: vec![d, if scc { !d } else { d }],
}
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (form, name) in FORMS {
let shift = matches!(form, Form::Lshl | Form::Lshr | Form::Ashr);
for scc in [false, true] {
let alu = [sop2(form, 10, 8, 9)];
let pairs = VALUES
.iter()
.flat_map(|&a| VALUES.map(|b| (a, b, "stage c domain")));
let counts = VALUES
.iter()
.flat_map(|&a| SHIFTS.map(|b| (a, b, "stage c shift count")));
let counts: Vec<_> = if shift { counts.collect() } else { Vec::new() };
for (a, b, family) in pairs.chain(counts) {
let code = program(&[(8, a), (9, b)], scc, &alu, 10);
let label = format!("{a:#x}, {b:#x}, scc before {scc}");
cases.push(case(name, family, label, code, expect(form, a, b)));
}
// dst/src aliasing with s8 = a, s9 = b.
for (a, b) in [(0xffff_fff0, 0x21), (0x8000_0001, 0x8000_0001)] {
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
let pick = |reg| if reg == 8 { a } else { b };
let code = program(&[(8, a), (9, b)], scc, &[sop2(form, dst, src0, src1)], dst);
let label =
format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x}), scc before {scc}");
let out = expect(form, pick(src0), pick(src1));
cases.push(case(name, "stage c aliasing", label, code, out));
}
}
// Every integer inline constant (-16..64) in each source slot. The
// register operand s8 takes a word and its complement, so a wrong
// inline value changes D for at least one of them (as a shift
// count it is 0x40 and 0x21, i.e. counts 0 and 1).
for selector in 128..=208 {
let value = inline_integer(selector);
for (slot, other) in [0, 1].into_iter().flat_map(|slot| {
let others = if slot == 0 && shift {
[0x40, 0x21]
} else {
[0x8000_0f0f, 0x7fff_f0f0]
};
others.map(|other| (slot, other))
}) {
let (alu, out) = if slot == 0 {
(sop2(form, 10, selector, 8), expect(form, value, other))
} else {
(sop2(form, 10, 8, selector), expect(form, other, value))
};
let code = program(&[(8, other)], scc, &[alu], 10);
let label =
format!("inline {value:#x} in src{slot}, s8 {other:#x}, scc before {scc}");
cases.push(case(name, "stage c inline integer", label, code, out));
}
}
// A 32-bit literal dword after the SOP2 word in each source slot.
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0xffff_ffe1] {
for slot in 0..2 {
let other = 0xc000_0003;
let (alu, out) = if slot == 0 {
(
[sop2(form, 10, LITERAL, 8), value],
expect(form, value, other),
)
} else {
(
[sop2(form, 10, 8, LITERAL), value],
expect(form, other, value),
)
};
let code = program(&[(8, other)], scc, &alu, 10);
let label = format!("literal {value:#x} in src{slot}, scc before {scc}");
cases.push(case(name, "stage c literal", label, code, out));
}
}
}
}
cases
}
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
let mut counts = BTreeMap::new();
for case in cases {
*counts.entry(key(case)).or_default() += 1;
}
counts
}
/// Runs `execute` on every case and returns one line per failing family: the
/// number of failures and the first one.
fn failures(
cases: &[Case],
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
) -> Vec<String> {
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
for case in cases {
let output = execute(&case.code, &case.input);
if output.as_deref().ok() != Some(case.expected.as_slice()) {
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
failed.entry(case.family).or_insert((0, first)).0 += 1;
}
}
failed
.into_iter()
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
.collect()
}
fn checked_cases() -> Vec<Case> {
let cases = cases();
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
cases
}
#[test]
fn stage_c_forms_match_the_guide_on_the_reference() {
let cases = checked_cases();
let failed = failures(&cases, |code, input| {
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
});
assert!(
failed.is_empty(),
"reference disagrees with the guide:\n{}",
failed.join("\n")
);
eprintln!("sop2_stage_c: {} reference cases", cases.len());
for (form, n) in tally(&cases, |case| case.form) {
eprintln!(" form {form}: {n}");
}
}
#[test]
fn stage_c_forms_match_the_guide_on_the_independent_interpreter() {
let cases = checked_cases();
let failed = failures(&cases, independent_ref::execute);
assert!(
failed.is_empty(),
"independent interpreter disagrees with the guide:\n{}",
failed.join("\n")
);
eprintln!(
"sop2_stage_c: {} independent-interpreter cases",
cases.len()
);
}
#[test]
fn odd_opcodes_beside_the_stage_c_forms_stay_unsupported() {
// The 64-bit neighbours (opcodes 21-35 odd) read aligned SGPR pairs
// (s[10:11] = s[8:9] op s[12:13], all initialized); neither interpreter
// supports them, so each must refuse the SOP2 word.
for op in (21..=35).step_by(2) {
let alu = [0x8000_0000 | op << 23 | 10 << 16 | 12 << 8 | 8];
let init = [(8, 1), (9, 2), (12, 3), (13, 4)];
let code = program(&init, false, &alu, 10);
assert!(
xenora_ref::execute(&code, &INPUT).is_err(),
"reference accepted opcode {op}"
);
assert!(
independent_ref::execute(&code, &INPUT).is_err(),
"independent accepted opcode {op}"
);
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn stage_c_forms_match_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
let cases = checked_cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
"sop2_stage_c: {} Metal cases in {programs} programs",
cases.len()
);
}