Compare commits

...
Author SHA1 Message Date
Ranveer Soni 83ef49c258 Merge branch 'main' into task/267-app-inspect 2026-11-24 16:11:56 +05:30
Swastick Chowdhury 7fa240f7ba app: open a PE executable and show read-only compatibility diagnostics (#267)
Add xenora_inspect_executable to the C interface: a bounded, read-only
report from the static probe and loader validation (hash, headers,
sections, imports not provided by the standard runtime services, DBT
coverage of the bounded disassembly, relocation and TLS counts). Nothing
in the file is executed. A probe panic becomes a report labelled as a
Xenora defect (#270). Xenora.app opens files via Open Executable..., drag
and drop, and Finder (alternate viewer for Windows executables).

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:09:15 +05:30
Ranveer Soni 7977dd4bf2 Merge pull request #268 from elforeign/task/215-sop1
isa, decoder: eleven SOP1 unary forms through the semantic registry (#215)
2026-11-24 16:06:11 +05:30
Ranveer Soni cd948d4a14 Merge pull request #269 from Swastickc/task/62-prefix-struct
loader: group interpreter instruction prefixes into a typed struct (#62)
2026-11-24 16:05:46 +05:30
Swastick Chowdhury d6189ae3ea loader: group interpreter instruction prefixes into a typed struct (#62)
Replace the #[allow(clippy::too_many_arguments)] on execute_mov_rm with a
Prefixes struct that carries rex_w, rex_r, rex_b, seg_gs and seg_fs. The
interpreter decodes the prefixes once per instruction and passes the struct to
the helpers that need them, so the lint is satisfied by construction instead
of suppressed.

Add a regression test module that pins the prefix and register-extension
behaviour of the interpreter: REX.R and REX.B selecting the expected ModRM
reg and rm registers, the two bits extending independent fields, a move
without REX.W staying 32-bit wide, and the FS prefix adding the FS base.
The test was run against unmodified main first and passed there, so the
refactor is shown to preserve semantics.

Closes #62

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:02:10 +05:30
elforeign e6eece6983 validation: require the compiler's SOP1 rejections at the SOP1 word (#215)
Review follow-up: the native test only checked that compilation failed,
so a regressed destination guard still passed when a later instruction
read an uninitialized SGPR (shown by allowing vcc_lo as a destination).
It now requires a decode error at the SOP1 offset. Also check that no
registry form duplicates a hand-written decoder form.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:30:44 -06:00
elforeign 1a78265ede Merge remote-tracking branch 'origin/main' into task/215-sop1
# Conflicts:
#	CHANGELOG.md
2026-11-24 04:27:26 -06:00
elforeign 2e0e5a36f6 isa, decoder, shader: SOP1 unary integer forms through the semantic registry (#215)
Adds eleven SOP1 forms as registry data: complement, bit reverse, bit
counts, find-first and find-last searches, sign extension and absolute
value. Sign extension declares source_bits, which the generator checks
against the XML's 8- and 16-bit source operands; forms whose XML shows
no SCC output must declare SCC unchanged. The decoder dispatches them
through the generated SOP1 table after s_mov_b32, and the translator
folds them with ScalarUnaryOp::evaluate. The separately written oracle
from task/215-sop1-oracle supplies the reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:27:14 -06:00
Ranveer Soni ece0fc27eb Merge pull request #265 from Swastickc/task/263-native-app-gate2
app: show the trusted fixture's guest-driven Metal frame (Gate 2, #263)
2026-11-24 15:56:25 +05:30
Swastick Chowdhury 82f2d9e9e6 app: show the trusted fixture's guest-driven Metal frame (#263)
Add xenora_session_run_trusted_fixture to the C interface. It runs only
the embedded trusted PE fixture through DBT startup; the guest's
fixture_draw import compiles the x9 RDNA2 shaders to MSL and renders on
native Metal. The 4x3 RGBA8 read-back is returned only when the guest
halts with the runner's expected results and every pixel equals the
pixel shader's export. Xenora.app shows the frame; --smoke-frame prints
it. Add a gpu-tests test run by scripts/test-gpu.sh.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:56:07 +05:30
elforeign 391367a531 Merge branch 'task/215-sop1-oracle' into task/215-sop1 2026-11-24 04:23:47 -06:00
Ranveer Soni e71a3da525 Merge pull request #264 from elforeign/task/215-stage-d
isa, decoder: SOPC integer compares through the semantic registry (#215 stage D)
2026-11-24 15:52:40 +05:30
elforeign b96511bfc5 validation: cover s105 in the SOP1 unary cases (#215)
Review found that every register operand was s8 or s10, so a decoder that
dropped the top bit of SDST or SSRC0 would pass. s105 now appears as source,
destination and both.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:22:34 -06:00
elforeign 84bb80d910 ref, validation: evaluate eleven SOP1 unary forms in both interpreters (#215)
Both interpreters now run s_not/brev/bcnt0/bcnt1/ff0/ff1/flbit(_b32)/
sext_i8/sext_i16/abs with SDST s0-s105. Not-found searches return -1,
s_flbit_i32 returns -1 for 0 and -1, abs keeps 0x80000000, and only NOT,
BCNT0, BCNT1 and ABS write SCC (D != 0). The reference uses host bit
intrinsics; the second interpreter works from an explicit bit array and
arithmetic, so they do not share an evaluation path.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:20:56 -06:00
elforeign 9edf644d77 Merge remote-tracking branch 'origin/main' into task/215-stage-d 2026-11-24 04:20:17 -06:00
elforeign b5d0382e89 semantics, docs: review follow-ups for the SOPC compares (#215)
Malformed relations and operand rules are diagnostics instead of
Python exceptions; the fixture now really carries a SOPC literal (LLVM
had encoded 0xffffffff as inline -1); the reference-interpreter table
and registry field table describe the current forms; the docs and
changelog state separately that the 348 rejections run on the CPU
interpreters and the compiler, not on Metal.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:20:16 -06:00
elforeign b705104403 validation: guide-derived expectations for eleven SOP1 unary forms (#215)
D and SCC for s_not/brev/bcnt0/bcnt1/ff0/ff1/flbit(_b32)/sext_i8/sext_i16/abs
are written from the RDNA 2 ISA guide (12.3 pseudocode and examples, Tables 12
and 14 for SCC) before either interpreter implements them.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:19:31 -06:00
Ranveer Soni f148b51a48 Merge pull request #262 from Swastickc/task/261-native-app-gate1
app: native macOS shell and versioned C runtime interface (Gate 1, #261)
2026-11-24 15:46:34 +05:30
elforeign c979870b3a Merge remote-tracking branch 'origin/main' into task/215-stage-d 2026-11-24 04:16:09 -06:00
elforeign cd59e081d9 isa, decoder: SOPC integer compares through the semantic registry (#215 stage D)
Adds a compare operation with a declared relation and the sopc_scalar
operand rule, so all twelve s_cmp_*_{i32,u32} forms are registry data.
The decoder dispatches them through the generated OP table and the
translator resolves SCC with ScalarCompareOp::test; the hand-written
s_cmp_eq_u32 path and its opcode constant are gone. A new LLVM-assembled
fixture records every compare's SCC, and the separately written oracle
from task/215-stage-d-oracle supplies the reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:16:09 -06:00
elforeign da41b6420d Merge branch 'task/215-stage-d-oracle' into task/215-stage-d 2026-11-24 04:10:54 -06:00
elforeign 3f710928af validation: close four blind spots in the stage D cases (#215)
Review found cases that a broken implementation would still pass: an inline
or literal value that compares like its neighbour against both registers, an
extra write to the SCC-setting scratch SGPR s12, and rejections accepted at
any offset. Inline and literal cases now also compare a value with itself,
s12 is read back, and every rejection must happen at the SOPC word.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:10:00 -06:00
elforeign 2fdf01fbb3 ref, validation: evaluate the twelve SOPC integer compares in both interpreters (#215)
Both interpreters now run s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}: SCC = S0 <rel>
S1, signed for opcodes 0-5 and unsigned for 6-11, with no SGPR written. The
reference keeps Op::CompareEqual for the two EQ opcodes (its public shape is
used by other crates' tests) and adds Op::ScalarCompare for the rest, reusing
the VOPC relation; the second interpreter orders signed operands by flipping
the sign bits, so the two do not share the comparison code.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:08:32 -06:00
elforeign 705b074a08 validation: guide-derived expectations for the stage D scalar compares (#215)
SCC for s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32} is written from the RDNA 2 ISA
guide (12.4, 13.1.4, 5.3) before either interpreter implements the new forms,
with cases for both branch edges, unchanged SGPRs and rejected operands.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:05:59 -06:00
46 changed files with 5072 additions and 197 deletions

No files matched your search

+4
View File
@@ -11,6 +11,10 @@ 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.
Generated
+2
View File
@@ -184,6 +184,8 @@ name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
"xenora-metal",
"xenora-shader",
]
[[package]]
+191 -5
View File
@@ -1,11 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Gate 1 shell: proves the app links the Rust runtime through the versioned C
// interface. It inspects the bundled trusted fixture and executes no guest code.
// 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 AppKit
import CXenora
import Foundation
import SwiftUI
import UniformTypeIdentifiers
struct RuntimeProbe {
var abiVersion: UInt32 = 0
@@ -30,29 +33,212 @@ struct RuntimeProbe {
}
}
/// 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
}
}
}
/// Read-only compatibility inspection of a user-chosen file. Nothing in it is executed.
@MainActor
final class InspectionModel: ObservableObject {
static let shared = InspectionModel()
@Published var fileName: String?
@Published var report = ""
@Published var status: Int32 = Int32(XENORA_OK)
@Published var busy = false
@Published var importing = false
func inspect(_ url: URL) {
fileName = url.lastPathComponent
busy = true
Task {
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
status = newStatus
report = newReport
busy = false
}
}
nonisolated static func run(_ url: URL) -> (Int32, String) {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
// Check the size before reading so an oversized file is never loaded into memory.
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize else {
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file's size.")
}
guard UInt64(size) <= UInt64(XENORA_MAX_INSPECT_BYTES) else {
return (Int32(XENORA_LIMIT_EXCEEDED), "The file is \(size) bytes; inspection accepts at most \(XENORA_MAX_INSPECT_BYTES).")
}
guard let data = try? Data(contentsOf: url) else {
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file.")
}
return data.withUnsafeBytes { raw in
let bytes = raw.bindMemory(to: UInt8.self).baseAddress
var required: UInt64 = 0
var probe: CChar = 0
var status = xenora_inspect_executable(bytes, UInt64(data.count), &probe, 1, &required)
guard status == Int32(XENORA_BUFFER_TOO_SMALL) else { return (status, "Inspection failed (status \(status)).") }
var text = [CChar](repeating: 0, count: Int(required))
status = xenora_inspect_executable(bytes, UInt64(data.count), &text, required, &required)
return (status, String(cString: text))
}
}
}
/// Receives files opened from Finder (double-click or Open With).
final class AppDelegate: NSObject, NSApplicationDelegate {
func application(_ application: NSApplication, open urls: [URL]) {
guard let url = urls.first else { return }
MainActor.assumeIsolated { InspectionModel.shared.inspect(url) }
}
}
struct InspectorView: View {
@ObservedObject var model: InspectionModel
var body: some View {
Section("Executable inspection (read-only)") {
HStack {
Button("Open Executable…") { model.importing = true }
Text("or drop a file on this window").foregroundStyle(.secondary)
}
if let name = model.fileName {
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
ScrollView {
Text(model.report)
.font(.system(.caption, design: .monospaced))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(minHeight: 160, maxHeight: 320)
}
Text("Opened files are inspected only. Running them is not available.")
.font(.callout)
.foregroundStyle(.secondary)
}
}
}
struct ContentView: View {
let probe = RuntimeProbe.run()
@ObservedObject var model: FrameModel
@ObservedObject var inspection = InspectionModel.shared
private var frame: GuestFrame? { model.frame }
private var running: Bool { model.running }
var body: some View {
Form {
InspectorView(model: inspection)
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("Guest execution and live display are not available in this build.")
Text("Only the bundled trusted fixture can run. Live presentation, persistent sessions and input are not available yet.")
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.frame(minWidth: 420, minHeight: 240)
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
if case .success(let url) = result { inspection.inspect(url) }
}
.dropDestination(for: URL.self) { urls, _ in
guard let url = urls.first, url.isFileURL else { return false }
inspection.inspect(url)
return true
}
.frame(minWidth: 520, minHeight: 560)
}
}
struct XenoraApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
let model = FrameModel()
var body: some Scene {
WindowGroup("Xenora") { ContentView() }
WindowGroup("Xenora") { ContentView(model: model) }
}
}
// `--inspect <path>` prints the read-only report for a file and exits with its status.
if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < CommandLine.arguments.count {
let (status, report) = InspectionModel.run(URL(fileURLWithPath: CommandLine.arguments[flag + 1]))
print(report.hasSuffix("\n") ? report : report + "\n", terminator: "")
print("status=\(status)")
exit(status == Int32(XENORA_OK) ? 0 : 1)
}
// `--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()
+23 -13
View File
@@ -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),
));
}
+40 -5
View File
@@ -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");
@@ -355,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,
@@ -443,13 +476,15 @@ fn compares_fixture_instructions_against_llvm() {
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(), 50, "forms compared: {forms:?}");
assert_eq!(forms.len(), 72, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
+8
View File
@@ -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());
}
+6
View File
@@ -12,5 +12,11 @@ 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" }
+42
View File
@@ -25,8 +25,14 @@ enum {
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. */
@@ -44,4 +50,40 @@ xenora_status xenora_session_inspect_trusted_fixture(
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);
/* Largest file xenora_inspect_executable accepts, in bytes. */
#define XENORA_MAX_INSPECT_BYTES 268435456u
/*
* Read-only compatibility inspection of a caller-supplied PE file. Nothing in
* `bytes` is executed: it is parsed and statically disassembled (bounded) only.
* On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a
* NUL-terminated UTF-8 report of `*out_required` bytes including the NUL.
* XENORA_PE_ERROR means the file is not an acceptable PE32+ image;
* XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity`
* is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required`
* set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return
* XENORA_LIMIT_EXCEEDED.
*/
xenora_status xenora_inspect_executable(
const uint8_t *bytes,
uint64_t length,
char *out_report,
uint64_t capacity,
uint64_t *out_required);
#endif
+396 -2
View File
@@ -6,9 +6,13 @@
//! 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::fmt::Write as _;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Mutex;
use xenora_loader::ParsedPe;
use std::sync::{Arc, Mutex};
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
use xenora_loader::{ExitReason, ImportRegistry, ParsedPe, ProbeConfig, Register, probe_pe_bytes};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
pub const XENORA_ABI_VERSION: u32 = 1;
@@ -19,6 +23,12 @@ 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;
@@ -129,6 +139,261 @@ pub unsafe extern "C" fn xenora_session_inspect_trusted_fixture(
})
}
// 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
})
}
pub const XENORA_MAX_INSPECT_BYTES: u64 = 256 * 1024 * 1024;
/// Build the read-only inspection report and its status: `XENORA_OK`, `XENORA_PE_ERROR`
/// for a rejected file, or `XENORA_INTERNAL_ERROR` if Xenora's own probe failed.
fn inspection_report(bytes: &[u8]) -> (i32, String) {
let mut out = String::from("Xenora read-only inspection: nothing in this file was executed.\n");
let _ = writeln!(out, "file_size: {} bytes", bytes.len());
let probed = catch_unwind(AssertUnwindSafe(|| {
probe_pe_bytes(bytes, &ProbeConfig::default())
}));
let report = match probed {
Ok(Ok(report)) => report,
Ok(Err(e)) => {
let _ = writeln!(out, "verdict: not a supported PE32+ (x86-64) image: {e}");
return (XENORA_PE_ERROR, out);
}
Err(_) => {
out.push_str(
"verdict: inspection failed inside Xenora's static probe. This is a Xenora \
defect, not a finding about the file.\n",
);
return (XENORA_INTERNAL_ERROR, out);
}
};
let pe = &report.parsed;
let _ = writeln!(out, "sha256: {}", report.sha256);
let _ = writeln!(
out,
"machine: {:#06x} image_base: {:#x} entry_rva: {:#x} size_of_image: {:#x}",
pe.machine, pe.image_base, pe.entry_point_rva, pe.size_of_image
);
match ParsedPe::parse(bytes) {
Ok(_) => out.push_str("loader_validation: accepted\n"),
Err(e) => {
let _ = writeln!(out, "loader_validation: rejected: {e}");
}
}
let _ = writeln!(out, "\nsections ({}):", pe.sections.len());
for s in &pe.sections {
let p = s.permissions;
let _ = writeln!(
out,
" {:<8} rva {:#010x} vsize {:#x} raw {:#x} {}{}{}",
s.name,
s.virtual_address,
s.virtual_size,
s.raw_data_size,
if p.read { 'r' } else { '-' },
if p.write { 'w' } else { '-' },
if p.execute { 'x' } else { '-' },
);
}
let missing: Vec<_> = report.imports.iter().filter(|i| !i.is_supported).collect();
let _ = writeln!(
out,
"\nimports: {} total, {} provided by Xenora's standard runtime services, {} not provided",
report.imports.len(),
report.imports.len() - missing.len(),
missing.len()
);
for i in &missing {
let _ = writeln!(out, " not provided: {}!{}", i.dll, i.symbol);
}
let decoded = report.instruction_records.len();
let unsupported = report
.instruction_records
.iter()
.filter(|r| !r.is_supported_dbt)
.count();
let _ = writeln!(
out,
"\nstatic disassembly (bounded): {decoded} instructions decoded, {unsupported} not supported by the ARM64 DBT"
);
if let Some(first) = &report.first_unsupported_dbt_insn {
let hex: String = first.bytes.iter().map(|b| format!("{b:02x}")).collect();
let _ = writeln!(
out,
" first unsupported: rva {:#x} {} [{hex}]",
first.rva, first.mnemonic
);
}
let _ = writeln!(
out,
"\nrelocations: {} entries\ntls callbacks: {}",
report.relocations.total_entries,
report.tls.callback_targets.len()
);
out.push_str("\nExecution of opened files is not available (see #257).\n");
(XENORA_OK, out)
}
/// # Safety
/// `bytes` must be valid for `length` reads; `out_report` must be null or valid
/// for `capacity` writes; `out_required` must be null or valid for one `u64` write.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn xenora_inspect_executable(
bytes: *const u8,
length: u64,
out_report: *mut std::ffi::c_char,
capacity: u64,
out_required: *mut u64,
) -> i32 {
guarded(|| {
if bytes.is_null() || out_report.is_null() || out_required.is_null() {
return XENORA_INVALID_ARGUMENT;
}
if length > XENORA_MAX_INSPECT_BYTES {
return XENORA_LIMIT_EXCEEDED;
}
// SAFETY: non-null, and the caller guarantees `length` readable bytes.
let input = unsafe { std::slice::from_raw_parts(bytes, length as usize) };
let (status, text) = inspection_report(input);
let required = text.len() as u64 + 1;
// SAFETY: non-null, checked above.
unsafe { out_required.write(required) };
if capacity < required {
return XENORA_BUFFER_TOO_SMALL;
}
// SAFETY: `capacity >= required`, checked above.
unsafe {
std::ptr::copy_nonoverlapping(text.as_ptr(), out_report.cast::<u8>(), text.len());
out_report.add(text.len()).write(0);
}
status
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -172,9 +437,17 @@ mod tests {
("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]
@@ -261,4 +534,125 @@ mod tests {
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));
}
fn inspect_bytes(bytes: &[u8]) -> (i32, String) {
let mut required = 0;
let mut buf = vec![0 as std::ffi::c_char; 1];
let status = unsafe {
xenora_inspect_executable(
bytes.as_ptr(),
bytes.len() as u64,
buf.as_mut_ptr(),
1,
&mut required,
)
};
assert_eq!(status, XENORA_BUFFER_TOO_SMALL);
assert_eq!(buf[0], 0, "nothing written when the buffer is too small");
buf.resize(required as usize, 0);
let status = unsafe {
xenora_inspect_executable(
bytes.as_ptr(),
bytes.len() as u64,
buf.as_mut_ptr(),
required,
&mut required,
)
};
let text = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) }
.to_str()
.unwrap()
.to_owned();
assert_eq!(text.len() as u64 + 1, required);
(status, text)
}
#[test]
fn inspection_reports_independently_read_facts_of_a_fixture() {
let (status, text) = inspect_bytes(FIXTURE);
assert_eq!(status, XENORA_OK);
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!(text.contains(&format!("file_size: {} bytes", FIXTURE.len())));
assert!(text.contains(&format!("entry_rva: {entry:#x}")));
assert!(text.contains(&format!("sections ({sections}):")));
assert!(text.contains("loader_validation: accepted"));
assert!(
text.contains("xenora.dll") || text.contains("1 provided by Xenora"),
"{text}"
);
assert!(text.contains("nothing in this file was executed"));
}
#[test]
fn inspection_rejects_malformed_and_oversized_input() {
for bad in [&b""[..], b"not a pe file", &[0u8; 0x100]] {
let (status, text) = inspect_bytes(bad);
assert_eq!(status, XENORA_PE_ERROR, "{text}");
assert!(text.contains("not a supported PE32+"), "{text}");
}
// Every truncation of a valid file yields a report and a deterministic status.
// Some truncations currently hit a panic inside the loader's static probe
// (probe.rs, #270); the boundary must turn it into a report.
for len in (0..FIXTURE.len()).step_by(7) {
let (status, text) = inspect_bytes(&FIXTURE[..len]);
assert!(
matches!(status, XENORA_OK | XENORA_PE_ERROR | XENORA_INTERNAL_ERROR),
"len {len}"
);
assert_eq!(
inspect_bytes(&FIXTURE[..len]),
(status, text),
"len {len} is deterministic"
);
}
let (mut req, mut c) = (0u64, 0 as std::ffi::c_char);
let one = [0u8];
assert_eq!(
unsafe {
xenora_inspect_executable(
one.as_ptr(),
XENORA_MAX_INSPECT_BYTES + 1,
&mut c,
1,
&mut req,
)
},
XENORA_LIMIT_EXCEEDED
);
assert_eq!(
unsafe { xenora_inspect_executable(std::ptr::null(), 0, &mut c, 1, &mut req) },
XENORA_INVALID_ARGUMENT
);
}
}
+40
View File
@@ -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);
}
}
-1
View File
@@ -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"),
+193 -19
View File
@@ -42,10 +42,38 @@ 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"}
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.
@@ -64,6 +92,7 @@ SCC = {
"borrow": "Borrow",
"signed_overflow": "SignedOverflow",
"nonzero": "Nonzero",
"relation": "Relation",
}
MASK = {"unchanged": "Unchanged"}
WAVE = {"any": "Any", "wave32": "Wave32"}
@@ -110,6 +139,16 @@ PRIMITIVES = {
("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
@@ -133,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",
},
}
@@ -228,15 +296,23 @@ 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"]]
count_field = rule["src"][1]["field"] if form["operation"] in SHIFTS else None
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")
if field == count_field:
@@ -244,6 +320,9 @@ def _check_xml(form, rule, snapshot, errors):
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}"
@@ -290,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 - {SHIFT_KEY})
extra = sorted(set(form) - FORM_KEYS - {SHIFT_KEY, RELATION_KEY, SOURCE_BITS_KEY})
if missing:
errors.append(f"{label}: incomplete, missing {missing}")
if extra:
@@ -337,7 +416,27 @@ def validate(registry, snapshot):
)
elif SHIFT_KEY in form:
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
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:
@@ -354,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:
@@ -399,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']};",
@@ -436,6 +541,9 @@ def render(registry, snapshot):
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']]},",
@@ -451,6 +559,8 @@ 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"]
@@ -472,9 +582,10 @@ def _render_enum(rule_name, forms, snapshot, positions):
]
for form in forms:
carry = " plus SCC" if form["carry_in"] == "scc" else ""
what = f"compare {form[RELATION_KEY]}" if 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}
@@ -482,7 +593,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
"}",
"",
f"/// {enum} by {family} OP field value; `None` for undeclared opcodes.",
f"const BY_OPCODE: [Option<{enum}>; {1 << size}] = [",
f"const {table}: [Option<{enum}>; {1 << size}] = [",
]
out += [
f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None,"
@@ -505,7 +616,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
" return None;",
" }",
f" BY_OPCODE[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
f" {table}[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
" }",
"",
" /// Lower-case mnemonic.",
@@ -516,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 {",
@@ -529,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) {",
+503
View File
@@ -372,3 +372,506 @@ 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
View File
@@ -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}")
}
+116
View File
@@ -98,3 +98,119 @@ 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)
}
-5
View File
@@ -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,
+35 -1
View File
@@ -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};
@@ -46,6 +47,27 @@ pub enum Operation {
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.
@@ -81,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.
@@ -105,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.
@@ -136,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,
}
@@ -159,6 +189,10 @@ pub struct FormSemantics {
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.
File diff suppressed because it is too large. Load diff
+55 -28
View File
@@ -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)
});
}
+234 -52
View File
@@ -53,6 +53,25 @@ impl Register {
}
}
/// Instruction prefixes decoded ahead of an opcode.
///
/// The interpreter decodes these once per instruction and passes them to the
/// helpers that need them, so prefix state travels as one typed value instead
/// of a list of independent booleans.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Prefixes {
/// REX.W: 64-bit operand size.
rex_w: bool,
/// REX.R: extends the ModRM `reg` field to R8-R15.
rex_r: bool,
/// REX.B: extends the ModRM `rm` field to R8-R15.
rex_b: bool,
/// The GS segment override prefix (0x65) is present.
seg_gs: bool,
/// The FS segment override prefix (0x64) is present.
seg_fs: bool,
}
/// RFLAGS status bits tracked during guest execution.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RFlags {
@@ -153,6 +172,167 @@ mod layout_tests {
}
}
#[cfg(test)]
mod prefix_tests {
use super::{CpuState, ExitReason, Interpreter, Register};
use crate::memory::{GuestMemory, MemoryPermissions};
const CODE_BASE: u64 = 0x1000;
const CODE_SIZE: usize = 0x1000;
const STACK_BASE: u64 = 0x8000_0000;
const STACK_SIZE: usize = 0x10000;
const FS_BASE: u64 = 0x9000;
const GS_BASE: u64 = 0xA000;
/// A guest memory image with executable code, a stack and distinct FS and
/// GS bases.
fn memory_with_code(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
CODE_BASE,
CODE_SIZE,
MemoryPermissions::READ_WRITE_EXECUTE,
code,
)
.expect("code region");
memory
.map_region(STACK_BASE, STACK_SIZE, MemoryPermissions::READ_WRITE)
.expect("stack region");
// The segment bases are distinct so a swapped prefix is visible.
memory
.map_region(FS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("fs region");
memory
.map_region(GS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("gs region");
memory
}
/// Run `code` on the interpreter and return the final state and exit reason.
fn run(code: &[u8]) -> (CpuState, ExitReason) {
let mut memory = memory_with_code(code);
let cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
(result.final_state, result.exit_reason)
}
/// `mov r8, imm64`: 49 B8 <imm64>.
fn mov_r8_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x49, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rbx, imm64`: 48 BB <imm64>.
fn mov_rbx_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rax, imm64`: 48 B8 <imm64>.
fn mov_rax_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// REX.B extends the ModRM `rm` field, so `rm=0` selects r8.
///
/// Encoding 49 89 D8 is `mov r8, rbx`.
#[test]
fn rex_b_extends_the_rm_field_to_r8() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x49, 0x89, 0xD8]); // mov r8, rbx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R extends the ModRM `reg` field, so `reg=0` selects r8.
///
/// Encoding 4C 89 C3 is `mov rbx, r8`.
#[test]
fn rex_r_extends_the_reg_field_to_r8() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4C, 0x89, 0xC3]); // mov rbx, r8
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R and REX.B extend independent fields, so the destination r9 and
/// the source r12 are chosen by different prefix bits.
///
/// Encoding 4D 89 E1 is `mov r9, r12`.
#[test]
fn rex_r_and_rex_b_extend_independent_fields() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4D, 0x89, 0xE1]); // mov r9, r12
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// r9 receives r12, which is zero here, and not the value in r8.
assert_eq!(state.get(Register::R9), 0);
assert_eq!(state.get(Register::R12), 0);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
}
/// Without REX.W the move is 32-bit wide, so the destination keeps only the
/// low half of the source and its upper half is cleared.
///
/// Encoding 89 D8 is `mov eax, ebx`.
#[test]
fn a_move_without_rex_w_is_32_bit_wide() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x89, 0xD8]); // mov eax, ebx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// Only the low 32 bits of ebx survive, and rax's upper half is cleared.
assert_eq!(state.get(Register::Rax), 0x5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
}
/// The FS segment override adds the FS base to the effective address.
///
/// Encoding 64 48 89 04 25 08 00 00 00 is `mov fs:[0x8], rax`.
#[test]
fn the_fs_prefix_adds_the_fs_base() {
let mut code = mov_rax_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x64, 0x48, 0x89, 0x04, 0x25, 0x08, 0x00, 0x00, 0x00]);
code.push(0xF4); // hlt
let mut memory = memory_with_code(&code);
let mut cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(
memory.read_u64(FS_BASE + 0x8).expect("fs read"),
0x1122_3344_5566_7788
);
// The GS base is untouched: the GS-prefixed store did not happen.
assert_eq!(memory.read_u64(GS_BASE + 0x8).expect("gs read"), 0);
}
}
/// Result returned after running guest execution.
#[derive(Debug)]
pub struct ExecutionResult {
@@ -255,29 +435,25 @@ impl<'a> Interpreter<'a> {
}
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
let mut rex_w = false;
let mut rex_r = false;
let mut rex_b = false;
let mut seg_gs = false;
let mut seg_fs = false;
let mut prefixes = Prefixes::default();
let mut byte = self.fetch_u8()?;
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
while byte == 0x65 || byte == 0x64 {
if byte == 0x65 {
seg_gs = true;
prefixes.seg_gs = true;
} else {
seg_fs = true;
prefixes.seg_fs = true;
}
byte = self.fetch_u8()?;
}
// Handle REX prefix (0x40 - 0x4F)
if (byte & 0xF0) == 0x40 {
rex_w = (byte & 0x08) != 0;
rex_r = (byte & 0x04) != 0;
rex_b = (byte & 0x01) != 0;
prefixes.rex_w = (byte & 0x08) != 0;
prefixes.rex_r = (byte & 0x04) != 0;
prefixes.rex_b = (byte & 0x01) != 0;
byte = self.fetch_u8()?;
}
@@ -288,9 +464,9 @@ impl<'a> Interpreter<'a> {
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(rex_b) << 3));
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if rex_w {
let reversed = if prefixes.rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
@@ -303,9 +479,9 @@ impl<'a> Interpreter<'a> {
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
0xB8..=0xBF => {
let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0xB8) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if rex_w {
if prefixes.rex_w {
let imm = self.fetch_u64()?;
self.cpu.set(reg, imm);
} else {
@@ -318,28 +494,28 @@ impl<'a> Interpreter<'a> {
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
0x31 | 0x33 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let res = if rex_w {
let res = if prefixes.rex_w {
val1 ^ val2
} else {
(val1 as u32 ^ val2 as u32) as u64
};
self.cpu.set(dst, res);
self.update_flags_logic(res, rex_w);
self.update_flags_logic(res, prefixes.rex_w);
Ok(None)
}
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
0x01 | 0x03 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
add64(val1, val2)
} else {
let (r, f) = add32(val1 as u32, val2 as u32);
@@ -353,11 +529,11 @@ impl<'a> Interpreter<'a> {
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
0x29 | 0x2B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
sub64(val1, val2)
} else {
let (r, f) = sub32(val1 as u32, val2 as u32);
@@ -371,13 +547,13 @@ impl<'a> Interpreter<'a> {
// CMP reg, r/m (0x3B) or CMP r/m, reg (0x39)
0x39 | 0x3B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (v1, v2) = if byte == 0x39 {
(self.cpu.get(rm), self.cpu.get(reg))
} else {
(self.cpu.get(reg), self.cpu.get(rm))
};
let (_, flags) = if rex_w {
let (_, flags) = if prefixes.rex_w {
sub64(v1, v2)
} else {
let (r, f) = sub32(v1 as u32, v2 as u32);
@@ -391,7 +567,7 @@ impl<'a> Interpreter<'a> {
0x83 => {
let modrm = self.fetch_u8()?;
let op = (modrm >> 3) & 7;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let imm8 = self.fetch_i8()? as i64;
let imm = imm8 as u64;
@@ -399,7 +575,7 @@ impl<'a> Interpreter<'a> {
match op {
0 => {
// ADD
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
add64(val, imm)
} else {
let (r, f) = add32(val as u32, imm as u32);
@@ -410,7 +586,7 @@ impl<'a> Interpreter<'a> {
}
5 => {
// SUB
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
@@ -421,7 +597,7 @@ impl<'a> Interpreter<'a> {
}
7 => {
// CMP
let (_, flags) = if rex_w {
let (_, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
@@ -438,7 +614,7 @@ impl<'a> Interpreter<'a> {
// MOV r/m, reg (0x89) or MOV reg, r/m (0x8B)
0x89 | 0x8B => {
let modrm = self.fetch_u8()?;
self.execute_mov_rm(modrm, rex_w, rex_r, rex_b, byte == 0x8B, seg_gs, seg_fs)
self.execute_mov_rm(modrm, &prefixes, byte == 0x8B)
}
// JMP rel8 (0xEB)
@@ -492,7 +668,7 @@ impl<'a> Interpreter<'a> {
// PUSH reg (0x50..=0x57)
0x50..=0x57 => {
let reg_idx = (byte - 0x50) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0x50) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.cpu.get(reg);
self.push_u64(val)?;
@@ -501,7 +677,7 @@ impl<'a> Interpreter<'a> {
// POP reg (0x58..=0x5F)
0x58..=0x5F => {
let reg_idx = (byte - 0x58) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0x58) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.pop_u64()?;
self.cpu.set(reg, val);
@@ -532,32 +708,26 @@ impl<'a> Interpreter<'a> {
fn decode_modrm_reg_reg(
&self,
modrm: u8,
rex_r: bool,
rex_b: bool,
prefixes: &Prefixes,
) -> Result<(Register, Register), ExitReason> {
let mode = (modrm >> 6) & 3;
if mode != 3 {
return Err(ExitReason::IllegalInstruction(modrm));
}
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
#[allow(clippy::too_many_arguments)]
fn execute_mov_rm(
&mut self,
modrm: u8,
rex_w: bool,
rex_r: bool,
rex_b: bool,
prefixes: &Prefixes,
is_load: bool,
seg_gs: bool,
seg_fs: bool,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if mode == 3 {
@@ -565,12 +735,24 @@ impl<'a> Interpreter<'a> {
let rm = Register::from_index(rm_idx);
if is_load {
let val = self.cpu.get(rm);
self.cpu
.set(reg, if rex_w { val } else { val as u32 as u64 });
self.cpu.set(
reg,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
} else {
let val = self.cpu.get(reg);
self.cpu
.set(rm, if rex_w { val } else { val as u32 as u64 });
self.cpu.set(
rm,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
}
return Ok(None);
}
@@ -580,8 +762,8 @@ impl<'a> Interpreter<'a> {
// SIB byte follows ModR/M
let sib = self.fetch_u8()?;
let scale_shift = (sib >> 6) & 3;
let index_raw = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
let index_raw = ((sib >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
let base_raw = (sib & 7) + if prefixes.rex_b { 8 } else { 0 };
let base_v = if mode == 0 && (sib & 7) == 5 {
// disp32 with no base register
@@ -637,15 +819,15 @@ impl<'a> Interpreter<'a> {
(base_val as i64 + disp) as u64
};
if seg_gs {
if prefixes.seg_gs {
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
} else if seg_fs {
} else if prefixes.seg_fs {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if rex_w {
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
@@ -661,7 +843,7 @@ impl<'a> Interpreter<'a> {
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if rex_w {
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
+116 -2
View File
@@ -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,
@@ -160,6 +166,34 @@ pub enum ScalarAlu {
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.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorAlu {
@@ -293,10 +327,48 @@ 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.
[
@@ -677,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"));
+17 -2
View File
@@ -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.
+28
View File
@@ -294,6 +294,34 @@ fn scalar_logic_results_reach_the_kernel_as_constants() {
);
}
#[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");
+4 -4
View File
@@ -1,17 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
<title id="title">Xenora · recorded progress</title>
<desc id="description">Decoded gfx1030 forms: 50 of 50. Accepted Metal forms · Apple M5: 18 of 50. 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">50 / 50</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 / 50</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="176.40" 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

+22
View File
@@ -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 |
+3 -2
View File
@@ -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. |
+42 -1
View File
@@ -78,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.
@@ -118,3 +118,44 @@ runs on all three and on native Metal.
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.
+5 -3
View File
@@ -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 |
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
| SOP2 | 51 | 17 | 17 | 17 | 17 | 17 | 0 | 0 | 12 |
| SOPC | 18 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| 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 | 50 | 17 | 54 | 50 | 50 | 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` |
+13 -1
View File
@@ -55,8 +55,10 @@ error.
| `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` |
| `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`, `unchanged` |
| `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` |
@@ -76,6 +78,16 @@ fixes the `scc` value:
| `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.
+264
View File
@@ -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"
+16
View File
@@ -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
+11
View File
@@ -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;
}
+29
View File
@@ -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
+35
View File
@@ -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.
+66
View File
@@ -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.
+59
View File
@@ -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
+1 -1
View File
@@ -12,7 +12,7 @@ case "${1:-}" in
esac
for name in add bitwise-branch float-exact or shifts ashr \
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic; 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"
+10
View File
@@ -35,6 +35,16 @@ cat > "$bundle/Contents/Info.plist" <<PLIST
<key>CFBundleShortVersionString</key><string>0.1.0</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
<key>NSHighResolutionCapable</key><true/>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key><string>Windows Executable</string>
<key>CFBundleTypeRole</key><string>Viewer</string>
<key>LSHandlerRank</key><string>Alternate</string>
<key>LSItemContentTypes</key>
<array><string>com.microsoft.windows-executable</string></array>
</dict>
</array>
</dict>
</plist>
PLIST
+5
View File
@@ -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
@@ -68,7 +68,52 @@ def snapshot():
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"):
@@ -82,15 +127,51 @@ 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"),
@@ -239,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()
@@ -342,6 +425,100 @@ class Validate(unittest.TestCase):
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")
@@ -482,14 +659,14 @@ class Render(unittest.TestCase):
reg = registry()
reg["form"].reverse()
text = gen.render(reg, snapshot())
body = text.split("const BY_OPCODE: [Option<ScalarAluOp>; 128] = [", 1)[1].split("];", 1)[0]
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("BY_OPCODE[((word >> 23) & 0x7f) as usize]", 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()
+101 -6
View File
@@ -8,7 +8,9 @@
//! 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, the stage C forms ANDN2, ORN2, NAND, NOR, XNOR, LSHL, LSHR and
//! ASHR (32-bit), VOP1 move
@@ -51,9 +53,12 @@ enum CmpSrc {
#[derive(Clone, Copy, Debug)]
enum Insn {
SMov(u8, Src),
/// 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,
@@ -206,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"))
@@ -219,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
})
}),
@@ -357,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"));
@@ -804,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 {
@@ -831,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 {
@@ -839,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));
+38 -1
View File
@@ -771,6 +771,12 @@ mod review {
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] = [
@@ -890,6 +896,33 @@ mod review {
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]) {
@@ -1112,6 +1145,10 @@ mod review {
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());
@@ -1120,7 +1157,7 @@ mod review {
}
eprintln!(
"{} SOP2 programs matched on native Metal",
vectors.len() + 2
vectors.len() + 4
);
}
+524
View File
@@ -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()
);
}
+397
View File
@@ -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()
);
}