1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use anyhow::{bail, Context as _, Result};
use object::write::Object;
use target_lexicon::Triple;
use wasmtime::Strategy;
use wasmtime_environ::{settings, settings::Configurable, ModuleEnvironment, Tunables};
use wasmtime_jit::{native, Compiler};
pub fn compile_to_obj(
wasm: &[u8],
target: Option<&Triple>,
strategy: Strategy,
enable_simd: bool,
opt_level: wasmtime::OptLevel,
debug_info: bool,
) -> Result<Object> {
let isa_builder = match target {
Some(target) => native::lookup(target.clone())?,
None => native::builder(),
};
let mut flag_builder = settings::builder();
flag_builder.enable("avoid_div_traps").unwrap();
if enable_simd {
flag_builder.enable("enable_simd").unwrap();
}
match opt_level {
wasmtime::OptLevel::None => {}
wasmtime::OptLevel::Speed => {
flag_builder.set("opt_level", "speed").unwrap();
}
wasmtime::OptLevel::SpeedAndSize => {
flag_builder.set("opt_level", "speed_and_size").unwrap();
}
other => bail!("unknown optimization level {:?}", other),
}
let isa = isa_builder.finish(settings::Flags::new(flag_builder));
let mut tunables = Tunables::default();
tunables.debug_info = debug_info;
let compiler = Compiler::new(
isa,
match strategy {
Strategy::Auto => wasmtime_jit::CompilationStrategy::Auto,
Strategy::Cranelift => wasmtime_jit::CompilationStrategy::Cranelift,
#[cfg(feature = "lightbeam")]
Strategy::Lightbeam => wasmtime_jit::CompilationStrategy::Lightbeam,
#[cfg(not(feature = "lightbeam"))]
Strategy::Lightbeam => bail!("lightbeam support not enabled"),
s => bail!("unknown compilation strategy {:?}", s),
},
tunables.clone(),
);
let environ = ModuleEnvironment::new(compiler.isa().frontend_config(), &tunables);
let translation = environ
.translate(wasm)
.context("failed to translate module")?;
let compilation = compiler.compile(&translation)?;
Ok(compilation.obj)
}