mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 01:21:11 +00:00
Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6eece6983 | ||
|
|
1a78265ede | ||
|
|
2e0e5a36f6 | ||
|
|
ece0fc27eb | ||
|
|
82f2d9e9e6 | ||
|
|
391367a531 | ||
|
|
e71a3da525 | ||
|
|
b96511bfc5 | ||
|
|
84bb80d910 | ||
|
|
9edf644d77 | ||
|
|
b5d0382e89 | ||
|
|
b705104403 | ||
|
|
f148b51a48 | ||
|
|
c979870b3a | ||
|
|
cd59e081d9 | ||
|
|
0bfb12fd17 | ||
|
|
c6d0986da2 | ||
|
|
9a9422c7da | ||
|
|
da41b6420d | ||
|
|
3f710928af | ||
|
|
2fdf01fbb3 | ||
|
|
de00cb2bfd | ||
|
|
d8f9669280 | ||
|
|
19b2e9b5d5 | ||
|
|
bb6bc52c95 | ||
|
|
ba6bbb2e4a | ||
|
|
705b074a08 | ||
|
|
d3c1150854 | ||
|
|
a81d62ffe3 | ||
|
|
bb1372cd70 | ||
|
|
8d53d82981 | ||
|
|
ba2cfc2a00 | ||
|
|
b13ab327f2 | ||
|
|
e7cb8db14f | ||
|
|
e7795d0e5a | ||
|
|
3ff9ddde24 | ||
|
|
ff191d89bd | ||
|
|
4039be8ee2 | ||
|
|
898b79dc84 | ||
|
|
30d20c8f33 | ||
|
|
0687a8add6 | ||
|
|
791b736b0e | ||
|
|
fcda9c09bd | ||
|
|
ad5a6f9c53 | ||
|
|
e1317322e1 | ||
|
|
92fd955a8d |
No files matched your search
@@ -37,3 +37,6 @@ __pycache__/
|
||||
*.pyc
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
|
||||
# Native application build output
|
||||
/app/.build/
|
||||
@@ -11,6 +11,12 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
|
||||
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
|
||||
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
|
||||
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
|
||||
- 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.
|
||||
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
|
||||
|
||||
Generated
+9
@@ -179,6 +179,15 @@ dependencies = [
|
||||
"xenora-ref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-ffi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-import-gen"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -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"]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
module CXenora [system] {
|
||||
header "../../../crates/ffi/include/xenora.h"
|
||||
link "xenora_ffi"
|
||||
export *
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Native shell over the versioned C interface. "Run trusted fixture" executes the
|
||||
// bundled trusted PE fixture (x86-64 translated to ARM64; its draw request is rendered
|
||||
// by native Metal) and shows the verified read-back frame. No other executable can run.
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame produced by one run of the trusted fixture.
|
||||
struct GuestFrame {
|
||||
let status: Int32
|
||||
let width: Int
|
||||
let height: Int
|
||||
let rgba: [UInt8]
|
||||
|
||||
static func run() -> GuestFrame {
|
||||
var session: xenora_session = 0
|
||||
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard status == XENORA_OK else { return GuestFrame(status: status, width: 0, height: 0, rgba: []) }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
var width: UInt32 = 0
|
||||
var height: UInt32 = 0
|
||||
status = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_run_trusted_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
|
||||
}
|
||||
return GuestFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
|
||||
}
|
||||
|
||||
var image: CGImage? {
|
||||
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
|
||||
return CGImage(
|
||||
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
let first = rgba.prefix(4).map(String.init).joined(separator: ",")
|
||||
return "status=\(status) frame=\(width)x\(height) first_pixel=\(first)"
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the latest fixture run. A class with @Published avoids SwiftUI macros,
|
||||
/// which the command-line toolchain does not ship.
|
||||
@MainActor
|
||||
final class FrameModel: ObservableObject {
|
||||
@Published var frame: GuestFrame?
|
||||
@Published var running = false
|
||||
|
||||
func run() {
|
||||
running = true
|
||||
Task {
|
||||
// The fixture blocks while it executes and renders, so keep it off the main thread.
|
||||
frame = await Task.detached { GuestFrame.run() }.value
|
||||
running = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
let probe = RuntimeProbe.run()
|
||||
@ObservedObject var model: FrameModel
|
||||
private var frame: GuestFrame? { model.frame }
|
||||
private var running: Bool { model.running }
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section("Guest display") {
|
||||
if let image = frame?.image {
|
||||
Image(decorative: image, scale: 1)
|
||||
.resizable()
|
||||
.interpolation(.none)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
|
||||
.accessibilityLabel("Guest frame, \(frame!.width) by \(frame!.height) pixels")
|
||||
Text("Guest code ran, its draw was rendered by native Metal, and all \(frame!.width * frame!.height) pixels matched the fixture shader's output.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
} else if let frame {
|
||||
Text("Run failed (status \(frame.status)). No frame is shown.")
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
|
||||
.disabled(running || !probe.connected)
|
||||
}
|
||||
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("Only the bundled trusted fixture can run. Live presentation, persistent sessions and input are not available yet.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.frame(minWidth: 460, minHeight: 420)
|
||||
}
|
||||
}
|
||||
|
||||
struct XenoraApp: App {
|
||||
let model = FrameModel()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup("Xenora") { ContentView(model: model) }
|
||||
}
|
||||
}
|
||||
|
||||
// `--smoke-frame` runs the trusted fixture on the Metal device and exits; it needs a GPU.
|
||||
if CommandLine.arguments.contains("--smoke-frame") {
|
||||
let frame = GuestFrame.run()
|
||||
print(frame.summary)
|
||||
exit(frame.status == XENORA_OK ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--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()
|
||||
+23
-13
@@ -4,15 +4,15 @@ use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarSource, VectorCompareOp, VectorSource,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorCompareOp, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
@@ -41,7 +41,7 @@ const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
|
||||
}
|
||||
|
||||
/// Decoded forms not yet described by the semantic registry.
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
@@ -50,7 +50,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_CMP_EQ_U32", EncodingFamily::Sopc),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
@@ -375,19 +374,30 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
|
||||
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
|
||||
}
|
||||
if S_CMP_EQ_U32.matches(first) {
|
||||
if let Some(op) = ScalarUnaryOp::from_word(first) {
|
||||
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
|
||||
let mnemonic = op.mnemonic();
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
|
||||
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
|
||||
}
|
||||
if let Some(op) = ScalarCompareOp::from_word(first) {
|
||||
let mnemonic = op.mnemonic();
|
||||
let src0_bits = first as u8;
|
||||
let src1_bits = (first >> 8) as u8;
|
||||
if src0_bits == 255 && src1_bits == 255 {
|
||||
return Err(unsupported(
|
||||
"s_cmp_eq_u32",
|
||||
mnemonic,
|
||||
"only one source may select a literal",
|
||||
));
|
||||
}
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
|
||||
return Ok((
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 },
|
||||
Instruction::ScalarCompare { op, src0, src1 },
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
|
||||
@@ -4,9 +4,12 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, VectorSource, decode, decode_at,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorSource, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
|
||||
};
|
||||
use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
@@ -340,6 +343,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),
|
||||
@@ -347,8 +358,38 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
),
|
||||
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
|
||||
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
|
||||
match op {
|
||||
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
|
||||
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
|
||||
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
|
||||
ScalarUnaryOp::Bcnt1I32B32 => ScalarUnary::CountOnes,
|
||||
ScalarUnaryOp::Ff0I32B32 => ScalarUnary::FindFirstZero,
|
||||
ScalarUnaryOp::Ff1I32B32 => ScalarUnary::FindFirstOne,
|
||||
ScalarUnaryOp::FlbitI32B32 => ScalarUnary::FindLastBit,
|
||||
ScalarUnaryOp::FlbitI32 => ScalarUnary::FindLastSignBit,
|
||||
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
|
||||
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
|
||||
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src),
|
||||
),
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
|
||||
// The reference keeps CompareEqual for EQ and uses its VOPC relation
|
||||
// offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest.
|
||||
match op.relation() {
|
||||
CompareRelation::Equal => Op::CompareEqual(src0, src1),
|
||||
relation => Op::ScalarCompare(
|
||||
Comparison {
|
||||
offset: relation as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
},
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
}
|
||||
}
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
@@ -434,13 +475,16 @@ 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/scalar-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-unary.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(), 72, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
|
||||
@@ -49,3 +49,11 @@ fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_forms_do_not_duplicate_hand_written_forms() {
|
||||
// A form declared in the semantic registry and also decoded by hand-written
|
||||
// code would have two implementations; the hand-written one would win.
|
||||
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[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
|
||||
|
||||
[features]
|
||||
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
|
||||
gpu-tests = []
|
||||
|
||||
[dependencies]
|
||||
xenora-loader = { path = "../loader" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
@@ -0,0 +1,68 @@
|
||||
/* 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,
|
||||
XENORA_BUFFER_TOO_SMALL = 7,
|
||||
XENORA_EXECUTION_FAILED = 8,
|
||||
};
|
||||
|
||||
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
|
||||
#define XENORA_FIXTURE_FRAME_WIDTH 4u
|
||||
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
|
||||
|
||||
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);
|
||||
|
||||
/*
|
||||
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
|
||||
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
|
||||
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
|
||||
* checked against the fixture shader's known output. `capacity` is the size of
|
||||
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
|
||||
* Only the embedded fixture can run; no caller-supplied executable is accepted.
|
||||
*/
|
||||
xenora_status xenora_session_run_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,438 @@
|
||||
// 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::{Arc, Mutex};
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, ParsedPe, Register};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
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;
|
||||
pub const XENORA_BUFFER_TOO_SMALL: i32 = 7;
|
||||
pub const XENORA_EXECUTION_FAILED: i32 = 8;
|
||||
|
||||
pub const XENORA_FIXTURE_FRAME_WIDTH: u32 = 4;
|
||||
pub const XENORA_FIXTURE_FRAME_HEIGHT: u32 = 3;
|
||||
const FRAME_BYTES: usize = (XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4) as usize;
|
||||
|
||||
/// 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
|
||||
})
|
||||
}
|
||||
|
||||
// The trusted fixture's contract, as checked by the CLI runner (crates/cli/src/runner.rs).
|
||||
// ponytail: duplicated from the runner so the CLI stays untouched; extract a shared
|
||||
// fixture-run function into a library when a third caller appears.
|
||||
const IMAGE_BASE: u64 = 0x1_5000_0000;
|
||||
const TICKET_ADDRESS: u64 = IMAGE_BASE + 0x3000;
|
||||
const TICKET: u64 = 17;
|
||||
const DRAW_RESULT: u64 = 0x42;
|
||||
const ENTRY_STEPS: usize = 100;
|
||||
/// `x9-constant-ps.s` exports (1.0, 0, 0, 1.0) to mrt0; in an RGBA8 target that is opaque red.
|
||||
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
fn draw() -> Result<Vec<u8>, String> {
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)
|
||||
.map_err(|e| format!("shader translation: {e}"))?;
|
||||
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
|
||||
let pixels = gpu
|
||||
.render_rgba8(
|
||||
&shader.msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[3.0, -1.0, 0.5, 1.0],
|
||||
[-1.0, 3.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
[
|
||||
XENORA_FIXTURE_FRAME_WIDTH as usize,
|
||||
XENORA_FIXTURE_FRAME_HEIGHT as usize,
|
||||
],
|
||||
[19, 43, 93, 251],
|
||||
)
|
||||
.map_err(|e| format!("Metal render: {e}"))?;
|
||||
if pixels != EXPECTED_PIXEL.repeat(FRAME_BYTES / 4) {
|
||||
return Err("read-back frame differs from the fixture shader's output".into());
|
||||
}
|
||||
Ok(pixels)
|
||||
}
|
||||
|
||||
/// Run the embedded fixture and return its verified frame.
|
||||
fn run_fixture() -> Result<Vec<u8>, String> {
|
||||
let frame = Arc::new(Mutex::new(None));
|
||||
let draw_frame = Arc::clone(&frame);
|
||||
let mut imports = ImportRegistry::new();
|
||||
imports.register("xenora.dll", "fixture_draw", move |args, _, memory| {
|
||||
let fault = ExitReason::IllegalInstruction(0xff);
|
||||
let ticket = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let mut slot = draw_frame.lock().map_err(|_| fault)?;
|
||||
if slot.is_some()
|
||||
|| ticket != TICKET_ADDRESS
|
||||
|| memory.read_u64(ticket).map_err(ExitReason::MemoryFault)? != TICKET
|
||||
{
|
||||
return Err(fault);
|
||||
}
|
||||
let result = draw();
|
||||
let ok = result.is_ok();
|
||||
*slot = Some(result);
|
||||
if ok { Ok(DRAW_RESULT) } else { Err(fault) }
|
||||
});
|
||||
let startup = run_synthetic_startup(
|
||||
FIXTURE,
|
||||
StartupLayout {
|
||||
image_base: IMAGE_BASE,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
},
|
||||
imports,
|
||||
ENTRY_STEPS,
|
||||
)
|
||||
.map_err(|e| format!("startup: {e}"))?;
|
||||
let drawn = frame.lock().map_err(|_| "frame lock poisoned")?.take();
|
||||
if let Some(Err(e)) = drawn {
|
||||
return Err(e);
|
||||
}
|
||||
let execution = &startup.execution;
|
||||
if execution.exit_reason != ExitReason::Halt
|
||||
|| startup.relocations.applied_dir64 != 4
|
||||
|| startup.bound_imports != 1
|
||||
|| startup.tls_callbacks != 1
|
||||
|| execution.final_state.get(Register::Rax) != DRAW_RESULT
|
||||
{
|
||||
return Err(format!(
|
||||
"unexpected guest result: {:?}",
|
||||
execution.exit_reason
|
||||
));
|
||||
}
|
||||
drawn.ok_or_else(|| String::from("guest halted without a draw"))?
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `out_rgba` must be null or valid for `capacity` byte writes; each `u32` output
|
||||
/// must be null or valid for one aligned write.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_run_trusted_fixture(
|
||||
session: u64,
|
||||
out_rgba: *mut u8,
|
||||
capacity: u64,
|
||||
out_width: *mut u32,
|
||||
out_height: *mut u32,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if out_rgba.is_null() || out_width.is_null() || out_height.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,
|
||||
}
|
||||
if capacity < FRAME_BYTES as u64 {
|
||||
return XENORA_BUFFER_TOO_SMALL;
|
||||
}
|
||||
let Ok(pixels) = run_fixture() else {
|
||||
return XENORA_EXECUTION_FAILED;
|
||||
};
|
||||
// SAFETY: non-null and at least FRAME_BYTES long, both checked above.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(pixels.as_ptr(), out_rgba, FRAME_BYTES);
|
||||
out_width.write(XENORA_FIXTURE_FRAME_WIDTH);
|
||||
out_height.write(XENORA_FIXTURE_FRAME_HEIGHT);
|
||||
}
|
||||
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),
|
||||
("XENORA_BUFFER_TOO_SMALL", XENORA_BUFFER_TOO_SMALL),
|
||||
("XENORA_EXECUTION_FAILED", XENORA_EXECUTION_FAILED),
|
||||
] {
|
||||
assert!(header.contains(&format!("{name} = {value},")), "{name}");
|
||||
}
|
||||
assert!(header.contains(&format!(
|
||||
"XENORA_FIXTURE_FRAME_WIDTH {XENORA_FIXTURE_FRAME_WIDTH}u"
|
||||
)));
|
||||
assert!(header.contains(&format!(
|
||||
"XENORA_FIXTURE_FRAME_HEIGHT {XENORA_FIXTURE_FRAME_HEIGHT}u"
|
||||
)));
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixture_run_rejects_bad_arguments_before_executing() {
|
||||
let _serial = serial();
|
||||
let handle = create();
|
||||
let (mut buf, mut w, mut h) = ([0u8; 48], 0u32, 0u32);
|
||||
let run = |session, buf: *mut u8, cap, w: *mut u32, h: *mut u32| unsafe {
|
||||
xenora_session_run_trusted_fixture(session, buf, cap, w, h)
|
||||
};
|
||||
assert_eq!(
|
||||
run(handle, buf.as_mut_ptr(), 47, &mut w, &mut h),
|
||||
XENORA_BUFFER_TOO_SMALL
|
||||
);
|
||||
assert_eq!(
|
||||
run(handle, null_mut(), 48, &mut w, &mut h),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
run(handle, buf.as_mut_ptr(), 48, null_mut(), &mut h),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
xenora_session_destroy(handle);
|
||||
assert_eq!(
|
||||
run(handle, buf.as_mut_ptr(), 48, &mut w, &mut h),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
assert_eq!((w, h), (0, 0), "outputs untouched on failure");
|
||||
assert!(buf.iter().all(|&b| b == 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Runs the trusted fixture through the C interface on a native Metal device.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
|
||||
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
|
||||
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
#[test]
|
||||
fn guest_fixture_frame_reaches_the_caller_through_metal() {
|
||||
for run in 0..3 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
|
||||
let status = unsafe {
|
||||
xenora_session_run_trusted_fixture(
|
||||
session,
|
||||
rgba.as_mut_ptr(),
|
||||
64,
|
||||
&mut width,
|
||||
&mut height,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, XENORA_OK, "run {run}");
|
||||
assert_eq!((width, height), (4, 3));
|
||||
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
|
||||
assert!(
|
||||
rgba[48..].iter().all(|&b| b == 0),
|
||||
"no write past the frame"
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ VARIANTS = (
|
||||
("V_ADD_NC_U32", "ENC_VOP3"),
|
||||
("S_ENDPGM", "ENC_SOPP"),
|
||||
("S_MOV_B32", "ENC_SOP1"),
|
||||
("S_CMP_EQ_U32", "ENC_SOPC"),
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP"),
|
||||
("S_CBRANCH_EXECZ", "ENC_SOPP"),
|
||||
("S_CBRANCH_VCCZ", "ENC_SOPP"),
|
||||
|
||||
@@ -38,8 +38,52 @@ 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",
|
||||
"compare": "Compare",
|
||||
"not": "Not", "brev": "ReverseBits", "bcnt0": "CountZeros", "bcnt1": "CountOnes",
|
||||
"ff0": "FindFirstZero", "ff1": "FindFirstOne", "flbit": "FindLastBit",
|
||||
"sext": "SignExtend", "abs": "Absolute",
|
||||
}
|
||||
# Unary operations read one source; they need an operand rule of the unary kind.
|
||||
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
|
||||
# Sign extension reads only the low source_bits of S0 (required for sext only).
|
||||
SOURCE_BITS_KEY = "source_bits"
|
||||
SOURCE_BITS = {8, 16}
|
||||
# Compares take a relation (S0 on the left) and set SCC to whether it holds.
|
||||
RELATION_KEY = "relation"
|
||||
RELATIONS = {
|
||||
"eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual",
|
||||
"lt": "Less", "le": "LessOrEqual",
|
||||
}
|
||||
# (relation, signedness) -> primitive. Equality does not depend on signedness,
|
||||
# so both declared signednesses of EQ and LG share one primitive.
|
||||
COMPARE_PRIMITIVES = {
|
||||
("eq", "signed"): "eq_b32", ("eq", "unsigned"): "eq_b32",
|
||||
("lg", "signed"): "ne_b32", ("lg", "unsigned"): "ne_b32",
|
||||
("gt", "signed"): "gt_i32", ("gt", "unsigned"): "gt_u32",
|
||||
("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32",
|
||||
("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32",
|
||||
("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32",
|
||||
}
|
||||
# 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",
|
||||
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1",
|
||||
}
|
||||
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 = {
|
||||
@@ -48,6 +92,7 @@ SCC = {
|
||||
"borrow": "Borrow",
|
||||
"signed_overflow": "SignedOverflow",
|
||||
"nonzero": "Nonzero",
|
||||
"relation": "Relation",
|
||||
}
|
||||
MASK = {"unchanged": "Unchanged"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
@@ -86,6 +131,24 @@ 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),
|
||||
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
|
||||
("brev", "bitwise"): ("unchanged", "brev_b32", False),
|
||||
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
|
||||
("bcnt1", "bitwise"): ("nonzero", "bcnt1_nonzero_b32", False),
|
||||
("ff0", "bitwise"): ("unchanged", "ff0_b32", False),
|
||||
("ff1", "bitwise"): ("unchanged", "ff1_b32", False),
|
||||
("flbit", "bitwise"): ("unchanged", "flbit_b32", False),
|
||||
("flbit", "signed"): ("unchanged", "flbit_i32", False),
|
||||
("sext", "signed"): ("unchanged", "sext_i32", False),
|
||||
("abs", "signed"): ("nonzero", "abs_nonzero_i32", False),
|
||||
}
|
||||
|
||||
# Operand rules the decoder implements, each exactly once. A registry rule must
|
||||
@@ -109,6 +172,35 @@ OPERAND_RULES = {
|
||||
},
|
||||
# Every one of these is rejected by the decoder's SOP2 operand checks.
|
||||
"unsupported": UNSUPPORTED_COMBOS,
|
||||
"kind": "alu",
|
||||
},
|
||||
"sopc_scalar": {
|
||||
"rust": "SopcScalar",
|
||||
"enum": "ScalarCompareOp",
|
||||
"shape": {
|
||||
"family": "SOPC",
|
||||
"src": [
|
||||
{"field": "SSRC0", "class": "scalar_source"},
|
||||
{"field": "SSRC1", "class": "scalar_source"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# SOPC has no destination field; the decoder rejects these sources.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if not combo.startswith("dst_")},
|
||||
"kind": "compare",
|
||||
},
|
||||
"sop1_sgpr": {
|
||||
"rust": "Sop1Sgpr",
|
||||
"enum": "ScalarUnaryOp",
|
||||
"shape": {
|
||||
"family": "SOP1",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [{"field": "SSRC0", "class": "scalar_source"}],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# One source, so two literals cannot occur; the rest are rejected.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
|
||||
"kind": "unary",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -204,18 +296,34 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output")
|
||||
if rule is None:
|
||||
return
|
||||
fields = [(rule["dst"]["field"], False)] + [(src["field"], True) for src in rule["src"]]
|
||||
if not isinstance(rule.get("src"), list) or not all(
|
||||
isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"]
|
||||
) or ("dst" in rule and not (isinstance(rule["dst"], dict) and "field" in rule["dst"])):
|
||||
return # the rule check already reported the malformed shape
|
||||
fields = [(rule["dst"]["field"], False)] if "dst" in rule else []
|
||||
fields += [(src["field"], True) for src in rule["src"]]
|
||||
shift = form["operation"] in SHIFTS and len(rule["src"]) > 1
|
||||
count_field = rule["src"][1]["field"] if shift else None
|
||||
for field, is_source in fields:
|
||||
if field not in operands:
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
if size != form["width"]:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {form['width']}")
|
||||
bits = form.get(SOURCE_BITS_KEY) if is_source else None
|
||||
expected = bits if type(bits) is int else form["width"]
|
||||
if size != expected:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
|
||||
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 type(bits) is int:
|
||||
if data_format != f"FMT_NUM_I{bits}":
|
||||
errors.append(f"{label}: {field} has XML format {data_format}, not FMT_NUM_I{bits}")
|
||||
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
|
||||
)
|
||||
@@ -261,7 +369,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, RELATION_KEY, SOURCE_BITS_KEY})
|
||||
if missing:
|
||||
errors.append(f"{label}: incomplete, missing {missing}")
|
||||
if extra:
|
||||
@@ -294,11 +402,41 @@ 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']}"
|
||||
)
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
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")
|
||||
if form["operation"] == "sext":
|
||||
bits = form.get(SOURCE_BITS_KEY)
|
||||
if type(bits) is not int or bits not in SOURCE_BITS:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} must be one of {sorted(SOURCE_BITS)}, got {bits!r}")
|
||||
elif SOURCE_BITS_KEY in form:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} on a non-sext operation")
|
||||
if form["operation"] == "compare":
|
||||
relation = form.get(RELATION_KEY)
|
||||
if not isinstance(relation, str) or relation not in RELATIONS:
|
||||
errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}")
|
||||
elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES:
|
||||
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
|
||||
if form["scc"] != "relation":
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)")
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = ("relation", None, False)
|
||||
else:
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
if primitive is None:
|
||||
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
|
||||
else:
|
||||
@@ -315,6 +453,11 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
|
||||
elif rule.get("family") != form["family"]:
|
||||
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
|
||||
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
|
||||
"compare" if form["operation"] == "compare"
|
||||
else "unary" if form["operation"] in UNARY else "alu"
|
||||
):
|
||||
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
|
||||
_check_spec(label, form["spec"], documents, errors)
|
||||
verify = form["verify"]
|
||||
if not verify:
|
||||
@@ -360,6 +503,7 @@ def render(registry, snapshot):
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, Wave,",
|
||||
"};",
|
||||
"use crate::CompareRelation;",
|
||||
"",
|
||||
"/// Registry schema of the generated tables.",
|
||||
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
|
||||
@@ -396,6 +540,10 @@ 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" source_bits: {form.get(SOURCE_BITS_KEY, form['width'])},",
|
||||
" relation: "
|
||||
+ (f"Some(CompareRelation::{RELATIONS[form[RELATION_KEY]]})," if RELATION_KEY in form else "None,"),
|
||||
f" scc: SccEffect::{SCC[form['scc']]},",
|
||||
f" vcc: MaskEffect::{MASK[form['vcc']]},",
|
||||
f" exec: MaskEffect::{MASK[form['exec']]},",
|
||||
@@ -411,9 +559,21 @@ def render(registry, snapshot):
|
||||
|
||||
def _render_enum(rule_name, forms, snapshot, positions):
|
||||
enum = OPERAND_RULES[rule_name]["enum"]
|
||||
kind = OPERAND_RULES[rule_name]["kind"]
|
||||
table = re.sub(r"(?<!^)(?=[A-Z])", "_", enum).upper() + "_BY_OPCODE"
|
||||
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}`).",
|
||||
@@ -422,14 +582,26 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
what = f"compare {form[RELATION_KEY]}" if kind == "compare" else form["operation"]
|
||||
out += [
|
||||
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
|
||||
f"{form['signedness']} {form['operation']}{carry}, SCC = {form['scc']}.",
|
||||
f"{form['signedness']} {what}{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 {table}: [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 +610,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" {table}[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
|
||||
" }",
|
||||
"",
|
||||
" /// Lower-case mnemonic.",
|
||||
@@ -457,6 +627,78 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The validated registry row.",
|
||||
" pub fn semantics(self) -> &'static FormSemantics {",
|
||||
" &FORMS[match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
|
||||
out += [
|
||||
" }]",
|
||||
" }",
|
||||
]
|
||||
if kind == "unary":
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation writes SCC.",
|
||||
" pub const fn writes_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
|
||||
" /// unchanged).",
|
||||
" pub const fn evaluate(self, src: u32) -> (u32, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, _ = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if form["operation"] == "sext":
|
||||
value = f"primitive::{function}(src, {form[SOURCE_BITS_KEY]})"
|
||||
else:
|
||||
value = f"primitive::{function}(src)"
|
||||
if form["scc"] == "unchanged":
|
||||
out.append(f" Self::{form['variant']} => ({value}, None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{form['variant']} => {{",
|
||||
f" let (value, scc) = {value};",
|
||||
" (value, Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "compare":
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with S0 on the left.",
|
||||
" pub const fn relation(self) -> CompareRelation {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The new SCC: whether the relation holds for S0 and S1.",
|
||||
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
|
||||
out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation reads SCC as a carry-in or borrow-in.",
|
||||
" pub const fn reads_scc(self) -> bool {",
|
||||
@@ -470,15 +712,6 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The validated registry row.",
|
||||
" pub fn semantics(self) -> &'static FormSemantics {",
|
||||
" &FORMS[match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
|
||||
out += [
|
||||
" }]",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and the new SCC, with `carry_in` the SCC read by forms that",
|
||||
" /// consume it (ignored by the others).",
|
||||
" pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {",
|
||||
@@ -489,6 +722,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},")
|
||||
|
||||
@@ -230,3 +230,648 @@ 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"]
|
||||
|
||||
# ---- Stage D: SOPC 32-bit integer compares (#215) ----
|
||||
# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4).
|
||||
|
||||
[operand_rules.sopc_scalar]
|
||||
family = "SOPC"
|
||||
src = [
|
||||
{ field = "SSRC0", class = "scalar_source" },
|
||||
{ field = "SSRC1", class = "scalar_source" },
|
||||
]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
|
||||
"src_special", "two_literals",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_EQ_I32"
|
||||
family = "SOPC"
|
||||
opcode = 0
|
||||
variant = "CmpEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LG_I32"
|
||||
family = "SOPC"
|
||||
opcode = 1
|
||||
variant = "CmpLgI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GT_I32"
|
||||
family = "SOPC"
|
||||
opcode = 2
|
||||
variant = "CmpGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GE_I32"
|
||||
family = "SOPC"
|
||||
opcode = 3
|
||||
variant = "CmpGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LT_I32"
|
||||
family = "SOPC"
|
||||
opcode = 4
|
||||
variant = "CmpLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LE_I32"
|
||||
family = "SOPC"
|
||||
opcode = 5
|
||||
variant = "CmpLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_EQ_U32"
|
||||
family = "SOPC"
|
||||
opcode = 6
|
||||
variant = "CmpEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LG_U32"
|
||||
family = "SOPC"
|
||||
opcode = 7
|
||||
variant = "CmpLgU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GT_U32"
|
||||
family = "SOPC"
|
||||
opcode = 8
|
||||
variant = "CmpGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GE_U32"
|
||||
family = "SOPC"
|
||||
opcode = 9
|
||||
variant = "CmpGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LT_U32"
|
||||
family = "SOPC"
|
||||
opcode = 10
|
||||
variant = "CmpLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LE_U32"
|
||||
family = "SOPC"
|
||||
opcode = 11
|
||||
variant = "CmpLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- SOP1 32-bit unary integer forms (#215) ----
|
||||
# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged.
|
||||
# Searches that find nothing return -1 (guide 12.3).
|
||||
|
||||
[operand_rules.sop1_sgpr]
|
||||
family = "SOP1"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [{ field = "SSRC0", class = "scalar_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "S_NOT_B32"
|
||||
family = "SOP1"
|
||||
opcode = 7
|
||||
variant = "NotB32"
|
||||
operation = "not"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BREV_B32"
|
||||
family = "SOP1"
|
||||
opcode = 11
|
||||
variant = "BrevB32"
|
||||
operation = "brev"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BCNT0_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 13
|
||||
variant = "Bcnt0I32B32"
|
||||
operation = "bcnt0"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BCNT1_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 15
|
||||
variant = "Bcnt1I32B32"
|
||||
operation = "bcnt1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FF0_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 17
|
||||
variant = "Ff0I32B32"
|
||||
operation = "ff0"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FF1_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 19
|
||||
variant = "Ff1I32B32"
|
||||
operation = "ff1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FLBIT_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 21
|
||||
variant = "FlbitI32B32"
|
||||
operation = "flbit"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FLBIT_I32"
|
||||
family = "SOP1"
|
||||
opcode = 23
|
||||
variant = "FlbitI32"
|
||||
operation = "flbit"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SEXT_I32_I8"
|
||||
family = "SOP1"
|
||||
opcode = 25
|
||||
variant = "SextI32I8"
|
||||
operation = "sext"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_bits = 8
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SEXT_I32_I16"
|
||||
family = "SOP1"
|
||||
opcode = 26
|
||||
variant = "SextI32I16"
|
||||
operation = "sext"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_bits = 16
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ABS_I32"
|
||||
family = "SOP1"
|
||||
opcode = 52
|
||||
variant = "AbsI32"
|
||||
operation = "abs"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+20
-11
@@ -12,13 +12,13 @@ mod rdna2_meta;
|
||||
mod semantics_gen;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::ScalarAluOp;
|
||||
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
@@ -209,6 +209,13 @@ pub enum Instruction {
|
||||
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
|
||||
ScalarMoveB32 { dst: u8, src: ScalarSource },
|
||||
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
|
||||
/// for some operations, SCC.
|
||||
ScalarUnary {
|
||||
op: ScalarUnaryOp,
|
||||
dst: u8,
|
||||
src: ScalarSource,
|
||||
},
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
|
||||
ScalarAlu {
|
||||
op: ScalarAluOp,
|
||||
@@ -216,8 +223,9 @@ pub enum Instruction {
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// SOPC 32-bit equality comparison writing SCC.
|
||||
ScalarCompareEqU32 {
|
||||
/// SOPC 32-bit integer compare writing only SCC.
|
||||
ScalarCompare {
|
||||
op: ScalarCompareOp,
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
@@ -306,8 +314,9 @@ impl Instruction {
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.mnemonic(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
@@ -370,13 +379,13 @@ impl fmt::Display for Instruction {
|
||||
| Self::VectorMulF32 { dst, src0, src1 } => {
|
||||
write!(formatter, " v{dst}, v{src0}, v{src1}")
|
||||
}
|
||||
Self::ScalarMoveB32 { dst, src } => {
|
||||
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
|
||||
write!(formatter, " {}, {src}", ScalarDestination(dst))
|
||||
}
|
||||
Self::ScalarAlu {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
|
||||
@@ -49,3 +49,168 @@ 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)
|
||||
}
|
||||
|
||||
/// `a == b` on the raw bits; signedness does not matter for equality.
|
||||
pub const fn eq_b32(a: u32, b: u32) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// `a != b` on the raw bits (the guide's LG, "less or greater").
|
||||
pub const fn ne_b32(a: u32, b: u32) -> bool {
|
||||
a != b
|
||||
}
|
||||
|
||||
/// Two's-complement `a > b`.
|
||||
pub const fn gt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) > (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a >= b`.
|
||||
pub const fn ge_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) >= (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a < b`.
|
||||
pub const fn lt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) < (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a <= b`.
|
||||
pub const fn le_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) <= (b as i32)
|
||||
}
|
||||
|
||||
/// Unsigned `a > b`.
|
||||
pub const fn gt_u32(a: u32, b: u32) -> bool {
|
||||
a > b
|
||||
}
|
||||
|
||||
/// Unsigned `a >= b`.
|
||||
pub const fn ge_u32(a: u32, b: u32) -> bool {
|
||||
a >= b
|
||||
}
|
||||
|
||||
/// Unsigned `a < b`.
|
||||
pub const fn lt_u32(a: u32, b: u32) -> bool {
|
||||
a < b
|
||||
}
|
||||
|
||||
/// Unsigned `a <= b`.
|
||||
pub const fn le_u32(a: u32, b: u32) -> bool {
|
||||
a <= b
|
||||
}
|
||||
|
||||
/// `!a` and whether the result is nonzero.
|
||||
pub const fn not_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = !a;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a` with bit `i` moved to bit `31 - i`.
|
||||
pub const fn brev_b32(a: u32) -> u32 {
|
||||
a.reverse_bits()
|
||||
}
|
||||
|
||||
/// Number of zero bits and whether that count is nonzero.
|
||||
pub const fn bcnt0_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_zeros();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Number of one bits and whether that count is nonzero.
|
||||
pub const fn bcnt1_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_ones();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Index of the lowest zero bit, or `0xffffffff` (-1) when every bit is one.
|
||||
pub const fn ff0_b32(a: u32) -> u32 {
|
||||
if a == u32::MAX {
|
||||
u32::MAX
|
||||
} else {
|
||||
a.trailing_ones()
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of the lowest one bit, or `0xffffffff` (-1) when every bit is zero.
|
||||
pub const fn ff1_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.trailing_zeros() }
|
||||
}
|
||||
|
||||
/// Zeros above the highest one bit, or `0xffffffff` (-1) when `a` is zero.
|
||||
pub const fn flbit_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.leading_zeros() }
|
||||
}
|
||||
|
||||
/// Bits above the highest bit that differs from the sign bit, or `0xffffffff`
|
||||
/// (-1) when every bit equals the sign bit (`a` is 0 or -1).
|
||||
pub const fn flbit_i32(a: u32) -> u32 {
|
||||
let differing = if a >> 31 == 0 { a } else { !a };
|
||||
if differing == 0 {
|
||||
u32::MAX
|
||||
} else {
|
||||
differing.leading_zeros()
|
||||
}
|
||||
}
|
||||
|
||||
/// The low `bits` of `a` sign-extended to 32 bits; `bits` is 8 or 16.
|
||||
pub const fn sext_i32(a: u32, bits: u32) -> u32 {
|
||||
let shift = 32 - bits;
|
||||
(((a << shift) as i32) >> shift) as u32
|
||||
}
|
||||
|
||||
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
|
||||
let value = (a as i32).wrapping_abs() as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
@@ -45,11 +45,6 @@ pub const S_MOV_B32: Opcode = Opcode {
|
||||
bits: 0xbe800300,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_SCC0: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf840000,
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! The reference interpreter (`crates/ref`) and the independent interpreter
|
||||
//! (`tests/validation/independent_ref.rs`) must not use this module.
|
||||
|
||||
use crate::CompareRelation;
|
||||
use crate::meta::EncodingFamily;
|
||||
|
||||
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
|
||||
@@ -30,6 +31,43 @@ 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,
|
||||
/// Compare S0 with S1 under the form's relation; writes only SCC.
|
||||
Compare,
|
||||
/// Bitwise complement of S0.
|
||||
Not,
|
||||
/// S0 with its bit order reversed.
|
||||
ReverseBits,
|
||||
/// Number of zero bits in S0.
|
||||
CountZeros,
|
||||
/// Number of one bits in S0.
|
||||
CountOnes,
|
||||
/// Index of the lowest zero bit of S0, or -1 when there is none.
|
||||
FindFirstZero,
|
||||
/// Index of the lowest one bit of S0, or -1 when there is none.
|
||||
FindFirstOne,
|
||||
/// Unsigned: count of zeros above the highest one bit; signed: count of bits
|
||||
/// above the highest bit that differs from the sign bit. -1 when none.
|
||||
FindLastBit,
|
||||
/// Sign-extend the low `source_bits` of S0 to 32 bits.
|
||||
SignExtend,
|
||||
/// Two's-complement absolute value; the most negative value maps to itself.
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
@@ -65,6 +103,8 @@ pub enum SccEffect {
|
||||
SignedOverflow,
|
||||
/// The result is not zero.
|
||||
Nonzero,
|
||||
/// The compare's relation holds for S0 and S1.
|
||||
Relation,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
@@ -89,6 +129,12 @@ pub enum OperandRule {
|
||||
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
|
||||
/// or one literal word. Everything else is rejected as unsupported.
|
||||
Sop2Sgpr,
|
||||
/// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline
|
||||
/// integers -16..64 or one literal word). Everything else is rejected.
|
||||
SopcScalar,
|
||||
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
|
||||
/// a literal word. Everything else is rejected as unsupported.
|
||||
Sop1Sgpr,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
@@ -120,7 +166,7 @@ pub struct SpecRef {
|
||||
pub document: Document,
|
||||
/// Section number, for example `"12.1"`.
|
||||
pub section: &'static str,
|
||||
/// Page in the document, 0 when not paginated.
|
||||
/// Page in the document, or 0 when the page has not been recorded.
|
||||
pub page: u16,
|
||||
}
|
||||
|
||||
@@ -141,6 +187,12 @@ 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,
|
||||
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
|
||||
pub source_bits: u8,
|
||||
/// The relation tested by compares (S0 on the left); `None` otherwise.
|
||||
pub relation: Option<CompareRelation>,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
|
||||
+1513
-30
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,8 @@
|
||||
//! Ties the generated semantic registry tables to the independent XML metadata table.
|
||||
|
||||
use xenora_isa::ScalarAluOp;
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
|
||||
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
@@ -18,43 +18,70 @@ fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
assert_eq!(ScalarAluOp::ALL.len(), FORMS.len());
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
}
|
||||
/// Every word of `family` that the XML metadata identifies selects an operation
|
||||
/// exactly when the registry declares that form, and no 32-bit word of another
|
||||
/// family selects one.
|
||||
fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) {
|
||||
let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect();
|
||||
let mut selected = 0;
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family == EncodingFamily::Sop2)
|
||||
{
|
||||
let word = meta.bits as u32;
|
||||
match ScalarAluOp::from_word(word) {
|
||||
Some(op) => {
|
||||
assert_eq!(op.semantics().name, meta.name);
|
||||
for meta in META_FORMS.iter().filter(|form| form.family == family) {
|
||||
match select(meta.bits as u32) {
|
||||
Some(name) => {
|
||||
assert_eq!(name, meta.name);
|
||||
selected += 1;
|
||||
}
|
||||
None => assert!(
|
||||
FORMS.iter().all(|row| row.name != meta.name),
|
||||
declared.iter().all(|row| row.name != meta.name),
|
||||
"{} is declared but not dispatched",
|
||||
meta.name
|
||||
),
|
||||
}
|
||||
}
|
||||
assert_eq!(selected, FORMS.len());
|
||||
// Other encodings never reach the SOP2 dispatch.
|
||||
assert_eq!(selected, declared.len());
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != EncodingFamily::Sop2 && form.bytes == 4)
|
||||
.filter(|form| form.family != family && form.bytes == 4)
|
||||
{
|
||||
assert_eq!(
|
||||
ScalarAluOp::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
assert_eq!(select(meta.bits as u32), None, "{}", meta.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop2);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
|
||||
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
|
||||
for op in ScalarCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopc);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sopc, |word| {
|
||||
ScalarCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
for op in ScalarUnaryOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop1);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
|
||||
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
|
||||
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
+90
-66
@@ -226,57 +226,102 @@ impl GuestMemory {
|
||||
true
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, src.len()) {
|
||||
if !region.permissions.write {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "write",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + src.len()].copy_from_slice(src);
|
||||
return Ok(());
|
||||
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
|
||||
///
|
||||
/// An access may span adjacent regions, as it would span adjacent pages, but every
|
||||
/// byte must be mapped and every region must grant `required` (`None` bypasses
|
||||
/// permission checks for the loader). The whole range is checked before any byte
|
||||
/// is copied, so a failed access never partially reads or writes.
|
||||
fn resolve(
|
||||
&self,
|
||||
address: u64,
|
||||
len: usize,
|
||||
required: Option<&'static str>,
|
||||
) -> Result<Vec<(usize, usize, usize)>, MemoryError> {
|
||||
let end = address
|
||||
.checked_add(len as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if len == 0 {
|
||||
return if self.regions.iter().any(|r| r.contains(address, 0)) {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
};
|
||||
}
|
||||
let mut pieces = Vec::new();
|
||||
let mut cursor = address;
|
||||
for (index, region) in self.regions.iter().enumerate() {
|
||||
let region_end = region.base + region.data.len() as u64;
|
||||
if region_end <= cursor {
|
||||
continue;
|
||||
}
|
||||
if region.base > cursor {
|
||||
break;
|
||||
}
|
||||
let permitted = match required {
|
||||
None => true,
|
||||
Some("read") => region.permissions.read,
|
||||
Some("write") => region.permissions.write,
|
||||
Some(_) => region.permissions.execute,
|
||||
};
|
||||
if let (false, Some(required)) = (permitted, required) {
|
||||
return Err(MemoryError::PermissionViolation { address, required });
|
||||
}
|
||||
let take = (end.min(region_end) - cursor) as usize;
|
||||
pieces.push((index, (cursor - region.base) as usize, take));
|
||||
cursor += take as u64;
|
||||
if cursor == end {
|
||||
return Ok(pieces);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
}
|
||||
|
||||
fn read_checked(
|
||||
&self,
|
||||
address: u64,
|
||||
dst: &mut [u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, dst.len(), required)? {
|
||||
dst[done..done + take]
|
||||
.copy_from_slice(&self.regions[index].data[offset..offset + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_checked(
|
||||
&mut self,
|
||||
address: u64,
|
||||
src: &[u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, src.len(), required)? {
|
||||
self.regions[index].data[offset..offset + take]
|
||||
.copy_from_slice(&src[done..done + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
self.write_checked(address, src, Some("write"))
|
||||
}
|
||||
|
||||
/// Read raw bytes from guest memory at the specified address, checking permissions.
|
||||
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, dst.len()) {
|
||||
if !region.permissions.read {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "read",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
dst.copy_from_slice(®ion.data[offset..offset + dst.len()]);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.read_checked(address, dst, Some("read"))
|
||||
}
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 1) {
|
||||
if !region.permissions.execute {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
return Ok(region.data[offset]);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 1];
|
||||
self.read_checked(address, &mut buf, Some("execute"))?;
|
||||
Ok(buf[0])
|
||||
}
|
||||
|
||||
/// Read a 64-bit integer (little endian) from guest memory.
|
||||
@@ -288,14 +333,9 @@ impl GuestMemory {
|
||||
|
||||
/// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase).
|
||||
pub fn read_u64_bypass(&self, address: u64) -> Result<u64, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
let buf: [u8; 8] = region.data[offset..offset + 8].try_into().unwrap();
|
||||
return Ok(u64::from_le_bytes(buf));
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 8];
|
||||
self.read_checked(address, &mut buf, None)?;
|
||||
Ok(u64::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Write a 64-bit integer (little endian) to guest memory.
|
||||
@@ -305,15 +345,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 8].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a 32-bit integer (little endian) from guest memory.
|
||||
@@ -330,15 +362,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 4) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 4].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a single byte from guest memory.
|
||||
|
||||
+18
-1
@@ -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]])
|
||||
@@ -170,7 +173,10 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
|
||||
for sec_bytes in bytes[section_table_offset..table_end].chunks_exact(SECTION_HEADER_SIZE) {
|
||||
for sec_bytes in bytes[section_table_offset..table_end]
|
||||
.as_chunks::<SECTION_HEADER_SIZE>()
|
||||
.0
|
||||
{
|
||||
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
|
||||
let name_raw = &sec_bytes[0..8];
|
||||
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
|
||||
@@ -270,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 {
|
||||
|
||||
@@ -117,7 +117,10 @@ pub fn apply_relocations(
|
||||
size: reloc_size,
|
||||
})?;
|
||||
|
||||
if reloc_file_offset + (reloc_size as usize) > bytes.len() {
|
||||
if reloc_file_offset
|
||||
.checked_add(reloc_size as usize)
|
||||
.is_none_or(|end| end > bytes.len())
|
||||
{
|
||||
return Err(RelocationError::DirectoryOutOfBounds {
|
||||
rva: reloc_rva,
|
||||
size: reloc_size,
|
||||
@@ -127,13 +130,20 @@ pub fn apply_relocations(
|
||||
let mut read_bytes = 0usize;
|
||||
let max_read = reloc_size as usize;
|
||||
|
||||
while read_bytes + 8 <= max_read {
|
||||
while read_bytes < max_read {
|
||||
// A partial block header after the last block is malformed, not padding.
|
||||
if max_read - read_bytes < 8 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: reloc_file_offset + read_bytes,
|
||||
});
|
||||
}
|
||||
let block_start = reloc_file_offset + read_bytes;
|
||||
let page_rva = u32::from_le_bytes(bytes[block_start..block_start + 4].try_into().unwrap());
|
||||
let block_size =
|
||||
u32::from_le_bytes(bytes[block_start + 4..block_start + 8].try_into().unwrap());
|
||||
|
||||
if block_size < 8 {
|
||||
// A block is an 8-byte header followed by whole 2-byte entries.
|
||||
if block_size < 8 || block_size % 2 != 0 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: block_start,
|
||||
});
|
||||
@@ -166,6 +176,15 @@ pub fn apply_relocations(
|
||||
let target_rva = page_rva
|
||||
.checked_add(offset_in_page)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
// The 8-byte target must lie inside the image, not in other mapped memory.
|
||||
if target_rva
|
||||
.checked_add(8)
|
||||
.is_none_or(|end| end > pe.size_of_image)
|
||||
{
|
||||
return Err(RelocationError::TargetOutOfBounds {
|
||||
target_va: loaded_base.wrapping_add(u64::from(target_rva)),
|
||||
});
|
||||
}
|
||||
let target_va = loaded_base
|
||||
.checked_add(target_rva as u64)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
@@ -213,8 +232,8 @@ fn find_reloc_directory(
|
||||
return Ok(None);
|
||||
}
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let opt_offset = e_lfanew + 24;
|
||||
let coff_offset = e_lfanew + 4;
|
||||
let opt_offset = coff_offset + 20;
|
||||
if bytes.len() < coff_offset + 18 {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -224,10 +243,19 @@ fn find_reloc_directory(
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
|
||||
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header)
|
||||
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header).
|
||||
// It exists only when NumberOfRvaAndSizes (offset 108) covers index 5.
|
||||
if size_of_opt < 160 || bytes.len() < opt_offset + 160 {
|
||||
return Ok(None);
|
||||
}
|
||||
let number_of_rva_and_sizes = u32::from_le_bytes(
|
||||
bytes[opt_offset + 108..opt_offset + 112]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
if number_of_rva_and_sizes < 6 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let reloc_rva = u32::from_le_bytes(
|
||||
bytes[opt_offset + 152..opt_offset + 156]
|
||||
|
||||
+136
-16
@@ -11,6 +11,14 @@ use crate::{
|
||||
|
||||
const STACK_SIZE: usize = 64 * 1024;
|
||||
const JIT_CAPACITY: usize = 1024 * 1024;
|
||||
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
|
||||
const TEB_OFFSET: u64 = 0x10000;
|
||||
const TEB_SIZE: usize = 0x2000;
|
||||
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
|
||||
const TEB_STACK_BASE: u64 = 0x08;
|
||||
const TEB_STACK_LIMIT: u64 = 0x10;
|
||||
const TEB_SELF: u64 = 0x30;
|
||||
const TEB_TLS_POINTER: u64 = 0x58;
|
||||
|
||||
/// Guest addresses reserved by the fixture harness.
|
||||
pub struct StartupLayout {
|
||||
@@ -79,6 +87,8 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)
|
||||
.into());
|
||||
}
|
||||
// Reject an impossible layout before parsing or mapping anything.
|
||||
let (stack_base, teb_base) = layout_regions(&layout)?;
|
||||
let pe = ParsedPe::parse(bytes)?;
|
||||
observe(StartupEvent::Parsed {
|
||||
sections: pe.sections.len(),
|
||||
@@ -112,24 +122,9 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)?;
|
||||
}
|
||||
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
|
||||
// Allocate and initialize Win64 TEB (Thread Environment Block)
|
||||
// Layout in TEB:
|
||||
// +0x08: StackBase (highest address)
|
||||
// +0x10: StackLimit (lowest address)
|
||||
// +0x30: Self pointer (TEB linear address)
|
||||
// +0x58: ThreadLocalStoragePointer
|
||||
let teb_base = layout.tls_base.saturating_add(0x10000);
|
||||
memory.map_region(teb_base, 0x2000, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + 0x08, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + 0x10, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x30, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x58, layout.tls_base)?;
|
||||
map_teb(memory, teb_base, &layout, stack_base)?;
|
||||
|
||||
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
|
||||
engine.set_import_registry(imports);
|
||||
@@ -171,3 +166,128 @@ pub fn run_synthetic_startup_with_observer(
|
||||
dbt_metrics: engine.metrics,
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate the harness layout and return `(stack_base, teb_base)`.
|
||||
///
|
||||
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
|
||||
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
|
||||
/// space and must not overlap each other.
|
||||
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_base = layout
|
||||
.tls_base
|
||||
.checked_add(TEB_OFFSET)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_end = teb_base
|
||||
.checked_add(TEB_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if teb_base < layout.stack_top && stack_base < teb_end {
|
||||
return Err(MemoryError::OverlappingRegion {
|
||||
base: teb_base,
|
||||
size: TEB_SIZE as u64,
|
||||
});
|
||||
}
|
||||
Ok((stack_base, teb_base))
|
||||
}
|
||||
|
||||
/// Map the Win64 TEB and write the fields the harness provides.
|
||||
fn map_teb(
|
||||
memory: &mut crate::GuestMemory,
|
||||
teb_base: u64,
|
||||
layout: &StartupLayout,
|
||||
stack_base: u64,
|
||||
) -> Result<(), MemoryError> {
|
||||
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::GuestMemory;
|
||||
|
||||
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top,
|
||||
tls_base,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_layout_places_stack_and_teb() {
|
||||
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
|
||||
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_below_zero_is_rejected() {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x8000, 0x3_0000_0000)),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_address_overflow_is_rejected_not_saturated() {
|
||||
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x2_0001_0000, tls_base)),
|
||||
Err(MemoryError::Overflow),
|
||||
"tls_base {tls_base:#x}"
|
||||
);
|
||||
}
|
||||
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
|
||||
// representable, and GuestMemory could not map that range either.
|
||||
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_overlapping_stack_is_rejected() {
|
||||
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
|
||||
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
|
||||
assert!(matches!(
|
||||
layout_regions(&collide),
|
||||
Err(MemoryError::OverlappingRegion { .. })
|
||||
));
|
||||
// Directly above the stack is fine.
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_layout_fails_before_parsing() {
|
||||
// Empty bytes would fail PE parsing; the layout error must come first.
|
||||
let err = run_synthetic_startup(
|
||||
&[],
|
||||
layout(0x2_0001_0000, u64::MAX),
|
||||
ImportRegistry::new(),
|
||||
1,
|
||||
)
|
||||
.err()
|
||||
.expect("startup must fail");
|
||||
assert_eq!(
|
||||
err.downcast_ref::<MemoryError>(),
|
||||
Some(&MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_fields_are_at_win64_offsets() {
|
||||
let l = layout(0x2_0001_0000, 0x3_0000_0000);
|
||||
let (stack_base, teb) = layout_regions(&l).unwrap();
|
||||
let mut memory = GuestMemory::new();
|
||||
map_teb(&mut memory, teb, &l, stack_base).unwrap();
|
||||
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
|
||||
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
|
||||
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest memory boundary regression tests (#82).
|
||||
//!
|
||||
//! Expected behavior follows x86-64 data access rules: an access is valid when
|
||||
//! every byte it touches is mapped with the required permission, whether or not
|
||||
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
|
||||
//! nothing.
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
const A: u64 = 0x10_0000;
|
||||
|
||||
fn two_regions(first: P, second: P) -> GuestMemory {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, first, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region_with_data(A + 0x1000, 0x1000, second, &[0x22; 0x1000])
|
||||
.unwrap();
|
||||
m
|
||||
}
|
||||
|
||||
fn bypass_bytes(m: &GuestMemory, at: u64) -> u64 {
|
||||
m.read_u64_bypass(at).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_are_enforced_per_access_kind() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::NO_ACCESS).unwrap();
|
||||
m.map_region(A + 0x1000, 0x1000, P::READ_ONLY).unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
let violation = |address, required| MemoryError::PermissionViolation { address, required };
|
||||
assert_eq!(m.read_u8(A), Err(violation(A, "read")));
|
||||
assert_eq!(
|
||||
m.write_u8(A + 0x1000, 1),
|
||||
Err(violation(A + 0x1000, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(A + 0x2000),
|
||||
Err(violation(A + 0x2000, "execute"))
|
||||
);
|
||||
assert!(m.read_u8(A + 0x1000).is_ok());
|
||||
assert!(m.write_u8(A + 0x2000, 1).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_end_is_exclusive() {
|
||||
let m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
assert!(m.read_u32(A + 0xFFC).is_ok());
|
||||
assert!(matches!(
|
||||
m.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::PermissionViolation { .. })
|
||||
));
|
||||
let mut lone = GuestMemory::new();
|
||||
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
|
||||
assert_eq!(
|
||||
lone.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFD))
|
||||
);
|
||||
assert_eq!(
|
||||
lone.read_u8(A - 1),
|
||||
Err(MemoryError::UnmappedAddress(A - 1))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unaligned_accesses_succeed_inside_a_region() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 3, 0x0102_0304_0506_0708).unwrap();
|
||||
assert_eq!(m.read_u64(A + 3), Ok(0x0102_0304_0506_0708));
|
||||
assert_eq!(m.read_u16(A + 3), Ok(0x0708));
|
||||
assert_eq!(m.read_u32(A + 5), Ok(0x0304_0506));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn access_spanning_adjacent_permitted_regions_succeeds() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 0xFFC, 0x8877_6655_4433_2211).unwrap();
|
||||
assert_eq!(m.read_u64(A + 0xFFC), Ok(0x8877_6655_4433_2211));
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x4433_2211)); // low half in the first region
|
||||
assert_eq!(m.read_u32(A + 0x1000), Ok(0x8877_6655)); // high half in the second
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_gap_fails_without_partial_write() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, P::READ_WRITE, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFC))
|
||||
);
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_forbidden_region_fails_atomically() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_ONLY);
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 0xFFC,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
assert_eq!(bypass_bytes(&m, A + 0xFFC), 0x2222_2222_1111_1111);
|
||||
|
||||
let m = two_regions(P::READ_EXECUTE, P::READ_WRITE);
|
||||
assert!(m.read_u64(A + 0xFFC).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0xFFF).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0x1000).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_bypass_ignores_permissions_but_not_mapping() {
|
||||
let mut m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
m.write_u64_bypass(A + 0xFFC, 0x0A0B_0C0D_0E0F_1011)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64_bypass(A + 0xFFC), Ok(0x0A0B_0C0D_0E0F_1011));
|
||||
m.write_u32_bypass(A, 7).unwrap();
|
||||
assert_eq!(m.read_u32(A), Ok(7));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(A + 0x1FFC, 0),
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address_overflow_is_reported() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX - 0xFFF, 0xFFF, P::READ_WRITE)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64(u64::MAX - 3), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(u64::MAX - 3, 0),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
m.map_region(u64::MAX, 2, P::READ_WRITE),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_mappings_are_rejected_and_adjacent_ones_accepted() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.map_region(A + 0xFFF, 0x10, P::READ_WRITE),
|
||||
Err(MemoryError::OverlappingRegion {
|
||||
base: A + 0xFFF,
|
||||
size: 0x10
|
||||
})
|
||||
);
|
||||
assert!(m.map_region(A + 0x1000, 0x10, P::READ_WRITE).is_ok());
|
||||
assert!(m.map_region(A - 0x10, 0x10, P::READ_WRITE).is_ok());
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Base relocation regression tests (#81).
|
||||
//!
|
||||
//! Images are built byte by byte from the PE/COFF layout: data directory 5
|
||||
//! (Base Relocation Table) at optional-header offset 152, and blocks made of a
|
||||
//! 4-byte page RVA, a 4-byte block size and 2-byte entries whose top 4 bits
|
||||
//! are the type (0 = ABSOLUTE padding, 3 = HIGHLOW, 10 = DIR64).
|
||||
|
||||
use xenora_loader::{GuestMemory, ParsedPe, RelocationError, apply_relocations};
|
||||
|
||||
const PREFERRED: u64 = 0x1_4000_0000;
|
||||
const RELOC_FILE: usize = 0x400;
|
||||
|
||||
/// .text at RVA 0x1000 (file 0x200) holding two pointers, .reloc at RVA 0x2000 (file 0x400).
|
||||
/// `NumberOfRvaAndSizes` and the relocation table bytes are parameters.
|
||||
fn build(rva_and_sizes: u32, table: &[u8], dir_size: u32) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x600];
|
||||
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(&2u16.to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&240u16.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(&PREFERRED.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&rva_and_sizes.to_le_bytes());
|
||||
pe[opt + 152..opt + 156].copy_from_slice(&0x2000u32.to_le_bytes());
|
||||
pe[opt + 156..opt + 160].copy_from_slice(&dir_size.to_le_bytes());
|
||||
|
||||
let sections: [(&[u8], u32, u32, u32, u32); 2] = [
|
||||
(b".text", 0x1000, 0x200, 0x200, 0x6000_0020),
|
||||
// .reloc fills the image up to SizeOfImage (0x3000).
|
||||
(b".reloc", 0x2000, 0x1000, RELOC_FILE as u32, 0x4200_0040),
|
||||
];
|
||||
for (i, (name, va, vsize, raw, flags)) in sections.into_iter().enumerate() {
|
||||
let h = opt + 240 + i * 40;
|
||||
pe[h..h + name.len()].copy_from_slice(name);
|
||||
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(&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());
|
||||
}
|
||||
|
||||
// Two absolute pointers into the image, at RVAs 0x1010 and 0x1018.
|
||||
pe[0x210..0x218].copy_from_slice(&(PREFERRED + 0x1100).to_le_bytes());
|
||||
pe[0x218..0x220].copy_from_slice(&(PREFERRED + 0x2000).to_le_bytes());
|
||||
pe[RELOC_FILE..RELOC_FILE + table.len()].copy_from_slice(table);
|
||||
pe
|
||||
}
|
||||
|
||||
fn block(page_rva: u32, entries: &[u16]) -> Vec<u8> {
|
||||
let mut b = page_rva.to_le_bytes().to_vec();
|
||||
b.extend_from_slice(&(8 + 2 * entries.len() as u32).to_le_bytes());
|
||||
for e in entries {
|
||||
b.extend_from_slice(&e.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// DIR64 at 0x1010 and 0x1018, plus one ABSOLUTE padding entry to keep 4-byte alignment.
|
||||
fn standard_table() -> Vec<u8> {
|
||||
block(0x1000, &[0xA010, 0xA018, 0x0000])
|
||||
}
|
||||
|
||||
fn load(bytes: &[u8], base: u64) -> (ParsedPe, GuestMemory) {
|
||||
let pe = ParsedPe::parse(bytes).expect("parse");
|
||||
let mut memory = GuestMemory::new();
|
||||
for s in &pe.sections {
|
||||
let raw = &bytes[s.raw_data_ptr as usize..(s.raw_data_ptr + s.raw_data_size) as usize];
|
||||
memory
|
||||
.map_region_with_data(
|
||||
base + u64::from(s.virtual_address),
|
||||
0x200,
|
||||
s.permissions,
|
||||
raw,
|
||||
)
|
||||
.expect("map");
|
||||
}
|
||||
(pe, memory)
|
||||
}
|
||||
|
||||
fn relocate(
|
||||
bytes: &[u8],
|
||||
base: u64,
|
||||
) -> (
|
||||
Result<xenora_loader::RelocationReport, RelocationError>,
|
||||
GuestMemory,
|
||||
) {
|
||||
let (pe, mut memory) = load(bytes, base);
|
||||
let result = apply_relocations(&pe, bytes, base, &mut memory);
|
||||
(result, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_rebase_adds_delta_to_each_dir64_target() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
let report = result.expect("relocate");
|
||||
assert_eq!(report.delta, 0x1_0000_0000);
|
||||
assert_eq!(report.applied_dir64, 2);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.total_entries, 3);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_rebase_subtracts_delta() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = 0x1000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.expect("relocate").delta,
|
||||
base as i64 - PREFERRED as i64
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_base_leaves_targets_unchanged() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, memory) = relocate(&bytes, PREFERRED);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(PREFERRED + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_beyond_declared_count_is_ignored() {
|
||||
// NumberOfRvaAndSizes = 5 means directory index 5 does not exist.
|
||||
let table = standard_table();
|
||||
let bytes = build(5, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_type_is_rejected() {
|
||||
let table = block(0x1000, &[0x3010, 0x0000]); // HIGHLOW is not a PE32+ fixup here
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::UnsupportedRelocationType(3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_block_sizes_are_rejected() {
|
||||
let base = PREFERRED + 0x1000;
|
||||
for size in [0u32, 4, 7, 11] {
|
||||
let mut table = 0x1000u32.to_le_bytes().to_vec();
|
||||
table.extend_from_slice(&size.to_le_bytes());
|
||||
table.extend_from_slice(&[0; 8]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader { offset: RELOC_FILE },
|
||||
"block size {size}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_larger_than_directory_is_rejected() {
|
||||
let table = standard_table(); // 14 bytes
|
||||
let bytes = build(16, &table, 12);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::BlockSizeOutOfBounds {
|
||||
block_size: 14,
|
||||
max_size: 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_partial_block_header_is_rejected() {
|
||||
let mut table = block(0x1000, &[0xA010, 0x0000]);
|
||||
table.extend_from_slice(&[0; 4]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader {
|
||||
offset: RELOC_FILE + 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_past_end_of_file_is_rejected() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, 0x300); // .reloc raw data starts at 0x400 in a 0x600-byte file
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::DirectoryOutOfBounds {
|
||||
rva: 0x2000,
|
||||
size: 0x300
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_outside_image_is_rejected_even_if_mapped() {
|
||||
// SizeOfImage is 0x3000; RVA 0x3000 is past the image but mapped by another region.
|
||||
let table = block(0x3000, &[0xA000, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1000;
|
||||
let (pe, mut memory) = load(&bytes, base);
|
||||
let rw = pe.sections[1].permissions;
|
||||
memory
|
||||
.map_region(base + 0x3000, 0x1000, rw)
|
||||
.expect("adjacent mapping");
|
||||
memory.write_u64_bypass(base + 0x3000, 0x55).unwrap();
|
||||
let result = apply_relocations(&pe, &bytes, base, &mut memory);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::TargetOutOfBounds {
|
||||
target_va: base + 0x3000
|
||||
}
|
||||
);
|
||||
assert_eq!(memory.read_u64_bypass(base + 0x3000).unwrap(), 0x55);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_rva_at_top_of_address_space_is_rejected() {
|
||||
let table = block(0xFFFF_F000, &[0xAFFC, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RelocationError::TargetOutOfBounds { .. })
|
||||
));
|
||||
}
|
||||
+159
-5
@@ -51,13 +51,19 @@ pub enum Op {
|
||||
Move(u8, Source),
|
||||
Add(u8, u8, u8),
|
||||
ScalarMove(u8, Source),
|
||||
/// SOP1 unary operation writing an SGPR (s0-s105), and SCC for some.
|
||||
ScalarUnary(ScalarUnary, u8, Source),
|
||||
/// VOP1 move of a normal SGPR or `vcc_lo` (106) into a VGPR.
|
||||
MoveScalar(u8, u8),
|
||||
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
|
||||
Compare(Comparison, CompareSource, u8),
|
||||
/// SOP2 operation writing an SGPR and SCC.
|
||||
Scalar(ScalarAlu, u8, Source, Source),
|
||||
/// SOPC `s_cmp_eq_{i32,u32}` (opcodes 0 and 6, identical per guide 12.4).
|
||||
CompareEqual(Source, Source),
|
||||
/// The other SOPC 32-bit integer compares (opcodes 1-5 and 7-11), writing
|
||||
/// only SCC: LG, GT, GE, LT, LE, signed for 1-5, unsigned for 7-11.
|
||||
ScalarCompare(Comparison, Source, Source),
|
||||
Branch {
|
||||
target: usize,
|
||||
condition: BranchCondition,
|
||||
@@ -129,7 +135,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 +148,50 @@ 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,
|
||||
}
|
||||
|
||||
/// SOP1 unary operations decoded by the reference interpreter (RDNA 2 ISA
|
||||
/// guide 12.3; SCC per Tables 12 and 14).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarUnary {
|
||||
/// D = ~S0, SCC = (D != 0).
|
||||
Not,
|
||||
/// D[31:0] = S0[0:31].
|
||||
ReverseBits,
|
||||
/// D = number of zero bits, SCC = (D != 0).
|
||||
CountZeros,
|
||||
/// D = number of one bits, SCC = (D != 0).
|
||||
CountOnes,
|
||||
/// D = index of the lowest zero bit, or -1.
|
||||
FindFirstZero,
|
||||
/// D = index of the lowest one bit, or -1.
|
||||
FindFirstOne,
|
||||
/// D = number of zeros above the highest one bit, or -1 for 0.
|
||||
FindLastBit,
|
||||
/// D = number of leading bits equal to the sign bit, or -1 for 0 and -1.
|
||||
FindLastSignBit,
|
||||
/// D = signext(S0[7:0]).
|
||||
SignExtendByte,
|
||||
/// D = signext(S0[15:0]).
|
||||
SignExtendShort,
|
||||
/// D = |S0| (0x80000000 stays), SCC = (D != 0).
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// VOP2 operations decoded by the reference interpreter.
|
||||
@@ -277,17 +327,55 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
let (source, length) = decode_scalar(*source, tail, offset)?;
|
||||
(Op::ScalarMove(destination & 0x7f, source), length)
|
||||
}
|
||||
[left, right, 6, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
|
||||
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST in 16-22 (s0-s105
|
||||
// only), OP in 8-15.
|
||||
[
|
||||
source,
|
||||
op @ (7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52),
|
||||
destination @ 0x80..=0xe9,
|
||||
0xbe,
|
||||
tail @ ..,
|
||||
] => {
|
||||
let kind = match op {
|
||||
7 => ScalarUnary::Not,
|
||||
11 => ScalarUnary::ReverseBits,
|
||||
13 => ScalarUnary::CountZeros,
|
||||
15 => ScalarUnary::CountOnes,
|
||||
17 => ScalarUnary::FindFirstZero,
|
||||
19 => ScalarUnary::FindFirstOne,
|
||||
21 => ScalarUnary::FindLastBit,
|
||||
23 => ScalarUnary::FindLastSignBit,
|
||||
25 => ScalarUnary::SignExtendByte,
|
||||
26 => ScalarUnary::SignExtendShort,
|
||||
_ => ScalarUnary::Absolute,
|
||||
};
|
||||
let (source, length) = decode_scalar(*source, tail, offset)?;
|
||||
(Op::ScalarUnary(kind, destination & 0x7f, source), length)
|
||||
}
|
||||
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22 (guide
|
||||
// 13.1.4); 0-5 signed and 6-11 unsigned EQ, LG, GT, GE, LT, LE.
|
||||
[left, right, op @ 0..=11, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
|
||||
let (left, left_length) = decode_scalar(*left, tail, offset)?;
|
||||
let (right, right_length) = decode_scalar(*right, tail, offset)?;
|
||||
(Op::CompareEqual(left, right), left_length.max(right_length))
|
||||
// VOPC relation offsets: LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6.
|
||||
let relation = [2, 5, 4, 6, 1, 3][usize::from(op % 6)];
|
||||
let comparison = Comparison {
|
||||
offset: relation,
|
||||
signed: *op < 6,
|
||||
};
|
||||
let op = if relation == 2 {
|
||||
Op::CompareEqual(left, right)
|
||||
} else {
|
||||
Op::ScalarCompare(comparison, left, right)
|
||||
};
|
||||
(op, left_length.max(right_length))
|
||||
}
|
||||
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
|
||||
[
|
||||
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 +390,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)?;
|
||||
@@ -652,9 +749,51 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
}
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
}
|
||||
Op::ScalarUnary(kind, dst, src) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
}
|
||||
let value = read_scalar(src)?;
|
||||
// -1 (all ones) when no bit is found.
|
||||
let found = |index: u32| if index == 32 { u32::MAX } else { index };
|
||||
let result = match kind {
|
||||
ScalarUnary::Not => !value,
|
||||
ScalarUnary::ReverseBits => value.reverse_bits(),
|
||||
ScalarUnary::CountZeros => value.count_zeros(),
|
||||
ScalarUnary::CountOnes => value.count_ones(),
|
||||
ScalarUnary::FindFirstZero => found(value.trailing_ones()),
|
||||
ScalarUnary::FindFirstOne => found(value.trailing_zeros()),
|
||||
ScalarUnary::FindLastBit => found(value.leading_zeros()),
|
||||
ScalarUnary::FindLastSignBit => {
|
||||
let same = if value >> 31 == 1 {
|
||||
value.leading_ones()
|
||||
} else {
|
||||
value.leading_zeros()
|
||||
};
|
||||
found(same)
|
||||
}
|
||||
ScalarUnary::SignExtendByte => value as u8 as i8 as i32 as u32,
|
||||
ScalarUnary::SignExtendShort => value as u16 as i16 as i32 as u32,
|
||||
ScalarUnary::Absolute => (value as i32).wrapping_abs() as u32,
|
||||
};
|
||||
scalars[usize::from(dst)] = Some(result);
|
||||
if matches!(
|
||||
kind,
|
||||
ScalarUnary::Not
|
||||
| ScalarUnary::CountZeros
|
||||
| ScalarUnary::CountOnes
|
||||
| ScalarUnary::Absolute
|
||||
) {
|
||||
scc = Some(result != 0);
|
||||
}
|
||||
}
|
||||
Op::CompareEqual(lhs, rhs) => {
|
||||
scc = Some(read_scalar(lhs)? == read_scalar(rhs)?);
|
||||
}
|
||||
// Guide 12.4: SCC = (S0 <relation> S1); no SGPR is written.
|
||||
Op::ScalarCompare(comparison, lhs, rhs) => {
|
||||
scc = Some(comparison.holds(read_scalar(lhs)?, read_scalar(rhs)?));
|
||||
}
|
||||
Op::Scalar(kind, dst, lhs, rhs) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
@@ -694,6 +833,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);
|
||||
|
||||
@@ -809,6 +809,21 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
*slot = Some(value);
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarUnary { op, dst, src } => {
|
||||
let src = read_scalar(src)?;
|
||||
if dst < 8 {
|
||||
return Err(error("scalar unary would modify a resource descriptor"));
|
||||
}
|
||||
let (value, flag) = op.evaluate(src);
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
@@ -832,8 +847,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
scc = Some(flag);
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
scc = Some(read_scalar(src0)? == read_scalar(src1)?);
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?));
|
||||
continue;
|
||||
}
|
||||
// docs/shaders/vector-compare.md sections 3 and 5.
|
||||
|
||||
@@ -280,6 +280,48 @@ 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 scalar_compare_results_resolve_every_branch() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-compare.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-compare.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-compare.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-unary.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-unary.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
|
||||
<title id="title">Xenora · recorded progress</title>
|
||||
<desc id="description">Decoded gfx1030 forms: 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: 72 of 72. Accepted Metal forms · Apple M5: 18 of 72. 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">72 / 72</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 / 72</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="122.50" 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 |
@@ -21,7 +21,29 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
|
||||
| `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
|
||||
| `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified |
|
||||
| `s_not_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0 | `BE890708` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_brev_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged | `BE8A0B08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bcnt0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0 | `BE8C0D08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bcnt1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0 | `BE8B0F08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ff0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged | `BE8E11FF 0000FFFF` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ff1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged | `BE8D13FF 00400000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_flbit_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged | `BE8F1508` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_flbit_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged | `BE9017FF FFF00000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sext_i32_i8` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged | `BE911908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sext_i32_i16` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged | `BE921AFF 00018000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_abs_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = \|S0\| (0x80000000 stays); SCC = D != 0 | `BE933412` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified |
|
||||
| `s_cmp_eq_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed) | `BF00C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lg_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed) | `BF010908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_gt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed) | `BF020908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_ge_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed) | `BF030909` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed) | `BF040908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_le_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed) | `BF050809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lg_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned) | `BF07FF0A 89ABCDEF` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_gt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned) | `BF080908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_ge_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned) | `BF090809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned) | `BF0A0809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_le_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned) | `BF0BC009` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out | `80088308` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sub_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow | `808A8180` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_add_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow | `8110C109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -31,6 +53,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 |
|
||||
|
||||
@@ -8,8 +8,9 @@
|
||||
| SOPP `S_WAITCNT`, SOPK `S_WAITCNT_VSCNT` | A zero vector-load or vector-store threshold completes the associated transfer. The model permits one pending operation per counter (CLAIM-RDNA2-TRANSFER-WAITS). |
|
||||
| VOP1 `V_MOV_B32` | Read a register, inline integer or literal. Copy all 32 bits. |
|
||||
| VOP3 `V_ADD_NC_U32` | Read two vector registers and add modulo 2^32. No implicit carry or flag update. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_EQ_U32` | Copy 32 bits into a scalar register or compare two operands and set SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32` | Exact integer result reduced modulo 2^32; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero bitwise result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| SOP1 `S_NOT_B32`, `S_BREV_B32`, `S_BCNT{0,1}_I32_B32`, `S_FF{0,1}_I32_B32`, `S_FLBIT_I32_B32`, `S_FLBIT_I32`, `S_SEXT_I32_I{8,16}`, `S_ABS_I32` | The guide's section 12.3 result; a search that finds nothing gives -1, and `S_ABS_I32` of 0x80000000 is 0x80000000. Only NOT, BCNT0, BCNT1 and ABS write SCC (= D != 0). Descriptor SGPRs are reserved. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_{EQ,LG,GT,GE,LT,LE}_{I32,U32}` | Copy 32 bits into a scalar register, or compare SSRC0 with SSRC1 (signed for `_I32` ordering, unsigned for `_U32`; EQ and LG on the raw bits) and set only SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32`, `S_ANDN2_B32`, `S_ORN2_B32`, `S_NAND_B32`, `S_NOR_B32`, `S_XNOR_B32`, `S_LSHL_B32`, `S_LSHR_B32`, `S_ASHR_I32` | Exact integer result reduced modulo 2^32; shifts use S1[4:0]; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero logical or shift result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). |
|
||||
| SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. |
|
||||
| VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. |
|
||||
|
||||
@@ -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
|
||||
@@ -65,7 +78,7 @@ the registry.
|
||||
## How it runs
|
||||
|
||||
Scalar state in a compute fixture is wave-uniform and known while the code is
|
||||
translated. As with `s_mov_b32` and `s_cmp_eq_u32`, the translator evaluates
|
||||
translated. As with `s_mov_b32` and the SOPC compares, the translator evaluates
|
||||
SOP2 forms itself. It resolves SCC-dependent branches and emits SGPR values
|
||||
read by `v_mov_b32_e32` as constants (`fixtures/golden/scalar-alu.ir`). So the
|
||||
IR and MSL contain the results, not scalar instructions.
|
||||
@@ -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,7 +107,55 @@ 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
|
||||
Apple M5 Pro; independent acceptance is pending.
|
||||
|
||||
## SOPC compares
|
||||
|
||||
The twelve 32-bit SOPC integer compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`
|
||||
are declared in the same registry (operand rule `sopc_scalar`). Each sets only
|
||||
SCC, to whether the relation holds with SSRC0 on the left; LG means not equal.
|
||||
EQ and LG give the same result for `_i32` and `_u32`; GT, GE, LT and LE compare
|
||||
two's-complement values for `_i32` and unsigned values for `_u32` (guide section
|
||||
12.4). Sources follow the SOP2 rule: normal SGPRs, inline integers or one
|
||||
literal. Both sources selecting the literal encoding (255) is rejected for SOPC
|
||||
as for SOP2; whether the guide allows one shared literal there was not settled.
|
||||
|
||||
`tests/validation/tests/sopc_stage_d.rs` checks 7,824 cases, with expected
|
||||
values derived from the guide separately from the registry, on both CPU
|
||||
interpreters and, through the translator, on native Metal (compiled per case
|
||||
and read back from nine distinct generated kernels). Its 348 rejected programs
|
||||
are checked on both CPU interpreters and against the compiler, which rejects
|
||||
them before any Metal dispatch. `fixtures/rdna2/scalar-compare.s` (LLVM-assembled, expected input ^
|
||||
0x00000d5b) records every compare's SCC through an `s_cbranch_scc0` per form.
|
||||
|
||||
## SOP1 unary forms
|
||||
|
||||
Eleven 32-bit SOP1 forms are declared in the registry (operand rule
|
||||
`sop1_sgpr`): `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
|
||||
`s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
|
||||
`s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`. Following the guide (section
|
||||
12.3): a find-first or find-last search that finds nothing returns -1
|
||||
(0xffffffff); `s_flbit_i32` returns -1 for both 0 and -1; sign extension reads
|
||||
S0[7:0] or S0[15:0]; `s_abs_i32` of 0x80000000 is 0x80000000. Only NOT, BCNT0,
|
||||
BCNT1 and ABS write SCC, as D != 0; the other seven leave it unchanged.
|
||||
`s_mov_b32` stays hand-written, because it also accepts EXEC and VCC halves as
|
||||
destinations. As for SOP2, destinations s0-s7 are refused when a fixture runs
|
||||
(they hold its buffer descriptors), and float inline constants are rejected.
|
||||
|
||||
`tests/validation/tests/sop1_unary.rs` checks 4,126 cases, with expected values
|
||||
derived from the guide (including its worked examples) separately from the
|
||||
registry, on both CPU interpreters and, through the translator, on native
|
||||
Metal; its 231 rejected programs are checked on the CPU interpreters and the
|
||||
compiler. `fixtures/rdna2/scalar-unary.s` (LLVM-assembled, expected input ^
|
||||
0x0f0080f5) chains all eleven and shows SCC surviving the forms that do not
|
||||
write it.
|
||||
@@ -24,9 +24,9 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
|
||||
| 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 |
|
||||
| SOPC | 18 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
|
||||
| SOP2 | 51 | 17 | 17 | 17 | 17 | 17 | 0 | 0 | 12 |
|
||||
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
|
||||
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
|
||||
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 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 | 72 | 40 | 76 | 72 | 72 | 18 | 18 | 30 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
@@ -44,4 +44,6 @@ The table counts distinct variant names per family across registry operand rules
|
||||
|
||||
| Family | Operand rule | Unsupported variants |
|
||||
| --- | --- | --- |
|
||||
| SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
@@ -51,11 +51,14 @@ 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` |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `unchanged` |
|
||||
| `source_bits` | Sign extension only: the low bits of S0 that are read. The XML must list S0 with that size and format (`FMT_NUM_I8` or `FMT_NUM_I16`) | `8`, `16`; required for `sext`, rejected elsewhere |
|
||||
| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere |
|
||||
| `shift_count_bits` | Shifts only: the low bits of S1 used as the count. The generator masks S1 with it, and the XML must list S1 as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (compares only), `unchanged` |
|
||||
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` |
|
||||
| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) |
|
||||
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
|
||||
@@ -71,7 +74,20 @@ 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 |
|
||||
| `not`, `bcnt0`, `bcnt1` / `bitwise` | `nonzero` | `not_nonzero_b32`, `bcnt0_nonzero_b32`, `bcnt1_nonzero_b32` | no |
|
||||
| `brev`, `ff0`, `ff1`, `flbit` / `bitwise` | `unchanged` | `brev_b32`, `ff0_b32`, `ff1_b32`, `flbit_b32` | no |
|
||||
| `flbit`, `sext` / `signed` | `unchanged` | `flbit_i32`, `sext_i32` | no |
|
||||
| `abs` / `signed` | `nonzero` | `abs_nonzero_i32` | no |
|
||||
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
|
||||
|
||||
A compare must use an operand rule of the compare kind (`sopc_scalar`: two
|
||||
sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
|
||||
one source and an SGPR destination), and a two-source ALU operation
|
||||
`sop2_sgpr`.
|
||||
|
||||
Behaviour is chosen only from these declared fields, never from the mnemonic.
|
||||
|
||||
|
||||
@@ -135,6 +135,138 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_not_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0"
|
||||
representation = "`BE890708`"
|
||||
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_brev_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged"
|
||||
representation = "`BE8A0B08`"
|
||||
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_bcnt0_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0"
|
||||
representation = "`BE8C0D08`"
|
||||
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_bcnt1_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0"
|
||||
representation = "`BE8B0F08`"
|
||||
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_ff0_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged"
|
||||
representation = "`BE8E11FF 0000FFFF`"
|
||||
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_ff1_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged"
|
||||
representation = "`BE8D13FF 00400000`"
|
||||
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_flbit_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged"
|
||||
representation = "`BE8F1508`"
|
||||
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_flbit_i32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged"
|
||||
representation = "`BE9017FF FFF00000`"
|
||||
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_sext_i32_i8"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged"
|
||||
representation = "`BE911908`"
|
||||
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_sext_i32_i16"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged"
|
||||
representation = "`BE921AFF 00018000`"
|
||||
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_abs_i32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = |S0| (0x80000000 stays); SCC = D != 0"
|
||||
representation = "`BE933412`"
|
||||
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_cmp_eq_u32"
|
||||
encoding = "Normal SGPR or integer operands, with at most one source selecting a literal"
|
||||
@@ -147,6 +279,138 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_eq_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed)"
|
||||
representation = "`BF00C108`"
|
||||
lowering = "resolved 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_cmp_lg_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed)"
|
||||
representation = "`BF010908`"
|
||||
lowering = "resolved 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_cmp_gt_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed)"
|
||||
representation = "`BF020908`"
|
||||
lowering = "resolved 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_cmp_ge_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed)"
|
||||
representation = "`BF030909`"
|
||||
lowering = "resolved 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_cmp_lt_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed)"
|
||||
representation = "`BF040908`"
|
||||
lowering = "resolved 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_cmp_le_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed)"
|
||||
representation = "`BF050809`"
|
||||
lowering = "resolved 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_cmp_lg_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned)"
|
||||
representation = "`BF07FF0A 89ABCDEF`"
|
||||
lowering = "resolved 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_cmp_gt_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned)"
|
||||
representation = "`BF080908`"
|
||||
lowering = "resolved 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_cmp_ge_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned)"
|
||||
representation = "`BF090809`"
|
||||
lowering = "resolved 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_cmp_lt_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned)"
|
||||
representation = "`BF0A0809`"
|
||||
lowering = "resolved 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_cmp_le_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned)"
|
||||
representation = "`BF0BC009`"
|
||||
lowering = "resolved 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_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out"
|
||||
@@ -255,6 +519,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"
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
001c: branch.uniform 0x0024 taken=false
|
||||
0028: branch.uniform 0x0030 taken=false
|
||||
0034: branch.uniform 0x003c taken=true
|
||||
0040: branch.uniform 0x0048 taken=false
|
||||
004c: branch.uniform 0x0054 taken=false
|
||||
0058: branch.uniform 0x0060 taken=true
|
||||
0064: branch.uniform 0x006c taken=false
|
||||
007c: branch.uniform 0x0088 taken=true
|
||||
008c: branch.uniform 0x0098 taken=false
|
||||
009c: branch.uniform 0x00a8 taken=true
|
||||
00ac: branch.uniform 0x00b8 taken=false
|
||||
00bc: branch.uniform 0x00c8 taken=false
|
||||
00c8: t13 = const.u32 0x00000d5b
|
||||
00cc: t14 = xor.b32 t0, t13
|
||||
00d0: store.u32 output[index], t14
|
||||
@@ -0,0 +1,11 @@
|
||||
#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 t13 = 0x00000d5bu;
|
||||
uint t14 = t0 ^ t13;
|
||||
output[index] = t14;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0060: branch.uniform 0x006c taken=true
|
||||
006c: t2 = const.u32 0xffffff0f
|
||||
0070: t3 = const.u32 0x0f000000
|
||||
0074: t4 = xor.b32 t2, t3
|
||||
0078: t5 = const.u32 0x00000004
|
||||
007c: t6 = xor.b32 t4, t5
|
||||
0080: t7 = const.u32 0x0000001c
|
||||
0084: t8 = xor.b32 t6, t7
|
||||
0088: t9 = const.u32 0x00000016
|
||||
008c: t10 = xor.b32 t8, t9
|
||||
0090: t11 = const.u32 0x00000010
|
||||
0094: t12 = xor.b32 t10, t11
|
||||
0098: t13 = const.u32 0x00000018
|
||||
009c: t14 = xor.b32 t12, t13
|
||||
00a0: t15 = const.u32 0x0000000c
|
||||
00a4: t16 = xor.b32 t14, t15
|
||||
00a8: t17 = const.u32 0xfffffff0
|
||||
00ac: t18 = xor.b32 t16, t17
|
||||
00b0: t19 = const.u32 0xffff8000
|
||||
00b4: t20 = xor.b32 t18, t19
|
||||
00b8: t21 = const.u32 0x00008000
|
||||
00bc: t22 = xor.b32 t20, t21
|
||||
00c0: t23 = const.u32 0x00007fff
|
||||
00c4: t24 = xor.b32 t22, t23
|
||||
00c8: t25 = const.u32 0xffffffff
|
||||
00cc: t26 = xor.b32 t24, t25
|
||||
00d0: t27 = xor.b32 t0, t26
|
||||
00d4: store.u32 output[index], t27
|
||||
@@ -0,0 +1,35 @@
|
||||
#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 = 0xffffff0fu;
|
||||
uint t3 = 0x0f000000u;
|
||||
uint t4 = t2 ^ t3;
|
||||
uint t5 = 0x00000004u;
|
||||
uint t6 = t4 ^ t5;
|
||||
uint t7 = 0x0000001cu;
|
||||
uint t8 = t6 ^ t7;
|
||||
uint t9 = 0x00000016u;
|
||||
uint t10 = t8 ^ t9;
|
||||
uint t11 = 0x00000010u;
|
||||
uint t12 = t10 ^ t11;
|
||||
uint t13 = 0x00000018u;
|
||||
uint t14 = t12 ^ t13;
|
||||
uint t15 = 0x0000000cu;
|
||||
uint t16 = t14 ^ t15;
|
||||
uint t17 = 0xfffffff0u;
|
||||
uint t18 = t16 ^ t17;
|
||||
uint t19 = 0xffff8000u;
|
||||
uint t20 = t18 ^ t19;
|
||||
uint t21 = 0x00008000u;
|
||||
uint t22 = t20 ^ t21;
|
||||
uint t23 = 0x00007fffu;
|
||||
uint t24 = t22 ^ t23;
|
||||
uint t25 = 0xffffffffu;
|
||||
uint t26 = t24 ^ t25;
|
||||
uint t27 = t0 ^ t26;
|
||||
output[index] = t27;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,66 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOPC vectors: each of the twelve 32-bit integer compares sets SCC,
|
||||
// and an s_cbranch_scc0 skips setting that compare's bit in s20, so s20
|
||||
// records every result. -1 and 1 separate signed from unsigned ordering;
|
||||
// inline and literal operands appear in the second position.
|
||||
// Expected: input ^ 0x00000d5b (bits worked out by hand below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, -1
|
||||
s_mov_b32 s9, 1
|
||||
s_mov_b32 s20, 0
|
||||
s_cmp_eq_i32 s8, -1 // -1 == -1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip0
|
||||
s_or_b32 s20, s20, 1
|
||||
.Lskip0:
|
||||
s_cmp_lg_i32 s8, s9 // -1 != 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip1
|
||||
s_or_b32 s20, s20, 2
|
||||
.Lskip1:
|
||||
s_cmp_gt_i32 s8, s9 // -1 > 1: SCC = 0
|
||||
s_cbranch_scc0 .Lskip2
|
||||
s_or_b32 s20, s20, 4
|
||||
.Lskip2:
|
||||
s_cmp_ge_i32 s9, s9 // 1 >= 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip3
|
||||
s_or_b32 s20, s20, 8
|
||||
.Lskip3:
|
||||
s_cmp_lt_i32 s8, s9 // -1 < 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip4
|
||||
s_or_b32 s20, s20, 16
|
||||
.Lskip4:
|
||||
s_cmp_le_i32 s9, s8 // 1 <= -1: SCC = 0
|
||||
s_cbranch_scc0 .Lskip5
|
||||
s_or_b32 s20, s20, 32
|
||||
.Lskip5:
|
||||
s_cmp_eq_u32 s9, 1 // 1 == 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip6
|
||||
s_or_b32 s20, s20, 64
|
||||
.Lskip6:
|
||||
s_mov_b32 s10, 0x89abcdef
|
||||
s_cmp_lg_u32 s10, 0x89abcdef // 0x89abcdef != 0x89abcdef: SCC = 0 (literal)
|
||||
s_cbranch_scc0 .Lskip7
|
||||
s_or_b32 s20, s20, 0x80
|
||||
.Lskip7:
|
||||
s_cmp_gt_u32 s8, s9 // 0xffffffff > 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip8
|
||||
s_or_b32 s20, s20, 0x100
|
||||
.Lskip8:
|
||||
s_cmp_ge_u32 s9, s8 // 1 >= 0xffffffff: SCC = 0
|
||||
s_cbranch_scc0 .Lskip9
|
||||
s_or_b32 s20, s20, 0x200
|
||||
.Lskip9:
|
||||
s_cmp_lt_u32 s9, s8 // 1 < 0xffffffff: SCC = 1
|
||||
s_cbranch_scc0 .Lskip10
|
||||
s_or_b32 s20, s20, 0x400
|
||||
.Lskip10:
|
||||
s_cmp_le_u32 s9, 64 // 1 <= 64: SCC = 1
|
||||
s_cbranch_scc0 .Lskip11
|
||||
s_or_b32 s20, s20, 0x800
|
||||
.Lskip11:
|
||||
v_mov_b32_e32 v2, s20
|
||||
v_xor_b32_e32 v2, v1, v2 // s20 = 0x00000d5b
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -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
|
||||
Binary file not shown.
@@ -0,0 +1,59 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOP1 vectors for the registry-declared unary forms: complement, bit
|
||||
// reverse, both bit counts, both find-first searches (one finding nothing, which
|
||||
// gives -1), both find-last-bit forms, sign extension from 8 and 16 bits, and
|
||||
// absolute value. SCC is set by NOT/BCNT/ABS only: an ABS of zero clears it, and
|
||||
// the following SEXT and FF1 leave it clear for the s_cbranch_scc0.
|
||||
// Expected: input ^ 0x0f0080f5 (worked out by hand below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, 0xf0
|
||||
s_not_b32 s9, s8 // s9 = 0xffffff0f, SCC = 1
|
||||
s_brev_b32 s10, s8 // s10 = 0x0f000000
|
||||
s_bcnt1_i32_b32 s11, s8 // s11 = 4, SCC = 1
|
||||
s_bcnt0_i32_b32 s12, s8 // s12 = 28, SCC = 1
|
||||
s_ff1_i32_b32 s13, 0x400000 // s13 = 22
|
||||
s_ff0_i32_b32 s14, 0xffff // s14 = 16
|
||||
s_flbit_i32_b32 s15, s8 // s15 = 24
|
||||
s_flbit_i32 s16, 0xfff00000 // s16 = 12 (bits equal to the sign above bit 19)
|
||||
s_sext_i32_i8 s17, s8 // s17 = 0xfffffff0
|
||||
s_sext_i32_i16 s18, 0x18000 // s18 = 0xffff8000
|
||||
s_abs_i32 s19, s18 // s19 = 0x8000, SCC = 1
|
||||
s_abs_i32 s20, 0 // s20 = 0, SCC = 0
|
||||
s_sext_i32_i16 s21, 0x7fff // s21 = 0x7fff, SCC unchanged (0)
|
||||
s_ff1_i32_b32 s22, 0 // s22 = 0xffffffff (none found), SCC unchanged (0)
|
||||
s_cbranch_scc0 .Lzero
|
||||
v_mov_b32_e32 v2, 0
|
||||
s_branch .Ldone
|
||||
.Lzero:
|
||||
v_mov_b32_e32 v2, s9
|
||||
v_mov_b32_e32 v3, s10
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s11
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s12
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s13
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s14
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s15
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s16
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s17
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s18
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s19
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s21
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s22
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_xor_b32_e32 v2, v1, v2 // v2 = input ^ 0x0f0080f5
|
||||
.Ldone:
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
@@ -12,7 +12,7 @@ case "${1:-}" in
|
||||
esac
|
||||
|
||||
for name in add bitwise-branch float-exact or shifts ashr \
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare; do
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary; 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"
|
||||
|
||||
Executable
+48
@@ -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"
|
||||
@@ -25,6 +25,11 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12
|
||||
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
# The native app interface runs the trusted fixture's guest draw on Metal.
|
||||
cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run
|
||||
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
|
||||
# and VOPC compares.
|
||||
cargo test --locked -p xenora-semantic-review --no-run
|
||||
|
||||
@@ -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,11 +62,58 @@ 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,
|
||||
}
|
||||
return {"source": {"sha256": SHA}, "encodings": {"ENC_SOP2": encoding}, "variants": variants}
|
||||
sopc = {
|
||||
"name": "ENC_SOPC",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["OP", [[16, 7]]], ["ENCODING", [[23, 9]]],
|
||||
],
|
||||
"identifier_mask": 0xFFFF0000,
|
||||
"identifiers": [0xBF000000 | (op << 16) for op in (4, 10)],
|
||||
}
|
||||
for name, opcode, data_format in (("S_CMP_LT_I32", 4, I32), ("S_CMP_LT_U32", 10, U32)):
|
||||
variants[(name, "ENC_SOPC")] = {
|
||||
"instruction": name, "encoding": "ENC_SOPC", "opcode": opcode,
|
||||
"operands": _operands(data_format)[1:],
|
||||
}
|
||||
sop1 = {
|
||||
"name": "ENC_SOP1",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SSRC0", [[0, 8]]], ["OP", [[8, 8]]], ["SDST", [[16, 7]]], ["ENCODING", [[23, 9]]],
|
||||
],
|
||||
"identifier_mask": 0xFF80FF00,
|
||||
"identifiers": [0xBE800000 | (op << 8) for op in (7, 11, 25)],
|
||||
}
|
||||
|
||||
def unary(dst, src, size, scc):
|
||||
rows = [
|
||||
["SDST", dst, "OPR_SDST", 32, False, True, False, True],
|
||||
["SSRC0", src, "OPR_SSRC_NOLDS", size, True, False, False, True],
|
||||
]
|
||||
if scc:
|
||||
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True])
|
||||
return rows
|
||||
|
||||
for name, opcode, operands in (
|
||||
("S_NOT_B32", 7, unary(U32, U32, 32, True)),
|
||||
("S_BREV_B32", 11, unary(U32, U32, 32, False)),
|
||||
("S_SEXT_I32_I8", 25, unary(I32, "FMT_NUM_I8", 8, False)),
|
||||
):
|
||||
variants[(name, "ENC_SOP1")] = {
|
||||
"instruction": name, "encoding": "ENC_SOP1", "opcode": opcode, "operands": operands,
|
||||
}
|
||||
return {
|
||||
"source": {"sha256": SHA},
|
||||
"encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1},
|
||||
"variants": variants,
|
||||
}
|
||||
|
||||
|
||||
def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
|
||||
@@ -80,20 +127,60 @@ def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
|
||||
}
|
||||
|
||||
|
||||
def unaries():
|
||||
reg = registry()
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["sop1_sgpr"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.OPERAND_RULES["sop1_sgpr"]["unsupported"])
|
||||
reg["operand_rules"]["sop1_sgpr"] = rule
|
||||
|
||||
def unary(name, opcode, variant, operation, signedness, scc, **extra):
|
||||
form = _form(name, opcode, variant, operation, signedness, scc)
|
||||
form.update(family="SOP1", operands="sop1_sgpr", **extra)
|
||||
return form
|
||||
|
||||
reg["form"] += [
|
||||
unary("S_NOT_B32", 7, "NotB32", "not", "bitwise", "nonzero"),
|
||||
unary("S_BREV_B32", 11, "BrevB32", "brev", "bitwise", "unchanged"),
|
||||
unary("S_SEXT_I32_I8", 25, "SextI32I8", "sext", "signed", "unchanged", source_bits=8),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def compares():
|
||||
reg = registry()
|
||||
reg["form"] += [
|
||||
_compare("S_CMP_LT_I32", 4, "CmpLtI32", "lt", "signed"),
|
||||
_compare("S_CMP_LT_U32", 10, "CmpLtU32", "lt", "unsigned"),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def _compare(name, opcode, variant, relation, signedness):
|
||||
form = _form(name, opcode, variant, "compare", signedness, "relation")
|
||||
form.update(family="SOPC", relation=relation, operands="sopc_scalar")
|
||||
return form
|
||||
|
||||
|
||||
def registry():
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["sop2_sgpr"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.UNSUPPORTED_COMBOS)
|
||||
compare_rule = copy.deepcopy(gen.OPERAND_RULES["sopc_scalar"]["shape"])
|
||||
compare_rule["unsupported"] = sorted(gen.OPERAND_RULES["sopc_scalar"]["unsupported"])
|
||||
return {
|
||||
"schema": 1,
|
||||
"architecture": "gfx1030",
|
||||
"source_sha256": SHA,
|
||||
"documents": copy.deepcopy(gen.PINNED_DOCUMENTS),
|
||||
"operand_rules": {"sop2_sgpr": rule},
|
||||
"operand_rules": {"sop2_sgpr": rule, "sopc_scalar": compare_rule},
|
||||
"form": [
|
||||
_form("S_ADD_U32", 0, "AddU32", "add", "unsigned", "carry_out"),
|
||||
_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,
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
@@ -233,7 +320,9 @@ class Validate(unittest.TestCase):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["family"] = "SOPC"
|
||||
self.rejects(reg, "S_ADD_U32: operand rule sop2_sgpr is for SOP2")
|
||||
self.rejects(reg, "S_ADD_U32: family SOPC has no XML encoding ENC_SOPC")
|
||||
self.rejects(reg, "S_ADD_U32: no default ENC_SOPC variant in the XML snapshot")
|
||||
form(reg, "S_ADD_U32")["family"] = "SOPK"
|
||||
self.rejects(reg, "S_ADD_U32: family SOPK has no XML encoding ENC_SOPK")
|
||||
|
||||
def test_rejects_form_absent_from_the_xml(self):
|
||||
reg = registry()
|
||||
@@ -288,6 +377,148 @@ 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_accepts_unaries(self):
|
||||
self.assertEqual(self.errors(unaries()), [])
|
||||
|
||||
def test_rejects_a_sext_without_source_bits(self):
|
||||
reg = unaries()
|
||||
del reg["form"][-1]["source_bits"]
|
||||
self.rejects(reg, "S_SEXT_I32_I8: source_bits must be one of [8, 16], got None")
|
||||
|
||||
def test_rejects_a_sext_whose_source_bits_contradict_the_xml(self):
|
||||
reg = unaries()
|
||||
reg["form"][-1]["source_bits"] = 16
|
||||
self.rejects(reg, "S_SEXT_I32_I8: SSRC0 is 8 bits in the XML, declared 16")
|
||||
self.rejects(reg, "S_SEXT_I32_I8: SSRC0 has XML format FMT_NUM_I8, not FMT_NUM_I16")
|
||||
|
||||
def test_rejects_source_bits_on_another_operation(self):
|
||||
reg = unaries()
|
||||
reg["form"][-2]["source_bits"] = 8
|
||||
self.rejects(reg, "S_BREV_B32: source_bits on a non-sext operation")
|
||||
|
||||
def test_rejects_an_scc_write_the_xml_does_not_show(self):
|
||||
reg = unaries()
|
||||
reg["form"][-2]["operation"] = "not"
|
||||
reg["form"][-2]["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_BREV_B32: scc nonzero contradicts the XML SCC output")
|
||||
|
||||
def test_rejects_a_unary_operation_under_a_binary_rule(self):
|
||||
reg = unaries()
|
||||
reg["form"][0]["operation"] = "not"
|
||||
reg["form"][0]["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_ADD_U32: operation not does not fit rule sop2_sgpr")
|
||||
|
||||
def test_renders_unary_scc_as_optional(self):
|
||||
text = gen.render(unaries(), snapshot())
|
||||
self.assertIn("Self::BrevB32 => (primitive::brev_b32(src), None),", text)
|
||||
self.assertIn("Self::SextI32I8 => (primitive::sext_i32(src, 8), None),", text)
|
||||
self.assertIn("let (value, scc) = primitive::not_nonzero_b32(src);", text)
|
||||
|
||||
def test_accepts_compares(self):
|
||||
self.assertEqual(self.errors(compares()), [])
|
||||
|
||||
def test_rejects_a_compare_without_a_relation(self):
|
||||
reg = compares()
|
||||
del reg["form"][-1]["relation"]
|
||||
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation None")
|
||||
|
||||
def test_rejects_an_unknown_relation(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["relation"] = "ne"
|
||||
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation 'ne'")
|
||||
|
||||
def test_rejects_a_non_string_relation(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["relation"] = ["lt"]
|
||||
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation ['lt']")
|
||||
|
||||
def test_rejects_a_rule_without_sources(self):
|
||||
reg = compares()
|
||||
del reg["operand_rules"]["sopc_scalar"]["src"]
|
||||
self.rejects(reg, "operand rule sopc_scalar: declaration differs from the decoder's implemented rule")
|
||||
|
||||
def test_rejects_a_relation_on_a_non_compare(self):
|
||||
reg = compares()
|
||||
reg["form"][0]["relation"] = "lt"
|
||||
self.rejects(reg, "S_ADD_U32: relation on a non-compare operation")
|
||||
|
||||
def test_rejects_a_compare_with_another_scc_effect(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_CMP_LT_U32: scc nonzero contradicts compare (requires relation)")
|
||||
|
||||
def test_rejects_a_bitwise_compare(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["signedness"] = "bitwise"
|
||||
self.rejects(reg, "S_CMP_LT_U32: no primitive implements lt/bitwise")
|
||||
|
||||
def test_rejects_a_compare_whose_signedness_contradicts_the_xml(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["signedness"] = "signed"
|
||||
self.rejects(reg, "S_CMP_LT_U32: signedness signed contradicts XML format FMT_NUM_U32")
|
||||
|
||||
def test_rejects_a_compare_under_an_alu_rule(self):
|
||||
reg = compares()
|
||||
reg["form"][0]["operation"] = "compare"
|
||||
reg["form"][0]["relation"] = "lt"
|
||||
reg["form"][0]["scc"] = "relation"
|
||||
self.rejects(reg, "S_ADD_U32: operation compare does not fit rule sop2_sgpr")
|
||||
|
||||
def test_renders_compare_dispatch_and_relation(self):
|
||||
text = gen.render(compares(), snapshot())
|
||||
self.assertIn("if word & 0xff80_0000 != 0xbf00_0000 {", text)
|
||||
self.assertIn("Self::CmpLtI32 => primitive::lt_i32(src0, src1),", text)
|
||||
self.assertIn("Self::CmpLtU32 => primitive::lt_u32(src0, src1),", text)
|
||||
self.assertIn("relation: Some(CompareRelation::Less),", text)
|
||||
|
||||
def test_rejects_an_incomplete_unsupported_list(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].remove("two_literals")
|
||||
@@ -424,14 +655,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 SCALAR_ALU_OP_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("SCALAR_ALU_OP_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())
|
||||
|
||||
@@ -8,9 +8,12 @@
|
||||
//! field layout and executes them with an explicit program-counter machine, so
|
||||
//! a defect in the production decoder or reference cannot cancel out here.
|
||||
//!
|
||||
//! Scope matches the demo fixtures: scalar move/compare/branch, SOP2 unsigned
|
||||
//! Scope matches the demo fixtures: scalar move, eleven SOP1 unary forms
|
||||
//! (NOT, BREV, BCNT0/1, FF0/1, FLBIT, FLBIT_I32, SEXT_I8/I16, ABS), the twelve SOPC 32-bit integer
|
||||
//! compares, 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,9 +53,12 @@ enum CmpSrc {
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Insn {
|
||||
SMov(u8, Src),
|
||||
/// SOP2 opcode 0-5, 14, 16 or 18.
|
||||
/// SOP1 unary opcode 7, 11, 13, 15, 17, 19, 21, 23, 25, 26 or 52.
|
||||
SUnary(u32, u8, Src),
|
||||
/// SOP2 opcode 0-5, 14, 16, 18 or an even opcode 20-34.
|
||||
SAlu(u32, u8, Src, Src),
|
||||
SCmpEq(Src, Src),
|
||||
/// SOPC opcode 0-11: `s_cmp_{eq,lg,gt,ge,lt,le}_i32` then `_u32`.
|
||||
SCmp(u32, Src, Src),
|
||||
BranchScc0(usize),
|
||||
BranchMaskZero {
|
||||
target: usize,
|
||||
@@ -205,6 +211,20 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
None
|
||||
})
|
||||
}
|
||||
Insn::SUnary(opcode, dst, src) => {
|
||||
if dst < 8 {
|
||||
Err(format!("{offset:#x}: write to a resource SGPR"))
|
||||
} else {
|
||||
read_s(&sgpr, src).map(|value| {
|
||||
let (result, flag) = scalar_unary(opcode, value);
|
||||
sgpr[dst as usize] = Some(result);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
}
|
||||
Insn::SMov(dst, src) => {
|
||||
if dst < 8 {
|
||||
Err(format!("{offset:#x}: write to a resource SGPR"))
|
||||
@@ -218,9 +238,9 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
})
|
||||
}
|
||||
}
|
||||
Insn::SCmpEq(a, b) => read_s(&sgpr, a).and_then(|a| {
|
||||
Insn::SCmp(opcode, a, b) => read_s(&sgpr, a).and_then(|a| {
|
||||
read_s(&sgpr, b).map(|b| {
|
||||
scc = Some(a == b);
|
||||
scc = Some(scalar_compare(opcode, a, b));
|
||||
None
|
||||
})
|
||||
}),
|
||||
@@ -320,6 +340,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 +359,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;
|
||||
}
|
||||
@@ -339,6 +376,69 @@ fn scalar_alu(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// RDNA 2 ISA guide 12.4: SCC = (S0 <relation> S1). Signed operands (opcodes
|
||||
/// 0-5) are ordered by flipping both sign bits and comparing unsigned.
|
||||
fn scalar_compare(opcode: u32, a: u32, b: u32) -> bool {
|
||||
let (a, b) = if opcode < 6 {
|
||||
(a ^ 0x8000_0000, b ^ 0x8000_0000)
|
||||
} else {
|
||||
(a, b)
|
||||
};
|
||||
match opcode % 6 {
|
||||
0 => a == b,
|
||||
1 => a != b,
|
||||
2 => a > b,
|
||||
3 => a >= b,
|
||||
4 => a < b,
|
||||
_ => a <= b,
|
||||
}
|
||||
}
|
||||
|
||||
/// RDNA 2 ISA guide 12.3, evaluated with arithmetic on the value (no host bit
|
||||
/// intrinsics): D and, for NOT, BCNT0, BCNT1 and ABS, SCC = (D != 0).
|
||||
fn scalar_unary(opcode: u32, value: u32) -> (u32, Option<bool>) {
|
||||
// The bits from the LSB, as repeated halving produces them.
|
||||
let mut bits = [false; 32];
|
||||
let mut rest = u64::from(value);
|
||||
for slot in &mut bits {
|
||||
*slot = rest % 2 == 1;
|
||||
rest /= 2;
|
||||
}
|
||||
let word = |bits: &dyn Fn(usize) -> bool| {
|
||||
(0..32).rev().fold(0u64, |w, i| w * 2 + u64::from(bits(i))) as u32
|
||||
};
|
||||
let position = |found: Option<usize>| found.map_or(u32::MAX, |i| i as u32);
|
||||
let ones = bits.iter().filter(|&&b| b).count() as u32;
|
||||
let result = match opcode {
|
||||
7 => 0xffff_ffff - value,
|
||||
11 => word(&|i| bits[31 - i]),
|
||||
13 => 32 - ones,
|
||||
15 => ones,
|
||||
17 => position(bits.iter().position(|&b| !b)),
|
||||
19 => position(bits.iter().position(|&b| b)),
|
||||
21 => position(bits.iter().rev().position(|&b| b)),
|
||||
23 => position(
|
||||
bits.iter()
|
||||
.rev()
|
||||
.skip(1)
|
||||
.position(|&b| b != bits[31])
|
||||
.map(|i| i + 1),
|
||||
),
|
||||
// signext of the low 8 or 16 bits: subtract 2^n when the value mod 2^n
|
||||
// is at least 2^(n-1).
|
||||
25 | 26 => {
|
||||
let span = if opcode == 25 { 256 } else { 65_536 };
|
||||
let low = i64::from(value) % span;
|
||||
let signed = if low >= span / 2 { low - span } else { low };
|
||||
signed.rem_euclid(1 << 32) as u32
|
||||
}
|
||||
// |S0| modulo 2^32, so INT_MIN stays 0x80000000.
|
||||
_ => i64::from(value as i32).abs().rem_euclid(1 << 32) as u32,
|
||||
};
|
||||
let flag = matches!(opcode, 7 | 13 | 15 | 52).then_some(result != 0);
|
||||
(result, flag)
|
||||
}
|
||||
|
||||
fn read_vgpr(lane: &Lane, reg: u8, offset: usize) -> Result<u32, String> {
|
||||
if reg == 0 {
|
||||
return Err(format!("{offset:#x}: v0 is the resource index"));
|
||||
@@ -786,6 +886,18 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
}
|
||||
return Ok((Insn::VAddNc(first as u8, src0 as u8, src1 as u8), 8));
|
||||
}
|
||||
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15.
|
||||
let sop1_op = (first >> 8) & 0xff;
|
||||
if first >> 23 == 0b1_0111_1101
|
||||
&& matches!(sop1_op, 7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52)
|
||||
{
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(fail("unsupported SOP1 destination"));
|
||||
}
|
||||
let (src, len) = scalar_source(code, offset, first as u8)?;
|
||||
return Ok((Insn::SUnary(sop1_op, dst, src), len));
|
||||
}
|
||||
if first & 0xff80_ff00 == 0xbe80_0300 {
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 107 && dst < 126 {
|
||||
@@ -795,7 +907,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"));
|
||||
@@ -808,7 +925,8 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
let (sb, lb) = scalar_source(code, offset, b)?;
|
||||
return Ok((Insn::SAlu((first >> 23) & 0x7f, dst, sa, sb), la.max(lb)));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf06_0000 {
|
||||
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22.
|
||||
if first >> 23 == 0b1_0111_1110 && (first >> 16) & 0x7f <= 11 {
|
||||
let a = first as u8;
|
||||
let b = (first >> 8) as u8;
|
||||
if a == 255 && b == 255 {
|
||||
@@ -816,7 +934,7 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
}
|
||||
let (sa, la) = scalar_source(code, offset, a)?;
|
||||
let (sb, lb) = scalar_source(code, offset, b)?;
|
||||
return Ok((Insn::SCmpEq(sa, sb), la.max(lb)));
|
||||
return Ok((Insn::SCmp((first >> 16) & 0x7f, sa, sb), la.max(lb)));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf82_0000 {
|
||||
return Ok((Insn::Branch(branch_target(first, offset)?), 4));
|
||||
|
||||
@@ -768,6 +768,15 @@ 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;
|
||||
const SCALAR_COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-compare.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-compare.s from the guide's 12.4 pseudocode.
|
||||
const SCALAR_COMPARE_KEY: u32 = 0x0000_0d5b;
|
||||
const SCALAR_UNARY_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-unary.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-unary.s from the guide's 12.3 pseudocode.
|
||||
const SCALAR_UNARY_KEY: u32 = 0x0f00_80f5;
|
||||
// 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 +878,51 @@ 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]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_fixture_records_every_registry_compare() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_COMPARE_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect();
|
||||
verify(SCALAR_COMPARE_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_COMPARE_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_cmp_le_u32 s9, 64"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_fixture_chains_registry_unary_forms() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_UNARY_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_UNARY_KEY).collect();
|
||||
verify(SCALAR_UNARY_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_UNARY_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_abs_i32 s20, 0"));
|
||||
// SCC stays clear across the SEXT and FF1 that follow s_abs_i32 s20, 0:
|
||||
// with s_abs_i32 s20, 1 instead, SCC = 1 and v2 = 0.
|
||||
let mut set = SCALAR_UNARY_FIXTURE.to_vec();
|
||||
let at = set
|
||||
.windows(4)
|
||||
.position(|word| word == [0x80, 0x34, 0x94, 0xbe])
|
||||
.unwrap();
|
||||
set[at] = 0x81;
|
||||
verify(&set, &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 +1143,12 @@ 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 compares: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect();
|
||||
assert_eq!(run(SCALAR_COMPARE_FIXTURE, &input), compares);
|
||||
let unary: Vec<_> = input.iter().map(|word| word ^ SCALAR_UNARY_KEY).collect();
|
||||
assert_eq!(run(SCALAR_UNARY_FIXTURE, &input), unary);
|
||||
let mut vectors = sop2_vectors();
|
||||
vectors.extend(sop2_operand_cases());
|
||||
vectors.extend(signed_immediate_overflows());
|
||||
@@ -1097,7 +1157,7 @@ mod review {
|
||||
}
|
||||
eprintln!(
|
||||
"{} SOP2 programs matched on native Metal",
|
||||
vectors.len() + 1
|
||||
vectors.len() + 4
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Operand-domain verification for the supported SOP2 and VOPC forms (part of
|
||||
//! #215, stage E).
|
||||
//!
|
||||
//! Every case runs three ways: the expected value written out below from the
|
||||
//! public AMD "RDNA 2" Instruction Set Architecture Reference Guide, the
|
||||
//! reference interpreter `xenora_ref`, and the translated MSL on native Metal.
|
||||
//! The expected values come only from `oracle`, which imports nothing from the
|
||||
//! ISA crate, the decoder, the shader compiler or the semantic registry, so a
|
||||
//! mistake there cannot also produce the expectation.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
mod harness;
|
||||
#[path = "operand_domains/oracle.rs"]
|
||||
mod oracle;
|
||||
#[path = "operand_domains/sop2.rs"]
|
||||
mod sop2;
|
||||
#[path = "operand_domains/vopc.rs"]
|
||||
mod vopc;
|
||||
|
||||
use harness::{Case, Rejection};
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut all = sop2::cases();
|
||||
all.extend(vopc::cases());
|
||||
all
|
||||
}
|
||||
|
||||
fn rejections() -> Vec<Rejection> {
|
||||
let mut all = sop2::rejections();
|
||||
all.extend(vopc::rejections());
|
||||
all
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operand_domains_match_the_guide_on_the_reference() {
|
||||
let cases = cases();
|
||||
harness::assert_counts(&cases, sop2::COUNTS.iter().chain(vopc::COUNTS));
|
||||
harness::check_reference(&cases).assert_none("reference disagrees with the guide");
|
||||
eprintln!("operand_domains: {} reference cases", cases.len());
|
||||
harness::print_counts(&cases);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_and_truncated_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), sop2::REJECTIONS + vopc::REJECTIONS);
|
||||
harness::check_rejected(&rejections).assert_none("not rejected as the guide requires");
|
||||
eprintln!("operand_domains: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn operand_domains_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 = cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"operand_domains: {} native Metal cases ({programs} distinct programs)",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Running a case on the reference and on Metal. The helpers mirror the ones in
|
||||
//! `known_answers.rs` (copied, not shared, so that file stays untouched).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
|
||||
use xenora_shader::{Architecture, CompileError, ENTRY_POINT, compile};
|
||||
|
||||
/// One program, its lane input and the guide's expected lane output.
|
||||
pub struct Case {
|
||||
pub form: &'static str,
|
||||
pub family: &'static str,
|
||||
pub label: String,
|
||||
pub code: Vec<u8>,
|
||||
pub input: Vec<u32>,
|
||||
pub expected: Vec<u32>,
|
||||
}
|
||||
|
||||
/// A program every implementation must refuse, at byte `offset`: as truncated
|
||||
/// when `truncated`, else as outside the supported subset.
|
||||
pub struct Rejection {
|
||||
pub family: &'static str,
|
||||
pub truncated: bool,
|
||||
pub label: String,
|
||||
pub code: Vec<u8>,
|
||||
pub offset: usize,
|
||||
}
|
||||
|
||||
pub fn words(code: &[u32]) -> Vec<u8> {
|
||||
code.iter().copied().flat_map(u32::to_le_bytes).collect()
|
||||
}
|
||||
|
||||
/// The cases that failed, grouped by family: the count and the first message.
|
||||
#[derive(Default)]
|
||||
pub struct Failures(BTreeMap<&'static str, (usize, String)>);
|
||||
|
||||
impl Failures {
|
||||
fn record(&mut self, family: &'static str, message: String) {
|
||||
let entry = self.0.entry(family).or_insert((0, message));
|
||||
entry.0 += 1;
|
||||
}
|
||||
|
||||
/// Panics with one line per failing family.
|
||||
pub fn assert_none(&self, what: &str) {
|
||||
let lines: Vec<String> = self
|
||||
.0
|
||||
.iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect();
|
||||
assert!(lines.is_empty(), "{what}:\n{}", lines.join("\n"));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check_reference(cases: &[Case]) -> Failures {
|
||||
let mut failures = Failures::default();
|
||||
for case in cases {
|
||||
let compiled = compile(Architecture::Gfx1030, &case.code);
|
||||
let reference = xenora_ref::execute(&case.code, &case.input);
|
||||
if compiled.is_err() {
|
||||
failures.record(case.family, format!("{}: {compiled:?}", case.label));
|
||||
} else if reference.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let expected = &case.expected;
|
||||
let message = format!("{}: {reference:?}, expected {expected:?}", case.label);
|
||||
failures.record(case.family, message);
|
||||
}
|
||||
}
|
||||
failures
|
||||
}
|
||||
|
||||
pub fn check_rejected(rejections: &[Rejection]) -> Failures {
|
||||
let mut failures = Failures::default();
|
||||
for rejection in rejections {
|
||||
if let Err(message) = rejected_at(rejection) {
|
||||
failures.record(rejection.family, format!("{}: {message}", rejection.label));
|
||||
}
|
||||
}
|
||||
failures
|
||||
}
|
||||
|
||||
fn rejected_at(rejection: &Rejection) -> Result<(), String> {
|
||||
let (compiler, compiler_truncated) = match compile(Architecture::Gfx1030, &rejection.code) {
|
||||
Ok(_) => return Err("the compiler accepted it".into()),
|
||||
Err(CompileError::Verify { offset, .. }) => (offset, false),
|
||||
// The decoder crate is not a dependency of this package, so its
|
||||
// `DecodeErrorKind::Truncated` variant is recognised by name.
|
||||
Err(CompileError::Decode(decode)) => (
|
||||
decode.offset,
|
||||
format!("{:?}", decode.kind).starts_with("Truncated "),
|
||||
),
|
||||
Err(other) => return Err(format!("{other:?}")),
|
||||
};
|
||||
let reference = match xenora_ref::execute(&rejection.code, &[0, 1]) {
|
||||
Ok(_) => return Err("the reference accepted it".into()),
|
||||
Err(error) => error,
|
||||
};
|
||||
// The reference names a missing word "truncated ..."; its fall-through
|
||||
// "unsupported or truncated ..." does not say which, and counts as unsupported.
|
||||
let reference_truncated = reference.detail.starts_with("truncated");
|
||||
if compiler != rejection.offset || reference.offset != rejection.offset {
|
||||
return Err(format!(
|
||||
"compiler at {compiler:#x}, reference at {:#x}, expected {:#x}",
|
||||
reference.offset, rejection.offset
|
||||
));
|
||||
}
|
||||
if compiler_truncated != rejection.truncated || reference_truncated != rejection.truncated {
|
||||
return Err(format!(
|
||||
"truncated: compiler {compiler_truncated}, reference {reference_truncated} ({}), \
|
||||
expected {}",
|
||||
reference.detail, rejection.truncated
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs every case on Metal. Cases whose translated MSL and input are identical
|
||||
/// are one program, so each distinct program runs once and its output is
|
||||
/// compared with every case that shares it. The programs are spread over
|
||||
/// `THREADS` threads, each with its own device queue, because pipeline
|
||||
/// compilation dominates the run time. Returns the failures and the number of
|
||||
/// programs.
|
||||
pub fn check_metal(cases: &[Case]) -> (Failures, usize) {
|
||||
const THREADS: usize = 4;
|
||||
let mut programs = BTreeSet::new();
|
||||
let mut failures = Failures::default();
|
||||
let mut keys = Vec::with_capacity(cases.len());
|
||||
for case in cases {
|
||||
match compile(Architecture::Gfx1030, &case.code) {
|
||||
Ok(compiled) => {
|
||||
let key = (compiled.msl, case.input.clone());
|
||||
programs.insert(key.clone());
|
||||
keys.push(Some(key));
|
||||
}
|
||||
Err(error) => {
|
||||
failures.record(case.family, format!("{}: {error:?}", case.label));
|
||||
keys.push(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
let work: Vec<&(String, Vec<u32>)> = programs.iter().collect();
|
||||
let chunk = work.len().div_ceil(THREADS).max(1);
|
||||
let outputs: HashMap<(String, Vec<u32>), Result<Vec<u32>, String>> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = work
|
||||
.chunks(chunk)
|
||||
.map(|part| {
|
||||
s.spawn(move || {
|
||||
let metal = xenora_metal::NativeCompute::new().unwrap();
|
||||
part.iter()
|
||||
.map(|&key| {
|
||||
let output = metal
|
||||
.run_words(&key.0, ENTRY_POINT, &key.1)
|
||||
.map_err(|error| error.to_string());
|
||||
(key.clone(), output)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.flat_map(|handle| handle.join().unwrap())
|
||||
.collect()
|
||||
});
|
||||
for (case, key) in cases.iter().zip(keys) {
|
||||
let Some(key) = key else { continue };
|
||||
match &outputs[&key] {
|
||||
Ok(output) if *output == case.expected => {}
|
||||
Ok(output) => {
|
||||
let expected = &case.expected;
|
||||
let message = format!("{}: {output:?}, expected {expected:?}", case.label);
|
||||
failures.record(case.family, message);
|
||||
}
|
||||
Err(error) => failures.record(case.family, format!("{}: {error}", case.label)),
|
||||
}
|
||||
}
|
||||
(failures, outputs.len())
|
||||
}
|
||||
|
||||
/// The number of cases in each family, which `expected` lists in full.
|
||||
pub fn assert_counts<'a>(
|
||||
cases: &[Case],
|
||||
expected: impl Iterator<Item = &'a (&'static str, usize)>,
|
||||
) {
|
||||
let expected: BTreeMap<_, _> = expected.map(|&(family, n)| (family, n)).collect();
|
||||
assert_eq!(tally(cases, |case| case.family), expected);
|
||||
}
|
||||
|
||||
pub fn print_counts(cases: &[Case]) {
|
||||
for (name, n) in tally(cases, |case| case.form) {
|
||||
eprintln!(" form {name}: {n}");
|
||||
}
|
||||
for (name, n) in tally(cases, |case| case.family) {
|
||||
eprintln!(" family {name}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Expected results transcribed from the AMD "RDNA 2" Instruction Set
|
||||
//! Architecture Reference Guide (30 November 2020). Section numbers refer to
|
||||
//! that guide. Nothing here comes from Xenora's own decoder, ISA tables,
|
||||
//! compiler or semantic registry.
|
||||
|
||||
/// The SOP2 forms under test with their opcode numbers (guide 12.1).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Sop2 {
|
||||
AddU32 = 0,
|
||||
SubU32 = 1,
|
||||
AddI32 = 2,
|
||||
SubI32 = 3,
|
||||
AddcU32 = 4,
|
||||
SubbU32 = 5,
|
||||
AndB32 = 14,
|
||||
OrB32 = 16,
|
||||
XorB32 = 18,
|
||||
}
|
||||
|
||||
pub const SOP2_FORMS: [(Sop2, &str); 9] = [
|
||||
(Sop2::AddU32, "s_add_u32"),
|
||||
(Sop2::SubU32, "s_sub_u32"),
|
||||
(Sop2::AddI32, "s_add_i32"),
|
||||
(Sop2::SubI32, "s_sub_i32"),
|
||||
(Sop2::AddcU32, "s_addc_u32"),
|
||||
(Sop2::SubbU32, "s_subb_u32"),
|
||||
(Sop2::AndB32, "s_and_b32"),
|
||||
(Sop2::OrB32, "s_or_b32"),
|
||||
(Sop2::XorB32, "s_xor_b32"),
|
||||
];
|
||||
|
||||
fn bit31(value: u32) -> bool {
|
||||
value >> 31 == 1
|
||||
}
|
||||
|
||||
/// D and SCC as guide 12.1 writes them; `scc` is the SCC value before the
|
||||
/// instruction. The `>= 0x100000000ULL` tests are evaluated in 64 bits, as the
|
||||
/// ULL constant says.
|
||||
pub fn sop2(op: Sop2, s0: u32, s1: u32, scc: bool) -> (u32, bool) {
|
||||
let (a, b, c) = (u64::from(s0), u64::from(s1), u64::from(scc));
|
||||
match op {
|
||||
// D.u32 = S0.u32 + S1.u32; SCC = S0.u32 + S1.u32 >= 0x100000000ULL.
|
||||
Sop2::AddU32 => (s0.wrapping_add(s1), a + b >= 0x1_0000_0000),
|
||||
// D.u = S0.u - S1.u; SCC = (S1.u > S0.u).
|
||||
Sop2::SubU32 => (s0.wrapping_sub(s1), s1 > s0),
|
||||
// D.i = S0.i + S1.i; SCC = (S0.u[31] == S1.u[31] && S0.u[31] != D.u[31]).
|
||||
Sop2::AddI32 => {
|
||||
let d = s0.wrapping_add(s1);
|
||||
(d, bit31(s0) == bit31(s1) && bit31(s0) != bit31(d))
|
||||
}
|
||||
// D.i = S0.i - S1.i; SCC = (S0.u[31] != S1.u[31] && S0.u[31] != D.u[31]).
|
||||
Sop2::SubI32 => {
|
||||
let d = s0.wrapping_sub(s1);
|
||||
(d, bit31(s0) != bit31(s1) && bit31(s0) != bit31(d))
|
||||
}
|
||||
// D.u32 = S0.u32 + S1.u32 + SCC; SCC = S0.u32 + S1.u32 + SCC >= 0x100000000ULL.
|
||||
Sop2::AddcU32 => (
|
||||
s0.wrapping_add(s1).wrapping_add(u32::from(scc)),
|
||||
a + b + c >= 0x1_0000_0000,
|
||||
),
|
||||
// D.u = S0.u - S1.u - SCC; SCC = (S1.u + SCC > S0.u), "unsigned overflow".
|
||||
// The guide does not say whether S1.u + SCC wraps at 32 bits. It is read
|
||||
// here at full width: only then does SCC report the borrow out of the
|
||||
// subtraction, which the comment names. This decides only S1 = 0xffffffff
|
||||
// with SCC set; `sop2::cases` keeps those in their own family.
|
||||
Sop2::SubbU32 => (s0.wrapping_sub(s1).wrapping_sub(u32::from(scc)), b + c > a),
|
||||
// D = S0 & S1, S0 | S1, S0 ^ S1; SCC = (D != 0).
|
||||
Sop2::AndB32 => (s0 & s1, s0 & s1 != 0),
|
||||
Sop2::OrB32 => (s0 | s1, s0 | s1 != 0),
|
||||
Sop2::XorB32 => (s0 ^ s1, s0 ^ s1 != 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Integer inline constants (guide 5.2, scalar source operand table): codes
|
||||
/// 128-192 are 0..=64 and codes 193-208 are -1..=-16.
|
||||
pub fn inline_integer(code: u32) -> Option<u32> {
|
||||
match code {
|
||||
128..=192 => Some(code - 128),
|
||||
193..=208 => Some((192_i32 - code as i32) as u32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Literal constant code: one 32-bit word follows the instruction (guide 5.2).
|
||||
pub const LITERAL: u32 = 255;
|
||||
|
||||
/// The VOPC integer compares (guide 12.9): V_CMP_{LT,EQ,LE,GT,NE,GE}_I32 are
|
||||
/// opcodes 129-134 and the _U32 forms 193-198.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Compare {
|
||||
pub opcode: u32,
|
||||
pub name: &'static str,
|
||||
}
|
||||
|
||||
pub const COMPARES: [Compare; 12] = [
|
||||
Compare {
|
||||
opcode: 129,
|
||||
name: "v_cmp_lt_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 130,
|
||||
name: "v_cmp_eq_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 131,
|
||||
name: "v_cmp_le_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 132,
|
||||
name: "v_cmp_gt_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 133,
|
||||
name: "v_cmp_ne_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 134,
|
||||
name: "v_cmp_ge_i32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 193,
|
||||
name: "v_cmp_lt_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 194,
|
||||
name: "v_cmp_eq_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 195,
|
||||
name: "v_cmp_le_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 196,
|
||||
name: "v_cmp_gt_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 197,
|
||||
name: "v_cmp_ne_u32",
|
||||
},
|
||||
Compare {
|
||||
opcode: 198,
|
||||
name: "v_cmp_ge_u32",
|
||||
},
|
||||
];
|
||||
|
||||
/// "D[threadId] = (S0 < S1)" and so on (guide 12.9), with I32 operands read as
|
||||
/// two's complement and U32 operands as unsigned (chapter 12 suffix rules).
|
||||
pub fn compare(form: Compare, s0: u32, s1: u32) -> bool {
|
||||
let signed = form.name.ends_with("_i32");
|
||||
let order = if signed {
|
||||
(s0 as i32).cmp(&(s1 as i32))
|
||||
} else {
|
||||
s0.cmp(&s1)
|
||||
};
|
||||
match &form.name[6..8] {
|
||||
"lt" => order.is_lt(),
|
||||
"eq" => order.is_eq(),
|
||||
"le" => order.is_le(),
|
||||
"gt" => order.is_gt(),
|
||||
"ne" => order.is_ne(),
|
||||
"ge" => order.is_ge(),
|
||||
other => unreachable!("{other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// VCC for one Wave32 wave (guide 3.9): "VCC[n] = EXEC[n] & (test passed for
|
||||
/// thread[n])", and "VCC is fully written", so inactive lanes read 0.
|
||||
pub fn vcc(exec: u32, passed: impl Fn(usize) -> bool) -> u32 {
|
||||
(0..32)
|
||||
.filter(|&lane| exec >> lane & 1 == 1 && passed(lane))
|
||||
.fold(0, |mask, lane| mask | 1 << lane)
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! SOP2 programs: the operands start in SGPRs (or as inline or literal
|
||||
//! sources), SCC is set or cleared first, and the result reaches the output as
|
||||
//! v2 = D, XORed with the lane input only when SCC is set afterwards. With the
|
||||
//! lane input [0, 0xffffffff] the output is [D, D] or [D, !D].
|
||||
|
||||
use super::harness::{Case, Rejection, words};
|
||||
use super::oracle::{self, LITERAL, SOP2_FORMS, Sop2, sop2 as expect};
|
||||
|
||||
/// Boundary operands: zero, one, signed max/min and min + 1, unsigned max and
|
||||
/// max - 1, and an ordinary pattern.
|
||||
const VALUES: [u32; 8] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
u32::MAX,
|
||||
0x1234_5678,
|
||||
];
|
||||
const LITERALS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0x1234_5678];
|
||||
/// 64-bit operands for add/addc and sub/subb chains.
|
||||
const WIDE: [u64; 6] = [
|
||||
0,
|
||||
1,
|
||||
0xffff_ffff,
|
||||
0x1_0000_0000,
|
||||
0x8000_0000_0000_0000,
|
||||
u64::MAX,
|
||||
];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
pub const COUNTS: &[(&str, usize)] = &[
|
||||
("sop2 domain", 9 * 8 * 8 * 2 - 8),
|
||||
("sop2 subb full-width borrow", 8),
|
||||
("sop2 carry chain", 2 * 6 * 6 * 2 * 2),
|
||||
("sop2 aliasing", 9 * 5 * 2),
|
||||
("sop2 inline integer", 9 * 81 * 2),
|
||||
("sop2 literal", 9 * 6 * 2 * 2),
|
||||
("sop2 max register", 9 * 4),
|
||||
];
|
||||
/// Two literals, 21 special destinations, 9 float inline codes in two slots,
|
||||
/// and a missing literal word in two slots, for each of the 9 forms.
|
||||
pub const REJECTIONS: usize = 9 * (1 + 21 + 9 * 2 + 2);
|
||||
/// The SOP2 word's offset: load 8, wait 4, two literal moves 8 each, s_cmp 4.
|
||||
const ALU_OFFSET: usize = 0x20;
|
||||
|
||||
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.1).
|
||||
pub fn sop2(op: Sop2, dst: u32, src0: u32, src1: u32) -> u32 {
|
||||
0x8000_0000 | (op as u32) << 23 | dst << 16 | src1 << 8 | src0
|
||||
}
|
||||
|
||||
/// `s_mov_b32 s<reg>, literal` (SOP1 opcode 3).
|
||||
fn mov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0xbe80_03ff | reg << 16, value]
|
||||
}
|
||||
|
||||
/// The program around `alu`: `init` sets SGPRs, SCC = `scc`, then `alu`, then
|
||||
/// v2 = s<result>, XORed with v1 when SCC 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(mov(reg, value));
|
||||
}
|
||||
// s_cmp_eq_u32 0, 0 sets SCC; s_cmp_eq_u32 0, 1 clears it.
|
||||
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 lanes((d, scc): (u32, bool)) -> Vec<u32> {
|
||||
vec![d, if scc { !d } else { d }]
|
||||
}
|
||||
|
||||
fn case(
|
||||
form: &'static str,
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
out: (u32, bool),
|
||||
) -> Case {
|
||||
Case {
|
||||
form,
|
||||
family,
|
||||
label: format!("{form} {label}"),
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: lanes(out),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (op, name) in SOP2_FORMS {
|
||||
let alu = [sop2(op, 10, 8, 9)];
|
||||
for a in VALUES {
|
||||
for b in VALUES {
|
||||
for scc in [false, true] {
|
||||
let family = if op == Sop2::SubbU32 && b == u32::MAX && scc {
|
||||
"sop2 subb full-width borrow"
|
||||
} else {
|
||||
"sop2 domain"
|
||||
};
|
||||
let code = program(&[(8, a), (9, b)], scc, &alu, 10);
|
||||
cases.push(case(
|
||||
name,
|
||||
family,
|
||||
format!("{a:#x}, {b:#x}, scc {scc}"),
|
||||
code,
|
||||
expect(op, a, b, scc),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// dst/src aliasing, SCC set: (dst, src0, src1) with s8 = a, s9 = b.
|
||||
for (a, b) in [(0xffff_fff0, 0x11), (0x8000_0000, 0x8000_0000)] {
|
||||
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)], true, &[sop2(op, dst, src0, src1)], dst);
|
||||
let out = expect(op, pick(src0), pick(src1), true);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 aliasing",
|
||||
format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x})"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
// Every integer inline constant in each source slot, s8 = 0xfffffff0, SCC set.
|
||||
let a = 0xffff_fff0;
|
||||
for code_point in (128..=208).filter_map(|c| oracle::inline_integer(c).map(|v| (c, v))) {
|
||||
let (selector, value) = code_point;
|
||||
for slot in 0..2 {
|
||||
let (alu, out) = if slot == 0 {
|
||||
(sop2(op, 10, selector, 8), expect(op, value, a, true))
|
||||
} else {
|
||||
(sop2(op, 10, 8, selector), expect(op, a, value, true))
|
||||
};
|
||||
let code = program(&[(8, a), (9, 0)], true, &[alu], 10);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 inline integer",
|
||||
format!("inline {selector} ({value:#x}) slot {slot}"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
// A literal word in each source slot, with SCC clear.
|
||||
for a in [1, 0x8000_0000] {
|
||||
for literal in LITERALS {
|
||||
for slot in 0..2 {
|
||||
let (alu, out) = if slot == 0 {
|
||||
(sop2(op, 10, LITERAL, 8), expect(op, literal, a, false))
|
||||
} else {
|
||||
(sop2(op, 10, 8, LITERAL), expect(op, a, literal, false))
|
||||
};
|
||||
let code = program(&[(8, a), (9, 0)], false, &[alu, literal], 10);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 literal",
|
||||
format!("literal {literal:#x} slot {slot}, s8 {a:#x}"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// s105, the highest SGPR a SOP2 operand may name (guide 5.2), as
|
||||
// destination and source; s105 = a, s8 = s9 = b, SCC set.
|
||||
let (a, b) = (0x8000_0001, u32::MAX);
|
||||
for (dst, src0, src1) in [(105, 105, 9), (105, 8, 105), (105, 105, 105), (8, 105, 9)] {
|
||||
let pick = |reg| if reg == 105 { a } else { b };
|
||||
let code = program(
|
||||
&[(105, a), (8, b), (9, b)],
|
||||
true,
|
||||
&[sop2(op, dst, src0, src1)],
|
||||
dst,
|
||||
);
|
||||
let out = expect(op, pick(src0), pick(src1), true);
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 max register",
|
||||
format!("s{dst} = s{src0}, s{src1}"),
|
||||
code,
|
||||
out,
|
||||
));
|
||||
}
|
||||
}
|
||||
cases.extend(chains());
|
||||
cases
|
||||
}
|
||||
|
||||
/// 64-bit add and subtract built from the u32 forms: low word with
|
||||
/// s_add_u32/s_sub_u32, high word with s_addc_u32/s_subb_u32 consuming its
|
||||
/// SCC. SCC is preset both ways first to show the low form overwrites it. Each
|
||||
/// chain runs twice, outputting the low word and then the high word, both with
|
||||
/// the final SCC. The expected words and SCC follow the guide; they are also
|
||||
/// checked against 64-bit arithmetic here.
|
||||
fn chains() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (low, high, name) in [
|
||||
(Sop2::AddU32, Sop2::AddcU32, "s_addc_u32"),
|
||||
(Sop2::SubU32, Sop2::SubbU32, "s_subb_u32"),
|
||||
] {
|
||||
for x in WIDE {
|
||||
for y in WIDE {
|
||||
for preset in [false, true] {
|
||||
let (xl, xh, yl, yh) = (x as u32, (x >> 32) as u32, y as u32, (y >> 32) as u32);
|
||||
let (d_low, carry) = expect(low, xl, yl, preset);
|
||||
let (d_high, scc) = expect(high, xh, yh, carry);
|
||||
let exact = if low == Sop2::AddU32 {
|
||||
(x.wrapping_add(y), x.checked_add(y).is_none())
|
||||
} else {
|
||||
(x.wrapping_sub(y), y > x)
|
||||
};
|
||||
let joined = u64::from(d_high) << 32 | u64::from(d_low);
|
||||
assert_eq!((joined, scc), exact, "{x:#x} {y:#x}");
|
||||
let alu = [sop2(low, 12, 8, 9), sop2(high, 13, 10, 11)];
|
||||
let init = [(8, xl), (9, yl), (10, xh), (11, yh)];
|
||||
for (word, d) in [("low", d_low), ("high", d_high)] {
|
||||
let result = if word == "low" { 12 } else { 13 };
|
||||
cases.push(case(
|
||||
name,
|
||||
"sop2 carry chain",
|
||||
format!("{x:#x}, {y:#x}, preset {preset}, {word} word"),
|
||||
program(&init, preset, &alu, result),
|
||||
(d, scc),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
pub fn rejections() -> Vec<Rejection> {
|
||||
let mut rejections = Vec::new();
|
||||
let reject = |family, label: String, alu: &[u32]| Rejection {
|
||||
family,
|
||||
truncated: false,
|
||||
label,
|
||||
code: program(&[(8, 1), (9, 2)], false, alu, 10),
|
||||
offset: ALU_OFFSET,
|
||||
};
|
||||
for (op, name) in SOP2_FORMS {
|
||||
// Both sources select the literal. The guide allows at most one literal
|
||||
// constant per instruction; whether two selectors may share one word is
|
||||
// not stated, and Xenora's subset rejects it.
|
||||
rejections.push(reject(
|
||||
"sop2 two literals",
|
||||
format!("{name} two literals"),
|
||||
&[sop2(op, 10, LITERAL, LITERAL), 3, 3],
|
||||
));
|
||||
// VCC_LO, VCC_HI, TTMP0-15, M0, EXEC_LO, EXEC_HI as destination. The
|
||||
// guide lists these as scalar destinations; Xenora's SOP2 subset writes
|
||||
// only s0-s105, so these are rejections of the subset, not of the guide.
|
||||
for dst in (106..=123).chain([124, 126, 127]) {
|
||||
rejections.push(reject(
|
||||
"sop2 special destination",
|
||||
format!("{name} dst {dst}"),
|
||||
&[sop2(op, dst, 8, 9)],
|
||||
));
|
||||
}
|
||||
// Float inline constants 0.5 .. -4.0 and 1/(2*pi) (codes 240-248). The
|
||||
// guide defines them for every source; Xenora's subset rejects them for
|
||||
// these integer forms.
|
||||
for selector in 240..=248 {
|
||||
rejections.push(reject(
|
||||
"sop2 float inline",
|
||||
format!("{name} float inline {selector} src0"),
|
||||
&[sop2(op, 10, selector, 8)],
|
||||
));
|
||||
rejections.push(reject(
|
||||
"sop2 float inline",
|
||||
format!("{name} float inline {selector} src1"),
|
||||
&[sop2(op, 10, 8, selector)],
|
||||
));
|
||||
}
|
||||
// The stream ends where the literal word should be.
|
||||
for (slot, alu) in [(0, sop2(op, 10, LITERAL, 8)), (1, sop2(op, 10, 8, LITERAL))] {
|
||||
let mut code = program(&[(8, 1), (9, 2)], false, &[], 10);
|
||||
code.truncate(ALU_OFFSET);
|
||||
code.extend(alu.to_le_bytes());
|
||||
rejections.push(Rejection {
|
||||
family: "sop2 missing literal",
|
||||
truncated: true,
|
||||
label: format!("{name} missing literal slot {slot}"),
|
||||
code,
|
||||
offset: ALU_OFFSET,
|
||||
});
|
||||
}
|
||||
}
|
||||
rejections
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! VOPC programs on one Wave32 wave: v1 = lane input, v3 (or v255) = a literal
|
||||
//! `b`, an optional EXEC mask around the compare, then every lane outputs
|
||||
//! VCC_LO. The 32 lane inputs are distinct, so a mask bit landing in the wrong
|
||||
//! lane changes the output.
|
||||
//!
|
||||
//! Not covered: whether a compare also writes EXEC. The supported subset has
|
||||
//! no instruction that reads EXEC back, so the EXEC cases restore it before
|
||||
//! the output move.
|
||||
|
||||
use super::harness::{Case, Rejection, words};
|
||||
use super::oracle::{COMPARES, Compare, LITERAL, compare, inline_integer, vcc};
|
||||
|
||||
/// Boundary operands, also the first ten lane inputs: zero, one, signed max - 1
|
||||
/// and max, signed min and min + 1, -16, unsigned max - 1 and max, and a
|
||||
/// pattern.
|
||||
const VALUES: [u32; 10] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_fffe,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fff0,
|
||||
0xffff_fffe,
|
||||
u32::MAX,
|
||||
0x0f0f_0f0f,
|
||||
];
|
||||
/// The other 22 lane inputs: more values near the boundaries and patterns.
|
||||
const MORE_LANES: [u32; 22] = [
|
||||
2,
|
||||
3,
|
||||
15,
|
||||
16,
|
||||
63,
|
||||
64,
|
||||
65,
|
||||
0x7fff_fffd,
|
||||
0x8000_0002,
|
||||
0xffff_fffd,
|
||||
0xffff_ffef,
|
||||
0xffff_fff1,
|
||||
0x4000_0000,
|
||||
0xc000_0000,
|
||||
0x0000_ffff,
|
||||
0xffff_0000,
|
||||
0x1234_5678,
|
||||
0x8765_4321,
|
||||
0x00ff_00ff,
|
||||
0xff00_ff00,
|
||||
0x5555_5555,
|
||||
0xaaaa_aaaa,
|
||||
];
|
||||
const LITERALS: [u32; 5] = [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX];
|
||||
const EXEC_MASKS: [u32; 5] = [0, 0x5555_5555, 0xaaaa_aaaa, 0x8000_0001, 0x0000_ffff];
|
||||
|
||||
pub const COUNTS: &[(&str, usize)] = &[
|
||||
("vopc domain", 12 * 10 * 2),
|
||||
("vopc aliasing", 12),
|
||||
("vopc inline integer", 12 * 81),
|
||||
("vopc literal", 12 * 5),
|
||||
("vopc sgpr source", 12 * 2 * 2),
|
||||
("vopc max register", 12 * 2),
|
||||
("vopc exec mask", 12 * 5),
|
||||
("vopc vccz", 12 * 11),
|
||||
];
|
||||
/// A missing literal word and 9 float inline codes (defined by the guide, outside
|
||||
/// Xenora's subset for integer compares), for each of the 12 forms.
|
||||
pub const REJECTIONS: usize = 12 * (1 + 9);
|
||||
/// The compare's offset: load 8, wait 4, v_mov with literal 8.
|
||||
const COMPARE_OFFSET: usize = 0x14;
|
||||
|
||||
/// ENCODING 0b0111110 in bits 25-31, OP 17-24, VSRC1 9-16, SRC0 0-8
|
||||
/// (guide 13.3.3); SRC0 256 + n is VGPR n.
|
||||
fn vopc(opcode: u32, src0: u32, vsrc1: u32) -> u32 {
|
||||
0x7c00_0000 | opcode << 17 | vsrc1 << 9 | src0
|
||||
}
|
||||
|
||||
const fn vgpr(n: u32) -> u32 {
|
||||
256 + n
|
||||
}
|
||||
|
||||
/// `v_mov_b32 v<reg>, literal` (VOP1 opcode 1).
|
||||
fn vmov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0x7e00_02ff | reg << 17, value]
|
||||
}
|
||||
|
||||
/// `s_mov_b32 vcc_lo, 0xffffffff`, so a compare that leaves bits untouched
|
||||
/// shows up.
|
||||
const SEED_VCC: [u32; 2] = [0xbeea_03ff, u32::MAX];
|
||||
/// `s_mov_b32 exec_lo, literal` and `s_mov_b32 exec_lo, -1`.
|
||||
const SET_EXEC: u32 = 0xbefe_03ff;
|
||||
const FULL_EXEC: u32 = 0xbefe_03c1;
|
||||
/// After v2 = VCC_LO: `s_cbranch_vccz` over `v_xor_b32 v2, v1, v2`.
|
||||
const VCCZ_TAIL: [u32; 2] = [0xbf86_0001, 0x3a04_0501];
|
||||
|
||||
/// Load v1, v<breg> = b, then `before`, the compare words, `after`, and every
|
||||
/// lane outputs VCC_LO.
|
||||
fn program(breg: u32, b: u32, before: &[u32], compare: &[u32], after: &[u32]) -> Vec<u8> {
|
||||
program_with_tail(breg, b, before, compare, after, &[])
|
||||
}
|
||||
|
||||
/// As `program`, with `tail` between the output move and the store.
|
||||
fn program_with_tail(
|
||||
breg: u32,
|
||||
b: u32,
|
||||
before: &[u32],
|
||||
compare: &[u32],
|
||||
after: &[u32],
|
||||
tail: &[u32],
|
||||
) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
code.extend(vmov(breg, b));
|
||||
code.extend(before);
|
||||
code.extend(compare);
|
||||
code.extend(after);
|
||||
code.push(0x7e04_026a);
|
||||
code.extend(tail);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn lanes() -> Vec<u32> {
|
||||
VALUES.iter().chain(&MORE_LANES).copied().collect()
|
||||
}
|
||||
|
||||
fn case(form: Compare, family: &'static str, label: String, code: Vec<u8>, mask: u32) -> Case {
|
||||
Case {
|
||||
form: form.name,
|
||||
family,
|
||||
label: format!("{} {label}", form.name),
|
||||
code,
|
||||
input: lanes(),
|
||||
expected: vec![mask; 32],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cases() -> Vec<Case> {
|
||||
let input = lanes();
|
||||
let all = u32::MAX;
|
||||
let mut cases = Vec::new();
|
||||
for form in COMPARES {
|
||||
let op = form.opcode;
|
||||
for b in VALUES {
|
||||
let code = program(3, b, &[], &[vopc(op, vgpr(1), 3)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, input[n], b));
|
||||
cases.push(case(form, "vopc domain", format!("v1, {b:#x}"), code, mask));
|
||||
let code = program(3, b, &[], &[vopc(op, vgpr(3), 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, b, input[n]));
|
||||
cases.push(case(form, "vopc domain", format!("{b:#x}, v1"), code, mask));
|
||||
}
|
||||
let code = program(3, 0, &[], &[vopc(op, vgpr(1), 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, input[n], input[n]));
|
||||
cases.push(case(form, "vopc aliasing", "v1, v1".into(), code, mask));
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector).unwrap();
|
||||
let code = program(3, 0, &[], &[vopc(op, selector, 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, value, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc inline integer",
|
||||
format!("inline {selector} ({value:#x})"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
for literal in LITERALS {
|
||||
let code = program(3, 0, &[], &[vopc(op, LITERAL, 1), literal], &[]);
|
||||
let mask = vcc(all, |n| compare(form, literal, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc literal",
|
||||
format!("literal {literal:#x}"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
// SGPR source s8 and s105, the highest SGPR (guide 5.2).
|
||||
for reg in [8, 105] {
|
||||
for value in [0x8000_0000, 0xffff_fff0] {
|
||||
let set = [0xbe80_03ff | reg << 16, value];
|
||||
let code = program(3, 0, &set, &[vopc(op, reg, 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, value, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc sgpr source",
|
||||
format!("s{reg} = {value:#x}"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
}
|
||||
// v255, the highest VGPR, in each slot.
|
||||
let b = 0x8000_0001;
|
||||
let code = program(255, b, &[], &[vopc(op, vgpr(1), 255)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, input[n], b));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc max register",
|
||||
"v1, v255".into(),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
let code = program(255, b, &[], &[vopc(op, vgpr(255), 1)], &[]);
|
||||
let mask = vcc(all, |n| compare(form, b, input[n]));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc max register",
|
||||
"v255, v1".into(),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
// Partial and empty EXEC around the compare, with VCC_LO = -1 before
|
||||
// it, so inactive lanes must be cleared ("VCC is fully written");
|
||||
// EXEC_LO = -1 again before the output move so every lane stores VCC_LO.
|
||||
let b = 0x8000_0000;
|
||||
for exec in EXEC_MASKS {
|
||||
let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, exec];
|
||||
let code = program(3, b, &before, &[vopc(op, vgpr(1), 3)], &[FULL_EXEC]);
|
||||
let mask = vcc(exec, |n| compare(form, input[n], b));
|
||||
cases.push(case(
|
||||
form,
|
||||
"vopc exec mask",
|
||||
format!("exec {exec:#x}"),
|
||||
code,
|
||||
mask,
|
||||
));
|
||||
}
|
||||
// VCCZ after the compare (guide 3.9: VCCZ is VCC == 0), read with
|
||||
// s_cbranch_vccz: lanes output VCC_LO when it is zero, else input ^ VCC_LO.
|
||||
let vccz = |mask: u32| -> Vec<u32> {
|
||||
if mask == 0 {
|
||||
vec![0; 32]
|
||||
} else {
|
||||
input.iter().map(|lane| lane ^ mask).collect()
|
||||
}
|
||||
};
|
||||
for b in VALUES {
|
||||
let code = program_with_tail(3, b, &[], &[vopc(op, vgpr(1), 3)], &[], &VCCZ_TAIL);
|
||||
let mask = vcc(all, |n| compare(form, input[n], b));
|
||||
let mut case = case(form, "vopc vccz", format!("v1, {b:#x}"), code, mask);
|
||||
case.expected = vccz(mask);
|
||||
cases.push(case);
|
||||
}
|
||||
let before = [SEED_VCC[0], SEED_VCC[1], SET_EXEC, 0];
|
||||
let compare_words = [vopc(op, vgpr(1), 3)];
|
||||
let code = program_with_tail(3, 0, &before, &compare_words, &[FULL_EXEC], &VCCZ_TAIL);
|
||||
let mut case = case(form, "vopc vccz", "exec 0".into(), code, 0);
|
||||
case.expected = vccz(0);
|
||||
cases.push(case);
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
pub fn rejections() -> Vec<Rejection> {
|
||||
let mut rejections = Vec::new();
|
||||
for form in COMPARES {
|
||||
let mut code = program(3, 0, &[], &[], &[]);
|
||||
code.truncate(COMPARE_OFFSET);
|
||||
code.extend(vopc(form.opcode, LITERAL, 1).to_le_bytes());
|
||||
rejections.push(Rejection {
|
||||
family: "vopc missing literal",
|
||||
truncated: true,
|
||||
label: format!("{} missing literal", form.name),
|
||||
code,
|
||||
offset: COMPARE_OFFSET,
|
||||
});
|
||||
for selector in 240..=248 {
|
||||
rejections.push(Rejection {
|
||||
family: "vopc float inline",
|
||||
truncated: false,
|
||||
label: format!("{} float inline {selector}", form.name),
|
||||
code: program(3, 0, &[], &[vopc(form.opcode, selector, 1)], &[]),
|
||||
offset: COMPARE_OFFSET,
|
||||
});
|
||||
}
|
||||
}
|
||||
rejections
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for eleven 32-bit SOP1 unary forms (#215):
|
||||
//! `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
|
||||
//! `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
|
||||
//! `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.3 "SOP1 Instructions"
|
||||
//! (pseudocode and functional examples), Tables 12 and 14 in section 5 (which
|
||||
//! forms set SCC), section 13.1.3 for the SOP1 word and the scalar operand
|
||||
//! table 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};
|
||||
use xenora_shader::{Architecture, CompileError, compile};
|
||||
|
||||
/// The eleven forms with their ENC_SOP1 opcodes (guide 12.3).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Form {
|
||||
Not = 7,
|
||||
Brev = 11,
|
||||
Bcnt0 = 13,
|
||||
Bcnt1 = 15,
|
||||
Ff0 = 17,
|
||||
Ff1 = 19,
|
||||
FlbitB32 = 21,
|
||||
FlbitI32 = 23,
|
||||
SextI8 = 25,
|
||||
SextI16 = 26,
|
||||
Abs = 52,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 11] = [
|
||||
(Form::Not, "s_not_b32"),
|
||||
(Form::Brev, "s_brev_b32"),
|
||||
(Form::Bcnt0, "s_bcnt0_i32_b32"),
|
||||
(Form::Bcnt1, "s_bcnt1_i32_b32"),
|
||||
(Form::Ff0, "s_ff0_i32_b32"),
|
||||
(Form::Ff1, "s_ff1_i32_b32"),
|
||||
(Form::FlbitB32, "s_flbit_i32_b32"),
|
||||
(Form::FlbitI32, "s_flbit_i32"),
|
||||
(Form::SextI8, "s_sext_i32_i8"),
|
||||
(Form::SextI16, "s_sext_i32_i16"),
|
||||
(Form::Abs, "s_abs_i32"),
|
||||
];
|
||||
|
||||
fn bit(value: u32, i: u32) -> bool {
|
||||
(value >> i) & 1 == 1
|
||||
}
|
||||
|
||||
/// The guide's D for `form` with S0 = `s0`, and the SCC after it: `Some` for
|
||||
/// the forms that write SCC, `None` for those that leave it unchanged. No form
|
||||
/// reads SCC.
|
||||
fn expect(form: Form, s0: u32) -> (u32, Option<bool>) {
|
||||
// Tables 12 and 14: NOT, BCNT0, BCNT1 and ABS set SCC ("SCC = (D != 0)",
|
||||
// "SCC=result not zero"); BREV, FF0, FF1, FLBIT and SEXT have "n".
|
||||
let not_zero = |d: u32| (d, Some(d != 0));
|
||||
match form {
|
||||
// 7 S_NOT_B32: D = ~S0; SCC = (D != 0).
|
||||
Form::Not => not_zero(!s0),
|
||||
// 11 S_BREV_B32: D.u[31:0] = S0.u[0:31].
|
||||
Form::Brev => (
|
||||
(0..32).fold(0, |d, i| d | u32::from(bit(s0, 31 - i)) << i),
|
||||
None,
|
||||
),
|
||||
// 13 S_BCNT0_I32_B32: D = 0; for i in 0..31: D += (S0[i] == 0 ? 1 : 0);
|
||||
// SCC = (D != 0).
|
||||
Form::Bcnt0 => not_zero((0..32).filter(|&i| !bit(s0, i)).count() as u32),
|
||||
// 15 S_BCNT1_I32_B32: D += (S0[i] == 1 ? 1 : 0); SCC = (D != 0).
|
||||
Form::Bcnt1 => not_zero((0..32).filter(|&i| bit(s0, i)).count() as u32),
|
||||
// 17 S_FF0_I32_B32: D.i = -1; for i in 0..31 (from the LSB): if
|
||||
// S0[i] == 0 then D.i = i; break.
|
||||
Form::Ff0 => ((0..32).find(|&i| !bit(s0, i)).unwrap_or(u32::MAX), None),
|
||||
// 19 S_FF1_I32_B32: D.i = -1; for i in 0..31: if S0[i] == 1 then
|
||||
// D.i = i; break.
|
||||
Form::Ff1 => ((0..32).find(|&i| bit(s0, i)).unwrap_or(u32::MAX), None),
|
||||
// 21 S_FLBIT_I32_B32: D.i = -1; for i in 0..31: if S0[31 - i] == 1
|
||||
// then D.i = i; break. (Zeros before the first one from the MSB.)
|
||||
Form::FlbitB32 => ((0..32).find(|&i| bit(s0, 31 - i)).unwrap_or(u32::MAX), None),
|
||||
// 23 S_FLBIT_I32: D.i = -1; for i in 1..31: if S0[31 - i] != S0[31]
|
||||
// then D.i = i; break. Table 14: -1 if the input is 0 or -1.
|
||||
Form::FlbitI32 => (
|
||||
(1..32)
|
||||
.find(|&i| bit(s0, 31 - i) != bit(s0, 31))
|
||||
.unwrap_or(u32::MAX),
|
||||
None,
|
||||
),
|
||||
// 25 S_SEXT_I32_I8: D.i = signext(S0.i[7:0]), i.e. { 24{S0[7]}, S0[7:0] }.
|
||||
Form::SextI8 => (
|
||||
if bit(s0, 7) {
|
||||
s0 | 0xffff_ff00
|
||||
} else {
|
||||
s0 & 0xff
|
||||
},
|
||||
None,
|
||||
),
|
||||
// 26 S_SEXT_I32_I16: D.i = signext(S0.i[15:0]), i.e. { 16{S0[15]}, S0[15:0] }.
|
||||
Form::SextI16 => (
|
||||
if bit(s0, 15) {
|
||||
s0 | 0xffff_0000
|
||||
} else {
|
||||
s0 & 0xffff
|
||||
},
|
||||
None,
|
||||
),
|
||||
// 52 S_ABS_I32: D.i = (S.i < 0 ? -S.i : S.i); SCC = (D.i != 0). The
|
||||
// guide's example keeps 0x80000000 ("Note this is negative!").
|
||||
Form::Abs => not_zero(if bit(s0, 31) {
|
||||
(!s0).wrapping_add(1)
|
||||
} else {
|
||||
s0
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The functional examples printed in guide 12.3, with D only; the final five
|
||||
/// are derived from the pseudocode, as their comment says.
|
||||
const GUIDE_EXAMPLES: [(Form, u32, u32); 39] = [
|
||||
(Form::Bcnt0, 0x0000_0000, 32),
|
||||
(Form::Bcnt0, 0xcccc_cccc, 16),
|
||||
(Form::Bcnt0, 0xffff_ffff, 0),
|
||||
(Form::Bcnt1, 0x0000_0000, 0),
|
||||
(Form::Bcnt1, 0xcccc_cccc, 16),
|
||||
(Form::Bcnt1, 0xffff_ffff, 32),
|
||||
(Form::Ff0, 0xaaaa_aaaa, 0),
|
||||
(Form::Ff0, 0x5555_5555, 1),
|
||||
(Form::Ff0, 0x0000_0000, 0),
|
||||
(Form::Ff0, 0xffff_ffff, 0xffff_ffff),
|
||||
(Form::Ff0, 0xfffe_ffff, 16),
|
||||
(Form::Ff1, 0xaaaa_aaaa, 1),
|
||||
(Form::Ff1, 0x5555_5555, 0),
|
||||
(Form::Ff1, 0x0000_0000, 0xffff_ffff),
|
||||
(Form::Ff1, 0xffff_ffff, 0),
|
||||
(Form::Ff1, 0x0001_0000, 16),
|
||||
(Form::FlbitB32, 0x0000_0000, 0xffff_ffff),
|
||||
(Form::FlbitB32, 0x0000_cccc, 16),
|
||||
(Form::FlbitB32, 0xffff_3333, 0),
|
||||
(Form::FlbitB32, 0x7fff_ffff, 1),
|
||||
(Form::FlbitB32, 0x8000_0000, 0),
|
||||
(Form::FlbitB32, 0xffff_ffff, 0),
|
||||
(Form::FlbitI32, 0x0000_0000, 0xffff_ffff),
|
||||
(Form::FlbitI32, 0x0000_cccc, 16),
|
||||
(Form::FlbitI32, 0xffff_3333, 16),
|
||||
(Form::FlbitI32, 0x7fff_ffff, 1),
|
||||
(Form::FlbitI32, 0x8000_0000, 1),
|
||||
(Form::FlbitI32, 0xffff_ffff, 0xffff_ffff),
|
||||
(Form::Abs, 0x0000_0001, 0x0000_0001),
|
||||
(Form::Abs, 0x7fff_ffff, 0x7fff_ffff),
|
||||
(Form::Abs, 0x8000_0000, 0x8000_0000),
|
||||
(Form::Abs, 0x8000_0001, 0x7fff_ffff),
|
||||
(Form::Abs, 0x8000_0002, 0x7fff_fffe),
|
||||
(Form::Abs, 0xffff_ffff, 0x0000_0001),
|
||||
// Not printed as examples; direct readings of the one-line pseudocode.
|
||||
(Form::Not, 0x0f0f_0000, 0xf0f0_ffff),
|
||||
(Form::Brev, 0x0000_0001, 0x8000_0000),
|
||||
(Form::Brev, 0x1234_5678, 0x1e6a_2c48),
|
||||
(Form::SextI8, 0x1234_5680, 0xffff_ff80),
|
||||
(Form::SextI16, 0x1234_7fff, 0x0000_7fff),
|
||||
];
|
||||
|
||||
/// Guide 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;
|
||||
/// Boundaries, alternating patterns, the guide's example inputs and values
|
||||
/// whose low 8 or 16 bits have the sign bit set (or just clear).
|
||||
const VALUES: [u32; 24] = [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
0xaaaa_aaaa,
|
||||
0x5555_5555,
|
||||
0xcccc_cccc,
|
||||
0x0000_cccc,
|
||||
0xffff_3333,
|
||||
0xfffe_ffff,
|
||||
0x0001_0000,
|
||||
0x0000_007f,
|
||||
0x0000_0080,
|
||||
0x0000_00ff,
|
||||
0x0000_7fff,
|
||||
0x0000_8000,
|
||||
0x0000_ffff,
|
||||
0xffff_ff7f,
|
||||
0x1234_8080,
|
||||
0x1234_5678,
|
||||
];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 7] = [
|
||||
("sop1 domain", 11 * 24 * 2),
|
||||
("sop1 single bit", 11 * 64 * 2),
|
||||
("sop1 guide example", 39 * 2),
|
||||
("sop1 inline integer", 11 * 81 * 2),
|
||||
("sop1 literal", 11 * 6 * 2),
|
||||
("sop1 aliasing", 11 * 3 * 2 * 2),
|
||||
("sop1 max register", 11 * 3 * 2),
|
||||
];
|
||||
/// Per form: 6 destinations and 15 sources outside the supported subset.
|
||||
const REJECTIONS: usize = 11 * (6 + 15);
|
||||
|
||||
/// ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.3).
|
||||
fn sop1(op: u32, dst: u32, src0: u32) -> u32 {
|
||||
0xbe80_0000 | dst << 16 | op << 8 | src0
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
|
||||
/// `scc` with `s_and_b32 s12, x, x` (x = 1 or 0), run `alu`, then
|
||||
/// v2 = s<result>, `s_cbranch_scc0` over `v_xor_b32 v2, v1, v2`, and store v2.
|
||||
/// With the lane input [0, !0] the output is [R, R] when SCC is clear after
|
||||
/// `alu` and [R, !R] 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]);
|
||||
}
|
||||
let x = if scc { 129 } else { 128 };
|
||||
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
/// The case for `form` with S0 = `s0` and SCC = `scc` before it, reading back
|
||||
/// `result`, whose value afterwards is `r` (D unless another register is read).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn case(
|
||||
(form, name): (Form, &'static str),
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
s0: u32,
|
||||
scc: bool,
|
||||
r: Option<u32>,
|
||||
) -> Case {
|
||||
let (d, written) = expect(form, s0);
|
||||
let r = r.unwrap_or(d);
|
||||
let label = format!("{name} {label}, scc before {scc}");
|
||||
let scc = written.unwrap_or(scc);
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label,
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![r, if scc { !r } else { r }],
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
for scc in [false, true] {
|
||||
let single = (0..32).flat_map(|k| [1 << k, !(1 << k)]);
|
||||
let values = VALUES.iter().map(|&v| (v, "sop1 domain"));
|
||||
let examples = GUIDE_EXAMPLES
|
||||
.iter()
|
||||
.filter(|example| example.0 == form)
|
||||
.map(|example| (example.1, "sop1 guide example"));
|
||||
let all = values
|
||||
.chain(single.map(|v| (v, "sop1 single bit")))
|
||||
.chain(examples);
|
||||
for (value, family) in all {
|
||||
let code = program(&[(8, value)], scc, &[sop1(op, 10, 8)], 10);
|
||||
let label = format!("{value:#x}");
|
||||
cases.push(case((form, name), family, label, code, value, scc, None));
|
||||
}
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
let code = program(&[], scc, &[sop1(op, 10, selector)], 10);
|
||||
let label = format!("inline {value:#x}");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 inline integer",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
}
|
||||
for value in [0, 1, 0x8000_0000, u32::MAX, 0x1234_8080, 0x0001_0000] {
|
||||
let code = program(&[], scc, &[sop1(op, 10, LITERAL), value], 10);
|
||||
let label = format!("literal {value:#x}");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 literal",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
}
|
||||
// s8 = op(s8), and s10 = op(s8) reading s8 back unchanged.
|
||||
for value in [0x8000_0000, 0x0000_80ff, u32::MAX] {
|
||||
let code = program(&[(8, value)], scc, &[sop1(op, 8, 8)], 8);
|
||||
let label = format!("s8 = op s8 ({value:#x})");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 aliasing",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
let code = program(&[(8, value)], scc, &[sop1(op, 10, 8)], 8);
|
||||
let label = format!("s8 kept after s10 = op s8 ({value:#x})");
|
||||
let kept = Some(value);
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 aliasing",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
kept,
|
||||
));
|
||||
}
|
||||
// The highest SGPR, s105 (0b1101001), as source, destination or both.
|
||||
let value = 0x0000_8001;
|
||||
for (dst, src, init) in [(105, 105, 105), (10, 105, 105), (105, 8, 8)] {
|
||||
let code = program(&[(init, value)], scc, &[sop1(op, dst, src)], dst);
|
||||
let label = format!("s{dst} = op s{src} ({value:#x})");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 max register",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// The SOP1 word's byte offset in `program` with one init pair.
|
||||
const ALU_OFFSET: usize = 12 + 8 + 4;
|
||||
|
||||
/// Programs both interpreters must refuse at the SOP1 word.
|
||||
fn rejections() -> Vec<(String, Vec<u8>)> {
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
// VCC_LO, VCC_HI, M0, NULL, EXEC_LO, EXEC_HI as SDST.
|
||||
for dst in [106, 107, 124, 125, 126, 127] {
|
||||
let code = program(&[(8, 1)], false, &[sop1(op, dst, 8)], 10);
|
||||
all.push((format!("{name} destination {dst}"), code));
|
||||
}
|
||||
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, SCC, and the float inline
|
||||
// constants 240-248 as SSRC0.
|
||||
for src in [106, 107, 124, 126, 127, 253].into_iter().chain(240..=248) {
|
||||
let code = program(&[(8, 1)], false, &[sop1(op, 10, src)], 10);
|
||||
all.push((format!("{name} source {src}"), code));
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn assert_rejected_at_alu(label: &str, code: &[u8]) {
|
||||
match xenora_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(
|
||||
error.offset, ALU_OFFSET,
|
||||
"reference rejected {label} elsewhere"
|
||||
),
|
||||
}
|
||||
match independent_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{ALU_OFFSET:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expectations_reproduce_the_guide_examples() {
|
||||
for (form, s0, d) in GUIDE_EXAMPLES {
|
||||
assert_eq!(expect(form, s0).0, d, "{form:?}({s0:#x})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop1_unary_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!("sop1_unary: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop1_unary_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!("sop1_unary: {} independent-interpreter cases", cases.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_sop1_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code) in &rejections {
|
||||
assert_rejected_at_alu(label, code);
|
||||
}
|
||||
eprintln!("sop1_unary: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_sop1_opcodes_stay_unsupported() {
|
||||
// Every 8-bit SOP1 opcode except s_mov_b32 (3) and the eleven forms.
|
||||
let supported: Vec<u32> = FORMS
|
||||
.iter()
|
||||
.map(|&(form, _)| form as u32)
|
||||
.chain([3])
|
||||
.collect();
|
||||
for op in (0..=255).filter(|op| !supported.contains(op)) {
|
||||
let code = program(&[(8, 1)], false, &[sop1(op, 10, 8)], 10);
|
||||
assert_rejected_at_alu(&format!("opcode {op}"), &code);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn sop1_unary_forms_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
for (label, code) in rejections() {
|
||||
// A decode error at the SOP1 word, so a later failure cannot stand in.
|
||||
match compile(Architecture::Gfx1030, &code) {
|
||||
Err(CompileError::Decode(error)) => assert_eq!(
|
||||
error.offset, ALU_OFFSET,
|
||||
"compiler rejected {label} elsewhere: {error:?}"
|
||||
),
|
||||
other => panic!("compiler did not reject {label} at decode: {other:?}"),
|
||||
}
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sop1_unary: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for the twelve SOPC 32-bit integer compares of
|
||||
//! #215 stage D: `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.4 "SOPC Instructions" for
|
||||
//! the SCC of each form, section 13.1.4 for the SOPC word, section 5.3 (compare
|
||||
//! operations set SCC = 1 when true) and the scalar operand table 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};
|
||||
use xenora_shader::{Architecture, compile};
|
||||
|
||||
/// The twelve forms with their ENC_SOPC opcodes (guide 12.4, Table 70).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Form {
|
||||
EqI32 = 0,
|
||||
LgI32 = 1,
|
||||
GtI32 = 2,
|
||||
GeI32 = 3,
|
||||
LtI32 = 4,
|
||||
LeI32 = 5,
|
||||
EqU32 = 6,
|
||||
LgU32 = 7,
|
||||
GtU32 = 8,
|
||||
GeU32 = 9,
|
||||
LtU32 = 10,
|
||||
LeU32 = 11,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 12] = [
|
||||
(Form::EqI32, "s_cmp_eq_i32"),
|
||||
(Form::LgI32, "s_cmp_lg_i32"),
|
||||
(Form::GtI32, "s_cmp_gt_i32"),
|
||||
(Form::GeI32, "s_cmp_ge_i32"),
|
||||
(Form::LtI32, "s_cmp_lt_i32"),
|
||||
(Form::LeI32, "s_cmp_le_i32"),
|
||||
(Form::EqU32, "s_cmp_eq_u32"),
|
||||
(Form::LgU32, "s_cmp_lg_u32"),
|
||||
(Form::GtU32, "s_cmp_gt_u32"),
|
||||
(Form::GeU32, "s_cmp_ge_u32"),
|
||||
(Form::LtU32, "s_cmp_lt_u32"),
|
||||
(Form::LeU32, "s_cmp_le_u32"),
|
||||
];
|
||||
|
||||
/// The guide's SCC for `form` with S0 = `s0` (SSRC0, the left operand) and
|
||||
/// S1 = `s1` (SSRC1). The compares write no SGPR and read no SCC.
|
||||
fn expect(form: Form, s0: u32, s1: u32) -> bool {
|
||||
let (i0, i1) = (s0 as i32, s1 as i32);
|
||||
match form {
|
||||
// 0 S_CMP_EQ_I32 and 6 S_CMP_EQ_U32 ("identical opcodes"): SCC = (S0 == S1).
|
||||
Form::EqI32 | Form::EqU32 => s0 == s1,
|
||||
// 1 S_CMP_LG_I32 and 7 S_CMP_LG_U32 ("identical opcodes"): SCC = (S0 != S1).
|
||||
Form::LgI32 | Form::LgU32 => s0 != s1,
|
||||
// 2 S_CMP_GT_I32: SCC = (S0.i > S1.i).
|
||||
Form::GtI32 => i0 > i1,
|
||||
// 3 S_CMP_GE_I32: SCC = (S0.i >= S1.i).
|
||||
Form::GeI32 => i0 >= i1,
|
||||
// 4 S_CMP_LT_I32: SCC = (S0.i < S1.i).
|
||||
Form::LtI32 => i0 < i1,
|
||||
// 5 S_CMP_LE_I32: SCC = (S0.i <= S1.i).
|
||||
Form::LeI32 => i0 <= i1,
|
||||
// 8 S_CMP_GT_U32: SCC = (S0.u > S1.u).
|
||||
Form::GtU32 => s0 > s1,
|
||||
// 9 S_CMP_GE_U32: SCC = (S0.u >= S1.u).
|
||||
Form::GeU32 => s0 >= s1,
|
||||
// 10 S_CMP_LT_U32: SCC = (S0.u < S1.u).
|
||||
Form::LtU32 => s0 < s1,
|
||||
// 11 S_CMP_LE_U32: SCC = (S0.u <= S1.u).
|
||||
Form::LeU32 => s0 <= s1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Guide 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;
|
||||
/// Signed and unsigned boundaries and their neighbours.
|
||||
const VALUES: [u32; 8] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_fffe,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
];
|
||||
/// The value s10 holds throughout; the output shows it unchanged.
|
||||
const MARKER: u32 = 0x0f0f_1234;
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 5] = [
|
||||
("sopc domain", 12 * 8 * 8 * 2),
|
||||
("sopc inline integer", 12 * 81 * 3 * 2),
|
||||
("sopc literal", 12 * 5 * 3 * 2),
|
||||
("sopc aliasing", 12 * 3),
|
||||
("sopc no sgpr write", 12 * 5),
|
||||
];
|
||||
/// Per form: two literals, 5 special registers and 9 float inline constants in
|
||||
/// each slot.
|
||||
const REJECTIONS: usize = 12 * (1 + (5 + 9) * 2);
|
||||
|
||||
/// ENCODING 0b10_1111110 in bits 23-31, OP 16-22, SSRC1 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.4).
|
||||
fn sopc(op: u32, src0: u32, src1: u32) -> u32 {
|
||||
0xbf00_0000 | op << 16 | src1 << 8 | src0
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair and
|
||||
/// s10 = MARKER, set SCC to `scc` with `s_and_b32 s12, x, x` (x = 1 or 0, a
|
||||
/// SOP2 form, so no compare is involved), run `alu`, then v2 = s<result>,
|
||||
/// `s_cbranch_scc0` over `v_xor_b32 v2, v1, v2`, and store v2. With the lane
|
||||
/// input [0, !0] the output is [R, R] when SCC is clear (branch taken) and
|
||||
/// [R, !R] when it is set (fall through).
|
||||
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.iter().chain(&[(10, MARKER)]) {
|
||||
code.extend([0xbe80_03ff | reg << 16, value]);
|
||||
}
|
||||
let x = if scc { 129 } else { 128 };
|
||||
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
|
||||
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 (r, scc) = out;
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label: format!("{name} {label}"),
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![r, if scc { !r } else { r }],
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
for a in VALUES {
|
||||
for b in VALUES {
|
||||
for scc in [false, true] {
|
||||
let code = program(&[(8, a), (9, b)], scc, &[sopc(op, 8, 9)], 10);
|
||||
let label = format!("{a:#x}, {b:#x}, scc before {scc}");
|
||||
let out = (MARKER, expect(form, a, b));
|
||||
cases.push(case(name, "sopc domain", label, code, out));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Every integer inline constant (-16..64) in each slot against a
|
||||
// register that is negative as i32 and large as u32, then 32. SCC
|
||||
// before is the opposite of the result, so a missing write shows.
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
for other in [0xffff_fff8, 0x20, value] {
|
||||
for slot in 0..2 {
|
||||
let (alu, scc) = if slot == 0 {
|
||||
(sopc(op, selector, 8), expect(form, value, other))
|
||||
} else {
|
||||
(sopc(op, 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}");
|
||||
cases.push(case(
|
||||
name,
|
||||
"sopc inline integer",
|
||||
label,
|
||||
code,
|
||||
(MARKER, scc),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// A literal dword after the SOPC word in each slot.
|
||||
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX] {
|
||||
for other in [0x7fff_ffff, 0x8000_0000, value] {
|
||||
for slot in 0..2 {
|
||||
let (alu, scc) = if slot == 0 {
|
||||
([sopc(op, LITERAL, 8), value], expect(form, value, other))
|
||||
} else {
|
||||
([sopc(op, 8, LITERAL), value], expect(form, other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], !scc, &alu, 10);
|
||||
let label = format!("literal {value:#x} in src{slot}, s8 {other:#x}");
|
||||
cases.push(case(name, "sopc literal", label, code, (MARKER, scc)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// One register in both slots: S0 == S1.
|
||||
for value in [0, 0x8000_0000, u32::MAX] {
|
||||
let scc = expect(form, value, value);
|
||||
let code = program(&[(8, value)], !scc, &[sopc(op, 8, 8)], 10);
|
||||
let label = format!("s8, s8 = {value:#x}");
|
||||
cases.push(case(name, "sopc aliasing", label, code, (MARKER, scc)));
|
||||
}
|
||||
// No SGPR is written: the sources, the marker and s11 (which a SOP2
|
||||
// reading of the word would name as SDST for opcode 11) keep their
|
||||
// values.
|
||||
let (a, b) = (0x8000_0000, 1);
|
||||
let scc = expect(form, a, b);
|
||||
let init = [(8, a), (9, b), (11, 0x1111_1111)];
|
||||
// s12 holds the SCC-setting AND result, 1 when SCC was set before.
|
||||
let s12 = u32::from(!scc);
|
||||
for (reg, value) in [(8, a), (9, b), (10, MARKER), (11, 0x1111_1111), (12, s12)] {
|
||||
let code = program(&init, !scc, &[sopc(op, 8, 9)], reg);
|
||||
let label = format!("s{reg} after s8 {a:#x}, s9 {b:#x}");
|
||||
cases.push(case(name, "sopc no sgpr write", label, code, (value, scc)));
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// The SOPC word's byte offset in `program` with `init` SGPR moves: three
|
||||
/// header words, one 8-byte move per init pair and the marker, and the AND.
|
||||
fn alu_offset(init: usize) -> usize {
|
||||
12 + 8 * (init + 1) + 4
|
||||
}
|
||||
|
||||
/// Both interpreters must refuse `code` at the SOPC word, not later.
|
||||
fn assert_rejected_at_alu(label: &str, code: &[u8], init: usize) {
|
||||
let offset = alu_offset(init);
|
||||
match xenora_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(error.offset, offset, "reference rejected {label} elsewhere"),
|
||||
}
|
||||
match independent_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{offset:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Programs both interpreters must refuse at the SOPC word, with the number
|
||||
/// of init pairs before it.
|
||||
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
let code = program(&[], false, &[sopc(op, LITERAL, LITERAL), 1], 10);
|
||||
all.push((format!("{name} two literals"), code, 0));
|
||||
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, and the float inline
|
||||
// constants 240-248 (0.5 .. 1/(2*pi)).
|
||||
for selector in [106, 107, 124, 126, 127].into_iter().chain(240..=248) {
|
||||
for slot in 0..2 {
|
||||
let alu = if slot == 0 {
|
||||
sopc(op, selector, 8)
|
||||
} else {
|
||||
sopc(op, 8, selector)
|
||||
};
|
||||
let code = program(&[(8, 1)], false, &[alu], 10);
|
||||
all.push((format!("{name} source {selector} in src{slot}"), code, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fn reference(code: &[u8], input: &[u32]) -> Result<Vec<u32>, String> {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_d_compares_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, reference);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sopc_stage_d: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_d_compares_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!(
|
||||
"sopc_stage_d: {} independent-interpreter cases",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_compare_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code, init) in &rejections {
|
||||
assert_rejected_at_alu(label, code, *init);
|
||||
}
|
||||
eprintln!("sopc_stage_d: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighbouring_sopc_opcodes_stay_unsupported() {
|
||||
// 12-15 are bit tests, 18-19 the 64-bit compares (guide 12.4); 16, 17 and
|
||||
// 20-127 are not listed. Neither interpreter supports any of them.
|
||||
for op in 12..=127 {
|
||||
let code = program(&[(8, 1), (9, 2)], false, &[sopc(op, 8, 9)], 10);
|
||||
assert_rejected_at_alu(&format!("opcode {op}"), &code, 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn stage_d_compares_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
for (label, code, _) in rejections() {
|
||||
assert!(
|
||||
compile(Architecture::Gfx1030, &code).is_err(),
|
||||
"compiler accepted {label}"
|
||||
);
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sopc_stage_d: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user