use std::collections::HashMap;
use vlk_ir::ir::{Block, Expr, FunctionIr, Stmt};
pub type NarrowReturn<'a> = &'a dyn Fn(u64) -> bool;
fn register_writes(blocks: &[Block], narrow_return: NarrowReturn<'_>) -> HashMap<u16, Vec<u8>> {
use vlk_ir::ir::BinOp;
let mut writes: HashMap<u16, Vec<u8>> = HashMap::new();
for block in blocks {
for stmt in &block.stmts {
match stmt {
Stmt::Assign { dest, value, .. } => {
let width = match value {
Expr::Bin {
op: BinOp::And,
rhs,
..
} if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => 32,
Expr::Const(value) if *value <= 0xffff_ffff => 0,
_ => 64,
};
writes.entry(dest.index).or_default().push(width);
}
Stmt::Call { target, .. } => {
let narrow = !stmt.has_declared_call() && target.is_some_and(narrow_return);
let returned = stmt.primary_call_output().map(|output| output.dest.index);
for written in vlk_ir::ir::visit::statement_registers(stmt).0 {
let width = if narrow && Some(written) == returned {
32
} else {
64
};
writes.entry(written).or_default().push(width);
}
}
_ => {
for written in vlk_ir::ir::visit::statement_registers(stmt).0 {
writes.entry(written).or_default().push(64);
}
}
}
}
}
writes
}
fn only_32_bit_writes(writes: &HashMap<u16, Vec<u8>>, register: u16) -> bool {
writes
.get(®ister)
.is_some_and(|widths| !widths.is_empty() && widths.iter().all(|width| *width == 32))
}
pub fn returns_32(blocks: &[Block], narrow_return: NarrowReturn<'_>) -> bool {
let writes = register_writes(blocks, narrow_return);
let mut returns = blocks
.iter()
.filter_map(|block| match block.stmts.last() {
Some(Stmt::Ret { value, .. }) => Some(value),
_ => None,
})
.peekable();
returns.peek().is_some()
&& returns.all(|value| {
let Expr::Reg { index, width: 64 } = value else {
return false;
};
writes.get(index).is_some_and(|widths| {
widths.contains(&32) && widths.iter().all(|width| *width <= 32)
})
})
}
pub fn specialize_widths(
ir: &mut FunctionIr,
narrow_return: NarrowReturn<'_>,
) -> std::collections::HashSet<u16> {
use std::collections::HashSet;
use vlk_ir::ir::BinOp;
let writes = register_writes(&ir.blocks, narrow_return);
for block in &mut ir.blocks {
for stmt in &mut block.stmts {
let Stmt::Ret { value, .. } = stmt else {
continue;
};
let Expr::Reg { index, width: 64 } = value else {
continue;
};
if only_32_bit_writes(&writes, *index) {
*value = Expr::Reg {
index: *index,
width: 32,
};
}
}
}
let mut reads: HashMap<u16, Vec<u8>> = HashMap::new();
for block in &mut ir.blocks {
for stmt in &mut block.stmts {
map_stmt(stmt, &mut |expr| {
let expr = expr.clone();
fn visit(expr: &Expr, reads: &mut HashMap<u16, Vec<u8>>) {
match expr {
Expr::Const(_) => {}
Expr::Reg { index, width } => {
reads.entry(*index).or_default().push(*width);
}
Expr::Bin {
op: BinOp::And,
lhs,
rhs,
..
} if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => match lhs.as_ref()
{
Expr::Reg { index, .. } => {
reads.entry(*index).or_default().push(32);
}
other => visit(other, reads),
},
Expr::Bin { lhs, rhs, .. } => {
visit(lhs, reads);
visit(rhs, reads);
}
Expr::Load { addr, .. } => visit(addr, reads),
Expr::SignExtend { value, .. } => visit(value, reads),
Expr::Select {
lhs,
rhs,
then,
els,
..
} => {
visit(lhs, reads);
visit(rhs, reads);
visit(then, reads);
visit(els, reads);
}
Expr::Apply { args, .. } => {
for arg in args {
visit(arg, reads);
}
}
}
}
visit(&expr, &mut reads);
expr
});
}
}
let registers_used_only_at_32_bits: HashSet<u16> = reads
.keys()
.chain(writes.keys())
.copied()
.filter(|index| {
let read_all_32 = reads
.get(index)
.is_none_or(|widths| widths.iter().all(|width| *width == 32));
let write_all_32 = writes
.get(index)
.is_none_or(|widths| widths.iter().all(|width| *width == 32));
*index != u16::MAX && read_all_32 && write_all_32
})
.collect();
for block in &mut ir.blocks {
for stmt in &mut block.stmts {
map_stmt(stmt, &mut |expr| {
rewrite_read_masks(expr, ®isters_used_only_at_32_bits)
});
for dest in vlk_ir::ir::visit::statement_destinations_mut(stmt) {
if registers_used_only_at_32_bits.contains(&dest.index) {
dest.width = 32;
}
}
if let Stmt::Assign { dest, value, .. } = stmt
&& registers_used_only_at_32_bits.contains(&dest.index)
&& let Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} = value
&& matches!(rhs.as_ref(), Expr::Const(0xffff_ffff))
{
*value = (**lhs).clone();
}
}
}
registers_used_only_at_32_bits
}
fn extended_word(value: &Expr, words: &std::collections::HashSet<u16>) -> bool {
use vlk_ir::ir::{BinOp, Operation};
match value {
Expr::SignExtend { width, .. } => *width <= 4,
Expr::Const(value) => *value as i64 == i64::from(*value as i32),
Expr::Load { width, signed, .. } => (*signed && *width <= 4) || *width <= 2,
Expr::Reg { index, width: 64 } => words.contains(index),
Expr::Select { then, els, .. } => extended_word(then, words) && extended_word(els, words),
Expr::Bin {
op: BinOp::And,
rhs,
..
} => matches!(rhs.as_ref(), Expr::Const(mask) if *mask <= 0x7fff_ffff),
Expr::Apply { op, .. } => matches!(
op,
Operation::FloatEqual(_)
| Operation::FloatLess(_)
| Operation::FloatLessEqual(_)
| Operation::FloatUnordered(_)
),
_ => false,
}
}
fn low_word(value: Expr) -> Expr {
use vlk_ir::ir::BinOp;
match value {
Expr::SignExtend { value, width: 4 } => low_word(*value),
Expr::Bin { op, lhs, rhs }
if matches!(
op,
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor
) =>
{
Expr::Bin {
op,
lhs: Box::new(low_word(*lhs)),
rhs: Box::new(low_word(*rhs)),
}
}
Expr::Bin {
op: BinOp::Shl,
lhs,
rhs,
} if matches!(rhs.as_ref(), Expr::Const(count) if *count < 32) => Expr::Bin {
op: BinOp::Shl,
lhs: Box::new(low_word(*lhs)),
rhs,
},
Expr::Select {
cond,
lhs,
rhs,
then,
els,
} => Expr::Select {
cond,
lhs,
rhs,
then: Box::new(low_word(*then)),
els: Box::new(low_word(*els)),
},
other => other,
}
}
fn compared_word(value: &Expr) -> Option<Expr> {
use vlk_ir::ir::BinOp;
match value {
Expr::SignExtend { value, width: 4 } => Some(match value.as_ref() {
Expr::Reg { width: 32, .. } => (**value).clone(),
other => Expr::Bin {
op: BinOp::And,
lhs: Box::new(low_word(other.clone())),
rhs: Box::new(Expr::Const(0xffff_ffff)),
},
}),
Expr::Const(value) if *value as i64 == i64::from(*value as i32) => {
Some(Expr::Const(value & 0xffff_ffff))
}
_ => None,
}
}
fn compare_words(cond: vlk_ir::ir::Cond, lhs: &mut Expr, rhs: &mut Expr) {
use vlk_ir::ir::Cond;
if !matches!(
cond,
Cond::Eq
| Cond::Ne
| Cond::Lt
| Cond::Ge
| Cond::Gt
| Cond::Le
| Cond::Cc
| Cond::Cs
| Cond::Hi
| Cond::Ls
) || !(matches!(lhs, Expr::SignExtend { .. }) || matches!(rhs, Expr::SignExtend { .. }))
{
return;
}
if let (Some(left), Some(right)) = (compared_word(lhs), compared_word(rhs)) {
*lhs = left;
*rhs = right;
}
}
fn rewrite_words(expr: &Expr, words: &std::collections::HashSet<u16>) -> Expr {
let again = |expr: &Expr| rewrite_words(expr, words);
match expr {
Expr::Reg { index, width: 64 } if words.contains(index) => Expr::SignExtend {
value: Box::new(Expr::Reg {
index: *index,
width: 32,
}),
width: 4,
},
Expr::Reg { .. } | Expr::Const(_) => expr.clone(),
Expr::Bin { op, lhs, rhs } => Expr::Bin {
op: *op,
lhs: Box::new(again(lhs)),
rhs: Box::new(again(rhs)),
},
Expr::Load {
addr,
width,
signed,
} => Expr::Load {
addr: Box::new(again(addr)),
width: *width,
signed: *signed,
},
Expr::SignExtend { value, width } => {
let value = again(value);
Expr::SignExtend {
value: Box::new(if *width == 4 { low_word(value) } else { value }),
width: *width,
}
}
Expr::Select {
cond,
lhs,
rhs,
then,
els,
} => {
let (mut lhs, mut rhs) = (again(lhs), again(rhs));
compare_words(*cond, &mut lhs, &mut rhs);
Expr::Select {
cond: *cond,
lhs: Box::new(lhs),
rhs: Box::new(rhs),
then: Box::new(again(then)),
els: Box::new(again(els)),
}
}
Expr::Apply { op, args } => Expr::Apply {
op: *op,
args: args.iter().map(again).collect(),
},
}
}
pub fn narrow_extended_words(ir: &mut FunctionIr) -> std::collections::HashSet<u16> {
use std::collections::HashSet;
let mut excluded: HashSet<u16> = HashSet::new();
let mut words: HashSet<u16> = HashSet::new();
for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
match stmt {
Stmt::Assign { dest, .. } if dest.width == 64 && vlk_ir::ir::is_temp(dest.index) => {
words.insert(dest.index);
}
Stmt::Assign { dest, .. } => {
excluded.insert(dest.index);
}
Stmt::Store { .. }
| Stmt::Brif { .. }
| Stmt::Ret { .. }
| Stmt::BrIndirect { .. }
| Stmt::Switch { .. } => {}
Stmt::Call { .. } => {
excluded.extend(vlk_ir::ir::visit::statement_registers(stmt).0);
}
other => {
excluded.extend(vlk_ir::ir::visit::statement_registers(other).0);
for value in other.operands() {
vlk_ir::ir::visit::expr_reads(value, &mut excluded);
}
}
}
}
words.retain(|index| !excluded.contains(index));
loop {
let unfit: Vec<u16> = ir
.blocks
.iter()
.flat_map(|block| &block.stmts)
.filter_map(|stmt| match stmt {
Stmt::Assign { dest, value, .. }
if words.contains(&dest.index) && !extended_word(value, &words) =>
{
Some(dest.index)
}
_ => None,
})
.collect();
if unfit.is_empty() {
break;
}
for index in unfit {
words.remove(&index);
}
}
for stmt in ir.blocks.iter_mut().flat_map(|block| &mut block.stmts) {
map_stmt(stmt, &mut |expr| rewrite_words(expr, &words));
match stmt {
Stmt::Assign { dest, value, .. } if words.contains(&dest.index) => {
dest.width = 32;
*value = match low_word(std::mem::replace(value, Expr::Const(0))) {
Expr::Const(value) => Expr::Const(value & 0xffff_ffff),
other => other,
};
}
Stmt::Store { value, width, .. } if *width <= 4 => {
*value = low_word(std::mem::replace(value, Expr::Const(0)));
}
Stmt::Brif { cond, lhs, rhs, .. } => compare_words(*cond, lhs, rhs),
_ => {}
}
}
words
}
fn rewrite_read_masks(
expr: &Expr,
registers_used_only_at_32_bits: &std::collections::HashSet<u16>,
) -> Expr {
use vlk_ir::ir::BinOp;
if let Expr::Bin {
op: BinOp::And,
lhs,
rhs,
} = expr
&& matches!(rhs.as_ref(), Expr::Const(0xffff_ffff))
&& let Expr::Reg { index, .. } = lhs.as_ref()
&& registers_used_only_at_32_bits.contains(index)
{
return Expr::Reg {
index: *index,
width: 32,
};
}
match expr {
Expr::Bin { op, lhs, rhs } => Expr::bin(
*op,
rewrite_read_masks(lhs, registers_used_only_at_32_bits),
rewrite_read_masks(rhs, registers_used_only_at_32_bits),
),
Expr::Load {
addr,
width,
signed,
} => Expr::Load {
addr: Box::new(rewrite_read_masks(addr, registers_used_only_at_32_bits)),
width: *width,
signed: *signed,
},
Expr::SignExtend { value, width } => Expr::SignExtend {
value: Box::new(rewrite_read_masks(value, registers_used_only_at_32_bits)),
width: *width,
},
Expr::Select {
cond,
lhs,
rhs,
then,
els,
} => Expr::Select {
cond: *cond,
lhs: Box::new(rewrite_read_masks(lhs, registers_used_only_at_32_bits)),
rhs: Box::new(rewrite_read_masks(rhs, registers_used_only_at_32_bits)),
then: Box::new(rewrite_read_masks(then, registers_used_only_at_32_bits)),
els: Box::new(rewrite_read_masks(els, registers_used_only_at_32_bits)),
},
Expr::Apply { op, args } => Expr::Apply {
op: *op,
args: args
.iter()
.map(|arg| rewrite_read_masks(arg, registers_used_only_at_32_bits))
.collect(),
},
other => other.clone(),
}
}
fn map_stmt(stmt: &mut Stmt, map: &mut dyn FnMut(&Expr) -> Expr) {
match stmt {
Stmt::Assign { value, .. } => *value = map(&*value),
Stmt::Store { addr, value, .. } => {
*addr = map(&*addr);
*value = map(&*value);
}
Stmt::Brif { lhs, rhs, .. } => {
*lhs = map(&*lhs);
*rhs = map(&*rhs);
}
Stmt::Ret { value, .. } => *value = map(&*value),
Stmt::BrIndirect { target, .. } => *target = map(&*target),
Stmt::Switch { index, .. } => *index = map(&*index),
Stmt::Call { through, args, .. } => {
for value in through.iter_mut().chain(args.iter_mut().flatten()) {
*value = map(&*value);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests;