use vlk_ir::ir::semantics::mask;
use vlk_ir::ir::{BinOp, Block, Expr, Stmt};
use vlk_loader::loader::Image;
use vlk_program::program::Program;
#[derive(Debug, Clone)]
pub struct Recovered {
pub block_start: u64,
pub index: Expr,
pub cases: Vec<(i64, u64)>,
pub default: Option<u64>,
pub table: (u64, u64),
}
impl Recovered {
pub fn targets(&self) -> Vec<u64> {
let mut targets: Vec<u64> = self.cases.iter().map(|(_, target)| *target).collect();
targets.extend(self.default);
targets
}
}
pub fn recover(
blocks: &[Block],
program: &Program,
extent: std::ops::Range<u64>,
) -> Vec<Recovered> {
if !blocks
.iter()
.any(|block| matches!(block.stmts.last(), Some(Stmt::BrIndirect { .. })))
{
return Vec::new();
}
let mut recovered = recover_once(blocks, program, &extent, &[]);
for _ in 0..4 {
let again = recover_once(blocks, program, &extent, &recovered);
if again.len() <= recovered.len() {
break;
}
recovered = again;
}
recovered
}
fn recover_once(
blocks: &[Block],
program: &Program,
extent: &std::ops::Range<u64>,
known: &[Recovered],
) -> Vec<Recovered> {
let image = &program.image;
let starts = program
.addressed
.get_or_init(|| referenced_addresses(image));
let read_only = |address: u64| {
image
.section_at(address)
.is_some_and(|section| section.read_only && !section.executable)
};
let held = held_constants(
blocks,
known,
(image.isa == vlk_base::target::Isa::Mips32).then_some(&read_only),
);
let mut recovered = Vec::new();
for (index, block) in blocks.iter().enumerate() {
let Some(Stmt::BrIndirect { target, .. }) = block.stmts.last() else {
continue;
};
let checked = index
.checked_sub(1)
.and_then(|previous| blocks.get(previous));
let bound = checked.and_then(bound);
let limits = Limits {
extent: extent.clone(),
tables: starts,
held: &held[index],
};
if let Some(mut entry) = recognize(block, target, image, bound, checked, &limits) {
entry.block_start = block.start;
recovered.push(entry);
}
}
recovered
}
pub(crate) fn bound(block: &Block) -> Option<Bound> {
let Some(last) = block.stmts.last() else {
return None;
};
let Stmt::Brif {
cond,
lhs,
rhs,
target,
..
} = last
else {
return Option::None;
};
let environment = environment_from(block, std::collections::HashMap::new());
let limit_of = |expr: &Expr| match expr {
Expr::Const(limit) => Some(*limit),
Expr::Reg { .. } => match resolve(expr, &environment) {
Expr::Const(limit) => Some(limit),
_ => None,
},
_ => None,
};
let flagless = match (cond, limit_of(rhs)) {
(vlk_ir::ir::Cond::Eq, Some(0)) => {
match strip_constant_masks(&resolve(lhs, &environment)) {
Expr::Select {
cond: vlk_ir::ir::Cond::Cc,
lhs: value,
rhs: limit,
then,
els,
} if constant(then) == Some(1) && constant(els) == Some(0) => {
constant(limit).map(|limit| ((**value).clone(), limit))
}
_ => None,
}
}
_ => None,
};
let (cond, resolved, limit) = match flagless {
Some((value, limit)) => (vlk_ir::ir::Cond::Cs, value, limit),
None => {
let (cond, lhs, limit) = match (cond, limit_of(rhs), limit_of(lhs)) {
(vlk_ir::ir::Cond::Hi | vlk_ir::ir::Cond::Cs, Some(limit), _) => {
(*cond, lhs, limit)
}
(vlk_ir::ir::Cond::Cc, None, Some(limit)) => (vlk_ir::ir::Cond::Hi, rhs, limit),
(vlk_ir::ir::Cond::Ls, None, Some(limit)) => (vlk_ir::ir::Cond::Cs, rhs, limit),
_ => return Option::None,
};
(cond, resolve(lhs, &environment), limit)
}
};
let limit = &limit;
let cond = &cond;
let resolved = cancel(resolved);
let checked = unwrap_mask(&resolved);
let bits = match vlk_ir::ir::semantics::width(&resolved) {
0 => 64,
bits => bits.min(64),
};
let (minimum, switch_base) = match checked {
Expr::Bin {
op: BinOp::Sub,
lhs: value,
rhs: offset,
} => match constant(offset) {
Some(offset) => (lowest_case(Adjustment::Sub(offset)), (**value).clone()),
None => (0, checked.clone()),
},
Expr::Bin {
op: BinOp::Add,
lhs: value,
rhs: offset,
} => match constant(offset) {
Some(offset) => (lowest_case(Adjustment::Add(offset)), (**value).clone()),
None => (0, checked.clone()),
},
_ => (0, checked.clone()),
};
let inclusive = *cond == vlk_ir::ir::Cond::Hi;
let count = case_count(inclusive, *limit & mask(bits)).unwrap_or(0);
Option::Some(Bound {
count,
default: Option::Some(*target),
minimum,
switch_base,
})
}
pub(crate) struct Bound {
count: i64,
default: Option<u64>,
minimum: i64,
switch_base: Expr,
}
#[derive(Clone, Copy)]
enum Adjustment {
Sub(u64),
Add(u64),
}
fn lowest_case(adjustment: Adjustment) -> i64 {
match adjustment {
Adjustment::Sub(offset) => offset as i64,
Adjustment::Add(offset) => (offset as i64).wrapping_neg(),
}
}
fn case_count(inclusive: bool, limit: u64) -> Option<i64> {
let Ok(limit) = i64::try_from(limit) else {
return None;
};
if inclusive {
limit.checked_add(1)
} else {
Some(limit)
}
}
fn case_value(minimum: i64, position: i64) -> i64 {
minimum.wrapping_add(position)
}
fn entry_address(table: u64, position: u64, entry_bytes: u64) -> Option<u64> {
let Some(distance) = position.checked_mul(entry_bytes) else {
return None;
};
table.checked_add(distance)
}
fn entry_address32(table: u64, position: u64) -> Option<u64> {
let Some(at) = entry_address(table, position, 4) else {
return None;
};
(at <= u64::from(u32::MAX) - 3).then_some(at)
}
fn byte_offset(byte: u8, scale: i64) -> Option<i64> {
let Ok(scale) = u32::try_from(scale) else {
return None;
};
i64::from(byte).checked_shl(scale)
}
pub fn apply(blocks: &mut [Block], recovered: &[Recovered]) {
for entry in recovered {
let Some(block) = blocks
.iter_mut()
.find(|block| block.start == entry.block_start)
else {
continue;
};
if !matches!(block.stmts.last(), Some(Stmt::BrIndirect { .. })) {
continue;
}
let at = block.stmts.pop().and_then(|stmt| stmt.origin());
if let Some(register) = register_holding_index(block, &entry.index) {
block.stmts.push(Stmt::Switch {
index: Expr::reg(register, 64),
cases: entry.cases.clone(),
default: entry.default,
at,
});
continue;
}
let mut read = std::collections::HashSet::new();
vlk_ir::ir::visit::collect_reads(&entry.index, &mut read);
let overwritten = block.stmts.iter().any(|stmt| {
vlk_ir::ir::visit::statement_registers(stmt)
.0
.iter()
.any(|written| read.contains(written))
});
let index = if overwritten {
block.stmts.insert(
0,
Stmt::Assign {
dest: vlk_ir::ir::RegRef {
index: vlk_ir::ir::SWITCH_INDEX,
width: 64,
},
value: entry.index.clone(),
at: None,
},
);
Expr::reg(vlk_ir::ir::SWITCH_INDEX, 64)
} else {
entry.index.clone()
};
block.stmts.push(Stmt::Switch {
index,
cases: entry.cases.clone(),
default: entry.default,
at,
});
}
}
pub(super) fn drop_data(
blocks: &mut Vec<Block>,
recovered: &[Recovered],
landing_pads: &[(u64, Vec<(u64, u64)>)],
) {
if recovered.is_empty() {
return;
}
let mut seen = vec![false; blocks.len()];
let mut pending = vec![0];
while let Some(index) = pending.pop() {
if index >= blocks.len() || std::mem::replace(&mut seen[index], true) {
continue;
}
let edges = vlk_ir::ir::cfg::block_successors_with_exceptions(blocks, index, landing_pads);
if edges.unknown_normal || edges.unknown_exceptional {
return;
}
pending.extend(edges.normal);
pending.extend(edges.exceptional);
}
let mut index = 0;
blocks.retain(|block| {
let reached = seen[index];
index += 1;
reached
|| !recovered.iter().any(|entry| {
let (start, size) = entry.table;
block.start >= start && block.start - start < size
})
});
}
fn register_holding_index(block: &Block, index: &Expr) -> Option<u16> {
let mut environment = std::collections::HashMap::new();
let mut found = None;
for stmt in &block.stmts {
let Stmt::Assign { dest, value, .. } = stmt else {
if !vlk_ir::ir::visit::statement_registers(stmt).0.is_empty() {
found = None;
}
continue;
};
let resolved = resolve(value, &environment);
if found == Some(dest.index) {
found = None;
}
if dest.width == 64 && resolved == *index && found.is_none() {
found = Some(dest.index);
}
environment.insert(dest.index, resolved);
}
found
}
fn largest(index: &Expr) -> u64 {
crate::ssa::ranges::expression(index, &|_, _| Some(crate::ssa::ranges::Fact::TOP))
.map_or(u64::MAX, |fact| fact.hi)
}
struct Limits<'a> {
extent: std::ops::Range<u64>,
tables: &'a std::collections::HashSet<u64>,
held: &'a std::collections::HashMap<u16, Expr>,
}
type Held = std::collections::HashMap<u16, Expr>;
fn reads(expr: &Expr, register: u16) -> bool {
let mut read = std::collections::HashSet::new();
vlk_ir::ir::visit::collect_reads(expr, &mut read);
read.contains(®ister)
}
fn computed(expr: &Expr, table: &dyn Fn(u64) -> bool, budget: &mut u32, named: &mut bool) -> bool {
if *budget == 0 {
return false;
}
*budget -= 1;
match expr {
Expr::Load { .. } => false,
Expr::Const(value) => {
*named |= table(*value);
true
}
other => vlk_ir::ir::visit::children(other)
.into_iter()
.all(|child| computed(child, table, budget, named)),
}
}
fn forget(held: &mut Held, register: u16) {
held.remove(®ister);
held.retain(|_, value| !reads(value, register));
}
fn write_out(held: &mut Held, local: &Held, register: u16) {
let Some(was) = local.get(®ister) else {
return;
};
let one = Held::from([(register, was.clone())]);
for (other, value) in held.iter_mut() {
if *other != register && reads(value, register) {
*value = resolve(value, &one);
}
}
}
fn held_after(block: &Block, mut held: Held, table: Option<&dyn Fn(u64) -> bool>) -> Held {
let mut local = Held::new();
for stmt in &block.stmts {
match stmt {
Stmt::Assign { dest, value, .. } => {
let resolved = resolve(value, &held);
if table.is_some() {
write_out(&mut held, &local, dest.index);
let kept = dest.width == 64
&& !reads(value, dest.index)
&& computed(value, &|_| false, &mut 16, &mut false);
forget(&mut local, dest.index);
if kept {
local.insert(dest.index, value.clone());
}
}
match constant(&resolved) {
Some(value) if dest.width == 64 => {
forget(&mut held, dest.index);
held.insert(dest.index, Expr::Const(value));
}
None if dest.width == 64
&& !reads(&resolved, dest.index)
&& table.is_some_and(|table| {
let mut named = false;
computed(&resolved, table, &mut 16, &mut named) && named
}) =>
{
forget(&mut held, dest.index);
held.insert(dest.index, resolved);
}
_ => forget(&mut held, dest.index),
}
}
other => {
for register in vlk_ir::ir::visit::statement_registers(other).0 {
if table.is_some() {
write_out(&mut held, &local, register);
}
forget(&mut held, register);
forget(&mut local, register);
}
}
}
}
held
}
fn direct_successors(
blocks: &[Block],
index: &std::collections::HashMap<u64, usize>,
at: usize,
) -> Vec<usize> {
let falls = at + 1 < blocks.len();
match blocks[at].stmts.last() {
Some(Stmt::Br { target, .. }) => target
.and_then(|target| index.get(&target).copied())
.into_iter()
.collect(),
Some(Stmt::Brif { target, .. } | Stmt::BrifFlags { target, .. }) => index
.get(target)
.copied()
.into_iter()
.chain(falls.then_some(at + 1))
.collect(),
Some(Stmt::Ret { .. } | Stmt::Trap { .. } | Stmt::BrIndirect { .. }) => Vec::new(),
_ => falls.then_some(at + 1).into_iter().collect(),
}
}
fn held_constants(
blocks: &[Block],
known: &[Recovered],
table: Option<&dyn Fn(u64) -> bool>,
) -> Vec<Held> {
if blocks.is_empty() {
return Vec::new();
}
let index: std::collections::HashMap<u64, usize> = blocks
.iter()
.enumerate()
.map(|(position, block)| (block.start, position))
.collect();
let tables: std::collections::HashMap<u64, Vec<usize>> = known
.iter()
.map(|table| {
let targets = table
.targets()
.iter()
.filter_map(|target| index.get(target).copied())
.collect();
(table.block_start, targets)
})
.collect();
let mut entry: Vec<Option<Held>> = vec![None; blocks.len()];
entry[0] = Some(Held::new());
let mut pending = vec![0];
while let Some(at) = pending.pop() {
let Some(before) = entry[at].clone() else {
continue;
};
let held = held_after(&blocks[at], before, table);
let next = match blocks[at].stmts.last() {
Some(Stmt::BrIndirect { .. }) => {
tables.get(&blocks[at].start).cloned().unwrap_or_default()
}
_ => direct_successors(blocks, &index, at),
};
for successor in next {
let merged = match &entry[successor] {
None => held.clone(),
Some(existing) => existing
.iter()
.filter(|(register, value)| held.get(register) == Some(value))
.map(|(register, value)| (*register, value.clone()))
.collect(),
};
if entry[successor].as_ref() != Some(&merged) {
entry[successor] = Some(merged);
pending.push(successor);
}
}
}
entry.into_iter().map(Option::unwrap_or_default).collect()
}
pub(crate) fn referenced_addresses(image: &Image) -> std::collections::HashSet<u64> {
let mut out = std::collections::HashSet::new();
for section in image.sections.iter().filter(|section| section.executable) {
let Some(bytes) = image.read_vaddr(section.vaddr, section.size) else {
continue;
};
match image.isa {
vlk_base::target::Isa::X86_64 => {
for (at, window) in bytes.windows(7).enumerate() {
if let Some(address) =
rip_relative_lea(window, section.vaddr.wrapping_add(at as u64))
{
out.insert(address);
}
}
}
vlk_base::target::Isa::AArch64 => {
let words = bytes.as_chunks::<4>().0;
for (index, pair) in words.windows(2).enumerate() {
let (adrp, add) = (u32::from_le_bytes(pair[0]), u32::from_le_bytes(pair[1]));
let site = section.vaddr.wrapping_add(index as u64 * 4);
if let Some(address) = adrp_add(adrp, add, site) {
out.insert(address);
}
}
}
vlk_base::target::Isa::Arm32
| vlk_base::target::Isa::I386
| vlk_base::target::Isa::RiscV64
| vlk_base::target::Isa::Mips32
| vlk_base::target::Isa::Unsupported => {}
}
}
out
}
fn rip_relative_lea(bytes: &[u8], site: u64) -> Option<u64> {
if bytes[0] & 0xf8 != 0x48 || bytes[1] != 0x8d || bytes[2] & 0xc7 != 0x05 {
return None;
}
let displacement = i32::from_le_bytes([bytes[3], bytes[4], bytes[5], bytes[6]]);
Some(
site.wrapping_add(7)
.wrapping_add(displacement as i64 as u64),
)
}
fn adrp_add(adrp: u32, add: u32, site: u64) -> Option<u64> {
if adrp & 0x9f00_0000 != 0x9000_0000
|| adrp & 0x1f == 31
|| add & 0xffc0_0000 != 0x9100_0000
|| (add >> 5) & 0x1f != adrp & 0x1f
{
return None;
}
let page = (((adrp >> 29) & 3) | (((adrp >> 5) & 0x7ffff) << 2)) as u64;
let page = ((page << 43) as i64 >> 31) as u64;
Some(
(site & !0xfff)
.wrapping_add(page)
.wrapping_add(u64::from((add >> 10) & 0xfff)),
)
}
fn environment_from(
block: &Block,
mut environment: std::collections::HashMap<u16, Expr>,
) -> std::collections::HashMap<u16, Expr> {
for stmt in &block.stmts {
if let Stmt::Assign { dest, value, .. } = stmt {
let resolved = resolve(value, &environment);
environment.insert(dest.index, resolved);
}
}
environment
}
struct Table {
base: u64,
start: u64,
scale: i64,
entry: Entry,
}
impl Table {
fn entry_bytes(&self) -> u64 {
match self.entry {
Entry::Absolute => 8,
Entry::Absolute32 => 4,
Entry::Offset32 | Entry::Wrapped32 => 4,
Entry::Byte => 1,
}
}
fn read_case(&self, image: &Image, position: u64) -> Option<u64> {
let offset = match self.entry {
Entry::Absolute => {
let Some(at) = entry_address(self.start, position, 8) else {
return None;
};
let Some(vaddr) = image.read_vaddr(at, 8) else {
return None;
};
image.value(vaddr) as i64
}
Entry::Absolute32 => {
let Some(at) = entry_address32(self.start, position) else {
return None;
};
let Some(bytes) = image.read_vaddr(at, 4) else {
return None;
};
image.value(bytes) as i64
}
Entry::Offset32 | Entry::Wrapped32 => {
let Some(at) = entry_address(self.start, position, 4) else {
return None;
};
let Some(bytes) = image.read_vaddr(at, 4) else {
return None;
};
i64::from(image.value(bytes) as u32 as i32)
}
Entry::Byte => {
let Some(at) = entry_address(self.start, position, 1) else {
return None;
};
let Some(entry_bytes) = image.read_vaddr(at, 1) else {
return None;
};
let Some(offset) = byte_offset(entry_bytes[0], self.scale) else {
return None;
};
offset
}
};
let case = self.base.wrapping_add(offset as u64);
let case = if matches!(self.entry, Entry::Wrapped32) {
case & 0xffff_ffff
} else {
case
};
image
.section_at(case)
.is_some_and(|section| section.executable)
.then_some(case)
}
fn unchecked_count(&self, image: &Image, limits: &Limits) -> usize {
let entry_bytes = self.entry_bytes();
let mut first_case = u64::MAX;
(0..4096u64)
.take_while(|position| {
let Some(at) = entry_address(self.start, *position, entry_bytes) else {
return false;
};
if at >= first_case || (*position != 0 && limits.tables.contains(&at)) {
return false;
}
let Some(case) = self.read_case(image, *position) else {
return false;
};
if !limits.extent.contains(&case) || (self.start..=at).contains(&case) {
return false;
}
if case > self.start {
first_case = first_case.min(case);
}
true
})
.count()
}
}
fn recognize(
block: &Block,
target: &Expr,
image: &Image,
bound: Option<Bound>,
checked_block: Option<&Block>,
limits: &Limits,
) -> Option<Recovered> {
let resolved = flatten(fixed_entries(
flatten(resolve(
target,
&environment_from(block, limits.held.clone()),
)),
image,
));
let pattern = table_pattern(&resolved).or_else(|| scaled_before(&resolved, checked_block));
let Some((base, start, index, scale, entry)) = pattern else {
return None;
};
let table = Table {
base,
start,
scale,
entry,
};
if !image
.section_at(table.start)
.is_some_and(|section| section.read_only || section.executable)
{
return None;
}
let entry_bytes = table.entry_bytes();
if let Some(value) = constant(&index)
&& value < 4096
{
let Some(case) = table.read_case(image, value) else {
return None;
};
let Some(at) = entry_address(table.start, value, entry_bytes) else {
return None;
};
return Some(Recovered {
block_start: block.start,
index: Expr::Const(value),
cases: vec![(value as i64, case)],
default: None,
table: (at, entry_bytes),
});
}
let (count, default, minimum, switch_base) = match bound {
Some(bound) => (bound.count, bound.default, bound.minimum, bound.switch_base),
None if let largest = largest(&index)
&& largest < 4096 =>
{
(largest as i64 + 1, None, 0, index.clone())
}
None => {
let count = table.unchecked_count(image, limits);
if count < 2 {
return None;
}
(count as i64, None, 0, index.clone())
}
};
if count <= 0 || count > 4096 {
return None;
}
let mut read = std::collections::HashSet::new();
vlk_ir::ir::visit::collect_reads(&switch_base, &mut read);
let base_still_held = !checked_block
.into_iter()
.chain(std::iter::once(block))
.flat_map(|block| &block.stmts)
.any(|stmt| {
vlk_ir::ir::visit::statement_registers(stmt)
.0
.iter()
.any(|written| read.contains(written))
});
let mut cases = Vec::new();
for position in 0..count {
let Some(case) = table.read_case(image, position as u64) else {
return None;
};
cases.push((case_value(minimum, position), case));
}
let index = if minimum == 0 {
index
} else if base_still_held {
switch_base
} else {
Expr::bin(BinOp::Add, index, Expr::Const(minimum as u64))
};
Some(Recovered {
block_start: block.start,
index,
cases,
default,
table: (table.start, count as u64 * entry_bytes),
})
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Entry {
Byte,
Offset32,
Wrapped32,
Absolute,
Absolute32,
}
fn fixed_entries(expr: Expr, image: &Image) -> Expr {
match expr {
Expr::Load {
addr,
width,
signed,
} => {
let addr = fixed_entries(*addr, image);
let address = match &addr {
Expr::Const(address) => Some(*address),
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} => match (lhs.as_ref(), rhs.as_ref()) {
(Expr::Const(address), Expr::Const(mask)) => Some(address & mask),
_ => None,
},
_ => None,
};
if width == 4
&& let Some(value) = address.and_then(|address| image.fixed_table_entry(address))
{
return Expr::Const(value);
}
Expr::Load {
addr: Box::new(addr),
width,
signed,
}
}
Expr::Bin { op, lhs, rhs } => Expr::Bin {
op,
lhs: Box::new(fixed_entries(*lhs, image)),
rhs: Box::new(fixed_entries(*rhs, image)),
},
other => other,
}
}
fn flatten(expr: Expr) -> Expr {
fn terms(expr: Expr, parts: &mut Vec<Expr>, constant: &mut u64) {
match expr {
Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} => {
terms(*lhs, parts, constant);
terms(*rhs, parts, constant);
}
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff))
&& matches!(
lhs.as_ref(),
Expr::Bin {
op: BinOp::Add | BinOp::Shl,
..
}
) =>
{
terms(*lhs, parts, constant);
}
Expr::Const(value) => *constant = constant.wrapping_add(value),
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} if matches!(
(lhs.as_ref(), rhs.as_ref()),
(Expr::Const(_), Expr::Const(0xffff_ffff))
) =>
{
if let Expr::Const(value) = *lhs {
*constant = constant.wrapping_add(value & 0xffff_ffff);
}
}
other => parts.push(flatten(other)),
}
}
match expr {
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff))
&& matches!(lhs.as_ref(), Expr::Bin { op: BinOp::Add, .. }) =>
{
let (mut parts, mut constant) = (Vec::new(), 0u64);
terms(*lhs, &mut parts, &mut constant);
let constant = constant & 0xffff_ffff;
let Some(sum) = parts.into_iter().reduce(|sum, part| Expr::Bin {
op: BinOp::Add,
lhs: Box::new(sum),
rhs: Box::new(part),
}) else {
return Expr::Const(constant);
};
let sum = if constant == 0 {
sum
} else {
Expr::Bin {
op: BinOp::Add,
lhs: Box::new(sum),
rhs: Box::new(Expr::Const(constant)),
}
};
Expr::Bin {
op: BinOp::And,
lhs: Box::new(sum),
rhs,
}
}
Expr::Bin { op, lhs, rhs } => Expr::Bin {
op,
lhs: Box::new(flatten(*lhs)),
rhs: Box::new(flatten(*rhs)),
},
Expr::Load {
addr,
width,
signed,
} => Expr::Load {
addr: Box::new(flatten(*addr)),
width,
signed,
},
other => other,
}
}
fn cancel(expr: Expr) -> Expr {
if let Expr::Bin { op, lhs, rhs } = &expr
&& let Expr::Bin {
op: inner_op,
lhs: value,
rhs: inner_rhs,
} = lhs.as_ref()
&& inner_rhs == rhs
&& matches!(
(op, inner_op),
(BinOp::Add, BinOp::Sub) | (BinOp::Sub, BinOp::Add)
)
{
return value.as_ref().clone();
}
expr
}
pub(crate) fn resolve(expr: &Expr, environment: &std::collections::HashMap<u16, Expr>) -> Expr {
match expr {
Expr::Reg { index, .. } => match environment.get(index) {
Some(value) => value.clone(),
None => expr.clone(),
},
Expr::Bin { op, lhs, rhs } => {
Expr::bin(*op, resolve(lhs, environment), resolve(rhs, environment))
}
Expr::Load {
addr,
width,
signed,
} => Expr::Load {
addr: Box::new(resolve(addr, environment)),
width: *width,
signed: *signed,
},
Expr::SignExtend { value, width } => Expr::SignExtend {
value: Box::new(resolve(value, environment)),
width: *width,
},
Expr::Select {
cond,
lhs,
rhs,
then,
els,
} => Expr::Select {
cond: *cond,
lhs: Box::new(resolve(lhs, environment)),
rhs: Box::new(resolve(rhs, environment)),
then: Box::new(resolve(then, environment)),
els: Box::new(resolve(els, environment)),
},
Expr::Apply { op, args } => Expr::Apply {
op: *op,
args: args.iter().map(|arg| resolve(arg, environment)).collect(),
},
Expr::Const(_) => expr.clone(),
}
}
fn strip_constant_masks(expr: &Expr) -> &Expr {
match expr {
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} if matches!(rhs.as_ref(), Expr::Const(_)) => strip_constant_masks(lhs),
_ => expr,
}
}
pub(crate) fn constant(expr: &Expr) -> Option<u64> {
match expr {
Expr::Const(value) => Some(*value),
_ => None,
}
}
fn unwrap_mask(expr: &Expr) -> &Expr {
if let Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} = expr
&& matches!(
rhs.as_ref(),
Expr::Const(0xffff_ffff) | Expr::Const(u64::MAX)
)
{
return unwrap_mask(lhs);
}
expr
}
fn scaled_before(
expr: &Expr,
checked_block: Option<&Block>,
) -> Option<(u64, u64, Expr, i64, Entry)> {
let Expr::Load {
addr,
width: 4,
signed: false,
} = strip_constant_masks(expr)
else {
return None;
};
let Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} = unwrap_mask(addr)
else {
return None;
};
let (table, register) = match (lhs.as_ref(), rhs.as_ref()) {
(Expr::Const(table), Expr::Reg { index, .. })
| (Expr::Reg { index, .. }, Expr::Const(table)) => (*table, *index),
_ => return None,
};
let scaled = checked_block?
.stmts
.iter()
.rev()
.find_map(|stmt| match stmt {
Stmt::Assign { dest, value, .. } if dest.index == register => Some(matches!(
unwrap_mask(value),
Expr::Bin { op: BinOp::Shl, rhs, .. } if constant(rhs) == Some(2)
)),
_ => None,
});
if scaled != Some(true) {
return None;
}
let index = Expr::bin(BinOp::Shr, Expr::reg(register, 32), Expr::Const(2));
Some((0, table & 0xffff_ffff, index, 0, Entry::Absolute32))
}
fn table_pattern(expr: &Expr) -> Option<(u64, u64, Expr, i64, Entry)> {
let expr = match expr {
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} if constant(rhs) == Some(0xffff_ffff)
&& matches!(
lhs.as_ref(),
Expr::Load {
width: 4,
signed: false,
..
}
) =>
{
lhs.as_ref()
}
expr => expr,
};
if let Expr::Load {
addr,
width,
signed,
} = expr
&& (*width == 8 || (*width == 4 && !signed))
{
let address = match addr.as_ref() {
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} if *width == 4 && constant(rhs) == Some(0xffff_ffff) => lhs.as_ref(),
_ => addr,
};
let (Some(table), Some(index)) = (table_address(address), index_expression(address)) else {
return None;
};
if *width == 4 && !absolute32_address(address) {
return None;
}
let entry = if *width == 4 {
Entry::Absolute32
} else {
Entry::Absolute
};
let table = if *width == 4 && address != addr.as_ref() {
table & 0xffff_ffff
} else {
table
};
return Some((0, table, index, 0, entry));
}
if let Expr::Bin {
op: BinOp::And,
lhs: sum,
rhs: mask,
} = expr
&& constant(mask) == Some(0xffff_ffff)
&& let Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} = sum.as_ref()
&& let Some((base, value)) = match (constant(lhs), constant(rhs)) {
(Some(base), None) => Some((base, rhs.as_ref())),
(None, Some(base)) => Some((base, lhs.as_ref())),
_ => None,
}
&& let Expr::Load {
addr,
width: 4,
signed: false,
} = strip_constant_masks(value)
&& let addr = unwrap_mask(addr)
&& let (Some(table), Some(index)) = (table_address(addr), index_expression(addr))
{
return Some((base, table, index, 0, Entry::Wrapped32));
}
let Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} = unwrap_mask(expr)
else {
return Option::None;
};
let (base, value) = match (constant(lhs), constant(rhs)) {
(Some(base), None) => (base, rhs.as_ref()),
(None, Some(base)) => (base, lhs.as_ref()),
_ => return Option::None,
};
if let Expr::Bin {
op: BinOp::Shl,
lhs,
rhs,
} = value
{
let peeled = strip_constant_masks(lhs);
if let (
Expr::Load {
addr,
width,
signed,
},
Some(scale),
) = (peeled, constant(rhs))
&& *width == 1
&& !*signed
&& let addr = unwrap_mask(addr)
&& let (Some(table), Some(index)) = (table_address(addr), index_expression(addr))
{
return Some((base, table, index, scale as i64, Entry::Byte));
}
}
let entry = match strip_constant_masks(value) {
Expr::SignExtend { value, width: 4 } => strip_constant_masks(value),
other => other,
};
let signed = matches!(
strip_constant_masks(value),
Expr::SignExtend { width: 4, .. }
) || matches!(entry, Expr::Load { signed: true, .. });
if let Expr::Load { addr, width: 4, .. } = entry
&& signed
&& let (Some(table), Some(index)) = (table_address(addr), index_expression(addr))
{
return Some((base, table, index, 0, Entry::Offset32));
}
Option::None
}
fn absolute32_address(address: &Expr) -> bool {
let scaled = match address {
Expr::Const(_) => return true,
Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} if constant(lhs).is_some() => rhs,
Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} if constant(rhs).is_some() => lhs,
_ => return false,
};
matches!(scaled.as_ref(), Expr::Bin { op: BinOp::Mul, rhs, .. } if constant(rhs) == Some(4))
|| matches!(scaled.as_ref(), Expr::Bin { op: BinOp::Shl, rhs, .. } if constant(rhs) == Some(2))
}
fn table_address(expr: &Expr) -> Option<u64> {
match expr {
Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} => constant(lhs).or_else(|| constant(rhs)),
Expr::Const(value) => Some(*value),
_ => None,
}
}
fn index_expression(expr: &Expr) -> Option<Expr> {
match expr {
Expr::Bin {
op: BinOp::Add,
lhs,
rhs,
} => {
if constant(lhs).is_some() {
Some(unscale((**rhs).clone()))
} else if constant(rhs).is_some() {
Some(unscale((**lhs).clone()))
} else {
None
}
}
Expr::Const(_) => Some(Expr::Const(0)),
_ => None,
}
}
fn unscale(expr: Expr) -> Expr {
if let Expr::Bin {
op: BinOp::Shr,
lhs,
rhs,
} = &expr
&& let Expr::Bin {
op: BinOp::Shl,
lhs: index,
rhs: up,
} = lhs.as_ref()
&& let (Some(up), Some(down)) = (constant(up), constant(rhs))
&& up < 64
&& (1..=3).contains(&up.wrapping_sub(down))
{
return Expr::bin(BinOp::And, (**index).clone(), Expr::Const(u64::MAX >> up));
}
match expr {
Expr::Bin {
op: BinOp::Mul,
lhs,
rhs,
} if matches!(rhs.as_ref(), Expr::Const(4 | 8)) => *lhs,
Expr::Bin {
op: BinOp::Shl,
lhs,
rhs,
} => match rhs.as_ref() {
Expr::Const(scale) if *scale > 0 => *lhs,
_ => Expr::Bin {
op: BinOp::Shl,
lhs,
rhs,
},
},
other => other,
}
}
#[cfg(test)]
mod tests;
#[cfg(kani)]
mod proofs {
use super::*;
#[kani::proof]
fn referenced_addresses_follow_the_encodings() {
let bytes: [u8; 7] = kani::any();
let site: u64 = kani::any();
let lea =
bytes[0] & 0xf8 == 0x48 && bytes[1] == 0x8d && bytes[2] >> 6 == 0 && bytes[2] & 7 == 5;
let displacement = i128::from(i32::from_le_bytes([bytes[3], bytes[4], bytes[5], bytes[6]]));
let expected = (i128::from(site) + 7 + displacement).rem_euclid(1 << 64) as u64;
assert_eq!(rip_relative_lea(&bytes, site), lea.then_some(expected));
let adrp: u32 = kani::any();
let add: u32 = kani::any();
let pair = adrp >> 31 == 1
&& (adrp >> 24) & 0x1f == 0x10
&& add >> 22 == 0x244
&& adrp & 0x1f != 31
&& (add >> 5) & 0x1f == adrp & 0x1f;
let immediate = ((adrp >> 29) & 0x3) | ((adrp >> 3) & 0x1f_fffc);
let pages = if immediate & (1 << 20) != 0 {
i128::from(immediate) - (1 << 21)
} else {
i128::from(immediate)
};
let target = i128::from(site & !0xfff) + pages * 4096 + i128::from((add >> 10) & 0xfff);
let target = target.rem_euclid(1 << 64) as u64;
assert_eq!(adrp_add(adrp, add, site), pair.then_some(target));
kani::cover!(pair && pages < 0, "a page below the site");
}
#[kani::proof]
fn case_values_name_the_checked_value() {
let bits: u32 = kani::any();
kani::assume((1..=64).contains(&bits));
let limit: u64 = kani::any();
let offset: u64 = kani::any();
let value: u64 = kani::any();
kani::assume(value & mask(bits) == value);
let subtract: bool = kani::any();
let inclusive: bool = kani::any();
let cond = if inclusive {
vlk_ir::ir::Cond::Hi
} else {
vlk_ir::ir::Cond::Cs
};
let (adjustment, checked) = if subtract {
(Adjustment::Sub(offset), value.wrapping_sub(offset))
} else {
(Adjustment::Add(offset), value.wrapping_add(offset))
};
let checked = checked & mask(bits);
let minimum = lowest_case(adjustment);
let Some(count) = case_count(inclusive, limit & mask(bits)) else {
assert!(
limit & mask(bits) > i64::MAX as u64
|| (inclusive && limit & mask(bits) == i64::MAX as u64)
);
return;
};
let passes = !vlk_ir::ir::semantics::holds(cond, checked, limit, bits);
assert_eq!(passes, (checked as i64) < count && checked < 1 << 63);
if passes {
let case = case_value(minimum, checked as i64) as u64;
assert_eq!(case & mask(bits), value);
if bits == 64 {
assert_eq!(case, value);
}
kani::cover!(
bits == 32 && offset > 0xffff_0000,
"a 32-bit negative constant"
);
kani::cover!(!inclusive && count > 0, "an exclusive check");
}
let position: u64 = kani::any();
if (position as i64) < count && position < 1 << 63 {
assert!(!vlk_ir::ir::semantics::holds(cond, position, limit, bits));
}
}
#[kani::proof]
fn absolute32_entries_follow_32_bit_addresses() {
let constant: u64 = kani::any();
let position: u64 = kani::any();
kani::assume(position < 4096);
let address = (u128::from(constant & 0xffff_ffff) + u128::from(position) * 4) as u64;
let wrapped = constant.wrapping_add(position * 4) & 0xffff_ffff;
match entry_address32(constant & 0xffff_ffff, position) {
Some(at) => {
assert_eq!(at, wrapped);
assert!(at + 3 <= u64::from(u32::MAX));
}
None => assert!(address + 3 > u64::from(u32::MAX)),
}
kani::cover!(
constant > u64::from(u32::MAX)
&& entry_address32(constant & 0xffff_ffff, position).is_some(),
"a sign-extended table address"
);
}
#[kani::proof]
fn table_entries_stay_in_the_address_space() {
let table: u64 = kani::any();
let position: u64 = kani::any();
let entry_bytes: u64 = kani::any();
let exact = u128::from(table) + u128::from(position) * u128::from(entry_bytes);
match entry_address(table, position, entry_bytes) {
Some(at) => assert_eq!(u128::from(at), exact),
None => {
assert!(exact > u128::from(u64::MAX));
}
}
let byte: u8 = kani::any();
let scale: i64 = kani::any();
match byte_offset(byte, scale) {
Some(offset) => {
assert!((0..64).contains(&scale));
assert_eq!(offset as u64, (u64::from(byte)).wrapping_shl(scale as u32));
kani::cover!(scale > 56 && byte > 1, "high bits leave the value");
}
None => {
assert!(!(0..64).contains(&scale));
}
}
}
}