use std::collections::{BTreeMap, HashMap, HashSet};
use crate::lift::{Summaries, tail_call};
use vlk_ir::ir::{BinOp, Block, Expr, Stmt};
use vlk_loader::loader::Image;
pub(super) type ContinuedCode = BTreeMap<u64, u64>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Leaving {
TailCall,
Continues(u64, u64),
}
pub(super) fn resolve_exits(
image: &Image,
summaries: Summaries<'_>,
function: u64,
blocks: &mut Vec<Block>,
ends: &HashMap<u64, u64>,
) -> ContinuedCode {
let own = image.functions.get(&function);
let exact = own.is_some_and(|function| function.size.is_some() && !function.size_estimated);
let extent = own.and_then(|function| function.size).unwrap_or(0);
let starts: HashSet<u64> = blocks.iter().map(|block| block.start).collect();
let heights = stack_heights(blocks, image.isa);
let mut exits: Vec<u64> = Vec::new();
let mut continued_code = ContinuedCode::new();
let mut jumps: Vec<usize> = Vec::new();
for (index, block) in blocks.iter().enumerate() {
let (target, jump) = match block.stmts.last() {
Some(Stmt::Brif { target, .. } | Stmt::BrifFlags { target, .. }) => (*target, false),
Some(Stmt::Br {
target: Some(target),
..
}) => (*target, true),
_ => continue,
};
if starts.contains(&target) || !(exact || image.functions.contains_key(&target)) {
continue;
}
if let Some(pc) = ends.get(&block.start) {
let at_entry = Some(*pc)
.filter(|pc| {
(function..function.saturating_add(extent)).contains(pc)
|| image.fragment_at(*pc).is_some()
})
.and_then(|pc| image.stack_at_entry(pc))
.or(heights[index].map(|height| height == 0));
if let Leaving::Continues(start, size) = leaving(image, function, target, at_entry) {
continued_code.insert(start, size);
}
}
if jump {
jumps.push(index);
} else {
exits.push(target);
}
}
for index in jumps {
let stmts = &mut blocks[index].stmts;
let Some(Stmt::Br { target, at }) = stmts.pop() else {
unreachable!("a jump ends the block")
};
let [call, result] = tail_call(image, summaries, target);
stmts.push(call.with_origin(at));
stmts.push(result);
}
if exits.is_empty() {
return continued_code;
}
exits.sort_unstable();
exits.dedup();
if let Some(last) = blocks.last_mut()
&& !matches!(
last.stmts.last(),
Some(
Stmt::Ret { .. }
| Stmt::Br { .. }
| Stmt::BrIndirect { .. }
| Stmt::Switch { .. }
| Stmt::Trap { .. }
)
)
{
last.stmts.push(Stmt::Trap { at: None });
}
for target in exits {
blocks.push(Block {
start: target,
stmts: tail_call(image, summaries, Some(target)).into(),
});
}
continued_code
}
fn leaving(image: &Image, function: u64, target: u64, at_entry: Option<bool>) -> Leaving {
if let Some(callee) = image.functions.get(&target) {
return match (at_entry, callee.size) {
(Some(false), Some(size)) => Leaving::Continues(target, size),
_ => Leaving::TailCall,
};
}
image
.functions
.range(..target)
.next_back()
.filter(|(start, _)| **start != function)
.and_then(|(start, function)| {
let Some(size) = function.size else {
return None;
};
Some(start + size)
})
.filter(|end| target < *end)
.map_or(Leaving::TailCall, |end| {
Leaving::Continues(target, end - target)
})
}
type Offsets = rustc_hash::FxHashMap<u16, i64>;
pub(crate) fn stack_heights(blocks: &[Block], isa: vlk_base::target::Isa) -> Vec<Option<i64>> {
let sp = vlk_arch::arch::stack_pointer(isa);
let count = blocks.len();
let successors: Vec<Vec<usize>> = (0..count)
.map(|index| vlk_ir::ir::cfg::block_successors(blocks, index))
.collect();
let mut entry: Vec<Option<Offsets>> = vec![None; count];
let mut exit: Vec<Option<Offsets>> = vec![None; count];
if count == 0 {
return Vec::new();
}
let start: Offsets = [(sp, 0)].into_iter().collect();
loop {
let mut next: Vec<Option<Offsets>> = vec![None; count];
next[0] = Some(start.clone());
for (index, out) in exit.iter().enumerate() {
let Some(out) = out else {
continue;
};
for successor in &successors[index] {
next[*successor] = Some(match next[*successor].take() {
None => out.clone(),
Some(mut known) => {
known.retain(|register, offset| out.get(register) == Some(offset));
known
}
});
}
}
if next == entry {
break;
}
for (index, block) in blocks.iter().enumerate() {
if next[index] == entry[index] {
continue;
}
exit[index] = next[index].clone().map(|mut state| {
for stmt in &block.stmts {
step(stmt, &mut state);
}
state
});
}
entry = next;
}
exit.into_iter()
.map(|state| state.and_then(|state| state.get(&sp).copied()))
.collect()
}
fn step(stmt: &Stmt, state: &mut Offsets) {
if let Stmt::Assign { dest, value, .. } = stmt
&& dest.width == 64
{
match offset_of(value, state) {
Some(offset) => state.insert(dest.index, offset),
None => state.remove(&dest.index),
};
return;
}
state.retain(|register, _| !vlk_ir::ir::visit::statement_writes_register(stmt, *register));
}
fn offset_of(value: &Expr, state: &Offsets) -> Option<i64> {
match value {
Expr::Reg { index, width: 64 } => state.get(index).copied(),
Expr::Bin { op, lhs, rhs } => {
let Expr::Const(by) = rhs.as_ref() else {
return None;
};
let Some(base) = offset_of(lhs, state) else {
return None;
};
match op {
BinOp::Add => Some(base.wrapping_add(*by as i64)),
BinOp::Sub => Some(base.wrapping_sub(*by as i64)),
_ => None,
}
}
_ => None,
}
}
#[cfg(test)]
mod tests;