Skip to content

Truly independent web browser

LibWasm: Run compiled code in the runtime, tiering up hot functions

Andreas Kling8f28e19e695d
diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rs
index 912edfa6b86..3d4897f50b8 100644
--- a/AK/Rust/src/lib.rs
+++ b/AK/Rust/src/lib.rs
@@ -6,6 +6,7 @@
//! Rust views of shared AK data structures.
+pub mod perf_map;
mod scope_guard;
mod slice;
diff --git a/AK/Rust/src/perf_map.rs b/AK/Rust/src/perf_map.rs
new file mode 100644
index 00000000000..210fefa03ab
--- /dev/null
+++ b/AK/Rust/src/perf_map.rs
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The process's perf map, `/tmp/perf-PID.map`, which tells `perf` what generated code is where. Every code generator
+//! in the process writes it through here.
+
+use std::fs::OpenOptions;
+use std::io::Write;
+
+/// Appends a line for `size` bytes of code at `address` called `name` to the perf map.
+///
+/// NB: The line goes out in one write to a file opened for appending, so lines that threads write at the same time
+/// never interleave, whichever copy of this crate they go through, and no lock is needed.
+pub fn write_perf_map_entry(address: usize, size: usize, name: &str) -> std::io::Result<()> {
+ let line = format!("{address:x} {size:x} {name}\n");
+ let mut file = OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(format!("/tmp/perf-{}.map", std::process::id()))?;
+ let written = file.write(line.as_bytes())?;
+ if written != line.len() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::WriteZero,
+ "a short write to the perf map",
+ ));
+ }
+ Ok(())
+}
diff --git a/Cargo.lock b/Cargo.lock
index 860a6e49c60..3ee9b8d67cb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -834,6 +834,7 @@ dependencies = [
"flapc",
"ladybird_allocator",
"libc",
+ "libwasm_jit",
"libwasm_module",
"rustc-demangle",
]
diff --git a/Libraries/LibJS/Rust/src/jit/executable_memory.rs b/Libraries/LibJS/Rust/src/jit/executable_memory.rs
index 7644058a7c0..fa58f131d14 100644
--- a/Libraries/LibJS/Rust/src/jit/executable_memory.rs
+++ b/Libraries/LibJS/Rust/src/jit/executable_memory.rs
@@ -16,7 +16,6 @@
//! pages that hold other installed code is safe.
use core::cell::RefCell;
-use std::io::Write;
use std::rc::Rc;
const CHUNK_SIZE: usize = 4 * 1024 * 1024;
@@ -408,11 +407,8 @@ impl Drop for ExecutableMemory {
}
fn write_perf_map_entry(address: *const u8, size: usize, name: &str) {
- let path = format!("/tmp/perf-{}.map", std::process::id());
- let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(&path) else {
- eprintln!("LIBJS_JIT: Unable to open {path} for writing");
- return;
- };
let name = if name.is_empty() { "<anonymous>" } else { name };
- let _ = writeln!(file, "{:x} {size:x} JIT {name}", address as usize);
+ if ak::perf_map::write_perf_map_entry(address as usize, size, &format!("JIT {name}")).is_err() {
+ eprintln!("LIBJS_JIT: Unable to write /tmp/perf-{}.map", std::process::id());
+ }
}
diff --git a/Libraries/LibWasm/Engine/Cargo.toml b/Libraries/LibWasm/Engine/Cargo.toml
index 12ac45441da..9e8c400e8e7 100644
--- a/Libraries/LibWasm/Engine/Cargo.toml
+++ b/Libraries/LibWasm/Engine/Cargo.toml
@@ -12,6 +12,7 @@ crate-type = ["staticlib", "rlib"]
ak = { path = "../../../AK/Rust" }
ladybird_allocator = { path = "../../RustAllocator", optional = true }
libc = "0.2"
+libwasm_jit = { path = "../JIT" }
libwasm_module = { path = "../Module" }
rustc-demangle = "0.1"
diff --git a/Libraries/LibWasm/Engine/src/abi.rs b/Libraries/LibWasm/Engine/src/abi.rs
index 0c3a8996c67..519fe6e7b62 100644
--- a/Libraries/LibWasm/Engine/src/abi.rs
+++ b/Libraries/LibWasm/Engine/src/abi.rs
@@ -32,10 +32,12 @@
use std::mem::offset_of;
-/// The frame header. All fields are 8 bytes, at `fp + FRAME_*`.
-pub const FRAME_SAVED_FP: isize = -8;
+/// The frame header. All fields are 8 bytes, at `fp + FRAME_*`. Its first two words are where a native call and
+/// `push fp` leave the return address and the caller's fp, so that compiled frames have the same header.
+///
/// The caller's instruction pointer after its call instruction.
-pub const FRAME_RETURN_IP: isize = -16;
+pub const FRAME_RETURN_IP: isize = -8;
+pub const FRAME_SAVED_FP: isize = -16;
pub const FRAME_SAVED_STP: isize = -24;
/// The `FunctionHeader` of the function running in the frame.
pub const FRAME_FUNCTION: isize = -32;
@@ -58,6 +60,14 @@ pub const FUNCTION_KIND_WASM: u32 = 0;
pub const FUNCTION_KIND_HOST: u32 = 1;
/// A WebAssembly function with v128 parameters or locals, whose frame has storage for them.
pub const FUNCTION_KIND_WASM_VECTOR: u32 = 2;
+/// A WebAssembly function with compiled code, which runs at its `native_entry`.
+pub const FUNCTION_KIND_COMPILED: u32 = 3;
+
+/// What a call costs of the callee's tier-up budget.
+pub const TIER_UP_CALL_COST: u32 = 10;
+
+/// The pseudo-instruction compiled code traps through, with the trap code in the context's first argument.
+pub const OPCODE_TRAP_FROM_NATIVE: u8 = 0xef;
/// One function, as the interpreter sees it. Function references point at these.
#[repr(C)]
@@ -75,8 +85,9 @@ pub struct FunctionHeader {
pub local_count: u32,
/// The bytes of locals above fp, 16-byte aligned.
pub locals_size: u32,
- /// The padding that keeps the pointers below aligned.
- pub reserved: u32,
+ /// What the function may still run before the runtime is asked to compile it: calls cost TIER_UP_CALL_COST, loop
+ /// entries and back edges 1. The runtime gets the call or loop that would take it below zero.
+ pub tier_up_budget: u32,
/// The bytes below fp the frame needs, operand stack and red zone included.
pub frame_size: u32,
/// The store-wide identity of the function's type, equal exactly for equal types.
@@ -266,6 +277,8 @@ pub fn layout_constants() -> String {
constant("FUNCTION_KIND_WASM", FUNCTION_KIND_WASM as usize);
constant("FUNCTION_KIND_HOST", FUNCTION_KIND_HOST as usize);
constant("FUNCTION_KIND_WASM_VECTOR", FUNCTION_KIND_WASM_VECTOR as usize);
+ constant("FUNCTION_KIND_COMPILED", FUNCTION_KIND_COMPILED as usize);
+ constant("TIER_UP_CALL_COST", TIER_UP_CALL_COST as usize);
macro_rules! field {
($name:literal, $type:ty, $field:ident) => {
constant($name, offset_of!($type, $field));
@@ -282,6 +295,7 @@ pub fn layout_constants() -> String {
field!("FUNCTION_LOCALS_SIZE", FunctionHeader, locals_size);
field!("FUNCTION_VECTOR_STORAGE", FunctionHeader, vector_storage);
field!("FUNCTION_NATIVE_ENTRY", FunctionHeader, native_entry);
+ field!("FUNCTION_TIER_UP_BUDGET", FunctionHeader, tier_up_budget);
field!("FUNCTION_FRAME_SIZE", FunctionHeader, frame_size);
field!("FUNCTION_TYPE_IDENTITY", FunctionHeader, type_identity);
field!("FUNCTION_HOST", FunctionHeader, host);
diff --git a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs
index 4b9ae5393cf..bacdfb02d99 100644
--- a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs
@@ -58,6 +58,12 @@ fn interpreter_code_range() -> (usize, usize) {
)
}
+/// The handler of a primary opcode.
+#[cfg(wasm_interpreter)]
+pub fn dispatch_table_entry(opcode: u8) -> usize {
+ unsafe { wasm_interpreter_dispatch_table[usize::from(opcode)] }
+}
+
#[cfg(wasm_interpreter)]
fn memory_fault_handler() -> usize {
unsafe { wasm_interpreter_dispatch_table[MEMORY_FAULT_OPCODE] }
@@ -237,6 +243,9 @@ mod fault {
*pc = memory_fault_handler();
return;
}
+ if is_in_any_reservation(address) && crate::runtime::jit::redirect_fault(context) {
+ return;
+ }
forward(signal, info, context);
}
}
diff --git a/Libraries/LibWasm/Engine/src/runtime/jit.rs b/Libraries/LibWasm/Engine/src/runtime/jit.rs
new file mode 100644
index 00000000000..902884018ef
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/jit.rs
@@ -0,0 +1,961 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The runtime's side of the JIT (`libwasm_jit`): when functions are compiled, where their code lives, and the calls
+//! between compiled code and the rest of the runtime.
+//!
+//! - A function with compiled code has `FUNCTION_KIND_COMPILED` and its code at `native_entry`. Every other function
+//! has the runtime adapter there, through which compiled code calls it (`call_from_native`). The interpreter calls
+//! compiled functions through the entry trampoline (`call_compiled`).
+//! - Compiled code traps through the trap exit, which leaves the interpreter's innermost entry like a trap in the
+//! interpreter does. A memory access of compiled code that faults goes to the trap exit too.
+//! - Each store has its own code space; the trap exit, the trampoline and the adapter are the process's.
+//!
+//! - Hot functions compile on the process's compile threads while the interpreter keeps running them. The runtime
+//! installs finished code when the interpreter asks it again, which it does every few calls or loop iterations of a
+//! function whose compile is pending.
+//!
+//! `LIBWASM_JIT` configures it, as a comma-separated list: `off` (the default for now), `on` (tier up hot functions),
+//! `threshold=N` (tier up once calls and loop iterations cost N, 1000 by default), `forced` (tier up at the first call
+//! or loop), `eager` (compile every function when its module is instantiated), and `perf-map` (write
+//! `/tmp/perf-PID.map` for `perf`), `verify-ir` (check every compile's IR and register allocation), `stress-osr`
+//! (tier up at loops only, where they start, so that as many loops as can continue compiled), `sync` (compile on the
+//! thread that runs the code, as `forced` and `stress-osr` do too), and `threads=N` (the number of compile threads,
+//! one per processor core but one by default).
+
+use super::ranges::RangeSet;
+use super::{FunctionAddress, FunctionInstance, InstanceAddress, Store, Trap, Value};
+use crate::abi::ExecutionContext;
+use crate::types::ValType;
+use std::sync::OnceLock;
+
+/// The code of compiled functions and of the stubs, for the fault handler.
+pub static CODE_RANGES: RangeSet = RangeSet::new();
+
+#[derive(Debug, Default, Clone, Copy)]
+pub struct Options {
+ pub enabled: bool,
+ /// Compile every function when its module is instantiated.
+ pub eager: bool,
+ /// The tier-up budget of a function: compile it once calls (10 each) and loop iterations (1 each) used it up.
+ pub threshold: u32,
+ /// Write `/tmp/perf-PID.map`, which tells `perf` what code is where.
+ pub perf_map: bool,
+ /// Check the IR and the register allocation of every compile.
+ pub verify_ir: bool,
+ /// Tier up at loops only, at the first iteration, so that loops continue compiled (OSR) as often as they can.
+ pub stress_osr: bool,
+ /// Compile on the thread that runs the code, and run the code as soon as it is compiled.
+ pub sync: bool,
+ /// The number of compile threads, or 0 for one per processor core but one.
+ pub threads: u32,
+}
+
+impl Options {
+ fn compile_options(self) -> libwasm_jit::Options {
+ libwasm_jit::Options {
+ verify_ir: self.verify_ir,
+ ..libwasm_jit::Options::default()
+ }
+ }
+}
+
+pub fn options() -> Options {
+ static OPTIONS: OnceLock<Options> = OnceLock::new();
+ *OPTIONS.get_or_init(|| {
+ let mut options = Options {
+ threshold: DEFAULT_THRESHOLD,
+ ..Options::default()
+ };
+ if let Ok(value) = std::env::var("LIBWASM_JIT") {
+ for option in value.split(',') {
+ match option.trim() {
+ "off" => options.enabled = false,
+ "on" => options.enabled = true,
+ "eager" => {
+ options.enabled = true;
+ options.eager = true;
+ }
+ "forced" => {
+ options.enabled = true;
+ options.sync = true;
+ options.threshold = 0;
+ }
+ "sync" => options.sync = true,
+ "perf-map" => options.perf_map = true,
+ "verify-ir" => options.verify_ir = true,
+ "stress-osr" => {
+ options.enabled = true;
+ options.sync = true;
+ options.stress_osr = true;
+ options.threshold = 1;
+ }
+ other => {
+ if let Some(threshold) = other.strip_prefix("threshold=").and_then(|value| value.parse().ok()) {
+ options.enabled = true;
+ options.threshold = threshold;
+ } else if let Some(threads) =
+ other.strip_prefix("threads=").and_then(|value| value.parse().ok())
+ {
+ options.threads = threads;
+ }
+ }
+ }
+ }
+ }
+ options.enabled &= cfg!(all(unix, target_arch = "x86_64"));
+ options
+ })
+}
+
+/// Export the runtime functions compiled code and the interpreter call, under the names the interpreter calls them
+/// by, with the System V calling convention on every x86-64 target.
+macro_rules! export {
+ ($($symbol:ident => $function:ident),* $(,)?) => {
+ $(
+ /// # Safety
+ ///
+ /// Only the interpreter and compiled code call this, with the context of the store they run in.
+ #[cfg(all(target_arch = "x86_64", windows))]
+ #[unsafe(no_mangle)]
+ pub unsafe extern "sysv64" fn $symbol(context: *mut ExecutionContext) -> u64 {
+ unsafe { $function(context) }
+ }
+
+ /// # Safety
+ ///
+ /// Only the interpreter and compiled code call this, with the context of the store they run in.
+ #[cfg(not(all(target_arch = "x86_64", windows)))]
+ #[unsafe(no_mangle)]
+ pub unsafe extern "C" fn $symbol(context: *mut ExecutionContext) -> u64 {
+ unsafe { $function(context) }
+ }
+ )*
+ };
+}
+
+export! {
+ wasm_runtime_call_compiled => call_compiled,
+ wasm_runtime_call_from_native => call_from_native,
+ wasm_runtime_tier_up => tier_up,
+}
+
+/// Called when a function's tier-up budget runs out: `arguments[0]` is its header, and `arguments[2]` is 0 for a call
+/// and 1 for a loop, whose instruction `arguments[1]` points at, in the frame at `arguments[3]`. Compiles the function
+/// if the JIT is on, or has it compiled in the background. At a loop, continues the frame in compiled code if it can
+/// (OSR) and returns the top of the frame's operand stack with the results on it; returns 0 otherwise.
+unsafe fn tier_up(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let [header, pc, reason, frame, ..] = (*context).arguments;
+ let address = FunctionAddress::from_ptr(header as *const FunctionInstance);
+ let store = store_of(context);
+ if !options().enabled {
+ address.get_mut().header.tier_up_budget = u32::MAX;
+ return 0;
+ }
+ if options().stress_osr && reason == 0 {
+ // NB: The interpreter charges the call once this returns, which leaves nothing for the first loop.
+ address.get_mut().header.tier_up_budget = crate::abi::TIER_UP_CALL_COST;
+ return 0;
+ }
+ let at_loop = reason == 1;
+ // NB: The interpreter charges a call once this returns, so every budget covers that.
+ let state = native::compile_function(store, address);
+ address.get_mut().header.tier_up_budget = match state {
+ // A compiled function keeps a budget, so that frames of it still running in the interpreter continue
+ // compiled at their next outermost loop.
+ native::CompileState::Compiled => options().threshold.max(1) + crate::abi::TIER_UP_CALL_COST,
+ native::CompileState::Pending => POLL_BUDGET + crate::abi::TIER_UP_CALL_COST,
+ native::CompileState::Failed => u32::MAX,
+ };
+ if !at_loop || state == native::CompileState::Failed {
+ return 0;
+ }
+ match native::enter_at_loop(store, address, pc, frame) {
+ native::LoopEntry::Ran(top) => top,
+ native::LoopEntry::Pending => {
+ address.get_mut().header.tier_up_budget = POLL_BUDGET + crate::abi::TIER_UP_CALL_COST;
+ 0
+ }
+ native::LoopEntry::Never => 0,
+ }
+ }
+}
+
+/// The budget of a function whose compile is pending: how much it runs in the interpreter before the runtime looks
+/// for the compile's result again.
+const POLL_BUDGET: u32 = 500;
+
+unsafe fn store_of(context: *mut ExecutionContext) -> &'static mut Store {
+ unsafe { &mut *(*context).store.cast::<Store>() }
+}
+
+const DEFAULT_THRESHOLD: u32 = 1000;
+
+/// What `tier_up_budget` starts as in a new function's header. Without the JIT, the runtime is asked again only every
+/// few billion calls and loop iterations.
+pub fn initial_tier_up_budget() -> u32 {
+ let options = options();
+ if options.enabled && !options.eager {
+ options.threshold
+ } else {
+ u32::MAX
+ }
+}
+
+/// What `native_entry` starts as in a new function's header.
+pub fn initial_native_entry() -> u64 {
+ if !options().enabled {
+ return 0;
+ }
+ native::stubs().adapter
+}
+
+impl Store {
+ /// Keeps everything in this store interpreted, whatever `LIBWASM_JIT` says, as tests comparing the tiers want.
+ pub fn disable_jit(&mut self) {
+ self.jit.get_or_insert_with(Default::default).disabled = true;
+ }
+}
+
+/// Called once a module is instantiated, before its start function runs.
+pub fn instantiated(store: &mut Store, instance: InstanceAddress) {
+ if options().eager {
+ native::compile_instance(store, instance);
+ }
+}
+
+/// Redirects a memory fault in compiled code to the trap exit. `context` is the signal handler's.
+///
+/// # Safety
+///
+/// Only the fault handler calls this, with its context.
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+pub unsafe fn redirect_fault(context: *mut libc::c_void) -> bool {
+ unsafe {
+ let context = context.cast::<libc::ucontext_t>();
+ let registers = &mut (*context).uc_mcontext.gregs;
+ let pc = registers[libc::REG_RIP as usize] as usize;
+ let Some(stubs) = native::STUBS.get() else {
+ return false;
+ };
+ if !CODE_RANGES.contains(pc) {
+ return false;
+ }
+ registers[libc::REG_RIP as usize] = stubs.trap_exit as i64;
+ registers[libc::REG_RDI as usize] = i64::from(crate::abi::TRAP_MEMORY_OUT_OF_BOUNDS);
+ true
+ }
+}
+
+#[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
+pub unsafe fn redirect_fault(_context: *mut libc::c_void) -> bool {
+ false
+}
+
+/// Appends a line for code at `address` to the process's perf map.
+fn write_perf_map_entry(address: u64, size: usize, name: &str) {
+ let _ = ak::perf_map::write_perf_map_entry(address as usize, size, name);
+}
+
+/// The TRAP_* code a trap of the runtime continues as in the interpreter, which keeps the details in the store.
+fn trap_code(trap: &Trap) -> u32 {
+ use crate::abi::*;
+ match trap {
+ Trap::Unreachable => TRAP_UNREACHABLE,
+ Trap::StackExhausted => TRAP_STACK_EXHAUSTED,
+ Trap::MemoryOutOfBounds => TRAP_MEMORY_OUT_OF_BOUNDS,
+ Trap::IntegerDivideByZero => TRAP_INTEGER_DIVIDE_BY_ZERO,
+ Trap::IntegerOverflow => TRAP_INTEGER_OVERFLOW,
+ Trap::InvalidConversion => TRAP_INVALID_CONVERSION,
+ Trap::UndefinedElement => TRAP_UNDEFINED_ELEMENT,
+ Trap::UninitializedElement => TRAP_UNINITIALIZED_ELEMENT,
+ Trap::IndirectCallTypeMismatch => TRAP_INDIRECT_CALL_TYPE_MISMATCH,
+ Trap::TableOutOfBounds => TRAP_TABLE_OUT_OF_BOUNDS,
+ Trap::NullReference => TRAP_NULL_REFERENCE,
+ Trap::CastFailure => TRAP_CAST_FAILURE,
+ Trap::ArrayOutOfBounds => TRAP_ARRAY_OUT_OF_BOUNDS,
+ Trap::UnalignedAtomic => TRAP_UNALIGNED_ATOMIC,
+ Trap::ExpectedSharedMemory => TRAP_EXPECTED_SHARED_MEMORY,
+ Trap::Host(_) => TRAP_RUNTIME,
+ Trap::UncaughtException(_) => TRAP_UNCAUGHT_EXCEPTION,
+ }
+}
+
+/// The value of type `ty` in `words`, as compiled code holds it: zero-extended i32 values, f32 values in the low 32
+/// bits.
+fn value_from_words(ty: ValType, words: &[u64]) -> Value {
+ match ty {
+ ValType::I32 => Value::I32(words[0] as u32 as i32),
+ ValType::I64 => Value::I64(words[0] as i64),
+ ValType::F32 => Value::F32(words[0] as u32),
+ ValType::F64 => Value::F64(words[0]),
+ ValType::Ref(_) => Value::Ref(words[0]),
+ ValType::V128 => Value::V128(u128::from(words[0]) | (u128::from(words[1]) << 64)),
+ }
+}
+
+fn words_of_value(value: &Value, words: &mut [u64]) {
+ match *value {
+ Value::I32(value) => words[0] = u64::from(value as u32),
+ Value::I64(value) => words[0] = value as u64,
+ Value::F32(bits) => words[0] = u64::from(bits),
+ Value::F64(bits) | Value::Ref(bits) => words[0] = bits,
+ Value::V128(bits) => {
+ words[0] = bits as u64;
+ words[1] = (bits >> 64) as u64;
+ }
+ }
+}
+
+fn ir_types(types: &[ValType]) -> Vec<libwasm_jit::ir::Type> {
+ types
+ .iter()
+ .map(|ty| libwasm_jit::builder::ir_type(*ty).expect("the JIT has a type for every value"))
+ .collect()
+}
+
+/// Calls a compiled function from the interpreter: `arguments[0]` is its header and `arguments[1]` the top of the
+/// operand stack, where its arguments are. Replaces them with its results and returns the new top.
+unsafe fn call_compiled(context: *mut ExecutionContext) -> u64 {
+ unsafe { native::call_compiled(context) }
+}
+
+/// Calls a function that runs in the runtime from compiled code, through the runtime adapter: `arguments[0]` is its
+/// header, `arguments[1]` the adapter's save area, and `arguments[2]` the adapter's frame, above which the home
+/// slots of the arguments are. Returns 0 with the results in place, or a trap code, with the trap in the store.
+unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {
+ use libwasm_jit::convention::{self, Place};
+ unsafe {
+ let [header, save_area, frame, ..] = (*context).arguments;
+ let function = &*(header as *const FunctionInstance);
+ let ty = function.ty.clone();
+ let save_area = save_area as *mut u64;
+ let params = ir_types(&ty.params);
+ let mut places = Vec::new();
+ convention::parameter_places(&params, &mut places);
+ let (mut gprs, mut xmms) = (0, 0);
+ let mut arguments = Vec::with_capacity(params.len());
+ for (index, place) in places.iter().enumerate() {
+ let words = match *place {
+ Place::Register(_) if params[index].uses_xmm() => {
+ xmms += 1;
+ ak::slice_from_raw_parts(save_area.add(6 + 2 * (xmms - 1)), 2)
+ }
+ Place::Register(_) => {
+ gprs += 1;
+ ak::slice_from_raw_parts(save_area.add(gprs - 1), 1)
+ }
+ Place::Memory(slot) => {
+ ak::slice_from_raw_parts((frame as *const u64).add(slot as usize), params[index].slots() as usize)
+ }
+ };
+ arguments.push(value_from_words(ty.params[index], words));
+ }
+ let store = store_of(context);
+ let address = FunctionAddress::from_ptr(function);
+ let results = match store.invoke(address, &arguments) {
+ Ok(results) => results,
+ Err(trap) => {
+ let code = trap_code(&trap);
+ store.pending_trap = Some(trap);
+ return u64::from(code);
+ }
+ };
+ let result_types = ir_types(&ty.results);
+ convention::result_places(&result_types, &mut places);
+ let area = *(frame as *const u64).add(convention::result_area_pointer(&params) as usize) as *mut u64;
+ let (mut gprs, mut xmms) = (0, 0);
+ for (index, place) in places.iter().enumerate() {
+ let words = match *place {
+ Place::Register(_) if result_types[index].uses_xmm() => {
+ xmms += 1;
+ ak::slice_from_raw_parts_mut(save_area.add(6 + 2 * (xmms - 1)), 2)
+ }
+ Place::Register(_) => {
+ gprs += 1;
+ ak::slice_from_raw_parts_mut(save_area.add(gprs - 1), 1)
+ }
+ Place::Memory(slot) => {
+ ak::slice_from_raw_parts_mut(area.add(slot as usize), result_types[index].slots() as usize)
+ }
+ };
+ words_of_value(&results[index], words);
+ }
+ 0
+ }
+}
+
+#[cfg(all(unix, target_arch = "x86_64"))]
+mod native {
+ use super::{CODE_RANGES, ir_types, value_from_words, words_of_value};
+ use crate::abi::{ExecutionContext, FUNCTION_KIND_COMPILED, FunctionHeader, OPCODE_TRAP_FROM_NATIVE};
+ use crate::module::Module;
+ use crate::runtime::{FunctionAddress, FunctionInstance, FunctionKind, InstanceAddress, Store, helpers};
+ use libwasm_jit::convention::{self, Place};
+ use libwasm_jit::stubs::NativeCall;
+ use libwasm_jit::{CompileContext, CompileRequest, RuntimeInfo};
+ use std::collections::{HashMap, HashSet};
+ use std::sync::mpsc::{Receiver, Sender, channel};
+ use std::sync::{Arc, Mutex, OnceLock};
+
+ /// The code the process's stores share.
+ pub struct Stubs {
+ pub trap_exit: u64,
+ pub entry: u64,
+ pub adapter: u64,
+ pub runtime: RuntimeInfo,
+ }
+
+ pub static STUBS: OnceLock<Stubs> = OnceLock::new();
+
+ pub fn stubs() -> &'static Stubs {
+ STUBS.get_or_init(|| {
+ let handler = crate::runtime::interpreter::dispatch_table_entry(OPCODE_TRAP_FROM_NATIVE) as u64;
+ // NB: The trap exit goes first, so that the others can jump to it. The chunk is never freed.
+ let mut chunk = CodeChunk::new(64 * 1024);
+ let trap_exit = chunk.add(&libwasm_jit::stubs::trap_exit(handler));
+ let runtime = RuntimeInfo {
+ trap_exit,
+ memory_grow: helpers::wasm_runtime_memory_grow as *const () as u64,
+ table_grow: helpers::wasm_runtime_table_grow as *const () as u64,
+ call_host: helpers::wasm_runtime_call_host as *const () as u64,
+ };
+ let trampoline = libwasm_jit::stubs::entry_trampoline();
+ let entry = chunk.add(&trampoline);
+ let adapter_code =
+ libwasm_jit::stubs::runtime_adapter(super::wasm_runtime_call_from_native as *const () as u64, &runtime);
+ let adapter = chunk.add(&adapter_code);
+ if super::options().perf_map {
+ super::write_perf_map_entry(entry, trampoline.len(), "wasm-entry-trampoline");
+ super::write_perf_map_entry(adapter, adapter_code.len(), "wasm-runtime-adapter");
+ }
+ std::mem::forget(chunk);
+ Stubs {
+ trap_exit,
+ entry,
+ adapter,
+ runtime,
+ }
+ })
+ }
+
+ /// Executable memory, written while it is not executable.
+ struct CodeChunk {
+ base: *mut u8,
+ size: usize,
+ used: usize,
+ }
+
+ const PAGE_SIZE: usize = 4096;
+ const CHUNK_SIZE: usize = 16 << 20;
+
+ impl CodeChunk {
+ fn new(size: usize) -> Self {
+ let base = unsafe {
+ libc::mmap(
+ std::ptr::null_mut(),
+ size,
+ libc::PROT_READ | libc::PROT_EXEC,
+ libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,
+ -1,
+ 0,
+ )
+ };
+ assert_ne!(base, libc::MAP_FAILED, "no memory for compiled code");
+ assert!(
+ CODE_RANGES.add(base as usize, size),
+ "too much compiled code to fault in"
+ );
+ Self {
+ base: base.cast(),
+ size,
+ used: 0,
+ }
+ }
+
+ fn has_room(&self, length: usize) -> bool {
+ self.used.next_multiple_of(16) + length <= self.size
+ }
+
+ /// Copies `code` in and returns its address.
+ fn add(&mut self, code: &[u8]) -> u64 {
+ let start = self.used.next_multiple_of(16);
+ assert!(start + code.len() <= self.size);
+ let first_page = start / PAGE_SIZE * PAGE_SIZE;
+ let length = (start + code.len()).next_multiple_of(PAGE_SIZE) - first_page;
+ unsafe {
+ let region = self.base.add(first_page);
+ assert_eq!(
+ libc::mprotect(region.cast(), length, libc::PROT_READ | libc::PROT_WRITE),
+ 0
+ );
+ std::ptr::copy_nonoverlapping(code.as_ptr(), self.base.add(start), code.len());
+ assert_eq!(
+ libc::mprotect(region.cast(), length, libc::PROT_READ | libc::PROT_EXEC),
+ 0
+ );
+ }
+ self.used = start + code.len();
+ self.base as u64 + start as u64
+ }
+ }
+
+ impl Drop for CodeChunk {
+ fn drop(&mut self) {
+ CODE_RANGES.remove(self.base as usize);
+ unsafe { libc::munmap(self.base.cast(), self.size) };
+ }
+ }
+
+ /// What a compile is of: a function of a module (by its address, which the store keeps alive), and for an OSR
+ /// compile, the module offset of the loop it continues a frame at.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+ struct CompileKey {
+ module: usize,
+ function: u32,
+ osr: Option<u32>,
+ }
+
+ /// A compile a compile thread finished, for the store that asked for it.
+ struct Finished {
+ key: CompileKey,
+ code: Result<Vec<u8>, libwasm_jit::CompileFailure>,
+ }
+
+ struct Job {
+ key: CompileKey,
+ request: CompileRequest,
+ reply: Sender<Finished>,
+ }
+
+ /// The process's compile threads, which every store sends its compiles to. Each thread takes the oldest job no
+ /// other thread took yet, so jobs finish in any order.
+ struct CompileThreads {
+ jobs: Mutex<Sender<Job>>,
+ }
+
+ fn compile_threads() -> &'static CompileThreads {
+ static THREADS: OnceLock<CompileThreads> = OnceLock::new();
+ THREADS.get_or_init(|| {
+ let (jobs, receiver) = channel::<Job>();
+ let receiver = Arc::new(Mutex::new(receiver));
+ let count = match super::options().threads {
+ 0 => std::thread::available_parallelism().map_or(1, |cores| cores.get().saturating_sub(1).max(1)),
+ count => count as usize,
+ };
+ for index in 0..count {
+ let receiver = Arc::clone(&receiver);
+ let spawned = std::thread::Builder::new()
+ .name("LibWasm JIT".to_string())
+ .spawn(move || {
+ let mut context = CompileContext::default();
+ loop {
+ // NB: The lock is held only while waiting for a job, so the other threads compile
+ // meanwhile.
+ let job = receiver.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).recv();
+ let Ok(job) = job else {
+ return;
+ };
+ let code = libwasm_jit::compile(&mut context, &job.request).map(|compiled| compiled.code);
+ // NB: The store may be gone, and its results with it.
+ let _ = job.reply.send(Finished { key: job.key, code });
+ }
+ });
+ // NB: The JIT needs one thread. If the process cannot start more, it compiles on those it started.
+ if index == 0 {
+ spawned.expect("starting a WebAssembly compile thread");
+ } else if spawned.is_err() {
+ break;
+ }
+ }
+ CompileThreads { jobs: Mutex::new(jobs) }
+ })
+ }
+
+ /// Where a store's function is in compiling.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ pub enum CompileState {
+ Compiled,
+ Pending,
+ Failed,
+ }
+
+ /// What became of entering compiled code at a loop.
+ pub enum LoopEntry {
+ /// The frame ran to its end compiled; this is the top of its operand stack, with the results on it.
+ Ran(u64),
+ /// The code for the loop is still compiling.
+ Pending,
+ /// The frame cannot continue compiled at this loop.
+ Never,
+ }
+
+ /// A store's compiled code.
+ #[derive(Default)]
+ pub struct StoreJit {
+ chunks: Vec<CodeChunk>,
+ context: CompileContext,
+ /// The code of each compile, and the compiles that failed.
+ code: HashMap<CompileKey, u64>,
+ failed: HashSet<CompileKey>,
+ /// The compiles the compile threads have yet to finish, and where they send them.
+ pending: HashSet<CompileKey>,
+ finished: Option<(Sender<Finished>, Receiver<Finished>)>,
+ /// The modules of the keys, so that their addresses stay theirs.
+ modules: HashMap<usize, Arc<Module>>,
+ pub disabled: bool,
+ }
+
+ impl StoreJit {
+ fn add_code(&mut self, code: &[u8]) -> u64 {
+ if !self.chunks.last().is_some_and(|chunk| chunk.has_room(code.len())) {
+ self.chunks
+ .push(CodeChunk::new(CHUNK_SIZE.max(code.len().next_multiple_of(PAGE_SIZE))));
+ }
+ self.chunks.last_mut().expect("there is a chunk").add(code)
+ }
+
+ fn key(&mut self, module: &Arc<Module>, function: u32, osr: Option<u32>) -> CompileKey {
+ let address = Arc::as_ptr(module) as usize;
+ self.modules.entry(address).or_insert_with(|| module.clone());
+ CompileKey {
+ module: address,
+ function,
+ osr,
+ }
+ }
+
+ fn request(&self, key: CompileKey) -> CompileRequest {
+ CompileRequest {
+ module: self.modules[&key.module].clone(),
+ function: key.function,
+ runtime: stubs().runtime,
+ options: super::options().compile_options(),
+ osr: key.osr,
+ }
+ }
+
+ /// Installs the result of a compile.
+ fn finish(&mut self, key: CompileKey, code: Result<Vec<u8>, libwasm_jit::CompileFailure>) {
+ let Ok(code) = code else {
+ self.failed.insert(key);
+ return;
+ };
+ let entry = self.add_code(&code);
+ if super::options().perf_map {
+ let name = match key.osr {
+ None => format!("wasm-function-{}", key.function),
+ Some(offset) => format!("wasm-function-{}-osr-{offset}", key.function),
+ };
+ super::write_perf_map_entry(entry, code.len(), &name);
+ }
+ self.code.insert(key, entry);
+ }
+
+ /// Where the compile of `key` is, after compiling it here and now in sync mode, or else having it compiled
+ /// in the background.
+ fn compile(&mut self, key: CompileKey) -> CompileState {
+ if self.code.contains_key(&key) {
+ return CompileState::Compiled;
+ }
+ if self.failed.contains(&key) {
+ return CompileState::Failed;
+ }
+ if super::options().sync {
+ let request = self.request(key);
+ let code = libwasm_jit::compile(&mut self.context, &request).map(|compiled| compiled.code);
+ self.finish(key, code);
+ return self.compile(key);
+ }
+ if self.pending.insert(key) {
+ self.submit(key);
+ }
+ CompileState::Pending
+ }
+
+ fn submit(&mut self, key: CompileKey) {
+ let request = self.request(key);
+ let (reply, _) = self.finished.get_or_insert_with(channel);
+ let job = Job {
+ key,
+ request,
+ reply: reply.clone(),
+ };
+ compile_threads()
+ .jobs
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .send(job)
+ .expect("the compile threads run while the process does");
+ }
+
+ /// Installs what the compile threads finished; with `wait`, waits for every pending compile first.
+ fn take_finished(&mut self, wait: bool) {
+ let Some((_, receiver)) = &self.finished else {
+ return;
+ };
+ let mut finished = Vec::new();
+ if wait {
+ for _ in 0..self.pending.len() {
+ finished.push(receiver.recv().expect("the store holds a sender"));
+ }
+ } else {
+ finished.extend(receiver.try_iter());
+ }
+ for Finished { key, code } in finished {
+ self.pending.remove(&key);
+ self.finish(key, code);
+ }
+ }
+ }
+
+ pub fn install_finished(jit: &mut StoreJit) {
+ if !jit.pending.is_empty() {
+ jit.take_finished(false);
+ }
+ }
+
+ /// Compiles every function of an instance, on the compile threads unless in sync mode, and installs the code.
+ pub fn compile_instance(store: &mut Store, instance: InstanceAddress) {
+ let functions = store.instance(instance).functions.clone();
+ let jit = store.jit.get_or_insert_with(Default::default);
+ if jit.disabled {
+ return;
+ }
+ for address in &functions {
+ let function = unsafe { address.get() };
+ if let FunctionKind::Wasm { module, index, .. } = &function.kind {
+ let key = jit.key(module, *index, None);
+ jit.compile(key);
+ }
+ }
+ jit.take_finished(true);
+ for address in functions {
+ compile_function(store, address);
+ }
+ }
+
+ /// Compiles a WebAssembly function, unless the store compiled its module's function already, and installs the
+ /// code once there is some.
+ pub fn compile_function(store: &mut Store, address: FunctionAddress) -> CompileState {
+ let jit = store.jit.get_or_insert_with(Default::default);
+ if jit.disabled {
+ return CompileState::Failed;
+ }
+ install_finished(jit);
+ let function = unsafe { address.get_mut() };
+ let FunctionKind::Wasm { module, index, .. } = &function.kind else {
+ return CompileState::Failed;
+ };
+ let key = jit.key(module, *index, None);
+ let state = jit.compile(key);
+ if state == CompileState::Compiled {
+ function.header.native_entry = jit.code[&key];
+ function.header.kind = FUNCTION_KIND_COMPILED;
+ }
+ state
+ }
+
+ pub unsafe fn call_compiled(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let [header, top, ..] = (*context).arguments;
+ let function = &*(header as *const FunctionInstance);
+ let params = ir_types(&function.ty.params);
+ let parameter_slots = function.header.param_slots as usize;
+ // The operand stack grows down, so the first argument is in the highest slots, and the results replace
+ // the arguments.
+ let stack = top as *mut u64;
+ let arguments = |index: usize| {
+ let home = convention::home_slot(&params, index) as usize;
+ stack
+ .add(parameter_slots - home - params[index].slots() as usize)
+ .cast_const()
+ };
+ run(
+ function,
+ function.header.native_entry,
+ &params,
+ arguments,
+ stack.add(parameter_slots),
+ )
+ }
+ }
+
+ /// Calls `entry`, compiled code of `function` that takes arguments of types `params`, the `index`th of which
+ /// is at `argument(index)`. Stores the function's results on an operand stack ending at `end`, and returns its
+ /// new top. A trap leaves through the code and does not return.
+ unsafe fn run(
+ function: &FunctionInstance,
+ entry: u64,
+ params: &[libwasm_jit::ir::Type],
+ argument: impl Fn(usize) -> *const u64,
+ end: *mut u64,
+ ) -> u64 {
+ unsafe {
+ let header_data: &FunctionHeader = &function.header;
+ let results = ir_types(&function.ty.results);
+ let result_slots = header_data.result_slots as usize;
+ let mut call = NativeCall {
+ entry,
+ header: header_data as *const FunctionHeader as u64,
+ instance: header_data.instance as u64,
+ memory_base: (*header_data.instance).memory0_base as u64,
+ result_pointer_slot: u64::MAX,
+ ..NativeCall::default()
+ };
+ let parameter_slots = convention::slots(params) as usize;
+ let image_slots = (convention::outgoing_size(params, &results) / 8) as usize;
+ // NB: On the stack where it fits, since a trap leaves through compiled code and skips this frame, which
+ // leaks what it owns.
+ const SMALL_IMAGE: usize = 64;
+ let mut small_image = [0u64; SMALL_IMAGE];
+ let mut large_image = Vec::new();
+ let image = if image_slots <= SMALL_IMAGE {
+ small_image.as_mut_ptr()
+ } else {
+ large_image.resize(image_slots, 0);
+ large_image.as_mut_ptr()
+ };
+ let mut places = Vec::new();
+ convention::parameter_places(params, &mut places);
+ let (mut gprs, mut xmms) = (0, 0);
+ for (index, place) in places.iter().enumerate() {
+ let home = convention::home_slot(params, index) as usize;
+ let count = params[index].slots() as usize;
+ let source = argument(index);
+ std::ptr::copy_nonoverlapping(source, image.add(home), count);
+ if let Place::Register(_) = place {
+ if params[index].uses_xmm() {
+ call.xmms[xmms] = [*source, if count == 2 { *source.add(1) } else { 0 }];
+ xmms += 1;
+ } else {
+ call.gprs[gprs] = *source;
+ gprs += 1;
+ }
+ }
+ }
+ if convention::has_result_area(&results) {
+ call.result_pointer_slot = parameter_slots as u64;
+ }
+ call.image = image as u64;
+ call.image_slots = image_slots as u64;
+ let trampoline: extern "C" fn(*mut NativeCall) = std::mem::transmute(stubs().entry as usize);
+ trampoline(&raw mut call);
+ let return_top = end.sub(result_slots);
+ convention::result_places(&results, &mut places);
+ let (mut gprs, mut xmms) = (0, 0);
+ for (index, place) in places.iter().enumerate() {
+ let home = convention::home_slot(&results, index) as usize;
+ let count = results[index].slots() as usize;
+ let mut words = [0u64; 2];
+ match *place {
+ Place::Register(_) if results[index].uses_xmm() => {
+ words = call.result_xmms[xmms];
+ xmms += 1;
+ }
+ Place::Register(_) => {
+ words[0] = call.result_gprs[gprs];
+ gprs += 1;
+ }
+ Place::Memory(slot) => {
+ let area = image.add(parameter_slots + 1 + slot as usize);
+ words[..count].copy_from_slice(ak::slice_from_raw_parts(area, count));
+ }
+ }
+ // NB: Through a value, so that i32 and f32 results take their slot's low half only.
+ let value = value_from_words(function.ty.results[index], &words);
+ words_of_value(&value, &mut words);
+ // The first result is in the highest slots.
+ let destination = return_top.add(result_slots - home - count);
+ std::ptr::copy_nonoverlapping(words.as_ptr(), destination, count);
+ }
+ return_top as u64
+ }
+ }
+
+ /// Continues the interpreter frame at `frame`, of `address`, compiled at the loop at `pc` (OSR), once there is
+ /// code for that. It cannot be entered at a loop in another loop, or if the function does not compile.
+ pub unsafe fn enter_at_loop(store: &mut Store, address: FunctionAddress, pc: u64, frame: u64) -> LoopEntry {
+ unsafe {
+ let function = address.get();
+ let FunctionKind::Wasm { module, index, .. } = &function.kind else {
+ return LoopEntry::Never;
+ };
+ let offset = (pc - module.bytes.as_ptr() as u64) as u32;
+ let jit = store.jit.get_or_insert_with(Default::default);
+ if jit.disabled {
+ return LoopEntry::Never;
+ }
+ let key = jit.key(module, *index, Some(offset));
+ match jit.compile(key) {
+ CompileState::Compiled => {}
+ CompileState::Pending => return LoopEntry::Pending,
+ CompileState::Failed => return LoopEntry::Never,
+ }
+ let entry = jit.code[&key];
+ let params = [libwasm_jit::ir::Type::Pointer];
+ let base = (frame as *mut u8).sub(crate::abi::FRAME_HEADER_SIZE).cast::<u64>();
+ LoopEntry::Ran(run(function, entry, &params, |_| &raw const frame, base))
+ }
+ }
+}
+
+#[cfg(not(all(unix, target_arch = "x86_64")))]
+mod native {
+ use crate::abi::ExecutionContext;
+ use crate::runtime::{InstanceAddress, Store};
+
+ pub struct Stubs {
+ pub trap_exit: u64,
+ pub adapter: u64,
+ }
+
+ pub static STUBS: std::sync::OnceLock<Stubs> = std::sync::OnceLock::new();
+
+ pub fn stubs() -> &'static Stubs {
+ unreachable!("the JIT is off where it has no code generator")
+ }
+
+ #[derive(Default)]
+ pub struct StoreJit {
+ pub disabled: bool,
+ }
+
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ pub enum CompileState {
+ Compiled,
+ Pending,
+ Failed,
+ }
+
+ pub enum LoopEntry {
+ Ran(u64),
+ Pending,
+ Never,
+ }
+
+ pub fn compile_instance(_store: &mut Store, _instance: InstanceAddress) {}
+
+ pub fn compile_function(_store: &mut Store, _address: crate::runtime::FunctionAddress) -> CompileState {
+ CompileState::Failed
+ }
+
+ pub unsafe fn enter_at_loop(
+ _store: &mut Store,
+ _address: crate::runtime::FunctionAddress,
+ _pc: u64,
+ _frame: u64,
+ ) -> LoopEntry {
+ LoopEntry::Never
+ }
+
+ pub unsafe fn call_compiled(_context: *mut ExecutionContext) -> u64 {
+ unreachable!("the JIT is off where it has no code generator")
+ }
+}
+
+pub use native::StoreJit;
diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rs
index 2d5d6492e8b..65e2e0bc26a 100644
--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs
@@ -13,6 +13,7 @@ pub mod gc;
pub mod heap;
pub mod helpers;
pub mod interpreter;
+pub mod jit;
pub mod memory;
pub mod ranges;
@@ -339,6 +340,8 @@ pub struct Store {
pending_trap: Option<Trap>,
/// What runs after `memory.grow` grows a memory.
pub memory_grow_callback: Option<Rc<dyn Fn(MemoryAddress)>>,
+ /// The store's compiled code, once it has some.
+ jit: Option<jit::StoreJit>,
}
impl Default for Store {
@@ -388,6 +391,7 @@ impl Store {
root: None,
rtt_pointers: Vec::new(),
memory_grow_callback: None,
+ jit: None,
}
}
@@ -549,12 +553,12 @@ impl Store {
result_slots: ty.results.iter().map(|result| result.slot_count()).sum(),
local_count: 0,
locals_size: 0,
- reserved: 0,
+ tier_up_budget: jit::initial_tier_up_budget(),
frame_size: 0,
type_identity,
host: std::ptr::null(),
vector_storage: std::ptr::null(),
- native_entry: 0,
+ native_entry: jit::initial_native_entry(),
},
ty,
vector_storage: Box::new([]),
@@ -600,6 +604,7 @@ impl Store {
let instance = self.instantiate_without_starting(module, imports);
self.heap.undefer_gc();
let (instance, start) = instance?;
+ jit::instantiated(self, instance);
if let Some(start) = start {
self.invoke(start, &[]).map_err(InstantiationError::Trap)?;
}
@@ -795,7 +800,7 @@ impl Store {
result_slots: ty.results.iter().map(|result| result.slot_count()).sum(),
local_count,
locals_size,
- reserved: 0,
+ tier_up_budget: jit::initial_tier_up_budget(),
frame_size,
type_identity: instance.type_identities[type_index as usize],
host: std::ptr::null(),
@@ -804,7 +809,7 @@ impl Store {
} else {
std::ptr::null()
},
- native_entry: 0,
+ native_entry: jit::initial_native_entry(),
},
ty,
vector_storage,
diff --git a/Libraries/LibWasm/Interpreter/interpreter.flap b/Libraries/LibWasm/Interpreter/interpreter.flap
index 4d673e2ecca..60cf160872c 100644
--- a/Libraries/LibWasm/Interpreter/interpreter.flap
+++ b/Libraries/LibWasm/Interpreter/interpreter.flap
@@ -305,6 +305,19 @@ inline fn call_host_function(function: u64, return_ip: u64, context_pointer: u64
dispatch;
}
+# Call a function with compiled code, with its arguments on top of the operand stack. The runtime runs it and replaces
+# the arguments with its results; a trap in it leaves the interpreter from the compiled code.
+inline fn call_compiled_function(function: u64, return_ip: u64, context_pointer: u64) {
+ store64([context_pointer, CONTEXT_ARGUMENTS], function);
+ let top: u64 = vsp;
+ store64([context_pointer, CONTEXT_ARGUMENT_1], top);
+ # The helper may clobber every allocatable register, so nothing but its result is kept across it.
+ ip = return_ip;
+ let new_top: u64 = call_helper(wasm_runtime_call_compiled, context_pointer);
+ vsp = new_top;
+ dispatch;
+}
+
# Continue at the exception handler the runtime found, which it left in the context's arguments.
inline fn resume_at_handler() {
let context_pointer = context();
@@ -481,17 +494,44 @@ inline fn call_vector_function(function: u64, return_ip: u64, context_pointer: u
dispatch;
}
+# Call `function` with its arguments on top of the operand stack, continuing at `return_ip` when it returns: charge
+# its tier-up budget, then enter it.
+inline fn call_function(function: u64, return_ip: u64, context_pointer: u64) {
+ let mut callee: u64 = function;
+ let mut callee_return_ip: u64 = return_ip;
+ let mut callee_context: u64 = context_pointer;
+ let mut budget: u64;
+ load32(budget, [callee, FUNCTION_TIER_UP_BUDGET]);
+ if budget < TIER_UP_CALL_COST @cold {
+ # The runtime compiles the function, or not, and resets its budget. It may clobber every allocatable register,
+ # so the call's operands wait in the context.
+ store64([callee_context, CONTEXT_ARGUMENTS], callee);
+ store64([callee_context, CONTEXT_ARGUMENT_1], callee_return_ip);
+ store64([callee_context, CONTEXT_ARGUMENT_2], 0);
+ let _ignored: u64 = call_helper(wasm_runtime_tier_up, callee_context);
+ callee_context = context();
+ load64(callee, [callee_context, CONTEXT_ARGUMENTS]);
+ load64(callee_return_ip, [callee_context, CONTEXT_ARGUMENT_1]);
+ load32(budget, [callee, FUNCTION_TIER_UP_BUDGET]);
+ }
+ store32([callee, FUNCTION_TIER_UP_BUDGET], budget - TIER_UP_CALL_COST);
+ enter_function(callee, callee_return_ip, callee_context);
+}
+
# Enter `function` with its arguments on top of the operand stack, continuing at `return_ip` when it returns.
#
# OPTIMIZATION: The caller's state goes into the new frame's header as soon as the frame's address is known, so that
# its registers can be reused while the arguments are copied.
-inline fn call_function(function: u64, return_ip: u64, context_pointer: u64) {
+inline fn enter_function(function: u64, return_ip: u64, context_pointer: u64) {
let mut kind: u64;
load32(kind, [function, FUNCTION_KIND]);
if kind != FUNCTION_KIND_WASM @cold {
if kind == FUNCTION_KIND_HOST {
call_host_function(function, return_ip, context_pointer);
}
+ if kind == FUNCTION_KIND_COMPILED {
+ call_compiled_function(function, return_ip, context_pointer);
+ }
call_vector_function(function, return_ip, context_pointer);
}
let mut locals_size: u64;
@@ -756,6 +796,15 @@ handler MemoryFault() @opcode(0xf2) {
trap(TRAP_MEMORY_OUT_OF_BOUNDS);
}
+# Compiled code traps here, with fp the frame of the code that trapped, whose header has the context, and the trap
+# code in the context's first argument.
+handler TrapFromNative() @opcode(0xef) {
+ let context_pointer = context();
+ let mut code: u64;
+ load64(code, [context_pointer, CONTEXT_ARGUMENTS]);
+ trap_with(code, context_pointer);
+}
+
# Bytes that are no instruction. Validation rejects every one of them, so this is never reached.
handler Fallback() @fallback {
trap(TRAP_UNREACHABLE);
@@ -777,6 +826,28 @@ handler Block() @opcode(0x02) {
}
handler Loop() @opcode(0x03) {
+ let function = frame_word(FRAME_FUNCTION);
+ let mut budget: u64;
+ load32(budget, [function, FUNCTION_TIER_UP_BUDGET]);
+ if budget == 0 @cold {
+ let context_pointer = context();
+ store64([context_pointer, CONTEXT_ARGUMENTS], function);
+ let current: u64 = ip;
+ store64([context_pointer, CONTEXT_ARGUMENT_1], current);
+ store64([context_pointer, CONTEXT_ARGUMENT_2], 1);
+ let frame: u64 = fp;
+ store64([context_pointer, CONTEXT_ARGUMENT_3], frame);
+ # The runtime may run the rest of the function compiled from here (OSR), leaving its results on the operand
+ # stack.
+ let results_top: u64 = call_helper(wasm_runtime_tier_up, context_pointer);
+ if results_top != 0 {
+ vsp = results_top;
+ return_from_function();
+ }
+ let skipped = block_type_length(immediates());
+ advance(skipped + 1);
+ }
+ store32([function, FUNCTION_TIER_UP_BUDGET], budget - 1);
let length = block_type_length(immediates());
advance(length + 1);
}
diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.md
index 8959e5bb46a..e0911656461 100644
--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md
+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md
@@ -5,9 +5,11 @@ compiler's structure updates it. Where it and the code disagree, one of them has
The compiler is the `libwasm_jit` crate (`Libraries/LibWasm/JIT`). It is a pure compiler: it takes
one function of a validated module and returns machine code, touching no heap and no store, so it
-runs on any thread. Besides the compiler, the crate has what compiled code calls at run time: the
-functions for bulk operations (`runtime.rs`) and the host stubs (`stubs.rs`). The runtime side
-(tier-up, installing code, entering it) is not written yet.
+runs on any thread. It depends on the module format (`libwasm_module`, whose sources are the
+engine's), not on the engine, which depends on it. Besides the compiler, the crate has what compiled
+code calls at run time: the functions for bulk operations (`runtime.rs`), and the stubs the runtime
+enters and leaves compiled code through (`stubs.rs`). The engine's side is `runtime/jit.rs` (section
+10).
## 1. Overview
@@ -227,7 +229,7 @@ target's state, with phis replaced by their inputs.
are; every i32 operation is a 32-bit instruction, which zero-extends its result.
A compiled frame has fp = the caller's rsp at the call: the return address at fp - 8, the caller's
-fp at fp - 16 (the order the interpreter's frame headers will take, design section 6), the instance
+fp at fp - 16 (the order of the interpreter's frame headers too), the instance
at `FRAME_INSTANCE`, then the spill slots, and the outgoing area at rsp. After a call, rsp is
recomputed from fp, which also undoes whatever a callee's tail calls did to it.
@@ -280,7 +282,30 @@ there; a phi in a register with a slot is stored where its block starts.
it, both reached rip-relative, so the code is position independent. The runtime is reached
through absolute addresses.
-## 10. Testing
+## 10. The runtime
+
+The engine's `runtime/jit.rs` decides what is compiled, installs it, and connects compiled code with
+the interpreter and the host. `LIBWASM_JIT` configures it: `eager` compiles every function when its
+module is instantiated, `perf-map` writes `/tmp/perf-PID.map`. It is off otherwise for now.
+
+- **Installing** a function's code stores it in its header: `native_entry`, and the kind
+ `FUNCTION_KIND_COMPILED`. Code is per module function, so each store compiles a module's function
+ once for all its instances. Each store has its own code space of executable chunks.
+- **Interpreter to compiled.** The interpreter's `call_function` hands a compiled callee to the
+ runtime helper `wasm_runtime_call_compiled`, which reads the arguments off the operand stack and
+ calls the code through the entry trampoline (a `NativeCall`: registers, and an image of the home
+ slots and result area), then puts the results where the arguments were.
+- **Compiled to the rest.** Every other function's native entry is the runtime adapter, which saves
+ the argument registers and calls `wasm_runtime_call_from_native`. That runs the callee through
+ `Store::invoke` (a nested interpreter entry, or the host function) and puts the results into the
+ saved registers and result area, or returns a trap code, keeping the trap in the store.
+- **Traps.** The trap exit stores the code in the context's first argument and the context in the
+ trapping frame's header, then continues at the interpreter's TrapFromNative pseudo-instruction
+ (opcode 0xEF), which traps like the interpreter does: out of the innermost interpreter entry,
+ past the compiled frames and the helpers' frames. Memory faults in compiled code go to the trap
+ exit too: the fault handler knows the code spaces from a lock-free range set (`CODE_RANGES`).
+
+## 11. Testing
- `cargo test -p libwasm_jit`: unit tests, and the decoder and execution tests over the spec
testsuite's modules when the build directory has them.
@@ -290,7 +315,10 @@ there; a phi in a register with a slot is stored where its block starts.
the interpreter's. `tests/harness` has a session per thread: a code space whose start is the trap
exit, a trampoline per signature, host stubs, and a stub for functions that did not compile, which
traps with a code of its own; binding a module's instance points the engine's function headers at
- the code.
+ the code. With `--runtime`, the script calls go through `Store::invoke` instead, and the runtime
+ compiles what `LIBWASM_JIT` says (`eager` by default).
+- `examples/bench_check.rs` runs a module's entry in an interpreted store and a compiled one, with
+ deterministic imports, and compares results, exit codes, memories, tables and globals.
- `examples/smith_check.rs` does the same for random modules from `wasm-tools smith` in the subset
the JIT compiles, calling every exported function with random arguments.
- `examples/run_kernel.rs` times calls of one function, compiled or interpreted, for the run time
diff --git a/Libraries/LibWasm/JIT/examples/bench_check.rs b/Libraries/LibWasm/JIT/examples/bench_check.rs
new file mode 100644
index 00000000000..93dffb2dfab
--- /dev/null
+++ b/Libraries/LibWasm/JIT/examples/bench_check.rs
@@ -0,0 +1,199 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Runs a module's entry function in two stores, one interpreted and one where the runtime compiles every function
+//! (`LIBWASM_JIT=eager` unless set otherwise), and compares the results, traps, exit codes, memories, tables and
+//! globals afterwards. The imports are deterministic: WASI, with `clock_time_get` and `random_get` replaced by
+//! counters, and any other function import returns a clock in milliseconds of its result type, 100 * calls^2, so that
+//! both stores see the same. A case that runs longer than `--timeout SECONDS` (300) ends the process with a failure.
+//!
+//! ```text
+//! bench_check [--timeout SECONDS] MODULE ENTRY [MODULE ENTRY]...
+//! ```
+
+#[path = "../tests/harness/mod.rs"]
+mod harness;
+
+use harness::script::{outcome, same_outcome, state_difference};
+use libwasm_engine::module::ImportDescription;
+use libwasm_engine::runtime::{ExternValue, HostCallback, InstanceAddress, MemoryAddress, Store, Value};
+use libwasm_engine::types::ValType;
+use libwasm_engine::wasi::Wasi;
+use std::cell::Cell;
+use std::rc::Rc;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+struct Instance {
+ store: Store,
+ instance: InstanceAddress,
+ wasi: Rc<Wasi>,
+}
+
+fn instantiate(module: &Arc<libwasm_engine::Module>, interpreted: bool) -> Option<Instance> {
+ let mut store = Store::new();
+ if interpreted {
+ store.disable_jit();
+ }
+ let wasi = Rc::new(Wasi::new(vec!["bench".to_string()], Vec::new(), Vec::new()));
+ let memory: Rc<Cell<Option<MemoryAddress>>> = Rc::new(Cell::new(None));
+ let counter = Rc::new(Cell::new(0u64));
+ let mut imports = Vec::new();
+ for import in &module.imports {
+ let ImportDescription::Function(type_index) = import.description else {
+ eprintln!("{}.{}: only function imports are provided", import.module, import.name);
+ return None;
+ };
+ let ty = module.types[type_index as usize].as_func()?.clone();
+ let function = match (import.module.as_str(), import.name.as_str()) {
+ ("wasi_snapshot_preview1", "clock_time_get" | "random_get") => {
+ let (memory, counter, name) = (memory.clone(), counter.clone(), import.name.clone());
+ let callback: HostCallback = Rc::new(move |store: &mut Store, arguments: &[Value]| {
+ let Some(memory) = memory.get() else {
+ return Ok(vec![Value::I32(8)]);
+ };
+ let bytes = store.memory_mut(memory).bytes_mut();
+ let argument = |index: usize| match arguments[index] {
+ Value::I32(value) => value as u32 as usize,
+ _ => 0,
+ };
+ counter.set(counter.get() + 1_000_000);
+ if name == "clock_time_get" {
+ let at = argument(2);
+ bytes[at..at + 8].copy_from_slice(&counter.get().to_le_bytes());
+ } else {
+ for (offset, byte) in bytes[argument(0)..argument(0) + argument(1)].iter_mut().enumerate() {
+ *byte = offset as u8;
+ }
+ }
+ Ok(vec![Value::I32(0)])
+ });
+ store.allocate_host_function(ty, callback)
+ }
+ ("wasi_snapshot_preview1", name) => wasi.allocate_function(&mut store, name)?,
+ _ => {
+ let results = ty.results.clone();
+ let calls = Rc::new(Cell::new(0u64));
+ let callback: HostCallback = Rc::new(move |_: &mut Store, _: &[Value]| {
+ // NB: A clock that advances more with every call, so that a benchmark that runs until enough
+ // time has passed, like coremark, stops after a few rounds.
+ calls.set(calls.get() + 1);
+ let now = 100 * calls.get() * calls.get();
+ Ok(results
+ .iter()
+ .map(|result| match result {
+ ValType::I32 => Value::I32(now as i32),
+ ValType::I64 => Value::I64(now as i64),
+ ValType::F32 => Value::F32((now as f32).to_bits()),
+ ValType::F64 => Value::F64((now as f64).to_bits()),
+ other => Value::default_for(*other),
+ })
+ .collect())
+ });
+ store.allocate_host_function(ty, callback)
+ }
+ };
+ imports.push(ExternValue::Function(function));
+ }
+ let instance = match store.instantiate(module.clone(), &imports) {
+ Ok(instance) => instance,
+ Err(error) => {
+ eprintln!("instantiation failed: {error:?}");
+ return None;
+ }
+ };
+ if let Some(ExternValue::Memory(exported)) = store.instance(instance).export("memory") {
+ wasi.set_memory(exported);
+ memory.set(Some(exported));
+ }
+ Some(Instance { store, instance, wasi })
+}
+
+fn main() {
+ if std::env::var_os("LIBWASM_JIT").is_none() {
+ // SAFETY: Nothing else runs yet.
+ unsafe { std::env::set_var("LIBWASM_JIT", "eager") };
+ }
+ let mut arguments = std::env::args().skip(1).collect::<Vec<_>>();
+ let mut timeout = 300;
+ if arguments.first().is_some_and(|argument| argument == "--timeout") {
+ timeout = arguments[1].parse().expect("--timeout SECONDS");
+ arguments.drain(..2);
+ }
+ // A watchdog, so that a case that hangs cannot hold the machine.
+ static DEADLINE: AtomicU64 = AtomicU64::new(u64::MAX);
+ static CURRENT: Mutex<String> = Mutex::new(String::new());
+ std::thread::spawn(|| {
+ loop {
+ std::thread::sleep(Duration::from_secs(1));
+ let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
+ if now > DEADLINE.load(Ordering::Relaxed) {
+ println!("TIMEOUT {}", CURRENT.lock().unwrap());
+ std::process::exit(1);
+ }
+ }
+ });
+ let mut failures = 0;
+ for pair in arguments.chunks(2) {
+ let [path, entry] = pair else {
+ eprintln!("usage: bench_check MODULE ENTRY [MODULE ENTRY]...");
+ std::process::exit(2);
+ };
+ *CURRENT.lock().unwrap() = path.clone();
+ let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
+ DEADLINE.store(now + timeout, Ordering::Relaxed);
+ let bytes = std::fs::read(path).expect("the module can be read");
+ let module = Arc::new(libwasm_engine::compile(&bytes).expect("the module validates"));
+ let (Some(mut interpreted), Some(mut jit)) = (instantiate(&module, true), instantiate(&module, false)) else {
+ failures += 1;
+ continue;
+ };
+ let run = |instance: &mut Instance| {
+ let Some(ExternValue::Function(function)) = instance.store.instance(instance.instance).export(entry) else {
+ panic!("{path} exports no function {entry}");
+ };
+ let start = std::time::Instant::now();
+ let outcome = outcome(instance.store.invoke(function, &[]));
+ (outcome, start.elapsed())
+ };
+ let (expected, interpreted_time) = run(&mut interpreted);
+ let (actual, jit_time) = run(&mut jit);
+ let mut problems = Vec::new();
+ if !same_outcome(&expected, &actual) {
+ problems.push(format!("interpreter {expected:?}, JIT {actual:?}"));
+ }
+ if interpreted.wasi.exit_code() != jit.wasi.exit_code() {
+ problems.push(format!(
+ "exit codes {:?} and {:?}",
+ interpreted.wasi.exit_code(),
+ jit.wasi.exit_code()
+ ));
+ }
+ if let Some(difference) = state_difference(&interpreted.store, interpreted.instance, &jit.store, jit.instance) {
+ problems.push(difference);
+ }
+ let name = std::path::Path::new(path)
+ .file_name()
+ .unwrap()
+ .to_string_lossy()
+ .into_owned();
+ if problems.is_empty() {
+ println!(
+ "same {name} ({expected:?}, exit {:?}; {:.2} s interpreted, {:.2} s compiled)",
+ jit.wasi.exit_code(),
+ interpreted_time.as_secs_f64(),
+ jit_time.as_secs_f64()
+ );
+ } else {
+ failures += 1;
+ println!("DIFFERENT {name}: {}", problems.join("; "));
+ }
+ }
+ if failures > 0 {
+ std::process::exit(1);
+ }
+}
diff --git a/Libraries/LibWasm/JIT/examples/compile_all.rs b/Libraries/LibWasm/JIT/examples/compile_all.rs
index a6d1f28d233..ccbe3053cea 100644
--- a/Libraries/LibWasm/JIT/examples/compile_all.rs
+++ b/Libraries/LibWasm/JIT/examples/compile_all.rs
@@ -128,6 +128,7 @@ fn timed_compile(module: &Arc<libwasm_engine::Module>, functions: &[u32], thread
break;
};
let request = CompileRequest {
+ osr: None,
module: module.clone(),
function,
runtime: RUNTIME,
@@ -173,6 +174,7 @@ fn main() {
options.dump_ir = !arguments.quiet;
options.stats = true;
let request = CompileRequest {
+ osr: None,
module: module.clone(),
function,
runtime: RUNTIME,
@@ -207,6 +209,7 @@ fn main() {
let mut failures: BTreeMap<&'static str, usize> = BTreeMap::new();
for index in 0..module.code.len() as u32 {
let request = CompileRequest {
+ osr: None,
module: module.clone(),
function: first + index,
runtime: RUNTIME,
@@ -234,6 +237,7 @@ fn main() {
for run in 0..arguments.runs.max(1) {
for (position, &function) in compiled.iter().enumerate() {
let request = CompileRequest {
+ osr: None,
module: module.clone(),
function,
runtime: RUNTIME,
diff --git a/Libraries/LibWasm/JIT/examples/spec_check.rs b/Libraries/LibWasm/JIT/examples/spec_check.rs
index a3234263e9f..d3ba7afee1a 100644
--- a/Libraries/LibWasm/JIT/examples/spec_check.rs
+++ b/Libraries/LibWasm/JIT/examples/spec_check.rs
@@ -8,7 +8,7 @@
//! with the interpreter (see `tests/harness/script.rs`).
//!
//! ```text
-//! spec_check [--verbose] [--stress-registers] [--no-licm] [--gvn] DIRECTORY|SCRIPT.json...
+//! spec_check [--verbose] [--stress-registers] [--no-licm] [--gvn] [--runtime] DIRECTORY|SCRIPT.json...
//! ```
#[path = "../tests/harness/mod.rs"]
@@ -16,6 +16,7 @@ mod harness;
fn main() {
let mut verbose = false;
+ let mut runtime = false;
let mut paths = Vec::new();
let mut options = libwasm_jit::Options {
verify_ir: true,
@@ -27,10 +28,15 @@ fn main() {
"--stress-registers" => options.stress_registers = true,
"--no-licm" => options.no_licm = true,
"--gvn" => options.gvn = true,
+ "--runtime" => runtime = true,
_ => paths.push(argument),
}
}
- let totals = harness::script::run(&paths, verbose, options);
+ if runtime && std::env::var_os("LIBWASM_JIT").is_none() {
+ // SAFETY: Nothing else runs yet.
+ unsafe { std::env::set_var("LIBWASM_JIT", "eager") };
+ }
+ let totals = harness::script::run(&paths, verbose, options, runtime);
println!(
"{} scripts, {} modules, {} functions: {} compiled, {} runnable, {} exercised; {} cases, {} failures, {} reached uncompiled code",
totals.scripts,
diff --git a/Libraries/LibWasm/JIT/src/builder/mod.rs b/Libraries/LibWasm/JIT/src/builder/mod.rs
index 48674be8844..7ec43b557f1 100644
--- a/Libraries/LibWasm/JIT/src/builder/mod.rs
+++ b/Libraries/LibWasm/JIT/src/builder/mod.rs
@@ -173,6 +173,40 @@ pub struct Builder {
memory_base: Value,
/// The zero vector, which every v128 local starts as, once made.
vector_zero: Value,
+ /// What an OSR compile needs (see `build_osr`), or what probing for one found.
+ osr: Option<Osr>,
+}
+
+/// An OSR compile: the function as a continuation of an interpreter frame at an outermost loop.
+///
+/// Its only parameter is the frame's fp. Its entry block branches, on a constant, to a block that loads the frame's
+/// locals and operand stack and jumps to the loop's header, and to the function's code as it starts, which never
+/// runs. That keeps the entry block dominating everything. At the loop's header, every value on the operand stack
+/// becomes a phi of the two ways in, and the back edges.
+#[derive(Default)]
+struct Osr {
+ /// The module offset of the loop instruction.
+ pc: u32,
+ /// The types of the operand stack at the loop, from bottom to top, parameters included.
+ stack_types: Vec<Type>,
+ /// While probing: whether the loop was found, reachable and in no other loop.
+ found: bool,
+ probing: bool,
+ /// The block that loads the frame, the slot of its jump to the header, and the values it loaded from the
+ /// operand stack.
+ block: BlockId,
+ slot: u32,
+ stack: Vec<Value>,
+ loop_index: u32,
+ entry_edge: u32,
+ edge: u32,
+ /// The phis of the values below the loop's parameters: (phi, value from the start, value from the frame).
+ below: Vec<(Value, Value, Value)>,
+}
+
+/// The fp offset of the local slot `local` of an interpreter frame.
+fn frame_local_offset(local: u32) -> i32 {
+ 8 * local as i32
}
fn key(block: BlockId, local: u32) -> u64 {
@@ -214,6 +248,55 @@ impl Builder {
/// Builds the IR of the defined function `index` (counting imports) of `module` into `func`.
pub fn build(&mut self, module: &Module, index: u32, func: &mut Func) -> Result<(), CompileFailure> {
+ self.osr = None;
+ self.build_function(module, index, func)
+ }
+
+ /// The types of the operand stack at the loop at module offset `pc`, if it is reachable and in no other loop,
+ /// which an OSR compile needs. Builds the function into `func` to find out.
+ pub fn probe_osr(
+ &mut self,
+ module: &Module,
+ index: u32,
+ pc: u32,
+ func: &mut Func,
+ ) -> Result<Option<Vec<Type>>, CompileFailure> {
+ self.osr = Some(Osr {
+ pc,
+ probing: true,
+ ..Osr::default()
+ });
+ self.build_function(module, index, func)?;
+ let osr = self.osr.take().expect("the probe is there");
+ Ok(osr.found.then_some(osr.stack_types))
+ }
+
+ /// Builds the OSR compile of the function at the loop at `pc`, whose operand stack has `stack_types` there (see
+ /// `probe_osr`).
+ pub fn build_osr(
+ &mut self,
+ module: &Module,
+ index: u32,
+ pc: u32,
+ stack_types: Vec<Type>,
+ func: &mut Func,
+ ) -> Result<(), CompileFailure> {
+ self.osr = Some(Osr {
+ pc,
+ stack_types,
+ loop_index: NONE,
+ ..Osr::default()
+ });
+ let result = self.build_function(module, index, func);
+ self.osr = None;
+ result
+ }
+
+ fn is_osr_compile(&self) -> bool {
+ self.osr.as_ref().is_some_and(|osr| !osr.probing)
+ }
+
+ fn build_function(&mut self, module: &Module, index: u32, func: &mut Func) -> Result<(), CompileFailure> {
self.clear();
func.clear();
let defined = (index - module.imported_function_count) as usize;
@@ -242,14 +325,18 @@ impl Builder {
self.current.resize(self.local_types.len(), (NONE, NONE));
self.global_epochs.resize(module.global_space.len(), 0);
- let entry = self.new_block(func);
+ let mut entry = self.new_block(func);
self.start_block(func, entry);
self.sealed[entry as usize] = true;
self.instance = self.entry_value(func, Op::Instance, Type::Pointer, 0);
self.memory_base = self.entry_value(func, Op::MemoryBase, Type::Pointer, 0);
- for (param_index, &param) in func.params.clone().iter().enumerate() {
- let value = self.entry_value(func, Op::Param, param, param_index as u32);
- self.params.push(value);
+ if self.is_osr_compile() {
+ entry = self.enter_osr(func);
+ } else {
+ for (param_index, &param) in func.params.clone().iter().enumerate() {
+ let value = self.entry_value(func, Op::Param, param, param_index as u32);
+ self.params.push(value);
+ }
}
let results = self.push_types(&ty.results)?;
self.controls.push(Control {
@@ -283,6 +370,73 @@ impl Builder {
// Blocks.
+ /// Makes the entry of an OSR compile (see `Osr`) and returns the block the function's code starts in.
+ fn enter_osr(&mut self, func: &mut Func) -> BlockId {
+ let param_types = std::mem::take(&mut func.params);
+ func.params.push(Type::Pointer);
+ let frame = self.entry_value(func, Op::Param, Type::Pointer, 0);
+ // The function's own code never runs, but it must build as it would, so its parameters are not constants
+ // there.
+ for (local, &ty) in param_types.iter().enumerate() {
+ let indirect = u8::from(ty == Type::V128);
+ let value = Self::append(
+ func,
+ Node::new(
+ Op::FrameLoad,
+ ty,
+ indirect,
+ [frame, frame_local_offset(local as u32) as u32, 0],
+ ),
+ );
+ self.params.push(value);
+ }
+ let from_frame = self.new_block(func);
+ let start = self.new_block(func);
+ let always = self.constant(func, Type::I32, 1);
+ let entry = self.current_block;
+ self.terminate(
+ func,
+ Node::new(Op::Branch, Type::None, 0, [always, 0, 0]),
+ &[from_frame, start],
+ );
+ Self::set_predecessors(func, from_frame, &[entry]);
+ Self::set_predecessors(func, start, &[entry]);
+ self.start_block(func, from_frame);
+ for local in 0..self.local_types.len() as u32 {
+ let ty = self.local_types[local as usize];
+ let indirect = u8::from(ty == Type::V128);
+ let value = Self::append(
+ func,
+ Node::new(
+ Op::FrameLoad,
+ ty,
+ indirect,
+ [frame, frame_local_offset(local) as u32, 0],
+ ),
+ );
+ self.write_local(local, value);
+ }
+ let stack_types = std::mem::take(&mut self.osr.as_mut().expect("this is an OSR compile").stack_types);
+ let mut offset = -(libwasm_module::abi::FRAME_HEADER_SIZE as i32);
+ let mut stack = Vec::with_capacity(stack_types.len());
+ for &ty in &stack_types {
+ // The operand stack grows down from the frame header; a value's lowest slot is its first.
+ offset -= 8 * ty.slots() as i32;
+ stack.push(Self::append(
+ func,
+ Node::new(Op::FrameLoad, ty, 0, [frame, offset as u32, 0]),
+ ));
+ }
+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
+ let osr = self.osr.as_mut().expect("this is an OSR compile");
+ osr.block = from_frame;
+ osr.slot = slot;
+ osr.stack = stack;
+ osr.stack_types = stack_types;
+ self.start_block(func, start);
+ start
+ }
+
fn new_block(&mut self, func: &mut Func) -> BlockId {
let block = func.blocks.len() as BlockId;
let loop_index = self
@@ -592,7 +746,11 @@ impl Builder {
continue;
}
let loop_index = func.blocks[frame.block as usize].loop_index;
- if self.may_be_on_cycle(func, frame.block) && self.loop_writes.get(key(loop_index, local)).is_none() {
+ let osr_loop = self.osr.as_ref().map_or(NONE, |osr| osr.loop_index);
+ if self.may_be_on_cycle(func, frame.block)
+ && loop_index != osr_loop
+ && self.loop_writes.get(key(loop_index, local)).is_none()
+ {
// OPTIMIZATION: Everywhere in a loop that does not write the local, it has the value it entered
// the loop with. Reads after a loop would otherwise go around all of it.
let header = func.loops[loop_index as usize].header;
@@ -824,7 +982,18 @@ impl Builder {
}
I::Loop(block_type) => {
let (params, results) = self.block_signature(module, block_type)?;
+ let at_osr_loop = self.osr.as_ref().is_some_and(|osr| osr.pc == pc as u32);
+ if at_osr_loop && self.osr.as_ref().is_some_and(|osr| osr.probing) {
+ let outermost = !self.controls.iter().any(|control| control.kind == ControlKind::Loop);
+ let stack_types = self.stack.iter().map(|value| func.node(*value).ty).collect();
+ let osr = self.osr.as_mut().expect("probing");
+ osr.found = outermost;
+ osr.stack_types = stack_types;
+ }
self.begin_loop(func, params, results);
+ if at_osr_loop && self.is_osr_compile() {
+ self.enter_osr_loop(func);
+ }
}
I::If(block_type) => {
let (params, results) = self.block_signature(module, block_type)?;
@@ -946,7 +1115,14 @@ impl Builder {
self.call_indirect(func, module, type_index, table, CallKind::Tail, pc)?;
}
I::ReturnCallRef(type_index) => self.call_ref(func, module, type_index, CallKind::Tail, pc)?,
- I::Throw(_) | I::ThrowRef | I::TryTable(_) => return unsupported(pc, "exception handling"),
+ I::Throw(_)
+ | I::ThrowRef
+ | I::TryTable(_)
+ | I::Try(_)
+ | I::Catch(_)
+ | I::CatchAll
+ | I::Delegate(_)
+ | I::Rethrow(_) => return unsupported(pc, "exception handling"),
I::TableGet(table) => self.table_get(func, table),
I::TableSet(table) => self.table_set(func, table),
I::RefNull(_) => {
@@ -1163,6 +1339,42 @@ impl Builder {
self.call_epoch += 1;
}
+ /// Makes the loop just begun the one an OSR compile enters (see `Osr`).
+ fn enter_osr_loop(&mut self, func: &mut Func) {
+ let index = self.controls.len() - 1;
+ let control = self.controls[index];
+ let header = control.block;
+ let height = control.height as usize;
+ let mut osr = self.osr.take().expect("this is an OSR compile");
+ func.successors[osr.slot as usize] = header;
+ // The edge from the frame comes second, after the one from the function's start and before every back edge.
+ let values = self.edge_values.len() as u32;
+ self.edge_values.extend_from_slice(&osr.stack[height..]);
+ osr.entry_edge = control.edges;
+ self.edges.push(Edge {
+ block: osr.block,
+ slot: NONE,
+ values,
+ next: control.edges,
+ });
+ osr.edge = self.edges.len() as u32 - 1;
+ self.controls[index].edges = osr.edge;
+ osr.loop_index = control.loop_index;
+ for position in 0..height {
+ let normal = Self::resolve(func, self.stack[position]);
+ let phi = Self::new_phi(func, header, func.node(normal).ty);
+ osr.below.push((phi, normal, osr.stack[position]));
+ self.stack[position] = phi;
+ }
+ self.osr = Some(osr);
+ // Nothing numbered before the loop dominates the code after it any more. Every construct still open forgets
+ // what is numbered from here on when it ends, the loop included.
+ self.unnumber(0);
+ for control in &mut self.controls {
+ control.numbering_mark = 0;
+ }
+ }
+
fn begin_if(&mut self, func: &mut Func, params: (u32, u32), results: (u32, u32)) {
let condition = Self::resolve(func, self.pop());
let then_block = self.new_block(func);
@@ -1344,6 +1556,26 @@ impl Builder {
}
Self::try_remove_trivial_phi(func, phi);
}
+ if let Some(osr) = &self.osr
+ && osr.loop_index == control.loop_index
+ && control.loop_index != NONE
+ {
+ for &(phi, normal, from_frame) in &osr.below {
+ let start = func.operands.len() as u32;
+ for &edge in &self.scratch_values {
+ let value = if edge == osr.entry_edge {
+ normal
+ } else if edge == osr.edge {
+ from_frame
+ } else {
+ phi
+ };
+ func.operands.push(value);
+ }
+ func.nodes[phi as usize].args[0] = start;
+ func.nodes[phi as usize].args[1] = self.scratch_values.len() as u32;
+ }
+ }
for &phi in param_phis {
Self::try_remove_trivial_phi(func, phi);
}
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/memory.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/memory.rs
index 33c0708deec..4563cab9f89 100644
--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/memory.rs
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/memory.rs
@@ -91,6 +91,20 @@ impl CodeGenerator<'_> {
};
self.store(stored, b, size, &address);
}
+ Op::FrameLoad => {
+ let mut address = Address::new(gpr(a), node.args[1] as i32);
+ if node.flags == 1 {
+ self.asm.mov_rm(Width::W64, SCRATCH, &address);
+ address = Address::new(SCRATCH, 0);
+ }
+ if node.ty == Type::V128 {
+ self.load_vector(fpr(output).0, &address);
+ } else if node.ty.is_float() {
+ self.asm.vmovs_rm(precision(node.ty), fpr(output), &address);
+ } else {
+ self.asm.mov_rm(width(node.ty), gpr(output), &address);
+ }
+ }
Op::InstanceField | Op::LoadPointer => {
let address = Address::new(gpr(a), node.args[1] as i32);
self.asm.mov_rm(Width::W64, gpr(output), &address);
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs
index 442862b02d9..70c1c438c45 100644
--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs
@@ -636,7 +636,13 @@ impl<'a> CodeGenerator<'a> {
let node = self.func.node(value);
match node.op {
op if op.is_terminator() => self.lower_terminator(value),
- Op::Load | Op::Store | Op::GlobalGet | Op::GlobalSet | Op::InstanceField | Op::LoadPointer => {
+ Op::Load
+ | Op::Store
+ | Op::GlobalGet
+ | Op::GlobalSet
+ | Op::InstanceField
+ | Op::LoadPointer
+ | Op::FrameLoad => {
self.lower_memory(value);
}
Op::Call | Op::CallResult => self.lower_call(value),
diff --git a/Libraries/LibWasm/JIT/src/convention.rs b/Libraries/LibWasm/JIT/src/convention.rs
index 8e0a900b92a..634c7072f8f 100644
--- a/Libraries/LibWasm/JIT/src/convention.rs
+++ b/Libraries/LibWasm/JIT/src/convention.rs
@@ -30,8 +30,8 @@
//! rsp outgoing area of calls, 8 bytes per argument (and result area pointer, and result area)
//! ```
//!
-//! fp is the caller's rsp at the call. The header's first two words are the reverse of the interpreter's current
-//! frames; the interpreter moves to this order before compiled code runs in its frames (design, section 6).
+//! fp is the caller's rsp at the call, and the header is the interpreter's: its first two words are where the call and
+//! `push rbp` put them.
use crate::ir::Type;
@@ -126,8 +126,8 @@ pub fn is_fpr(register: Register) -> bool {
}
/// The frame header, as offsets from fp (see the module documentation).
-pub const FRAME_RETURN_ADDRESS: i32 = -8;
-pub const FRAME_SAVED_FP: i32 = -16;
+pub const FRAME_RETURN_ADDRESS: i32 = libwasm_module::abi::FRAME_RETURN_IP as i32;
+pub const FRAME_SAVED_FP: i32 = libwasm_module::abi::FRAME_SAVED_FP as i32;
pub const FRAME_INSTANCE: i32 = libwasm_module::abi::FRAME_INSTANCE as i32;
pub const FRAME_HEADER_SIZE: i32 = libwasm_module::abi::FRAME_HEADER_SIZE as i32;
diff --git a/Libraries/LibWasm/JIT/src/decode.rs b/Libraries/LibWasm/JIT/src/decode.rs
index b2b6c6259d5..833a2035302 100644
--- a/Libraries/LibWasm/JIT/src/decode.rs
+++ b/Libraries/LibWasm/JIT/src/decode.rs
@@ -66,6 +66,13 @@ pub enum Instruction {
ThrowRef,
/// A `try_table`, whose catch clauses the decoder skipped.
TryTable(BlockType),
+ /// The legacy exception handling instructions: `try`, `catch` and its tag, `catch_all`, `delegate` and its
+ /// label, and `rethrow` and its label.
+ Try(BlockType),
+ Catch(u32),
+ CatchAll,
+ Delegate(u32),
+ Rethrow(u32),
Drop,
Select,
SelectTyped(ValType),
@@ -387,6 +394,11 @@ impl<'a> Decoder<'a> {
opcode::RETURN_CALL_REF => Instruction::ReturnCallRef(self.u32()),
opcode::THROW => Instruction::Throw(self.u32()),
opcode::THROW_REF => Instruction::ThrowRef,
+ opcode::TRY => Instruction::Try(self.block_type()),
+ opcode::CATCH => Instruction::Catch(self.u32()),
+ opcode::CATCH_ALL => Instruction::CatchAll,
+ opcode::DELEGATE => Instruction::Delegate(self.u32()),
+ opcode::RETHROW => Instruction::Rethrow(self.u32()),
opcode::TRY_TABLE => {
let block_type = self.block_type();
let count = self.u32();
@@ -578,8 +590,13 @@ impl<'a> Decoder<'a> {
/// How an instruction changes the nesting of blocks: +1 for those that open one, -1 for `end`.
pub fn nesting_change(instruction: &Instruction) -> i32 {
match instruction {
- Instruction::Block(_) | Instruction::Loop(_) | Instruction::If(_) | Instruction::TryTable(_) => 1,
- Instruction::End => -1,
+ Instruction::Block(_)
+ | Instruction::Loop(_)
+ | Instruction::If(_)
+ | Instruction::TryTable(_)
+ | Instruction::Try(_) => 1,
+ // NB: `catch` and `catch_all` continue the `try` they are in, like `else`.
+ Instruction::End | Instruction::Delegate(_) => -1,
_ => 0,
}
}
diff --git a/Libraries/LibWasm/JIT/src/ir/dump.rs b/Libraries/LibWasm/JIT/src/ir/dump.rs
index f91c7a77fd2..1a9d4c9871e 100644
--- a/Libraries/LibWasm/JIT/src/ir/dump.rs
+++ b/Libraries/LibWasm/JIT/src/ir/dump.rs
@@ -64,6 +64,7 @@ pub fn node_text(func: &Func, value: Value) -> String {
write!(text, " function {}", node.args[2]).unwrap();
}
Op::Offset | Op::ReadField => write!(text, " +{}", node.args[1]).unwrap(),
+ Op::FrameLoad => write!(text, " {:+}", node.args[1] as i32).unwrap(),
Op::WriteField => write!(text, " +{}", node.args[2]).unwrap(),
Op::Helper => write!(text, " {}", crate::ir::Helper::from_index(node.args[2]).name()).unwrap(),
Op::CallResult => write!(text, " v{} #{}", node.args[0], node.args[1]).unwrap(),
diff --git a/Libraries/LibWasm/JIT/src/ir/mod.rs b/Libraries/LibWasm/JIT/src/ir/mod.rs
index fb8b9fc576d..128191f10e5 100644
--- a/Libraries/LibWasm/JIT/src/ir/mod.rs
+++ b/Libraries/LibWasm/JIT/src/ir/mod.rs
@@ -526,6 +526,9 @@ ops! {
/// args: pointer, byte offset. The address that far from the pointer.
Offset: Fixed(1), Pure, "offset";
+ /// args: an interpreter frame's fp, byte offset (a signed 32-bit value); flags: 1 for a v128 local, whose slot
+ /// has the address of its storage. A local or operand stack value of the frame an OSR compile continues.
+ FrameLoad: Fixed(1), Read, "frame_load";
/// args: pointer, byte offset; flags: the bytes it reads, 4 or 8. A field of runtime data that may change, like
/// the size of a memory or table, read where it is.
ReadField: Fixed(1), Read, "read_field";
diff --git a/Libraries/LibWasm/JIT/src/ir/verify.rs b/Libraries/LibWasm/JIT/src/ir/verify.rs
index c49bf6a557a..8a2df32dd1d 100644
--- a/Libraries/LibWasm/JIT/src/ir/verify.rs
+++ b/Libraries/LibWasm/JIT/src/ir/verify.rs
@@ -258,6 +258,7 @@ fn check_types(func: &Func, value: Value, error: &mut impl FnMut(String)) {
| Op::GlobalGet
| Op::GlobalSet
| Op::Offset
+ | Op::FrameLoad
| Op::ReadField
| Op::WriteField => input_type(0) == Type::Pointer,
Op::TableElement => input_type(0) == Type::Pointer && node.ty == Type::Ref,
diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rs
index 2d6bebc0331..f5d605e5afc 100644
--- a/Libraries/LibWasm/JIT/src/lib.rs
+++ b/Libraries/LibWasm/JIT/src/lib.rs
@@ -78,6 +78,9 @@ pub struct CompileRequest {
pub function: u32,
pub runtime: RuntimeInfo,
pub options: Options,
+ /// For an OSR compile, the module offset of the outermost loop that it continues an interpreter frame at. Its
+ /// code takes the frame's fp as its only argument and returns the function's results.
+ pub osr: Option<u32>,
}
/// The reusable state of one compile thread: every phase's storage, cleared between compiles.
@@ -148,7 +151,23 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result
last = now;
}
};
- context.builder.build(module, request.function, &mut context.func)?;
+ match request.osr {
+ None => context.builder.build(module, request.function, &mut context.func)?,
+ Some(pc) => {
+ let Some(stack_types) = context
+ .builder
+ .probe_osr(module, request.function, pc, &mut context.func)?
+ else {
+ return Err(CompileFailure::Unsupported {
+ pc,
+ what: "OSR at a loop that is unreachable or in another loop",
+ });
+ };
+ context
+ .builder
+ .build_osr(module, request.function, pc, stack_types, &mut context.func)?;
+ }
+ }
lap(0, &mut stats);
if request.options.verify_ir
&& let Err(errors) = ir::verify::verify(&context.func, &|_| false, false)
@@ -160,7 +179,9 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result
);
}
passes::cleanup::cleanup(&mut context.func, &mut context.liveliness);
- if request.options.no_licm {
+ // NB: The loop an OSR compile enters has two ways in, so it has no preheader to hoist into.
+ let no_licm = request.options.no_licm || request.osr.is_some();
+ if no_licm {
context.licm.home.clear();
context.licm.home.resize(context.func.nodes.len(), ir::NONE);
} else {
@@ -217,11 +238,7 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result
stats.nodes = context.func.nodes.len() as u32;
stats.slots = context.allocation.slot_count;
stats.moves = context.allocation.moves.len() as u32;
- stats.hoisted = if request.options.no_licm {
- 0
- } else {
- context.licm.hoisted
- };
+ stats.hoisted = if no_licm { 0 } else { context.licm.hoisted };
stats.eliminated = if request.options.gvn { context.gvn.eliminated } else { 0 };
let mut compiled = CompiledFunction {
code: generated.code,
diff --git a/Libraries/LibWasm/JIT/src/regalloc/mod.rs b/Libraries/LibWasm/JIT/src/regalloc/mod.rs
index 4b9c4c9b768..fa3d31c2ae6 100644
--- a/Libraries/LibWasm/JIT/src/regalloc/mod.rs
+++ b/Libraries/LibWasm/JIT/src/regalloc/mod.rs
@@ -563,8 +563,15 @@ impl Allocator {
}
}
self.place_phis(func, allocation, block, entry, &mut state);
- let slot = edge_slot(func, entry, block);
- self.edge_moves(func, allocation, entry, block, slot, &state);
+ // NB: Every forward edge gets its moves here: the entry's, and an OSR compile's second way in. The back
+ // edges get theirs where their blocks end.
+ for index in 0..predecessors.len() {
+ let predecessor = func.predecessors(block)[index];
+ if predecessor < block {
+ let slot = edge_slot(func, predecessor, block);
+ self.edge_moves(func, allocation, predecessor, block, slot, &state);
+ }
+ }
self.header_states[loop_index as usize] = state;
self.set_contents(state);
return;
diff --git a/Libraries/LibWasm/JIT/src/stubs.rs b/Libraries/LibWasm/JIT/src/stubs.rs
index 66b047b2938..36a9ee8c282 100644
--- a/Libraries/LibWasm/JIT/src/stubs.rs
+++ b/Libraries/LibWasm/JIT/src/stubs.rs
@@ -4,17 +4,25 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! Code that is not a compiled function but is called like one. A host function's `native_entry` is the host stub of
-//! its signature, which lays the arguments out as the interpreter's operand stack would hold them, calls the host
-//! function through the runtime's `wasm_runtime_call_host` like the interpreter does, and returns its results under the compiled
-//! convention.
+//! Code around compiled functions, which the runtime makes once per process:
+//!
+//! - The trap exit, which compiled code jumps to with a TRAP_* code in edi. It leaves the code through the
+//! interpreter's TrapFromNative handler, which returns from the interpreter's innermost entry with the trap.
+//! - The entry trampoline, through which the runtime calls compiled code: an `extern "C"` function of a
+//! `NativeCall`, whose registers and home slot image it loads.
+//! - The runtime adapter, the native entry of functions that run in the runtime (interpreted and host functions):
+//! it saves the argument registers and calls a function of the runtime with them, the callee's header and the
+//! frame, which puts the results where they go or returns a trap code.
+//!
+//! A host stub, of a signature, calls a host function through `wasm_runtime_call_host` directly, for the tests that
+//! run compiled code without the runtime.
use crate::RuntimeInfo;
use crate::asm::x86_64::{Assembler, Cond, Precision, VexMap, VexOpcode, VexOperand, VexPrefix};
use crate::asm::{Address, Fpr, Gpr, Width};
use crate::convention::{self, Place, Register};
use crate::ir::Type;
-use libwasm_module::abi::{ExecutionContext, InstanceData, TRAP_RUNTIME, TRAP_STACK_EXHAUSTED};
+use libwasm_module::abi::{ExecutionContext, FRAME_CONTEXT, InstanceData, TRAP_RUNTIME, TRAP_STACK_EXHAUSTED};
use std::mem::offset_of;
const VMOVUPS_LOAD: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x10);
@@ -176,3 +184,227 @@ pub fn host_stub(params: &[Type], results: &[Type], runtime: &RuntimeInfo) -> Ve
}
asm.finish().expect("stubs have no unbound labels")
}
+
+/// What the entry trampoline calls compiled code with, and what it returns.
+#[repr(C)]
+#[derive(Debug, Default)]
+pub struct NativeCall {
+ /// The code to call: the callee's `native_entry`, or the entry of an OSR compile.
+ pub entry: u64,
+ pub header: u64,
+ pub instance: u64,
+ pub memory_base: u64,
+ /// The integer argument registers, in `convention::GPR_ARGUMENTS` order.
+ pub gprs: [u64; 6],
+ /// The vector argument registers, low half first.
+ pub xmms: [[u64; 2]; 8],
+ /// The home slots of the call, and a result area if it needs one: copied to the outgoing area before the
+ /// call, and back after it.
+ pub image: u64,
+ pub image_slots: u64,
+ /// The slot of the result area pointer in the image, or u64::MAX.
+ pub result_pointer_slot: u64,
+ /// rax and rdx after the call.
+ pub result_gprs: [u64; 2],
+ /// xmm0 and xmm1 after the call.
+ pub result_xmms: [[u64; 2]; 2],
+ /// Where the trampoline keeps its stack pointer during the call.
+ pub saved_sp: u64,
+}
+
+/// The size of the area the runtime adapter saves the argument registers in: the six integer ones, then the eight
+/// vector ones, 16 bytes each. The runtime function stores the results' registers in the same places: rax and rdx
+/// where rdi and rsi were, xmm0 and xmm1 where they were.
+pub const ADAPTER_SAVE_AREA: usize = 6 * 8 + 8 * 16;
+
+fn gpr(register: Register) -> Gpr {
+ Gpr(register)
+}
+
+fn field(offset: usize) -> i32 {
+ offset as i32
+}
+
+/// The trap exit: stores the code in edi as the context's first argument, and the context in the frame that
+/// trapped, and continues at the interpreter's TrapFromNative handler at `handler`.
+pub fn trap_exit(handler: u64) -> Vec<u8> {
+ let mut asm = Assembler::new();
+ let context = gpr(convention::RAX);
+ asm.mov_rm(Width::W64, context, &Address::new(FP, convention::FRAME_INSTANCE));
+ asm.mov_rm(
+ Width::W64,
+ context,
+ &Address::new(context, field(offset_of!(InstanceData, context))),
+ );
+ asm.mov_mr(Width::W64, &Address::new(FP, FRAME_CONTEXT as i32), context);
+ asm.mov_mr(
+ Width::W64,
+ &Address::new(context, field(offset_of!(ExecutionContext, arguments))),
+ gpr(convention::RDI),
+ );
+ asm.mov_ri(SCRATCH, handler);
+ asm.jmp_r(SCRATCH);
+ asm.finish().expect("stubs have no unbound labels")
+}
+
+/// Copies `count` 8-byte words from `from` up to `to` through `temp`, clobbering all four.
+fn copy_words(asm: &mut Assembler, from: Gpr, to: Gpr, count: Gpr, temp: Gpr) {
+ let done = asm.new_label();
+ let again = asm.new_label();
+ asm.test_rr(Width::W64, count, count);
+ asm.jcc(Cond::Equal, done);
+ asm.bind(again);
+ asm.mov_rm(Width::W64, temp, &Address::new(from, 0));
+ asm.mov_mr(Width::W64, &Address::new(to, 0), temp);
+ asm.add_ri(Width::W64, from, 8);
+ asm.add_ri(Width::W64, to, 8);
+ asm.sub_ri(Width::W64, count, 1);
+ asm.jcc(Cond::NotEqual, again);
+ asm.bind(done);
+}
+
+/// The entry trampoline, `extern "C" fn(*mut NativeCall)`.
+pub fn entry_trampoline() -> Vec<u8> {
+ let mut asm = Assembler::new();
+ let record = gpr(convention::R11);
+ let (rax, rcx, rdx, rsi, rdi) = (
+ gpr(convention::RAX),
+ gpr(convention::RCX),
+ gpr(convention::RDX),
+ gpr(convention::RSI),
+ gpr(convention::RDI),
+ );
+ let call_field = |offset: usize| Address::new(record, field(offset));
+ asm.push(FP);
+ asm.mov_rr(Width::W64, FP, SP);
+ for register in [
+ convention::RBX,
+ convention::R12,
+ convention::R13,
+ convention::R14,
+ convention::R15,
+ ] {
+ asm.push(gpr(register));
+ }
+ // NB: Six pushes after the return address leave rsp 16-byte aligned. The record is the sixth.
+ asm.push(rdi);
+ asm.mov_rr(Width::W64, record, rdi);
+ asm.mov_rm(Width::W64, rcx, &call_field(offset_of!(NativeCall, image_slots)));
+ asm.mov_rr(Width::W64, rax, rcx);
+ asm.shl_ri(Width::W64, rax, 3);
+ asm.add_ri(Width::W64, rax, 15);
+ asm.and_ri(Width::W64, rax, -16);
+ asm.sub_rr(Width::W64, SP, rax);
+ asm.mov_mr(Width::W64, &call_field(offset_of!(NativeCall, saved_sp)), SP);
+ asm.mov_rm(Width::W64, rsi, &call_field(offset_of!(NativeCall, image)));
+ asm.mov_rr(Width::W64, rdi, SP);
+ copy_words(&mut asm, rsi, rdi, rcx, rdx);
+ let no_area = asm.new_label();
+ asm.mov_rm(
+ Width::W64,
+ rax,
+ &Address::new(record, field(offset_of!(NativeCall, result_pointer_slot))),
+ );
+ asm.cmp_ri(Width::W64, rax, -1);
+ asm.jcc(Cond::Equal, no_area);
+ asm.lea(Width::W64, rdx, &Address::indexed(SP, rax, crate::asm::Scale::Eight, 8));
+ asm.mov_mr(Width::W64, &Address::indexed(SP, rax, crate::asm::Scale::Eight, 0), rdx);
+ asm.bind(no_area);
+ for index in 0..8u8 {
+ let address = Address::new(record, field(offset_of!(NativeCall, xmms) + 16 * index as usize));
+ asm.vex(VMOVUPS_LOAD, index, 0, VexOperand::Memory(address), None);
+ }
+ for (index, register) in convention::GPR_ARGUMENTS.iter().enumerate() {
+ let address = Address::new(record, field(offset_of!(NativeCall, gprs) + 8 * index));
+ asm.mov_rm(Width::W64, gpr(*register), &address);
+ }
+ for (register, offset) in [
+ (convention::CALLEE_REGISTER, offset_of!(NativeCall, header)),
+ (convention::INSTANCE_REGISTER, offset_of!(NativeCall, instance)),
+ (convention::MEMORY_BASE_REGISTER, offset_of!(NativeCall, memory_base)),
+ ] {
+ asm.mov_rm(Width::W64, gpr(register), &Address::new(record, field(offset)));
+ }
+ asm.call_m(&call_field(offset_of!(NativeCall, entry)));
+ // NB: Tail calls may have moved rsp; the record has it.
+ asm.mov_rm(Width::W64, record, &Address::new(FP, -48));
+ asm.mov_rm(Width::W64, SP, &call_field(offset_of!(NativeCall, saved_sp)));
+ asm.mov_mr(Width::W64, &call_field(offset_of!(NativeCall, result_gprs)), rax);
+ asm.mov_mr(Width::W64, &call_field(offset_of!(NativeCall, result_gprs) + 8), rdx);
+ for index in 0..2u8 {
+ let address = Address::new(record, field(offset_of!(NativeCall, result_xmms) + 16 * index as usize));
+ asm.vex(VMOVUPS_STORE, index, 0, VexOperand::Memory(address), None);
+ }
+ asm.mov_rm(Width::W64, rcx, &call_field(offset_of!(NativeCall, image_slots)));
+ asm.mov_rm(Width::W64, rdi, &call_field(offset_of!(NativeCall, image)));
+ asm.mov_rr(Width::W64, rsi, SP);
+ copy_words(&mut asm, rsi, rdi, rcx, rdx);
+ asm.lea(Width::W64, SP, &Address::new(FP, -40));
+ for register in [
+ convention::R15,
+ convention::R14,
+ convention::R13,
+ convention::R12,
+ convention::RBX,
+ ] {
+ asm.pop(gpr(register));
+ }
+ asm.pop(FP);
+ asm.ret();
+ asm.finish().expect("stubs have no unbound labels")
+}
+
+/// The runtime adapter. `function` is the runtime's `extern "C" fn(*mut ExecutionContext) -> u64`, which it calls
+/// with the callee's header, the save area and fp as the context's first three arguments. A nonzero result is a
+/// trap code.
+pub fn runtime_adapter(function: u64, runtime: &RuntimeInfo) -> Vec<u8> {
+ let mut asm = Assembler::new();
+ let instance = gpr(convention::INSTANCE_REGISTER);
+ // Below the frame header, the save area at rsp.
+ let frame_size = (convention::FRAME_HEADER_SIZE as usize + ADAPTER_SAVE_AREA).next_multiple_of(16) as i32;
+ asm.push(FP);
+ asm.lea(Width::W64, FP, &Address::new(SP, 16));
+ asm.mov_mr(Width::W64, &Address::new(FP, convention::FRAME_INSTANCE), instance);
+ asm.sub_ri(Width::W64, SP, frame_size - 16);
+ for (index, register) in convention::GPR_ARGUMENTS.iter().enumerate() {
+ asm.mov_mr(Width::W64, &Address::new(SP, 8 * index as i32), gpr(*register));
+ }
+ for index in 0..8u8 {
+ let address = Address::new(SP, 48 + 16 * i32::from(index));
+ asm.vex(VMOVUPS_STORE, index, 0, VexOperand::Memory(address), None);
+ }
+ let context = gpr(convention::RAX);
+ asm.mov_rm(
+ Width::W64,
+ context,
+ &Address::new(instance, field(offset_of!(InstanceData, context))),
+ );
+ let arguments = field(offset_of!(ExecutionContext, arguments));
+ asm.mov_mr(
+ Width::W64,
+ &Address::new(context, arguments),
+ gpr(convention::CALLEE_REGISTER),
+ );
+ asm.mov_mr(Width::W64, &Address::new(context, arguments + 8), SP);
+ asm.mov_mr(Width::W64, &Address::new(context, arguments + 16), FP);
+ asm.mov_rr(Width::W64, gpr(convention::RDI), context);
+ asm.mov_ri(SCRATCH, function);
+ asm.call_r(SCRATCH);
+ let trap = asm.new_label();
+ asm.test_rr(Width::W64, gpr(convention::RAX), gpr(convention::RAX));
+ asm.jcc(Cond::NotEqual, trap);
+ asm.mov_rm(Width::W64, gpr(convention::RAX), &Address::new(SP, 0));
+ asm.mov_rm(Width::W64, gpr(convention::RDX), &Address::new(SP, 8));
+ for index in 0..2u8 {
+ let address = Address::new(SP, 48 + 16 * i32::from(index));
+ asm.vex(VMOVUPS_LOAD, index, 0, VexOperand::Memory(address), None);
+ }
+ asm.lea(Width::W64, SP, &Address::new(FP, convention::FRAME_SAVED_FP));
+ asm.pop(FP);
+ asm.ret();
+ asm.bind(trap);
+ asm.mov_rr(Width::W32, gpr(convention::RDI), gpr(convention::RAX));
+ asm.mov_ri(SCRATCH, runtime.trap_exit);
+ asm.jmp_r(SCRATCH);
+ asm.finish().expect("stubs have no unbound labels")
+}
diff --git a/Libraries/LibWasm/JIT/tests/execution.rs b/Libraries/LibWasm/JIT/tests/execution.rs
index 346ab2be737..68894e22d51 100644
--- a/Libraries/LibWasm/JIT/tests/execution.rs
+++ b/Libraries/LibWasm/JIT/tests/execution.rs
@@ -28,7 +28,7 @@ fn spec_scripts_run_the_same_compiled() {
stress_registers,
..Default::default()
};
- let totals = harness::script::run(&[directory.to_string_lossy().into_owned()], false, options);
+ let totals = harness::script::run(&[directory.to_string_lossy().into_owned()], false, options, false);
assert!(totals.cases > 10_000, "only {} cases ran compiled", totals.cases);
assert_eq!(totals.failures, 0);
}
diff --git a/Libraries/LibWasm/JIT/tests/harness/mod.rs b/Libraries/LibWasm/JIT/tests/harness/mod.rs
index 5e03c3c1a9e..2714dd4869f 100644
--- a/Libraries/LibWasm/JIT/tests/harness/mod.rs
+++ b/Libraries/LibWasm/JIT/tests/harness/mod.rs
@@ -393,6 +393,7 @@ impl CompiledModule {
let mut context = CompileContext::default();
for (index, slot) in failures.iter_mut().enumerate().skip(first) {
let request = CompileRequest {
+ osr: None,
module: module.clone(),
function: index as u32,
runtime,
diff --git a/Libraries/LibWasm/JIT/tests/harness/script.rs b/Libraries/LibWasm/JIT/tests/harness/script.rs
index 54e4eecf3b9..c8ff15fce78 100644
--- a/Libraries/LibWasm/JIT/tests/harness/script.rs
+++ b/Libraries/LibWasm/JIT/tests/harness/script.rs
@@ -38,8 +38,8 @@ struct LoadedModule {
name: Option<String>,
interpreted: InstanceAddress,
jit: InstanceAddress,
- compiled: CompiledModule,
- binding: TestBinding,
+ /// The module compiled by the tests, unless the runtime compiles it.
+ compiled: Option<(CompiledModule, TestBinding)>,
diverged: bool,
}
@@ -66,7 +66,7 @@ pub fn trap_code(trap: &Trap) -> u32 {
}
}
-fn outcome(result: Result<Vec<Value>, Trap>) -> Outcome {
+pub fn outcome(result: Result<Vec<Value>, Trap>) -> Outcome {
match result {
Ok(values) => Outcome::Values(values),
Err(trap) => Outcome::Trap(trap_code(&trap)),
@@ -226,6 +226,7 @@ struct Script<'a> {
verbose: bool,
name: String,
options: Options,
+ runtime: bool,
}
impl Script<'_> {
@@ -260,20 +261,24 @@ impl Script<'_> {
let Ok(jit) = self.jit.instantiate(module.clone(), &jit_imports) else {
return;
};
- let compiled = CompiledModule::compile(module.clone(), self.options);
- let binding = TestBinding::new(&compiled, &self.jit, jit);
let defined = module.code.len();
self.totals.modules += 1;
self.totals.functions += defined;
- let first = module.imported_function_count as usize;
- self.totals.compiled += compiled.entries[first..].iter().filter(|entry| **entry != 0).count();
- self.totals.runnable += compiled.runnable[first..].iter().filter(|runnable| **runnable).count();
+ let compiled = if self.runtime {
+ None
+ } else {
+ let compiled = CompiledModule::compile(module.clone(), self.options);
+ let binding = TestBinding::new(&compiled, &self.jit, jit);
+ let first = module.imported_function_count as usize;
+ self.totals.compiled += compiled.entries[first..].iter().filter(|entry| **entry != 0).count();
+ self.totals.runnable += compiled.runnable[first..].iter().filter(|runnable| **runnable).count();
+ Some((compiled, binding))
+ };
self.modules.push(LoadedModule {
name,
interpreted,
jit,
compiled,
- binding,
diverged: false,
});
self.current = Some(self.modules.len() - 1);
@@ -320,15 +325,16 @@ impl Script<'_> {
let expected = outcome(self.interpreted.invoke(*interpreted, &arguments));
let loaded = &mut self.modules[index];
let function = function_index(&self.jit, *jit, loaded.jit);
- let actual = match function {
- Some(function) if loaded.compiled.runnable[function as usize] => {
+ let actual = match (function, &mut loaded.compiled) {
+ (Some(function), None) => {
+ exercised.insert((index, function));
+ self.totals.cases += 1;
+ Some(outcome(self.jit.invoke(*jit, &arguments)))
+ }
+ (Some(function), Some((compiled, binding))) if compiled.runnable[function as usize] => {
exercised.insert((index, function));
self.totals.cases += 1;
- Some(
- loaded
- .binding
- .call(&mut self.jit, &loaded.compiled, function, &arguments),
- )
+ Some(binding.call(&mut self.jit, compiled, function, &arguments))
}
_ => None,
};
@@ -445,7 +451,9 @@ pub fn scripts(paths: &[String]) -> Vec<PathBuf> {
}
/// Runs every script of `paths` (scripts or directories of them).
-pub fn run(paths: &[String], verbose: bool, options: Options) -> Totals {
+/// Runs the scripts at `paths`. With `runtime`, the JIT's store runs every call through the runtime, which compiles
+/// what `LIBWASM_JIT` says, instead of calling compiled code directly.
+pub fn run(paths: &[String], verbose: bool, options: Options, runtime: bool) -> Totals {
let mut totals = Totals::default();
for path in scripts(paths) {
let Ok(text) = std::fs::read_to_string(&path) else {
@@ -456,6 +464,7 @@ pub fn run(paths: &[String], verbose: bool, options: Options) -> Totals {
};
totals.scripts += 1;
let mut interpreted = Store::new();
+ interpreted.disable_jit();
let mut jit = Store::new();
let spectest = (spectest(&mut interpreted), spectest(&mut jit));
let mut registered = HashMap::new();
@@ -471,6 +480,7 @@ pub fn run(paths: &[String], verbose: bool, options: Options) -> Totals {
verbose,
name: path.file_name().unwrap().to_string_lossy().into_owned(),
options,
+ runtime,
};
runner.run(&script);
}