use crate::func_environ::{FuncEnvironment, GlobalVariable};
use crate::heap::Heap;
use crate::translator::code_translator::CatchClause;
use crate::{HashMap, Occupied, Vacant};
use cranelift_codegen::ir::{self, Block, Inst, Value};
use cranelift_frontend::FunctionBuilder;
use itertools::Itertools;
use std::vec::Vec;
use wasmer_types::{
CATCH_ALL_TAG_VALUE, FunctionIndex, GlobalIndex, MemoryIndex, SignatureIndex, WasmResult,
};
#[derive(Debug)]
pub enum ElseData {
NoElse {
branch_inst: Inst,
placeholder: Block,
},
WithElse {
else_block: Block,
},
}
#[derive(Debug)]
pub enum ControlStackFrame {
If {
destination: Block,
else_data: ElseData,
num_param_values: usize,
num_return_values: usize,
original_stack_size: usize,
exit_is_branched_to: bool,
blocktype: wasmer_compiler::wasmparser::BlockType,
head_is_reachable: bool,
consequent_ends_reachable: Option<bool>,
},
Block {
destination: Block,
num_param_values: usize,
num_return_values: usize,
original_stack_size: usize,
exit_is_branched_to: bool,
try_table_info: Option<(HandlerStateCheckpoint, Vec<Block>)>,
},
Loop {
destination: Block,
header: Block,
num_param_values: usize,
num_return_values: usize,
original_stack_size: usize,
},
}
impl ControlStackFrame {
pub fn num_return_values(&self) -> usize {
match *self {
Self::If {
num_return_values, ..
}
| Self::Block {
num_return_values, ..
}
| Self::Loop {
num_return_values, ..
} => num_return_values,
}
}
pub fn num_param_values(&self) -> usize {
match *self {
Self::If {
num_param_values, ..
}
| Self::Block {
num_param_values, ..
}
| Self::Loop {
num_param_values, ..
} => num_param_values,
}
}
pub fn following_code(&self) -> Block {
match *self {
Self::If { destination, .. }
| Self::Block { destination, .. }
| Self::Loop { destination, .. } => destination,
}
}
pub fn br_destination(&self) -> Block {
match *self {
Self::If { destination, .. } | Self::Block { destination, .. } => destination,
Self::Loop { header, .. } => header,
}
}
fn original_stack_size(&self) -> usize {
match *self {
Self::If {
original_stack_size,
..
}
| Self::Block {
original_stack_size,
..
}
| Self::Loop {
original_stack_size,
..
} => original_stack_size,
}
}
pub fn is_loop(&self) -> bool {
match *self {
Self::If { .. } | Self::Block { .. } => false,
Self::Loop { .. } => true,
}
}
pub fn exit_is_branched_to(&self) -> bool {
match *self {
Self::If {
exit_is_branched_to,
..
}
| Self::Block {
exit_is_branched_to,
..
} => exit_is_branched_to,
Self::Loop { .. } => false,
}
}
pub fn set_branched_to_exit(&mut self) {
match *self {
Self::If {
ref mut exit_is_branched_to,
..
}
| Self::Block {
ref mut exit_is_branched_to,
..
} => *exit_is_branched_to = true,
Self::Loop { .. } => {}
}
}
pub fn truncate_value_stack_to_else_params(&self, stack: &mut Vec<Value>) {
debug_assert!(matches!(self, &Self::If { .. }));
stack.truncate(self.original_stack_size());
}
pub fn truncate_value_stack_to_original_size(&self, stack: &mut Vec<Value>) {
let num_duplicated_params = match self {
&Self::If {
num_param_values, ..
} => {
debug_assert!(num_param_values <= self.original_stack_size());
num_param_values
}
_ => 0,
};
stack.truncate(self.original_stack_size() - num_duplicated_params);
}
pub fn restore_catch_handlers(
&self,
handlers: &mut HandlerState,
builder: &mut FunctionBuilder,
) {
if let Self::Block {
try_table_info: Some((checkpoint, catch_blocks)),
..
} = self
{
handlers.restore_checkpoint(*checkpoint);
for block in catch_blocks {
builder.seal_block(*block);
}
}
}
}
pub struct FuncTranslationState {
pub(crate) stack: Vec<Value>,
pub(crate) control_stack: Vec<ControlStackFrame>,
pub(crate) handlers: HandlerState,
pub(crate) reachable: bool,
globals: HashMap<GlobalIndex, GlobalVariable>,
heaps: HashMap<MemoryIndex, Heap>,
signatures: HashMap<SignatureIndex, (ir::SigRef, usize)>,
functions: HashMap<FunctionIndex, (ir::FuncRef, usize)>,
}
impl FuncTranslationState {
#[inline]
#[allow(dead_code)]
pub fn reachable(&self) -> bool {
self.reachable
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct HandlerStateCheckpoint(usize, usize);
#[derive(Default)]
pub(crate) struct HandlerState {
handlers: Vec<Block>,
clauses: Vec<CatchClause>,
}
#[derive(Debug)]
pub(crate) struct LandingPad {
pub(crate) block: Block,
pub(crate) clauses: Vec<CatchClause>,
}
impl HandlerState {
pub fn add_handler(&mut self, block: Block) {
self.handlers.push(block);
}
pub fn add_clause(&mut self, clause: CatchClause) {
self.clauses.push(clause);
}
pub fn take_checkpoint(&self) -> HandlerStateCheckpoint {
HandlerStateCheckpoint(self.handlers.len(), self.clauses.len())
}
pub fn restore_checkpoint(&mut self, checkpoint: HandlerStateCheckpoint) {
debug_assert!(checkpoint.0 <= self.handlers.len());
debug_assert!(checkpoint.1 <= self.clauses.len());
self.handlers.truncate(checkpoint.0);
self.clauses.truncate(checkpoint.1);
}
pub fn landing_pad(&self) -> Option<LandingPad> {
self.handlers.last().copied().map(|block| LandingPad {
block,
clauses: self.unique_clauses(),
})
}
pub fn unique_clauses(&self) -> Vec<CatchClause> {
self.clauses
.iter()
.rev()
.unique_by(|c| c.tag_value)
.take_while_inclusive(|c| c.tag_value != CATCH_ALL_TAG_VALUE)
.cloned()
.collect()
}
pub fn is_empty(&self) -> bool {
self.handlers.is_empty()
}
pub fn clear(&mut self) {
self.handlers.clear();
self.clauses.clear();
}
}
impl FuncTranslationState {
pub(crate) fn new() -> Self {
Self {
stack: Vec::new(),
control_stack: Vec::new(),
handlers: HandlerState::default(),
reachable: true,
globals: HashMap::new(),
heaps: HashMap::new(),
signatures: HashMap::new(),
functions: HashMap::new(),
}
}
fn clear(&mut self) {
debug_assert!(self.stack.is_empty());
debug_assert!(self.control_stack.is_empty());
debug_assert!(self.handlers.is_empty());
self.reachable = true;
self.handlers.clear();
self.globals.clear();
self.heaps.clear();
self.signatures.clear();
self.functions.clear();
}
pub(crate) fn initialize(
&mut self,
_sig: &ir::Signature,
exit_block: Block,
result_count: usize,
) {
self.clear();
self.push_block(exit_block, 0, result_count);
}
pub(crate) fn push1(&mut self, val: Value) {
self.stack.push(val);
}
pub(crate) fn pushn(&mut self, vals: &[Value]) {
self.stack.extend_from_slice(vals);
}
pub(crate) fn pop1(&mut self) -> Value {
self.stack
.pop()
.expect("attempted to pop a value from an empty stack")
}
pub(crate) fn peek1(&self) -> Value {
*self
.stack
.last()
.expect("attempted to peek at a value on an empty stack")
}
pub(crate) fn pop2(&mut self) -> (Value, Value) {
let v2 = self.pop1();
let v1 = self.pop1();
(v1, v2)
}
pub(crate) fn pop3(&mut self) -> (Value, Value, Value) {
let v3 = self.pop1();
let v2 = self.pop1();
let v1 = self.pop1();
(v1, v2, v3)
}
#[inline]
fn ensure_length_is_at_least(&self, n: usize) {
debug_assert!(
n <= self.stack.len(),
"attempted to access {} values but stack only has {} values",
n,
self.stack.len()
);
}
pub(crate) fn popn(&mut self, n: usize) {
self.ensure_length_is_at_least(n);
let new_len = self.stack.len() - n;
self.stack.truncate(new_len);
}
pub(crate) fn peekn(&self, n: usize) -> &[Value] {
self.ensure_length_is_at_least(n);
&self.stack[self.stack.len() - n..]
}
pub(crate) fn peekn_mut(&mut self, n: usize) -> &mut [Value] {
self.ensure_length_is_at_least(n);
let len = self.stack.len();
&mut self.stack[len - n..]
}
fn push_block_impl(
&mut self,
following_code: Block,
num_param_types: usize,
num_result_types: usize,
try_table_info: Option<(HandlerStateCheckpoint, Vec<Block>)>,
) {
debug_assert!(num_param_types <= self.stack.len());
self.control_stack.push(ControlStackFrame::Block {
destination: following_code,
original_stack_size: self.stack.len() - num_param_types,
num_param_values: num_param_types,
num_return_values: num_result_types,
exit_is_branched_to: false,
try_table_info,
});
}
pub(crate) fn push_block(
&mut self,
following_code: Block,
num_param_types: usize,
num_result_types: usize,
) {
self.push_block_impl(following_code, num_param_types, num_result_types, None);
}
pub(crate) fn push_try_table_block(
&mut self,
following_code: Block,
catch_blocks: Vec<Block>,
num_param_types: usize,
num_result_types: usize,
checkpoint: HandlerStateCheckpoint,
) {
self.push_block_impl(
following_code,
num_param_types,
num_result_types,
Some((checkpoint, catch_blocks)),
);
}
pub(crate) fn push_loop(
&mut self,
header: Block,
following_code: Block,
num_param_types: usize,
num_result_types: usize,
) {
debug_assert!(num_param_types <= self.stack.len());
self.control_stack.push(ControlStackFrame::Loop {
header,
destination: following_code,
original_stack_size: self.stack.len() - num_param_types,
num_param_values: num_param_types,
num_return_values: num_result_types,
});
}
pub(crate) fn push_if(
&mut self,
destination: Block,
else_data: ElseData,
num_param_types: usize,
num_result_types: usize,
blocktype: wasmer_compiler::wasmparser::BlockType,
) {
debug_assert!(num_param_types <= self.stack.len());
self.stack.reserve(num_param_types);
for i in (self.stack.len() - num_param_types)..self.stack.len() {
let val = self.stack[i];
self.stack.push(val);
}
self.control_stack.push(ControlStackFrame::If {
destination,
else_data,
original_stack_size: self.stack.len() - num_param_types,
num_param_values: num_param_types,
num_return_values: num_result_types,
exit_is_branched_to: false,
head_is_reachable: self.reachable,
consequent_ends_reachable: None,
blocktype,
});
}
}
impl FuncTranslationState {
pub(crate) fn get_global(
&mut self,
func: &mut ir::Function,
index: u32,
environ: &mut FuncEnvironment<'_>,
) -> WasmResult<GlobalVariable> {
let index = GlobalIndex::from_u32(index);
match self.globals.entry(index) {
Occupied(entry) => Ok(*entry.get()),
Vacant(entry) => Ok(*entry.insert(environ.make_global(func, index)?)),
}
}
pub(crate) fn get_heap(
&mut self,
func: &mut ir::Function,
index: u32,
environ: &mut FuncEnvironment<'_>,
) -> WasmResult<Heap> {
let index = MemoryIndex::from_u32(index);
match self.heaps.entry(index) {
Occupied(entry) => Ok(*entry.get()),
Vacant(entry) => Ok(*entry.insert(environ.make_heap(func, index)?)),
}
}
pub(crate) fn get_indirect_sig(
&mut self,
func: &mut ir::Function,
index: u32,
environ: &mut FuncEnvironment<'_>,
) -> WasmResult<(ir::SigRef, usize)> {
let index = SignatureIndex::from_u32(index);
match self.signatures.entry(index) {
Occupied(entry) => Ok(*entry.get()),
Vacant(entry) => {
let sig = environ.make_indirect_sig(func, index)?;
Ok(*entry.insert((sig, num_wasm_parameters(environ, &func.dfg.signatures[sig]))))
}
}
}
pub(crate) fn get_direct_func(
&mut self,
func: &mut ir::Function,
index: u32,
environ: &mut FuncEnvironment<'_>,
) -> WasmResult<(ir::FuncRef, usize)> {
let index = FunctionIndex::from_u32(index);
match self.functions.entry(index) {
Occupied(entry) => Ok(*entry.get()),
Vacant(entry) => {
let fref = environ.make_direct_func(func, index)?;
let sig = func.dfg.ext_funcs[fref].signature;
Ok(*entry.insert((
fref,
num_wasm_parameters(environ, &func.dfg.signatures[sig]),
)))
}
}
}
}
fn num_wasm_parameters(environ: &FuncEnvironment<'_>, signature: &ir::Signature) -> usize {
(0..signature.params.len())
.filter(|index| environ.is_wasm_parameter(signature, *index))
.count()
}