use wings_abi::MAX_SHADOW_ROOTS;
use wings_ir::{Function, Instruction, Operation, Procedure, Register};
const MAX_INLINE_INSTRUCTIONS: usize = 32;
const MAX_INLINED_FUNCTION_LEN: usize = 1024;
const MAX_INLINE_ROUNDS: usize = 3;
pub(crate) fn optimize_procedures(procedures: &[Procedure]) -> Vec<Procedure> {
let mut current: Vec<Procedure> = procedures.to_vec();
for proc in &mut current {
crate::constfold::optimize_function(&mut proc.function);
}
if current.len() <= 1 {
return current;
}
for _ in 0..MAX_INLINE_ROUNDS {
let snapshot = current.clone();
let (own_roots, chain_roots) = procedure_chain_roots(&snapshot);
let mut changed = false;
for (idx, proc) in current.iter_mut().enumerate() {
let before_len = proc.function.instructions.len();
let max_roots = own_roots[idx];
let inlined = inline_small_leaf_calls_with_budget(
&proc.function,
&snapshot,
max_roots,
Some(&chain_roots),
);
if inlined.instructions.len() != before_len
|| inlined
.instructions
.iter()
.zip(&proc.function.instructions)
.any(|(a, b)| {
std::mem::discriminant(&a.operation) != std::mem::discriminant(&b.operation)
})
{
let mut folded = inlined;
crate::constfold::optimize_function(&mut folded);
proc.function = folded;
changed = true;
}
}
if !changed {
break;
}
}
current
}
pub(crate) fn inline_small_leaf_calls(caller: &Function, procedures: &[Procedure]) -> Function {
inline_small_leaf_calls_with_budget(caller, procedures, MAX_SHADOW_ROOTS, None)
}
fn procedure_chain_roots(procedures: &[Procedure]) -> (Vec<usize>, Vec<usize>) {
let own: Vec<usize> = procedures
.iter()
.map(|proc| proc.function.root_plan().capacity)
.collect();
let adjacency: Vec<Vec<usize>> = procedures
.iter()
.map(|proc| {
let mut edges = Vec::new();
for inst in &proc.function.instructions {
if let Operation::Call {
function: callee_idx,
..
} = inst.operation
{
if callee_idx < procedures.len() {
edges.push(callee_idx);
}
}
}
edges
})
.collect();
let chain = wings_analysis::calls::acyclic_chain_costs(&adjacency, &own)
.into_iter()
.map(|cost| cost.min(MAX_SHADOW_ROOTS))
.collect();
(own, chain)
}
fn inline_small_leaf_calls_with_budget(
caller: &Function,
procedures: &[Procedure],
max_total_roots: usize,
cached_chain_roots: Option<&[usize]>,
) -> Function {
if !caller
.instructions
.iter()
.any(|inst| matches!(inst.operation, Operation::Call { .. }))
{
return caller.clone();
}
let eligible: Vec<bool> = procedures
.iter()
.map(|proc| is_inlineable_leaf(&proc.function))
.collect();
if !eligible.iter().any(|&flag| flag) {
return caller.clone();
}
let mut out = Vec::with_capacity(caller.instructions.len());
let mut caller_map = vec![0usize; caller.instructions.len()];
let mut inlined_any = false;
for (index, instruction) in caller.instructions.iter().enumerate() {
if let Operation::Call {
function: callee_idx,
ref arguments,
} = instruction.operation
{
if eligible.get(callee_idx).copied().unwrap_or(false) {
let callee = &procedures[callee_idx].function;
if out.len() + callee.instructions.len() <= MAX_INLINED_FUNCTION_LEN {
let mut callee_map = vec![0usize; callee.instructions.len()];
for (c_idx, c_inst) in callee.instructions.iter().enumerate() {
if let Operation::Argument(arg_idx) = c_inst.operation {
callee_map[c_idx] = caller_map[arguments[arg_idx]];
} else {
let remapped = remap_operation(&c_inst.operation, &callee_map);
let new_idx = out.len();
out.push(Instruction {
ty: c_inst.ty,
operation: remapped,
});
callee_map[c_idx] = new_idx;
}
}
caller_map[index] = callee_map[callee.reply];
inlined_any = true;
continue;
}
}
}
let remapped = remap_operation(&instruction.operation, &caller_map);
let new_idx = out.len();
out.push(Instruction {
ty: instruction.ty,
operation: remapped,
});
caller_map[index] = new_idx;
}
if !inlined_any {
return caller.clone();
}
let candidate = Function {
instructions: out,
state: caller_map[caller.state],
reply: caller_map[caller.reply],
};
let owned_chain_roots;
let callee_chain_roots = match cached_chain_roots {
Some(cached) => cached,
None => {
owned_chain_roots = procedure_chain_roots(procedures).1;
&owned_chain_roots
}
};
let remaining_callee_roots = candidate
.instructions
.iter()
.filter_map(|inst| match inst.operation {
Operation::Call {
function: callee_idx,
..
} => callee_chain_roots.get(callee_idx).copied(),
_ => None,
})
.max()
.unwrap_or(0);
let candidate_roots = candidate.root_plan().capacity;
if candidate_roots > max_total_roots
|| candidate_roots.saturating_add(remaining_callee_roots) > MAX_SHADOW_ROOTS
{
return caller.clone();
}
candidate
}
fn is_inlineable_leaf(function: &Function) -> bool {
if function.instructions.is_empty() || function.instructions.len() > MAX_INLINE_INSTRUCTIONS {
return false;
}
function.instructions.iter().all(|instruction| {
!matches!(
instruction.operation,
Operation::Call { .. }
| Operation::State
| Operation::Loop(_)
| Operation::While(_, _)
| Operation::EndLoop(_)
)
})
}
fn remap_vec(values: &[Register], map: &[usize]) -> Vec<Register> {
values.iter().map(|®| map[reg]).collect()
}
pub(crate) fn remap_operation(operation: &Operation, map: &[usize]) -> Operation {
match *operation {
Operation::Constant(value) => Operation::Constant(value),
Operation::NullPid => Operation::NullPid,
Operation::State => Operation::State,
Operation::Argument(index) => Operation::Argument(index),
Operation::Negate(value) => Operation::Negate(map[value]),
Operation::Binary(op, left, right) => Operation::Binary(op, map[left], map[right]),
Operation::Compare(cmp, left, right) => Operation::Compare(cmp, map[left], map[right]),
Operation::If(cond) => Operation::If(map[cond]),
Operation::Else(ref values) => Operation::Else(remap_vec(values, map)),
Operation::EndIf(ref values) => Operation::EndIf(remap_vec(values, map)),
Operation::Loop(ref values) => Operation::Loop(remap_vec(values, map)),
Operation::While(cond, ref values) => Operation::While(map[cond], remap_vec(values, map)),
Operation::EndLoop(ref values) => Operation::EndLoop(remap_vec(values, map)),
Operation::PhiValue(index) => Operation::PhiValue(index),
Operation::EmptyInts => Operation::EmptyInts,
Operation::PrependInt(head, tail) => Operation::PrependInt(map[head], map[tail]),
Operation::HeadInt(list) => Operation::HeadInt(map[list]),
Operation::TailInts(list) => Operation::TailInts(map[list]),
Operation::IsEmptyInts(list) => Operation::IsEmptyInts(map[list]),
Operation::FillBytes(len, byte) => Operation::FillBytes(map[len], map[byte]),
Operation::BytesLen(value) => Operation::BytesLen(map[value]),
Operation::ByteAt(value, index) => Operation::ByteAt(map[value], map[index]),
Operation::ReplaceByte([source, index, byte]) => {
Operation::ReplaceByte([map[source], map[index], map[byte]])
}
Operation::ReadI64Be(value, index) => Operation::ReadI64Be(map[value], map[index]),
Operation::ReplaceI64Be([source, index, value]) => {
Operation::ReplaceI64Be([map[source], map[index], map[value]])
}
Operation::StringFromBytes(value) => Operation::StringFromBytes(map[value]),
Operation::StringBytes(value) => Operation::StringBytes(map[value]),
Operation::StringLen(value) => Operation::StringLen(map[value]),
Operation::StringAt(value, index) => Operation::StringAt(map[value], map[index]),
Operation::StringSlice([value, start, end]) => {
Operation::StringSlice([map[value], map[start], map[end]])
}
Operation::ConcatStrings(left, right) => Operation::ConcatStrings(map[left], map[right]),
Operation::EqualStrings(left, right) => Operation::EqualStrings(map[left], map[right]),
Operation::StringLiteral(ref text) => Operation::StringLiteral(text.clone()),
Operation::FormatString {
ref blob,
ref pieces,
ref arguments,
} => Operation::FormatString {
blob: blob.clone(),
pieces: pieces.clone(),
arguments: remap_vec(arguments, map),
},
Operation::BytesLiteral(ref bytes) => Operation::BytesLiteral(bytes.clone()),
Operation::IntToString(value) => Operation::IntToString(map[value]),
Operation::BoolToString(value) => Operation::BoolToString(map[value]),
Operation::Collect => Operation::Collect,
Operation::RecordNew {
schema,
ref arguments,
} => Operation::RecordNew {
schema,
arguments: remap_vec(arguments, map),
},
Operation::RecordField { value, field } => Operation::RecordField {
value: map[value],
field,
},
Operation::Call {
function,
ref arguments,
} => Operation::Call {
function,
arguments: remap_vec(arguments, map),
},
Operation::SendSelf {
handler,
ref arguments,
} => Operation::SendSelf {
handler,
arguments: remap_vec(arguments, map),
},
Operation::SendAfterSelf {
delay,
handler,
ref arguments,
} => Operation::SendAfterSelf {
delay: map[delay],
handler,
arguments: remap_vec(arguments, map),
},
Operation::Send {
target,
handler,
ref arguments,
} => Operation::Send {
target: map[target],
handler,
arguments: remap_vec(arguments, map),
},
Operation::SendActor {
target,
actor,
handler,
ref arguments,
} => Operation::SendActor {
target: map[target],
actor,
handler,
arguments: remap_vec(arguments, map),
},
Operation::SendAfter {
target,
delay,
handler,
ref arguments,
} => Operation::SendAfter {
target: map[target],
delay: map[delay],
handler,
arguments: remap_vec(arguments, map),
},
Operation::SendAfterActor {
target,
delay,
actor,
handler,
ref arguments,
} => Operation::SendAfterActor {
target: map[target],
delay: map[delay],
actor,
handler,
arguments: remap_vec(arguments, map),
},
Operation::Monitor { target, handler } => Operation::Monitor {
target: map[target],
handler,
},
Operation::Hostcall {
timeout,
ref arguments,
} => Operation::Hostcall {
timeout: map[timeout],
arguments: remap_vec(arguments, map),
},
Operation::SelfPid => Operation::SelfPid,
Operation::SpawnSelf => Operation::SpawnSelf,
Operation::SpawnActor(actor) => Operation::SpawnActor(actor),
Operation::Request {
target,
timeout,
handler,
callback,
ref arguments,
} => Operation::Request {
target: map[target],
timeout: map[timeout],
handler,
callback,
arguments: remap_vec(arguments, map),
},
Operation::RequestActor {
target,
timeout,
actor,
handler,
callback,
ref arguments,
} => Operation::RequestActor {
target: map[target],
timeout: map[timeout],
actor,
handler,
callback,
arguments: remap_vec(arguments, map),
},
Operation::CancelRequest(id) => Operation::CancelRequest(map[id]),
}
}
#[cfg(test)]
mod tests {
use wings_abi::ValueType;
use wings_ir::{Function, Instruction, Operation, Operator, Procedure};
use super::inline_small_leaf_calls;
use crate::sra::RecordAnalysis;
#[test]
fn inlining_record_constructor_helper_enables_full_sra() {
let make_pair = Procedure {
name: "make_pair".into(),
parameters: vec![("a".into(), ValueType::Int), ("b".into(), ValueType::Int)],
result: ValueType::RecordRef(0),
function: Function {
instructions: vec![
Instruction {
ty: ValueType::Int,
operation: Operation::Argument(0),
},
Instruction {
ty: ValueType::Int,
operation: Operation::Argument(1),
},
Instruction {
ty: ValueType::RecordRef(0),
operation: Operation::RecordNew {
schema: 0,
arguments: vec![0, 1],
},
},
],
state: 2,
reply: 2,
},
};
let caller = Function {
instructions: vec![
Instruction {
ty: ValueType::Int,
operation: Operation::Constant(10),
},
Instruction {
ty: ValueType::Int,
operation: Operation::Constant(32),
},
Instruction {
ty: ValueType::RecordRef(0),
operation: Operation::Call {
function: 0,
arguments: vec![0, 1],
},
},
Instruction {
ty: ValueType::Int,
operation: Operation::RecordField { value: 2, field: 0 },
},
Instruction {
ty: ValueType::Int,
operation: Operation::RecordField { value: 2, field: 1 },
},
Instruction {
ty: ValueType::Int,
operation: Operation::Binary(Operator::Add, 3, 4),
},
],
state: 5,
reply: 5,
};
let inlined = inline_small_leaf_calls(&caller, &[make_pair]);
assert!(
!inlined
.instructions
.iter()
.any(|inst| matches!(inst.operation, Operation::Call { .. }))
);
let mut analysis = RecordAnalysis::analyze(&inlined);
assert!(analysis.elided.iter().any(|&flag| flag));
let mut plan = inlined.root_plan();
analysis.rewrite_root_plan(&inlined, &mut plan);
assert_eq!(plan.capacity, 0);
}
fn inst(ty: ValueType, operation: Operation) -> Instruction {
Instruction { ty, operation }
}
fn int(operation: Operation) -> Instruction {
inst(ValueType::Int, operation)
}
fn adder_procedure() -> Procedure {
Procedure {
name: "add".into(),
parameters: vec![("a".into(), ValueType::Int), ("b".into(), ValueType::Int)],
result: ValueType::Int,
function: Function {
instructions: vec![
int(Operation::Argument(0)),
int(Operation::Argument(1)),
int(Operation::Binary(Operator::Add, 0, 1)),
],
state: 2,
reply: 2,
},
}
}
fn scalar_caller_with_call() -> Function {
Function {
instructions: vec![
int(Operation::Constant(10)),
int(Operation::Constant(32)),
int(Operation::Call {
function: 0,
arguments: vec![0, 1],
}),
],
state: 2,
reply: 2,
}
}
#[test]
fn caller_without_calls_is_returned_unchanged() {
let caller = Function {
instructions: vec![
int(Operation::Constant(1)),
int(Operation::Binary(Operator::Add, 0, 0)),
],
state: 1,
reply: 1,
};
let inlined = inline_small_leaf_calls(&caller, &[adder_procedure()]);
assert_eq!(inlined.instructions.len(), caller.instructions.len());
assert!(matches!(
inlined.instructions[1].operation,
Operation::Binary(Operator::Add, 0, 0)
));
}
#[test]
fn callee_using_state_is_never_inlined() {
let mut stateful = adder_procedure();
stateful.function.instructions[0] = int(Operation::State);
stateful.function.instructions[2].operation = Operation::Binary(Operator::Add, 1, 1);
let caller = scalar_caller_with_call();
let inlined = inline_small_leaf_calls(&caller, &[stateful]);
assert!(matches!(
inlined.instructions[2].operation,
Operation::Call { .. }
));
assert_eq!(inlined.instructions.len(), caller.instructions.len());
}
#[test]
fn callee_containing_a_call_is_never_inlined() {
let mut non_leaf = adder_procedure();
non_leaf.function.instructions.push(int(Operation::Call {
function: 0,
arguments: vec![0, 1],
}));
non_leaf.function.reply = 3;
let caller = scalar_caller_with_call();
let inlined = inline_small_leaf_calls(&caller, &[non_leaf]);
assert_eq!(inlined.instructions.len(), caller.instructions.len());
assert!(matches!(
inlined.instructions[2].operation,
Operation::Call { .. }
));
}
#[test]
fn callee_containing_a_loop_is_never_inlined() {
let mut loopy = adder_procedure();
loopy
.function
.instructions
.push(int(Operation::Loop(vec![0])));
loopy.function.reply = 2;
let caller = scalar_caller_with_call();
let inlined = inline_small_leaf_calls(&caller, &[loopy]);
assert_eq!(inlined.instructions.len(), caller.instructions.len());
assert!(matches!(
inlined.instructions[2].operation,
Operation::Call { .. }
));
}
#[test]
fn callee_exceeding_the_size_cap_is_never_inlined() {
let mut large = adder_procedure();
large.function.instructions = (0..33)
.map(|index| {
if index == 0 {
int(Operation::Argument(0))
} else {
int(Operation::Binary(Operator::Add, index - 1, 0))
}
})
.collect();
large.function.reply = 32;
large.function.state = 32;
let caller = scalar_caller_with_call();
let inlined = inline_small_leaf_calls(&caller, &[large]);
assert_eq!(inlined.instructions.len(), caller.instructions.len());
assert!(matches!(
inlined.instructions[2].operation,
Operation::Call { .. }
));
}
#[test]
fn empty_callee_is_never_inlined() {
let mut empty = adder_procedure();
empty.function.instructions = Vec::new();
empty.function.state = 0;
empty.function.reply = 0;
let caller = scalar_caller_with_call();
let inlined = inline_small_leaf_calls(&caller, &[empty]);
assert_eq!(inlined.instructions.len(), caller.instructions.len());
}
#[test]
fn call_to_unknown_function_index_is_copied_through() {
let caller = Function {
instructions: vec![
int(Operation::Constant(10)),
int(Operation::Constant(32)),
int(Operation::Call {
function: 7,
arguments: vec![0, 1],
}),
],
state: 2,
reply: 2,
};
let inlined = inline_small_leaf_calls(&caller, &[adder_procedure()]);
assert_eq!(inlined.instructions.len(), 3);
assert!(matches!(
inlined.instructions[2].operation,
Operation::Call { function: 7, .. }
));
}
#[test]
fn callee_returning_an_argument_substitutes_the_caller_operand() {
let identity = Procedure {
name: "identity".into(),
parameters: vec![("a".into(), ValueType::Int)],
result: ValueType::Int,
function: Function {
instructions: vec![int(Operation::Argument(0))],
state: 0,
reply: 0,
},
};
let caller = scalar_caller_with_call();
let inlined = inline_small_leaf_calls(&caller, &[identity]);
assert_eq!(inlined.instructions.len(), 2);
assert_eq!(inlined.reply, 0);
assert!(
!inlined
.instructions
.iter()
.any(|inst| matches!(inst.operation, Operation::Call { .. }))
);
}
#[test]
fn branchy_callee_inlines_with_remapped_control_flow() {
let pick = Procedure {
name: "pick".into(),
parameters: vec![
("a".into(), ValueType::Int),
("b".into(), ValueType::Int),
("cond".into(), ValueType::Bool),
],
result: ValueType::Int,
function: Function {
instructions: vec![
int(Operation::Argument(0)),
int(Operation::Argument(1)),
inst(ValueType::Bool, Operation::Argument(2)),
inst(ValueType::Unit, Operation::If(2)),
int(Operation::Binary(Operator::Add, 0, 1)),
inst(ValueType::Unit, Operation::Else(vec![4])),
int(Operation::Binary(Operator::Subtract, 0, 1)),
int(Operation::EndIf(vec![6])),
],
state: 7,
reply: 7,
},
};
let caller = Function {
instructions: vec![
int(Operation::Constant(10)),
int(Operation::Constant(3)),
inst(ValueType::Bool, Operation::Constant(1)),
int(Operation::Call {
function: 0,
arguments: vec![0, 1, 2],
}),
],
state: 3,
reply: 3,
};
let inlined = inline_small_leaf_calls(&caller, &[pick]);
assert!(!inlined.instructions.iter().any(|inst| matches!(
inst.operation,
Operation::Call { .. } | Operation::Argument(_)
)));
assert_eq!(inlined.instructions.len(), 8);
assert!(matches!(
inlined.instructions[3].operation,
Operation::If(2)
));
assert_eq!(inlined.reply, 7);
assert_eq!(inlined.state, 7);
}
#[test]
fn inlining_at_multiple_call_sites_offsets_registers_independently() {
let caller = Function {
instructions: vec![
int(Operation::Constant(1)),
int(Operation::Constant(2)),
int(Operation::Call {
function: 0,
arguments: vec![0, 1],
}),
int(Operation::Call {
function: 0,
arguments: vec![2, 1],
}),
int(Operation::Binary(Operator::Add, 2, 3)),
],
state: 4,
reply: 4,
};
let inlined = inline_small_leaf_calls(&caller, &[adder_procedure()]);
assert!(
!inlined
.instructions
.iter()
.any(|inst| matches!(inst.operation, Operation::Call { .. }))
);
assert_eq!(inlined.instructions.len(), 5);
assert!(matches!(
inlined.instructions[2].operation,
Operation::Binary(Operator::Add, 0, 1)
));
assert!(matches!(
inlined.instructions[3].operation,
Operation::Binary(Operator::Add, 2, 1)
));
}
#[test]
fn calls_that_would_exceed_inlined_length_cap_are_left_as_calls() {
let mut instructions: Vec<Instruction> = vec![int(Operation::Constant(1))];
for _ in 0..1021 {
let last = instructions.len() - 1;
instructions.push(int(Operation::Binary(Operator::Add, last, 0)));
}
let call_index = instructions.len();
let last = instructions.len() - 1;
instructions.push(int(Operation::Call {
function: 0,
arguments: vec![last, 0],
}));
let caller = Function {
instructions,
state: call_index,
reply: call_index,
};
assert_eq!(caller.instructions.len(), 1023);
let inlined = inline_small_leaf_calls(&caller, &[adder_procedure()]);
assert!(
inlined
.instructions
.iter()
.any(|inst| matches!(inst.operation, Operation::Call { .. }))
);
}
}