diff --git a/CHANGELOG.md b/CHANGELOG.md index e748aa94..6fb5e2a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added +- 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 interpreter support for the MOVSX/MOVSXD opcode (0x63) in `crates/loader/src/cpu.rs` (issue #117): with REX.W the instruction is MOVSXD (sign-extends the 32-bit source register into the destination), without REX.W it writes the 32-bit destination register and zeroes the upper half. REX.R and REX.B extend the destination and source registers, and non-register addressing is rejected as an illegal instruction. Five interpreter known-answer tests in `crates/loader/tests/movsxd.rs` cover negative and positive sign extension, the upper-half behaviour and REX register extension, and a sixth test executes the instruction through the native ARM64 DBT: `crates/loader/src/arm64.rs` gains `Arm64Assembler::sxtw_64` (encoding verified against llvm-mc 23.1.6) and `crates/loader/src/dbt.rs` lowers the `0x63` register form to `SXTW`. - 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. diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 201720c2..30e0ef28 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -86,6 +86,127 @@ final class FrameModel: ObservableObject { } } +/// Persistent guest rendering model (Gate 3, #266). +@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? + + private var session: xenora_session = 0 + private var pollTask: Task? + + 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 + } + state = UInt32(XENORA_LOOP_RUNNING) + completed = 0 + frameId = XENORA_NO_FRAME + image = nil + startPolling() + } + + 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 +291,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 +317,40 @@ 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("Pause") { loop.pause() } + .disabled(!loop.isRunning) + Button("Resume") { loop.resume() } + .disabled(!loop.isPaused) + Button("Stop") { loop.stop() } + .disabled(!loop.isRunning && !loop.isPaused) + } + } 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 fixture and frame-loop guest can run. Presentation uses read-back Metal frames. Arbitrary executables and input are not available yet.") .foregroundStyle(.secondary) } .formStyle(.grouped) @@ -211,16 +362,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 +384,37 @@ if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < Comm exit(status == Int32(XENORA_OK) ? 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() diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 5a868184..8077ef5c 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -351,6 +351,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), @@ -478,13 +494,14 @@ 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-compare.bin"), high_registers, &matrix, ] { count += compare_against_llvm(fixture, &mut forms); } - assert_eq!(forms.len(), 72, "forms compared: {forms:?}"); + assert_eq!(forms.len(), 88, "forms compared: {forms:?}"); eprintln!( "{count} three-way instruction comparisons across {} forms", forms.len() diff --git a/crates/ffi/include/xenora.h b/crates/ffi/include/xenora.h index f78f3f46..1c278771 100644 --- a/crates/ffi/include/xenora.h +++ b/crates/ffi/include/xenora.h @@ -27,8 +27,23 @@ 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 + /* 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 +80,34 @@ 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_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); + +/* + * 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 diff --git a/crates/ffi/src/frame_loop.rs b/crates/ffi/src/frame_loop.rs new file mode 100644 index 00000000..5b263646 --- /dev/null +++ b/crates/ffi/src/frame_loop.rs @@ -0,0 +1,243 @@ +// 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"); +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; +/// `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)] +struct State { + status: u32, + paused: bool, + stop: bool, + limit: u32, + completed: u32, + /// Every `frame_submit` call the guest made, including the one answered with 0. + calls: u64, + latest: Option<(u32, Vec)>, +} + +#[derive(Default)] +pub struct FrameLoop { + state: Mutex, + wake: Condvar, + thread: Mutex>>, +} + +pub struct Snapshot { + pub status: u32, + pub completed: u32, + pub latest: Option<(u32, Vec)>, +} + +impl FrameLoop { + fn lock(&self) -> MutexGuard<'_, State> { + self.state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + pub fn start(limit: u32) -> Arc { + let shared = Arc::new(Self::default()); + { + let mut state = shared.lock(); + state.status = RUNNING; + state.limit = limit; + } + 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 snapshot(&self) -> Snapshot { + let state = self.lock(); + Snapshot { + status: state.status, + completed: state.completed, + latest: state.latest.clone(), + } + } + + fn run(self: Arc) { + 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) -> 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)) + }); + let limit = self.lock().limit as usize; + let startup = run_synthetic_startup( + FIXTURE, + StartupLayout { + image_base: 0x1_4000_0000, + stack_top: 0x2_0001_0000, + tls_base: 0x3_0000_0000, + }, + imports, + (limit + 1) * STEPS_PER_FRAME + 16, + ) + .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); + // The guest increments RBX after every call, so it must equal the calls we served. + if startup.execution.exit_reason != ExitReason::Halt || rbx != calls { + return Err(format!( + "guest ended with {:?}, rbx={rbx}, calls={calls}", + startup.execution.exit_reason + )); + } + 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 { + 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 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)); + Some(u64::from(state.completed < state.limit && !state.stop)) + } +} + +thread_local! { + static GPU: RefCell> = 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> { + 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 { + (0..WIDTH * HEIGHT) + .flat_map(|pixel| { + if pixel % WIDTH == index as usize % WIDTH { + RED + } else { + CLEAR + } + }) + .collect() +} diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index 51f979cc..0a49a1dc 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -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,16 @@ 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_FIXTURE_FRAME_WIDTH: u32 = 4; pub const XENORA_FIXTURE_FRAME_HEIGHT: u32 = 3; @@ -38,6 +51,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>, } static SESSIONS: Mutex> = Mutex::new(Vec::new()); @@ -79,7 +94,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 +123,128 @@ 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>, 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)); + XENORA_OK + }) +} + +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 }) } @@ -439,6 +578,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 +594,13 @@ 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")); } #[test] @@ -655,4 +808,51 @@ 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_frame_loop(handle, XENORA_FRAME_LOOP_MAX_FRAMES + 1), + XENORA_INVALID_ARGUMENT + ); + 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 + ); + } } diff --git a/crates/ffi/tests/frame_loop.rs b/crates/ffi/tests/frame_loop.rs new file mode 100644 index 00000000..dbf24de9 --- /dev/null +++ b/crates/ffi/tests/frame_loop.rs @@ -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 { + 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" + ); +} diff --git a/crates/isa/generate_semantics.py b/crates/isa/generate_semantics.py index 4dd842d1..4485f281 100755 --- a/crates/isa/generate_semantics.py +++ b/crates/isa/generate_semantics.py @@ -46,6 +46,9 @@ 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", } # 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 +75,15 @@ 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"} +ARITHMETIC = {"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add"} 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 +92,9 @@ 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} SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"} CARRY_IN = {"none": "None", "scc": "Scc"} SCC = { @@ -93,6 +104,7 @@ SCC = { "signed_overflow": "SignedOverflow", "nonzero": "Nonzero", "relation": "Relation", + "selected_src0": "SelectedSrc0", } MASK = {"unchanged": "Unchanged"} WAVE = {"any": "Any", "wave32": "Wave32"} @@ -149,6 +161,19 @@ 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), } # Operand rules the decoder implements, each exactly once. A registry rule must @@ -302,7 +327,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 +343,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 +394,9 @@ 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} + ) if missing: errors.append(f"{label}: incomplete, missing {missing}") if extra: @@ -416,6 +443,16 @@ 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 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: @@ -541,6 +578,7 @@ 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" source_bits: {form.get(SOURCE_BITS_KEY, form['width'])},", " relation: " + (f"Some(CompareRelation::{RELATIONS[form[RELATION_KEY]]})," if RELATION_KEY in form else "None,"), @@ -700,7 +738,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 +750,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) {", " 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 diff --git a/crates/isa/semantics/rdna2.toml b/crates/isa/semantics/rdna2.toml index 1fd8fcd6..33292472 100644 --- a/crates/isa/semantics/rdna2.toml +++ b/crates/isa/semantics/rdna2.toml @@ -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). diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index 899aa117..63ac8daf 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -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, diff --git a/crates/isa/src/primitive.rs b/crates/isa/src/primitive.rs index efc39aad..3395572a 100644 --- a/crates/isa/src/primitive.rs +++ b/crates/isa/src/primitive.rs @@ -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) +} diff --git a/crates/isa/src/semantics.rs b/crates/isa/src/semantics.rs index 0b31aa3f..6623a980 100644 --- a/crates/isa/src/semantics.rs +++ b/crates/isa/src/semantics.rs @@ -68,6 +68,24 @@ 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, } /// How the operands are interpreted. `Bitwise` exactly when the operation is logical. @@ -81,12 +99,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 +123,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. @@ -183,12 +203,14 @@ 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, /// 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. diff --git a/crates/isa/src/semantics_gen.rs b/crates/isa/src/semantics_gen.rs index 67072835..c0d561ed 100644 --- a/crates/isa/src/semantics_gen.rs +++ b/crates/isa/src/semantics_gen.rs @@ -344,17 +344,17 @@ impl ScalarUnaryOp { /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::NotB32 => 29, - Self::BrevB32 => 30, - Self::Bcnt0I32B32 => 31, - Self::Bcnt1I32B32 => 32, - Self::Ff0I32B32 => 33, - Self::Ff1I32B32 => 34, - Self::FlbitI32B32 => 35, - Self::FlbitI32 => 36, - Self::SextI32I8 => 37, - Self::SextI32I16 => 38, - Self::AbsI32 => 39, + Self::NotB32 => 45, + Self::BrevB32 => 46, + Self::Bcnt0I32B32 => 47, + Self::Bcnt1I32B32 => 48, + Self::Ff0I32B32 => 49, + Self::Ff1I32B32 => 50, + Self::FlbitI32B32 => 51, + Self::FlbitI32 => 52, + Self::SextI32I8 => 53, + Self::SextI32I16 => 54, + Self::AbsI32 => 55, }] } @@ -443,6 +443,38 @@ pub enum ScalarAluOp { LshrB32, /// `s_ashr_i32` (SOP2 opcode 34): signed ashr, SCC = nonzero. AshrI32, + /// `s_min_i32` (SOP2 opcode 6): signed min, SCC = selected_src0. + MinI32, + /// `s_min_u32` (SOP2 opcode 7): unsigned min, SCC = selected_src0. + MinU32, + /// `s_max_i32` (SOP2 opcode 8): signed max, SCC = selected_src0. + MaxI32, + /// `s_max_u32` (SOP2 opcode 9): unsigned max, SCC = selected_src0. + MaxU32, + /// `s_cselect_b32` (SOP2 opcode 10): bitwise cselect plus SCC, SCC = unchanged. + CselectB32, + /// `s_bfm_b32` (SOP2 opcode 36): bitwise bfm, SCC = unchanged. + BfmB32, + /// `s_mul_i32` (SOP2 opcode 38): signed mul, SCC = unchanged. + MulI32, + /// `s_bfe_u32` (SOP2 opcode 39): unsigned bfe, SCC = nonzero. + BfeU32, + /// `s_bfe_i32` (SOP2 opcode 40): signed bfe, SCC = nonzero. + BfeI32, + /// `s_absdiff_i32` (SOP2 opcode 44): signed absdiff, SCC = nonzero. + AbsdiffI32, + /// `s_lshl1_add_u32` (SOP2 opcode 46): unsigned lshl_add, SCC = carry_out. + Lshl1AddU32, + /// `s_lshl2_add_u32` (SOP2 opcode 47): unsigned lshl_add, SCC = carry_out. + Lshl2AddU32, + /// `s_lshl3_add_u32` (SOP2 opcode 48): unsigned lshl_add, SCC = carry_out. + Lshl3AddU32, + /// `s_lshl4_add_u32` (SOP2 opcode 49): unsigned lshl_add, SCC = carry_out. + Lshl4AddU32, + /// `s_mul_hi_u32` (SOP2 opcode 53): unsigned mul_hi, SCC = unchanged. + MulHiU32, + /// `s_mul_hi_i32` (SOP2 opcode 54): signed mul_hi, SCC = unchanged. + MulHiI32, } /// ScalarAluOp by SOP2 OP field value; `None` for undeclared opcodes. @@ -453,11 +485,11 @@ const SCALAR_ALU_OP_BY_OPCODE: [Option; 128] = [ Some(ScalarAluOp::SubI32), Some(ScalarAluOp::AddcU32), Some(ScalarAluOp::SubbU32), - None, - None, - None, - None, - None, + Some(ScalarAluOp::MinI32), + Some(ScalarAluOp::MinU32), + Some(ScalarAluOp::MaxI32), + Some(ScalarAluOp::MaxU32), + Some(ScalarAluOp::CselectB32), None, None, None, @@ -483,25 +515,25 @@ const SCALAR_ALU_OP_BY_OPCODE: [Option; 128] = [ None, Some(ScalarAluOp::AshrI32), None, + Some(ScalarAluOp::BfmB32), + None, + Some(ScalarAluOp::MulI32), + Some(ScalarAluOp::BfeU32), + Some(ScalarAluOp::BfeI32), None, None, None, + Some(ScalarAluOp::AbsdiffI32), + None, + Some(ScalarAluOp::Lshl1AddU32), + Some(ScalarAluOp::Lshl2AddU32), + Some(ScalarAluOp::Lshl3AddU32), + Some(ScalarAluOp::Lshl4AddU32), None, None, None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, - None, + Some(ScalarAluOp::MulHiU32), + Some(ScalarAluOp::MulHiI32), None, None, None, @@ -579,7 +611,7 @@ const SCALAR_ALU_OP_BY_OPCODE: [Option; 128] = [ impl ScalarAluOp { /// Every operation, in registry order. - pub const ALL: [Self; 17] = [ + pub const ALL: [Self; 33] = [ Self::AddU32, Self::SubU32, Self::AddI32, @@ -597,6 +629,22 @@ impl ScalarAluOp { Self::LshlB32, Self::LshrB32, Self::AshrI32, + Self::MinI32, + Self::MinU32, + Self::MaxI32, + Self::MaxU32, + Self::CselectB32, + Self::BfmB32, + Self::MulI32, + Self::BfeU32, + Self::BfeI32, + Self::AbsdiffI32, + Self::Lshl1AddU32, + Self::Lshl2AddU32, + Self::Lshl3AddU32, + Self::Lshl4AddU32, + Self::MulHiU32, + Self::MulHiI32, ]; /// Selects the operation from a first instruction word: the SOP2 encoding @@ -628,6 +676,22 @@ impl ScalarAluOp { Self::LshlB32 => "s_lshl_b32", Self::LshrB32 => "s_lshr_b32", Self::AshrI32 => "s_ashr_i32", + Self::MinI32 => "s_min_i32", + Self::MinU32 => "s_min_u32", + Self::MaxI32 => "s_max_i32", + Self::MaxU32 => "s_max_u32", + Self::CselectB32 => "s_cselect_b32", + Self::BfmB32 => "s_bfm_b32", + Self::MulI32 => "s_mul_i32", + Self::BfeU32 => "s_bfe_u32", + Self::BfeI32 => "s_bfe_i32", + Self::AbsdiffI32 => "s_absdiff_i32", + Self::Lshl1AddU32 => "s_lshl1_add_u32", + Self::Lshl2AddU32 => "s_lshl2_add_u32", + Self::Lshl3AddU32 => "s_lshl3_add_u32", + Self::Lshl4AddU32 => "s_lshl4_add_u32", + Self::MulHiU32 => "s_mul_hi_u32", + Self::MulHiI32 => "s_mul_hi_i32", } } @@ -651,10 +715,26 @@ impl ScalarAluOp { Self::LshlB32 => 14, Self::LshrB32 => 15, Self::AshrI32 => 16, + Self::MinI32 => 17, + Self::MinU32 => 18, + Self::MaxI32 => 19, + Self::MaxU32 => 20, + Self::CselectB32 => 21, + Self::BfmB32 => 22, + Self::MulI32 => 23, + Self::BfeU32 => 24, + Self::BfeI32 => 25, + Self::AbsdiffI32 => 26, + Self::Lshl1AddU32 => 27, + Self::Lshl2AddU32 => 28, + Self::Lshl3AddU32 => 29, + Self::Lshl4AddU32 => 30, + Self::MulHiU32 => 31, + Self::MulHiI32 => 32, }] } - /// 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 { Self::AddU32 => false, @@ -674,30 +754,186 @@ impl ScalarAluOp { Self::LshlB32 => false, Self::LshrB32 => false, Self::AshrI32 => false, + Self::MinI32 => false, + Self::MinU32 => false, + Self::MaxI32 => false, + Self::MaxU32 => false, + Self::CselectB32 => true, + Self::BfmB32 => false, + Self::MulI32 => false, + Self::BfeU32 => false, + Self::BfeI32 => false, + Self::AbsdiffI32 => false, + Self::Lshl1AddU32 => false, + Self::Lshl2AddU32 => false, + Self::Lshl3AddU32 => false, + Self::Lshl4AddU32 => false, + Self::MulHiU32 => false, + Self::MulHiI32 => false, } } - /// 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 { - Self::AddU32 => primitive::add_carry_u32(src0, src1, false), - Self::SubU32 => primitive::sub_borrow_u32(src0, src1, false), - Self::AddI32 => primitive::add_overflow_i32(src0, src1), - Self::SubI32 => primitive::sub_overflow_i32(src0, src1), - Self::AddcU32 => primitive::add_carry_u32(src0, src1, carry_in), - Self::SubbU32 => primitive::sub_borrow_u32(src0, src1, carry_in), - Self::AndB32 => primitive::and_nonzero_b32(src0, src1), - Self::OrB32 => primitive::or_nonzero_b32(src0, src1), - Self::XorB32 => primitive::xor_nonzero_b32(src0, src1), - Self::Andn2B32 => primitive::andn2_nonzero_b32(src0, src1), - Self::Orn2B32 => primitive::orn2_nonzero_b32(src0, src1), - Self::NandB32 => primitive::nand_nonzero_b32(src0, src1), - Self::NorB32 => primitive::nor_nonzero_b32(src0, src1), - Self::XnorB32 => primitive::xnor_nonzero_b32(src0, src1), - Self::LshlB32 => primitive::lshl_nonzero_b32(src0, src1 & 0x1f), - Self::LshrB32 => primitive::lshr_nonzero_b32(src0, src1 & 0x1f), - Self::AshrI32 => primitive::ashr_nonzero_i32(src0, src1 & 0x1f), + Self::AddU32 => true, + Self::SubU32 => true, + Self::AddI32 => true, + Self::SubI32 => true, + Self::AddcU32 => true, + Self::SubbU32 => true, + Self::AndB32 => true, + Self::OrB32 => true, + Self::XorB32 => true, + Self::Andn2B32 => true, + Self::Orn2B32 => true, + Self::NandB32 => true, + Self::NorB32 => true, + Self::XnorB32 => true, + Self::LshlB32 => true, + Self::LshrB32 => true, + Self::AshrI32 => true, + Self::MinI32 => true, + Self::MinU32 => true, + Self::MaxI32 => true, + Self::MaxU32 => true, + Self::CselectB32 => false, + Self::BfmB32 => false, + Self::MulI32 => false, + Self::BfeU32 => true, + Self::BfeI32 => true, + Self::AbsdiffI32 => true, + Self::Lshl1AddU32 => true, + Self::Lshl2AddU32 => true, + Self::Lshl3AddU32 => true, + Self::Lshl4AddU32 => true, + Self::MulHiU32 => false, + Self::MulHiI32 => false, + } + } + + /// 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) { + match self { + Self::AddU32 => { + let (value, scc) = primitive::add_carry_u32(src0, src1, false); + (value, Some(scc)) + } + Self::SubU32 => { + let (value, scc) = primitive::sub_borrow_u32(src0, src1, false); + (value, Some(scc)) + } + Self::AddI32 => { + let (value, scc) = primitive::add_overflow_i32(src0, src1); + (value, Some(scc)) + } + Self::SubI32 => { + let (value, scc) = primitive::sub_overflow_i32(src0, src1); + (value, Some(scc)) + } + Self::AddcU32 => { + let (value, scc) = primitive::add_carry_u32(src0, src1, scc_in); + (value, Some(scc)) + } + Self::SubbU32 => { + let (value, scc) = primitive::sub_borrow_u32(src0, src1, scc_in); + (value, Some(scc)) + } + Self::AndB32 => { + let (value, scc) = primitive::and_nonzero_b32(src0, src1); + (value, Some(scc)) + } + Self::OrB32 => { + let (value, scc) = primitive::or_nonzero_b32(src0, src1); + (value, Some(scc)) + } + Self::XorB32 => { + let (value, scc) = primitive::xor_nonzero_b32(src0, src1); + (value, Some(scc)) + } + Self::Andn2B32 => { + let (value, scc) = primitive::andn2_nonzero_b32(src0, src1); + (value, Some(scc)) + } + Self::Orn2B32 => { + let (value, scc) = primitive::orn2_nonzero_b32(src0, src1); + (value, Some(scc)) + } + Self::NandB32 => { + let (value, scc) = primitive::nand_nonzero_b32(src0, src1); + (value, Some(scc)) + } + Self::NorB32 => { + let (value, scc) = primitive::nor_nonzero_b32(src0, src1); + (value, Some(scc)) + } + Self::XnorB32 => { + let (value, scc) = primitive::xnor_nonzero_b32(src0, src1); + (value, Some(scc)) + } + Self::LshlB32 => { + let (value, scc) = primitive::lshl_nonzero_b32(src0, src1 & 0x1f); + (value, Some(scc)) + } + Self::LshrB32 => { + let (value, scc) = primitive::lshr_nonzero_b32(src0, src1 & 0x1f); + (value, Some(scc)) + } + Self::AshrI32 => { + let (value, scc) = primitive::ashr_nonzero_i32(src0, src1 & 0x1f); + (value, Some(scc)) + } + Self::MinI32 => { + let (value, scc) = primitive::min_i32(src0, src1); + (value, Some(scc)) + } + Self::MinU32 => { + let (value, scc) = primitive::min_u32(src0, src1); + (value, Some(scc)) + } + Self::MaxI32 => { + let (value, scc) = primitive::max_i32(src0, src1); + (value, Some(scc)) + } + Self::MaxU32 => { + let (value, scc) = primitive::max_u32(src0, src1); + (value, Some(scc)) + } + Self::CselectB32 => (primitive::cselect_b32(src0, src1, scc_in), None), + Self::BfmB32 => (primitive::bfm_b32(src0, src1), None), + Self::MulI32 => (primitive::mul_lo_i32(src0, src1), None), + Self::BfeU32 => { + let (value, scc) = primitive::bfe_nonzero_u32(src0, src1); + (value, Some(scc)) + } + Self::BfeI32 => { + let (value, scc) = primitive::bfe_nonzero_i32(src0, src1); + (value, Some(scc)) + } + Self::AbsdiffI32 => { + let (value, scc) = primitive::absdiff_nonzero_i32(src0, src1); + (value, Some(scc)) + } + Self::Lshl1AddU32 => { + let (value, scc) = primitive::lshl_add_carry_u32(src0, src1, 1); + (value, Some(scc)) + } + Self::Lshl2AddU32 => { + let (value, scc) = primitive::lshl_add_carry_u32(src0, src1, 2); + (value, Some(scc)) + } + Self::Lshl3AddU32 => { + let (value, scc) = primitive::lshl_add_carry_u32(src0, src1, 3); + (value, Some(scc)) + } + Self::Lshl4AddU32 => { + let (value, scc) = primitive::lshl_add_carry_u32(src0, src1, 4); + (value, Some(scc)) + } + Self::MulHiU32 => (primitive::mul_hi_u32(src0, src1), None), + Self::MulHiI32 => (primitive::mul_hi_i32(src0, src1), None), } } } @@ -910,18 +1146,18 @@ impl ScalarCompareOp { /// The validated registry row. pub fn semantics(self) -> &'static FormSemantics { &FORMS[match self { - Self::CmpEqI32 => 17, - Self::CmpLgI32 => 18, - Self::CmpGtI32 => 19, - Self::CmpGeI32 => 20, - Self::CmpLtI32 => 21, - Self::CmpLeI32 => 22, - Self::CmpEqU32 => 23, - Self::CmpLgU32 => 24, - Self::CmpGtU32 => 25, - Self::CmpGeU32 => 26, - Self::CmpLtU32 => 27, - Self::CmpLeU32 => 28, + Self::CmpEqI32 => 33, + Self::CmpLgI32 => 34, + Self::CmpGtI32 => 35, + Self::CmpGeI32 => 36, + Self::CmpLtI32 => 37, + Self::CmpLeI32 => 38, + Self::CmpEqU32 => 39, + Self::CmpLgU32 => 40, + Self::CmpGtU32 => 41, + Self::CmpGeU32 => 42, + Self::CmpLtU32 => 43, + Self::CmpLeU32 => 44, }] } @@ -963,7 +1199,7 @@ impl ScalarCompareOp { } /// Identity of every registry form, in registry order. -pub const FORM_IDS: [(&str, EncodingFamily); 40] = [ +pub const FORM_IDS: [(&str, EncodingFamily); 56] = [ ("S_ADD_U32", EncodingFamily::Sop2), ("S_SUB_U32", EncodingFamily::Sop2), ("S_ADD_I32", EncodingFamily::Sop2), @@ -981,6 +1217,22 @@ pub const FORM_IDS: [(&str, EncodingFamily); 40] = [ ("S_LSHL_B32", EncodingFamily::Sop2), ("S_LSHR_B32", EncodingFamily::Sop2), ("S_ASHR_I32", EncodingFamily::Sop2), + ("S_MIN_I32", EncodingFamily::Sop2), + ("S_MIN_U32", EncodingFamily::Sop2), + ("S_MAX_I32", EncodingFamily::Sop2), + ("S_MAX_U32", EncodingFamily::Sop2), + ("S_CSELECT_B32", EncodingFamily::Sop2), + ("S_BFM_B32", EncodingFamily::Sop2), + ("S_MUL_I32", EncodingFamily::Sop2), + ("S_BFE_U32", EncodingFamily::Sop2), + ("S_BFE_I32", EncodingFamily::Sop2), + ("S_ABSDIFF_I32", EncodingFamily::Sop2), + ("S_LSHL1_ADD_U32", EncodingFamily::Sop2), + ("S_LSHL2_ADD_U32", EncodingFamily::Sop2), + ("S_LSHL3_ADD_U32", EncodingFamily::Sop2), + ("S_LSHL4_ADD_U32", EncodingFamily::Sop2), + ("S_MUL_HI_U32", EncodingFamily::Sop2), + ("S_MUL_HI_I32", EncodingFamily::Sop2), ("S_CMP_EQ_I32", EncodingFamily::Sopc), ("S_CMP_LG_I32", EncodingFamily::Sopc), ("S_CMP_GT_I32", EncodingFamily::Sopc), @@ -1007,7 +1259,7 @@ pub const FORM_IDS: [(&str, EncodingFamily); 40] = [ ]; /// One validated row per registry form, in registry order. -pub static FORMS: [FormSemantics; 40] = [ +pub static FORMS: [FormSemantics; 56] = [ FormSemantics { name: "S_ADD_U32", family: EncodingFamily::Sop2, @@ -1017,6 +1269,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::CarryOut, @@ -1036,6 +1289,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Borrow, @@ -1055,6 +1309,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::SignedOverflow, @@ -1074,6 +1329,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::SignedOverflow, @@ -1093,6 +1349,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::Scc, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::CarryOut, @@ -1112,6 +1369,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::Scc, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Borrow, @@ -1131,6 +1389,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1150,6 +1409,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1169,6 +1429,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1188,6 +1449,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1207,6 +1469,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1226,6 +1489,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1245,6 +1509,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1264,6 +1529,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1283,6 +1549,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 5, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1302,6 +1569,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 5, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1321,6 +1589,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 5, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1331,6 +1600,326 @@ pub static FORMS: [FormSemantics; 40] = [ spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }], verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], }, + FormSemantics { + name: "S_MIN_I32", + family: EncodingFamily::Sop2, + opcode: 6, + operation: Operation::Minimum, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::SelectedSrc0, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }, SpecRef { document: Document::Guide, section: "5.4", page: 34 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_MIN_U32", + family: EncodingFamily::Sop2, + opcode: 7, + operation: Operation::Minimum, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::SelectedSrc0, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }, SpecRef { document: Document::Guide, section: "5.4", page: 34 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_MAX_I32", + family: EncodingFamily::Sop2, + opcode: 8, + operation: Operation::Maximum, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::SelectedSrc0, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 102 }, SpecRef { document: Document::Guide, section: "5.4", page: 34 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_MAX_U32", + family: EncodingFamily::Sop2, + opcode: 9, + operation: Operation::Maximum, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::SelectedSrc0, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 103 }, SpecRef { document: Document::Guide, section: "5.4", page: 34 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_CSELECT_B32", + family: EncodingFamily::Sop2, + opcode: 10, + operation: Operation::Select, + signedness: Signedness::Bitwise, + carry_in: CarryIn::Scc, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 103 }, SpecRef { document: Document::Guide, section: "5.5", page: 34 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_BFM_B32", + family: EncodingFamily::Sop2, + opcode: 36, + operation: Operation::BitfieldMask, + signedness: Signedness::Bitwise, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 104 }, SpecRef { document: Document::Guide, section: "5.7", page: 36 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_MUL_I32", + family: EncodingFamily::Sop2, + opcode: 38, + operation: Operation::Multiply, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 105 }, SpecRef { document: Document::Guide, section: "5.4", page: 34 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_BFE_U32", + family: EncodingFamily::Sop2, + opcode: 39, + operation: Operation::BitfieldExtract, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::Nonzero, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 105 }, SpecRef { document: Document::Guide, section: "5.7", page: 36 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_BFE_I32", + family: EncodingFamily::Sop2, + opcode: 40, + operation: Operation::BitfieldExtract, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::Nonzero, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 105 }, SpecRef { document: Document::Guide, section: "5.7", page: 36 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_ABSDIFF_I32", + family: EncodingFamily::Sop2, + opcode: 44, + operation: Operation::AbsoluteDifference, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::Nonzero, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 105 }, SpecRef { document: Document::Guide, section: "5.4", page: 34 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_LSHL1_ADD_U32", + family: EncodingFamily::Sop2, + opcode: 46, + operation: Operation::ShiftLeftAdd, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 1, + source_bits: 32, + relation: None, + scc: SccEffect::CarryOut, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 105 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_LSHL2_ADD_U32", + family: EncodingFamily::Sop2, + opcode: 47, + operation: Operation::ShiftLeftAdd, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 2, + source_bits: 32, + relation: None, + scc: SccEffect::CarryOut, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 105 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_LSHL3_ADD_U32", + family: EncodingFamily::Sop2, + opcode: 48, + operation: Operation::ShiftLeftAdd, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 3, + source_bits: 32, + relation: None, + scc: SccEffect::CarryOut, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 106 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_LSHL4_ADD_U32", + family: EncodingFamily::Sop2, + opcode: 49, + operation: Operation::ShiftLeftAdd, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 4, + source_bits: 32, + relation: None, + scc: SccEffect::CarryOut, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 106 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_MUL_HI_U32", + family: EncodingFamily::Sop2, + opcode: 53, + operation: Operation::MultiplyHigh, + signedness: Signedness::Unsigned, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 106 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, + FormSemantics { + name: "S_MUL_HI_I32", + family: EncodingFamily::Sop2, + opcode: 54, + operation: Operation::MultiplyHigh, + signedness: Signedness::Signed, + carry_in: CarryIn::None, + width: 32, + shift_count_bits: 0, + shift_amount: 0, + source_bits: 32, + relation: None, + scc: SccEffect::Unchanged, + vcc: MaskEffect::Unchanged, + exec: MaskEffect::Unchanged, + wave: Wave::Any, + operands: OperandRule::Sop2Sgpr, + spec: &[SpecRef { document: Document::Guide, section: "12.1", page: 106 }], + verify: &[Evidence::Reference, Evidence::Independent, Evidence::Metal, Evidence::LlvmEncoding], + }, FormSemantics { name: "S_CMP_EQ_I32", family: EncodingFamily::Sopc, @@ -1340,6 +1929,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::Equal), scc: SccEffect::Relation, @@ -1359,6 +1949,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::NotEqual), scc: SccEffect::Relation, @@ -1378,6 +1969,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::Greater), scc: SccEffect::Relation, @@ -1397,6 +1989,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::GreaterOrEqual), scc: SccEffect::Relation, @@ -1416,6 +2009,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::Less), scc: SccEffect::Relation, @@ -1435,6 +2029,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::LessOrEqual), scc: SccEffect::Relation, @@ -1454,6 +2049,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::Equal), scc: SccEffect::Relation, @@ -1473,6 +2069,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::NotEqual), scc: SccEffect::Relation, @@ -1492,6 +2089,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::Greater), scc: SccEffect::Relation, @@ -1511,6 +2109,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::GreaterOrEqual), scc: SccEffect::Relation, @@ -1530,6 +2129,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::Less), scc: SccEffect::Relation, @@ -1549,6 +2149,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: Some(CompareRelation::LessOrEqual), scc: SccEffect::Relation, @@ -1568,6 +2169,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1587,6 +2189,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Unchanged, @@ -1606,6 +2209,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1625,6 +2229,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, @@ -1644,6 +2249,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Unchanged, @@ -1663,6 +2269,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Unchanged, @@ -1682,6 +2289,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Unchanged, @@ -1701,6 +2309,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Unchanged, @@ -1720,6 +2329,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 8, relation: None, scc: SccEffect::Unchanged, @@ -1739,6 +2349,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 16, relation: None, scc: SccEffect::Unchanged, @@ -1758,6 +2369,7 @@ pub static FORMS: [FormSemantics; 40] = [ carry_in: CarryIn::None, width: 32, shift_count_bits: 0, + shift_amount: 0, source_bits: 32, relation: None, scc: SccEffect::Nonzero, diff --git a/crates/isa/tests/semantics.rs b/crates/isa/tests/semantics.rs index cfbb1d58..1e6eb07f 100644 --- a/crates/isa/tests/semantics.rs +++ b/crates/isa/tests/semantics.rs @@ -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) diff --git a/crates/loader/src/cpu.rs b/crates/loader/src/cpu.rs index 1f61376a..2547b974 100644 --- a/crates/loader/src/cpu.rs +++ b/crates/loader/src/cpu.rs @@ -65,6 +65,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. @@ -464,6 +466,7 @@ impl<'a> Interpreter<'a> { } 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()?; } @@ -794,7 +797,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 { @@ -804,7 +811,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 { diff --git a/crates/loader/tests/bootstrap.rs b/crates/loader/tests/bootstrap.rs index 9176b329..2573c708 100644 --- a/crates/loader/tests/bootstrap.rs +++ b/crates/loader/tests/bootstrap.rs @@ -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 ). +fn mov_rax_data_base() -> Vec { + let mut code = vec![0x48, 0xB8]; + code.extend_from_slice(&DATA_BASE.to_le_bytes()); + code +} + +/// `mov rbx, 0x12345678_9abcdef0` (48 BB ). +fn mov_rbx_value() -> Vec { + 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 ) + // mov r12, 4 (41 bc 04 00 00 00) + // mov rbx, 0x12345678_9abcdef0 (48 bb ) + // 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 ) + // mov r11, 0x11223344_55667788 (49 bb ) + // 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 ) + // mov r11, 0x11223344_55667788 (49 bb ) + // 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 ) + // 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 + ); +} diff --git a/crates/ref/src/lib.rs b/crates/ref/src/lib.rs index 5f5a22db..91c31d23 100644 --- a/crates/ref/src/lib.rs +++ b/crates/ref/src/lib.rs @@ -164,6 +164,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 @@ -371,35 +400,46 @@ pub fn decode(code: &[u8]) -> Result, 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)?; @@ -803,8 +843,13 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result 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 +878,65 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result { + 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 +955,16 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result { diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 5f35e622..29394c52 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -831,20 +831,22 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { 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 } => { diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index a860669c..f6eeee1e 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -322,6 +322,20 @@ 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_compares_lower_to_per_thread_wave_masks_and_selects() { let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin"); diff --git a/docs/assets/xenora-progress.svg b/docs/assets/xenora-progress.svg index 36f90586..61360e75 100644 --- a/docs/assets/xenora-progress.svg +++ b/docs/assets/xenora-progress.svg @@ -1,17 +1,17 @@ Xenora · recorded progress -Decoded gfx1030 forms: 72 of 72. Accepted Metal forms · Apple M5: 18 of 72. Accepted guest milestones · X1–X4: 4 of 4 +Decoded gfx1030 forms: 88 of 88. Accepted Metal forms · Apple M5: 18 of 88. Accepted guest milestones · X1–X4: 4 of 4 RECORDED FIXTURE PROGRESS Decoded gfx1030 forms -72 / 72 +88 / 88 Accepted Metal forms · Apple M5 -18 / 72 +18 / 88 - + Accepted guest milestones · X1–X4 4 / 4 diff --git a/docs/shaders/instruction-coverage.md b/docs/shaders/instruction-coverage.md index c324fadc..43ede3ef 100644 --- a/docs/shaders/instruction-coverage.md +++ b/docs/shaders/instruction-coverage.md @@ -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 | diff --git a/docs/shaders/reference-interpreter.md b/docs/shaders/reference-interpreter.md index d37c6d59..a0b7e95c 100644 --- a/docs/shaders/reference-interpreter.md +++ b/docs/shaders/reference-interpreter.md @@ -8,6 +8,7 @@ | 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. | diff --git a/docs/shaders/scalar-alu.md b/docs/shaders/scalar-alu.md index 6eaf4fe2..213e8965 100644 --- a/docs/shaders/scalar-alu.md +++ b/docs/shaders/scalar-alu.md @@ -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)`, 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}` diff --git a/docs/shaders/semantic-coverage.md b/docs/shaders/semantic-coverage.md index 41aab276..a685080e 100644 --- a/docs/shaders/semantic-coverage.md +++ b/docs/shaders/semantic-coverage.md @@ -25,7 +25,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt | SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | SOP1 | 65 | 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 | @@ -36,7 +36,7 @@ acceptance remain outside the verified count. All results concern synthetic fixt | VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 | -| **Total** | 1465 | 72 | 40 | 76 | 72 | 72 | 18 | 18 | 30 | +| **Total** | 1465 | 88 | 56 | 92 | 88 | 88 | 18 | 18 | 30 | ## Unsupported operand variants diff --git a/docs/shaders/semantic-registry.md b/docs/shaders/semantic-registry.md index 49e81e48..35ce5969 100644 --- a/docs/shaders/semantic-registry.md +++ b/docs/shaders/semantic-registry.md @@ -51,14 +51,15 @@ 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`, `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 | +| `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,6 +83,14 @@ 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 | A compare must use an operand rule of the compare kind (`sopc_scalar`: two @@ -103,7 +112,8 @@ vocabularies above, it rejects: - 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; diff --git a/docs/status.toml b/docs/status.toml index 0aacf618..a368eaee 100644 --- a/docs/status.toml +++ b/docs/status.toml @@ -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" diff --git a/fixtures/golden/scalar-arith.ir b/fixtures/golden/scalar-arith.ir new file mode 100644 index 00000000..7e37918d --- /dev/null +++ b/fixtures/golden/scalar-arith.ir @@ -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 diff --git a/fixtures/golden/scalar-arith.metal b/fixtures/golden/scalar-arith.metal new file mode 100644 index 00000000..69b97ebb --- /dev/null +++ b/fixtures/golden/scalar-arith.metal @@ -0,0 +1,45 @@ +#include +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; +} diff --git a/fixtures/pe/frame-loop.exe b/fixtures/pe/frame-loop.exe new file mode 100644 index 00000000..f4c9df85 Binary files /dev/null and b/fixtures/pe/frame-loop.exe differ diff --git a/fixtures/pe/frame-loop.py b/fixtures/pe/frame-loop.py new file mode 100644 index 00000000..41a422aa --- /dev/null +++ b/fixtures/pe/frame-loop.py @@ -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(" IAT] + code += b"\x48\xff\xc3" # inc rbx + code += b"\x48\x85\xc0" # test rax, rax + code += b"\x75" + pack(" primitive::ashr_nonzero_i32(src0, src1 & 0x1f),", + "let (value, scc) = primitive::ashr_nonzero_i32(src0, src1 & 0x1f);", gen.render(registry(), snapshot()), ) @@ -462,6 +488,77 @@ 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_compares(self): self.assertEqual(self.errors(compares()), []) diff --git a/tests/validation/independent_ref.rs b/tests/validation/independent_ref.rs index 9fd7e324..10be2c3a 100644 --- a/tests/validation/independent_ref.rs +++ b/tests/validation/independent_ref.rs @@ -13,7 +13,8 @@ //! 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 //! load/store and the two waits plus `s_endpgm`. Anything else is a controlled @@ -55,7 +56,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), @@ -318,8 +320,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 +453,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(()) } @@ -910,7 +995,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; diff --git a/tests/validation/known_answers.rs b/tests/validation/known_answers.rs index 7ba1e40f..277813b1 100644 --- a/tests/validation/known_answers.rs +++ b/tests/validation/known_answers.rs @@ -777,6 +777,9 @@ 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; // 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 +926,25 @@ mod review { verify(&set, &input, Some(&[0; 5])); } + #[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 +1096,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 +1171,8 @@ 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 mut vectors = sop2_vectors(); vectors.extend(sop2_operand_cases()); vectors.extend(signed_immediate_overflows()); @@ -1157,7 +1181,7 @@ mod review { } eprintln!( "{} SOP2 programs matched on native Metal", - vectors.len() + 4 + vectors.len() + 5 ); } diff --git a/tests/validation/tests/sop2_arith.rs b/tests/validation/tests/sop2_arith.rs new file mode 100644 index 00000000..725dc74d --- /dev/null +++ b/tests/validation/tests/sop2_arith.rs @@ -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) { + 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, 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, alu: &[u32], result: u32) -> Vec { + 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, + (s0, s1): (u32, u32), + scc: bool, + r: Option, +) -> 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 { + 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, 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, String>, +) -> Vec { + 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 { + 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 = 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() + ); +}