forked from wasmerio/wasmer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler_llvm.rs
65 lines (53 loc) · 1.81 KB
/
compiler_llvm.rs
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
//! A Wasm module can be compiled with multiple compilers.
//!
//! This example illustrates how to use the LLVM compiler.
//!
//! You can run the example directly by executing in Wasmer root:
//!
//! ```shell
//! cargo run --example compiler-llvm --release --features "llvm"
//! ```
//!
//! Ready?
use wasmer::{imports, wat2wasm, Instance, Module, Store, Value};
use wasmer_compiler_llvm::LLVM;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Let's declare the Wasm module with the text representation.
let wasm_bytes = wat2wasm(
r#"
(module
(type $sum_t (func (param i32 i32) (result i32)))
(func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32)
local.get $x
local.get $y
i32.add)
(export "sum" (func $sum_f)))
"#
.as_bytes(),
)?;
// Use LLVM compiler with the default settings
let compiler = LLVM::default();
// Create the store
let mut store = Store::new(compiler);
println!("Compiling module...");
// Let's compile the Wasm module.
let module = Module::new(&store, wasm_bytes)?;
// Create an empty import object.
let import_object = imports! {};
println!("Instantiating module...");
// Let's instantiate the Wasm module.
let instance = Instance::new(&mut store, &module, &import_object)?;
let sum = instance.exports.get_function("sum")?;
println!("Calling `sum` function...");
// Let's call the `sum` exported function. The parameters are a
// slice of `Value`s. The results are a boxed slice of `Value`s.
let results = sum.call(&mut store, &[Value::I32(1), Value::I32(2)])?;
println!("Results: {:?}", results);
assert_eq!(results.to_vec(), vec![Value::I32(3)]);
Ok(())
}
#[test]
#[cfg(feature = "llvm")]
fn test_compiler_llvm() -> Result<(), Box<dyn std::error::Error>> {
main()
}