mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 20:41:11 +00:00
Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f70e6d0534 | ||
|
|
223fe253c9 | ||
|
|
62be091197 | ||
|
|
cf288dd940 | ||
|
|
9f57d8b3bb | ||
|
|
5d4d15d596 | ||
|
|
95ddc28518 | ||
|
|
9cc4a965c4 | ||
|
|
9b767186a2 | ||
|
|
823007888f | ||
|
|
881c2a2e52 | ||
|
|
475b27e5d4 | ||
|
|
cac93574ce | ||
|
|
085b0e28e5 | ||
|
|
835689e5df | ||
|
|
55e1818ccd | ||
|
|
44ea8133fc | ||
|
|
756597a6b4 | ||
|
|
4038cdbe41 | ||
|
|
51b60381c5 | ||
|
|
2593f73f29 | ||
|
|
3f3f154d2d | ||
|
|
4d68733f3c | ||
|
|
d22f046bf9 | ||
|
|
430f63e27d | ||
|
|
ce29b87770 | ||
|
|
ad424d690a | ||
|
|
9e47234e92 | ||
|
|
5ba0496c63 | ||
|
|
cd224d86f4 | ||
|
|
dd4bcb30eb | ||
|
|
aef29ff65d | ||
|
|
3392c226ce | ||
|
|
72bf5f7e32 | ||
|
|
78df3a5c6b | ||
|
|
133c9df448 | ||
|
|
a6d354fb2a | ||
|
|
00f79c10d2 | ||
|
|
95a8c61f1b | ||
|
|
31627363f1 | ||
|
|
ee2d29a65c | ||
|
|
84b6fb4d50 | ||
|
|
b98380c1b0 | ||
|
|
0e9211cd42 | ||
|
|
c41e034fa1 | ||
|
|
a2c696b551 |
No files matched your search
@@ -53,6 +53,7 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
concurrency:
|
||||
group: agent-queue
|
||||
cancel-in-progress: false
|
||||
|
||||
@@ -10,7 +10,16 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
|
||||
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
|
||||
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
|
||||
- Added interactive guest execution with dynamic input handling and rendering to the native application (Gate 4, #276). The C interface gains `xenora_session_start_interactive_loop`, `xenora_session_send_input`, `xenora_session_queue_input`, and `xenora_session_get_recorded_frame`, along with input masks (`XENORA_INPUT_*`) and `xenora_input_state`. The original interactive guest fixture (`fixtures/pe/interactive.exe`, generated by `fixtures/pe/interactive.py` using only the supported ARM64 DBT instruction subset) polls host input via `xenora.dll!input_poll` and steers its rendered column position (0..3) on native Metal. Xenora.app gains interactive frame-loop controls ("Interactive (300 frames)", "◀ Left", "▶ Right", "Release") and `--smoke-interactive`. Four GPU acceptance tests with Metal validation verify that input events drive guest state and pixel geometry, deterministic input replay reproduces identical frame sequences across multiple sessions, key release and focus loss cleanly hold position without stuck keys, and destroying an interactive session joins promptly. Wired the interactive tests into `scripts/test-gpu.sh`.
|
||||
|
||||
- Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`.
|
||||
|
||||
- Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised.
|
||||
- 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.
|
||||
@@ -80,6 +89,7 @@ remains unsupported.
|
||||
native DBT.
|
||||
|
||||
### Fixed
|
||||
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
|
||||
|
||||
- Fixed `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
|
||||
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
|
||||
|
||||
@@ -86,6 +86,172 @@ final class FrameModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistent guest rendering model (Gate 3, #266; Gate 4, #276).
|
||||
@MainActor
|
||||
final class FrameLoopModel: ObservableObject {
|
||||
@Published var state: UInt32 = UInt32(XENORA_LOOP_NONE)
|
||||
@Published var completed: UInt32 = 0
|
||||
@Published var frameId: UInt32 = XENORA_NO_FRAME
|
||||
@Published var image: CGImage?
|
||||
@Published var errorMessage: String?
|
||||
@Published var isInteractive: Bool = false
|
||||
|
||||
private var session: xenora_session = 0
|
||||
private var pollTask: Task<Void, Never>?
|
||||
|
||||
deinit {
|
||||
pollTask?.cancel()
|
||||
if session != 0 {
|
||||
_ = xenora_session_destroy(session)
|
||||
}
|
||||
}
|
||||
|
||||
var isRunning: Bool { state == UInt32(XENORA_LOOP_RUNNING) }
|
||||
var isPaused: Bool { state == UInt32(XENORA_LOOP_PAUSED) }
|
||||
var canStart: Bool {
|
||||
session == 0 || state == UInt32(XENORA_LOOP_NONE) || state == UInt32(XENORA_LOOP_FINISHED)
|
||||
|| state == UInt32(XENORA_LOOP_STOPPED) || state == UInt32(XENORA_LOOP_FAILED)
|
||||
}
|
||||
|
||||
var stateDescription: String {
|
||||
switch state {
|
||||
case UInt32(XENORA_LOOP_NONE): return "Idle"
|
||||
case UInt32(XENORA_LOOP_RUNNING): return "Running"
|
||||
case UInt32(XENORA_LOOP_PAUSED): return "Paused"
|
||||
case UInt32(XENORA_LOOP_FINISHED): return "Finished"
|
||||
case UInt32(XENORA_LOOP_STOPPED): return "Stopped"
|
||||
case UInt32(XENORA_LOOP_FAILED): return "Failed"
|
||||
default: return "Unknown (\(state))"
|
||||
}
|
||||
}
|
||||
|
||||
func start(frameCount: UInt32 = 300) {
|
||||
errorMessage = nil
|
||||
if session != 0 {
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
}
|
||||
var newSession: xenora_session = 0
|
||||
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession)
|
||||
guard createStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to create session (status \(createStatus))"
|
||||
return
|
||||
}
|
||||
session = newSession
|
||||
let startStatus = xenora_session_start_frame_loop(session, frameCount)
|
||||
guard startStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to start frame loop (status \(startStatus))"
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
return
|
||||
}
|
||||
isInteractive = false
|
||||
state = UInt32(XENORA_LOOP_RUNNING)
|
||||
completed = 0
|
||||
frameId = XENORA_NO_FRAME
|
||||
image = nil
|
||||
startPolling()
|
||||
}
|
||||
|
||||
func startInteractive(frameCount: UInt32 = 300) {
|
||||
errorMessage = nil
|
||||
if session != 0 {
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
}
|
||||
var newSession: xenora_session = 0
|
||||
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession)
|
||||
guard createStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to create session (status \(createStatus))"
|
||||
return
|
||||
}
|
||||
session = newSession
|
||||
let startStatus = xenora_session_start_interactive_loop(session, frameCount)
|
||||
guard startStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to start interactive loop (status \(startStatus))"
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
return
|
||||
}
|
||||
isInteractive = true
|
||||
state = UInt32(XENORA_LOOP_RUNNING)
|
||||
completed = 0
|
||||
frameId = XENORA_NO_FRAME
|
||||
image = nil
|
||||
startPolling()
|
||||
}
|
||||
|
||||
func sendInput(buttons: UInt32) {
|
||||
guard session != 0 else { return }
|
||||
var input = xenora_input_state(
|
||||
buttons: buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0
|
||||
)
|
||||
_ = xenora_session_send_input(session, &input)
|
||||
}
|
||||
|
||||
func pause() {
|
||||
guard session != 0 else { return }
|
||||
_ = xenora_session_pause_frame_loop(session)
|
||||
}
|
||||
|
||||
func resume() {
|
||||
guard session != 0 else { return }
|
||||
_ = xenora_session_resume_frame_loop(session)
|
||||
}
|
||||
|
||||
func stop() {
|
||||
guard session != 0 else { return }
|
||||
_ = xenora_session_stop_frame_loop(session)
|
||||
}
|
||||
|
||||
private func startPolling() {
|
||||
pollTask?.cancel()
|
||||
pollTask = Task { [weak self] in
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(nanoseconds: 16_000_000)
|
||||
guard let self = self, self.session != 0 else { break }
|
||||
var st: UInt32 = 0
|
||||
var comp: UInt32 = 0
|
||||
var fId: UInt32 = 0
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
let code = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_frame_loop_status(
|
||||
self.session, &st, &comp, &fId, buffer.baseAddress, UInt64(buffer.count))
|
||||
}
|
||||
guard code == XENORA_OK else { break }
|
||||
self.state = st
|
||||
self.completed = comp
|
||||
self.frameId = fId
|
||||
if fId != XENORA_NO_FRAME, let provider = CGDataProvider(data: Data(rgba) as CFData) {
|
||||
self.image = CGImage(
|
||||
width: Int(XENORA_FIXTURE_FRAME_WIDTH),
|
||||
height: Int(XENORA_FIXTURE_FRAME_HEIGHT),
|
||||
bitsPerComponent: 8,
|
||||
bitsPerPixel: 32,
|
||||
bytesPerRow: Int(XENORA_FIXTURE_FRAME_WIDTH) * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider,
|
||||
decode: nil,
|
||||
shouldInterpolate: false,
|
||||
intent: .defaultIntent
|
||||
)
|
||||
}
|
||||
if st != UInt32(XENORA_LOOP_RUNNING) && st != UInt32(XENORA_LOOP_PAUSED) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only compatibility inspection of a user-chosen file. Nothing in it is executed.
|
||||
@MainActor
|
||||
final class InspectionModel: ObservableObject {
|
||||
@@ -170,6 +336,7 @@ struct InspectorView: View {
|
||||
struct ContentView: View {
|
||||
let probe = RuntimeProbe.run()
|
||||
@ObservedObject var model: FrameModel
|
||||
@ObservedObject var loop: FrameLoopModel
|
||||
@ObservedObject var inspection = InspectionModel.shared
|
||||
private var frame: GuestFrame? { model.frame }
|
||||
private var running: Bool { model.running }
|
||||
@@ -195,11 +362,52 @@ struct ContentView: View {
|
||||
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
|
||||
.disabled(running || !probe.connected)
|
||||
}
|
||||
Section("Persistent frame loop") {
|
||||
if let image = loop.image {
|
||||
Image(decorative: image, scale: 1)
|
||||
.resizable()
|
||||
.interpolation(.none)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
|
||||
.accessibilityLabel("Guest frame #\(loop.frameId)")
|
||||
Text("Frame #\(loop.frameId) (\(loop.completed) completed) • \(loop.stateDescription)")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
} else if let error = loop.errorMessage {
|
||||
Text(error).foregroundStyle(.red)
|
||||
} else if loop.state != UInt32(XENORA_LOOP_NONE) {
|
||||
Text("State: \(loop.stateDescription) • \(loop.completed) completed")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
HStack {
|
||||
Button("Start 300 frames") { loop.start(frameCount: 300) }
|
||||
.disabled(!loop.canStart || !probe.connected)
|
||||
Button("Interactive (300 frames)") { loop.startInteractive(frameCount: 300) }
|
||||
.disabled(!loop.canStart || !probe.connected)
|
||||
Button("Pause") { loop.pause() }
|
||||
.disabled(!loop.isRunning)
|
||||
Button("Resume") { loop.resume() }
|
||||
.disabled(!loop.isPaused)
|
||||
Button("Stop") { loop.stop() }
|
||||
.disabled(!loop.isRunning && !loop.isPaused)
|
||||
}
|
||||
if loop.isInteractive && (loop.isRunning || loop.isPaused) {
|
||||
HStack {
|
||||
Button("◀ Left") { loop.sendInput(buttons: UInt32(XENORA_INPUT_LEFT)) }
|
||||
Button("▶ Right") { loop.sendInput(buttons: UInt32(XENORA_INPUT_RIGHT)) }
|
||||
Button("Release") { loop.sendInput(buttons: UInt32(XENORA_INPUT_NONE)) }
|
||||
}
|
||||
Text("Interactive guest: steer the rendered strip across columns 0..3 with Left/Right.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
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.")
|
||||
Text("Only the bundled trusted fixtures (single-frame, frame-loop, and interactive guest) can run. Presentation uses read-back Metal frames. Arbitrary executables are not available yet.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
@@ -211,16 +419,17 @@ struct ContentView: View {
|
||||
inspection.inspect(url)
|
||||
return true
|
||||
}
|
||||
.frame(minWidth: 520, minHeight: 560)
|
||||
.frame(minWidth: 520, minHeight: 680)
|
||||
}
|
||||
}
|
||||
|
||||
struct XenoraApp: App {
|
||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||
let model = FrameModel()
|
||||
let loop = FrameLoopModel()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup("Xenora") { ContentView(model: model) }
|
||||
WindowGroup("Xenora") { ContentView(model: model, loop: loop) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,6 +441,75 @@ if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < Comm
|
||||
exit(status == Int32(XENORA_OK) ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-interactive` runs 60 frames with queued inputs on the Metal device and exits.
|
||||
if CommandLine.arguments.contains("--smoke-interactive") {
|
||||
var session: xenora_session = 0
|
||||
guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else {
|
||||
print("failed to create session")
|
||||
exit(1)
|
||||
}
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
guard xenora_session_start_interactive_loop(session, 60) == XENORA_OK else {
|
||||
print("failed to start interactive loop")
|
||||
exit(1)
|
||||
}
|
||||
for f in 0..<60 {
|
||||
let btn: UInt32 = (f < 15) ? UInt32(XENORA_INPUT_RIGHT) :
|
||||
(f < 30) ? UInt32(XENORA_INPUT_NONE) :
|
||||
(f < 45) ? UInt32(XENORA_INPUT_LEFT) : UInt32(XENORA_INPUT_RIGHT)
|
||||
var input = xenora_input_state(buttons: btn, stick_x: 0, stick_y: 0, mouse_dx: 0, mouse_dy: 0, mouse_buttons: 0, connected: 1, reserved: 0)
|
||||
_ = xenora_session_queue_input(session, &input)
|
||||
}
|
||||
var state: UInt32 = 0
|
||||
var completed: UInt32 = 0
|
||||
var frameId: UInt32 = 0
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
while true {
|
||||
let code = rgba.withUnsafeMutableBufferPointer { buf in
|
||||
xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count))
|
||||
}
|
||||
if code != XENORA_OK {
|
||||
print("frame_loop_status failed: \(code)")
|
||||
exit(1)
|
||||
}
|
||||
if state != UInt32(XENORA_LOOP_RUNNING) { break }
|
||||
Thread.sleep(forTimeInterval: 0.005)
|
||||
}
|
||||
print("interactive: state=\(state) completed=\(completed) frame_id=\(frameId)")
|
||||
exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 60 ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-loop` runs 300 frames on the Metal device and exits; it needs a GPU.
|
||||
if CommandLine.arguments.contains("--smoke-loop") {
|
||||
var session: xenora_session = 0
|
||||
guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else {
|
||||
print("failed to create session")
|
||||
exit(1)
|
||||
}
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
guard xenora_session_start_frame_loop(session, 300) == XENORA_OK else {
|
||||
print("failed to start frame loop")
|
||||
exit(1)
|
||||
}
|
||||
var state: UInt32 = 0
|
||||
var completed: UInt32 = 0
|
||||
var frameId: UInt32 = 0
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
while true {
|
||||
let code = rgba.withUnsafeMutableBufferPointer { buf in
|
||||
xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count))
|
||||
}
|
||||
if code != XENORA_OK {
|
||||
print("frame_loop_status failed: \(code)")
|
||||
exit(1)
|
||||
}
|
||||
if state != UInt32(XENORA_LOOP_RUNNING) { break }
|
||||
Thread.sleep(forTimeInterval: 0.005)
|
||||
}
|
||||
print("state=\(state) completed=\(completed) frame_id=\(frameId)")
|
||||
exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 300 ? 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()
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorCompareOp, VectorSource,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorCompareOp, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
@@ -17,6 +17,7 @@ use xenora_isa::{
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
use xenora_isa::semantics::FORM_IDS;
|
||||
pub use xenora_isa::semantics::VectorBinary;
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination: the hand-written forms below followed by every form of
|
||||
@@ -429,6 +430,21 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
S_CBRANCH_VCCZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if let Some(op) = VectorAluOp::from_word(first) {
|
||||
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
|
||||
let dst = ((first >> 17) & 0xff) as u8;
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = vector_src0(first, bytes, op.assembly_name())?;
|
||||
return Ok((
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
len,
|
||||
));
|
||||
}
|
||||
if V_LSHLREV_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
|
||||
return Ok((
|
||||
@@ -698,10 +714,21 @@ fn vector_compare(
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let source = first & 0x1ff;
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = vector_src0(first, bytes, op.mnemonic())?;
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
}
|
||||
|
||||
/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an
|
||||
/// inline integer -16..64 or a literal word; everything else is unsupported.
|
||||
fn vector_src0(
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
mnemonic: &'static str,
|
||||
) -> Result<(VectorSource, u8), DecodeErrorKind> {
|
||||
let source = first & 0x1ff;
|
||||
let base_len = 4;
|
||||
let (src0, len) = match source {
|
||||
Ok(match source {
|
||||
0..=106 => (VectorSource::Scalar(source as u8), base_len),
|
||||
128..=192 => (VectorSource::Immediate(source - 128), base_len),
|
||||
193..=208 => (
|
||||
@@ -715,12 +742,11 @@ fn vector_compare(
|
||||
256..=511 => (VectorSource::Register(source as u8), base_len),
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
op.mnemonic(),
|
||||
mnemonic,
|
||||
"expected a VGPR, normal SGPR, vcc_lo, inline integer or literal",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
})
|
||||
}
|
||||
|
||||
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
|
||||
@@ -4,11 +4,12 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorSource, decode, decode_at,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorSource, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
|
||||
VectorInteger,
|
||||
};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
@@ -351,6 +352,22 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
|
||||
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
|
||||
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
|
||||
ScalarAluOp::MinI32 => ScalarAlu::Minimum { signed: true },
|
||||
ScalarAluOp::MinU32 => ScalarAlu::Minimum { signed: false },
|
||||
ScalarAluOp::MaxI32 => ScalarAlu::Maximum { signed: true },
|
||||
ScalarAluOp::MaxU32 => ScalarAlu::Maximum { signed: false },
|
||||
ScalarAluOp::CselectB32 => ScalarAlu::Select,
|
||||
ScalarAluOp::BfmB32 => ScalarAlu::BitfieldMask,
|
||||
ScalarAluOp::MulI32 => ScalarAlu::Multiply,
|
||||
ScalarAluOp::BfeU32 => ScalarAlu::BitfieldExtract { signed: false },
|
||||
ScalarAluOp::BfeI32 => ScalarAlu::BitfieldExtract { signed: true },
|
||||
ScalarAluOp::AbsdiffI32 => ScalarAlu::AbsoluteDifference,
|
||||
ScalarAluOp::Lshl1AddU32 => ScalarAlu::ShiftLeftAdd(1),
|
||||
ScalarAluOp::Lshl2AddU32 => ScalarAlu::ShiftLeftAdd(2),
|
||||
ScalarAluOp::Lshl3AddU32 => ScalarAlu::ShiftLeftAdd(3),
|
||||
ScalarAluOp::Lshl4AddU32 => ScalarAlu::ShiftLeftAdd(4),
|
||||
ScalarAluOp::MulHiU32 => ScalarAlu::MultiplyHigh { signed: false },
|
||||
ScalarAluOp::MulHiI32 => ScalarAlu::MultiplyHigh { signed: true },
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src0),
|
||||
@@ -454,6 +471,34 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
},
|
||||
src1,
|
||||
),
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
match op {
|
||||
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
|
||||
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
|
||||
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
|
||||
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
|
||||
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
|
||||
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
|
||||
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
|
||||
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
|
||||
VectorAluOp::XnorB32 => VectorInteger::Xnor,
|
||||
VectorAluOp::AddNcU32 => VectorInteger::Add,
|
||||
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
|
||||
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
|
||||
},
|
||||
dst,
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
src1,
|
||||
),
|
||||
Instruction::EndProgram => Op::End,
|
||||
}
|
||||
}
|
||||
@@ -478,13 +523,15 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
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/scalar-arith.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 72, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 100, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -768,7 +815,13 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
let target = next_offset + displacement * 4;
|
||||
format!("{mnemonic} -> 0x{target:04x}")
|
||||
}
|
||||
mnemonic if mnemonic.starts_with("v_cmp_") => {
|
||||
// VOPC and the registry VOP2 forms print SRC0 (the second operand) as bits.
|
||||
mnemonic
|
||||
if mnemonic.starts_with("v_cmp_")
|
||||
|| VectorAluOp::ALL
|
||||
.iter()
|
||||
.any(|op| op.assembly_name() == mnemonic) =>
|
||||
{
|
||||
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
|
||||
parts[1] = match literal_bits(&parts[1]) {
|
||||
Some(bits) => format!("0x{bits:x}"),
|
||||
|
||||
@@ -27,8 +27,43 @@ enum {
|
||||
XENORA_LIMIT_EXCEEDED = 6,
|
||||
XENORA_BUFFER_TOO_SMALL = 7,
|
||||
XENORA_EXECUTION_FAILED = 8,
|
||||
XENORA_INVALID_STATE = 9,
|
||||
};
|
||||
|
||||
/* Frame-loop states reported by xenora_session_frame_loop_status. */
|
||||
enum {
|
||||
XENORA_LOOP_NONE = 0,
|
||||
XENORA_LOOP_RUNNING = 1,
|
||||
XENORA_LOOP_PAUSED = 2,
|
||||
XENORA_LOOP_FINISHED = 3,
|
||||
XENORA_LOOP_STOPPED = 4,
|
||||
XENORA_LOOP_FAILED = 5,
|
||||
};
|
||||
|
||||
#define XENORA_FRAME_LOOP_MAX_FRAMES 100000u
|
||||
/* Frame id reported when no frame has been completed yet. */
|
||||
#define XENORA_NO_FRAME 0xFFFFFFFFu
|
||||
|
||||
/* Input snapshot delivered to guest runtime services (Gate 4, #276). */
|
||||
typedef struct {
|
||||
uint32_t buttons;
|
||||
int16_t stick_x;
|
||||
int16_t stick_y;
|
||||
int16_t mouse_dx;
|
||||
int16_t mouse_dy;
|
||||
uint8_t mouse_buttons;
|
||||
uint8_t connected;
|
||||
uint16_t reserved;
|
||||
} xenora_input_state;
|
||||
|
||||
#define XENORA_INPUT_NONE 0u
|
||||
#define XENORA_INPUT_RIGHT (1u << 0)
|
||||
#define XENORA_INPUT_LEFT (1u << 1)
|
||||
#define XENORA_INPUT_UP (1u << 2)
|
||||
#define XENORA_INPUT_DOWN (1u << 3)
|
||||
#define XENORA_INPUT_ACTION_A (1u << 4)
|
||||
#define XENORA_INPUT_ACTION_B (1u << 5)
|
||||
|
||||
/* 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
|
||||
@@ -65,6 +100,49 @@ xenora_status xenora_session_run_trusted_fixture(
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height);
|
||||
|
||||
/*
|
||||
* Persistent rendering (one frame loop per session). Start runs the embedded
|
||||
* frame-loop fixture on a session-owned guest thread: the guest submits frames
|
||||
* 0, 1, 2, ... and each is rendered on native Metal and verified before it
|
||||
* becomes the latest frame. The guest stops after `frame_count` frames
|
||||
* (1..=XENORA_FRAME_LOOP_MAX_FRAMES). Pause holds the guest at its next frame
|
||||
* submission; resume continues it; stop makes it leave its loop and halt, and
|
||||
* waits for its thread. Destroying the session stops the loop first. Starting a
|
||||
* second loop on the same session returns XENORA_INVALID_STATE.
|
||||
*/
|
||||
xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count);
|
||||
xenora_status xenora_session_start_interactive_loop(xenora_session session, uint32_t frame_count);
|
||||
xenora_status xenora_session_send_input(xenora_session session, const xenora_input_state *input);
|
||||
xenora_status xenora_session_queue_input(xenora_session session, const xenora_input_state *input);
|
||||
xenora_status xenora_session_pause_frame_loop(xenora_session session);
|
||||
xenora_status xenora_session_resume_frame_loop(xenora_session session);
|
||||
xenora_status xenora_session_stop_frame_loop(xenora_session session);
|
||||
|
||||
/*
|
||||
* Retrieve a previously completed frame by sequence index (0 <= frame_index < completed).
|
||||
* Used for deterministic replay verification and frame inspection.
|
||||
*/
|
||||
xenora_status xenora_session_get_recorded_frame(
|
||||
xenora_session session,
|
||||
uint32_t frame_index,
|
||||
uint32_t *out_frame_id,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity
|
||||
);
|
||||
|
||||
/*
|
||||
* Report the loop's state, the number of completed frames, and the latest
|
||||
* verified frame: its id (XENORA_NO_FRAME if none yet) and, when one exists,
|
||||
* its RGBA8 pixels (XENORA_FIXTURE_FRAME_WIDTH x HEIGHT) in `out_rgba`.
|
||||
*/
|
||||
xenora_status xenora_session_frame_loop_status(
|
||||
xenora_session session,
|
||||
uint32_t *out_state,
|
||||
uint32_t *out_completed,
|
||||
uint32_t *out_frame_id,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity);
|
||||
|
||||
/* Largest file xenora_inspect_executable accepts, in bytes. */
|
||||
#define XENORA_MAX_INSPECT_BYTES 268435456u
|
||||
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Persistent guest rendering for one session (Gate 3, #266).
|
||||
//!
|
||||
//! The embedded `frame-loop.exe` fixture calls `xenora.dll!frame_submit(index)`
|
||||
//! with index 0, 1, 2, ... and halts when the call returns 0. The guest runs on
|
||||
//! its own thread for the session's lifetime. Pause, resume and stop act at the
|
||||
//! frame-submit boundary: a paused guest waits inside that call with its
|
||||
//! architectural state untouched, and a stop request makes the call return 0 so
|
||||
//! the guest leaves its loop and halts.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, Register};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/frame-loop.exe");
|
||||
const INTERACTIVE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/interactive.exe");
|
||||
pub const WIDTH: usize = 4;
|
||||
pub const HEIGHT: usize = 3;
|
||||
pub const FRAME_BYTES: usize = WIDTH * HEIGHT * 4;
|
||||
pub const MAX_FRAMES: u32 = 100_000;
|
||||
/// Guest instructions per loop iteration (mov, call, inc, test, jnz) plus slack.
|
||||
const STEPS_PER_FRAME: usize = 8;
|
||||
const STEPS_PER_INTERACTIVE_FRAME: usize = 24;
|
||||
/// `x9-constant-ps.s` exports (1, 0, 0, 1): opaque red. Everything else is the clear colour.
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const CLEAR: [u8; 4] = [19, 43, 93, 251];
|
||||
|
||||
pub const RUNNING: u32 = 1;
|
||||
pub const PAUSED: u32 = 2;
|
||||
pub const FINISHED: u32 = 3;
|
||||
pub const STOPPED: u32 = 4;
|
||||
pub const FAILED: u32 = 5;
|
||||
|
||||
#[derive(Default, Copy, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct InputState {
|
||||
pub buttons: u32,
|
||||
pub stick_x: i16,
|
||||
pub stick_y: i16,
|
||||
pub mouse_dx: i16,
|
||||
pub mouse_dy: i16,
|
||||
pub mouse_buttons: u8,
|
||||
pub connected: u8,
|
||||
pub reserved: u16,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
status: u32,
|
||||
paused: bool,
|
||||
stop: bool,
|
||||
interactive: bool,
|
||||
limit: u32,
|
||||
completed: u32,
|
||||
input: InputState,
|
||||
input_queue: std::collections::VecDeque<InputState>,
|
||||
recorded_frames: Vec<(u32, Vec<u8>)>,
|
||||
/// Every `frame_submit` call the guest made, including the one answered with 0.
|
||||
calls: u64,
|
||||
latest: Option<(u32, Vec<u8>)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct FrameLoop {
|
||||
state: Mutex<State>,
|
||||
wake: Condvar,
|
||||
thread: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
pub struct Snapshot {
|
||||
pub status: u32,
|
||||
pub completed: u32,
|
||||
pub latest: Option<(u32, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl FrameLoop {
|
||||
fn lock(&self) -> MutexGuard<'_, State> {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
pub fn start(limit: u32, interactive: bool) -> Arc<Self> {
|
||||
let shared = Arc::new(Self::default());
|
||||
{
|
||||
let mut state = shared.lock();
|
||||
state.status = RUNNING;
|
||||
state.limit = limit;
|
||||
state.interactive = interactive;
|
||||
}
|
||||
let guest = Arc::clone(&shared);
|
||||
let handle = std::thread::Builder::new()
|
||||
.name("xenora-guest".into())
|
||||
.spawn(move || guest.run())
|
||||
.ok();
|
||||
if handle.is_none() {
|
||||
shared.lock().status = FAILED;
|
||||
}
|
||||
*shared.thread.lock().unwrap_or_else(|p| p.into_inner()) = handle;
|
||||
shared
|
||||
}
|
||||
|
||||
/// Pause or resume. Returns false unless the loop is running or paused.
|
||||
pub fn set_paused(&self, paused: bool) -> bool {
|
||||
let mut state = self.lock();
|
||||
if !matches!(state.status, RUNNING | PAUSED) {
|
||||
return false;
|
||||
}
|
||||
state.paused = paused;
|
||||
state.status = if paused { PAUSED } else { RUNNING };
|
||||
self.wake.notify_all();
|
||||
true
|
||||
}
|
||||
|
||||
/// Ask the guest to stop at its next frame submission and wait for its thread.
|
||||
pub fn stop(&self) {
|
||||
{
|
||||
let mut state = self.lock();
|
||||
state.stop = true;
|
||||
self.wake.notify_all();
|
||||
}
|
||||
if let Some(handle) = self.thread.lock().unwrap_or_else(|p| p.into_inner()).take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_input(&self, input: InputState) {
|
||||
let mut state = self.lock();
|
||||
state.input = input;
|
||||
}
|
||||
|
||||
pub fn queue_input(&self, input: InputState) {
|
||||
let mut state = self.lock();
|
||||
state.input_queue.push_back(input);
|
||||
}
|
||||
|
||||
pub fn get_recorded_frame(&self, index: usize) -> Option<(u32, Vec<u8>)> {
|
||||
let state = self.lock();
|
||||
state.recorded_frames.get(index).cloned()
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Snapshot {
|
||||
let state = self.lock();
|
||||
Snapshot {
|
||||
status: state.status,
|
||||
completed: state.completed,
|
||||
latest: state.latest.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(self: Arc<Self>) {
|
||||
let outcome = self.execute();
|
||||
let mut state = self.lock();
|
||||
state.status = match outcome {
|
||||
Err(_) => FAILED,
|
||||
Ok(()) if state.stop && state.completed < state.limit => STOPPED,
|
||||
Ok(()) => FINISHED,
|
||||
};
|
||||
}
|
||||
|
||||
fn execute(self: &Arc<Self>) -> Result<(), 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}"))?;
|
||||
// The session's GPU resources live on the guest thread, where the import runs.
|
||||
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
|
||||
|
||||
let shared = Arc::clone(self);
|
||||
let mut imports = ImportRegistry::new();
|
||||
imports.register("xenora.dll", "frame_submit", move |args, _, memory| {
|
||||
let index = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
shared
|
||||
.submit(index)
|
||||
.ok_or(ExitReason::IllegalInstruction(0xff))
|
||||
});
|
||||
if self.lock().interactive {
|
||||
let shared_poll = Arc::clone(self);
|
||||
imports.register("xenora.dll", "input_poll", move |_args, _, _memory| {
|
||||
let mut state = shared_poll.lock();
|
||||
let input = state.input_queue.pop_front().unwrap_or(state.input);
|
||||
let cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 {
|
||||
1u64
|
||||
} else if input.buttons & crate::XENORA_INPUT_LEFT != 0 {
|
||||
2u64
|
||||
} else {
|
||||
0u64
|
||||
};
|
||||
Ok(cmd)
|
||||
});
|
||||
}
|
||||
let limit = self.lock().limit as usize;
|
||||
let is_interactive = self.lock().interactive;
|
||||
let fixture_bytes = if is_interactive {
|
||||
INTERACTIVE_FIXTURE
|
||||
} else {
|
||||
FIXTURE
|
||||
};
|
||||
let steps_per_frame = if is_interactive {
|
||||
STEPS_PER_INTERACTIVE_FRAME
|
||||
} else {
|
||||
STEPS_PER_FRAME
|
||||
};
|
||||
let startup = run_synthetic_startup(
|
||||
fixture_bytes,
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
},
|
||||
imports,
|
||||
(limit + 1) * steps_per_frame + 32,
|
||||
)
|
||||
.map_err(|e| format!("startup: {e}"));
|
||||
GPU.with(|slot| slot.borrow_mut().take());
|
||||
let startup = startup?;
|
||||
let calls = self.lock().calls;
|
||||
let rbx = startup.execution.final_state.get(Register::Rbx);
|
||||
if startup.execution.exit_reason != ExitReason::Halt {
|
||||
return Err(format!(
|
||||
"guest ended with {:?}",
|
||||
startup.execution.exit_reason
|
||||
));
|
||||
}
|
||||
if !is_interactive && rbx != calls {
|
||||
return Err(format!("guest ended with rbx={rbx}, calls={calls}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle one `frame_submit`: wait while paused, then render and verify the
|
||||
/// frame. `None` fails the guest; `Some(0)` tells it to stop.
|
||||
fn submit(&self, index: u64) -> Option<u64> {
|
||||
let mut state = self.lock();
|
||||
state.calls += 1;
|
||||
while state.paused && !state.stop {
|
||||
state = self.wake.wait(state).unwrap_or_else(|p| p.into_inner());
|
||||
}
|
||||
if state.stop || state.completed >= state.limit {
|
||||
return Some(0);
|
||||
}
|
||||
if state.interactive {
|
||||
if index >= WIDTH as u64 {
|
||||
return None; // column must be inside 0..WIDTH
|
||||
}
|
||||
} else if index != u64::from(state.completed) {
|
||||
return None; // frame identities must arrive in order
|
||||
}
|
||||
drop(state);
|
||||
let pixels = render(index as u32)?;
|
||||
let mut state = self.lock();
|
||||
state.completed += 1;
|
||||
state.latest = Some((index as u32, pixels.clone()));
|
||||
if state.interactive {
|
||||
state.recorded_frames.push((index as u32, pixels));
|
||||
}
|
||||
Some(u64::from(state.completed < state.limit && !state.stop))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static GPU: RefCell<Option<(NativeCompute, String)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
|
||||
///
|
||||
/// The triangle (x0, -10), (x0 + 0.7, 0), (x0, 10) in clip space, with x0 the
|
||||
/// column's left edge, covers that column's pixel centres in all three rows and
|
||||
/// none of its neighbours'.
|
||||
fn render(index: u32) -> Option<Vec<u8>> {
|
||||
let column = (index as usize % WIDTH) as f32;
|
||||
let x0 = -1.0 + column * (2.0 / WIDTH as f32);
|
||||
let pixels = GPU.with(|slot| {
|
||||
let slot = slot.borrow();
|
||||
let (gpu, msl) = slot.as_ref()?;
|
||||
gpu.render_rgba8(
|
||||
msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[x0, -10.0, 0.5, 1.0],
|
||||
[x0 + 0.7, 0.0, 0.5, 1.0],
|
||||
[x0, 10.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
[WIDTH, HEIGHT],
|
||||
CLEAR,
|
||||
)
|
||||
.ok()
|
||||
})?;
|
||||
(pixels == expected(index)).then_some(pixels)
|
||||
}
|
||||
|
||||
/// The expected frame for `index`, from the strip rule alone.
|
||||
pub fn expected(index: u32) -> Vec<u8> {
|
||||
(0..WIDTH * HEIGHT)
|
||||
.flat_map(|pixel| {
|
||||
if pixel % WIDTH == index as usize % WIDTH {
|
||||
RED
|
||||
} else {
|
||||
CLEAR
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
+350
-2
@@ -7,6 +7,9 @@
|
||||
//! Every exported function catches panics and reports them as `XENORA_INTERNAL_ERROR`.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
mod frame_loop;
|
||||
|
||||
use frame_loop::FrameLoop;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
@@ -25,6 +28,26 @@ 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_INVALID_STATE: i32 = 9;
|
||||
|
||||
pub const XENORA_LOOP_NONE: u32 = 0;
|
||||
pub const XENORA_LOOP_RUNNING: u32 = frame_loop::RUNNING;
|
||||
pub const XENORA_LOOP_PAUSED: u32 = frame_loop::PAUSED;
|
||||
pub const XENORA_LOOP_FINISHED: u32 = frame_loop::FINISHED;
|
||||
pub const XENORA_LOOP_STOPPED: u32 = frame_loop::STOPPED;
|
||||
pub const XENORA_LOOP_FAILED: u32 = frame_loop::FAILED;
|
||||
pub const XENORA_FRAME_LOOP_MAX_FRAMES: u32 = frame_loop::MAX_FRAMES;
|
||||
pub const XENORA_NO_FRAME: u32 = u32::MAX;
|
||||
|
||||
pub const XENORA_INPUT_NONE: u32 = 0;
|
||||
pub const XENORA_INPUT_RIGHT: u32 = 1 << 0;
|
||||
pub const XENORA_INPUT_LEFT: u32 = 1 << 1;
|
||||
pub const XENORA_INPUT_UP: u32 = 1 << 2;
|
||||
pub const XENORA_INPUT_DOWN: u32 = 1 << 3;
|
||||
pub const XENORA_INPUT_ACTION_A: u32 = 1 << 4;
|
||||
pub const XENORA_INPUT_ACTION_B: u32 = 1 << 5;
|
||||
|
||||
pub use frame_loop::InputState as xenora_input_state;
|
||||
|
||||
pub const XENORA_FIXTURE_FRAME_WIDTH: u32 = 4;
|
||||
pub const XENORA_FIXTURE_FRAME_HEIGHT: u32 = 3;
|
||||
@@ -38,6 +61,8 @@ 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,
|
||||
/// The session's persistent frame loop, if one was started.
|
||||
frame_loop: Option<Arc<FrameLoop>>,
|
||||
}
|
||||
|
||||
static SESSIONS: Mutex<Vec<Slot>> = Mutex::new(Vec::new());
|
||||
@@ -79,7 +104,10 @@ pub unsafe extern "C" fn xenora_session_create(abi_version: u32, out_session: *m
|
||||
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.push(Slot {
|
||||
generation: 0,
|
||||
frame_loop: None,
|
||||
});
|
||||
slots.len() - 1
|
||||
}
|
||||
None => return XENORA_LIMIT_EXCEEDED,
|
||||
@@ -105,7 +133,230 @@ pub extern "C" fn xenora_session_destroy(session: u64) -> i32 {
|
||||
if !is_live(&slots, session) {
|
||||
return XENORA_INVALID_HANDLE;
|
||||
}
|
||||
slots[split(session).0].generation += 1;
|
||||
let slot = &mut slots[split(session).0];
|
||||
slot.generation += 1;
|
||||
let running = slot.frame_loop.take();
|
||||
drop(slots);
|
||||
// Stop and join the guest thread without holding the session table.
|
||||
if let Some(running) = running {
|
||||
running.stop();
|
||||
}
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
/// The live session's frame loop, or the status to return.
|
||||
fn session_loop(session: u64) -> Result<Option<Arc<FrameLoop>>, i32> {
|
||||
let slots = SESSIONS.lock().map_err(|_| XENORA_INTERNAL_ERROR)?;
|
||||
if !is_live(&slots, session) {
|
||||
return Err(XENORA_INVALID_HANDLE);
|
||||
}
|
||||
Ok(slots[split(session).0].frame_loop.clone())
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn xenora_session_start_frame_loop(session: u64, frame_count: u32) -> i32 {
|
||||
guarded(|| {
|
||||
if !(1..=XENORA_FRAME_LOOP_MAX_FRAMES).contains(&frame_count) {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
let Ok(mut slots) = SESSIONS.lock() else {
|
||||
return XENORA_INTERNAL_ERROR;
|
||||
};
|
||||
if !is_live(&slots, session) {
|
||||
return XENORA_INVALID_HANDLE;
|
||||
}
|
||||
let slot = &mut slots[split(session).0];
|
||||
if slot.frame_loop.is_some() {
|
||||
return XENORA_INVALID_STATE;
|
||||
}
|
||||
slot.frame_loop = Some(FrameLoop::start(frame_count, false));
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn xenora_session_start_interactive_loop(session: u64, frame_count: u32) -> i32 {
|
||||
guarded(|| {
|
||||
if !(1..=XENORA_FRAME_LOOP_MAX_FRAMES).contains(&frame_count) {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
let Ok(mut slots) = SESSIONS.lock() else {
|
||||
return XENORA_INTERNAL_ERROR;
|
||||
};
|
||||
if !is_live(&slots, session) {
|
||||
return XENORA_INVALID_HANDLE;
|
||||
}
|
||||
let slot = &mut slots[split(session).0];
|
||||
if slot.frame_loop.is_some() {
|
||||
return XENORA_INVALID_STATE;
|
||||
}
|
||||
slot.frame_loop = Some(FrameLoop::start(frame_count, true));
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `input` must be a valid pointer to an initialized `xenora_input_state`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_send_input(
|
||||
session: u64,
|
||||
input: *const frame_loop::InputState,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if input.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
let input_val = unsafe { *input };
|
||||
match session_loop(session) {
|
||||
Ok(Some(running)) => {
|
||||
running.send_input(input_val);
|
||||
XENORA_OK
|
||||
}
|
||||
Ok(None) => XENORA_INVALID_STATE,
|
||||
Err(status) => status,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `input` must be a valid pointer to an initialized `xenora_input_state`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_queue_input(
|
||||
session: u64,
|
||||
input: *const frame_loop::InputState,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if input.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
let input_val = unsafe { *input };
|
||||
match session_loop(session) {
|
||||
Ok(Some(running)) => {
|
||||
running.queue_input(input_val);
|
||||
XENORA_OK
|
||||
}
|
||||
Ok(None) => XENORA_INVALID_STATE,
|
||||
Err(status) => status,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn set_paused(session: u64, paused: bool) -> i32 {
|
||||
guarded(|| match session_loop(session) {
|
||||
Ok(Some(running)) if running.set_paused(paused) => XENORA_OK,
|
||||
Ok(_) => XENORA_INVALID_STATE,
|
||||
Err(status) => status,
|
||||
})
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn xenora_session_pause_frame_loop(session: u64) -> i32 {
|
||||
set_paused(session, true)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn xenora_session_resume_frame_loop(session: u64) -> i32 {
|
||||
set_paused(session, false)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn xenora_session_stop_frame_loop(session: u64) -> i32 {
|
||||
guarded(|| match session_loop(session) {
|
||||
Ok(Some(running)) => {
|
||||
running.stop();
|
||||
XENORA_OK
|
||||
}
|
||||
Ok(None) => XENORA_INVALID_STATE,
|
||||
Err(status) => status,
|
||||
})
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Each `u32` output must be null or valid for one aligned write; `out_rgba` must be
|
||||
/// null or valid for `capacity` byte writes.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_frame_loop_status(
|
||||
session: u64,
|
||||
out_state: *mut u32,
|
||||
out_completed: *mut u32,
|
||||
out_frame_id: *mut u32,
|
||||
out_rgba: *mut u8,
|
||||
capacity: u64,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if out_state.is_null()
|
||||
|| out_completed.is_null()
|
||||
|| out_frame_id.is_null()
|
||||
|| out_rgba.is_null()
|
||||
{
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
if capacity < frame_loop::FRAME_BYTES as u64 {
|
||||
return XENORA_BUFFER_TOO_SMALL;
|
||||
}
|
||||
let running = match session_loop(session) {
|
||||
Ok(running) => running,
|
||||
Err(status) => return status,
|
||||
};
|
||||
let (state, completed, latest) = match running {
|
||||
Some(running) => {
|
||||
let snapshot = running.snapshot();
|
||||
(snapshot.status, snapshot.completed, snapshot.latest)
|
||||
}
|
||||
None => (XENORA_LOOP_NONE, 0, None),
|
||||
};
|
||||
// SAFETY: all outputs checked non-null and `out_rgba` at least FRAME_BYTES long.
|
||||
unsafe {
|
||||
out_state.write(state);
|
||||
out_completed.write(completed);
|
||||
match latest {
|
||||
Some((id, pixels)) => {
|
||||
out_frame_id.write(id);
|
||||
std::ptr::copy_nonoverlapping(
|
||||
pixels.as_ptr(),
|
||||
out_rgba,
|
||||
frame_loop::FRAME_BYTES,
|
||||
);
|
||||
}
|
||||
None => out_frame_id.write(XENORA_NO_FRAME),
|
||||
}
|
||||
}
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `out_frame_id` must be valid for one aligned write; `out_rgba` must be valid
|
||||
/// for `capacity` byte writes.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_get_recorded_frame(
|
||||
session: u64,
|
||||
frame_index: u32,
|
||||
out_frame_id: *mut u32,
|
||||
out_rgba: *mut u8,
|
||||
capacity: u64,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if out_frame_id.is_null() || out_rgba.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
if capacity < frame_loop::FRAME_BYTES as u64 {
|
||||
return XENORA_BUFFER_TOO_SMALL;
|
||||
}
|
||||
let running = match session_loop(session) {
|
||||
Ok(Some(running)) => running,
|
||||
Ok(None) => return XENORA_INVALID_STATE,
|
||||
Err(status) => return status,
|
||||
};
|
||||
let Some((id, pixels)) = running.get_recorded_frame(frame_index as usize) else {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
};
|
||||
// SAFETY: checked non-null and capacity >= FRAME_BYTES
|
||||
unsafe {
|
||||
out_frame_id.write(id);
|
||||
std::ptr::copy_nonoverlapping(pixels.as_ptr(), out_rgba, frame_loop::FRAME_BYTES);
|
||||
}
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
@@ -439,6 +690,13 @@ mod tests {
|
||||
("XENORA_LIMIT_EXCEEDED", XENORA_LIMIT_EXCEEDED),
|
||||
("XENORA_BUFFER_TOO_SMALL", XENORA_BUFFER_TOO_SMALL),
|
||||
("XENORA_EXECUTION_FAILED", XENORA_EXECUTION_FAILED),
|
||||
("XENORA_INVALID_STATE", XENORA_INVALID_STATE),
|
||||
("XENORA_LOOP_NONE", XENORA_LOOP_NONE as i32),
|
||||
("XENORA_LOOP_RUNNING", XENORA_LOOP_RUNNING as i32),
|
||||
("XENORA_LOOP_PAUSED", XENORA_LOOP_PAUSED as i32),
|
||||
("XENORA_LOOP_FINISHED", XENORA_LOOP_FINISHED as i32),
|
||||
("XENORA_LOOP_STOPPED", XENORA_LOOP_STOPPED as i32),
|
||||
("XENORA_LOOP_FAILED", XENORA_LOOP_FAILED as i32),
|
||||
] {
|
||||
assert!(header.contains(&format!("{name} = {value},")), "{name}");
|
||||
}
|
||||
@@ -448,6 +706,20 @@ mod tests {
|
||||
assert!(header.contains(&format!(
|
||||
"XENORA_FIXTURE_FRAME_HEIGHT {XENORA_FIXTURE_FRAME_HEIGHT}u"
|
||||
)));
|
||||
assert!(header.contains(&format!(
|
||||
"XENORA_MAX_INSPECT_BYTES {XENORA_MAX_INSPECT_BYTES}u"
|
||||
)));
|
||||
assert!(header.contains(&format!(
|
||||
"XENORA_FRAME_LOOP_MAX_FRAMES {XENORA_FRAME_LOOP_MAX_FRAMES}u"
|
||||
)));
|
||||
assert!(header.contains("XENORA_NO_FRAME 0xFFFFFFFFu"));
|
||||
assert!(header.contains("XENORA_INPUT_NONE 0u"));
|
||||
assert!(header.contains("XENORA_INPUT_RIGHT (1u << 0)"));
|
||||
assert!(header.contains("XENORA_INPUT_LEFT (1u << 1)"));
|
||||
assert!(header.contains("XENORA_INPUT_UP (1u << 2)"));
|
||||
assert!(header.contains("XENORA_INPUT_DOWN (1u << 3)"));
|
||||
assert!(header.contains("XENORA_INPUT_ACTION_A (1u << 4)"));
|
||||
assert!(header.contains("XENORA_INPUT_ACTION_B (1u << 5)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -655,4 +927,80 @@ mod tests {
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_loop_rejects_bad_arguments_and_states() {
|
||||
let _serial = serial();
|
||||
let handle = create();
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(handle, 0),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(handle, 0),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(handle, XENORA_FRAME_LOOP_MAX_FRAMES + 1),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(handle, XENORA_FRAME_LOOP_MAX_FRAMES + 1),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_send_input(handle, std::ptr::null()) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
let dummy_input = xenora_input_state::default();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_send_input(handle, &dummy_input) },
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_queue_input(handle, &dummy_input) },
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
let mut rec_id = 0u32;
|
||||
let mut rec_rgba = [0u8; 48];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_get_recorded_frame(handle, 0, &mut rec_id, rec_rgba.as_mut_ptr(), 48)
|
||||
},
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_pause_frame_loop(handle),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_resume_frame_loop(handle),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(xenora_session_stop_frame_loop(handle), XENORA_INVALID_STATE);
|
||||
let (mut state, mut done, mut id, mut rgba) = (9, 9, 9, [0u8; 48]);
|
||||
let mut status = |h, cap| unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
h,
|
||||
&mut state,
|
||||
&mut done,
|
||||
&mut id,
|
||||
rgba.as_mut_ptr(),
|
||||
cap,
|
||||
)
|
||||
};
|
||||
assert_eq!(status(handle, 47), XENORA_BUFFER_TOO_SMALL);
|
||||
assert_eq!(status(handle, 48), XENORA_OK);
|
||||
xenora_session_destroy(handle);
|
||||
assert_eq!(status(handle, 48), XENORA_INVALID_HANDLE);
|
||||
assert_eq!((state, done, id), (XENORA_LOOP_NONE, 0, XENORA_NO_FRAME));
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(handle, 1),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_pause_frame_loop(handle),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 3 acceptance on a native Metal device: persistent guest rendering through
|
||||
//! the C interface. Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Expected frame `id`, derived only from the geometry: the guest's frame index picks
|
||||
/// column `id % 4`, which is opaque red (x9-constant-ps exports (1, 0, 0, 1)); the
|
||||
/// other columns keep the clear colour (19, 43, 93, 251).
|
||||
fn expected(id: u32) -> Vec<u8> {
|
||||
let mut frame = Vec::new();
|
||||
for _row in 0..3 {
|
||||
for column in 0..4 {
|
||||
if column == id % 4 {
|
||||
frame.extend([255, 0, 0, 255]);
|
||||
} else {
|
||||
frame.extend([19, 43, 93, 251]);
|
||||
}
|
||||
}
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
struct Status {
|
||||
state: u32,
|
||||
completed: u32,
|
||||
frame_id: u32,
|
||||
rgba: [u8; 48],
|
||||
}
|
||||
|
||||
fn status(session: u64) -> Status {
|
||||
let mut s = Status {
|
||||
state: 99,
|
||||
completed: 0,
|
||||
frame_id: 0,
|
||||
rgba: [0; 48],
|
||||
};
|
||||
let code = unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut s.state,
|
||||
&mut s.completed,
|
||||
&mut s.frame_id,
|
||||
s.rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
session
|
||||
}
|
||||
|
||||
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let s = status(session);
|
||||
if done(&s) {
|
||||
return s;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for {what} (state {}, completed {})",
|
||||
s.state,
|
||||
s.completed
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
|
||||
fn footprint() -> u64 {
|
||||
unsafe extern "C" {
|
||||
fn proc_pid_rusage(pid: i32, flavor: i32, buffer: *mut [u64; 32]) -> i32;
|
||||
}
|
||||
let mut info = [0u64; 32];
|
||||
assert_eq!(
|
||||
unsafe { proc_pid_rusage(std::process::id() as i32, 2, &mut info) },
|
||||
0
|
||||
);
|
||||
info[9] // after the 16-byte UUID: user, system, idle wakeups, interrupts, pageins, wired, resident, footprint
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_hundred_guest_frames_arrive_verified_and_in_order() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, 300),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(s.state, XENORA_LOOP_FINISHED);
|
||||
assert_eq!(s.completed, 300);
|
||||
assert_eq!(s.frame_id, 299);
|
||||
assert_eq!(s.rgba.to_vec(), expected(299));
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observed_frame_ids_never_go_backwards_and_match_their_pixels() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 2_000), XENORA_OK);
|
||||
let mut previous = None;
|
||||
let mut samples = 0;
|
||||
loop {
|
||||
let s = status(session);
|
||||
if s.frame_id != XENORA_NO_FRAME {
|
||||
if let Some(p) = previous {
|
||||
assert!(s.frame_id >= p, "frame id went from {p} to {}", s.frame_id);
|
||||
}
|
||||
assert!(
|
||||
s.frame_id < s.completed,
|
||||
"id {} not below completed {}",
|
||||
s.frame_id,
|
||||
s.completed
|
||||
);
|
||||
assert_eq!(
|
||||
s.rgba.to_vec(),
|
||||
expected(s.frame_id),
|
||||
"frame {}",
|
||||
s.frame_id
|
||||
);
|
||||
previous = Some(s.frame_id);
|
||||
samples += 1;
|
||||
}
|
||||
if s.state != XENORA_LOOP_RUNNING {
|
||||
assert_eq!(s.state, XENORA_LOOP_FINISHED);
|
||||
assert_eq!((s.completed, s.frame_id), (2_000, 1_999));
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(samples > 1);
|
||||
xenora_session_destroy(session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pause_holds_the_guest_resume_continues_and_stop_halts_it() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "10 frames", |s| s.completed >= 10);
|
||||
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
// At most the frame already being rendered can still complete after pausing.
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let held = status(session);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
let later = status(session);
|
||||
assert_eq!(later.state, XENORA_LOOP_PAUSED);
|
||||
assert_eq!(later.completed, held.completed, "no frames while paused");
|
||||
assert_eq!(later.frame_id, held.completed - 1);
|
||||
assert_eq!(later.rgba.to_vec(), expected(later.frame_id));
|
||||
|
||||
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
|
||||
let resumed = wait_until(session, "progress after resume", |s| {
|
||||
s.completed >= held.completed + 10
|
||||
});
|
||||
assert_eq!(resumed.state, XENORA_LOOP_RUNNING);
|
||||
|
||||
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
|
||||
let stopped = status(session);
|
||||
assert_eq!(stopped.state, XENORA_LOOP_STOPPED);
|
||||
assert!(stopped.completed < XENORA_FRAME_LOOP_MAX_FRAMES);
|
||||
assert_eq!(stopped.frame_id, stopped.completed - 1);
|
||||
assert_eq!(stopped.rgba.to_vec(), expected(stopped.frame_id));
|
||||
// Pause and resume are refused once the guest has halted.
|
||||
assert_eq!(
|
||||
xenora_session_pause_frame_loop(session),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_resume_frame_loop(session),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destroying_a_running_or_paused_session_stops_it() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
for pause_first in [false, true] {
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "a frame", |s| s.completed >= 1);
|
||||
if pause_first {
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
}
|
||||
let started = Instant::now();
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"destroy joined promptly"
|
||||
);
|
||||
let mut x = 0;
|
||||
let mut rgba = [0u8; 48];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut x,
|
||||
&mut x,
|
||||
&mut x,
|
||||
rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_sessions_do_not_grow_the_memory_footprint() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let run = || {
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
|
||||
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 300));
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
};
|
||||
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
|
||||
run();
|
||||
run();
|
||||
let baseline = footprint();
|
||||
for _ in 0..5 {
|
||||
run();
|
||||
}
|
||||
let after = footprint();
|
||||
let growth = after.saturating_sub(baseline);
|
||||
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
|
||||
assert!(
|
||||
growth < 16 << 20,
|
||||
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 4 acceptance on a native Metal device: interactive guest execution with
|
||||
//! dynamic input handling and rendering through the C interface.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Expected frame `column` (0..3): column `column` is opaque red (255, 0, 0, 255);
|
||||
/// all other columns keep the clear colour (19, 43, 93, 251).
|
||||
fn expected(column: u32) -> Vec<u8> {
|
||||
let mut frame = Vec::new();
|
||||
for _row in 0..3 {
|
||||
for col in 0..4 {
|
||||
if col == column % 4 {
|
||||
frame.extend([255, 0, 0, 255]);
|
||||
} else {
|
||||
frame.extend([19, 43, 93, 251]);
|
||||
}
|
||||
}
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
struct Status {
|
||||
state: u32,
|
||||
completed: u32,
|
||||
frame_id: u32,
|
||||
rgba: [u8; 48],
|
||||
}
|
||||
|
||||
fn status(session: u64) -> Status {
|
||||
let mut s = Status {
|
||||
state: 99,
|
||||
completed: 0,
|
||||
frame_id: 0,
|
||||
rgba: [0; 48],
|
||||
};
|
||||
let code = unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut s.state,
|
||||
&mut s.completed,
|
||||
&mut s.frame_id,
|
||||
s.rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
session
|
||||
}
|
||||
|
||||
fn send_buttons(session: u64, buttons: u32) {
|
||||
let input = xenora_input_state {
|
||||
buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_send_input(session, &input) },
|
||||
XENORA_OK
|
||||
);
|
||||
}
|
||||
|
||||
fn queue_buttons(session: u64, buttons: u32) {
|
||||
let input = xenora_input_state {
|
||||
buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_queue_input(session, &input) },
|
||||
XENORA_OK
|
||||
);
|
||||
}
|
||||
|
||||
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let s = status(session);
|
||||
if done(&s) {
|
||||
return s;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for {what} (state {}, completed {})",
|
||||
s.state,
|
||||
s.completed
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_input_moves_guest_column_and_updates_pixels() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
// Start interactive loop with 120 frames
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 120),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Initial frames without input stay at column 0
|
||||
let s = wait_until(session, "initial frames", |s| s.completed >= 5);
|
||||
assert_eq!(s.frame_id, 0);
|
||||
assert_eq!(s.rgba.to_vec(), expected(0));
|
||||
|
||||
// Send Right input: column should advance 0 -> 1 -> 2 -> 3 -> 0
|
||||
send_buttons(session, XENORA_INPUT_RIGHT);
|
||||
let s_right = wait_until(session, "column moves right", |s| {
|
||||
s.completed >= 15 && s.frame_id != 0
|
||||
});
|
||||
assert_eq!(s_right.rgba.to_vec(), expected(s_right.frame_id));
|
||||
|
||||
// Release input: position stops moving
|
||||
send_buttons(session, XENORA_INPUT_NONE);
|
||||
let s_hold_start = wait_until(session, "wait for release frame", |s| {
|
||||
s.completed >= s_right.completed + 2
|
||||
});
|
||||
let hold_col = s_hold_start.frame_id;
|
||||
let s_hold = wait_until(session, "position holds on release", |s| {
|
||||
s.completed >= s_hold_start.completed + 10
|
||||
});
|
||||
assert_eq!(s_hold.frame_id, hold_col);
|
||||
assert_eq!(s_hold.rgba.to_vec(), expected(s_hold.frame_id));
|
||||
|
||||
// Send Left input: column should move left
|
||||
send_buttons(session, XENORA_INPUT_LEFT);
|
||||
let s_left = wait_until(session, "column moves left", |s| {
|
||||
s.completed >= s_hold.completed + 10 && s.frame_id != hold_col
|
||||
});
|
||||
assert_eq!(s_left.rgba.to_vec(), expected(s_left.frame_id));
|
||||
|
||||
// Wait until finished
|
||||
let s_end = wait_until(session, "loop finish", |s| s.state == XENORA_LOOP_FINISHED);
|
||||
assert_eq!(s_end.completed, 120);
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deterministic_input_replay_produces_identical_frames() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
|
||||
// Timeline of inputs across 60 frames:
|
||||
// frames 0..15: Right
|
||||
// frames 15..30: None
|
||||
// frames 30..45: Left
|
||||
// frames 45..60: Right
|
||||
let replay_sequence: Vec<u32> = (0..60)
|
||||
.map(|f| {
|
||||
if f < 15 {
|
||||
XENORA_INPUT_RIGHT
|
||||
} else if f < 30 {
|
||||
XENORA_INPUT_NONE
|
||||
} else if f < 45 {
|
||||
XENORA_INPUT_LEFT
|
||||
} else {
|
||||
XENORA_INPUT_RIGHT
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let run_replay = || {
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 60),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Pre-queue the complete input sequence
|
||||
for &btn in &replay_sequence {
|
||||
queue_buttons(session, btn);
|
||||
}
|
||||
|
||||
// Wait until all 60 frames are rendered
|
||||
let s = wait_until(session, "replay completion", |s| {
|
||||
s.state == XENORA_LOOP_FINISHED && s.completed == 60
|
||||
});
|
||||
assert_eq!(s.completed, 60);
|
||||
|
||||
// Inspect all 60 recorded frames
|
||||
let mut frames = Vec::with_capacity(60);
|
||||
for i in 0..60 {
|
||||
let mut id = 0u32;
|
||||
let mut rgba = [0u8; 48];
|
||||
let code = unsafe {
|
||||
xenora_session_get_recorded_frame(session, i, &mut id, rgba.as_mut_ptr(), 48)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
assert_eq!(rgba.to_vec(), expected(id));
|
||||
frames.push((id, rgba));
|
||||
}
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
frames
|
||||
};
|
||||
|
||||
let run1 = run_replay();
|
||||
let run2 = run_replay();
|
||||
|
||||
assert_eq!(run1.len(), 60);
|
||||
assert_eq!(run2.len(), 60);
|
||||
for i in 0..60 {
|
||||
assert_eq!(
|
||||
run1[i].0, run2[i].0,
|
||||
"frame {} column mismatch: {} vs {}",
|
||||
i, run1[i].0, run2[i].0
|
||||
);
|
||||
assert_eq!(run1[i].1, run2[i].1, "frame {} pixel mismatch", i);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_loss_and_release_resets_input_cleanly() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 100),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Send Right
|
||||
send_buttons(session, XENORA_INPUT_RIGHT);
|
||||
let s1 = wait_until(session, "moving right", |s| s.completed >= 10);
|
||||
|
||||
// Simulate focus loss / key release
|
||||
send_buttons(session, XENORA_INPUT_NONE);
|
||||
// Wait for the release to take effect in the guest
|
||||
let s_released = wait_until(session, "release takes effect", |s| {
|
||||
s.completed >= s1.completed + 2
|
||||
});
|
||||
let stopped_col = s_released.frame_id;
|
||||
|
||||
// Check next 15 frames: frame_id must remain fixed at stopped_col
|
||||
let s2 = wait_until(session, "hold after release", |s| {
|
||||
s.completed >= s_released.completed + 15
|
||||
});
|
||||
assert_eq!(s2.frame_id, stopped_col);
|
||||
assert_eq!(s2.rgba.to_vec(), expected(stopped_col));
|
||||
|
||||
// Clean stop
|
||||
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
|
||||
let s_stopped = wait_until(session, "stopped", |s| s.state == XENORA_LOOP_STOPPED);
|
||||
assert_eq!(s_stopped.state, XENORA_LOOP_STOPPED);
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destroying_interactive_session_stops_cleanly() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 5000),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Wait until it actually starts rendering
|
||||
wait_until(session, "running", |s| s.completed >= 5);
|
||||
|
||||
let start = Instant::now();
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
assert!(
|
||||
start.elapsed() < Duration::from_millis(500),
|
||||
"destroy took too long: {:?}",
|
||||
start.elapsed()
|
||||
);
|
||||
}
|
||||
@@ -46,6 +46,10 @@ OPERATIONS = {
|
||||
"not": "Not", "brev": "ReverseBits", "bcnt0": "CountZeros", "bcnt1": "CountOnes",
|
||||
"ff0": "FindFirstZero", "ff1": "FindFirstOne", "flbit": "FindLastBit",
|
||||
"sext": "SignExtend", "abs": "Absolute",
|
||||
"min": "Minimum", "max": "Maximum", "cselect": "Select", "bfm": "BitfieldMask",
|
||||
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
|
||||
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
|
||||
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
|
||||
}
|
||||
# Unary operations read one source; they need an operand rule of the unary kind.
|
||||
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
|
||||
@@ -72,10 +76,17 @@ COMPARE_PRIMITIVES = {
|
||||
# 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",
|
||||
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
|
||||
}
|
||||
ARITHMETIC = {
|
||||
"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24",
|
||||
}
|
||||
ARITHMETIC = {"add", "sub"}
|
||||
SHIFTS = {"lshl", "lshr", "ashr"}
|
||||
# Operations whose S1 is an unsigned control word (a shift count or a bit-field
|
||||
# descriptor), so the XML gives it FMT_NUM_U32 whatever the form's signedness.
|
||||
CONTROL_S1 = SHIFTS | {"bfe"}
|
||||
# Operations that always read SCC: the select condition. They need carry_in scc.
|
||||
SCC_READERS = {"cselect"}
|
||||
# XML number formats a source may have for each declared signedness.
|
||||
SOURCE_FORMATS = {
|
||||
"signed": {"FMT_NUM_I32"},
|
||||
@@ -84,6 +95,13 @@ SOURCE_FORMATS = {
|
||||
}
|
||||
# Optional keys: required exactly when the condition holds.
|
||||
SHIFT_KEY = "shift_count_bits"
|
||||
# Shift-and-add declares its fixed S0 shift (required for lshl_add only).
|
||||
SHIFT_AMOUNT_KEY = "shift_amount"
|
||||
SHIFT_AMOUNTS = {1, 2, 3, 4}
|
||||
# Vector forms whose guide pseudocode reads S1 before S0 (D = op(S1, S0))
|
||||
# declare it; the XML records no operand order.
|
||||
SOURCE_ORDER_KEY = "source_order"
|
||||
SOURCE_ORDERS = {"reversed"}
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
SCC = {
|
||||
@@ -93,6 +111,7 @@ SCC = {
|
||||
"signed_overflow": "SignedOverflow",
|
||||
"nonzero": "Nonzero",
|
||||
"relation": "Relation",
|
||||
"selected_src0": "SelectedSrc0",
|
||||
}
|
||||
MASK = {"unchanged": "Unchanged"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
@@ -149,6 +168,35 @@ PRIMITIVES = {
|
||||
("flbit", "signed"): ("unchanged", "flbit_i32", False),
|
||||
("sext", "signed"): ("unchanged", "sext_i32", False),
|
||||
("abs", "signed"): ("nonzero", "abs_nonzero_i32", False),
|
||||
("min", "signed"): ("selected_src0", "min_i32", False),
|
||||
("min", "unsigned"): ("selected_src0", "min_u32", False),
|
||||
("max", "signed"): ("selected_src0", "max_i32", False),
|
||||
("max", "unsigned"): ("selected_src0", "max_u32", False),
|
||||
("cselect", "bitwise"): ("unchanged", "cselect_b32", True),
|
||||
("bfm", "bitwise"): ("unchanged", "bfm_b32", False),
|
||||
("mul", "signed"): ("unchanged", "mul_lo_i32", False),
|
||||
("mul_hi", "unsigned"): ("unchanged", "mul_hi_u32", False),
|
||||
("mul_hi", "signed"): ("unchanged", "mul_hi_i32", False),
|
||||
("bfe", "unsigned"): ("nonzero", "bfe_nonzero_u32", False),
|
||||
("bfe", "signed"): ("nonzero", "bfe_nonzero_i32", False),
|
||||
("absdiff", "signed"): ("nonzero", "absdiff_nonzero_i32", False),
|
||||
("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False),
|
||||
}
|
||||
|
||||
# Vector (VOP2) forms: (operation, signedness) -> the per-lane VectorBinary their
|
||||
# MSL lowering uses. They write no SCC, VCC or EXEC, so scc must be unchanged.
|
||||
VECTOR_PRIMITIVES = {
|
||||
("add", "unsigned"): "Add",
|
||||
("sub", "unsigned"): "Sub",
|
||||
("xnor", "bitwise"): "Xnor",
|
||||
("min", "signed"): "MinSigned",
|
||||
("min", "unsigned"): "MinUnsigned",
|
||||
("max", "signed"): "MaxSigned",
|
||||
("max", "unsigned"): "MaxUnsigned",
|
||||
("mul24", "signed"): "Mul24Signed",
|
||||
("mul24", "unsigned"): "Mul24Unsigned",
|
||||
("mul_hi24", "signed"): "MulHi24Signed",
|
||||
("mul_hi24", "unsigned"): "MulHi24Unsigned",
|
||||
}
|
||||
|
||||
# Operand rules the decoder implements, each exactly once. A registry rule must
|
||||
@@ -157,6 +205,9 @@ UNSUPPORTED_COMBOS = {
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", "src_vcc", "src_exec",
|
||||
"src_m0", "src_ttmp", "src_float_inline", "src_special", "two_literals",
|
||||
}
|
||||
# Every combo name a rule may list (VOP2 also names vcc_hi and NULL sources,
|
||||
# which SOP2 groups under src_vcc and src_special).
|
||||
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"}
|
||||
OPERAND_RULES = {
|
||||
"sop2_sgpr": {
|
||||
"rust": "Sop2Sgpr",
|
||||
@@ -202,6 +253,26 @@ OPERAND_RULES = {
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
|
||||
"kind": "unary",
|
||||
},
|
||||
"vop2_vgpr": {
|
||||
"rust": "Vop2Vgpr",
|
||||
"enum": "VectorAluOp",
|
||||
"shape": {
|
||||
"family": "VOP2",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# vector_source = VGPR, s0-s105, vcc_lo, inline integer -16..64 or a
|
||||
# literal; the decoder rejects these SRC0 selectors.
|
||||
"unsupported": {
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector",
|
||||
},
|
||||
}
|
||||
|
||||
VARIANT = re.compile(r"^[A-Z][A-Za-z0-9]*$")
|
||||
@@ -249,7 +320,7 @@ def _check_rule(name, rule, errors):
|
||||
errors.append(f"operand rule {name}: not implemented by the decoder")
|
||||
return
|
||||
unsupported = rule.get("unsupported", [])
|
||||
unknown = sorted(set(unsupported) - UNSUPPORTED_COMBOS)
|
||||
unknown = sorted(set(unsupported) - ALL_COMBOS)
|
||||
if unknown:
|
||||
errors.append(f"operand rule {name}: unknown unsupported combos {unknown}")
|
||||
if len(set(unsupported)) != len(unsupported):
|
||||
@@ -284,12 +355,19 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
errors.append(f"{label}: opcode {form['opcode']} is not an identifier of {encoding_name}")
|
||||
operands = {}
|
||||
scc_in = scc_out = False
|
||||
implicit = set()
|
||||
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
scc_out |= is_output
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
else:
|
||||
implicit.add(kind)
|
||||
# The vocabulary can state only SCC effects (vcc and exec are "unchanged"),
|
||||
# so any other implicit XML operand, such as VCC, is undeclared.
|
||||
if implicit:
|
||||
errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared")
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts the XML SCC input")
|
||||
if scc_out != (form["scc"] != "unchanged"):
|
||||
@@ -302,7 +380,7 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
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
|
||||
shift = form["operation"] in CONTROL_S1 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:
|
||||
@@ -318,7 +396,7 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
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"
|
||||
f"{label}: control operand {field} has XML format {data_format}, not FMT_NUM_U32"
|
||||
)
|
||||
elif type(bits) is int:
|
||||
if data_format != f"FMT_NUM_I{bits}":
|
||||
@@ -369,7 +447,10 @@ def validate(registry, snapshot):
|
||||
for index, form in enumerate(forms):
|
||||
label = form.get("name", f"form #{index}")
|
||||
missing = sorted(FORM_KEYS - set(form))
|
||||
extra = sorted(set(form) - FORM_KEYS - {SHIFT_KEY, RELATION_KEY, SOURCE_BITS_KEY})
|
||||
extra = sorted(
|
||||
set(form) - FORM_KEYS
|
||||
- {SHIFT_KEY, SHIFT_AMOUNT_KEY, RELATION_KEY, SOURCE_BITS_KEY, SOURCE_ORDER_KEY}
|
||||
)
|
||||
if missing:
|
||||
errors.append(f"{label}: incomplete, missing {missing}")
|
||||
if extra:
|
||||
@@ -397,10 +478,12 @@ def validate(registry, snapshot):
|
||||
for key, value in (
|
||||
("name", form["name"]),
|
||||
("opcode", (form["family"], form["opcode"])),
|
||||
("variant", form["variant"]),
|
||||
# Variants are names in their operand rule's enum.
|
||||
("variant", (_rule_enum(form), form["variant"])),
|
||||
):
|
||||
if value in seen[key]:
|
||||
errors.append(f"{label}: duplicate {key} {value}")
|
||||
shown = form["variant"] if key == "variant" else value
|
||||
errors.append(f"{label}: duplicate {key} {shown}")
|
||||
seen[key].add(value)
|
||||
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
|
||||
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
|
||||
@@ -416,6 +499,22 @@ def validate(registry, snapshot):
|
||||
)
|
||||
elif SHIFT_KEY in form:
|
||||
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
|
||||
if form["operation"] == "lshl_add":
|
||||
amount = form.get(SHIFT_AMOUNT_KEY)
|
||||
if type(amount) is not int or amount not in SHIFT_AMOUNTS:
|
||||
errors.append(
|
||||
f"{label}: {SHIFT_AMOUNT_KEY} must be one of {sorted(SHIFT_AMOUNTS)}, got {amount!r}"
|
||||
)
|
||||
elif SHIFT_AMOUNT_KEY in form:
|
||||
errors.append(f"{label}: {SHIFT_AMOUNT_KEY} on a non-lshl_add operation")
|
||||
if SOURCE_ORDER_KEY in form:
|
||||
order = form[SOURCE_ORDER_KEY]
|
||||
if not isinstance(order, str) or order not in SOURCE_ORDERS:
|
||||
errors.append(f"{label}: unknown {SOURCE_ORDER_KEY} {order!r}")
|
||||
elif _rule_kind(form) != "vector":
|
||||
errors.append(f"{label}: {SOURCE_ORDER_KEY} on a non-vector form")
|
||||
if form["operation"] in SCC_READERS and form["carry_in"] != "scc":
|
||||
errors.append(f"{label}: operation {form['operation']} reads SCC (requires carry_in scc)")
|
||||
if form["operation"] == "sext":
|
||||
bits = form.get(SOURCE_BITS_KEY)
|
||||
if type(bits) is not int or bits not in SOURCE_BITS:
|
||||
@@ -433,6 +532,11 @@ def validate(registry, snapshot):
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = ("relation", None, False)
|
||||
elif _rule_kind(form) == "vector":
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
primitive = None if lowering is None else ("unchanged", lowering, False)
|
||||
else:
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
@@ -455,7 +559,9 @@ def validate(registry, snapshot):
|
||||
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"
|
||||
else "unary" if form["operation"] in UNARY
|
||||
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
|
||||
else "alu"
|
||||
):
|
||||
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
|
||||
_check_spec(label, form["spec"], documents, errors)
|
||||
@@ -470,6 +576,23 @@ def validate(registry, snapshot):
|
||||
return errors
|
||||
|
||||
|
||||
def _implemented_rule(form):
|
||||
operands = form.get("operands")
|
||||
return OPERAND_RULES.get(operands) if isinstance(operands, str) else None
|
||||
|
||||
|
||||
def _rule_kind(form):
|
||||
"""The implemented kind of the form's operand rule, or None if unknown."""
|
||||
rule = _implemented_rule(form)
|
||||
return rule["kind"] if rule else None
|
||||
|
||||
|
||||
def _rule_enum(form):
|
||||
"""The generated enum of the form's operand rule, or None if unknown."""
|
||||
rule = _implemented_rule(form)
|
||||
return rule["enum"] if rule else None
|
||||
|
||||
|
||||
def _check_spec(label, spec, documents, errors):
|
||||
has_guide = False
|
||||
for ref in spec:
|
||||
@@ -501,7 +624,7 @@ def render(registry, snapshot):
|
||||
"use crate::primitive;",
|
||||
"use crate::semantics::{",
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, Wave,",
|
||||
" Signedness, SpecRef, VectorBinary, Wave,",
|
||||
"};",
|
||||
"use crate::CompareRelation;",
|
||||
"",
|
||||
@@ -541,6 +664,8 @@ def render(registry, snapshot):
|
||||
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
|
||||
f" width: {form['width']},",
|
||||
f" shift_count_bits: {form.get(SHIFT_KEY, 0)},",
|
||||
f" shift_amount: {form.get(SHIFT_AMOUNT_KEY, 0)},",
|
||||
f" swap_sources: {'true' if SOURCE_ORDER_KEY in form else 'false'},",
|
||||
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,"),
|
||||
@@ -674,6 +799,41 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "vector":
|
||||
out += [
|
||||
"",
|
||||
" /// Assembler name of the 32-bit (VOP2) encoding, as LLVM prints it.",
|
||||
" pub const fn assembly_name(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}_e32\"," for form in forms]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The per-lane operation its MSL lowering uses.",
|
||||
" pub const fn lowering(self) -> VectorBinary {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => "
|
||||
f"VectorBinary::{VECTOR_PRIMITIVES[(form['operation'], form['signedness'])]},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation reads its sources reversed (`D = op(S1, S0)`).",
|
||||
" pub const fn swaps_sources(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if SOURCE_ORDER_KEY in form else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "compare":
|
||||
out += [
|
||||
"",
|
||||
@@ -700,7 +860,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
return out
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation reads SCC as a carry-in or borrow-in.",
|
||||
" /// Whether the operation reads SCC (carry-in, borrow-in or select condition).",
|
||||
" pub const fn reads_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
@@ -712,22 +872,45 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// 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) {",
|
||||
" /// 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). `scc_in` is the SCC read by forms that consume it (ignored by",
|
||||
" /// the others).",
|
||||
" pub const fn evaluate(self, src0: u32, src1: u32, scc_in: bool) -> (u32, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, takes_carry = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if takes_carry:
|
||||
argument = "carry_in" if form["carry_in"] == "scc" else "false"
|
||||
argument = "scc_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})"
|
||||
elif form["operation"] == "lshl_add":
|
||||
call = f"primitive::{function}(src0, src1, {form[SHIFT_AMOUNT_KEY]})"
|
||||
else:
|
||||
call = f"primitive::{function}(src0, src1)"
|
||||
out.append(f" Self::{form['variant']} => {call},")
|
||||
if form["scc"] == "unchanged":
|
||||
out.append(f" Self::{form['variant']} => ({call}, None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{form['variant']} => {{",
|
||||
f" let (value, scc) = {call};",
|
||||
" (value, Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
|
||||
|
||||
@@ -49,11 +49,11 @@ unsupported = [
|
||||
# family encoding family; must match the XML base encoding
|
||||
# opcode XML opcode; must match
|
||||
# variant Rust enum variant of the typed op
|
||||
# operation primitive: add | sub | and | or | xor
|
||||
# operation primitive (closed vocabulary in generate_semantics.py OPERATIONS)
|
||||
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
|
||||
# carry_in none | scc (scc only for unsigned add/sub)
|
||||
# carry_in none | scc (scc for unsigned add/sub carry and the cselect condition)
|
||||
# width operand and result width in bits
|
||||
# scc carry_out | borrow | signed_overflow | nonzero
|
||||
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
|
||||
# vcc, exec unchanged (stated, not implied)
|
||||
# wave any | wave32
|
||||
# operands a key of [operand_rules]
|
||||
@@ -373,6 +373,317 @@ operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- SOP2 32-bit integer arithmetic, select and bit-field forms (#215) ----
|
||||
# min/max: SCC = S0 chosen by the strict compare (a tie gives S1, SCC 0). cselect
|
||||
# reads SCC and writes none. bfm, mul, mul_hi write no SCC (Tables 11, 12, 14).
|
||||
# bfe: offset S1[4:0], width S1[22:16]. lshl_add: SCC = carry of (S0 << N) + S1.
|
||||
|
||||
[[form]]
|
||||
name = "S_MIN_I32"
|
||||
family = "SOP2"
|
||||
opcode = 6
|
||||
variant = "MinI32"
|
||||
operation = "min"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MIN_U32"
|
||||
family = "SOP2"
|
||||
opcode = 7
|
||||
variant = "MinU32"
|
||||
operation = "min"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MAX_I32"
|
||||
family = "SOP2"
|
||||
opcode = 8
|
||||
variant = "MaxI32"
|
||||
operation = "max"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MAX_U32"
|
||||
family = "SOP2"
|
||||
opcode = 9
|
||||
variant = "MaxU32"
|
||||
operation = "max"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 103 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CSELECT_B32"
|
||||
family = "SOP2"
|
||||
opcode = 10
|
||||
variant = "CselectB32"
|
||||
operation = "cselect"
|
||||
signedness = "bitwise"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 103 },
|
||||
{ document = "guide", section = "5.5", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BFM_B32"
|
||||
family = "SOP2"
|
||||
opcode = 36
|
||||
variant = "BfmB32"
|
||||
operation = "bfm"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 104 },
|
||||
{ document = "guide", section = "5.7", page = 36 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MUL_I32"
|
||||
family = "SOP2"
|
||||
opcode = 38
|
||||
variant = "MulI32"
|
||||
operation = "mul"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BFE_U32"
|
||||
family = "SOP2"
|
||||
opcode = 39
|
||||
variant = "BfeU32"
|
||||
operation = "bfe"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.7", page = 36 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BFE_I32"
|
||||
family = "SOP2"
|
||||
opcode = 40
|
||||
variant = "BfeI32"
|
||||
operation = "bfe"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.7", page = 36 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ABSDIFF_I32"
|
||||
family = "SOP2"
|
||||
opcode = 44
|
||||
variant = "AbsdiffI32"
|
||||
operation = "absdiff"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL1_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 46
|
||||
variant = "Lshl1AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 1
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 105 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL2_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 47
|
||||
variant = "Lshl2AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 2
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 105 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL3_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 48
|
||||
variant = "Lshl3AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 3
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL4_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 49
|
||||
variant = "Lshl4AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 4
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MUL_HI_U32"
|
||||
family = "SOP2"
|
||||
opcode = 53
|
||||
variant = "MulHiU32"
|
||||
operation = "mul_hi"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MUL_HI_I32"
|
||||
family = "SOP2"
|
||||
opcode = 54
|
||||
variant = "MulHiI32"
|
||||
operation = "mul_hi"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
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).
|
||||
|
||||
@@ -875,3 +1186,226 @@ spec = [
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOP2 32-bit vector integer forms (#215) ----
|
||||
# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The 24-bit
|
||||
# multiplies read S0[23:0] and S1[23:0], sign-extended when signed; the high
|
||||
# forms keep bits 63:32 of the product. SUBREV declares its reversed sources.
|
||||
|
||||
[operand_rules.vop2_vgpr]
|
||||
family = "VOP2"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_I32_I24"
|
||||
family = "VOP2"
|
||||
opcode = 9
|
||||
variant = "MulI32I24"
|
||||
operation = "mul24"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 131 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_HI_I32_I24"
|
||||
family = "VOP2"
|
||||
opcode = 10
|
||||
variant = "MulHiI32I24"
|
||||
operation = "mul_hi24"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 132 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_U32_U24"
|
||||
family = "VOP2"
|
||||
opcode = 11
|
||||
variant = "MulU32U24"
|
||||
operation = "mul24"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 132 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_HI_U32_U24"
|
||||
family = "VOP2"
|
||||
opcode = 12
|
||||
variant = "MulHiU32U24"
|
||||
operation = "mul_hi24"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 132 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MIN_I32"
|
||||
family = "VOP2"
|
||||
opcode = 17
|
||||
variant = "MinI32"
|
||||
operation = "min"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MAX_I32"
|
||||
family = "VOP2"
|
||||
opcode = 18
|
||||
variant = "MaxI32"
|
||||
operation = "max"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MIN_U32"
|
||||
family = "VOP2"
|
||||
opcode = 19
|
||||
variant = "MinU32"
|
||||
operation = "min"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MAX_U32"
|
||||
family = "VOP2"
|
||||
opcode = 20
|
||||
variant = "MaxU32"
|
||||
operation = "max"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_XNOR_B32"
|
||||
family = "VOP2"
|
||||
opcode = 30
|
||||
variant = "XnorB32"
|
||||
operation = "xnor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_ADD_NC_U32"
|
||||
family = "VOP2"
|
||||
opcode = 37
|
||||
variant = "AddNcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUB_NC_U32"
|
||||
family = "VOP2"
|
||||
opcode = 38
|
||||
variant = "SubNcU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUBREV_NC_U32"
|
||||
family = "VOP2"
|
||||
opcode = 39
|
||||
variant = "SubrevNcU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_order = "reversed"
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+18
-2
@@ -18,7 +18,7 @@ pub use rdna2::{
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
|
||||
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
@@ -216,7 +216,8 @@ pub enum Instruction {
|
||||
dst: u8,
|
||||
src: ScalarSource,
|
||||
},
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and, for
|
||||
/// most operations, SCC; `s_cselect_b32` also reads SCC.
|
||||
ScalarAlu {
|
||||
op: ScalarAluOp,
|
||||
dst: u8,
|
||||
@@ -236,6 +237,15 @@ pub enum Instruction {
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// VOP2 32-bit per-lane integer operation from the semantic registry.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal;
|
||||
/// `src1` is a VGPR. Inactive lanes keep `dst`.
|
||||
VectorAlu {
|
||||
op: VectorAluOp,
|
||||
dst: u8,
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// SOPP jump to a stream byte offset when SCC is clear.
|
||||
BranchSccZero { target: usize },
|
||||
/// SOPP jump when the Wave32 execution mask is empty.
|
||||
@@ -318,6 +328,7 @@ impl Instruction {
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorAlu { op, .. } => op.assembly_name(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
Self::BranchVccZero { .. } => "s_cbranch_vccz",
|
||||
@@ -389,6 +400,11 @@ impl fmt::Display for Instruction {
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
Self::VectorAlu {
|
||||
dst, src0, src1, ..
|
||||
} => {
|
||||
write!(formatter, " v{dst}, {src0}, v{src1}")
|
||||
}
|
||||
Self::Branch { target }
|
||||
| Self::BranchSccZero { target }
|
||||
| Self::BranchExecZero { target }
|
||||
|
||||
@@ -214,3 +214,105 @@ pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
|
||||
let value = (a as i32).wrapping_abs() as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Two's-complement minimum and whether S0 was strictly smaller (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn min_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) < (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned minimum and whether S0 was strictly smaller.
|
||||
pub const fn min_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a < b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Two's-complement maximum and whether S0 was strictly greater (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn max_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) > (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned maximum and whether S0 was strictly greater.
|
||||
pub const fn max_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a > b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// `a` when `condition` (SCC) is set, otherwise `b`.
|
||||
pub const fn cselect_b32(a: u32, b: u32, condition: bool) -> u32 {
|
||||
if condition { a } else { b }
|
||||
}
|
||||
|
||||
/// `((1 << a[4:0]) - 1) << b[4:0]`: a mask of `a[4:0]` ones starting at bit `b[4:0]`.
|
||||
pub const fn bfm_b32(a: u32, b: u32) -> u32 {
|
||||
((1u32 << (a & 0x1f)) - 1) << (b & 0x1f)
|
||||
}
|
||||
|
||||
/// The low 32 bits of the product (identical for signed and unsigned operands).
|
||||
pub const fn mul_lo_i32(a: u32, b: u32) -> u32 {
|
||||
a.wrapping_mul(b)
|
||||
}
|
||||
|
||||
/// The high 32 bits of the unsigned 64-bit product.
|
||||
pub const fn mul_hi_u32(a: u32, b: u32) -> u32 {
|
||||
((a as u64 * b as u64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The high 32 bits of the two's-complement 64-bit product.
|
||||
pub const fn mul_hi_i32(a: u32, b: u32) -> u32 {
|
||||
((a as i32 as i64 * b as i32 as i64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The `bfe` field descriptor: offset `b[4:0]` and width `b[22:16]` (0-127).
|
||||
const fn bfe_field(b: u32) -> (u32, u32) {
|
||||
(b & 0x1f, (b >> 16) & 0x7f)
|
||||
}
|
||||
|
||||
/// Unsigned bit-field extract: `(a >> offset) & ((1 << width) - 1)`, where a
|
||||
/// width of 32 or more keeps every shifted bit; and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = a >> offset;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
shifted & ((1 << width) - 1)
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Signed bit-field extract: `a` shifted arithmetically by the offset, the low
|
||||
/// `width` bits kept and sign-extended from bit `width - 1` (a width of 32 or
|
||||
/// more keeps the whole shifted word); and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = ((a as i32) >> offset) as u32;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
let unused = 32 - width;
|
||||
(((shifted << unused) as i32) >> unused) as u32
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `|a - b|` of the wrapped 32-bit difference (so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn absdiff_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = (a.wrapping_sub(b) as i32).unsigned_abs();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `(a << shift) + b` and the carry out of the exact sum, which counts the bits
|
||||
/// shifted out of `a`; `shift` is 1 to 4.
|
||||
pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
|
||||
let sum = ((a as u64) << shift) + b as u64;
|
||||
(sum as u32, sum >> 32 != 0)
|
||||
}
|
||||
@@ -68,6 +68,57 @@ pub enum Operation {
|
||||
SignExtend,
|
||||
/// Two's-complement absolute value; the most negative value maps to itself.
|
||||
Absolute,
|
||||
/// S0 when it is strictly less than S1, otherwise S1.
|
||||
Minimum,
|
||||
/// S0 when it is strictly greater than S1, otherwise S1.
|
||||
Maximum,
|
||||
/// S0 when SCC is set, otherwise S1.
|
||||
Select,
|
||||
/// `((1 << S0[4:0]) - 1) << S1[4:0]`.
|
||||
BitfieldMask,
|
||||
/// Low 32 bits of the product.
|
||||
Multiply,
|
||||
/// High 32 bits of the 64-bit product.
|
||||
MultiplyHigh,
|
||||
/// The field of S0 at offset S1[4:0] with width S1[22:16]; sign-extended when signed.
|
||||
BitfieldExtract,
|
||||
/// Absolute value of the wrapped 32-bit difference S0 - S1.
|
||||
AbsoluteDifference,
|
||||
/// `(S0 << shift_amount) + S1`.
|
||||
ShiftLeftAdd,
|
||||
/// Low 32 bits of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
Multiply24,
|
||||
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
MultiplyHigh24,
|
||||
}
|
||||
|
||||
/// The per-lane integer operation a vector form lowers to. One reusable MSL
|
||||
/// template exists per variant; a form selects it through its declared
|
||||
/// operation and signedness, never through its opcode.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorBinary {
|
||||
/// Wrapping `a + b`.
|
||||
Add,
|
||||
/// Wrapping `a - b`.
|
||||
Sub,
|
||||
/// `!(a ^ b)`.
|
||||
Xnor,
|
||||
/// Two's-complement minimum.
|
||||
MinSigned,
|
||||
/// Unsigned minimum.
|
||||
MinUnsigned,
|
||||
/// Two's-complement maximum.
|
||||
MaxSigned,
|
||||
/// Unsigned maximum.
|
||||
MaxUnsigned,
|
||||
/// Low 32 bits of `sext(a[23:0]) * sext(b[23:0])`.
|
||||
Mul24Signed,
|
||||
/// Low 32 bits of `a[23:0] * b[23:0]`.
|
||||
Mul24Unsigned,
|
||||
/// Bits 63:32 of `sext(a[23:0]) * sext(b[23:0])`.
|
||||
MulHi24Signed,
|
||||
/// Bits 63:32 of `a[23:0] * b[23:0]`.
|
||||
MulHi24Unsigned,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
@@ -81,12 +132,12 @@ pub enum Signedness {
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Extra input consumed by the operation.
|
||||
/// Whether the operation reads SCC.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// No carry or borrow input.
|
||||
/// SCC is not read.
|
||||
None,
|
||||
/// SCC as carry-in (add) or borrow-in (sub).
|
||||
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
|
||||
Scc,
|
||||
}
|
||||
|
||||
@@ -105,6 +156,8 @@ pub enum SccEffect {
|
||||
Nonzero,
|
||||
/// The compare's relation holds for S0 and S1.
|
||||
Relation,
|
||||
/// The result is S0 by the strict comparison (min, max): equal operands give 0.
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
@@ -135,6 +188,10 @@ pub enum OperandRule {
|
||||
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
|
||||
/// a literal word. Everything else is rejected as unsupported.
|
||||
Sop1Sgpr,
|
||||
/// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline
|
||||
/// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is
|
||||
/// rejected as unsupported.
|
||||
Vop2Vgpr,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
@@ -183,12 +240,16 @@ pub struct FormSemantics {
|
||||
pub operation: Operation,
|
||||
/// Operand interpretation.
|
||||
pub signedness: Signedness,
|
||||
/// Carry or borrow input.
|
||||
/// SCC input.
|
||||
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,
|
||||
/// Fixed left shift of S0 for shift-and-add operations (1 to 4); 0 otherwise.
|
||||
pub shift_amount: u8,
|
||||
/// Whether the operation reads its sources in reverse order (`D = op(S1, S0)`).
|
||||
pub swap_sources: bool,
|
||||
/// 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.
|
||||
|
||||
+1212
-66
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,7 @@
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
|
||||
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
|
||||
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
@@ -53,6 +53,7 @@ fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
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);
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
|
||||
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
@@ -85,3 +86,20 @@ fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
|
||||
for op in VectorAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Vop2);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
|
||||
assert_eq!(op.swaps_sources(), row.swap_sources);
|
||||
assert_eq!(row.scc, SccEffect::Unchanged);
|
||||
}
|
||||
// The hand-written VOP2 forms (v_and_b32, v_add_f32, ...) must not be
|
||||
// dispatched here.
|
||||
dispatch_selects_exactly(EncodingFamily::Vop2, |word| {
|
||||
VectorAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
@@ -64,6 +64,8 @@ struct Prefixes {
|
||||
rex_w: bool,
|
||||
/// REX.R: extends the ModRM `reg` field to R8-R15.
|
||||
rex_r: bool,
|
||||
/// REX.X: extends the SIB `index` field to R8-R15.
|
||||
rex_x: bool,
|
||||
/// REX.B: extends the ModRM `rm` field to R8-R15.
|
||||
rex_b: bool,
|
||||
/// The GS segment override prefix (0x65) is present.
|
||||
@@ -453,6 +455,7 @@ impl<'a> Interpreter<'a> {
|
||||
if (byte & 0xF0) == 0x40 {
|
||||
prefixes.rex_w = (byte & 0x08) != 0;
|
||||
prefixes.rex_r = (byte & 0x04) != 0;
|
||||
prefixes.rex_x = (byte & 0x02) != 0;
|
||||
prefixes.rex_b = (byte & 0x01) != 0;
|
||||
byte = self.fetch_u8()?;
|
||||
}
|
||||
@@ -762,7 +765,11 @@ 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 prefixes.rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
|
||||
// REX.X extends the SIB index field; REX.R extends the ModRM reg
|
||||
// field and must not affect the index. An index field of 100b
|
||||
// selects r12 when REX.X is set, and means "no index" otherwise.
|
||||
let index_field = (sib >> 3) & 7;
|
||||
let index_raw = index_field + if prefixes.rex_x { 8 } else { 0 };
|
||||
let base_raw = (sib & 7) + if prefixes.rex_b { 8 } else { 0 };
|
||||
|
||||
let base_v = if mode == 0 && (sib & 7) == 5 {
|
||||
@@ -772,7 +779,7 @@ impl<'a> Interpreter<'a> {
|
||||
self.cpu.get(Register::from_index(base_raw))
|
||||
};
|
||||
|
||||
let index_v = if (sib >> 3) & 7 == 4 {
|
||||
let index_v = if index_field == 4 && !prefixes.rex_x {
|
||||
// index == 4 means no index register (ESP/RSP)
|
||||
0u64
|
||||
} else {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! End-to-end integration tests for Xenora X12: PE32+ loading & x86-64 execution bootstrap.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Register};
|
||||
use xenora_loader::memory::{MemoryError, MemoryPermissions};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
};
|
||||
@@ -289,3 +289,176 @@ fn test_sib_addressing_mode() {
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(result.final_state.get(Register::Rdx), 0x12345678_9abcdef0);
|
||||
}
|
||||
|
||||
/// Base address of the read-write data region used by the SIB tests.
|
||||
const DATA_BASE: u64 = 0x6000_0000;
|
||||
/// Base address of the read-write stack region used by the SIB tests.
|
||||
const STACK_BASE: u64 = 0x5000_0000;
|
||||
|
||||
/// Run `code` on the interpreter with a writable stack and a writable data
|
||||
/// region, and return the final state, the exit reason and the guest memory.
|
||||
///
|
||||
/// `DATA_BASE` is mapped read-write so a test can observe where a store
|
||||
/// landed. `STACK_BASE` holds the stack pointer.
|
||||
fn run_with_regions(code: &[u8]) -> (CpuState, ExitReason, GuestMemory) {
|
||||
let pe_bytes = build_synthetic_pe32_plus(code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("data mapping should succeed");
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
(result.final_state, result.exit_reason, loaded.memory)
|
||||
}
|
||||
|
||||
/// `mov rax, DATA_BASE` (48 B8 <imm64>).
|
||||
fn mov_rax_data_base() -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xB8];
|
||||
code.extend_from_slice(&DATA_BASE.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov rbx, 0x12345678_9abcdef0` (48 BB <imm64>).
|
||||
fn mov_rbx_value() -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xBB];
|
||||
code.extend_from_slice(&0x1234_5678_9abc_def0u64.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// A SIB index register is extended by REX.X, not by REX.R.
|
||||
///
|
||||
/// The encoding 4A 89 1C E0 is `mov [rax + r12*8], rbx`. Its REX prefix sets
|
||||
/// REX.X, so the SIB index field 100b selects r12 and the store lands at
|
||||
/// `rax + r12*8`. REX.R is clear in this prefix, so the ModRM `reg` field is
|
||||
/// rbx.
|
||||
#[test]
|
||||
fn test_rex_x_extends_the_sib_index_register() {
|
||||
// mov rax, DATA_BASE (48 b8 <imm64>)
|
||||
// mov r12, 4 (41 bc 04 00 00 00)
|
||||
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
|
||||
// mov [rax + r12*8], rbx (4a 89 1c e0)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rax_data_base();
|
||||
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
|
||||
code.extend_from_slice(&mov_rbx_value());
|
||||
code.extend_from_slice(&[0x4A, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], rbx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (_state, reason, memory) = run_with_regions(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// r12 holds 4, so the store lands at DATA_BASE + 4*8.
|
||||
assert_eq!(
|
||||
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
|
||||
0x1234_5678_9abc_def0
|
||||
);
|
||||
// The unindexed slot at DATA_BASE must be untouched.
|
||||
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
|
||||
}
|
||||
|
||||
/// REX.R and REX.X extend independent fields in the same instruction.
|
||||
///
|
||||
/// The encoding 4C 89 1C C8 is `mov [rax + rcx*8], r11`. Its REX prefix sets
|
||||
/// REX.R, so the ModRM `reg` field 011 selects r11. It does not set REX.X, so
|
||||
/// the SIB index field 001 selects rcx and must not be extended to r9.
|
||||
#[test]
|
||||
fn test_rex_r_does_not_extend_the_sib_index_register() {
|
||||
// mov rax, DATA_BASE (48 b8 <imm64>)
|
||||
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
|
||||
// mov ecx, 4 (b9 04 00 00 00)
|
||||
// mov r9, 8 (41 b9 08 00 00 00)
|
||||
// mov [rax + rcx*8], r11 (4c 89 1c c8)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rax_data_base();
|
||||
let mut r11 = vec![0x49, 0xBB];
|
||||
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
|
||||
code.extend_from_slice(&r11);
|
||||
code.extend_from_slice(&[0xB9, 0x04, 0x00, 0x00, 0x00]); // mov ecx, 4
|
||||
code.extend_from_slice(&[0x41, 0xB9, 0x08, 0x00, 0x00, 0x00]); // mov r9d, 8
|
||||
code.extend_from_slice(&[0x4C, 0x89, 0x1C, 0xC8]); // mov [rax + rcx*8], r11
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (_state, reason, memory) = run_with_regions(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// rcx holds 4, so the store lands at DATA_BASE + 4*8. A wrongly extended
|
||||
// index would have selected r9 and landed at DATA_BASE + 8*8.
|
||||
assert_eq!(
|
||||
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
|
||||
0x1122_3344_5566_7788
|
||||
);
|
||||
assert_eq!(memory.read_u64(DATA_BASE + 64).expect("r9 slot"), 0);
|
||||
}
|
||||
|
||||
/// REX.R and REX.X set together extend their own fields independently.
|
||||
///
|
||||
/// The encoding 4E 89 1C E0 is `mov [rax + r12*8], r11`. Its REX prefix sets
|
||||
/// both REX.R and REX.X: the ModRM `reg` field 011 becomes r11 and the SIB
|
||||
/// index field 100b becomes r12.
|
||||
#[test]
|
||||
fn test_rex_r_and_rex_x_set_together_extend_independent_fields() {
|
||||
// mov rax, DATA_BASE (48 b8 <imm64>)
|
||||
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
|
||||
// mov r12, 4 (41 bc 04 00 00 00)
|
||||
// mov [rax + r12*8], r11 (4e 89 1c e0)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rax_data_base();
|
||||
let mut r11 = vec![0x49, 0xBB];
|
||||
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
|
||||
code.extend_from_slice(&r11);
|
||||
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
|
||||
code.extend_from_slice(&[0x4E, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], r11
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (_state, reason, memory) = run_with_regions(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(
|
||||
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
|
||||
0x1122_3344_5566_7788
|
||||
);
|
||||
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
|
||||
}
|
||||
|
||||
/// Without REX.X, a SIB index field of 100b means "no index register" and the
|
||||
/// address is the base alone.
|
||||
///
|
||||
/// The encoding 48 89 1C 24 is `mov [rsp], rbx`: the SIB index field is 100b
|
||||
/// and REX.X is clear, so no index register contributes to the address.
|
||||
#[test]
|
||||
fn test_sib_index_field_100b_without_rex_x_means_no_index() {
|
||||
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
|
||||
// mov r12, 0x1000 (41 bc 00 10 00 00)
|
||||
// mov [rsp], rbx (48 89 1c 24)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rbx_value();
|
||||
code.extend_from_slice(&[0x41, 0xBC, 0x00, 0x10, 0x00, 0x00]); // mov r12d, 0x1000
|
||||
code.extend_from_slice(&[0x48, 0x89, 0x1C, 0x24]); // mov [rsp], rbx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let pe_bytes = build_synthetic_pe32_plus(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
|
||||
// The index is absent, so the address is the base (rsp) alone.
|
||||
let stack_top = STACK_BASE + 0x8000;
|
||||
assert_eq!(
|
||||
loaded.memory.read_u64(stack_top).expect("base slot"),
|
||||
0x1234_5678_9abc_def0
|
||||
);
|
||||
}
|
||||
+299
-48
@@ -69,6 +69,9 @@ pub enum Op {
|
||||
condition: BranchCondition,
|
||||
},
|
||||
Vector(VectorAlu, u8, u8, u8),
|
||||
/// VOP2 32-bit integer form: VDST, SRC0 (VGPR, SGPR, `vcc_lo`, inline
|
||||
/// integer or literal) and VSRC1. Writes neither VCC nor SCC.
|
||||
VectorInteger(VectorInteger, u8, CompareSource, u8),
|
||||
End,
|
||||
}
|
||||
|
||||
@@ -107,7 +110,7 @@ impl Comparison {
|
||||
}
|
||||
}
|
||||
|
||||
/// First source of a VOPC compare.
|
||||
/// First source of a VOPC compare or a VOP2 integer form.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareSource {
|
||||
/// VGPR index.
|
||||
@@ -164,6 +167,35 @@ pub enum ScalarAlu {
|
||||
ShiftRight,
|
||||
/// D = signext(S0) >> S1[4:0], SCC = (D != 0).
|
||||
ArithmeticShiftRight,
|
||||
/// Guide 12.1: D = (S0 < S1) ? S0 : S1, SCC = (S0 < S1); signed or not.
|
||||
Minimum {
|
||||
signed: bool,
|
||||
},
|
||||
/// D = (S0 > S1) ? S0 : S1, SCC = (S0 > S1).
|
||||
Maximum {
|
||||
signed: bool,
|
||||
},
|
||||
/// D = SCC ? S0 : S1; reads SCC and leaves it unchanged.
|
||||
Select,
|
||||
/// D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged.
|
||||
BitfieldMask,
|
||||
/// D = low 32 bits of S0 * S1; SCC unchanged.
|
||||
Multiply,
|
||||
/// D = (S0 >> S1[4:0]) & ((1 << S1[22:16]) - 1), sign-extended from the
|
||||
/// field's top bit when signed (S0 then shifts arithmetically);
|
||||
/// SCC = (D != 0).
|
||||
BitfieldExtract {
|
||||
signed: bool,
|
||||
},
|
||||
/// D = |S0 - S1| with the 32-bit difference (0x80000000 stays),
|
||||
/// SCC = (D != 0).
|
||||
AbsoluteDifference,
|
||||
/// D = (S0 << N) + S1, SCC = ((S0 << N) + S1 >= 2^32) with N = 1..4.
|
||||
ShiftLeftAdd(u8),
|
||||
/// D = high 32 bits of S0 * S1; SCC unchanged.
|
||||
MultiplyHigh {
|
||||
signed: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// SOP1 unary operations decoded by the reference interpreter (RDNA 2 ISA
|
||||
@@ -207,6 +239,90 @@ pub enum VectorAlu {
|
||||
FloatMultiply,
|
||||
}
|
||||
|
||||
/// VOP2 32-bit integer forms with a general SRC0 (AMD RDNA 2 ISA guide
|
||||
/// section 12.7). None has a carry-in or carry-out.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorInteger {
|
||||
/// 9 / 11: D = low 32 bits of S0[23:0] * S1[23:0], sign-extended from
|
||||
/// bit 23 when `signed`.
|
||||
Multiply24 { signed: bool },
|
||||
/// 10 / 12: D = bits 63:32 of the same 48-bit product.
|
||||
MultiplyHigh24 { signed: bool },
|
||||
/// 17 / 19: D = S0 < S1 ? S0 : S1.
|
||||
Minimum { signed: bool },
|
||||
/// 18 / 20: D = S0 >= S1 ? S0 : S1.
|
||||
Maximum { signed: bool },
|
||||
/// 30: D = ~(S0 ^ S1).
|
||||
Xnor,
|
||||
/// 37: D = S0 + S1.
|
||||
Add,
|
||||
/// 38: D = S0 - S1.
|
||||
Subtract,
|
||||
/// 39: D = S1 - S0.
|
||||
SubtractReverse,
|
||||
}
|
||||
|
||||
impl VectorInteger {
|
||||
/// Opcode bits 30-25 of the VOP2 word.
|
||||
fn from_opcode(opcode: u8) -> Option<Self> {
|
||||
Some(match opcode {
|
||||
9 => Self::Multiply24 { signed: true },
|
||||
10 => Self::MultiplyHigh24 { signed: true },
|
||||
11 => Self::Multiply24 { signed: false },
|
||||
12 => Self::MultiplyHigh24 { signed: false },
|
||||
17 => Self::Minimum { signed: true },
|
||||
18 => Self::Maximum { signed: true },
|
||||
19 => Self::Minimum { signed: false },
|
||||
20 => Self::Maximum { signed: false },
|
||||
30 => Self::Xnor,
|
||||
37 => Self::Add,
|
||||
38 => Self::Subtract,
|
||||
39 => Self::SubtractReverse,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// D for S0 = `a`, S1 = `b`, from exact i64 arithmetic reduced modulo 2^32.
|
||||
fn apply(self, a: u32, b: u32) -> u32 {
|
||||
let field = |bits: u32, signed: bool| {
|
||||
if signed {
|
||||
i64::from(((bits << 8) as i32) >> 8)
|
||||
} else {
|
||||
i64::from(bits & 0x00ff_ffff)
|
||||
}
|
||||
};
|
||||
let widen = |bits: u32, signed: bool| {
|
||||
if signed {
|
||||
i64::from(bits as i32)
|
||||
} else {
|
||||
i64::from(bits)
|
||||
}
|
||||
};
|
||||
match self {
|
||||
Self::Multiply24 { signed } => (field(a, signed) * field(b, signed)) as u32,
|
||||
Self::MultiplyHigh24 { signed } => ((field(a, signed) * field(b, signed)) >> 32) as u32,
|
||||
Self::Minimum { signed } => {
|
||||
if widen(a, signed) < widen(b, signed) {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
Self::Maximum { signed } => {
|
||||
if widen(a, signed) >= widen(b, signed) {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
Self::Xnor => !(a ^ b),
|
||||
Self::Add => a.wrapping_add(b),
|
||||
Self::Subtract => a.wrapping_sub(b),
|
||||
Self::SubtractReverse => b.wrapping_sub(a),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute original little-endian gfx1030 bytes with the synthetic binding ABI.
|
||||
///
|
||||
/// Each dispatched lane reads the corresponding input word and may write only
|
||||
@@ -371,35 +487,46 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
(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..=0x91),
|
||||
tail @ ..,
|
||||
] if (*left, *right) != (255, 255)
|
||||
&& low & 0x7f <= 105
|
||||
&& (low & 0x80 == 0 || matches!(high, 0x80..=0x82)) =>
|
||||
[left, right, low, high @ 0x80..=0xbf, tail @ ..]
|
||||
if (*left, *right) != (255, 255)
|
||||
&& low & 0x7f <= 105
|
||||
&& matches!(
|
||||
(high & 0x3f) << 1 | low >> 7,
|
||||
0..=10 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34
|
||||
| 36 | 38..=40 | 44 | 46..=49 | 53 | 54
|
||||
) =>
|
||||
{
|
||||
let kind = match (high, low >> 7) {
|
||||
(0x80, 0) => ScalarAlu::Add,
|
||||
(0x80, _) => ScalarAlu::Subtract,
|
||||
(0x81, 0) => ScalarAlu::AddSigned,
|
||||
(0x81, _) => ScalarAlu::SubtractSigned,
|
||||
(0x82, 0) => ScalarAlu::AddWithCarry,
|
||||
(0x82, _) => ScalarAlu::SubtractWithBorrow,
|
||||
(0x87, _) => ScalarAlu::And,
|
||||
(0x88, _) => ScalarAlu::Or,
|
||||
(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 kind = match (high & 0x3f) << 1 | low >> 7 {
|
||||
0 => ScalarAlu::Add,
|
||||
1 => ScalarAlu::Subtract,
|
||||
2 => ScalarAlu::AddSigned,
|
||||
3 => ScalarAlu::SubtractSigned,
|
||||
4 => ScalarAlu::AddWithCarry,
|
||||
5 => ScalarAlu::SubtractWithBorrow,
|
||||
6 => ScalarAlu::Minimum { signed: true },
|
||||
7 => ScalarAlu::Minimum { signed: false },
|
||||
8 => ScalarAlu::Maximum { signed: true },
|
||||
9 => ScalarAlu::Maximum { signed: false },
|
||||
10 => ScalarAlu::Select,
|
||||
14 => ScalarAlu::And,
|
||||
16 => ScalarAlu::Or,
|
||||
18 => ScalarAlu::Xor,
|
||||
20 => ScalarAlu::AndNot,
|
||||
22 => ScalarAlu::OrNot,
|
||||
24 => ScalarAlu::Nand,
|
||||
26 => ScalarAlu::Nor,
|
||||
28 => ScalarAlu::Xnor,
|
||||
30 => ScalarAlu::ShiftLeft,
|
||||
32 => ScalarAlu::ShiftRight,
|
||||
34 => ScalarAlu::ArithmeticShiftRight,
|
||||
36 => ScalarAlu::BitfieldMask,
|
||||
38 => ScalarAlu::Multiply,
|
||||
39 => ScalarAlu::BitfieldExtract { signed: false },
|
||||
40 => ScalarAlu::BitfieldExtract { signed: true },
|
||||
44 => ScalarAlu::AbsoluteDifference,
|
||||
op @ 46..=49 => ScalarAlu::ShiftLeftAdd(op - 45),
|
||||
53 => ScalarAlu::MultiplyHigh { signed: false },
|
||||
_ => ScalarAlu::MultiplyHigh { signed: true },
|
||||
};
|
||||
let (left, left_length) = decode_scalar(*left, tail, offset)?;
|
||||
let (right, right_length) = decode_scalar(*right, tail, offset)?;
|
||||
@@ -461,25 +588,22 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
signed: opcode < 192,
|
||||
};
|
||||
let vsrc1 = (packed >> 1) | ((upper & 1) << 7);
|
||||
let selector = u16::from(*lo) | (u16::from(packed & 1) << 8);
|
||||
let (src0, length) = match selector {
|
||||
0..=106 => (CompareSource::Scalar(*lo), 4),
|
||||
128..=192 => (CompareSource::Immediate(u32::from(selector - 128)), 4),
|
||||
193..=208 => (
|
||||
CompareSource::Immediate(0_u32.wrapping_sub(u32::from(selector - 192))),
|
||||
4,
|
||||
),
|
||||
255 => {
|
||||
let literal = tail
|
||||
.first_chunk::<4>()
|
||||
.ok_or_else(|| error(offset, "truncated literal"))?;
|
||||
(CompareSource::Immediate(u32::from_le_bytes(*literal)), 8)
|
||||
}
|
||||
256..=511 => (CompareSource::Vector(*lo), 4),
|
||||
_ => return Err(error(offset, "unsupported VOPC source")),
|
||||
};
|
||||
let (src0, length) =
|
||||
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOPC source")?;
|
||||
(Op::Compare(comparison, src0, vsrc1), length)
|
||||
}
|
||||
// VOP2 integer forms (bit 31 = 0): OP bits 25-30, VDST 17-24,
|
||||
// VSRC1 9-16, SRC0 0-8.
|
||||
[lo, packed, upper, tag @ 0x00..=0x7b, tail @ ..]
|
||||
if VectorInteger::from_opcode(tag >> 1).is_some() =>
|
||||
{
|
||||
let kind = VectorInteger::from_opcode(tag >> 1).unwrap();
|
||||
let dst = (upper >> 1) | ((tag & 1) << 7);
|
||||
let vsrc1 = (packed >> 1) | ((upper & 1) << 7);
|
||||
let (src0, length) =
|
||||
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOP2 source")?;
|
||||
(Op::VectorInteger(kind, dst, src0, vsrc1), length)
|
||||
}
|
||||
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
|
||||
if packed & 0xfe == 2 && upper & 1 == 0 =>
|
||||
{
|
||||
@@ -564,6 +688,34 @@ fn decode_scalar(
|
||||
}
|
||||
}
|
||||
|
||||
/// A vector SRC0 selector (bits 0-8: `lo` and bit 0 of `packed`): s0-s105 or
|
||||
/// `vcc_lo` (106), an inline integer, a literal dword from `tail`, or a VGPR.
|
||||
fn decode_vector_source(
|
||||
lo: u8,
|
||||
packed: u8,
|
||||
tail: &[u8],
|
||||
offset: usize,
|
||||
unsupported: &'static str,
|
||||
) -> Result<(CompareSource, usize), ReferenceError> {
|
||||
let selector = u16::from(lo) | (u16::from(packed & 1) << 8);
|
||||
Ok(match selector {
|
||||
0..=106 => (CompareSource::Scalar(lo), 4),
|
||||
128..=192 => (CompareSource::Immediate(u32::from(selector - 128)), 4),
|
||||
193..=208 => (
|
||||
CompareSource::Immediate(0_u32.wrapping_sub(u32::from(selector - 192))),
|
||||
4,
|
||||
),
|
||||
255 => {
|
||||
let literal = tail
|
||||
.first_chunk::<4>()
|
||||
.ok_or_else(|| error(offset, "truncated literal"))?;
|
||||
(CompareSource::Immediate(u32::from_le_bytes(*literal)), 8)
|
||||
}
|
||||
256..=511 => (CompareSource::Vector(lo), 4),
|
||||
_ => return Err(error(offset, unsupported)),
|
||||
})
|
||||
}
|
||||
|
||||
fn vector_alu(op: VectorAlu, a: u32, b: u32, offset: usize) -> Result<u32, ReferenceError> {
|
||||
let error = || {
|
||||
error(
|
||||
@@ -654,7 +806,8 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
Op::Move(dst, _)
|
||||
| Op::MoveScalar(dst, _)
|
||||
| Op::Add(dst, ..)
|
||||
| Op::Vector(_, dst, ..) => {
|
||||
| Op::Vector(_, dst, ..)
|
||||
| Op::VectorInteger(_, dst, ..) => {
|
||||
if exec != 0
|
||||
&& registers
|
||||
.iter()
|
||||
@@ -736,6 +889,31 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
results[lane] = Some((dst, value));
|
||||
}
|
||||
}
|
||||
Op::VectorInteger(kind, dst, src0, src1) => {
|
||||
if exec != 0 {
|
||||
// As for a compare, sources are checked once for the wave,
|
||||
// whichever present lanes are active.
|
||||
let check = |register: u8| {
|
||||
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))
|
||||
};
|
||||
match src0 {
|
||||
CompareSource::Vector(register) => check(register)?,
|
||||
CompareSource::Scalar(register) => {
|
||||
read_scalar(Source::Register(register))?;
|
||||
}
|
||||
CompareSource::Immediate(_) => {}
|
||||
}
|
||||
check(src1)?;
|
||||
}
|
||||
for lane in (0..lanes).filter(|&lane| executes(lane)) {
|
||||
let s0 = match src0 {
|
||||
CompareSource::Vector(register) => read(lane, register)?,
|
||||
CompareSource::Scalar(register) => read_scalar(Source::Register(register))?,
|
||||
CompareSource::Immediate(bits) => bits,
|
||||
};
|
||||
results[lane] = Some((dst, kind.apply(s0, read(lane, src1)?)));
|
||||
}
|
||||
}
|
||||
Op::ScalarMove(dst, src) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
@@ -803,8 +981,13 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
ScalarAlu::AddWithCarry | ScalarAlu::SubtractWithBorrow => i64::from(
|
||||
scc.ok_or_else(|| error(offset, "carry-in from uninitialized SCC"))?,
|
||||
),
|
||||
ScalarAlu::Select => {
|
||||
i64::from(scc.ok_or_else(|| error(offset, "select on uninitialized SCC"))?)
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
let (signed_lhs, signed_rhs) =
|
||||
(i64::from(lhs as u32 as i32), i64::from(rhs as u32 as i32));
|
||||
// Exact integer arithmetic, then reduction modulo 2^32.
|
||||
let (exact, flag) = match kind {
|
||||
ScalarAlu::Add | ScalarAlu::AddWithCarry => {
|
||||
@@ -833,6 +1016,65 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
};
|
||||
(bits, bits != 0)
|
||||
}
|
||||
// Guide 12.1: strict comparisons, so equal operands give
|
||||
// S1 (the same value) and SCC = 0.
|
||||
ScalarAlu::Minimum { signed } | ScalarAlu::Maximum { signed } => {
|
||||
let (a, b) = if signed {
|
||||
(signed_lhs, signed_rhs)
|
||||
} else {
|
||||
(lhs, rhs)
|
||||
};
|
||||
let first = if matches!(kind, ScalarAlu::Minimum { .. }) {
|
||||
a < b
|
||||
} else {
|
||||
a > b
|
||||
};
|
||||
(if first { lhs } else { rhs }, first)
|
||||
}
|
||||
// The SCC-less forms; `flag` is unused for them below.
|
||||
ScalarAlu::Select => (if carry == 1 { lhs } else { rhs }, false),
|
||||
ScalarAlu::BitfieldMask => (((1 << (lhs & 0x1f)) - 1) << (rhs & 0x1f), false),
|
||||
ScalarAlu::Multiply => (signed_lhs * signed_rhs, false),
|
||||
ScalarAlu::MultiplyHigh { signed } => {
|
||||
// The unsigned product fits only in u64.
|
||||
let high = if signed {
|
||||
(signed_lhs * signed_rhs) >> 32
|
||||
} else {
|
||||
((lhs as u64 * rhs as u64) >> 32) as i64
|
||||
};
|
||||
(high, false)
|
||||
}
|
||||
// Offset S1[4:0], width S1[22:16] (0-127). A width of 32 or
|
||||
// more keeps every bit of the shifted word.
|
||||
ScalarAlu::BitfieldExtract { signed } => {
|
||||
let (shift, width) = (rhs & 0x1f, (rhs >> 16) & 0x7f);
|
||||
let data = if signed { signed_lhs } else { lhs };
|
||||
let shifted = data >> shift;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
let field = shifted & ((1 << width) - 1);
|
||||
if signed && field >> (width - 1) == 1 {
|
||||
field - (1 << width)
|
||||
} else {
|
||||
field
|
||||
}
|
||||
};
|
||||
(value, value.rem_euclid(1 << 32) != 0)
|
||||
}
|
||||
// The 32-bit difference first (guide examples), then |D|.
|
||||
ScalarAlu::AbsoluteDifference => {
|
||||
let difference = (signed_lhs - signed_rhs) as u32 as i32;
|
||||
let value = difference.unsigned_abs();
|
||||
(i64::from(value), value != 0)
|
||||
}
|
||||
// The carry out of the exact (S0 << N) + S1.
|
||||
ScalarAlu::ShiftLeftAdd(n) => {
|
||||
let sum = (lhs << n) + rhs;
|
||||
(sum, sum >= 1 << 32)
|
||||
}
|
||||
// Guide 12.1: shifts use only S1[4:0]; all set SCC = (D != 0).
|
||||
_ => {
|
||||
let (a, b) = (lhs as u32, rhs as u32);
|
||||
@@ -851,7 +1093,16 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
};
|
||||
let value = exact.rem_euclid(1 << 32) as u32;
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
scc = Some(flag);
|
||||
// Guide 12.1 and Tables 11, 12, 14: these forms leave SCC unchanged.
|
||||
if !matches!(
|
||||
kind,
|
||||
ScalarAlu::Select
|
||||
| ScalarAlu::BitfieldMask
|
||||
| ScalarAlu::Multiply
|
||||
| ScalarAlu::MultiplyHigh { .. }
|
||||
) {
|
||||
scc = Some(flag);
|
||||
}
|
||||
}
|
||||
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
|
||||
Op::Compare(comparison, src0, src1) => {
|
||||
|
||||
+115
-8
@@ -9,7 +9,8 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
pub use xenora_decoder::Architecture;
|
||||
use xenora_decoder::{
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorCompareOp, VectorSource,
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorBinary, VectorCompareOp,
|
||||
VectorSource,
|
||||
};
|
||||
|
||||
/// SGPR index of `vcc_lo`.
|
||||
@@ -161,6 +162,7 @@ impl Op {
|
||||
Binary::ShiftLeft | Binary::ShiftRight => {
|
||||
format!("{left} {symbol} ({right} & 31u)")
|
||||
}
|
||||
Binary::Vector(operation) => vector_expression(operation, &left, &right),
|
||||
_ => format!("{left} {symbol} {right}"),
|
||||
}
|
||||
}
|
||||
@@ -219,6 +221,8 @@ enum Binary {
|
||||
Xor,
|
||||
FloatAdd,
|
||||
FloatMul,
|
||||
/// A registry VOP2 integer operation, lowered by its typed template.
|
||||
Vector(VectorBinary),
|
||||
}
|
||||
|
||||
impl Binary {
|
||||
@@ -233,10 +237,56 @@ impl Binary {
|
||||
Self::Xor => ("xor.b32", "^"),
|
||||
Self::FloatAdd => ("add.f32", "+"),
|
||||
Self::FloatMul => ("mul.f32", "*"),
|
||||
Self::Vector(operation) => (
|
||||
match operation {
|
||||
VectorBinary::Add => "add.u32",
|
||||
VectorBinary::Sub => "sub.u32",
|
||||
VectorBinary::Xnor => "xnor.b32",
|
||||
VectorBinary::MinSigned => "min.i32",
|
||||
VectorBinary::MinUnsigned => "min.u32",
|
||||
VectorBinary::MaxSigned => "max.i32",
|
||||
VectorBinary::MaxUnsigned => "max.u32",
|
||||
VectorBinary::Mul24Signed => "mul24.i32",
|
||||
VectorBinary::Mul24Unsigned => "mul24.u32",
|
||||
VectorBinary::MulHi24Signed => "mulhi24.i32",
|
||||
VectorBinary::MulHi24Unsigned => "mulhi24.u32",
|
||||
},
|
||||
"",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The MSL template of each per-lane registry operation. Integer arithmetic is
|
||||
/// on `uint` (wrapping); signed forms reinterpret with `as_type`, and the
|
||||
/// 24-bit forms sign-extend bit 23 with a shift pair or mask to 24 bits first.
|
||||
fn vector_expression(operation: VectorBinary, left: &str, right: &str) -> String {
|
||||
let int = |value: &str| format!("as_type<int>({value})");
|
||||
let i24 = |value: &str| format!("(as_type<int>({value} << 8u) >> 8)");
|
||||
let u24 = |value: &str| format!("({value} & 0x00ffffffu)");
|
||||
match operation {
|
||||
VectorBinary::Add => format!("{left} + {right}"),
|
||||
VectorBinary::Sub => format!("{left} - {right}"),
|
||||
VectorBinary::Xnor => format!("~({left} ^ {right})"),
|
||||
VectorBinary::MinSigned => format!("as_type<uint>(min({}, {}))", int(left), int(right)),
|
||||
VectorBinary::MinUnsigned => format!("min({left}, {right})"),
|
||||
VectorBinary::MaxSigned => format!("as_type<uint>(max({}, {}))", int(left), int(right)),
|
||||
VectorBinary::MaxUnsigned => format!("max({left}, {right})"),
|
||||
// The low 32 bits of a product do not depend on signedness, so the
|
||||
// sign-extended factors multiply as wrapping uint.
|
||||
VectorBinary::Mul24Signed => format!(
|
||||
"as_type<uint>({}) * as_type<uint>({})",
|
||||
i24(left),
|
||||
i24(right)
|
||||
),
|
||||
VectorBinary::Mul24Unsigned => format!("{} * {}", u24(left), u24(right)),
|
||||
VectorBinary::MulHi24Signed => {
|
||||
format!("as_type<uint>(mulhi({}, {}))", i24(left), i24(right))
|
||||
}
|
||||
VectorBinary::MulHi24Unsigned => format!("mulhi({}, {})", u24(left), u24(right)),
|
||||
}
|
||||
}
|
||||
|
||||
// Each bit is either known zero, known one or unconstrained.
|
||||
#[derive(Clone, Copy)]
|
||||
struct KnownBits {
|
||||
@@ -632,7 +682,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
| Instruction::VectorXorB32 { dst, .. } => dst,
|
||||
_ => {
|
||||
return Err(error(
|
||||
"code skipped by a runtime s_cbranch_vccz may contain only integer vector ALU instructions",
|
||||
"code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the hand-written integer VOP2 forms",
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -670,7 +720,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
| Instruction::VectorOrB32 { .. }
|
||||
| Instruction::VectorXorB32 { .. }
|
||||
| Instruction::VectorAddF32 { .. }
|
||||
| Instruction::VectorMulF32 { .. } => continue,
|
||||
| Instruction::VectorMulF32 { .. }
|
||||
| Instruction::VectorAlu { .. } => continue,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -831,20 +882,22 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
src1,
|
||||
} => {
|
||||
let (src0, src1) = (read_scalar(src0)?, read_scalar(src1)?);
|
||||
let carry_in = if op.reads_scc() {
|
||||
scc.ok_or_else(|| error("carry-in or borrow-in reads uninitialized SCC"))?
|
||||
let scc_in = if op.reads_scc() {
|
||||
scc.ok_or_else(|| error("SOP2 SCC input reads uninitialized SCC"))?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if dst < 8 {
|
||||
return Err(error("scalar ALU would modify a resource descriptor"));
|
||||
}
|
||||
let (value, flag) = op.evaluate(src0, src1, carry_in);
|
||||
let (value, flag) = op.evaluate(src0, src1, scc_in);
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
scc = Some(flag);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
@@ -938,6 +991,44 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
},
|
||||
)
|
||||
}
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => {
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(register) => read(register)?,
|
||||
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
|
||||
match (lane_vcc, scalars[VCC_LO]) {
|
||||
(Some(mask), _) => mask,
|
||||
(None, Some(bits)) => {
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
(None, None) => {
|
||||
return Err(error("vector ALU reads uninitialized VCC_LO"));
|
||||
}
|
||||
}
|
||||
}
|
||||
VectorSource::Scalar(register) => {
|
||||
let bits = read_scalar(ScalarSource::Register(register))?;
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
VectorSource::Immediate(bits) => {
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
};
|
||||
let src1 = read(src1)?;
|
||||
let (left, right) = if op.swaps_sources() {
|
||||
(src1, src0)
|
||||
} else {
|
||||
(src0, src1)
|
||||
};
|
||||
(
|
||||
Some(dst),
|
||||
Op::Binary(Binary::Vector(op.lowering()), left, right),
|
||||
)
|
||||
}
|
||||
Instruction::VectorAddF32 { dst, src0, src1 } => (
|
||||
Some(dst),
|
||||
Op::Binary(Binary::FloatAdd, read(src0)?, read(src1)?),
|
||||
@@ -973,6 +1064,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
}
|
||||
_ => KnownBits::UNKNOWN,
|
||||
};
|
||||
// Arms may push operand constants first, so the result is the next slot
|
||||
// now rather than `next`.
|
||||
let produced = Value(operations.len());
|
||||
facts.push(value_bits);
|
||||
operations.push((offset, operation));
|
||||
if let Some(dest) = dest {
|
||||
@@ -987,7 +1081,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
&mut facts,
|
||||
offset,
|
||||
exec,
|
||||
next,
|
||||
produced,
|
||||
registers[slot],
|
||||
)?);
|
||||
}
|
||||
@@ -998,6 +1092,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
})
|
||||
}
|
||||
|
||||
/// A wave-uniform constant operand at `offset`.
|
||||
fn constant(
|
||||
operations: &mut Vec<(usize, Op)>,
|
||||
facts: &mut Vec<KnownBits>,
|
||||
offset: usize,
|
||||
bits: u32,
|
||||
) -> Value {
|
||||
let value = Value(operations.len());
|
||||
operations.push((offset, Op::Constant(bits)));
|
||||
facts.push(KnownBits::constant(bits));
|
||||
value
|
||||
}
|
||||
|
||||
// Keeping a value for inactive lanes requires a previously initialized destination.
|
||||
fn merge_lanes(
|
||||
operations: &mut Vec<(usize, Op)>,
|
||||
|
||||
@@ -322,6 +322,34 @@ fn scalar_unary_results_reach_the_kernel_as_constants() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_arith_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-arith.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-arith.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-arith.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_integer_forms_lower_to_per_lane_templates() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-integer.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/vector-integer.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/vector-integer.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
|
||||
|
||||
@@ -54,3 +54,6 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
|
||||
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
|
||||
- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents.
|
||||
- [Infrastructure QA ownership](coordination/infrastructure-qa-ownership.md) — Non-overlapping paths for infrastructure and QA tooling.
|
||||
- [Agent queue smoke evidence](coordination/agent-queue-smoke.md) — Live Actions results from the disposable smoke repository.
|
||||
- [Infrastructure QA tooling](testing/infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
|
||||
@@ -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: 72 of 72. Accepted Metal forms · Apple M5: 18 of 72. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<desc id="description">Decoded gfx1030 forms: 100 of 100. Accepted Metal forms · Apple M5: 18 of 100. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
|
||||
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
|
||||
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
|
||||
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">72 / 72</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">100 / 100</text>
|
||||
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 72</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 100</text>
|
||||
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="103" width="122.50" height="4" rx="2" fill="#88c6bd"/>
|
||||
<rect x="20" y="103" width="88.20" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
|
||||
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
|
||||
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,48 @@
|
||||
# Agent queue live smoke test
|
||||
|
||||
Issue: #180
|
||||
Disposable repository: [`ranveersoni98/xenora-agent-queue-smoke`](https://github.com/ranveersoni98/xenora-agent-queue-smoke) (private)
|
||||
Production Xenora workflows are not modified by this exercise except where a
|
||||
separate coordinated fix is recorded.
|
||||
|
||||
## Why a disposable repository
|
||||
|
||||
The queue unit suite does not call the GitHub API. Issue #180 requires Actions
|
||||
evidence for simultaneous claims, refusal, release, stale-lease audit behaviour,
|
||||
pending-run replay and exact head-SHA verification against a real repository.
|
||||
|
||||
## Harness notes
|
||||
|
||||
- Copies `scripts/agent_queue/`, the unit tests, `agent-queue.sh`,
|
||||
`agent-sync.sh` and the two agent workflows from Xenora.
|
||||
- Uses `ubuntu-latest` runners in the disposable repo only. Queue decisions are
|
||||
standard-library Python; production Xenora keeps `ubuntu-24.04-arm`.
|
||||
- Config upstream is `ranveersoni98/xenora-agent-queue-smoke`.
|
||||
|
||||
## Evidence log
|
||||
|
||||
| Scenario | Result | Evidence | Recorded |
|
||||
| --- | --- | --- | --- |
|
||||
| Claim grant on ready task | pass | issue #1 labels `agent:claimed,claimed-by:ranveersoni98`; run `45383910132` | 2026-11-24 |
|
||||
| Overlap claim refusal | pass | issue #2 bot: file overlap with claimed task #1; run `45384365386` | 2026-11-24 |
|
||||
| Disjoint second claim | pass | issue #3 claimed; run `45384367521` | 2026-11-24 |
|
||||
| `/progress` renew | pass | issue #1 bot: Lease renewed; run `45384473061` | 2026-11-24 |
|
||||
| `/release` | pass | issue #3 returned to `agent:ready`; bot release marker | 2026-11-24 |
|
||||
| Claim without `agent:ready` | pass | issue #4 refused: not labelled agent:ready | 2026-11-24 |
|
||||
| Comment-only apply crash | fixed | `ghio.apply_actions` skipped no-op `gh issue edit`; mirrored to smoke | 2026-11-24 |
|
||||
| Audit `workflow_dispatch` | pass | run `45385817420` after `pull-requests: read` and `summary --now` argparse fix | 2026-11-24 |
|
||||
| Exact `/verified` head SHA | deferred | needs second eligible non-author account on the smoke repo | 2026-11-24 |
|
||||
| Full wall-clock stale lease | deferred | covered by unit tests with frozen clock (`lease_hours=168`) | 2026-11-24 |
|
||||
|
||||
## Production follow-ups
|
||||
|
||||
1. Keep `agent-pr-checks` advisory until this evidence is reviewed.
|
||||
2. Coordinate adding `pull-requests: read` to the production audit job permissions
|
||||
(same defect as the smoke audit failure).
|
||||
3. Add a second QA-eligible verifier before treating `/verified` as smoke-complete.
|
||||
|
||||
## Local unit suite
|
||||
|
||||
```sh
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
# Infrastructure QA campaign ledger
|
||||
|
||||
Running record for the infrastructure and engineering-quality campaign.
|
||||
Update after each meaningful commit batch. Do not invent passing tests.
|
||||
|
||||
## Baseline
|
||||
|
||||
- Branch: `main` synchronized with `origin/main` before each batch
|
||||
- Hard exclusions: CPU/runtime crates, RDNA2 crates, `app/`, fixtures, GPU tests
|
||||
- Approved paths: see `infrastructure-qa-ownership.md`
|
||||
|
||||
## Commits
|
||||
|
||||
| SHA | Summary | Tests |
|
||||
| --- | --- | --- |
|
||||
| `dcc6f7a` | fix(agent-queue): skip no-op gh issue edit on comment-only actions. | focused suite before commit |
|
||||
| `261493b` | test(agent-queue): add read-only claim conflict prediction coverage. | focused suite before commit |
|
||||
| `87a5ada` | docs(coordination): record infrastructure QA ownership manifest. | focused suite before commit |
|
||||
| `7fa9820` | fix(agent-queue): accept summary --now after the subcommand. | focused suite before commit |
|
||||
| `f902617` | fix(ci): grant agent-queue audit pull-requests:read. | focused suite before commit |
|
||||
| `f5c72a4` | docs(coordination): record agent-queue disposable smoke evidence. | focused suite before commit |
|
||||
| `a10ac43` | docs(coordination): add infrastructure QA campaign ledger. | focused suite before commit |
|
||||
| `8b5cee5` | feat(qa): preserve command exit status for orchestration pipes. | focused suite before commit |
|
||||
| `1b555a5` | feat(qa): add structured multi-suite test orchestration reports. | focused suite before commit |
|
||||
| `19879c8` | feat(qa): add advisory PR scope, DCO and artifact validators. | focused suite before commit |
|
||||
| `f772081` | feat(qa): analyze existing benchmark samples for percentiles. | focused suite before commit |
|
||||
| `53f73a8` | feat(qa): compare orchestration history and emit handoff reports. | focused suite before commit |
|
||||
| `fc1587e` | feat(qa): add Apple Silicon environment diagnostic helpers. | focused suite before commit |
|
||||
| `8e039d9` | feat(qa): predict claim file-scope conflicts before editing. | focused suite before commit |
|
||||
| `f6350ad` | feat(release): verify ARM64 Mach-O arch, linkage and app bundles. | focused suite before commit |
|
||||
| `eaf78a2` | feat(release): build checksum manifests and license inventories. | focused suite before commit |
|
||||
| `8694751` | docs(testing): index infrastructure QA and release tooling. | focused suite before commit |
|
||||
| `27c3d28` | docs(changelog): note infrastructure QA tooling and agent-queue smoke fixes. | focused suite before commit |
|
||||
|
||||
## Smoke repository
|
||||
|
||||
- Repo: `ranveersoni98/xenora-agent-queue-smoke`
|
||||
- See `agent-queue-smoke.md` for Actions evidence
|
||||
|
||||
## Limitations
|
||||
|
||||
- Production agent PR checks remain advisory
|
||||
- Independent `/verified` on smoke PRs needs a second eligible account
|
||||
- New QA/release tools are local/advisory until review
|
||||
@@ -0,0 +1,54 @@
|
||||
# Infrastructure and QA ownership manifest
|
||||
|
||||
Non-overlapping file ownership for the infrastructure and engineering-quality
|
||||
campaign. Active CPU/runtime, RDNA2 and native-application Gates 4–9 work stays
|
||||
outside this manifest.
|
||||
|
||||
Rechecked against `origin/main` at the claim of issue #180. Update this file
|
||||
when a path is claimed, released or closed.
|
||||
|
||||
## Hard exclusions (do not edit under this campaign)
|
||||
|
||||
- `crates/loader/`, `crates/import-gen/`, `crates/ffi/`, `crates/isa/`
|
||||
- `crates/decoder/`, `crates/shader/`, `crates/ref/`, `crates/metal/`, `crates/texture/`
|
||||
- `app/`, `fixtures/`, `tests/validation/`
|
||||
- `scripts/test-gpu.sh` and existing CPU/GPU benchmark workload implementations
|
||||
- Guest execution authorization and trusted-fixture policy
|
||||
|
||||
Shared Cargo configuration, production CI workflows and `CHANGELOG.md` require
|
||||
an explicit per-change coordination note even when a QA issue mentions them.
|
||||
|
||||
## Active claims
|
||||
|
||||
| Issue | Holder | Paths | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| #180 | ranveersoni98 | `tests/agent_queue/`, `docs/coordination/` | Live smoke evidence; no production workflow edits |
|
||||
| #277 | held until #180 releases coordination docs | `scripts/qa/`, `tests/qa/`, `scripts/release/`, `tests/release/`, `docs/testing/infrastructure/` | Maintainer-approved new paths; depends on #180 |
|
||||
|
||||
## Approved new paths (not yet exclusively held)
|
||||
|
||||
Maintainer-approved for the infrastructure/QA campaign once claimed without
|
||||
overlapping an active issue:
|
||||
|
||||
| Path | Intended workstream |
|
||||
| --- | --- |
|
||||
| `scripts/qa/` | Advisory PR verification, test orchestration, env diagnostics |
|
||||
| `tests/qa/` | Independent tests for `scripts/qa/` |
|
||||
| `scripts/release/` | Native Mach-O, SBOM, checksum and release-evidence tools |
|
||||
| `tests/release/` | Independent tests for `scripts/release/` |
|
||||
| `docs/testing/infrastructure/` | Tooling docs; not product GPU/CPU protocol docs |
|
||||
|
||||
## Existing scripts to extend or wrap, not duplicate
|
||||
|
||||
| Existing path | Relation |
|
||||
| --- | --- |
|
||||
| `scripts/agent_queue/` | Owned by the merged queue (#165); #180 smoke-tests only |
|
||||
| `scripts/audit/native.sh` | ARM64 and linkage gate; release tools may consume its outputs |
|
||||
| `scripts/audit/claims.sh`, `dependencies.sh`, `status.py`, `test_inventory.py` | Prefer calling or summarizing; do not reimplement |
|
||||
| `scripts/benchmark.sh` | Analysis tools consume results only; do not change workloads |
|
||||
|
||||
## Disposable remote testing
|
||||
|
||||
Live agent-queue Actions exercises run only in the maintainer-approved private
|
||||
repository `ranveersoni98/xenora-agent-queue-smoke`. Do not enable blocking
|
||||
production checks until that smoke evidence is recorded and reviewed.
|
||||
@@ -61,6 +61,22 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `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 |
|
||||
| `s_min_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1 | `830A0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_min_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1 | `83988509` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_max_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1 | `84170908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_max_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1 | `848C0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cselect_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged | `850B0809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bfm_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged | `920D848C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mul_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged | `930F0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bfe_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0 | `9390FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bfe_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] (sign fill) masked to S1[22:16] bits, sign-extended; SCC = D != 0 | `9411FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_absdiff_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = \|S0 - S1\| of the 32-bit difference (0x80000000 stays); SCC = D != 0 | `96120809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl1_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum | `970E0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl2_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum | `97990909` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl3_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum | `98130808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl4_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum | `9894D009` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mul_hi_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged | `9A950808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mul_hi_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged | `9B160808` | 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 |
|
||||
@@ -85,6 +101,18 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0]) | `120402C3` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_hi_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0]) | `14060208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0] | `160802FF 00123456` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_hi_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of S0[23:0] * S1[23:0] | `180A0208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_min_i32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed min(S0, S1) | `220C0501` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_max_i32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed max(S0, S1) | `240E0285` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_min_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned min(S0, S1) | `26100303` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_max_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned max(S0, S1) | `28120208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_xnor_b32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = ~(S0 ^ S1) | `3C140B04` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_add_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 + S1, no carry | `4A160F06` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_sub_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 - S1, no carry | `4C181308` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_subrev_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S1 - S0, no carry | `4E1A170A` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
<!-- status:instructions:end -->
|
||||
|
||||
## Automated three-way comparison
|
||||
|
||||
@@ -8,6 +8,8 @@ Apple documents `uint`, device address space and the scalar compute grid-positio
|
||||
|
||||
The integer emitter uses unsigned addition, bitwise logic, and shifts. Scalar moves and compares are evaluated at translation time using known SGPR initializers. Forward branches must target instruction boundaries. Conditional branches require known scalar condition code (SCC), execution mask (EXEC), or vector condition code (VCC) state. Wave32 zero checks read the low halves of EXEC and VCC. Known partial EXEC masks merge each vector result with the initialized destination according to the logical lane number, computed from the grid index modulo 32. Empty EXEC suppresses vector arithmetic and moves. Reachable vector memory operations require a full mask. The IR records the statically selected path. Scalar values can originate only from constants and initialized SGPRs, and SGPR 0–7 remain reserved for synthetic descriptors. The generated kernel contains only the selected scalar branch path. The partial-mask merge uses a per-invocation selection from two vector values.
|
||||
|
||||
Twelve VOP2 integer forms from the semantic registry lower through one typed template per declared operation (`VectorBinary`), not per opcode: wrapping `uint` add, subtract and XNOR; `min`/`max` on `uint`, or on `as_type<int>` for the signed forms; and the 24-bit multiplies, which first sign-extend bit 23 with `as_type<int>(x << 8u) >> 8` (or mask to 24 bits for the unsigned forms), then take the low word as a wrapping `uint` product or the high word with MSL `mulhi`. `v_subrev_nc_u32` declares reversed sources, so the translator swaps them. A wave-uniform SRC0 (an SGPR, inline integer or literal) becomes a constant operand, while the lane's VGPRs stay runtime values; `vcc_lo` as SRC0 uses the lane-derived compare mask when a VOPC produced it. These forms are refused inside code skipped by a runtime `s_cbranch_vccz`, as both interpreters refuse them.
|
||||
|
||||
The float subset accepts addition and multiplication only when every possible operand is a positive normal binary32 value and the exact result is itself representable as a normal binary32 value. A known-bit analysis propagates the effect of masks and XOR. It enumerates up to two candidate bit patterns per operand, proves the result for each pair, and retains at most two unique results for an ensuing operation. No rounding mode, signed-zero behavior, subnormal mode, NaN handling or infinity policy is required for this restricted domain. Unknown or inexact cases fail verification.
|
||||
|
||||
The generated MSL uses unsigned words for register bits and `as_type` for reinterpretation at individual float operations. It disables contraction and reassociation for these kernels. The compiler tests compare all three fixture outputs against tracked IR and MSL goldens. The [native demonstration](../../scripts/demo.sh) checks executed results.
|
||||
@@ -8,12 +8,14 @@
|
||||
| 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. |
|
||||
| SOP2 `S_MIN_{I32,U32}`, `S_MAX_{I32,U32}`, `S_CSELECT_B32`, `S_BFM_B32`, `S_MUL_I32`, `S_MUL_HI_{U32,I32}`, `S_BFE_{U32,I32}`, `S_ABSDIFF_I32`, `S_LSHL{1,2,3,4}_ADD_U32` | The guide's section 12.1 result, computed exactly and reduced modulo 2^32. Min and max compare strictly (a tie gives S1, SCC = 0); CSELECT reads SCC and refuses it unset; BFM, MUL, MUL_HI and CSELECT leave SCC unchanged; BFE uses offset S1[4:0] and width S1[22:16] (32 or more keeps every shifted bit); ABSDIFF negates the wrapped difference; LSHLn_ADD sets SCC to the carry of the exact sum. 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. |
|
||||
| VOP2 `V_MUL_{I32_I24,HI_I32_I24,U32_U24,HI_U32_U24}`, `V_MIN_{I32,U32}`, `V_MAX_{I32,U32}`, `V_XNOR_B32`, `V_ADD_NC_U32`, `V_SUB_NC_U32`, `V_SUBREV_NC_U32` | The guide's section 12.7 result per active lane, computed exactly: the 24-bit multiplies use S0[23:0] and S1[23:0] (sign-extended for I24) and keep bits 31:0 or 63:32; SUBREV gives S1 - S0. SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline integer or a literal. Inactive lanes keep VDST; no SCC or VCC write. |
|
||||
| VOP2 `V_ADD_F32`, `V_MUL_F32` | Require exact binary32 results by checking the inputs and the wider intermediate. Multiplication of the significands fits in binary64. Addition must also recover the smaller operand by subtracting the larger. |
|
||||
| SOPP `S_ENDPGM` | Stop at the end of the byte stream. The synthetic contract requires explicitly completed transfers and a produced output first (CLAIM-RDNA2-TRANSFER-WAITS). |
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# SOP2 scalar ALU subset
|
||||
|
||||
Xenora decodes and executes seventeen gfx1030 SOP2 forms. Each takes 32-bit
|
||||
operands, writes a normal SGPR (s0-s105) and sets SCC.
|
||||
Xenora decodes and executes thirty-three gfx1030 SOP2 forms. Each takes 32-bit
|
||||
operands and writes a normal SGPR (s0-s105). The seventeen below set SCC; the
|
||||
sixteen in [Arithmetic, select and bit-field forms](#arithmetic-select-and-bit-field-forms)
|
||||
set it or leave it as the guide says.
|
||||
|
||||
| Form | D | SCC |
|
||||
| --- | --- | --- |
|
||||
@@ -68,11 +70,11 @@ the registry.
|
||||
|
||||
## Not supported
|
||||
|
||||
- Every other SOP2 form, including the 64-bit bitwise forms.
|
||||
- Every other SOP2 form, including the 64-bit bitwise forms and `s_cselect_b64`.
|
||||
- Destinations other than s0-s105 (VCC, EXEC, TTMP and M0).
|
||||
- Sources other than normal SGPRs, inline integers and one literal.
|
||||
- Both sources selecting a literal.
|
||||
- ADDC or SUBB before SCC is set.
|
||||
- ADDC, SUBB or CSELECT before SCC is set.
|
||||
- Writes to the fixture's resource descriptors s0-s7.
|
||||
|
||||
## How it runs
|
||||
@@ -119,6 +121,45 @@ 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.
|
||||
|
||||
## Arithmetic, select and bit-field forms
|
||||
|
||||
Sixteen more 32-bit SOP2 forms are declared in the registry with the same
|
||||
operand rule (`sop2_sgpr`), each one TOML entry over a shared primitive:
|
||||
|
||||
| Form | D | SCC |
|
||||
| --- | --- | --- |
|
||||
| `s_min_i32`, `s_min_u32` | S0 if S0 < S1 (signed or unsigned), else S1 | S0 < S1 |
|
||||
| `s_max_i32`, `s_max_u32` | S0 if S0 > S1, else S1 | S0 > S1 |
|
||||
| `s_cselect_b32` | SCC ? S0 : S1 | read, not written |
|
||||
| `s_bfm_b32` | ((1 << S0[4:0]) - 1) << S1[4:0] | unchanged |
|
||||
| `s_mul_i32` | low 32 bits of S0 * S1 | unchanged |
|
||||
| `s_mul_hi_u32`, `s_mul_hi_i32` | high 32 bits of the unsigned or signed 64-bit product | unchanged |
|
||||
| `s_bfe_u32` | (S0 >> S1[4:0]) masked to S1[22:16] bits | D != 0 |
|
||||
| `s_bfe_i32` | (S0 >> S1[4:0], sign fill) masked to S1[22:16] bits, sign-extended from the field's top bit | D != 0 |
|
||||
| `s_absdiff_i32` | \|S0 - S1\| of the wrapped 32-bit difference (0x80000000 stays) | D != 0 |
|
||||
| `s_lshl1_add_u32` to `s_lshl4_add_u32` | (S0 << N) + S1, N = 1 to 4 | carry out of the exact sum, counting bits shifted out of S0 |
|
||||
|
||||
These follow the guide's 12.1 pseudocode and Tables 11, 12 and 14 (pages
|
||||
34-36). Min and max compare strictly, so equal operands give S1 and SCC = 0.
|
||||
The guide leaves two C-like operators open; Xenora reads them as exact
|
||||
arithmetic: a BFE width of 32 to 127 keeps every shifted bit, and a width of 0
|
||||
gives 0. These are guide readings, not hardware evidence. CSELECT is refused
|
||||
when SCC has not been set, as ADDC and SUBB are.
|
||||
|
||||
The registry gained the vocabulary for them: the operations above, a
|
||||
`selected_src0` SCC effect for min and max, `carry_in = "scc"` for the select
|
||||
condition, and a declared `shift_amount` (1 to 4) for the shift-and-add forms.
|
||||
The generated `ScalarAluOp::evaluate` now returns `(u32, Option<bool>)`, with
|
||||
`None` for forms that leave SCC unchanged.
|
||||
|
||||
`tests/validation/tests/sop2_arith.rs` checks 21,070 cases, with expected values
|
||||
derived from the guide (including its ABSDIFF examples) separately from the
|
||||
registry, on both CPU interpreters and, through the translator, on native
|
||||
Metal; its 597 rejected programs are checked on the CPU interpreters and the
|
||||
compiler. `fixtures/rdna2/scalar-arith.s` (LLVM-assembled, expected input ^
|
||||
0x81157dfe) chains all sixteen, including a min tie and CSELECT on both SCC
|
||||
values, and shows SCC surviving the forms that do not write it.
|
||||
|
||||
## SOPC compares
|
||||
|
||||
The twelve 32-bit SOPC integer compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`
|
||||
|
||||
@@ -25,18 +25,18 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
|
||||
| SOP2 | 51 | 17 | 17 | 17 | 17 | 17 | 0 | 0 | 12 |
|
||||
| SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 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 |
|
||||
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP2 | 47 | 8 | 0 | 8 | 8 | 8 | 7 | 7 | 0 |
|
||||
| VOP2 | 47 | 20 | 12 | 20 | 20 | 20 | 7 | 7 | 7 |
|
||||
| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
|
||||
| **Total** | 1465 | 72 | 40 | 76 | 72 | 72 | 18 | 18 | 30 |
|
||||
| **Total** | 1465 | 100 | 68 | 104 | 100 | 100 | 18 | 18 | 37 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
@@ -47,3 +47,4 @@ The table counts distinct variant names per family across registry operand rules
|
||||
| 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` |
|
||||
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
@@ -51,14 +51,16 @@ 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`, `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`) |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `compare` and the SOP1 unaries |
|
||||
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
|
||||
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
|
||||
| `width` | Operand and result width in bits | `32` |
|
||||
| `source_bits` | Sign extension only: the low bits of S0 that are read. The XML must list S0 with that size and format (`FMT_NUM_I8` or `FMT_NUM_I16`) | `8`, `16`; required for `sext`, rejected elsewhere |
|
||||
| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere |
|
||||
| `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` |
|
||||
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
|
||||
| `shift_count_bits` | Shifts only: the low bits of S1 used as the count. The generator masks S1 with it, and the XML must list S1 as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (compares only), `unchanged` |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
|
||||
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` |
|
||||
| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) |
|
||||
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
|
||||
@@ -82,8 +84,27 @@ fixes the `scc` value:
|
||||
| `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 |
|
||||
| `min`, `max` / `signed` or `unsigned` | `selected_src0` | `min_i32`/`min_u32`, `max_i32`/`max_u32` | no |
|
||||
| `cselect` / `bitwise` | `unchanged` | `cselect_b32` | required |
|
||||
| `bfm` / `bitwise` | `unchanged` | `bfm_b32` | no |
|
||||
| `mul` / `signed` | `unchanged` | `mul_lo_i32` | no |
|
||||
| `mul_hi` / `unsigned` or `signed` | `unchanged` | `mul_hi_u32`, `mul_hi_i32` | no |
|
||||
| `bfe` / `unsigned` or `signed` | `nonzero` | `bfe_nonzero_u32`, `bfe_nonzero_i32` | no |
|
||||
| `absdiff` / `signed` | `nonzero` | `absdiff_nonzero_i32` | no |
|
||||
| `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no |
|
||||
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
|
||||
|
||||
Vector forms (operand rule `vop2_vgpr`, kind `vector`) use a separate table:
|
||||
the pair picks the per-lane `VectorBinary` the MSL lowering uses, and `scc`
|
||||
must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
|
||||
|
||||
| `operation` / `signedness` | `VectorBinary` |
|
||||
| --- | --- |
|
||||
| `add` / `unsigned`, `sub` / `unsigned` | `Add`, `Sub` |
|
||||
| `xnor` / `bitwise` | `Xnor` |
|
||||
| `min`, `max` / `signed` or `unsigned` | `MinSigned`, `MinUnsigned`, `MaxSigned`, `MaxUnsigned` |
|
||||
| `mul24`, `mul_hi24` / `signed` or `unsigned` | `Mul24Signed`, `Mul24Unsigned`, `MulHi24Signed`, `MulHi24Unsigned` |
|
||||
|
||||
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
|
||||
@@ -98,12 +119,13 @@ vocabularies above, it rejects:
|
||||
|
||||
- contradictions: a declared `scc` or `carry_in` that the primitive does not
|
||||
have, `bitwise` on an arithmetic operation or the reverse;
|
||||
- duplicates: the same `name`, the same `(family, opcode)` or the same
|
||||
`variant` declared twice;
|
||||
- duplicates: the same `name`, the same `(family, opcode)`, or the same
|
||||
`variant` twice in one generated enum;
|
||||
- XML disagreements: a family with no XML encoding, a form with no default XML
|
||||
variant, a different opcode, an SCC input or output the XML does not show (or
|
||||
that the declaration omits), an operand width other than `width`, a signed
|
||||
declaration on unsigned XML formats or the reverse, an operand direction that
|
||||
declaration on unsigned XML formats or the reverse (a shift count or the `bfe`
|
||||
field descriptor in S1 must be `FMT_NUM_U32` whatever the signedness), an operand direction that
|
||||
differs, and XML operands the operand rule does not cover;
|
||||
- references: a spec citing an undeclared document, a bad section or page, or
|
||||
no guide page at all;
|
||||
|
||||
@@ -127,8 +127,11 @@ While VCC_LO is lane-derived it may be read only by:
|
||||
lanes (inactive lanes keep vD, as for any partial-EXEC move);
|
||||
3. SRC0 of a supported compare (`v_cmp_* vcc_lo, vcc_lo, vN`), which reads the
|
||||
old VCC_LO in every active lane before the new value is written.
|
||||
4. SRC0 of a registry VOP2 integer form (for example
|
||||
`v_add_nc_u32_e32 vD, vcc_lo, vN`), which reads the 32-bit mask in every
|
||||
active lane, as `v_mov_b32_e32` does.
|
||||
|
||||
`v_mov_b32_e32 vD, vcc_lo` follows the usual EXEC rules: with EXEC_LO = 0 it
|
||||
`v_mov_b32_e32 vD, vcc_lo` and the VOP2 forms follow the usual EXEC rules: with EXEC_LO = 0 it
|
||||
is skipped without reading VCC; otherwise VCC_LO must be known or
|
||||
lane-derived. Every other read of vcc_lo is rejected in any state: the
|
||||
supported scalar instructions (`s_mov_b32`, SOP2, `s_cmp_eq_u32`) do not
|
||||
|
||||
@@ -615,6 +615,198 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_min_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1"
|
||||
representation = "`830A0908`"
|
||||
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_min_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1"
|
||||
representation = "`83988509`"
|
||||
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_max_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1"
|
||||
representation = "`84170908`"
|
||||
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_max_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1"
|
||||
representation = "`848C0908`"
|
||||
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_cselect_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged"
|
||||
representation = "`850B0809`"
|
||||
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_bfm_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged"
|
||||
representation = "`920D848C`"
|
||||
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_mul_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged"
|
||||
representation = "`930F0908`"
|
||||
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_bfe_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0"
|
||||
representation = "`9390FF08 00080004`"
|
||||
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_bfe_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) masked to S1[22:16] bits, sign-extended; SCC = D != 0"
|
||||
representation = "`9411FF08 00080004`"
|
||||
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_absdiff_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = |S0 - S1| of the 32-bit difference (0x80000000 stays); SCC = D != 0"
|
||||
representation = "`96120809`"
|
||||
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_lshl1_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`970E0908`"
|
||||
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_lshl2_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`97990909`"
|
||||
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_lshl3_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`98130808`"
|
||||
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_lshl4_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`9894D009`"
|
||||
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_mul_hi_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged"
|
||||
representation = "`9A950808`"
|
||||
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_mul_hi_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged"
|
||||
representation = "`9B160808`"
|
||||
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"
|
||||
@@ -902,6 +1094,150 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_mul_i32_i24_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0])"
|
||||
representation = "`120402C3`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_mul_hi_i32_i24_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0])"
|
||||
representation = "`14060208`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_mul_u32_u24_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0]"
|
||||
representation = "`160802FF 00123456`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_mul_hi_u32_u24_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of S0[23:0] * S1[23:0]"
|
||||
representation = "`180A0208`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_min_i32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed min(S0, S1)"
|
||||
representation = "`220C0501`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_max_i32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed max(S0, S1)"
|
||||
representation = "`240E0285`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_min_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned min(S0, S1)"
|
||||
representation = "`26100303`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_max_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned max(S0, S1)"
|
||||
representation = "`28120208`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_xnor_b32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = ~(S0 ^ S1)"
|
||||
representation = "`3C140B04`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_add_nc_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 + S1, no carry"
|
||||
representation = "`4A160F06`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_sub_nc_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 - S1, no carry"
|
||||
representation = "`4C181308`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
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_subrev_nc_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S1 - S0, no carry"
|
||||
representation = "`4E1A170A`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[guest_milestones]
|
||||
X1 = "accepted"
|
||||
X2 = "accepted"
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# Infrastructure QA tooling
|
||||
|
||||
Standalone helpers under `scripts/qa/` and `scripts/release/`. They do not replace
|
||||
`scripts/audit/*`, `scripts/benchmark.sh` or `scripts/test-gpu.sh`. New checks are
|
||||
advisory until reviewed.
|
||||
|
||||
## Suites
|
||||
|
||||
| Path | Role |
|
||||
| --- | --- |
|
||||
| `scripts/qa/exit_pipe.py` | Preserve command exit status |
|
||||
| `scripts/qa/orchestrate.py` | Structured multi-suite runs and failure excerpts |
|
||||
| `scripts/qa/pr_validate.py` | Advisory PR scope, DCO, artifact and evidence checks |
|
||||
| `scripts/qa/bench_stats.py` | Median/percentile analysis of existing samples |
|
||||
| `scripts/qa/regression.py` | Compare historical orchestration JSON reports |
|
||||
| `scripts/qa/env_check.py` | Host, toolchain and branch diagnostics |
|
||||
| `scripts/qa/claim_conflict.py` | Read-only file-scope conflict prediction |
|
||||
| `scripts/release/macho.py` | ARM64 arch and forbidden-linkage checks |
|
||||
| `scripts/release/bundle.py` | App bundle layout and codesign diagnosis |
|
||||
| `scripts/release/manifest.py` | Checksums, manifests, license inventory |
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/qa
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/release
|
||||
```
|
||||
@@ -0,0 +1,39 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0068: branch.uniform 0x0074 taken=true
|
||||
0074: t2 = const.u32 0x89abcdef
|
||||
0078: t3 = const.u32 0x00000005
|
||||
007c: t4 = xor.b32 t2, t3
|
||||
0080: t5 = const.u32 0x89abcdef
|
||||
0084: t6 = xor.b32 t4, t5
|
||||
0088: t7 = const.u32 0x0000fff0
|
||||
008c: t8 = xor.b32 t6, t7
|
||||
0090: t9 = const.u32 0x13579be3
|
||||
0094: t10 = xor.b32 t8, t9
|
||||
0098: t11 = const.u32 0xb05b05ab
|
||||
009c: t12 = xor.b32 t10, t11
|
||||
00a0: t13 = const.u32 0x000000de
|
||||
00a4: t14 = xor.b32 t12, t13
|
||||
00a8: t15 = const.u32 0xffffffde
|
||||
00ac: t16 = xor.b32 t14, t15
|
||||
00b0: t17 = const.u32 0x76543216
|
||||
00b4: t18 = xor.b32 t16, t17
|
||||
00b8: t19 = const.u32 0xd70a3d67
|
||||
00bc: t20 = xor.b32 t18, t19
|
||||
00c0: t21 = const.u32 0x00000040
|
||||
00c4: t22 = xor.b32 t20, t21
|
||||
00c8: t23 = const.u32 0x4a0955b6
|
||||
00cc: t24 = xor.b32 t22, t23
|
||||
00d0: t25 = const.u32 0x36b1b9d8
|
||||
00d4: t26 = xor.b32 t24, t25
|
||||
00d8: t27 = const.u32 0x00000005
|
||||
00dc: t28 = xor.b32 t26, t27
|
||||
00e0: t29 = const.u32 0x00000005
|
||||
00e4: t30 = xor.b32 t28, t29
|
||||
00e8: t31 = const.u32 0x00000019
|
||||
00ec: t32 = xor.b32 t30, t31
|
||||
00f0: t33 = const.u32 0x00000005
|
||||
00f4: t34 = xor.b32 t32, t33
|
||||
00f8: t35 = const.u32 0x00000000
|
||||
00fc: t36 = xor.b32 t34, t35
|
||||
0100: t37 = xor.b32 t0, t36
|
||||
0104: store.u32 output[index], t37
|
||||
@@ -0,0 +1,45 @@
|
||||
#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 = 0x89abcdefu;
|
||||
uint t3 = 0x00000005u;
|
||||
uint t4 = t2 ^ t3;
|
||||
uint t5 = 0x89abcdefu;
|
||||
uint t6 = t4 ^ t5;
|
||||
uint t7 = 0x0000fff0u;
|
||||
uint t8 = t6 ^ t7;
|
||||
uint t9 = 0x13579be3u;
|
||||
uint t10 = t8 ^ t9;
|
||||
uint t11 = 0xb05b05abu;
|
||||
uint t12 = t10 ^ t11;
|
||||
uint t13 = 0x000000deu;
|
||||
uint t14 = t12 ^ t13;
|
||||
uint t15 = 0xffffffdeu;
|
||||
uint t16 = t14 ^ t15;
|
||||
uint t17 = 0x76543216u;
|
||||
uint t18 = t16 ^ t17;
|
||||
uint t19 = 0xd70a3d67u;
|
||||
uint t20 = t18 ^ t19;
|
||||
uint t21 = 0x00000040u;
|
||||
uint t22 = t20 ^ t21;
|
||||
uint t23 = 0x4a0955b6u;
|
||||
uint t24 = t22 ^ t23;
|
||||
uint t25 = 0x36b1b9d8u;
|
||||
uint t26 = t24 ^ t25;
|
||||
uint t27 = 0x00000005u;
|
||||
uint t28 = t26 ^ t27;
|
||||
uint t29 = 0x00000005u;
|
||||
uint t30 = t28 ^ t29;
|
||||
uint t31 = 0x00000019u;
|
||||
uint t32 = t30 ^ t31;
|
||||
uint t33 = 0x00000005u;
|
||||
uint t34 = t32 ^ t33;
|
||||
uint t35 = 0x00000000u;
|
||||
uint t36 = t34 ^ t35;
|
||||
uint t37 = t0 ^ t36;
|
||||
output[index] = t37;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
0000: t0 = load.u32 input[index]
|
||||
0014: t1 = const.u32 0xfffffffd
|
||||
0014: t2 = mul24.i32 t1, t0
|
||||
0018: t3 = const.u32 0x00800001
|
||||
0018: t4 = mulhi24.i32 t3, t0
|
||||
001c: t5 = const.u32 0x00123456
|
||||
001c: t6 = mul24.u32 t5, t0
|
||||
0024: t7 = const.u32 0x00800001
|
||||
0024: t8 = mulhi24.u32 t7, t0
|
||||
0028: t9 = min.i32 t0, t2
|
||||
002c: t10 = const.u32 0x00000005
|
||||
002c: t11 = max.i32 t10, t0
|
||||
0030: t12 = min.u32 t4, t0
|
||||
0034: t13 = const.u32 0x00800001
|
||||
0034: t14 = max.u32 t13, t0
|
||||
0038: t15 = xnor.b32 t6, t8
|
||||
003c: t16 = add.u32 t9, t11
|
||||
0040: t17 = sub.u32 t12, t14
|
||||
0044: t18 = sub.u32 t16, t15
|
||||
0048: t19 = xor.b32 t2, t4
|
||||
004c: t20 = xor.b32 t6, t19
|
||||
0050: t21 = xor.b32 t8, t20
|
||||
0054: t22 = xor.b32 t9, t21
|
||||
0058: t23 = xor.b32 t11, t22
|
||||
005c: t24 = xor.b32 t12, t23
|
||||
0060: t25 = xor.b32 t14, t24
|
||||
0064: t26 = xor.b32 t15, t25
|
||||
0068: t27 = xor.b32 t16, t26
|
||||
006c: t28 = xor.b32 t17, t27
|
||||
0070: t29 = xor.b32 t18, t28
|
||||
0074: store.u32 output[index], t29
|
||||
@@ -0,0 +1,38 @@
|
||||
#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 t1 = 0xfffffffdu;
|
||||
uint t2 = as_type<uint>((as_type<int>(t1 << 8u) >> 8)) * as_type<uint>((as_type<int>(t0 << 8u) >> 8));
|
||||
uint t3 = 0x00800001u;
|
||||
uint t4 = as_type<uint>(mulhi((as_type<int>(t3 << 8u) >> 8), (as_type<int>(t0 << 8u) >> 8)));
|
||||
uint t5 = 0x00123456u;
|
||||
uint t6 = (t5 & 0x00ffffffu) * (t0 & 0x00ffffffu);
|
||||
uint t7 = 0x00800001u;
|
||||
uint t8 = mulhi((t7 & 0x00ffffffu), (t0 & 0x00ffffffu));
|
||||
uint t9 = as_type<uint>(min(as_type<int>(t0), as_type<int>(t2)));
|
||||
uint t10 = 0x00000005u;
|
||||
uint t11 = as_type<uint>(max(as_type<int>(t10), as_type<int>(t0)));
|
||||
uint t12 = min(t4, t0);
|
||||
uint t13 = 0x00800001u;
|
||||
uint t14 = max(t13, t0);
|
||||
uint t15 = ~(t6 ^ t8);
|
||||
uint t16 = t9 + t11;
|
||||
uint t17 = t12 - t14;
|
||||
uint t18 = t16 - t15;
|
||||
uint t19 = t2 ^ t4;
|
||||
uint t20 = t6 ^ t19;
|
||||
uint t21 = t8 ^ t20;
|
||||
uint t22 = t9 ^ t21;
|
||||
uint t23 = t11 ^ t22;
|
||||
uint t24 = t12 ^ t23;
|
||||
uint t25 = t14 ^ t24;
|
||||
uint t26 = t15 ^ t25;
|
||||
uint t27 = t16 ^ t26;
|
||||
uint t28 = t17 ^ t27;
|
||||
uint t29 = t18 ^ t28;
|
||||
output[index] = t29;
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,69 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Generate the original PE32+ frame-loop fixture without an x86 toolchain.
|
||||
|
||||
The guest calls xenora.dll!frame_submit(index) with index = 0, 1, 2, ... and
|
||||
stops when the import returns 0, then halts. Frame order is guest state (RBX).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from struct import pack, pack_into
|
||||
|
||||
|
||||
def fixture():
|
||||
base = 0x140000000
|
||||
entry, imports = 0x1000, 0x2000
|
||||
iat, lookup, module, symbol = (imports + x for x in (0x40, 0x50, 0x60, 0x80))
|
||||
|
||||
data = bytearray(0x800)
|
||||
data[:2] = b"MZ"
|
||||
pack_into("<I", data, 0x3C, 0x80)
|
||||
data[0x80:0x84] = b"PE\0\0"
|
||||
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
|
||||
opt = 0x98
|
||||
pack_into("<H", data, opt, 0x20B)
|
||||
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
|
||||
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
|
||||
pack_into("<II", data, opt + 56, 0x3000, 0x400)
|
||||
pack_into("<HH", data, opt + 68, 3, 0x160)
|
||||
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
|
||||
for index, rva, size in ((1, imports, 40), (12, iat, 16)):
|
||||
pack_into("<II", data, opt + 112 + index * 8, rva, size)
|
||||
|
||||
for index, (name, rva, permissions) in enumerate(
|
||||
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
|
||||
):
|
||||
pack_into(
|
||||
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
|
||||
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
|
||||
)
|
||||
|
||||
loop = entry + 6
|
||||
code = b"\x48\x83\xec\x28" # sub rsp, 0x28 (Win64 home area)
|
||||
code += b"\x31\xdb" # xor ebx, ebx (frame index)
|
||||
code += b"\x48\x89\xd9" # loop: mov rcx, rbx
|
||||
code += b"\xff\x15" + pack("<i", iat - (loop + 9)) # call [rip -> IAT]
|
||||
code += b"\x48\xff\xc3" # inc rbx
|
||||
code += b"\x48\x85\xc0" # test rax, rax
|
||||
code += b"\x75" + pack("<b", loop - (loop + 17)) # jnz loop
|
||||
code += b"\x48\x83\xc4\x28\xf4" # add rsp, 0x28; hlt
|
||||
data[0x400:0x400 + len(code)] = code
|
||||
|
||||
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
|
||||
pack_into("<Q", data, 0x640, symbol)
|
||||
pack_into("<Q", data, 0x650, symbol)
|
||||
data[0x660:0x66B] = b"xenora.dll\0"
|
||||
data[0x682:0x68E] = b"frame_submit"
|
||||
return data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
path = Path(__file__).with_suffix(".exe")
|
||||
if args.check:
|
||||
if path.read_bytes() != fixture():
|
||||
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
|
||||
else:
|
||||
path.write_bytes(fixture())
|
||||
Binary file not shown.
@@ -0,0 +1,100 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Generate the original PE32+ interactive fixture without an x86 toolchain.
|
||||
|
||||
The guest polls host input via xenora.dll!input_poll() and updates its
|
||||
internal position:
|
||||
- input 1 (Right): column = (column + 1) % 4
|
||||
- input 2 (Left): column = (column - 1) % 4
|
||||
- other: column stays unchanged
|
||||
|
||||
The guest then calls xenora.dll!frame_submit(column) and stops when the
|
||||
import returns 0, then halts.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from struct import pack, pack_into
|
||||
|
||||
|
||||
def fixture():
|
||||
base = 0x140000000
|
||||
entry, imports = 0x1000, 0x2000
|
||||
lookup = imports + 0x30
|
||||
iat = imports + 0x50
|
||||
module = imports + 0x70
|
||||
sym_poll = imports + 0x80
|
||||
sym_submit = imports + 0x90
|
||||
|
||||
data = bytearray(0x800)
|
||||
data[:2] = b"MZ"
|
||||
pack_into("<I", data, 0x3C, 0x80)
|
||||
data[0x80:0x84] = b"PE\0\0"
|
||||
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
|
||||
opt = 0x98
|
||||
pack_into("<H", data, opt, 0x20B)
|
||||
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
|
||||
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
|
||||
pack_into("<II", data, opt + 56, 0x3000, 0x400)
|
||||
pack_into("<HH", data, opt + 68, 3, 0x160)
|
||||
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
|
||||
for index, rva, size in ((1, imports, 40), (12, iat, 24)):
|
||||
pack_into("<II", data, opt + 112 + index * 8, rva, size)
|
||||
|
||||
for index, (name, rva, permissions) in enumerate(
|
||||
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
|
||||
):
|
||||
pack_into(
|
||||
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
|
||||
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
|
||||
)
|
||||
|
||||
code = bytearray()
|
||||
code += b"\x48\x83\xec\x28" # sub rsp, 0x28
|
||||
code += b"\x48\x31\xdb" # xor rbx, rbx (column: 0)
|
||||
|
||||
loop_start = entry + len(code)
|
||||
# call [rip -> iat[0]: input_poll]
|
||||
code += b"\xff\x15" + pack("<i", iat - (entry + len(code) + 6))
|
||||
|
||||
# cmp rax, 1; jne not_right; add rbx, 1
|
||||
code += b"\x48\x83\xf8\x01\x75\x04\x48\x83\xc3\x01"
|
||||
# cmp rax, 2; jne not_left; sub rbx, 1
|
||||
code += b"\x48\x83\xf8\x02\x75\x04\x48\x83\xeb\x01"
|
||||
# wrap check: cmp rbx, 4; jl check_min; sub rbx, 4
|
||||
code += b"\x48\x83\xfb\x04\x7c\x04\x48\x83\xeb\x04"
|
||||
# check_min: cmp rbx, 0; jge do_submit; add rbx, 4
|
||||
code += b"\x48\x83\xfb\x00\x7d\x04\x48\x83\xc3\x04"
|
||||
|
||||
# do_submit:
|
||||
code += b"\x48\x89\xd9" # mov rcx, rbx
|
||||
# call [rip -> iat[1]: frame_submit]
|
||||
code += b"\xff\x15" + pack("<i", (iat + 8) - (entry + len(code) + 6))
|
||||
|
||||
code += b"\x48\x85\xc0" # test rax, rax
|
||||
rel_loop = loop_start - (entry + len(code) + 2)
|
||||
code += b"\x75" + pack("<b", rel_loop)
|
||||
|
||||
code += b"\x48\x83\xc4\x28" # add rsp, 0x28
|
||||
code += b"\xf4" # hlt
|
||||
|
||||
data[0x400:0x400 + len(code)] = code
|
||||
|
||||
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
|
||||
pack_into("<QQ", data, 0x600 + (lookup - imports), sym_poll, sym_submit)
|
||||
pack_into("<QQ", data, 0x600 + (iat - imports), sym_poll, sym_submit)
|
||||
data[0x600 + (module - imports):0x600 + (module - imports) + 11] = b"xenora.dll\0"
|
||||
data[0x600 + (sym_poll - imports) + 2:0x600 + (sym_poll - imports) + 2 + 10] = b"input_poll"
|
||||
data[0x600 + (sym_submit - imports) + 2:0x600 + (sym_submit - imports) + 2 + 12] = b"frame_submit"
|
||||
return data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
path = Path(__file__).with_suffix(".exe")
|
||||
if args.check:
|
||||
if path.read_bytes() != fixture():
|
||||
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
|
||||
else:
|
||||
path.write_bytes(fixture())
|
||||
Binary file not shown.
@@ -0,0 +1,77 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original SOP2 vectors for the registry-declared arithmetic, select and
|
||||
// bit-field forms: signed and unsigned min/max (including a tie, which gives S1
|
||||
// and SCC = 0), select on both SCC values, bit-field mask, low and high
|
||||
// multiplies, both bit-field extracts, absolute difference and the four
|
||||
// shift-and-add forms. BFM, MUL, MUL_HI and CSELECT leave SCC unchanged; the
|
||||
// last SCC writer (LSHL2_ADD, no carry) clears it for the s_cbranch_scc0.
|
||||
// Values from the guide's 12.1 pseudocode, with s8 = 0x89abcdef (negative as
|
||||
// i32) and s9 = 5.
|
||||
// Expected: input ^ 0x81157dfe (the XOR of s10-s27 below).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, 0x89abcdef
|
||||
s_mov_b32 s9, 5
|
||||
s_min_i32 s10, s8, s9 // s10 = 0x89abcdef, SCC = 1 (S0 < S1 signed)
|
||||
s_cselect_b32 s11, s9, s8 // s11 = 5 (SCC = 1 picks S0), SCC unchanged
|
||||
s_max_u32 s12, s8, s9 // s12 = 0x89abcdef, SCC = 1
|
||||
s_bfm_b32 s13, 12, 4 // s13 = 0xfff << 4 = 0xfff0, SCC unchanged
|
||||
s_lshl1_add_u32 s14, s8, s9 // (s8 << 1) + 5 = 0x1_13579be3: s14 = 0x13579be3, SCC = 1
|
||||
s_mul_i32 s15, s8, s9 // 5 * s8 = 0x2_b05b05ab: s15 = 0xb05b05ab
|
||||
s_bfe_u32 s16, s8, 0x80004 // offset 4, width 8: s16 = 0xde, SCC = 1
|
||||
s_bfe_i32 s17, s8, 0x80004 // 0xde sign-extended from bit 7: s17 = 0xffffffde, SCC = 1
|
||||
s_absdiff_i32 s18, s9, s8 // 5 - (-0x76543211) = 0x76543216: s18, SCC = 1
|
||||
s_lshl3_add_u32 s19, s8, s8 // 9 * s8 = 0x4_d70a3d67: s19 = 0xd70a3d67, SCC = 1
|
||||
s_lshl4_add_u32 s20, s9, -16 // 80 + 0xfffffff0 = 0x1_00000040: s20 = 0x40, SCC = 1
|
||||
s_mul_hi_u32 s21, s8, s8 // high word of s8 * s8 (unsigned): s21 = 0x4a0955b6
|
||||
s_mul_hi_i32 s22, s8, s8 // high word of 0x76543211^2: s22 = 0x36b1b9d8
|
||||
s_max_i32 s23, s8, s9 // s23 = 5, SCC = 0 (S0 not greater)
|
||||
s_min_u32 s24, s9, 5 // tie: s24 = 5 (S1), SCC = 0
|
||||
s_lshl2_add_u32 s25, s9, s9 // 20 + 5: s25 = 25, SCC = 0 (no carry)
|
||||
s_cselect_b32 s26, s8, s9 // s26 = 5 (SCC = 0 picks S1), SCC unchanged
|
||||
s_mul_hi_u32 s27, s9, s9 // s27 = 0, SCC unchanged (0)
|
||||
s_cbranch_scc0 .Lzero
|
||||
v_mov_b32_e32 v2, 0
|
||||
s_branch .Ldone
|
||||
.Lzero:
|
||||
v_mov_b32_e32 v2, s10
|
||||
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, s20
|
||||
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_mov_b32_e32 v3, s23
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s24
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s25
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s26
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_mov_b32_e32 v3, s27
|
||||
v_xor_b32_e32 v2, v2, v3
|
||||
v_xor_b32_e32 v2, v1, v2 // v2 = input ^ 0x81157dfe
|
||||
.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,38 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Original VOP2 vectors for the registry-declared per-lane integer forms: the
|
||||
// four 24-bit multiplies, signed and unsigned min/max, XNOR and the three
|
||||
// no-carry add/subtract forms (SUBREV reads its sources reversed). Every result
|
||||
// depends on the lane's own input word x = v1, with SRC0 taken from an inline
|
||||
// constant, a literal, an SGPR or a VGPR. No form writes SCC or VCC.
|
||||
// Expected per lane: v14 = v2 ^ v3 ^ ... ^ v13, worked out from the guide's
|
||||
// 12.7 pseudocode in tests/validation/known_answers.rs (vector_integer_key).
|
||||
.text
|
||||
buffer_load_dword v1, v0, s[0:3], 0 idxen
|
||||
s_waitcnt vmcnt(0)
|
||||
s_mov_b32 s8, 0x800001 // as i24: -0x7fffff
|
||||
v_mul_i32_i24_e32 v2, -3, v1 // v2 = sext24(x) * -3 (low 32 bits)
|
||||
v_mul_hi_i32_i24_e32 v3, s8, v1 // v3 = (-0x7fffff * sext24(x)) >> 32
|
||||
v_mul_u32_u24_e32 v4, 0x123456, v1 // v4 = 0x123456 * x[23:0] (low 32 bits)
|
||||
v_mul_hi_u32_u24_e32 v5, s8, v1 // v5 = (0x800001 * x[23:0]) >> 32
|
||||
v_min_i32_e32 v6, v1, v2 // v6 = signed min(x, v2)
|
||||
v_max_i32_e32 v7, 5, v1 // v7 = signed max(5, x)
|
||||
v_min_u32_e32 v8, v3, v1 // v8 = unsigned min(v3, x)
|
||||
v_max_u32_e32 v9, s8, v1 // v9 = unsigned max(0x800001, x)
|
||||
v_xnor_b32_e32 v10, v4, v5 // v10 = ~(v4 ^ v5)
|
||||
v_add_nc_u32_e32 v11, v6, v7 // v11 = v6 + v7
|
||||
v_sub_nc_u32_e32 v12, v8, v9 // v12 = v8 - v9
|
||||
v_subrev_nc_u32_e32 v13, v10, v11 // v13 = v11 - v10
|
||||
v_xor_b32_e32 v14, v2, v3
|
||||
v_xor_b32_e32 v14, v4, v14
|
||||
v_xor_b32_e32 v14, v5, v14
|
||||
v_xor_b32_e32 v14, v6, v14
|
||||
v_xor_b32_e32 v14, v7, v14
|
||||
v_xor_b32_e32 v14, v8, v14
|
||||
v_xor_b32_e32 v14, v9, v14
|
||||
v_xor_b32_e32 v14, v10, v14
|
||||
v_xor_b32_e32 v14, v11, v14
|
||||
v_xor_b32_e32 v14, v12, v14
|
||||
v_xor_b32_e32 v14, v13, v14
|
||||
buffer_store_dword v14, v0, s[4:7], 0 idxen
|
||||
s_waitcnt_vscnt null, 0
|
||||
s_endpgm
|
||||
@@ -42,6 +42,7 @@ def main(argv):
|
||||
s = sub.add_parser("apply"); s.add_argument("--repo", required=True); s.add_argument("--actions", required=True)
|
||||
s = sub.add_parser("audit"); s.add_argument("--state", required=True)
|
||||
s = sub.add_parser("summary"); s.add_argument("--state", required=True); s.add_argument("--text", action="store_true")
|
||||
s.add_argument("--now", default="", help="UTC time YYYY-MM-DDTHH:MM:SSZ (overrides parent --now)")
|
||||
s = sub.add_parser("pr-check"); s.add_argument("--state", required=True)
|
||||
s = sub.add_parser("acceptance"); s.add_argument("--issue", required=True); s.add_argument("--comments", required=True)
|
||||
s = sub.add_parser("task"); s.add_argument("--issue", required=True)
|
||||
|
||||
@@ -79,12 +79,15 @@ def apply_actions(repo, actions):
|
||||
n = str(a["issue"])
|
||||
for label in a["add_labels"]:
|
||||
gh("label", "create", label, "-R", repo, "--force", "--color", "BFD4F2")
|
||||
args = ["issue", "edit", n, "-R", repo]
|
||||
for l in a["add_labels"]:
|
||||
args += ["--add-label", l]
|
||||
for l in a["remove_labels"]:
|
||||
args += ["--remove-label", l]
|
||||
if len(args) > 4:
|
||||
# Comment-only actions (for example claim refusals) must not call `gh issue edit`:
|
||||
# `["issue", "edit", n, "-R", repo]` is already five tokens, so a length check is not
|
||||
# enough to detect missing label flags and newer gh rejects a no-op edit.
|
||||
if a["add_labels"] or a["remove_labels"]:
|
||||
args = ["issue", "edit", n, "-R", repo]
|
||||
for l in a["add_labels"]:
|
||||
args += ["--add-label", l]
|
||||
for l in a["remove_labels"]:
|
||||
args += ["--remove-label", l]
|
||||
gh(*args)
|
||||
if a["comment"]:
|
||||
gh("issue", "comment", n, "-R", repo, "--body", a["comment"])
|
||||
@@ -12,7 +12,7 @@ case "${1:-}" in
|
||||
esac
|
||||
|
||||
for name in add bitwise-branch float-exact or shifts ashr \
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary; do
|
||||
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith vector-integer; do
|
||||
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
|
||||
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
|
||||
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Standalone infrastructure QA helpers. Advisory until reviewed."""
|
||||
@@ -0,0 +1,122 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Benchmark result analysis over existing measurement samples.
|
||||
|
||||
Consumes numeric samples only. Does not run workloads or invent timings.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import statistics
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import Any, Sequence
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SampleStats:
|
||||
count: int
|
||||
median: float
|
||||
p95: float
|
||||
p99: float
|
||||
mean: float
|
||||
stdev: float
|
||||
iqr: float
|
||||
minimum: float
|
||||
maximum: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RegressionResult:
|
||||
metric: str
|
||||
baseline_median: float
|
||||
current_median: float
|
||||
ratio: float
|
||||
threshold: float
|
||||
regressing: bool
|
||||
|
||||
|
||||
def _percentile(sorted_samples: Sequence[float], pct: float) -> float:
|
||||
if not sorted_samples:
|
||||
raise ValueError("no samples")
|
||||
if pct <= 0:
|
||||
return float(sorted_samples[0])
|
||||
if pct >= 100:
|
||||
return float(sorted_samples[-1])
|
||||
k = (len(sorted_samples) - 1) * (pct / 100.0)
|
||||
f = math.floor(k)
|
||||
c = math.ceil(k)
|
||||
if f == c:
|
||||
return float(sorted_samples[int(k)])
|
||||
d0 = sorted_samples[f] * (c - k)
|
||||
d1 = sorted_samples[c] * (k - f)
|
||||
return float(d0 + d1)
|
||||
|
||||
|
||||
def summarize(samples: Sequence[float]) -> SampleStats:
|
||||
if not samples:
|
||||
raise ValueError("summarize requires at least one sample")
|
||||
ordered = sorted(float(x) for x in samples)
|
||||
q1 = _percentile(ordered, 25)
|
||||
q3 = _percentile(ordered, 75)
|
||||
stdev = statistics.pstdev(ordered) if len(ordered) > 1 else 0.0
|
||||
return SampleStats(
|
||||
count=len(ordered),
|
||||
median=statistics.median(ordered),
|
||||
p95=_percentile(ordered, 95),
|
||||
p99=_percentile(ordered, 99),
|
||||
mean=statistics.fmean(ordered),
|
||||
stdev=stdev,
|
||||
iqr=q3 - q1,
|
||||
minimum=ordered[0],
|
||||
maximum=ordered[-1],
|
||||
)
|
||||
|
||||
|
||||
def compare_medians(
|
||||
baseline: Sequence[float],
|
||||
current: Sequence[float],
|
||||
*,
|
||||
metric: str = "latency",
|
||||
threshold: float = 1.10,
|
||||
) -> RegressionResult:
|
||||
base = summarize(baseline)
|
||||
cur = summarize(current)
|
||||
if base.median <= 0:
|
||||
ratio = math.inf if cur.median > 0 else 1.0
|
||||
else:
|
||||
ratio = cur.median / base.median
|
||||
return RegressionResult(
|
||||
metric=metric,
|
||||
baseline_median=base.median,
|
||||
current_median=cur.median,
|
||||
ratio=ratio,
|
||||
threshold=threshold,
|
||||
regressing=ratio > threshold,
|
||||
)
|
||||
|
||||
|
||||
def export_json(
|
||||
stats: SampleStats,
|
||||
*,
|
||||
host: str,
|
||||
toolchain: str,
|
||||
revision: str,
|
||||
metric: str,
|
||||
) -> str:
|
||||
payload: dict[str, Any] = {
|
||||
"metric": metric,
|
||||
"host": host,
|
||||
"toolchain": toolchain,
|
||||
"revision": revision,
|
||||
"stats": asdict(stats),
|
||||
}
|
||||
return json.dumps(payload, indent=2, sort_keys=True) + "\n"
|
||||
|
||||
|
||||
def human_report(stats: SampleStats, *, metric: str) -> str:
|
||||
return (
|
||||
f"{metric}: n={stats.count} median={stats.median:.6g} "
|
||||
f"p95={stats.p95:.6g} p99={stats.p99:.6g} "
|
||||
f"iqr={stats.iqr:.6g} stdev={stats.stdev:.6g} "
|
||||
f"min={stats.minimum:.6g} max={stats.maximum:.6g}\n"
|
||||
)
|
||||
@@ -0,0 +1,85 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Read-only claim conflict prediction for contributors.
|
||||
|
||||
Wraps the same path-overlap idea used by the agent queue without requiring a
|
||||
network call. Useful before posting /claim or starting edits.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClaimSnapshot:
|
||||
number: int
|
||||
holder: str
|
||||
files: tuple[str, ...]
|
||||
claimed: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ConflictHit:
|
||||
candidate: int
|
||||
held_by: int
|
||||
holder: str
|
||||
pattern_a: str
|
||||
pattern_b: str
|
||||
|
||||
|
||||
def _dir_prefix(pattern: str) -> str | None:
|
||||
if pattern.endswith("/**"):
|
||||
return pattern[:-3].rstrip("/")
|
||||
if pattern.endswith("/"):
|
||||
return pattern.rstrip("/")
|
||||
return None
|
||||
|
||||
|
||||
def patterns_overlap(a: str, b: str) -> bool:
|
||||
if a == b:
|
||||
return True
|
||||
pa, pb = _dir_prefix(a), _dir_prefix(b)
|
||||
if pa is not None and (b == pa or b.startswith(pa + "/") or _dir_prefix(b) == pa):
|
||||
return True
|
||||
if pb is not None and (a == pb or a.startswith(pb + "/") or _dir_prefix(a) == pb):
|
||||
return True
|
||||
# prefix directory without slash: treat trailing path segment containment
|
||||
if a.endswith("/") and (b.startswith(a) or b == a.rstrip("/")):
|
||||
return True
|
||||
if b.endswith("/") and (a.startswith(b) or a == b.rstrip("/")):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def predict_conflicts(candidate_files: Sequence[str], held: Iterable[ClaimSnapshot]) -> tuple[ConflictHit, ...]:
|
||||
hits: list[ConflictHit] = []
|
||||
for claim in held:
|
||||
if not claim.claimed:
|
||||
continue
|
||||
for ca in candidate_files:
|
||||
for hb in claim.files:
|
||||
if patterns_overlap(ca, hb):
|
||||
hits.append(ConflictHit(
|
||||
candidate=-1,
|
||||
held_by=claim.number,
|
||||
holder=claim.holder,
|
||||
pattern_a=ca,
|
||||
pattern_b=hb,
|
||||
))
|
||||
break
|
||||
else:
|
||||
continue
|
||||
break
|
||||
return tuple(hits)
|
||||
|
||||
|
||||
def format_conflicts(hits: Sequence[ConflictHit]) -> str:
|
||||
if not hits:
|
||||
return "no file conflicts predicted\n"
|
||||
lines = ["predicted claim conflicts:", ""]
|
||||
for hit in hits:
|
||||
lines.append(
|
||||
f"- overlaps claimed #{hit.held_by} by {hit.holder}: `{hit.pattern_a}` vs `{hit.pattern_b}`"
|
||||
)
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,87 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Development environment diagnostics for Apple Silicon Xenora contributors."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
@dataclass
|
||||
class EnvFinding:
|
||||
name: str
|
||||
ok: bool
|
||||
detail: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class EnvReport:
|
||||
findings: list[EnvFinding] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def ok(self) -> bool:
|
||||
return all(f.ok for f in self.findings)
|
||||
|
||||
|
||||
def check_uname_machine(machine: str) -> EnvFinding:
|
||||
ok = machine.strip() == "arm64"
|
||||
return EnvFinding("host-arch", ok, f"uname -m => {machine.strip()}" + ("" if ok else " (want arm64)"))
|
||||
|
||||
|
||||
def check_rosetta_translated(proc_translated: str) -> EnvFinding:
|
||||
ok = proc_translated.strip() == "0"
|
||||
return EnvFinding(
|
||||
"rosetta",
|
||||
ok,
|
||||
f"sysctl.proc_translated => {proc_translated.strip()}" + ("" if ok else " (Rosetta translation active)"),
|
||||
)
|
||||
|
||||
|
||||
def check_rustc_host(rustc_vv: str) -> EnvFinding:
|
||||
host = ""
|
||||
for line in rustc_vv.splitlines():
|
||||
if line.startswith("host:"):
|
||||
host = line.split(":", 1)[1].strip()
|
||||
ok = host == "aarch64-apple-darwin"
|
||||
return EnvFinding("rustc-host", ok, f"host={host or 'unknown'}" + ("" if ok else " (want aarch64-apple-darwin)"))
|
||||
|
||||
|
||||
def check_swift_version(swift_version: str) -> EnvFinding:
|
||||
ok = "Swift version" in swift_version
|
||||
return EnvFinding("swift", ok, swift_version.strip().splitlines()[0] if swift_version.strip() else "missing")
|
||||
|
||||
|
||||
_LLVM_RE = re.compile(r"LLVM|clang", re.IGNORECASE)
|
||||
|
||||
|
||||
def check_llvm_tool(which_path: str, version_text: str) -> EnvFinding:
|
||||
if not which_path.strip():
|
||||
return EnvFinding("llvm", False, "tool not found on PATH")
|
||||
ok = bool(_LLVM_RE.search(version_text) or version_text.strip())
|
||||
return EnvFinding("llvm", ok, f"{which_path.strip()}: {version_text.strip().splitlines()[0] if version_text.strip() else 'no version'}")
|
||||
|
||||
|
||||
def check_git_worktree_clean(porcelain: str) -> EnvFinding:
|
||||
ok = porcelain.strip() == ""
|
||||
return EnvFinding("worktree-clean", ok, "clean" if ok else "dirty worktree")
|
||||
|
||||
|
||||
def check_branch_sync(*, ahead: int, behind: int) -> EnvFinding:
|
||||
ok = ahead == 0 and behind == 0
|
||||
detail = f"ahead={ahead} behind={behind}"
|
||||
return EnvFinding("branch-sync", ok, detail)
|
||||
|
||||
|
||||
def summarize(findings: Iterable[EnvFinding]) -> EnvReport:
|
||||
return EnvReport(findings=list(findings))
|
||||
|
||||
|
||||
def format_report(report: EnvReport) -> str:
|
||||
lines = ["# Environment diagnostics", ""]
|
||||
for finding in report.findings:
|
||||
mark = "ok" if finding.ok else "FAIL"
|
||||
lines.append(f"- [{mark}] {finding.name}: {finding.detail}")
|
||||
lines.append("")
|
||||
lines.append("overall: " + ("ok" if report.ok else "problems found"))
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,48 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Run a command and preserve its exit status through pipes.
|
||||
|
||||
Never report success because a later pipe stage (grep, head) succeeded while
|
||||
the measured command failed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PipedResult:
|
||||
command: tuple[str, ...]
|
||||
returncode: int
|
||||
stdout: str
|
||||
stderr: str
|
||||
|
||||
|
||||
def run_preserving_status(
|
||||
command: Sequence[str],
|
||||
*,
|
||||
cwd: str | None = None,
|
||||
timeout: float | None = None,
|
||||
) -> PipedResult:
|
||||
"""Run `command` with check disabled and return its real exit status."""
|
||||
completed = subprocess.run(
|
||||
list(command),
|
||||
cwd=cwd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
return PipedResult(
|
||||
command=tuple(command),
|
||||
returncode=int(completed.returncode),
|
||||
stdout=completed.stdout,
|
||||
stderr=completed.stderr,
|
||||
)
|
||||
|
||||
|
||||
def classify_status(returncode: int) -> str:
|
||||
if returncode == 0:
|
||||
return "passed"
|
||||
return "failed"
|
||||
@@ -0,0 +1,90 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Contributor progress summaries and engineering handoff reports."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkItem:
|
||||
issue: int
|
||||
title: str
|
||||
status: str
|
||||
paths: tuple[str, ...]
|
||||
notes: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HandoffReport:
|
||||
author: str
|
||||
revision: str
|
||||
items: tuple[WorkItem, ...]
|
||||
limitations: tuple[str, ...]
|
||||
|
||||
|
||||
def progress_summary(items: Iterable[WorkItem]) -> str:
|
||||
rows = list(items)
|
||||
lines = ["# Contributor progress", "", f"items: {len(rows)}", ""]
|
||||
for item in rows:
|
||||
paths = ", ".join(f"`{p}`" for p in item.paths) or "(none)"
|
||||
lines.append(f"- #{item.issue} [{item.status}] {item.title} — {paths}")
|
||||
if item.notes:
|
||||
lines.append(f" - {item.notes}")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def handoff_markdown(report: HandoffReport) -> str:
|
||||
lines = [
|
||||
"# Engineering handoff",
|
||||
"",
|
||||
f"- author: `{report.author}`",
|
||||
f"- revision: `{report.revision}`",
|
||||
"",
|
||||
"## Work items",
|
||||
"",
|
||||
]
|
||||
lines.append(progress_summary(report.items).split("\n", 2)[-1].lstrip("\n"))
|
||||
if not report.items:
|
||||
lines.append("(none)")
|
||||
lines.append("")
|
||||
lines.extend(["## Limitations", ""])
|
||||
if report.limitations:
|
||||
for lim in report.limitations:
|
||||
lines.append(f"- {lim}")
|
||||
else:
|
||||
lines.append("- (none recorded)")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def conflict_paths(items: Sequence[WorkItem]) -> tuple[tuple[int, int, str], ...]:
|
||||
"""Return overlapping path pairs between distinct open items."""
|
||||
hits: list[tuple[int, int, str]] = []
|
||||
open_items = [i for i in items if i.status in {"claimed", "in-progress", "open"}]
|
||||
for i, a in enumerate(open_items):
|
||||
for b in open_items[i + 1 :]:
|
||||
for pa in a.paths:
|
||||
for pb in b.paths:
|
||||
if paths_overlap(pa, pb):
|
||||
hits.append((a.issue, b.issue, pa if len(pa) <= len(pb) else pb))
|
||||
return tuple(hits)
|
||||
|
||||
|
||||
def paths_overlap(a: str, b: str) -> bool:
|
||||
a = a.rstrip("/")
|
||||
b = b.rstrip("/")
|
||||
if a == b:
|
||||
return True
|
||||
if a.endswith("/**"):
|
||||
root = a[:-3].rstrip("/")
|
||||
return b == root or b.startswith(root + "/")
|
||||
if b.endswith("/**"):
|
||||
root = b[:-3].rstrip("/")
|
||||
return a == root or a.startswith(root + "/")
|
||||
if a.endswith("/"):
|
||||
return b.startswith(a) or b == a.rstrip("/")
|
||||
if b.endswith("/"):
|
||||
return a.startswith(b) or a == b.rstrip("/")
|
||||
return a.startswith(b + "/") or b.startswith(a + "/")
|
||||
@@ -0,0 +1,172 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Independent test orchestration with structured JSON reports.
|
||||
|
||||
Runs listed commands, records durations and exit codes, and never promotes a
|
||||
failed command to passed because output was filtered.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Sequence
|
||||
|
||||
from .exit_pipe import classify_status, run_preserving_status
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SuiteSpec:
|
||||
name: str
|
||||
command: tuple[str, ...]
|
||||
kind: str = "cpu" # cpu | gpu | other
|
||||
|
||||
|
||||
@dataclass
|
||||
class SuiteResult:
|
||||
name: str
|
||||
kind: str
|
||||
command: list[str]
|
||||
status: str
|
||||
returncode: int
|
||||
duration_seconds: float
|
||||
stdout: str
|
||||
stderr: str
|
||||
reproduction: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class OrchestrationReport:
|
||||
suites: list[SuiteResult] = field(default_factory=list)
|
||||
started_at: float = 0.0
|
||||
finished_at: float = 0.0
|
||||
|
||||
@property
|
||||
def passed(self) -> int:
|
||||
return sum(1 for s in self.suites if s.status == "passed")
|
||||
|
||||
@property
|
||||
def failed(self) -> int:
|
||||
return sum(1 for s in self.suites if s.status == "failed")
|
||||
|
||||
@property
|
||||
def ignored(self) -> int:
|
||||
return sum(1 for s in self.suites if s.status == "ignored")
|
||||
|
||||
@property
|
||||
def unexecuted(self) -> int:
|
||||
return sum(1 for s in self.suites if s.status == "unexecuted")
|
||||
|
||||
def overall_returncode(self) -> int:
|
||||
codes = [s.returncode for s in self.suites if s.status == "failed"]
|
||||
if not codes:
|
||||
return 0
|
||||
return codes[0] if codes[0] != 0 else 1
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"started_at": self.started_at,
|
||||
"finished_at": self.finished_at,
|
||||
"duration_seconds": self.finished_at - self.started_at,
|
||||
"counts": {
|
||||
"passed": self.passed,
|
||||
"failed": self.failed,
|
||||
"ignored": self.ignored,
|
||||
"unexecuted": self.unexecuted,
|
||||
},
|
||||
"suites": [asdict(s) for s in self.suites],
|
||||
"overall_returncode": self.overall_returncode(),
|
||||
}
|
||||
|
||||
|
||||
def shell_quote(part: str) -> str:
|
||||
if part == "":
|
||||
return "''"
|
||||
if all(c.isalnum() or c in "@%_+:=,./-" for c in part):
|
||||
return part
|
||||
return "'" + part.replace("'", "'\"'\"'") + "'"
|
||||
|
||||
|
||||
def run_suites(
|
||||
specs: Sequence[SuiteSpec],
|
||||
*,
|
||||
stop_on_fail: bool = False,
|
||||
) -> OrchestrationReport:
|
||||
report = OrchestrationReport(started_at=time.time())
|
||||
halted = False
|
||||
for spec in specs:
|
||||
if halted:
|
||||
report.suites.append(
|
||||
SuiteResult(
|
||||
name=spec.name,
|
||||
kind=spec.kind,
|
||||
command=list(spec.command),
|
||||
status="unexecuted",
|
||||
returncode=-1,
|
||||
duration_seconds=0.0,
|
||||
stdout="",
|
||||
stderr="not executed because a previous suite failed",
|
||||
reproduction=" ".join(shell_quote(p) for p in spec.command),
|
||||
)
|
||||
)
|
||||
continue
|
||||
if spec.kind == "ignored":
|
||||
report.suites.append(
|
||||
SuiteResult(
|
||||
name=spec.name,
|
||||
kind=spec.kind,
|
||||
command=list(spec.command),
|
||||
status="ignored",
|
||||
returncode=0,
|
||||
duration_seconds=0.0,
|
||||
stdout="",
|
||||
stderr="suite marked ignored",
|
||||
reproduction=" ".join(shell_quote(p) for p in spec.command),
|
||||
)
|
||||
)
|
||||
continue
|
||||
started = time.time()
|
||||
result = run_preserving_status(spec.command)
|
||||
finished = time.time()
|
||||
status = classify_status(result.returncode)
|
||||
report.suites.append(
|
||||
SuiteResult(
|
||||
name=spec.name,
|
||||
kind=spec.kind,
|
||||
command=list(spec.command),
|
||||
status=status,
|
||||
returncode=result.returncode,
|
||||
duration_seconds=finished - started,
|
||||
stdout=result.stdout,
|
||||
stderr=result.stderr,
|
||||
reproduction=" ".join(shell_quote(p) for p in spec.command),
|
||||
)
|
||||
)
|
||||
if stop_on_fail and status == "failed":
|
||||
halted = True
|
||||
report.finished_at = time.time()
|
||||
return report
|
||||
|
||||
|
||||
def dumps_report(report: OrchestrationReport) -> str:
|
||||
return json.dumps(report.to_dict(), indent=2, sort_keys=True) + "\n"
|
||||
|
||||
|
||||
def failure_log_excerpt(report: OrchestrationReport, *, limit: int = 40) -> str:
|
||||
lines: list[str] = []
|
||||
for suite in report.suites:
|
||||
if suite.status != "failed":
|
||||
continue
|
||||
lines.append(f"## {suite.name} (exit {suite.returncode})")
|
||||
lines.append(f"reproduce: {suite.reproduction}")
|
||||
err = (suite.stderr or suite.stdout).splitlines()
|
||||
lines.extend(err[:limit])
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def separate_cpu_gpu(report: OrchestrationReport) -> dict[str, list[SuiteResult]]:
|
||||
out = {"cpu": [], "gpu": [], "other": []}
|
||||
for suite in report.suites:
|
||||
bucket = suite.kind if suite.kind in out else "other"
|
||||
out[bucket].append(suite)
|
||||
return out
|
||||
@@ -0,0 +1,150 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Advisory pull-request validation helpers.
|
||||
|
||||
Checks changed paths against an approved scope, DCO trailers, native arch
|
||||
hints, changelog presence and accidental build-artifact inclusion. Advisory
|
||||
only: callers decide whether to fail a gate.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import PurePosixPath
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
DCO_RE = re.compile(r"^Signed-off-by:\s+\S.+\s+<\S+@\S+>\s*$", re.MULTILINE)
|
||||
FULL_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
|
||||
ARTIFACT_SUFFIXES = (
|
||||
".o", ".a", ".dylib", ".so", ".pyc", ".rlib", ".rmeta",
|
||||
)
|
||||
ARTIFACT_NAMES = {"__pycache__", "target", ".DS_Store"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Finding:
|
||||
code: str
|
||||
severity: str # advisory | blocking-candidate
|
||||
message: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class ValidationReport:
|
||||
findings: list[Finding] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def ok(self) -> bool:
|
||||
return not any(f.severity == "blocking-candidate" for f in self.findings)
|
||||
|
||||
def add(self, code: str, message: str, *, severity: str = "advisory") -> None:
|
||||
self.findings.append(Finding(code=code, severity=severity, message=message))
|
||||
|
||||
|
||||
def path_in_scope(path: str, patterns: Sequence[str]) -> bool:
|
||||
posix = PurePosixPath(path)
|
||||
for pattern in patterns:
|
||||
pat = pattern.rstrip()
|
||||
if pat.endswith("/**"):
|
||||
root = pat[:-3]
|
||||
if path == root or path.startswith(root.rstrip("/") + "/"):
|
||||
return True
|
||||
elif pat.endswith("/"):
|
||||
if path.startswith(pat) or path == pat.rstrip("/"):
|
||||
return True
|
||||
elif "*" in pat or "?" in pat:
|
||||
if posix.match(pat):
|
||||
return True
|
||||
elif path == pat:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def check_scope(changed_files: Iterable[str], allowed: Sequence[str]) -> ValidationReport:
|
||||
report = ValidationReport()
|
||||
for path in changed_files:
|
||||
if not path_in_scope(path, allowed):
|
||||
report.add(
|
||||
"scope",
|
||||
f"changed file outside approved scope: {path}",
|
||||
severity="blocking-candidate",
|
||||
)
|
||||
return report
|
||||
|
||||
|
||||
def check_dco(commit_messages: Iterable[str]) -> ValidationReport:
|
||||
report = ValidationReport()
|
||||
for i, message in enumerate(commit_messages, start=1):
|
||||
if not DCO_RE.search(message or ""):
|
||||
report.add(
|
||||
"dco",
|
||||
f"commit {i} is missing a Signed-off-by trailer",
|
||||
severity="blocking-candidate",
|
||||
)
|
||||
return report
|
||||
|
||||
|
||||
def check_artifacts(changed_files: Iterable[str]) -> ValidationReport:
|
||||
report = ValidationReport()
|
||||
for path in changed_files:
|
||||
name = PurePosixPath(path).name
|
||||
if name in ARTIFACT_NAMES or any(part in ARTIFACT_NAMES for part in PurePosixPath(path).parts):
|
||||
report.add("artifact", f"build artifact path included: {path}")
|
||||
continue
|
||||
if name.endswith(ARTIFACT_SUFFIXES):
|
||||
report.add("artifact", f"build artifact suffix included: {path}")
|
||||
return report
|
||||
|
||||
|
||||
def check_changelog_required(changed_files: Iterable[str], *, require: bool = True) -> ValidationReport:
|
||||
report = ValidationReport()
|
||||
files = list(changed_files)
|
||||
meaningful = [
|
||||
f for f in files
|
||||
if not f.startswith("docs/") and f != "CHANGELOG.md" and not f.startswith("tests/")
|
||||
]
|
||||
if require and meaningful and "CHANGELOG.md" not in files:
|
||||
report.add(
|
||||
"changelog",
|
||||
"meaningful non-docs code changes without CHANGELOG.md",
|
||||
severity="advisory",
|
||||
)
|
||||
return report
|
||||
|
||||
|
||||
def check_report_commit_identity(report_sha: str, head_sha: str) -> ValidationReport:
|
||||
report = ValidationReport()
|
||||
if not FULL_SHA_RE.fullmatch(report_sha or ""):
|
||||
report.add("evidence-sha", "test report commit is not a full 40-character SHA",
|
||||
severity="blocking-candidate")
|
||||
return report
|
||||
if report_sha != head_sha:
|
||||
report.add(
|
||||
"evidence-sha",
|
||||
f"test report SHA {report_sha} does not match head {head_sha}",
|
||||
severity="blocking-candidate",
|
||||
)
|
||||
return report
|
||||
|
||||
|
||||
def check_native_arch_strings(file_output_lines: Iterable[str]) -> ValidationReport:
|
||||
"""Advisory scan of `file`/`lipo` style lines for non-arm64 host binaries."""
|
||||
report = ValidationReport()
|
||||
for line in file_output_lines:
|
||||
lower = line.lower()
|
||||
if "mach-o" not in lower:
|
||||
continue
|
||||
if "arm64" in lower or "aarch64" in lower:
|
||||
continue
|
||||
if "x86_64" in lower or "i386" in lower:
|
||||
report.add(
|
||||
"arch",
|
||||
f"non-ARM64 Mach-O mention: {line.strip()}",
|
||||
severity="blocking-candidate",
|
||||
)
|
||||
return report
|
||||
|
||||
|
||||
def merge_reports(*reports: ValidationReport) -> ValidationReport:
|
||||
out = ValidationReport()
|
||||
for report in reports:
|
||||
out.findings.extend(report.findings)
|
||||
return out
|
||||
@@ -0,0 +1,65 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Historical orchestration report comparison."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SuiteDelta:
|
||||
name: str
|
||||
previous_status: str | None
|
||||
current_status: str | None
|
||||
kind: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RegressionDiff:
|
||||
newly_failed: tuple[SuiteDelta, ...]
|
||||
newly_passed: tuple[SuiteDelta, ...]
|
||||
still_failed: tuple[SuiteDelta, ...]
|
||||
missing: tuple[SuiteDelta, ...]
|
||||
|
||||
|
||||
def load_report(text: str) -> dict[str, Any]:
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
def _status_map(report: dict[str, Any]) -> dict[str, tuple[str, str]]:
|
||||
out: dict[str, tuple[str, str]] = {}
|
||||
for suite in report.get("suites", []):
|
||||
out[suite["name"]] = (suite.get("status", "unknown"), suite.get("kind", "other"))
|
||||
return out
|
||||
|
||||
|
||||
def compare_reports(previous: dict[str, Any], current: dict[str, Any]) -> RegressionDiff:
|
||||
prev = _status_map(previous)
|
||||
cur = _status_map(current)
|
||||
newly_failed: list[SuiteDelta] = []
|
||||
newly_passed: list[SuiteDelta] = []
|
||||
still_failed: list[SuiteDelta] = []
|
||||
missing: list[SuiteDelta] = []
|
||||
for name, (status, kind) in sorted(cur.items()):
|
||||
before = prev.get(name)
|
||||
before_status = before[0] if before else None
|
||||
if status == "failed" and before_status != "failed":
|
||||
newly_failed.append(SuiteDelta(name, before_status, status, kind))
|
||||
elif status == "passed" and before_status == "failed":
|
||||
newly_passed.append(SuiteDelta(name, before_status, status, kind))
|
||||
elif status == "failed" and before_status == "failed":
|
||||
still_failed.append(SuiteDelta(name, before_status, status, kind))
|
||||
for name, (status, kind) in sorted(prev.items()):
|
||||
if name not in cur:
|
||||
missing.append(SuiteDelta(name, status, None, kind))
|
||||
return RegressionDiff(
|
||||
newly_failed=tuple(newly_failed),
|
||||
newly_passed=tuple(newly_passed),
|
||||
still_failed=tuple(still_failed),
|
||||
missing=tuple(missing),
|
||||
)
|
||||
|
||||
|
||||
def has_new_regressions(diff: RegressionDiff) -> bool:
|
||||
return bool(diff.newly_failed or diff.missing)
|
||||
@@ -0,0 +1,50 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Read-only repository health checks for contributors."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HealthFinding:
|
||||
code: str
|
||||
ok: bool
|
||||
detail: str
|
||||
|
||||
|
||||
def check_ignored_artifacts_tracked(tracked_paths: Iterable[str]) -> HealthFinding:
|
||||
bad = []
|
||||
for path in tracked_paths:
|
||||
parts = path.split("/")
|
||||
if "__pycache__" in parts or path.endswith(".pyc"):
|
||||
bad.append(path)
|
||||
if "/target/" in f"/{path}/" or path.startswith("target/"):
|
||||
bad.append(path)
|
||||
ok = not bad
|
||||
detail = "no tracked build artifacts" if ok else "tracked artifacts: " + ", ".join(bad[:10])
|
||||
return HealthFinding("tracked-artifacts", ok, detail)
|
||||
|
||||
|
||||
def check_large_generated_paths(tracked_paths: Iterable[str], *, suspicious_prefixes: tuple[str, ...] = ("artifacts/",)) -> HealthFinding:
|
||||
hits = [p for p in tracked_paths if any(p.startswith(pref) for pref in suspicious_prefixes)]
|
||||
ok = not hits
|
||||
detail = "no generated artifact paths tracked" if ok else "suspicious paths: " + ", ".join(hits[:10])
|
||||
return HealthFinding("generated-paths", ok, detail)
|
||||
|
||||
|
||||
def check_upstream_configured(remotes: Iterable[str], *, expected: str = "ranveersoni98/Xenora") -> HealthFinding:
|
||||
names = set(remotes)
|
||||
# Accept either a remote named upstream or origin pointing at expected.
|
||||
ok = "upstream" in names or "origin" in names
|
||||
detail = f"remotes={sorted(names)}; expected repo {expected}"
|
||||
return HealthFinding("remotes", ok, detail)
|
||||
|
||||
|
||||
def format_health(findings: Iterable[HealthFinding]) -> str:
|
||||
lines = ["# Repository health", ""]
|
||||
for finding in findings:
|
||||
mark = "ok" if finding.ok else "FAIL"
|
||||
lines.append(f"- [{mark}] {finding.code}: {finding.detail}")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Standalone release and packaging verification helpers."""
|
||||
@@ -0,0 +1,65 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Application bundle structure and codesign diagnostic helpers."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
REQUIRED_APP_ENTRIES = (
|
||||
"Contents/Info.plist",
|
||||
"Contents/MacOS",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BundleCheck:
|
||||
root: str
|
||||
ok: bool
|
||||
problems: tuple[str, ...]
|
||||
present: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CodesignDiagnosis:
|
||||
path: str
|
||||
ok: bool
|
||||
problems: tuple[str, ...]
|
||||
notes: tuple[str, ...]
|
||||
|
||||
|
||||
def check_app_bundle(root: Path, entries: Iterable[str] | None = None) -> BundleCheck:
|
||||
required = tuple(entries) if entries is not None else REQUIRED_APP_ENTRIES
|
||||
present: list[str] = []
|
||||
problems: list[str] = []
|
||||
if not root.exists():
|
||||
return BundleCheck(root=str(root), ok=False, problems=(f"missing bundle root: {root}",), present=())
|
||||
if not root.is_dir():
|
||||
return BundleCheck(root=str(root), ok=False, problems=(f"bundle root is not a directory: {root}",), present=())
|
||||
for rel in required:
|
||||
path = root / rel
|
||||
if path.exists():
|
||||
present.append(rel)
|
||||
else:
|
||||
problems.append(f"missing {rel}")
|
||||
return BundleCheck(root=str(root), ok=not problems, problems=tuple(problems), present=tuple(present))
|
||||
|
||||
|
||||
def diagnose_codesign_output(path: str, codesign_stderr_or_stdout: str) -> CodesignDiagnosis:
|
||||
text = codesign_stderr_or_stdout.strip()
|
||||
notes = tuple(line.strip() for line in text.splitlines() if line.strip())
|
||||
problems: list[str] = []
|
||||
lower = text.casefold()
|
||||
if "code object is not signed at all" in lower:
|
||||
problems.append("unsigned")
|
||||
if "cssmerr_tp_cert_expired" in lower or "expired" in lower:
|
||||
problems.append("certificate expired or reported expired")
|
||||
if "errsec" in lower or "failed" in lower:
|
||||
if not problems:
|
||||
problems.append("codesign reported failure")
|
||||
ok = not problems
|
||||
if not text:
|
||||
problems.append("empty codesign output")
|
||||
ok = False
|
||||
return CodesignDiagnosis(path=path, ok=ok, problems=tuple(problems), notes=notes)
|
||||
@@ -0,0 +1,69 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""ARM64 Mach-O architecture and linkage inspection helpers."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
FORBIDDEN_LINKAGE = ("vulkan", "moltenvk", "libvulkan")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ArchCheck:
|
||||
path: str
|
||||
archs: tuple[str, ...]
|
||||
ok: bool
|
||||
problems: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LinkageCheck:
|
||||
path: str
|
||||
lines: tuple[str, ...]
|
||||
ok: bool
|
||||
problems: tuple[str, ...]
|
||||
|
||||
|
||||
def parse_lipo_archs(text: str) -> tuple[str, ...]:
|
||||
parts = [p for p in text.strip().split() if p]
|
||||
return tuple(parts)
|
||||
|
||||
|
||||
def check_archs(path: str, arch_text: str, *, require: Sequence[str] = ("arm64",)) -> ArchCheck:
|
||||
archs = parse_lipo_archs(arch_text)
|
||||
problems: list[str] = []
|
||||
required = tuple(require)
|
||||
if archs != required:
|
||||
problems.append(f"expected archs {required}, got {archs}")
|
||||
return ArchCheck(path=path, archs=archs, ok=not problems, problems=tuple(problems))
|
||||
|
||||
|
||||
def check_otool_linkage(path: str, otool_text: str) -> LinkageCheck:
|
||||
lines = tuple(line.rstrip() for line in otool_text.splitlines() if line.strip())
|
||||
problems: list[str] = []
|
||||
joined = "\n".join(lines).casefold()
|
||||
for name in FORBIDDEN_LINKAGE:
|
||||
if name in joined:
|
||||
problems.append(f"forbidden linkage mention: {name}")
|
||||
return LinkageCheck(path=path, lines=lines, ok=not problems, problems=tuple(problems))
|
||||
|
||||
|
||||
_DEPLOY_RE = re.compile(r"minos|sdk|version.min", re.IGNORECASE)
|
||||
|
||||
|
||||
def deployment_target_tokens(otool_header_text: str) -> tuple[str, ...]:
|
||||
tokens: list[str] = []
|
||||
for line in otool_header_text.splitlines():
|
||||
if _DEPLOY_RE.search(line):
|
||||
tokens.append(line.strip())
|
||||
return tuple(tokens)
|
||||
|
||||
|
||||
def consistent_deployment_targets(texts: Iterable[str]) -> tuple[bool, tuple[str, ...]]:
|
||||
sets = [frozenset(deployment_target_tokens(t)) for t in texts]
|
||||
if not sets:
|
||||
return True, ()
|
||||
first = sets[0]
|
||||
ok = all(s == first for s in sets[1:])
|
||||
return ok, tuple(sorted(first))
|
||||
@@ -0,0 +1,74 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Reproducible artifact manifests, checksums and simple SBOM stubs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ArtifactRecord:
|
||||
path: str
|
||||
sha256: str
|
||||
size: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Manifest:
|
||||
revision: str
|
||||
artifacts: tuple[ArtifactRecord, ...]
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"revision": self.revision,
|
||||
"artifacts": [asdict(a) for a in self.artifacts],
|
||||
}
|
||||
|
||||
|
||||
def sha256_bytes(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> ArtifactRecord:
|
||||
data = path.read_bytes()
|
||||
return ArtifactRecord(path=str(path), sha256=sha256_bytes(data), size=len(data))
|
||||
|
||||
|
||||
def build_manifest(paths: Iterable[Path], *, revision: str) -> Manifest:
|
||||
records = tuple(sha256_file(Path(p)) for p in paths)
|
||||
return Manifest(revision=revision, artifacts=records)
|
||||
|
||||
|
||||
def dumps_manifest(manifest: Manifest) -> str:
|
||||
return json.dumps(manifest.to_dict(), indent=2, sort_keys=True) + "\n"
|
||||
|
||||
|
||||
def license_inventory(entries: Iterable[tuple[str, str]]) -> str:
|
||||
"""Build a deterministic dependency license inventory from (name, license) pairs."""
|
||||
rows = sorted((name, lic) for name, lic in entries)
|
||||
lines = ["# Dependency license inventory", ""]
|
||||
for name, lic in rows:
|
||||
lines.append(f"- `{name}`: {lic}")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def validate_evidence(
|
||||
*,
|
||||
manifest_sha_by_path: dict[str, str],
|
||||
observed_sha_by_path: dict[str, str],
|
||||
) -> tuple[bool, tuple[str, ...]]:
|
||||
problems: list[str] = []
|
||||
for path, expected in sorted(manifest_sha_by_path.items()):
|
||||
got = observed_sha_by_path.get(path)
|
||||
if got is None:
|
||||
problems.append(f"missing artifact: {path}")
|
||||
elif got != expected:
|
||||
problems.append(f"checksum mismatch: {path}")
|
||||
for path in sorted(observed_sha_by_path):
|
||||
if path not in manifest_sha_by_path:
|
||||
problems.append(f"unexpected artifact: {path}")
|
||||
return not problems, tuple(problems)
|
||||
@@ -30,6 +30,16 @@ cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-
|
||||
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
# The persistent frame loop runs the guest on its own thread and renders on Metal.
|
||||
cargo test --locked -p xenora-ffi --features gpu-tests --test frame_loop --no-run
|
||||
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test frame_loop -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
# Interactive guest execution with dynamic input handling and rendering (Gate 4, #276).
|
||||
cargo test --locked -p xenora-ffi --features gpu-tests --test interactive --no-run
|
||||
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test interactive -- \
|
||||
--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
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Regression for live smoke failure: comment-only actions must not call issue edit."""
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from agent_queue import ghio
|
||||
|
||||
|
||||
class ApplyActions(unittest.TestCase):
|
||||
def test_comment_only_skips_issue_edit(self):
|
||||
calls = []
|
||||
|
||||
def fake_gh(*args):
|
||||
calls.append(list(args))
|
||||
return ""
|
||||
|
||||
with mock.patch.object(ghio, "gh", side_effect=fake_gh):
|
||||
ghio.apply_actions("o/r", [{
|
||||
"issue": 2,
|
||||
"add_labels": [],
|
||||
"remove_labels": [],
|
||||
"comment": "Claim refused for alice: file overlap with claimed task #1.",
|
||||
}])
|
||||
self.assertEqual(calls, [[
|
||||
"issue", "comment", "2", "-R", "o/r", "--body",
|
||||
"Claim refused for alice: file overlap with claimed task #1.",
|
||||
]])
|
||||
|
||||
def test_label_change_edits_then_comments(self):
|
||||
calls = []
|
||||
|
||||
def fake_gh(*args):
|
||||
calls.append(list(args))
|
||||
return ""
|
||||
|
||||
with mock.patch.object(ghio, "gh", side_effect=fake_gh):
|
||||
ghio.apply_actions("o/r", [{
|
||||
"issue": 1,
|
||||
"add_labels": ["agent:claimed", "claimed-by:alice"],
|
||||
"remove_labels": ["agent:ready"],
|
||||
"comment": "Claimed by alice.\n<!-- agent-queue:grant -->",
|
||||
}])
|
||||
self.assertEqual(calls[0][:2], ["label", "create"])
|
||||
self.assertEqual(calls[1][:2], ["label", "create"])
|
||||
self.assertEqual(calls[2], [
|
||||
"issue", "edit", "1", "-R", "o/r",
|
||||
"--add-label", "agent:claimed",
|
||||
"--add-label", "claimed-by:alice",
|
||||
"--remove-label", "agent:ready",
|
||||
])
|
||||
self.assertEqual(calls[3][:3], ["issue", "comment", "1"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,63 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Read-only conflict prediction before a claim is posted.
|
||||
|
||||
Uses the same pure `claim_problem` rules as the bot, without applying labels or
|
||||
posting comments. Contributors can evaluate overlap, area, dependency and
|
||||
readiness failures locally before they edit files.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
from agent_queue.decide import claim_problem, decide, task_index
|
||||
|
||||
from helpers import CFG, event, issue, state
|
||||
|
||||
|
||||
class ConflictPredict(unittest.TestCase):
|
||||
def test_predicts_overlap_without_mutating_state(self):
|
||||
held = issue(1, labels=("agent:claimed", "claimed-by:gpuer", "area:gpu"),
|
||||
area="gpu", files="src/gpu/**")
|
||||
candidate = issue(2, labels=("agent:ready", "area:gpu"),
|
||||
area="gpu", files="src/gpu/a.rs")
|
||||
snap = state(held, candidate, task_comments={
|
||||
"1": [{"user": "github-actions[bot]", "body": "Granted to gpuer.\n<!-- agent-queue:grant -->",
|
||||
"created_at": "2026-01-10T09:00:00Z"}],
|
||||
})
|
||||
before = [dict(i) for i in snap["issues"]]
|
||||
tasks = task_index(snap)
|
||||
problem = claim_problem(tasks[2], tasks, CFG, "gpuer")
|
||||
self.assertIn("file overlap with claimed task #1", problem)
|
||||
self.assertEqual(snap["issues"], before)
|
||||
|
||||
def test_predicts_ready_when_no_conflict(self):
|
||||
ready = issue(3, labels=("agent:ready", "area:qa"), area="qa", files="tests/qa/**")
|
||||
tasks = task_index(state(ready))
|
||||
self.assertEqual(claim_problem(tasks[3], tasks, CFG, "qaer"), "")
|
||||
|
||||
def test_predicts_wrong_area_and_open_dependency(self):
|
||||
dep = issue(4, labels=("agent:ready", "area:cpu"), area="cpu", files="crates/loader/**")
|
||||
blocked = issue(5, labels=("agent:ready", "area:qa"), area="qa",
|
||||
files="docs/testing/**", deps="#4")
|
||||
tasks = task_index(state(dep, blocked))
|
||||
self.assertIn("not allowed to claim area:cpu", claim_problem(tasks[4], tasks, CFG, "qaer"))
|
||||
self.assertIn("open dependencies: #4", claim_problem(tasks[5], tasks, CFG, "qaer"))
|
||||
|
||||
def test_predict_agrees_with_live_claim_decision(self):
|
||||
held = issue(6, labels=("agent:claimed", "claimed-by:maint", "area:shared"),
|
||||
area="shared", files="docs/interfaces.md")
|
||||
ready = issue(7, labels=("agent:ready", "area:shared"),
|
||||
area="shared", files="docs/interfaces.md")
|
||||
snap = state(held, ready, task_comments={
|
||||
"6": [{"user": "github-actions[bot]", "body": "Granted.\n<!-- agent-queue:grant -->",
|
||||
"created_at": "2026-01-10T09:00:00Z"}],
|
||||
})
|
||||
tasks = task_index(snap)
|
||||
predicted = claim_problem(tasks[7], tasks, CFG, "maint")
|
||||
actions = decide(event("maint", "/claim", n=7), snap, CFG)
|
||||
self.assertTrue(predicted)
|
||||
self.assertEqual(len(actions), 1)
|
||||
self.assertIn(predicted, actions[0]["comment"])
|
||||
self.assertEqual(actions[0].get("add_labels"), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -134,6 +134,16 @@ class Cli(unittest.TestCase):
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(r.stdout.strip(), "ranveersoni98/Xenora")
|
||||
|
||||
def test_summary_accepts_now_after_subcommand(self):
|
||||
# Actions passes --now after `summary`; parent-only --now used to reject that.
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
state = os.path.join(d, "state.json")
|
||||
dump({"issues": [], "prs": []}, state)
|
||||
r = self.run_cli("summary", "--state", state, "--now", "2026-01-10T12:00:00Z")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
payload = json.loads(r.stdout)
|
||||
self.assertEqual(payload["generated_at"], "2026-01-10T12:00:00Z")
|
||||
|
||||
def test_acceptance_authorization_end_to_end(self):
|
||||
from agent_queue import lease as L, tasks as T
|
||||
i = issue(1)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from qa.bench_stats import compare_medians, export_json, human_report, summarize
|
||||
|
||||
|
||||
class BenchStats(unittest.TestCase):
|
||||
def test_percentiles_and_export(self):
|
||||
samples = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
stats = summarize(samples)
|
||||
self.assertEqual(stats.count, 10)
|
||||
self.assertEqual(stats.median, 5.5)
|
||||
self.assertGreaterEqual(stats.p95, stats.median)
|
||||
self.assertGreaterEqual(stats.p99, stats.p95)
|
||||
payload = json.loads(export_json(stats, host="m5", toolchain="rustc", revision="abc", metric="gpu"))
|
||||
self.assertEqual(payload["host"], "m5")
|
||||
self.assertIn("median", human_report(stats, metric="gpu"))
|
||||
|
||||
def test_regression_threshold(self):
|
||||
ok = compare_medians([10, 10, 10], [10.5, 10.4, 10.6], threshold=1.10)
|
||||
self.assertFalse(ok.regressing)
|
||||
bad = compare_medians([10, 10, 10], [12, 12, 12], threshold=1.10)
|
||||
self.assertTrue(bad.regressing)
|
||||
self.assertGreater(bad.ratio, 1.10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,29 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import unittest
|
||||
|
||||
from qa.claim_conflict import ClaimSnapshot, format_conflicts, predict_conflicts
|
||||
|
||||
|
||||
class ClaimConflict(unittest.TestCase):
|
||||
def test_predicts_directory_overlap(self):
|
||||
held = [
|
||||
ClaimSnapshot(10, "alice", ("scripts/qa/",), True),
|
||||
ClaimSnapshot(11, "bob", ("scripts/release/",), True),
|
||||
]
|
||||
hits = predict_conflicts(["scripts/qa/orchestrate.py"], held)
|
||||
self.assertEqual(len(hits), 1)
|
||||
self.assertEqual(hits[0].held_by, 10)
|
||||
self.assertIn("overlaps claimed #10", format_conflicts(hits))
|
||||
|
||||
def test_ignores_unclaimed_and_disjoint(self):
|
||||
held = [
|
||||
ClaimSnapshot(12, "", ("scripts/qa/",), False),
|
||||
ClaimSnapshot(13, "carol", ("docs/testing/infrastructure/",), True),
|
||||
]
|
||||
hits = predict_conflicts(["scripts/release/macho.py"], held)
|
||||
self.assertEqual(hits, ())
|
||||
self.assertEqual(format_conflicts(hits), "no file conflicts predicted\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,28 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import unittest
|
||||
|
||||
from qa.exit_pipe import classify_status, run_preserving_status
|
||||
|
||||
|
||||
class ExitPipe(unittest.TestCase):
|
||||
def test_preserves_nonzero_status(self):
|
||||
result = run_preserving_status(["python3", "-c", "import sys; sys.exit(7)"])
|
||||
self.assertEqual(result.returncode, 7)
|
||||
self.assertEqual(classify_status(result.returncode), "failed")
|
||||
|
||||
def test_preserves_zero_status(self):
|
||||
result = run_preserving_status(["python3", "-c", "print('ok')"])
|
||||
self.assertEqual(result.returncode, 0)
|
||||
self.assertEqual(classify_status(result.returncode), "passed")
|
||||
self.assertIn("ok", result.stdout)
|
||||
|
||||
def test_failure_not_masked_by_later_success_semantics(self):
|
||||
# The helper returns the command status directly; callers must not pipe
|
||||
# through shell grep. This asserts the contract used by orchestrate.
|
||||
failed = run_preserving_status(["python3", "-c", "import sys; print('needle'); sys.exit(3)"])
|
||||
self.assertEqual(failed.returncode, 3)
|
||||
self.assertIn("needle", failed.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,59 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from qa.orchestrate import (
|
||||
SuiteSpec,
|
||||
dumps_report,
|
||||
failure_log_excerpt,
|
||||
run_suites,
|
||||
separate_cpu_gpu,
|
||||
)
|
||||
|
||||
|
||||
class Orchestrate(unittest.TestCase):
|
||||
def test_records_pass_and_fail_with_durations(self):
|
||||
report = run_suites([
|
||||
SuiteSpec("ok", ("python3", "-c", "print(1)"), "cpu"),
|
||||
SuiteSpec("bad", ("python3", "-c", "import sys; sys.exit(2)"), "cpu"),
|
||||
])
|
||||
self.assertEqual(report.passed, 1)
|
||||
self.assertEqual(report.failed, 1)
|
||||
self.assertGreaterEqual(report.suites[0].duration_seconds, 0.0)
|
||||
self.assertEqual(report.overall_returncode(), 2)
|
||||
payload = json.loads(dumps_report(report))
|
||||
self.assertEqual(payload["counts"]["failed"], 1)
|
||||
|
||||
def test_stop_on_fail_marks_unexecuted(self):
|
||||
report = run_suites(
|
||||
[
|
||||
SuiteSpec("bad", ("python3", "-c", "import sys; sys.exit(5)"), "cpu"),
|
||||
SuiteSpec("later", ("python3", "-c", "print('nope')"), "gpu"),
|
||||
],
|
||||
stop_on_fail=True,
|
||||
)
|
||||
self.assertEqual(report.suites[1].status, "unexecuted")
|
||||
self.assertEqual(report.unexecuted, 1)
|
||||
|
||||
def test_ignored_and_cpu_gpu_split(self):
|
||||
report = run_suites([
|
||||
SuiteSpec("skip", ("true",), "ignored"),
|
||||
SuiteSpec("cpu", ("python3", "-c", "print('c')"), "cpu"),
|
||||
SuiteSpec("gpu", ("python3", "-c", "print('g')"), "gpu"),
|
||||
])
|
||||
self.assertEqual(report.ignored, 1)
|
||||
buckets = separate_cpu_gpu(report)
|
||||
self.assertEqual(len(buckets["cpu"]), 1)
|
||||
self.assertEqual(len(buckets["gpu"]), 1)
|
||||
|
||||
def test_failure_excerpt_includes_reproduction(self):
|
||||
report = run_suites([
|
||||
SuiteSpec("bad", ("python3", "-c", "import sys; sys.stderr.write('boom\\n'); sys.exit(1)"), "cpu"),
|
||||
])
|
||||
text = failure_log_excerpt(report)
|
||||
self.assertIn("reproduce:", text)
|
||||
self.assertIn("boom", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,44 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import unittest
|
||||
|
||||
from qa.pr_validate import (
|
||||
check_artifacts,
|
||||
check_changelog_required,
|
||||
check_dco,
|
||||
check_native_arch_strings,
|
||||
check_report_commit_identity,
|
||||
check_scope,
|
||||
merge_reports,
|
||||
)
|
||||
|
||||
|
||||
class PRValidate(unittest.TestCase):
|
||||
def test_scope_and_artifacts(self):
|
||||
scope = check_scope(["scripts/qa/a.py", "crates/loader/x.rs"], ["scripts/qa/", "tests/qa/"])
|
||||
self.assertFalse(scope.ok)
|
||||
arts = check_artifacts(["scripts/qa/a.py", "foo/__pycache__/x.pyc", "bar.o"])
|
||||
self.assertTrue(any(f.code == "artifact" for f in arts.findings))
|
||||
|
||||
def test_dco_and_changelog(self):
|
||||
bad = check_dco(["feat: no trailer\n"])
|
||||
self.assertFalse(bad.ok)
|
||||
good = check_dco(["feat: x\n\nSigned-off-by: A U <a@b.c>\n"])
|
||||
self.assertTrue(good.ok)
|
||||
log = check_changelog_required(["scripts/qa/x.py"])
|
||||
self.assertTrue(any(f.code == "changelog" for f in log.findings))
|
||||
|
||||
def test_evidence_sha_and_arch(self):
|
||||
sha = "a" * 40
|
||||
mismatch = check_report_commit_identity(sha, "b" * 40)
|
||||
self.assertFalse(mismatch.ok)
|
||||
arch = check_native_arch_strings([
|
||||
"foo: Mach-O 64-bit executable x86_64",
|
||||
"bar: Mach-O 64-bit executable arm64",
|
||||
])
|
||||
self.assertFalse(arch.ok)
|
||||
merged = merge_reports(mismatch, arch)
|
||||
self.assertGreaterEqual(len(merged.findings), 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,45 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from qa.handoff import HandoffReport, WorkItem, conflict_paths, handoff_markdown, progress_summary
|
||||
from qa.regression import compare_reports, has_new_regressions
|
||||
from qa.repo_health import check_ignored_artifacts_tracked, check_large_generated_paths, format_health
|
||||
|
||||
|
||||
class RegressionHandoffHealth(unittest.TestCase):
|
||||
def test_compare_reports(self):
|
||||
prev = {"suites": [{"name": "a", "status": "passed", "kind": "cpu"},
|
||||
{"name": "b", "status": "failed", "kind": "cpu"}]}
|
||||
cur = {"suites": [{"name": "a", "status": "failed", "kind": "cpu"},
|
||||
{"name": "b", "status": "passed", "kind": "cpu"}]}
|
||||
diff = compare_reports(prev, cur)
|
||||
self.assertEqual(diff.newly_failed[0].name, "a")
|
||||
self.assertEqual(diff.newly_passed[0].name, "b")
|
||||
self.assertTrue(has_new_regressions(diff))
|
||||
self.assertIn("a", json.dumps(prev))
|
||||
|
||||
def test_handoff_and_conflicts(self):
|
||||
items = [
|
||||
WorkItem(1, "one", "claimed", ("scripts/qa/",)),
|
||||
WorkItem(2, "two", "claimed", ("scripts/qa/x.py",)),
|
||||
WorkItem(3, "three", "done", ("scripts/release/",)),
|
||||
]
|
||||
self.assertTrue(conflict_paths(items))
|
||||
text = progress_summary(items)
|
||||
self.assertIn("#1", text)
|
||||
report = HandoffReport("alice", "deadbeef", tuple(items), ("gpu not measured",))
|
||||
md = handoff_markdown(report)
|
||||
self.assertIn("Limitations", md)
|
||||
self.assertIn("gpu not measured", md)
|
||||
|
||||
def test_repo_health(self):
|
||||
bad = check_ignored_artifacts_tracked(["scripts/qa/a.py", "x/__pycache__/y.pyc"])
|
||||
self.assertFalse(bad.ok)
|
||||
gen = check_large_generated_paths(["artifacts/foo.json", "scripts/qa/a.py"])
|
||||
self.assertFalse(gen.ok)
|
||||
self.assertIn("Repository health", format_health([bad, gen]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,43 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from release.bundle import check_app_bundle, diagnose_codesign_output
|
||||
from release.macho import check_archs, check_otool_linkage, consistent_deployment_targets
|
||||
|
||||
|
||||
class MachOBundle(unittest.TestCase):
|
||||
def test_arch_and_linkage(self):
|
||||
ok = check_archs("/tmp/x", "arm64")
|
||||
self.assertTrue(ok.ok)
|
||||
bad = check_archs("/tmp/x", "x86_64 arm64")
|
||||
self.assertFalse(bad.ok)
|
||||
link = check_otool_linkage("/tmp/x", "/tmp/x:\n\t/usr/lib/libSystem.B.dylib")
|
||||
self.assertTrue(link.ok)
|
||||
vuln = check_otool_linkage("/tmp/x", "/tmp/x:\n\t@rpath/libvulkan.dylib")
|
||||
self.assertFalse(vuln.ok)
|
||||
|
||||
def test_deployment_targets(self):
|
||||
a = "version.min osx,10.15\n"
|
||||
b = "version.min osx,10.15\n"
|
||||
c = "version.min osx,11.0\n"
|
||||
self.assertTrue(consistent_deployment_targets([a, b])[0])
|
||||
self.assertFalse(consistent_deployment_targets([a, c])[0])
|
||||
|
||||
def test_bundle_and_codesign(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "Xenora.app"
|
||||
(root / "Contents" / "MacOS").mkdir(parents=True)
|
||||
(root / "Contents" / "Info.plist").write_text("{}", encoding="utf-8")
|
||||
check = check_app_bundle(root)
|
||||
self.assertTrue(check.ok)
|
||||
missing = check_app_bundle(Path(tmp) / "Missing.app")
|
||||
self.assertFalse(missing.ok)
|
||||
unsigned = diagnose_codesign_output("/tmp/x", "code object is not signed at all")
|
||||
self.assertFalse(unsigned.ok)
|
||||
self.assertIn("unsigned", unsigned.problems)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,47 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from release.manifest import (
|
||||
build_manifest,
|
||||
dumps_manifest,
|
||||
license_inventory,
|
||||
sha256_bytes,
|
||||
validate_evidence,
|
||||
)
|
||||
|
||||
|
||||
class Manifest(unittest.TestCase):
|
||||
def test_checksums_and_validation(self):
|
||||
self.assertEqual(sha256_bytes(b"abc"),
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p = Path(tmp) / "a.bin"
|
||||
p.write_bytes(b"hello")
|
||||
manifest = build_manifest([p], revision="rev1")
|
||||
payload = json.loads(dumps_manifest(manifest))
|
||||
self.assertEqual(payload["revision"], "rev1")
|
||||
expected = {payload["artifacts"][0]["path"]: payload["artifacts"][0]["sha256"]}
|
||||
ok, problems = validate_evidence(
|
||||
manifest_sha_by_path=expected,
|
||||
observed_sha_by_path=expected,
|
||||
)
|
||||
self.assertTrue(ok)
|
||||
self.assertEqual(problems, ())
|
||||
bad, problems = validate_evidence(
|
||||
manifest_sha_by_path=expected,
|
||||
observed_sha_by_path={payload["artifacts"][0]["path"]: "0" * 64},
|
||||
)
|
||||
self.assertFalse(bad)
|
||||
self.assertTrue(problems)
|
||||
|
||||
def test_license_inventory_sorted(self):
|
||||
text = license_inventory([("zeta", "MIT"), ("alpha", "Apache-2.0")])
|
||||
self.assertLess(text.index("alpha"), text.index("zeta"))
|
||||
self.assertIn("Apache-2.0", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -32,13 +32,14 @@ U32 = "FMT_NUM_U32"
|
||||
I32 = "FMT_NUM_I32"
|
||||
|
||||
|
||||
def _operands(data_format, scc_in=False, src1_format=None):
|
||||
def _operands(data_format, scc_in=False, src1_format=None, scc_out=True):
|
||||
rows = [
|
||||
["SDST", data_format, "OPR_SDST", 32, False, True, False, True],
|
||||
["SSRC0", 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_out:
|
||||
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True])
|
||||
if scc_in:
|
||||
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, True, False, True, True])
|
||||
return rows
|
||||
@@ -54,7 +55,9 @@ def snapshot():
|
||||
["OP", [[23, 7]]], ["ENCODING", [[30, 2]]],
|
||||
],
|
||||
"identifier_mask": 0xFF800000,
|
||||
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14, 34)],
|
||||
"identifiers": [
|
||||
sop2_base | (op << 23) for op in (0, 2, 4, 6, 10, 14, 34, 38, 40, 47, 53)
|
||||
],
|
||||
}
|
||||
variants = {}
|
||||
for name, opcode, operands in (
|
||||
@@ -64,6 +67,13 @@ def snapshot():
|
||||
("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)),
|
||||
# Values copied from the AMD XML snapshot for the arithmetic fixture.
|
||||
("S_MIN_I32", 6, _operands(I32)),
|
||||
("S_CSELECT_B32", 10, _operands("FMT_NUM_B32", scc_in=True, scc_out=False)),
|
||||
("S_MUL_I32", 38, _operands(I32, scc_out=False)),
|
||||
("S_BFE_I32", 40, _operands(I32, src1_format=U32)),
|
||||
("S_LSHL2_ADD_U32", 47, _operands(U32)),
|
||||
("S_MUL_HI_U32", 53, _operands(U32, scc_out=False)),
|
||||
):
|
||||
variants[(name, "ENC_SOP2")] = {
|
||||
"instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands,
|
||||
@@ -109,9 +119,34 @@ def snapshot():
|
||||
variants[(name, "ENC_SOP1")] = {
|
||||
"instruction": name, "encoding": "ENC_SOP1", "opcode": opcode, "operands": operands,
|
||||
}
|
||||
vop2 = {
|
||||
"name": "ENC_VOP2",
|
||||
"bits": 32,
|
||||
"fields": [
|
||||
["SRC0", [[0, 9]]], ["VSRC1", [[9, 8]]], ["VDST", [[17, 8]]], ["OP", [[25, 6]]],
|
||||
["ENCODING", [[31, 1]]],
|
||||
],
|
||||
"identifier_mask": 0xFE000000,
|
||||
"identifiers": [op << 25 for op in (9, 17, 39)],
|
||||
}
|
||||
|
||||
def vector(data_format):
|
||||
return [
|
||||
["VDST", data_format, "OPR_VGPR", 32, False, True, False, True],
|
||||
["SRC0", data_format, "OPR_SRC", 32, True, False, False, True],
|
||||
["VSRC1", data_format, "OPR_VGPR", 32, True, False, False, True],
|
||||
]
|
||||
|
||||
for name, opcode, data_format in (
|
||||
("V_MUL_I32_I24", 9, I32), ("V_MIN_I32", 17, I32), ("V_SUBREV_NC_U32", 39, U32),
|
||||
):
|
||||
variants[(name, "ENC_VOP2")] = {
|
||||
"instruction": name, "encoding": "ENC_VOP2", "opcode": opcode,
|
||||
"operands": vector(data_format),
|
||||
}
|
||||
return {
|
||||
"source": {"sha256": SHA},
|
||||
"encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1},
|
||||
"encodings": {"ENC_SOP2": encoding, "ENC_SOPC": sopc, "ENC_SOP1": sop1, "ENC_VOP2": vop2},
|
||||
"variants": variants,
|
||||
}
|
||||
|
||||
@@ -146,6 +181,42 @@ def unaries():
|
||||
return reg
|
||||
|
||||
|
||||
def ariths():
|
||||
reg = registry()
|
||||
reg["form"] += [
|
||||
_form("S_MIN_I32", 6, "MinI32", "min", "signed", "selected_src0"),
|
||||
_form("S_CSELECT_B32", 10, "CselectB32", "cselect", "bitwise", "unchanged", carry_in="scc"),
|
||||
_form("S_MUL_I32", 38, "MulI32", "mul", "signed", "unchanged"),
|
||||
_form("S_BFE_I32", 40, "BfeI32", "bfe", "signed", "nonzero"),
|
||||
dict(
|
||||
_form("S_LSHL2_ADD_U32", 47, "Lshl2AddU32", "lshl_add", "unsigned", "carry_out"),
|
||||
shift_amount=2,
|
||||
),
|
||||
_form("S_MUL_HI_U32", 53, "MulHiU32", "mul_hi", "unsigned", "unchanged"),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def vectors():
|
||||
reg = registry()
|
||||
rule = copy.deepcopy(gen.OPERAND_RULES["vop2_vgpr"]["shape"])
|
||||
rule["unsupported"] = sorted(gen.OPERAND_RULES["vop2_vgpr"]["unsupported"])
|
||||
reg["operand_rules"]["vop2_vgpr"] = rule
|
||||
|
||||
def vector(name, opcode, variant, operation, signedness, **extra):
|
||||
form = _form(name, opcode, variant, operation, signedness, "unchanged")
|
||||
form.update(family="VOP2", operands="vop2_vgpr", **extra)
|
||||
return form
|
||||
|
||||
reg["form"] += [
|
||||
vector("V_MUL_I32_I24", 9, "MulI32I24", "mul24", "signed"),
|
||||
# The same variant name as a scalar form: variants are per enum.
|
||||
vector("V_MIN_I32", 17, "AddU32", "min", "signed"),
|
||||
vector("V_SUBREV_NC_U32", 39, "SubrevNcU32", "sub", "unsigned", source_order="reversed"),
|
||||
]
|
||||
return reg
|
||||
|
||||
|
||||
def compares():
|
||||
reg = registry()
|
||||
reg["form"] += [
|
||||
@@ -246,8 +317,8 @@ class Validate(unittest.TestCase):
|
||||
|
||||
def test_rejects_unknown_operation(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_U32")["operation"] = "mul"
|
||||
self.rejects(reg, "S_ADD_U32: unknown operation 'mul'")
|
||||
form(reg, "S_ADD_U32")["operation"] = "fma"
|
||||
self.rejects(reg, "S_ADD_U32: unknown operation 'fma'")
|
||||
|
||||
def test_rejects_unknown_scc_effect(self):
|
||||
reg = registry()
|
||||
@@ -326,8 +397,8 @@ class Validate(unittest.TestCase):
|
||||
|
||||
def test_rejects_form_absent_from_the_xml(self):
|
||||
reg = registry()
|
||||
reg["form"].append(_form("S_MUL_I32", 38, "MulI32", "add", "signed", "signed_overflow"))
|
||||
self.rejects(reg, "S_MUL_I32: no default ENC_SOP2 variant in the XML snapshot")
|
||||
reg["form"].append(_form("S_ABSDIFF_I32", 44, "AbsdiffI32", "absdiff", "signed", "nonzero"))
|
||||
self.rejects(reg, "S_ABSDIFF_I32: no default ENC_SOP2 variant in the XML snapshot")
|
||||
|
||||
# ---- duplicates ----
|
||||
|
||||
@@ -369,8 +440,8 @@ class Validate(unittest.TestCase):
|
||||
|
||||
def test_rejects_operand_rule_the_decoder_does_not_implement(self):
|
||||
reg = registry()
|
||||
reg["operand_rules"]["vop2_vgpr"] = {"family": "VOP2"}
|
||||
self.rejects(reg, "operand rule vop2_vgpr: not implemented by the decoder")
|
||||
reg["operand_rules"]["vop3_vgpr"] = {"family": "VOP3"}
|
||||
self.rejects(reg, "operand rule vop3_vgpr: not implemented by the decoder")
|
||||
|
||||
def test_rejects_operand_rule_shape_differing_from_the_decoder(self):
|
||||
reg = registry()
|
||||
@@ -395,14 +466,14 @@ class Validate(unittest.TestCase):
|
||||
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)
|
||||
self.rejects(registry(), "S_ASHR_I32: control operand 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)
|
||||
self.rejects(registry(), "S_ASHR_I32: control operand SSRC1 has XML format FMT_NUM_F32", snap)
|
||||
|
||||
def test_rejects_a_float_source_format(self):
|
||||
snap = snapshot()
|
||||
@@ -421,7 +492,7 @@ class Validate(unittest.TestCase):
|
||||
|
||||
def test_renders_the_declared_count_mask(self):
|
||||
self.assertIn(
|
||||
"Self::AshrI32 => primitive::ashr_nonzero_i32(src0, src1 & 0x1f),",
|
||||
"let (value, scc) = primitive::ashr_nonzero_i32(src0, src1 & 0x1f);",
|
||||
gen.render(registry(), snapshot()),
|
||||
)
|
||||
|
||||
@@ -462,6 +533,139 @@ class Validate(unittest.TestCase):
|
||||
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_ariths(self):
|
||||
self.assertEqual(self.errors(ariths()), [])
|
||||
|
||||
def test_rejects_min_with_a_nonzero_scc(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_MIN_I32")["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_MIN_I32: scc nonzero contradicts min/signed (requires selected_src0)")
|
||||
|
||||
def test_rejects_a_select_that_does_not_read_scc(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_CSELECT_B32")["carry_in"] = "none"
|
||||
self.rejects(reg, "S_CSELECT_B32: operation cselect reads SCC (requires carry_in scc)")
|
||||
self.rejects(reg, "S_CSELECT_B32: carry_in none contradicts the XML SCC input")
|
||||
|
||||
def test_rejects_a_select_that_writes_scc(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_CSELECT_B32")["scc"] = "nonzero"
|
||||
self.rejects(reg, "S_CSELECT_B32: scc nonzero contradicts cselect/bitwise (requires unchanged)")
|
||||
self.rejects(reg, "S_CSELECT_B32: scc nonzero contradicts the XML SCC output")
|
||||
|
||||
def test_rejects_a_typed_select(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_CSELECT_B32")["signedness"] = "unsigned"
|
||||
self.rejects(reg, "S_CSELECT_B32: signedness unsigned contradicts operation cselect")
|
||||
|
||||
def test_rejects_a_multiply_that_writes_scc(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_MUL_I32")["scc"] = "signed_overflow"
|
||||
self.rejects(reg, "S_MUL_I32: scc signed_overflow contradicts mul/signed (requires unchanged)")
|
||||
|
||||
def test_rejects_a_bitwise_multiply(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_MUL_HI_U32")["signedness"] = "bitwise"
|
||||
self.rejects(reg, "S_MUL_HI_U32: signedness bitwise contradicts operation mul_hi")
|
||||
|
||||
def test_rejects_a_signed_bfe_descriptor_in_the_xml(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_BFE_I32", "ENC_SOP2")]["operands"] = _operands(I32)
|
||||
self.rejects(ariths(), "S_BFE_I32: control operand SSRC1 has XML format FMT_NUM_I32", snap)
|
||||
|
||||
def test_rejects_a_signed_bfe_data_operand_in_the_xml(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("S_BFE_I32", "ENC_SOP2")]["operands"] = _operands(U32)
|
||||
self.rejects(ariths(), "S_BFE_I32: signedness signed contradicts XML format FMT_NUM_U32", snap)
|
||||
|
||||
def test_rejects_shift_add_without_or_with_a_wrong_amount(self):
|
||||
for amount, shown in ((None, "None"), (0, "0"), (5, "5"), (True, "True"), ("2", "'2'")):
|
||||
with self.subTest(amount=amount):
|
||||
reg = ariths()
|
||||
if amount is None:
|
||||
del form(reg, "S_LSHL2_ADD_U32")["shift_amount"]
|
||||
else:
|
||||
form(reg, "S_LSHL2_ADD_U32")["shift_amount"] = amount
|
||||
self.rejects(reg, f"S_LSHL2_ADD_U32: shift_amount must be one of [1, 2, 3, 4], got {shown}")
|
||||
|
||||
def test_rejects_a_shift_amount_on_another_operation(self):
|
||||
reg = ariths()
|
||||
form(reg, "S_MIN_I32")["shift_amount"] = 1
|
||||
self.rejects(reg, "S_MIN_I32: shift_amount on a non-lshl_add operation")
|
||||
|
||||
def test_renders_alu_scc_as_optional_and_the_declared_data(self):
|
||||
text = gen.render(ariths(), snapshot())
|
||||
self.assertIn("Self::CselectB32 => (primitive::cselect_b32(src0, src1, scc_in), None),", text)
|
||||
self.assertIn("Self::MulHiU32 => (primitive::mul_hi_u32(src0, src1), None),", text)
|
||||
self.assertIn("let (value, scc) = primitive::lshl_add_carry_u32(src0, src1, 2);", text)
|
||||
self.assertIn("let (value, scc) = primitive::min_i32(src0, src1);", text)
|
||||
self.assertIn("Self::CselectB32 => true,", text.split("fn reads_scc", 1)[1].split("}", 1)[0])
|
||||
self.assertIn("Self::CselectB32 => false,", text.split("fn writes_scc", 1)[1].split("}", 1)[0])
|
||||
self.assertIn("shift_amount: 2,", text)
|
||||
self.assertIn("scc: SccEffect::SelectedSrc0,", text)
|
||||
|
||||
def test_accepts_vectors(self):
|
||||
self.assertEqual(self.errors(vectors()), [])
|
||||
|
||||
def test_rejects_a_vector_form_that_writes_scc(self):
|
||||
reg = vectors()
|
||||
form(reg, "V_MIN_I32")["scc"] = "selected_src0"
|
||||
self.rejects(reg, "V_MIN_I32: scc selected_src0 contradicts min/signed (requires unchanged)")
|
||||
|
||||
def test_rejects_a_scalar_only_operation_under_the_vector_rule(self):
|
||||
reg = vectors()
|
||||
form(reg, "V_MUL_I32_I24")["operation"] = "mul"
|
||||
self.rejects(reg, "V_MUL_I32_I24: no primitive implements mul/signed")
|
||||
|
||||
def test_rejects_a_vector_only_operation_under_a_scalar_rule(self):
|
||||
reg = registry()
|
||||
form(reg, "S_ADD_I32")["operation"] = "mul24"
|
||||
self.rejects(reg, "S_ADD_I32: no primitive implements mul24/signed")
|
||||
|
||||
def test_rejects_a_bitwise_24_bit_multiply(self):
|
||||
reg = vectors()
|
||||
form(reg, "V_MUL_I32_I24")["signedness"] = "bitwise"
|
||||
self.rejects(reg, "V_MUL_I32_I24: signedness bitwise contradicts operation mul24")
|
||||
|
||||
def test_rejects_a_source_order_on_a_scalar_form(self):
|
||||
reg = vectors()
|
||||
form(reg, "S_ADD_U32")["source_order"] = "reversed"
|
||||
self.rejects(reg, "S_ADD_U32: source_order on a non-vector form")
|
||||
|
||||
def test_rejects_an_unknown_source_order(self):
|
||||
for order in ("normal", True, ["reversed"]):
|
||||
with self.subTest(order=order):
|
||||
reg = vectors()
|
||||
form(reg, "V_SUBREV_NC_U32")["source_order"] = order
|
||||
self.rejects(reg, f"V_SUBREV_NC_U32: unknown source_order {order!r}")
|
||||
|
||||
def test_rejects_a_duplicate_variant_within_one_enum(self):
|
||||
reg = vectors()
|
||||
form(reg, "V_SUBREV_NC_U32")["variant"] = "MulI32I24"
|
||||
self.rejects(reg, "V_SUBREV_NC_U32: duplicate variant MulI32I24")
|
||||
|
||||
def test_rejects_a_vector_rule_without_its_null_rejection(self):
|
||||
reg = vectors()
|
||||
reg["operand_rules"]["vop2_vgpr"]["unsupported"].remove("src_null")
|
||||
self.rejects(reg, "operand rule vop2_vgpr: unsupported combos differ from those the decoder rejects")
|
||||
|
||||
def test_rejects_an_implicit_vcc_operand_in_the_xml(self):
|
||||
snap = snapshot()
|
||||
snap["variants"][("V_MIN_I32", "ENC_VOP2")]["operands"].append(
|
||||
["", "FMT_NUM_B32", "OPR_VCC", 32, True, False, True, False]
|
||||
)
|
||||
self.rejects(vectors(), "V_MIN_I32: XML implicit operands ['OPR_VCC'] are not declared", snap)
|
||||
|
||||
def test_renders_vector_lowering_and_source_order(self):
|
||||
text = gen.render(vectors(), snapshot())
|
||||
self.assertIn("pub enum VectorAluOp {", text)
|
||||
self.assertIn("if word & 0x8000_0000 != 0x0000_0000 {", text)
|
||||
self.assertIn("Self::MulI32I24 => VectorBinary::Mul24Signed,", text)
|
||||
self.assertIn("Self::SubrevNcU32 => VectorBinary::Sub,", text)
|
||||
self.assertIn("Self::SubrevNcU32 => true,", text.split("fn swaps_sources", 1)[1])
|
||||
self.assertIn('Self::AddU32 => "v_min_i32_e32",', text)
|
||||
self.assertIn("swap_sources: true,", text)
|
||||
|
||||
def test_accepts_compares(self):
|
||||
self.assertEqual(self.errors(compares()), [])
|
||||
|
||||
|
||||
@@ -13,9 +13,14 @@
|
||||
//! compares, branch, SOP2 unsigned
|
||||
//! and signed add and subtract, add-with-carry, subtract-with-borrow, AND, OR
|
||||
//! and XOR, the stage C forms ANDN2, ORN2, NAND, NOR, XNOR, LSHL, LSHR and
|
||||
//! ASHR (32-bit), VOP1 move
|
||||
//! ASHR (32-bit), the 32-bit integer forms MIN/MAX (I32, U32), CSELECT, BFM,
|
||||
//! MUL_I32, BFE (U32, I32), ABSDIFF, LSHL1-4_ADD and MUL_HI (U32, I32), VOP1 move
|
||||
//! (including from an SGPR),
|
||||
//! VOP2 bitwise, shift, arithmetic-shift and float, VOP3 add-no-carry, MUBUF
|
||||
//! VOP2 bitwise, shift, arithmetic-shift and float, the VOP2 integer forms
|
||||
//! MUL_I32_I24, MUL_HI_I32_I24, MUL_U32_U24, MUL_HI_U32_U24, MIN/MAX (I32,
|
||||
//! U32), XNOR and ADD/SUB/SUBREV_NC_U32 (any SRC0 a VOPC compare takes; a
|
||||
//! shift-and-add multiplier and floor division for the high half, the ripple
|
||||
//! adder for add and subtract), VOP3 add-no-carry, MUBUF
|
||||
//! load/store and the two waits plus `s_endpgm`. Anything else is a controlled
|
||||
//! error. The arithmetic shift is evaluated as a floor division by a power of
|
||||
//! two rather than with a host signed shift, so the oracle does not share the
|
||||
@@ -55,7 +60,8 @@ enum Insn {
|
||||
SMov(u8, Src),
|
||||
/// SOP1 unary opcode 7, 11, 13, 15, 17, 19, 21, 23, 25, 26 or 52.
|
||||
SUnary(u32, u8, Src),
|
||||
/// SOP2 opcode 0-5, 14, 16, 18 or an even opcode 20-34.
|
||||
/// SOP2 opcode 0-10, 14, 16, 18, an even opcode 20-36, 38-40, 44, 46-49,
|
||||
/// 53 or 54.
|
||||
SAlu(u32, u8, Src, Src),
|
||||
/// SOPC opcode 0-11: `s_cmp_{eq,lg,gt,ge,lt,le}_i32` then `_u32`.
|
||||
SCmp(u32, Src, Src),
|
||||
@@ -83,6 +89,8 @@ enum Insn {
|
||||
VShiftRight(u8, u8, u8),
|
||||
VShiftRightArithmetic(u8, u8, u8),
|
||||
VXor(u8, u8, u8),
|
||||
/// VOP2 integer opcode 9-12, 17-20, 30 or 37-39: VDST, SRC0, VSRC1.
|
||||
VInt(u32, u8, CmpSrc, u8),
|
||||
VAddF(u8, u8, u8),
|
||||
VMulF(u8, u8, u8),
|
||||
Load(u8),
|
||||
@@ -318,8 +326,87 @@ fn scalar_alu(
|
||||
};
|
||||
let (a, b) = (read(a)?, read(b)?);
|
||||
let carry_in = || scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"));
|
||||
let bit = |word: u32, i: u32| (word >> i) & 1 == 1;
|
||||
let (value, flag) = match opcode {
|
||||
0 => ripple(a, b, false),
|
||||
// RDNA 2 ISA guide 12.1: MIN/MAX pick S0 iff S0 < S1 (> for MAX), the
|
||||
// order a borrow out of S0 - S1 (or S1 - S0) shows; signed forms flip
|
||||
// both sign bits first. SCC = whether S0 was picked (0 on a tie).
|
||||
6..=9 => {
|
||||
let flip = if opcode % 2 == 0 { 0x8000_0000 } else { 0 };
|
||||
let (x, y) = (a ^ flip, b ^ flip);
|
||||
let (p, q) = if opcode < 8 { (x, y) } else { (y, x) };
|
||||
let first = !ripple(p, !q, true).1;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
// CSELECT: D = SCC ? S0 : S1.
|
||||
10 => {
|
||||
let pick_first = carry_in()?;
|
||||
(if pick_first { a } else { b }, false)
|
||||
}
|
||||
// BFM: bit i of D is set iff S1[4:0] <= i < S1[4:0] + S0[4:0].
|
||||
36 => {
|
||||
let (size, start) = (a % 32, b % 32);
|
||||
let value = (0..32)
|
||||
.filter(|&i| i >= start && i < start + size)
|
||||
.fold(0, |d, i| d | 1 << i);
|
||||
(value, false)
|
||||
}
|
||||
// MUL_I32 and MUL_HI: the 64-bit unsigned product by shift and add;
|
||||
// the signed high word subtracts S1 when S0 < 0 and S0 when S1 < 0
|
||||
// (two's complement correction).
|
||||
38 | 53 | 54 => {
|
||||
let product = (0..32)
|
||||
.filter(|&i| bit(b, i))
|
||||
.fold(0_u64, |sum, i| sum + (u64::from(a) << i));
|
||||
let (low, mut high) = (product as u32, (product >> 32) as u32);
|
||||
if opcode == 54 {
|
||||
if bit(a, 31) {
|
||||
high = ripple(high, !b, true).0;
|
||||
}
|
||||
if bit(b, 31) {
|
||||
high = ripple(high, !a, true).0;
|
||||
}
|
||||
}
|
||||
(if opcode == 38 { low } else { high }, false)
|
||||
}
|
||||
// BFE: D[i] = S0[offset + i] for i < width (offset S1[4:0], width
|
||||
// S1[22:16]); positions past bit 31 read 0 (U32) or S0[31] (I32), and
|
||||
// I32 copies D[width - 1] into the bits at and above width. SCC = D != 0.
|
||||
39 | 40 => {
|
||||
let (start, width) = (b % 32, (b >> 16) % 128);
|
||||
let source = |i: u32| match start + i {
|
||||
at @ 0..=31 => bit(a, at),
|
||||
_ => opcode == 40 && bit(a, 31),
|
||||
};
|
||||
let value = (0..32).fold(0, |d, i| {
|
||||
let set = if i < width {
|
||||
source(i)
|
||||
} else {
|
||||
opcode == 40 && width > 0 && source(width - 1)
|
||||
};
|
||||
d | u32::from(set) << i
|
||||
});
|
||||
(value, value != 0)
|
||||
}
|
||||
// ABSDIFF: the 32-bit S0 - S1, negated when bit 31 is set
|
||||
// (0x80000000 stays). SCC = D != 0.
|
||||
44 => {
|
||||
let difference = ripple(a, !b, true).0;
|
||||
let value = if bit(difference, 31) {
|
||||
ripple(!difference, 0, true).0
|
||||
} else {
|
||||
difference
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
// LSHLn_ADD, n = 1-4: D = (S0 << n) + S1; SCC = 1 iff the exact sum
|
||||
// reaches 2^32, i.e. bits shifted out of S0 or a carry out of the add.
|
||||
46..=49 => {
|
||||
let n = opcode - 45;
|
||||
let (value, carry) = ripple(a << n, b, false);
|
||||
(value, carry || a >> (32 - n) != 0)
|
||||
}
|
||||
// RDNA 2 ISA guide 12.1: signed overflow from the sign bits,
|
||||
// add: S0[31] == S1[31] != D[31]; subtract: S0[31] != S1[31] != D[31].
|
||||
2 | 3 => {
|
||||
@@ -372,7 +459,11 @@ fn scalar_alu(
|
||||
}
|
||||
};
|
||||
sgpr[dst as usize] = Some(value);
|
||||
*scc = Some(flag);
|
||||
// CSELECT, BFM, MUL_I32 and MUL_HI have no SCC line in guide 12.1 ("n" in
|
||||
// Tables 11, 12 and 14): SCC stays as it was, possibly unset.
|
||||
if !matches!(opcode, 10 | 36 | 38 | 53 | 54) {
|
||||
*scc = Some(flag);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -593,6 +684,7 @@ fn lane_step(
|
||||
| Insn::VShiftLeft(dst, ..)
|
||||
| Insn::VShiftRight(dst, ..)
|
||||
| Insn::VShiftRightArithmetic(dst, ..)
|
||||
| Insn::VInt(_, dst, ..)
|
||||
| Insn::VAddF(dst, ..)
|
||||
| Insn::VMulF(dst, ..) => {
|
||||
if execution_mask != 0 && lane.vgpr[usize::from(dst)].is_none() {
|
||||
@@ -606,6 +698,22 @@ fn lane_step(
|
||||
Insn::VMovFromVcc(_) => {
|
||||
read_vcc()?;
|
||||
}
|
||||
// Sources must be readable even in an inactive lane.
|
||||
Insn::VInt(_, _, src0, src1) => {
|
||||
match src0 {
|
||||
CmpSrc::Sgpr(reg) => {
|
||||
read_s(reg)?;
|
||||
}
|
||||
CmpSrc::Vcc => {
|
||||
read_vcc()?;
|
||||
}
|
||||
CmpSrc::Vgpr(reg) => {
|
||||
read_vgpr(lane, reg, offset)?;
|
||||
}
|
||||
CmpSrc::Imm(_) => {}
|
||||
}
|
||||
read_vgpr(lane, src1, offset)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -701,6 +809,16 @@ fn lane_step(
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, read_v(a)? ^ read_v(b)?)
|
||||
}
|
||||
Insn::VInt(opcode, dst, src0, src1) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
let a = match src0 {
|
||||
CmpSrc::Sgpr(reg) => read_s(reg)?,
|
||||
CmpSrc::Vcc => read_vcc()?,
|
||||
CmpSrc::Imm(value) => value,
|
||||
CmpSrc::Vgpr(reg) => read_v(reg)?,
|
||||
};
|
||||
(dst, vector_integer(opcode, a, read_v(src1)?))
|
||||
}
|
||||
Insn::VAddF(dst, a, b) => {
|
||||
check_destination(dst, pending_read, offset)?;
|
||||
(dst, exact_float(true, read_v(a)?, read_v(b)?, offset)?)
|
||||
@@ -715,6 +833,78 @@ fn lane_step(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// D of VOP2 integer opcode `opcode` (guide 12.7) for S0 = `a`, S1 = `b`.
|
||||
fn vector_integer(opcode: u32, a: u32, b: u32) -> u32 {
|
||||
// Signed order equals unsigned order after flipping the sign bit.
|
||||
let below = |signed: bool| {
|
||||
let flip = if signed { 0x8000_0000 } else { 0 };
|
||||
(a ^ flip) < (b ^ flip)
|
||||
};
|
||||
match opcode {
|
||||
9 => product_word(multiply_field(a, b, 24, true), false),
|
||||
10 => product_word(multiply_field(a, b, 24, true), true),
|
||||
11 => product_word(multiply_field(a, b, 24, false), false),
|
||||
12 => product_word(multiply_field(a, b, 24, false), true),
|
||||
17 | 19 => {
|
||||
if below(opcode == 17) {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
18 | 20 => {
|
||||
if below(opcode == 18) {
|
||||
b
|
||||
} else {
|
||||
a
|
||||
}
|
||||
}
|
||||
30 => (a & b) | (!a & !b),
|
||||
37 => ripple(a, b, false).0,
|
||||
38 => ripple(a, !b, true).0,
|
||||
_ => ripple(b, !a, true).0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The exact product of the low `width` bits of `a` and `b`, read as two's
|
||||
/// complement when `signed`, by shift-and-add on the magnitudes.
|
||||
fn multiply_field(a: u32, b: u32, width: u32, signed: bool) -> i128 {
|
||||
let read = |value: u32| {
|
||||
let low = i128::from(value) % (1_i128 << width);
|
||||
if signed && low >= 1_i128 << (width - 1) {
|
||||
low - (1_i128 << width)
|
||||
} else {
|
||||
low
|
||||
}
|
||||
};
|
||||
let (x, y) = (read(a), read(b));
|
||||
let (mx, my) = (x.unsigned_abs(), y.unsigned_abs());
|
||||
let mut magnitude = 0_u128;
|
||||
for bit in 0..width {
|
||||
if (my >> bit) & 1 == 1 {
|
||||
magnitude += mx << bit;
|
||||
}
|
||||
}
|
||||
let magnitude = magnitude as i128;
|
||||
if (x < 0) != (y < 0) {
|
||||
-magnitude
|
||||
} else {
|
||||
magnitude
|
||||
}
|
||||
}
|
||||
|
||||
/// Bits 31:0 (or 63:32 when `high`) of `product` in 64-bit two's complement,
|
||||
/// by Euclidean division rather than a shift.
|
||||
fn product_word(product: i128, high: bool) -> u32 {
|
||||
let word = 1_i128 << 32;
|
||||
let part = if high {
|
||||
product.div_euclid(word)
|
||||
} else {
|
||||
product
|
||||
};
|
||||
part.rem_euclid(word) as u32
|
||||
}
|
||||
|
||||
/// Bit-serial addition with carry-in; returns the sum and the carry-out.
|
||||
fn ripple(a: u32, b: u32, carry_in: bool) -> (u32, bool) {
|
||||
let mut carry = carry_in;
|
||||
@@ -853,22 +1043,7 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
193..=198 => (false, opcode - 192),
|
||||
_ => return Err(fail("unsupported VOPC opcode")),
|
||||
};
|
||||
let selector = first & 0x1ff;
|
||||
let (src0, len) = match selector {
|
||||
0..=105 => (CmpSrc::Sgpr(selector as u8), 4),
|
||||
106 => (CmpSrc::Vcc, 4),
|
||||
128..=192 => (CmpSrc::Imm(selector - 128), 4),
|
||||
193..=208 => (CmpSrc::Imm(192u32.wrapping_sub(selector)), 4),
|
||||
255 => (
|
||||
CmpSrc::Imm(
|
||||
word(code, offset + 4)
|
||||
.map_err(|_| format!("{offset:#x}: truncated VOPC literal"))?,
|
||||
),
|
||||
8,
|
||||
),
|
||||
256..=511 => (CmpSrc::Vgpr(selector as u8), 4),
|
||||
_ => return Err(fail("bad VOPC source")),
|
||||
};
|
||||
let (src0, len) = vector_src0(code, offset, first, "VOPC")?;
|
||||
let insn = Insn::VCmp {
|
||||
relation: relation as u8,
|
||||
signed,
|
||||
@@ -877,6 +1052,13 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
};
|
||||
return Ok((insn, len));
|
||||
}
|
||||
// VOP2 integer forms: bit 31 = 0, OP 30:25, VDST 24:17, VSRC1 16:9, SRC0 8:0.
|
||||
let vop2_op = (first >> 25) & 0x3f;
|
||||
if first >> 31 == 0 && matches!(vop2_op, 9..=12 | 17..=20 | 30 | 37..=39) {
|
||||
let (src0, len) = vector_src0(code, offset, first, "VOP2")?;
|
||||
let insn = Insn::VInt(vop2_op, (first >> 17) as u8, src0, (first >> 9) as u8);
|
||||
return Ok((insn, len));
|
||||
}
|
||||
if first & 0xffff_0000 == 0xd525_0000 {
|
||||
let second = word(code, offset + 4)?;
|
||||
let src0 = second & 0x1ff;
|
||||
@@ -910,7 +1092,24 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
if first >> 30 == 0b10
|
||||
&& matches!(
|
||||
(first >> 23) & 0x7f,
|
||||
0..=5 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34
|
||||
0..=10
|
||||
| 14
|
||||
| 16
|
||||
| 18
|
||||
| 20
|
||||
| 22
|
||||
| 24
|
||||
| 26
|
||||
| 28
|
||||
| 30
|
||||
| 32
|
||||
| 34
|
||||
| 36
|
||||
| 38..=40
|
||||
| 44
|
||||
| 46..=49
|
||||
| 53
|
||||
| 54
|
||||
)
|
||||
{
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
@@ -1007,6 +1206,32 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
|
||||
Err(fail("unsupported opcode"))
|
||||
}
|
||||
|
||||
/// SRC0 (bits 8:0 of `first`) of a VOPC or VOP2 integer word: an SGPR,
|
||||
/// `vcc_lo`, an inline integer, a literal dword or a VGPR.
|
||||
fn vector_src0(
|
||||
code: &[u8],
|
||||
offset: usize,
|
||||
first: u32,
|
||||
what: &str,
|
||||
) -> Result<(CmpSrc, usize), String> {
|
||||
let selector = first & 0x1ff;
|
||||
Ok(match selector {
|
||||
0..=105 => (CmpSrc::Sgpr(selector as u8), 4),
|
||||
106 => (CmpSrc::Vcc, 4),
|
||||
128..=192 => (CmpSrc::Imm(selector - 128), 4),
|
||||
193..=208 => (CmpSrc::Imm(192u32.wrapping_sub(selector)), 4),
|
||||
255 => (
|
||||
CmpSrc::Imm(
|
||||
word(code, offset + 4)
|
||||
.map_err(|_| format!("{offset:#x}: truncated {what} literal"))?,
|
||||
),
|
||||
8,
|
||||
),
|
||||
256..=511 => (CmpSrc::Vgpr(selector as u8), 4),
|
||||
_ => return Err(format!("{offset:#x}: bad {what} source")),
|
||||
})
|
||||
}
|
||||
|
||||
fn vector_source(selector: u32) -> Option<Src> {
|
||||
match selector {
|
||||
128..=192 => Some(Src::Imm(selector - 128)),
|
||||
|
||||
@@ -777,6 +777,65 @@ mod review {
|
||||
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;
|
||||
const SCALAR_ARITH_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-arith.bin");
|
||||
// Hand-derived in fixtures/rdna2/scalar-arith.s from the guide's 12.1 pseudocode.
|
||||
const SCALAR_ARITH_KEY: u32 = 0x8115_7dfe;
|
||||
const VECTOR_INTEGER_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/vector-integer.bin");
|
||||
|
||||
/// fixtures/rdna2/vector-integer.s for one lane input `x`, written from the
|
||||
/// guide's 12.7 pseudocode: exact products of the 24-bit fields (sign-
|
||||
/// extended for the I24 forms), D = the low or high 32 bits.
|
||||
fn vector_integer_key(x: u32) -> u32 {
|
||||
let i24 = |v: u32| i64::from(((v << 8) as i32) >> 8);
|
||||
let u24 = |v: u32| i64::from(v & 0x00ff_ffff);
|
||||
let low = |product: i64| product as u32;
|
||||
let high = |product: i64| (product >> 32) as u32;
|
||||
let s8 = 0x0080_0001_u32;
|
||||
let v2 = low(i24(x) * -3);
|
||||
let v3 = high(i24(s8) * i24(x));
|
||||
let v4 = low(0x0012_3456 * u24(x));
|
||||
let v5 = high(u24(s8) * u24(x));
|
||||
let v6 = (x as i32).min(v2 as i32) as u32;
|
||||
let v7 = 5_i32.max(x as i32) as u32;
|
||||
let v8 = v3.min(x);
|
||||
let v9 = s8.max(x);
|
||||
let v10 = !(v4 ^ v5);
|
||||
let v11 = v6.wrapping_add(v7);
|
||||
let v12 = v8.wrapping_sub(v9);
|
||||
let v13 = v11.wrapping_sub(v10);
|
||||
v2 ^ v3 ^ v4 ^ v5 ^ v6 ^ v7 ^ v8 ^ v9 ^ v10 ^ v11 ^ v12 ^ v13
|
||||
}
|
||||
|
||||
/// LLVM-assembled: v_cmp_ne_u32_e32 vcc_lo, 0, v1 then
|
||||
/// v_add_nc_u32_e32 v2, vcc_lo, v1, with the usual load and store.
|
||||
const VCC_LANE_ADD: [u32; 9] = [
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0x7d8a_0280,
|
||||
0x4a04_026a,
|
||||
0xe070_2000,
|
||||
0x8001_0200,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
];
|
||||
|
||||
/// Lane inputs covering both 24-bit signs, the bits above 23, zero and the
|
||||
/// signed and unsigned extremes.
|
||||
const VECTOR_INTEGER_INPUT: [u32; 12] = [
|
||||
0,
|
||||
1,
|
||||
5,
|
||||
0x007f_ffff,
|
||||
0x0080_0000,
|
||||
0x00ff_ffff,
|
||||
0x0123_4567,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x89ab_cdef,
|
||||
0xff80_0001,
|
||||
u32::MAX,
|
||||
];
|
||||
// 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] = [
|
||||
@@ -923,6 +982,83 @@ mod review {
|
||||
verify(&set, &input, Some(&[0; 5]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_integer_fixture_computes_each_lane_from_its_input() {
|
||||
let expected: Vec<_> = VECTOR_INTEGER_INPUT
|
||||
.iter()
|
||||
.map(|&x| vector_integer_key(x))
|
||||
.collect();
|
||||
verify(
|
||||
VECTOR_INTEGER_FIXTURE,
|
||||
&VECTOR_INTEGER_INPUT,
|
||||
Some(&expected),
|
||||
);
|
||||
// The results stay runtime per-lane values: the only constants are the
|
||||
// six uniform SRC0 operands (-3, s8 three times, the literal and 5), and
|
||||
// the twelve lane inputs give twelve different results.
|
||||
let compiled = compile(Architecture::Gfx1030, VECTOR_INTEGER_FIXTURE).unwrap();
|
||||
assert!(compiled.ir.contains("mul24.i32 t1, t0"), "{}", compiled.ir);
|
||||
assert!(compiled.msl.contains("mulhi("), "{}", compiled.msl);
|
||||
assert_eq!(
|
||||
compiled.ir.matches(" = const.u32 ").count(),
|
||||
6,
|
||||
"{}",
|
||||
compiled.ir
|
||||
);
|
||||
let distinct: std::collections::BTreeSet<_> = expected.iter().collect();
|
||||
assert_eq!(distinct.len(), expected.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_integer_reads_a_lane_derived_vcc_lo() {
|
||||
// LLVM: v_cmp_ne_u32_e32 vcc_lo, 0, v1; v_add_nc_u32_e32 v2, vcc_lo, v1.
|
||||
// Lane 0 (x = 0) fails the compare and lane 1 (x = 7) passes, so the
|
||||
// mask is 0b10 and every lane adds 2.
|
||||
let code = words(&VCC_LANE_ADD);
|
||||
verify(&code, &[0, 7], Some(&[2, 9]));
|
||||
verify(&code, &[7, 7], Some(&[10, 10]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_integer_is_refused_in_a_runtime_vccz_skip_region() {
|
||||
// LLVM: v_mov_b32 v2, 0; v_cmp_ne_u32 vcc_lo, 0, v1; s_cbranch_vccz
|
||||
// over v_add_nc_u32_e32 v2, vcc_lo, v1 (at 0x18), whatever the mask.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
0x7e04_0280,
|
||||
0x7d8a_0280,
|
||||
0xbf86_0001,
|
||||
0x4a04_026a,
|
||||
0xe070_2000,
|
||||
0x8001_0200,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
rejected_at_with(&code, 0x18, &[0, 7]);
|
||||
rejected_at_with(&code, 0x18, &[7, 7]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_arith_fixture_chains_registry_arithmetic_forms() {
|
||||
let input = [0, 1, u32::MAX, SCALAR_ARITH_KEY, 0x1234_5678];
|
||||
let expected: Vec<_> = input.iter().map(|word| word ^ SCALAR_ARITH_KEY).collect();
|
||||
verify(SCALAR_ARITH_FIXTURE, &input, Some(&expected));
|
||||
let compiled = compile(Architecture::Gfx1030, SCALAR_ARITH_FIXTURE).unwrap();
|
||||
assert!(compiled.disassembly.contains("s_lshl2_add_u32 s25, s9, s9"));
|
||||
// SCC stays clear across the CSELECT and MUL_HI that follow
|
||||
// s_lshl2_add_u32 s25, s9, s9: with s_lshl2_add_u32 s25, s9, -1 instead,
|
||||
// 20 + 0xffffffff carries, SCC = 1 and v2 = 0.
|
||||
let mut set = SCALAR_ARITH_FIXTURE.to_vec();
|
||||
let at = set
|
||||
.windows(4)
|
||||
.position(|word| word == [0x09, 0x09, 0x99, 0x97])
|
||||
.unwrap();
|
||||
set[at + 1] = 0xc1;
|
||||
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]) {
|
||||
@@ -1074,8 +1210,8 @@ mod review {
|
||||
#[test]
|
||||
fn scalar_alu_rejects_forms_outside_the_subset() {
|
||||
// load 8, wait 4, two literal moves 8 each, s_cmp 4: the SOP2 word is at 0x20.
|
||||
for opcode in [6, 15, 17, 19] {
|
||||
// s_min_i32 and the 64-bit bitwise forms.
|
||||
for opcode in [11, 15, 17, 19] {
|
||||
// s_cselect_b64 and the 64-bit bitwise forms.
|
||||
rejected_at(
|
||||
&sop2_program(&[sop2(opcode, 10, 8, 9)], 10, 1, 2, Some(false)),
|
||||
0x20,
|
||||
@@ -1149,6 +1285,14 @@ mod review {
|
||||
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 arith: Vec<_> = input.iter().map(|word| word ^ SCALAR_ARITH_KEY).collect();
|
||||
assert_eq!(run(SCALAR_ARITH_FIXTURE, &input), arith);
|
||||
let lanes: Vec<_> = VECTOR_INTEGER_INPUT
|
||||
.iter()
|
||||
.map(|&x| vector_integer_key(x))
|
||||
.collect();
|
||||
assert_eq!(run(VECTOR_INTEGER_FIXTURE, &VECTOR_INTEGER_INPUT), lanes);
|
||||
assert_eq!(run(&words(&VCC_LANE_ADD), &[0, 7]), [2, 9]);
|
||||
let mut vectors = sop2_vectors();
|
||||
vectors.extend(sop2_operand_cases());
|
||||
vectors.extend(signed_immediate_overflows());
|
||||
@@ -1156,8 +1300,8 @@ mod review {
|
||||
assert_eq!(&run(code, &[0, u32::MAX]), expected);
|
||||
}
|
||||
eprintln!(
|
||||
"{} SOP2 programs matched on native Metal",
|
||||
vectors.len() + 4
|
||||
"{} SOP2 programs and fixtures matched on native Metal",
|
||||
vectors.len() + 7
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,589 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent expected values for sixteen 32-bit SOP2 integer forms (#215):
|
||||
//! `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`,
|
||||
//! `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`,
|
||||
//! `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.1 "SOP2 Instructions"
|
||||
//! (pseudocode and the ABSDIFF functional examples), Tables 11, 12 and 14 in
|
||||
//! section 5 (which forms set SCC, and that CSELECT reads it), section 13.1.1
|
||||
//! for the SOP2 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.
|
||||
//!
|
||||
//! Reading of the pseudocode where the guide leaves C-like operators open:
|
||||
//! arithmetic is exact (unbounded integers, as the guide's own
|
||||
//! `>= 0x100000000ULL` carry tests require) and D keeps the low 32 bits. So a
|
||||
//! BFE width of 32 or more gives an all-ones mask, and LSHLn_ADD's SCC is the
|
||||
//! carry out of the whole `(S0 << N) + S1`, including bits shifted out of S0.
|
||||
//! These are guide readings, not hardware evidence.
|
||||
|
||||
#[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 sixteen forms with their ENC_SOP2 opcodes (guide 12.1).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Form {
|
||||
MinI32 = 6,
|
||||
MinU32 = 7,
|
||||
MaxI32 = 8,
|
||||
MaxU32 = 9,
|
||||
Cselect = 10,
|
||||
Bfm = 36,
|
||||
Mul = 38,
|
||||
BfeU32 = 39,
|
||||
BfeI32 = 40,
|
||||
Absdiff = 44,
|
||||
Lshl1Add = 46,
|
||||
Lshl2Add = 47,
|
||||
Lshl3Add = 48,
|
||||
Lshl4Add = 49,
|
||||
MulHiU32 = 53,
|
||||
MulHiI32 = 54,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 16] = [
|
||||
(Form::MinI32, "s_min_i32"),
|
||||
(Form::MinU32, "s_min_u32"),
|
||||
(Form::MaxI32, "s_max_i32"),
|
||||
(Form::MaxU32, "s_max_u32"),
|
||||
(Form::Cselect, "s_cselect_b32"),
|
||||
(Form::Bfm, "s_bfm_b32"),
|
||||
(Form::Mul, "s_mul_i32"),
|
||||
(Form::BfeU32, "s_bfe_u32"),
|
||||
(Form::BfeI32, "s_bfe_i32"),
|
||||
(Form::Absdiff, "s_absdiff_i32"),
|
||||
(Form::Lshl1Add, "s_lshl1_add_u32"),
|
||||
(Form::Lshl2Add, "s_lshl2_add_u32"),
|
||||
(Form::Lshl3Add, "s_lshl3_add_u32"),
|
||||
(Form::Lshl4Add, "s_lshl4_add_u32"),
|
||||
(Form::MulHiU32, "s_mul_hi_u32"),
|
||||
(Form::MulHiI32, "s_mul_hi_i32"),
|
||||
];
|
||||
|
||||
/// BFE's S1 fields (guide 12.1): "S1[4:0] is field offset, S1[22:16] is field
|
||||
/// width", so the width is seven bits (0-127) and bits 5-15 and 23-31 are
|
||||
/// ignored.
|
||||
fn field(s1: u32) -> (u32, u32) {
|
||||
(s1 & 0x1f, (s1 >> 16) & 0x7f)
|
||||
}
|
||||
|
||||
/// `(1 << width) - 1` in exact arithmetic.
|
||||
fn mask(width: u32) -> i128 {
|
||||
((1u128 << width) - 1) as i128
|
||||
}
|
||||
|
||||
/// The guide's D for `form` with S0 = `s0`, S1 = `s1` and SCC = `scc` before
|
||||
/// it, and the SCC after it: `Some` for the forms that write SCC, `None` for
|
||||
/// those that leave it unchanged. Only CSELECT reads `scc`.
|
||||
fn expect(form: Form, s0: u32, s1: u32, scc: bool) -> (u32, Option<bool>) {
|
||||
let (i0, i1) = (i128::from(s0 as i32), i128::from(s1 as i32));
|
||||
let (u0, u1) = (i128::from(s0), i128::from(s1));
|
||||
// D keeps the low 32 bits of the exact result.
|
||||
let low = |exact: i128| exact as u32;
|
||||
let not_zero = |d: u32| (d, Some(d != 0));
|
||||
match form {
|
||||
// 6 S_MIN_I32: D.i = (S0.i < S1.i) ? S0.i : S1.i; SCC = (S0.i < S1.i).
|
||||
// Equal operands give S1 (the same value) and SCC = 0; Table 11's
|
||||
// "SCC = 1 if S0 was min" agrees only if a tie does not count as S0.
|
||||
Form::MinI32 => (if i0 < i1 { s0 } else { s1 }, Some(i0 < i1)),
|
||||
// 7 S_MIN_U32: D.u = (S0.u < S1.u) ? S0.u : S1.u; SCC = (S0.u < S1.u).
|
||||
Form::MinU32 => (if u0 < u1 { s0 } else { s1 }, Some(u0 < u1)),
|
||||
// 8 S_MAX_I32: D.i = (S0.i > S1.i) ? S0.i : S1.i; SCC = (S0.i > S1.i).
|
||||
Form::MaxI32 => (if i0 > i1 { s0 } else { s1 }, Some(i0 > i1)),
|
||||
// 9 S_MAX_U32: D.u = (S0.u > S1.u) ? S0.u : S1.u; SCC = (S0.u > S1.u).
|
||||
Form::MaxU32 => (if u0 > u1 { s0 } else { s1 }, Some(u0 > u1)),
|
||||
// 10 S_CSELECT_B32: D.u = SCC ? S0.u : S1.u. Table 12: "Sets SCC? n".
|
||||
Form::Cselect => (if scc { s0 } else { s1 }, None),
|
||||
// 36 S_BFM_B32: D.u = ((1 << S0.u[4:0]) - 1) << S1.u[4:0]. Table 14:
|
||||
// "Sets SCC? n".
|
||||
Form::Bfm => (low(mask(s0 & 0x1f) << (s1 & 0x1f)), None),
|
||||
// 38 S_MUL_I32: D.i = S0.i * S1.i; Table 11: "Low 32 bits of result",
|
||||
// "Sets SCC? n".
|
||||
Form::Mul => (low(i0 * i1), None),
|
||||
// 39 S_BFE_U32: D.u = (S0.u >> S1.u[4:0]) & ((1 << S1.u[22:16]) - 1);
|
||||
// SCC = (D.u != 0). Width 0 gives 0; bits past bit 31 of S0 are 0.
|
||||
Form::BfeU32 => {
|
||||
let (offset, width) = field(s1);
|
||||
not_zero(low((u0 >> offset) & mask(width)))
|
||||
}
|
||||
// 40 S_BFE_I32: D.i = signext((S0.i >> S1.u[4:0]) & ((1 << S1.u[22:16])
|
||||
// - 1)); SCC = (D.i != 0). Section 5.7: "Bit Field Extract, then
|
||||
// sign-extend result", i.e. from the field's top bit, width - 1. S0.i
|
||||
// shifts arithmetically, so a field past bit 31 is filled with S0[31].
|
||||
// Width 0 gives 0.
|
||||
Form::BfeI32 => {
|
||||
let (offset, width) = field(s1);
|
||||
let bits = (i0 >> offset) & mask(width);
|
||||
let d = if width > 0 && (bits >> (width - 1)) & 1 == 1 {
|
||||
bits.wrapping_sub(1i128.wrapping_shl(width))
|
||||
} else {
|
||||
bits
|
||||
};
|
||||
not_zero(low(d))
|
||||
}
|
||||
// 44 S_ABSDIFF_I32: D.i = S0.i - S1.i; if (D.i < 0) D.i = -D.i;
|
||||
// SCC = (D.i != 0). D.i is 32-bit: the functional examples give
|
||||
// (0x80000000, 1) => 0x7fffffff and keep 0x80000000 for
|
||||
// (0x80000000, 0), so the difference wraps before the negation.
|
||||
Form::Absdiff => {
|
||||
let d = (s0 as i32).wrapping_sub(s1 as i32);
|
||||
not_zero(if d < 0 { d.wrapping_neg() } else { d } as u32)
|
||||
}
|
||||
// 46-49 S_LSHLn_ADD_U32: D.u = (S0.u << N) + S1.u; SCC = (((S0.u << N)
|
||||
// + S1.u) >= 0x100000000ULL ? 1 : 0), N = 1, 2, 3, 4.
|
||||
Form::Lshl1Add | Form::Lshl2Add | Form::Lshl3Add | Form::Lshl4Add => {
|
||||
let n = form as u32 - 45;
|
||||
let exact = (u0 << n) + u1;
|
||||
(low(exact), Some(exact >= 1 << 32))
|
||||
}
|
||||
// 53 S_MUL_HI_U32: D.u = (S0.u * S1.u) >> 32. No SCC line.
|
||||
Form::MulHiU32 => (low((u0 * u1) >> 32), None),
|
||||
// 54 S_MUL_HI_I32: D.i = (S0.i * S1.i) >> 32 (signed). No SCC line.
|
||||
Form::MulHiI32 => (low((i0 * i1) >> 32), None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The ABSDIFF functional examples printed in guide 12.1, with D only, and
|
||||
/// direct readings of other one-line pseudocode.
|
||||
const GUIDE_EXAMPLES: [(Form, u32, u32, u32); 18] = [
|
||||
(Form::Absdiff, 0x0000_0002, 0x0000_0005, 0x0000_0003),
|
||||
(Form::Absdiff, 0xffff_ffff, 0x0000_0000, 0x0000_0001),
|
||||
(Form::Absdiff, 0x8000_0000, 0x0000_0000, 0x8000_0000),
|
||||
(Form::Absdiff, 0x8000_0000, 0x0000_0001, 0x7fff_ffff),
|
||||
(Form::Absdiff, 0x8000_0000, 0xffff_ffff, 0x7fff_ffff),
|
||||
(Form::Absdiff, 0x8000_0000, 0xffff_fffe, 0x7fff_fffe),
|
||||
// Not printed as examples.
|
||||
(Form::Bfm, 4, 8, 0x0000_0f00),
|
||||
(Form::Bfm, 31, 1, 0xffff_fffe),
|
||||
(Form::Bfm, 32, 0, 0),
|
||||
(Form::BfeU32, 0x1234_5678, 0x0008_0004, 0x0000_0067),
|
||||
(Form::BfeU32, 0x8000_0000, 0x0004_001f, 0x0000_0001),
|
||||
(Form::BfeI32, 0x0000_0080, 0x0008_0000, 0xffff_ff80),
|
||||
(Form::BfeI32, 0x8000_0000, 0x0004_001f, 0xffff_ffff),
|
||||
(Form::BfeI32, 0x1234_5678, 0x0040_0000, 0x1234_5678),
|
||||
(Form::MulHiU32, 0xffff_ffff, 0xffff_ffff, 0xffff_fffe),
|
||||
(Form::MulHiI32, 0xffff_ffff, 0xffff_ffff, 0x0000_0000),
|
||||
(Form::MulHiI32, 0x8000_0000, 0x8000_0000, 0x4000_0000),
|
||||
(Form::Lshl4Add, 0x1000_0000, 0x0000_0001, 0x0000_0001),
|
||||
];
|
||||
|
||||
/// 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, their neighbours and alternating patterns; all pairs include
|
||||
/// the equal pairs that are MIN/MAX ties.
|
||||
const VALUES: [u32; 13] = [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
0xaaaa_aaaa,
|
||||
0x5555_5555,
|
||||
0x1234_5678,
|
||||
0x0000_ffff,
|
||||
0xffff_0000,
|
||||
];
|
||||
/// BFE widths around 0, 32 and the seven-bit field, and offsets around 0, 31
|
||||
/// and the five-bit field.
|
||||
const WIDTHS: [u32; 10] = [0, 1, 2, 8, 16, 31, 32, 33, 64, 127];
|
||||
const OFFSETS: [u32; 8] = [0, 1, 4, 16, 28, 31, 32, 63];
|
||||
/// S1 words with bit 23 (just above the width) or every ignored bit set.
|
||||
const BFE_EXTRA: [u32; 2] = [0x0084_0004, 0xff80_ffe4];
|
||||
/// BFM sizes and offsets around the five-bit fields.
|
||||
const BFM_FIELDS: [u32; 9] = [0, 1, 4, 16, 31, 32, 33, 63, 0xffff_ffe1];
|
||||
const INPUT: [u32; 2] = [0, u32::MAX];
|
||||
|
||||
const COUNTS: [(&str, usize); 7] = [
|
||||
("sop2 arith domain", 16 * 13 * 13 * 2),
|
||||
("sop2 arith bit field", (2 * 13 * (10 * 8 + 2) + 9 * 9) * 2),
|
||||
("sop2 arith guide example", 18 * 2),
|
||||
("sop2 arith aliasing", 16 * 2 * 5 * 2),
|
||||
("sop2 arith inline integer", 16 * 81 * 2 * 2 * 2),
|
||||
("sop2 arith literal", 16 * 6 * 2 * 2),
|
||||
("sop2 arith max register", 16 * 4 * 2),
|
||||
];
|
||||
/// Per form: two literals, 6 destinations and 15 sources in each slot outside
|
||||
/// the supported subset; and CSELECT with SCC never written.
|
||||
const REJECTIONS: usize = 16 * (1 + 6 + 2 * 15) + 1 + 4;
|
||||
|
||||
/// ENCODING 0b10 in bits 30-31, OP 23-29, SDST 16-22, SSRC1 8-15, SSRC0 0-7
|
||||
/// (guide 13.1.1).
|
||||
fn sop2(op: u32, dst: u32, src0: u32, src1: u32) -> u32 {
|
||||
0x8000_0000 | op << 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` (or leave it unwritten for `None`), 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 [R, R] when SCC is clear after `alu`
|
||||
/// and [R, !R] when it is set.
|
||||
fn program(init: &[(u32, u32)], scc: Option<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]);
|
||||
}
|
||||
match scc {
|
||||
Some(true) => code.push(0xbf06_8080),
|
||||
Some(false) => code.push(0xbf06_8180),
|
||||
None => {}
|
||||
}
|
||||
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` on `s0`, `s1` with 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, s1): (u32, u32),
|
||||
scc: bool,
|
||||
r: Option<u32>,
|
||||
) -> Case {
|
||||
let (d, written) = expect(form, s0, s1, scc);
|
||||
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 pairs(form: Form) -> Vec<(u32, u32, &'static str)> {
|
||||
let mut all: Vec<_> = VALUES
|
||||
.iter()
|
||||
.flat_map(|&a| VALUES.map(|b| (a, b, "sop2 arith domain")))
|
||||
.collect();
|
||||
let family = "sop2 arith bit field";
|
||||
if matches!(form, Form::BfeU32 | Form::BfeI32) {
|
||||
let fields = WIDTHS
|
||||
.iter()
|
||||
.flat_map(|&w| OFFSETS.map(|o| w << 16 | o))
|
||||
.chain(BFE_EXTRA);
|
||||
let fields: Vec<_> = fields.collect();
|
||||
all.extend(
|
||||
VALUES
|
||||
.iter()
|
||||
.flat_map(|&a| fields.iter().map(move |&b| (a, b, family))),
|
||||
);
|
||||
}
|
||||
if form == Form::Bfm {
|
||||
all.extend(
|
||||
BFM_FIELDS
|
||||
.iter()
|
||||
.flat_map(|&a| BFM_FIELDS.map(|b| (a, b, family))),
|
||||
);
|
||||
}
|
||||
let examples = GUIDE_EXAMPLES.iter().filter(|example| example.0 == form);
|
||||
all.extend(examples.map(|example| (example.1, example.2, "sop2 arith guide example")));
|
||||
all
|
||||
}
|
||||
|
||||
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 alu = [sop2(op, 10, 8, 9)];
|
||||
for (a, b, family) in pairs(form) {
|
||||
let code = program(&[(8, a), (9, b)], Some(scc), &alu, 10);
|
||||
let label = format!("{a:#x}, {b:#x}");
|
||||
cases.push(case((form, name), family, label, code, (a, b), scc, None));
|
||||
}
|
||||
// dst/src aliasing with s8 = a, s9 = b.
|
||||
for (a, b) in [(0xffff_fff0, 0x0008_0004), (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 alu = [sop2(op, dst, src0, src1)];
|
||||
let code = program(&[(8, a), (9, b)], Some(scc), &alu, dst);
|
||||
let label = format!("s{dst} = s{src0}, s{src1} ({a:#x}, {b:#x})");
|
||||
let operands = (pick(src0), pick(src1));
|
||||
let family = "sop2 arith aliasing";
|
||||
cases.push(case((form, name), family, label, code, operands, scc, None));
|
||||
}
|
||||
}
|
||||
// Every integer inline constant (-16..64) in each source slot. The
|
||||
// register operand s8 takes two words chosen so a wrong inline value
|
||||
// changes D for at least one of them; as a BFE S1 they are fields
|
||||
// (width 8, offset 0) and (width 32, offset 1).
|
||||
let bfe = matches!(form, Form::BfeU32 | Form::BfeI32);
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
for slot in 0..2 {
|
||||
let others = if slot == 0 && bfe {
|
||||
[0x0008_0000, 0x0020_0001]
|
||||
} else {
|
||||
[0x8000_0f0f, 0x7fff_f0f0]
|
||||
};
|
||||
for other in others {
|
||||
let (alu, operands) = if slot == 0 {
|
||||
(sop2(op, 10, selector, 8), (value, other))
|
||||
} else {
|
||||
(sop2(op, 10, 8, selector), (other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], Some(scc), &[alu], 10);
|
||||
let label = format!("inline {value:#x} in src{slot}, s8 {other:#x}");
|
||||
let family = "sop2 arith inline integer";
|
||||
cases.push(case((form, name), family, label, code, operands, scc, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
// The highest SGPR, s105 (0b1101001), as destination, either
|
||||
// source or all three; s8 and s105 differ in sign and as BFE fields.
|
||||
let (a, b, top) = (0x0004_0001, 0x0003_0002, 0x8000_0006);
|
||||
for (dst, src0, src1) in [(105, 8, 9), (10, 105, 8), (10, 8, 105), (105, 105, 105)] {
|
||||
let pick = |reg| match reg {
|
||||
8 => a,
|
||||
9 => b,
|
||||
_ => top,
|
||||
};
|
||||
let alu = [sop2(op, dst, src0, src1)];
|
||||
let code = program(&[(8, a), (9, b), (105, top)], Some(scc), &alu, dst);
|
||||
let label = format!("s{dst} = s{src0}, s{src1}");
|
||||
let operands = (pick(src0), pick(src1));
|
||||
let family = "sop2 arith max register";
|
||||
cases.push(case((form, name), family, label, code, operands, scc, None));
|
||||
}
|
||||
// A 32-bit literal dword after the SOP2 word in each source slot.
|
||||
for value in [0, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX, 0x0021_0003] {
|
||||
for slot in 0..2 {
|
||||
let other = 0xc005_0003;
|
||||
let (alu, operands) = if slot == 0 {
|
||||
([sop2(op, 10, LITERAL, 8), value], (value, other))
|
||||
} else {
|
||||
([sop2(op, 10, 8, LITERAL), value], (other, value))
|
||||
};
|
||||
let code = program(&[(8, other)], Some(scc), &alu, 10);
|
||||
let label = format!("literal {value:#x} in src{slot}");
|
||||
let family = "sop2 arith literal";
|
||||
cases.push(case((form, name), family, label, code, operands, scc, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// The SOP2 word's byte offset in `program` with two init pairs and the SCC
|
||||
/// preset.
|
||||
const ALU_OFFSET: usize = 12 + 16 + 4;
|
||||
|
||||
/// Programs both interpreters must refuse at the SOP2 word, with that offset.
|
||||
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
|
||||
let init = [(8, 1), (9, 2)];
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
// Guide 12.1 (SOP2 note): at most one literal; two are refused.
|
||||
let alu = [sop2(op, 10, LITERAL, LITERAL), 1];
|
||||
let code = program(&init, Some(false), &alu, 10);
|
||||
all.push((format!("{name} two literals"), code, ALU_OFFSET));
|
||||
// VCC_LO, VCC_HI, M0, NULL, EXEC_LO, EXEC_HI as SDST.
|
||||
for dst in [106, 107, 124, 125, 126, 127] {
|
||||
let code = program(&init, Some(false), &[sop2(op, dst, 8, 9)], 10);
|
||||
all.push((format!("{name} destination {dst}"), code, ALU_OFFSET));
|
||||
}
|
||||
// VCC_LO, VCC_HI, M0, EXEC_LO, EXEC_HI, SCC, and the float inline
|
||||
// constants 240-248 in either source slot.
|
||||
for src in [106, 107, 124, 126, 127, 253].into_iter().chain(240..=248) {
|
||||
for (src0, src1, slot) in [(src, 9, 0), (8, src, 1)] {
|
||||
let code = program(&init, Some(false), &[sop2(op, 10, src0, src1)], 10);
|
||||
all.push((format!("{name} src{slot} {src}"), code, ALU_OFFSET));
|
||||
}
|
||||
}
|
||||
}
|
||||
// CSELECT reads SCC; here nothing has written it.
|
||||
let code = program(&init, None, &[sop2(Form::Cselect as u32, 10, 8, 9)], 10);
|
||||
all.push(("s_cselect_b32 with SCC unset".into(), code, ALU_OFFSET - 4));
|
||||
// The forms that leave SCC unchanged must keep it unset, so a CSELECT after
|
||||
// them is still refused (at the CSELECT, the second ALU word).
|
||||
for form in [Form::Bfm, Form::Mul, Form::MulHiU32, Form::MulHiI32] {
|
||||
let alu = [
|
||||
sop2(form as u32, 10, 8, 9),
|
||||
sop2(Form::Cselect as u32, 11, 8, 9),
|
||||
];
|
||||
let code = program(&init, None, &alu, 11);
|
||||
all.push((
|
||||
format!("{form:?} then s_cselect_b32 with SCC unset"),
|
||||
code,
|
||||
ALU_OFFSET,
|
||||
));
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn assert_rejected_at(label: &str, code: &[u8], offset: usize) {
|
||||
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}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
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, s1, d) in GUIDE_EXAMPLES {
|
||||
assert_eq!(
|
||||
expect(form, s0, s1, false).0,
|
||||
d,
|
||||
"{form:?}({s0:#x}, {s1:#x})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop2_arith_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_arith: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sop2_arith_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_arith: {} independent-interpreter cases", cases.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_sop2_arith_operands_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code, offset) in &rejections {
|
||||
assert_rejected_at(label, code, *offset);
|
||||
}
|
||||
eprintln!("sop2_arith: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_sop2_opcodes_stay_unsupported() {
|
||||
// Every SOP2 opcode (0-95; 96 and up are other encodings) except the
|
||||
// earlier stages' forms (0-5 and the even opcodes 14-34) and these
|
||||
// sixteen. Sources and destination are aligned pairs, all initialized, so
|
||||
// a 64-bit form would read and write only set registers.
|
||||
let earlier = (0..=5).chain((14..=34).step_by(2));
|
||||
let supported: Vec<u32> = FORMS
|
||||
.iter()
|
||||
.map(|&(form, _)| form as u32)
|
||||
.chain(earlier)
|
||||
.collect();
|
||||
let init = [(8, 1), (9, 2), (12, 3), (13, 4)];
|
||||
for op in (0..=95).filter(|op| !supported.contains(op)) {
|
||||
let code = program(&init, Some(false), &[sop2(op, 10, 8, 12)], 10);
|
||||
assert_rejected_at(&format!("opcode {op}"), &code, 12 + 32 + 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn sop2_arith_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, offset) in rejections() {
|
||||
// Refused at the same word as by the interpreters, so a later failure
|
||||
// cannot stand in.
|
||||
let at = match compile(Architecture::Gfx1030, &code) {
|
||||
Err(CompileError::Decode(error)) => error.offset,
|
||||
Err(CompileError::Verify { offset, .. }) => offset,
|
||||
other => panic!("compiler did not reject {label}: {other:?}"),
|
||||
};
|
||||
assert_eq!(at, offset, "compiler rejected {label} elsewhere");
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"sop2_arith: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,786 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent per-lane expected values for twelve 32-bit VOP2 integer forms
|
||||
//! (#215): `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`,
|
||||
//! `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`,
|
||||
//! `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32`, all
|
||||
//! `_e32`.
|
||||
//!
|
||||
//! The expectations are written below from the public AMD "RDNA 2" Instruction
|
||||
//! Set Architecture Reference Guide only: section 12.7 "VOP2 Instructions"
|
||||
//! (pseudocode and descriptions), section 13.3.1 for the VOP2 word and the
|
||||
//! vector operand table for SRC0 (SGPRs, `vcc_lo`, inline integers, the
|
||||
//! literal, VGPRs). Nothing here comes from the ISA crate, the semantic
|
||||
//! registry, the decoder or the shader compiler. Every case runs on the
|
||||
//! reference interpreter `xenora_ref` and on the second interpreter
|
||||
//! `independent_ref`; the ignored test also runs the translated MSL on native
|
||||
//! Metal.
|
||||
//!
|
||||
//! Readings of the guide (not hardware evidence):
|
||||
//! - `.i24` / `.u24` read bits 23:0 of a source; `.i24` sign-extends bit 23.
|
||||
//! The product is exact (at most 48 bits); MUL_* keep bits 31:0 and MUL_HI_*
|
||||
//! bits 63:32 of the 64-bit two's-complement (I24) or unsigned (U24) value,
|
||||
//! so `>> 32` is arithmetic for the signed form.
|
||||
//! - SUBREV is `D = S1 - S0`; the `_NC` forms have "no carry-in or
|
||||
//! carry-out", so none of the twelve writes VCC or SCC.
|
||||
//! - MAX uses `S0 >= S1 ? S0 : S1`; on a tie both choices are the same value.
|
||||
//! - A lane whose EXEC bit is clear keeps its old VDST (guide section 3.3).
|
||||
|
||||
#[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 twelve forms with their ENC_VOP2 opcodes (guide 12.7).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Form {
|
||||
MulI24 = 9,
|
||||
MulHiI24 = 10,
|
||||
MulU24 = 11,
|
||||
MulHiU24 = 12,
|
||||
MinI32 = 17,
|
||||
MaxI32 = 18,
|
||||
MinU32 = 19,
|
||||
MaxU32 = 20,
|
||||
Xnor = 30,
|
||||
AddNc = 37,
|
||||
SubNc = 38,
|
||||
SubrevNc = 39,
|
||||
}
|
||||
|
||||
const FORMS: [(Form, &str); 12] = [
|
||||
(Form::MulI24, "v_mul_i32_i24"),
|
||||
(Form::MulHiI24, "v_mul_hi_i32_i24"),
|
||||
(Form::MulU24, "v_mul_u32_u24"),
|
||||
(Form::MulHiU24, "v_mul_hi_u32_u24"),
|
||||
(Form::MinI32, "v_min_i32"),
|
||||
(Form::MaxI32, "v_max_i32"),
|
||||
(Form::MinU32, "v_min_u32"),
|
||||
(Form::MaxU32, "v_max_u32"),
|
||||
(Form::Xnor, "v_xnor_b32"),
|
||||
(Form::AddNc, "v_add_nc_u32"),
|
||||
(Form::SubNc, "v_sub_nc_u32"),
|
||||
(Form::SubrevNc, "v_subrev_nc_u32"),
|
||||
];
|
||||
|
||||
/// `S.i24`: bits 23:0, sign-extended from bit 23.
|
||||
fn i24(s: u32) -> i64 {
|
||||
let field = i64::from(s & 0x00ff_ffff);
|
||||
if field >= 1 << 23 {
|
||||
field - (1 << 24)
|
||||
} else {
|
||||
field
|
||||
}
|
||||
}
|
||||
|
||||
/// `S.u24`: bits 23:0, zero-extended.
|
||||
fn u24(s: u32) -> i64 {
|
||||
i64::from(s & 0x00ff_ffff)
|
||||
}
|
||||
|
||||
/// The guide's D for `form` with S0 = `s0` and S1 = `s1`. Arithmetic is exact
|
||||
/// in i64; `as u32` keeps the low 32 bits.
|
||||
fn expect(form: Form, s0: u32, s1: u32) -> u32 {
|
||||
let (i0, i1) = (i64::from(s0 as i32), i64::from(s1 as i32));
|
||||
let (u0, u1) = (i64::from(s0), i64::from(s1));
|
||||
match form {
|
||||
// 9 V_MUL_I32_I24: D.i32 = S0.i24 * S1.i24.
|
||||
Form::MulI24 => (i24(s0) * i24(s1)) as u32,
|
||||
// 10 V_MUL_HI_I32_I24: D.i32 = (S0.i24 * S1.i24)>>32.
|
||||
Form::MulHiI24 => ((i24(s0) * i24(s1)) >> 32) as u32,
|
||||
// 11 V_MUL_U32_U24: D.u32 = S0.u24 * S1.u24.
|
||||
Form::MulU24 => (u24(s0) * u24(s1)) as u32,
|
||||
// 12 V_MUL_HI_U32_U24: D.u32 = (S0.u24 * S1.u24)>>32.
|
||||
Form::MulHiU24 => ((u24(s0) * u24(s1)) >> 32) as u32,
|
||||
// 17 V_MIN_I32: D.i32 = (S0.i32 < S1.i32 ? S0.i32 : S1.i32).
|
||||
Form::MinI32 => {
|
||||
if i0 < i1 {
|
||||
s0
|
||||
} else {
|
||||
s1
|
||||
}
|
||||
}
|
||||
// 18 V_MAX_I32: D.i32 = (S0.i32 >= S1.i32 ? S0.i32 : S1.i32).
|
||||
Form::MaxI32 => {
|
||||
if i0 >= i1 {
|
||||
s0
|
||||
} else {
|
||||
s1
|
||||
}
|
||||
}
|
||||
// 19 V_MIN_U32: D.u32 = (S0.u32 < S1.u32 ? S0.u32 : S1.u32).
|
||||
Form::MinU32 => {
|
||||
if u0 < u1 {
|
||||
s0
|
||||
} else {
|
||||
s1
|
||||
}
|
||||
}
|
||||
// 20 V_MAX_U32: D.u32 = (S0.u32 >= S1.u32 ? S0.u32 : S1.u32).
|
||||
Form::MaxU32 => {
|
||||
if u0 >= u1 {
|
||||
s0
|
||||
} else {
|
||||
s1
|
||||
}
|
||||
}
|
||||
// 30 V_XNOR_B32: D.u32 = ~(S0.u32 ^ S1.u32).
|
||||
Form::Xnor => !(s0 ^ s1),
|
||||
// 37 V_ADD_NC_U32: D.u32 = S0.u32 + S1.u32. No carry-in or carry-out.
|
||||
Form::AddNc => (u0 + u1) as u32,
|
||||
// 38 V_SUB_NC_U32: D.u32 = S0.u32 - S1.u32. No carry-in or carry-out.
|
||||
Form::SubNc => (u0 - u1) as u32,
|
||||
// 39 V_SUBREV_NC_U32: D.u32 = S1.u32 - S0.u32. No carry-in or carry-out.
|
||||
Form::SubrevNc => (u1 - u0) as u32,
|
||||
}
|
||||
}
|
||||
|
||||
/// Values worked by hand from the pseudocode above (S0, S1, D).
|
||||
const GUIDE_EXAMPLES: [(Form, u32, u32, u32); 20] = [
|
||||
// (-2^23)^2 = 2^46: low half 0, high half 2^14.
|
||||
(Form::MulI24, 0x0080_0000, 0x0080_0000, 0x0000_0000),
|
||||
(Form::MulHiI24, 0x0080_0000, 0x0080_0000, 0x0000_4000),
|
||||
// -1 * 2 = -2, sign-extended into the high half.
|
||||
(Form::MulI24, 0x00ff_ffff, 0x0000_0002, 0xffff_fffe),
|
||||
(Form::MulHiI24, 0x00ff_ffff, 0x0000_0002, 0xffff_ffff),
|
||||
// -2^23 * (2^23 - 1) = -2^46 + 2^23.
|
||||
(Form::MulI24, 0x0080_0000, 0x007f_ffff, 0x0080_0000),
|
||||
(Form::MulHiI24, 0x0080_0000, 0x007f_ffff, 0xffff_c000),
|
||||
// Bits 31:24 are ignored: 3 * 5.
|
||||
(Form::MulI24, 0xff00_0003, 0x0100_0005, 0x0000_000f),
|
||||
(Form::MulU24, 0xff00_0003, 0x0100_0005, 0x0000_000f),
|
||||
// (2^24 - 1)^2 = 0xffff_fe00_0001.
|
||||
(Form::MulU24, 0x00ff_ffff, 0x00ff_ffff, 0xfe00_0001),
|
||||
(Form::MulHiU24, 0x00ff_ffff, 0x00ff_ffff, 0x0000_ffff),
|
||||
(Form::MulHiI24, 0x00ff_ffff, 0x00ff_ffff, 0x0000_0000),
|
||||
(Form::MinI32, 0x8000_0000, 0x7fff_ffff, 0x8000_0000),
|
||||
(Form::MinU32, 0x8000_0000, 0x7fff_ffff, 0x7fff_ffff),
|
||||
(Form::MaxI32, 0x8000_0000, 0x7fff_ffff, 0x7fff_ffff),
|
||||
(Form::MaxU32, 0x8000_0000, 0x7fff_ffff, 0x8000_0000),
|
||||
(Form::Xnor, 0x0f0f_0f0f, 0x00ff_00ff, 0xf00f_f00f),
|
||||
(Form::AddNc, 0xffff_ffff, 0x0000_0001, 0x0000_0000),
|
||||
(Form::SubNc, 0x0000_0005, 0x0000_0003, 0x0000_0002),
|
||||
(Form::SubrevNc, 0x0000_0005, 0x0000_0003, 0xffff_fffe),
|
||||
(Form::SubrevNc, 0x0000_0000, 0x8000_0000, 0x8000_0000),
|
||||
];
|
||||
|
||||
/// Boundary operands (also the first 18 lane inputs): 0, 1, 2, around the
|
||||
/// 24-bit sign bit and field top, values with bits above 23 set, and the
|
||||
/// 32-bit boundaries.
|
||||
const VALUES: [u32; 18] = [
|
||||
0x0000_0000,
|
||||
0x0000_0001,
|
||||
0x0000_0002,
|
||||
0x007f_ffff,
|
||||
0x0080_0000,
|
||||
0x0080_0001,
|
||||
0x00ff_ffff,
|
||||
0x0100_0000,
|
||||
0x1234_5678,
|
||||
0x5555_5555,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0x8000_0001,
|
||||
0xaaaa_aaaa,
|
||||
0xff00_0001,
|
||||
0xff80_0000,
|
||||
0xffff_fffe,
|
||||
0xffff_ffff,
|
||||
];
|
||||
/// The other 14 lane inputs, so all 32 lanes differ.
|
||||
const MORE_LANES: [u32; 14] = [
|
||||
0x007f_fffe,
|
||||
0x00ff_fffe,
|
||||
0x0100_0001,
|
||||
0x00c0_0000,
|
||||
0xff7f_ffff,
|
||||
0xff80_0001,
|
||||
0xffff_0000,
|
||||
0x0000_ffff,
|
||||
0x4000_0000,
|
||||
0xc000_0000,
|
||||
0x8765_4321,
|
||||
0x0f0f_0f0f,
|
||||
0x7fff_fffe,
|
||||
0x1fff_ffff,
|
||||
];
|
||||
const LITERALS: [u32; 9] = [
|
||||
0,
|
||||
1,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
u32::MAX,
|
||||
0x00ff_ffff,
|
||||
0x0080_0000,
|
||||
0xff80_0000,
|
||||
0x0100_0001,
|
||||
];
|
||||
const SGPR_VALUES: [u32; 3] = [0x8000_0000, 0x00ff_ffff, 0xff80_0001];
|
||||
/// XORed with v1 to make a second per-lane source that differs from v1.
|
||||
const PAIR_KEYS: [u32; 5] = [0x00ff_ffff, 0x8000_0000, u32::MAX, 0x0080_0001, 0x5555_5555];
|
||||
/// The last one is set explicitly, as a full EXEC written by `s_mov_b32`.
|
||||
const EXEC_MASKS: [u32; 7] = [
|
||||
0,
|
||||
0x5555_5555,
|
||||
0xaaaa_aaaa,
|
||||
0x8000_0001,
|
||||
0x0000_ffff,
|
||||
0x7fff_fffe,
|
||||
u32::MAX,
|
||||
];
|
||||
/// XORed with v1 to give every lane its own old VDST before a masked write.
|
||||
const OLD: u32 = 0x0bad_f00d;
|
||||
|
||||
const COUNTS: [(&str, usize); 11] = [
|
||||
("vop2 domain", 12 * 18 * 2),
|
||||
("vop2 lane pairs", 12 * 5 * 2),
|
||||
("vop2 aliasing", 12 * 4),
|
||||
("vop2 inline integer", 12 * 81),
|
||||
("vop2 literal", 12 * 9),
|
||||
("vop2 sgpr source", 12 * 2 * 3),
|
||||
("vop2 vcc_lo source", 12 * 3),
|
||||
("vop2 max register", 12 * 3),
|
||||
("vop2 exec", 12 * (7 + 3)),
|
||||
("vop2 partial wave", 12 * 3),
|
||||
("vop2 no vcc or scc write", 12 * 5),
|
||||
];
|
||||
/// Per form: a missing literal, 9 float inline constants, 8 other special
|
||||
/// SRC0 selectors, the 24 reserved selectors 209-232, SDWA, DPP16 and two DPP8 forms, and the VOP3 form with
|
||||
/// clamp; and for each form but ADD_NC (whose plain VOP3 form is supported
|
||||
/// already) the plain VOP3 form.
|
||||
const REJECTIONS: usize = 12 * (1 + 9 + 8 + 24 + 4 + 1) + 11;
|
||||
|
||||
const LITERAL: u32 = 255;
|
||||
const VCC_LO: u32 = 106;
|
||||
|
||||
/// ENCODING 0 in bit 31, OP 25-30, VDST 17-24, VSRC1 9-16, SRC0 0-8 (guide
|
||||
/// 13.3.1); SRC0 256 + n is VGPR n.
|
||||
fn vop2(op: u32, dst: u32, src0: u32, vsrc1: u32) -> u32 {
|
||||
op << 25 | dst << 17 | vsrc1 << 9 | src0
|
||||
}
|
||||
|
||||
const fn vgpr(n: u32) -> u32 {
|
||||
256 + n
|
||||
}
|
||||
|
||||
/// `v_mov_b32 v<reg>, literal` (VOP1 opcode 1).
|
||||
fn vmov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0x7e00_02ff | reg << 17, value]
|
||||
}
|
||||
|
||||
/// `s_mov_b32 s<reg>, literal` (SOP1 opcode 3).
|
||||
fn smov(reg: u32, value: u32) -> [u32; 2] {
|
||||
[0xbe80_03ff | reg << 16, value]
|
||||
}
|
||||
|
||||
/// `v_xor_b32 v<dst>, v<a>, v<b>` (VOP2 opcode 29, supported before this form set).
|
||||
fn vxor(dst: u32, a: u32, b: u32) -> u32 {
|
||||
vop2(29, dst, vgpr(a), b)
|
||||
}
|
||||
|
||||
/// `s_mov_b32 exec_lo, -1`.
|
||||
const FULL_EXEC: u32 = 0xbefe_03c1;
|
||||
/// `s_cmp_eq_u32 0, 0` (SCC = 1) and `s_cmp_eq_u32 0, 1` (SCC = 0).
|
||||
const SCC_SET: u32 = 0xbf06_8080;
|
||||
const SCC_CLEAR: u32 = 0xbf06_8180;
|
||||
/// v6 = vcc_lo; v2 ^= v6; `s_cbranch_scc0` over v2 ^= v1.
|
||||
const FLAG_TAIL: [u32; 4] = [0x7e0c_026a, 0x3a04_0506, 0xbf84_0001, 0x3a04_0501];
|
||||
|
||||
/// Load v1 = lane input, then `setup`, the ALU words, `after`, then
|
||||
/// v2 = v<result> (unless it is v2) and store v2.
|
||||
fn program(setup: &[u32], alu: &[u32], after: &[u32], result: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
code.extend(setup);
|
||||
code.extend(alu);
|
||||
code.extend(after);
|
||||
if result != 2 {
|
||||
code.push(0x7e04_0300 | result);
|
||||
}
|
||||
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
|
||||
words(&code)
|
||||
}
|
||||
|
||||
/// The ALU word's byte offset in `program` with `setup`.
|
||||
fn alu_offset(setup: &[u32]) -> usize {
|
||||
12 + 4 * setup.len()
|
||||
}
|
||||
|
||||
fn lanes() -> Vec<u32> {
|
||||
VALUES.iter().chain(&MORE_LANES).copied().collect()
|
||||
}
|
||||
|
||||
/// A case whose lane `n` (dispatch index) with input `x` expects `lane(n, x)`.
|
||||
fn case(
|
||||
(_, name): (Form, &'static str),
|
||||
family: &'static str,
|
||||
label: String,
|
||||
code: Vec<u8>,
|
||||
input: Vec<u32>,
|
||||
lane: impl Fn(usize, u32) -> u32,
|
||||
) -> Case {
|
||||
let expected = input.iter().enumerate().map(|(n, &x)| lane(n, x)).collect();
|
||||
Case {
|
||||
form: name,
|
||||
family,
|
||||
label: format!("{name} {label}"),
|
||||
code,
|
||||
input,
|
||||
expected,
|
||||
}
|
||||
}
|
||||
|
||||
/// D where the lane is active under `exec` (bit `n % 32`), else the old VDST.
|
||||
fn masked(exec: u32, n: usize, d: u32, old: u32) -> u32 {
|
||||
if exec >> (n % 32) & 1 == 1 { d } else { old }
|
||||
}
|
||||
|
||||
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"),
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
for entry @ (form, _) in FORMS {
|
||||
let op = form as u32;
|
||||
let f = move |a, b| expect(form, a, b);
|
||||
// Every boundary value against all 32 lane inputs, in each slot.
|
||||
for b in VALUES {
|
||||
let setup = vmov(3, b);
|
||||
let code = program(&setup, &[vop2(op, 2, vgpr(1), 3)], &[], 2);
|
||||
let label = format!("v1, {b:#x}");
|
||||
cases.push(case(entry, "vop2 domain", label, code, lanes(), |_, x| {
|
||||
f(x, b)
|
||||
}));
|
||||
let code = program(&setup, &[vop2(op, 2, vgpr(3), 1)], &[], 2);
|
||||
let label = format!("{b:#x}, v1");
|
||||
cases.push(case(entry, "vop2 domain", label, code, lanes(), |_, x| {
|
||||
f(b, x)
|
||||
}));
|
||||
}
|
||||
// Both sources differ per lane: v4 = v1 ^ key.
|
||||
for key in PAIR_KEYS {
|
||||
let mut setup = vmov(3, key).to_vec();
|
||||
setup.push(vxor(4, 3, 1));
|
||||
let family = "vop2 lane pairs";
|
||||
let code = program(&setup, &[vop2(op, 2, vgpr(1), 4)], &[], 2);
|
||||
let label = format!("v1, v1 ^ {key:#x}");
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, x| {
|
||||
f(x, x ^ key)
|
||||
}));
|
||||
let code = program(&setup, &[vop2(op, 2, vgpr(4), 1)], &[], 2);
|
||||
let label = format!("v1 ^ {key:#x}, v1");
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, x| {
|
||||
f(x ^ key, x)
|
||||
}));
|
||||
}
|
||||
// VDST aliasing a source, with v3 = b.
|
||||
let b = 0xff80_0001;
|
||||
let setup = vmov(3, b);
|
||||
let family = "vop2 aliasing";
|
||||
let alu = [vop2(op, 1, vgpr(1), 1)];
|
||||
let code = program(&setup, &alu, &[], 1);
|
||||
cases.push(case(
|
||||
entry,
|
||||
family,
|
||||
"v1 = v1, v1".into(),
|
||||
code,
|
||||
lanes(),
|
||||
|_, x| f(x, x),
|
||||
));
|
||||
let code = program(&setup, &[vop2(op, 1, vgpr(1), 3)], &[], 1);
|
||||
cases.push(case(
|
||||
entry,
|
||||
family,
|
||||
"v1 = v1, v3".into(),
|
||||
code,
|
||||
lanes(),
|
||||
|_, x| f(x, b),
|
||||
));
|
||||
let code = program(&setup, &[vop2(op, 3, vgpr(1), 3)], &[], 3);
|
||||
cases.push(case(
|
||||
entry,
|
||||
family,
|
||||
"v3 = v1, v3".into(),
|
||||
code,
|
||||
lanes(),
|
||||
|_, x| f(x, b),
|
||||
));
|
||||
let code = program(&setup, &[vop2(op, 3, vgpr(3), 3)], &[], 3);
|
||||
cases.push(case(
|
||||
entry,
|
||||
family,
|
||||
"v3 = v3, v3".into(),
|
||||
code,
|
||||
lanes(),
|
||||
|_, _| f(b, b),
|
||||
));
|
||||
// Every integer inline constant (-16..64) as SRC0.
|
||||
for selector in 128..=208 {
|
||||
let value = inline_integer(selector);
|
||||
let code = program(&[], &[vop2(op, 2, selector, 1)], &[], 2);
|
||||
let label = format!("inline {selector} ({value:#x}), v1");
|
||||
let family = "vop2 inline integer";
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, x| {
|
||||
f(value, x)
|
||||
}));
|
||||
}
|
||||
// One literal dword after the VOP2 word as SRC0.
|
||||
for literal in LITERALS {
|
||||
let code = program(&[], &[vop2(op, 2, LITERAL, 1), literal], &[], 2);
|
||||
let label = format!("literal {literal:#x}, v1");
|
||||
let family = "vop2 literal";
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, x| {
|
||||
f(literal, x)
|
||||
}));
|
||||
}
|
||||
// SGPR SRC0: s8 and s105, the highest SGPR (guide 5.2), and vcc_lo.
|
||||
for (reg, family) in [
|
||||
(8, "vop2 sgpr source"),
|
||||
(105, "vop2 sgpr source"),
|
||||
(VCC_LO, "vop2 vcc_lo source"),
|
||||
] {
|
||||
for value in SGPR_VALUES {
|
||||
let code = program(&smov(reg, value), &[vop2(op, 2, reg, 1)], &[], 2);
|
||||
let label = format!("s{reg} = {value:#x}, v1");
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, x| {
|
||||
f(value, x)
|
||||
}));
|
||||
}
|
||||
}
|
||||
// v255, the highest VGPR, in each slot.
|
||||
let b = 0x8000_0001;
|
||||
let setup = vmov(255, b);
|
||||
let family = "vop2 max register";
|
||||
let alu = [vop2(op, 255, vgpr(1), 1)];
|
||||
let code = program(&setup, &alu, &[], 255);
|
||||
cases.push(case(
|
||||
entry,
|
||||
family,
|
||||
"v255 = v1, v1".into(),
|
||||
code,
|
||||
lanes(),
|
||||
|_, x| f(x, x),
|
||||
));
|
||||
let code = program(&setup, &[vop2(op, 2, vgpr(255), 1)], &[], 2);
|
||||
cases.push(case(
|
||||
entry,
|
||||
family,
|
||||
"v255, v1".into(),
|
||||
code,
|
||||
lanes(),
|
||||
|_, x| f(b, x),
|
||||
));
|
||||
let code = program(&setup, &[vop2(op, 2, vgpr(1), 255)], &[], 2);
|
||||
cases.push(case(
|
||||
entry,
|
||||
family,
|
||||
"v1, v255".into(),
|
||||
code,
|
||||
lanes(),
|
||||
|_, x| f(x, b),
|
||||
));
|
||||
// EXEC around the ALU word: v2 = v1 ^ OLD before it, so each inactive
|
||||
// lane must keep its own old value; EXEC is -1 again for the store.
|
||||
let b = 0x00ff_fff0;
|
||||
let mut setup = vmov(3, b).to_vec();
|
||||
setup.extend(vmov(5, OLD));
|
||||
setup.push(vxor(2, 5, 1));
|
||||
let family = "vop2 exec";
|
||||
for exec in EXEC_MASKS {
|
||||
let mut before = setup.clone();
|
||||
before.extend(smov(126, exec));
|
||||
let code = program(&before, &[vop2(op, 2, vgpr(1), 3)], &[FULL_EXEC], 2);
|
||||
let label = format!("exec {exec:#x}, v1, {b:#x}");
|
||||
cases.push(case(entry, family, label, code, lanes(), |n, x| {
|
||||
masked(exec, n, f(x, b), x ^ OLD)
|
||||
}));
|
||||
}
|
||||
// Partial EXEC with a scalar SRC0 (s8) and with a literal.
|
||||
let exec = 0x0f0f_0f0f;
|
||||
let value = 0xff80_0003;
|
||||
let mut before = setup.clone();
|
||||
before.extend(smov(8, value));
|
||||
before.extend(smov(126, exec));
|
||||
let code = program(&before, &[vop2(op, 2, 8, 1)], &[FULL_EXEC], 2);
|
||||
let label = format!("exec {exec:#x}, s8 = {value:#x}, v1");
|
||||
cases.push(case(entry, family, label, code, lanes(), |n, x| {
|
||||
masked(exec, n, f(value, x), x ^ OLD)
|
||||
}));
|
||||
// The literal also under empty EXEC: its dword is still consumed.
|
||||
for exec in [exec, 0] {
|
||||
let mut before = setup.clone();
|
||||
before.extend(smov(126, exec));
|
||||
let alu = [vop2(op, 2, LITERAL, 1), value];
|
||||
let code = program(&before, &alu, &[FULL_EXEC], 2);
|
||||
let label = format!("exec {exec:#x}, literal {value:#x}, v1");
|
||||
cases.push(case(entry, family, label, code, lanes(), |n, x| {
|
||||
masked(exec, n, f(value, x), x ^ OLD)
|
||||
}));
|
||||
}
|
||||
// A final wave with absent lanes: 7 lanes, and 45 lanes (one full wave
|
||||
// and 13 lanes), also with partial EXEC in both waves.
|
||||
let family = "vop2 partial wave";
|
||||
let long: Vec<u32> = lanes()
|
||||
.into_iter()
|
||||
.chain(MORE_LANES.into_iter().take(13))
|
||||
.collect();
|
||||
let code = program(&setup, &[vop2(op, 2, vgpr(1), 3)], &[], 2);
|
||||
let label = "7 lanes".into();
|
||||
let short = lanes()[..7].to_vec();
|
||||
cases.push(case(entry, family, label, code.clone(), short, |_, x| {
|
||||
f(x, b)
|
||||
}));
|
||||
cases.push(case(
|
||||
entry,
|
||||
family,
|
||||
"45 lanes".into(),
|
||||
code,
|
||||
long.clone(),
|
||||
|_, x| f(x, b),
|
||||
));
|
||||
let exec = 0x5555_5555;
|
||||
let mut before = setup.clone();
|
||||
before.extend(smov(126, exec));
|
||||
let code = program(&before, &[vop2(op, 2, vgpr(1), 3)], &[FULL_EXEC], 2);
|
||||
let label = format!("45 lanes, exec {exec:#x}");
|
||||
cases.push(case(entry, family, label, code, long, |n, x| {
|
||||
masked(exec, n, f(x, b), x ^ OLD)
|
||||
}));
|
||||
// VCC_LO seeded to 0 or -1 and SCC to 0 or 1 before the ALU word.
|
||||
// Afterwards each lane outputs D ^ VCC_LO, XORed with its input when
|
||||
// SCC is set, so any VCC or SCC write changes the output. b = -1 makes
|
||||
// ADD carry and SUB borrow in most lanes.
|
||||
let b = u32::MAX;
|
||||
for vcc in [0, u32::MAX] {
|
||||
for scc in [false, true] {
|
||||
let mut setup = vmov(3, b).to_vec();
|
||||
setup.extend(smov(VCC_LO, vcc));
|
||||
setup.push(if scc { SCC_SET } else { SCC_CLEAR });
|
||||
let code = program(&setup, &[vop2(op, 2, vgpr(1), 3)], &FLAG_TAIL, 2);
|
||||
let label = format!("vcc_lo {vcc:#x}, scc {scc}");
|
||||
let family = "vop2 no vcc or scc write";
|
||||
cases.push(case(entry, family, label, code, lanes(), |_, x| {
|
||||
f(x, b) ^ vcc ^ if scc { x } else { 0 }
|
||||
}));
|
||||
}
|
||||
}
|
||||
// The same under partial EXEC with SCC = 1 and VCC_LO bits both inside
|
||||
// and outside EXEC, so a VCC write limited to active lanes also shows.
|
||||
let (exec, vcc) = (0x0f0f_0f0f, 0x0000_00f3);
|
||||
let mut before = setup.clone();
|
||||
before.extend(vmov(3, b));
|
||||
before.extend(smov(VCC_LO, vcc));
|
||||
before.push(SCC_SET);
|
||||
before.extend(smov(126, exec));
|
||||
let mut after = vec![FULL_EXEC];
|
||||
after.extend(FLAG_TAIL);
|
||||
let code = program(&before, &[vop2(op, 2, vgpr(1), 3)], &after, 2);
|
||||
let label = format!("exec {exec:#x}, vcc_lo {vcc:#x}, scc true");
|
||||
let family = "vop2 no vcc or scc write";
|
||||
cases.push(case(entry, family, label, code, lanes(), |n, x| {
|
||||
masked(exec, n, f(x, b), x ^ OLD) ^ vcc ^ x
|
||||
}));
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
/// Programs both interpreters must refuse at the ALU word, with that offset.
|
||||
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
|
||||
let setup = vmov(3, 7);
|
||||
let offset = alu_offset(&setup);
|
||||
let mut all = Vec::new();
|
||||
for (form, name) in FORMS {
|
||||
let op = form as u32;
|
||||
// A literal SRC0 with no literal dword: the program ends at the word.
|
||||
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
|
||||
code.extend(setup);
|
||||
code.push(vop2(op, 2, LITERAL, 1));
|
||||
all.push((format!("{name} missing literal"), words(&code), offset));
|
||||
// Float inline constants 240-248 (0.5 to -4.0 and 1/(2*pi)), VCC_HI,
|
||||
// M0, NULL, EXEC_LO, EXEC_HI, VCCZ, EXECZ and SCC (outside the
|
||||
// supported SRC0 subset), and the reserved selectors 209-232.
|
||||
let special = [107, 124, 125, 126, 127, 251, 252, 253];
|
||||
for src0 in (240..=248).chain(special).chain(209..=232) {
|
||||
let code = program(&setup, &[vop2(op, 2, src0, 1)], &[], 2);
|
||||
all.push((format!("{name} src0 {src0}"), code, offset));
|
||||
}
|
||||
// SDWA (249) with SRC0 v1 and DWORD selects, DPP16 (250) with the
|
||||
// identity quad_perm, DPP8 (233) and DPP8FI (234) with the identity
|
||||
// lane selects.
|
||||
for (src0, extension) in [
|
||||
(249, 0x0606_0601),
|
||||
(250, 0xff00_e401),
|
||||
(233, 0xfac6_8801),
|
||||
(234, 0xfac6_8801),
|
||||
] {
|
||||
let code = program(&setup, &[vop2(op, 2, src0, 3), extension], &[], 2);
|
||||
all.push((format!("{name} src0 {src0} extension"), code, offset));
|
||||
}
|
||||
// VOP3 (ENCODING 0b110101, OP 256 + the VOP2 opcode): v2 = v1, v3,
|
||||
// with the clamp bit, and without it for the forms not yet supported
|
||||
// as VOP3.
|
||||
let vop3 = 0xd400_0000 | (256 + op) << 16 | 2;
|
||||
let sources = vgpr(1) | vgpr(3) << 9;
|
||||
let code = program(&setup, &[vop3 | 0x8000, sources], &[], 2);
|
||||
all.push((format!("{name} VOP3 clamp"), code, offset));
|
||||
if form != Form::AddNc {
|
||||
let code = program(&setup, &[vop3, sources], &[], 2);
|
||||
all.push((format!("{name} VOP3"), code, offset));
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn assert_rejected_at(label: &str, code: &[u8], offset: usize, input: &[u32]) {
|
||||
match xenora_ref::execute(code, input) {
|
||||
Ok(_) => panic!("reference accepted {label}"),
|
||||
Err(error) => assert_eq!(
|
||||
error.offset, offset,
|
||||
"reference rejected {label} elsewhere: {error:?}"
|
||||
),
|
||||
}
|
||||
match independent_ref::execute(code, input) {
|
||||
Ok(_) => panic!("independent accepted {label}"),
|
||||
Err(error) => assert!(
|
||||
error.starts_with(&format!("{offset:#x}:")),
|
||||
"independent rejected {label} elsewhere: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for case in cases {
|
||||
*counts.entry(key(case)).or_default() += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Runs `execute` on every case and returns one line per failing family: the
|
||||
/// number of failures and the first one.
|
||||
fn failures(
|
||||
cases: &[Case],
|
||||
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
|
||||
) -> Vec<String> {
|
||||
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
|
||||
for case in cases {
|
||||
let output = execute(&case.code, &case.input);
|
||||
if output.as_deref().ok() != Some(case.expected.as_slice()) {
|
||||
let first = format!("{}: {output:?}, 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_worked_examples() {
|
||||
for (form, s0, s1, d) in GUIDE_EXAMPLES {
|
||||
assert_eq!(expect(form, s0, s1), d, "{form:?}({s0:#x}, {s1:#x})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop2_integer_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!("vop2_integer: {} reference cases", cases.len());
|
||||
for (form, n) in tally(&cases, |case| case.form) {
|
||||
eprintln!(" form {form}: {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop2_integer_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!(
|
||||
"vop2_integer: {} independent-interpreter cases",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_vop2_integer_encodings_are_rejected() {
|
||||
let rejections = rejections();
|
||||
assert_eq!(rejections.len(), REJECTIONS);
|
||||
for (label, code, offset) in &rejections {
|
||||
assert_rejected_at(label, code, *offset, &lanes());
|
||||
}
|
||||
eprintln!("vop2_integer: {} rejections", rejections.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_vop2_opcodes_stay_unsupported() {
|
||||
// Every VOP2 opcode (0-61; 62 and 63 are the VOPC and VOP1 encodings)
|
||||
// except the forms supported before this set (V_ADD_F32 3, V_MUL_F32 8,
|
||||
// the shifts 22, 24, 26 and AND, OR, XOR 27-29) and these twelve. VDST is
|
||||
// initialized, so a form that also reads it fails only on the opcode.
|
||||
let earlier = [3, 8, 22, 24, 26, 27, 28, 29];
|
||||
let supported: Vec<u32> = FORMS
|
||||
.iter()
|
||||
.map(|&(form, _)| form as u32)
|
||||
.chain(earlier)
|
||||
.collect();
|
||||
let mut setup = vmov(3, 7).to_vec();
|
||||
setup.extend(vmov(2, 5));
|
||||
for op in (0..=61).filter(|op| !supported.contains(op)) {
|
||||
let code = program(&setup, &[vop2(op, 2, vgpr(1), 3)], &[], 2);
|
||||
assert_rejected_at(&format!("opcode {op}"), &code, alu_offset(&setup), &lanes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a native Metal device with API and shader validation"]
|
||||
fn vop2_integer_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, offset) in rejections() {
|
||||
// Refused at the same word as by the interpreters, so a later failure
|
||||
// cannot stand in.
|
||||
let at = match compile(Architecture::Gfx1030, &code) {
|
||||
Err(CompileError::Decode(error)) => error.offset,
|
||||
Err(CompileError::Verify { offset, .. }) => offset,
|
||||
other => panic!("compiler did not reject {label}: {other:?}"),
|
||||
};
|
||||
assert_eq!(at, offset, "compiler rejected {label} elsewhere");
|
||||
}
|
||||
let cases = checked_cases();
|
||||
let (failures, programs) = harness::check_metal(&cases);
|
||||
failures.assert_none("native Metal disagrees with the guide");
|
||||
eprintln!(
|
||||
"vop2_integer: {} Metal cases in {programs} programs",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user