mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 23:21:11 +00:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83ef49c258 | ||
|
|
7fa240f7ba | ||
|
|
7977dd4bf2 | ||
|
|
cd948d4a14 | ||
|
|
d6189ae3ea | ||
|
|
e6eece6983 | ||
|
|
1a78265ede | ||
|
|
2e0e5a36f6 | ||
|
|
ece0fc27eb | ||
|
|
82f2d9e9e6 | ||
|
|
391367a531 | ||
|
|
e71a3da525 | ||
|
|
b96511bfc5 | ||
|
|
84bb80d910 | ||
|
|
9edf644d77 | ||
|
|
b5d0382e89 | ||
|
|
b705104403 | ||
|
|
f148b51a48 | ||
|
|
c979870b3a | ||
|
|
cd59e081d9 | ||
|
|
0bfb12fd17 | ||
|
|
c6d0986da2 | ||
|
|
9a9422c7da | ||
|
|
da41b6420d | ||
|
|
3f710928af | ||
|
|
2fdf01fbb3 | ||
|
|
de00cb2bfd | ||
|
|
d8f9669280 | ||
|
|
19b2e9b5d5 | ||
|
|
bb6bc52c95 | ||
|
|
ba6bbb2e4a | ||
|
|
705b074a08 | ||
|
|
d3c1150854 | ||
|
|
a81d62ffe3 | ||
|
|
bb1372cd70 | ||
|
|
8d53d82981 | ||
|
|
ba2cfc2a00 | ||
|
|
b13ab327f2 | ||
|
|
e7cb8db14f | ||
|
|
e7795d0e5a | ||
|
|
3ff9ddde24 | ||
|
|
ff191d89bd | ||
|
|
4039be8ee2 | ||
|
|
898b79dc84 | ||
|
|
30d20c8f33 | ||
|
|
0687a8add6 | ||
|
|
e1317322e1 | ||
|
|
92fd955a8d |
No files matched your search
@@ -37,3 +37,6 @@ __pycache__/
|
||||
*.pyc
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
|
||||
# Native application build output
|
||||
/app/.build/
|
||||
@@ -11,6 +11,11 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
|
||||
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
|
||||
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
|
||||
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
|
||||
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
|
||||
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
|
||||
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
|
||||
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
|
||||
|
||||
Generated
+9
@@ -179,6 +179,15 @@ dependencies = [
|
||||
"xenora-ref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-ffi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-import-gen"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// swift-tools-version: 6.0
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Build with scripts/build-app.sh, which builds the Rust static library first.
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Xenora",
|
||||
platforms: [.macOS(.v14)],
|
||||
targets: [
|
||||
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
|
||||
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
module CXenora [system] {
|
||||
header "../../../crates/ffi/include/xenora.h"
|
||||
link "xenora_ffi"
|
||||
export *
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Native shell over the versioned C interface. "Run trusted fixture" executes the
|
||||
// bundled trusted PE fixture (x86-64 translated to ARM64; its draw request is rendered
|
||||
// by native Metal) and shows the verified read-back frame. No other executable can run.
|
||||
|
||||
import AppKit
|
||||
import CXenora
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct RuntimeProbe {
|
||||
var abiVersion: UInt32 = 0
|
||||
var status: Int32 = -1
|
||||
var sections: UInt32 = 0
|
||||
var entryRVA: UInt32 = 0
|
||||
|
||||
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
|
||||
|
||||
static func run() -> RuntimeProbe {
|
||||
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
|
||||
var session: xenora_session = 0
|
||||
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard probe.status == XENORA_OK else { return probe }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
|
||||
return probe
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame produced by one run of the trusted fixture.
|
||||
struct GuestFrame {
|
||||
let status: Int32
|
||||
let width: Int
|
||||
let height: Int
|
||||
let rgba: [UInt8]
|
||||
|
||||
static func run() -> GuestFrame {
|
||||
var session: xenora_session = 0
|
||||
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard status == XENORA_OK else { return GuestFrame(status: status, width: 0, height: 0, rgba: []) }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
var width: UInt32 = 0
|
||||
var height: UInt32 = 0
|
||||
status = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_run_trusted_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
|
||||
}
|
||||
return GuestFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
|
||||
}
|
||||
|
||||
var image: CGImage? {
|
||||
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
|
||||
return CGImage(
|
||||
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
let first = rgba.prefix(4).map(String.init).joined(separator: ",")
|
||||
return "status=\(status) frame=\(width)x\(height) first_pixel=\(first)"
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the latest fixture run. A class with @Published avoids SwiftUI macros,
|
||||
/// which the command-line toolchain does not ship.
|
||||
@MainActor
|
||||
final class FrameModel: ObservableObject {
|
||||
@Published var frame: GuestFrame?
|
||||
@Published var running = false
|
||||
|
||||
func run() {
|
||||
running = true
|
||||
Task {
|
||||
// The fixture blocks while it executes and renders, so keep it off the main thread.
|
||||
frame = await Task.detached { GuestFrame.run() }.value
|
||||
running = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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("Only the bundled trusted fixture can run. Live presentation, persistent sessions and input are not available yet.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.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(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()
|
||||
print(probe.summary)
|
||||
exit(probe.connected ? 0 : 1)
|
||||
}
|
||||
XenoraApp.main()
|
||||
+23
-13
@@ -4,15 +4,15 @@ use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarSource, VectorCompareOp, VectorSource,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorCompareOp, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
@@ -41,7 +41,7 @@ const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
|
||||
}
|
||||
|
||||
/// Decoded forms not yet described by the semantic registry.
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
@@ -50,7 +50,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_CMP_EQ_U32", EncodingFamily::Sopc),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
@@ -375,19 +374,30 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
|
||||
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
|
||||
}
|
||||
if S_CMP_EQ_U32.matches(first) {
|
||||
if let Some(op) = ScalarUnaryOp::from_word(first) {
|
||||
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
|
||||
let mnemonic = op.mnemonic();
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
|
||||
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
|
||||
}
|
||||
if let Some(op) = ScalarCompareOp::from_word(first) {
|
||||
let mnemonic = op.mnemonic();
|
||||
let src0_bits = first as u8;
|
||||
let src1_bits = (first >> 8) as u8;
|
||||
if src0_bits == 255 && src1_bits == 255 {
|
||||
return Err(unsupported(
|
||||
"s_cmp_eq_u32",
|
||||
mnemonic,
|
||||
"only one source may select a literal",
|
||||
));
|
||||
}
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
|
||||
return Ok((
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 },
|
||||
Instruction::ScalarCompare { op, src0, src1 },
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
|
||||
@@ -4,9 +4,12 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, VectorSource, decode, decode_at,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorSource, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
|
||||
};
|
||||
use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
@@ -340,6 +343,14 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
ScalarAluOp::AndB32 => ScalarAlu::And,
|
||||
ScalarAluOp::OrB32 => ScalarAlu::Or,
|
||||
ScalarAluOp::XorB32 => ScalarAlu::Xor,
|
||||
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
|
||||
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
|
||||
ScalarAluOp::NandB32 => ScalarAlu::Nand,
|
||||
ScalarAluOp::NorB32 => ScalarAlu::Nor,
|
||||
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
|
||||
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
|
||||
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
|
||||
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src0),
|
||||
@@ -347,8 +358,38 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
),
|
||||
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
|
||||
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
|
||||
match op {
|
||||
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
|
||||
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
|
||||
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
|
||||
ScalarUnaryOp::Bcnt1I32B32 => ScalarUnary::CountOnes,
|
||||
ScalarUnaryOp::Ff0I32B32 => ScalarUnary::FindFirstZero,
|
||||
ScalarUnaryOp::Ff1I32B32 => ScalarUnary::FindFirstOne,
|
||||
ScalarUnaryOp::FlbitI32B32 => ScalarUnary::FindLastBit,
|
||||
ScalarUnaryOp::FlbitI32 => ScalarUnary::FindLastSignBit,
|
||||
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
|
||||
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
|
||||
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src),
|
||||
),
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
|
||||
// The reference keeps CompareEqual for EQ and uses its VOPC relation
|
||||
// offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest.
|
||||
match op.relation() {
|
||||
CompareRelation::Equal => Op::CompareEqual(src0, src1),
|
||||
relation => Op::ScalarCompare(
|
||||
Comparison {
|
||||
offset: relation as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
},
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
}
|
||||
}
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
@@ -434,13 +475,16 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
SHIFT_FIXTURE,
|
||||
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 42, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 72, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
|
||||
@@ -49,3 +49,11 @@ fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_forms_do_not_duplicate_hand_written_forms() {
|
||||
// A form declared in the semantic registry and also decoded by hand-written
|
||||
// code would have two implementations; the hand-written one would win.
|
||||
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "xenora-ffi"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Versioned C interface between the native macOS application and the Xenora runtime"
|
||||
|
||||
[lib]
|
||||
crate-type = ["staticlib", "rlib"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
|
||||
gpu-tests = []
|
||||
|
||||
[dependencies]
|
||||
xenora-loader = { path = "../loader" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
@@ -0,0 +1,89 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
/*
|
||||
* Xenora native application interface, version 1.
|
||||
*
|
||||
* Every function returns a xenora_status. Sessions are identified by opaque
|
||||
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
|
||||
* handle stays invalid even if its slot is reused. Output pointers are owned
|
||||
* by the caller and are written only when the call returns XENORA_OK.
|
||||
* All functions are thread-safe. No Rust panic crosses this boundary: one is
|
||||
* reported as XENORA_INTERNAL_ERROR.
|
||||
*/
|
||||
#ifndef XENORA_H
|
||||
#define XENORA_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define XENORA_ABI_VERSION 1u
|
||||
|
||||
typedef int32_t xenora_status;
|
||||
enum {
|
||||
XENORA_OK = 0,
|
||||
XENORA_INVALID_ARGUMENT = 1,
|
||||
XENORA_INVALID_HANDLE = 2,
|
||||
XENORA_VERSION_MISMATCH = 3,
|
||||
XENORA_INTERNAL_ERROR = 4,
|
||||
XENORA_PE_ERROR = 5,
|
||||
XENORA_LIMIT_EXCEEDED = 6,
|
||||
XENORA_BUFFER_TOO_SMALL = 7,
|
||||
XENORA_EXECUTION_FAILED = 8,
|
||||
};
|
||||
|
||||
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
|
||||
#define XENORA_FIXTURE_FRAME_WIDTH 4u
|
||||
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
|
||||
|
||||
typedef uint64_t xenora_session;
|
||||
|
||||
/* The interface version this library implements. */
|
||||
uint32_t xenora_abi_version(void);
|
||||
|
||||
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
|
||||
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
|
||||
|
||||
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
|
||||
xenora_status xenora_session_destroy(xenora_session session);
|
||||
|
||||
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
|
||||
xenora_status xenora_session_inspect_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint32_t *out_section_count,
|
||||
uint32_t *out_entry_rva);
|
||||
|
||||
/*
|
||||
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
|
||||
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
|
||||
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
|
||||
* checked against the fixture shader's known output. `capacity` is the size of
|
||||
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
|
||||
* Only the embedded fixture can run; no caller-supplied executable is accepted.
|
||||
*/
|
||||
xenora_status xenora_session_run_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height);
|
||||
|
||||
/* 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
|
||||
@@ -0,0 +1,658 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Versioned C interface for the native macOS application (see `include/xenora.h`).
|
||||
//!
|
||||
//! Sessions are opaque 64-bit handles: the low 32 bits index a slot and the high
|
||||
//! 32 bits hold that slot's generation, so a stale handle never reaches a reused slot.
|
||||
//! Every exported function catches panics and reports them as `XENORA_INTERNAL_ERROR`.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, ParsedPe, 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;
|
||||
|
||||
pub const XENORA_OK: i32 = 0;
|
||||
pub const XENORA_INVALID_ARGUMENT: i32 = 1;
|
||||
pub const XENORA_INVALID_HANDLE: i32 = 2;
|
||||
pub const XENORA_VERSION_MISMATCH: i32 = 3;
|
||||
pub const XENORA_INTERNAL_ERROR: i32 = 4;
|
||||
pub const XENORA_PE_ERROR: i32 = 5;
|
||||
pub const XENORA_LIMIT_EXCEEDED: i32 = 6;
|
||||
pub const XENORA_BUFFER_TOO_SMALL: i32 = 7;
|
||||
pub const XENORA_EXECUTION_FAILED: i32 = 8;
|
||||
|
||||
pub const XENORA_FIXTURE_FRAME_WIDTH: u32 = 4;
|
||||
pub const XENORA_FIXTURE_FRAME_HEIGHT: u32 = 3;
|
||||
const FRAME_BYTES: usize = (XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4) as usize;
|
||||
|
||||
/// Upper bound on simultaneously live sessions.
|
||||
const MAX_SESSIONS: usize = 64;
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
|
||||
struct Slot {
|
||||
/// Odd while live, even while free; starts at 0 so the first handle is never 0.
|
||||
generation: u32,
|
||||
}
|
||||
|
||||
static SESSIONS: Mutex<Vec<Slot>> = Mutex::new(Vec::new());
|
||||
|
||||
fn guarded(f: impl FnOnce() -> i32) -> i32 {
|
||||
catch_unwind(AssertUnwindSafe(f)).unwrap_or(XENORA_INTERNAL_ERROR)
|
||||
}
|
||||
|
||||
fn split(handle: u64) -> (usize, u32) {
|
||||
((handle & 0xFFFF_FFFF) as usize, (handle >> 32) as u32)
|
||||
}
|
||||
|
||||
fn is_live(slots: &[Slot], handle: u64) -> bool {
|
||||
let (index, generation) = split(handle);
|
||||
slots
|
||||
.get(index)
|
||||
.is_some_and(|slot| slot.generation == generation && generation % 2 == 1)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn xenora_abi_version() -> u32 {
|
||||
XENORA_ABI_VERSION
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `out_session` must be null or valid for one aligned `u64` write.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_create(abi_version: u32, out_session: *mut u64) -> i32 {
|
||||
guarded(|| {
|
||||
if out_session.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
if abi_version != XENORA_ABI_VERSION {
|
||||
return XENORA_VERSION_MISMATCH;
|
||||
}
|
||||
let Ok(mut slots) = SESSIONS.lock() else {
|
||||
return XENORA_INTERNAL_ERROR;
|
||||
};
|
||||
let index = match slots.iter().position(|slot| slot.generation % 2 == 0) {
|
||||
Some(index) => index,
|
||||
None if slots.len() < MAX_SESSIONS => {
|
||||
slots.push(Slot { generation: 0 });
|
||||
slots.len() - 1
|
||||
}
|
||||
None => return XENORA_LIMIT_EXCEEDED,
|
||||
};
|
||||
let slot = &mut slots[index];
|
||||
// ponytail: a slot retires after 2^31 reuses instead of wrapping its generation.
|
||||
let Some(generation) = slot.generation.checked_add(1) else {
|
||||
return XENORA_LIMIT_EXCEEDED;
|
||||
};
|
||||
slot.generation = generation;
|
||||
// SAFETY: checked non-null above; the caller guarantees validity.
|
||||
unsafe { out_session.write((u64::from(generation) << 32) | index as u64) };
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn xenora_session_destroy(session: u64) -> i32 {
|
||||
guarded(|| {
|
||||
let Ok(mut slots) = SESSIONS.lock() else {
|
||||
return XENORA_INTERNAL_ERROR;
|
||||
};
|
||||
if !is_live(&slots, session) {
|
||||
return XENORA_INVALID_HANDLE;
|
||||
}
|
||||
slots[split(session).0].generation += 1;
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Each output pointer must be null or valid for one aligned `u32` write.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_inspect_trusted_fixture(
|
||||
session: u64,
|
||||
out_section_count: *mut u32,
|
||||
out_entry_rva: *mut u32,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if out_section_count.is_null() || out_entry_rva.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
match SESSIONS.lock() {
|
||||
Ok(slots) if is_live(&slots, session) => {}
|
||||
Ok(_) => return XENORA_INVALID_HANDLE,
|
||||
Err(_) => return XENORA_INTERNAL_ERROR,
|
||||
}
|
||||
let Ok(pe) = ParsedPe::parse(FIXTURE) else {
|
||||
return XENORA_PE_ERROR;
|
||||
};
|
||||
// SAFETY: both checked non-null above; the caller guarantees validity.
|
||||
unsafe {
|
||||
out_section_count.write(u32::from(pe.number_of_sections));
|
||||
out_entry_rva.write(pe.entry_point_rva);
|
||||
}
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
// The trusted fixture's contract, as checked by the CLI runner (crates/cli/src/runner.rs).
|
||||
// ponytail: duplicated from the runner so the CLI stays untouched; extract a shared
|
||||
// fixture-run function into a library when a third caller appears.
|
||||
const IMAGE_BASE: u64 = 0x1_5000_0000;
|
||||
const TICKET_ADDRESS: u64 = IMAGE_BASE + 0x3000;
|
||||
const TICKET: u64 = 17;
|
||||
const DRAW_RESULT: u64 = 0x42;
|
||||
const ENTRY_STEPS: usize = 100;
|
||||
/// `x9-constant-ps.s` exports (1.0, 0, 0, 1.0) to mrt0; in an RGBA8 target that is opaque red.
|
||||
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
fn draw() -> Result<Vec<u8>, String> {
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)
|
||||
.map_err(|e| format!("shader translation: {e}"))?;
|
||||
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
|
||||
let pixels = gpu
|
||||
.render_rgba8(
|
||||
&shader.msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[3.0, -1.0, 0.5, 1.0],
|
||||
[-1.0, 3.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
[
|
||||
XENORA_FIXTURE_FRAME_WIDTH as usize,
|
||||
XENORA_FIXTURE_FRAME_HEIGHT as usize,
|
||||
],
|
||||
[19, 43, 93, 251],
|
||||
)
|
||||
.map_err(|e| format!("Metal render: {e}"))?;
|
||||
if pixels != EXPECTED_PIXEL.repeat(FRAME_BYTES / 4) {
|
||||
return Err("read-back frame differs from the fixture shader's output".into());
|
||||
}
|
||||
Ok(pixels)
|
||||
}
|
||||
|
||||
/// Run the embedded fixture and return its verified frame.
|
||||
fn run_fixture() -> Result<Vec<u8>, String> {
|
||||
let frame = Arc::new(Mutex::new(None));
|
||||
let draw_frame = Arc::clone(&frame);
|
||||
let mut imports = ImportRegistry::new();
|
||||
imports.register("xenora.dll", "fixture_draw", move |args, _, memory| {
|
||||
let fault = ExitReason::IllegalInstruction(0xff);
|
||||
let ticket = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let mut slot = draw_frame.lock().map_err(|_| fault)?;
|
||||
if slot.is_some()
|
||||
|| ticket != TICKET_ADDRESS
|
||||
|| memory.read_u64(ticket).map_err(ExitReason::MemoryFault)? != TICKET
|
||||
{
|
||||
return Err(fault);
|
||||
}
|
||||
let result = draw();
|
||||
let ok = result.is_ok();
|
||||
*slot = Some(result);
|
||||
if ok { Ok(DRAW_RESULT) } else { Err(fault) }
|
||||
});
|
||||
let startup = run_synthetic_startup(
|
||||
FIXTURE,
|
||||
StartupLayout {
|
||||
image_base: IMAGE_BASE,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
},
|
||||
imports,
|
||||
ENTRY_STEPS,
|
||||
)
|
||||
.map_err(|e| format!("startup: {e}"))?;
|
||||
let drawn = frame.lock().map_err(|_| "frame lock poisoned")?.take();
|
||||
if let Some(Err(e)) = drawn {
|
||||
return Err(e);
|
||||
}
|
||||
let execution = &startup.execution;
|
||||
if execution.exit_reason != ExitReason::Halt
|
||||
|| startup.relocations.applied_dir64 != 4
|
||||
|| startup.bound_imports != 1
|
||||
|| startup.tls_callbacks != 1
|
||||
|| execution.final_state.get(Register::Rax) != DRAW_RESULT
|
||||
{
|
||||
return Err(format!(
|
||||
"unexpected guest result: {:?}",
|
||||
execution.exit_reason
|
||||
));
|
||||
}
|
||||
drawn.ok_or_else(|| String::from("guest halted without a draw"))?
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `out_rgba` must be null or valid for `capacity` byte writes; each `u32` output
|
||||
/// must be null or valid for one aligned write.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_run_trusted_fixture(
|
||||
session: u64,
|
||||
out_rgba: *mut u8,
|
||||
capacity: u64,
|
||||
out_width: *mut u32,
|
||||
out_height: *mut u32,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if out_rgba.is_null() || out_width.is_null() || out_height.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
match SESSIONS.lock() {
|
||||
Ok(slots) if is_live(&slots, session) => {}
|
||||
Ok(_) => return XENORA_INVALID_HANDLE,
|
||||
Err(_) => return XENORA_INTERNAL_ERROR,
|
||||
}
|
||||
if capacity < FRAME_BYTES as u64 {
|
||||
return XENORA_BUFFER_TOO_SMALL;
|
||||
}
|
||||
let Ok(pixels) = run_fixture() else {
|
||||
return XENORA_EXECUTION_FAILED;
|
||||
};
|
||||
// SAFETY: non-null and at least FRAME_BYTES long, both checked above.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(pixels.as_ptr(), out_rgba, FRAME_BYTES);
|
||||
out_width.write(XENORA_FIXTURE_FRAME_WIDTH);
|
||||
out_height.write(XENORA_FIXTURE_FRAME_HEIGHT);
|
||||
}
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
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::*;
|
||||
use std::ptr::null_mut;
|
||||
|
||||
/// The session table is process-global, so tests that fill or count it run one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn serial() -> std::sync::MutexGuard<'static, ()> {
|
||||
SERIAL
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
fn create() -> u64 {
|
||||
let mut handle = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(handle, 0);
|
||||
handle
|
||||
}
|
||||
|
||||
fn inspect(handle: u64) -> (i32, u32, u32) {
|
||||
let (mut sections, mut entry) = (u32::MAX, u32::MAX);
|
||||
let status =
|
||||
unsafe { xenora_session_inspect_trusted_fixture(handle, &mut sections, &mut entry) };
|
||||
(status, sections, entry)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_and_rust_constants_agree() {
|
||||
let header = include_str!("../include/xenora.h");
|
||||
assert!(header.contains(&format!("#define XENORA_ABI_VERSION {XENORA_ABI_VERSION}u")));
|
||||
for (name, value) in [
|
||||
("XENORA_OK", XENORA_OK),
|
||||
("XENORA_INVALID_ARGUMENT", XENORA_INVALID_ARGUMENT),
|
||||
("XENORA_INVALID_HANDLE", XENORA_INVALID_HANDLE),
|
||||
("XENORA_VERSION_MISMATCH", XENORA_VERSION_MISMATCH),
|
||||
("XENORA_INTERNAL_ERROR", XENORA_INTERNAL_ERROR),
|
||||
("XENORA_PE_ERROR", XENORA_PE_ERROR),
|
||||
("XENORA_LIMIT_EXCEEDED", XENORA_LIMIT_EXCEEDED),
|
||||
("XENORA_BUFFER_TOO_SMALL", XENORA_BUFFER_TOO_SMALL),
|
||||
("XENORA_EXECUTION_FAILED", XENORA_EXECUTION_FAILED),
|
||||
] {
|
||||
assert!(header.contains(&format!("{name} = {value},")), "{name}");
|
||||
}
|
||||
assert!(header.contains(&format!(
|
||||
"XENORA_FIXTURE_FRAME_WIDTH {XENORA_FIXTURE_FRAME_WIDTH}u"
|
||||
)));
|
||||
assert!(header.contains(&format!(
|
||||
"XENORA_FIXTURE_FRAME_HEIGHT {XENORA_FIXTURE_FRAME_HEIGHT}u"
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_inspects_the_trusted_fixture() {
|
||||
let _serial = serial();
|
||||
let handle = create();
|
||||
// Independent expectation: read straight from the fixture's COFF and optional headers.
|
||||
let lfanew = u32::from_le_bytes(FIXTURE[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let sections = u16::from_le_bytes(FIXTURE[lfanew + 6..lfanew + 8].try_into().unwrap());
|
||||
let entry = u32::from_le_bytes(FIXTURE[lfanew + 40..lfanew + 44].try_into().unwrap());
|
||||
assert_eq!(inspect(handle), (XENORA_OK, u32::from(sections), entry));
|
||||
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_mismatch_and_null_outputs_are_rejected() {
|
||||
let _serial = serial();
|
||||
let mut handle = 7;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(2, &mut handle) },
|
||||
XENORA_VERSION_MISMATCH
|
||||
);
|
||||
assert_eq!(handle, 7, "output untouched on failure");
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(1, null_mut()) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
let live = create();
|
||||
let mut x = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_inspect_trusted_fixture(live, null_mut(), &mut x) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
xenora_session_destroy(live);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_stale_and_double_destroyed_handles_are_rejected() {
|
||||
let _serial = serial();
|
||||
for bogus in [0, u64::MAX, 0xFFFF_FFFF, 1 << 32] {
|
||||
assert_eq!(
|
||||
xenora_session_destroy(bogus),
|
||||
XENORA_INVALID_HANDLE,
|
||||
"{bogus:#x}"
|
||||
);
|
||||
assert_eq!(inspect(bogus), (XENORA_INVALID_HANDLE, u32::MAX, u32::MAX));
|
||||
}
|
||||
let handle = create();
|
||||
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(handle), XENORA_INVALID_HANDLE);
|
||||
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
|
||||
// Reusing the slot must not revive the old handle.
|
||||
let reused: Vec<u64> = (0..MAX_SESSIONS).map(|_| create()).collect();
|
||||
assert!(!reused.contains(&handle));
|
||||
assert_eq!(inspect(handle).0, XENORA_INVALID_HANDLE);
|
||||
for h in reused {
|
||||
xenora_session_destroy(h);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_and_concurrent_lifecycles_do_not_leak_slots() {
|
||||
let _serial = serial();
|
||||
let threads: Vec<_> = (0..8)
|
||||
.map(|_| {
|
||||
std::thread::spawn(|| {
|
||||
for _ in 0..500 {
|
||||
let mut handle = 0;
|
||||
let status = unsafe { xenora_session_create(1, &mut handle) };
|
||||
assert_eq!(status, XENORA_OK);
|
||||
assert_eq!(inspect(handle).0, XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(handle), XENORA_OK);
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for t in threads {
|
||||
t.join().unwrap();
|
||||
}
|
||||
assert!(SESSIONS.lock().unwrap().len() <= MAX_SESSIONS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panics_do_not_cross_the_boundary() {
|
||||
assert_eq!(guarded(|| panic!("injected")), XENORA_INTERNAL_ERROR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixture_run_rejects_bad_arguments_before_executing() {
|
||||
let _serial = serial();
|
||||
let handle = create();
|
||||
let (mut buf, mut w, mut h) = ([0u8; 48], 0u32, 0u32);
|
||||
let run = |session, buf: *mut u8, cap, w: *mut u32, h: *mut u32| unsafe {
|
||||
xenora_session_run_trusted_fixture(session, buf, cap, w, h)
|
||||
};
|
||||
assert_eq!(
|
||||
run(handle, buf.as_mut_ptr(), 47, &mut w, &mut h),
|
||||
XENORA_BUFFER_TOO_SMALL
|
||||
);
|
||||
assert_eq!(
|
||||
run(handle, null_mut(), 48, &mut w, &mut h),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
run(handle, buf.as_mut_ptr(), 48, null_mut(), &mut h),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
xenora_session_destroy(handle);
|
||||
assert_eq!(
|
||||
run(handle, buf.as_mut_ptr(), 48, &mut w, &mut h),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
assert_eq!((w, h), (0, 0), "outputs untouched on failure");
|
||||
assert!(buf.iter().all(|&b| b == 0));
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Runs the trusted fixture through the C interface on a native Metal device.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
|
||||
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
|
||||
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
#[test]
|
||||
fn guest_fixture_frame_reaches_the_caller_through_metal() {
|
||||
for run in 0..3 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
|
||||
let status = unsafe {
|
||||
xenora_session_run_trusted_fixture(
|
||||
session,
|
||||
rgba.as_mut_ptr(),
|
||||
64,
|
||||
&mut width,
|
||||
&mut height,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, XENORA_OK, "run {run}");
|
||||
assert_eq!((width, height), (4, 3));
|
||||
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
|
||||
assert!(
|
||||
rgba[48..].iter().all(|&b| b == 0),
|
||||
"no write past the frame"
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ VARIANTS = (
|
||||
("V_ADD_NC_U32", "ENC_VOP3"),
|
||||
("S_ENDPGM", "ENC_SOPP"),
|
||||
("S_MOV_B32", "ENC_SOP1"),
|
||||
("S_CMP_EQ_U32", "ENC_SOPC"),
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP"),
|
||||
("S_CBRANCH_EXECZ", "ENC_SOPP"),
|
||||
("S_CBRANCH_VCCZ", "ENC_SOPP"),
|
||||
|
||||
@@ -38,8 +38,52 @@ FORM_KEYS = {
|
||||
}
|
||||
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
|
||||
|
||||
OPERATIONS = {"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor"}
|
||||
LOGICAL = {"and", "or", "xor"}
|
||||
OPERATIONS = {
|
||||
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
|
||||
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
|
||||
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
|
||||
"compare": "Compare",
|
||||
"not": "Not", "brev": "ReverseBits", "bcnt0": "CountZeros", "bcnt1": "CountOnes",
|
||||
"ff0": "FindFirstZero", "ff1": "FindFirstOne", "flbit": "FindLastBit",
|
||||
"sext": "SignExtend", "abs": "Absolute",
|
||||
}
|
||||
# Unary operations read one source; they need an operand rule of the unary kind.
|
||||
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
|
||||
# Sign extension reads only the low source_bits of S0 (required for sext only).
|
||||
SOURCE_BITS_KEY = "source_bits"
|
||||
SOURCE_BITS = {8, 16}
|
||||
# Compares take a relation (S0 on the left) and set SCC to whether it holds.
|
||||
RELATION_KEY = "relation"
|
||||
RELATIONS = {
|
||||
"eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual",
|
||||
"lt": "Less", "le": "LessOrEqual",
|
||||
}
|
||||
# (relation, signedness) -> primitive. Equality does not depend on signedness,
|
||||
# so both declared signednesses of EQ and LG share one primitive.
|
||||
COMPARE_PRIMITIVES = {
|
||||
("eq", "signed"): "eq_b32", ("eq", "unsigned"): "eq_b32",
|
||||
("lg", "signed"): "ne_b32", ("lg", "unsigned"): "ne_b32",
|
||||
("gt", "signed"): "gt_i32", ("gt", "unsigned"): "gt_u32",
|
||||
("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32",
|
||||
("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32",
|
||||
("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32",
|
||||
}
|
||||
# Logical operations take untyped bits; arithmetic ones never do. Shifts take
|
||||
# the signedness their primitive names, and their S1 is an unsigned count.
|
||||
LOGICAL = {
|
||||
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
|
||||
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1",
|
||||
}
|
||||
ARITHMETIC = {"add", "sub"}
|
||||
SHIFTS = {"lshl", "lshr", "ashr"}
|
||||
# XML number formats a source may have for each declared signedness.
|
||||
SOURCE_FORMATS = {
|
||||
"signed": {"FMT_NUM_I32"},
|
||||
"unsigned": {"FMT_NUM_U32"},
|
||||
"bitwise": {"FMT_NUM_U32", "FMT_NUM_B32"},
|
||||
}
|
||||
# Optional keys: required exactly when the condition holds.
|
||||
SHIFT_KEY = "shift_count_bits"
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
SCC = {
|
||||
@@ -48,6 +92,7 @@ SCC = {
|
||||
"borrow": "Borrow",
|
||||
"signed_overflow": "SignedOverflow",
|
||||
"nonzero": "Nonzero",
|
||||
"relation": "Relation",
|
||||
}
|
||||
MASK = {"unchanged": "Unchanged"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
@@ -86,6 +131,24 @@ PRIMITIVES = {
|
||||
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
|
||||
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
|
||||
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
|
||||
("andn2", "bitwise"): ("nonzero", "andn2_nonzero_b32", False),
|
||||
("orn2", "bitwise"): ("nonzero", "orn2_nonzero_b32", False),
|
||||
("nand", "bitwise"): ("nonzero", "nand_nonzero_b32", False),
|
||||
("nor", "bitwise"): ("nonzero", "nor_nonzero_b32", False),
|
||||
("xnor", "bitwise"): ("nonzero", "xnor_nonzero_b32", False),
|
||||
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
|
||||
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
|
||||
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
|
||||
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
|
||||
("brev", "bitwise"): ("unchanged", "brev_b32", False),
|
||||
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
|
||||
("bcnt1", "bitwise"): ("nonzero", "bcnt1_nonzero_b32", False),
|
||||
("ff0", "bitwise"): ("unchanged", "ff0_b32", False),
|
||||
("ff1", "bitwise"): ("unchanged", "ff1_b32", False),
|
||||
("flbit", "bitwise"): ("unchanged", "flbit_b32", False),
|
||||
("flbit", "signed"): ("unchanged", "flbit_i32", False),
|
||||
("sext", "signed"): ("unchanged", "sext_i32", False),
|
||||
("abs", "signed"): ("nonzero", "abs_nonzero_i32", False),
|
||||
}
|
||||
|
||||
# Operand rules the decoder implements, each exactly once. A registry rule must
|
||||
@@ -109,6 +172,35 @@ OPERAND_RULES = {
|
||||
},
|
||||
# Every one of these is rejected by the decoder's SOP2 operand checks.
|
||||
"unsupported": UNSUPPORTED_COMBOS,
|
||||
"kind": "alu",
|
||||
},
|
||||
"sopc_scalar": {
|
||||
"rust": "SopcScalar",
|
||||
"enum": "ScalarCompareOp",
|
||||
"shape": {
|
||||
"family": "SOPC",
|
||||
"src": [
|
||||
{"field": "SSRC0", "class": "scalar_source"},
|
||||
{"field": "SSRC1", "class": "scalar_source"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# SOPC has no destination field; the decoder rejects these sources.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if not combo.startswith("dst_")},
|
||||
"kind": "compare",
|
||||
},
|
||||
"sop1_sgpr": {
|
||||
"rust": "Sop1Sgpr",
|
||||
"enum": "ScalarUnaryOp",
|
||||
"shape": {
|
||||
"family": "SOP1",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [{"field": "SSRC0", "class": "scalar_source"}],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# One source, so two literals cannot occur; the rest are rejected.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
|
||||
"kind": "unary",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -204,18 +296,34 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output")
|
||||
if rule is None:
|
||||
return
|
||||
fields = [(rule["dst"]["field"], False)] + [(src["field"], True) for src in rule["src"]]
|
||||
if not isinstance(rule.get("src"), list) or not all(
|
||||
isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"]
|
||||
) or ("dst" in rule and not (isinstance(rule["dst"], dict) and "field" in rule["dst"])):
|
||||
return # the rule check already reported the malformed shape
|
||||
fields = [(rule["dst"]["field"], False)] if "dst" in rule else []
|
||||
fields += [(src["field"], True) for src in rule["src"]]
|
||||
shift = form["operation"] in SHIFTS and len(rule["src"]) > 1
|
||||
count_field = rule["src"][1]["field"] if shift else None
|
||||
for field, is_source in fields:
|
||||
if field not in operands:
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
if size != form["width"]:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {form['width']}")
|
||||
bits = form.get(SOURCE_BITS_KEY) if is_source else None
|
||||
expected = bits if type(bits) is int else form["width"]
|
||||
if size != expected:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
|
||||
if (is_input, is_output) != (is_source, not is_source):
|
||||
errors.append(f"{label}: {field} direction disagrees with the XML")
|
||||
signed_format = data_format.startswith("FMT_NUM_I")
|
||||
if is_source and signed_format != (form["signedness"] == "signed"):
|
||||
if field == count_field:
|
||||
if data_format != "FMT_NUM_U32":
|
||||
errors.append(
|
||||
f"{label}: shift count {field} has XML format {data_format}, not FMT_NUM_U32"
|
||||
)
|
||||
elif type(bits) is int:
|
||||
if data_format != f"FMT_NUM_I{bits}":
|
||||
errors.append(f"{label}: {field} has XML format {data_format}, not FMT_NUM_I{bits}")
|
||||
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
|
||||
)
|
||||
@@ -261,7 +369,7 @@ def validate(registry, snapshot):
|
||||
for index, form in enumerate(forms):
|
||||
label = form.get("name", f"form #{index}")
|
||||
missing = sorted(FORM_KEYS - set(form))
|
||||
extra = sorted(set(form) - FORM_KEYS)
|
||||
extra = sorted(set(form) - FORM_KEYS - {SHIFT_KEY, RELATION_KEY, SOURCE_BITS_KEY})
|
||||
if missing:
|
||||
errors.append(f"{label}: incomplete, missing {missing}")
|
||||
if extra:
|
||||
@@ -294,11 +402,41 @@ def validate(registry, snapshot):
|
||||
if value in seen[key]:
|
||||
errors.append(f"{label}: duplicate {key} {value}")
|
||||
seen[key].add(value)
|
||||
if (form["signedness"] == "bitwise") != (form["operation"] in LOGICAL):
|
||||
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
|
||||
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
|
||||
):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
|
||||
)
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
if form["operation"] in SHIFTS:
|
||||
bits = form.get(SHIFT_KEY)
|
||||
if type(bits) is not int or not 0 < bits < 32 or (1 << bits) != form["width"]:
|
||||
errors.append(
|
||||
f"{label}: {SHIFT_KEY} must be log2 of the width ({form['width']}), got {bits!r}"
|
||||
)
|
||||
elif SHIFT_KEY in form:
|
||||
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
|
||||
if form["operation"] == "sext":
|
||||
bits = form.get(SOURCE_BITS_KEY)
|
||||
if type(bits) is not int or bits not in SOURCE_BITS:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} must be one of {sorted(SOURCE_BITS)}, got {bits!r}")
|
||||
elif SOURCE_BITS_KEY in form:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} on a non-sext operation")
|
||||
if form["operation"] == "compare":
|
||||
relation = form.get(RELATION_KEY)
|
||||
if not isinstance(relation, str) or relation not in RELATIONS:
|
||||
errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}")
|
||||
elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES:
|
||||
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
|
||||
if form["scc"] != "relation":
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)")
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = ("relation", None, False)
|
||||
else:
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
if primitive is None:
|
||||
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
|
||||
else:
|
||||
@@ -315,6 +453,11 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
|
||||
elif rule.get("family") != form["family"]:
|
||||
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
|
||||
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
|
||||
"compare" if form["operation"] == "compare"
|
||||
else "unary" if form["operation"] in UNARY else "alu"
|
||||
):
|
||||
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
|
||||
_check_spec(label, form["spec"], documents, errors)
|
||||
verify = form["verify"]
|
||||
if not verify:
|
||||
@@ -360,6 +503,7 @@ def render(registry, snapshot):
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, Wave,",
|
||||
"};",
|
||||
"use crate::CompareRelation;",
|
||||
"",
|
||||
"/// Registry schema of the generated tables.",
|
||||
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
|
||||
@@ -396,6 +540,10 @@ def render(registry, snapshot):
|
||||
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
|
||||
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
|
||||
f" width: {form['width']},",
|
||||
f" shift_count_bits: {form.get(SHIFT_KEY, 0)},",
|
||||
f" source_bits: {form.get(SOURCE_BITS_KEY, form['width'])},",
|
||||
" relation: "
|
||||
+ (f"Some(CompareRelation::{RELATIONS[form[RELATION_KEY]]})," if RELATION_KEY in form else "None,"),
|
||||
f" scc: SccEffect::{SCC[form['scc']]},",
|
||||
f" vcc: MaskEffect::{MASK[form['vcc']]},",
|
||||
f" exec: MaskEffect::{MASK[form['exec']]},",
|
||||
@@ -411,9 +559,21 @@ def render(registry, snapshot):
|
||||
|
||||
def _render_enum(rule_name, forms, snapshot, positions):
|
||||
enum = OPERAND_RULES[rule_name]["enum"]
|
||||
kind = OPERAND_RULES[rule_name]["kind"]
|
||||
table = re.sub(r"(?<!^)(?=[A-Z])", "_", enum).upper() + "_BY_OPCODE"
|
||||
family = forms[0]["family"]
|
||||
encoding = snapshot["encodings"][_family_encoding(family)]
|
||||
mask = encoding["identifier_mask"]
|
||||
(offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"]
|
||||
op_mask = ((1 << size) - 1) << offset
|
||||
fixed_mask = mask & ~op_mask
|
||||
fixed_bits = encoding["identifiers"][0] & fixed_mask
|
||||
# Every identifier of the family must share the fixed bits, or the split
|
||||
# into an encoding test plus an OP match would change which words match.
|
||||
if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]) or (
|
||||
mask & op_mask != op_mask
|
||||
):
|
||||
raise ValueError(f"{family}: identifiers do not split into fixed bits and OP")
|
||||
out = [
|
||||
"",
|
||||
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
|
||||
@@ -422,14 +582,26 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
what = f"compare {form[RELATION_KEY]}" if kind == "compare" else form["operation"]
|
||||
out += [
|
||||
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
|
||||
f"{form['signedness']} {form['operation']}{carry}, SCC = {form['scc']}.",
|
||||
f"{form['signedness']} {what}{carry}, SCC = {form['scc']}.",
|
||||
f" {form['variant']},",
|
||||
]
|
||||
by_opcode = {form["opcode"]: form["variant"] for form in forms}
|
||||
out += [
|
||||
"}",
|
||||
"",
|
||||
f"/// {enum} by {family} OP field value; `None` for undeclared opcodes.",
|
||||
f"const {table}: [Option<{enum}>; {1 << size}] = [",
|
||||
]
|
||||
out += [
|
||||
f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None,"
|
||||
for opcode in range(1 << size)
|
||||
]
|
||||
out += [
|
||||
"];",
|
||||
"",
|
||||
f"impl {enum} {{",
|
||||
" /// Every operation, in registry order.",
|
||||
f" pub const ALL: [Self; {len(forms)}] = [",
|
||||
@@ -438,15 +610,13 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
out += [
|
||||
" ];",
|
||||
"",
|
||||
f" /// Selects the operation from a first instruction word (mask 0x{mask:09_x}).",
|
||||
f" /// Selects the operation from a first instruction word: the {family} encoding",
|
||||
f" /// bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits {offset}-{offset + size - 1}).",
|
||||
" pub const fn from_word(word: u32) -> Option<Self> {",
|
||||
f" match word & 0x{mask:09_x} {{",
|
||||
]
|
||||
for form in sorted(forms, key=lambda item: item["opcode"]):
|
||||
out.append(f" 0x{_identifier(encoding, form['opcode']):09_x} => Some(Self::{form['variant']}),")
|
||||
out += [
|
||||
" _ => None,",
|
||||
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
|
||||
" return None;",
|
||||
" }",
|
||||
f" {table}[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
|
||||
" }",
|
||||
"",
|
||||
" /// Lower-case mnemonic.",
|
||||
@@ -457,6 +627,78 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The validated registry row.",
|
||||
" pub fn semantics(self) -> &'static FormSemantics {",
|
||||
" &FORMS[match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
|
||||
out += [
|
||||
" }]",
|
||||
" }",
|
||||
]
|
||||
if kind == "unary":
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation writes SCC.",
|
||||
" pub const fn writes_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
|
||||
" /// unchanged).",
|
||||
" pub const fn evaluate(self, src: u32) -> (u32, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, _ = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if form["operation"] == "sext":
|
||||
value = f"primitive::{function}(src, {form[SOURCE_BITS_KEY]})"
|
||||
else:
|
||||
value = f"primitive::{function}(src)"
|
||||
if form["scc"] == "unchanged":
|
||||
out.append(f" Self::{form['variant']} => ({value}, None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{form['variant']} => {{",
|
||||
f" let (value, scc) = {value};",
|
||||
" (value, Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "compare":
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with S0 on the left.",
|
||||
" pub const fn relation(self) -> CompareRelation {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The new SCC: whether the relation holds for S0 and S1.",
|
||||
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
|
||||
out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation reads SCC as a carry-in or borrow-in.",
|
||||
" pub const fn reads_scc(self) -> bool {",
|
||||
@@ -470,15 +712,6 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The validated registry row.",
|
||||
" pub fn semantics(self) -> &'static FormSemantics {",
|
||||
" &FORMS[match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
|
||||
out += [
|
||||
" }]",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and the new SCC, with `carry_in` the SCC read by forms that",
|
||||
" /// consume it (ignored by the others).",
|
||||
" pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {",
|
||||
@@ -489,6 +722,9 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
if takes_carry:
|
||||
argument = "carry_in" if form["carry_in"] == "scc" else "false"
|
||||
call = f"primitive::{function}(src0, src1, {argument})"
|
||||
elif form["operation"] in SHIFTS:
|
||||
mask = (1 << form[SHIFT_KEY]) - 1
|
||||
call = f"primitive::{function}(src0, src1 & 0x{mask:x})"
|
||||
else:
|
||||
call = f"primitive::{function}(src0, src1)"
|
||||
out.append(f" Self::{form['variant']} => {call},")
|
||||
|
||||
@@ -230,3 +230,648 @@ wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- Stage C: further SOP2 logical and shift forms (#215) ----
|
||||
# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode).
|
||||
|
||||
[[form]]
|
||||
name = "S_ANDN2_B32"
|
||||
family = "SOP2"
|
||||
opcode = 20
|
||||
variant = "Andn2B32"
|
||||
operation = "andn2"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 103 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ORN2_B32"
|
||||
family = "SOP2"
|
||||
opcode = 22
|
||||
variant = "Orn2B32"
|
||||
operation = "orn2"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 103 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_NAND_B32"
|
||||
family = "SOP2"
|
||||
opcode = 24
|
||||
variant = "NandB32"
|
||||
operation = "nand"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_NOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 26
|
||||
variant = "NorB32"
|
||||
operation = "nor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_XNOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 28
|
||||
variant = "XnorB32"
|
||||
operation = "xnor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL_B32"
|
||||
family = "SOP2"
|
||||
opcode = 30
|
||||
variant = "LshlB32"
|
||||
operation = "lshl"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 32
|
||||
variant = "LshrB32"
|
||||
operation = "lshr"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ASHR_I32"
|
||||
family = "SOP2"
|
||||
opcode = 34
|
||||
variant = "AshrI32"
|
||||
operation = "ashr"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- Stage D: SOPC 32-bit integer compares (#215) ----
|
||||
# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4).
|
||||
|
||||
[operand_rules.sopc_scalar]
|
||||
family = "SOPC"
|
||||
src = [
|
||||
{ field = "SSRC0", class = "scalar_source" },
|
||||
{ field = "SSRC1", class = "scalar_source" },
|
||||
]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
|
||||
"src_special", "two_literals",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_EQ_I32"
|
||||
family = "SOPC"
|
||||
opcode = 0
|
||||
variant = "CmpEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LG_I32"
|
||||
family = "SOPC"
|
||||
opcode = 1
|
||||
variant = "CmpLgI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GT_I32"
|
||||
family = "SOPC"
|
||||
opcode = 2
|
||||
variant = "CmpGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GE_I32"
|
||||
family = "SOPC"
|
||||
opcode = 3
|
||||
variant = "CmpGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LT_I32"
|
||||
family = "SOPC"
|
||||
opcode = 4
|
||||
variant = "CmpLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LE_I32"
|
||||
family = "SOPC"
|
||||
opcode = 5
|
||||
variant = "CmpLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_EQ_U32"
|
||||
family = "SOPC"
|
||||
opcode = 6
|
||||
variant = "CmpEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LG_U32"
|
||||
family = "SOPC"
|
||||
opcode = 7
|
||||
variant = "CmpLgU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GT_U32"
|
||||
family = "SOPC"
|
||||
opcode = 8
|
||||
variant = "CmpGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GE_U32"
|
||||
family = "SOPC"
|
||||
opcode = 9
|
||||
variant = "CmpGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LT_U32"
|
||||
family = "SOPC"
|
||||
opcode = 10
|
||||
variant = "CmpLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LE_U32"
|
||||
family = "SOPC"
|
||||
opcode = 11
|
||||
variant = "CmpLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- SOP1 32-bit unary integer forms (#215) ----
|
||||
# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged.
|
||||
# Searches that find nothing return -1 (guide 12.3).
|
||||
|
||||
[operand_rules.sop1_sgpr]
|
||||
family = "SOP1"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [{ field = "SSRC0", class = "scalar_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "S_NOT_B32"
|
||||
family = "SOP1"
|
||||
opcode = 7
|
||||
variant = "NotB32"
|
||||
operation = "not"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BREV_B32"
|
||||
family = "SOP1"
|
||||
opcode = 11
|
||||
variant = "BrevB32"
|
||||
operation = "brev"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BCNT0_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 13
|
||||
variant = "Bcnt0I32B32"
|
||||
operation = "bcnt0"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BCNT1_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 15
|
||||
variant = "Bcnt1I32B32"
|
||||
operation = "bcnt1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FF0_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 17
|
||||
variant = "Ff0I32B32"
|
||||
operation = "ff0"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FF1_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 19
|
||||
variant = "Ff1I32B32"
|
||||
operation = "ff1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FLBIT_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 21
|
||||
variant = "FlbitI32B32"
|
||||
operation = "flbit"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FLBIT_I32"
|
||||
family = "SOP1"
|
||||
opcode = 23
|
||||
variant = "FlbitI32"
|
||||
operation = "flbit"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SEXT_I32_I8"
|
||||
family = "SOP1"
|
||||
opcode = 25
|
||||
variant = "SextI32I8"
|
||||
operation = "sext"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_bits = 8
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SEXT_I32_I16"
|
||||
family = "SOP1"
|
||||
opcode = 26
|
||||
variant = "SextI32I16"
|
||||
operation = "sext"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_bits = 16
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ABS_I32"
|
||||
family = "SOP1"
|
||||
opcode = 52
|
||||
variant = "AbsI32"
|
||||
operation = "abs"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+20
-11
@@ -12,13 +12,13 @@ mod rdna2_meta;
|
||||
mod semantics_gen;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32,
|
||||
V_CMP_GE_U32, V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32,
|
||||
V_CMP_LT_U32, V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32,
|
||||
V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::ScalarAluOp;
|
||||
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
@@ -209,6 +209,13 @@ pub enum Instruction {
|
||||
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
|
||||
ScalarMoveB32 { dst: u8, src: ScalarSource },
|
||||
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
|
||||
/// for some operations, SCC.
|
||||
ScalarUnary {
|
||||
op: ScalarUnaryOp,
|
||||
dst: u8,
|
||||
src: ScalarSource,
|
||||
},
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
|
||||
ScalarAlu {
|
||||
op: ScalarAluOp,
|
||||
@@ -216,8 +223,9 @@ pub enum Instruction {
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// SOPC 32-bit equality comparison writing SCC.
|
||||
ScalarCompareEqU32 {
|
||||
/// SOPC 32-bit integer compare writing only SCC.
|
||||
ScalarCompare {
|
||||
op: ScalarCompareOp,
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
@@ -306,8 +314,9 @@ impl Instruction {
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.mnemonic(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
@@ -370,13 +379,13 @@ impl fmt::Display for Instruction {
|
||||
| Self::VectorMulF32 { dst, src0, src1 } => {
|
||||
write!(formatter, " v{dst}, v{src0}, v{src1}")
|
||||
}
|
||||
Self::ScalarMoveB32 { dst, src } => {
|
||||
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
|
||||
write!(formatter, " {}, {src}", ScalarDestination(dst))
|
||||
}
|
||||
Self::ScalarAlu {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
|
||||
@@ -49,3 +49,168 @@ pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a ^ b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `a & !b` and whether the result is nonzero.
|
||||
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a & !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `a | !b` and whether the result is nonzero.
|
||||
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a | !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a & b)` and whether the result is nonzero.
|
||||
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a & b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a | b)` and whether the result is nonzero.
|
||||
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a | b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
|
||||
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a ^ b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a << count` and whether the result is nonzero. The caller masks the count
|
||||
/// to the declared count width, so `count` is below 32.
|
||||
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a << count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a >> count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = ((a as i32) >> count) as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a == b` on the raw bits; signedness does not matter for equality.
|
||||
pub const fn eq_b32(a: u32, b: u32) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// `a != b` on the raw bits (the guide's LG, "less or greater").
|
||||
pub const fn ne_b32(a: u32, b: u32) -> bool {
|
||||
a != b
|
||||
}
|
||||
|
||||
/// Two's-complement `a > b`.
|
||||
pub const fn gt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) > (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a >= b`.
|
||||
pub const fn ge_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) >= (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a < b`.
|
||||
pub const fn lt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) < (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a <= b`.
|
||||
pub const fn le_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) <= (b as i32)
|
||||
}
|
||||
|
||||
/// Unsigned `a > b`.
|
||||
pub const fn gt_u32(a: u32, b: u32) -> bool {
|
||||
a > b
|
||||
}
|
||||
|
||||
/// Unsigned `a >= b`.
|
||||
pub const fn ge_u32(a: u32, b: u32) -> bool {
|
||||
a >= b
|
||||
}
|
||||
|
||||
/// Unsigned `a < b`.
|
||||
pub const fn lt_u32(a: u32, b: u32) -> bool {
|
||||
a < b
|
||||
}
|
||||
|
||||
/// Unsigned `a <= b`.
|
||||
pub const fn le_u32(a: u32, b: u32) -> bool {
|
||||
a <= b
|
||||
}
|
||||
|
||||
/// `!a` and whether the result is nonzero.
|
||||
pub const fn not_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = !a;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a` with bit `i` moved to bit `31 - i`.
|
||||
pub const fn brev_b32(a: u32) -> u32 {
|
||||
a.reverse_bits()
|
||||
}
|
||||
|
||||
/// Number of zero bits and whether that count is nonzero.
|
||||
pub const fn bcnt0_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_zeros();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Number of one bits and whether that count is nonzero.
|
||||
pub const fn bcnt1_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_ones();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Index of the lowest zero bit, or `0xffffffff` (-1) when every bit is one.
|
||||
pub const fn ff0_b32(a: u32) -> u32 {
|
||||
if a == u32::MAX {
|
||||
u32::MAX
|
||||
} else {
|
||||
a.trailing_ones()
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of the lowest one bit, or `0xffffffff` (-1) when every bit is zero.
|
||||
pub const fn ff1_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.trailing_zeros() }
|
||||
}
|
||||
|
||||
/// Zeros above the highest one bit, or `0xffffffff` (-1) when `a` is zero.
|
||||
pub const fn flbit_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.leading_zeros() }
|
||||
}
|
||||
|
||||
/// Bits above the highest bit that differs from the sign bit, or `0xffffffff`
|
||||
/// (-1) when every bit equals the sign bit (`a` is 0 or -1).
|
||||
pub const fn flbit_i32(a: u32) -> u32 {
|
||||
let differing = if a >> 31 == 0 { a } else { !a };
|
||||
if differing == 0 {
|
||||
u32::MAX
|
||||
} else {
|
||||
differing.leading_zeros()
|
||||
}
|
||||
}
|
||||
|
||||
/// The low `bits` of `a` sign-extended to 32 bits; `bits` is 8 or 16.
|
||||
pub const fn sext_i32(a: u32, bits: u32) -> u32 {
|
||||
let shift = 32 - bits;
|
||||
(((a << shift) as i32) >> shift) as u32
|
||||
}
|
||||
|
||||
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
|
||||
let value = (a as i32).wrapping_abs() as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
@@ -45,11 +45,6 @@ pub const S_MOV_B32: Opcode = Opcode {
|
||||
bits: 0xbe800300,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_SCC0: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf840000,
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! The reference interpreter (`crates/ref`) and the independent interpreter
|
||||
//! (`tests/validation/independent_ref.rs`) must not use this module.
|
||||
|
||||
use crate::CompareRelation;
|
||||
use crate::meta::EncodingFamily;
|
||||
|
||||
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
|
||||
@@ -30,6 +31,43 @@ pub enum Operation {
|
||||
Or,
|
||||
/// Bitwise exclusive OR.
|
||||
Xor,
|
||||
/// Bitwise AND with the complement of S1.
|
||||
AndNot,
|
||||
/// Bitwise OR with the complement of S1.
|
||||
OrNot,
|
||||
/// Complement of bitwise AND.
|
||||
Nand,
|
||||
/// Complement of bitwise OR.
|
||||
Nor,
|
||||
/// Complement of bitwise exclusive OR.
|
||||
Xnor,
|
||||
/// Shift S0 left by the masked count in S1, filling with zeros.
|
||||
ShiftLeft,
|
||||
/// Shift S0 right by the masked count in S1, filling with zeros.
|
||||
LogicalShiftRight,
|
||||
/// Shift S0 right by the masked count in S1, filling with its sign bit.
|
||||
ArithmeticShiftRight,
|
||||
/// Compare S0 with S1 under the form's relation; writes only SCC.
|
||||
Compare,
|
||||
/// Bitwise complement of S0.
|
||||
Not,
|
||||
/// S0 with its bit order reversed.
|
||||
ReverseBits,
|
||||
/// Number of zero bits in S0.
|
||||
CountZeros,
|
||||
/// Number of one bits in S0.
|
||||
CountOnes,
|
||||
/// Index of the lowest zero bit of S0, or -1 when there is none.
|
||||
FindFirstZero,
|
||||
/// Index of the lowest one bit of S0, or -1 when there is none.
|
||||
FindFirstOne,
|
||||
/// Unsigned: count of zeros above the highest one bit; signed: count of bits
|
||||
/// above the highest bit that differs from the sign bit. -1 when none.
|
||||
FindLastBit,
|
||||
/// Sign-extend the low `source_bits` of S0 to 32 bits.
|
||||
SignExtend,
|
||||
/// Two's-complement absolute value; the most negative value maps to itself.
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
@@ -65,6 +103,8 @@ pub enum SccEffect {
|
||||
SignedOverflow,
|
||||
/// The result is not zero.
|
||||
Nonzero,
|
||||
/// The compare's relation holds for S0 and S1.
|
||||
Relation,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
@@ -89,6 +129,12 @@ pub enum OperandRule {
|
||||
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
|
||||
/// or one literal word. Everything else is rejected as unsupported.
|
||||
Sop2Sgpr,
|
||||
/// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline
|
||||
/// integers -16..64 or one literal word). Everything else is rejected.
|
||||
SopcScalar,
|
||||
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
|
||||
/// a literal word. Everything else is rejected as unsupported.
|
||||
Sop1Sgpr,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
@@ -120,7 +166,7 @@ pub struct SpecRef {
|
||||
pub document: Document,
|
||||
/// Section number, for example `"12.1"`.
|
||||
pub section: &'static str,
|
||||
/// Page in the document, 0 when not paginated.
|
||||
/// Page in the document, or 0 when the page has not been recorded.
|
||||
pub page: u16,
|
||||
}
|
||||
|
||||
@@ -141,6 +187,12 @@ pub struct FormSemantics {
|
||||
pub carry_in: CarryIn,
|
||||
/// Operand and result width in bits.
|
||||
pub width: u8,
|
||||
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
|
||||
pub shift_count_bits: u8,
|
||||
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
|
||||
pub source_bits: u8,
|
||||
/// The relation tested by compares (S0 on the left); `None` otherwise.
|
||||
pub relation: Option<CompareRelation>,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
|
||||
+1513
-30
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,8 @@
|
||||
//! Ties the generated semantic registry tables to the independent XML metadata table.
|
||||
|
||||
use xenora_isa::ScalarAluOp;
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
|
||||
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
@@ -18,43 +18,70 @@ fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
assert_eq!(ScalarAluOp::ALL.len(), FORMS.len());
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
}
|
||||
/// Every word of `family` that the XML metadata identifies selects an operation
|
||||
/// exactly when the registry declares that form, and no 32-bit word of another
|
||||
/// family selects one.
|
||||
fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) {
|
||||
let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect();
|
||||
let mut selected = 0;
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family == EncodingFamily::Sop2)
|
||||
{
|
||||
let word = meta.bits as u32;
|
||||
match ScalarAluOp::from_word(word) {
|
||||
Some(op) => {
|
||||
assert_eq!(op.semantics().name, meta.name);
|
||||
for meta in META_FORMS.iter().filter(|form| form.family == family) {
|
||||
match select(meta.bits as u32) {
|
||||
Some(name) => {
|
||||
assert_eq!(name, meta.name);
|
||||
selected += 1;
|
||||
}
|
||||
None => assert!(
|
||||
FORMS.iter().all(|row| row.name != meta.name),
|
||||
declared.iter().all(|row| row.name != meta.name),
|
||||
"{} is declared but not dispatched",
|
||||
meta.name
|
||||
),
|
||||
}
|
||||
}
|
||||
assert_eq!(selected, FORMS.len());
|
||||
// Other encodings never reach the SOP2 dispatch.
|
||||
assert_eq!(selected, declared.len());
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != EncodingFamily::Sop2 && form.bytes == 4)
|
||||
.filter(|form| form.family != family && form.bytes == 4)
|
||||
{
|
||||
assert_eq!(
|
||||
ScalarAluOp::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
assert_eq!(select(meta.bits as u32), None, "{}", meta.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop2);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
|
||||
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
|
||||
for op in ScalarCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopc);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sopc, |word| {
|
||||
ScalarCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
for op in ScalarUnaryOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop1);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
|
||||
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
|
||||
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
+234
-52
@@ -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)?;
|
||||
|
||||
+90
-66
@@ -226,57 +226,102 @@ impl GuestMemory {
|
||||
true
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, src.len()) {
|
||||
if !region.permissions.write {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "write",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + src.len()].copy_from_slice(src);
|
||||
return Ok(());
|
||||
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
|
||||
///
|
||||
/// An access may span adjacent regions, as it would span adjacent pages, but every
|
||||
/// byte must be mapped and every region must grant `required` (`None` bypasses
|
||||
/// permission checks for the loader). The whole range is checked before any byte
|
||||
/// is copied, so a failed access never partially reads or writes.
|
||||
fn resolve(
|
||||
&self,
|
||||
address: u64,
|
||||
len: usize,
|
||||
required: Option<&'static str>,
|
||||
) -> Result<Vec<(usize, usize, usize)>, MemoryError> {
|
||||
let end = address
|
||||
.checked_add(len as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if len == 0 {
|
||||
return if self.regions.iter().any(|r| r.contains(address, 0)) {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
};
|
||||
}
|
||||
let mut pieces = Vec::new();
|
||||
let mut cursor = address;
|
||||
for (index, region) in self.regions.iter().enumerate() {
|
||||
let region_end = region.base + region.data.len() as u64;
|
||||
if region_end <= cursor {
|
||||
continue;
|
||||
}
|
||||
if region.base > cursor {
|
||||
break;
|
||||
}
|
||||
let permitted = match required {
|
||||
None => true,
|
||||
Some("read") => region.permissions.read,
|
||||
Some("write") => region.permissions.write,
|
||||
Some(_) => region.permissions.execute,
|
||||
};
|
||||
if let (false, Some(required)) = (permitted, required) {
|
||||
return Err(MemoryError::PermissionViolation { address, required });
|
||||
}
|
||||
let take = (end.min(region_end) - cursor) as usize;
|
||||
pieces.push((index, (cursor - region.base) as usize, take));
|
||||
cursor += take as u64;
|
||||
if cursor == end {
|
||||
return Ok(pieces);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
}
|
||||
|
||||
fn read_checked(
|
||||
&self,
|
||||
address: u64,
|
||||
dst: &mut [u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, dst.len(), required)? {
|
||||
dst[done..done + take]
|
||||
.copy_from_slice(&self.regions[index].data[offset..offset + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_checked(
|
||||
&mut self,
|
||||
address: u64,
|
||||
src: &[u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, src.len(), required)? {
|
||||
self.regions[index].data[offset..offset + take]
|
||||
.copy_from_slice(&src[done..done + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
self.write_checked(address, src, Some("write"))
|
||||
}
|
||||
|
||||
/// Read raw bytes from guest memory at the specified address, checking permissions.
|
||||
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, dst.len()) {
|
||||
if !region.permissions.read {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "read",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
dst.copy_from_slice(®ion.data[offset..offset + dst.len()]);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.read_checked(address, dst, Some("read"))
|
||||
}
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 1) {
|
||||
if !region.permissions.execute {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
return Ok(region.data[offset]);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 1];
|
||||
self.read_checked(address, &mut buf, Some("execute"))?;
|
||||
Ok(buf[0])
|
||||
}
|
||||
|
||||
/// Read a 64-bit integer (little endian) from guest memory.
|
||||
@@ -288,14 +333,9 @@ impl GuestMemory {
|
||||
|
||||
/// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase).
|
||||
pub fn read_u64_bypass(&self, address: u64) -> Result<u64, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
let buf: [u8; 8] = region.data[offset..offset + 8].try_into().unwrap();
|
||||
return Ok(u64::from_le_bytes(buf));
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 8];
|
||||
self.read_checked(address, &mut buf, None)?;
|
||||
Ok(u64::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Write a 64-bit integer (little endian) to guest memory.
|
||||
@@ -305,15 +345,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 8].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a 32-bit integer (little endian) from guest memory.
|
||||
@@ -330,15 +362,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 4) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 4].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a single byte from guest memory.
|
||||
|
||||
+18
-1
@@ -94,6 +94,9 @@ pub const PE32_PLUS_MAGIC: u16 = 0x020B;
|
||||
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
|
||||
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
|
||||
const SECTION_HEADER_SIZE: usize = 40;
|
||||
/// Host memory budget for all mapped sections of one image. This is a loader policy
|
||||
/// limit, not a property of the PE format.
|
||||
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
fn read_u16(bytes: &[u8], at: usize) -> u16 {
|
||||
u16::from_le_bytes([bytes[at], bytes[at + 1]])
|
||||
@@ -170,7 +173,10 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
|
||||
for sec_bytes in bytes[section_table_offset..table_end].chunks_exact(SECTION_HEADER_SIZE) {
|
||||
for sec_bytes in bytes[section_table_offset..table_end]
|
||||
.as_chunks::<SECTION_HEADER_SIZE>()
|
||||
.0
|
||||
{
|
||||
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
|
||||
let name_raw = &sec_bytes[0..8];
|
||||
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
|
||||
@@ -270,6 +276,17 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
|
||||
// Each section becomes a zero-filled host allocation, so bound the total before
|
||||
// allocating anything. Sections may not overlap, so the sum is the mapped size.
|
||||
let mapped: u64 = self
|
||||
.sections
|
||||
.iter()
|
||||
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
|
||||
.sum();
|
||||
if mapped > MAX_MAPPED_IMAGE_BYTES {
|
||||
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
|
||||
}
|
||||
|
||||
let mut memory = GuestMemory::new();
|
||||
|
||||
for sec in &self.sections {
|
||||
|
||||
@@ -117,7 +117,10 @@ pub fn apply_relocations(
|
||||
size: reloc_size,
|
||||
})?;
|
||||
|
||||
if reloc_file_offset + (reloc_size as usize) > bytes.len() {
|
||||
if reloc_file_offset
|
||||
.checked_add(reloc_size as usize)
|
||||
.is_none_or(|end| end > bytes.len())
|
||||
{
|
||||
return Err(RelocationError::DirectoryOutOfBounds {
|
||||
rva: reloc_rva,
|
||||
size: reloc_size,
|
||||
@@ -127,13 +130,20 @@ pub fn apply_relocations(
|
||||
let mut read_bytes = 0usize;
|
||||
let max_read = reloc_size as usize;
|
||||
|
||||
while read_bytes + 8 <= max_read {
|
||||
while read_bytes < max_read {
|
||||
// A partial block header after the last block is malformed, not padding.
|
||||
if max_read - read_bytes < 8 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: reloc_file_offset + read_bytes,
|
||||
});
|
||||
}
|
||||
let block_start = reloc_file_offset + read_bytes;
|
||||
let page_rva = u32::from_le_bytes(bytes[block_start..block_start + 4].try_into().unwrap());
|
||||
let block_size =
|
||||
u32::from_le_bytes(bytes[block_start + 4..block_start + 8].try_into().unwrap());
|
||||
|
||||
if block_size < 8 {
|
||||
// A block is an 8-byte header followed by whole 2-byte entries.
|
||||
if block_size < 8 || block_size % 2 != 0 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: block_start,
|
||||
});
|
||||
@@ -166,6 +176,15 @@ pub fn apply_relocations(
|
||||
let target_rva = page_rva
|
||||
.checked_add(offset_in_page)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
// The 8-byte target must lie inside the image, not in other mapped memory.
|
||||
if target_rva
|
||||
.checked_add(8)
|
||||
.is_none_or(|end| end > pe.size_of_image)
|
||||
{
|
||||
return Err(RelocationError::TargetOutOfBounds {
|
||||
target_va: loaded_base.wrapping_add(u64::from(target_rva)),
|
||||
});
|
||||
}
|
||||
let target_va = loaded_base
|
||||
.checked_add(target_rva as u64)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
@@ -213,8 +232,8 @@ fn find_reloc_directory(
|
||||
return Ok(None);
|
||||
}
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let opt_offset = e_lfanew + 24;
|
||||
let coff_offset = e_lfanew + 4;
|
||||
let opt_offset = coff_offset + 20;
|
||||
if bytes.len() < coff_offset + 18 {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -224,10 +243,19 @@ fn find_reloc_directory(
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
|
||||
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header)
|
||||
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header).
|
||||
// It exists only when NumberOfRvaAndSizes (offset 108) covers index 5.
|
||||
if size_of_opt < 160 || bytes.len() < opt_offset + 160 {
|
||||
return Ok(None);
|
||||
}
|
||||
let number_of_rva_and_sizes = u32::from_le_bytes(
|
||||
bytes[opt_offset + 108..opt_offset + 112]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
if number_of_rva_and_sizes < 6 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let reloc_rva = u32::from_le_bytes(
|
||||
bytes[opt_offset + 152..opt_offset + 156]
|
||||
|
||||
+136
-16
@@ -11,6 +11,14 @@ use crate::{
|
||||
|
||||
const STACK_SIZE: usize = 64 * 1024;
|
||||
const JIT_CAPACITY: usize = 1024 * 1024;
|
||||
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
|
||||
const TEB_OFFSET: u64 = 0x10000;
|
||||
const TEB_SIZE: usize = 0x2000;
|
||||
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
|
||||
const TEB_STACK_BASE: u64 = 0x08;
|
||||
const TEB_STACK_LIMIT: u64 = 0x10;
|
||||
const TEB_SELF: u64 = 0x30;
|
||||
const TEB_TLS_POINTER: u64 = 0x58;
|
||||
|
||||
/// Guest addresses reserved by the fixture harness.
|
||||
pub struct StartupLayout {
|
||||
@@ -79,6 +87,8 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)
|
||||
.into());
|
||||
}
|
||||
// Reject an impossible layout before parsing or mapping anything.
|
||||
let (stack_base, teb_base) = layout_regions(&layout)?;
|
||||
let pe = ParsedPe::parse(bytes)?;
|
||||
observe(StartupEvent::Parsed {
|
||||
sections: pe.sections.len(),
|
||||
@@ -112,24 +122,9 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)?;
|
||||
}
|
||||
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
|
||||
// Allocate and initialize Win64 TEB (Thread Environment Block)
|
||||
// Layout in TEB:
|
||||
// +0x08: StackBase (highest address)
|
||||
// +0x10: StackLimit (lowest address)
|
||||
// +0x30: Self pointer (TEB linear address)
|
||||
// +0x58: ThreadLocalStoragePointer
|
||||
let teb_base = layout.tls_base.saturating_add(0x10000);
|
||||
memory.map_region(teb_base, 0x2000, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + 0x08, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + 0x10, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x30, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x58, layout.tls_base)?;
|
||||
map_teb(memory, teb_base, &layout, stack_base)?;
|
||||
|
||||
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
|
||||
engine.set_import_registry(imports);
|
||||
@@ -171,3 +166,128 @@ pub fn run_synthetic_startup_with_observer(
|
||||
dbt_metrics: engine.metrics,
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate the harness layout and return `(stack_base, teb_base)`.
|
||||
///
|
||||
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
|
||||
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
|
||||
/// space and must not overlap each other.
|
||||
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_base = layout
|
||||
.tls_base
|
||||
.checked_add(TEB_OFFSET)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_end = teb_base
|
||||
.checked_add(TEB_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if teb_base < layout.stack_top && stack_base < teb_end {
|
||||
return Err(MemoryError::OverlappingRegion {
|
||||
base: teb_base,
|
||||
size: TEB_SIZE as u64,
|
||||
});
|
||||
}
|
||||
Ok((stack_base, teb_base))
|
||||
}
|
||||
|
||||
/// Map the Win64 TEB and write the fields the harness provides.
|
||||
fn map_teb(
|
||||
memory: &mut crate::GuestMemory,
|
||||
teb_base: u64,
|
||||
layout: &StartupLayout,
|
||||
stack_base: u64,
|
||||
) -> Result<(), MemoryError> {
|
||||
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::GuestMemory;
|
||||
|
||||
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top,
|
||||
tls_base,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_layout_places_stack_and_teb() {
|
||||
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
|
||||
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_below_zero_is_rejected() {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x8000, 0x3_0000_0000)),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_address_overflow_is_rejected_not_saturated() {
|
||||
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x2_0001_0000, tls_base)),
|
||||
Err(MemoryError::Overflow),
|
||||
"tls_base {tls_base:#x}"
|
||||
);
|
||||
}
|
||||
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
|
||||
// representable, and GuestMemory could not map that range either.
|
||||
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_overlapping_stack_is_rejected() {
|
||||
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
|
||||
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
|
||||
assert!(matches!(
|
||||
layout_regions(&collide),
|
||||
Err(MemoryError::OverlappingRegion { .. })
|
||||
));
|
||||
// Directly above the stack is fine.
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_layout_fails_before_parsing() {
|
||||
// Empty bytes would fail PE parsing; the layout error must come first.
|
||||
let err = run_synthetic_startup(
|
||||
&[],
|
||||
layout(0x2_0001_0000, u64::MAX),
|
||||
ImportRegistry::new(),
|
||||
1,
|
||||
)
|
||||
.err()
|
||||
.expect("startup must fail");
|
||||
assert_eq!(
|
||||
err.downcast_ref::<MemoryError>(),
|
||||
Some(&MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_fields_are_at_win64_offsets() {
|
||||
let l = layout(0x2_0001_0000, 0x3_0000_0000);
|
||||
let (stack_base, teb) = layout_regions(&l).unwrap();
|
||||
let mut memory = GuestMemory::new();
|
||||
map_teb(&mut memory, teb, &l, stack_base).unwrap();
|
||||
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
|
||||
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
|
||||
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest memory boundary regression tests (#82).
|
||||
//!
|
||||
//! Expected behavior follows x86-64 data access rules: an access is valid when
|
||||
//! every byte it touches is mapped with the required permission, whether or not
|
||||
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
|
||||
//! nothing.
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
const A: u64 = 0x10_0000;
|
||||
|
||||
fn two_regions(first: P, second: P) -> GuestMemory {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, first, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region_with_data(A + 0x1000, 0x1000, second, &[0x22; 0x1000])
|
||||
.unwrap();
|
||||
m
|
||||
}
|
||||
|
||||
fn bypass_bytes(m: &GuestMemory, at: u64) -> u64 {
|
||||
m.read_u64_bypass(at).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_are_enforced_per_access_kind() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::NO_ACCESS).unwrap();
|
||||
m.map_region(A + 0x1000, 0x1000, P::READ_ONLY).unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
let violation = |address, required| MemoryError::PermissionViolation { address, required };
|
||||
assert_eq!(m.read_u8(A), Err(violation(A, "read")));
|
||||
assert_eq!(
|
||||
m.write_u8(A + 0x1000, 1),
|
||||
Err(violation(A + 0x1000, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(A + 0x2000),
|
||||
Err(violation(A + 0x2000, "execute"))
|
||||
);
|
||||
assert!(m.read_u8(A + 0x1000).is_ok());
|
||||
assert!(m.write_u8(A + 0x2000, 1).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_end_is_exclusive() {
|
||||
let m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
assert!(m.read_u32(A + 0xFFC).is_ok());
|
||||
assert!(matches!(
|
||||
m.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::PermissionViolation { .. })
|
||||
));
|
||||
let mut lone = GuestMemory::new();
|
||||
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
|
||||
assert_eq!(
|
||||
lone.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFD))
|
||||
);
|
||||
assert_eq!(
|
||||
lone.read_u8(A - 1),
|
||||
Err(MemoryError::UnmappedAddress(A - 1))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unaligned_accesses_succeed_inside_a_region() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 3, 0x0102_0304_0506_0708).unwrap();
|
||||
assert_eq!(m.read_u64(A + 3), Ok(0x0102_0304_0506_0708));
|
||||
assert_eq!(m.read_u16(A + 3), Ok(0x0708));
|
||||
assert_eq!(m.read_u32(A + 5), Ok(0x0304_0506));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn access_spanning_adjacent_permitted_regions_succeeds() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 0xFFC, 0x8877_6655_4433_2211).unwrap();
|
||||
assert_eq!(m.read_u64(A + 0xFFC), Ok(0x8877_6655_4433_2211));
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x4433_2211)); // low half in the first region
|
||||
assert_eq!(m.read_u32(A + 0x1000), Ok(0x8877_6655)); // high half in the second
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_gap_fails_without_partial_write() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, P::READ_WRITE, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFC))
|
||||
);
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_forbidden_region_fails_atomically() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_ONLY);
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 0xFFC,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
assert_eq!(bypass_bytes(&m, A + 0xFFC), 0x2222_2222_1111_1111);
|
||||
|
||||
let m = two_regions(P::READ_EXECUTE, P::READ_WRITE);
|
||||
assert!(m.read_u64(A + 0xFFC).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0xFFF).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0x1000).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_bypass_ignores_permissions_but_not_mapping() {
|
||||
let mut m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
m.write_u64_bypass(A + 0xFFC, 0x0A0B_0C0D_0E0F_1011)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64_bypass(A + 0xFFC), Ok(0x0A0B_0C0D_0E0F_1011));
|
||||
m.write_u32_bypass(A, 7).unwrap();
|
||||
assert_eq!(m.read_u32(A), Ok(7));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(A + 0x1FFC, 0),
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address_overflow_is_reported() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX - 0xFFF, 0xFFF, P::READ_WRITE)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64(u64::MAX - 3), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(u64::MAX - 3, 0),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
m.map_region(u64::MAX, 2, P::READ_WRITE),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_mappings_are_rejected_and_adjacent_ones_accepted() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.map_region(A + 0xFFF, 0x10, P::READ_WRITE),
|
||||
Err(MemoryError::OverlappingRegion {
|
||||
base: A + 0xFFF,
|
||||
size: 0x10
|
||||
})
|
||||
);
|
||||
assert!(m.map_region(A + 0x1000, 0x10, P::READ_WRITE).is_ok());
|
||||
assert!(m.map_region(A - 0x10, 0x10, P::READ_WRITE).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! PE image mapping budget tests (#80).
|
||||
//!
|
||||
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
|
||||
//! backs it with zero-filled host memory, so a small file can request a large
|
||||
//! allocation. The loader's documented budget is 256 MiB per image.
|
||||
|
||||
use xenora_loader::{MemoryError, ParsedPe, PeError};
|
||||
|
||||
const BUDGET: u32 = 256 * 1024 * 1024;
|
||||
|
||||
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
|
||||
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
|
||||
fn build(bss_sizes: &[u32]) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x400];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x44;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&(1 + bss_sizes.len() as u16).to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&112u16.to_le_bytes());
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
|
||||
|
||||
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
|
||||
let h = opt + 112 + i * 40;
|
||||
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
};
|
||||
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
|
||||
let mut va = 0x2000u32;
|
||||
for (i, &size) in bss_sizes.iter().enumerate() {
|
||||
section(i + 1, va, size, 0, 0xC000_0080);
|
||||
va += size;
|
||||
}
|
||||
pe
|
||||
}
|
||||
|
||||
fn over_budget() -> PeError {
|
||||
PeError::SectionMappingError(MemoryError::AllocationFailed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_image_loads() {
|
||||
let bytes = build(&[0x1000]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_exactly_at_budget_loads() {
|
||||
let bytes = build(&[BUDGET - 0x200]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_byte_over_budget_is_rejected() {
|
||||
let bytes = build(&[BUDGET - 0x1FF]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_counts_all_sections_together() {
|
||||
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
|
||||
let bytes = build(&[128 << 20; 3]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
|
||||
let bytes = build(&[0xF000_0000]);
|
||||
assert_eq!(bytes.len(), 0x400);
|
||||
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_fixture_is_within_budget() {
|
||||
let path = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/trusted-runner.exe"
|
||||
);
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Base relocation regression tests (#81).
|
||||
//!
|
||||
//! Images are built byte by byte from the PE/COFF layout: data directory 5
|
||||
//! (Base Relocation Table) at optional-header offset 152, and blocks made of a
|
||||
//! 4-byte page RVA, a 4-byte block size and 2-byte entries whose top 4 bits
|
||||
//! are the type (0 = ABSOLUTE padding, 3 = HIGHLOW, 10 = DIR64).
|
||||
|
||||
use xenora_loader::{GuestMemory, ParsedPe, RelocationError, apply_relocations};
|
||||
|
||||
const PREFERRED: u64 = 0x1_4000_0000;
|
||||
const RELOC_FILE: usize = 0x400;
|
||||
|
||||
/// .text at RVA 0x1000 (file 0x200) holding two pointers, .reloc at RVA 0x2000 (file 0x400).
|
||||
/// `NumberOfRvaAndSizes` and the relocation table bytes are parameters.
|
||||
fn build(rva_and_sizes: u32, table: &[u8], dir_size: u32) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x600];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x44;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&2u16.to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&rva_and_sizes.to_le_bytes());
|
||||
pe[opt + 152..opt + 156].copy_from_slice(&0x2000u32.to_le_bytes());
|
||||
pe[opt + 156..opt + 160].copy_from_slice(&dir_size.to_le_bytes());
|
||||
|
||||
let sections: [(&[u8], u32, u32, u32, u32); 2] = [
|
||||
(b".text", 0x1000, 0x200, 0x200, 0x6000_0020),
|
||||
// .reloc fills the image up to SizeOfImage (0x3000).
|
||||
(b".reloc", 0x2000, 0x1000, RELOC_FILE as u32, 0x4200_0040),
|
||||
];
|
||||
for (i, (name, va, vsize, raw, flags)) in sections.into_iter().enumerate() {
|
||||
let h = opt + 240 + i * 40;
|
||||
pe[h..h + name.len()].copy_from_slice(name);
|
||||
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
}
|
||||
|
||||
// Two absolute pointers into the image, at RVAs 0x1010 and 0x1018.
|
||||
pe[0x210..0x218].copy_from_slice(&(PREFERRED + 0x1100).to_le_bytes());
|
||||
pe[0x218..0x220].copy_from_slice(&(PREFERRED + 0x2000).to_le_bytes());
|
||||
pe[RELOC_FILE..RELOC_FILE + table.len()].copy_from_slice(table);
|
||||
pe
|
||||
}
|
||||
|
||||
fn block(page_rva: u32, entries: &[u16]) -> Vec<u8> {
|
||||
let mut b = page_rva.to_le_bytes().to_vec();
|
||||
b.extend_from_slice(&(8 + 2 * entries.len() as u32).to_le_bytes());
|
||||
for e in entries {
|
||||
b.extend_from_slice(&e.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// DIR64 at 0x1010 and 0x1018, plus one ABSOLUTE padding entry to keep 4-byte alignment.
|
||||
fn standard_table() -> Vec<u8> {
|
||||
block(0x1000, &[0xA010, 0xA018, 0x0000])
|
||||
}
|
||||
|
||||
fn load(bytes: &[u8], base: u64) -> (ParsedPe, GuestMemory) {
|
||||
let pe = ParsedPe::parse(bytes).expect("parse");
|
||||
let mut memory = GuestMemory::new();
|
||||
for s in &pe.sections {
|
||||
let raw = &bytes[s.raw_data_ptr as usize..(s.raw_data_ptr + s.raw_data_size) as usize];
|
||||
memory
|
||||
.map_region_with_data(
|
||||
base + u64::from(s.virtual_address),
|
||||
0x200,
|
||||
s.permissions,
|
||||
raw,
|
||||
)
|
||||
.expect("map");
|
||||
}
|
||||
(pe, memory)
|
||||
}
|
||||
|
||||
fn relocate(
|
||||
bytes: &[u8],
|
||||
base: u64,
|
||||
) -> (
|
||||
Result<xenora_loader::RelocationReport, RelocationError>,
|
||||
GuestMemory,
|
||||
) {
|
||||
let (pe, mut memory) = load(bytes, base);
|
||||
let result = apply_relocations(&pe, bytes, base, &mut memory);
|
||||
(result, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_rebase_adds_delta_to_each_dir64_target() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
let report = result.expect("relocate");
|
||||
assert_eq!(report.delta, 0x1_0000_0000);
|
||||
assert_eq!(report.applied_dir64, 2);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.total_entries, 3);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_rebase_subtracts_delta() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = 0x1000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.expect("relocate").delta,
|
||||
base as i64 - PREFERRED as i64
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_base_leaves_targets_unchanged() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, memory) = relocate(&bytes, PREFERRED);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(PREFERRED + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_beyond_declared_count_is_ignored() {
|
||||
// NumberOfRvaAndSizes = 5 means directory index 5 does not exist.
|
||||
let table = standard_table();
|
||||
let bytes = build(5, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_type_is_rejected() {
|
||||
let table = block(0x1000, &[0x3010, 0x0000]); // HIGHLOW is not a PE32+ fixup here
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::UnsupportedRelocationType(3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_block_sizes_are_rejected() {
|
||||
let base = PREFERRED + 0x1000;
|
||||
for size in [0u32, 4, 7, 11] {
|
||||
let mut table = 0x1000u32.to_le_bytes().to_vec();
|
||||
table.extend_from_slice(&size.to_le_bytes());
|
||||
table.extend_from_slice(&[0; 8]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader { offset: RELOC_FILE },
|
||||
"block size {size}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_larger_than_directory_is_rejected() {
|
||||
let table = standard_table(); // 14 bytes
|
||||
let bytes = build(16, &table, 12);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::BlockSizeOutOfBounds {
|
||||
block_size: 14,
|
||||
max_size: 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_partial_block_header_is_rejected() {
|
||||
let mut table = block(0x1000, &[0xA010, 0x0000]);
|
||||
table.extend_from_slice(&[0; 4]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader {
|
||||
offset: RELOC_FILE + 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_past_end_of_file_is_rejected() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, 0x300); // .reloc raw data starts at 0x400 in a 0x600-byte file
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::DirectoryOutOfBounds {
|
||||
rva: 0x2000,
|
||||
size: 0x300
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_outside_image_is_rejected_even_if_mapped() {
|
||||
// SizeOfImage is 0x3000; RVA 0x3000 is past the image but mapped by another region.
|
||||
let table = block(0x3000, &[0xA000, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1000;
|
||||
let (pe, mut memory) = load(&bytes, base);
|
||||
let rw = pe.sections[1].permissions;
|
||||
memory
|
||||
.map_region(base + 0x3000, 0x1000, rw)
|
||||
.expect("adjacent mapping");
|
||||
memory.write_u64_bypass(base + 0x3000, 0x55).unwrap();
|
||||
let result = apply_relocations(&pe, &bytes, base, &mut memory);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::TargetOutOfBounds {
|
||||
target_va: base + 0x3000
|
||||
}
|
||||
);
|
||||
assert_eq!(memory.read_u64_bypass(base + 0x3000).unwrap(), 0x55);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_rva_at_top_of_address_space_is_rejected() {
|
||||
let table = block(0xFFFF_F000, &[0xAFFC, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RelocationError::TargetOutOfBounds { .. })
|
||||
));
|
||||
}
|
||||
+159
-5
@@ -51,13 +51,19 @@ pub enum Op {
|
||||
Move(u8, Source),
|
||||
Add(u8, u8, u8),
|
||||
ScalarMove(u8, Source),
|
||||
/// SOP1 unary operation writing an SGPR (s0-s105), and SCC for some.
|
||||
ScalarUnary(ScalarUnary, u8, Source),
|
||||
/// VOP1 move of a normal SGPR or `vcc_lo` (106) into a VGPR.
|
||||
MoveScalar(u8, u8),
|
||||
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
|
||||
Compare(Comparison, CompareSource, u8),
|
||||
/// SOP2 operation writing an SGPR and SCC.
|
||||
Scalar(ScalarAlu, u8, Source, Source),
|
||||
/// SOPC `s_cmp_eq_{i32,u32}` (opcodes 0 and 6, identical per guide 12.4).
|
||||
CompareEqual(Source, Source),
|
||||
/// The other SOPC 32-bit integer compares (opcodes 1-5 and 7-11), writing
|
||||
/// only SCC: LG, GT, GE, LT, LE, signed for 1-5, unsigned for 7-11.
|
||||
ScalarCompare(Comparison, Source, Source),
|
||||
Branch {
|
||||
target: usize,
|
||||
condition: BranchCondition,
|
||||
@@ -129,7 +135,7 @@ pub enum BranchCondition {
|
||||
///
|
||||
/// AMD RDNA 2 XML descriptions: additions store the carry-out in SCC,
|
||||
/// subtractions the borrow; ADDC/SUBB add or subtract SCC; bitwise
|
||||
/// operations set SCC iff the result is nonzero.
|
||||
/// operations and shifts set SCC iff the result is nonzero.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarAlu {
|
||||
Add,
|
||||
@@ -142,6 +148,50 @@ pub enum ScalarAlu {
|
||||
And,
|
||||
Or,
|
||||
Xor,
|
||||
/// RDNA 2 ISA guide 12.1: D = S0 & ~S1, SCC = (D != 0).
|
||||
AndNot,
|
||||
/// D = S0 | ~S1, SCC = (D != 0).
|
||||
OrNot,
|
||||
/// D = ~(S0 & S1), SCC = (D != 0).
|
||||
Nand,
|
||||
/// D = ~(S0 | S1), SCC = (D != 0).
|
||||
Nor,
|
||||
/// D = ~(S0 ^ S1), SCC = (D != 0).
|
||||
Xnor,
|
||||
/// D = S0 << S1[4:0], SCC = (D != 0).
|
||||
ShiftLeft,
|
||||
/// D = S0 >> S1[4:0] (logical), SCC = (D != 0).
|
||||
ShiftRight,
|
||||
/// D = signext(S0) >> S1[4:0], SCC = (D != 0).
|
||||
ArithmeticShiftRight,
|
||||
}
|
||||
|
||||
/// SOP1 unary operations decoded by the reference interpreter (RDNA 2 ISA
|
||||
/// guide 12.3; SCC per Tables 12 and 14).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarUnary {
|
||||
/// D = ~S0, SCC = (D != 0).
|
||||
Not,
|
||||
/// D[31:0] = S0[0:31].
|
||||
ReverseBits,
|
||||
/// D = number of zero bits, SCC = (D != 0).
|
||||
CountZeros,
|
||||
/// D = number of one bits, SCC = (D != 0).
|
||||
CountOnes,
|
||||
/// D = index of the lowest zero bit, or -1.
|
||||
FindFirstZero,
|
||||
/// D = index of the lowest one bit, or -1.
|
||||
FindFirstOne,
|
||||
/// D = number of zeros above the highest one bit, or -1 for 0.
|
||||
FindLastBit,
|
||||
/// D = number of leading bits equal to the sign bit, or -1 for 0 and -1.
|
||||
FindLastSignBit,
|
||||
/// D = signext(S0[7:0]).
|
||||
SignExtendByte,
|
||||
/// D = signext(S0[15:0]).
|
||||
SignExtendShort,
|
||||
/// D = |S0| (0x80000000 stays), SCC = (D != 0).
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// VOP2 operations decoded by the reference interpreter.
|
||||
@@ -277,17 +327,55 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
let (source, length) = decode_scalar(*source, tail, offset)?;
|
||||
(Op::ScalarMove(destination & 0x7f, source), length)
|
||||
}
|
||||
[left, right, 6, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
|
||||
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST in 16-22 (s0-s105
|
||||
// only), OP in 8-15.
|
||||
[
|
||||
source,
|
||||
op @ (7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52),
|
||||
destination @ 0x80..=0xe9,
|
||||
0xbe,
|
||||
tail @ ..,
|
||||
] => {
|
||||
let kind = match op {
|
||||
7 => ScalarUnary::Not,
|
||||
11 => ScalarUnary::ReverseBits,
|
||||
13 => ScalarUnary::CountZeros,
|
||||
15 => ScalarUnary::CountOnes,
|
||||
17 => ScalarUnary::FindFirstZero,
|
||||
19 => ScalarUnary::FindFirstOne,
|
||||
21 => ScalarUnary::FindLastBit,
|
||||
23 => ScalarUnary::FindLastSignBit,
|
||||
25 => ScalarUnary::SignExtendByte,
|
||||
26 => ScalarUnary::SignExtendShort,
|
||||
_ => ScalarUnary::Absolute,
|
||||
};
|
||||
let (source, length) = decode_scalar(*source, tail, offset)?;
|
||||
(Op::ScalarUnary(kind, destination & 0x7f, source), length)
|
||||
}
|
||||
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22 (guide
|
||||
// 13.1.4); 0-5 signed and 6-11 unsigned EQ, LG, GT, GE, LT, LE.
|
||||
[left, right, op @ 0..=11, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
|
||||
let (left, left_length) = decode_scalar(*left, tail, offset)?;
|
||||
let (right, right_length) = decode_scalar(*right, tail, offset)?;
|
||||
(Op::CompareEqual(left, right), left_length.max(right_length))
|
||||
// VOPC relation offsets: LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6.
|
||||
let relation = [2, 5, 4, 6, 1, 3][usize::from(op % 6)];
|
||||
let comparison = Comparison {
|
||||
offset: relation,
|
||||
signed: *op < 6,
|
||||
};
|
||||
let op = if relation == 2 {
|
||||
Op::CompareEqual(left, right)
|
||||
} else {
|
||||
Op::ScalarCompare(comparison, left, right)
|
||||
};
|
||||
(op, left_length.max(right_length))
|
||||
}
|
||||
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
|
||||
[
|
||||
left,
|
||||
right,
|
||||
low,
|
||||
high @ (0x80..=0x82 | 0x87 | 0x88 | 0x89),
|
||||
high @ (0x80..=0x82 | 0x87..=0x91),
|
||||
tail @ ..,
|
||||
] if (*left, *right) != (255, 255)
|
||||
&& low & 0x7f <= 105
|
||||
@@ -302,7 +390,16 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
(0x82, _) => ScalarAlu::SubtractWithBorrow,
|
||||
(0x87, _) => ScalarAlu::And,
|
||||
(0x88, _) => ScalarAlu::Or,
|
||||
_ => ScalarAlu::Xor,
|
||||
(0x89, _) => ScalarAlu::Xor,
|
||||
// Even opcodes 20-34 (bit 23 clear, checked above).
|
||||
(0x8a, _) => ScalarAlu::AndNot,
|
||||
(0x8b, _) => ScalarAlu::OrNot,
|
||||
(0x8c, _) => ScalarAlu::Nand,
|
||||
(0x8d, _) => ScalarAlu::Nor,
|
||||
(0x8e, _) => ScalarAlu::Xnor,
|
||||
(0x8f, _) => ScalarAlu::ShiftLeft,
|
||||
(0x90, _) => ScalarAlu::ShiftRight,
|
||||
_ => ScalarAlu::ArithmeticShiftRight,
|
||||
};
|
||||
let (left, left_length) = decode_scalar(*left, tail, offset)?;
|
||||
let (right, right_length) = decode_scalar(*right, tail, offset)?;
|
||||
@@ -652,9 +749,51 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
}
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
}
|
||||
Op::ScalarUnary(kind, dst, src) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
}
|
||||
let value = read_scalar(src)?;
|
||||
// -1 (all ones) when no bit is found.
|
||||
let found = |index: u32| if index == 32 { u32::MAX } else { index };
|
||||
let result = match kind {
|
||||
ScalarUnary::Not => !value,
|
||||
ScalarUnary::ReverseBits => value.reverse_bits(),
|
||||
ScalarUnary::CountZeros => value.count_zeros(),
|
||||
ScalarUnary::CountOnes => value.count_ones(),
|
||||
ScalarUnary::FindFirstZero => found(value.trailing_ones()),
|
||||
ScalarUnary::FindFirstOne => found(value.trailing_zeros()),
|
||||
ScalarUnary::FindLastBit => found(value.leading_zeros()),
|
||||
ScalarUnary::FindLastSignBit => {
|
||||
let same = if value >> 31 == 1 {
|
||||
value.leading_ones()
|
||||
} else {
|
||||
value.leading_zeros()
|
||||
};
|
||||
found(same)
|
||||
}
|
||||
ScalarUnary::SignExtendByte => value as u8 as i8 as i32 as u32,
|
||||
ScalarUnary::SignExtendShort => value as u16 as i16 as i32 as u32,
|
||||
ScalarUnary::Absolute => (value as i32).wrapping_abs() as u32,
|
||||
};
|
||||
scalars[usize::from(dst)] = Some(result);
|
||||
if matches!(
|
||||
kind,
|
||||
ScalarUnary::Not
|
||||
| ScalarUnary::CountZeros
|
||||
| ScalarUnary::CountOnes
|
||||
| ScalarUnary::Absolute
|
||||
) {
|
||||
scc = Some(result != 0);
|
||||
}
|
||||
}
|
||||
Op::CompareEqual(lhs, rhs) => {
|
||||
scc = Some(read_scalar(lhs)? == read_scalar(rhs)?);
|
||||
}
|
||||
// Guide 12.4: SCC = (S0 <relation> S1); no SGPR is written.
|
||||
Op::ScalarCompare(comparison, lhs, rhs) => {
|
||||
scc = Some(comparison.holds(read_scalar(lhs)?, read_scalar(rhs)?));
|
||||
}
|
||||
Op::Scalar(kind, dst, lhs, rhs) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
@@ -694,6 +833,21 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
};
|
||||
(bits, bits != 0)
|
||||
}
|
||||
// Guide 12.1: shifts use only S1[4:0]; all set SCC = (D != 0).
|
||||
_ => {
|
||||
let (a, b) = (lhs as u32, rhs as u32);
|
||||
let bits = match kind {
|
||||
ScalarAlu::AndNot => a & !b,
|
||||
ScalarAlu::OrNot => a | !b,
|
||||
ScalarAlu::Nand => !(a & b),
|
||||
ScalarAlu::Nor => !(a | b),
|
||||
ScalarAlu::Xnor => !(a ^ b),
|
||||
ScalarAlu::ShiftLeft => a << (b & 0x1f),
|
||||
ScalarAlu::ShiftRight => a >> (b & 0x1f),
|
||||
_ => ((a as i32) >> (b & 0x1f)) as u32,
|
||||
};
|
||||
(i64::from(bits), bits != 0)
|
||||
}
|
||||
};
|
||||
let value = exact.rem_euclid(1 << 32) as u32;
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
|
||||
@@ -809,6 +809,21 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
*slot = Some(value);
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarUnary { op, dst, src } => {
|
||||
let src = read_scalar(src)?;
|
||||
if dst < 8 {
|
||||
return Err(error("scalar unary would modify a resource descriptor"));
|
||||
}
|
||||
let (value, flag) = op.evaluate(src);
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
@@ -832,8 +847,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
scc = Some(flag);
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
scc = Some(read_scalar(src0)? == read_scalar(src1)?);
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?));
|
||||
continue;
|
||||
}
|
||||
// docs/shaders/vector-compare.md sections 3 and 5.
|
||||
|
||||
@@ -280,6 +280,48 @@ fn scalar_alu_results_reach_the_kernel_as_constants() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_logic_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-logic.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-logic.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-logic.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_results_resolve_every_branch() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-compare.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-compare.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-compare.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-unary.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-unary.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
|
||||
<title id="title">Xenora · recorded progress</title>
|
||||
<desc id="description">Decoded gfx1030 forms: 42 of 42. Accepted Metal forms · Apple M5: 18 of 42. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<desc id="description">Decoded gfx1030 forms: 72 of 72. Accepted Metal forms · Apple M5: 18 of 72. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
|
||||
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
|
||||
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
|
||||
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">42 / 42</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">72 / 72</text>
|
||||
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 42</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 72</text>
|
||||
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="103" width="210.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<rect x="20" y="103" width="122.50" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
|
||||
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
|
||||
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -21,7 +21,29 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
|
||||
| `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
|
||||
| `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified |
|
||||
| `s_not_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0 | `BE890708` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_brev_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged | `BE8A0B08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bcnt0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0 | `BE8C0D08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bcnt1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0 | `BE8B0F08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ff0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged | `BE8E11FF 0000FFFF` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ff1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged | `BE8D13FF 00400000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_flbit_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged | `BE8F1508` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_flbit_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged | `BE9017FF FFF00000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sext_i32_i8` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged | `BE911908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sext_i32_i16` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged | `BE921AFF 00018000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_abs_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = \|S0\| (0x80000000 stays); SCC = D != 0 | `BE933412` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified |
|
||||
| `s_cmp_eq_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed) | `BF00C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lg_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed) | `BF010908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_gt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed) | `BF020908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_ge_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed) | `BF030909` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed) | `BF040908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_le_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed) | `BF050809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lg_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned) | `BF07FF0A 89ABCDEF` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_gt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned) | `BF080908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_ge_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned) | `BF090809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned) | `BF0A0809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_le_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned) | `BF0BC009` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out | `80088308` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sub_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow | `808A8180` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_add_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow | `8110C109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -31,6 +53,14 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_and_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `870D090C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_or_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `880ED00D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_xor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `890C0A0B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_andn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0 | `8A09FF08 FF00FF00` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_orn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 \| ~S1; SCC = result != 0 | `8B0AC109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_nand_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0 | `8C0B0808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_nor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 \| S1); SCC = result != 0 | `8D0C090B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_xnor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0 | `8E0D080C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0 | `8F0EA40D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshr_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0 | `900FFF0E FFFFFFE1` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ashr_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0 | `91109F0E` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written | `7D020701` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 == S1), fully written | `7D040280` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 <= S1), fully written | `7D060208` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
|
||||
@@ -8,8 +8,9 @@
|
||||
| SOPP `S_WAITCNT`, SOPK `S_WAITCNT_VSCNT` | A zero vector-load or vector-store threshold completes the associated transfer. The model permits one pending operation per counter (CLAIM-RDNA2-TRANSFER-WAITS). |
|
||||
| VOP1 `V_MOV_B32` | Read a register, inline integer or literal. Copy all 32 bits. |
|
||||
| VOP3 `V_ADD_NC_U32` | Read two vector registers and add modulo 2^32. No implicit carry or flag update. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_EQ_U32` | Copy 32 bits into a scalar register or compare two operands and set SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32` | Exact integer result reduced modulo 2^32; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero bitwise result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| SOP1 `S_NOT_B32`, `S_BREV_B32`, `S_BCNT{0,1}_I32_B32`, `S_FF{0,1}_I32_B32`, `S_FLBIT_I32_B32`, `S_FLBIT_I32`, `S_SEXT_I32_I{8,16}`, `S_ABS_I32` | The guide's section 12.3 result; a search that finds nothing gives -1, and `S_ABS_I32` of 0x80000000 is 0x80000000. Only NOT, BCNT0, BCNT1 and ABS write SCC (= D != 0). Descriptor SGPRs are reserved. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_{EQ,LG,GT,GE,LT,LE}_{I32,U32}` | Copy 32 bits into a scalar register, or compare SSRC0 with SSRC1 (signed for `_I32` ordering, unsigned for `_U32`; EQ and LG on the raw bits) and set only SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32`, `S_ANDN2_B32`, `S_ORN2_B32`, `S_NAND_B32`, `S_NOR_B32`, `S_XNOR_B32`, `S_LSHL_B32`, `S_LSHR_B32`, `S_ASHR_I32` | Exact integer result reduced modulo 2^32; shifts use S1[4:0]; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero logical or shift result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). |
|
||||
| SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. |
|
||||
| VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SOP2 scalar ALU subset
|
||||
|
||||
Xenora decodes and executes nine gfx1030 SOP2 forms. Each takes 32-bit
|
||||
Xenora decodes and executes seventeen gfx1030 SOP2 forms. Each takes 32-bit
|
||||
operands, writes a normal SGPR (s0-s105) and sets SCC.
|
||||
|
||||
| Form | D | SCC |
|
||||
@@ -14,10 +14,23 @@ operands, writes a normal SGPR (s0-s105) and sets SCC.
|
||||
| `s_and_b32` | S0 & S1 | D != 0 |
|
||||
| `s_or_b32` | S0 \| S1 | D != 0 |
|
||||
| `s_xor_b32` | S0 ^ S1 | D != 0 |
|
||||
| `s_andn2_b32` | S0 & ~S1 | D != 0 |
|
||||
| `s_orn2_b32` | S0 \| ~S1 | D != 0 |
|
||||
| `s_nand_b32` | ~(S0 & S1) | D != 0 |
|
||||
| `s_nor_b32` | ~(S0 \| S1) | D != 0 |
|
||||
| `s_xnor_b32` | ~(S0 ^ S1) | D != 0 |
|
||||
| `s_lshl_b32` | S0 << S1[4:0] | D != 0 |
|
||||
| `s_lshr_b32` | S0 >> S1[4:0], zero fill | D != 0 |
|
||||
| `s_ashr_i32` | S0 >> S1[4:0], sign fill | D != 0 |
|
||||
|
||||
The last eight were added through the semantic registry alone: one TOML entry
|
||||
each, with no hand-written Rust per form. Shifts use only the low five bits of
|
||||
S1 as the count, as the guide's pseudocode states (section 12.1); higher bits are
|
||||
ignored.
|
||||
|
||||
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
|
||||
|
||||
These nine forms are declared as data in the semantic registry,
|
||||
These forms are declared as data in the semantic registry,
|
||||
`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in,
|
||||
SCC effect, operand rule and guide references. `crates/isa/generate_semantics.py`
|
||||
checks each declaration against the pinned AMD XML snapshot and rejects
|
||||
@@ -65,7 +78,7 @@ the registry.
|
||||
## How it runs
|
||||
|
||||
Scalar state in a compute fixture is wave-uniform and known while the code is
|
||||
translated. As with `s_mov_b32` and `s_cmp_eq_u32`, the translator evaluates
|
||||
translated. As with `s_mov_b32` and the SOPC compares, the translator evaluates
|
||||
SOP2 forms itself. It resolves SCC-dependent branches and emits SGPR values
|
||||
read by `v_mov_b32_e32` as constants (`fixtures/golden/scalar-alu.ir`). So the
|
||||
IR and MSL contain the results, not scalar instructions.
|
||||
@@ -85,7 +98,7 @@ literal operands, bitwise results that set and clear SCC, and an
|
||||
Its expected output, input ^ 0x0000000e,
|
||||
was derived by hand.
|
||||
|
||||
`tests/validation/known_answers.rs` runs every supported form over 10 boundary
|
||||
`tests/validation/known_answers.rs` runs the first nine forms over 10 boundary
|
||||
operands squared, with SCC clear and set. That is 1,800 programs. The same file
|
||||
covers aliasing, inline and literal operands, and rejected forms. Expected
|
||||
values come from exact integer definitions in the test. Three implementations
|
||||
@@ -94,7 +107,55 @@ must agree with them:
|
||||
- the reference interpreter (exact integers, reduced modulo 2^32);
|
||||
- the independent interpreter (a bit-serial ripple-carry adder).
|
||||
|
||||
The eight logical and shift forms added through the registry have their own
|
||||
suite, `tests/validation/tests/sop2_stage_c.rs`: 6,896 cases whose expected
|
||||
values were derived from the guide separately from the registry, checked on
|
||||
both CPU interpreters and, through the translator, on native Metal. The
|
||||
LLVM-assembled `fixtures/rdna2/scalar-logic.s` (expected input ^ 0x887f00f8)
|
||||
runs on all three and on native Metal.
|
||||
|
||||
`scalar_alu_native_metal_known_answers` runs the fixture, the 1,800 programs
|
||||
and the aliasing and immediate cases on native Metal with API and shader
|
||||
validation. `scripts/test-gpu.sh` runs it. This is local evidence from one
|
||||
Apple M5 Pro; independent acceptance is pending.
|
||||
|
||||
## SOPC compares
|
||||
|
||||
The twelve 32-bit SOPC integer compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`
|
||||
are declared in the same registry (operand rule `sopc_scalar`). Each sets only
|
||||
SCC, to whether the relation holds with SSRC0 on the left; LG means not equal.
|
||||
EQ and LG give the same result for `_i32` and `_u32`; GT, GE, LT and LE compare
|
||||
two's-complement values for `_i32` and unsigned values for `_u32` (guide section
|
||||
12.4). Sources follow the SOP2 rule: normal SGPRs, inline integers or one
|
||||
literal. Both sources selecting the literal encoding (255) is rejected for SOPC
|
||||
as for SOP2; whether the guide allows one shared literal there was not settled.
|
||||
|
||||
`tests/validation/tests/sopc_stage_d.rs` checks 7,824 cases, with expected
|
||||
values derived from the guide separately from the registry, on both CPU
|
||||
interpreters and, through the translator, on native Metal (compiled per case
|
||||
and read back from nine distinct generated kernels). Its 348 rejected programs
|
||||
are checked on both CPU interpreters and against the compiler, which rejects
|
||||
them before any Metal dispatch. `fixtures/rdna2/scalar-compare.s` (LLVM-assembled, expected input ^
|
||||
0x00000d5b) records every compare's SCC through an `s_cbranch_scc0` per form.
|
||||
|
||||
## SOP1 unary forms
|
||||
|
||||
Eleven 32-bit SOP1 forms are declared in the registry (operand rule
|
||||
`sop1_sgpr`): `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
|
||||
`s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
|
||||
`s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`. Following the guide (section
|
||||
12.3): a find-first or find-last search that finds nothing returns -1
|
||||
(0xffffffff); `s_flbit_i32` returns -1 for both 0 and -1; sign extension reads
|
||||
S0[7:0] or S0[15:0]; `s_abs_i32` of 0x80000000 is 0x80000000. Only NOT, BCNT0,
|
||||
BCNT1 and ABS write SCC, as D != 0; the other seven leave it unchanged.
|
||||
`s_mov_b32` stays hand-written, because it also accepts EXEC and VCC halves as
|
||||
destinations. As for SOP2, destinations s0-s7 are refused when a fixture runs
|
||||
(they hold its buffer descriptors), and float inline constants are rejected.
|
||||
|
||||
`tests/validation/tests/sop1_unary.rs` checks 4,126 cases, with expected values
|
||||
derived from the guide (including its worked examples) separately from the
|
||||
registry, on both CPU interpreters and, through the translator, on native
|
||||
Metal; its 231 rejected programs are checked on the CPU interpreters and the
|
||||
compiler. `fixtures/rdna2/scalar-unary.s` (LLVM-assembled, expected input ^
|
||||
0x0f0080f5) chains all eleven and shows SCC surviving the forms that do not
|
||||
write it.
|
||||
@@ -24,9 +24,9 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
|
||||
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SOP1 | 65 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOP2 | 51 | 9 | 9 | 9 | 9 | 9 | 0 | 0 | 12 |
|
||||
| SOPC | 18 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
|
||||
| SOP2 | 51 | 17 | 17 | 17 | 17 | 17 | 0 | 0 | 12 |
|
||||
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
|
||||
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
|
||||
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
|
||||
@@ -36,7 +36,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
|
||||
| **Total** | 1465 | 42 | 9 | 46 | 42 | 42 | 18 | 18 | 12 |
|
||||
| **Total** | 1465 | 72 | 40 | 76 | 72 | 72 | 18 | 18 | 30 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
@@ -44,4 +44,6 @@ The table counts distinct variant names per family across registry operand rules
|
||||
|
||||
| Family | Operand rule | Unsupported variants |
|
||||
| --- | --- | --- |
|
||||
| SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
@@ -51,11 +51,14 @@ error.
|
||||
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
|
||||
| `opcode` | Opcode; must match the XML | non-negative integer |
|
||||
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor` |
|
||||
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (`bitwise` exactly for `and`, `or`, `xor`) |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr` |
|
||||
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, never for `add` and `sub`; shifts take their primitive's signedness) |
|
||||
| `carry_in` | Whether the form reads SCC as carry-in or borrow-in | `none`, `scc` (`scc` only for unsigned `add` and `sub`) |
|
||||
| `width` | Operand and result width in bits | `32` |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `unchanged` |
|
||||
| `source_bits` | Sign extension only: the low bits of S0 that are read. The XML must list S0 with that size and format (`FMT_NUM_I8` or `FMT_NUM_I16`) | `8`, `16`; required for `sext`, rejected elsewhere |
|
||||
| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere |
|
||||
| `shift_count_bits` | Shifts only: the low bits of S1 used as the count. The generator masks S1 with it, and the XML must list S1 as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (compares only), `unchanged` |
|
||||
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` |
|
||||
| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) |
|
||||
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
|
||||
@@ -71,7 +74,20 @@ fixes the `scc` value:
|
||||
| `sub` / `unsigned` | `borrow` | `sub_borrow_u32` | allowed |
|
||||
| `add` / `signed` | `signed_overflow` | `add_overflow_i32` | no |
|
||||
| `sub` / `signed` | `signed_overflow` | `sub_overflow_i32` | no |
|
||||
| `and`, `or`, `xor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32` | no |
|
||||
| `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32`, `andn2_nonzero_b32`, `orn2_nonzero_b32`, `nand_nonzero_b32`, `nor_nonzero_b32`, `xnor_nonzero_b32` | no |
|
||||
| `lshl` / `bitwise` | `nonzero` | `lshl_nonzero_b32` | no |
|
||||
| `lshr` / `unsigned` | `nonzero` | `lshr_nonzero_b32` | no |
|
||||
| `ashr` / `signed` | `nonzero` | `ashr_nonzero_i32` | no |
|
||||
| `not`, `bcnt0`, `bcnt1` / `bitwise` | `nonzero` | `not_nonzero_b32`, `bcnt0_nonzero_b32`, `bcnt1_nonzero_b32` | no |
|
||||
| `brev`, `ff0`, `ff1`, `flbit` / `bitwise` | `unchanged` | `brev_b32`, `ff0_b32`, `ff1_b32`, `flbit_b32` | no |
|
||||
| `flbit`, `sext` / `signed` | `unchanged` | `flbit_i32`, `sext_i32` | no |
|
||||
| `abs` / `signed` | `nonzero` | `abs_nonzero_i32` | no |
|
||||
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
|
||||
|
||||
A compare must use an operand rule of the compare kind (`sopc_scalar`: two
|
||||
sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
|
||||
one source and an SGPR destination), and a two-source ALU operation
|
||||
`sop2_sgpr`.
|
||||
|
||||
Behaviour is chosen only from these declared fields, never from the mnemonic.
|
||||
|
||||
|
||||
@@ -135,6 +135,138 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_not_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0"
|
||||
representation = "`BE890708`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_brev_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged"
|
||||
representation = "`BE8A0B08`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bcnt0_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0"
|
||||
representation = "`BE8C0D08`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bcnt1_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0"
|
||||
representation = "`BE8B0F08`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_ff0_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged"
|
||||
representation = "`BE8E11FF 0000FFFF`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_ff1_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged"
|
||||
representation = "`BE8D13FF 00400000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_flbit_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged"
|
||||
representation = "`BE8F1508`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_flbit_i32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged"
|
||||
representation = "`BE9017FF FFF00000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_sext_i32_i8"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged"
|
||||
representation = "`BE911908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_sext_i32_i16"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged"
|
||||
representation = "`BE921AFF 00018000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_abs_i32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = |S0| (0x80000000 stays); SCC = D != 0"
|
||||
representation = "`BE933412`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_eq_u32"
|
||||
encoding = "Normal SGPR or integer operands, with at most one source selecting a literal"
|
||||
@@ -147,6 +279,138 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_eq_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed)"
|
||||
representation = "`BF00C108`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lg_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed)"
|
||||
representation = "`BF010908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_gt_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed)"
|
||||
representation = "`BF020908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_ge_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed)"
|
||||
representation = "`BF030909`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lt_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed)"
|
||||
representation = "`BF040908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_le_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed)"
|
||||
representation = "`BF050809`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lg_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned)"
|
||||
representation = "`BF07FF0A 89ABCDEF`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_gt_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned)"
|
||||
representation = "`BF080908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_ge_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned)"
|
||||
representation = "`BF090809`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lt_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned)"
|
||||
representation = "`BF0A0809`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_le_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned)"
|
||||
representation = "`BF0BC009`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out"
|
||||
@@ -255,6 +519,102 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_andn2_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0"
|
||||
representation = "`8A09FF08 FF00FF00`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_orn2_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 | ~S1; SCC = result != 0"
|
||||
representation = "`8B0AC109`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_nand_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0"
|
||||
representation = "`8C0B0808`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_nor_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 | S1); SCC = result != 0"
|
||||
representation = "`8D0C090B`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_xnor_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0"
|
||||
representation = "`8E0D080C`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0"
|
||||
representation = "`8F0EA40D`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshr_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0"
|
||||
representation = "`900FFF0E FFFFFFE1`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_ashr_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0"
|
||||
representation = "`91109F0E`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_lt_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written"
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
001c: branch.uniform 0x0024 taken=false
|
||||
0028: branch.uniform 0x0030 taken=false
|
||||
0034: branch.uniform 0x003c taken=true
|
||||
0040: branch.uniform 0x0048 taken=false
|
||||
004c: branch.uniform 0x0054 taken=false
|
||||
0058: branch.uniform 0x0060 taken=true
|
||||
0064: branch.uniform 0x006c taken=false
|
||||
007c: branch.uniform 0x0088 taken=true
|
||||
008c: branch.uniform 0x0098 taken=false
|
||||
009c: branch.uniform 0x00a8 taken=true
|
||||
00ac: branch.uniform 0x00b8 taken=false
|
||||
00bc: branch.uniform 0x00c8 taken=false
|
||||
00c8: t13 = const.u32 0x00000d5b
|
||||
00cc: t14 = xor.b32 t0, t13
|
||||
00d0: store.u32 output[index], t14
|
||||
@@ -0,0 +1,11 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t13 = 0x00000d5bu;
|
||||
uint t14 = t0 ^ t13;
|
||||
output[index] = t14;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0040: branch.uniform 0x004c taken=true
|
||||
004c: t2 = const.u32 0xff0fffff
|
||||
0050: t3 = const.u32 0x787ffff8
|
||||
0054: t4 = xor.b32 t2, t3
|
||||
0058: t5 = const.u32 0xffffffff
|
||||
005c: t6 = xor.b32 t4, t5
|
||||
0060: t7 = const.u32 0x00f00000
|
||||
0064: t8 = xor.b32 t6, t7
|
||||
0068: t9 = const.u32 0xf000ff00
|
||||
006c: t10 = xor.b32 t8, t9
|
||||
0070: t11 = xor.b32 t0, t10
|
||||
0074: store.u32 output[index], t11
|
||||
@@ -0,0 +1,19 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t2 = 0xff0fffffu;
|
||||
uint t3 = 0x787ffff8u;
|
||||
uint t4 = t2 ^ t3;
|
||||
uint t5 = 0xffffffffu;
|
||||
uint t6 = t4 ^ t5;
|
||||
uint t7 = 0x00f00000u;
|
||||
uint t8 = t6 ^ t7;
|
||||
uint t9 = 0xf000ff00u;
|
||||
uint t10 = t8 ^ t9;
|
||||
uint t11 = t0 ^ t10;
|
||||
output[index] = t11;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0060: branch.uniform 0x006c taken=true
|
||||
006c: t2 = const.u32 0xffffff0f
|
||||
0070: t3 = const.u32 0x0f000000
|
||||
0074: t4 = xor.b32 t2, t3
|
||||
0078: t5 = const.u32 0x00000004
|
||||
007c: t6 = xor.b32 t4, t5
|
||||
0080: t7 = const.u32 0x0000001c
|
||||
0084: t8 = xor.b32 t6, t7
|
||||
0088: t9 = const.u32 0x00000016
|
||||
008c: t10 = xor.b32 t8, t9
|
||||
0090: t11 = const.u32 0x00000010
|
||||
0094: t12 = xor.b32 t10, t11
|
||||
0098: t13 = const.u32 0x00000018
|
||||
009c: t14 = xor.b32 t12, t13
|
||||
00a0: t15 = const.u32 0x0000000c
|
||||
00a4: t16 = xor.b32 t14, t15
|
||||
00a8: t17 = const.u32 0xfffffff0
|
||||
00ac: t18 = xor.b32 t16, t17
|
||||
00b0: t19 = const.u32 0xffff8000
|
||||
00b4: t20 = xor.b32 t18, t19
|
||||
00b8: t21 = const.u32 0x00008000
|
||||
00bc: t22 = xor.b32 t20, t21
|
||||
00c0: t23 = const.u32 0x00007fff
|
||||
00c4: t24 = xor.b32 t22, t23
|
||||
00c8: t25 = const.u32 0xffffffff
|
||||
00cc: t26 = xor.b32 t24, t25
|
||||
00d0: t27 = xor.b32 t0, t26
|
||||
00d4: store.u32 output[index], t27
|
||||
@@ -0,0 +1,35 @@
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t2 = 0xffffff0fu;
|
||||
uint t3 = 0x0f000000u;
|
||||
uint t4 = t2 ^ t3;
|
||||
uint t5 = 0x00000004u;
|
||||
uint t6 = t4 ^ t5;
|
||||
uint t7 = 0x0000001cu;
|
||||
uint t8 = t6 ^ t7;
|
||||
uint t9 = 0x00000016u;
|
||||
uint t10 = t8 ^ t9;
|
||||
uint t11 = 0x00000010u;
|
||||
uint t12 = t10 ^ t11;
|
||||
uint t13 = 0x00000018u;
|
||||
uint t14 = t12 ^ t13;
|
||||
uint t15 = 0x0000000cu;
|
||||
uint t16 = t14 ^ t15;
|
||||
uint t17 = 0xfffffff0u;
|
||||
uint t18 = t16 ^ t17;
|
||||
uint t19 = 0xffff8000u;
|
||||
uint t20 = t18 ^ t19;
|
||||
uint t21 = 0x00008000u;
|
||||
uint t22 = t20 ^ t21;
|
||||
uint t23 = 0x00007fffu;
|
||||
uint t24 = t22 ^ t23;
|
||||
uint t25 = 0xffffffffu;
|
||||
uint t26 = t24 ^ t25;
|
||||
uint t27 = t0 ^ t26;
|
||||
output[index] = t27;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,66 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOPC vectors: each of the twelve 32-bit integer compares sets SCC,
|
||||
// and an s_cbranch_scc0 skips setting that compare's bit in s20, so s20
|
||||
// records every result. -1 and 1 separate signed from unsigned ordering;
|
||||
// inline and literal operands appear in the second position.
|
||||
// Expected: input ^ 0x00000d5b (bits worked out by hand below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, -1
|
||||
s_mov_b32 s9, 1
|
||||
s_mov_b32 s20, 0
|
||||
s_cmp_eq_i32 s8, -1 // -1 == -1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip0
|
||||
s_or_b32 s20, s20, 1
|
||||
.Lskip0:
|
||||
s_cmp_lg_i32 s8, s9 // -1 != 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip1
|
||||
s_or_b32 s20, s20, 2
|
||||
.Lskip1:
|
||||
s_cmp_gt_i32 s8, s9 // -1 > 1: SCC = 0
|
||||
s_cbranch_scc0 .Lskip2
|
||||
s_or_b32 s20, s20, 4
|
||||
.Lskip2:
|
||||
s_cmp_ge_i32 s9, s9 // 1 >= 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip3
|
||||
s_or_b32 s20, s20, 8
|
||||
.Lskip3:
|
||||
s_cmp_lt_i32 s8, s9 // -1 < 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip4
|
||||
s_or_b32 s20, s20, 16
|
||||
.Lskip4:
|
||||
s_cmp_le_i32 s9, s8 // 1 <= -1: SCC = 0
|
||||
s_cbranch_scc0 .Lskip5
|
||||
s_or_b32 s20, s20, 32
|
||||
.Lskip5:
|
||||
s_cmp_eq_u32 s9, 1 // 1 == 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip6
|
||||
s_or_b32 s20, s20, 64
|
||||
.Lskip6:
|
||||
s_mov_b32 s10, 0x89abcdef
|
||||
s_cmp_lg_u32 s10, 0x89abcdef // 0x89abcdef != 0x89abcdef: SCC = 0 (literal)
|
||||
s_cbranch_scc0 .Lskip7
|
||||
s_or_b32 s20, s20, 0x80
|
||||
.Lskip7:
|
||||
s_cmp_gt_u32 s8, s9 // 0xffffffff > 1: SCC = 1
|
||||
s_cbranch_scc0 .Lskip8
|
||||
s_or_b32 s20, s20, 0x100
|
||||
.Lskip8:
|
||||
s_cmp_ge_u32 s9, s8 // 1 >= 0xffffffff: SCC = 0
|
||||
s_cbranch_scc0 .Lskip9
|
||||
s_or_b32 s20, s20, 0x200
|
||||
.Lskip9:
|
||||
s_cmp_lt_u32 s9, s8 // 1 < 0xffffffff: SCC = 1
|
||||
s_cbranch_scc0 .Lskip10
|
||||
s_or_b32 s20, s20, 0x400
|
||||
.Lskip10:
|
||||
s_cmp_le_u32 s9, 64 // 1 <= 64: SCC = 1
|
||||
s_cbranch_scc0 .Lskip11
|
||||
s_or_b32 s20, s20, 0x800
|
||||
.Lskip11:
|
||||
v_mov_b32_e32 v2, s20
|
||||
v_xor_b32_e32 v2, v1, v2 // s20 = 0x00000d5b
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,38 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOP2 vectors for the registry-declared logical and shift forms:
|
||||
// ANDN2/ORN2 with a literal and an inline -1, NAND with aliased sources,
|
||||
// NOR/XNOR chains, shift counts that use only S1[4:0] (36 -> 4, a literal
|
||||
// 0xffffffe1 -> 1, 31), an arithmetic shift of a negative and a positive value,
|
||||
// and an SCC branch on a zero shift result. SGPR results are moved into VGPRs.
|
||||
// Expected: input ^ 0x887f00f8 (worked out by hand below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, 0xf0f0ff00
|
||||
s_andn2_b32 s9, s8, 0xff00ff00 // s9 = 0x00f00000, SCC = 1
|
||||
s_orn2_b32 s10, s9, -1 // s10 = 0x00f00000, SCC = 1
|
||||
s_nand_b32 s11, s8, s8 // s11 = 0x0f0f00ff, SCC = 1
|
||||
s_nor_b32 s12, s11, s9 // s12 = 0xf000ff00, SCC = 1
|
||||
s_xnor_b32 s13, s12, s8 // s13 = 0xff0fffff, SCC = 1
|
||||
s_lshl_b32 s14, s13, 36 // s14 = 0xf0fffff0 (count 4), SCC = 1
|
||||
s_lshr_b32 s15, s14, 0xffffffe1 // s15 = 0x787ffff8 (count 1), SCC = 1
|
||||
s_ashr_i32 s16, s14, 31 // s16 = 0xffffffff, SCC = 1
|
||||
s_ashr_i32 s17, s15, 31 // s17 = 0, SCC = 0
|
||||
s_cbranch_scc0 .Lzero
|
||||
v_mov_b32_e32 v2, 0
|
||||
s_branch .Ldone
|
||||
.Lzero:
|
||||
v_mov_b32_e32 v2, s13
|
||||
v_mov_b32_e32 v3, s15
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v4, s16
|
||||
v_xor_b32_e32 v2, v2, v4
|
||||
v_mov_b32_e32 v5, s10
|
||||
v_xor_b32_e32 v2, v2, v5
|
||||
v_mov_b32_e32 v6, s12
|
||||
v_xor_b32_e32 v2, v2, v6 // 0xff0fffff ^ 0x787ffff8 ^ 0xffffffff ^ 0x00f00000 ^ 0xf000ff00
|
||||
v_xor_b32_e32 v2, v1, v2
|
||||
.Ldone:
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
Binary file not shown.
@@ -0,0 +1,59 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOP1 vectors for the registry-declared unary forms: complement, bit
|
||||
// reverse, both bit counts, both find-first searches (one finding nothing, which
|
||||
// gives -1), both find-last-bit forms, sign extension from 8 and 16 bits, and
|
||||
// absolute value. SCC is set by NOT/BCNT/ABS only: an ABS of zero clears it, and
|
||||
// the following SEXT and FF1 leave it clear for the s_cbranch_scc0.
|
||||
// Expected: input ^ 0x0f0080f5 (worked out by hand below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, 0xf0
|
||||
s_not_b32 s9, s8 // s9 = 0xffffff0f, SCC = 1
|
||||
s_brev_b32 s10, s8 // s10 = 0x0f000000
|
||||
s_bcnt1_i32_b32 s11, s8 // s11 = 4, SCC = 1
|
||||
s_bcnt0_i32_b32 s12, s8 // s12 = 28, SCC = 1
|
||||
s_ff1_i32_b32 s13, 0x400000 // s13 = 22
|
||||
s_ff0_i32_b32 s14, 0xffff // s14 = 16
|
||||
s_flbit_i32_b32 s15, s8 // s15 = 24
|
||||
s_flbit_i32 s16, 0xfff00000 // s16 = 12 (bits equal to the sign above bit 19)
|
||||
s_sext_i32_i8 s17, s8 // s17 = 0xfffffff0
|
||||
s_sext_i32_i16 s18, 0x18000 // s18 = 0xffff8000
|
||||
s_abs_i32 s19, s18 // s19 = 0x8000, SCC = 1
|
||||
s_abs_i32 s20, 0 // s20 = 0, SCC = 0
|
||||
s_sext_i32_i16 s21, 0x7fff // s21 = 0x7fff, SCC unchanged (0)
|
||||
s_ff1_i32_b32 s22, 0 // s22 = 0xffffffff (none found), SCC unchanged (0)
|
||||
s_cbranch_scc0 .Lzero
|
||||
v_mov_b32_e32 v2, 0
|
||||
s_branch .Ldone
|
||||
.Lzero:
|
||||
v_mov_b32_e32 v2, s9
|
||||
v_mov_b32_e32 v3, s10
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s11
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s12
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s13
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s14
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s15
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s16
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s17
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s18
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s19
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s21
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s22
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_xor_b32_e32 v2, v1, v2 // v2 = input ^ 0x0f0080f5
|
||||
.Ldone:
|
||||
buffer_store_dword v2, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
@@ -12,7 +12,7 @@ case "${1:-}" in
|
||||
esac
|
||||
|
||||
for name in add bitwise-branch float-exact or shifts ashr \
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare; do
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary; do
|
||||
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
|
||||
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
|
||||
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
|
||||
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Build Xenora.app (native ARM64) into build/Xenora.app and run its smoke check.
|
||||
# Requires: macOS on Apple Silicon, Rust 1.100 (aarch64-apple-darwin), Swift 6 toolchain.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
root=$(pwd)
|
||||
|
||||
fail() { echo "build-app: $*" >&2; exit 1; }
|
||||
[ "$(uname -s)" = Darwin ] || fail "macOS is required"
|
||||
[ "$(uname -m)" = arm64 ] || fail "a native arm64 host is required"
|
||||
[ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 0 ] || fail "running under Rosetta is not supported"
|
||||
command -v cargo >/dev/null || fail "cargo not found; install Rust 1.100"
|
||||
command -v swift >/dev/null || fail "swift not found; install the Xcode command line tools"
|
||||
|
||||
target=aarch64-apple-darwin
|
||||
# Match the app's LSMinimumSystemVersion so the static library links cleanly.
|
||||
MACOSX_DEPLOYMENT_TARGET=14.0 cargo build --locked --release -p xenora-ffi --target "$target"
|
||||
swift build --package-path app -c release --arch arm64 \
|
||||
-Xlinker -L -Xlinker "$root/target/$target/release"
|
||||
|
||||
bundle="$root/build/Xenora.app"
|
||||
rm -rf "$bundle"
|
||||
mkdir -p "$bundle/Contents/MacOS"
|
||||
cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/Xenora" "$bundle/Contents/MacOS/Xenora"
|
||||
cat > "$bundle/Contents/Info.plist" <<PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleExecutable</key><string>Xenora</string>
|
||||
<key>CFBundleIdentifier</key><string>local.xenora.Xenora</string>
|
||||
<key>CFBundleName</key><string>Xenora</string>
|
||||
<key>CFBundlePackageType</key><string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key><string>0.1.0</string>
|
||||
<key>LSMinimumSystemVersion</key><string>14.0</string>
|
||||
<key>NSHighResolutionCapable</key><true/>
|
||||
<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
|
||||
# Ad-hoc signature for local development only. No entitlements are requested:
|
||||
# this build executes no guest code, so it needs no JIT entitlement.
|
||||
codesign --force --sign - "$bundle"
|
||||
|
||||
binary="$bundle/Contents/MacOS/Xenora"
|
||||
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
|
||||
"$binary" --smoke
|
||||
echo "build-app: built $bundle"
|
||||
@@ -25,6 +25,11 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12
|
||||
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
# The native app interface runs the trusted fixture's guest draw on Metal.
|
||||
cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run
|
||||
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
|
||||
# and VOPC compares.
|
||||
cargo test --locked -p xenora-semantic-review --no-run
|
||||
|
||||
@@ -32,11 +32,11 @@ U32 = "FMT_NUM_U32"
|
||||
I32 = "FMT_NUM_I32"
|
||||
|
||||
|
||||
def _operands(data_format, scc_in=False):
|
||||
def _operands(data_format, scc_in=False, src1_format=None):
|
||||
rows = [
|
||||
["SDST", data_format, "OPR_SDST", 32, False, True, False, True],
|
||||
["SSRC0", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
|
||||
["SSRC1", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
|
||||
["SSRC1", src1_format or data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
|
||||
["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True],
|
||||
]
|
||||
if scc_in:
|
||||
@@ -54,7 +54,7 @@ def snapshot():
|
||||
["OP", [[23, 7]]], ["ENCODING", [[30, 2]]],
|
||||
],
|
||||
"identifier_mask": 0xFF800000,
|
||||
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14)],
|
||||
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14, 34)],
|
||||
}
|
||||
variants = {}
|
||||
for name, opcode, operands in (
|
||||
@@ -62,11 +62,58 @@ def snapshot():
|
||||
("S_ADD_I32", 2, _operands(I32)),
|
||||
("S_ADDC_U32", 4, _operands(U32, scc_in=True)),
|
||||
("S_AND_B32", 14, _operands(U32)),
|
||||
# The XML gives S_ASHR_I32 a signed S0 and an unsigned shift count.
|
||||
("S_ASHR_I32", 34, _operands(I32, src1_format=U32)),
|
||||
):
|
||||
variants[(name, "ENC_SOP2")] = {
|
||||
"instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands,
|
||||
}
|
||||
return {"source": {"sha256": SHA}, "encodings": {"ENC_SOP2": encoding}, "variants": variants}
|
||||
sopc = {
|
||||
"name": "ENC_SOPC",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["OP", [[16, 7]]], ["ENCODING", [[23, 9]]],
|
||||
],
|
||||
"identifier_mask": 0xFFFF0000,
|
||||
"identifiers": [0xBF000000 | (op << 16) for op in (4, 10)],
|
||||
}
|
||||
for name, opcode, data_format in (("S_CMP_LT_I32", 4, I32), ("S_CMP_LT_U32", 10, U32)):
|
||||
variants[(name, "ENC_SOPC")] = {
|
||||
"instruction": name, "encoding": "ENC_SOPC", "opcode": opcode,
|
||||
"operands": _operands(data_format)[1:],
|
||||
}
|
||||
sop1 = {
|
||||
"name": "ENC_SOP1",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SSRC0", [[0, 8]]], ["OP", [[8, 8]]], ["SDST", [[16, 7]]], ["ENCODING", [[23, 9]]],
|
||||
],
|
||||
"identifier_mask": 0xFF80FF00,
|
||||
"identifiers": [0xBE800000 | (op << 8) for op in (7, 11, 25)],
|
||||
}
|
||||
|
||||
def unary(dst, src, size, scc):
|
||||
rows = [
|
||||
["SDST", dst, "OPR_SDST", 32, False, True, False, True],
|
||||
["SSRC0", src, "OPR_SSRC_NOLDS", size, True, False, False, True],
|
||||
]
|
||||
if scc:
|
||||
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True])
|
||||
return rows
|
||||
|
||||
for name, opcode, operands in (
|
||||
("S_NOT_B32", 7, unary(U32, U32, 32, True)),
|
||||
("S_BREV_B32", 11, unary(U32, U32, 32, False)),
|
||||
("S_SEXT_I32_I8", 25, unary(I32, "FMT_NUM_I8", 8, False)),
|
||||
):
|
||||
variants[(name, "ENC_SOP1")] = {
|
||||
"instruction": name, "encoding": "ENC_SOP1", "opcode": opcode, "operands": operands,
|
||||
}
|
||||
return {
|
||||
"source": {"sha256": SHA},
|
||||
"encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1},
|
||||
"variants": variants,
|
||||
}
|
||||
|
||||
|
||||
def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
|
||||
@@ -80,20 +127,60 @@ def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
|
||||
}
|
||||
|
||||
|
||||
def unaries():
|
||||
reg = registry()
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["sop1_sgpr"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.OPERAND_RULES["sop1_sgpr"]["unsupported"])
|
||||
reg["operand_rules"]["sop1_sgpr"] = rule
|
||||
|
||||
def unary(name, opcode, variant, operation, signedness, scc, **extra):
|
||||
form = _form(name, opcode, variant, operation, signedness, scc)
|
||||
form.update(family="SOP1", operands="sop1_sgpr", **extra)
|
||||
return form
|
||||
|
||||
reg["form"] += [
|
||||
unary("S_NOT_B32", 7, "NotB32", "not", "bitwise", "nonzero"),
|
||||
unary("S_BREV_B32", 11, "BrevB32", "brev", "bitwise", "unchanged"),
|
||||
unary("S_SEXT_I32_I8", 25, "SextI32I8", "sext", "signed", "unchanged", source_bits=8),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def compares():
|
||||
reg = registry()
|
||||
reg["form"] += [
|
||||
_compare("S_CMP_LT_I32", 4, "CmpLtI32", "lt", "signed"),
|
||||
_compare("S_CMP_LT_U32", 10, "CmpLtU32", "lt", "unsigned"),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def _compare(name, opcode, variant, relation, signedness):
|
||||
form = _form(name, opcode, variant, "compare", signedness, "relation")
|
||||
form.update(family="SOPC", relation=relation, operands="sopc_scalar")
|
||||
return form
|
||||
|
||||
|
||||
def registry():
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["sop2_sgpr"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.UNSUPPORTED_COMBOS)
|
||||
compare_rule = copy.deepcopy(gen.OPERAND_RULES["sopc_scalar"]["shape"])
|
||||
compare_rule["unsupported"] = sorted(gen.OPERAND_RULES["sopc_scalar"]["unsupported"])
|
||||
return {
|
||||
"schema": 1,
|
||||
"architecture": "gfx1030",
|
||||
"source_sha256": SHA,
|
||||
"documents": copy.deepcopy(gen.PINNED_DOCUMENTS),
|
||||
"operand_rules": {"sop2_sgpr": rule},
|
||||
"operand_rules": {"sop2_sgpr": rule, "sopc_scalar": compare_rule},
|
||||
"form": [
|
||||
_form("S_ADD_U32", 0, "AddU32", "add", "unsigned", "carry_out"),
|
||||
_form("S_ADD_I32", 2, "AddI32", "add", "signed", "signed_overflow"),
|
||||
_form("S_ADDC_U32", 4, "AddcU32", "add", "unsigned", "carry_out", carry_in="scc"),
|
||||
_form("S_AND_B32", 14, "AndB32", "and", "bitwise", "nonzero"),
|
||||
dict(
|
||||
_form("S_ASHR_I32", 34, "AshrI32", "ashr", "signed", "nonzero"),
|
||||
shift_count_bits=5,
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
@@ -233,7 +320,9 @@ class Validate(unittest.TestCase):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["family"] = "SOPC"
|
||||
self.rejects(reg, "S_ADD_U32: operand rule sop2_sgpr is for SOP2")
|
||||
self.rejects(reg, "S_ADD_U32: family SOPC has no XML encoding ENC_SOPC")
|
||||
self.rejects(reg, "S_ADD_U32: no default ENC_SOPC variant in the XML snapshot")
|
||||
form(reg, "S_ADD_U32")["family"] = "SOPK"
|
||||
self.rejects(reg, "S_ADD_U32: family SOPK has no XML encoding ENC_SOPK")
|
||||
|
||||
def test_rejects_form_absent_from_the_xml(self):
|
||||
reg = registry()
|
||||
@@ -288,6 +377,148 @@ class Validate(unittest.TestCase):
|
||||
reg["operand_rules"]["sop2_sgpr"]["max_literals"] = 2
|
||||
self.rejects(reg, "operand rule sop2_sgpr: declaration differs")
|
||||
|
||||
def test_rejects_a_shift_without_a_count_width(self):
|
||||
reg = registry()
|
||||
del reg["form"][-1]["shift_count_bits"]
|
||||
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got None")
|
||||
|
||||
def test_rejects_a_wrong_count_width(self):
|
||||
reg = registry()
|
||||
reg["form"][-1]["shift_count_bits"] = 6
|
||||
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got 6")
|
||||
|
||||
def test_rejects_a_count_width_on_a_non_shift(self):
|
||||
reg = registry()
|
||||
reg["form"][0]["shift_count_bits"] = 5
|
||||
self.rejects(reg, "S_ADD_U32: shift_count_bits on a non-shift operation")
|
||||
|
||||
def test_rejects_a_signed_shift_count_in_the_xml(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(I32)
|
||||
self.rejects(registry(), "S_ASHR_I32: shift count SSRC1 has XML format FMT_NUM_I32", snap)
|
||||
|
||||
def test_rejects_a_float_shift_count_in_the_xml(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_ASHR_I32", "ENC_SOP2")]["operands"] = _operands(
|
||||
I32, src1_format="FMT_NUM_F32"
|
||||
)
|
||||
self.rejects(registry(), "S_ASHR_I32: shift count SSRC1 has XML format FMT_NUM_F32", snap)
|
||||
|
||||
def test_rejects_a_float_source_format(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_AND_B32", "ENC_SOP2")]["operands"] = _operands("FMT_NUM_F32")
|
||||
self.rejects(registry(), "S_AND_B32: signedness bitwise contradicts XML format FMT_NUM_F32", snap)
|
||||
|
||||
def test_rejects_a_negative_count_width(self):
|
||||
reg = registry()
|
||||
reg["form"][-1]["shift_count_bits"] = -1
|
||||
self.rejects(reg, "S_ASHR_I32: shift_count_bits must be log2 of the width (32), got -1")
|
||||
|
||||
def test_rejects_an_unsigned_arithmetic_shift(self):
|
||||
reg = registry()
|
||||
reg["form"][-1]["signedness"] = "unsigned"
|
||||
self.rejects(reg, "S_ASHR_I32: no primitive implements ashr/unsigned")
|
||||
|
||||
def test_renders_the_declared_count_mask(self):
|
||||
self.assertIn(
|
||||
"Self::AshrI32 => primitive::ashr_nonzero_i32(src0, src1 & 0x1f),",
|
||||
gen.render(registry(), snapshot()),
|
||||
)
|
||||
|
||||
def test_accepts_unaries(self):
|
||||
self.assertEqual(self.errors(unaries()), [])
|
||||
|
||||
def test_rejects_a_sext_without_source_bits(self):
|
||||
reg = unaries()
|
||||
del reg["form"][-1]["source_bits"]
|
||||
self.rejects(reg, "S_SEXT_I32_I8: source_bits must be one of [8, 16], got None")
|
||||
|
||||
def test_rejects_a_sext_whose_source_bits_contradict_the_xml(self):
|
||||
reg = unaries()
|
||||
reg["form"][-1]["source_bits"] = 16
|
||||
self.rejects(reg, "S_SEXT_I32_I8: SSRC0 is 8 bits in the XML, declared 16")
|
||||
self.rejects(reg, "S_SEXT_I32_I8: SSRC0 has XML format FMT_NUM_I8, not FMT_NUM_I16")
|
||||
|
||||
def test_rejects_source_bits_on_another_operation(self):
|
||||
reg = unaries()
|
||||
reg["form"][-2]["source_bits"] = 8
|
||||
self.rejects(reg, "S_BREV_B32: source_bits on a non-sext operation")
|
||||
|
||||
def test_rejects_an_scc_write_the_xml_does_not_show(self):
|
||||
reg = unaries()
|
||||
reg["form"][-2]["operation"] = "not"
|
||||
reg["form"][-2]["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_BREV_B32: scc nonzero contradicts the XML SCC output")
|
||||
|
||||
def test_rejects_a_unary_operation_under_a_binary_rule(self):
|
||||
reg = unaries()
|
||||
reg["form"][0]["operation"] = "not"
|
||||
reg["form"][0]["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_ADD_U32: operation not does not fit rule sop2_sgpr")
|
||||
|
||||
def test_renders_unary_scc_as_optional(self):
|
||||
text = gen.render(unaries(), snapshot())
|
||||
self.assertIn("Self::BrevB32 => (primitive::brev_b32(src), None),", text)
|
||||
self.assertIn("Self::SextI32I8 => (primitive::sext_i32(src, 8), None),", text)
|
||||
self.assertIn("let (value, scc) = primitive::not_nonzero_b32(src);", text)
|
||||
|
||||
def test_accepts_compares(self):
|
||||
self.assertEqual(self.errors(compares()), [])
|
||||
|
||||
def test_rejects_a_compare_without_a_relation(self):
|
||||
reg = compares()
|
||||
del reg["form"][-1]["relation"]
|
||||
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation None")
|
||||
|
||||
def test_rejects_an_unknown_relation(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["relation"] = "ne"
|
||||
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation 'ne'")
|
||||
|
||||
def test_rejects_a_non_string_relation(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["relation"] = ["lt"]
|
||||
self.rejects(reg, "S_CMP_LT_U32: unknown or missing relation ['lt']")
|
||||
|
||||
def test_rejects_a_rule_without_sources(self):
|
||||
reg = compares()
|
||||
del reg["operand_rules"]["sopc_scalar"]["src"]
|
||||
self.rejects(reg, "operand rule sopc_scalar: declaration differs from the decoder's implemented rule")
|
||||
|
||||
def test_rejects_a_relation_on_a_non_compare(self):
|
||||
reg = compares()
|
||||
reg["form"][0]["relation"] = "lt"
|
||||
self.rejects(reg, "S_ADD_U32: relation on a non-compare operation")
|
||||
|
||||
def test_rejects_a_compare_with_another_scc_effect(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_CMP_LT_U32: scc nonzero contradicts compare (requires relation)")
|
||||
|
||||
def test_rejects_a_bitwise_compare(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["signedness"] = "bitwise"
|
||||
self.rejects(reg, "S_CMP_LT_U32: no primitive implements lt/bitwise")
|
||||
|
||||
def test_rejects_a_compare_whose_signedness_contradicts_the_xml(self):
|
||||
reg = compares()
|
||||
reg["form"][-1]["signedness"] = "signed"
|
||||
self.rejects(reg, "S_CMP_LT_U32: signedness signed contradicts XML format FMT_NUM_U32")
|
||||
|
||||
def test_rejects_a_compare_under_an_alu_rule(self):
|
||||
reg = compares()
|
||||
reg["form"][0]["operation"] = "compare"
|
||||
reg["form"][0]["relation"] = "lt"
|
||||
reg["form"][0]["scc"] = "relation"
|
||||
self.rejects(reg, "S_ADD_U32: operation compare does not fit rule sop2_sgpr")
|
||||
|
||||
def test_renders_compare_dispatch_and_relation(self):
|
||||
text = gen.render(compares(), snapshot())
|
||||
self.assertIn("if word & 0xff80_0000 != 0xbf00_0000 {", text)
|
||||
self.assertIn("Self::CmpLtI32 => primitive::lt_i32(src0, src1),", text)
|
||||
self.assertIn("Self::CmpLtU32 => primitive::lt_u32(src0, src1),", text)
|
||||
self.assertIn("relation: Some(CompareRelation::Less),", text)
|
||||
|
||||
def test_rejects_an_incomplete_unsupported_list(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["sop2_sgpr"]["unsupported"].remove("two_literals")
|
||||
@@ -424,14 +655,24 @@ class Render(unittest.TestCase):
|
||||
self.assertNotEqual(list(reg["form"][0]), list(reordered["form"][0]))
|
||||
self.assertEqual(gen.render(reg, snapshot()), gen.render(reordered, snapshot()))
|
||||
|
||||
def test_dispatch_is_sorted_by_opcode(self):
|
||||
def test_dispatch_table_is_indexed_by_opcode(self):
|
||||
reg = registry()
|
||||
reg["form"].reverse()
|
||||
text = gen.render(reg, snapshot())
|
||||
body = text.split("match word & ", 1)[1].split("_ => None", 1)[0]
|
||||
words = [line.split(" => ")[0].strip() for line in body.splitlines()[1:] if "=>" in line]
|
||||
self.assertEqual(words, sorted(words))
|
||||
self.assertEqual(len(words), 4)
|
||||
body = text.split("const SCALAR_ALU_OP_BY_OPCODE: [Option<ScalarAluOp>; 128] = [", 1)[1].split("];", 1)[0]
|
||||
rows = [line.strip() for line in body.splitlines() if line.strip()]
|
||||
self.assertEqual(len(rows), 128)
|
||||
declared = {index: row for index, row in enumerate(rows) if row != "None,"}
|
||||
self.assertEqual(sorted(declared), [0, 2, 4, 14, 34])
|
||||
self.assertEqual(declared[34], "Some(ScalarAluOp::AshrI32),")
|
||||
self.assertIn("if word & 0xc000_0000 != 0x8000_0000 {", text)
|
||||
self.assertIn("SCALAR_ALU_OP_BY_OPCODE[((word >> 23) & 0x7f) as usize]", text)
|
||||
|
||||
def test_rejects_identifiers_that_do_not_share_the_encoding_bits(self):
|
||||
snap = snapshot()
|
||||
snap["encodings"]["ENC_SOP2"]["identifiers"].append(0x40000000)
|
||||
with self.assertRaisesRegex(ValueError, "do not split into fixed bits and OP"):
|
||||
gen.render(registry(), snap)
|
||||
|
||||
def test_real_registry_renders_the_committed_file(self):
|
||||
text = gen.render(gen.load_registry(), gen.load_snapshot())
|
||||
|
||||
@@ -8,9 +8,12 @@
|
||||
//! field layout and executes them with an explicit program-counter machine, so
|
||||
//! a defect in the production decoder or reference cannot cancel out here.
|
||||
//!
|
||||
//! Scope matches the demo fixtures: scalar move/compare/branch, SOP2 unsigned
|
||||
//! Scope matches the demo fixtures: scalar move, eleven SOP1 unary forms
|
||||
//! (NOT, BREV, BCNT0/1, FF0/1, FLBIT, FLBIT_I32, SEXT_I8/I16, ABS), the twelve SOPC 32-bit integer
|
||||
//! compares, branch, SOP2 unsigned
|
||||
//! and signed add and subtract, add-with-carry, subtract-with-borrow, AND, OR
|
||||
//! and XOR, VOP1 move
|
||||
//! and XOR, the stage C forms ANDN2, ORN2, NAND, NOR, XNOR, LSHL, LSHR and
|
||||
//! ASHR (32-bit), VOP1 move
|
||||
//! (including from an SGPR),
|
||||
//! VOP2 bitwise, shift, arithmetic-shift and float, VOP3 add-no-carry, MUBUF
|
||||
//! load/store and the two waits plus `s_endpgm`. Anything else is a controlled
|
||||
@@ -50,9 +53,12 @@ enum CmpSrc {
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Insn {
|
||||
SMov(u8, Src),
|
||||
/// SOP2 opcode 0-5, 14, 16 or 18.
|
||||
/// SOP1 unary opcode 7, 11, 13, 15, 17, 19, 21, 23, 25, 26 or 52.
|
||||
SUnary(u32, u8, Src),
|
||||
/// SOP2 opcode 0-5, 14, 16, 18 or an even opcode 20-34.
|
||||
SAlu(u32, u8, Src, Src),
|
||||
SCmpEq(Src, Src),
|
||||
/// SOPC opcode 0-11: `s_cmp_{eq,lg,gt,ge,lt,le}_i32` then `_u32`.
|
||||
SCmp(u32, Src, Src),
|
||||
BranchScc0(usize),
|
||||
BranchMaskZero {
|
||||
target: usize,
|
||||
@@ -205,6 +211,20 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
None
|
||||
})
|
||||
}
|
||||
Insn::SUnary(opcode, dst, src) => {
|
||||
if dst < 8 {
|
||||
Err(format!("{offset:#x}: write to a resource SGPR"))
|
||||
} else {
|
||||
read_s(&sgpr, src).map(|value| {
|
||||
let (result, flag) = scalar_unary(opcode, value);
|
||||
sgpr[dst as usize] = Some(result);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
}
|
||||
Insn::SMov(dst, src) => {
|
||||
if dst < 8 {
|
||||
Err(format!("{offset:#x}: write to a resource SGPR"))
|
||||
@@ -218,9 +238,9 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
|
||||
})
|
||||
}
|
||||
}
|
||||
Insn::SCmpEq(a, b) => read_s(&sgpr, a).and_then(|a| {
|
||||
Insn::SCmp(opcode, a, b) => read_s(&sgpr, a).and_then(|a| {
|
||||
read_s(&sgpr, b).map(|b| {
|
||||
scc = Some(a == b);
|
||||
scc = Some(scalar_compare(opcode, a, b));
|
||||
None
|
||||
})
|
||||
}),
|
||||
@@ -320,6 +340,18 @@ fn scalar_alu(
|
||||
let (value, carry) = ripple(a, !b, !borrow);
|
||||
(value, !carry)
|
||||
}
|
||||
// RDNA 2 ISA guide 12.1: the shifts use only S1[4:0], taken here as
|
||||
// the remainder modulo 32, and scale by a power of two in exact
|
||||
// arithmetic; ASHR is floor division of the signed S0. SCC = D != 0.
|
||||
30 | 32 | 34 => {
|
||||
let scale = 1_i64 << (b % 32);
|
||||
let value = match opcode {
|
||||
30 => (i64::from(a) * scale).rem_euclid(1 << 32),
|
||||
32 => i64::from(a) / scale,
|
||||
_ => i64::from(a as i32).div_euclid(scale).rem_euclid(1 << 32),
|
||||
} as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
_ => {
|
||||
let mut value = 0;
|
||||
for bit in 0..32 {
|
||||
@@ -327,7 +359,12 @@ fn scalar_alu(
|
||||
let set = match opcode {
|
||||
14 => x && y,
|
||||
16 => x || y,
|
||||
_ => x != y,
|
||||
18 => x != y,
|
||||
20 => x && !y,
|
||||
22 => x || !y,
|
||||
24 => !(x && y),
|
||||
26 => !(x || y),
|
||||
_ => x == y,
|
||||
};
|
||||
value |= u32::from(set) << bit;
|
||||
}
|
||||
@@ -339,6 +376,69 @@ fn scalar_alu(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// RDNA 2 ISA guide 12.4: SCC = (S0 <relation> S1). Signed operands (opcodes
|
||||
/// 0-5) are ordered by flipping both sign bits and comparing unsigned.
|
||||
fn scalar_compare(opcode: u32, a: u32, b: u32) -> bool {
|
||||
let (a, b) = if opcode < 6 {
|
||||
(a ^ 0x8000_0000, b ^ 0x8000_0000)
|
||||
} else {
|
||||
(a, b)
|
||||
};
|
||||
match opcode % 6 {
|
||||
0 => a == b,
|
||||
1 => a != b,
|
||||
2 => a > b,
|
||||
3 => a >= b,
|
||||
4 => a < b,
|
||||
_ => a <= b,
|
||||
}
|
||||
}
|
||||
|
||||
/// RDNA 2 ISA guide 12.3, evaluated with arithmetic on the value (no host bit
|
||||
/// intrinsics): D and, for NOT, BCNT0, BCNT1 and ABS, SCC = (D != 0).
|
||||
fn scalar_unary(opcode: u32, value: u32) -> (u32, Option<bool>) {
|
||||
// The bits from the LSB, as repeated halving produces them.
|
||||
let mut bits = [false; 32];
|
||||
let mut rest = u64::from(value);
|
||||
for slot in &mut bits {
|
||||
*slot = rest % 2 == 1;
|
||||
rest /= 2;
|
||||
}
|
||||
let word = |bits: &dyn Fn(usize) -> bool| {
|
||||
(0..32).rev().fold(0u64, |w, i| w * 2 + u64::from(bits(i))) as u32
|
||||
};
|
||||
let position = |found: Option<usize>| found.map_or(u32::MAX, |i| i as u32);
|
||||
let ones = bits.iter().filter(|&&b| b).count() as u32;
|
||||
let result = match opcode {
|
||||
7 => 0xffff_ffff - value,
|
||||
11 => word(&|i| bits[31 - i]),
|
||||
13 => 32 - ones,
|
||||
15 => ones,
|
||||
17 => position(bits.iter().position(|&b| !b)),
|
||||
19 => position(bits.iter().position(|&b| b)),
|
||||
21 => position(bits.iter().rev().position(|&b| b)),
|
||||
23 => position(
|
||||
bits.iter()
|
||||
.rev()
|
||||
.skip(1)
|
||||
.position(|&b| b != bits[31])
|
||||
.map(|i| i + 1),
|
||||
),
|
||||
// signext of the low 8 or 16 bits: subtract 2^n when the value mod 2^n
|
||||
// is at least 2^(n-1).
|
||||
25 | 26 => {
|
||||
let span = if opcode == 25 { 256 } else { 65_536 };
|
||||
let low = i64::from(value) % span;
|
||||
let signed = if low >= span / 2 { low - span } else { low };
|
||||
signed.rem_euclid(1 << 32) as u32
|
||||
}
|
||||
// |S0| modulo 2^32, so INT_MIN stays 0x80000000.
|
||||
_ => i64::from(value as i32).abs().rem_euclid(1 << 32) as u32,
|
||||
};
|
||||
let flag = matches!(opcode, 7 | 13 | 15 | 52).then_some(result != 0);
|
||||
(result, flag)
|
||||
}
|
||||
|
||||
fn read_vgpr(lane: &Lane, reg: u8, offset: usize) -> Result<u32, String> {
|
||||
if reg == 0 {
|
||||
return Err(format!("{offset:#x}: v0 is the resource index"));
|
||||
@@ -786,6 +886,18 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
}
|
||||
return Ok((Insn::VAddNc(first as u8, src0 as u8, src1 as u8), 8));
|
||||
}
|
||||
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15.
|
||||
let sop1_op = (first >> 8) & 0xff;
|
||||
if first >> 23 == 0b1_0111_1101
|
||||
&& matches!(sop1_op, 7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52)
|
||||
{
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(fail("unsupported SOP1 destination"));
|
||||
}
|
||||
let (src, len) = scalar_source(code, offset, first as u8)?;
|
||||
return Ok((Insn::SUnary(sop1_op, dst, src), len));
|
||||
}
|
||||
if first & 0xff80_ff00 == 0xbe80_0300 {
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 107 && dst < 126 {
|
||||
@@ -795,7 +907,12 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
return Ok((Insn::SMov(dst, src), len));
|
||||
}
|
||||
// SOP2: ENCODING 0b10 in bits 30-31, OP in bits 23-29, SDST in 16-22.
|
||||
if first >> 30 == 0b10 && matches!((first >> 23) & 0x7f, 0..=5 | 14 | 16 | 18) {
|
||||
if first >> 30 == 0b10
|
||||
&& matches!(
|
||||
(first >> 23) & 0x7f,
|
||||
0..=5 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34
|
||||
)
|
||||
{
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(fail("unsupported SOP2 destination"));
|
||||
@@ -808,7 +925,8 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
let (sb, lb) = scalar_source(code, offset, b)?;
|
||||
return Ok((Insn::SAlu((first >> 23) & 0x7f, dst, sa, sb), la.max(lb)));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf06_0000 {
|
||||
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22.
|
||||
if first >> 23 == 0b1_0111_1110 && (first >> 16) & 0x7f <= 11 {
|
||||
let a = first as u8;
|
||||
let b = (first >> 8) as u8;
|
||||
if a == 255 && b == 255 {
|
||||
@@ -816,7 +934,7 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
}
|
||||
let (sa, la) = scalar_source(code, offset, a)?;
|
||||
let (sb, lb) = scalar_source(code, offset, b)?;
|
||||
return Ok((Insn::SCmpEq(sa, sb), la.max(lb)));
|
||||
return Ok((Insn::SCmp((first >> 16) & 0x7f, sa, sb), la.max(lb)));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xbf82_0000 {
|
||||
return Ok((Insn::Branch(branch_target(first, offset)?), 4));
|
||||
|
||||
@@ -768,6 +768,15 @@ mod review {
|
||||
}
|
||||
|
||||
const SCALAR_ALU_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-alu.bin");
|
||||
const SCALAR_LOGIC_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-logic.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-logic.s from the guide's 12.1 pseudocode.
|
||||
const SCALAR_LOGIC_KEY: u32 = 0x887f_00f8;
|
||||
const SCALAR_COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-compare.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-compare.s from the guide's 12.4 pseudocode.
|
||||
const SCALAR_COMPARE_KEY: u32 = 0x0000_0d5b;
|
||||
const SCALAR_UNARY_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-unary.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-unary.s from the guide's 12.3 pseudocode.
|
||||
const SCALAR_UNARY_KEY: u32 = 0x0f00_80f5;
|
||||
// SOP2 opcodes of the supported subset (RDNA 2 XML opcode table).
|
||||
const SOP2_OPCODES: [u32; 9] = [0, 1, 2, 3, 4, 5, 14, 16, 18];
|
||||
const SCALAR_VALUES: [u32; 10] = [
|
||||
@@ -869,6 +878,51 @@ mod review {
|
||||
verify(&nonzero, &input, Some(&[0; 5]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_logic_fixture_chains_registry_logical_and_shift_forms() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_LOGIC_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
|
||||
verify(SCALAR_LOGIC_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_LOGIC_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_ashr_i32 s17, s15, 31"));
|
||||
// The SCC-zero edge is observable: with a shift count of 30 instead of
|
||||
// 31, s17 = 0x787ffff8 >> 30 = 1, SCC = 1, and v2 = 0.
|
||||
let mut nonzero = SCALAR_LOGIC_FIXTURE.to_vec();
|
||||
let at = nonzero
|
||||
.windows(4)
|
||||
.position(|word| word == [0x0f, 0x9f, 0x11, 0x91])
|
||||
.unwrap();
|
||||
nonzero[at + 1] = 0x9e;
|
||||
verify(&nonzero, &input, Some(&[0; 5]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_fixture_records_every_registry_compare() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_COMPARE_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect();
|
||||
verify(SCALAR_COMPARE_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_COMPARE_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_cmp_le_u32 s9, 64"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_fixture_chains_registry_unary_forms() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_UNARY_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_UNARY_KEY).collect();
|
||||
verify(SCALAR_UNARY_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_UNARY_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_abs_i32 s20, 0"));
|
||||
// SCC stays clear across the SEXT and FF1 that follow s_abs_i32 s20, 0:
|
||||
// with s_abs_i32 s20, 1 instead, SCC = 1 and v2 = 0.
|
||||
let mut set = SCALAR_UNARY_FIXTURE.to_vec();
|
||||
let at = set
|
||||
.windows(4)
|
||||
.position(|word| word == [0x80, 0x34, 0x94, 0xbe])
|
||||
.unwrap();
|
||||
set[at] = 0x81;
|
||||
verify(&set, &input, Some(&[0; 5]));
|
||||
}
|
||||
|
||||
/// The translator's own folding: v2 = D as a constant, and the SCC-zero edge
|
||||
/// is taken exactly when SCC is clear.
|
||||
fn assert_translated(code: &[u8], expected: &[u32; 2]) {
|
||||
@@ -1089,6 +1143,12 @@ mod review {
|
||||
let input: Vec<u32> = (0..64).map(|lane| lane * 0x0101_0101).collect();
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ 0x0000_000e).collect();
|
||||
assert_eq!(run(SCALAR_ALU_FIXTURE, &input), expected);
|
||||
let logic: Vec<_> = input.iter().map(|word| word ^ SCALAR_LOGIC_KEY).collect();
|
||||
assert_eq!(run(SCALAR_LOGIC_FIXTURE, &input), logic);
|
||||
let compares: Vec<_> = input.iter().map(|word| word ^ SCALAR_COMPARE_KEY).collect();
|
||||
assert_eq!(run(SCALAR_COMPARE_FIXTURE, &input), compares);
|
||||
let unary: Vec<_> = input.iter().map(|word| word ^ SCALAR_UNARY_KEY).collect();
|
||||
assert_eq!(run(SCALAR_UNARY_FIXTURE, &input), unary);
|
||||
let mut vectors = sop2_vectors();
|
||||
vectors.extend(sop2_operand_cases());
|
||||
vectors.extend(signed_immediate_overflows());
|
||||
@@ -1097,7 +1157,7 @@ mod review {
|
||||
}
|
||||
eprintln!(
|
||||
"{} SOP2 programs matched on native Metal",
|
||||
vectors.len() + 1
|
||||
vectors.len() + 4
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,524 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for eleven 32-bit SOP1 unary forms (#215):
|
||||
//! `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
|
||||
//! `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
|
||||
//! `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.3 "SOP1 Instructions"
|
||||
//! (pseudocode and functional examples), Tables 12 and 14 in section 5 (which
|
||||
//! forms set SCC), section 13.1.3 for the SOP1 word and the scalar operand
|
||||
//! table for inline integer constants. Nothing here comes from the ISA crate,
|
||||
//! the semantic registry, the decoder or the shader compiler. Every case runs
|
||||
//! on the reference interpreter `xenora_ref` and on the second interpreter
|
||||
//! `independent_ref`; the ignored test also runs the translated MSL on native
|
||||
//! Metal.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod harness;
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harness::{Case, words};
|
||||
use xenora_shader::{Architecture, CompileError, compile};
|
||||
|
||||
/// The eleven forms with their ENC_SOP1 opcodes (guide 12.3).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Form {
|
||||
Not = 7,
|
||||
Brev = 11,
|
||||
Bcnt0 = 13,
|
||||
Bcnt1 = 15,
|
||||
Ff0 = 17,
|
||||
Ff1 = 19,
|
||||
FlbitB32 = 21,
|
||||
FlbitI32 = 23,
|
||||
SextI8 = 25,
|
||||
SextI16 = 26,
|
||||
Abs = 52,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 11] = [
|
||||
(Form::Not, "s_not_b32"),
|
||||
(Form::Brev, "s_brev_b32"),
|
||||
(Form::Bcnt0, "s_bcnt0_i32_b32"),
|
||||
(Form::Bcnt1, "s_bcnt1_i32_b32"),
|
||||
(Form::Ff0, "s_ff0_i32_b32"),
|
||||
(Form::Ff1, "s_ff1_i32_b32"),
|
||||
(Form::FlbitB32, "s_flbit_i32_b32"),
|
||||
(Form::FlbitI32, "s_flbit_i32"),
|
||||
(Form::SextI8, "s_sext_i32_i8"),
|
||||
(Form::SextI16, "s_sext_i32_i16"),
|
||||
(Form::Abs, "s_abs_i32"),
|
||||
];
|
||||
|
||||
fn bit(value: u32, i: u32) -> bool {
|
||||
(value >> i) & 1 == 1
|
||||
}
|
||||
|
||||
/// The guide's D for `form` with S0 = `s0`, and the SCC after it: `Some` for
|
||||
/// the forms that write SCC, `None` for those that leave it unchanged. No form
|
||||
/// reads SCC.
|
||||
fn expect(form: Form, s0: u32) -> (u32, Option<bool>) {
|
||||
// Tables 12 and 14: NOT, BCNT0, BCNT1 and ABS set SCC ("SCC = (D != 0)",
|
||||
// "SCC=result not zero"); BREV, FF0, FF1, FLBIT and SEXT have "n".
|
||||
let not_zero = |d: u32| (d, Some(d != 0));
|
||||
match form {
|
||||
// 7 S_NOT_B32: D = ~S0; SCC = (D != 0).
|
||||
Form::Not => not_zero(!s0),
|
||||
// 11 S_BREV_B32: D.u[31:0] = S0.u[0:31].
|
||||
Form::Brev => (
|
||||
(0..32).fold(0, |d, i| d | u32::from(bit(s0, 31 - i)) << i),
|
||||
None,
|
||||
),
|
||||
// 13 S_BCNT0_I32_B32: D = 0; for i in 0..31: D += (S0[i] == 0 ? 1 : 0);
|
||||
// SCC = (D != 0).
|
||||
Form::Bcnt0 => not_zero((0..32).filter(|&i| !bit(s0, i)).count() as u32),
|
||||
// 15 S_BCNT1_I32_B32: D += (S0[i] == 1 ? 1 : 0); SCC = (D != 0).
|
||||
Form::Bcnt1 => not_zero((0..32).filter(|&i| bit(s0, i)).count() as u32),
|
||||
// 17 S_FF0_I32_B32: D.i = -1; for i in 0..31 (from the LSB): if
|
||||
// S0[i] == 0 then D.i = i; break.
|
||||
Form::Ff0 => ((0..32).find(|&i| !bit(s0, i)).unwrap_or(u32::MAX), None),
|
||||
// 19 S_FF1_I32_B32: D.i = -1; for i in 0..31: if S0[i] == 1 then
|
||||
// D.i = i; break.
|
||||
Form::Ff1 => ((0..32).find(|&i| bit(s0, i)).unwrap_or(u32::MAX), None),
|
||||
// 21 S_FLBIT_I32_B32: D.i = -1; for i in 0..31: if S0[31 - i] == 1
|
||||
// then D.i = i; break. (Zeros before the first one from the MSB.)
|
||||
Form::FlbitB32 => ((0..32).find(|&i| bit(s0, 31 - i)).unwrap_or(u32::MAX), None),
|
||||
// 23 S_FLBIT_I32: D.i = -1; for i in 1..31: if S0[31 - i] != S0[31]
|
||||
// then D.i = i; break. Table 14: -1 if the input is 0 or -1.
|
||||
Form::FlbitI32 => (
|
||||
(1..32)
|
||||
.find(|&i| bit(s0, 31 - i) != bit(s0, 31))
|
||||
.unwrap_or(u32::MAX),
|
||||
None,
|
||||
),
|
||||
// 25 S_SEXT_I32_I8: D.i = signext(S0.i[7:0]), i.e. { 24{S0[7]}, S0[7:0] }.
|
||||
Form::SextI8 => (
|
||||
if bit(s0, 7) {
|
||||
s0 | 0xffff_ff00
|
||||
} else {
|
||||
s0 & 0xff
|
||||
},
|
||||
None,
|
||||
),
|
||||
// 26 S_SEXT_I32_I16: D.i = signext(S0.i[15:0]), i.e. { 16{S0[15]}, S0[15:0] }.
|
||||
Form::SextI16 => (
|
||||
if bit(s0, 15) {
|
||||
s0 | 0xffff_0000
|
||||
} else {
|
||||
s0 & 0xffff
|
||||
},
|
||||
None,
|
||||
),
|
||||
// 52 S_ABS_I32: D.i = (S.i < 0 ? -S.i : S.i); SCC = (D.i != 0). The
|
||||
// guide's example keeps 0x80000000 ("Note this is negative!").
|
||||
Form::Abs => not_zero(if bit(s0, 31) {
|
||||
(!s0).wrapping_add(1)
|
||||
} else {
|
||||
s0
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The functional examples printed in guide 12.3, with D only; the final five
|
||||
/// are derived from the pseudocode, as their comment says.
|
||||
const GUIDE_EXAMPLES: [(Form, u32, u32); 39] = [
|
||||
(Form::Bcnt0, 0x0000_0000, 32),
|
||||
(Form::Bcnt0, 0xcccc_cccc, 16),
|
||||
(Form::Bcnt0, 0xffff_ffff, 0),
|
||||
(Form::Bcnt1, 0x0000_0000, 0),
|
||||
(Form::Bcnt1, 0xcccc_cccc, 16),
|
||||
(Form::Bcnt1, 0xffff_ffff, 32),
|
||||
(Form::Ff0, 0xaaaa_aaaa, 0),
|
||||
(Form::Ff0, 0x5555_5555, 1),
|
||||
(Form::Ff0, 0x0000_0000, 0),
|
||||
(Form::Ff0, 0xffff_ffff, 0xffff_ffff),
|
||||
(Form::Ff0, 0xfffe_ffff, 16),
|
||||
(Form::Ff1, 0xaaaa_aaaa, 1),
|
||||
(Form::Ff1, 0x5555_5555, 0),
|
||||
(Form::Ff1, 0x0000_0000, 0xffff_ffff),
|
||||
(Form::Ff1, 0xffff_ffff, 0),
|
||||
(Form::Ff1, 0x0001_0000, 16),
|
||||
(Form::FlbitB32, 0x0000_0000, 0xffff_ffff),
|
||||
(Form::FlbitB32, 0x0000_cccc, 16),
|
||||
(Form::FlbitB32, 0xffff_3333, 0),
|
||||
(Form::FlbitB32, 0x7fff_ffff, 1),
|
||||
(Form::FlbitB32, 0x8000_0000, 0),
|
||||
(Form::FlbitB32, 0xffff_ffff, 0),
|
||||
(Form::FlbitI32, 0x0000_0000, 0xffff_ffff),
|
||||
(Form::FlbitI32, 0x0000_cccc, 16),
|
||||
(Form::FlbitI32, 0xffff_3333, 16),
|
||||
(Form::FlbitI32, 0x7fff_ffff, 1),
|
||||
(Form::FlbitI32, 0x8000_0000, 1),
|
||||
(Form::FlbitI32, 0xffff_ffff, 0xffff_ffff),
|
||||
(Form::Abs, 0x0000_0001, 0x0000_0001),
|
||||
(Form::Abs, 0x7fff_ffff, 0x7fff_ffff),
|
||||
(Form::Abs, 0x8000_0000, 0x8000_0000),
|
||||
(Form::Abs, 0x8000_0001, 0x7fff_ffff),
|
||||
(Form::Abs, 0x8000_0002, 0x7fff_fffe),
|
||||
(Form::Abs, 0xffff_ffff, 0x0000_0001),
|
||||
// Not printed as examples; direct readings of the one-line pseudocode.
|
||||
(Form::Not, 0x0f0f_0000, 0xf0f0_ffff),
|
||||
(Form::Brev, 0x0000_0001, 0x8000_0000),
|
||||
(Form::Brev, 0x1234_5678, 0x1e6a_2c48),
|
||||
(Form::SextI8, 0x1234_5680, 0xffff_ff80),
|
||||
(Form::SextI16, 0x1234_7fff, 0x0000_7fff),
|
||||
];
|
||||
|
||||
/// Guide scalar operand table: 128 is 0, 129-192 are 1 to 64 and 193-208 are
|
||||
/// -1 to -16, as 32-bit words.
|
||||
fn inline_integer(selector: u32) -> u32 {
|
||||
match selector {
|
||||
128..=192 => selector - 128,
|
||||
193..=208 => (-((selector - 192) as i32)) as u32,
|
||||
_ => unreachable!("not an integer inline constant"),
|
||||
}
|
||||
}
|
||||
|
||||
const LITERAL: u32 = 255;
|
||||
/// Boundaries, alternating patterns, the guide's example inputs and values
|
||||
/// whose low 8 or 16 bits have the sign bit set (or just clear).
|
||||
const VALUES: [u32; 24] = [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
0xaaaa_aaaa,
|
||||
0x5555_5555,
|
||||
0xcccc_cccc,
|
||||
0x0000_cccc,
|
||||
0xffff_3333,
|
||||
0xfffe_ffff,
|
||||
0x0001_0000,
|
||||
0x0000_007f,
|
||||
0x0000_0080,
|
||||
0x0000_00ff,
|
||||
0x0000_7fff,
|
||||
0x0000_8000,
|
||||
0x0000_ffff,
|
||||
0xffff_ff7f,
|
||||
0x1234_8080,
|
||||
0x1234_5678,
|
||||
];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 7] = [
|
||||
("sop1 domain", 11 * 24 * 2),
|
||||
("sop1 single bit", 11 * 64 * 2),
|
||||
("sop1 guide example", 39 * 2),
|
||||
("sop1 inline integer", 11 * 81 * 2),
|
||||
("sop1 literal", 11 * 6 * 2),
|
||||
("sop1 aliasing", 11 * 3 * 2 * 2),
|
||||
("sop1 max register", 11 * 3 * 2),
|
||||
];
|
||||
/// Per form: 6 destinations and 15 sources outside the supported subset.
|
||||
const REJECTIONS: usize = 11 * (6 + 15);
|
||||
|
||||
/// ENCODING 0b10_1111101 in bits 23-31, SDST 16-22, OP 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.3).
|
||||
fn sop1(op: u32, dst: u32, src0: u32) -> u32 {
|
||||
0xbe80_0000 | dst << 16 | op << 8 | src0
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
|
||||
/// `scc` with `s_and_b32 s12, x, x` (x = 1 or 0), run `alu`, then
|
||||
/// v2 = s<result>, `s_cbranch_scc0` over `v_xor_b32 v2, v1, v2`, and store v2.
|
||||
/// With the lane input [0, !0] the output is [R, R] when SCC is clear after
|
||||
/// `alu` and [R, !R] when it is set.
|
||||
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init {
|
||||
code.extend([0xbe80_03ff | reg << 16, value]);
|
||||
}
|
||||
let x = if scc { 129 } else { 128 };
|
||||
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
/// The case for `form` with S0 = `s0` and SCC = `scc` before it, reading back
|
||||
/// `result`, whose value afterwards is `r` (D unless another register is read).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn case(
|
||||
(form, name): (Form, &'static str),
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
s0: u32,
|
||||
scc: bool,
|
||||
r: Option<u32>,
|
||||
) -> Case {
|
||||
let (d, written) = expect(form, s0);
|
||||
let r = r.unwrap_or(d);
|
||||
let label = format!("{name} {label}, scc before {scc}");
|
||||
let scc = written.unwrap_or(scc);
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label,
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![r, if scc { !r } else { r }],
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
for scc in [false, true] {
|
||||
let single = (0..32).flat_map(|k| [1 << k, !(1 << k)]);
|
||||
let values = VALUES.iter().map(|&v| (v, "sop1 domain"));
|
||||
let examples = GUIDE_EXAMPLES
|
||||
.iter()
|
||||
.filter(|example| example.0 == form)
|
||||
.map(|example| (example.1, "sop1 guide example"));
|
||||
let all = values
|
||||
.chain(single.map(|v| (v, "sop1 single bit")))
|
||||
.chain(examples);
|
||||
for (value, family) in all {
|
||||
let code = program(&[(8, value)], scc, &[sop1(op, 10, 8)], 10);
|
||||
let label = format!("{value:#x}");
|
||||
cases.push(case((form, name), family, label, code, value, scc, None));
|
||||
}
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
let code = program(&[], scc, &[sop1(op, 10, selector)], 10);
|
||||
let label = format!("inline {value:#x}");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 inline integer",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
}
|
||||
for value in [0, 1, 0x8000_0000, u32::MAX, 0x1234_8080, 0x0001_0000] {
|
||||
let code = program(&[], scc, &[sop1(op, 10, LITERAL), value], 10);
|
||||
let label = format!("literal {value:#x}");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 literal",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
}
|
||||
// s8 = op(s8), and s10 = op(s8) reading s8 back unchanged.
|
||||
for value in [0x8000_0000, 0x0000_80ff, u32::MAX] {
|
||||
let code = program(&[(8, value)], scc, &[sop1(op, 8, 8)], 8);
|
||||
let label = format!("s8 = op s8 ({value:#x})");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 aliasing",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
let code = program(&[(8, value)], scc, &[sop1(op, 10, 8)], 8);
|
||||
let label = format!("s8 kept after s10 = op s8 ({value:#x})");
|
||||
let kept = Some(value);
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 aliasing",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
kept,
|
||||
));
|
||||
}
|
||||
// The highest SGPR, s105 (0b1101001), as source, destination or both.
|
||||
let value = 0x0000_8001;
|
||||
for (dst, src, init) in [(105, 105, 105), (10, 105, 105), (105, 8, 8)] {
|
||||
let code = program(&[(init, value)], scc, &[sop1(op, dst, src)], dst);
|
||||
let label = format!("s{dst} = op s{src} ({value:#x})");
|
||||
cases.push(case(
|
||||
(form, name),
|
||||
"sop1 max register",
|
||||
label,
|
||||
code,
|
||||
value,
|
||||
scc,
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// The SOP1 word's byte offset in `program` with one init pair.
|
||||
const ALU_OFFSET: usize = 12 + 8 + 4;
|
||||
|
||||
/// Programs both interpreters must refuse at the SOP1 word.
|
||||
fn rejections() -> Vec<(String, Vec<u8>)> {
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
// VCC_LO, VCC_HI, M0, NULL, EXEC_LO, EXEC_HI as SDST.
|
||||
for dst in [106, 107, 124, 125, 126, 127] {
|
||||
let code = program(&[(8, 1)], false, &[sop1(op, dst, 8)], 10);
|
||||
all.push((format!("{name} destination {dst}"), code));
|
||||
}
|
||||
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, SCC, and the float inline
|
||||
// constants 240-248 as SSRC0.
|
||||
for src in [106, 107, 124, 126, 127, 253].into_iter().chain(240..=248) {
|
||||
let code = program(&[(8, 1)], false, &[sop1(op, 10, src)], 10);
|
||||
all.push((format!("{name} source {src}"), code));
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn assert_rejected_at_alu(label: &str, code: &[u8]) {
|
||||
match xenora_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(
|
||||
error.offset, ALU_OFFSET,
|
||||
"reference rejected {label} elsewhere"
|
||||
),
|
||||
}
|
||||
match independent_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{ALU_OFFSET:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expectations_reproduce_the_guide_examples() {
|
||||
for (form, s0, d) in GUIDE_EXAMPLES {
|
||||
assert_eq!(expect(form, s0).0, d, "{form:?}({s0:#x})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop1_unary_forms_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, |code, input| {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
});
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sop1_unary: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop1_unary_forms_match_the_guide_on_the_independent_interpreter() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, independent_ref::execute);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"independent interpreter disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sop1_unary: {} independent-interpreter cases", cases.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_sop1_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code) in &rejections {
|
||||
assert_rejected_at_alu(label, code);
|
||||
}
|
||||
eprintln!("sop1_unary: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_sop1_opcodes_stay_unsupported() {
|
||||
// Every 8-bit SOP1 opcode except s_mov_b32 (3) and the eleven forms.
|
||||
let supported: Vec<u32> = FORMS
|
||||
.iter()
|
||||
.map(|&(form, _)| form as u32)
|
||||
.chain([3])
|
||||
.collect();
|
||||
for op in (0..=255).filter(|op| !supported.contains(op)) {
|
||||
let code = program(&[(8, 1)], false, &[sop1(op, 10, 8)], 10);
|
||||
assert_rejected_at_alu(&format!("opcode {op}"), &code);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn sop1_unary_forms_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
for (label, code) in rejections() {
|
||||
// A decode error at the SOP1 word, so a later failure cannot stand in.
|
||||
match compile(Architecture::Gfx1030, &code) {
|
||||
Err(CompileError::Decode(error)) => assert_eq!(
|
||||
error.offset, ALU_OFFSET,
|
||||
"compiler rejected {label} elsewhere: {error:?}"
|
||||
),
|
||||
other => panic!("compiler did not reject {label} at decode: {other:?}"),
|
||||
}
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sop1_unary: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for the eight SOP2 forms added in #215 stage C:
|
||||
//! `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`,
|
||||
//! `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.1 "SOP2 Instructions" for
|
||||
//! D and SCC of each form, section 5.3 for the SCC rule of bit/logical
|
||||
//! operations, and the scalar operand table (section 3) for inline integer
|
||||
//! constants. Nothing here comes from the ISA crate, the semantic registry, the
|
||||
//! decoder or the shader compiler. Every case runs on the reference interpreter
|
||||
//! `xenora_ref` and on the second interpreter `independent_ref`; the ignored
|
||||
//! test also runs the translated MSL on native Metal.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod harness;
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harness::{Case, words};
|
||||
|
||||
/// The eight stage C forms with their ENC_SOP2 opcodes (guide 12.1).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Form {
|
||||
Andn2 = 20,
|
||||
Orn2 = 22,
|
||||
Nand = 24,
|
||||
Nor = 26,
|
||||
Xnor = 28,
|
||||
Lshl = 30,
|
||||
Lshr = 32,
|
||||
Ashr = 34,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 8] = [
|
||||
(Form::Andn2, "s_andn2_b32"),
|
||||
(Form::Orn2, "s_orn2_b32"),
|
||||
(Form::Nand, "s_nand_b32"),
|
||||
(Form::Nor, "s_nor_b32"),
|
||||
(Form::Xnor, "s_xnor_b32"),
|
||||
(Form::Lshl, "s_lshl_b32"),
|
||||
(Form::Lshr, "s_lshr_b32"),
|
||||
(Form::Ashr, "s_ashr_i32"),
|
||||
];
|
||||
|
||||
/// The guide's D and SCC for `form` with S0 = `s0` and S1 = `s1`. None of
|
||||
/// these forms reads SCC, so the value of SCC before the instruction is not an
|
||||
/// input.
|
||||
fn expect(form: Form, s0: u32, s1: u32) -> (u32, bool) {
|
||||
let d = match form {
|
||||
// 20 S_ANDN2_B32: D = S0 & ~S1; SCC = (D != 0).
|
||||
Form::Andn2 => s0 & !s1,
|
||||
// 22 S_ORN2_B32: D = S0 | ~S1; SCC = (D != 0).
|
||||
Form::Orn2 => s0 | !s1,
|
||||
// 24 S_NAND_B32: D = ~(S0 & S1); SCC = (D != 0).
|
||||
Form::Nand => !(s0 & s1),
|
||||
// 26 S_NOR_B32: D = ~(S0 | S1); SCC = (D != 0).
|
||||
Form::Nor => !(s0 | s1),
|
||||
// 28 S_XNOR_B32: D = ~(S0 ^ S1); SCC = (D != 0).
|
||||
Form::Xnor => !(s0 ^ s1),
|
||||
// 30 S_LSHL_B32: D.u = S0.u << S1.u[4:0]; SCC = (D.u != 0).
|
||||
Form::Lshl => s0 << (s1 & 0x1f),
|
||||
// 32 S_LSHR_B32: D.u = S0.u >> S1.u[4:0]; SCC = (D.u != 0).
|
||||
Form::Lshr => s0 >> (s1 & 0x1f),
|
||||
// 34 S_ASHR_I32: D.i = signext(S0.i) >> S1.u[4:0]; SCC = (D.i != 0).
|
||||
// S1 is read as unsigned and only its low five bits count, so its
|
||||
// sign never matters; the shift replicates S0's sign bit.
|
||||
Form::Ashr => ((s0 as i32) >> (s1 & 0x1f)) as u32,
|
||||
};
|
||||
// Section 5.3: bit/logical operations set SCC = 1 iff the result is not zero.
|
||||
(d, d != 0)
|
||||
}
|
||||
|
||||
/// Guide section 3 scalar operand table: 128 is 0, 129-192 are 1 to 64 and
|
||||
/// 193-208 are -1 to -16, as 32-bit words.
|
||||
fn inline_integer(selector: u32) -> u32 {
|
||||
match selector {
|
||||
128..=192 => selector - 128,
|
||||
193..=208 => (-((selector - 192) as i32)) as u32,
|
||||
_ => unreachable!("not an integer inline constant"),
|
||||
}
|
||||
}
|
||||
|
||||
const LITERAL: u32 = 255;
|
||||
/// Boundary operands and alternating bit patterns.
|
||||
const VALUES: [u32; 8] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0xffff_ffff,
|
||||
0xaaaa_aaaa,
|
||||
0x5555_5555,
|
||||
0x1234_5678,
|
||||
];
|
||||
/// Shift counts around the five-bit field, and one whose low bits are 1.
|
||||
const SHIFTS: [u32; 7] = [0, 1, 31, 32, 33, 63, 0xffff_ffe1];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 5] = [
|
||||
("stage c domain", 8 * 8 * 8 * 2),
|
||||
("stage c shift count", 3 * 8 * 7 * 2),
|
||||
("stage c aliasing", 8 * 2 * 5 * 2),
|
||||
("stage c inline integer", 8 * 81 * 2 * 2 * 2),
|
||||
("stage c literal", 8 * 6 * 2 * 2),
|
||||
];
|
||||
|
||||
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7.
|
||||
fn sop2(form: Form, dst: u32, src0: u32, src1: u32) -> u32 {
|
||||
0x8000_0000 | (form as u32) << 23 | dst << 16 | src1 << 8 | src0
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair, set SCC to
|
||||
/// `scc` with `s_cmp_eq_u32`, run `alu`, then v2 = s<result>, XORed with v1
|
||||
/// when SCC is set afterwards, and store v2. With the lane input [0, !0] the
|
||||
/// output is [D, D] when SCC is clear and [D, !D] when it is set.
|
||||
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init {
|
||||
code.extend([0xbe80_03ff | reg << 16, value]);
|
||||
}
|
||||
code.push(if scc { 0xbf06_8080 } else { 0xbf06_8180 });
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn case(
|
||||
name: &'static str,
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
out: (u32, bool),
|
||||
) -> Case {
|
||||
let (d, scc) = out;
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label: format!("{name} {label}"),
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![d, if scc { !d } else { d }],
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let shift = matches!(form, Form::Lshl | Form::Lshr | Form::Ashr);
|
||||
for scc in [false, true] {
|
||||
let alu = [sop2(form, 10, 8, 9)];
|
||||
let pairs = VALUES
|
||||
.iter()
|
||||
.flat_map(|&a| VALUES.map(|b| (a, b, "stage c domain")));
|
||||
let counts = VALUES
|
||||
.iter()
|
||||
.flat_map(|&a| SHIFTS.map(|b| (a, b, "stage c shift count")));
|
||||
let counts: Vec<_> = if shift { counts.collect() } else { Vec::new() };
|
||||
for (a, b, family) in pairs.chain(counts) {
|
||||
let code = program(&[(8, a), (9, b)], scc, &alu, 10);
|
||||
let label = format!("{a:#x}, {b:#x}, scc before {scc}");
|
||||
cases.push(case(name, family, label, code, expect(form, a, b)));
|
||||
}
|
||||
// dst/src aliasing with s8 = a, s9 = b.
|
||||
for (a, b) in [(0xffff_fff0, 0x21), (0x8000_0001, 0x8000_0001)] {
|
||||
for (dst, src0, src1) in [(8, 8, 9), (9, 8, 9), (8, 8, 8), (9, 9, 9), (8, 9, 8)] {
|
||||
let pick = |reg| if reg == 8 { a } else { b };
|
||||
let code = program(&[(8, a), (9, b)], scc, &[sop2(form, dst, src0, src1)], dst);
|
||||
let label =
|
||||
format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x}), scc before {scc}");
|
||||
let out = expect(form, pick(src0), pick(src1));
|
||||
cases.push(case(name, "stage c aliasing", label, code, out));
|
||||
}
|
||||
}
|
||||
// Every integer inline constant (-16..64) in each source slot. The
|
||||
// register operand s8 takes a word and its complement, so a wrong
|
||||
// inline value changes D for at least one of them (as a shift
|
||||
// count it is 0x40 and 0x21, i.e. counts 0 and 1).
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
for (slot, other) in [0, 1].into_iter().flat_map(|slot| {
|
||||
let others = if slot == 0 && shift {
|
||||
[0x40, 0x21]
|
||||
} else {
|
||||
[0x8000_0f0f, 0x7fff_f0f0]
|
||||
};
|
||||
others.map(|other| (slot, other))
|
||||
}) {
|
||||
let (alu, out) = if slot == 0 {
|
||||
(sop2(form, 10, selector, 8), expect(form, value, other))
|
||||
} else {
|
||||
(sop2(form, 10, 8, selector), expect(form, other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], scc, &[alu], 10);
|
||||
let label =
|
||||
format!("inline {value:#x} in src{slot}, s8 {other:#x}, scc before {scc}");
|
||||
cases.push(case(name, "stage c inline integer", label, code, out));
|
||||
}
|
||||
}
|
||||
// A 32-bit literal dword after the SOP2 word in each source slot.
|
||||
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0xffff_ffe1] {
|
||||
for slot in 0..2 {
|
||||
let other = 0xc000_0003;
|
||||
let (alu, out) = if slot == 0 {
|
||||
(
|
||||
[sop2(form, 10, LITERAL, 8), value],
|
||||
expect(form, value, other),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
[sop2(form, 10, 8, LITERAL), value],
|
||||
expect(form, other, value),
|
||||
)
|
||||
};
|
||||
let code = program(&[(8, other)], scc, &alu, 10);
|
||||
let label = format!("literal {value:#x} in src{slot}, scc before {scc}");
|
||||
cases.push(case(name, "stage c literal", label, code, out));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_c_forms_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, |code, input| {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
});
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sop2_stage_c: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_c_forms_match_the_guide_on_the_independent_interpreter() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, independent_ref::execute);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"independent interpreter disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!(
|
||||
"sop2_stage_c: {} independent-interpreter cases",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_opcodes_beside_the_stage_c_forms_stay_unsupported() {
|
||||
// The 64-bit neighbours (opcodes 21-35 odd) read aligned SGPR pairs
|
||||
// (s[10:11] = s[8:9] op s[12:13], all initialized); neither interpreter
|
||||
// supports them, so each must refuse the SOP2 word.
|
||||
for op in (21..=35).step_by(2) {
|
||||
let alu = [0x8000_0000 | op << 23 | 10 << 16 | 12 << 8 | 8];
|
||||
let init = [(8, 1), (9, 2), (12, 3), (13, 4)];
|
||||
let code = program(&init, false, &alu, 10);
|
||||
assert!(
|
||||
xenora_ref::execute(&code, &INPUT).is_err(),
|
||||
"reference accepted opcode {op}"
|
||||
);
|
||||
assert!(
|
||||
independent_ref::execute(&code, &INPUT).is_err(),
|
||||
"independent accepted opcode {op}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn stage_c_forms_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sop2_stage_c: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for the twelve SOPC 32-bit integer compares of
|
||||
//! #215 stage D: `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.4 "SOPC Instructions" for
|
||||
//! the SCC of each form, section 13.1.4 for the SOPC word, section 5.3 (compare
|
||||
//! operations set SCC = 1 when true) and the scalar operand table for inline
|
||||
//! integer constants. Nothing here comes from the ISA crate, the semantic
|
||||
//! registry, the decoder or the shader compiler. Every case runs on the
|
||||
//! reference interpreter `xenora_ref` and on the second interpreter
|
||||
//! `independent_ref`; the ignored test also runs the translated MSL on native
|
||||
//! Metal.
|
||||
|
||||
#[path = "operand_domains/harness.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod harness;
|
||||
#[path = "../independent_ref.rs"]
|
||||
mod independent_ref;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harness::{Case, words};
|
||||
use xenora_shader::{Architecture, compile};
|
||||
|
||||
/// The twelve forms with their ENC_SOPC opcodes (guide 12.4, Table 70).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Form {
|
||||
EqI32 = 0,
|
||||
LgI32 = 1,
|
||||
GtI32 = 2,
|
||||
GeI32 = 3,
|
||||
LtI32 = 4,
|
||||
LeI32 = 5,
|
||||
EqU32 = 6,
|
||||
LgU32 = 7,
|
||||
GtU32 = 8,
|
||||
GeU32 = 9,
|
||||
LtU32 = 10,
|
||||
LeU32 = 11,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 12] = [
|
||||
(Form::EqI32, "s_cmp_eq_i32"),
|
||||
(Form::LgI32, "s_cmp_lg_i32"),
|
||||
(Form::GtI32, "s_cmp_gt_i32"),
|
||||
(Form::GeI32, "s_cmp_ge_i32"),
|
||||
(Form::LtI32, "s_cmp_lt_i32"),
|
||||
(Form::LeI32, "s_cmp_le_i32"),
|
||||
(Form::EqU32, "s_cmp_eq_u32"),
|
||||
(Form::LgU32, "s_cmp_lg_u32"),
|
||||
(Form::GtU32, "s_cmp_gt_u32"),
|
||||
(Form::GeU32, "s_cmp_ge_u32"),
|
||||
(Form::LtU32, "s_cmp_lt_u32"),
|
||||
(Form::LeU32, "s_cmp_le_u32"),
|
||||
];
|
||||
|
||||
/// The guide's SCC for `form` with S0 = `s0` (SSRC0, the left operand) and
|
||||
/// S1 = `s1` (SSRC1). The compares write no SGPR and read no SCC.
|
||||
fn expect(form: Form, s0: u32, s1: u32) -> bool {
|
||||
let (i0, i1) = (s0 as i32, s1 as i32);
|
||||
match form {
|
||||
// 0 S_CMP_EQ_I32 and 6 S_CMP_EQ_U32 ("identical opcodes"): SCC = (S0 == S1).
|
||||
Form::EqI32 | Form::EqU32 => s0 == s1,
|
||||
// 1 S_CMP_LG_I32 and 7 S_CMP_LG_U32 ("identical opcodes"): SCC = (S0 != S1).
|
||||
Form::LgI32 | Form::LgU32 => s0 != s1,
|
||||
// 2 S_CMP_GT_I32: SCC = (S0.i > S1.i).
|
||||
Form::GtI32 => i0 > i1,
|
||||
// 3 S_CMP_GE_I32: SCC = (S0.i >= S1.i).
|
||||
Form::GeI32 => i0 >= i1,
|
||||
// 4 S_CMP_LT_I32: SCC = (S0.i < S1.i).
|
||||
Form::LtI32 => i0 < i1,
|
||||
// 5 S_CMP_LE_I32: SCC = (S0.i <= S1.i).
|
||||
Form::LeI32 => i0 <= i1,
|
||||
// 8 S_CMP_GT_U32: SCC = (S0.u > S1.u).
|
||||
Form::GtU32 => s0 > s1,
|
||||
// 9 S_CMP_GE_U32: SCC = (S0.u >= S1.u).
|
||||
Form::GeU32 => s0 >= s1,
|
||||
// 10 S_CMP_LT_U32: SCC = (S0.u < S1.u).
|
||||
Form::LtU32 => s0 < s1,
|
||||
// 11 S_CMP_LE_U32: SCC = (S0.u <= S1.u).
|
||||
Form::LeU32 => s0 <= s1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Guide scalar operand table: 128 is 0, 129-192 are 1 to 64 and 193-208 are
|
||||
/// -1 to -16, as 32-bit words.
|
||||
fn inline_integer(selector: u32) -> u32 {
|
||||
match selector {
|
||||
128..=192 => selector - 128,
|
||||
193..=208 => (-((selector - 192) as i32)) as u32,
|
||||
_ => unreachable!("not an integer inline constant"),
|
||||
}
|
||||
}
|
||||
|
||||
const LITERAL: u32 = 255;
|
||||
/// Signed and unsigned boundaries and their neighbours.
|
||||
const VALUES: [u32; 8] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_fffe,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
];
|
||||
/// The value s10 holds throughout; the output shows it unchanged.
|
||||
const MARKER: u32 = 0x0f0f_1234;
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 5] = [
|
||||
("sopc domain", 12 * 8 * 8 * 2),
|
||||
("sopc inline integer", 12 * 81 * 3 * 2),
|
||||
("sopc literal", 12 * 5 * 3 * 2),
|
||||
("sopc aliasing", 12 * 3),
|
||||
("sopc no sgpr write", 12 * 5),
|
||||
];
|
||||
/// Per form: two literals, 5 special registers and 9 float inline constants in
|
||||
/// each slot.
|
||||
const REJECTIONS: usize = 12 * (1 + (5 + 9) * 2);
|
||||
|
||||
/// ENCODING 0b10_1111110 in bits 23-31, OP 16-22, SSRC1 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.4).
|
||||
fn sopc(op: u32, src0: u32, src1: u32) -> u32 {
|
||||
0xbf00_0000 | op << 16 | src1 << 8 | src0
|
||||
}
|
||||
|
||||
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair and
|
||||
/// s10 = MARKER, set SCC to `scc` with `s_and_b32 s12, x, x` (x = 1 or 0, a
|
||||
/// SOP2 form, so no compare is involved), run `alu`, then v2 = s<result>,
|
||||
/// `s_cbranch_scc0` over `v_xor_b32 v2, v1, v2`, and store v2. With the lane
|
||||
/// input [0, !0] the output is [R, R] when SCC is clear (branch taken) and
|
||||
/// [R, !R] when it is set (fall through).
|
||||
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
for &(reg, value) in init.iter().chain(&[(10, MARKER)]) {
|
||||
code.extend([0xbe80_03ff | reg << 16, value]);
|
||||
}
|
||||
let x = if scc { 129 } else { 128 };
|
||||
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
|
||||
code.extend(alu);
|
||||
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
fn case(
|
||||
name: &'static str,
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
out: (u32, bool),
|
||||
) -> Case {
|
||||
let (r, scc) = out;
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label: format!("{name} {label}"),
|
||||
code,
|
||||
input: INPUT.to_vec(),
|
||||
expected: vec![r, if scc { !r } else { r }],
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
for a in VALUES {
|
||||
for b in VALUES {
|
||||
for scc in [false, true] {
|
||||
let code = program(&[(8, a), (9, b)], scc, &[sopc(op, 8, 9)], 10);
|
||||
let label = format!("{a:#x}, {b:#x}, scc before {scc}");
|
||||
let out = (MARKER, expect(form, a, b));
|
||||
cases.push(case(name, "sopc domain", label, code, out));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Every integer inline constant (-16..64) in each slot against a
|
||||
// register that is negative as i32 and large as u32, then 32. SCC
|
||||
// before is the opposite of the result, so a missing write shows.
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
for other in [0xffff_fff8, 0x20, value] {
|
||||
for slot in 0..2 {
|
||||
let (alu, scc) = if slot == 0 {
|
||||
(sopc(op, selector, 8), expect(form, value, other))
|
||||
} else {
|
||||
(sopc(op, 8, selector), expect(form, other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], !scc, &[alu], 10);
|
||||
let label = format!("inline {value:#x} in src{slot}, s8 {other:#x}");
|
||||
cases.push(case(
|
||||
name,
|
||||
"sopc inline integer",
|
||||
label,
|
||||
code,
|
||||
(MARKER, scc),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// A literal dword after the SOPC word in each slot.
|
||||
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX] {
|
||||
for other in [0x7fff_ffff, 0x8000_0000, value] {
|
||||
for slot in 0..2 {
|
||||
let (alu, scc) = if slot == 0 {
|
||||
([sopc(op, LITERAL, 8), value], expect(form, value, other))
|
||||
} else {
|
||||
([sopc(op, 8, LITERAL), value], expect(form, other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], !scc, &alu, 10);
|
||||
let label = format!("literal {value:#x} in src{slot}, s8 {other:#x}");
|
||||
cases.push(case(name, "sopc literal", label, code, (MARKER, scc)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// One register in both slots: S0 == S1.
|
||||
for value in [0, 0x8000_0000, u32::MAX] {
|
||||
let scc = expect(form, value, value);
|
||||
let code = program(&[(8, value)], !scc, &[sopc(op, 8, 8)], 10);
|
||||
let label = format!("s8, s8 = {value:#x}");
|
||||
cases.push(case(name, "sopc aliasing", label, code, (MARKER, scc)));
|
||||
}
|
||||
// No SGPR is written: the sources, the marker and s11 (which a SOP2
|
||||
// reading of the word would name as SDST for opcode 11) keep their
|
||||
// values.
|
||||
let (a, b) = (0x8000_0000, 1);
|
||||
let scc = expect(form, a, b);
|
||||
let init = [(8, a), (9, b), (11, 0x1111_1111)];
|
||||
// s12 holds the SCC-setting AND result, 1 when SCC was set before.
|
||||
let s12 = u32::from(!scc);
|
||||
for (reg, value) in [(8, a), (9, b), (10, MARKER), (11, 0x1111_1111), (12, s12)] {
|
||||
let code = program(&init, !scc, &[sopc(op, 8, 9)], reg);
|
||||
let label = format!("s{reg} after s8 {a:#x}, s9 {b:#x}");
|
||||
cases.push(case(name, "sopc no sgpr write", label, code, (value, scc)));
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// The SOPC word's byte offset in `program` with `init` SGPR moves: three
|
||||
/// header words, one 8-byte move per init pair and the marker, and the AND.
|
||||
fn alu_offset(init: usize) -> usize {
|
||||
12 + 8 * (init + 1) + 4
|
||||
}
|
||||
|
||||
/// Both interpreters must refuse `code` at the SOPC word, not later.
|
||||
fn assert_rejected_at_alu(label: &str, code: &[u8], init: usize) {
|
||||
let offset = alu_offset(init);
|
||||
match xenora_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(error.offset, offset, "reference rejected {label} elsewhere"),
|
||||
}
|
||||
match independent_ref::execute(code, &INPUT) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{offset:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Programs both interpreters must refuse at the SOPC word, with the number
|
||||
/// of init pairs before it.
|
||||
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
let code = program(&[], false, &[sopc(op, LITERAL, LITERAL), 1], 10);
|
||||
all.push((format!("{name} two literals"), code, 0));
|
||||
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, and the float inline
|
||||
// constants 240-248 (0.5 .. 1/(2*pi)).
|
||||
for selector in [106, 107, 124, 126, 127].into_iter().chain(240..=248) {
|
||||
for slot in 0..2 {
|
||||
let alu = if slot == 0 {
|
||||
sopc(op, selector, 8)
|
||||
} else {
|
||||
sopc(op, 8, selector)
|
||||
};
|
||||
let code = program(&[(8, 1)], false, &[alu], 10);
|
||||
all.push((format!("{name} source {selector} in src{slot}"), code, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
|
||||
failed.entry(case.family).or_insert((0, first)).0 += 1;
|
||||
}
|
||||
}
|
||||
failed
|
||||
.into_iter()
|
||||
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_cases() -> Vec<Case> {
|
||||
let cases = cases();
|
||||
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
|
||||
cases
|
||||
}
|
||||
|
||||
fn reference(code: &[u8], input: &[u32]) -> Result<Vec<u32>, String> {
|
||||
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_d_compares_match_the_guide_on_the_reference() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, reference);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"reference disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!("sopc_stage_d: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_d_compares_match_the_guide_on_the_independent_interpreter() {
|
||||
let cases = checked_cases();
|
||||
let failed = failures(&cases, independent_ref::execute);
|
||||
assert!(
|
||||
failed.is_empty(),
|
||||
"independent interpreter disagrees with the guide:\n{}",
|
||||
failed.join("\n")
|
||||
);
|
||||
eprintln!(
|
||||
"sopc_stage_d: {} independent-interpreter cases",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_compare_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code, init) in &rejections {
|
||||
assert_rejected_at_alu(label, code, *init);
|
||||
}
|
||||
eprintln!("sopc_stage_d: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighbouring_sopc_opcodes_stay_unsupported() {
|
||||
// 12-15 are bit tests, 18-19 the 64-bit compares (guide 12.4); 16, 17 and
|
||||
// 20-127 are not listed. Neither interpreter supports any of them.
|
||||
for op in 12..=127 {
|
||||
let code = program(&[(8, 1), (9, 2)], false, &[sopc(op, 8, 9)], 10);
|
||||
assert_rejected_at_alu(&format!("opcode {op}"), &code, 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn stage_d_compares_match_the_guide_on_native_metal() {
|
||||
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
|
||||
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
|
||||
for (label, code, _) in rejections() {
|
||||
assert!(
|
||||
compile(Architecture::Gfx1030, &code).is_err(),
|
||||
"compiler accepted {label}"
|
||||
);
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sopc_stage_d: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user