use wings_ir::{Comparison, Function, Instruction, Operation, Operator};
pub(crate) fn optimize_function(function: &mut Function) {
fold_constants(function);
while prune_constant_branches(function) {
fold_constants(function);
}
}
pub(crate) fn fold_constants(function: &mut Function) {
let mut known: Vec<Option<i64>> = vec![None; function.instructions.len()];
let mut branch_stack: Vec<Option<Vec<usize>>> = Vec::new();
for index in 0..function.instructions.len() {
let folded = match function.instructions[index].operation {
Operation::Constant(value) => {
known[index] = Some(value);
None
}
Operation::NullPid => {
known[index] = Some(0);
None
}
Operation::Negate(operand) => known[operand].and_then(i64::checked_neg),
Operation::Binary(operator, left, right) => match (known[left], known[right]) {
(Some(lv), Some(rv)) => match operator {
Operator::Add => lv.checked_add(rv),
Operator::Subtract => lv.checked_sub(rv),
Operator::Multiply => lv.checked_mul(rv),
Operator::Divide => {
if rv != 0 && !(lv == i64::MIN && rv == -1) {
lv.checked_div(rv)
} else {
None
}
}
Operator::Remainder => {
if rv != 0 && !(lv == i64::MIN && rv == -1) {
lv.checked_rem(rv)
} else {
None
}
}
},
_ => None,
},
Operation::Compare(comparison, left, right) => {
if left == right {
let result = matches!(
comparison,
Comparison::Equal | Comparison::LessEqual | Comparison::GreaterEqual
);
Some(i64::from(result))
} else {
match (known[left], known[right]) {
(Some(lv), Some(rv)) => {
let result = match comparison {
Comparison::Equal => lv == rv,
Comparison::NotEqual => lv != rv,
Comparison::Less => lv < rv,
Comparison::LessEqual => lv <= rv,
Comparison::Greater => lv > rv,
Comparison::GreaterEqual => lv >= rv,
};
Some(i64::from(result))
}
_ => None,
}
}
}
Operation::IsEmptyInts(value) => match function.instructions[value].operation {
Operation::EmptyInts => Some(1),
Operation::PrependInt(_, _) => Some(0),
_ => None,
},
Operation::If(_) => {
branch_stack.push(None);
None
}
Operation::Else(ref then_values) => {
if let Some(slot) = branch_stack.last_mut() {
*slot = Some(then_values.clone());
}
None
}
Operation::EndIf(ref else_values) => {
if let Some(Some(then_values)) = branch_stack.pop() {
for (offset, (&t_reg, &e_reg)) in
then_values.iter().zip(else_values.iter()).enumerate()
{
if let (Some(tv), Some(ev)) = (known[t_reg], known[e_reg]) {
if tv == ev && index + offset < known.len() {
known[index + offset] = Some(tv);
}
}
}
}
None
}
_ => None,
};
if let Some(value) = folded {
function.instructions[index].operation = Operation::Constant(value);
known[index] = Some(value);
}
}
}
pub(crate) fn prune_constant_branches(function: &mut Function) -> bool {
let len = function.instructions.len();
let bounds = compute_branch_bounds(function);
let mut has_candidate = false;
for (index, &branch_bounds) in bounds.iter().enumerate() {
if let Operation::If(cond) = function.instructions[index].operation {
if matches!(
function.instructions[cond].operation,
Operation::Constant(_)
) || is_trivial_identical_branch(function, index, branch_bounds)
{
has_candidate = true;
break;
}
}
}
if !has_candidate {
return false;
}
let mut out = Vec::with_capacity(len);
let mut map = vec![0usize; len];
let mut pruned = false;
let mut index = 0usize;
while index < len {
if let Operation::If(cond) = function.instructions[index].operation {
let taken = match function.instructions[cond].operation {
Operation::Constant(value) => Some(value != 0),
_ if is_trivial_identical_branch(function, index, bounds[index]) => Some(true),
_ => None,
};
if let Some(take_then) = taken {
if let Some((else_idx, endif_idx)) = bounds[index] {
let Operation::Else(ref then_values) =
function.instructions[else_idx].operation
else {
unreachable!();
};
let Operation::EndIf(ref else_values) =
function.instructions[endif_idx].operation
else {
unreachable!();
};
let arity = else_values.len();
if take_then {
for cur in (index + 1)..else_idx {
let inst = &function.instructions[cur];
let remapped = crate::inline::remap_operation(&inst.operation, &map);
map[cur] = out.len();
out.push(Instruction {
ty: inst.ty,
operation: remapped,
});
}
for (offset, &src) in then_values.iter().enumerate() {
map[endif_idx + offset] = map[src];
}
} else {
for cur in (else_idx + 1)..endif_idx {
let inst = &function.instructions[cur];
let remapped = crate::inline::remap_operation(&inst.operation, &map);
map[cur] = out.len();
out.push(Instruction {
ty: inst.ty,
operation: remapped,
});
}
for (offset, &src) in else_values.iter().enumerate() {
map[endif_idx + offset] = map[src];
}
}
pruned = true;
index = endif_idx + arity;
continue;
}
}
}
let inst = &function.instructions[index];
let remapped = crate::inline::remap_operation(&inst.operation, &map);
map[index] = out.len();
out.push(Instruction {
ty: inst.ty,
operation: remapped,
});
index += 1;
}
if pruned {
function.state = map[function.state];
function.reply = map[function.reply];
function.instructions = out;
}
pruned
}
fn compute_branch_bounds(function: &Function) -> Vec<Option<(usize, usize)>> {
let mut bounds = vec![None; function.instructions.len()];
let mut stack: Vec<(usize, Option<usize>)> = Vec::new();
for (idx, inst) in function.instructions.iter().enumerate() {
match inst.operation {
Operation::If(_) => stack.push((idx, None)),
Operation::Else(_) => {
if let Some((_, else_slot)) = stack.last_mut() {
if else_slot.is_none() {
*else_slot = Some(idx);
}
}
}
Operation::EndIf(_) => {
if let Some((if_idx, Some(else_idx))) = stack.pop() {
bounds[if_idx] = Some((else_idx, idx));
}
}
_ => {}
}
}
bounds
}
fn is_trivial_identical_branch(
function: &Function,
if_idx: usize,
bounds: Option<(usize, usize)>,
) -> bool {
let Some((else_idx, endif_idx)) = bounds else {
return false;
};
if else_idx != if_idx + 1 || endif_idx != else_idx + 1 {
return false;
}
match (
&function.instructions[else_idx].operation,
&function.instructions[endif_idx].operation,
) {
(Operation::Else(then_vals), Operation::EndIf(else_vals)) => then_vals == else_vals,
_ => false,
}
}
#[cfg(test)]
mod tests {
use wings_abi::ValueType;
use wings_ir::{Comparison, Function, Instruction, Operation, Operator};
use super::fold_constants;
#[test]
fn folds_safe_constants_and_preserves_overflow_and_div_by_zero_faults() {
let mut function = Function {
instructions: vec![
Instruction {
ty: ValueType::Int,
operation: Operation::Constant(20),
},
Instruction {
ty: ValueType::Int,
operation: Operation::Constant(22),
},
Instruction {
ty: ValueType::Int,
operation: Operation::Binary(Operator::Add, 0, 1),
},
Instruction {
ty: ValueType::Bool,
operation: Operation::Compare(Comparison::Equal, 2, 0),
},
Instruction {
ty: ValueType::Int,
operation: Operation::Constant(0),
},
Instruction {
ty: ValueType::Int,
operation: Operation::Binary(Operator::Divide, 2, 4),
},
],
state: 2,
reply: 3,
};
fold_constants(&mut function);
assert!(matches!(
function.instructions[2].operation,
Operation::Constant(42)
));
assert!(matches!(
function.instructions[3].operation,
Operation::Constant(0)
));
assert!(matches!(
function.instructions[5].operation,
Operation::Binary(Operator::Divide, 2, 4)
));
}
fn inst(ty: ValueType, operation: Operation) -> Instruction {
Instruction { ty, operation }
}
fn int(operation: Operation) -> Instruction {
inst(ValueType::Int, operation)
}
#[test]
fn folds_subtract_multiply_divide_remainder_and_negate_when_safe() {
let mut function = Function {
instructions: vec![
int(Operation::Constant(10)),
int(Operation::Constant(3)),
int(Operation::Binary(Operator::Subtract, 0, 1)),
int(Operation::Binary(Operator::Multiply, 0, 1)),
int(Operation::Binary(Operator::Divide, 0, 1)),
int(Operation::Binary(Operator::Remainder, 0, 1)),
int(Operation::Negate(0)),
],
state: 2,
reply: 2,
};
fold_constants(&mut function);
assert!(matches!(
function.instructions[2].operation,
Operation::Constant(7)
));
assert!(matches!(
function.instructions[3].operation,
Operation::Constant(30)
));
assert!(matches!(
function.instructions[4].operation,
Operation::Constant(3)
));
assert!(matches!(
function.instructions[5].operation,
Operation::Constant(1)
));
assert!(matches!(
function.instructions[6].operation,
Operation::Constant(-10)
));
}
#[test]
fn never_folds_add_subtract_or_multiply_overflow() {
let mut function = Function {
instructions: vec![
int(Operation::Constant(i64::MAX)),
int(Operation::Constant(1)),
int(Operation::Binary(Operator::Add, 0, 1)),
int(Operation::Constant(i64::MIN)),
int(Operation::Binary(Operator::Subtract, 3, 1)),
int(Operation::Constant(i64::MAX)),
int(Operation::Binary(Operator::Multiply, 5, 5)),
],
state: 2,
reply: 2,
};
fold_constants(&mut function);
assert!(matches!(
function.instructions[2].operation,
Operation::Binary(Operator::Add, 0, 1)
));
assert!(matches!(
function.instructions[4].operation,
Operation::Binary(Operator::Subtract, 3, 1)
));
assert!(matches!(
function.instructions[6].operation,
Operation::Binary(Operator::Multiply, 5, 5)
));
}
#[test]
fn never_folds_min_negation_or_min_divide_or_remainder_by_negative_one() {
let mut function = Function {
instructions: vec![
int(Operation::Constant(i64::MIN)),
int(Operation::Negate(0)),
int(Operation::Constant(-1)),
int(Operation::Binary(Operator::Divide, 0, 2)),
int(Operation::Binary(Operator::Remainder, 0, 2)),
],
state: 1,
reply: 1,
};
fold_constants(&mut function);
assert!(matches!(
function.instructions[1].operation,
Operation::Negate(0)
));
assert!(matches!(
function.instructions[3].operation,
Operation::Binary(Operator::Divide, 0, 2)
));
assert!(matches!(
function.instructions[4].operation,
Operation::Binary(Operator::Remainder, 0, 2)
));
}
#[test]
fn never_folds_division_or_remainder_by_zero() {
let mut function = Function {
instructions: vec![
int(Operation::Constant(10)),
int(Operation::Constant(0)),
int(Operation::Binary(Operator::Divide, 0, 1)),
int(Operation::Binary(Operator::Remainder, 0, 1)),
],
state: 2,
reply: 2,
};
fold_constants(&mut function);
assert!(matches!(
function.instructions[2].operation,
Operation::Binary(Operator::Divide, 0, 1)
));
assert!(matches!(
function.instructions[3].operation,
Operation::Binary(Operator::Remainder, 0, 1)
));
}
#[test]
fn folds_every_comparison_operator() {
let mut function = Function {
instructions: vec![
int(Operation::Constant(5)),
int(Operation::Constant(3)),
inst(ValueType::Bool, Operation::Compare(Comparison::Equal, 0, 0)),
inst(
ValueType::Bool,
Operation::Compare(Comparison::NotEqual, 0, 1),
),
inst(ValueType::Bool, Operation::Compare(Comparison::Less, 0, 1)),
inst(
ValueType::Bool,
Operation::Compare(Comparison::LessEqual, 0, 0),
),
inst(
ValueType::Bool,
Operation::Compare(Comparison::Greater, 0, 1),
),
inst(
ValueType::Bool,
Operation::Compare(Comparison::GreaterEqual, 1, 0),
),
],
state: 0,
reply: 2,
};
fold_constants(&mut function);
let expected = [1i64, 1, 0, 1, 1, 0];
for (position, value) in expected.into_iter().enumerate() {
assert!(
matches!(
function.instructions[position + 2].operation,
Operation::Constant(v) if v == value
),
"comparison {} should fold to {value}",
position + 2
);
}
}
#[test]
fn folding_propagates_through_chained_dependent_operations() {
let mut function = Function {
instructions: vec![
int(Operation::Constant(2)),
int(Operation::Constant(3)),
int(Operation::Binary(Operator::Add, 0, 1)),
int(Operation::Constant(4)),
int(Operation::Binary(Operator::Multiply, 2, 3)),
int(Operation::Negate(4)),
inst(ValueType::Bool, Operation::Compare(Comparison::Less, 5, 0)),
],
state: 5,
reply: 6,
};
fold_constants(&mut function);
assert!(matches!(
function.instructions[4].operation,
Operation::Constant(20)
));
assert!(matches!(
function.instructions[5].operation,
Operation::Constant(-20)
));
assert!(matches!(
function.instructions[6].operation,
Operation::Constant(1)
));
}
#[test]
fn folds_null_pid_and_comparisons_over_it() {
let mut function = Function {
instructions: vec![
inst(ValueType::Pid, Operation::NullPid),
inst(ValueType::Pid, Operation::NullPid),
inst(ValueType::Bool, Operation::Compare(Comparison::Equal, 0, 1)),
],
state: 2,
reply: 2,
};
fold_constants(&mut function);
assert!(matches!(
function.instructions[0].operation,
Operation::NullPid
));
assert!(matches!(
function.instructions[2].operation,
Operation::Constant(1)
));
}
#[test]
fn leaves_operations_with_unknown_operands_and_non_scalar_ops_untouched() {
let mut function = Function {
instructions: vec![
int(Operation::Constant(2)),
int(Operation::State),
int(Operation::Binary(Operator::Add, 0, 1)),
inst(ValueType::ListRef, Operation::EmptyInts),
int(Operation::HeadInt(3)),
int(Operation::Binary(Operator::Add, 0, 4)),
],
state: 1,
reply: 5,
};
let before = function.instructions.len();
fold_constants(&mut function);
assert_eq!(function.instructions.len(), before);
assert!(matches!(
function.instructions[2].operation,
Operation::Binary(Operator::Add, 0, 1)
));
assert!(matches!(
function.instructions[4].operation,
Operation::HeadInt(3)
));
assert!(matches!(
function.instructions[5].operation,
Operation::Binary(Operator::Add, 0, 4)
));
}
#[test]
fn preserves_instruction_count_and_positions() {
let mut function = Function {
instructions: vec![
int(Operation::Constant(1)),
int(Operation::Constant(2)),
int(Operation::Binary(Operator::Add, 0, 1)),
int(Operation::Constant(0)),
int(Operation::Binary(Operator::Divide, 2, 3)),
],
state: 2,
reply: 4,
};
fold_constants(&mut function);
assert_eq!(function.instructions.len(), 5);
assert_eq!(function.state, 2);
assert_eq!(function.reply, 4);
assert!(matches!(
function.instructions[2].operation,
Operation::Constant(3)
));
assert!(matches!(
function.instructions[4].operation,
Operation::Binary(Operator::Divide, 2, 3)
));
}
#[test]
fn folds_reflexive_comparisons_and_known_list_emptiness() {
let mut function = Function {
instructions: vec![
int(Operation::State),
inst(ValueType::Bool, Operation::Compare(Comparison::Equal, 0, 0)),
inst(
ValueType::Bool,
Operation::Compare(Comparison::NotEqual, 0, 0),
),
inst(ValueType::Bool, Operation::Compare(Comparison::Less, 0, 0)),
inst(
ValueType::Bool,
Operation::Compare(Comparison::LessEqual, 0, 0),
),
inst(ValueType::ListRef, Operation::EmptyInts),
inst(ValueType::Bool, Operation::IsEmptyInts(5)),
inst(ValueType::ListRef, Operation::PrependInt(0, 5)),
inst(ValueType::Bool, Operation::IsEmptyInts(7)),
],
state: 0,
reply: 1,
};
fold_constants(&mut function);
assert!(matches!(
function.instructions[1].operation,
Operation::Constant(1)
));
assert!(matches!(
function.instructions[2].operation,
Operation::Constant(0)
));
assert!(matches!(
function.instructions[3].operation,
Operation::Constant(0)
));
assert!(matches!(
function.instructions[4].operation,
Operation::Constant(1)
));
assert!(matches!(
function.instructions[6].operation,
Operation::Constant(1)
));
assert!(matches!(
function.instructions[8].operation,
Operation::Constant(0)
));
}
#[test]
fn optimize_function_prunes_nested_constant_branches_and_propagates_multi_phi_merges() {
let mut function = Function {
instructions: vec![
int(Operation::Constant(10)), int(Operation::Constant(10)), inst(ValueType::Bool, Operation::Compare(Comparison::Equal, 0, 1)), inst(ValueType::Unit, Operation::If(2)), inst(ValueType::Bool, Operation::Constant(0)), inst(ValueType::Unit, Operation::If(4)), int(Operation::Binary(Operator::Divide, 0, 4)), int(Operation::Constant(999)), inst(ValueType::Unit, Operation::Else(vec![6, 7])), int(Operation::Constant(32)), int(Operation::Constant(5)), int(Operation::EndIf(vec![9, 10])), int(Operation::PhiValue(1)), inst(ValueType::Unit, Operation::Else(vec![11, 12])), int(Operation::Constant(777)), int(Operation::Constant(888)), int(Operation::EndIf(vec![14, 15])), int(Operation::PhiValue(1)), int(Operation::Binary(Operator::Add, 16, 17)), ],
state: 17,
reply: 18,
};
super::optimize_function(&mut function);
assert!(
!function.instructions.iter().any(|inst| matches!(
inst.operation,
Operation::If(_)
| Operation::Else(_)
| Operation::EndIf(_)
| Operation::PhiValue(_)
)),
"all constant branches and phi nodes should be eliminated"
);
assert!(matches!(
function.instructions[function.state].operation,
Operation::Constant(5)
));
assert!(matches!(
function.instructions[function.reply].operation,
Operation::Constant(37)
));
}
#[test]
fn fold_constants_propagates_identical_branch_constants_and_prunes_trivial_merges() {
let mut function = Function {
instructions: vec![
inst(ValueType::Bool, Operation::Argument(0)), inst(ValueType::Unit, Operation::If(0)), int(Operation::Constant(21)), inst(ValueType::Unit, Operation::Else(vec![2])), int(Operation::Constant(21)), int(Operation::EndIf(vec![4])), int(Operation::Constant(21)), inst(ValueType::Bool, Operation::Compare(Comparison::Equal, 5, 6)), inst(ValueType::Unit, Operation::If(7)), int(Operation::Binary(Operator::Add, 5, 6)), inst(ValueType::Unit, Operation::Else(vec![9])), int(Operation::Constant(0)), int(Operation::EndIf(vec![11])), inst(ValueType::Unit, Operation::If(0)), inst(ValueType::Unit, Operation::Else(vec![12])), int(Operation::EndIf(vec![12])), ],
state: 15,
reply: 15,
};
super::optimize_function(&mut function);
let if_count = function
.instructions
.iter()
.filter(|inst| matches!(inst.operation, Operation::If(_)))
.count();
assert_eq!(if_count, 1);
assert!(matches!(
function.instructions[function.reply].operation,
Operation::Constant(42)
));
}
}