use vlk_ir::ir::{Expr, Stmt};
use vlk_types::types::Convention;
use crate::lift::{Summaries, arguments};
pub(super) fn count_from_format(
image: &vlk_loader::loader::Image,
made: &mut Stmt,
named: usize,
address: Option<u32>,
) {
if let Some(address) = address
&& let Some(format) = crate::ssa::c_string(image, u64::from(address))
&& let Stmt::Call { kind, args, .. } = made
{
let (words, skipped) = crate::analysis::variadic::o32_argument_words(&format, named);
*args = arguments(
*kind,
Convention::O32,
image.isa,
Some(words.min(4)),
words.saturating_sub(4),
);
if let Some(args) = args {
for word in skipped.into_iter().rev() {
args.remove(word);
}
}
}
}
pub(crate) fn count_from_block_format(
image: &vlk_loader::loader::Image,
summaries: Summaries<'_>,
before: &[Stmt],
made: &mut Stmt,
) {
let Stmt::Call {
target: Some(target),
convention: Convention::O32,
..
} = made
else {
return;
};
let named = usize::from(summaries(*target).further_from);
if !(1..=4).contains(&named) {
return;
}
let format = left_in(before, Convention::O32.arguments()[named - 1]);
count_from_format(image, made, named, format);
}
pub(in crate::lift) fn count_format(
image: &vlk_loader::loader::Image,
summaries: Summaries<'_>,
made: &mut Stmt,
held: impl Fn(u16) -> Option<u64>,
) {
let Stmt::Call {
target: Some(target),
convention: Convention::O32,
..
} = made
else {
return;
};
let named = usize::from(summaries(*target).further_from);
if !(1..=4).contains(&named) {
return;
}
let format = held(Convention::O32.arguments()[named - 1])
.and_then(|address| u32::try_from(address).ok());
count_from_format(image, made, named, format);
}
fn left_in(stmts: &[Stmt], register: u16) -> Option<u32> {
stmts.iter().fold(None, |held, stmt| match stmt {
Stmt::Assign {
dest,
value: Expr::Const(value),
..
} if dest.index == register => u32::try_from(*value).ok(),
other
if vlk_ir::ir::visit::statement_registers(other)
.0
.contains(®ister) =>
{
None
}
_ => held,
})
}
const COPIED: usize = 24;
pub(in crate::lift) fn split_shared_calls(
image: &vlk_loader::loader::Image,
summaries: Summaries<'_>,
kept: &std::collections::HashSet<u64>,
blocks: &mut Vec<vlk_ir::ir::Block>,
) {
let mut index = 1;
while index < blocks.len() {
let shared = &blocks[index];
let ends = matches!(
shared.stmts.last(),
Some(
Stmt::Br {
target: Some(_),
..
} | Stmt::Ret { .. }
| Stmt::Trap { .. }
)
);
let call = shared.stmts.iter().enumerate().find_map(|(at, stmt)| {
let Stmt::Call {
target: Some(target),
convention: Convention::O32,
..
} = stmt
else {
return None;
};
let named = usize::from(summaries(*target).further_from);
(1..=4)
.contains(&named)
.then(|| (at, Convention::O32.arguments()[named - 1]))
});
let Some((at, register)) = call.filter(|(at, register)| {
ends && shared.stmts.len() <= COPIED
&& !shared.stmts[..*at].iter().any(|stmt| {
vlk_ir::ir::visit::statement_registers(stmt)
.0
.contains(register)
})
}) else {
index += 1;
continue;
};
let start = shared.start;
let jumps_here = |block: &vlk_ir::ir::Block| matches!(block.stmts.last(), Some(Stmt::Br { target: Some(target), .. }) if *target == start);
let setting: Vec<(usize, u32)> = blocks
.iter()
.enumerate()
.filter(|(other, block)| *other != index && jumps_here(block))
.filter_map(|(other, block)| Some((other, left_in(&block.stmts, register)?)))
.collect();
if setting.len() < 2 || setting.iter().all(|(_, format)| *format == setting[0].1) {
index += 1;
continue;
}
let copied = blocks[index].stmts.clone();
for (other, _) in &setting {
let stmts = &mut blocks[*other].stmts;
stmts.pop();
let call_at = stmts.len() + at;
stmts.extend(copied.iter().cloned());
let (before, rest) = stmts.split_at_mut(call_at);
count_from_block_format(image, summaries, before, &mut rest[0]);
}
let falls_in = !matches!(
blocks[index - 1].stmts.last(),
Some(
Stmt::Br { .. }
| Stmt::Ret { .. }
| Stmt::Trap { .. }
| Stmt::BrIndirect { .. }
| Stmt::Switch { .. }
)
);
let reached = falls_in
|| kept.contains(&start)
|| blocks.iter().any(|block| {
block.stmts.iter().any(|stmt| match stmt {
Stmt::Br {
target: Some(target),
..
}
| Stmt::Brif { target, .. }
| Stmt::BrifFlags { target, .. } => *target == start,
Stmt::Switch { cases, default, .. } => {
cases.iter().any(|(_, target)| *target == start) || *default == Some(start)
}
_ => false,
})
});
if reached {
index += 1;
} else {
blocks.remove(index);
}
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::split_shared_calls;
use vlk_base::target::Isa;
use vlk_ir::ir::{Block, Cond, Expr, RegRef, Stmt};
use vlk_loader::loader::{Image, Summary};
use vlk_types::types::{CallKind, Convention};
const START: u64 = 0x1000;
const CALLEE: u64 = 0x2000;
fn image() -> Image {
Image::from_code(Isa::Mips32, START, b"done\0%d of %d\0\0\0".to_vec())
}
fn summaries(target: u64) -> Summary {
Summary {
further_from: u8::from(target == CALLEE),
..Summary::default()
}
}
fn set(value: u64) -> Stmt {
Stmt::Assign {
dest: RegRef {
index: Convention::O32.arguments()[0],
width: 64,
},
value: Expr::Const(value),
at: None,
}
}
fn jump(target: u64) -> Stmt {
Stmt::Br {
target: Some(target),
at: None,
}
}
fn returns() -> Stmt {
Stmt::Ret {
value: Expr::reg(vlk_arch::arch::RETURN, 32),
at: None,
}
}
fn blocks(image: &Image, first: u64, second: u64) -> Vec<Block> {
let call = crate::lift::call(CallKind::Invoke, image, &summaries, Some(CALLEE));
vec![
Block {
start: 0x100,
stmts: vec![Stmt::Brif {
cond: Cond::Eq,
lhs: Expr::reg(9, 64),
rhs: Expr::Const(0),
target: 0x120,
at: None,
}],
},
Block {
start: 0x110,
stmts: vec![set(first), jump(0x130)],
},
Block {
start: 0x120,
stmts: vec![set(second), jump(0x130)],
},
Block {
start: 0x130,
stmts: vec![call, returns()],
},
]
}
fn arguments(block: &Block) -> usize {
block
.stmts
.iter()
.find_map(|stmt| match stmt {
Stmt::Call {
args: Some(args), ..
} => Some(args.len()),
_ => None,
})
.unwrap_or_else(|| panic!("{block:?}"))
}
#[test]
fn a_call_two_formats_reach_is_made_once_for_each() {
let image = image();
let mut split = blocks(&image, START, START + 5);
split_shared_calls(&image, &summaries, &HashSet::new(), &mut split);
assert_eq!(
split.iter().map(|block| block.start).collect::<Vec<_>>(),
[0x100, 0x110, 0x120]
);
assert!(matches!(split[1].stmts.last(), Some(Stmt::Ret { .. })));
assert_eq!(arguments(&split[1]), 1);
assert_eq!(arguments(&split[2]), 3);
}
#[test]
fn a_shared_call_stays_where_copying_would_not_help() {
let image = image();
let same = blocks(&image, START, START);
let mut split = same.clone();
split_shared_calls(&image, &summaries, &HashSet::new(), &mut split);
assert_eq!(split.len(), same.len());
let mut split = blocks(&image, START, START + 5);
split_shared_calls(&image, &summaries, &HashSet::from([0x130]), &mut split);
assert_eq!(split.len(), 4);
assert_eq!(arguments(&split[1]), 1);
let mut own = blocks(&image, START, START + 5);
own[3].stmts.insert(0, set(START));
let before = own.len();
split_shared_calls(&image, &summaries, &HashSet::new(), &mut own);
assert_eq!(own.len(), before);
}
}