wasmer_compiler_cranelift/translator/
translation_utils.rs

1//! Helper functions and structures for the translation.
2
3use crate::translator::EXN_REF_TYPE;
4
5use super::func_environ::TargetEnvironment;
6use cranelift_codegen::{
7    binemit::Reloc,
8    ir::{self, AbiParam},
9    isa::TargetFrontendConfig,
10};
11use cranelift_frontend::FunctionBuilder;
12use wasmer_compiler::{
13    types::relocation::RelocationKind,
14    wasmparser::{self, RefType},
15};
16use wasmer_types::{FunctionType, LibCall, Type, WasmError, WasmResult};
17
18/// Helper function translate a Function signature into Cranelift Ir
19pub fn signature_to_cranelift_ir(
20    signature: &FunctionType,
21    target_config: TargetFrontendConfig,
22) -> ir::Signature {
23    let mut sig = ir::Signature::new(target_config.default_call_conv);
24    sig.params.extend(signature.params().iter().map(|&ty| {
25        let cret_arg: ir::Type = type_to_irtype(ty, target_config)
26            .expect("only numeric types are supported in function signatures");
27        AbiParam::new(cret_arg)
28    }));
29    sig.returns.extend(signature.results().iter().map(|&ty| {
30        let cret_arg: ir::Type = type_to_irtype(ty, target_config)
31            .expect("only numeric types are supported in function signatures");
32        AbiParam::new(cret_arg)
33    }));
34    // The Vmctx signature
35    sig.params.insert(
36        0,
37        AbiParam::special(target_config.pointer_type(), ir::ArgumentPurpose::VMContext),
38    );
39    sig
40}
41
42/// Helper function translating wasmparser types to Cranelift types when possible.
43pub fn reference_type(target_config: TargetFrontendConfig) -> WasmResult<ir::Type> {
44    Ok(target_config.pointer_type())
45}
46
47/// Helper function translating wasmparser types to Cranelift types when possible.
48pub fn type_to_irtype(ty: Type, target_config: TargetFrontendConfig) -> WasmResult<ir::Type> {
49    match ty {
50        Type::I32 => Ok(ir::types::I32),
51        Type::I64 => Ok(ir::types::I64),
52        Type::F32 => Ok(ir::types::F32),
53        Type::F64 => Ok(ir::types::F64),
54        Type::V128 => Ok(ir::types::I8X16),
55        Type::ExternRef | Type::FuncRef => reference_type(target_config),
56        Type::ExceptionRef => Ok(EXN_REF_TYPE),
57        // ty => Err(wasm_unsupported!("type_to_type: wasm type {:?}", ty)),
58    }
59}
60
61/// Transform Cranelift LibCall into runtime LibCall
62pub fn irlibcall_to_libcall(libcall: ir::LibCall) -> LibCall {
63    match libcall {
64        ir::LibCall::Probestack => LibCall::Probestack,
65        ir::LibCall::CeilF32 => LibCall::CeilF32,
66        ir::LibCall::CeilF64 => LibCall::CeilF64,
67        ir::LibCall::FloorF32 => LibCall::FloorF32,
68        ir::LibCall::FloorF64 => LibCall::FloorF64,
69        ir::LibCall::TruncF32 => LibCall::TruncF32,
70        ir::LibCall::TruncF64 => LibCall::TruncF64,
71        ir::LibCall::NearestF32 => LibCall::NearestF32,
72        ir::LibCall::NearestF64 => LibCall::NearestF64,
73        _ => panic!("Unsupported libcall"),
74    }
75}
76
77/// Transform Cranelift Reloc to compiler Relocation
78pub fn irreloc_to_relocationkind(reloc: Reloc) -> RelocationKind {
79    match reloc {
80        Reloc::Abs4 => RelocationKind::Abs4,
81        Reloc::Abs8 => RelocationKind::Abs8,
82        Reloc::X86PCRel4 => RelocationKind::X86PCRel4,
83        Reloc::X86CallPCRel4 => RelocationKind::X86CallPCRel4,
84        Reloc::X86CallPLTRel4 => RelocationKind::X86CallPLTRel4,
85        Reloc::X86GOTPCRel4 => RelocationKind::X86GOTPCRel4,
86        Reloc::Arm64Call => RelocationKind::Arm64Call,
87        Reloc::RiscvCallPlt => RelocationKind::RiscvCall,
88        _ => panic!("The relocation {reloc} is not yet supported."),
89    }
90}
91
92/// Create a `Block` with the given Wasm parameters.
93pub fn block_with_params<'a, PE: TargetEnvironment + ?Sized>(
94    builder: &mut FunctionBuilder,
95    params: impl Iterator<Item = &'a wasmparser::ValType>,
96    environ: &PE,
97) -> WasmResult<ir::Block> {
98    let block = builder.create_block();
99    for ty in params.into_iter() {
100        match ty {
101            wasmparser::ValType::I32 => {
102                builder.append_block_param(block, ir::types::I32);
103            }
104            wasmparser::ValType::I64 => {
105                builder.append_block_param(block, ir::types::I64);
106            }
107            wasmparser::ValType::F32 => {
108                builder.append_block_param(block, ir::types::F32);
109            }
110            wasmparser::ValType::F64 => {
111                builder.append_block_param(block, ir::types::F64);
112            }
113            wasmparser::ValType::Ref(ty) => {
114                if ty.is_extern_ref() || ty.is_func_ref() {
115                    builder.append_block_param(block, environ.reference_type());
116                } else if ty == &RefType::EXNREF {
117                    builder.append_block_param(block, EXN_REF_TYPE);
118                } else {
119                    return Err(WasmError::Unsupported(format!(
120                        "unsupported reference type: {ty:?}"
121                    )));
122                }
123            }
124            wasmparser::ValType::V128 => {
125                builder.append_block_param(block, ir::types::I8X16);
126            }
127        }
128    }
129    Ok(block)
130}
131
132/// Turns a `wasmparser` `f32` into a `Cranelift` one.
133pub fn f32_translation(x: wasmparser::Ieee32) -> ir::immediates::Ieee32 {
134    ir::immediates::Ieee32::with_bits(x.bits())
135}
136
137/// Turns a `wasmparser` `f64` into a `Cranelift` one.
138pub fn f64_translation(x: wasmparser::Ieee64) -> ir::immediates::Ieee64 {
139    ir::immediates::Ieee64::with_bits(x.bits())
140}
141
142/// Special VMContext value label. It is tracked as 0xffff_fffe label.
143pub fn get_vmctx_value_label() -> ir::ValueLabel {
144    const VMCTX_LABEL: u32 = 0xffff_fffe;
145    ir::ValueLabel::from_u32(VMCTX_LABEL)
146}