code
stringlengths
40
729k
docstring
stringlengths
22
46.3k
func_name
stringlengths
1
97
language
stringclasses
1 value
repo
stringlengths
6
48
path
stringlengths
8
176
url
stringlengths
47
228
license
stringclasses
7 values
pub fn is_else_reachable(&self) -> bool { match self.reachability { IfReachability::Both { .. } | IfReachability::OnlyElse => true, IfReachability::OnlyThen => false, } }
Returns `true` if the `else` branch is reachable. # Note The `else` branch is unreachable if the `if` condition is a constant `true` value.
is_else_reachable
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_frame.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_frame.rs
Apache-2.0
pub fn update_end_of_then_reachability(&mut self, reachable: bool) { assert!(self.end_of_then_is_reachable.is_none()); self.end_of_then_is_reachable = Some(reachable); }
Updates the reachability of the end of the `then` branch. # Note This is expected to be called when visiting the `else` of an `if` control frame to inform the `if` control frame if the end of the `then` block is reachable. This information is important to decide whether code coming after the entire `if` control frame is reachable again. # Panics If this information has already been provided prior.
update_end_of_then_reachability
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_frame.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_frame.rs
Apache-2.0
pub fn visited_else(&mut self) { self.visited_else = true; }
Informs the [`IfControlFrame`] that the `else` block has been visited.
visited_else
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_frame.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_frame.rs
Apache-2.0
pub fn update_consume_fuel_instr(&mut self, instr: Instr) { assert!( self.consume_fuel.is_some(), "can only update the consume fuel instruction if it existed before" ); self.consume_fuel = Some(instr); }
Updates the [`ConsumeFuel`] instruction for when the `else` block is entered. # Note This is required since the `consume_fuel` field represents the [`ConsumeFuel`] instruction for both `then` and `else` blocks. This is possible because only one of them is needed at the same time during translation. # Panics If the `consume_fuel` field was not already `Some`. [`ConsumeFuel`]: enum.Instruction.html#variant.ConsumeFuel
update_consume_fuel_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_frame.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_frame.rs
Apache-2.0
pub fn branch_destination(&self) -> LabelRef { match self { Self::Block(frame) => frame.branch_destination(), Self::Loop(frame) => frame.branch_destination(), Self::If(frame) => frame.branch_destination(), Self::Unreachable(frame) => panic!( "tried to call `branch_destination` for an unreachable control frame: {frame:?}" ), } }
Returns the label for the branch destination of the [`ControlFrame`].
branch_destination
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_frame.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_frame.rs
Apache-2.0
pub fn branch_to(&mut self) { match self { ControlFrame::Block(frame) => frame.branch_to(), ControlFrame::Loop(frame) => frame.branch_to(), ControlFrame::If(frame) => frame.branch_to(), Self::Unreachable(frame) => { panic!("tried to `bump_branches` on an unreachable control frame: {frame:?}") } } }
Makes the [`ControlFrame`] aware that there is a branch to it.
branch_to
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_frame.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_frame.rs
Apache-2.0
pub fn control_frame(&'a mut self) -> &'a mut ControlFrame { match self { Self::Return(frame) => frame, Self::Branch(frame) => frame, } }
Returns an exclusive reference to the [`ControlFrame`] of the [`AcquiredTarget`].
control_frame
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn reset(&mut self) { self.frames.clear(); self.else_providers.reset(); }
Resets the [`ControlStack`] to allow for reuse.
reset
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn is_root(&self, relative_depth: u32) -> bool { debug_assert!(!self.is_empty()); relative_depth as usize == self.len() - 1 }
Returns `true` if `relative_depth` points to the first control flow frame.
is_root
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn is_empty(&self) -> bool { self.frames.len() == 0 }
Returns `true` if the [`ControlStack`] is empty.
is_empty
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn push_frame<T>(&mut self, frame: T) where T: Into<ControlFrame>, { self.frames.push(frame.into()) }
Pushes a new control flow frame to the [`ControlStack`].
push_frame
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn pop_frame(&mut self) -> ControlFrame { self.frames .pop() .expect("tried to pop control flow frame from empty control flow stack") }
Pops the last control flow frame from the [`ControlStack`]. # Panics If the [`ControlStack`] is empty.
pop_frame
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn push_else_providers<I>(&mut self, providers: I) -> Result<(), Error> where I: IntoIterator<Item = Provider<TypedVal>>, { self.else_providers.push(providers)?; Ok(()) }
Push a [`Provider`] slice for the `else` branch of an [`IfControlFrame`] to the [`ControlStack`]. [`IfControlFrame`]: super::control_frame::IfControlFrame
push_else_providers
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn pop_else_providers(&mut self) -> Drain<Provider<TypedVal>> { self.else_providers .pop() .expect("missing else providers for `else` branch") }
Pops the top-most [`Provider`] slice of an `else` branch of an [`IfControlFrame`] to the [`ControlStack`]. [`IfControlFrame`]: super::control_frame::IfControlFrame
pop_else_providers
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn last(&self) -> &ControlFrame { self.frames.last().expect( "tried to exclusively peek the last control flow \ frame from an empty control flow stack", ) }
Returns the last control flow frame on the control stack.
last
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn nth_back_mut(&mut self, depth: u32) -> &mut ControlFrame { let len = self.len(); self.frames .iter_mut() .nth_back(depth as usize) .unwrap_or_else(|| { panic!( "tried to peek the {depth}-th control flow frame \ but there are only {len} control flow frames", ) }) }
Returns a shared reference to the control flow frame at the given `depth`. A `depth` of 0 is equal to calling [`ControlStack::last`]. # Panics If `depth` exceeds the length of the stack of control flow frames.
nth_back_mut
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
pub fn acquire_target(&mut self, depth: u32) -> AcquiredTarget { let is_root = self.is_root(depth); let frame = self.nth_back_mut(depth); if is_root { AcquiredTarget::Return(frame) } else { AcquiredTarget::Branch(frame) } }
Acquires the target [`ControlFrame`] at the given relative `depth`.
acquire_target
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/control_stack.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/control_stack.rs
Apache-2.0
fn push(&mut self, instruction: Instruction) -> Result<Instr, Error> { let instr = self.next_instr(); self.instrs.push(instruction); Ok(instr) }
Pushes an [`Instruction`] to the instruction sequence and returns its [`Instr`]. # Errors If there are too many instructions in the instruction sequence.
push
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
fn push_before(&mut self, instr: Instr, instruction: Instruction) -> Result<Instr, Error> { self.instrs.insert(instr.into_usize(), instruction); let shifted_instr = u32::from(instr) .checked_add(1) .map(Instr::from) .unwrap_or_else(|| panic!("pushed to many instructions to a single function")); Ok(shifted_instr) }
Pushes an [`Instruction`] before the [`Instruction`] at [`Instr`]. Returns the [`Instr`] of the [`Instruction`] that was at [`Instr`] before this operation. # Note - This operation might be costly. Callers are advised to only insert instructions near the end of the sequence in order to avoid massive copy overhead since all following instructions are required to be shifted in memory. - The `instr` will refer to the inserted [`Instruction`] after this operation. # Errors If there are too many instructions in the instruction sequence.
push_before
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
fn get_mut(&mut self, instr: Instr) -> &mut Instruction { &mut self.instrs[instr.into_usize()] }
Returns the [`Instruction`] associated to the [`Instr`] for this [`InstrSequence`]. # Panics If no [`Instruction`] is associated to the [`Instr`] for this [`InstrSequence`].
get_mut
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn get_slice_at_mut(&mut self, start: Instr) -> &mut [Instruction] { &mut self.instrs[start.into_usize()..] }
Returns a slice to the sequence of [`Instruction`] starting at `start`. # Panics If `start` is out of bounds for [`InstrSequence`].
get_slice_at_mut
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn reset_last_instr(&mut self) { self.last_instr = None; }
Resets the [`Instr`] last created via [`InstrEncoder::push_instr`]. # Note The `last_instr` information is used for an optimization with `local.set` and `local.tee` translation to replace the result [`Reg`] of the last created [`Instruction`] instead of creating another copy [`Instruction`]. Whenever ending a control block during Wasm translation the `last_instr` information needs to be reset so that a `local.set` or `local.tee` does not invalidly optimize across control flow boundaries.
reset_last_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn pin_label_if_unpinned(&mut self, label: LabelRef) { self.labels.try_pin_label(label, self.instrs.next_instr()) }
Resolve the label at the current instruction position. Does nothing if the label has already been resolved. # Note This is used at a position of the Wasm bytecode where it is clear that the given label can be resolved properly. This usually takes place when encountering the Wasm `End` operand for example.
pin_label_if_unpinned
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn pin_label(&mut self, label: LabelRef) { self.labels .pin_label(label, self.instrs.next_instr()) .unwrap_or_else(|err| panic!("failed to pin label: {err}")); }
Resolve the label at the current instruction position. # Note This is used at a position of the Wasm bytecode where it is clear that the given label can be resolved properly. This usually takes place when encountering the Wasm `End` operand for example. # Panics If the label has already been resolved.
pin_label
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn try_resolve_label(&mut self, label: LabelRef) -> Result<BranchOffset, Error> { let user = self.instrs.next_instr(); self.try_resolve_label_for(label, user) }
Try resolving the [`LabelRef`] for the currently constructed instruction. Returns an uninitialized [`BranchOffset`] if the `label` cannot yet be resolved and defers resolution to later.
try_resolve_label
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn try_resolve_label_for( &mut self, label: LabelRef, instr: Instr, ) -> Result<BranchOffset, Error> { self.labels.try_resolve_label(label, instr) }
Try resolving the [`LabelRef`] for the given [`Instr`]. Returns an uninitialized [`BranchOffset`] if the `label` cannot yet be resolved and defers resolution to later. # Errors If the [`BranchOffset`] cannot be encoded in 32 bits.
try_resolve_label_for
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn update_branch_offsets(&mut self, stack: &mut ValueStack) -> Result<(), Error> { for (user, offset) in self.labels.resolved_users() { self.instrs .get_mut(user) .update_branch_offset(stack, offset?)?; } Ok(()) }
Updates the branch offsets of all branch instructions inplace. # Panics If this is used before all branching labels have been pinned.
update_branch_offsets
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
fn push_instr(&mut self, instr: Instruction) -> Result<Instr, Error> { debug_assert!(!instr.is_instruction_parameter(), "parameter: {instr:?}"); let last_instr = self.instrs.push(instr)?; self.last_instr = Some(last_instr); Ok(last_instr) }
Push the [`Instruction`] to the [`InstrEncoder`].
push_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn push_fuel_instr( &mut self, fuel_costs: Option<&FuelCostsProvider>, ) -> Result<Option<Instr>, Error> { let Some(fuel_costs) = fuel_costs else { // Fuel metering is disabled so there is no need to create an `Instruction::ConsumeFuel`. return Ok(None); }; let base = u32::try_from(fuel_costs.base()) .expect("base fuel must be valid for creating `Instruction::ConsumeFuel`"); let fuel_instr = Instruction::consume_fuel(base); let instr = self.push_instr(fuel_instr)?; Ok(Some(instr)) }
Pushes a [`Instruction::ConsumeFuel`] with base costs if fuel metering is enabled. Returns `None` if fuel metering is disabled.
push_fuel_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn push_fueled_instr<F>( &mut self, instr: Instruction, fuel_info: &FuelInfo, f: F, ) -> Result<Instr, Error> where F: FnOnce(&FuelCostsProvider) -> u64, { self.bump_fuel_consumption(fuel_info, f)?; self.push_instr(instr) }
Utility function for pushing a new [`Instruction`] with fuel costs. # Note Fuel metering is only encoded or adjusted if it is enabled.
push_fueled_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn append_instr(&mut self, instr: Instruction) -> Result<Instr, Error> { debug_assert!( instr.is_instruction_parameter() // Note: `br_table` may have `Instruction::Branch` as parameter. || matches!(instr, Instruction::Branch { .. }), "non-parameter: {instr:?}" ); self.instrs.push(instr) }
Appends the [`Instruction`] to the last [`Instruction`] created via [`InstrEncoder::push_instr`]. # Note This is used primarily for [`Instruction`] words that are just carrying parameters for the [`Instruction`]. An example of this is [`Instruction::RegisterAndImm32`] carrying the `ptr` and `offset` parameters for [`Instruction::Load32`].
append_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
fn merge_copy_instrs(&mut self, result: Reg, value: TypedProvider) -> Option<Instr> { let TypedProvider::Register(mut value) = value else { // Case: cannot merge copies with immediate values at the moment. // // Note: we could implement this but it would require us to allocate // function local constants which we want to avoid generally. return None; }; let Some(last_instr) = self.last_instr else { // There is no last instruction, e.g. when ending a `block`. return None; }; let Instruction::Copy { result: last_result, value: last_value, } = *self.instrs.get(last_instr) else { // Case: last instruction was not a copy instruction, so we cannot merge anything. return None; }; if !(result == last_result.next() || result == last_result.prev()) { // Case: cannot merge copy instructions as `copy2` since result registers are not contiguous. return None; } // Propagate values according to the order of the merged copies. if value == last_result { value = last_value; } let (merged_result, value0, value1) = if last_result < result { (last_result, last_value, value) } else { (result, value, last_value) }; let merged_copy = Instruction::copy2_ext(RegSpan::new(merged_result), value0, value1); *self.instrs.get_mut(last_instr) = merged_copy; Some(last_instr) }
Tries to merge `copy(result, value)` if the last instruction is a matching copy instruction. - Returns `None` if merging of the copy instruction was not possible. - Returns the `Instr` of the merged `copy2` instruction if merging was successful.
merge_copy_instrs
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn encode_copy( &mut self, stack: &mut ValueStack, result: Reg, value: TypedProvider, fuel_info: &FuelInfo, ) -> Result<Option<Instr>, Error> { /// Convenience to create an [`Instruction::Copy`] to copy a constant value. fn copy_imm( stack: &mut ValueStack, result: Reg, value: impl Into<UntypedVal>, ) -> Result<Instruction, Error> { let cref = stack.alloc_const(value.into())?; Ok(Instruction::copy(result, cref)) } if let Some(merged_instr) = self.merge_copy_instrs(result, value) { return Ok(Some(merged_instr)); } let instr = match value { TypedProvider::Register(value) => { if result == value { // Optimization: copying from register `x` into `x` is a no-op. return Ok(None); } Instruction::copy(result, value) } TypedProvider::Const(value) => match value.ty() { ValType::I32 => Instruction::copy_imm32(result, i32::from(value)), ValType::F32 => Instruction::copy_imm32(result, f32::from(value)), ValType::I64 => match <Const32<i64>>::try_from(i64::from(value)).ok() { Some(value) => Instruction::copy_i64imm32(result, value), None => copy_imm(stack, result, value)?, }, ValType::F64 => match <Const32<f64>>::try_from(f64::from(value)).ok() { Some(value) => Instruction::copy_f64imm32(result, value), None => copy_imm(stack, result, value)?, }, ValType::V128 | ValType::FuncRef | ValType::ExternRef => { copy_imm(stack, result, value)? } }, }; self.bump_fuel_consumption(fuel_info, FuelCostsProvider::base)?; let instr = self.push_instr(instr)?; Ok(Some(instr)) }
Encode a `copy result <- value` instruction. # Note Applies optimizations for `copy x <- x` and properly selects the most optimized `copy` instruction variant for the given `value`.
encode_copy
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
fn copy_imm( stack: &mut ValueStack, result: Reg, value: impl Into<UntypedVal>, ) -> Result<Instruction, Error> { let cref = stack.alloc_const(value.into())?; Ok(Instruction::copy(result, cref)) }
Convenience to create an [`Instruction::Copy`] to copy a constant value.
copy_imm
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn encode_copies( &mut self, stack: &mut ValueStack, mut results: BoundedRegSpan, values: &[TypedProvider], fuel_info: &FuelInfo, ) -> Result<Option<Instr>, Error> { assert_eq!(usize::from(results.len()), values.len()); let result = results.span().head(); if let Some((TypedProvider::Register(value), rest)) = values.split_first() { if result == *value { // Case: `result` and `value` are equal thus this is a no-op copy which we can avoid. // Applied recursively we thereby remove all no-op copies at the start of the // copy sequence until the first actual copy. results = BoundedRegSpan::new(RegSpan::new(result.next()), results.len() - 1); return self.encode_copies(stack, results, rest, fuel_info); } } match values { [] => { // The copy sequence is empty, nothing to encode in this case. Ok(None) } [v0] => self.encode_copy(stack, result, *v0, fuel_info), [v0, v1] => { if TypedProvider::Register(result.next()) == *v1 { // Case: the second of the 2 copies is a no-op which we can avoid // Note: we already asserted that the first copy is not a no-op return self.encode_copy(stack, result, *v0, fuel_info); } let reg0 = stack.provider2reg(v0)?; let reg1 = stack.provider2reg(v1)?; self.bump_fuel_consumption(fuel_info, FuelCostsProvider::base)?; let instr = self.push_instr(Instruction::copy2_ext(results.span(), reg0, reg1))?; Ok(Some(instr)) } [v0, v1, rest @ ..] => { debug_assert!(!rest.is_empty()); // Note: The fuel for copies might result in 0 charges if there aren't // enough copies to account for at least 1 fuel. Therefore we need // to also bump by `FuelCosts::base` to charge at least 1 fuel. self.bump_fuel_consumption(fuel_info, FuelCostsProvider::base)?; self.bump_fuel_consumption(fuel_info, |costs| { costs.fuel_for_copying_values(rest.len() as u64 + 3) })?; if let Some(values) = BoundedRegSpan::from_providers(values) { let make_instr = match Self::has_overlapping_copy_spans( results.span(), values.span(), values.len(), ) { true => Instruction::copy_span, false => Instruction::copy_span_non_overlapping, }; let instr = self.push_instr(make_instr(results.span(), values.span(), values.len()))?; return Ok(Some(instr)); } let make_instr = match Self::has_overlapping_copies(results, values) { true => Instruction::copy_many_ext, false => Instruction::copy_many_non_overlapping_ext, }; let reg0 = stack.provider2reg(v0)?; let reg1 = stack.provider2reg(v1)?; let instr = self.push_instr(make_instr(results.span(), reg0, reg1))?; self.encode_register_list(stack, rest)?; Ok(Some(instr)) } } }
Encode a generic `copy` instruction. # Note Avoids no-op copies such as `copy x <- x` and properly selects the most optimized `copy` instruction variant for the given `value`.
encode_copies
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn has_overlapping_copy_spans(results: RegSpan, values: RegSpan, len: u16) -> bool { RegSpan::has_overlapping_copies(results, values, len) }
Returns `true` if `copy_span results <- values` has overlapping copies. # Examples - `[ ]`: empty never overlaps - `[ 1 <- 0 ]`: single element never overlaps - `[ 0 <- 1, 1 <- 2, 2 <- 3 ]``: no overlap - `[ 1 <- 0, 2 <- 1 ]`: overlaps!
has_overlapping_copy_spans
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn has_overlapping_copies(results: BoundedRegSpan, values: &[TypedProvider]) -> bool { debug_assert_eq!(usize::from(results.len()), values.len()); if results.is_empty() { // Note: An empty set of copies can never have overlapping copies. return false; } let result0 = results.span().head(); for (result, value) in results.iter().zip(values) { // Note: We only have to check the register case since constant value // copies can never overlap. if let TypedProvider::Register(value) = *value { // If the register `value` index is within range of `result0..result` // then its value has been overwritten by previous copies. if result0 <= value && value < result { return true; } } } false }
Returns `true` if the `copy results <- values` instruction has overlaps. # Examples - The sequence `[ 0 <- 1, 1 <- 1, 2 <- 4 ]` has no overlapping copies. - The sequence `[ 0 <- 1, 1 <- 0 ]` has overlapping copies since register `0` is written to in the first copy but read from in the next. - The sequence `[ 3 <- 1, 4 <- 2, 5 <- 3 ]` has overlapping copies since register `3` is written to in the first copy but read from in the third.
has_overlapping_copies
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn bump_fuel_consumption<F>(&mut self, fuel_info: &FuelInfo, f: F) -> Result<(), Error> where F: FnOnce(&FuelCostsProvider) -> u64, { let FuelInfo::Some { costs, instr } = fuel_info else { // Fuel metering is disabled so we can bail out. return Ok(()); }; let fuel_consumed = f(costs); self.instrs .get_mut(*instr) .bump_fuel_consumption(fuel_consumed)?; Ok(()) }
Bumps consumed fuel for [`Instruction::ConsumeFuel`] of `instr` by `delta`. # Errors If consumed fuel is out of bounds after this operation.
bump_fuel_consumption
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn encode_register_list( &mut self, stack: &mut ValueStack, inputs: &[TypedProvider], ) -> Result<(), Error> { let mut remaining = inputs; let instr = loop { match remaining { [] => return Ok(()), [v0] => break Instruction::register(stack.provider2reg(v0)?), [v0, v1] => { break Instruction::register2_ext( stack.provider2reg(v0)?, stack.provider2reg(v1)?, ) } [v0, v1, v2] => { break Instruction::register3_ext( stack.provider2reg(v0)?, stack.provider2reg(v1)?, stack.provider2reg(v2)?, ); } [v0, v1, v2, rest @ ..] => { self.instrs.push(Instruction::register_list_ext( stack.provider2reg(v0)?, stack.provider2reg(v1)?, stack.provider2reg(v2)?, ))?; remaining = rest; } }; }; self.instrs.push(instr)?; Ok(()) }
Encode the given slice of [`TypedProvider`] as a list of [`Reg`]. # Note This is used for the following n-ary instructions: - [`Instruction::ReturnMany`] - [`Instruction::CopyMany`] - [`Instruction::CallInternal`] - [`Instruction::CallImported`] - [`Instruction::CallIndirect`] - [`Instruction::ReturnCallInternal`] - [`Instruction::ReturnCallImported`] - [`Instruction::ReturnCallIndirect`]
encode_register_list
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn encode_local_set( &mut self, stack: &mut ValueStack, res: &ModuleHeader, local: Reg, value: TypedProvider, preserved: Option<Reg>, fuel_info: FuelInfo, ) -> Result<(), Error> { fn fallback_case( this: &mut InstrEncoder, stack: &mut ValueStack, local: Reg, value: TypedProvider, preserved: Option<Reg>, fuel_info: FuelInfo, ) -> Result<(), Error> { if let Some(preserved) = preserved { this.bump_fuel_consumption(&fuel_info, FuelCostsProvider::base)?; let preserve_instr = this.push_instr(Instruction::copy(preserved, local))?; this.notify_preserved_register(preserve_instr); } this.encode_copy(stack, local, value, &fuel_info)?; Ok(()) } debug_assert!(matches!( stack.get_register_space(local), RegisterSpace::Local )); let TypedProvider::Register(returned_value) = value else { // Cannot apply the optimization for `local.set C` where `C` is a constant value. return fallback_case(self, stack, local, value, preserved, fuel_info); }; if matches!( stack.get_register_space(returned_value), RegisterSpace::Local | RegisterSpace::Preserve ) { // Can only apply the optimization if the returned value of `last_instr` // is _NOT_ itself a local register due to observable behavior or already preserved. return fallback_case(self, stack, local, value, preserved, fuel_info); } let Some(last_instr) = self.last_instr else { // Can only apply the optimization if there is a previous instruction // to replace its result register instead of emitting a copy. return fallback_case(self, stack, local, value, preserved, fuel_info); }; if preserved.is_some() && last_instr.distance(self.instrs.next_instr()) >= 4 { // We avoid applying the optimization if the last instruction // has a very large encoding, e.g. for function calls with lots // of parameters. This is because the optimization while also // preserving a local register requires costly shifting all // instruction words of the last instruction. // Thankfully most instructions are small enough. return fallback_case(self, stack, local, value, preserved, fuel_info); } if let Some(preserved) = preserved { let mut last_instr_uses_preserved = false; for instr in self.instrs.get_slice_at_mut(last_instr).iter_mut() { instr.visit_input_registers(|input| { if *input == preserved { last_instr_uses_preserved = true; } }); } if last_instr_uses_preserved { // Note: we cannot apply the local.set preservation optimization since this would // siltently overwrite inputs of the last encoded instruction. return fallback_case(self, stack, local, value, Some(preserved), fuel_info); } } if !self .instrs .get_mut(last_instr) .relink_result(res, local, returned_value)? { // It was not possible to relink the result of `last_instr` therefore we fallback. return fallback_case(self, stack, local, value, preserved, fuel_info); } if let Some(preserved) = preserved { // We were able to apply the optimization. // Preservation requires the copy to be before the optimized last instruction. // Therefore we need to push the preservation `copy` instruction before it. self.bump_fuel_consumption(&fuel_info, FuelCostsProvider::base)?; let shifted_last_instr = self .instrs .push_before(last_instr, Instruction::copy(preserved, local))?; self.notify_preserved_register(last_instr); self.last_instr = Some(shifted_last_instr); } Ok(()) }
Encode a `local.set` or `local.tee` instruction. This also applies an optimization in that the previous instruction result is replaced with the `local` [`Reg`] instead of encoding another `copy` instruction if the `local.set` or `local.tee` belongs to the same basic block. # Note - If `value` is a [`Reg`] it usually is equal to the result [`Reg`] of the previous instruction.
encode_local_set
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn notify_preserved_register(&mut self, preserve_instr: Instr) { { let preserved = self.instrs.get(preserve_instr); debug_assert!( matches!( preserved, Instruction::Copy { .. } | Instruction::Copy2 { .. } | Instruction::CopySpanNonOverlapping { .. } | Instruction::CopyManyNonOverlapping { .. } ), "a preserve instruction is always a register copy instruction but found: {preserved:?}", ); } if self.notified_preservation.is_none() { self.notified_preservation = Some(preserve_instr); } }
Notifies the [`InstrEncoder`] that a local variable has been preserved. # Note This is an optimization that we perform to avoid or minimize the work done in [`InstrEncoder::defrag_registers`] by either avoiding defragmentation entirely if no local preservations took place or by at least only defragmenting the slice of instructions that could have been affected by it but not all encoded instructions. Only instructions that are encoded after the preservation could have been affected. This will ignore any preservation notifications after the first one.
notify_preserved_register
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn defrag_registers(&mut self, stack: &mut ValueStack) -> Result<(), Error> { stack.finalize_alloc(); if let Some(notified_preserved) = self.notified_preservation { for instr in self.instrs.get_slice_at_mut(notified_preserved) { instr.visit_input_registers(|reg| *reg = stack.defrag_register(*reg)); } } Ok(()) }
Defragments storage-space registers of all encoded [`Instruction`].
defrag_registers
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn fuse_eqz<T: WasmInteger>( &mut self, stack: &mut ValueStack, lhs: Reg, rhs: T, ) -> Result<bool, Error> { if !rhs.eq_zero() { // Case: `rhs` needs to be zero to apply this optimization. return Ok(false); } let Some(last_instr) = self.last_instr else { // If there is no last instruction there is no comparison instruction to negate. return Ok(false); }; let last_instruction = *self.instrs.get(last_instr); let Some(result) = last_instruction.result() else { // All negatable instructions have a single result register. return Ok(false); }; if matches!(stack.get_register_space(result), RegisterSpace::Local) { // The instruction stores its result into a local variable which // is an observable side effect which we are not allowed to mutate. return Ok(false); } if result != lhs { // The result of the instruction and the `lhs` are not equal // thus indicating that we cannot fuse the instructions. return Ok(false); } let Some(negated) = last_instruction.negate_cmp_instr() else { // Last instruction is unable to be negated. return Ok(false); }; _ = mem::replace(self.instrs.get_mut(last_instr), negated); stack.push_register(result)?; Ok(true) }
Tries to fuse a Wasm `i32.eqz` (or `i32.eq` with 0 `rhs` value) instruction. Returns - `Ok(true)` if the intruction fusion was successful. - `Ok(false)` if instruction fusion could not be applied. - `Err(_)` if an error occurred.
fuse_eqz
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn fuse_nez<T: WasmInteger>( &mut self, stack: &mut ValueStack, lhs: Reg, rhs: T, ) -> Result<bool, Error> { if !rhs.eq_zero() { // Case: `rhs` needs to be zero to apply this optimization. return Ok(false); } let Some(last_instr) = self.last_instr else { // If there is no last instruction there is no comparison instruction to negate. return Ok(false); }; let last_instruction = *self.instrs.get(last_instr); let Some(result) = last_instruction.result() else { // All negatable instructions have a single result register. return Ok(false); }; if matches!(stack.get_register_space(result), RegisterSpace::Local) { // The instruction stores its result into a local variable which // is an observable side effect which we are not allowed to mutate. return Ok(false); } if result != lhs { // The result of the instruction and the `lhs` are not equal // thus indicating that we cannot fuse the instructions. return Ok(false); } let Some(logicalized) = last_instruction.logicalize_cmp_instr() else { // Last instruction is unable to be negated. return Ok(false); }; _ = mem::replace(self.instrs.get_mut(last_instr), logicalized); stack.push_register(result)?; Ok(true) }
Tries to fuse a Wasm `i32.ne` instruction with 0 `rhs` value. Returns - `Ok(true)` if the intruction fusion was successful. - `Ok(false)` if instruction fusion could not be applied. - `Err(_)` if an error occurred.
fuse_nez
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn try_fuse_select( &mut self, stack: &mut ValueStack, select_result: Reg, select_condition: Reg, ) -> Option<(Instruction, bool)> { let Some(last_instr) = self.last_instr else { // If there is no last instruction there is no comparison instruction to negate. return None; }; let last_instruction = *self.instrs.get(last_instr); let Some(last_result) = last_instruction.result() else { // All negatable instructions have a single result register. return None; }; if matches!(stack.get_register_space(last_result), RegisterSpace::Local) { // The instruction stores its result into a local variable which // is an observable side effect which we are not allowed to mutate. return None; } if last_result != select_condition { // The result of the last instruction and the select's `condition` // are not equal thus indicating that we cannot fuse the instructions. return None; } let (fused_select, swap_operands) = last_instruction.try_into_cmp_select_instr(select_result)?; _ = mem::replace(self.instrs.get_mut(last_instr), fused_select); Some((fused_select, swap_operands)) }
Tries to fuse a compare instruction with a Wasm `select` instruction. # Returns - Returns `Some` if fusion was successful. - Returns `None` if fusion could not be applied.
try_fuse_select
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn encode_branch_eqz( &mut self, stack: &mut ValueStack, condition: Reg, label: LabelRef, ) -> Result<(), Error> { let Some(last_instr) = self.last_instr else { return self.encode_branch_eqz_unopt(stack, condition, label); }; let fused_instr = self.try_fuse_branch_cmp_for_instr(stack, last_instr, condition, label, true)?; if let Some(fused_instr) = fused_instr { _ = mem::replace(self.instrs.get_mut(last_instr), fused_instr); return Ok(()); } self.encode_branch_eqz_unopt(stack, condition, label) }
Encodes a `branch_eqz` instruction and tries to fuse it with a previous comparison instruction.
encode_branch_eqz
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
fn encode_branch_eqz_unopt( &mut self, stack: &mut ValueStack, condition: Reg, label: LabelRef, ) -> Result<(), Error> { let offset = self.try_resolve_label(label)?; let instr = match BranchOffset16::try_from(offset) { Ok(offset) => Instruction::branch_i32_eq_imm16(condition, 0, offset), Err(_) => { let zero = stack.alloc_const(0_i32)?; InstrEncoder::make_branch_cmp_fallback( stack, Comparator::I32Eq, condition, zero, offset, )? } }; self.push_instr(instr)?; Ok(()) }
Encode an unoptimized `branch_eqz` instruction. This is used as fallback whenever fusing compare and branch instructions is not possible.
encode_branch_eqz_unopt
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
pub fn encode_branch_nez( &mut self, stack: &mut ValueStack, condition: Reg, label: LabelRef, ) -> Result<(), Error> { let Some(last_instr) = self.last_instr else { return self.encode_branch_nez_unopt(stack, condition, label); }; let fused_instr = self.try_fuse_branch_cmp_for_instr(stack, last_instr, condition, label, false)?; if let Some(fused_instr) = fused_instr { _ = mem::replace(self.instrs.get_mut(last_instr), fused_instr); return Ok(()); } self.encode_branch_nez_unopt(stack, condition, label) }
Encodes a `branch_nez` instruction and tries to fuse it with a previous comparison instruction.
encode_branch_nez
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
fn try_fuse_branch_cmp_for_instr( &mut self, stack: &mut ValueStack, last_instr: Instr, condition: Reg, label: LabelRef, negate: bool, ) -> Result<Option<Instruction>, Error> { let last_instruction = *self.instrs.get(last_instr); let Some(result) = last_instruction.compare_result() else { return Ok(None); }; if matches!(stack.get_register_space(result), RegisterSpace::Local) { // We need to filter out instructions that store their result // into a local register slot because they introduce observable behavior // which a fused cmp+branch instruction would remove. return Ok(None); } if result != condition { // We cannot fuse the instructions since the result of the compare instruction // does not match the input of the conditional branch instruction. return Ok(None); } let last_instruction = match negate { true => match last_instruction.negate_cmp_instr() { Some(negated) => negated, None => return Ok(None), }, false => last_instruction, }; let offset = self.try_resolve_label_for(label, last_instr)?; last_instruction.try_into_cmp_branch_instr(offset, stack) }
Try to fuse [`Instruction`] at `instr` into a branch+cmp instruction. Returns `Ok(Some)` if successful.
try_fuse_branch_cmp_for_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
fn encode_branch_nez_unopt( &mut self, stack: &mut ValueStack, condition: Reg, label: LabelRef, ) -> Result<(), Error> { let offset = self.try_resolve_label(label)?; let instr = match BranchOffset16::try_from(offset) { Ok(offset) => Instruction::branch_i32_ne_imm16(condition, 0, offset), Err(_) => { let zero = stack.alloc_const(0_i32)?; InstrEncoder::make_branch_cmp_fallback( stack, Comparator::I32Ne, condition, zero, offset, )? } }; self.push_instr(instr)?; Ok(()) }
Encode an unoptimized `branch_nez` instruction. This is used as fallback whenever fusing compare and branch instructions is not possible.
encode_branch_nez_unopt
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/instr_encoder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/instr_encoder.rs
Apache-2.0
fn init_func_body_block(&mut self) -> Result<(), Error> { let func_type = self.module.get_type_of_func(self.func); let block_type = BlockType::func_type(func_type); let end_label = self.instr_encoder.new_label(); let consume_fuel = self.make_fuel_instr()?; // Note: we use a dummy `RegSpan` as placeholder since the function enclosing // control block never has branch parameters. let branch_params = RegSpan::new(Reg::from(0)); let block_frame = BlockControlFrame::new( block_type, end_label, branch_params, BlockHeight::default(), consume_fuel, ); self.control_stack.push_frame(block_frame); Ok(()) }
Registers the `block` control frame surrounding the entire function body.
init_func_body_block
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn init_func_params(&mut self) -> Result<(), Error> { for _param_type in self.func_type().params() { self.stack.register_locals(1)?; } Ok(()) }
Registers the function parameters in the emulated value stack.
init_func_params
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn into_allocations(self) -> FuncTranslatorAllocations { FuncTranslatorAllocations { stack: self.stack, instr_encoder: self.instr_encoder, control_stack: self.control_stack, buffer: TranslationBuffers { providers: self.providers, br_table_targets: self.br_table_targets, preserved: self.preserved, }, } }
Consumes `self` and returns the underlying reusable [`FuncTranslatorAllocations`].
into_allocations
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn func_type(&self) -> FuncType { let dedup_func_type = self.module.get_type_of_func(self.func); self.engine() .resolve_func_type(dedup_func_type, Clone::clone) }
Returns the [`FuncType`] of the function that is currently translated.
func_type
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn func_type_at(&self, func_type_index: index::FuncType) -> FuncType { let func_type_index = FuncTypeIdx::from(u32::from(func_type_index)); let dedup_func_type = self.module.get_func_type(func_type_index); self.engine() .resolve_func_type(dedup_func_type, Clone::clone) }
Resolves the [`FuncType`] of the given [`FuncTypeIdx`].
func_type_at
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn func_type_of(&self, func_index: FuncIdx) -> FuncType { let dedup_func_type = self.module.get_type_of_func(func_index); self.engine() .resolve_func_type(dedup_func_type, Clone::clone) }
Resolves the [`FuncType`] of the given [`FuncIdx`].
func_type_of
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn fuel_info_for(&self, frame: &impl ControlFrameBase) -> FuelInfo { self.fuel_info_with(|_| frame.consume_fuel_instr()) }
Returns the [`FuelInfo`] for the given `frame`. Returns [`FuelInfo::None`] if fuel metering is disabled.
fuel_info_for
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn fuel_info_with( &self, fuel_instr: impl FnOnce(&FuncTranslator) -> Option<Instr>, ) -> FuelInfo { let Some(fuel_costs) = self.fuel_costs() else { // Fuel metering is disabled so we can bail out. return FuelInfo::None; }; let fuel_instr = fuel_instr(self) .expect("fuel metering is enabled but there is no Instruction::ConsumeFuel"); FuelInfo::some(fuel_costs.clone(), fuel_instr) }
Returns the [`FuelInfo`] for the current translation state. Returns [`FuelInfo::None`] if fuel metering is disabled.
fuel_info_with
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn push_fueled_instr<F>(&mut self, instr: Instruction, f: F) -> Result<Instr, Error> where F: FnOnce(&FuelCostsProvider) -> u64, { let fuel_info = self.fuel_info(); self.instr_encoder.push_fueled_instr(instr, &fuel_info, f) }
Utility function for pushing a new [`Instruction`] with fuel costs. # Note Fuel metering is only encoded or adjusted if it is enabled.
push_fueled_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn append_instr(&mut self, instr: Instruction) -> Result<(), Error> { self.instr_encoder.append_instr(instr)?; Ok(()) }
Convenience method for appending an [`Instruction`] parameter.
append_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn push_base_instr(&mut self, instr: Instruction) -> Result<Instr, Error> { self.push_fueled_instr(instr, FuelCostsProvider::base) }
Utility function for pushing a new [`Instruction`] with basic fuel costs. # Note Fuel metering is only encoded or adjusted if it is enabled.
push_base_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn preserve_locals(&mut self) -> Result<(), Error> { let fuel_info = self.fuel_info(); let preserved = &mut self.preserved; preserved.clear(); self.stack.preserve_all_locals(|preserved_local| { preserved.push(preserved_local); Ok(()) })?; preserved.reverse(); let copy_groups = preserved.chunk_by(|a, b| { // Note: we group copies into groups with continuous result register indices // because this is what allows us to fuse single `Copy` instructions into // more efficient `Copy2` or `CopyManyNonOverlapping` instructions. // // At the time of this writing the author was not sure if all result registers // of all preserved locals are always continuous so this can be understood as // a safety guard. (i16::from(b.preserved) - i16::from(a.preserved)) == 1 }); for copy_group in copy_groups { let len = u16::try_from(copy_group.len()).unwrap_or_else(|error| { panic!( "too many ({}) registers in copy group: {}", copy_group.len(), error ) }); let results = BoundedRegSpan::new(RegSpan::new(copy_group[0].preserved), len); let providers = &mut self.providers; providers.clear(); providers.extend( copy_group .iter() .map(|p| p.local) .map(TypedProvider::Register), ); let instr = self.instr_encoder.encode_copies( &mut self.stack, results, &providers[..], &fuel_info, )?; if let Some(instr) = instr { self.instr_encoder.notify_preserved_register(instr) } } Ok(()) }
Preserve all locals that are currently on the emulated stack. # Note This is required for correctness upon entering the compilation of a Wasm control flow structure such as a Wasm `block`, `if` or `loop`. Locals on the stack might be manipulated conditionally witihn the control flow structure and therefore need to be preserved before this might happen. For efficiency reasons all locals are preserved independent of their actual use in the entered control flow structure since the analysis of their uses would be too costly.
preserve_locals
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
pub fn translate_unsupported_operator(&self, name: &str) -> Result<(), Error> { panic!("tried to translate an unsupported Wasm operator: {name}") }
Called when translating an unsupported Wasm operator. # Note We panic instead of returning an error because unsupported Wasm errors should have been filtered out by the validation procedure already, therefore encountering an unsupported Wasm operator in the function translation procedure can be considered a bug.
translate_unsupported_operator
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_copy_branch_params(&mut self, frame: &impl ControlFrameBase) -> Result<(), Error> { let branch_params = frame.branch_params(&self.engine); let consume_fuel_instr = frame.consume_fuel_instr(); self.translate_copy_branch_params_impl(branch_params, consume_fuel_instr) }
Convenience function to copy the parameters when branching to a control frame.
translate_copy_branch_params
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_copy_branch_params_impl( &mut self, branch_params: BoundedRegSpan, consume_fuel_instr: Option<Instr>, ) -> Result<(), Error> { if branch_params.is_empty() { // If the block does not have branch parameters there is no need to copy anything. return Ok(()); } let fuel_info = self.fuel_info_with(|_| consume_fuel_instr); let params = &mut self.providers; self.stack.pop_n(usize::from(branch_params.len()), params); self.instr_encoder.encode_copies( &mut self.stack, branch_params, &self.providers[..], &fuel_info, )?; Ok(()) }
Convenience function to copy the parameters when branching to a control frame.
translate_copy_branch_params_impl
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_end_block(&mut self, frame: BlockControlFrame) -> Result<(), Error> { let is_func_block = self.control_stack.is_empty(); if self.reachable && frame.is_branched_to() { self.translate_copy_branch_params(&frame)?; } // Since the `block` is now sealed we can pin its end label. self.instr_encoder.pin_label(frame.end_label()); if frame.is_branched_to() { // Case: branches to this block exist so we cannot treat the // basic block as a no-op and instead have to put its // block results on top of the stack. self.stack .trunc(usize::from(frame.block_height().into_u16())); for result in frame.branch_params(self.engine()) { self.stack.push_register(result)?; } } self.reachable |= frame.is_branched_to(); if self.reachable && is_func_block { // We dropped the Wasm `block` that encloses the function itself so we can return. self.translate_return_with(&frame)?; } Ok(()) }
Translates the `end` of a Wasm `block` control frame.
translate_end_block
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_end_loop(&mut self, _frame: LoopControlFrame) -> Result<(), Error> { debug_assert!( !self.control_stack.is_empty(), "control stack must not be empty since its first element is always a `block`" ); // # Note // // There is no need to copy the top of the stack over // to the `loop` result registers because a Wasm `loop` // only has exactly one exit point right at their end. // // If Wasm validation succeeds we can simply take whatever // is on top of the provider stack at that point to continue // translation or in other words: we do nothing. Ok(()) }
Translates the `end` of a Wasm `loop` control frame.
translate_end_loop
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_end_if(&mut self, frame: IfControlFrame) -> Result<(), Error> { debug_assert!( !self.control_stack.is_empty(), "control stack must not be empty since its first element is always a `block`" ); match (frame.is_then_reachable(), frame.is_else_reachable()) { (true, true) => self.translate_end_if_then_else(frame), (true, false) => self.translate_end_if_then_only(frame), (false, true) => self.translate_end_if_else_only(frame), (false, false) => unreachable!("at least one of `then` or `else` must be reachable"), } }
Translates the `end` of a Wasm `if` control frame.
translate_end_if
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_end_if_then_only(&mut self, frame: IfControlFrame) -> Result<(), Error> { debug_assert!(frame.is_then_reachable()); debug_assert!(!frame.is_else_reachable()); debug_assert!(frame.else_label().is_none()); let end_of_then_reachable = frame.is_end_of_then_reachable().unwrap_or(self.reachable); self.translate_end_if_then_or_else_only(frame, end_of_then_reachable) }
Translates the `end` of a Wasm `if` [`ControlFrame`] were only `then` is reachable. # Example This is used for translating ```wasm (if X (then ..) (else ..) ) ``` or ```wasm (if X (then ..) ) ``` where `X` is a constant value that evaluates to `true` such as `(i32.const 1)`.
translate_end_if_then_only
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_end_if_else_only(&mut self, frame: IfControlFrame) -> Result<(), Error> { debug_assert!(!frame.is_then_reachable()); debug_assert!(frame.is_else_reachable()); debug_assert!(frame.else_label().is_none()); let end_of_else_reachable = self.reachable || !frame.has_visited_else(); self.translate_end_if_then_or_else_only(frame, end_of_else_reachable) }
Translates the `end` of a Wasm `if` [`ControlFrame`] were only `else` is reachable. # Example This is used for translating ```wasm (if X (then ..) (else ..) ) ``` or ```wasm (if X (then ..) ) ``` where `X` is a constant value that evaluates to `false` such as `(i32.const 0)`.
translate_end_if_else_only
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_end_if_then_or_else_only( &mut self, frame: IfControlFrame, end_is_reachable: bool, ) -> Result<(), Error> { if end_is_reachable && frame.is_branched_to() { // If the end of the `if` is reachable AND // there are branches to the end of the `block` // prior, we need to copy the results to the // block result registers. // // # Note // // We can skip this step if the above condition is // not met since the code at this point is either // unreachable OR there is only one source of results // and thus there is no need to copy the results around. self.translate_copy_branch_params(&frame)?; } // Since the `if` is now sealed we can pin its `end` label. self.instr_encoder.pin_label(frame.end_label()); if frame.is_branched_to() { // Case: branches to this block exist so we cannot treat the // basic block as a no-op and instead have to put its // block results on top of the stack. self.stack .trunc(usize::from(frame.block_height().into_u16())); for result in frame.branch_params(self.engine()) { self.stack.push_register(result)?; } } // We reset reachability in case the end of the `block` was reachable. self.reachable = end_is_reachable || frame.is_branched_to(); Ok(()) }
Translates the `end` of a Wasm `if` [`ControlFrame`] were only `then` xor `else` is reachable.
translate_end_if_then_or_else_only
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_end_if_then_else(&mut self, frame: IfControlFrame) -> Result<(), Error> { debug_assert!(frame.is_then_reachable()); debug_assert!(frame.is_else_reachable()); match frame.has_visited_else() { true => self.translate_end_if_then_with_else(frame), false => self.translate_end_if_then_missing_else(frame), } }
Translates the `end` of a Wasm `if` [`ControlFrame`] were both `then` and `else` are reachable.
translate_end_if_then_else
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_end_if_then_with_else(&mut self, frame: IfControlFrame) -> Result<(), Error> { debug_assert!(frame.has_visited_else()); let end_of_then_reachable = frame .is_end_of_then_reachable() .expect("must be set since `else` was visited"); let end_of_else_reachable = self.reachable; let reachable = match (end_of_then_reachable, end_of_else_reachable) { (false, false) => frame.is_branched_to(), _ => true, }; self.instr_encoder.pin_label_if_unpinned( frame .else_label() .expect("must have `else` label since `else` is reachable"), ); let if_height = usize::from(frame.block_height().into_u16()); if end_of_else_reachable { // Since the end of `else` is reachable we need to properly // write the `else` block results back to were the `if` expects // its results to reside upon exit. self.translate_copy_branch_params(&frame)?; } // After `else` parameters have been copied we can finally pin the `end` label. self.instr_encoder.pin_label(frame.end_label()); if reachable { // In case the code following the `if` is reachable we need // to clean up and prepare the value stack. self.stack.trunc(if_height); for result in frame.branch_params(self.engine()) { self.stack.push_register(result)?; } } self.reachable = reachable; Ok(()) }
Variant of [`Self::translate_end_if_then_else`] were the `else` block exists.
translate_end_if_then_with_else
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_end_if_then_missing_else(&mut self, frame: IfControlFrame) -> Result<(), Error> { debug_assert!(!frame.has_visited_else()); let end_of_then_reachable = self.reachable; let has_results = frame.block_type().len_results(self.engine()) >= 1; if end_of_then_reachable && has_results { // Since the `else` block is missing we need to write the results // from the `then` block back to were the `if` control frame expects // its results afterwards. // Furthermore we need to encode the branch to the `if` end label. self.translate_copy_branch_params(&frame)?; let end_offset = self.instr_encoder.try_resolve_label(frame.end_label())?; self.push_fueled_instr(Instruction::branch(end_offset), FuelCostsProvider::base)?; } self.instr_encoder.pin_label_if_unpinned( frame .else_label() .expect("must have `else` label since `else` is reachable"), ); let engine = self.engine().clone(); let if_height = usize::from(frame.block_height().into_u16()); let else_providers = self.control_stack.pop_else_providers(); if has_results { // We haven't visited the `else` block and thus the `else` // providers are still on the auxiliary stack and need to // be popped. We use them to restore the stack to the state // when entering the `if` block so that we can properly copy // the `else` results to were they are expected. self.stack.trunc(if_height); for provider in else_providers { self.stack.push_provider(provider)?; if let TypedProvider::Register(register) = provider { self.stack.dec_register_usage(register); } } self.translate_copy_branch_params(&frame)?; } // After `else` parameters have been copied we can finally pin the `end` label. self.instr_encoder.pin_label(frame.end_label()); // Without `else` block the code after the `if` is always reachable and // thus we need to clean up and prepare the value stack for the following code. self.stack.trunc(if_height); for result in frame.branch_params(&engine) { self.stack.push_register(result)?; } self.reachable = true; Ok(()) }
Variant of [`Self::translate_end_if_then_else`] were the `else` block does not exist. # Note A missing `else` block forwards the [`IfControlFrame`] inputs like an identity function.
translate_end_if_then_missing_else
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn alloc_branch_params( &mut self, len_block_params: u16, len_branch_params: u16, ) -> Result<RegSpan, Error> { let params = &mut self.providers; // Pop the block parameters off the stack. self.stack.pop_n(usize::from(len_block_params), params); // Peek the branch parameter registers which are going to be returned. let branch_params = self.stack.peek_dynamic_n(usize::from(len_branch_params))?; // Push the block parameters onto the stack again as if nothing happened. self.stack.push_n(params)?; params.clear(); Ok(branch_params) }
Allocate control flow block branch parameters. # Note The naive description of this algorithm is as follows: 1. Pop off all block parameters of the control flow block from the stack and store them temporarily in the `buffer`. 2. For each branch parameter dynamically allocate a register. - Note: All dynamically allocated registers must be contiguous. - These registers serve as the registers and to hold the branch parameters upon branching to the control flow block and are going to be returned via [`RegSpan`]. 3. Drop all dynamically allocated branch parameter registers again. 4. Push the block parameters stored in the `buffer` back onto the stack. 5. Return the result registers of step 2. The `buffer` will be empty after this operation. # Dev. Note The current implementation is naive and rather inefficient for the purpose of simplicity and correctness and should be optimized if it turns out to be a bottleneck. # Errors If this procedure would allocate more registers than are available.
alloc_branch_params
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn push_binary_instr( &mut self, lhs: Reg, rhs: Reg, make_instr: fn(result: Reg, lhs: Reg, rhs: Reg) -> Instruction, ) -> Result<(), Error> { let result = self.stack.push_dynamic()?; self.push_fueled_instr(make_instr(result, lhs, rhs), FuelCostsProvider::base)?; Ok(()) }
Pushes a binary instruction with two register inputs `lhs` and `rhs`.
push_binary_instr
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn try_push_binary_instr_imm16<T>( &mut self, lhs: Reg, rhs: T, make_instr_imm16: fn(result: Reg, lhs: Reg, rhs: Const16<T>) -> Instruction, ) -> Result<bool, Error> where T: Copy + TryInto<Const16<T>>, { if let Ok(rhs) = rhs.try_into() { // Optimization: We can use a compact instruction for small constants. let result = self.stack.push_dynamic()?; self.push_fueled_instr(make_instr_imm16(result, lhs, rhs), FuelCostsProvider::base)?; return Ok(true); } Ok(false) }
Pushes a binary instruction if the immediate operand can be encoded in 16 bits. # Note - Returns `Ok(true)` is the optimization was applied. - Returns `Ok(false)` is the optimization could not be applied. - Returns `Err(_)` if a translation error occurred.
try_push_binary_instr_imm16
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn try_push_binary_instr_imm16_rev<T>( &mut self, lhs: T, rhs: Reg, make_instr_imm16: fn(result: Reg, lhs: Const16<T>, rhs: Reg) -> Instruction, ) -> Result<bool, Error> where T: Copy + TryInto<Const16<T>>, { if let Ok(lhs) = lhs.try_into() { // Optimization: We can use a compact instruction for small constants. let result = self.stack.push_dynamic()?; self.push_fueled_instr(make_instr_imm16(result, lhs, rhs), FuelCostsProvider::base)?; return Ok(true); } Ok(false) }
Variant of [`Self::try_push_binary_instr_imm16`] with swapped operands for `make_instr_imm16`.
try_push_binary_instr_imm16_rev
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn push_binary_consteval<T, R>( &mut self, lhs: TypedVal, rhs: TypedVal, consteval: fn(T, T) -> R, ) -> Result<(), Error> where T: From<TypedVal>, R: Into<TypedVal>, { self.stack .push_const(consteval(lhs.into(), rhs.into()).into()); Ok(()) }
Evaluates the constants and pushes the proper result to the value stack.
push_binary_consteval
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn push_binary_instr_imm<T>( &mut self, lhs: Reg, rhs: T, make_instr: fn(result: Reg, lhs: Reg, rhs: Reg) -> Instruction, ) -> Result<(), Error> where T: Into<UntypedVal>, { let result = self.stack.push_dynamic()?; let rhs = self.stack.alloc_const(rhs)?; self.push_fueled_instr(make_instr(result, lhs, rhs), FuelCostsProvider::base)?; Ok(()) }
Pushes a binary instruction with a generic immediate value. # Note The resulting binary instruction always takes up two instruction words for its encoding in the [`Instruction`] sequence.
push_binary_instr_imm
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn push_binary_instr_imm_rev<T>( &mut self, lhs: T, rhs: Reg, make_instr: fn(result: Reg, lhs: Reg, rhs: Reg) -> Instruction, ) -> Result<(), Error> where T: Into<UntypedVal>, { let result = self.stack.push_dynamic()?; let lhs = self.stack.alloc_const(lhs)?; self.push_fueled_instr(make_instr(result, lhs, rhs), FuelCostsProvider::base)?; Ok(()) }
Pushes a binary instruction with a generic immediate value. # Note The resulting binary instruction always takes up two instruction words for its encoding in the [`Instruction`] sequence.
push_binary_instr_imm_rev
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_fcopysign<T>( &mut self, make_instr: fn(result: Reg, lhs: Reg, rhs: Reg) -> Instruction, make_instr_imm: fn(result: Reg, lhs: Reg, rhs: Sign<T>) -> Instruction, consteval: fn(T, T) -> T, ) -> Result<(), Error> where T: WasmFloat, { bail_unreachable!(self); match self.stack.pop2() { (TypedProvider::Register(lhs), TypedProvider::Register(rhs)) => { if lhs == rhs { // Optimization: `copysign x x` is always just `x` self.stack.push_register(lhs)?; return Ok(()); } self.push_binary_instr(lhs, rhs, make_instr) } (TypedProvider::Register(lhs), TypedProvider::Const(rhs)) => { let sign = T::from(rhs).sign(); let result = self.stack.push_dynamic()?; self.push_fueled_instr(make_instr_imm(result, lhs, sign), FuelCostsProvider::base)?; Ok(()) } (TypedProvider::Const(lhs), TypedProvider::Register(rhs)) => { self.push_binary_instr_imm_rev(lhs, rhs, make_instr) } (TypedProvider::Const(lhs), TypedProvider::Const(rhs)) => { self.push_binary_consteval(lhs, rhs, consteval) } } }
Translate Wasmi float `{f32,f64}.copysign` instructions. # Note - This applies several optimization that are valid for copysign instructions. - Applies constant evaluation if both operands are constant values.
translate_fcopysign
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_unary<T, R>( &mut self, make_instr: fn(result: Reg, input: Reg) -> Instruction, consteval: fn(input: T) -> R, ) -> Result<(), Error> where T: From<TypedVal>, R: Into<TypedVal>, { bail_unreachable!(self); match self.stack.pop() { TypedProvider::Register(input) => { let result = self.stack.push_dynamic()?; self.push_fueled_instr(make_instr(result, input), FuelCostsProvider::base)?; Ok(()) } TypedProvider::Const(input) => { self.stack.push_const(consteval(input.into()).into()); Ok(()) } } }
Translates a unary Wasm instruction to Wasmi bytecode.
translate_unary
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_unary_fallible<T, R>( &mut self, make_instr: fn(result: Reg, input: Reg) -> Instruction, consteval: fn(input: T) -> Result<R, TrapCode>, ) -> Result<(), Error> where T: From<TypedVal>, R: Into<TypedVal>, { bail_unreachable!(self); match self.stack.pop() { TypedProvider::Register(input) => { let result = self.stack.push_dynamic()?; self.push_fueled_instr(make_instr(result, input), FuelCostsProvider::base)?; Ok(()) } TypedProvider::Const(input) => match consteval(input.into()) { Ok(result) => { self.stack.push_const(result); Ok(()) } Err(trap_code) => self.translate_trap(trap_code), }, } }
Translates a fallible unary Wasm instruction to Wasmi bytecode.
translate_unary_fallible
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn decode_memarg(memarg: MemArg) -> (index::Memory, u64) { let memory = index::Memory::from(memarg.memory); (memory, memarg.offset) }
Returns the [`MemArg`] linear `memory` index and load/store `offset`. # Panics If the [`MemArg`] offset is not 32-bit.
decode_memarg
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn effective_address(&self, mem: index::Memory, ptr: TypedVal, offset: u64) -> Option<Address> { let memory_type = *self .module .get_type_of_memory(MemoryIdx::from(u32::from(mem))); let ptr = match memory_type.is_64() { true => u64::from(ptr), false => u64::from(u32::from(ptr)), }; let Some(address) = ptr.checked_add(offset) else { // Case: address overflows any legal memory index. return None; }; if let Some(max) = memory_type.maximum() { // The memory's maximum size in bytes. let max_size = max << memory_type.page_size_log2(); if address > max_size { // Case: address overflows the memory's maximum size. return None; } } if !memory_type.is_64() && address >= 1 << 32 { // Case: address overflows the 32-bit memory index. return None; } let Ok(address) = Address::try_from(address) else { // Case: address is too big for the system to handle properly. return None; }; Some(address) }
Returns the effective address `ptr+offset` if it is valid.
effective_address
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_load( &mut self, memarg: MemArg, make_instr: fn(result: Reg, offset_lo: Offset64Lo) -> Instruction, make_instr_offset16: fn(result: Reg, ptr: Reg, offset: Offset16) -> Instruction, make_instr_at: fn(result: Reg, address: Address32) -> Instruction, ) -> Result<(), Error> { bail_unreachable!(self); let (memory, offset) = Self::decode_memarg(memarg); let ptr = self.stack.pop(); let (ptr, offset) = match ptr { Provider::Register(ptr) => (ptr, offset), Provider::Const(ptr) => { let Some(address) = self.effective_address(memory, ptr, offset) else { return self.translate_trap(TrapCode::MemoryOutOfBounds); }; if let Ok(address) = Address32::try_from(address) { let result = self.stack.push_dynamic()?; self.push_fueled_instr( make_instr_at(result, address), FuelCostsProvider::load, )?; if !memory.is_default() { self.instr_encoder .append_instr(Instruction::memory_index(memory))?; } return Ok(()); } // Case: we cannot use specialized encoding and thus have to fall back // to the general case where `ptr` is zero and `offset` stores the // `ptr+offset` address value. let zero_ptr = self.stack.alloc_const(0_u64)?; (zero_ptr, u64::from(address)) } }; let result = self.stack.push_dynamic()?; if memory.is_default() { if let Ok(offset) = Offset16::try_from(offset) { self.push_fueled_instr( make_instr_offset16(result, ptr, offset), FuelCostsProvider::load, )?; return Ok(()); } } let (offset_hi, offset_lo) = Offset64::split(offset); self.push_fueled_instr(make_instr(result, offset_lo), FuelCostsProvider::load)?; self.instr_encoder .append_instr(Instruction::register_and_offset_hi(ptr, offset_hi))?; if !memory.is_default() { self.instr_encoder .append_instr(Instruction::memory_index(memory))?; } Ok(()) }
Translates a Wasm `load` instruction to Wasmi bytecode. # Note This chooses the right encoding for the given `load` instruction. If `ptr+offset` is a constant value the address is pre-calculated. # Usage Used for translating the following Wasm operators to Wasmi bytecode: - `{i32, i64, f32, f64}.load` - `i32.{load8_s, load8_u, load16_s, load16_u}` - `i64.{load8_s, load8_u, load16_s, load16_u load32_s, load32_u}`
translate_load
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_istore_wrap_at<Src, Wrapped, Field>( &mut self, memory: index::Memory, address: Address32, value: TypedProvider, make_instr_at: fn(value: Reg, address: Address32) -> Instruction, make_instr_at_imm: fn(value: Field, address: Address32) -> Instruction, ) -> Result<(), Error> where Src: Copy + From<TypedVal> + Wrap<Wrapped>, Field: TryFrom<Wrapped>, { match value { Provider::Register(value) => { self.push_fueled_instr(make_instr_at(value, address), FuelCostsProvider::store)?; } Provider::Const(value) => { if let Ok(value) = Field::try_from(Src::from(value).wrap()) { self.push_fueled_instr( make_instr_at_imm(value, address), FuelCostsProvider::store, )?; } else { let value = self.stack.alloc_const(value)?; self.push_fueled_instr( make_instr_at(value, address), FuelCostsProvider::store, )?; } } } if !memory.is_default() { self.instr_encoder .append_instr(Instruction::memory_index(memory))?; } Ok(()) }
Translates Wasm integer `store` and `storeN` instructions to Wasmi bytecode. # Note This is used in cases where the `ptr` is a known constant value.
translate_istore_wrap_at
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_istore_wrap_mem0<Src, Wrapped, Field>( &mut self, ptr: Reg, offset: u64, value: TypedProvider, make_instr_offset16: fn(Reg, Offset16, Reg) -> Instruction, make_instr_offset16_imm: fn(Reg, Offset16, Field) -> Instruction, ) -> Result<Option<Instr>, Error> where Src: Copy + From<TypedVal> + Wrap<Wrapped>, Field: TryFrom<Wrapped>, { let Ok(offset16) = Offset16::try_from(offset) else { return Ok(None); }; let instr = match value { Provider::Register(value) => self.push_fueled_instr( make_instr_offset16(ptr, offset16, value), FuelCostsProvider::store, )?, Provider::Const(value) => match Field::try_from(Src::from(value).wrap()) { Ok(value) => self.push_fueled_instr( make_instr_offset16_imm(ptr, offset16, value), FuelCostsProvider::store, )?, Err(_) => { let value = self.stack.alloc_const(value)?; self.push_fueled_instr( make_instr_offset16(ptr, offset16, value), FuelCostsProvider::store, )? } }, }; Ok(Some(instr)) }
Translates Wasm integer `store` and `storeN` instructions to Wasmi bytecode. # Note This optimizes for cases where the Wasm linear memory that is operated on is known to be the default memory. Returns `Some` in case the optimized instructions have been encoded.
translate_istore_wrap_mem0
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_store( &mut self, memarg: MemArg, make_instr: fn(ptr: Reg, offset_lo: Offset64Lo) -> Instruction, make_instr_offset16: fn(ptr: Reg, offset: Offset16, value: Reg) -> Instruction, make_instr_at: fn(value: Reg, address: Address32) -> Instruction, ) -> Result<(), Error> { bail_unreachable!(self); let (memory, offset) = Self::decode_memarg(memarg); let (ptr, value) = self.stack.pop2(); let (ptr, offset) = match ptr { Provider::Register(ptr) => (ptr, offset), Provider::Const(ptr) => { let Some(address) = self.effective_address(memory, ptr, offset) else { return self.translate_trap(TrapCode::MemoryOutOfBounds); }; if let Ok(address) = Address32::try_from(address) { return self.translate_fstore_at(memory, address, value, make_instr_at); } let zero_ptr = self.stack.alloc_const(0_u64)?; (zero_ptr, u64::from(address)) } }; let (offset_hi, offset_lo) = Offset64::split(offset); let value = self.stack.provider2reg(&value)?; if memory.is_default() { if let Ok(offset) = Offset16::try_from(offset) { self.push_fueled_instr( make_instr_offset16(ptr, offset, value), FuelCostsProvider::store, )?; return Ok(()); } } self.push_fueled_instr(make_instr(ptr, offset_lo), FuelCostsProvider::store)?; self.instr_encoder .append_instr(Instruction::register_and_offset_hi(value, offset_hi))?; if !memory.is_default() { self.instr_encoder .append_instr(Instruction::memory_index(memory))?; } Ok(()) }
Translates a general Wasm `store` instruction to Wasmi bytecode. # Note This chooses the most efficient encoding for the given `store` instruction. If `ptr+offset` is a constant value the pointer address is pre-calculated. # Usage Used for translating the following Wasm operators to Wasmi bytecode: - `{f32, f64, v128}.store`
translate_store
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_fstore_at( &mut self, memory: index::Memory, address: Address32, value: TypedProvider, make_instr_at: fn(value: Reg, address: Address32) -> Instruction, ) -> Result<(), Error> { let value = self.stack.provider2reg(&value)?; self.push_fueled_instr(make_instr_at(value, address), FuelCostsProvider::store)?; if !memory.is_default() { self.instr_encoder .append_instr(Instruction::memory_index(memory))?; } Ok(()) }
Translates a general Wasm `store` instruction to Wasmi bytecode. # Note This is used in cases where the `ptr` is a known constant value.
translate_fstore_at
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_select(&mut self, _type_hint: Option<ValType>) -> Result<(), Error> { bail_unreachable!(self); let (true_val, false_val, condition) = self.stack.pop3(); if true_val == false_val { // Optimization: both `lhs` and `rhs` either are the same register or constant values and // thus `select` will always yield this same value irrespective of the condition. // // TODO: we could technically look through registers representing function local constants and // check whether they are equal to a given constant in cases where `lhs` and `rhs` are referring // to a function local register and a constant value or vice versa. self.stack.push_provider(true_val)?; return Ok(()); } let condition = match condition { Provider::Register(condition) => condition, Provider::Const(condition) => { // Optimization: since condition is a constant value we can const-fold the `select` // instruction and simply push the selected value back to the provider stack. let selected = match i32::from(condition) != 0 { true => true_val, false => false_val, }; if let Provider::Register(reg) = selected { if matches!( self.stack.get_register_space(reg), RegisterSpace::Dynamic | RegisterSpace::Preserve ) { // Case: constant propagating a dynamic or preserved register might overwrite it in // future instruction translation steps and thus we may require a copy instruction // to prevent this from happening. let result = self.stack.push_dynamic()?; let fuel_info = self.fuel_info(); self.instr_encoder.encode_copy( &mut self.stack, result, selected, &fuel_info, )?; return Ok(()); } } self.stack.push_provider(selected)?; return Ok(()); } }; let mut true_val = self.stack.provider2reg(&true_val)?; let mut false_val = self.stack.provider2reg(&false_val)?; let result = self.stack.push_dynamic()?; match self .instr_encoder .try_fuse_select(&mut self.stack, result, condition) { Some((_, swap_operands)) => { if swap_operands { mem::swap(&mut true_val, &mut false_val); } } None => { let select_instr = Instruction::select_i32_eq_imm16(result, condition, 0_i16); self.push_fueled_instr(select_instr, FuelCostsProvider::base)?; mem::swap(&mut true_val, &mut false_val); } }; self.append_instr(Instruction::register2_ext(true_val, false_val))?; Ok(()) }
Translates a Wasm `select` or `select <ty>` instruction. # Note - This applies constant propagation in case `condition` is a constant value. - If both `lhs` and `rhs` are equal registers or constant values `lhs` is forwarded. - Fuses compare instructions with the associated select instructions if possible.
translate_select
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_return_with(&mut self, frame: &impl ControlFrameBase) -> Result<(), Error> { let fuel_info = self.fuel_info_for(frame); self.translate_return_impl(&fuel_info) }
Translates an unconditional `return` instruction given fuel information.
translate_return_with
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_return_impl(&mut self, fuel_info: &FuelInfo) -> Result<(), Error> { let func_type = self.func_type(); let results = func_type.results(); let values = &mut self.providers; self.stack.pop_n(results.len(), values); self.instr_encoder .encode_return(&mut self.stack, values, fuel_info)?; self.reachable = false; Ok(()) }
Translates an unconditional `return` instruction given fuel information.
translate_return_impl
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn call_indirect_params( &mut self, index: Provider<TypedVal>, table_index: u32, ) -> Result<Instruction, Error> { let table_type = *self.module.get_type_of_table(TableIdx::from(table_index)); let index = self.as_index_type_const16(index, table_type.index_ty())?; let instr = match index { Provider::Register(index) => Instruction::call_indirect_params(index, table_index), Provider::Const(index) => Instruction::call_indirect_params_imm16(index, table_index), }; Ok(instr) }
Create either [`Instruction::CallIndirectParams`] or [`Instruction::CallIndirectParamsImm16`] depending on the inputs.
call_indirect_params
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_br(&mut self, relative_depth: u32) -> Result<(), Error> { let engine = self.engine().clone(); match self.control_stack.acquire_target(relative_depth) { AcquiredTarget::Return(_frame) => self.translate_return(), AcquiredTarget::Branch(frame) => { frame.branch_to(); let branch_dst = frame.branch_destination(); let branch_params = frame.branch_params(&engine); let consume_fuel_instr = frame.consume_fuel_instr(); self.translate_copy_branch_params_impl(branch_params, consume_fuel_instr)?; let branch_offset = self.instr_encoder.try_resolve_label(branch_dst)?; self.push_base_instr(Instruction::branch(branch_offset))?; self.reachable = false; Ok(()) } } }
Translates a Wasm `br` instruction with its `relative_depth`.
translate_br
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn populate_br_table_buffer<'a>( buffer: &'a mut Vec<u32>, table: &wasmparser::BrTable, ) -> Result<&'a [u32], Error> { let default_target = table.default(); buffer.clear(); for target in table.targets() { buffer.push(target?); } buffer.push(default_target); Ok(buffer) }
Populate the `buffer` with the `table` targets including the `table` default target. Returns a shared slice to the `buffer` after it has been filled. # Note The `table` default target is pushed last to the `buffer`.
populate_br_table_buffer
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn apply_providers_buffer<R>(&mut self, f: impl FnOnce(&mut Self, &[TypedProvider]) -> R) -> R { let values = mem::take(&mut self.providers); let result = f(self, &values[..]); let _ = mem::replace(&mut self.providers, values); result }
Convenience method to allow inspecting the provider buffer while manipulating `self` circumventing the borrow checker.
apply_providers_buffer
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_br_table(&mut self, table: wasmparser::BrTable) -> Result<(), Error> { let engine = self.engine().clone(); let index = self.stack.pop(); let default_target = table.default(); if table.is_empty() { // Case: the `br_table` only has a single target `t` which is equal to a `br t`. return self.translate_br(default_target); } let index: Reg = match index { TypedProvider::Register(index) => index, TypedProvider::Const(index) => { // Case: the `br_table` index is a constant value, therefore always taking the same branch. let chosen_index = u32::from(index) as usize; let chosen_target = table .targets() .nth(chosen_index) .transpose()? .unwrap_or(default_target); return self.translate_br(chosen_target); } }; let targets = &mut self.br_table_targets; Self::populate_br_table_buffer(targets, &table)?; if targets.iter().all(|&target| target == default_target) { // Case: all targets are the same and thus the `br_table` is equal to a `br`. return self.translate_br(default_target); } // Note: The Wasm spec mandates that all `br_table` targets manipulate the // Wasm value stack the same. This implies for Wasmi that all `br_table` // targets have the same branch parameter arity. let branch_params = self .control_stack .acquire_target(default_target) .control_frame() .branch_params(&engine); match branch_params.len() { 0 => self.translate_br_table_0(index), 1 => self.translate_br_table_1(index), 2 => self.translate_br_table_2(index), 3 => self.translate_br_table_3(index), n => self.translate_br_table_n(index, n), } }
Translates a Wasm `br_table` instruction with its branching targets.
translate_br_table
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0
fn translate_br_table_targets_simple(&mut self, values: &[TypedProvider]) -> Result<(), Error> { self.translate_br_table_targets(values, |_, _| unreachable!()) }
Translates the branching targets of a Wasm `br_table` instruction for simple cases without value copying.
translate_br_table_targets_simple
rust
wasmi-labs/wasmi
crates/wasmi/src/engine/translator/func/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/engine/translator/func/mod.rs
Apache-2.0