use super::*;
use crate::emit::{BudgetVars, ShadowRoots, flush_budget, reload_budget};
use cranelift_codegen::ir::FuncRef;
pub(super) fn is_tail_call(function: &Function, kind: BodyKind, index: usize) -> bool {
if !matches!(kind, BodyKind::Procedure { .. }) {
return false;
}
let mut cur_val = index;
let mut next_pc = index + 1;
loop {
if next_pc == function.instructions.len() {
return function.reply == cur_val;
}
match &function.instructions[next_pc].operation {
Operation::Else(values) if !values.is_empty() && values[0] == cur_val => {
let Some(endif) = find_matching_endif(function, next_pc) else {
return false;
};
let Operation::EndIf(ref else_values) = function.instructions[endif].operation
else {
return false;
};
cur_val = endif;
next_pc = endif + else_values.len();
}
Operation::EndIf(values) if !values.is_empty() && values[0] == cur_val => {
cur_val = next_pc;
next_pc += values.len();
}
_ => return false,
}
}
}
fn find_matching_endif(function: &Function, else_index: usize) -> Option<usize> {
let mut depth = 0usize;
for (idx, inst) in function
.instructions
.iter()
.enumerate()
.skip(else_index + 1)
{
match inst.operation {
Operation::If(_) => depth += 1,
Operation::EndIf(_) => {
if depth == 0 {
return Some(idx);
}
depth -= 1;
}
_ => {}
}
}
None
}
#[allow(clippy::too_many_arguments)]
pub(super) fn emit_tail_call(
builder: &mut FunctionBuilder<'_>,
context_ptr: Value,
budget: BudgetVars,
roots: Option<ShadowRoots>,
callee: FuncRef,
arguments: &[usize],
registers: &[Value],
) {
flush_budget(builder, context_ptr, budget);
super::frame::unlink_shadow_roots(builder, roots);
let args: Vec<Value> = arguments
.iter()
.map(|®ister| registers[register])
.collect();
builder.ins().return_call(callee, &args);
}
pub(super) fn emit_managed_call(
builder: &mut FunctionBuilder<'_>,
context_ptr: Value,
budget: BudgetVars,
callee: FuncRef,
arguments: &[usize],
registers: &[Value],
exit: Block,
) -> Value {
flush_budget(builder, context_ptr, budget);
let args: Vec<Value> = arguments
.iter()
.map(|®ister| registers[register])
.collect();
let call = builder.ins().call(callee, &args);
let results = builder.inst_results(call);
let status = results[0];
let value = results[1];
let success = builder.ins().icmp_imm(IntCC::Equal, status, 0);
let continuation = builder.create_block();
let failure = builder.create_block();
builder.set_cold_block(failure);
builder.ins().brif(success, continuation, &[], failure, &[]);
builder.switch_to_block(failure);
builder.ins().jump(exit, &[status]);
builder.switch_to_block(continuation);
reload_budget(builder, context_ptr, budget);
value
}
#[allow(clippy::too_many_arguments)]
pub(super) fn setup_procedure_entry(
builder: &mut FunctionBuilder<'_>,
function: &Function,
kind: BodyKind,
parameters: &mut Vec<Value>,
registers: &mut Vec<Value>,
published_roots: &mut Option<&[usize]>,
deferred_steps: &mut usize,
index: &mut usize,
) -> Option<(usize, Block)> {
let prefix_end = function
.instructions
.iter()
.take_while(|inst| {
matches!(
inst.operation,
Operation::Constant(_) | Operation::NullPid | Operation::Argument(_)
)
})
.count();
let all_ref_args_in_prefix =
function.instructions.iter().skip(prefix_end).all(|inst| {
!(matches!(inst.operation, Operation::Argument(_)) && inst.ty.is_reference())
});
let self_loop = match kind {
BodyKind::Procedure {
index: self_idx,
arity,
} if all_ref_args_in_prefix
&& function.instructions.iter().enumerate().any(|(idx, inst)| {
matches!(inst.operation, Operation::Call { function: callee, .. } if callee == self_idx)
&& is_tail_call(function, kind, idx)
}) =>
{
let header = builder.create_block();
for _ in 0..arity {
builder.append_block_param(header, types::I64);
}
builder.ins().jump(header, parameters);
builder.switch_to_block(header);
*parameters = builder.block_params(header).to_vec();
*published_roots = None;
Some((self_idx, header))
}
_ => None,
};
if matches!(kind, BodyKind::Procedure { .. }) && all_ref_args_in_prefix && prefix_end > 0 {
for inst in &function.instructions[..prefix_end] {
let val = match inst.operation {
Operation::Constant(v) => builder.ins().iconst(types::I64, v),
Operation::NullPid => builder.ins().iconst(types::I64, 0),
Operation::Argument(arg_idx) => parameters[arg_idx],
_ => unreachable!(),
};
registers.push(val);
}
*deferred_steps = prefix_end;
*index = prefix_end;
}
self_loop
}
#[allow(clippy::too_many_arguments)]
pub(super) fn emit_call_op(
builder: &mut FunctionBuilder<'_>,
pointer_type: types::Type,
context_ptr: Value,
budget: BudgetVars,
roots: Option<ShadowRoots>,
function: &Function,
callees: &[FuncRef],
callee_idx: usize,
arguments: &[usize],
registers: &[Value],
exit: Block,
tail_call: bool,
self_loop_header: Option<(usize, Block)>,
block_terminated: &mut bool,
) -> Value {
if tail_call {
let ref_arg_count = arguments
.iter()
.filter(|&&arg_reg| function.instructions[arg_reg].ty.is_reference())
.count();
if ref_arg_count >= 2 {
for &arg_reg in arguments {
if function.instructions[arg_reg].ty.is_reference() {
crate::emit_heap_reuse::emit_pin_shared_ref(
builder,
pointer_type,
context_ptr,
registers[arg_reg],
);
}
}
}
if let Some((self_idx, header)) = self_loop_header {
if callee_idx == self_idx {
let args: Vec<Value> = arguments.iter().map(|®| registers[reg]).collect();
builder.ins().jump(header, &args);
*block_terminated = true;
return context_ptr;
}
}
emit_tail_call(
builder,
context_ptr,
budget,
roots,
callees[callee_idx],
arguments,
registers,
);
*block_terminated = true;
context_ptr
} else {
for &arg_reg in arguments {
if function.instructions[arg_reg].ty.is_reference() {
crate::emit_heap_reuse::emit_pin_shared_ref(
builder,
pointer_type,
context_ptr,
registers[arg_reg],
);
}
}
emit_managed_call(
builder,
context_ptr,
budget,
callees[callee_idx],
arguments,
registers,
exit,
)
}
}