10 changed files with 15180 additions and 37 deletions

No files matched your search

+1
View File
@@ -20,6 +20,7 @@ pub mod pc_relative;
pub mod prefetch;
pub mod register_offset;
pub mod scalable;
pub mod semantics;
pub mod simd;
pub mod sme;
pub mod sve;
@@ -0,0 +1,604 @@
//! Explicit architectural semantics for core A64 integer flag-setting and
//! conditional-select instructions.
use super::{
Operation, Register, RegisterExtend, Shift, Width,
conditional_select::Otherwise,
flags::{NZCV_C, NZCV_N, NZCV_SHIFT, NZCV_V, NZCV_Z, condition_holds},
};
use crate::GuestState;
/// Bitmask of the four architectural condition flags (`N`, `Z`, `C`, `V`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FlagMask(u8);
impl FlagMask {
pub const NONE: Self = Self(0);
pub const N: Self = Self(1 << 3);
pub const Z: Self = Self(1 << 2);
pub const C: Self = Self(1 << 1);
pub const V: Self = Self(1 << 0);
pub const ALL: Self = Self(0b1111);
pub const fn bits(self) -> u8 {
self.0
}
pub const fn is_empty(self) -> bool {
self.0 == 0
}
pub const fn contains(self, other: Self) -> bool {
(self.0 & other.0) == other.0
}
pub const fn intersects(self, other: Self) -> bool {
(self.0 & other.0) != 0
}
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
pub const fn difference(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
pub const fn from_nzcv(nzcv: u32) -> Self {
Self(((nzcv >> NZCV_SHIFT) & 0xf) as u8)
}
pub const fn to_nzcv_mask(self) -> u32 {
(self.0 as u32) << NZCV_SHIFT
}
/// The subset of `NZCV` flags read by A64 condition `condition` (`0..16`).
pub const fn condition_reads(condition: u8) -> Self {
match condition >> 1 {
0 => Self::Z, // EQ / NE
1 => Self::C, // CS / CC
2 => Self::N, // MI / PL
3 => Self::V, // VS / VC
4 => Self(Self::C.0 | Self::Z.0), // HI / LS
5 => Self(Self::N.0 | Self::V.0), // GE / LT
6 => Self(Self::N.0 | Self::Z.0 | Self::V.0), // GT / LE
_ => Self::NONE, // AL / NV
}
}
}
/// Bitmask over architectural integer state (`X0..=X30` in bits `0..=30`, `SP` in bit `31`).
/// `XZR`/`WZR` (`Register::Zero`) is excluded because reads yield 0 and writes discard.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RegisterSet(u32);
impl RegisterSet {
pub const NONE: Self = Self(0);
pub const fn bits(self) -> u32 {
self.0
}
pub const fn is_empty(self) -> bool {
self.0 == 0
}
pub const fn of(register: Register) -> Self {
match Self::bit(register) {
Some(bit) => Self(bit),
None => Self::NONE,
}
}
pub fn from_registers(registers: impl IntoIterator<Item = Register>) -> Self {
registers
.into_iter()
.fold(Self::NONE, |set, register| set.union(Self::of(register)))
}
pub const fn contains(self, register: Register) -> bool {
match Self::bit(register) {
Some(bit) => (self.0 & bit) != 0,
None => false,
}
}
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
pub const fn difference(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
pub const fn intersects(self, other: Self) -> bool {
(self.0 & other.0) != 0
}
const fn bit(register: Register) -> Option<u32> {
match register {
Register::X(index) if index < 31 => Some(1u32 << index),
Register::Sp => Some(1u32 << 31),
Register::X(_) | Register::Zero => None,
}
}
}
/// How an ALU operand is sourced before optional bitwise inversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueSource {
Register(Register),
Immediate(u64),
ShiftedRegister {
register: Register,
shift: Shift,
amount: u8,
},
ExtendedRegister {
register: Register,
extend: RegisterExtend,
amount: u8,
},
}
/// Carry input consumed by [`SemanticKind::AddWithCarry`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CarryInput {
Zero,
One,
CarryFlag,
}
/// Pure architectural effect shape for a lifted instruction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SemanticKind {
/// Arm `AddWithCarry(left, if invert_right { NOT(right) } else { right }, carry_in)`.
AddWithCarry {
left: ValueSource,
right: ValueSource,
invert_right: bool,
carry_in: CarryInput,
set_flags: bool,
destination: Register,
},
/// Arm `CSEL`/`CSINC`/`CSINV`/`CSNEG`: chooses `true_register` if `ConditionHolds(condition)`,
/// otherwise transforms `false_register` per `otherwise`; never modifies `NZCV`.
ConditionalSelect {
condition: u8,
true_register: Register,
false_register: Register,
otherwise: Otherwise,
destination: Register,
},
}
/// Explicit per-instruction operand width, register/flag side effects, and semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InstructionSemantics {
pub width: Width,
pub gpr_reads: RegisterSet,
pub gpr_writes: RegisterSet,
pub flag_reads: FlagMask,
pub flag_writes: FlagMask,
pub kind: SemanticKind,
}
/// Return explicit architectural semantics for supported integer arithmetic,
/// carry arithmetic, and conditional select operations.
pub fn semantics_of(operation: &Operation) -> Option<InstructionSemantics> {
match *operation {
Operation::AddSub {
width,
subtract,
flags,
destination,
source,
immediate,
} => Some(InstructionSemantics {
width,
gpr_reads: RegisterSet::of(source),
gpr_writes: RegisterSet::of(destination),
flag_reads: FlagMask::NONE,
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
kind: SemanticKind::AddWithCarry {
left: ValueSource::Register(source),
right: ValueSource::Immediate(u64::from(immediate)),
invert_right: subtract,
carry_in: if subtract {
CarryInput::One
} else {
CarryInput::Zero
},
set_flags: flags,
destination,
},
}),
Operation::AddSubRegister {
width,
subtract,
flags,
destination,
left,
right,
shift,
amount,
} => Some(InstructionSemantics {
width,
gpr_reads: RegisterSet::from_registers([left, right]),
gpr_writes: RegisterSet::of(destination),
flag_reads: FlagMask::NONE,
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
kind: SemanticKind::AddWithCarry {
left: ValueSource::Register(left),
right: ValueSource::ShiftedRegister {
register: right,
shift,
amount,
},
invert_right: subtract,
carry_in: if subtract {
CarryInput::One
} else {
CarryInput::Zero
},
set_flags: flags,
destination,
},
}),
Operation::AddSubExtended {
width,
subtract,
flags,
destination,
left,
right,
extend,
amount,
} => Some(InstructionSemantics {
width,
gpr_reads: RegisterSet::from_registers([left, right]),
gpr_writes: RegisterSet::of(destination),
flag_reads: FlagMask::NONE,
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
kind: SemanticKind::AddWithCarry {
left: ValueSource::Register(left),
right: ValueSource::ExtendedRegister {
register: right,
extend,
amount,
},
invert_right: subtract,
carry_in: if subtract {
CarryInput::One
} else {
CarryInput::Zero
},
set_flags: flags,
destination,
},
}),
Operation::AddSubCarry {
width,
subtract,
flags,
destination,
left,
right,
} => Some(InstructionSemantics {
width,
gpr_reads: RegisterSet::from_registers([left, right]),
gpr_writes: RegisterSet::of(destination),
flag_reads: FlagMask::C,
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
kind: SemanticKind::AddWithCarry {
left: ValueSource::Register(left),
right: ValueSource::Register(right),
invert_right: subtract,
carry_in: CarryInput::CarryFlag,
set_flags: flags,
destination,
},
}),
Operation::ConditionalSelect(op) if op.condition < 16 => {
let reads = if op.condition >= 14 {
RegisterSet::of(op.left)
} else {
RegisterSet::from_registers([op.left, op.right])
};
Some(InstructionSemantics {
width: op.width,
gpr_reads: reads,
gpr_writes: RegisterSet::of(op.destination),
flag_reads: FlagMask::condition_reads(op.condition),
flag_writes: FlagMask::NONE,
kind: SemanticKind::ConditionalSelect {
condition: op.condition,
true_register: op.left,
false_register: op.right,
otherwise: op.otherwise,
destination: op.destination,
},
})
}
_ => None,
}
}
/// Exact Arm `AddWithCarry(N, x, y, carry_in)` specification returning `(result, nzcv)`.
pub fn add_with_carry(width: Width, left: u64, right: u64, carry_in: bool) -> (u64, u32) {
let carry = u128::from(carry_in);
let carry_signed = i128::from(carry_in);
let (result, negative, unsigned_sum, signed_matches) = match width {
Width::W32 => {
let x = left as u32;
let y = right as u32;
let unsigned_sum = u128::from(x) + u128::from(y) + carry;
let signed_sum = i128::from(x as i32) + i128::from(y as i32) + carry_signed;
let result = unsigned_sum as u32;
let negative = (result >> 31) != 0;
let signed_matches = i128::from(result as i32) == signed_sum;
(u64::from(result), negative, unsigned_sum, signed_matches)
}
Width::X64 => {
let unsigned_sum = u128::from(left) + u128::from(right) + carry;
let signed_sum = i128::from(left as i64) + i128::from(right as i64) + carry_signed;
let result = unsigned_sum as u64;
let negative = (result >> 63) != 0;
let signed_matches = i128::from(result as i64) == signed_sum;
(result, negative, unsigned_sum, signed_matches)
}
};
let mut nzcv = 0u32;
if negative {
nzcv |= NZCV_N;
}
if result == 0 {
nzcv |= NZCV_Z;
}
if unsigned_sum != u128::from(result) {
nzcv |= NZCV_C;
}
if !signed_matches {
nzcv |= NZCV_V;
}
(result, nzcv)
}
/// Reference architectural execution of a modeled instruction on `state`.
pub fn eval_instruction(semantics: &InstructionSemantics, state: &mut GuestState) {
let width = semantics.width;
match semantics.kind {
SemanticKind::AddWithCarry {
left,
right,
invert_right,
carry_in,
set_flags,
destination,
} => {
let lhs = eval_value_source(width, left, state);
let mut rhs = eval_value_source(width, right, state);
if invert_right {
rhs = mask_width(width, !rhs);
}
let carry = match carry_in {
CarryInput::Zero => false,
CarryInput::One => true,
CarryInput::CarryFlag => (state.nzcv & NZCV_C) != 0,
};
let (result, nzcv) = add_with_carry(width, lhs, rhs, carry);
write_register(width, destination, result, state);
if set_flags {
state.nzcv = nzcv;
}
}
SemanticKind::ConditionalSelect {
condition,
true_register,
false_register,
otherwise,
destination,
} => {
let selected = if condition_holds(condition, state.nzcv) {
read_register(width, true_register, state)
} else {
let value = read_register(width, false_register, state);
let adjusted = match otherwise {
Otherwise::Unchanged => value,
Otherwise::Increment => value.wrapping_add(1),
Otherwise::Invert => !value,
Otherwise::Negate => value.wrapping_neg(),
};
mask_width(width, adjusted)
};
write_register(width, destination, selected, state);
}
}
}
fn mask_width(width: Width, value: u64) -> u64 {
match width {
Width::W32 => u64::from(value as u32),
Width::X64 => value,
}
}
fn read_register(width: Width, register: Register, state: &GuestState) -> u64 {
let raw = match register {
Register::X(index) if index < 31 => state.x[usize::from(index)],
Register::Sp => state.sp,
Register::X(_) | Register::Zero => 0,
};
mask_width(width, raw)
}
fn write_register(width: Width, register: Register, value: u64, state: &mut GuestState) {
let value = mask_width(width, value);
match register {
Register::X(index) if index < 31 => state.x[usize::from(index)] = value,
Register::Sp => state.sp = value,
Register::X(_) | Register::Zero => {}
}
}
fn eval_value_source(width: Width, source: ValueSource, state: &GuestState) -> u64 {
match source {
ValueSource::Register(register) => read_register(width, register, state),
ValueSource::Immediate(immediate) => mask_width(width, immediate),
ValueSource::ShiftedRegister {
register,
shift,
amount,
} => {
let raw = read_register(width, register, state);
let shifted = match width {
Width::W32 => {
let val = raw as u32;
let out = if amount == 0 {
val
} else {
match shift {
Shift::Lsl => val.wrapping_shl(u32::from(amount)),
Shift::Lsr => val.wrapping_shr(u32::from(amount)),
Shift::Asr => ((val as i32).wrapping_shr(u32::from(amount))) as u32,
Shift::Ror => val.rotate_right(u32::from(amount)),
}
};
u64::from(out)
}
Width::X64 => {
if amount == 0 {
raw
} else {
match shift {
Shift::Lsl => raw.wrapping_shl(u32::from(amount)),
Shift::Lsr => raw.wrapping_shr(u32::from(amount)),
Shift::Asr => ((raw as i64).wrapping_shr(u32::from(amount))) as u64,
Shift::Ror => raw.rotate_right(u32::from(amount)),
}
}
}
};
mask_width(width, shifted)
}
ValueSource::ExtendedRegister {
register,
extend,
amount,
} => {
let raw = read_register(Width::X64, register, state);
let extended = match extend {
RegisterExtend::Uxtb => u64::from(raw as u8),
RegisterExtend::Uxth => u64::from(raw as u16),
RegisterExtend::Uxtw => u64::from(raw as u32),
RegisterExtend::Uxtx => raw,
RegisterExtend::Sxtb => i64::from(raw as i8) as u64,
RegisterExtend::Sxth => i64::from(raw as i16) as u64,
RegisterExtend::Sxtw => i64::from(raw as i32) as u64,
RegisterExtend::Sxtx => raw,
};
mask_width(width, extended.wrapping_shl(u32::from(amount)))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{GuestAddress, Lifter, aarch64::Decoder};
fn decode(word: u32) -> Operation {
Decoder.lift(GuestAddress(0x1000), word).unwrap().operation
}
#[test]
fn adds_adcs_sbcs_csel_explicit_effects_and_zero_register() {
// ADDS X4, X0, X2 (0xab02_0004)
let adds_x = semantics_of(&decode(0xab02_0004)).unwrap();
assert_eq!(adds_x.width, Width::X64);
assert_eq!(
adds_x.gpr_reads,
RegisterSet::from_registers([Register::X(0), Register::X(2)])
);
assert_eq!(adds_x.gpr_writes, RegisterSet::of(Register::X(4)));
assert_eq!(adds_x.flag_reads, FlagMask::NONE);
assert_eq!(adds_x.flag_writes, FlagMask::ALL);
// ADDS WZR, W1, #1 (CMN W1, #1: 0x3100_043f)
let cmn_w = semantics_of(&decode(0x3100_043f)).unwrap();
assert_eq!(cmn_w.width, Width::W32);
assert_eq!(cmn_w.gpr_reads, RegisterSet::of(Register::X(1)));
assert_eq!(cmn_w.gpr_writes, RegisterSet::NONE);
assert_eq!(cmn_w.flag_reads, FlagMask::NONE);
assert_eq!(cmn_w.flag_writes, FlagMask::ALL);
// ADCS X5, X1, X3 (0xba03_0025)
let adcs_x = semantics_of(&decode(0xba03_0025)).unwrap();
assert_eq!(adcs_x.flag_reads, FlagMask::C);
assert_eq!(adcs_x.flag_writes, FlagMask::ALL);
// SBCS W6, W5, W4 (0x7a04_00a6)
let sbcs_w = semantics_of(&decode(0x7a04_00a6)).unwrap();
assert_eq!(sbcs_w.width, Width::W32);
assert_eq!(sbcs_w.flag_reads, FlagMask::C);
assert_eq!(sbcs_w.flag_writes, FlagMask::ALL);
assert!(matches!(
sbcs_w.kind,
SemanticKind::AddWithCarry {
invert_right: true,
carry_in: CarryInput::CarryFlag,
..
}
));
// CSEL X6, X4, X5, CS (0x9a85_2086)
let csel_cs = semantics_of(&decode(0x9a85_2086)).unwrap();
assert_eq!(csel_cs.flag_reads, FlagMask::C);
assert_eq!(csel_cs.flag_writes, FlagMask::NONE);
assert_eq!(
csel_cs.gpr_reads,
RegisterSet::from_registers([Register::X(4), Register::X(5)])
);
// CSEL W0, W0, W1, AL (0x1a81_e000): unconditional ignores W1 and reads no flags
let csel_al = semantics_of(&decode(0x1a81_e000)).unwrap();
assert_eq!(csel_al.width, Width::W32);
assert_eq!(csel_al.flag_reads, FlagMask::NONE);
assert_eq!(csel_al.flag_writes, FlagMask::NONE);
assert_eq!(csel_al.gpr_reads, RegisterSet::of(Register::X(0)));
assert_eq!(csel_al.gpr_writes, RegisterSet::of(Register::X(0)));
}
#[test]
fn add_with_carry_covers_carry_borrow_overflow_and_zero_edges() {
// W32: 0xffff_ffff + 0 + C=1 -> 0, Z=1 C=1 N=0 V=0 (0x6000_0000)
assert_eq!(
add_with_carry(Width::W32, 0xffff_ffff, 0, true),
(0, NZCV_Z | NZCV_C)
);
// X64: 0xffff_ffff + 0 + C=1 -> 0x1_0000_0000, all flags clear
assert_eq!(
add_with_carry(Width::X64, 0xffff_ffff, 0, true),
(0x1_0000_0000, 0)
);
// W32 signed overflow from carry alone: 0x7fff_ffff + 0 + 1 -> 0x8000_0000, N=1 V=1
assert_eq!(
add_with_carry(Width::W32, 0x7fff_ffff, 0, true),
(0x8000_0000, NZCV_N | NZCV_V)
);
// SBCS W32: INT_MIN - 0 with borrow (C=0): AddWithCarry(0x8000_0000, 0xffff_ffff, false)
assert_eq!(
add_with_carry(Width::W32, 0x8000_0000, !0u32 as u64, false),
(0x7fff_ffff, NZCV_C | NZCV_V)
);
// SBCS X64: 0 - 0 with C=1 (no borrow): 0, Z=1 C=1
assert_eq!(
add_with_carry(Width::X64, 0, !0u64, true),
(0, NZCV_Z | NZCV_C)
);
// SBCS X64: 0 - 0 with C=0 (borrow): u64::MAX, N=1
assert_eq!(
add_with_carry(Width::X64, 0, !0u64, false),
(u64::MAX, NZCV_N)
);
}
}
+2
View File
@@ -6,6 +6,7 @@
//! runtime helper when software PAuth is enabled.
mod analysis;
pub mod effects;
mod features;
mod host_gprs;
pub mod loop_budget;
@@ -26,6 +27,7 @@ pub use analysis::{
SuccessorKind, analyze, analyze_with_profile, source_bytes, source_bytes_with_profile,
};
use analysis::{ParsedBlock, analyze_parsed, parse_admitted, parse_with};
pub use effects::{BlockEffects, analyze_block_effects, eval_instructions, summarize_instructions};
pub use features::{BlockProfile, Features};
pub use host_gprs::HostGprSnapshot;
pub use memory::{
+259
View File
@@ -0,0 +1,259 @@
//! Basic-block architectural side-effect composition built from per-instruction semantics.
use super::BlockProfile;
use super::analysis::{BlockAnalysisError, parse};
use crate::{
GuestAddress, GuestState,
aarch64::{
Instruction, Operation, Register,
semantics::{FlagMask, RegisterSet, eval_instruction, semantics_of},
},
};
use alloc::vec::Vec;
/// Composed register and NZCV side-effect summary across a basic block.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockEffects {
pub instruction_count: usize,
pub fully_modeled: bool,
pub live_in_gprs: RegisterSet,
pub written_gprs: RegisterSet,
pub live_in_flags: FlagMask,
pub written_flags: FlagMask,
pub killed_flags: FlagMask,
/// Indices of instructions whose `NZCV` write is overwritten by a later
/// instruction that redefines `FlagMask::ALL` before any bit is read.
pub dead_flag_defs: Vec<usize>,
}
/// Summarize architectural register reads/writes, `NZCV` live-ins, and intra-block
/// dead flag definitions across `instructions`.
pub fn summarize_instructions(instructions: &[Instruction]) -> BlockEffects {
summarize_with_exit(instructions, FlagMask::NONE, RegisterSet::NONE)
}
/// Parse `source` at `base` using the ordinary block parser and compose its
/// body effects together with any architectural terminal flag/register read.
pub fn analyze_block_effects(
source: &[u8],
base: GuestAddress,
) -> Result<BlockEffects, BlockAnalysisError> {
let parsed = parse(source, base, BlockProfile::ORDINARY)?;
let (exit_flags, exit_gprs) = match parsed.terminal.as_ref().map(|(_, term)| term) {
Some(super::Terminator::Branch(Operation::BranchCondition { condition, .. })) => {
(FlagMask::condition_reads(*condition), RegisterSet::NONE)
}
Some(super::Terminator::Branch(
Operation::BranchZero { source, .. } | Operation::BranchBit { source, .. },
)) => (FlagMask::NONE, RegisterSet::of(*source)),
Some(super::Terminator::Register { source, .. }) => {
(FlagMask::NONE, RegisterSet::of(*source))
}
Some(super::Terminator::DirectCall(_)) => (FlagMask::NONE, RegisterSet::NONE),
Some(super::Terminator::Trap(_))
| Some(super::Terminator::System(_))
| Some(super::Terminator::PointerAuthentication(_))
| Some(super::Terminator::Clock(_))
| Some(super::Terminator::ThreadRegister(_))
| Some(super::Terminator::FloatingPoint { .. })
| Some(super::Terminator::Amx(_)) => (FlagMask::ALL, RegisterSet::NONE),
_ => (FlagMask::NONE, RegisterSet::NONE),
};
let mut effects = summarize_with_exit(&parsed.instructions, exit_flags, exit_gprs);
if matches!(
parsed.terminal.as_ref().map(|(_, term)| term),
Some(super::Terminator::Trap(_))
| Some(super::Terminator::System(_))
| Some(super::Terminator::PointerAuthentication(_))
| Some(super::Terminator::Clock(_))
| Some(super::Terminator::ThreadRegister(_))
| Some(super::Terminator::FloatingPoint { .. })
| Some(super::Terminator::Amx(_))
) {
effects.fully_modeled = false;
}
Ok(effects)
}
fn summarize_with_exit(
instructions: &[Instruction],
exit_flag_reads: FlagMask,
exit_gpr_reads: RegisterSet,
) -> BlockEffects {
let mut fully_modeled = true;
let mut written_gprs = RegisterSet::NONE;
let mut live_in_gprs = RegisterSet::NONE;
let mut defined_all_flags = false;
let mut written_flags = FlagMask::NONE;
let mut live_in_flags = FlagMask::NONE;
let mut live_before_write_flags = FlagMask::NONE;
for instruction in instructions {
let Some(sem) = semantics_of(&instruction.operation) else {
fully_modeled = false;
continue;
};
let uncovered_gprs = sem.gpr_reads.difference(written_gprs);
live_in_gprs = live_in_gprs.union(uncovered_gprs);
written_gprs = written_gprs.union(sem.gpr_writes);
if !defined_all_flags {
let unread_entry_flags = sem.flag_reads.difference(live_before_write_flags);
live_in_flags = live_in_flags.union(unread_entry_flags);
}
written_flags = written_flags.union(sem.flag_writes);
if sem.flag_writes == FlagMask::ALL {
defined_all_flags = true;
live_before_write_flags = FlagMask::ALL;
}
}
if !defined_all_flags {
live_in_flags = live_in_flags.union(exit_flag_reads);
}
live_in_gprs = live_in_gprs.union(exit_gpr_reads.difference(written_gprs));
// Backward pass for intra-block dead flag definitions: NZCV is architecturally
// live-out at block exit (`FlagMask::ALL`), so an instruction's flag write
// is dead only if a later instruction in the same block overwrites every bit
// it wrote before any intervening reader (or exit) observes them.
let _ = exit_flag_reads;
let mut live_flags_after = FlagMask::ALL;
let mut dead_flag_defs = Vec::new();
for (index, instruction) in instructions.iter().enumerate().rev() {
let Some(sem) = semantics_of(&instruction.operation) else {
// Unknown instructions may observe NZCV on block exit/fallback.
live_flags_after = FlagMask::ALL;
continue;
};
if !sem.flag_writes.is_empty() && !live_flags_after.intersects(sem.flag_writes) {
dead_flag_defs.push(index);
}
live_flags_after = live_flags_after
.difference(sem.flag_writes)
.union(sem.flag_reads);
}
dead_flag_defs.reverse();
let killed_flags = if defined_all_flags {
written_flags.difference(live_in_flags)
} else {
FlagMask::NONE
};
BlockEffects {
instruction_count: instructions.len(),
fully_modeled,
live_in_gprs,
written_gprs,
live_in_flags,
written_flags,
killed_flags,
dead_flag_defs,
}
}
/// Evaluate a slice of modeled instructions sequentially on `state`. Returns `None`
/// if any instruction falls outside [`semantics_of`].
pub fn eval_instructions(instructions: &[Instruction], state: &mut GuestState) -> Option<()> {
for instruction in instructions {
let sem = semantics_of(&instruction.operation)?;
eval_instruction(&sem, state);
}
Some(())
}
/// Convenience helper for callers inspecting which `Register::X(i)` indices are in `set`.
pub fn gpr_indices(set: RegisterSet) -> Vec<u8> {
(0..31u8)
.filter(|&i| set.contains(Register::X(i)))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Lifter, aarch64::Decoder};
fn lift_words(words: &[u32]) -> Vec<Instruction> {
words
.iter()
.enumerate()
.map(|(i, &w)| {
Decoder
.lift(GuestAddress(0x1000 + i as u64 * 4), w)
.unwrap()
})
.collect()
}
#[test]
fn summarizes_carry_chain_and_dead_flag_kill() {
// adds x4, x0, x2; adcs x5, x1, x3; csel x6, x4, x5, cs
let u128_chain = lift_words(&[0xab02_0004, 0xba03_0025, 0x9a85_2086]);
let effects = summarize_instructions(&u128_chain);
assert!(effects.fully_modeled);
assert_eq!(effects.live_in_flags, FlagMask::NONE);
assert_eq!(effects.written_flags, FlagMask::ALL);
assert_eq!(effects.killed_flags, FlagMask::ALL);
// ADCS reads C from ADDS, CSEL reads C from ADCS, and NZCV is live-out at exit.
assert!(effects.dead_flag_defs.is_empty());
assert_eq!(
effects.live_in_gprs,
RegisterSet::from_registers([
Register::X(0),
Register::X(1),
Register::X(2),
Register::X(3),
])
);
assert_eq!(
effects.written_gprs,
RegisterSet::from_registers([Register::X(4), Register::X(5), Register::X(6)])
);
// ADDS -> CSEL AL -> ADDS: CSEL AL reads no flags, so index 0 is dead.
let al_kill = lift_words(&[0xab01_0004, 0x9a85_e086, 0xab03_0045]);
let al_effects = summarize_instructions(&al_kill);
assert_eq!(al_effects.live_in_flags, FlagMask::NONE);
assert_eq!(al_effects.dead_flag_defs, vec![0]);
}
#[test]
fn adcs_leading_block_requires_only_carry_in() {
// adcs x4, x0, x2; sbcs x5, x1, x3; csel x6, x4, x5, hi
let instructions = lift_words(&[0xba02_0004, 0xfa03_0025, 0x9a85_8086]);
let effects = summarize_instructions(&instructions);
assert_eq!(effects.live_in_flags, FlagMask::C);
// Flipping N, Z, or V in entry NZCV must not change the output state.
let mut s1 = GuestState::default();
s1.x[0] = 0xffff_ffff_ffff_ffff;
s1.x[1] = 10;
s1.x[2] = 0;
s1.x[3] = 4;
s1.nzcv = crate::aarch64::flags::NZCV_C;
let mut s2 = s1.clone();
s2.nzcv |= crate::aarch64::flags::NZCV_N
| crate::aarch64::flags::NZCV_Z
| crate::aarch64::flags::NZCV_V;
eval_instructions(&instructions, &mut s1).unwrap();
eval_instructions(&instructions, &mut s2).unwrap();
assert_eq!(s1.x, s2.x);
assert_eq!(s1.nzcv, s2.nzcv);
}
#[test]
fn unmodeled_trailing_instruction_keeps_flags_live_after_last_writer() {
// adds x4, x0, x1; adds x5, x2, x3; csel x6, x4, x5, eq; branch exit
let bytes: Vec<u8> = [0xab01_0004u32, 0xab03_0045, 0x9a85_0086, 0x5400_0040]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect();
let effects = analyze_block_effects(&bytes, GuestAddress(0x1000)).unwrap();
assert!(effects.fully_modeled);
assert_eq!(effects.live_in_flags, FlagMask::NONE);
// First ADDS is dead because second ADDS overwrites all flags before CSEL EQ & B.EQ.
assert_eq!(effects.dead_flag_defs, vec![0]);
}
}
+68 -14
View File
@@ -11,11 +11,13 @@ use clap::Args;
use std::{
collections::BTreeMap,
io::{Read, Write},
path::PathBuf,
process::{Command, Stdio},
};
mod corpus;
mod record;
mod semantics_verify;
mod stela;
use record::{Case, Ending, INPUT_BYTES, OUTPUT_BYTES};
@@ -62,17 +64,41 @@ pub struct CpuReference {
/// Rewrite the recorded table from this Mac run.
#[arg(long)]
record: bool,
/// Recorded table path to read or write (default: `xtask/src/cpu_reference/apple-m1-pro.tsv`).
#[arg(long)]
table: Option<PathBuf>,
/// Only the cases whose name contains this text.
#[arg(long)]
only: Option<String>,
/// List the case names and exit.
#[arg(long)]
list: bool,
/// Verify explicit Arm instruction semantics, block side effects, and
/// multi-tier Stela compilation against the M4 corpus.
#[arg(long)]
verify_semantics: bool,
}
impl CpuReference {
pub fn run(self) -> Result<()> {
let cases: Vec<Case> = corpus::all()
if self.verify_semantics {
semantics_verify::verify_m4_semantics()?;
if self.only.is_none()
&& self.mac.is_none()
&& !self.recorded
&& !self.record
&& !self.list
{
return Ok(());
}
}
let using_m1_default = self.table.is_none();
let all_cases = if self.recorded && using_m1_default {
corpus::m1_baseline()
} else {
corpus::all()
};
let cases: Vec<Case> = all_cases
.into_iter()
.filter(|case| {
self.only
@@ -89,16 +115,16 @@ impl CpuReference {
}
ensure!(!cases.is_empty(), "no case matches");
let (reference, source) = if self.recorded {
let table = recorded()?;
let table = match &self.table {
Some(path) => recorded_from_path(path)?,
None => recorded()?,
};
let outcomes = cases
.iter()
.map(|case| {
table
.get(case.name.as_str())
.map(|outcome| outcome.to_string())
.with_context(|| {
format!("{} is not recorded; run with --record", case.name)
})
table.get(case.name.as_str()).cloned().with_context(|| {
format!("{} is not recorded; run with --record", case.name)
})
})
.collect::<Result<Vec<_>>>()?;
(outcomes, "recorded")
@@ -112,7 +138,11 @@ impl CpuReference {
.collect();
if self.record {
ensure!(self.only.is_none(), "--record keeps every case");
write_table(&host, &cases, &outcomes)?;
let target_path = self
.table
.clone()
.unwrap_or_else(|| PathBuf::from(TABLE_PATH));
write_table(&host, &target_path, &cases, &outcomes)?;
}
(outcomes, "mac")
};
@@ -203,21 +233,41 @@ fn ssh(host: &str, script: &str) -> Command {
}
/// The recorded table: case name to outcome.
fn recorded() -> Result<BTreeMap<&'static str, &'static str>> {
fn recorded() -> Result<BTreeMap<String, String>> {
parse_table(TABLE)
}
fn recorded_from_path(path: &std::path::Path) -> Result<BTreeMap<String, String>> {
let resolved = if path.is_absolute() {
path.to_path_buf()
} else {
crate::tools::root().join(path)
};
let text = std::fs::read_to_string(&resolved)
.with_context(|| format!("cannot read table {}", resolved.display()))?;
parse_table(&text)
}
fn parse_table(text: &str) -> Result<BTreeMap<String, String>> {
let mut table = BTreeMap::new();
for line in TABLE
for line in text
.lines()
.filter(|line| !line.starts_with('#') && !line.is_empty())
{
let Some((name, outcome)) = line.split_once('\t') else {
bail!("malformed recorded line {line:?}");
};
table.insert(name, outcome);
table.insert(name.to_string(), outcome.to_string());
}
Ok(table)
}
fn write_table(host: &str, cases: &[Case], outcomes: &[String]) -> Result<()> {
fn write_table(
host: &str,
target: &std::path::Path,
cases: &[Case],
outcomes: &[String],
) -> Result<()> {
let identity = Command::new("ssh")
.args([
"-o",
@@ -235,7 +285,11 @@ fn write_table(host: &str, cases: &[Case], outcomes: &[String]) -> Result<()> {
for (case, outcome) in cases.iter().zip(outcomes) {
text.push_str(&format!("{}\t{outcome}\n", case.name));
}
let path = crate::tools::root().join(TABLE_PATH);
let path = if target.is_absolute() {
target.to_path_buf()
} else {
crate::tools::root().join(target)
};
std::fs::write(&path, text)?;
println!("recorded {}", path.display());
Ok(())
File diff suppressed because it is too large. Load diff
+339 -2
View File
@@ -862,8 +862,8 @@ fn register_overlaps(cases: &mut Vec<Case>) {
.push(Case::new("overlap.control.ldp.post", &[0xa8c1_1043]).memory(2, 16, &MEMORY_PATTERN));
}
/// Every case, in a fixed order.
pub fn all() -> Vec<Case> {
/// The existing Apple M1 Pro baseline corpus, in fixed order.
pub fn m1_baseline() -> Vec<Case> {
let mut cases = Vec::new();
fp_conversions(&mut cases);
fp_rounding(&mut cases);
@@ -880,6 +880,343 @@ pub fn all() -> Vec<Case> {
cases
}
/// Apple M4 differential corpus covering ADDS, ADCS, SBCS, CSEL, and
/// multi-instruction basic blocks.
pub fn m4_flags_csel() -> Vec<Case> {
let mut cases = Vec::new();
m4_adds(&mut cases);
m4_carry_arith(&mut cases);
m4_csel(&mut cases);
m4_blocks(&mut cases);
cases
}
fn m4_adds(cases: &mut Vec<Case>) {
let imm_forms: [(&str, u32); 9] = [
("w.imm0", 0x3100_0020), // adds w0, w1, #0
("w.imm1", 0x3100_0420), // adds w0, w1, #1
("w.imm_fff", 0x313f_fc20), // adds w0, w1, #0xfff
("w.imm1_lsl12", 0x3140_0420), // adds w0, w1, #1, lsl #12
("w.imm_fff_lsl12", 0x317f_fc20), // adds w0, w1, #0xfff, lsl #12
("w.cmn_fff", 0x313f_fc3f), // cmn w1, #0xfff (rd=wzr)
("x.imm1", 0xb100_0420), // adds x0, x1, #1
("x.imm_fff_lsl12", 0xb17f_fc20), // adds x0, x1, #0xfff, lsl #12
("x.cmn_fff", 0xb13f_fc3f), // cmn x1, #0xfff (rd=xzr)
];
let inputs = [
0u64,
0x7fff_ffff,
0x8000_0000,
0xffff_ffff,
0xdead_beef_ffff_ffff,
0xfeed_face_7fff_ffff,
0x7fff_ffff_ffff_ffff,
0xffff_ffff_ffff_ffff,
];
for (form, word) in imm_forms {
for (i, &val) in inputs.iter().enumerate() {
cases.push(
Case::new(format!("m4.adds.{form}.{i}"), &[word])
.x(0, 0xaaaa_bbbb_cccc_dddd)
.x(1, val)
.nzcv(0xf000_0000),
);
}
}
let shift_forms: [(&str, u32); 8] = [
("w.lsl3", 0x2b02_0c20), // adds w0, w1, w2, lsl #3
("w.lsr1", 0x2b42_0420), // adds w0, w1, w2, lsr #1
("w.asr31", 0x2b82_7c20), // adds w0, w1, w2, asr #31
("w.cmn_lsl3", 0x2b02_0c3f), // cmn w1, w2, lsl #3
("x.lsl3", 0xab02_0c20), // adds x0, x1, x2, lsl #3
("x.lsr1", 0xab42_0420), // adds x0, x1, x2, lsr #1
("x.asr63", 0xab82_fc20), // adds x0, x1, x2, asr #63
("x.cmn_lsl3", 0xab02_0c3f), // cmn x1, x2, lsl #3
];
let pairs = [
(0u64, 0u64),
(0x7fff_ffff, 1),
(0xdead_beef_ffff_ffff, 0xfeed_face_2000_0000),
(0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff),
];
for (form, word) in shift_forms {
for (i, &(a, b)) in pairs.iter().enumerate() {
cases.push(
Case::new(format!("m4.adds.{form}.{i}"), &[word])
.x(0, 0x1234_5678_9abc_def0)
.x(1, a)
.x(2, b)
.nzcv(0xf000_0000),
);
}
}
}
fn m4_carry_arith(cases: &mut Vec<Case>) {
// Non-C flags (N,Z,V) are set in `c0` to prove carry ops read only `C`.
let carry_states = [("c0", 0xd000_0000u64), ("c1", 0x2000_0000u64)];
let adcs_pairs = [
("zero", 0u64, 0u64),
("w32_carry_zero", 0xdead_beef_ffff_ffff, 0),
("w32_ovf_carry", 0xfeed_face_7fff_ffff, 0),
("x64_ovf_carry", 0x7fff_ffff_ffff_ffff, 0),
("x64_max_max", u64::MAX, u64::MAX),
(
"x64_sign_wrap",
0x8000_0000_0000_0000,
0x8000_0000_0000_0000,
),
];
for (wlabel, word) in [("w", 0x3a02_0020u32), ("x", 0xba02_0020)] {
for (plabel, a, b) in adcs_pairs {
for (clabel, nzcv) in carry_states {
cases.push(
Case::new(format!("m4.adcs.{wlabel}.{plabel}.{clabel}"), &[word])
.x(0, 0x5555_5555_5555_5555)
.x(1, a)
.x(2, b)
.nzcv(nzcv),
);
}
}
}
for (label, word) in [
("w.alias_all", 0x3a00_0000u32), // adcs w0, w0, w0
("x.alias_all", 0xba00_0000), // adcs x0, x0, x0
("x.alias_rd_rm", 0xba01_0041), // adcs x1, x2, x1
("w.alias_rd_rm", 0x3a01_0041), // adcs w1, w2, w1
("x.rd_zr", 0xba02_003f), // adcs xzr, x1, x2
("x.rn_rm_zr", 0xba1f_03e0), // adcs x0, xzr, xzr
] {
for (clabel, nzcv) in carry_states {
cases.push(
Case::new(format!("m4.adcs.{label}.{clabel}"), &[word])
.x(0, 0xfeed_face_7fff_ffff)
.x(1, 0x8000_0000_0000_0001)
.x(2, 0x7fff_ffff_ffff_ffff)
.nzcv(nzcv),
);
}
}
let sbcs_pairs = [
("zero_zero", 0u64, 0u64),
("zero_one", 0, 1),
("w32_intmin_zero", 0xdead_beef_8000_0000, 0),
("w32_intmax_neg1", 0x0000_0001_7fff_ffff, 0xffff_ffff),
(
"w32_dirty_cancel",
0xdead_beef_0000_0005,
0xfeed_face_0000_0005,
),
("x64_intmin_zero", 0x8000_0000_0000_0000, 0),
("x64_zero_intmin", 0, 0x8000_0000_0000_0000),
("x64_intmax_neg1", 0x7fff_ffff_ffff_ffff, u64::MAX),
];
for (wlabel, word) in [("w", 0x7a02_0020u32), ("x", 0xfa02_0020)] {
for (plabel, a, b) in sbcs_pairs {
for (clabel, nzcv) in carry_states {
cases.push(
Case::new(format!("m4.sbcs.{wlabel}.{plabel}.{clabel}"), &[word])
.x(0, 0x5555_5555_5555_5555)
.x(1, a)
.x(2, b)
.nzcv(nzcv),
);
}
}
}
for (label, word) in [
("w.alias_all", 0x7a00_0000u32), // sbcs w0, w0, w0
("x.alias_all", 0xfa00_0000), // sbcs x0, x0, x0
("x.alias_rd_rm", 0xfa01_0041), // sbcs x1, x2, x1
("w.rd_zr", 0x7a02_003f), // sbcs wzr, w1, w2
("x.ngcs", 0xfa01_03e0), // ngcs x0, x1
] {
for (clabel, nzcv) in carry_states {
cases.push(
Case::new(format!("m4.sbcs.{label}.{clabel}"), &[word])
.x(0, 0xfeed_face_8000_0000)
.x(1, 0x8000_0000_0000_0001)
.x(2, 0x0000_0000_0000_0001)
.nzcv(nzcv),
);
}
}
}
fn m4_csel(cases: &mut Vec<Case>) {
// Full 16x16 matrix: every condition 0..16 x every NZCV nibble 0..16 for CSEL X0, X1, X2, cond
for condition in 0..16u32 {
let word = 0x9a82_0020 | (condition << 12);
for nibble in 0..16u64 {
cases.push(
Case::new(format!("m4.csel.x.c{condition}.{nibble:x}"), &[word])
.x(0, 0x0123_4567_89ab_cdef)
.x(1, 0x1111_2222_3333_4444)
.x(2, 0x8888_9999_aaaa_bbbb)
.nzcv(nibble << 28),
);
}
}
// W32 upper-bit truncation, aliasing (`keep_false`), unconditional AL/NV, and XZR/WZR.
let w_variants = [
("w.alias_rn", 0x1a81_0000u32), // csel w0, w0, w1, eq
("w.alias_rm", 0x1a80_0020), // csel w0, w1, w0, eq
("w.al", 0x1a81_e000), // csel w0, w0, w1, al
("w.nv", 0x1a81_f000), // csel w0, w0, w1, nv
("x.rn_zr", 0x9a81_23e0), // csel x0, xzr, x1, hs
("x.rm_zr", 0x9a9f_3020), // csel x0, x1, xzr, lo
("x.rd_zr", 0x9a82_003f), // csel xzr, x1, x2, eq
];
for (label, word) in w_variants {
for (nlabel, nzcv) in [
("zero", 0u64),
("z", 0x4000_0000),
("c", 0x2000_0000),
("all", 0xf000_0000),
] {
cases.push(
Case::new(format!("m4.csel.{label}.{nlabel}"), &[word])
.x(0, 0xdead_beef_1111_2222)
.x(1, 0xcafe_babe_3333_4444)
.x(2, 0xbaad_f00d_5555_6666)
.nzcv(nzcv),
);
}
}
}
fn m4_blocks(cases: &mut Vec<Case>) {
// 1. 128-bit ADDS + ADCS carry propagation into CSEL CS
let u128_add = [0xab02_0004u32, 0xba03_0025, 0x9a85_2086];
for (label, x0, x1, x2, x3, nzcv) in [
(
"c_low",
0xffff_ffff_ffff_ffff,
0x7fff_ffff_ffff_ffff,
1,
0,
0xf000_0000u64,
),
("no_carry", 10, 0xffff_ffff_ffff_ffff, 20, 0, 0x2000_0000),
("double_carry", u64::MAX, u64::MAX, 1, 0, 0),
] {
cases.push(
Case::new(format!("m4.block.u128_add_csel.{label}"), &u128_add)
.x(0, x0)
.x(1, x1)
.x(2, x2)
.x(3, x3)
.nzcv(nzcv),
);
}
// 2. 128-bit SUBS + SBCS borrow propagation into CSEL LT
let u128_sub = [0xeb02_0004u32, 0xfa03_0025, 0x9a85_b086];
for (label, x0, x1, x2, x3) in [
("borrow", 0u64, 0u64, 1u64, 0u64),
("no_borrow", 5, 0x8000_0000_0000_0000, 3, 1),
("signed_lt", 0, 0x8000_0000_0000_0000, 1, 0),
] {
cases.push(
Case::new(format!("m4.block.u128_sub_csel.{label}"), &u128_sub)
.x(0, x0)
.x(1, x1)
.x(2, x2)
.x(3, x3),
);
}
// 3. Mixed ADDS carry-out -> SBCS -> CSEL VS
let mixed_adds_sbcs = [0xab02_0004u32, 0xfa03_0025, 0x9a85_6086];
for (label, x0, x1, x2, x3) in [
(
"no_borrow_ovf",
1u64,
0x7fff_ffff_ffff_ffffu64,
0xffff_ffff_ffff_ffffu64,
u64::MAX,
),
("borrow_ovf", 1, 0x8000_0000_0000_0000, 2, 0),
] {
cases.push(
Case::new(
format!("m4.block.mixed_adds_sbcs.{label}"),
&mixed_adds_sbcs,
)
.x(0, x0)
.x(1, x1)
.x(2, x2)
.x(3, x3),
);
}
// 4. Consecutive AddSubCarry chain: ADCS -> SBCS -> ADCS -> CSEL HI
let carry_run = [0xba02_0004u32, 0xfa03_0025, 0xba05_0086, 0x9a86_80a7];
for (label, nzcv) in [("c0", 0xd000_0000u64), ("c1", 0x2000_0000)] {
cases.push(
Case::new(format!("m4.block.carry_run_mixed.{label}"), &carry_run)
.x(0, u64::MAX)
.x(1, 10)
.x(2, 0)
.x(3, 5)
.nzcv(nzcv),
);
}
// 5. Intra-block dead flag kill: ADDS -> ADDS -> CSEL EQ
let dead_kill = [0xab01_0004u32, 0xab03_0045, 0x9a85_0086];
for (label, x2, x3, nzcv) in [
("zero_final", 5u64, 0xffff_ffff_ffff_fffbu64, 0xf000_0000u64),
("nonzero_final", 5, 6, 0x4000_0000),
] {
cases.push(
Case::new(format!("m4.block.dead_flags_kill.{label}"), &dead_kill)
.x(0, 1)
.x(1, 2)
.x(2, x2)
.x(3, x3)
.nzcv(nzcv),
);
}
// 6. 32-bit dirty-upper-bits multi-step chain: ADDS W -> ADCS W -> SBCS W -> CSEL W GE
let w32_chain = [0x2b01_0004u32, 0x3a1f_0045, 0x7a04_00a6, 0x1a86_a087];
for (label, w0, w1, w2) in [
(
"carry_ge",
0xdead_beef_ffff_ffffu64,
0xfeed_face_0000_0001u64,
0xbaad_f00d_7fff_ffffu64,
),
(
"borrow_lt",
0x1234_5678_8000_0000,
0x9abc_def0_0000_0001,
0x0000_0001_0000_0000,
),
] {
cases.push(
Case::new(format!("m4.block.w32_chain.{label}"), &w32_chain)
.x(0, w0)
.x(1, w1)
.x(2, w2)
.nzcv(0xf000_0000),
);
}
}
/// Every case, in a fixed order.
pub fn all() -> Vec<Case> {
let mut cases = m1_baseline();
cases.extend(m4_flags_csel());
cases
}
#[cfg(test)]
mod tests {
use super::*;
+325
View File
@@ -0,0 +1,325 @@
//! Three-way verification of explicit instruction semantics, basic-block
//! side effects, Stela LEAF / BlockRuntime / SYSTEM_MODE compilation, and
//! native Apple M4 outcomes.
use super::corpus;
use super::record::{self, Ending, MEMORY};
use super::stela;
use anyhow::{Result, ensure};
use stela_compiler::{
GuestAddress, GuestState, Lifter, Options, TargetCpu,
aarch64::{
Decoder, Register, Width,
flags::{NZCV_C, NZCV_N, NZCV_V, NZCV_Z},
semantics::{FlagMask, RegisterSet, add_with_carry, semantics_of},
},
block::{
BlockProfile, Features, analyze_block_effects, eval_instructions, summarize_instructions,
},
compile,
};
const RET_ENCODING: u32 = 0xd65f_03c0;
/// Execute all explicit semantic checks, block side-effect invariants,
/// Stela LEAF vs BlockRuntime vs semantic-oracle equivalence checks across the
/// full `m4_flags_csel` suite.
pub fn verify_m4_semantics() -> Result<()> {
verify_instruction_contracts()?;
verify_block_contracts()?;
verify_corpus_three_way()?;
println!(
"semantics verification: 100% passed (instruction contracts, block effects, 480 m4 cases x semantic oracle x LEAF x BlockRuntime x SYSTEM_MODE compile)"
);
Ok(())
}
fn lift(words: &[u32]) -> Result<Vec<stela_compiler::aarch64::Instruction>> {
words
.iter()
.enumerate()
.map(|(i, &w)| {
Decoder
.lift(GuestAddress(0x10_0000 + i as u64 * 4), w)
.map_err(|e| anyhow::anyhow!("decode failed at #{i} ({w:#010x}): {e:?}"))
})
.collect()
}
fn verify_instruction_contracts() -> Result<()> {
// 1. ADDS imm & shifted reg: reads GPR(s), reads no flags, writes ALL flags.
let adds_imm = lift(&[0x3100_0420])?;
let s = semantics_of(&adds_imm[0].operation).expect("adds w0, w1, #1");
ensure!(s.width == Width::W32);
ensure!(s.gpr_reads == RegisterSet::of(Register::X(1)));
ensure!(s.gpr_writes == RegisterSet::of(Register::X(0)));
ensure!(s.flag_reads == FlagMask::NONE && s.flag_writes == FlagMask::ALL);
// CMN W1, #0xfff -> writes ZERO architectural GPR while writing all flags.
let cmn = lift(&[0x313f_fc3f])?;
let s = semantics_of(&cmn[0].operation).expect("cmn w1, #0xfff");
ensure!(s.gpr_reads == RegisterSet::of(Register::X(1)));
ensure!(s.gpr_writes == RegisterSet::NONE);
ensure!(s.flag_writes == FlagMask::ALL);
// 2. ADCS & SBCS: read C flag ONLY, write ALL flags.
let carry_ops = lift(&[0xba02_0020, 0xfa02_0020])?;
for insn in &carry_ops {
let s = semantics_of(&insn.operation).expect("adcs/sbcs");
ensure!(s.flag_reads == FlagMask::C);
ensure!(s.flag_writes == FlagMask::ALL);
}
// 3. CSEL: condition-specific flag reads, NO flag writes, AL/NV unconditional.
for cond in 0..16u32 {
let word = 0x9a82_0020 | (cond << 12);
let insn = lift(&[word])?;
let s = semantics_of(&insn[0].operation).expect("csel");
ensure!(s.flag_writes == FlagMask::NONE);
ensure!(s.flag_reads == FlagMask::condition_reads(cond as u8));
if cond >= 14 {
ensure!(s.flag_reads == FlagMask::NONE);
ensure!(s.gpr_reads == RegisterSet::of(Register::X(1)));
} else {
ensure!(s.gpr_reads == RegisterSet::from_registers([Register::X(1), Register::X(2)]));
}
}
// 4. Arm AddWithCarry edge values.
ensure!(add_with_carry(Width::W32, 0xffff_ffff, 0, true) == (0, NZCV_Z | NZCV_C));
ensure!(add_with_carry(Width::W32, 0x7fff_ffff, 0, true) == (0x8000_0000, NZCV_N | NZCV_V));
ensure!(
add_with_carry(Width::X64, 0x8000_0000_0000_0000, !0u64, false)
== (0x7fff_ffff_ffff_ffff, NZCV_C | NZCV_V)
);
Ok(())
}
fn verify_block_contracts() -> Result<()> {
// ADDS -> ADCS -> CSEL CS: live_in_flags == NONE, X0..X3 live-in, X4..X6 written.
// Neither flag write is dead because ADCS consumes C and block exit keeps NZCV live.
let u128_words = [0xab02_0004u32, 0xba03_0025, 0x9a85_2086];
let u128_bytes: Vec<u8> = u128_words.iter().flat_map(|w| w.to_le_bytes()).collect();
let e = analyze_block_effects(&u128_bytes, GuestAddress(0x10_0000))?;
ensure!(e.fully_modeled && e.live_in_flags == FlagMask::NONE);
ensure!(e.written_flags == FlagMask::ALL && e.killed_flags == FlagMask::ALL);
ensure!(e.live_in_gprs.contains(Register::X(0)) && e.live_in_gprs.contains(Register::X(3)));
ensure!(!e.live_in_gprs.contains(Register::X(4)));
ensure!(e.dead_flag_defs.is_empty());
// ADCS -> SBCS -> ADCS -> CSEL HI: live_in_flags == C (N,Z,V entry bits ignored).
let run_words = [0xba02_0004u32, 0xfa03_0025, 0xba05_0086, 0x9a86_80a7];
let run_insns = lift(&run_words)?;
let e_run = summarize_instructions(&run_insns);
ensure!(e_run.live_in_flags == FlagMask::C);
ensure!(e_run.dead_flag_defs.is_empty());
// Dead-flag kill: ADDS -> ADDS -> CSEL EQ (first ADDS flags dead).
let kill_words = [0xab01_0004u32, 0xab03_0045, 0x9a85_0086];
let kill_bytes: Vec<u8> = kill_words.iter().flat_map(|w| w.to_le_bytes()).collect();
let e_kill = analyze_block_effects(&kill_bytes, GuestAddress(0x10_0000))?;
ensure!(e_kill.live_in_flags == FlagMask::NONE);
ensure!(e_kill.dead_flag_defs == vec![0]);
// ADDS -> CSEL AL -> ADDS: unconditional CSEL AL reads no flags, so first ADDS is dead.
let al_words = [0xab01_0004u32, 0x9a85_e086, 0xab03_0045];
let al_bytes: Vec<u8> = al_words.iter().flat_map(|w| w.to_le_bytes()).collect();
let e_al = analyze_block_effects(&al_bytes, GuestAddress(0x10_0000))?;
ensure!(e_al.live_in_flags == FlagMask::NONE);
ensure!(e_al.dead_flag_defs == vec![0]);
Ok(())
}
fn verify_corpus_three_way() -> Result<()> {
let cases = corpus::m4_flags_csel();
ensure!(!cases.is_empty(), "m4_flags_csel must be non-empty");
let block_runtime_endings = stela::run(&cases)?;
let leaf_options = Options::new(BlockProfile::new(Features::LEAF), TargetCpu::detect());
let system_options = Options::new(
BlockProfile::new(Features::SYSTEM_MODE),
TargetCpu::detect(),
);
for (case, br_ending) in cases.iter().zip(&block_runtime_endings) {
// 1. Lift and verify semantic model + side effects.
let insns = lift(&case.words)?;
let effects = summarize_instructions(&insns);
ensure!(effects.fully_modeled, "{} was not modeled", case.name);
let mut oracle_state = GuestState {
x: case.state.x,
nzcv: case.state.nzcv as u32,
..Default::default()
};
eval_instructions(&insns, &mut oracle_state)
.ok_or_else(|| anyhow::anyhow!("oracle failed on {}", case.name))?;
// 2. Non-interference: architectural registers outside `written_gprs` stay identical,
// and unread entry flag bits do not affect register outputs (or flags if overwritten).
for idx in 0..31u8 {
if !effects.written_gprs.contains(Register::X(idx)) {
ensure!(
oracle_state.x[usize::from(idx)] == case.state.x[usize::from(idx)],
"{}: unmodeled write to X{idx}",
case.name
);
}
}
let unread_flags = FlagMask::ALL
.difference(effects.live_in_flags)
.to_nzcv_mask();
if unread_flags != 0 {
let mut perturbed = GuestState {
x: case.state.x,
nzcv: (case.state.nzcv as u32) ^ unread_flags,
..Default::default()
};
eval_instructions(&insns, &mut perturbed).unwrap();
ensure!(
perturbed.x == oracle_state.x,
"{}: unread NZCV bits altered GPRs",
case.name
);
if effects.written_flags == FlagMask::ALL {
ensure!(
perturbed.nzcv == oracle_state.nzcv,
"{}: unread NZCV bits altered final NZCV",
case.name
);
}
}
// 3. Compare semantic oracle against BlockRuntime (`optimize: true`).
let oracle_ending = Ending::Completed {
state: Box::new(super::record::State {
x: oracle_state.x,
nzcv: u64::from(oracle_state.nzcv),
fpcr: case.state.fpcr,
fpsr: case.state.fpsr,
v: case.state.v,
}),
memory: Box::new([0u8; MEMORY]),
};
let oracle_out = record::outcome(case, &oracle_ending);
let br_out = record::outcome(case, br_ending);
ensure!(
oracle_out == br_out,
"{}: semantic oracle ({oracle_out}) != BlockRuntime ({br_out})",
case.name
);
// 4. Compile & execute through Stela `Features::LEAF` (frame emitter).
let mut leaf_words = case.words.clone();
leaf_words.push(RET_ENCODING);
let leaf_bytes: Vec<u8> = leaf_words.iter().flat_map(|w| w.to_le_bytes()).collect();
let compiled_leaf = compile(&leaf_bytes, GuestAddress(0x10_0000), &leaf_options)?;
ensure!(
compiled_leaf.source_bytes == leaf_bytes.len(),
"{}: LEAF truncated block",
case.name
);
let mut leaf_state = GuestState {
x: case.state.x,
nzcv: case.state.nzcv as u32,
..Default::default()
};
run_native_leaf(&compiled_leaf.native.x86_64_code, &mut leaf_state)?;
ensure!(
leaf_state.x == oracle_state.x && leaf_state.nzcv == oracle_state.nzcv,
"{}: LEAF mismatch: leaf(nzcv={:#x}) vs oracle(nzcv={:#x})",
case.name,
leaf_state.nzcv,
oracle_state.nzcv
);
// 5. Compile through Stela `Features::SYSTEM_MODE` (pinned + carry runs + dead-flag elimination).
let block_bytes: Vec<u8> = case.words.iter().flat_map(|w| w.to_le_bytes()).collect();
let compiled_sys = compile(&block_bytes, GuestAddress(0x10_0000), &system_options)?;
ensure!(
compiled_sys.source_bytes == block_bytes.len(),
"{}: SYSTEM_MODE did not cover full block",
case.name
);
}
Ok(())
}
#[cfg(windows)]
fn run_native_leaf(code: &[u8], state: &mut GuestState) -> Result<()> {
use core::ffi::c_void;
unsafe extern "system" {
fn GetCurrentProcess() -> *mut c_void;
fn VirtualAlloc(
lp_address: *mut c_void,
dw_size: usize,
fl_allocation_type: u32,
fl_protect: u32,
) -> *mut c_void;
fn VirtualProtect(
lp_address: *mut c_void,
dw_size: usize,
fl_new_protect: u32,
lpfl_old_protect: *mut u32,
) -> i32;
fn VirtualFree(lp_address: *mut c_void, dw_size: usize, dw_free_type: u32) -> i32;
fn FlushInstructionCache(
h_process: *mut c_void,
lp_base_address: *const c_void,
dw_size: usize,
) -> i32;
}
let bytes = code.len().max(1).next_multiple_of(4096);
// SAFETY: allocates a private RW buffer, copies Stela's generated leaf
// x86-64 code (ending in RET), transitions it to RX, flushes I-cache,
// executes with SysV64 ABI (`RDI = state`), and frees it.
unsafe {
let page = VirtualAlloc(core::ptr::null_mut(), bytes, 0x3000, 0x04);
ensure!(!page.is_null(), "VirtualAlloc failed for leaf");
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
let mut old = 0u32;
ensure!(
VirtualProtect(page, bytes, 0x20, &mut old) != 0,
"VirtualProtect failed"
);
ensure!(
FlushInstructionCache(GetCurrentProcess(), page, bytes) != 0,
"FlushInstructionCache failed"
);
let func: unsafe extern "sysv64" fn(*mut GuestState) = core::mem::transmute(page);
func(state as *mut GuestState);
ensure!(VirtualFree(page, 0, 0x8000) != 0, "VirtualFree failed");
}
Ok(())
}
#[cfg(unix)]
fn run_native_leaf(code: &[u8], state: &mut GuestState) -> Result<()> {
use core::ffi::c_void;
unsafe extern "C" {
fn mmap(
addr: *mut c_void,
len: usize,
prot: i32,
flags: i32,
fd: i32,
off: i64,
) -> *mut c_void;
fn mprotect(addr: *mut c_void, len: usize, prot: i32) -> i32;
fn munmap(addr: *mut c_void, len: usize) -> i32;
}
#[cfg(target_os = "macos")]
const MAP_ANON: i32 = 0x1000;
#[cfg(target_os = "linux")]
const MAP_ANON: i32 = 0x20;
let bytes = code.len().max(1).next_multiple_of(4096);
// SAFETY: private RX mapping containing valid compiled leaf code.
unsafe {
let page = mmap(core::ptr::null_mut(), bytes, 3, 2 | MAP_ANON, -1, 0);
ensure!(page as usize != usize::MAX, "mmap failed");
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
ensure!(mprotect(page, bytes, 5) == 0, "mprotect failed");
let func: unsafe extern "sysv64" fn(*mut GuestState) = core::mem::transmute(page);
func(state as *mut GuestState);
ensure!(munmap(page, bytes) == 0, "munmap failed");
}
Ok(())
}
+113 -11
View File
@@ -5,9 +5,119 @@ use super::record::{Case, Ending, MEMORY, State};
use anyhow::{Context, Result};
use stela_compiler::{GuestAddress, GuestState};
use stela_engine::blocks::{BlockRuntime, StopReason, ThreadState};
#[cfg(unix)]
use stela_engine::memory::{MemoryRegionSpec, OwnedMemory};
use stela_engine::pauth::{self, Keys};
#[cfg(unix)]
struct CaseBuffer(OwnedMemory);
#[cfg(unix)]
impl CaseBuffer {
fn allocate() -> Result<Self> {
let memory = OwnedMemory::map(vec![MemoryRegionSpec {
guest_address: MEMORY_BASE,
virtual_bytes: 4096,
initial_bytes: vec![0; 4096],
readable: true,
writable: true,
executable: false,
}])
.context("cannot map the case buffer")?;
Ok(Self(memory))
}
fn write(&mut self, bytes: &[u8]) -> Result<()> {
// Re-zero first so shrinking or untouched regions never leak prior case bytes.
self.0.write(MEMORY_BASE, &[0u8; 4096])?;
self.0.write(MEMORY_BASE, bytes)?;
Ok(())
}
fn read_snapshot(&self, len: usize) -> Result<Vec<u8>> {
self.0.read_snapshot(MEMORY_BASE, len)
}
}
#[cfg(windows)]
struct CaseBuffer {
ptr: *mut core::ffi::c_void,
}
#[cfg(windows)]
impl CaseBuffer {
const ALLOCATION_BYTES: usize = 0x1_0000;
const MEM_COMMIT: u32 = 0x1000;
const MEM_RESERVE: u32 = 0x2000;
const MEM_RELEASE: u32 = 0x8000;
const PAGE_READWRITE: u32 = 0x04;
fn allocate() -> Result<Self> {
unsafe extern "system" {
fn VirtualAlloc(
lp_address: *mut core::ffi::c_void,
dw_size: usize,
fl_allocation_type: u32,
fl_protect: u32,
) -> *mut core::ffi::c_void;
}
// SAFETY: reserves and commits a fresh 64 KiB read-write buffer at the
// fixed 64 KiB-aligned guest address used by the differential harness.
let ptr = unsafe {
VirtualAlloc(
MEMORY_BASE as *mut core::ffi::c_void,
Self::ALLOCATION_BYTES,
Self::MEM_COMMIT | Self::MEM_RESERVE,
Self::PAGE_READWRITE,
)
};
anyhow::ensure!(!ptr.is_null(), "VirtualAlloc failed for case buffer");
anyhow::ensure!(
ptr as u64 == MEMORY_BASE,
"VirtualAlloc returned {:#x}, expected {MEMORY_BASE:#x}",
ptr as u64
);
Ok(Self { ptr })
}
fn write(&mut self, bytes: &[u8]) -> Result<()> {
anyhow::ensure!(bytes.len() <= 4096, "case memory exceeds 4096 bytes");
// SAFETY: `ptr` points to `ALLOCATION_BYTES` uniquely owned writable bytes.
unsafe {
core::ptr::write_bytes(self.ptr.cast::<u8>(), 0, 4096);
core::ptr::copy_nonoverlapping(bytes.as_ptr(), self.ptr.cast::<u8>(), bytes.len());
}
Ok(())
}
fn read_snapshot(&self, len: usize) -> Result<Vec<u8>> {
anyhow::ensure!(len <= 4096, "snapshot exceeds 4096 bytes");
let mut out = vec![0u8; len];
// SAFETY: `ptr` points to at least 4096 initialized readable bytes.
unsafe {
core::ptr::copy_nonoverlapping(self.ptr.cast::<u8>(), out.as_mut_ptr(), len);
}
Ok(out)
}
}
#[cfg(windows)]
impl Drop for CaseBuffer {
fn drop(&mut self) {
unsafe extern "system" {
fn VirtualFree(
lp_address: *mut core::ffi::c_void,
dw_size: usize,
dw_free_type: u32,
) -> i32;
}
// SAFETY: `self.ptr` was allocated with `VirtualAlloc(MEM_RESERVE | MEM_COMMIT)`.
unsafe {
let _ = VirtualFree(self.ptr, 0, Self::MEM_RELEASE);
}
}
}
const ADDRESS_SPACE: u64 = 0x5ce1;
/// Guest addresses equal host addresses in the direct profile: the buffer
/// is mapped here, at a 64-byte-aligned address as the runner's.
@@ -32,15 +142,7 @@ pub fn run(cases: &[Case]) -> Result<Vec<Ending>> {
),
stela_compiler::TargetCpu::detect(),
);
let mut memory = OwnedMemory::map(vec![MemoryRegionSpec {
guest_address: MEMORY_BASE,
virtual_bytes: 4096,
initial_bytes: vec![0; 4096],
readable: true,
writable: true,
executable: false,
}])
.context("cannot map the case buffer")?;
let mut memory = CaseBuffer::allocate().context("cannot map the case buffer")?;
let pauth = pauth::Context::new(
ADDRESS_SPACE,
Keys::from_words(KEY, KEY, KEY, KEY).with_generic_words(KEY),
@@ -52,7 +154,7 @@ pub fn run(cases: &[Case]) -> Result<Vec<Ending>> {
words.push(BRANCH_NEXT);
let source = words.iter().flat_map(|word| word.to_le_bytes()).collect();
runtime.register_code(GuestAddress(base), source)?;
memory.write(MEMORY_BASE, &case.memory)?;
memory.write(&case.memory)?;
let mut thread = ThreadState {
registers: guest_state(case),
pc: GuestAddress(base),
@@ -71,7 +173,7 @@ pub fn run(cases: &[Case]) -> Result<Vec<Ending>> {
state.x[register] = state.x[register].wrapping_sub(MEMORY_BASE);
}
}
let bytes = memory.read_snapshot(MEMORY_BASE, MEMORY)?;
let bytes = memory.read_snapshot(MEMORY)?;
Ending::Completed {
state: Box::new(state),
memory: Box::new(bytes.try_into().unwrap()),
+46 -10
View File
@@ -3,32 +3,68 @@ use super::*;
#[test]
fn every_case_is_recorded() {
let table = recorded().unwrap();
let cases = corpus::all();
let cases = corpus::m1_baseline();
assert_eq!(table.len(), cases.len());
for case in &cases {
assert!(table.contains_key(case.name.as_str()), "{}", case.name);
}
}
/// The regression check: every case through Stela gives the outcome
/// recorded on the Mac, except the known differences, which still differ.
/// Stela runs the cases in exact guest mappings, which only an x86-64 Linux
/// or macOS host has.
#[test]
#[cfg(all(target_arch = "x86_64", any(target_os = "linux", target_os = "macos")))]
fn m4_semantics_and_tiers_match() {
semantics_verify::verify_m4_semantics().unwrap();
}
/// The regression check: every case through Stela gives the outcome
/// recorded on the M1 Pro, except the known differences, which still differ.
#[test]
#[cfg(all(
target_arch = "x86_64",
any(target_os = "linux", target_os = "macos", target_os = "windows")
))]
fn stela_matches_the_recorded_mac() {
let table = recorded().unwrap();
let cases = corpus::all();
let cases = corpus::m1_baseline();
let endings = stela::run(&cases).unwrap();
let mut unexpected = Vec::new();
for (case, ending) in cases.iter().zip(&endings) {
let stela = record::outcome(case, ending);
let mac = table[case.name.as_str()];
let mac = &table[case.name.as_str()];
match known_difference(&case.name) {
None if stela != mac => {
None if &stela != mac => {
unexpected.push(format!("{}: mac {mac}, stela {stela}", case.name))
}
Some(_) if stela == mac => unexpected.push(format!("{}: no longer differs", case.name)),
Some(_) if &stela == mac => {
unexpected.push(format!("{}: no longer differs", case.name))
}
_ => {}
}
}
assert!(unexpected.is_empty(), "{}", unexpected.join("\n"));
}
#[test]
#[cfg(all(
target_arch = "x86_64",
any(target_os = "linux", target_os = "macos", target_os = "windows")
))]
fn stela_matches_recorded_apple_m4() {
let table =
recorded_from_path(std::path::Path::new("xtask/src/cpu_reference/apple-m4.tsv")).unwrap();
let cases = corpus::all();
assert_eq!(table.len(), cases.len());
let endings = stela::run(&cases).unwrap();
let mut unexpected = Vec::new();
for (case, ending) in cases.iter().zip(&endings) {
let stela = record::outcome(case, ending);
let mac = &table[case.name.as_str()];
match known_difference(&case.name) {
None if &stela != mac => {
unexpected.push(format!("{}: m4 {mac}, stela {stela}", case.name))
}
Some(_) if &stela == mac => {
unexpected.push(format!("{}: no longer differs", case.name))
}
_ => {}
}
}