Skip to content

Truly independent web browser

LibWasm: Compile SIMD, GC, atomics and exceptions in the JIT

Andreas Kling4cd3e0319cb9
diff --git a/Libraries/LibWasm/Engine/src/abi.rs b/Libraries/LibWasm/Engine/src/abi.rs
index 519fe6e7b62..66cdb315497 100644
--- a/Libraries/LibWasm/Engine/src/abi.rs
+++ b/Libraries/LibWasm/Engine/src/abi.rs
@@ -188,6 +188,11 @@ pub struct ExecutionContext {
pub arguments: [u64; 6],
/// The runtime type of each store-wide type identity.
pub rtts: *const *const Rtt,
+ /// The exception that compiled code handles where a call returns to it, or 0 (see `runtime/jit.rs`).
+ pub exception: u64,
+ /// Where an exception continues in compiled code, or in the entry trampoline: rsp, rbp and the address the
+ /// resume stub jumps to.
+ pub resume: [u64; 3],
}
/// What the interpreter knows about a type at runtime: how to check subtyping against it, and how objects of it are
@@ -233,6 +238,15 @@ pub const OBJECT_DATA_OFFSET: usize = 16;
pub const OBJECT_LENGTH_OFFSET: usize = 24;
pub const OBJECT_INLINE_DATA_OFFSET: usize = 32;
+/// An exception is a cell with the identity of its tag, the address of its payload (its values' slots in operand
+/// stack order, the last value in the lowest slot), the payload's length in slots, and how the collector follows
+/// each slot.
+pub const EXCEPTION_CELL_SIZE: usize = 48;
+pub const EXCEPTION_TAG_OFFSET: usize = 16;
+pub const EXCEPTION_PAYLOAD_OFFSET: usize = 24;
+pub const EXCEPTION_LENGTH_OFFSET: usize = 32;
+pub const EXCEPTION_KINDS_OFFSET: usize = 40;
+
/// What the runtime enters the interpreter with, and what it gets back.
#[repr(C)]
pub struct EntryRecord {
diff --git a/Libraries/LibWasm/Engine/src/runtime/gc.rs b/Libraries/LibWasm/Engine/src/runtime/gc.rs
index ab94f82efda..0de36e9fd29 100644
--- a/Libraries/LibWasm/Engine/src/runtime/gc.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/gc.rs
@@ -17,7 +17,9 @@ use super::heap::{
object_size_class,
};
use super::{Store, TagAddress, Value};
+pub use crate::abi::EXCEPTION_CELL_SIZE;
use crate::abi::{
+ EXCEPTION_KINDS_OFFSET, EXCEPTION_LENGTH_OFFSET, EXCEPTION_PAYLOAD_OFFSET, EXCEPTION_TAG_OFFSET,
OBJECT_DATA_OFFSET, OBJECT_INLINE_DATA_OFFSET, OBJECT_LENGTH_OFFSET, RTT_KIND_ARRAY, RTT_KIND_FUNCTION,
RTT_KIND_STRUCT, Rtt, STORAGE_32, STORAGE_64, STORAGE_FUNCTION_REFERENCE, STORAGE_I8, STORAGE_I16,
STORAGE_REFERENCE, STORAGE_V128,
@@ -25,11 +27,6 @@ use crate::abi::{
use crate::types::{CompositeType, HeapType, StorageType, SubType, ValType};
use core::ffi::c_void;
-pub const EXCEPTION_CELL_SIZE: usize = 48;
-const EXCEPTION_TAG_OFFSET: usize = 16;
-const EXCEPTION_PAYLOAD_OFFSET: usize = 24;
-const EXCEPTION_LENGTH_OFFSET: usize = 32;
-const EXCEPTION_KINDS_OFFSET: usize = 40;
const STORE_ROOT_STORE_OFFSET: usize = 16;
/// The largest data an object can have.
diff --git a/Libraries/LibWasm/Engine/src/runtime/helpers.rs b/Libraries/LibWasm/Engine/src/runtime/helpers.rs
index 8b807053536..d1fd42996b4 100644
--- a/Libraries/LibWasm/Engine/src/runtime/helpers.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/helpers.rs
@@ -205,7 +205,13 @@ unsafe fn throw(context: *mut ExecutionContext) -> u64 {
/// Find the handler of `exception`, thrown by the instruction at `pc` in the frame `frame`, in that frame or the ones
/// it was called from, up to where the runtime entered the interpreter. If there is one, push what the handler
/// receives and put where it continues into the context's arguments.
-unsafe fn unwind(context: *mut ExecutionContext, store: &Store, exception: u64, mut frame: u64, mut pc: u64) -> bool {
+pub(crate) unsafe fn unwind(
+ context: *mut ExecutionContext,
+ store: &Store,
+ exception: u64,
+ mut frame: u64,
+ mut pc: u64,
+) -> bool {
let read = |address: u64| unsafe { *(address as *const u64) };
let thrown_tag = store.exception(exception).tag;
loop {
diff --git a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs
index bacdfb02d99..50d7d66f3f0 100644
--- a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs
@@ -118,9 +118,20 @@ fn missing_cpu_features() -> Vec<&'static str> {
/// The lowest address the interpreter's frames may use on the current thread, leaving `reserve` bytes below it.
pub fn stack_limit(reserve: usize) -> u64 {
- let marker = 0u8;
- let current = &raw const marker as usize;
- let lowest = thread_stack_lowest_address().unwrap_or(current.saturating_sub(1024 * 1024));
+ // OPTIMIZATION: Finding where a thread's stack ends can mean reading /proc/self/maps (glibc does for the main
+ // thread), which took over half a millisecond per call from JavaScript into WebAssembly, so each
+ // thread finds it once.
+ thread_local! {
+ static LOWEST: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+ }
+ let lowest = LOWEST.with(|lowest| {
+ if lowest.get() == 0 {
+ let marker = 0u8;
+ let current = &raw const marker as usize;
+ lowest.set(thread_stack_lowest_address().unwrap_or(current.saturating_sub(1024 * 1024)));
+ }
+ lowest.get()
+ });
(lowest + reserve) as u64
}
diff --git a/Libraries/LibWasm/Engine/src/runtime/jit.rs b/Libraries/LibWasm/Engine/src/runtime/jit.rs
index 902884018ef..834a24c45e0 100644
--- a/Libraries/LibWasm/Engine/src/runtime/jit.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/jit.rs
@@ -12,6 +12,11 @@
//! 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.
+//! - Compiled code handles the exceptions of its own handlers itself. An exception that leaves a compiled function,
+//! or comes out of a call through the runtime adapter, is unwound here over the compiled frames, to the first
+//! call that handles exceptions (an exception site) or to the entry trampoline, which continue as if the call had
+//! returned, with the exception in the context. From the trampoline, the exception goes on in the interpreter
+//! frame that called the compiled code.
//! - 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
@@ -141,12 +146,15 @@ export! {
wasm_runtime_call_compiled => call_compiled,
wasm_runtime_call_from_native => call_from_native,
wasm_runtime_tier_up => tier_up,
+ wasm_runtime_allocate_exception => allocate_exception,
+ wasm_runtime_throw_from_native => throw_from_native,
}
/// 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.
+/// (OSR) and returns the top of the frame's operand stack with the results on it, or if the frame threw an exception,
+/// 1 if a handler of the interpreter caught it and 2 if it left the interpreter; returns 0 otherwise.
unsafe fn tier_up(context: *mut ExecutionContext) -> u64 {
unsafe {
let [header, pc, reason, frame, ..] = (*context).arguments;
@@ -176,6 +184,18 @@ unsafe fn tier_up(context: *mut ExecutionContext) -> u64 {
}
match native::enter_at_loop(store, address, pc, frame) {
native::LoopEntry::Ran(top) => top,
+ native::LoopEntry::Threw(exception) => {
+ // The frame's own handlers had their chance in the compiled code, so the exception goes on in the
+ // frame's caller, at the call instruction it returns past.
+ let read = |offset: isize| *((frame as *const u8).offset(offset) as *const u64);
+ let caller = read(crate::abi::FRAME_SAVED_FP);
+ let call = read(crate::abi::FRAME_RETURN_IP) - 1;
+ // NB: 0 means the loop goes on in the interpreter, so a trap is 2 here.
+ match rethrow_in_interpreter(context, store, exception, caller, call) {
+ 0 => 2,
+ resumed => resumed,
+ }
+ }
native::LoopEntry::Pending => {
address.get_mut().header.tier_up_budget = POLL_BUDGET + crate::abi::TIER_UP_CALL_COST;
0
@@ -185,6 +205,45 @@ unsafe fn tier_up(context: *mut ExecutionContext) -> u64 {
}
}
+/// Continues an exception that compiled code did not handle in the interpreter, at the instruction `pc` of the frame
+/// `frame`. Returns 1 if a handler there caught it (see `wasm_runtime_throw`), or 0 if it leaves the interpreter, as a
+/// trap the store keeps.
+unsafe fn rethrow_in_interpreter(
+ context: *mut ExecutionContext,
+ store: &mut Store,
+ exception: u64,
+ frame: u64,
+ pc: u64,
+) -> u64 {
+ unsafe {
+ if super::helpers::unwind(context, store, exception, frame, pc) {
+ return 1;
+ }
+ store.pending_trap = Some(Trap::UncaughtException(exception));
+ 0
+ }
+}
+
+/// `Helper::AllocateException`: a new exception with the tag whose identity is `arguments[0]` and a zeroed payload.
+unsafe fn allocate_exception(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let store = store_of(context);
+ let tag = store.tag_from_identity((*context).arguments[0]);
+ let slot_count: u32 = store.tag(tag).ty.params.iter().map(|param| param.slot_count()).sum();
+ store.allocate_exception(tag, &vec![0; slot_count as usize])
+ }
+}
+
+/// Throws the exception `arguments[0]` from the compiled frame whose fp is `arguments[1]`, whose own handlers did not
+/// catch it. Returns the context, whose `resume` says where the code continues.
+unsafe fn throw_from_native(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let [exception, frame, ..] = (*context).arguments;
+ native::unwind(store_of(context), exception, frame);
+ context as u64
+ }
+}
+
/// 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;
@@ -319,9 +378,19 @@ fn ir_types(types: &[ValType]) -> Vec<libwasm_jit::ir::Type> {
}
/// 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.
+/// operand stack, where its arguments are, `arguments[2]` where the call returns to and `arguments[3]` the caller's
+/// frame. Replaces the arguments with its results and returns the new top, or if it threw an exception, 1 if a
+/// handler of the interpreter caught it, or 0 if it left the interpreter (see `rethrow_in_interpreter`).
unsafe fn call_compiled(context: *mut ExecutionContext) -> u64 {
- unsafe { native::call_compiled(context) }
+ unsafe {
+ match native::call_compiled(context) {
+ Ok(top) => top,
+ Err(exception) => {
+ let [_, _, return_ip, frame, ..] = (*context).arguments;
+ rethrow_in_interpreter(context, store_of(context), exception, frame, return_ip - 1)
+ }
+ }
+ }
}
/// Calls a function that runs in the runtime from compiled code, through the runtime adapter: `arguments[0]` is its
@@ -359,6 +428,11 @@ unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {
let address = FunctionAddress::from_ptr(function);
let results = match store.invoke(address, &arguments) {
Ok(results) => results,
+ Err(Trap::UncaughtException(exception)) => {
+ // NB: The adapter's frame is a frame of the compiled caller's callee.
+ native::unwind(store, exception, frame);
+ return libwasm_jit::stubs::ADAPTER_RESUME;
+ }
Err(trap) => {
let code = trap_code(&trap);
store.pending_trap = Some(trap);
@@ -397,7 +471,7 @@ mod native {
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 libwasm_jit::{CompileContext, CompileRequest, CompiledFunction, RuntimeInfo};
use std::collections::{HashMap, HashSet};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex, OnceLock};
@@ -406,6 +480,8 @@ mod native {
pub struct Stubs {
pub trap_exit: u64,
pub entry: u64,
+ /// Where the entry trampoline's call of compiled code returns to.
+ pub entry_return: u64,
pub adapter: u64,
pub runtime: RuntimeInfo,
}
@@ -423,8 +499,13 @@ mod native {
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,
+ allocate: helpers::wasm_runtime_allocate as *const () as u64,
+ wait: helpers::wasm_runtime_wait as *const () as u64,
+ notify: helpers::wasm_runtime_notify as *const () as u64,
+ allocate_exception: super::wasm_runtime_allocate_exception as *const () as u64,
+ throw: super::wasm_runtime_throw_from_native as *const () as u64,
};
- let trampoline = libwasm_jit::stubs::entry_trampoline();
+ let (trampoline, return_offset) = 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);
@@ -437,6 +518,7 @@ mod native {
Stubs {
trap_exit,
entry,
+ entry_return: entry + return_offset as u64,
adapter,
runtime,
}
@@ -523,7 +605,7 @@ mod native {
/// A compile a compile thread finished, for the store that asked for it.
struct Finished {
key: CompileKey,
- code: Result<Vec<u8>, libwasm_jit::CompileFailure>,
+ code: Result<CompiledFunction, libwasm_jit::CompileFailure>,
}
struct Job {
@@ -560,7 +642,7 @@ mod native {
let Ok(job) = job else {
return;
};
- let code = libwasm_jit::compile(&mut context, &job.request).map(|compiled| compiled.code);
+ let code = libwasm_jit::compile(&mut context, &job.request);
// NB: The store may be gone, and its results with it.
let _ = job.reply.send(Finished { key: job.key, code });
}
@@ -588,6 +670,8 @@ mod native {
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 frame threw this exception, which its own handlers did not catch.
+ Threw(u64),
/// The code for the loop is still compiling.
Pending,
/// The frame cannot continue compiled at this loop.
@@ -602,6 +686,8 @@ mod native {
/// The code of each compile, and the compiles that failed.
code: HashMap<CompileKey, u64>,
failed: HashSet<CompileKey>,
+ /// The return addresses of the calls in compiled code that handle exceptions.
+ exception_sites: HashSet<u64>,
/// The compiles the compile threads have yet to finish, and where they send them.
pending: HashSet<CompileKey>,
finished: Option<(Sender<Finished>, Receiver<Finished>)>,
@@ -640,12 +726,17 @@ mod native {
}
/// Installs the result of a compile.
- fn finish(&mut self, key: CompileKey, code: Result<Vec<u8>, libwasm_jit::CompileFailure>) {
- let Ok(code) = code else {
+ fn finish(&mut self, key: CompileKey, compiled: Result<CompiledFunction, libwasm_jit::CompileFailure>) {
+ let Ok(CompiledFunction {
+ code, exception_sites, ..
+ }) = compiled
+ else {
self.failed.insert(key);
return;
};
let entry = self.add_code(&code);
+ self.exception_sites
+ .extend(exception_sites.iter().map(|offset| entry + u64::from(*offset)));
if super::options().perf_map {
let name = match key.osr {
None => format!("wasm-function-{}", key.function),
@@ -667,7 +758,7 @@ mod native {
}
if super::options().sync {
let request = self.request(key);
- let code = libwasm_jit::compile(&mut self.context, &request).map(|compiled| compiled.code);
+ let code = libwasm_jit::compile(&mut self.context, &request);
self.finish(key, code);
return self.compile(key);
}
@@ -713,6 +804,33 @@ mod native {
}
}
+ /// Unwinds `exception` from the compiled frame whose fp is `frame`: finds the first exception site its callers
+ /// return to, or else the entry trampoline, and has the code continue there (see `ExecutionContext::resume`),
+ /// with the exception in the context.
+ pub unsafe fn unwind(store: &mut Store, exception: u64, frame: u64) {
+ unsafe {
+ let read = |address: u64| *(address as *const u64);
+ let entry_return = stubs().entry_return;
+ let sites = &store.jit.as_ref().expect("compiled code ran").exception_sites;
+ // The return address of the callee whose fp `callee` is leads into its caller's frame.
+ let mut callee = frame;
+ loop {
+ let return_address = read(callee.wrapping_add_signed(crate::abi::FRAME_RETURN_IP as i64));
+ if return_address == entry_return || sites.contains(&return_address) {
+ let context = &mut *store.context;
+ context.exception = exception;
+ context.resume = [
+ callee,
+ read(callee.wrapping_add_signed(crate::abi::FRAME_SAVED_FP as i64)),
+ return_address,
+ ];
+ return;
+ }
+ callee = read(callee.wrapping_add_signed(crate::abi::FRAME_SAVED_FP as i64));
+ }
+ }
+ }
+
pub fn install_finished(jit: &mut StoreJit) {
if !jit.pending.is_empty() {
jit.take_finished(false);
@@ -760,7 +878,7 @@ mod native {
state
}
- pub unsafe fn call_compiled(context: *mut ExecutionContext) -> u64 {
+ pub unsafe fn call_compiled(context: *mut ExecutionContext) -> Result<u64, u64> {
unsafe {
let [header, top, ..] = (*context).arguments;
let function = &*(header as *const FunctionInstance);
@@ -787,14 +905,14 @@ mod native {
/// 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.
+ /// new top, or the exception it threw. 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 {
+ ) -> Result<u64, u64> {
unsafe {
let header_data: &FunctionHeader = &function.header;
let results = ir_types(&function.ty.results);
@@ -845,6 +963,10 @@ mod native {
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 context = (*header_data.instance).context;
+ if (*context).exception != 0 {
+ return Err(std::mem::take(&mut (*context).exception));
+ }
let return_top = end.sub(result_slots);
convention::result_places(&results, &mut places);
let (mut gprs, mut xmms) = (0, 0);
@@ -873,7 +995,7 @@ mod native {
let destination = return_top.add(result_slots - home - count);
std::ptr::copy_nonoverlapping(words.as_ptr(), destination, count);
}
- return_top as u64
+ Ok(return_top as u64)
}
}
@@ -899,7 +1021,10 @@ mod native {
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))
+ match run(function, entry, &params, |_| &raw const frame, base) {
+ Ok(top) => LoopEntry::Ran(top),
+ Err(exception) => LoopEntry::Threw(exception),
+ }
}
}
}
@@ -934,10 +1059,15 @@ mod native {
pub enum LoopEntry {
Ran(u64),
+ Threw(u64),
Pending,
Never,
}
+ pub unsafe fn unwind(_store: &mut Store, _exception: u64, _frame: u64) {
+ unreachable!("the JIT is off where it has no code generator")
+ }
+
pub fn compile_instance(_store: &mut Store, _instance: InstanceAddress) {}
pub fn compile_function(_store: &mut Store, _address: crate::runtime::FunctionAddress) -> CompileState {
@@ -953,7 +1083,7 @@ mod native {
LoopEntry::Never
}
- pub unsafe fn call_compiled(_context: *mut ExecutionContext) -> u64 {
+ pub unsafe fn call_compiled(_context: *mut ExecutionContext) -> Result<u64, u64> {
unreachable!("the JIT is off where it has no code generator")
}
}
diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rs
index 65e2e0bc26a..87f56378946 100644
--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs
@@ -381,6 +381,8 @@ impl Store {
store: std::ptr::null_mut(),
arguments: [0; 6],
rtts: std::ptr::null(),
+ exception: 0,
+ resume: [0; 3],
}),
canonicalizer: TypeCanonicalizer::new(),
types: Vec::new(),
diff --git a/Libraries/LibWasm/Interpreter/interpreter.flap b/Libraries/LibWasm/Interpreter/interpreter.flap
index 60cf160872c..11df05f8814 100644
--- a/Libraries/LibWasm/Interpreter/interpreter.flap
+++ b/Libraries/LibWasm/Interpreter/interpreter.flap
@@ -306,14 +306,23 @@ inline fn call_host_function(function: u64, return_ip: u64, context_pointer: u64
}
# 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.
+# the arguments with its results; a trap in it leaves the interpreter from the compiled code. An exception it throws
+# continues at the call, as with host functions.
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);
+ store64([context_pointer, CONTEXT_ARGUMENT_2], return_ip);
+ store64([context_pointer, CONTEXT_ARGUMENT_3], fp);
# 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);
+ guard new_top != 0 else @cold {
+ trap(TRAP_RUNTIME);
+ };
+ if new_top == 1 @cold {
+ resume_at_handler();
+ }
vsp = new_top;
dispatch;
}
@@ -840,6 +849,12 @@ handler Loop() @opcode(0x03) {
# 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 == 1 {
+ resume_at_handler();
+ }
+ if results_top == 2 {
+ trap(TRAP_RUNTIME);
+ }
if results_top != 0 {
vsp = results_top;
return_from_function();
diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.md
index e0911656461..67592a4939a 100644
--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md
+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md
@@ -31,9 +31,8 @@ register allocation (`regalloc/verify.rs`).
The JIT is meant to compile every function that validates, of any size: a hot function that does
not compile would run interpreted forever. Until the JIT gets there, functions that use something it
-does not compile yet fail with `CompileFailure::Unsupported` and stay interpreted: exceptions, GC,
-atomics, accesses of memories without guard pages, and the SIMD instructions outside the slice
-`builder/simd.rs` lists. Nothing fails for its size, depth, number of locals or
+does not compile yet fail with `CompileFailure::Unsupported` and stay interpreted: exceptions. Nothing
+fails for its size, depth, number of locals or
register pressure.
## 2. Decoding
@@ -41,7 +40,9 @@ register pressure.
`Decoder` reads one instruction at a time from a validated, quickened body
(`libwasm_engine::quickening`): plain loads and stores access memory 0, which is a memory32 with
guard pages, and the bounds-checked forms are `0xFF` instructions. It reads every instruction the
-engine validates, so that the builder can skip unreachable code of any kind.
+engine validates, so that the builder can skip unreachable code of any kind. Accesses of other memories
+and of memory64s are the bounds-checked `0xFF` forms (`CheckedAccess`); atomic accesses are never
+quickened.
## 3. The IR
@@ -85,8 +86,14 @@ truncations, unless their flags say they cannot), and are neither removed nor mo
| ReadField, WriteField | Fields of runtime data that change, like the size of a memory or table, or a segment's length. |
| TableElement, TableStore | A table's element, after checking the index against its size. |
| GlobalGet, GlobalSet | A global's value, through its storage pointer. Gets of immutable globals are pure. |
-| Load, Store | Memory 0 at base + zero-extended index + offset; may trap. |
-| VectorUnary, VectorBinary, VectorTernary | SIMD operations, by their sub-opcode: splats, lane-wise arithmetic, comparisons, shifts by an i32, bitselect, and reductions to an i32. |
+| Load, Store | Memory 0 at base + zero-extended index + offset; may trap. With a pointer or a GC object as the base and a zero index, any other address, like a checked access's or a field's. |
+| CheckedAddress | The address of an access of a memory without guard pages, or an atomic access, after checking it against the memory's size (and for atomics, its alignment). |
+| AtomicRmw, AtomicCompareExchange, AtomicFence | Atomic read-modify-write operations at an address (add, sub, and, or, xor, exchange), compare-exchange, and `atomic.fence`. |
+| Rtt | The runtime type of one of the module's types. |
+| I31New, I31Get | `ref.i31`, and the value of an i31 reference. |
+| ElementAddress | The address of an array's element, after checking the array for null and the index against its length. |
+| RefTest | Whether a reference matches a heap type, or for casts, a check that traps where it does not. |
+| VectorUnary, VectorBinary, VectorTernary | SIMD operations, by their sub-opcode: splats, lane-wise arithmetic, comparisons, conversions, shifts by an i32, bitselect and the relaxed multiply-adds, and reductions to an i32. |
| ExtractLane, ReplaceLane, Shuffle | Lane access, and `i8x16.shuffle`. |
| VectorLoad | A SIMD load of memory 0, by its sub-opcode (whole, extending, splatting or zero-filling); may trap. |
| CalleeInstance | The instance a call of a function passes: the header's, or the caller's for host functions. |
@@ -122,7 +129,12 @@ structured control flow:
- After a loop, the code goes on in a block of its own, so that the loop's blocks end where it does.
- The quickened v128 forms of `local.get` and the like (`0xF4` to `0xFA`) build like the plain ones,
since values carry their types. SIMD instructions keep their sub-opcode in the IR
- (`builder/simd.rs`), so that one node kind per shape carries all of them.
+ (`builder/simd.rs`), so that one node kind per shape carries all of them; the shape comes from the
+ module's `simd_kind()` table. Lane loads and stores become scalar loads and stores with lane
+ insertions and extractions. Accesses of other memories and of memory64s check their address as the
+ core ones do (`CheckedAddress`) and access it with a zero index. Relaxed instructions get the interpreter's semantics: all but the
+ multiply-adds and dot products become their deterministic counterparts. A shuffle that uses one
+ operand names it twice, with lanes 0 to 15, so the other one need not stay live.
Nodes fold as they are created (`builder/fold.rs`): integer constant folding and algebraic
identities, constants to the right, `eqz` of a comparison as the inverted comparison, and divisions
@@ -263,6 +275,36 @@ does not preserve, so values stay in rbx and r12 to r15 across them. Growing cal
helpers; fill, copy and init of memories and tables call the JIT's (`runtime.rs`), which return 0 or
the trap code.
+**Memories without guard pages and atomics** (`builder/memories.rs`). An access of a memory64, or of
+a memory other than memory 0, is a `CheckedAddress` and a `Load` or `Store` at it. `CheckedAddress`
+computes the end of the access, index + offset + size, in 64 bits, trapping where that wraps around
+(only a memory64's can), compares it with the memory's size, and returns base + end - size. Atomic
+accesses take the same path for every memory, and check the end for alignment too, after the bounds,
+as the interpreter does. Atomic loads are plain loads, and stores are exchanges, as in the
+interpreter's lowering: on x86-64 that makes both sequentially consistent. Add, sub and exchange are
+`lock xadd` and `xchg`; and, or and xor are `lock cmpxchg` loops. `atomic.fence` is `mfence`. Waiting
+and notifying call the runtime; whether the memory is shared is part of its type, so waiting on an
+unshared memory traps, and notifying one wakes nobody, without a call.
+
+**GC** (`builder/gc.rs`). Objects are cells of the runtime's heap: the Rtt first, the address of the
+data, an array's length, then the data inline if it has at most 4096 bytes. A struct's fields are at
+constant offsets (8 bytes each, 16 for v128, packed and 32-bit values zero-extended in their word), so
+`struct.get` is a null check and a load at the object plus the field's offset; a large struct's data
+is reached through its address first. `array.get` and `array.set` access the element at its
+`ElementAddress`. Allocation, filling, copying and initializing from segments call the runtime
+(`Helper`); the allocation traps with `TRAP_RUNTIME` where the runtime returns null. `ref.test`,
+`ref.cast`, `br_on_cast` and `br_on_cast_fail` are a `RefTest`: abstract heap types test the
+reference's bits (an i31 has bit 0 set, a host value bits 1:0 equal to 0b10, a GC object neither) and
+the kind of the object's Rtt; concrete types compare the type's identity with the actual type's
+display at the expected type's depth, which the module's subtype chain gives at compile time.
+
+GC references in compiled frames need nothing of their own: the collector scans the stack
+conservatively, recognizes pointers into cells (so tagged references keep their cells alive), and
+every allocation is a call of the runtime, around which values live in stack slots or callee-saved
+registers. The one hazard is a pointer to data outside the heap, which does not keep its object
+alive; `ReadField` and `ElementAddress` are not pure, so such pointers are computed where they are
+used, while the object is live.
+
## 9. Code generation
`codegen/x86_64/` lowers the blocks in linear order with x86-64-v3 instructions (VEX three-operand
@@ -271,6 +313,15 @@ libjs_jit's encoders and the additions in its `asm/x86_64/extended.rs`, whose `v
VEX instruction from its opcode (`codegen/x86_64/vector.rs` names the SIMD ones). After each node, a value with a slot is stored
there; a phi in a register with a slot is stored where its block starts.
+- **Vectors.** A vector node's output register differs from its inputs and temps, so lowerings may
+ write it first; xmm15 is their scratch, and `vector_temps()` says which take an extra register.
+ Where the interpreter's instruction sequence decides bits the spec leaves open (NaN payloads of
+ min and max, relaxed instructions), the lowering is the same sequence, so both tiers agree bit for
+ bit. Shift counts that are constants use the immediate forms, v128 constants that are an
+ instruction's r/m operand stay in the constant pool (`vector_constant_inputs()`), and shuffles
+ become one `vpshufd`, `vpalignr`, `vpunpck*dq`, `vshufps`, `vpblendd` or `vpshufb` where they can,
+ else two `vpshufb` and an or.
+
- **Edges.** A jump moves its values and jumps unless its target comes next. A two-way branch whose
taken edge needs moves jumps to a stub that moves them; its other edge moves inline. Where the
taken target comes next and needs no moves, the condition is inverted. `br_table` is a jump table
diff --git a/Libraries/LibWasm/JIT/examples/bench_check.rs b/Libraries/LibWasm/JIT/examples/bench_check.rs
index 93dffb2dfab..65516edd436 100644
--- a/Libraries/LibWasm/JIT/examples/bench_check.rs
+++ b/Libraries/LibWasm/JIT/examples/bench_check.rs
@@ -9,9 +9,10 @@
//! 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.
+//! `--compiled-only` runs and times only the compiled store, for timing.
//!
//! ```text
-//! bench_check [--timeout SECONDS] MODULE ENTRY [MODULE ENTRY]...
+//! bench_check [--timeout SECONDS] [--compiled-only] MODULE ENTRY [MODULE ENTRY]...
//! ```
#[path = "../tests/harness/mod.rs"]
@@ -124,6 +125,11 @@ fn main() {
timeout = arguments[1].parse().expect("--timeout SECONDS");
arguments.drain(..2);
}
+ // For timing: runs only the compiled store, and compares nothing.
+ let compiled_only = arguments.first().is_some_and(|argument| argument == "--compiled-only");
+ if compiled_only {
+ arguments.drain(..1);
+ }
// 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());
@@ -160,6 +166,19 @@ fn main() {
let outcome = outcome(instance.store.invoke(function, &[]));
(outcome, start.elapsed())
};
+ let name = std::path::Path::new(path)
+ .file_name()
+ .unwrap()
+ .to_string_lossy()
+ .into_owned();
+ if compiled_only {
+ let (actual, jit_time) = run(&mut jit);
+ println!(
+ "timed {name} ({actual:?}; {:.3} s compiled)",
+ jit_time.as_secs_f64()
+ );
+ continue;
+ }
let (expected, interpreted_time) = run(&mut interpreted);
let (actual, jit_time) = run(&mut jit);
let mut problems = Vec::new();
@@ -176,11 +195,6 @@ fn main() {
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)",
diff --git a/Libraries/LibWasm/JIT/examples/compile_all.rs b/Libraries/LibWasm/JIT/examples/compile_all.rs
index ccbe3053cea..b2afc889a2a 100644
--- a/Libraries/LibWasm/JIT/examples/compile_all.rs
+++ b/Libraries/LibWasm/JIT/examples/compile_all.rs
@@ -30,6 +30,11 @@ const RUNTIME: RuntimeInfo = RuntimeInfo {
memory_grow: 0x7fff_0000_2000,
table_grow: 0x7fff_0000_3000,
call_host: 0x7fff_0000_4000,
+ allocate: 0x7fff_0000_5000,
+ wait: 0x7fff_0000_6000,
+ notify: 0x7fff_0000_7000,
+ allocate_exception: 0x7fff_0000_8000,
+ throw: 0x7fff_0000_9000,
};
/// Functions at least this big count for the slowest function per byte.
diff --git a/Libraries/LibWasm/JIT/examples/smith_check.rs b/Libraries/LibWasm/JIT/examples/smith_check.rs
index 70d3344f6da..01ae2cdb938 100644
--- a/Libraries/LibWasm/JIT/examples/smith_check.rs
+++ b/Libraries/LibWasm/JIT/examples/smith_check.rs
@@ -9,7 +9,11 @@
//!
//! ```text
//! smith_check [--count N] [--seed S] [--keep DIRECTORY] [--wasm-tools PATH] [--stress-registers] [--no-licm] [--gvn]
+//! [--simd] [--features gc,threads,memory64,multi-memory]
//! ```
+//!
+//! `--features` turns on proposals besides the default ones, in every module. Modules that wait on shared memory are
+//! skipped, since nothing would wake them. With GC, modules get less fuel, since the stores never free objects.
#[path = "../tests/harness/mod.rs"]
mod harness;
@@ -38,12 +42,12 @@ const SMITH_FLAGS: &[&str] = &[
"1",
"--max-memory32-bytes",
"262144",
+ "--max-memory64-bytes",
+ "262144",
"--bulk-memory-enabled",
"true",
"--reference-types-enabled",
"true",
- "--relaxed-simd-enabled",
- "false",
"--exceptions-enabled",
"false",
"--gc-enabled",
@@ -152,6 +156,8 @@ fn main() {
let mut stress_registers = false;
let mut no_licm = false;
let mut gvn = false;
+ let mut simd = false;
+ let mut features: Vec<String> = Vec::new();
let mut wasm_tools = std::env::var("HOME")
.map(|home| format!("{home}/.cargo/bin/wasm-tools"))
.unwrap_or_default();
@@ -170,9 +176,44 @@ fn main() {
"--stress-registers" => stress_registers = true,
"--no-licm" => no_licm = true,
"--gvn" => gvn = true,
+ "--simd" => simd = true,
+ "--features" => {
+ features = arguments
+ .next()
+ .expect("--features LIST")
+ .split(',')
+ .map(str::to_string)
+ .collect();
+ }
_ => panic!("unknown argument {argument}"),
}
}
+ let simd_flag = |iteration: usize| {
+ if simd || iteration.is_multiple_of(2) {
+ "true"
+ } else {
+ "false"
+ }
+ };
+ let mut flags: Vec<&str> = SMITH_FLAGS.to_vec();
+ let mut set_flag = |name: &str, value: &'static str| {
+ let position = flags.iter().position(|flag| *flag == name).expect("a known flag");
+ flags[position + 1] = value;
+ };
+ for feature in &features {
+ match feature.as_str() {
+ "gc" => {
+ set_flag("--gc-enabled", "true");
+ // NB: The stores of these tests never free GC objects, so allocating loops run out of memory with
+ // the usual fuel.
+ set_flag("--fuel", "20000");
+ }
+ "threads" => set_flag("--threads-enabled", "true"),
+ "memory64" => set_flag("--memory64-enabled", "true"),
+ "multi-memory" => set_flag("--max-memories", "4"),
+ _ => panic!("unknown feature {feature}"),
+ }
+ }
let mut random = Random(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1);
let mut totals = Totals::default();
for iteration in 0..count {
@@ -181,9 +222,10 @@ fn main() {
.collect::<Vec<_>>();
let mut child = Command::new(&wasm_tools)
.arg("smith")
- .args(SMITH_FLAGS)
- // NB: Every other module without SIMD, whose functions the JIT compiles more often.
- .args(["--simd-enabled", if iteration % 2 == 0 { "true" } else { "false" }])
+ .args(&flags)
+ // NB: Every other module without SIMD, unless --simd says otherwise.
+ .args(["--simd-enabled", simd_flag(iteration)])
+ .args(["--relaxed-simd-enabled", simd_flag(iteration)])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -198,6 +240,9 @@ fn main() {
let Ok(module) = libwasm_engine::compile(&bytes) else {
continue;
};
+ if waits(&module) {
+ continue;
+ }
let module = Arc::new(module);
let mut interpreted = Store::new();
let mut jit = Store::new();
@@ -325,3 +370,17 @@ fn main() {
std::process::exit(1);
}
}
+
+/// Whether a function of the module waits on shared memory (`memory.atomic.wait32` and `wait64`).
+fn waits(module: &libwasm_engine::module::Module) -> bool {
+ use libwasm_jit::decode::{Decoder, Instruction};
+ module.code.iter().any(|body| {
+ let mut decoder = Decoder::new(&module.bytes, body.code.start as usize, body.code.end as usize);
+ while !decoder.is_at_end() {
+ if let Instruction::Atomic(1 | 2) = decoder.decode() {
+ return true;
+ }
+ }
+ false
+ })
+}
diff --git a/Libraries/LibWasm/JIT/src/builder/calls.rs b/Libraries/LibWasm/JIT/src/builder/calls.rs
index f9b649e556f..2cec530b953 100644
--- a/Libraries/LibWasm/JIT/src/builder/calls.rs
+++ b/Libraries/LibWasm/JIT/src/builder/calls.rs
@@ -213,6 +213,7 @@ impl Builder {
self.push(value);
}
self.call_epoch += 1;
+ self.check_exception(func, call);
Ok(())
}
}
diff --git a/Libraries/LibWasm/JIT/src/builder/exceptions.rs b/Libraries/LibWasm/JIT/src/builder/exceptions.rs
new file mode 100644
index 00000000000..0f0e8310bb0
--- /dev/null
+++ b/Libraries/LibWasm/JIT/src/builder/exceptions.rs
@@ -0,0 +1,515 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Exception handling, in the IR of the function.
+//!
+//! A handler is a `try_table`, or the body of a legacy `try`. Every way an exception comes up in a handler's region
+//! is an edge to the handler's dispatch, carrying the exception: a throw branches there, and a call checks the
+//! context's `exception` when it returns, which the runtime sets when it unwinds an exception to the call (a call
+//! with `FLAG_CHECKS_EXCEPTION` is an exception site). The dispatch is a block of its own, made where the region ends,
+//! which tests the clauses in order: the first that catches the exception gets what it pushes, and an exception none
+//! catches goes on to the handler around, or leaves the function through `Op::Throw`, which has the runtime unwind it
+//! to the callers.
+//!
+//! The clauses of a `try_table` branch to labels around it. Those of a legacy `try` branch to its handlers, the
+//! `catch` and `catch_all` blocks that follow its body, which run outside the region and keep the exception for
+//! `rethrow`. A body that ends with `delegate` has no clauses, and its exceptions go to the handler that the label is,
+//! or is in.
+
+use super::{Builder, ControlKind, Edge};
+use crate::ir::{BlockId, FLAG_CHECKS_EXCEPTION, Func, Helper, IntCondition, NONE, Node, Op, Type, Value};
+use libwasm_module::Module;
+use libwasm_module::abi::{EXCEPTION_PAYLOAD_OFFSET, EXCEPTION_TAG_OFFSET, ExecutionContext, InstanceData};
+use libwasm_module::types::ValType;
+use std::mem::offset_of;
+
+/// A clause of a handler: catch (0), catch_ref (1), catch_all (2) or catch_all_ref (3), its tag, and for `try_table`
+/// its label. For a legacy `try`, once the dispatch is made, the block and successor slot of its edge to the handler,
+/// or NONE.
+#[derive(Debug, Clone, Copy)]
+pub(super) struct Clause {
+ pub kind: u32,
+ pub tag: u32,
+ pub label: u32,
+ pub block: BlockId,
+}
+
+const CATCH_ALL: u32 = 2;
+
+fn pushes_reference(kind: u32) -> bool {
+ kind == 1 || kind == 3
+}
+
+impl Builder {
+ /// The parameter types of tag `tag`.
+ fn tag_params(module: &Module, tag: u32) -> &[ValType] {
+ let type_index = module.tag_space[tag as usize].type_index;
+ &module.types[type_index as usize]
+ .as_func()
+ .expect("tags have function types")
+ .params
+ }
+
+ /// Makes the construct just pushed a handler, with the clauses from `clauses` on.
+ fn begin_handler(&mut self, clauses: usize) {
+ let index = self.controls.len() - 1;
+ let control = &mut self.controls[index];
+ control.clauses = (clauses as u32, (self.clauses.len() - clauses) as u32);
+ control.outer_handler = self.handler;
+ self.handler = index as u32;
+ }
+
+ pub(super) fn begin_try_table(&mut self, params: (u32, u32), results: (u32, u32), clauses: &[[u32; 3]]) {
+ let start = self.clauses.len();
+ self.clauses.extend(clauses.iter().map(|&[kind, tag, label]| Clause {
+ kind,
+ tag,
+ label,
+ block: NONE,
+ }));
+ self.push_control(ControlKind::TryTable, params, results, NONE);
+ self.begin_handler(start);
+ }
+
+ /// A legacy `try` whose body starts at module offset `body`.
+ pub(super) fn begin_try(&mut self, module: &Module, params: (u32, u32), results: (u32, u32), body: usize) {
+ let info = &module.function_infos[self.defined as usize];
+ let region = info
+ .try_regions
+ .iter()
+ .find(|region| region.start as usize == body)
+ .expect("validation made a region of every try");
+ let start = self.clauses.len();
+ let clauses =
+ &info.catch_clauses[region.first_clause as usize..(region.first_clause + region.clause_count) as usize];
+ for clause in clauses {
+ let kind = match clause.kind {
+ libwasm_module::validator::CatchKind::Catch => 0,
+ _ => CATCH_ALL,
+ };
+ self.clauses.push(Clause {
+ kind,
+ tag: clause.tag,
+ label: NONE,
+ block: NONE,
+ });
+ }
+ self.push_control(ControlKind::Try, params, results, NONE);
+ self.begin_handler(start);
+ }
+
+ /// Records an edge from the current block, through the successor `slot`, to the dispatch of the handler
+ /// `controls[handler]`, carrying `exception`.
+ fn add_throw_edge(&mut self, handler: u32, slot: u32, exception: Value) {
+ let values = self.edge_values.len() as u32;
+ self.edge_values.push(exception);
+ let control = &mut self.controls[handler as usize];
+ self.edges.push(Edge {
+ block: self.current_block,
+ slot,
+ values,
+ next: control.throws,
+ });
+ control.throws = self.edges.len() as u32 - 1;
+ }
+
+ /// Ends the current block by throwing `exception` to the handler `handler`, or out of the function if it is NONE.
+ fn throw_to(&mut self, func: &mut Func, handler: u32, exception: Value) {
+ if handler == NONE {
+ self.terminate(func, Node::new(Op::Throw, Type::None, 0, [exception, 0, 0]), &[]);
+ } else {
+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
+ self.add_throw_edge(handler, slot, exception);
+ }
+ }
+
+ /// Throws `exception` from the current position, and makes what follows unreachable.
+ pub(super) fn throw_exception(&mut self, func: &mut Func, exception: Value) {
+ let handler = self.handler;
+ self.throw_to(func, handler, exception);
+ self.set_unreachable();
+ }
+
+ /// `throw tag`: a new exception with the tag and the values on the stack.
+ pub(super) fn throw_tag(&mut self, func: &mut Func, module: &Module, tag: u32) {
+ let identity = self.instance_pointer(func, offset_of!(InstanceData, tags), tag, Type::Pointer);
+ let exception = self.helper(func, Helper::AllocateException, &[identity], Type::Ref);
+ let payload = self.read_field(func, exception, EXCEPTION_PAYLOAD_OFFSET, Type::Pointer);
+ let params = Self::tag_params(module, tag);
+ // The payload is in operand stack order: the last value in the lowest slot.
+ let mut slot = 0;
+ for &param in params.iter().rev() {
+ let value = Self::resolve(func, self.pop());
+ self.write_payload(func, payload, slot, param, value);
+ slot += param.slot_count();
+ }
+ self.throw_exception(func, exception);
+ }
+
+ fn read_field(&mut self, func: &mut Func, pointer: Value, offset: usize, ty: Type) -> Value {
+ let bytes = if ty == Type::I32 { 4 } else { 8 };
+ Self::append(func, Node::new(Op::ReadField, ty, bytes, [pointer, offset as u32, 0]))
+ }
+
+ fn write_field(func: &mut Func, pointer: Value, offset: u32, value: Value) {
+ let bytes = if func.node(value).ty == Type::I32 { 4 } else { 8 };
+ Self::append(
+ func,
+ Node::new(Op::WriteField, Type::None, bytes, [pointer, value, offset]),
+ );
+ }
+
+ /// Stores `value`, of type `ty`, in the payload at `payload` from `slot` on.
+ fn write_payload(&mut self, func: &mut Func, payload: Value, slot: u32, ty: ValType, value: Value) {
+ let offset = 8 * slot;
+ match ty {
+ ValType::I32 | ValType::I64 | ValType::Ref(_) => Self::write_field(func, payload, offset, value),
+ ValType::F32 | ValType::F64 => {
+ let bits = if ty == ValType::F32 { Type::I32 } else { Type::I64 };
+ let bits = self.unary(func, Op::Reinterpret, bits, value);
+ Self::write_field(func, payload, offset, bits);
+ }
+ ValType::V128 => {
+ for lane in 0..2 {
+ let half = self.pure(
+ func,
+ Node::new(Op::ExtractLane, Type::I64, 0, [value, I64X2_EXTRACT_LANE, lane]),
+ );
+ Self::write_field(func, payload, offset + 8 * lane, half);
+ }
+ }
+ }
+ }
+
+ /// The value of type `ty` in the payload at `payload` from `slot` on.
+ fn read_payload(&mut self, func: &mut Func, payload: Value, slot: u32, ty: ValType) -> Value {
+ let offset = 8 * slot as usize;
+ match ty {
+ ValType::I32 => self.read_field(func, payload, offset, Type::I32),
+ ValType::I64 => self.read_field(func, payload, offset, Type::I64),
+ ValType::Ref(_) => self.read_field(func, payload, offset, Type::Ref),
+ ValType::F32 => {
+ let bits = self.read_field(func, payload, offset, Type::I32);
+ self.unary(func, Op::Reinterpret, Type::F32, bits)
+ }
+ ValType::F64 => {
+ let bits = self.read_field(func, payload, offset, Type::I64);
+ self.unary(func, Op::Reinterpret, Type::F64, bits)
+ }
+ ValType::V128 => {
+ let low = self.read_field(func, payload, offset, Type::I64);
+ let high = self.read_field(func, payload, offset + 8, Type::I64);
+ let vector = self.pure(func, Node::new(Op::VectorUnary, Type::V128, 0, [low, I64X2_SPLAT, 0]));
+ self.pure(
+ func,
+ Node::new(
+ Op::ReplaceLane,
+ Type::V128,
+ 0,
+ [vector, high, I64X2_REPLACE_LANE | (1 << 16)],
+ ),
+ )
+ }
+ }
+ }
+
+ /// Pushes what a clause of `kind` with tag `tag` pushes for `exception`.
+ fn push_caught(&mut self, func: &mut Func, module: &Module, kind: u32, tag: u32, exception: Value) {
+ if kind < CATCH_ALL {
+ let params = Self::tag_params(module, tag);
+ let payload = self.read_field(func, exception, EXCEPTION_PAYLOAD_OFFSET, Type::Pointer);
+ let mut slot: u32 = params.iter().map(|param| param.slot_count()).sum();
+ for &param in params {
+ slot -= param.slot_count();
+ let value = self.read_payload(func, payload, slot, param);
+ self.push(value);
+ }
+ }
+ if pushes_reference(kind) {
+ self.push(exception);
+ }
+ }
+
+ /// After a call in a handler's region: continues at the handler's dispatch if the call threw.
+ pub(super) fn check_exception(&mut self, func: &mut Func, call: Value) {
+ let handler = self.handler;
+ if handler == NONE {
+ return;
+ }
+ func.nodes[call as usize].flags |= FLAG_CHECKS_EXCEPTION;
+ let context = self.instance_field(func, offset_of!(InstanceData, context));
+ let exception = self.read_field(func, context, offset_of!(ExecutionContext, exception), Type::Ref);
+ let zero = self.constant(func, Type::Ref, 0);
+ let slot = self.terminate(
+ func,
+ Node::new(
+ Op::BranchCompare,
+ Type::None,
+ IntCondition::Ne as u8,
+ [exception, zero, 0],
+ ),
+ &[NONE, NONE],
+ );
+ self.add_throw_edge(handler, slot, exception);
+ self.continue_after(func, slot + 1);
+ }
+
+ /// Starts a block whose only predecessor is the current block, through its successor `slot`.
+ fn continue_after(&mut self, func: &mut Func, slot: u32) {
+ let block = self.current_block;
+ self.continue_from(func, block, slot);
+ }
+
+ /// Starts a block whose only predecessor is `predecessor`, through its successor `slot`.
+ fn continue_from(&mut self, func: &mut Func, predecessor: BlockId, slot: u32) {
+ let block = self.new_block(func);
+ Self::set_predecessors(func, block, &[predecessor]);
+ func.successors[slot as usize] = block;
+ self.start_block(func, block);
+ }
+
+ /// Makes the dispatch of the handler `controls[index]`, if anything throws to it, and returns the exception it
+ /// starts with, in its block, which is current then. Clears the context's `exception`, which a call that threw
+ /// left there.
+ fn begin_dispatch(&mut self, func: &mut Func, index: usize) -> Option<Value> {
+ let control = self.controls[index];
+ if control.throws == NONE {
+ return None;
+ }
+ self.collect_edges(control.throws);
+ let block = self.new_block(func);
+ let predecessors = std::mem::take(&mut self.scratch_blocks);
+ Self::set_predecessors(func, block, &predecessors);
+ self.scratch_blocks = predecessors;
+ for &edge in &self.scratch_values {
+ func.successors[self.edges[edge as usize].slot as usize] = block;
+ }
+ self.start_block(func, block);
+ let first = Self::resolve(
+ func,
+ self.edge_values[self.edges[self.scratch_values[0] as usize].values as usize],
+ );
+ let all_same = self
+ .scratch_values
+ .iter()
+ .all(|edge| Self::resolve(func, self.edge_values[self.edges[*edge as usize].values as usize]) == first);
+ let exception = if all_same {
+ first
+ } else {
+ let phi = Self::new_phi(func, block, Type::Ref);
+ let start = func.operands.len() as u32;
+ for &edge in &self.scratch_values {
+ let value = self.edge_values[self.edges[edge as usize].values as usize];
+ func.operands.push(Self::resolve(func, value));
+ }
+ func.nodes[phi as usize].args[0] = start;
+ func.nodes[phi as usize].args[1] = self.scratch_values.len() as u32;
+ phi
+ };
+ let context = self.instance_field(func, offset_of!(InstanceData, context));
+ let zero = self.constant(func, Type::I64, 0);
+ Self::append(
+ func,
+ Node::new(
+ Op::WriteField,
+ Type::None,
+ 8,
+ [context, zero, offset_of!(ExecutionContext, exception) as u32],
+ ),
+ );
+ Some(exception)
+ }
+
+ /// Ends the current block with a test of whether `exception` has tag `tag`, whose first successor is the match,
+ /// and returns the block and the slot of that successor.
+ fn test_tag(&mut self, func: &mut Func, tag: u32, exception: Value) -> (BlockId, u32) {
+ let identity = self.instance_pointer(func, offset_of!(InstanceData, tags), tag, Type::Pointer);
+ let thrown = self.read_field(func, exception, EXCEPTION_TAG_OFFSET, Type::Pointer);
+ let slot = self.terminate(
+ func,
+ Node::new(
+ Op::BranchCompare,
+ Type::None,
+ IntCondition::Eq as u8,
+ [thrown, identity, 0],
+ ),
+ &[NONE, NONE],
+ );
+ (self.current_block, slot)
+ }
+
+ /// Ends the body of the handler `controls[index]`: the fallthrough goes to the end of the construct, and the
+ /// handler stops being the current one.
+ fn end_region(&mut self, func: &mut Func, index: usize) {
+ let control = self.controls[index];
+ if !control.unreachable {
+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
+ self.add_edge(index, slot);
+ self.controls[index].unreachable = true;
+ }
+ self.unnumber(control.numbering_mark);
+ self.stack.truncate(control.height as usize);
+ self.handler = control.outer_handler;
+ }
+
+ /// The `end` of a `try_table`.
+ pub(super) fn end_try_table(&mut self, func: &mut Func, module: &Module, index: usize) {
+ let control = self.controls[index];
+ if control.throws == NONE {
+ self.handler = control.outer_handler;
+ self.end_block(func, index);
+ return;
+ }
+ self.end_region(func, index);
+ let exception = self.begin_dispatch(func, index).expect("something throws");
+ let mut caught_all = false;
+ for clause_index in control.clauses.0..control.clauses.0 + control.clauses.1 {
+ let clause = self.clauses[clause_index as usize];
+ let otherwise = if clause.kind < CATCH_ALL {
+ let (test, slot) = self.test_tag(func, clause.tag, exception);
+ self.continue_from(func, test, slot);
+ Some((test, slot + 1))
+ } else {
+ None
+ };
+ self.push_caught(func, module, clause.kind, clause.tag, exception);
+ // NB: The labels are counted from outside the try_table, whose own construct is still open.
+ self.branch(func, clause.label + 1);
+ self.stack.truncate(control.height as usize);
+ match otherwise {
+ Some((test, slot)) => self.continue_from(func, test, slot),
+ None => {
+ caught_all = true;
+ break;
+ }
+ }
+ }
+ if !caught_all {
+ self.throw_to(func, control.outer_handler, exception);
+ }
+ self.end_block(func, index);
+ }
+
+ /// `catch` or `catch_all` of a legacy `try`: ends the body or the previous handler, and starts the next handler.
+ pub(super) fn begin_catch(&mut self, func: &mut Func, module: &Module) {
+ let index = self.controls.len() - 1;
+ let control = self.controls[index];
+ if control.kind == ControlKind::Try {
+ self.end_region(func, index);
+ // The dispatch branches to each handler that catches, in order; the handlers' blocks come later.
+ let exception = self.begin_dispatch(func, index);
+ let mut caught_all = false;
+ if let Some(exception) = exception {
+ for clause_index in control.clauses.0..control.clauses.0 + control.clauses.1 {
+ let clause = self.clauses[clause_index as usize];
+ let (block, slot) = if clause.kind == CATCH_ALL {
+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
+ (self.current_block, slot)
+ } else {
+ self.test_tag(func, clause.tag, exception)
+ };
+ self.clauses[clause_index as usize].label = slot;
+ self.clauses[clause_index as usize].block = block;
+ if clause.kind == CATCH_ALL {
+ caught_all = true;
+ break;
+ }
+ self.continue_from(func, block, slot + 1);
+ }
+ if !caught_all {
+ self.throw_to(func, control.outer_handler, exception);
+ }
+ }
+ let control = &mut self.controls[index];
+ control.kind = ControlKind::Catch;
+ control.exception = exception.unwrap_or(NONE);
+ control.next_clause = control.clauses.0;
+ } else {
+ // The end of the previous handler.
+ if !control.unreachable {
+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
+ self.add_edge(index, slot);
+ }
+ self.unnumber(control.numbering_mark);
+ self.stack.truncate(control.height as usize);
+ }
+ let control = self.controls[index];
+ let clause_index = control.next_clause;
+ self.controls[index].next_clause += 1;
+ let clause = self.clauses[clause_index as usize];
+ if control.exception == NONE || clause.label == NONE {
+ // Nothing throws to the try, or an earlier catch_all catches everything: the handler is unreachable.
+ self.controls[index].unreachable = true;
+ return;
+ }
+ // The dispatch's edge to this handler: the first successor of the test's block, or the jump of catch_all.
+ self.continue_from(func, clause.block, clause.label);
+ self.controls[index].unreachable = false;
+ self.push_caught(func, module, clause.kind, clause.tag, control.exception);
+ }
+
+ /// The `end` of a legacy `try`, after its body or a handler.
+ pub(super) fn end_try(&mut self, func: &mut Func, index: usize) {
+ let control = self.controls[index];
+ if control.kind == ControlKind::Try {
+ // A try without handlers: what its body throws goes on to the handler around it.
+ if control.throws == NONE {
+ self.handler = control.outer_handler;
+ self.end_block(func, index);
+ return;
+ }
+ self.end_region(func, index);
+ let exception = self.begin_dispatch(func, index).expect("something throws");
+ self.throw_to(func, control.outer_handler, exception);
+ }
+ self.end_block(func, index);
+ }
+
+ /// `delegate label` of a legacy `try`: its body ends, and what it throws goes to the handler that the label is,
+ /// or the one around it.
+ pub(super) fn delegate(&mut self, func: &mut Func, label: u32) {
+ let index = self.controls.len() - 1;
+ let control = self.controls[index];
+ self.handler = control.outer_handler;
+ if control.throws != NONE {
+ // The label is counted from outside the try. A legacy try whose body is open catches what is delegated to
+ // its label; any other construct passes it on to the handler around it.
+ let target = index - 1 - label as usize;
+ let mut handler = control.outer_handler;
+ while handler != NONE
+ && !(handler as usize == target && self.controls[target].kind == ControlKind::Try)
+ && handler as usize >= target
+ {
+ handler = self.controls[handler as usize].outer_handler;
+ }
+ if !control.unreachable {
+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);
+ self.add_edge(index, slot);
+ self.controls[index].unreachable = true;
+ }
+ self.unnumber(control.numbering_mark);
+ self.stack.truncate(control.height as usize);
+ let exception = self.begin_dispatch(func, index).expect("something throws");
+ self.throw_to(func, handler, exception);
+ }
+ self.end_block(func, index);
+ }
+
+ /// `rethrow label`: throws the exception the legacy handler `label` caught again.
+ pub(super) fn rethrow(&mut self, func: &mut Func, label: u32) {
+ let index = self.controls.len() - 1 - label as usize;
+ let exception = self.controls[index].exception;
+ debug_assert_ne!(
+ exception, NONE,
+ "a reachable rethrow is in a handler that caught something"
+ );
+ self.throw_exception(func, exception);
+ }
+}
+
+const I64X2_SPLAT: u32 = 0x12;
+const I64X2_EXTRACT_LANE: u32 = 0x1d;
+const I64X2_REPLACE_LANE: u32 = 0x1e;
diff --git a/Libraries/LibWasm/JIT/src/builder/gc.rs b/Libraries/LibWasm/JIT/src/builder/gc.rs
new file mode 100644
index 00000000000..d0c02b41d5e
--- /dev/null
+++ b/Libraries/LibWasm/JIT/src/builder/gc.rs
@@ -0,0 +1,503 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The GC instructions (the `0xFB` prefix): structs, arrays, i31 references, and tests and casts of references.
+//!
+//! Objects are cells of the runtime's heap (see `abi::Rtt`): the Rtt first, the data's address at OBJECT_DATA_OFFSET
+//! and an array's length at OBJECT_LENGTH_OFFSET. Data of up to `MAX_INLINE_DATA_SIZE` bytes is inline at
+//! OBJECT_INLINE_DATA_OFFSET, so a struct's fields are at constant offsets from the object where the struct is small
+//! enough. Fields take 8 bytes (16 for v128), with packed and 32-bit values zero-extended in them.
+//!
+//! GC references in compiled frames need nothing special: the collector scans the stack conservatively and recognizes
+//! pointers into cells, and every allocation is a call of the runtime, around which values live in stack slots or in
+//! registers the runtime saves. The data of a large object lives outside the heap, so its address does not keep the
+//! object alive; that address is read where the access is (`ReadField` and `ElementAddress` are not pure), so the
+//! object is live up to there.
+
+use super::Builder;
+use crate::ir::{Func, HeapTest, Helper, LoadKind, Node, Op, REF_TEST_CAST, REF_TEST_NULLABLE, Type, Value};
+use libwasm_module::Module;
+use libwasm_module::abi::{
+ InstanceData, OBJECT_DATA_OFFSET, OBJECT_INLINE_DATA_OFFSET, OBJECT_LENGTH_OFFSET, TRAP_MEMORY_OUT_OF_BOUNDS,
+ TRAP_NULL_REFERENCE, TRAP_TABLE_OUT_OF_BOUNDS,
+};
+use libwasm_module::opcode::gc::*;
+use libwasm_module::opcode::simd::I64X2_EXTRACT_LANE;
+use libwasm_module::types::{CompositeType, HeapType, StorageType, ValType};
+use std::mem::offset_of;
+
+/// The most data an object has inline, which is the largest size class of the runtime's heap (heap.rs).
+pub const MAX_INLINE_DATA_SIZE: u32 = 4096;
+
+/// The bytes a field or element of `storage` takes in an object.
+fn storage_bytes(storage: StorageType) -> u32 {
+ if storage == StorageType::Val(ValType::V128) {
+ 16
+ } else {
+ 8
+ }
+}
+
+/// The bytes an element of `storage` takes in a data segment.
+fn data_bytes(storage: StorageType) -> u64 {
+ match storage {
+ StorageType::I8 => 1,
+ StorageType::I16 => 2,
+ StorageType::Val(ValType::I32 | ValType::F32) => 4,
+ StorageType::Val(ValType::V128) => 16,
+ StorageType::Val(_) => 8,
+ }
+}
+
+/// The log2 of the bytes a store of a value of `storage` writes.
+fn store_size_log2(storage: StorageType) -> u8 {
+ match storage {
+ StorageType::I8 => 0,
+ StorageType::I16 => 1,
+ StorageType::Val(ValType::I32 | ValType::F32) => 2,
+ StorageType::Val(ValType::V128) => 4,
+ StorageType::Val(_) => 3,
+ }
+}
+
+fn struct_fields(module: &Module, type_index: u32) -> &[libwasm_module::types::FieldType] {
+ match &module.types[type_index as usize].composite {
+ CompositeType::Struct(fields) => fields,
+ _ => unreachable!("validated code accesses fields of struct types"),
+ }
+}
+
+fn array_storage(module: &Module, type_index: u32) -> StorageType {
+ match &module.types[type_index as usize].composite {
+ CompositeType::Array(element) => element.storage,
+ _ => unreachable!("validated code accesses elements of array types"),
+ }
+}
+
+/// The number of supertypes above the module's type `type_index`.
+fn type_depth(module: &Module, mut type_index: u32) -> u32 {
+ let mut depth = 0;
+ while let Some(&supertype) = module.types[type_index as usize].supertypes.first() {
+ type_index = supertype;
+ depth += 1;
+ }
+ depth
+}
+
+impl Builder {
+ /// The byte offset of field `field` in the data of a struct of the module's type `type_index`, or with `field`
+ /// equal to the field count, the size of its data.
+ fn field_offset(&mut self, module: &Module, type_index: u32, field: u32) -> u32 {
+ let key = (u64::from(type_index) << 32) | u64::from(field);
+ if let Some(offset) = self.field_offsets.get(key) {
+ return offset;
+ }
+ let mut offset = 0;
+ for (index, field_type) in struct_fields(module, type_index).iter().enumerate() {
+ self.field_offsets
+ .insert((u64::from(type_index) << 32) | index as u64, offset);
+ offset += storage_bytes(field_type.storage);
+ }
+ let count = struct_fields(module, type_index).len() as u64;
+ self.field_offsets.insert((u64::from(type_index) << 32) | count, offset);
+ self.field_offsets.get(key).expect("every field has an offset")
+ }
+
+ /// The runtime type of the module's type `type_index`.
+ fn rtt(&mut self, func: &mut Func, type_index: u32) -> Value {
+ self.pure(
+ func,
+ Node::new(Op::Rtt, Type::Pointer, 0, [self.instance, type_index, 0]),
+ )
+ }
+
+ /// Where the data of an object with `size` bytes of it is: the object and the offset of its inline data, or the
+ /// address of data outside the heap.
+ fn object_data(func: &mut Func, object: Value, size: u32) -> (Value, u32) {
+ if size <= MAX_INLINE_DATA_SIZE {
+ return (object, OBJECT_INLINE_DATA_OFFSET as u32);
+ }
+ let data = Self::append(
+ func,
+ Node::new(Op::ReadField, Type::Pointer, 8, [object, OBJECT_DATA_OFFSET as u32, 0]),
+ );
+ (data, 0)
+ }
+
+ /// A field or element of `storage` at `base` + `offset`, sign-extended if it is packed and `signed`.
+ fn load_field(&mut self, func: &mut Func, base: Value, offset: u32, storage: StorageType, signed: bool) -> Value {
+ let (kind, ty) = match storage {
+ StorageType::I8 if signed => (LoadKind::I32S8, Type::I32),
+ StorageType::I8 => (LoadKind::I32U8, Type::I32),
+ StorageType::I16 if signed => (LoadKind::I32S16, Type::I32),
+ StorageType::I16 => (LoadKind::I32U16, Type::I32),
+ StorageType::Val(ValType::I32) => (LoadKind::I32, Type::I32),
+ StorageType::Val(ValType::F32) => (LoadKind::F32, Type::F32),
+ StorageType::Val(ValType::F64) => (LoadKind::F64, Type::F64),
+ StorageType::Val(ValType::I64) => (LoadKind::I64, Type::I64),
+ StorageType::Val(ValType::Ref(_)) => (LoadKind::I64, Type::Ref),
+ StorageType::Val(ValType::V128) => {
+ let zero = self.constant(func, Type::I32, 0);
+ // NB: The flags are the sub-opcode of `v128.load`, which is 0.
+ return Self::append(func, Node::new(Op::VectorLoad, Type::V128, 0, [base, zero, offset]));
+ }
+ };
+ self.load_at(func, kind, ty, base, offset)
+ }
+
+ fn check_null(func: &mut Func, reference: Value) {
+ Self::append(
+ func,
+ Node::new(Op::CheckNull, Type::None, TRAP_NULL_REFERENCE as u8, [reference, 0, 0]),
+ );
+ }
+
+ /// A call of the runtime that allocates an object of the module's type `type_index` with `size` bytes of zeroed
+ /// data and, for an array, `length` elements (both i64 values).
+ fn allocate(&mut self, func: &mut Func, type_index: u32, size: Value, length: Value) -> Value {
+ let rtt = self.rtt(func, type_index);
+ self.helper(func, Helper::Allocate, &[rtt, size, length], Type::Ref)
+ }
+
+ /// The bits of an element's value as the runtime's functions take them: the low and the high 64 bits.
+ fn value_bits(&mut self, func: &mut Func, value: Value, storage: StorageType) -> (Value, Value) {
+ let value = Self::resolve(func, value);
+ let zero = self.constant(func, Type::I64, 0);
+ match storage {
+ StorageType::Val(ValType::F32) => {
+ let bits = self.pure(func, Node::new(Op::Reinterpret, Type::I32, 0, [value, 0, 0]));
+ (bits, zero)
+ }
+ StorageType::Val(ValType::F64) => {
+ let bits = self.pure(func, Node::new(Op::Reinterpret, Type::I64, 0, [value, 0, 0]));
+ (bits, zero)
+ }
+ StorageType::Val(ValType::V128) => {
+ let low = self.pure(
+ func,
+ Node::new(Op::ExtractLane, Type::I64, 0, [value, I64X2_EXTRACT_LANE, 0]),
+ );
+ let high = self.pure(
+ func,
+ Node::new(Op::ExtractLane, Type::I64, 0, [value, I64X2_EXTRACT_LANE, 1]),
+ );
+ (low, high)
+ }
+ _ => (value, zero),
+ }
+ }
+
+ /// Whether `value` is the zero of its type, which every new object's fields start as.
+ fn is_zero(&self, func: &Func, value: Value) -> bool {
+ let value = Self::resolve(func, value);
+ func.node(value).constant() == Some(0) || (value == self.vector_zero && value != crate::ir::NONE)
+ }
+
+ /// The test of `reference` against `heap`, as an i32, or for a cast, a check that traps.
+ fn ref_test(
+ &mut self,
+ func: &mut Func,
+ module: &Module,
+ reference: Value,
+ heap: HeapType,
+ nullable: bool,
+ cast: bool,
+ ) -> Value {
+ let reference = Self::resolve(func, reference);
+ let (test, identity, depth) = match heap {
+ HeapType::Any | HeapType::Func | HeapType::Extern | HeapType::Exn => (HeapTest::NonNull, None, 0),
+ HeapType::Eq => (HeapTest::Eq, None, 0),
+ HeapType::I31 => (HeapTest::I31, None, 0),
+ HeapType::Struct => (HeapTest::Struct, None, 0),
+ HeapType::Array => (HeapTest::Array, None, 0),
+ HeapType::None | HeapType::NoFunc | HeapType::NoExtern | HeapType::NoExn | HeapType::Bottom => {
+ (HeapTest::Nothing, None, 0)
+ }
+ HeapType::Concrete(type_index) => {
+ let test = match module.types[type_index as usize].composite {
+ CompositeType::Func(_) => HeapTest::ConcreteFunction,
+ _ => HeapTest::ConcreteObject,
+ };
+ (
+ test,
+ Some(self.type_identity(func, type_index)),
+ type_depth(module, type_index),
+ )
+ }
+ };
+ let identity = match identity {
+ Some(identity) => identity,
+ None => self.constant(func, Type::I32, 0),
+ };
+ let mut flags = test as u8;
+ if nullable {
+ flags |= REF_TEST_NULLABLE;
+ }
+ if cast {
+ flags |= REF_TEST_CAST;
+ return Self::append(
+ func,
+ Node::new(Op::RefTest, Type::None, flags, [reference, identity, depth]),
+ );
+ }
+ self.pure(
+ func,
+ Node::new(Op::RefTest, Type::I32, flags, [reference, identity, depth]),
+ )
+ }
+
+ /// The instructions of the `0xFB` prefix, with the immediates the decoder kept.
+ pub(super) fn gc(
+ &mut self,
+ func: &mut Func,
+ module: &Module,
+ sub_opcode: u32,
+ [first, second]: [u32; 2],
+ heap_types: [HeapType; 2],
+ cast_flags: u8,
+ ) {
+ match sub_opcode {
+ STRUCT_NEW | STRUCT_NEW_DEFAULT => {
+ let count = struct_fields(module, first).len();
+ let size = self.field_offset(module, first, count as u32);
+ let mut values = Vec::new();
+ if sub_opcode == STRUCT_NEW {
+ values = self.stack.split_off(self.stack.len() - count);
+ }
+ let size_value = self.constant(func, Type::I64, u64::from(size));
+ let zero = self.constant(func, Type::I64, 0);
+ let object = self.allocate(func, first, size_value, zero);
+ if !values.is_empty() {
+ let (base, data_offset) = Self::object_data(func, object, size);
+ for (index, &value) in values.iter().enumerate() {
+ if self.is_zero(func, value) {
+ continue;
+ }
+ let storage = struct_fields(module, first)[index].storage;
+ let offset = data_offset + self.field_offset(module, first, index as u32);
+ self.store_at(func, store_size_log2(storage), base, offset, value);
+ }
+ }
+ self.push(object);
+ }
+ STRUCT_GET | STRUCT_GET_S | STRUCT_GET_U => {
+ let object = Self::resolve(func, self.pop());
+ Self::check_null(func, object);
+ let count = struct_fields(module, first).len() as u32;
+ let size = self.field_offset(module, first, count);
+ let (base, data_offset) = Self::object_data(func, object, size);
+ let offset = data_offset + self.field_offset(module, first, second);
+ let storage = struct_fields(module, first)[second as usize].storage;
+ let value = self.load_field(func, base, offset, storage, sub_opcode == STRUCT_GET_S);
+ self.push(value);
+ }
+ STRUCT_SET => {
+ let value = self.pop();
+ let object = Self::resolve(func, self.pop());
+ Self::check_null(func, object);
+ let count = struct_fields(module, first).len() as u32;
+ let size = self.field_offset(module, first, count);
+ let (base, data_offset) = Self::object_data(func, object, size);
+ let offset = data_offset + self.field_offset(module, first, second);
+ let storage = struct_fields(module, first)[second as usize].storage;
+ self.store_at(func, store_size_log2(storage), base, offset, value);
+ }
+ ARRAY_NEW | ARRAY_NEW_DEFAULT => {
+ let count = self.pop();
+ let storage = array_storage(module, first);
+ let length = self.unary(func, Op::ExtendI32U, Type::I64, count);
+ let element_size = self.constant(func, Type::I64, u64::from(storage_bytes(storage)));
+ let size = self.binary(func, Op::Mul, Type::I64, length, element_size);
+ let array = if sub_opcode == ARRAY_NEW {
+ let value = self.pop();
+ let array = self.allocate(func, first, size, length);
+ if !self.is_zero(func, value) {
+ let (low, high) = self.value_bits(func, value, storage);
+ let zero = self.constant(func, Type::I64, 0);
+ self.helper(func, Helper::ArrayFill, &[array, zero, low, high, length], Type::None);
+ }
+ array
+ } else {
+ self.allocate(func, first, size, length)
+ };
+ self.push(array);
+ }
+ ARRAY_NEW_FIXED => {
+ let storage = array_storage(module, first);
+ let values = self.stack.split_off(self.stack.len() - second as usize);
+ let element_size = storage_bytes(storage);
+ let data_size = second * element_size;
+ let size = self.constant(func, Type::I64, u64::from(data_size));
+ let length = self.constant(func, Type::I64, u64::from(second));
+ let array = self.allocate(func, first, size, length);
+ let (base, data_offset) = Self::object_data(func, array, data_size);
+ for (index, &value) in values.iter().enumerate() {
+ if self.is_zero(func, value) {
+ continue;
+ }
+ let offset = data_offset + index as u32 * element_size;
+ self.store_at(func, store_size_log2(storage), base, offset, value);
+ }
+ self.push(array);
+ }
+ ARRAY_NEW_DATA | ARRAY_NEW_ELEM => {
+ let count = self.pop();
+ let source = self.pop();
+ let storage = array_storage(module, first);
+ let (segments, unit, trap, init) = if sub_opcode == ARRAY_NEW_DATA {
+ (
+ offset_of!(InstanceData, data_segments),
+ data_bytes(storage),
+ TRAP_MEMORY_OUT_OF_BOUNDS,
+ Helper::ArrayInitData,
+ )
+ } else {
+ (
+ offset_of!(InstanceData, element_segments),
+ 1,
+ TRAP_TABLE_OUT_OF_BOUNDS,
+ Helper::ArrayInitElem,
+ )
+ };
+ let segment = self.segment(func, segments, second);
+ // The segment's range is checked first, before the array is allocated.
+ let unit = self.constant(func, Type::I64, unit);
+ let trap = self.constant(func, Type::I64, u64::from(trap));
+ self.helper(
+ func,
+ Helper::SegmentRange,
+ &[segment, source, count, unit, trap],
+ Type::None,
+ );
+ let length = self.unary(func, Op::ExtendI32U, Type::I64, count);
+ let element_size = self.constant(func, Type::I64, u64::from(storage_bytes(storage)));
+ let size = self.binary(func, Op::Mul, Type::I64, length, element_size);
+ let array = self.allocate(func, first, size, length);
+ let zero = self.constant(func, Type::I64, 0);
+ self.helper(func, init, &[array, segment, zero, source, count], Type::None);
+ self.push(array);
+ }
+ ARRAY_GET | ARRAY_GET_S | ARRAY_GET_U => {
+ let index = Self::resolve(func, self.pop());
+ let array = Self::resolve(func, self.pop());
+ let storage = array_storage(module, first);
+ let size_log2 = storage_bytes(storage).trailing_zeros() as u8;
+ let address = Self::append(
+ func,
+ Node::new(Op::ElementAddress, Type::Pointer, size_log2, [array, index, 0]),
+ );
+ let value = self.load_field(func, address, 0, storage, sub_opcode == ARRAY_GET_S);
+ self.push(value);
+ }
+ ARRAY_SET => {
+ let value = self.pop();
+ let index = Self::resolve(func, self.pop());
+ let array = Self::resolve(func, self.pop());
+ let storage = array_storage(module, first);
+ let size_log2 = storage_bytes(storage).trailing_zeros() as u8;
+ let address = Self::append(
+ func,
+ Node::new(Op::ElementAddress, Type::Pointer, size_log2, [array, index, 0]),
+ );
+ self.store_at(func, store_size_log2(storage), address, 0, value);
+ }
+ ARRAY_LEN => {
+ let array = Self::resolve(func, self.pop());
+ Self::check_null(func, array);
+ let length = Self::append(
+ func,
+ Node::new(Op::ReadField, Type::I32, 4, [array, OBJECT_LENGTH_OFFSET as u32, 0]),
+ );
+ self.push(length);
+ }
+ ARRAY_FILL => {
+ let count = self.pop();
+ let value = self.pop();
+ let start = self.pop();
+ let array = self.pop();
+ let (low, high) = self.value_bits(func, value, array_storage(module, first));
+ self.helper(func, Helper::ArrayFill, &[array, start, low, high, count], Type::None);
+ }
+ ARRAY_COPY => {
+ let count = self.pop();
+ let source_start = self.pop();
+ let source = self.pop();
+ let destination_start = self.pop();
+ let destination = self.pop();
+ self.helper(
+ func,
+ Helper::ArrayCopy,
+ &[destination, destination_start, source, source_start, count],
+ Type::None,
+ );
+ }
+ ARRAY_INIT_DATA | ARRAY_INIT_ELEM => {
+ let count = self.pop();
+ let source = self.pop();
+ let destination = self.pop();
+ let array = self.pop();
+ let (segments, init) = if sub_opcode == ARRAY_INIT_DATA {
+ (offset_of!(InstanceData, data_segments), Helper::ArrayInitData)
+ } else {
+ (offset_of!(InstanceData, element_segments), Helper::ArrayInitElem)
+ };
+ let segment = self.segment(func, segments, second);
+ self.helper(func, init, &[array, segment, destination, source, count], Type::None);
+ }
+ REF_TEST | REF_TEST_NULL => {
+ let reference = self.pop();
+ let value = self.ref_test(
+ func,
+ module,
+ reference,
+ heap_types[0],
+ sub_opcode == REF_TEST_NULL,
+ false,
+ );
+ self.push(value);
+ }
+ REF_CAST | REF_CAST_NULL => {
+ let reference = Self::resolve(func, self.pop());
+ self.ref_test(
+ func,
+ module,
+ reference,
+ heap_types[0],
+ sub_opcode == REF_CAST_NULL,
+ true,
+ );
+ self.push(reference);
+ }
+ BR_ON_CAST | BR_ON_CAST_FAIL => {
+ let reference = *self.stack.last().expect("br_on_cast has an operand");
+ let nullable = cast_flags & 2 != 0;
+ let matches = self.ref_test(func, module, reference, heap_types[1], nullable, false);
+ let condition = if sub_opcode == BR_ON_CAST {
+ matches
+ } else {
+ self.unary(func, Op::Eqz, Type::I32, matches)
+ };
+ self.conditional_branch(func, first, condition);
+ }
+ ANY_CONVERT_EXTERN | EXTERN_CONVERT_ANY => {
+ // References keep their bits between the any and extern hierarchies.
+ }
+ REF_I31 => {
+ let value = self.pop();
+ let reference = self.unary(func, Op::I31New, Type::Ref, value);
+ self.push(reference);
+ }
+ I31_GET_S | I31_GET_U => {
+ let reference = Self::resolve(func, self.pop());
+ Self::check_null(func, reference);
+ let flags = u8::from(sub_opcode == I31_GET_S);
+ let value = self.pure(func, Node::new(Op::I31Get, Type::I32, flags, [reference, 0, 0]));
+ self.push(value);
+ }
+ _ => unreachable!("validated code has no unknown 0xFB instruction {sub_opcode:#x}"),
+ }
+ }
+}
diff --git a/Libraries/LibWasm/JIT/src/builder/memories.rs b/Libraries/LibWasm/JIT/src/builder/memories.rs
new file mode 100644
index 00000000000..fdbda13678f
--- /dev/null
+++ b/Libraries/LibWasm/JIT/src/builder/memories.rs
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Accesses of memories without guard pages (memory64, and memories other than memory 0), and atomics. Both access
+//! the memory at a `CheckedAddress`, which checks the access against the memory's current size; atomic accesses are
+//! checked for alignment too, whatever memory they access.
+
+use super::{Builder, load_kind, store_size_log2};
+use crate::decode::{Decoder, MemoryArgument};
+use crate::ir::{AtomicOp, CHECKED_ATOMIC, CHECKED_MEMORY64, Func, Helper, LoadKind, Node, Op, Type, Value};
+use libwasm_module::Module;
+use libwasm_module::abi::TRAP_EXPECTED_SHARED_MEMORY;
+use libwasm_module::instruction_tables::{AtomicKind, atomic_kind};
+use libwasm_module::opcode::atomic;
+use libwasm_module::types::{AddressType, ValType};
+
+impl Builder {
+ /// The address of an access of `1 << size_log2` bytes at `index` + `argument.offset` in `argument.memory`, after
+ /// checking it (`Op::CheckedAddress`).
+ pub(super) fn checked_address(
+ &mut self,
+ func: &mut Func,
+ module: &Module,
+ argument: MemoryArgument,
+ index: Value,
+ size_log2: u8,
+ atomic: bool,
+ ) -> Value {
+ let memory64 = module.memory_space[argument.memory as usize].limits.address_type == AddressType::I64;
+ let index = Self::resolve(func, index);
+ let data = self.memory_data(func, argument.memory);
+ let offset = self.constant(func, Type::I64, argument.offset);
+ let mut flags = size_log2;
+ if atomic {
+ flags |= CHECKED_ATOMIC;
+ }
+ if memory64 {
+ flags |= CHECKED_MEMORY64;
+ }
+ Self::append(
+ func,
+ Node::new(Op::CheckedAddress, Type::Pointer, flags, [data, index, offset]),
+ )
+ }
+
+ /// A load of `kind` at `address`, a pointer.
+ pub(super) fn load_at(&mut self, func: &mut Func, kind: LoadKind, ty: Type, address: Value, offset: u32) -> Value {
+ let zero = self.constant(func, Type::I32, 0);
+ Self::append(func, Node::new(Op::Load, ty, kind as u8, [address, zero, offset]))
+ }
+
+ /// A store of `1 << size_log2` bytes of `value` at `address`, a pointer.
+ pub(super) fn store_at(&mut self, func: &mut Func, size_log2: u8, address: Value, offset: u32, value: Value) {
+ let zero = self.constant(func, Type::I32, 0);
+ let value = Self::resolve(func, value);
+ let start = func.operands.len() as u32;
+ func.operands.extend_from_slice(&[address, zero, value]);
+ Self::append(func, Node::new(Op::Store, Type::None, size_log2, [start, 3, offset]));
+ }
+
+ /// A core load or store in its bounds-checked form (quickening rule 1).
+ pub(super) fn checked_access(&mut self, func: &mut Func, module: &Module, opcode: u8, argument: MemoryArgument) {
+ if opcode <= libwasm_module::opcode::I64_LOAD32_U {
+ let (kind, ty) = load_kind(opcode);
+ let index = self.pop();
+ let size_log2 = kind.size().trailing_zeros() as u8;
+ let address = self.checked_address(func, module, argument, index, size_log2, false);
+ let value = self.load_at(func, kind, ty, address, 0);
+ self.push(value);
+ } else {
+ let value = self.pop();
+ let index = self.pop();
+ let size_log2 = store_size_log2(opcode);
+ let address = self.checked_address(func, module, argument, index, size_log2, false);
+ self.store_at(func, size_log2, address, 0, value);
+ }
+ }
+
+ /// The instructions of the `0xFE` prefix.
+ pub(super) fn atomic(&mut self, func: &mut Func, module: &Module, sub_opcode: u32, decoder: &Decoder<'_>) {
+ let argument = decoder.atomic_argument();
+ let kind = atomic_kind(sub_opcode).expect("validated code has no unknown atomic instructions");
+ let ir = |value: ValType| if value == ValType::I64 { Type::I64 } else { Type::I32 };
+ match kind {
+ AtomicKind::Fence => {
+ Self::append(func, Node::new(Op::AtomicFence, Type::None, 0, [0; 3]));
+ }
+ AtomicKind::Notify => {
+ let count = self.pop();
+ let index = self.pop();
+ let address = self.checked_address(func, module, argument, index, 2, true);
+ // Only a shared memory can have threads waiting on it.
+ let woken = if module.memory_space[argument.memory as usize].limits.shared {
+ self.helper(func, Helper::AtomicNotify, &[address, count], Type::I32)
+ } else {
+ self.constant(func, Type::I32, 0)
+ };
+ self.push(woken);
+ }
+ AtomicKind::Wait { value } => {
+ let timeout = self.pop();
+ let expected = self.pop();
+ let index = self.pop();
+ let size_log2 = if value == ValType::I64 { 3 } else { 2 };
+ let address = self.checked_address(func, module, argument, index, size_log2, true);
+ if !module.memory_space[argument.memory as usize].limits.shared {
+ self.terminate(
+ func,
+ Node::new(Op::Trap, Type::None, 0, [TRAP_EXPECTED_SHARED_MEMORY, 0, 0]),
+ &[],
+ );
+ self.set_unreachable();
+ return;
+ }
+ let size = self.constant(func, Type::I64, 1 << size_log2);
+ let result = self.helper(func, Helper::AtomicWait, &[address, expected, timeout, size], Type::I32);
+ self.push(result);
+ }
+ AtomicKind::Load { value, size } => {
+ let index = self.pop();
+ let size_log2 = size.trailing_zeros() as u8;
+ let address = self.checked_address(func, module, argument, index, size_log2, true);
+ let kind = match (value, size) {
+ (ValType::I64, 8) => LoadKind::I64,
+ (ValType::I64, 4) => LoadKind::I64U32,
+ (ValType::I64, 2) => LoadKind::I64U16,
+ (ValType::I64, _) => LoadKind::I64U8,
+ (_, 4) => LoadKind::I32,
+ (_, 2) => LoadKind::I32U16,
+ _ => LoadKind::I32U8,
+ };
+ // NB: Plain loads are sequentially consistent on x86-64, where stores are locked exchanges.
+ let loaded = self.load_at(func, kind, ir(value), address, 0);
+ self.push(loaded);
+ }
+ AtomicKind::Store { value, size } => {
+ let stored = Self::resolve(func, self.pop());
+ let index = self.pop();
+ let size_log2 = size.trailing_zeros() as u8;
+ let address = self.checked_address(func, module, argument, index, size_log2, true);
+ // An exchange is a sequentially consistent store.
+ Self::append(
+ func,
+ Node::new(
+ Op::AtomicRmw,
+ ir(value),
+ size_log2,
+ [address, stored, AtomicOp::Exchange as u32],
+ ),
+ );
+ }
+ AtomicKind::ReadModifyWrite { value, size } => {
+ let operand = Self::resolve(func, self.pop());
+ let index = self.pop();
+ let size_log2 = size.trailing_zeros() as u8;
+ let address = self.checked_address(func, module, argument, index, size_log2, true);
+ let op = AtomicOp::from_index((sub_opcode - atomic::I32_ATOMIC_RMW_ADD) / 7);
+ let old = Self::append(
+ func,
+ Node::new(Op::AtomicRmw, ir(value), size_log2, [address, operand, op as u32]),
+ );
+ self.push(old);
+ }
+ AtomicKind::CompareExchange { value, size } => {
+ let replacement = Self::resolve(func, self.pop());
+ let expected = Self::resolve(func, self.pop());
+ let index = self.pop();
+ let size_log2 = size.trailing_zeros() as u8;
+ let address = self.checked_address(func, module, argument, index, size_log2, true);
+ let old = Self::append(
+ func,
+ Node::new(
+ Op::AtomicCompareExchange,
+ ir(value),
+ size_log2,
+ [address, expected, replacement],
+ ),
+ );
+ self.push(old);
+ }
+ }
+ }
+}
diff --git a/Libraries/LibWasm/JIT/src/builder/mod.rs b/Libraries/LibWasm/JIT/src/builder/mod.rs
index 7ec43b557f1..0152e0a5394 100644
--- a/Libraries/LibWasm/JIT/src/builder/mod.rs
+++ b/Libraries/LibWasm/JIT/src/builder/mod.rs
@@ -24,7 +24,10 @@
//! dominates its use. Global values are numbered too, keyed by epochs that `global.set` and calls advance.
mod calls;
+mod exceptions;
pub mod fold;
+pub mod gc;
+mod memories;
mod simd;
mod tables;
@@ -61,6 +64,10 @@ enum ControlKind {
Loop,
If,
Else,
+ /// A `try_table`, the body of a legacy `try`, and a legacy `catch` or `catch_all` handler.
+ TryTable,
+ Try,
+ Catch,
}
/// The parameter and result types of a block, as ranges of `Builder::types`.
@@ -92,6 +99,15 @@ struct Control {
/// For loops, their index in `Func::loops` and the start of their incomplete phis.
loop_index: u32,
incomplete_start: u32,
+ /// For a handler (see `exceptions.rs`): the exceptions thrown in its region, as a list through `Builder::edges`
+ /// of edges carrying the exception, and the handler around it in `Builder::controls`, or NONE.
+ throws: u32,
+ outer_handler: u32,
+ /// For `try_table` and legacy `try`: the start and count of its clauses in `Builder::clauses`.
+ clauses: (u32, u32),
+ /// For a legacy handler: the exception it caught, or NONE if nothing throws to it, and its next clause.
+ exception: Value,
+ next_clause: u32,
}
impl Control {
@@ -173,8 +189,15 @@ pub struct Builder {
memory_base: Value,
/// The zero vector, which every v128 local starts as, once made.
vector_zero: Value,
+ /// The byte offsets of struct fields, by (type index, field index); the field count gives the size.
+ field_offsets: Table<u64>,
/// What an OSR compile needs (see `build_osr`), or what probing for one found.
osr: Option<Osr>,
+ /// The innermost handler whose region the code is in, as an index into `controls`, or NONE.
+ handler: u32,
+ clauses: Vec<exceptions::Clause>,
+ /// The function, among the module's defined ones.
+ defined: u32,
}
/// An OSR compile: the function as a continuation of an interpreter frame at an outermost loop.
@@ -244,6 +267,9 @@ impl Builder {
self.read_values.clear();
self.params.clear();
self.vector_zero = NONE;
+ self.field_offsets.clear();
+ self.handler = NONE;
+ self.clauses.clear();
}
/// Builds the IR of the defined function `index` (counting imports) of `module` into `func`.
@@ -300,6 +326,7 @@ impl Builder {
self.clear();
func.clear();
let defined = (index - module.imported_function_count) as usize;
+ self.defined = defined as u32;
let body = &module.code[defined];
let ty = module.function_type(index).expect("functions have function types");
let start = body.code.start as usize;
@@ -353,6 +380,11 @@ impl Builder {
numbering_mark: 0,
loop_index: NONE,
incomplete_start: 0,
+ throws: NONE,
+ outer_handler: NONE,
+ clauses: (0, 0),
+ exception: NONE,
+ next_clause: 0,
});
let mut decoder = Decoder::new(&module.bytes, start, body.code.end as usize);
@@ -944,7 +976,11 @@ impl Builder {
pc: usize,
) -> Result<(), CompileFailure> {
match instruction {
- Instruction::Else | Instruction::End => self.instruction(func, module, *instruction, decoder, pc),
+ Instruction::Else
+ | Instruction::End
+ | Instruction::Catch(_)
+ | Instruction::CatchAll
+ | Instruction::Delegate(_) => self.instruction(func, module, *instruction, decoder, pc),
_ if crate::decode::nesting_change(instruction) > 0 => {
// Skips the nested construct, which is unreachable as a whole.
let mut depth = 1;
@@ -984,7 +1020,11 @@ impl Builder {
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);
+ // NB: A legacy handler's exception is no value the frame has, so loops in handlers do not OSR.
+ let outermost = !self
+ .controls
+ .iter()
+ .any(|control| matches!(control.kind, ControlKind::Loop | ControlKind::Catch));
let stack_types = self.stack.iter().map(|value| func.node(*value).ty).collect();
let osr = self.osr.as_mut().expect("probing");
osr.found = outermost;
@@ -1000,7 +1040,7 @@ impl Builder {
self.begin_if(func, params, results);
}
I::Else => self.begin_else(func),
- I::End => self.end(func),
+ I::End => self.end(func, module),
I::Br(depth) => {
self.branch(func, depth);
self.set_unreachable();
@@ -1103,7 +1143,7 @@ impl Builder {
let value = self.pure(func, Node::new(op, ty, 0, [a, 0, 0]));
self.push(value);
}
- I::CheckedAccess { .. } => return unsupported(pc, "an access of a memory without guard pages"),
+ I::CheckedAccess { opcode, argument } => self.checked_access(func, module, opcode, argument),
I::MemorySize(memory) => self.memory_size(func, module, memory),
I::MemoryGrow(memory) => self.memory_grow(func, module, memory),
I::CallIndirect { type_index, table } => {
@@ -1115,14 +1155,27 @@ 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(_)
- | I::Try(_)
- | I::Catch(_)
- | I::CatchAll
- | I::Delegate(_)
- | I::Rethrow(_) => return unsupported(pc, "exception handling"),
+ I::TryTable(block_type) => {
+ let (params, results) = self.block_signature(module, block_type)?;
+ let clauses: Vec<[u32; 3]> = decoder.catch_clauses().collect();
+ self.begin_try_table(params, results, &clauses);
+ }
+ I::Try(block_type) => {
+ let (params, results) = self.block_signature(module, block_type)?;
+ self.begin_try(module, params, results, decoder.position());
+ }
+ I::Catch(_) | I::CatchAll => self.begin_catch(func, module),
+ I::Delegate(label) => self.delegate(func, label),
+ I::Throw(tag) => self.throw_tag(func, module, tag),
+ I::ThrowRef => {
+ let exception = Self::resolve(func, self.pop());
+ Self::append(
+ func,
+ Node::new(Op::CheckNull, Type::None, TRAP_NULL_REFERENCE as u8, [exception, 0, 0]),
+ );
+ self.throw_exception(func, exception);
+ }
+ I::Rethrow(label) => self.rethrow(func, label),
I::TableGet(table) => self.table_get(func, table),
I::TableSet(table) => self.table_set(func, table),
I::RefNull(_) => {
@@ -1171,7 +1224,14 @@ impl Builder {
}
}
I::Misc(sub_opcode) => self.bulk(func, module, sub_opcode, decoder.misc_indices()),
- I::Gc(_) => return unsupported(pc, "a GC instruction"),
+ I::Gc(sub_opcode) => self.gc(
+ func,
+ module,
+ sub_opcode,
+ decoder.gc_indices(),
+ decoder.gc_heap_types(),
+ decoder.gc_flags(),
+ ),
I::Vector { opcode, index } => {
let plain = match opcode {
quickening::LOCAL_GET_V128 => I::LocalGet(index),
@@ -1184,13 +1244,8 @@ impl Builder {
};
return self.instruction(func, module, plain, decoder, pc);
}
- I::Simd { sub_opcode, checked } => {
- if checked {
- return unsupported(pc, "an access of a memory without guard pages");
- }
- return self.simd(func, sub_opcode, decoder, pc);
- }
- I::Atomic(_) => return unsupported(pc, "an atomic instruction"),
+ I::Simd { sub_opcode, checked } => return self.simd(func, module, sub_opcode, checked, decoder, pc),
+ I::Atomic(sub_opcode) => self.atomic(func, module, sub_opcode, decoder),
}
Ok(())
}
@@ -1291,6 +1346,11 @@ impl Builder {
numbering_mark: self.numbering_log.len() as u32,
loop_index: NONE,
incomplete_start: self.incomplete.len() as u32,
+ throws: NONE,
+ outer_handler: NONE,
+ clauses: (0, 0),
+ exception: NONE,
+ next_clause: 0,
});
}
@@ -1419,7 +1479,7 @@ impl Builder {
control.unreachable = false;
}
- fn end(&mut self, func: &mut Func) {
+ fn end(&mut self, func: &mut Func, module: &Module) {
let index = self.controls.len() - 1;
let control = self.controls[index];
match control.kind {
@@ -1432,6 +1492,8 @@ impl Builder {
}
ControlKind::Loop => self.end_loop(func, index),
ControlKind::Block | ControlKind::If | ControlKind::Else => self.end_block(func, index),
+ ControlKind::TryTable => self.end_try_table(func, module, index),
+ ControlKind::Try | ControlKind::Catch => self.end_try(func, index),
}
}
diff --git a/Libraries/LibWasm/JIT/src/builder/simd.rs b/Libraries/LibWasm/JIT/src/builder/simd.rs
index 728f6cf86f8..1e09d3fce68 100644
--- a/Libraries/LibWasm/JIT/src/builder/simd.rs
+++ b/Libraries/LibWasm/JIT/src/builder/simd.rs
@@ -6,83 +6,48 @@
//! The SIMD instructions. They keep their sub-opcode in the IR (`VectorUnary`, `VectorBinary`, ...), so that one
//! node kind per shape carries all of them and code generation picks each one's instructions.
+//!
+//! The relaxed instructions get the semantics the interpreter chose for them: all but the multiply-adds and the dot
+//! products are their deterministic counterparts, which they become here, so that they share those nodes' value
+//! numbers and code.
use super::{Builder, unsupported};
use crate::CompileFailure;
-use crate::decode::Decoder;
-use crate::ir::{Func, Node, Op, Type, Value};
+use crate::decode::{Decoder, MemoryArgument};
+use crate::ir::{Func, LoadKind, Node, Op, Type, Value};
+use libwasm_module::Module;
+use libwasm_module::instruction_tables::{SimdKind, simd_kind};
use libwasm_module::opcode::simd::*;
-/// What the builder knows about a SIMD instruction it compiles.
-enum Shape {
- /// A load of 16 bytes or fewer into a vector.
- Load,
- Store,
- Const,
- Shuffle,
- /// A unary operation, and its result's type.
- Unary(Type),
- /// A binary operation of vectors, or of a vector and an i32 shift count.
- Binary,
- Ternary,
- /// An extraction of a lane, of the lane's type.
- ExtractLane(Type),
- ReplaceLane,
+/// The deterministic instruction a relaxed one behaves as, or the instruction itself.
+fn canonical(sub_opcode: u32) -> u32 {
+ match sub_opcode {
+ I8X16_RELAXED_SWIZZLE => I8X16_SWIZZLE,
+ I32X4_RELAXED_TRUNC_F32X4_S => I32X4_TRUNC_SAT_F32X4_S,
+ I32X4_RELAXED_TRUNC_F32X4_U => I32X4_TRUNC_SAT_F32X4_U,
+ I32X4_RELAXED_TRUNC_F64X2_S_ZERO => I32X4_TRUNC_SAT_F64X2_S_ZERO,
+ I32X4_RELAXED_TRUNC_F64X2_U_ZERO => I32X4_TRUNC_SAT_F64X2_U_ZERO,
+ I8X16_RELAXED_LANESELECT | I16X8_RELAXED_LANESELECT | I32X4_RELAXED_LANESELECT | I64X2_RELAXED_LANESELECT => {
+ V128_BITSELECT
+ }
+ F32X4_RELAXED_MIN => F32X4_MIN,
+ F32X4_RELAXED_MAX => F32X4_MAX,
+ F64X2_RELAXED_MIN => F64X2_MIN,
+ F64X2_RELAXED_MAX => F64X2_MAX,
+ I16X8_RELAXED_Q15MULR_S => I16X8_Q15MULR_SAT_S,
+ _ => sub_opcode,
+ }
}
-/// The shape of a SIMD instruction the JIT compiles, or None.
-fn shape(sub_opcode: u32) -> Option<Shape> {
- use Type::{F32, F64, I32, I64, V128};
- Some(match sub_opcode {
- V128_LOAD..=V128_LOAD64_SPLAT | V128_LOAD32_ZERO | V128_LOAD64_ZERO => Shape::Load,
- V128_STORE => Shape::Store,
- V128_CONST => Shape::Const,
- I8X16_SHUFFLE => Shape::Shuffle,
- I8X16_SPLAT | I16X8_SPLAT | I32X4_SPLAT => Shape::Unary(V128),
- I64X2_SPLAT => Shape::Unary(V128),
- F32X4_SPLAT => Shape::Unary(V128),
- F64X2_SPLAT => Shape::Unary(V128),
- I8X16_EXTRACT_LANE_S | I8X16_EXTRACT_LANE_U | I16X8_EXTRACT_LANE_S | I16X8_EXTRACT_LANE_U
- | I32X4_EXTRACT_LANE => Shape::ExtractLane(I32),
- I64X2_EXTRACT_LANE => Shape::ExtractLane(I64),
- F32X4_EXTRACT_LANE => Shape::ExtractLane(F32),
- F64X2_EXTRACT_LANE => Shape::ExtractLane(F64),
- I8X16_REPLACE_LANE | I16X8_REPLACE_LANE | I32X4_REPLACE_LANE => Shape::ReplaceLane,
- I64X2_REPLACE_LANE => Shape::ReplaceLane,
- F32X4_REPLACE_LANE => Shape::ReplaceLane,
- F64X2_REPLACE_LANE => Shape::ReplaceLane,
- V128_NOT
- | I8X16_ABS
- | I16X8_ABS
- | I32X4_ABS
- | I8X16_NEG
- | I16X8_NEG
- | I32X4_NEG
- | I64X2_NEG
- | F32X4_ABS
- | F32X4_NEG
- | F32X4_SQRT
- | F64X2_ABS
- | F64X2_NEG
- | F64X2_SQRT
- | F32X4_CONVERT_I32X4_S => Shape::Unary(V128),
- V128_ANY_TRUE | I8X16_ALL_TRUE | I16X8_ALL_TRUE | I32X4_ALL_TRUE | I64X2_ALL_TRUE | I8X16_BITMASK
- | I32X4_BITMASK | I64X2_BITMASK => Shape::Unary(I32),
- V128_AND | V128_ANDNOT | V128_OR | V128_XOR | I8X16_SWIZZLE | I8X16_EQ | I8X16_NE | I16X8_EQ | I16X8_NE
- | I32X4_EQ | I32X4_NE | I64X2_EQ | I64X2_NE | I8X16_GT_S | I16X8_GT_S | I32X4_GT_S | I64X2_GT_S
- | I8X16_LT_S | I16X8_LT_S | I32X4_LT_S | I64X2_LT_S | F32X4_EQ | F32X4_NE | F32X4_LT | F32X4_GT | F32X4_LE
- | F32X4_GE | F64X2_EQ | F64X2_NE | F64X2_LT | F64X2_GT | F64X2_LE | F64X2_GE | I8X16_ADD | I8X16_SUB
- | I8X16_ADD_SAT_S | I8X16_ADD_SAT_U | I8X16_SUB_SAT_S | I8X16_SUB_SAT_U | I16X8_ADD | I16X8_SUB | I16X8_MUL
- | I32X4_ADD | I32X4_SUB | I32X4_MUL | I64X2_ADD | I64X2_SUB | I8X16_MIN_S | I8X16_MIN_U | I8X16_MAX_S
- | I8X16_MAX_U | I16X8_MIN_S | I16X8_MIN_U | I16X8_MAX_S | I16X8_MAX_U | I32X4_MIN_S | I32X4_MIN_U
- | I32X4_MAX_S | I32X4_MAX_U | F32X4_ADD | F32X4_SUB | F32X4_MUL | F32X4_DIV | F64X2_ADD | F64X2_SUB
- | F64X2_MUL | F64X2_DIV => Shape::Binary,
- I16X8_SHL | I16X8_SHR_S | I16X8_SHR_U | I32X4_SHL | I32X4_SHR_S | I32X4_SHR_U | I64X2_SHL | I64X2_SHR_U => {
- Shape::Binary
- }
- V128_BITSELECT => Shape::Ternary,
- _ => return None,
- })
+/// The type of a lane of `lane.extract` or `lane.replace` instruction, as values carry it.
+fn lane_type(ty: libwasm_module::types::ValType) -> Type {
+ use libwasm_module::types::ValType;
+ match ty {
+ ValType::I64 => Type::I64,
+ ValType::F32 => Type::F32,
+ ValType::F64 => Type::F64,
+ _ => Type::I32,
+ }
}
impl Builder {
@@ -92,64 +57,136 @@ impl Builder {
Self::append(func, Node::new(Op::Const128, Type::V128, 0, [index, 0, 0]))
}
+ /// The base, index and offset of an access of `1 << size_log2` bytes at `index` in `argument`'s memory: memory 0
+ /// with guard pages, or else the address after checking it (quickening rule 2).
+ fn simd_address(
+ &mut self,
+ func: &mut Func,
+ module: &Module,
+ checked: bool,
+ argument: MemoryArgument,
+ index: Value,
+ size_log2: u8,
+ ) -> (Value, Value, u32) {
+ if !checked {
+ debug_assert_eq!(argument.memory, 0, "plain accesses are of memory 0");
+ return (self.memory_base, index, argument.offset as u32);
+ }
+ let address = self.checked_address(func, module, argument, index, size_log2, false);
+ let zero = self.constant(func, Type::I32, 0);
+ (address, zero, 0)
+ }
+
+ fn store(&mut self, func: &mut Func, (base, index, offset): (Value, Value, u32), value: Value, size_log2: u8) {
+ let start = func.operands.len() as u32;
+ func.operands.extend_from_slice(&[base, index, value]);
+ Self::append(func, Node::new(Op::Store, Type::None, size_log2, [start, 3, offset]));
+ }
+
pub(super) fn simd(
&mut self,
func: &mut Func,
+ module: &Module,
sub_opcode: u32,
+ checked: bool,
decoder: &Decoder<'_>,
pc: usize,
) -> Result<(), CompileFailure> {
- let Some(shape) = shape(sub_opcode) else {
- return unsupported(pc, "a SIMD instruction");
+ let sub_opcode = canonical(sub_opcode);
+ let Some(kind) = simd_kind(sub_opcode) else {
+ return unsupported(pc, "an unknown SIMD instruction");
};
- let value = match shape {
- Shape::Load => {
- let argument = decoder.simd_argument();
- debug_assert_eq!(argument.memory, 0, "plain accesses are of memory 0");
+ let value = match kind {
+ SimdKind::Load { size } => {
let index = Self::resolve(func, self.pop());
+ let argument = decoder.simd_argument();
+ let size_log2 = size.trailing_zeros() as u8;
+ let (base, index, offset) = self.simd_address(func, module, checked, argument, index, size_log2);
Self::append(
func,
- Node::new(
- Op::VectorLoad,
- Type::V128,
- sub_opcode as u8,
- [self.memory_base, index, argument.offset as u32],
- ),
+ Node::new(Op::VectorLoad, Type::V128, sub_opcode as u8, [base, index, offset]),
)
}
- Shape::Store => {
- let argument = decoder.simd_argument();
+ SimdKind::Store { .. } => {
let value = Self::resolve(func, self.pop());
let index = Self::resolve(func, self.pop());
- let start = func.operands.len() as u32;
- func.operands.extend_from_slice(&[self.memory_base, index, value]);
- Self::append(
+ let address = self.simd_address(func, module, checked, decoder.simd_argument(), index, 4);
+ self.store(func, address, value, 4);
+ return Ok(());
+ }
+ SimdKind::LoadLane { size } => {
+ // A scalar load, and its value replacing the lane.
+ let lane = u32::from(decoder.simd_lane());
+ let vector = Self::resolve(func, self.pop());
+ let index = Self::resolve(func, self.pop());
+ let argument = decoder.simd_argument();
+ let size_log2 = size.trailing_zeros() as u8;
+ let (base, index, offset) = self.simd_address(func, module, checked, argument, index, size_log2);
+ let (kind, ty, replace) = match size {
+ 1 => (LoadKind::I32U8, Type::I32, I8X16_REPLACE_LANE),
+ 2 => (LoadKind::I32U16, Type::I32, I16X8_REPLACE_LANE),
+ 4 => (LoadKind::I32, Type::I32, I32X4_REPLACE_LANE),
+ _ => (LoadKind::I64, Type::I64, I64X2_REPLACE_LANE),
+ };
+ let scalar = Self::append(func, Node::new(Op::Load, ty, kind as u8, [base, index, offset]));
+ self.pure(
func,
- Node::new(Op::Store, Type::None, 4, [start, 3, argument.offset as u32]),
- );
+ Node::new(Op::ReplaceLane, Type::V128, 0, [vector, scalar, replace | (lane << 16)]),
+ )
+ }
+ SimdKind::StoreLane { size } => {
+ // The lane extracted, and stored as a scalar.
+ let lane = u32::from(decoder.simd_lane());
+ let vector = Self::resolve(func, self.pop());
+ let index = Self::resolve(func, self.pop());
+ let (ty, extract, size_log2) = match size {
+ 1 => (Type::I32, I8X16_EXTRACT_LANE_U, 0),
+ 2 => (Type::I32, I16X8_EXTRACT_LANE_U, 1),
+ 4 => (Type::I32, I32X4_EXTRACT_LANE, 2),
+ _ => (Type::I64, I64X2_EXTRACT_LANE, 3),
+ };
+ let scalar = self.pure(func, Node::new(Op::ExtractLane, ty, 0, [vector, extract, lane]));
+ let address = self.simd_address(func, module, checked, decoder.simd_argument(), index, size_log2);
+ self.store(func, address, scalar, size_log2);
return Ok(());
}
- Shape::Const => {
+ SimdKind::Const => {
let bits = u128::from_le_bytes(decoder.simd_bytes());
self.vector_constant(func, bits)
}
- Shape::Shuffle => {
- let b = Self::resolve(func, self.pop());
- let a = Self::resolve(func, self.pop());
+ SimdKind::Shuffle => {
+ let mut b = Self::resolve(func, self.pop());
+ let mut a = Self::resolve(func, self.pop());
+ let mut lanes = decoder.simd_bytes();
+ // A shuffle of one vector names it twice, with lanes 0 to 15, so that the other one need not live
+ // on for it, and code generation sees what it is.
+ if lanes.iter().all(|lane| *lane < 16) {
+ b = a;
+ } else if lanes.iter().all(|lane| *lane >= 16) {
+ a = b;
+ }
+ if a == b {
+ lanes = lanes.map(|lane| lane & 15);
+ }
let index = func.constants.len() as u32;
- func.constants.push(u128::from_le_bytes(decoder.simd_bytes()));
+ func.constants.push(u128::from_le_bytes(lanes));
Self::append(func, Node::new(Op::Shuffle, Type::V128, 0, [a, b, index]))
}
- Shape::Unary(result) => {
+ SimdKind::Splat(_) | SimdKind::Unary | SimdKind::Test => {
+ let result = if matches!(kind, SimdKind::Test) {
+ Type::I32
+ } else {
+ Type::V128
+ };
let a = Self::resolve(func, self.pop());
self.pure(func, Node::new(Op::VectorUnary, result, 0, [a, sub_opcode, 0]))
}
- Shape::Binary => {
+ SimdKind::Binary | SimdKind::Shift => {
let b = Self::resolve(func, self.pop());
let a = Self::resolve(func, self.pop());
self.pure(func, Node::new(Op::VectorBinary, Type::V128, 0, [a, b, sub_opcode]))
}
- Shape::Ternary => {
+ SimdKind::Ternary => {
let c = Self::resolve(func, self.pop());
let b = Self::resolve(func, self.pop());
let a = Self::resolve(func, self.pop());
@@ -158,12 +195,15 @@ impl Builder {
Node::new(Op::VectorTernary, Type::V128, sub_opcode as u8, [a, b, c]),
)
}
- Shape::ExtractLane(ty) => {
+ SimdKind::ExtractLane { result, .. } => {
let a = Self::resolve(func, self.pop());
let lane = u32::from(decoder.simd_lane());
- self.pure(func, Node::new(Op::ExtractLane, ty, 0, [a, sub_opcode, lane]))
+ self.pure(
+ func,
+ Node::new(Op::ExtractLane, lane_type(result), 0, [a, sub_opcode, lane]),
+ )
}
- Shape::ReplaceLane => {
+ SimdKind::ReplaceLane { .. } => {
let b = Self::resolve(func, self.pop());
let a = Self::resolve(func, self.pop());
let lane = u32::from(decoder.simd_lane());
diff --git a/Libraries/LibWasm/JIT/src/builder/tables.rs b/Libraries/LibWasm/JIT/src/builder/tables.rs
index 50fe9140e7c..c53e662d711 100644
--- a/Libraries/LibWasm/JIT/src/builder/tables.rs
+++ b/Libraries/LibWasm/JIT/src/builder/tables.rs
@@ -19,7 +19,7 @@ const PAGE_SHIFT: u64 = 16;
impl Builder {
/// A call of the runtime's `helper` with `operands`, whose value has type `ty`.
- fn helper(&mut self, func: &mut Func, helper: Helper, operands: &[Value], ty: Type) -> Value {
+ pub(super) fn helper(&mut self, func: &mut Func, helper: Helper, operands: &[Value], ty: Type) -> Value {
let start = func.operands.len() as u32;
func.operands.push(self.instance);
for &operand in operands {
@@ -35,7 +35,7 @@ impl Builder {
}
/// The address of passive segment `index` in the instance's array of them at `offset`.
- fn segment(&mut self, func: &mut Func, offset: usize, index: u32) -> Value {
+ pub(super) fn segment(&mut self, func: &mut Func, offset: usize, index: u32) -> Value {
let segments = self.instance_field(func, offset);
self.pure(
func,
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rs
index 6f7b53cf04b..683f87f5418 100644
--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rs
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rs
@@ -11,7 +11,7 @@
use super::{CodeGenerator, FP, SCRATCH, SP, fpr, gpr, precision, width};
use crate::asm::{Address, Gpr, Width};
use crate::convention::{self, Place};
-use crate::ir::{Func, Op, Type, Value};
+use crate::ir::{FLAG_CHECKS_EXCEPTION, Func, Op, Type, Value};
use libwasm_module::abi::FunctionHeader;
use std::mem::offset_of;
@@ -40,6 +40,9 @@ impl CodeGenerator<'_> {
let callee = gpr(convention::CALLEE_REGISTER);
self.asm
.call_m(&Address::new(callee, offset_of!(FunctionHeader, native_entry) as i32));
+ if node.flags & FLAG_CHECKS_EXCEPTION != 0 {
+ self.exception_sites.push(self.asm.offset() as u32);
+ }
self.asm
.lea(Width::W64, SP, &Address::new(FP, -(self.frame_size as i32)));
}
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/gc.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/gc.rs
new file mode 100644
index 00000000000..abd1e6a6438
--- /dev/null
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/gc.rs
@@ -0,0 +1,329 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Accesses of memories without guard pages, atomics, and GC objects: their addresses and checks, and the tests of
+//! references against heap types.
+
+use super::{CodeGenerator, FP, SCRATCH, gpr};
+use crate::asm::x86_64::{AluOp, Cond};
+use crate::asm::{Address, Gpr, Scale, Width};
+use crate::convention::{self, Register};
+use crate::ir::{AtomicOp, CHECKED_ATOMIC, CHECKED_MEMORY64, HeapTest, Op, REF_TEST_CAST, REF_TEST_NULLABLE, Value};
+use crate::regalloc::CONSTANT_INPUT;
+use libwasm_module::abi::{
+ ExecutionContext, FunctionHeader, InstanceData, MemoryData, OBJECT_DATA_OFFSET, OBJECT_LENGTH_OFFSET,
+ RTT_KIND_ARRAY, RTT_KIND_STRUCT, Rtt, TRAP_ARRAY_OUT_OF_BOUNDS, TRAP_CAST_FAILURE, TRAP_MEMORY_OUT_OF_BOUNDS,
+ TRAP_NULL_REFERENCE, TRAP_UNALIGNED_ATOMIC,
+};
+use std::mem::offset_of;
+
+fn field(offset: usize) -> i32 {
+ offset as i32
+}
+
+/// The width of the instructions for an access of `size` bytes whose value is zero-extended to 32 or 64 bits.
+fn access_width(size: u32) -> Width {
+ if size == 8 { Width::W64 } else { Width::W32 }
+}
+
+impl CodeGenerator<'_> {
+ pub(super) fn lower_gc(&mut self, value: Value) {
+ let func = self.func;
+ let node = *func.node(value);
+ let record = *self.allocation.node(value);
+ let input = |index: usize| gpr(record.inputs[index]);
+ match node.op {
+ Op::CheckedAddress => self.checked_address(value),
+ Op::AtomicRmw => {
+ let size = 1u32 << node.flags;
+ let (address, operand) = (Address::new(input(0), 0), input(1));
+ let old = Gpr(convention::RAX);
+ match AtomicOp::from_index(node.args[2]) {
+ op @ (AtomicOp::Add | AtomicOp::Sub) => {
+ self.asm.mov_rr(Width::W64, old, operand);
+ if op == AtomicOp::Sub {
+ self.asm.neg(Width::W64, old);
+ }
+ self.asm.lock_xadd(size, &address, old);
+ }
+ AtomicOp::Exchange => {
+ self.asm.mov_rr(Width::W64, old, operand);
+ self.asm.xchg_mr(size, &address, old);
+ }
+ op => {
+ // A compare-exchange loop, until no other thread changed the location in between.
+ let updated = gpr(record.temps[1]);
+ let alu = match op {
+ AtomicOp::And => AluOp::And,
+ AtomicOp::Or => AluOp::Or,
+ _ => AluOp::Xor,
+ };
+ self.load_zero_extended(size, old, &address);
+ let again = self.asm.new_label();
+ self.asm.bind(again);
+ self.asm.mov_rr(Width::W64, updated, old);
+ self.asm.alu_rr(alu, Width::W64, updated, operand);
+ self.asm.lock_cmpxchg(size, &address, updated);
+ self.asm.jcc(Cond::NotEqual, again);
+ }
+ }
+ self.zero_extend(size, old);
+ }
+ Op::AtomicCompareExchange => {
+ let size = 1u32 << node.flags;
+ // NB: Only the low `size` bytes of rax are compared, which is the expected value wrapped at the
+ // access width.
+ self.asm.lock_cmpxchg(size, &Address::new(input(0), 0), input(2));
+ self.zero_extend(size, Gpr(convention::RAX));
+ }
+ Op::AtomicFence => self.asm.mfence(),
+ Op::Rtt => {
+ let (instance, output) = (input(0), gpr(record.output));
+ self.asm.mov_rm(
+ Width::W64,
+ SCRATCH,
+ &Address::new(instance, field(offset_of!(InstanceData, type_identities))),
+ );
+ self.asm
+ .mov_rm(Width::W32, SCRATCH, &Address::new(SCRATCH, 4 * node.args[1] as i32));
+ self.rtts(output, instance);
+ self.asm
+ .mov_rm(Width::W64, output, &Address::indexed(output, SCRATCH, Scale::Eight, 0));
+ }
+ Op::I31New => {
+ // NB: Shifting the 32-bit value left drops its bit 31: ((value & 0x7fffffff) << 1) | 1.
+ self.asm.lea(
+ Width::W32,
+ gpr(record.output),
+ &Address::indexed(input(0), input(0), Scale::One, 1),
+ );
+ }
+ Op::I31Get => {
+ let output = gpr(record.output);
+ self.asm.mov_rr(Width::W32, output, input(0));
+ if node.flags != 0 {
+ self.asm.sar_ri(Width::W32, output, 1);
+ } else {
+ self.asm.shr_ri(Width::W32, output, 1);
+ }
+ }
+ Op::ElementAddress => {
+ let (array, index, output) = (input(0), input(1), gpr(record.output));
+ let null = self.trap_label(TRAP_NULL_REFERENCE);
+ self.asm.test_rr(Width::W64, array, array);
+ self.asm.jcc(Cond::Equal, null);
+ // NB: The index is zero-extended, so a 64-bit comparison checks it as an unsigned i32.
+ self.asm.alu_rm(
+ AluOp::Cmp,
+ Width::W64,
+ index,
+ &Address::new(array, field(OBJECT_LENGTH_OFFSET)),
+ );
+ let out_of_bounds = self.trap_label(TRAP_ARRAY_OUT_OF_BOUNDS);
+ self.asm.jcc(Cond::AboveOrEqual, out_of_bounds);
+ self.asm
+ .mov_rm(Width::W64, output, &Address::new(array, field(OBJECT_DATA_OFFSET)));
+ self.asm
+ .lea(Width::W64, output, &Address::indexed(output, index, Scale::Eight, 0));
+ if node.flags == 4 {
+ self.asm
+ .lea(Width::W64, output, &Address::indexed(output, index, Scale::Eight, 0));
+ }
+ }
+ Op::RefTest => self.ref_test(value),
+ _ => unreachable!("{} is no GC or atomic operation", node.op.name()),
+ }
+ }
+
+ /// `output` = the runtime types of the store, from `instance`.
+ fn rtts(&mut self, output: Gpr, instance: Gpr) {
+ self.asm.mov_rm(
+ Width::W64,
+ output,
+ &Address::new(instance, field(offset_of!(InstanceData, context))),
+ );
+ self.asm.mov_rm(
+ Width::W64,
+ output,
+ &Address::new(output, field(offset_of!(ExecutionContext, rtts))),
+ );
+ }
+
+ fn load_zero_extended(&mut self, size: u32, dst: Gpr, address: &Address) {
+ match size {
+ 1 => self.asm.movzx8_rm(dst, address),
+ 2 => self.asm.movzx16_rm(dst, address),
+ _ => self.asm.mov_rm(access_width(size), dst, address),
+ }
+ }
+
+ fn zero_extend(&mut self, size: u32, register: Gpr) {
+ match size {
+ 1 => self.asm.movzx8_rr(register, register),
+ 2 => self.asm.movzx16_rr(register, register),
+ 4 => self.asm.mov_rr(Width::W32, register, register),
+ _ => {}
+ }
+ }
+
+ /// The address of a checked access: the memory's base + index + offset, after checking that index + offset +
+ /// size is at most the memory's size, and for atomics that index + offset is aligned.
+ fn checked_address(&mut self, value: Value) {
+ let func = self.func;
+ let node = *func.node(value);
+ let record = *self.allocation.node(value);
+ let size = 1u64 << (node.flags & 7);
+ let memory64 = node.flags & CHECKED_MEMORY64 != 0;
+ let (memory, index, output) = (gpr(record.inputs[0]), gpr(record.inputs[1]), gpr(record.output));
+ let out_of_bounds = self.trap_label(TRAP_MEMORY_OUT_OF_BOUNDS);
+ // The end of the access, which may wrap around for a memory64; i32 indices are zero-extended already.
+ let end = SCRATCH;
+ self.asm.mov_rr(Width::W64, end, index);
+ if record.inputs[2] == CONSTANT_INPUT {
+ let offset = self.immediate(value, 2);
+ self.asm.add_ri(Width::W64, end, (offset + size) as i32);
+ if memory64 {
+ self.asm.jcc(Cond::Below, out_of_bounds);
+ }
+ } else {
+ self.asm.add_rr(Width::W64, end, gpr(record.inputs[2]));
+ if memory64 {
+ self.asm.jcc(Cond::Below, out_of_bounds);
+ }
+ self.asm.add_ri(Width::W64, end, size as i32);
+ if memory64 {
+ self.asm.jcc(Cond::Below, out_of_bounds);
+ }
+ }
+ self.asm.alu_rm(
+ AluOp::Cmp,
+ Width::W64,
+ end,
+ &Address::new(memory, field(offset_of!(MemoryData, size))),
+ );
+ self.asm.jcc(Cond::Above, out_of_bounds);
+ if node.flags & CHECKED_ATOMIC != 0 && size > 1 {
+ // NB: The end and the address differ by the size, a multiple of the alignment.
+ let unaligned = self.trap_label(TRAP_UNALIGNED_ATOMIC);
+ self.asm.test_ri(Width::W32, end, size as i32 - 1);
+ self.asm.jcc(Cond::NotEqual, unaligned);
+ }
+ self.asm.mov_rm(
+ Width::W64,
+ output,
+ &Address::new(memory, field(offset_of!(MemoryData, base))),
+ );
+ self.asm.lea(
+ Width::W64,
+ output,
+ &Address::indexed(output, end, Scale::One, -(size as i32)),
+ );
+ }
+
+ /// `RefTest`: whether a reference matches a heap type, as 0 or 1, or for a cast a trap where it does not.
+ fn ref_test(&mut self, value: Value) {
+ let func = self.func;
+ let node = *func.node(value);
+ let record = *self.allocation.node(value);
+ let reference = gpr(record.inputs[0]);
+ let identity: Register = record.inputs[1];
+ let depth = node.args[2] as i32;
+ let cast = node.flags & REF_TEST_CAST != 0;
+ let matched = self.asm.new_label();
+ let failed = if cast {
+ self.trap_label(TRAP_CAST_FAILURE)
+ } else {
+ self.asm.new_label()
+ };
+ self.asm.test_rr(Width::W64, reference, reference);
+ let null_matches = node.flags & REF_TEST_NULLABLE != 0;
+ self.asm.jcc(Cond::Equal, if null_matches { matched } else { failed });
+ let compare_identity = |generator: &mut Self, address: &Address| {
+ if identity == CONSTANT_INPUT {
+ let bits = generator.immediate(value, 1);
+ generator.asm.cmp_mi(Width::W32, address, bits as i32);
+ } else {
+ generator.asm.cmp_mr(Width::W32, address, gpr(identity));
+ }
+ };
+ // Whether the Rtt in `rtt` is the expected type or a subtype of it: the expected type is in its display at
+ // the expected type's depth.
+ let subtype_check = |generator: &mut Self, rtt: Gpr| {
+ generator
+ .asm
+ .cmp_mi(Width::W32, &Address::new(rtt, field(offset_of!(Rtt, depth))), depth);
+ generator.asm.jcc(Cond::Below, failed);
+ generator
+ .asm
+ .mov_rm(Width::W64, rtt, &Address::new(rtt, field(offset_of!(Rtt, display))));
+ compare_identity(generator, &Address::new(rtt, 4 * depth));
+ generator.asm.jcc(Cond::NotEqual, failed);
+ };
+ match HeapTest::from_flags(node.flags) {
+ HeapTest::NonNull => {}
+ HeapTest::Nothing => self.asm.jmp(failed),
+ HeapTest::I31 => {
+ self.asm.test_ri(Width::W32, reference, 1);
+ self.asm.jcc(Cond::Equal, failed);
+ }
+ HeapTest::Eq => {
+ // An i31 (bit 0), or a GC object (bits 1:0 clear) rather than a host value (0b10).
+ self.asm.test_ri(Width::W32, reference, 1);
+ self.asm.jcc(Cond::NotEqual, matched);
+ self.asm.test_ri(Width::W32, reference, 2);
+ self.asm.jcc(Cond::NotEqual, failed);
+ }
+ kind @ (HeapTest::Struct | HeapTest::Array) => {
+ let rtt = gpr(record.temps[0]);
+ self.asm.test_ri(Width::W32, reference, 3);
+ self.asm.jcc(Cond::NotEqual, failed);
+ self.asm.mov_rm(Width::W64, rtt, &Address::new(reference, 0));
+ let expected = if kind == HeapTest::Struct {
+ RTT_KIND_STRUCT
+ } else {
+ RTT_KIND_ARRAY
+ };
+ self.asm.cmp_mi(
+ Width::W32,
+ &Address::new(rtt, field(offset_of!(Rtt, kind))),
+ expected as i32,
+ );
+ self.asm.jcc(Cond::NotEqual, failed);
+ }
+ HeapTest::ConcreteObject => {
+ let rtt = gpr(record.temps[0]);
+ self.asm.test_ri(Width::W32, reference, 3);
+ self.asm.jcc(Cond::NotEqual, failed);
+ self.asm.mov_rm(Width::W64, rtt, &Address::new(reference, 0));
+ subtype_check(self, rtt);
+ }
+ HeapTest::ConcreteFunction => {
+ let [rtt, rtts] = [gpr(record.temps[0]), gpr(record.temps[1])];
+ let type_identity = Address::new(reference, field(offset_of!(FunctionHeader, type_identity)));
+ compare_identity(self, &type_identity);
+ self.asm.jcc(Cond::Equal, matched);
+ self.asm.mov_rm(Width::W32, rtt, &type_identity);
+ self.asm
+ .mov_rm(Width::W64, rtts, &Address::new(FP, convention::FRAME_INSTANCE));
+ self.rtts(rtts, rtts);
+ self.asm
+ .mov_rm(Width::W64, rtt, &Address::indexed(rtts, rtt, Scale::Eight, 0));
+ subtype_check(self, rtt);
+ }
+ }
+ self.asm.bind(matched);
+ if cast {
+ return;
+ }
+ let output = gpr(record.output);
+ let done = self.asm.new_label();
+ self.asm.mov_ri32(output, 1);
+ self.asm.jmp(done);
+ self.asm.bind(failed);
+ self.asm.mov_ri32(output, 0);
+ self.asm.bind(done);
+ }
+}
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs
index 70c1c438c45..6dcc1811fd3 100644
--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs
@@ -10,11 +10,14 @@
//! addresses and its own data through rip-relative operands.
mod calls;
+mod gc;
mod memory;
mod numeric;
mod tables;
mod vector;
+pub(crate) use vector::{is_vector_shift, vector_constant_inputs, vector_temps};
+
use crate::RuntimeInfo;
use crate::asm::x86_64::{Assembler, BitwiseOp, Cond, Precision, VexOperand};
use crate::asm::{Address, Fpr, Gpr, Label, Width};
@@ -75,6 +78,8 @@ pub(crate) fn condition(condition: IntCondition) -> Cond {
pub struct Generated {
pub code: Vec<u8>,
pub frame_size: u32,
+ /// The offsets of the return addresses of calls that check for an exception once they return.
+ pub exception_sites: Vec<u32>,
}
/// Out-of-line code for an edge that needs moves: its label, the edge's slot and its target.
@@ -102,6 +107,7 @@ pub struct CodeGenerator<'a> {
frame_size: u32,
/// The block whose code is being generated.
block: BlockId,
+ exception_sites: Vec<u32>,
}
impl<'a> CodeGenerator<'a> {
@@ -127,6 +133,7 @@ impl<'a> CodeGenerator<'a> {
constants: Vec::new(),
frame_size: size.next_multiple_of(16),
block: 0,
+ exception_sites: Vec::new(),
}
}
@@ -171,6 +178,7 @@ impl<'a> CodeGenerator<'a> {
Ok(Generated {
code,
frame_size: self.frame_size,
+ exception_sites: self.exception_sites,
})
}
@@ -223,6 +231,28 @@ impl<'a> CodeGenerator<'a> {
}
}
+ /// Has the runtime unwind the exception in `exception` from this frame, and continues where it says: at a call
+ /// that checks for exceptions, or in the entry trampoline.
+ fn throw(&mut self, exception: Gpr) {
+ let context = SCRATCH;
+ self.asm
+ .mov_rm(Width::W64, context, &Address::new(FP, convention::FRAME_INSTANCE));
+ self.asm.mov_rm(
+ Width::W64,
+ context,
+ &Address::new(context, offset_of!(InstanceData, context) as i32),
+ );
+ let arguments = offset_of!(ExecutionContext, arguments) as i32;
+ self.asm
+ .mov_mr(Width::W64, &Address::new(context, arguments), exception);
+ self.asm.mov_mr(Width::W64, &Address::new(context, arguments + 8), FP);
+ self.asm.mov_rr(Width::W64, Gpr(convention::RDI), context);
+ let target = Gpr(convention::RAX);
+ self.asm.mov_ri(target, self.runtime.throw);
+ self.asm.call_r(target);
+ crate::stubs::resume(&mut self.asm, target);
+ }
+
fn epilogue(&mut self) {
self.asm
.lea(Width::W64, SP, &Address::new(FP, convention::FRAME_SAVED_FP));
@@ -590,6 +620,7 @@ impl<'a> CodeGenerator<'a> {
let label = self.trap_label(node.args[0]);
self.asm.jmp(label);
}
+ Op::Throw => self.throw(gpr(record.inputs[0])),
_ => unreachable!("{} is no terminator", node.op.name()),
}
}
@@ -656,6 +687,15 @@ impl<'a> CodeGenerator<'a> {
| Op::CheckFunction
| Op::Helper => self.lower_runtime(value),
Op::VectorLoad => self.lower_memory(value),
+ Op::CheckedAddress
+ | Op::AtomicRmw
+ | Op::AtomicCompareExchange
+ | Op::AtomicFence
+ | Op::Rtt
+ | Op::I31New
+ | Op::I31Get
+ | Op::ElementAddress
+ | Op::RefTest => self.lower_gc(value),
Op::VectorUnary
| Op::VectorBinary
| Op::VectorTernary
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs
index 5556c6a1358..8eea3005d76 100644
--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs
@@ -150,6 +150,10 @@ impl CodeGenerator<'_> {
let trap = self.dynamic_trap_label();
self.asm.test_rr(Width::W64, target, target);
self.asm.jcc(Cond::NotEqual, trap);
+ } else if helper.traps_on_zero() {
+ let trap = self.trap_label(libwasm_module::abi::TRAP_RUNTIME);
+ self.asm.test_rr(Width::W64, target, target);
+ self.asm.jcc(Cond::Equal, trap);
}
}
_ => unreachable!("{} is no runtime operation", node.op.name()),
diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs
index 96e0ade58d8..19f3c82d300 100644
--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs
+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs
@@ -5,22 +5,36 @@
*/
//! Vectors: v128 loads, constants, lanes and SIMD arithmetic, as AVX2 instructions on xmm registers.
+//!
+//! The allocator gives a vector node an output register apart from its inputs and temps, so a lowering may write
+//! its output before it has read all inputs. Inputs may share a register (`i32x4.add x x`), and are never written.
+//! Where the interpreter's sequence decides bits the spec leaves open (NaN payloads, relaxed instructions), the
+//! lowering is the same sequence, so that both tiers agree.
use super::{CodeGenerator, SCRATCH, SCRATCH_FPR, fpr, gpr};
use crate::asm::x86_64::{Cond, VexMap, VexOpcode, VexOperand, VexPrefix};
use crate::asm::{Address, Width};
use crate::convention::Register;
-use crate::ir::{Op, Type, Value};
+use crate::ir::{Func, Op, Type, Value};
+use crate::regalloc::CONSTANT_INPUT;
use libwasm_module::opcode::simd::*;
const fn op(prefix: VexPrefix, map: VexMap, opcode: u8) -> VexOpcode {
VexOpcode::new(prefix, map, opcode)
}
+const fn op0f(opcode: u8) -> VexOpcode {
+ op(VexPrefix::None, VexMap::Map0F, opcode)
+}
+
const fn op66(opcode: u8) -> VexOpcode {
op(VexPrefix::OperandSize, VexMap::Map0F, opcode)
}
+const fn opf3(opcode: u8) -> VexOpcode {
+ op(VexPrefix::Rep, VexMap::Map0F, opcode)
+}
+
const fn op66_38(opcode: u8) -> VexOpcode {
op(VexPrefix::OperandSize, VexMap::Map0F38, opcode)
}
@@ -29,22 +43,45 @@ const fn op66_3a(opcode: u8) -> VexOpcode {
op(VexPrefix::OperandSize, VexMap::Map0F3A, opcode)
}
-pub(super) const VMOVUPS_LOAD: VexOpcode = op(VexPrefix::None, VexMap::Map0F, 0x10);
-pub(super) const VMOVUPS_STORE: VexOpcode = op(VexPrefix::None, VexMap::Map0F, 0x11);
+pub(super) const VMOVUPS_LOAD: VexOpcode = op0f(0x10);
+pub(super) const VMOVUPS_STORE: VexOpcode = op0f(0x11);
const VMOVD_LOAD: VexOpcode = op66(0x6e);
-const VMOVQ_LOAD: VexOpcode = op(VexPrefix::Rep, VexMap::Map0F, 0x7e);
+const VMOVQ_LOAD: VexOpcode = opf3(0x7e);
const VPXOR: VexOpcode = op66(0xef);
const VPAND: VexOpcode = op66(0xdb);
const VPANDN: VexOpcode = op66(0xdf);
const VPOR: VexOpcode = op66(0xeb);
+const VPCMPEQB: VexOpcode = op66(0x74);
+const VPCMPEQW: VexOpcode = op66(0x75);
const VPCMPEQD: VexOpcode = op66(0x76);
+const VPCMPEQQ: VexOpcode = op66_38(0x29);
+const VPCMPGTQ: VexOpcode = op66_38(0x37);
const VPTEST: VexOpcode = op66_38(0x17);
const VPSHUFB: VexOpcode = op66_38(0x00);
+const VPSHUFD: VexOpcode = op66(0x70);
const VPADDUSB: VexOpcode = op66(0xdc);
+const VPADDB: VexOpcode = op66(0xfc);
+const VPADDD: VexOpcode = op66(0xfe);
+const VPADDQ: VexOpcode = op66(0xd4);
const VPSUBB: VexOpcode = op66(0xf8);
const VPSUBW: VexOpcode = op66(0xf9);
const VPSUBD: VexOpcode = op66(0xfa);
const VPSUBQ: VexOpcode = op66(0xfb);
+const VPMULLW: VexOpcode = op66(0xd5);
+const VPMULUDQ: VexOpcode = op66(0xf4);
+const VPMADDWD: VexOpcode = op66(0xf5);
+const VPMADDUBSW: VexOpcode = op66_38(0x04);
+const VPMAXSD: VexOpcode = op66_38(0x3d);
+const VPACKSSWB: VexOpcode = op66(0x63);
+const VPUNPCKLBW: VexOpcode = op66(0x60);
+const VPUNPCKHBW: VexOpcode = op66(0x68);
+const VPUNPCKLWD: VexOpcode = op66(0x61);
+const VPUNPCKHWD: VexOpcode = op66(0x69);
+const VPBLENDW: VexOpcode = op66_3a(0x0e);
+const VPBLENDD: VexOpcode = op66_3a(0x02);
+const VPALIGNR: VexOpcode = op66_3a(0x0f);
+const VPUNPCKLDQ: VexOpcode = op66(0x62);
+const VPUNPCKHDQ: VexOpcode = op66(0x6a);
const VPBROADCASTB: VexOpcode = op66_38(0x78);
const VPBROADCASTW: VexOpcode = op66_38(0x79);
const VPBROADCASTD: VexOpcode = op66_38(0x58);
@@ -61,12 +98,92 @@ const VINSERTPS: VexOpcode = op66_3a(0x21);
const VPERMILPS: VexOpcode = op66_3a(0x04);
const VPERMILPD: VexOpcode = op66_3a(0x05);
const VMOVSD_MERGE: VexOpcode = op(VexPrefix::Repne, VexMap::Map0F, 0x10);
-const VMOVLHPS: VexOpcode = op(VexPrefix::None, VexMap::Map0F, 0x16);
+const VMOVLHPS: VexOpcode = op0f(0x16);
const VPMOVMSKB: VexOpcode = op66(0xd7);
-const VMOVMSKPS: VexOpcode = op(VexPrefix::None, VexMap::Map0F, 0x50);
+const VMOVMSKPS: VexOpcode = op0f(0x50);
const VMOVMSKPD: VexOpcode = op66(0x50);
-const VANDNPS: VexOpcode = op(VexPrefix::None, VexMap::Map0F, 0x55);
-const VXORPS: VexOpcode = op(VexPrefix::None, VexMap::Map0F, 0x57);
+const VANDNPS: VexOpcode = op0f(0x55);
+const VXORPS: VexOpcode = op0f(0x57);
+const VSHUFPS: VexOpcode = op0f(0xc6);
+const VUNPCKLPS: VexOpcode = op0f(0x14);
+const VCVTDQ2PS: VexOpcode = op0f(0x5b);
+const VCVTTPS2DQ: VexOpcode = opf3(0x5b);
+
+/// The packed float instructions of one precision.
+struct Packed {
+ add: VexOpcode,
+ sub: VexOpcode,
+ mul: VexOpcode,
+ min: VexOpcode,
+ max: VexOpcode,
+ and: VexOpcode,
+ andn: VexOpcode,
+ or: VexOpcode,
+ xor: VexOpcode,
+ cmp: VexOpcode,
+ round: VexOpcode,
+ /// The logical right shift by an immediate of lanes of this width: the group opcode and its ModRM.reg digit.
+ shift_right: (VexOpcode, u8),
+ /// The shift that turns an all-ones lane into the bits a NaN lane keeps of it: 10 or 13, so that what stays set
+ /// is the sign, the exponent and the quiet bit.
+ nan_payload_shift: u8,
+}
+
+const PS: Packed = Packed {
+ add: op0f(0x58),
+ sub: op0f(0x5c),
+ mul: op0f(0x59),
+ min: op0f(0x5d),
+ max: op0f(0x5f),
+ and: op0f(0x54),
+ andn: op0f(0x55),
+ or: op0f(0x56),
+ xor: op0f(0x57),
+ cmp: op0f(0xc2),
+ round: op66_3a(0x08),
+ shift_right: (op66(0x72), 2),
+ nan_payload_shift: 10,
+};
+
+const PD: Packed = Packed {
+ add: op66(0x58),
+ sub: op66(0x5c),
+ mul: op66(0x59),
+ min: op66(0x5d),
+ max: op66(0x5f),
+ and: op66(0x54),
+ andn: op66(0x55),
+ or: op66(0x56),
+ xor: op66(0x57),
+ cmp: op66(0xc2),
+ round: op66_3a(0x09),
+ shift_right: (op66(0x73), 2),
+ nan_payload_shift: 13,
+};
+
+/// `vcmpps`/`vcmppd` predicates.
+const CMP_EQ: u8 = 0;
+const CMP_LE: u8 = 2;
+const CMP_UNORD: u8 = 3;
+
+const fn splat8(byte: u8) -> u128 {
+ u128::from_le_bytes([byte; 16])
+}
+
+const fn splat16(lane: u16) -> u128 {
+ let lane = lane as u128;
+ lane * 0x0001_0001_0001_0001_0001_0001_0001_0001
+}
+
+const fn splat32(lane: u32) -> u128 {
+ let lane = lane as u128;
+ lane * 0x0000_0001_0000_0001_0000_0001_0000_0001
+}
+
+const fn splat64(lane: u64) -> u128 {
+ let lane = lane as u128;
+ lane | (lane << 64)
+}
/// The instruction of a binary SIMD operation that maps to one, with whether its operands are swapped and whether
/// its result is inverted (for comparisons), and the immediate of `vcmpps` and `vcmppd`.
@@ -93,9 +210,9 @@ fn binary(sub_opcode: u32) -> Option<Binary> {
invert: false,
immediate: None,
};
- let inverted = |opcode| Binary {
+ let inverted = |opcode, swap| Binary {
opcode,
- swap: false,
+ swap,
invert: true,
immediate: None,
};
@@ -105,30 +222,32 @@ fn binary(sub_opcode: u32) -> Option<Binary> {
invert: false,
immediate: Some(immediate),
};
- let ps = op(VexPrefix::None, VexMap::Map0F, 0xc2);
- let pd = op66(0xc2);
+ let ps = PS.cmp;
+ let pd = PD.cmp;
Some(match sub_opcode {
V128_AND => plain(VPAND),
V128_OR => plain(VPOR),
V128_XOR => plain(VPXOR),
// NB: andnot is a & !b, vpandn computes !lhs & rhs.
V128_ANDNOT => swapped(VPANDN),
- I8X16_EQ => plain(op66(0x74)),
- I16X8_EQ => plain(op66(0x75)),
- I32X4_EQ => plain(op66(0x76)),
- I64X2_EQ => plain(op66_38(0x29)),
- I8X16_NE => inverted(op66(0x74)),
- I16X8_NE => inverted(op66(0x75)),
- I32X4_NE => inverted(op66(0x76)),
- I64X2_NE => inverted(op66_38(0x29)),
+ I8X16_EQ => plain(VPCMPEQB),
+ I16X8_EQ => plain(VPCMPEQW),
+ I32X4_EQ => plain(VPCMPEQD),
+ I64X2_EQ => plain(VPCMPEQQ),
+ I8X16_NE => inverted(VPCMPEQB, false),
+ I16X8_NE => inverted(VPCMPEQW, false),
+ I32X4_NE => inverted(VPCMPEQD, false),
+ I64X2_NE => inverted(VPCMPEQQ, false),
I8X16_GT_S => plain(op66(0x64)),
I16X8_GT_S => plain(op66(0x65)),
I32X4_GT_S => plain(op66(0x66)),
- I64X2_GT_S => plain(op66_38(0x37)),
+ I64X2_GT_S => plain(VPCMPGTQ),
I8X16_LT_S => swapped(op66(0x64)),
I16X8_LT_S => swapped(op66(0x65)),
I32X4_LT_S => swapped(op66(0x66)),
- I64X2_LT_S => swapped(op66_38(0x37)),
+ I64X2_LT_S => swapped(VPCMPGTQ),
+ I64X2_LE_S => inverted(VPCMPGTQ, false),
+ I64X2_GE_S => inverted(VPCMPGTQ, true),
F32X4_EQ => compare(ps, false, 0),
F32X4_NE => compare(ps, false, 4),
F32X4_LT => compare(ps, false, 1),
@@ -141,10 +260,10 @@ fn binary(sub_opcode: u32) -> Option<Binary> {
F64X2_LE => compare(pd, false, 2),
F64X2_GT => compare(pd, true, 1),
F64X2_GE => compare(pd, true, 2),
- I8X16_ADD => plain(op66(0xfc)),
+ I8X16_ADD => plain(VPADDB),
I16X8_ADD => plain(op66(0xfd)),
- I32X4_ADD => plain(op66(0xfe)),
- I64X2_ADD => plain(op66(0xd4)),
+ I32X4_ADD => plain(VPADDD),
+ I64X2_ADD => plain(VPADDQ),
I8X16_SUB => plain(VPSUBB),
I16X8_SUB => plain(VPSUBW),
I32X4_SUB => plain(VPSUBD),
@@ -153,8 +272,21 @@ fn binary(sub_opcode: u32) -> Option<Binary> {
I8X16_ADD_SAT_U => plain(VPADDUSB),
I8X16_SUB_SAT_S => plain(op66(0xe8)),
I8X16_SUB_SAT_U => plain(op66(0xd8)),
- I16X8_MUL => plain(op66(0xd5)),
+ I16X8_ADD_SAT_S => plain(op66(0xed)),
+ I16X8_ADD_SAT_U => plain(op66(0xdd)),
+ I16X8_SUB_SAT_S => plain(op66(0xe9)),
+ I16X8_SUB_SAT_U => plain(op66(0xd9)),
+ I8X16_AVGR_U => plain(op66(0xe0)),
+ I16X8_AVGR_U => plain(op66(0xe3)),
+ I16X8_MUL => plain(VPMULLW),
I32X4_MUL => plain(op66_38(0x40)),
+ I32X4_DOT_I16X8_S => plain(VPMADDWD),
+ // NB: vpmaddubsw multiplies the unsigned bytes of its first source with the signed bytes of its second.
+ I16X8_RELAXED_DOT_I8X16_I7X16_S => swapped(VPMADDUBSW),
+ I8X16_NARROW_I16X8_S => plain(VPACKSSWB),
+ I8X16_NARROW_I16X8_U => plain(op66(0x67)),
+ I16X8_NARROW_I32X4_S => plain(op66(0x6b)),
+ I16X8_NARROW_I32X4_U => plain(op66_38(0x2b)),
I8X16_MIN_S => plain(op66_38(0x38)),
I8X16_MIN_U => plain(op66(0xda)),
I8X16_MAX_S => plain(op66_38(0x3c)),
@@ -165,35 +297,162 @@ fn binary(sub_opcode: u32) -> Option<Binary> {
I16X8_MAX_U => plain(op66_38(0x3e)),
I32X4_MIN_S => plain(op66_38(0x39)),
I32X4_MIN_U => plain(op66_38(0x3b)),
- I32X4_MAX_S => plain(op66_38(0x3d)),
+ I32X4_MAX_S => plain(VPMAXSD),
I32X4_MAX_U => plain(op66_38(0x3f)),
- F32X4_ADD => plain(op(VexPrefix::None, VexMap::Map0F, 0x58)),
- F32X4_SUB => plain(op(VexPrefix::None, VexMap::Map0F, 0x5c)),
- F32X4_MUL => plain(op(VexPrefix::None, VexMap::Map0F, 0x59)),
- F32X4_DIV => plain(op(VexPrefix::None, VexMap::Map0F, 0x5e)),
- F64X2_ADD => plain(op66(0x58)),
- F64X2_SUB => plain(op66(0x5c)),
- F64X2_MUL => plain(op66(0x59)),
+ F32X4_ADD => plain(PS.add),
+ F32X4_SUB => plain(PS.sub),
+ F32X4_MUL => plain(PS.mul),
+ F32X4_DIV => plain(op0f(0x5e)),
+ F64X2_ADD => plain(PD.add),
+ F64X2_SUB => plain(PD.sub),
+ F64X2_MUL => plain(PD.mul),
F64X2_DIV => plain(op66(0x5e)),
+ // pmin is b < a ? b : a, which minps computes with b first.
+ F32X4_PMIN => swapped(PS.min),
+ F32X4_PMAX => swapped(PS.max),
+ F64X2_PMIN => swapped(PD.min),
+ F64X2_PMAX => swapped(PD.max),
_ => return None,
})
}
-/// The shift by an xmm count of a SIMD shift, and the bits of its lanes.
-fn shift(sub_opcode: u32) -> Option<(VexOpcode, u32)> {
+/// The 32-bit lanes a shuffle picks, if it moves whole ones: 0 to 3 from the first operand, 4 to 7 from the second.
+fn dword_lanes(lanes: &[u8; 16]) -> Option<[u8; 4]> {
+ let mut dwords = [0; 4];
+ for (index, group) in lanes.as_chunks::<4>().0.iter().enumerate() {
+ if group[0] % 4 != 0 || (1..4).any(|byte| group[byte] != group[0] + byte as u8) {
+ return None;
+ }
+ dwords[index] = group[0] / 4;
+ }
+ Some(dwords)
+}
+
+/// The unsigned or signed comparisons that compare a lane with the minimum or maximum of both: the min/max
+/// instruction, the equality comparison, and whether the result is inverted.
+fn compare_with_bound(sub_opcode: u32) -> Option<(VexOpcode, VexOpcode, bool)> {
+ let (min_u8, max_u8, min_s8, max_s8) = (op66(0xda), op66(0xde), op66_38(0x38), op66_38(0x3c));
+ let (min_u16, max_u16, min_s16, max_s16) = (op66_38(0x3a), op66_38(0x3e), op66(0xea), op66(0xee));
+ let (min_u32, max_u32, min_s32, max_s32) = (op66_38(0x3b), op66_38(0x3f), op66_38(0x39), VPMAXSD);
+ // a <= b where min(a, b) == a, a >= b where max(a, b) == a, and the strict ones are the others inverted.
+ Some(match sub_opcode {
+ I8X16_LT_U => (max_u8, VPCMPEQB, true),
+ I8X16_GT_U => (min_u8, VPCMPEQB, true),
+ I8X16_LE_U => (min_u8, VPCMPEQB, false),
+ I8X16_GE_U => (max_u8, VPCMPEQB, false),
+ I8X16_LE_S => (min_s8, VPCMPEQB, false),
+ I8X16_GE_S => (max_s8, VPCMPEQB, false),
+ I16X8_LT_U => (max_u16, VPCMPEQW, true),
+ I16X8_GT_U => (min_u16, VPCMPEQW, true),
+ I16X8_LE_U => (min_u16, VPCMPEQW, false),
+ I16X8_GE_U => (max_u16, VPCMPEQW, false),
+ I16X8_LE_S => (min_s16, VPCMPEQW, false),
+ I16X8_GE_S => (max_s16, VPCMPEQW, false),
+ I32X4_LT_U => (max_u32, VPCMPEQD, true),
+ I32X4_GT_U => (min_u32, VPCMPEQD, true),
+ I32X4_LE_U => (min_u32, VPCMPEQD, false),
+ I32X4_GE_U => (max_u32, VPCMPEQD, false),
+ I32X4_LE_S => (min_s32, VPCMPEQD, false),
+ I32X4_GE_S => (max_s32, VPCMPEQD, false),
+ _ => return None,
+ })
+}
+
+/// A shift of 16-, 32- or 64-bit lanes: the shift by an xmm count, the group opcode and digit of the shift by an
+/// immediate, and the bits of the lanes.
+fn shift(sub_opcode: u32) -> Option<(VexOpcode, (VexOpcode, u8), u32)> {
+ let (words, dwords, qwords) = (op66(0x71), op66(0x72), op66(0x73));
Some(match sub_opcode {
- I16X8_SHL => (op66(0xf1), 16),
- I16X8_SHR_S => (op66(0xe1), 16),
- I16X8_SHR_U => (op66(0xd1), 16),
- I32X4_SHL => (op66(0xf2), 32),
- I32X4_SHR_S => (op66(0xe2), 32),
- I32X4_SHR_U => (op66(0xd2), 32),
- I64X2_SHL => (op66(0xf3), 64),
- I64X2_SHR_U => (op66(0xd3), 64),
+ I16X8_SHL => (op66(0xf1), (words, 6), 16),
+ I16X8_SHR_S => (op66(0xe1), (words, 4), 16),
+ I16X8_SHR_U => (op66(0xd1), (words, 2), 16),
+ I32X4_SHL => (op66(0xf2), (dwords, 6), 32),
+ I32X4_SHR_S => (op66(0xe2), (dwords, 4), 32),
+ I32X4_SHR_U => (op66(0xd2), (dwords, 2), 32),
+ I64X2_SHL => (op66(0xf3), (qwords, 6), 64),
+ I64X2_SHR_U => (op66(0xd3), (qwords, 2), 64),
_ => return None,
})
}
+const VPSLLW: VexOpcode = op66(0xf1);
+const VPSRLW: VexOpcode = op66(0xd1);
+const VPSRAW: VexOpcode = op66(0xe1);
+const VPSRLQ: VexOpcode = op66(0xd3);
+const SHIFT_WORDS: VexOpcode = op66(0x71);
+const SHIFT_DWORDS: VexOpcode = op66(0x72);
+const SHIFT_QWORDS: VexOpcode = op66(0x73);
+
+/// The sub-opcode of a ternary SIMD operation, from the flags of its `VectorTernary` node: its low byte.
+fn ternary_sub_opcode(flags: u8) -> u32 {
+ if u32::from(flags) == V128_BITSELECT {
+ V128_BITSELECT
+ } else {
+ 0x100 | u32::from(flags)
+ }
+}
+
+/// Whether a SIMD binary operation is a shift by an i32, whose count may be a constant.
+pub(crate) fn is_vector_shift(sub_opcode: u32) -> bool {
+ matches!(
+ sub_opcode,
+ I8X16_SHL
+ | I8X16_SHR_S
+ | I8X16_SHR_U
+ | I16X8_SHL
+ | I16X8_SHR_S
+ | I16X8_SHR_U
+ | I32X4_SHL
+ | I32X4_SHR_S
+ | I32X4_SHR_U
+ | I64X2_SHL
+ | I64X2_SHR_S
+ | I64X2_SHR_U
+ )
+}
+
+/// The inputs of vector node `value` its lowering may read from the constant pool where they are v128 constants, as
+/// a mask: those that are the r/m operand of an instruction and read only there.
+pub(crate) fn vector_constant_inputs(func: &Func, value: Value) -> u8 {
+ let node = func.node(value);
+ match node.op {
+ Op::VectorBinary => match binary(node.args[2]) {
+ // NB: The encoder has no rip-relative operands before an immediate.
+ Some(binary) if binary.immediate.is_some() => 0,
+ Some(binary) if binary.swap => 0b001,
+ Some(_) => 0b010,
+ None if compare_with_bound(node.args[2]).is_some() => 0b010,
+ None => 0,
+ },
+ Op::VectorTernary => match ternary_sub_opcode(node.flags) {
+ F32X4_RELAXED_MADD | F64X2_RELAXED_MADD => 0b110,
+ F32X4_RELAXED_NMADD | F64X2_RELAXED_NMADD => 0b010,
+ I32X4_RELAXED_DOT_I8X16_I7X16_ADD_S => 0b101,
+ _ => 0,
+ },
+ _ => 0,
+ }
+}
+
+/// The number of xmm temps the lowering of vector node `value` takes, besides the scratch register.
+pub(crate) fn vector_temps(func: &Func, value: Value) -> usize {
+ let node = func.node(value);
+ match node.op {
+ // NB: Only shuffles of two vectors that no single instruction does need one.
+ Op::Shuffle => usize::from(node.args[0] != node.args[1]),
+ Op::VectorTernary => usize::from(ternary_sub_opcode(node.flags) == V128_BITSELECT),
+ Op::VectorUnary => usize::from(matches!(
+ node.args[1],
+ I8X16_ALL_TRUE | I16X8_ALL_TRUE | I32X4_ALL_TRUE | I64X2_ALL_TRUE | I8X16_POPCNT | I32X4_TRUNC_SAT_F32X4_U
+ )),
+ Op::VectorBinary => usize::from(matches!(
+ node.args[2],
+ I64X2_MUL | I8X16_SHL | I8X16_SHR_S | I8X16_SHR_U | I64X2_SHR_S
+ )),
+ _ => 0,
+ }
+}
+
fn register(register: Register) -> VexOperand {
VexOperand::Register(register_number(register))
}
@@ -210,25 +469,58 @@ fn register_number(register: Register) -> u8 {
const SCRATCH_XMM: u8 = SCRATCH_FPR.0;
impl CodeGenerator<'_> {
- /// `op dst, lhs, rhs` with allocator registers.
- fn vector_op(&mut self, opcode: VexOpcode, dst: u8, lhs: u8, rhs: VexOperand) {
- self.asm.vex(opcode, dst, lhs, rhs, None);
+ /// Input `index` of vector node `value` as an operand: its register, or the constant pool entry of a v128 constant
+ /// the allocator left where it is.
+ fn vector_input(&mut self, value: Value, index: usize, register: Register) -> VexOperand {
+ if register != CONSTANT_INPUT {
+ return VexOperand::Register(fpr(register).0);
+ }
+ let func = self.func;
+ let constant = func.node(func.inputs(value)[index]);
+ debug_assert_eq!(constant.op, Op::Const128);
+ VexOperand::Label(self.constant_label(func.constants[constant.args[0] as usize]))
+ }
+
+ /// `op dst, lhs, rhs` on xmm registers by their encoding.
+ fn vector_op(&mut self, opcode: VexOpcode, dst: u8, lhs: u8, rhs: u8) {
+ self.asm.vex(opcode, dst, lhs, VexOperand::Register(rhs), None);
+ }
+
+ /// `op dst, lhs, [constant]`.
+ fn vector_op_constant(&mut self, opcode: VexOpcode, dst: u8, lhs: u8, bits: u128) {
+ let label = self.constant_label(bits);
+ self.asm.vex(opcode, dst, lhs, VexOperand::Label(label), None);
+ }
+
+ /// `op dst, src` (and an immediate) of the instructions without a second source.
+ fn vector_unary_op(&mut self, opcode: VexOpcode, dst: u8, src: u8, immediate: Option<u8>) {
+ self.asm.vex(opcode, dst, 0, VexOperand::Register(src), immediate);
}
- /// The label of a 16-byte constant in the constant pool.
- fn vector_label(&mut self, bits: u128) -> crate::asm::Label {
- self.constant_label(bits)
+ /// A shift by an immediate: `group` is the opcode of the lane width, `digit` picks the shift.
+ fn vector_shift_immediate(&mut self, (group, digit): (VexOpcode, u8), dst: u8, src: u8, count: u8) {
+ self.asm.vex(group, digit, dst, VexOperand::Register(src), Some(count));
}
- /// Fills the scratch xmm register with ones.
- fn scratch_ones(&mut self) {
- self.asm.vex(
- VPCMPEQD,
- SCRATCH_XMM,
- SCRATCH_XMM,
- VexOperand::Register(SCRATCH_XMM),
- None,
- );
+ /// Loads a 16-byte constant into the xmm register `dst`.
+ fn vector_load_constant(&mut self, dst: u8, bits: u128) {
+ let label = self.constant_label(bits);
+ self.asm.vex(VMOVUPS_LOAD, dst, 0, VexOperand::Label(label), None);
+ }
+
+ /// Fills the xmm register `dst` with ones.
+ fn vector_ones(&mut self, dst: u8) {
+ self.vector_op(VPCMPEQD, dst, dst, dst);
+ }
+
+ fn vector_zero(&mut self, dst: u8) {
+ self.vector_op(VPXOR, dst, dst, dst);
+ }
+
+ /// Inverts the bits of the xmm register `dst`, through the scratch register.
+ fn vector_invert(&mut self, dst: u8) {
+ self.vector_ones(SCRATCH_XMM);
+ self.vector_op(VPXOR, dst, dst, SCRATCH_XMM);
}
pub(super) fn vector_load(&mut self, value: Value, address: &Address) {
@@ -259,16 +551,12 @@ impl CodeGenerator<'_> {
let record = *self.allocation.node(value);
let [a, b, c] = record.inputs;
let output = record.output;
+ let temp = record.temps[0];
match node.op {
- Op::VectorUnary => self.vector_unary(node.args[1], node.ty, output, a, record.temps[0]),
- Op::VectorBinary => self.vector_binary(node.args[2], output, a, b),
+ Op::VectorUnary => self.vector_unary(node.args[1], node.ty, output, a, temp),
+ Op::VectorBinary => self.vector_binary(value, node.args[2], output, a, b, temp),
Op::VectorTernary => {
- // bitselect(a, b, mask) = (a & mask) | (b & !mask)
- let (dst, a, b, mask) = (fpr(output).0, fpr(a).0, fpr(b).0, fpr(c).0);
- let temp = fpr(record.temps[0]).0;
- self.vector_op(VPAND, temp, a, VexOperand::Register(mask));
- self.vector_op(VPANDN, dst, mask, VexOperand::Register(b));
- self.vector_op(VPOR, dst, dst, VexOperand::Register(temp));
+ self.vector_ternary(value, ternary_sub_opcode(node.flags), output, [a, b, c], temp);
}
Op::ExtractLane => self.extract_lane(node.args[1], node.args[2] as u8, output, a),
Op::ReplaceLane => {
@@ -283,36 +571,106 @@ impl CodeGenerator<'_> {
F32X4_REPLACE_LANE => self.asm.vex(VINSERTPS, dst, vector, register(b), Some(lane << 4)),
_ => {
let opcode = if lane == 0 { VMOVSD_MERGE } else { VMOVLHPS };
- self.vector_op(opcode, dst, vector, register(b));
+ self.asm.vex(opcode, dst, vector, register(b), None);
}
}
}
Op::Shuffle => {
let lanes = func.constants[node.args[2] as usize].to_le_bytes();
- let (mut from_a, mut from_b) = ([0x80u8; 16], [0x80u8; 16]);
- for (position, lane) in lanes.iter().enumerate() {
- if *lane < 16 {
- from_a[position] = *lane;
- } else {
- from_b[position] = lane - 16;
- }
- }
- let (dst, a, b) = (fpr(output).0, fpr(a).0, fpr(b).0);
- let temp = fpr(record.temps[0]).0;
- let label_a = self.vector_label(u128::from_le_bytes(from_a));
- let label_b = self.vector_label(u128::from_le_bytes(from_b));
- self.asm.vex(VPSHUFB, temp, a, VexOperand::Label(label_a), None);
- self.asm.vex(VPSHUFB, dst, b, VexOperand::Label(label_b), None);
- self.vector_op(VPOR, dst, dst, VexOperand::Register(temp));
+ let single = node.args[0] == node.args[1];
+ let temp = if temp == crate::regalloc::NO_REGISTER {
+ 0
+ } else {
+ fpr(temp).0
+ };
+ self.shuffle(lanes, single, fpr(output).0, fpr(a).0, fpr(b).0, temp);
}
_ => unreachable!("{} is no vector op", node.op.name()),
}
}
+ /// `i8x16.shuffle`, with the lanes of `a` and `b` (0 to 31). The builder made `a` and `b` the same value where
+ /// only one of them is used, and its lanes 0 to 15.
+ fn shuffle(&mut self, lanes: [u8; 16], single: bool, dst: u8, a: u8, b: u8, temp: u8) {
+ let dwords = dword_lanes(&lanes);
+ if single {
+ if let Some(d) = dwords {
+ let immediate = d[0] | (d[1] << 2) | (d[2] << 4) | (d[3] << 6);
+ self.vector_unary_op(VPSHUFD, dst, a, Some(immediate));
+ return;
+ }
+ if let Some(n) = (1..16u8).find(|&n| lanes.iter().enumerate().all(|(i, &lane)| lane == (i as u8 + n) & 15))
+ {
+ self.asm.vex(VPALIGNR, dst, a, VexOperand::Register(a), Some(n));
+ return;
+ }
+ self.vector_op_constant(VPSHUFB, dst, a, u128::from_le_bytes(lanes));
+ return;
+ }
+ if let Some(d) = dwords {
+ match d {
+ [0, 4, 1, 5] => return self.vector_op(VPUNPCKLDQ, dst, a, b),
+ [2, 6, 3, 7] => return self.vector_op(VPUNPCKHDQ, dst, a, b),
+ [4, 0, 5, 1] => return self.vector_op(VPUNPCKLDQ, dst, b, a),
+ [6, 2, 7, 3] => return self.vector_op(VPUNPCKHDQ, dst, b, a),
+ _ => {}
+ }
+ let immediate = |d: [u8; 4]| (d[0] & 3) | ((d[1] & 3) << 2) | ((d[2] & 3) << 4) | ((d[3] & 3) << 6);
+ if d[0] < 4 && d[1] < 4 && d[2] >= 4 && d[3] >= 4 {
+ self.asm
+ .vex(VSHUFPS, dst, a, VexOperand::Register(b), Some(immediate(d)));
+ return;
+ }
+ if d[0] >= 4 && d[1] >= 4 && d[2] < 4 && d[3] < 4 {
+ self.asm
+ .vex(VSHUFPS, dst, b, VexOperand::Register(a), Some(immediate(d)));
+ return;
+ }
+ if d.iter().enumerate().all(|(i, &lane)| lane & 3 == i as u8) {
+ let mask = d
+ .iter()
+ .enumerate()
+ .fold(0, |mask, (i, &lane)| mask | (u8::from(lane >= 4) << i));
+ self.asm.vex(VPBLENDD, dst, a, VexOperand::Register(b), Some(mask));
+ return;
+ }
+ }
+ // a and b concatenated, shifted right by n bytes, or b and a.
+ for n in 1..16u8 {
+ if lanes.iter().enumerate().all(|(i, &lane)| lane == i as u8 + n) {
+ self.asm.vex(VPALIGNR, dst, b, VexOperand::Register(a), Some(n));
+ return;
+ }
+ if lanes
+ .iter()
+ .enumerate()
+ .all(|(i, &lane)| lane == (i as u8 + n + 16) & 31)
+ {
+ self.asm.vex(VPALIGNR, dst, a, VexOperand::Register(b), Some(n));
+ return;
+ }
+ }
+ let (mut from_a, mut from_b) = ([0x80u8; 16], [0x80u8; 16]);
+ for (position, lane) in lanes.iter().enumerate() {
+ if *lane < 16 {
+ from_a[position] = *lane;
+ } else {
+ from_b[position] = lane - 16;
+ }
+ }
+ self.vector_op_constant(VPSHUFB, temp, a, u128::from_le_bytes(from_a));
+ self.vector_op_constant(VPSHUFB, dst, b, u128::from_le_bytes(from_b));
+ self.vector_op(VPOR, dst, dst, temp);
+ }
+
fn vector_unary(&mut self, sub_opcode: u32, ty: Type, output: Register, a: Register, temp: Register) {
+ if ty == Type::I32 {
+ self.vector_test(sub_opcode, output, a, temp);
+ return;
+ }
+ let dst = fpr(output).0;
match sub_opcode {
I8X16_SPLAT | I16X8_SPLAT | I32X4_SPLAT | I64X2_SPLAT => {
- let dst = fpr(output).0;
let width = if sub_opcode == I64X2_SPLAT {
Width::W64
} else {
@@ -325,21 +683,30 @@ impl CodeGenerator<'_> {
I32X4_SPLAT => VPBROADCASTD,
_ => VPBROADCASTQ,
};
- self.asm.vex(broadcast, dst, 0, VexOperand::Register(dst), None);
+ self.vector_unary_op(broadcast, dst, dst, None);
}
- F32X4_SPLAT => self.asm.vex(VBROADCASTSS, fpr(output).0, 0, register(a), None),
- F64X2_SPLAT => self.asm.vex(VMOVDDUP, fpr(output).0, 0, register(a), None),
+ F32X4_SPLAT => self.vector_unary_op(VBROADCASTSS, dst, fpr(a).0, None),
+ F64X2_SPLAT => self.vector_unary_op(VMOVDDUP, dst, fpr(a).0, None),
+ _ => self.vector_lanewise_unary(sub_opcode, dst, fpr(a).0, temp),
+ }
+ }
+
+ /// The unary operations from a vector to a vector.
+ fn vector_lanewise_unary(&mut self, sub_opcode: u32, dst: u8, a: u8, temp: Register) {
+ match sub_opcode {
V128_NOT => {
- self.scratch_ones();
- self.vector_op(VPXOR, fpr(output).0, fpr(a).0, VexOperand::Register(SCRATCH_XMM));
- }
- I8X16_ABS | I16X8_ABS | I32X4_ABS => {
- let opcode = match sub_opcode {
- I8X16_ABS => op66_38(0x1c),
- I16X8_ABS => op66_38(0x1d),
- _ => op66_38(0x1e),
- };
- self.asm.vex(opcode, fpr(output).0, 0, register(a), None);
+ self.vector_ones(SCRATCH_XMM);
+ self.vector_op(VPXOR, dst, a, SCRATCH_XMM);
+ }
+ I8X16_ABS => self.vector_unary_op(op66_38(0x1c), dst, a, None),
+ I16X8_ABS => self.vector_unary_op(op66_38(0x1d), dst, a, None),
+ I32X4_ABS => self.vector_unary_op(op66_38(0x1e), dst, a, None),
+ I64X2_ABS => {
+ // (a ^ sign) - sign
+ self.vector_zero(SCRATCH_XMM);
+ self.vector_op(VPCMPGTQ, SCRATCH_XMM, SCRATCH_XMM, a);
+ self.vector_op(VPXOR, dst, a, SCRATCH_XMM);
+ self.vector_op(VPSUBQ, dst, dst, SCRATCH_XMM);
}
I8X16_NEG | I16X8_NEG | I32X4_NEG | I64X2_NEG => {
let subtract = match sub_opcode {
@@ -348,46 +715,163 @@ impl CodeGenerator<'_> {
I32X4_NEG => VPSUBD,
_ => VPSUBQ,
};
- let dst = fpr(output).0;
- self.vector_op(VPXOR, dst, dst, VexOperand::Register(dst));
- self.vector_op(subtract, dst, dst, register(a));
+ self.vector_zero(dst);
+ self.vector_op(subtract, dst, dst, a);
+ }
+ I8X16_POPCNT => {
+ // The bits of each nibble, looked up in a table of 16.
+ const NIBBLE_BITS: u128 = u128::from_le_bytes([0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]);
+ let table = fpr(temp).0;
+ self.vector_load_constant(table, NIBBLE_BITS);
+ self.vector_op_constant(VPAND, SCRATCH_XMM, a, splat8(0x0f));
+ self.vector_op(VPSHUFB, SCRATCH_XMM, table, SCRATCH_XMM);
+ self.vector_shift_immediate((SHIFT_WORDS, 2), dst, a, 4);
+ self.vector_op_constant(VPAND, dst, dst, splat8(0x0f));
+ self.vector_op(VPSHUFB, dst, table, dst);
+ self.vector_op(VPADDB, dst, dst, SCRATCH_XMM);
}
F32X4_ABS | F32X4_NEG | F64X2_ABS | F64X2_NEG => {
let sign = if matches!(sub_opcode, F32X4_ABS | F32X4_NEG) {
- 0x8000_0000_8000_0000_8000_0000_8000_0000u128
+ splat32(0x8000_0000)
} else {
- 0x8000_0000_0000_0000_8000_0000_0000_0000u128
+ splat64(0x8000_0000_0000_0000)
};
- let label = self.vector_label(sign);
- let negate = matches!(sub_opcode, F32X4_NEG | F64X2_NEG);
- if negate {
- self.asm
- .vex(VXORPS, fpr(output).0, fpr(a).0, VexOperand::Label(label), None);
+ if matches!(sub_opcode, F32X4_NEG | F64X2_NEG) {
+ self.vector_op_constant(VXORPS, dst, a, sign);
} else {
- self.asm
- .vex(VMOVUPS_LOAD, SCRATCH_XMM, 0, VexOperand::Label(label), None);
- self.vector_op(VANDNPS, fpr(output).0, SCRATCH_XMM, register(a));
+ self.vector_load_constant(SCRATCH_XMM, sign);
+ self.vector_op(VANDNPS, dst, SCRATCH_XMM, a);
}
}
- F32X4_SQRT => self.asm.vex(
- op(VexPrefix::None, VexMap::Map0F, 0x51),
- fpr(output).0,
- 0,
- register(a),
- None,
- ),
- F64X2_SQRT => self.asm.vex(op66(0x51), fpr(output).0, 0, register(a), None),
- F32X4_CONVERT_I32X4_S => {
- self.asm.vex(
- op(VexPrefix::None, VexMap::Map0F, 0x5b),
- fpr(output).0,
- 0,
- register(a),
- None,
- );
+ F32X4_SQRT => self.vector_unary_op(op0f(0x51), dst, a, None),
+ F64X2_SQRT => self.vector_unary_op(op66(0x51), dst, a, None),
+ // roundps immediates: 0 to nearest, 1 down, 2 up, 3 toward zero.
+ F32X4_NEAREST => self.vector_unary_op(PS.round, dst, a, Some(0)),
+ F32X4_FLOOR => self.vector_unary_op(PS.round, dst, a, Some(1)),
+ F32X4_CEIL => self.vector_unary_op(PS.round, dst, a, Some(2)),
+ F32X4_TRUNC => self.vector_unary_op(PS.round, dst, a, Some(3)),
+ F64X2_NEAREST => self.vector_unary_op(PD.round, dst, a, Some(0)),
+ F64X2_FLOOR => self.vector_unary_op(PD.round, dst, a, Some(1)),
+ F64X2_CEIL => self.vector_unary_op(PD.round, dst, a, Some(2)),
+ F64X2_TRUNC => self.vector_unary_op(PD.round, dst, a, Some(3)),
+ I16X8_EXTEND_LOW_I8X16_S
+ | I16X8_EXTEND_HIGH_I8X16_S
+ | I16X8_EXTEND_LOW_I8X16_U
+ | I16X8_EXTEND_HIGH_I8X16_U
+ | I32X4_EXTEND_LOW_I16X8_S
+ | I32X4_EXTEND_HIGH_I16X8_S
+ | I32X4_EXTEND_LOW_I16X8_U
+ | I32X4_EXTEND_HIGH_I16X8_U
+ | I64X2_EXTEND_LOW_I32X4_S
+ | I64X2_EXTEND_HIGH_I32X4_S
+ | I64X2_EXTEND_LOW_I32X4_U
+ | I64X2_EXTEND_HIGH_I32X4_U => {
+ let (extend, high) = extension(sub_opcode);
+ let source = if high {
+ // The high half moves down first.
+ self.vector_unary_op(VPSHUFD, dst, a, Some(0xee));
+ dst
+ } else {
+ a
+ };
+ self.vector_unary_op(extend, dst, source, None);
+ }
+ I16X8_EXTADD_PAIRWISE_I8X16_S => {
+ self.vector_load_constant(SCRATCH_XMM, splat8(1));
+ self.vector_op(VPMADDUBSW, dst, SCRATCH_XMM, a);
+ }
+ I16X8_EXTADD_PAIRWISE_I8X16_U => self.vector_op_constant(VPMADDUBSW, dst, a, splat8(1)),
+ I32X4_EXTADD_PAIRWISE_I16X8_S => self.vector_op_constant(VPMADDWD, dst, a, splat16(1)),
+ I32X4_EXTADD_PAIRWISE_I16X8_U => {
+ // Biased to signed lanes, added in pairs, and the bias of two lanes added back.
+ self.vector_op_constant(VPXOR, dst, a, splat16(0x8000));
+ self.vector_op_constant(VPMADDWD, dst, dst, splat16(1));
+ self.vector_op_constant(VPADDD, dst, dst, splat32(0x10000));
+ }
+ F32X4_CONVERT_I32X4_S => self.vector_unary_op(VCVTDQ2PS, dst, a, None),
+ F32X4_CONVERT_I32X4_U => {
+ // The low 16 bits and the rest convert exactly on their own; the rest halved, so that it is
+ // positive, and doubled again. Adding both rounds once.
+ self.vector_zero(SCRATCH_XMM);
+ self.asm
+ .vex(VPBLENDW, SCRATCH_XMM, SCRATCH_XMM, VexOperand::Register(a), Some(0x55));
+ self.vector_op(VPSUBD, dst, a, SCRATCH_XMM);
+ self.vector_unary_op(VCVTDQ2PS, SCRATCH_XMM, SCRATCH_XMM, None);
+ self.vector_shift_immediate((SHIFT_DWORDS, 2), dst, dst, 1);
+ self.vector_unary_op(VCVTDQ2PS, dst, dst, None);
+ self.vector_op(PS.add, dst, dst, dst);
+ self.vector_op(PS.add, dst, dst, SCRATCH_XMM);
+ }
+ I32X4_TRUNC_SAT_F32X4_S => {
+ // NaN lanes become 0 first. cvttps2dq makes every lane out of range 0x80000000, which is right for
+ // negative ones; positive ones, whose sign flipped, become 0x7fffffff.
+ self.asm
+ .vex(PS.cmp, SCRATCH_XMM, a, VexOperand::Register(a), Some(CMP_EQ));
+ self.vector_op(PS.and, dst, a, SCRATCH_XMM);
+ self.vector_op(VPXOR, SCRATCH_XMM, SCRATCH_XMM, dst);
+ self.vector_unary_op(VCVTTPS2DQ, dst, dst, None);
+ self.vector_op(VPAND, SCRATCH_XMM, SCRATCH_XMM, dst);
+ self.vector_shift_immediate((SHIFT_DWORDS, 4), SCRATCH_XMM, SCRATCH_XMM, 31);
+ self.vector_op(VPXOR, dst, dst, SCRATCH_XMM);
+ }
+ I32X4_TRUNC_SAT_F32X4_U => {
+ let temp = fpr(temp).0;
+ // NaN and negative lanes become 0.
+ self.vector_zero(temp);
+ self.vector_op(PS.max, dst, a, temp);
+ // 2^31 as a float, and the lanes less that: those of 2^31 and up convert as signed, those of 2^32
+ // and up have all bits set, and the others are clamped to 0.
+ self.vector_ones(temp);
+ self.vector_shift_immediate((SHIFT_DWORDS, 2), temp, temp, 1);
+ self.vector_unary_op(VCVTDQ2PS, temp, temp, None);
+ self.vector_op(PS.sub, SCRATCH_XMM, dst, temp);
+ self.asm
+ .vex(PS.cmp, temp, temp, VexOperand::Register(SCRATCH_XMM), Some(CMP_LE));
+ self.vector_unary_op(VCVTTPS2DQ, SCRATCH_XMM, SCRATCH_XMM, None);
+ self.vector_op(VPXOR, SCRATCH_XMM, SCRATCH_XMM, temp);
+ self.vector_zero(temp);
+ self.vector_op(VPMAXSD, SCRATCH_XMM, SCRATCH_XMM, temp);
+ // The lanes below 2^31 convert as they are, the others to 0x80000000, plus what they exceed it by.
+ self.vector_unary_op(VCVTTPS2DQ, dst, dst, None);
+ self.vector_op(VPADDD, dst, dst, SCRATCH_XMM);
+ }
+ I32X4_TRUNC_SAT_F64X2_S_ZERO => {
+ // NaN lanes are clamped to 0, the others to i32::MAX; cvttpd2dq makes the negative lanes out of
+ // range 0x80000000.
+ self.asm
+ .vex(PD.cmp, SCRATCH_XMM, a, VexOperand::Register(a), Some(CMP_EQ));
+ self.vector_op_constant(PD.and, SCRATCH_XMM, SCRATCH_XMM, splat64(2_147_483_647f64.to_bits()));
+ self.vector_op(PD.min, dst, a, SCRATCH_XMM);
+ self.vector_unary_op(op66(0xe6), dst, dst, None);
}
+ I32X4_TRUNC_SAT_F64X2_U_ZERO => {
+ // Clamped to [0, u32::MAX] (NaN to 0), truncated, and the integer read from the mantissa of
+ // 2^52 + lane.
+ self.vector_zero(SCRATCH_XMM);
+ self.vector_op(PD.max, dst, a, SCRATCH_XMM);
+ self.vector_op_constant(PD.min, dst, dst, splat64(4_294_967_295f64.to_bits()));
+ self.vector_unary_op(PD.round, dst, dst, Some(3));
+ self.vector_op_constant(PD.add, dst, dst, splat64(4_503_599_627_370_496f64.to_bits()));
+ self.asm
+ .vex(VSHUFPS, dst, dst, VexOperand::Register(SCRATCH_XMM), Some(0x88));
+ }
+ F64X2_CONVERT_LOW_I32X4_S => self.vector_unary_op(opf3(0xe6), dst, a, None),
+ F64X2_CONVERT_LOW_I32X4_U => {
+ // Each lane as the low bits of the mantissa of 2^52, less 2^52.
+ self.vector_op_constant(VUNPCKLPS, dst, a, splat32(0x4330_0000));
+ self.vector_op_constant(PD.sub, dst, dst, splat64(4_503_599_627_370_496f64.to_bits()));
+ }
+ F32X4_DEMOTE_F64X2_ZERO => self.vector_unary_op(op66(0x5a), dst, a, None),
+ F64X2_PROMOTE_LOW_F32X4 => self.vector_unary_op(op0f(0x5a), dst, a, None),
+ _ => unreachable!("SIMD sub-opcode {sub_opcode:#x} is no unary vector operation"),
+ }
+ }
+
+ /// The reductions of a vector to an i32.
+ fn vector_test(&mut self, sub_opcode: u32, output: Register, a: Register, temp: Register) {
+ let dst = gpr(output);
+ match sub_opcode {
V128_ANY_TRUE => {
- let dst = gpr(output);
self.asm.xor_rr(Width::W32, dst, dst);
self.asm.vex(VPTEST, fpr(a).0, 0, register(a), None);
self.asm.setcc(Cond::NotEqual, dst);
@@ -395,54 +879,308 @@ impl CodeGenerator<'_> {
I8X16_ALL_TRUE | I16X8_ALL_TRUE | I32X4_ALL_TRUE | I64X2_ALL_TRUE => {
// All lanes are nonzero where no lane equals zero.
let compare = match sub_opcode {
- I8X16_ALL_TRUE => op66(0x74),
- I16X8_ALL_TRUE => op66(0x75),
- I32X4_ALL_TRUE => op66(0x76),
- _ => op66_38(0x29),
+ I8X16_ALL_TRUE => VPCMPEQB,
+ I16X8_ALL_TRUE => VPCMPEQW,
+ I32X4_ALL_TRUE => VPCMPEQD,
+ _ => VPCMPEQQ,
};
- let (dst, temp) = (gpr(output), fpr(temp).0);
- self.vector_op(VPXOR, temp, temp, VexOperand::Register(temp));
- self.vector_op(compare, temp, temp, register(a));
+ let temp = fpr(temp).0;
+ self.vector_zero(temp);
+ self.vector_op(compare, temp, temp, fpr(a).0);
self.asm.xor_rr(Width::W32, dst, dst);
self.asm.vex(VPTEST, temp, 0, VexOperand::Register(temp), None);
self.asm.setcc(Cond::Equal, dst);
}
- I8X16_BITMASK => self.asm.vex(VPMOVMSKB, gpr(output).0, 0, register(a), None),
- I32X4_BITMASK => self.asm.vex(VMOVMSKPS, gpr(output).0, 0, register(a), None),
- I64X2_BITMASK => self.asm.vex(VMOVMSKPD, gpr(output).0, 0, register(a), None),
- _ => unreachable!("the builder does not make SIMD sub-opcode {sub_opcode:#x} a unary op of {ty:?}"),
+ I8X16_BITMASK => self.asm.vex(VPMOVMSKB, dst.0, 0, register(a), None),
+ I16X8_BITMASK => {
+ // Narrowing with saturation keeps the signs.
+ self.vector_op(VPACKSSWB, SCRATCH_XMM, fpr(a).0, fpr(a).0);
+ self.asm
+ .vex(VPMOVMSKB, dst.0, 0, VexOperand::Register(SCRATCH_XMM), None);
+ self.asm.movzx8_rr(dst, dst);
+ }
+ I32X4_BITMASK => self.asm.vex(VMOVMSKPS, dst.0, 0, register(a), None),
+ I64X2_BITMASK => self.asm.vex(VMOVMSKPD, dst.0, 0, register(a), None),
+ _ => unreachable!("SIMD sub-opcode {sub_opcode:#x} is no reduction to an i32"),
}
}
- fn vector_binary(&mut self, sub_opcode: u32, output: Register, a: Register, b: Register) {
+ fn vector_binary(
+ &mut self,
+ value: Value,
+ sub_opcode: u32,
+ output: Register,
+ a: Register,
+ b: Register,
+ temp: Register,
+ ) {
let dst = fpr(output).0;
- if let Some((opcode, bits)) = shift(sub_opcode) {
- // The count is taken modulo the lane width.
- self.asm.mov_rr(Width::W32, SCRATCH, gpr(b));
- self.asm.and_ri(Width::W32, SCRATCH, bits as i32 - 1);
- self.asm.vmov_xr(Width::W32, SCRATCH_FPR, SCRATCH);
- self.vector_op(opcode, dst, fpr(a).0, VexOperand::Register(SCRATCH_XMM));
+ if is_vector_shift(sub_opcode) {
+ let count = (b == CONSTANT_INPUT).then(|| self.immediate(value, 1) as u32);
+ self.vector_shift(sub_opcode, dst, fpr(a).0, b, count, temp);
return;
}
- if sub_opcode == I8X16_SWIZZLE {
- // Indices of 16 and up select zero: adding 0x70 with saturation sets their top bit, which vpshufb zeroes.
- let label = self.vector_label(0x7070_7070_7070_7070_7070_7070_7070_7070);
- self.asm
- .vex(VPADDUSB, SCRATCH_XMM, fpr(b).0, VexOperand::Label(label), None);
- self.vector_op(VPSHUFB, dst, fpr(a).0, VexOperand::Register(SCRATCH_XMM));
+ if let Some(binary) = binary(sub_opcode) {
+ let (lhs, rhs) = if binary.swap {
+ ((b, 1), (a, 0))
+ } else {
+ ((a, 0), (b, 1))
+ };
+ let rhs = self.vector_input(value, rhs.1, rhs.0);
+ self.asm.vex(binary.opcode, dst, fpr(lhs.0).0, rhs, binary.immediate);
+ if binary.invert {
+ self.vector_invert(dst);
+ }
return;
}
- let binary = binary(sub_opcode).expect("the builder only makes the binary ops code generation knows");
- let (lhs, rhs) = if binary.swap {
- (fpr(b).0, fpr(a).0)
- } else {
- (fpr(a).0, fpr(b).0)
+ if let Some((bound, equal, invert)) = compare_with_bound(sub_opcode) {
+ let rhs = self.vector_input(value, 1, b);
+ self.asm.vex(bound, SCRATCH_XMM, fpr(a).0, rhs, None);
+ self.vector_op(equal, dst, SCRATCH_XMM, fpr(a).0);
+ if invert {
+ self.vector_invert(dst);
+ }
+ return;
+ }
+ let (a, b) = (fpr(a).0, fpr(b).0);
+ match sub_opcode {
+ I8X16_SWIZZLE => {
+ // Indices of 16 and up select zero: adding 0x70 with saturation sets their top bit, which vpshufb
+ // zeroes.
+ self.vector_op_constant(VPADDUSB, SCRATCH_XMM, b, splat8(0x70));
+ self.vector_op(VPSHUFB, dst, a, SCRATCH_XMM);
+ }
+ I64X2_MUL => {
+ // The low halves' full product, plus the cross products shifted up.
+ let temp = fpr(temp).0;
+ self.vector_shift_immediate((SHIFT_QWORDS, 2), temp, a, 32);
+ self.vector_op(VPMULUDQ, temp, temp, b);
+ self.vector_shift_immediate((SHIFT_QWORDS, 2), SCRATCH_XMM, b, 32);
+ self.vector_op(VPMULUDQ, SCRATCH_XMM, SCRATCH_XMM, a);
+ self.vector_op(VPADDQ, temp, temp, SCRATCH_XMM);
+ self.vector_shift_immediate((SHIFT_QWORDS, 6), temp, temp, 32);
+ self.vector_op(VPMULUDQ, dst, a, b);
+ self.vector_op(VPADDQ, dst, dst, temp);
+ }
+ I16X8_Q15MULR_SAT_S => {
+ // The only product that overflows is -1 * -1, which gives 0x8000 and must saturate to 0x7fff.
+ self.vector_op(op66_38(0x0b), dst, a, b);
+ self.vector_op_constant(VPCMPEQW, SCRATCH_XMM, dst, splat16(0x8000));
+ self.vector_op(VPXOR, dst, dst, SCRATCH_XMM);
+ }
+ I16X8_EXTMUL_LOW_I8X16_S
+ | I16X8_EXTMUL_HIGH_I8X16_S
+ | I16X8_EXTMUL_LOW_I8X16_U
+ | I16X8_EXTMUL_HIGH_I8X16_U => {
+ let (extend, high) = extension(sub_opcode);
+ let (a_source, b_source) = if high {
+ self.vector_unary_op(VPSHUFD, SCRATCH_XMM, a, Some(0xee));
+ self.vector_unary_op(VPSHUFD, dst, b, Some(0xee));
+ (SCRATCH_XMM, dst)
+ } else {
+ (a, b)
+ };
+ self.vector_unary_op(extend, SCRATCH_XMM, a_source, None);
+ self.vector_unary_op(extend, dst, b_source, None);
+ self.vector_op(VPMULLW, dst, dst, SCRATCH_XMM);
+ }
+ I32X4_EXTMUL_LOW_I16X8_S
+ | I32X4_EXTMUL_HIGH_I16X8_S
+ | I32X4_EXTMUL_LOW_I16X8_U
+ | I32X4_EXTMUL_HIGH_I16X8_U => {
+ // The low and high halves of the products, interleaved.
+ let signed = matches!(sub_opcode, I32X4_EXTMUL_LOW_I16X8_S | I32X4_EXTMUL_HIGH_I16X8_S);
+ let high = matches!(sub_opcode, I32X4_EXTMUL_HIGH_I16X8_S | I32X4_EXTMUL_HIGH_I16X8_U);
+ self.vector_op(VPMULLW, SCRATCH_XMM, a, b);
+ self.vector_op(if signed { op66(0xe5) } else { op66(0xe4) }, dst, a, b);
+ self.vector_op(if high { VPUNPCKHWD } else { VPUNPCKLWD }, dst, SCRATCH_XMM, dst);
+ }
+ I64X2_EXTMUL_LOW_I32X4_S
+ | I64X2_EXTMUL_HIGH_I32X4_S
+ | I64X2_EXTMUL_LOW_I32X4_U
+ | I64X2_EXTMUL_HIGH_I32X4_U => {
+ // The lanes moved to the low halves of 64-bit lanes, where vpmuldq and vpmuludq multiply.
+ let signed = matches!(sub_opcode, I64X2_EXTMUL_LOW_I32X4_S | I64X2_EXTMUL_HIGH_I32X4_S);
+ let high = matches!(sub_opcode, I64X2_EXTMUL_HIGH_I32X4_S | I64X2_EXTMUL_HIGH_I32X4_U);
+ let lanes = if high { 0xfa } else { 0x50 };
+ self.vector_unary_op(VPSHUFD, SCRATCH_XMM, a, Some(lanes));
+ self.vector_unary_op(VPSHUFD, dst, b, Some(lanes));
+ self.vector_op(if signed { op66_38(0x28) } else { VPMULUDQ }, dst, SCRATCH_XMM, dst);
+ }
+ F32X4_MIN | F64X2_MIN => {
+ // Both orders, so that a NaN or -0 in either operand makes it into the result, and NaN lanes
+ // canonical.
+ let packed = if sub_opcode == F32X4_MIN { &PS } else { &PD };
+ self.vector_op(packed.min, SCRATCH_XMM, a, b);
+ self.vector_op(packed.min, dst, b, a);
+ self.vector_op(packed.or, dst, dst, SCRATCH_XMM);
+ self.asm
+ .vex(packed.cmp, SCRATCH_XMM, dst, VexOperand::Register(dst), Some(CMP_UNORD));
+ self.vector_op(packed.or, dst, dst, SCRATCH_XMM);
+ self.vector_shift_immediate(packed.shift_right, SCRATCH_XMM, SCRATCH_XMM, packed.nan_payload_shift);
+ self.vector_op(packed.andn, dst, SCRATCH_XMM, dst);
+ }
+ F32X4_MAX | F64X2_MAX => {
+ // Both orders, so that a NaN in either operand makes it into the result, +0 beats -0, and NaN
+ // lanes are canonical.
+ let packed = if sub_opcode == F32X4_MAX { &PS } else { &PD };
+ self.vector_op(packed.max, SCRATCH_XMM, a, b);
+ self.vector_op(packed.max, dst, b, a);
+ self.vector_op(packed.xor, SCRATCH_XMM, SCRATCH_XMM, dst);
+ self.vector_op(packed.or, dst, dst, SCRATCH_XMM);
+ self.vector_op(packed.sub, dst, dst, SCRATCH_XMM);
+ self.asm.vex(
+ packed.cmp,
+ SCRATCH_XMM,
+ SCRATCH_XMM,
+ VexOperand::Register(dst),
+ Some(CMP_UNORD),
+ );
+ self.vector_shift_immediate(packed.shift_right, SCRATCH_XMM, SCRATCH_XMM, packed.nan_payload_shift);
+ self.vector_op(packed.andn, dst, SCRATCH_XMM, dst);
+ }
+ _ => unreachable!("SIMD sub-opcode {sub_opcode:#x} is no binary vector operation"),
+ }
+ }
+
+ /// A shift of the vector in `a` by the i32 in `count_register`, or by `count` where it is a constant.
+ fn vector_shift(
+ &mut self,
+ sub_opcode: u32,
+ dst: u8,
+ a: u8,
+ count_register: Register,
+ count: Option<u32>,
+ temp: Register,
+ ) {
+ let bits = match sub_opcode {
+ I8X16_SHL | I8X16_SHR_S | I8X16_SHR_U => 8,
+ I64X2_SHR_S => 64,
+ _ => shift(sub_opcode).expect("a vector shift").2,
};
- self.asm
- .vex(binary.opcode, dst, lhs, VexOperand::Register(rhs), binary.immediate);
- if binary.invert {
- self.scratch_ones();
- self.vector_op(VPXOR, dst, dst, VexOperand::Register(SCRATCH_XMM));
+ let count = count.map(|count| (count & (bits - 1)) as u8);
+ // The masked count in the scratch xmm register, plus `bias`.
+ let count_into_scratch = |this: &mut Self, bias: i32| {
+ this.asm.mov_rr(Width::W32, SCRATCH, gpr(count_register));
+ this.asm.and_ri(Width::W32, SCRATCH, bits as i32 - 1);
+ if bias != 0 {
+ this.asm.add_ri(Width::W32, SCRATCH, bias);
+ }
+ this.asm.vmov_xr(Width::W32, SCRATCH_FPR, SCRATCH);
+ };
+ match sub_opcode {
+ I8X16_SHL | I8X16_SHR_U => {
+ // 16-bit lanes shifted, and the bits that crossed into the next byte cleared.
+ let left = sub_opcode == I8X16_SHL;
+ if let Some(count) = count {
+ let (digit, mask) = if left {
+ (6, 0xffu8 << count)
+ } else {
+ (2, 0xffu8 >> count)
+ };
+ self.vector_shift_immediate((SHIFT_WORDS, digit), dst, a, count);
+ self.vector_op_constant(VPAND, dst, dst, splat8(mask));
+ return;
+ }
+ let temp = fpr(temp).0;
+ count_into_scratch(self, 0);
+ let opcode = if left { VPSLLW } else { VPSRLW };
+ self.vector_op(opcode, dst, a, SCRATCH_XMM);
+ // The mask is the byte of ones shifted the same: the low byte of each shifted 16-bit lane of ones
+ // for a left shift, the high one for a right shift, spread over all bytes.
+ self.vector_ones(temp);
+ self.vector_op(opcode, temp, temp, SCRATCH_XMM);
+ if left {
+ self.vector_zero(SCRATCH_XMM);
+ self.vector_op(VPSHUFB, temp, temp, SCRATCH_XMM);
+ } else {
+ self.vector_op_constant(VPSHUFB, temp, temp, splat8(1));
+ }
+ self.vector_op(VPAND, dst, dst, temp);
+ }
+ I8X16_SHR_S => {
+ // Each byte in the high half of a 16-bit lane, shifted arithmetically by 8 more, and narrowed.
+ let temp = fpr(temp).0;
+ self.vector_op(VPUNPCKHBW, temp, a, a);
+ self.vector_op(VPUNPCKLBW, dst, a, a);
+ if let Some(count) = count {
+ self.vector_shift_immediate((SHIFT_WORDS, 4), temp, temp, count + 8);
+ self.vector_shift_immediate((SHIFT_WORDS, 4), dst, dst, count + 8);
+ } else {
+ count_into_scratch(self, 8);
+ self.vector_op(VPSRAW, temp, temp, SCRATCH_XMM);
+ self.vector_op(VPSRAW, dst, dst, SCRATCH_XMM);
+ }
+ self.vector_op(VPACKSSWB, dst, dst, temp);
+ }
+ I64X2_SHR_S => {
+ // ((a ^ sign) >>> count) ^ sign
+ let temp = fpr(temp).0;
+ self.vector_zero(SCRATCH_XMM);
+ self.vector_op(VPCMPGTQ, temp, SCRATCH_XMM, a);
+ self.vector_op(VPXOR, dst, a, temp);
+ if let Some(count) = count {
+ self.vector_shift_immediate((SHIFT_QWORDS, 2), dst, dst, count);
+ } else {
+ count_into_scratch(self, 0);
+ self.vector_op(VPSRLQ, dst, dst, SCRATCH_XMM);
+ }
+ self.vector_op(VPXOR, dst, dst, temp);
+ }
+ _ => {
+ let (opcode, immediate, _) = shift(sub_opcode).expect("a vector shift");
+ if let Some(count) = count {
+ self.vector_shift_immediate(immediate, dst, a, count);
+ } else {
+ count_into_scratch(self, 0);
+ self.vector_op(opcode, dst, a, SCRATCH_XMM);
+ }
+ }
+ }
+ }
+
+ fn vector_ternary(
+ &mut self,
+ value: Value,
+ sub_opcode: u32,
+ output: Register,
+ inputs: [Register; 3],
+ temp: Register,
+ ) {
+ let dst = fpr(output).0;
+ // The inputs `vector_constant_inputs()` allows to be constants are operands, the others registers.
+ let operand = |this: &mut Self, index: usize| this.vector_input(value, index, inputs[index]);
+ let register = |index: usize| fpr(inputs[index]).0;
+ match sub_opcode {
+ V128_BITSELECT => {
+ // (a & mask) | (b & !mask)
+ let [a, b, c] = [0, 1, 2].map(register);
+ let temp = fpr(temp).0;
+ self.vector_op(VPAND, temp, a, c);
+ self.vector_op(VPANDN, dst, c, b);
+ self.vector_op(VPOR, dst, dst, temp);
+ }
+ // The multiply-adds round twice, as the interpreter's do.
+ F32X4_RELAXED_MADD | F64X2_RELAXED_MADD => {
+ let packed = if sub_opcode == F32X4_RELAXED_MADD { &PS } else { &PD };
+ let (b, c) = (operand(self, 1), operand(self, 2));
+ self.asm.vex(packed.mul, dst, register(0), b, None);
+ self.asm.vex(packed.add, dst, dst, c, None);
+ }
+ F32X4_RELAXED_NMADD | F64X2_RELAXED_NMADD => {
+ let packed = if sub_opcode == F32X4_RELAXED_NMADD { &PS } else { &PD };
+ let b = operand(self, 1);
+ self.asm.vex(packed.mul, dst, register(0), b, None);
+ self.vector_op(packed.sub, dst, register(2), dst);
+ }
+ I32X4_RELAXED_DOT_I8X16_I7X16_ADD_S => {
+ // NB: vpmaddubsw takes b's bytes as unsigned, and its sums of pairs saturate.
+ let (a, c) = (operand(self, 0), operand(self, 2));
+ self.asm.vex(VPMADDUBSW, dst, register(1), a, None);
+ self.vector_op_constant(VPMADDWD, dst, dst, splat16(1));
+ self.asm.vex(VPADDD, dst, dst, c, None);
+ }
+ _ => unreachable!("SIMD sub-opcode {sub_opcode:#x} is no ternary vector operation"),
}
}
@@ -480,3 +1218,21 @@ impl CodeGenerator<'_> {
.vex(VMOVUPS_LOAD, register, 0, VexOperand::Memory(*address), None);
}
}
+
+/// The sign or zero extension of an extend or extending multiply, and whether it is of the high half.
+fn extension(sub_opcode: u32) -> (VexOpcode, bool) {
+ match sub_opcode {
+ I16X8_EXTEND_LOW_I8X16_S | I16X8_EXTMUL_LOW_I8X16_S => (op66_38(0x20), false),
+ I16X8_EXTEND_HIGH_I8X16_S | I16X8_EXTMUL_HIGH_I8X16_S => (op66_38(0x20), true),
+ I16X8_EXTEND_LOW_I8X16_U | I16X8_EXTMUL_LOW_I8X16_U => (op66_38(0x30), false),
+ I16X8_EXTEND_HIGH_I8X16_U | I16X8_EXTMUL_HIGH_I8X16_U => (op66_38(0x30), true),
+ I32X4_EXTEND_LOW_I16X8_S => (op66_38(0x23), false),
+ I32X4_EXTEND_HIGH_I16X8_S => (op66_38(0x23), true),
+ I32X4_EXTEND_LOW_I16X8_U => (op66_38(0x33), false),
+ I32X4_EXTEND_HIGH_I16X8_U => (op66_38(0x33), true),
+ I64X2_EXTEND_LOW_I32X4_S => (op66_38(0x25), false),
+ I64X2_EXTEND_HIGH_I32X4_S => (op66_38(0x25), true),
+ I64X2_EXTEND_LOW_I32X4_U => (op66_38(0x35), false),
+ _ => (op66_38(0x35), true),
+ }
+}
diff --git a/Libraries/LibWasm/JIT/src/decode.rs b/Libraries/LibWasm/JIT/src/decode.rs
index 833a2035302..d9f1d2db2b3 100644
--- a/Libraries/LibWasm/JIT/src/decode.rs
+++ b/Libraries/LibWasm/JIT/src/decode.rs
@@ -113,7 +113,8 @@ pub enum Instruction {
BrOnNonNull(u32),
/// A `0xFC` instruction. The decoder keeps its index immediates (see `Decoder::misc_indices()`).
Misc(u32),
- /// A `0xFB` instruction, its immediates skipped.
+ /// A `0xFB` instruction. The decoder keeps its immediates (see `Decoder::gc_indices()`, `gc_heap_types()` and
+ /// `gc_flags()`).
Gc(u32),
/// A `0xFD` instruction. `checked` for the bounds-checked forms of accesses. The decoder keeps its immediates
/// (see `Decoder::simd_argument()`, `simd_lane()` and `simd_bytes()`).
@@ -121,7 +122,7 @@ pub enum Instruction {
sub_opcode: u32,
checked: bool,
},
- /// A `0xFE` instruction, its immediates skipped.
+ /// A `0xFE` instruction. The decoder keeps its memory immediate (see `Decoder::atomic_argument()`).
Atomic(u32),
/// A v128 form of `local.get`, `local.set`, `local.tee`, `global.get`, `global.set`, `drop` or `select`
/// (quickening rule 2), and its index immediate if it has one.
@@ -144,6 +145,10 @@ pub struct Decoder<'a> {
simd_lane: u8,
simd_bytes: [u8; 16],
misc_indices: [u32; 2],
+ gc_indices: [u32; 2],
+ gc_heap_types: [HeapType; 2],
+ gc_flags: u8,
+ atomic_argument: MemoryArgument,
}
impl<'a> Decoder<'a> {
@@ -158,6 +163,10 @@ impl<'a> Decoder<'a> {
simd_lane: 0,
simd_bytes: [0; 16],
misc_indices: [0; 2],
+ gc_indices: [0; 2],
+ gc_heap_types: [HeapType::Any; 2],
+ gc_flags: 0,
+ atomic_argument: MemoryArgument { memory: 0, offset: 0 },
}
}
@@ -182,6 +191,12 @@ impl<'a> Decoder<'a> {
&self.targets
}
+ /// The catch clauses of the last `try_table`, as its encoding has them: the kind (0 for catch, 1 catch_ref, 2
+ /// catch_all, 3 catch_all_ref), the tag and the label of each.
+ pub fn catch_clauses(&self) -> impl Iterator<Item = [u32; 3]> + '_ {
+ self.targets.as_chunks::<3>().0.iter().copied()
+ }
+
/// The memory immediate of the last SIMD load or store.
pub fn simd_argument(&self) -> MemoryArgument {
self.simd_argument
@@ -198,6 +213,30 @@ impl<'a> Decoder<'a> {
self.misc_indices
}
+ /// The index immediates of the last `0xFB` instruction with any, in order: a type index, then a field index, a
+ /// count, or a data or element segment index; for `array.copy`, the two type indices; for `br_on_cast` and
+ /// `br_on_cast_fail`, the label first.
+ pub fn gc_indices(&self) -> [u32; 2] {
+ self.gc_indices
+ }
+
+ /// The heap types of the last `ref.test`, `ref.cast` (the first only), `br_on_cast` or `br_on_cast_fail` (source,
+ /// then target).
+ pub fn gc_heap_types(&self) -> [HeapType; 2] {
+ self.gc_heap_types
+ }
+
+ /// The flags byte of the last `br_on_cast` or `br_on_cast_fail`: bit 0 for a nullable source, bit 1 for a
+ /// nullable target.
+ pub fn gc_flags(&self) -> u8 {
+ self.gc_flags
+ }
+
+ /// The memory immediate of the last atomic access.
+ pub fn atomic_argument(&self) -> MemoryArgument {
+ self.atomic_argument
+ }
+
/// The 16 bytes of the last `v128.const` or `i8x16.shuffle`.
pub fn simd_bytes(&self) -> [u8; 16] {
self.simd_bytes
@@ -402,12 +441,12 @@ impl<'a> Decoder<'a> {
opcode::TRY_TABLE => {
let block_type = self.block_type();
let count = self.u32();
+ self.targets.clear();
for _ in 0..count {
let kind = self.byte();
- if kind < 2 {
- self.u32();
- }
- self.u32();
+ let tag = if kind < 2 { self.u32() } else { 0 };
+ let label = self.u32();
+ self.targets.extend_from_slice(&[u32::from(kind), tag, label]);
}
Instruction::TryTable(block_type)
}
@@ -459,7 +498,7 @@ impl<'a> Decoder<'a> {
self.byte();
}
Some(_) => {
- self.memory_argument();
+ self.atomic_argument = self.memory_argument();
}
None => unreachable!("validated code has no unknown atomic instructions"),
}
@@ -507,21 +546,19 @@ impl<'a> Decoder<'a> {
match sub_opcode {
STRUCT_NEW | STRUCT_NEW_DEFAULT | ARRAY_NEW | ARRAY_NEW_DEFAULT | ARRAY_GET | ARRAY_GET_S | ARRAY_GET_U
| ARRAY_SET | ARRAY_FILL => {
- self.u32();
+ self.gc_indices = [self.u32(), 0];
}
STRUCT_GET | STRUCT_GET_S | STRUCT_GET_U | STRUCT_SET | ARRAY_NEW_FIXED | ARRAY_NEW_DATA
| ARRAY_NEW_ELEM | ARRAY_COPY | ARRAY_INIT_DATA | ARRAY_INIT_ELEM => {
- self.u32();
- self.u32();
+ self.gc_indices = [self.u32(), self.u32()];
}
REF_TEST | REF_TEST_NULL | REF_CAST | REF_CAST_NULL => {
- self.heap_type();
+ self.gc_heap_types[0] = self.heap_type();
}
BR_ON_CAST | BR_ON_CAST_FAIL => {
- self.byte();
- self.u32();
- self.heap_type();
- self.heap_type();
+ self.gc_flags = self.byte();
+ self.gc_indices[0] = self.u32();
+ self.gc_heap_types = [self.heap_type(), self.heap_type()];
}
_ => {}
}
diff --git a/Libraries/LibWasm/JIT/src/ir/dump.rs b/Libraries/LibWasm/JIT/src/ir/dump.rs
index 1a9d4c9871e..751a0e9c592 100644
--- a/Libraries/LibWasm/JIT/src/ir/dump.rs
+++ b/Libraries/LibWasm/JIT/src/ir/dump.rs
@@ -69,6 +69,34 @@ pub fn node_text(func: &Func, value: Value) -> String {
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(),
Op::Trap => write!(text, " {}", node.args[0]).unwrap(),
+ Op::CheckedAddress => write!(text, " size {} flags {:#x}", 1 << (node.flags & 7), node.flags & !7).unwrap(),
+ Op::AtomicRmw => write!(
+ text,
+ " {} size {}",
+ crate::ir::AtomicOp::from_index(node.args[2]).name(),
+ 1 << node.flags
+ )
+ .unwrap(),
+ Op::AtomicCompareExchange | Op::ElementAddress => write!(text, " size {}", 1 << node.flags).unwrap(),
+ Op::Rtt => write!(text, " type {}", node.args[1]).unwrap(),
+ Op::I31Get if node.flags != 0 => text.push_str(" signed"),
+ Op::RefTest => write!(
+ text,
+ " {}{}{} depth {}",
+ crate::ir::HeapTest::from_flags(node.flags).name(),
+ if node.flags & crate::ir::REF_TEST_NULLABLE != 0 {
+ " null"
+ } else {
+ ""
+ },
+ if node.flags & crate::ir::REF_TEST_CAST != 0 {
+ " cast"
+ } else {
+ ""
+ },
+ node.args[2]
+ )
+ .unwrap(),
Op::BrTable => {
let block = func
.blocks
diff --git a/Libraries/LibWasm/JIT/src/ir/mod.rs b/Libraries/LibWasm/JIT/src/ir/mod.rs
index 128191f10e5..ff32bbb2402 100644
--- a/Libraries/LibWasm/JIT/src/ir/mod.rs
+++ b/Libraries/LibWasm/JIT/src/ir/mod.rs
@@ -337,10 +337,28 @@ pub enum Helper {
TableCopy,
/// table data, segment, destination, source, count.
TableInit,
+ /// address, expected value, timeout in nanoseconds, size: 0 when woken, 1 if the value differed, 2 on timeout.
+ AtomicWait,
+ /// address, count: how many waiters it woke.
+ AtomicNotify,
+ /// rtt, data size in bytes, array length: the new zeroed GC object, or zero (when the runtime has the trap).
+ Allocate,
+ /// array, start, the low and high 64 bits of the value, count.
+ ArrayFill,
+ /// destination array, destination start, source array, source start, count.
+ ArrayCopy,
+ /// array, data segment, destination, source, count.
+ ArrayInitData,
+ /// array, element segment, destination, source, count.
+ ArrayInitElem,
+ /// segment, start, count, bytes per item, TRAP_* code: traps with the code unless the items are in the segment.
+ SegmentRange,
+ /// tag identity: a new exception with that tag and a zeroed payload, for the code to fill in.
+ AllocateException,
}
impl Helper {
- pub const ALL: [Helper; 8] = [
+ pub const ALL: [Helper; 17] = [
Helper::MemoryGrow,
Helper::TableGrow,
Helper::MemoryFill,
@@ -349,6 +367,15 @@ impl Helper {
Helper::TableFill,
Helper::TableCopy,
Helper::TableInit,
+ Helper::AtomicWait,
+ Helper::AtomicNotify,
+ Helper::Allocate,
+ Helper::ArrayFill,
+ Helper::ArrayCopy,
+ Helper::ArrayInitData,
+ Helper::ArrayInitElem,
+ Helper::SegmentRange,
+ Helper::AllocateException,
];
pub fn from_index(index: u32) -> Self {
@@ -357,7 +384,20 @@ impl Helper {
/// Whether the helper returns 0 or the TRAP_* code to trap with, rather than a value.
pub fn may_trap(self) -> bool {
- !matches!(self, Helper::MemoryGrow | Helper::TableGrow)
+ !matches!(
+ self,
+ Helper::MemoryGrow
+ | Helper::TableGrow
+ | Helper::AtomicWait
+ | Helper::AtomicNotify
+ | Helper::Allocate
+ | Helper::AllocateException
+ )
+ }
+
+ /// Whether a value of zero means the runtime trapped, with TRAP_RUNTIME.
+ pub fn traps_on_zero(self) -> bool {
+ self == Helper::Allocate
}
pub fn name(self) -> &'static str {
@@ -370,6 +410,15 @@ impl Helper {
Helper::TableFill => "table_fill",
Helper::TableCopy => "table_copy",
Helper::TableInit => "table_init",
+ Helper::AtomicWait => "atomic_wait",
+ Helper::AtomicNotify => "atomic_notify",
+ Helper::Allocate => "allocate",
+ Helper::ArrayFill => "array_fill",
+ Helper::ArrayCopy => "array_copy",
+ Helper::ArrayInitData => "array_init_data",
+ Helper::ArrayInitElem => "array_init_elem",
+ Helper::SegmentRange => "segment_range",
+ Helper::AllocateException => "allocate_exception",
}
}
}
@@ -385,6 +434,108 @@ pub const FLAG_CANNOT_TRAP: u8 = 0x80;
/// `Node::flags` bit of `GlobalGet` for globals no code can change.
pub const FLAG_IMMUTABLE: u8 = 0x40;
+/// `Node::flags` bits of `CheckedAddress`, besides log2 of the access size in the low bits: an atomic access, which
+/// must be aligned, and an access of a memory64, whose index and offset may add up past 2^64.
+pub const CHECKED_ATOMIC: u8 = 0x08;
+pub const CHECKED_MEMORY64: u8 = 0x10;
+
+/// The read-modify-write operations of `AtomicRmw`, in its args[2].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u32)]
+pub enum AtomicOp {
+ Add,
+ Sub,
+ And,
+ Or,
+ Xor,
+ Exchange,
+}
+
+impl AtomicOp {
+ pub const ALL: [AtomicOp; 6] = [
+ AtomicOp::Add,
+ AtomicOp::Sub,
+ AtomicOp::And,
+ AtomicOp::Or,
+ AtomicOp::Xor,
+ AtomicOp::Exchange,
+ ];
+
+ pub fn from_index(index: u32) -> Self {
+ Self::ALL[index as usize]
+ }
+
+ pub fn name(self) -> &'static str {
+ match self {
+ AtomicOp::Add => "add",
+ AtomicOp::Sub => "sub",
+ AtomicOp::And => "and",
+ AtomicOp::Or => "or",
+ AtomicOp::Xor => "xor",
+ AtomicOp::Exchange => "xchg",
+ }
+ }
+}
+
+/// What `RefTest` checks a reference against, in the low bits of its flags.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum HeapTest {
+ /// Every reference but null: any, func, extern and exn.
+ NonNull,
+ /// An i31 or a GC object: eq.
+ Eq,
+ I31,
+ /// A GC object of a struct type.
+ Struct,
+ /// A GC object of an array type.
+ Array,
+ /// Only null: none, nofunc, noextern and noexn.
+ Nothing,
+ /// A GC object whose type is the identity input or one of its subtypes, which are args[2] deep.
+ ConcreteObject,
+ /// A function whose type is the identity input or one of its subtypes, which are args[2] deep.
+ ConcreteFunction,
+}
+
+impl HeapTest {
+ pub const ALL: [HeapTest; 8] = [
+ HeapTest::NonNull,
+ HeapTest::Eq,
+ HeapTest::I31,
+ HeapTest::Struct,
+ HeapTest::Array,
+ HeapTest::Nothing,
+ HeapTest::ConcreteObject,
+ HeapTest::ConcreteFunction,
+ ];
+
+ pub fn from_flags(flags: u8) -> Self {
+ Self::ALL[(flags & 0xf) as usize]
+ }
+
+ pub fn name(self) -> &'static str {
+ match self {
+ HeapTest::NonNull => "non_null",
+ HeapTest::Eq => "eq",
+ HeapTest::I31 => "i31",
+ HeapTest::Struct => "struct",
+ HeapTest::Array => "array",
+ HeapTest::Nothing => "nothing",
+ HeapTest::ConcreteObject => "object",
+ HeapTest::ConcreteFunction => "function",
+ }
+ }
+}
+
+/// `Node::flags` bits of `RefTest`, besides the `HeapTest`: null matches too; and the test is a cast, which traps
+/// where the reference does not match and has no value.
+pub const REF_TEST_NULLABLE: u8 = 0x10;
+pub const REF_TEST_CAST: u8 = 0x80;
+/// `Node::flags` bit of a `Call` in a region of an exception handler, which checks the context's `exception` once
+/// it returns (see `builder/exceptions.rs`).
+pub const FLAG_CHECKS_EXCEPTION: u8 = 0x01;
+
macro_rules! ops {
($($(#[$meta:meta])* $name:ident: $shape:expr, $effect:ident, $text:literal;)*) => {
/// The operation of a node. See `ARCHITECTURE.md` for what each one does.
@@ -541,6 +692,35 @@ ops! {
/// args: table data, index, value; flags: the TRAP_* code for an index out of bounds.
TableStore: Fixed(3), Write, "table_store";
+ // Memories without guard pages, and atomics.
+ /// args: memory data, index (i32, or i64 for a memory64), offset (i64); flags: log2 of the access size,
+ /// CHECKED_ATOMIC, CHECKED_MEMORY64. The address of the access at index + offset, after checking that it is in
+ /// the memory, and for atomics then that it is aligned.
+ CheckedAddress: Fixed(3), Read, "checked_address";
+ /// args: address, value, the `AtomicOp`; flags: log2 of the size. Applies the op atomically and returns the old
+ /// value, zero-extended.
+ AtomicRmw: Fixed(2), Write, "atomic_rmw";
+ /// args: address, expected value, replacement; flags: log2 of the size. Returns the old value, zero-extended.
+ AtomicCompareExchange: Fixed(3), Write, "atomic_cmpxchg";
+ /// A sequentially consistent fence.
+ AtomicFence: Fixed(0), Write, "atomic_fence";
+
+ // GC objects. A field or element is accessed with `Load`, `VectorLoad` and `Store` at its address, or at the
+ // object with the field's offset where the data is inline.
+ /// args: instance, the module's type index. The `Rtt` of the type, which never changes.
+ Rtt: Fixed(1), Pure, "rtt";
+ /// args: i32. The i31 reference of its low 31 bits.
+ I31New: Fixed(1), Pure, "ref_i31";
+ /// args: i31 reference (not null); flags: 1 to sign-extend. The i32 value.
+ I31Get: Fixed(1), Pure, "i31_get";
+ /// args: array, index; flags: log2 of the element size. The address of the element, after checking the array for
+ /// null and the index against its length.
+ ElementAddress: Fixed(2), Read, "element_address";
+ /// args: reference, the type identity it is tested against (a constant for abstract heap types), the depth of
+ /// that type; flags: `HeapTest`, REF_TEST_NULLABLE, REF_TEST_CAST. Whether the reference matches, as an i32; a
+ /// cast has no value and traps instead where it does not.
+ RefTest: Fixed(2), Pure, "ref_test";
+
// Calls.
/// args: callee FunctionHeader, the calling instance. The callee's instance: its function header's, or for a host
/// function, which has none, the caller's, through which its stub finds the runtime.
@@ -576,6 +756,9 @@ ops! {
Trap: Fixed(0), Terminator, "trap";
/// operands and args like `Call`. A call whose results are the function's.
TailCall: Variadic, Terminator, "tail_call";
+ /// args: an exception reference, not null. Throws it to the function's callers: the runtime unwinds it to the
+ /// first call that handles exceptions, or out of compiled code.
+ Throw: Fixed(1), Terminator, "throw";
}
impl Op {
@@ -629,6 +812,7 @@ impl Node {
{
Effect::Pure
}
+ Op::RefTest if self.flags & REF_TEST_CAST != 0 => Effect::Write,
op => op.base_effect(),
}
}
diff --git a/Libraries/LibWasm/JIT/src/ir/verify.rs b/Libraries/LibWasm/JIT/src/ir/verify.rs
index 8a2df32dd1d..08af7af88a5 100644
--- a/Libraries/LibWasm/JIT/src/ir/verify.rs
+++ b/Libraries/LibWasm/JIT/src/ir/verify.rs
@@ -124,7 +124,7 @@ pub fn verify(func: &Func, is_dead: &dyn Fn(Value) -> bool, after_cleanup: bool)
let expected_successors = match func.node(terminator).op {
Op::Jump => Some(1),
Op::Branch | Op::BranchCompare | Op::BranchFloatCompare => Some(2),
- Op::Return | Op::Trap | Op::TailCall => Some(0),
+ Op::Return | Op::Trap | Op::TailCall | Op::Throw => Some(0),
_ => None,
};
if let Some(expected) = expected_successors
@@ -228,7 +228,7 @@ fn check_types(func: &Func, value: Value, error: &mut impl FnMut(String)) {
| Op::Extend32S => matches!(node.ty, Type::I32 | Type::I64) && same(node.ty),
Op::Eqz => node.ty == Type::I32 && matches!(input_type(0), Type::I32 | Type::I64 | Type::Ref),
Op::Compare | Op::BranchCompare => {
- matches!(input_type(0), Type::I32 | Type::I64 | Type::Ref) && input_type(0) == input_type(1)
+ matches!(input_type(0), Type::I32 | Type::I64 | Type::Ref | Type::Pointer) && input_type(0) == input_type(1)
}
Op::FAdd
| Op::FSub
@@ -249,18 +249,31 @@ fn check_types(func: &Func, value: Value, error: &mut impl FnMut(String)) {
Op::Wrap => node.ty == Type::I32 && input_type(0) == Type::I64,
Op::Select => input_type(0) == Type::I32 && input_type(1) == node.ty && input_type(2) == node.ty,
Op::Phi => same(node.ty),
- Op::Load => input_type(0) == Type::Pointer && input_type(1) == Type::I32,
- Op::Store => input_type(0) == Type::Pointer && input_type(1) == Type::I32,
+ // NB: GC objects' fields are accessed at the object's reference.
+ Op::Load | Op::Store => matches!(input_type(0), Type::Pointer | Type::Ref) && input_type(1) == Type::I32,
Op::Branch => input_type(0) == Type::I32,
Op::BrTable => input_type(0) == Type::I32,
- Op::InstanceField
- | Op::LoadPointer
- | Op::GlobalGet
- | Op::GlobalSet
- | Op::Offset
- | Op::FrameLoad
- | Op::ReadField
- | Op::WriteField => input_type(0) == Type::Pointer,
+ Op::InstanceField | Op::LoadPointer | Op::GlobalGet | Op::GlobalSet | Op::Offset | Op::FrameLoad => {
+ input_type(0) == Type::Pointer
+ }
+ // NB: References to runtime objects, like exceptions and GC objects, point at them.
+ Op::ReadField | Op::WriteField => matches!(input_type(0), Type::Pointer | Type::Ref),
+ Op::CheckedAddress => {
+ input_type(0) == Type::Pointer
+ && matches!(input_type(1), Type::I32 | Type::I64)
+ && input_type(2) == Type::I64
+ && node.ty == Type::Pointer
+ }
+ Op::AtomicRmw | Op::AtomicCompareExchange => {
+ input_type(0) == Type::Pointer
+ && matches!(node.ty, Type::I32 | Type::I64)
+ && inputs[1..].iter().all(|input| func.node(*input).ty == node.ty)
+ }
+ Op::Rtt => input_type(0) == Type::Pointer && node.ty == Type::Pointer,
+ Op::I31New => input_type(0) == Type::I32 && node.ty == Type::Ref,
+ Op::I31Get => input_type(0) == Type::Ref && node.ty == Type::I32,
+ Op::ElementAddress => input_type(0) == Type::Ref && input_type(1) == Type::I32 && node.ty == Type::Pointer,
+ Op::RefTest => input_type(0) == Type::Ref && input_type(1) == Type::I32,
Op::TableElement => input_type(0) == Type::Pointer && node.ty == Type::Ref,
Op::TableStore => input_type(0) == Type::Pointer && input_type(2) == Type::Ref,
Op::CheckFunction => input_type(0) == Type::Ref && input_type(1) == Type::I32,
diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rs
index f5d605e5afc..709e1df9735 100644
--- a/Libraries/LibWasm/JIT/src/lib.rs
+++ b/Libraries/LibWasm/JIT/src/lib.rs
@@ -69,6 +69,15 @@ pub struct RuntimeInfo {
pub memory_grow: u64,
pub table_grow: u64,
pub call_host: u64,
+ /// `wasm_runtime_allocate`, `wasm_runtime_wait` and `wasm_runtime_notify`.
+ pub allocate: u64,
+ pub wait: u64,
+ pub notify: u64,
+ /// `wasm_runtime_allocate_exception` (`Helper::AllocateException`), and `wasm_runtime_throw_from_native`, which
+ /// takes an exception and the fp of the frame that throws it, unwinds the exception, and returns the context,
+ /// whose `resume` says where to continue.
+ pub allocate_exception: u64,
+ pub throw: u64,
}
/// What to compile.
@@ -134,6 +143,9 @@ pub struct CompiledFunction {
pub code: Vec<u8>,
/// The bytes between fp and rsp in the function's frame.
pub frame_size: u32,
+ /// The offsets of the return addresses of the calls that handle exceptions: an exception the runtime unwinds to
+ /// one of them continues there, with the context's `exception` set, as if the call had returned.
+ pub exception_sites: Vec<u32>,
pub stats: Stats,
pub dump: Option<String>,
}
@@ -243,6 +255,7 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result
let mut compiled = CompiledFunction {
code: generated.code,
frame_size: generated.frame_size,
+ exception_sites: generated.exception_sites,
stats,
dump: None,
};
diff --git a/Libraries/LibWasm/JIT/src/passes/gvn.rs b/Libraries/LibWasm/JIT/src/passes/gvn.rs
index b6a524ad9c7..31a6bdc9219 100644
--- a/Libraries/LibWasm/JIT/src/passes/gvn.rs
+++ b/Libraries/LibWasm/JIT/src/passes/gvn.rs
@@ -79,7 +79,7 @@ impl Gvn {
pub fn visit(&mut self, func: &Func, value: Value) -> Option<Value> {
let node = func.node(value);
let epochs = match node.op {
- Op::Store => {
+ Op::Store | Op::AtomicRmw | Op::AtomicCompareExchange | Op::AtomicFence => {
self.memory_epoch += 1;
return None;
}
diff --git a/Libraries/LibWasm/JIT/src/regalloc/mod.rs b/Libraries/LibWasm/JIT/src/regalloc/mod.rs
index fa3d31c2ae6..59019b21d9a 100644
--- a/Libraries/LibWasm/JIT/src/regalloc/mod.rs
+++ b/Libraries/LibWasm/JIT/src/regalloc/mod.rs
@@ -22,6 +22,7 @@
pub mod liveness;
pub mod verify;
+use crate::codegen;
use crate::convention::{self, Place, Register};
use crate::ir::{BlockId, Func, NONE, Op, Type, Value};
use crate::passes::cleanup::Liveliness;
@@ -124,6 +125,8 @@ enum Input {
Fixed(Register),
/// A register, or the constant itself if it fits the instruction as an immediate.
RegisterOrConstant,
+ /// A register, or a v128 constant itself, which the instruction reads from the constant pool.
+ RegisterOrVectorConstant,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -228,7 +231,7 @@ fn constraints(func: &Func, value: Value) -> Constraints {
Op::ConvertU if input_type(0) == Type::I64 => {
constraints.temps[0] = Temp::Gpr;
}
- Op::Load => {
+ Op::Load | Op::VectorLoad => {
if fits_displacement(func, node.args[1], node.args[2]) {
constraints.inputs[1] = Input::RegisterOrConstant;
}
@@ -243,18 +246,61 @@ fn constraints(func: &Func, value: Value) -> Constraints {
Op::GlobalSet => constraints.inputs[1] = Input::RegisterOrConstant,
Op::WriteField => constraints.inputs[1] = Input::RegisterOrConstant,
Op::CheckFunction => constraints.temps = [Temp::Gpr, Temp::Gpr],
- Op::BrTable => constraints.temps[0] = Temp::Gpr,
- Op::Shuffle | Op::VectorTernary => constraints.temps[0] = Temp::Fpr,
- Op::VectorUnary
+ Op::CheckedAddress => {
+ let size = 1u64 << (node.flags & 7);
+ let offset = func.node(node.args[2]).constant();
+ // NB: A memory64's offset can be close enough to 2^64 that adding the size wraps around.
+ if offset
+ .and_then(|offset| offset.checked_add(size))
+ .is_some_and(|end| end <= i32::MAX as u64)
+ {
+ constraints.inputs[2] = Input::RegisterOrConstant;
+ }
+ }
+ Op::AtomicRmw => {
+ constraints.temps[0] = Temp::Fixed(RAX);
if matches!(
- node.args[1],
- libwasm_module::opcode::simd::I8X16_ALL_TRUE
- | libwasm_module::opcode::simd::I16X8_ALL_TRUE
- | libwasm_module::opcode::simd::I32X4_ALL_TRUE
- | libwasm_module::opcode::simd::I64X2_ALL_TRUE
- ) =>
- {
- constraints.temps[0] = Temp::Fpr;
+ crate::ir::AtomicOp::from_index(node.args[2]),
+ crate::ir::AtomicOp::And | crate::ir::AtomicOp::Or | crate::ir::AtomicOp::Xor
+ ) {
+ constraints.temps[1] = Temp::Gpr;
+ }
+ constraints.clobbers = 1 << RAX;
+ constraints.output = Output::Fixed(RAX);
+ }
+ Op::AtomicCompareExchange => {
+ constraints.inputs[1] = Input::Fixed(RAX);
+ constraints.clobbers = 1 << RAX;
+ constraints.output = Output::Fixed(RAX);
+ }
+ Op::RefTest => {
+ constraints.inputs[1] = Input::RegisterOrConstant;
+ constraints.temps = match crate::ir::HeapTest::from_flags(node.flags) {
+ crate::ir::HeapTest::Struct | crate::ir::HeapTest::Array | crate::ir::HeapTest::ConcreteObject => {
+ [Temp::Gpr, Temp::None]
+ }
+ crate::ir::HeapTest::ConcreteFunction => [Temp::Gpr, Temp::Gpr],
+ _ => [Temp::None, Temp::None],
+ };
+ }
+ Op::BrTable => constraints.temps[0] = Temp::Gpr,
+ Op::Shuffle | Op::VectorUnary | Op::VectorBinary | Op::VectorTernary => {
+ for temp in constraints
+ .temps
+ .iter_mut()
+ .take(codegen::x86_64::vector_temps(func, value))
+ {
+ *temp = Temp::Fpr;
+ }
+ if node.op == Op::VectorBinary && codegen::x86_64::is_vector_shift(node.args[2]) {
+ constraints.inputs[1] = Input::RegisterOrConstant;
+ }
+ let constants = codegen::x86_64::vector_constant_inputs(func, value);
+ for (index, input) in constraints.inputs.iter_mut().enumerate() {
+ if constants & (1 << index) != 0 {
+ *input = Input::RegisterOrVectorConstant;
+ }
+ }
}
_ => {}
}
@@ -916,6 +962,9 @@ impl Allocator {
Input::RegisterOrConstant if func.node(input).op.is_constant() && fits_immediate(func, input) => {
registers[index] = CONSTANT_INPUT;
}
+ Input::RegisterOrVectorConstant if func.node(input).op == Op::Const128 => {
+ registers[index] = CONSTANT_INPUT;
+ }
_ => {
let register = self.register_input(func, allocation, input, blocked);
blocked |= 1 << register;
diff --git a/Libraries/LibWasm/JIT/src/runtime.rs b/Libraries/LibWasm/JIT/src/runtime.rs
index 74f12242788..7666c4f32da 100644
--- a/Libraries/LibWasm/JIT/src/runtime.rs
+++ b/Libraries/LibWasm/JIT/src/runtime.rs
@@ -4,14 +4,17 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The functions of the runtime compiled code calls for bulk memory and table operations (`Op::Helper`). They take
-//! their operands in the context's `arguments` like the runtime's own helpers, need nothing but the data the
-//! operands point at, and return 0, or the TRAP_* code to trap with. Growing calls the runtime's own helpers.
+//! The functions of the runtime compiled code calls for bulk memory, table and array operations (`Op::Helper`). They
+//! take their operands in the context's `arguments` like the runtime's own helpers, need nothing but the data the
+//! operands point at, and return 0, or the TRAP_* code to trap with. Growing, allocating, and waiting on and
+//! notifying shared memory locations call the runtime's own helpers.
use crate::RuntimeInfo;
use crate::ir::Helper;
use libwasm_module::abi::{
- ExecutionContext, MemoryData, Segment, TRAP_MEMORY_OUT_OF_BOUNDS, TRAP_TABLE_OUT_OF_BOUNDS, TableData,
+ ExecutionContext, MemoryData, OBJECT_DATA_OFFSET, OBJECT_LENGTH_OFFSET, Rtt, STORAGE_32, STORAGE_64, STORAGE_I8,
+ STORAGE_I16, STORAGE_V128, Segment, TRAP_ARRAY_OUT_OF_BOUNDS, TRAP_MEMORY_OUT_OF_BOUNDS, TRAP_NULL_REFERENCE,
+ TRAP_TABLE_OUT_OF_BOUNDS, TableData,
};
/// The address of the function `helper` calls.
@@ -19,12 +22,21 @@ pub fn helper_address(helper: Helper, runtime: &RuntimeInfo) -> u64 {
let function: unsafe extern "C" fn(*mut ExecutionContext) -> u64 = match helper {
Helper::MemoryGrow => return runtime.memory_grow,
Helper::TableGrow => return runtime.table_grow,
+ Helper::AllocateException => return runtime.allocate_exception,
Helper::MemoryFill => memory_fill,
Helper::MemoryCopy => memory_copy,
Helper::MemoryInit => memory_init,
Helper::TableFill => table_fill,
Helper::TableCopy => table_copy,
Helper::TableInit => table_init,
+ Helper::AtomicWait => return runtime.wait,
+ Helper::AtomicNotify => return runtime.notify,
+ Helper::Allocate => return runtime.allocate,
+ Helper::ArrayFill => array_fill,
+ Helper::ArrayCopy => array_copy,
+ Helper::ArrayInitData => array_init_data,
+ Helper::ArrayInitElem => array_init_elem,
+ Helper::SegmentRange => segment_range,
};
function as usize as u64
}
@@ -147,3 +159,160 @@ unsafe extern "C" fn table_init(context: *mut ExecutionContext) -> u64 {
0
}
}
+
+// GC arrays. An array is a cell with its data's address at OBJECT_DATA_OFFSET, its length at OBJECT_LENGTH_OFFSET, and
+// its Rtt first; elements take 8 bytes, or 16 for v128 (see abi.rs).
+
+/// An array's data, length, and element storage kind.
+unsafe fn array_parts(array: u64) -> (*mut u8, u64, u8) {
+ unsafe {
+ let cell = array as *const u8;
+ let data = cell.add(OBJECT_DATA_OFFSET).cast::<*mut u8>().read();
+ let length = cell.add(OBJECT_LENGTH_OFFSET).cast::<u64>().read();
+ let rtt = cell.cast::<*const Rtt>().read();
+ (data, length, *(*rtt).field_kinds)
+ }
+}
+
+fn element_size(kind: u8) -> usize {
+ if kind == STORAGE_V128 { 16 } else { 8 }
+}
+
+/// The bytes an element of storage `kind` takes in a data segment.
+fn data_size(kind: u8) -> usize {
+ match kind {
+ STORAGE_I8 => 1,
+ STORAGE_I16 => 2,
+ STORAGE_32 => 4,
+ STORAGE_V128 => 16,
+ _ => 8,
+ }
+}
+
+unsafe extern "C" fn array_fill(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let &[array, start, low, high, count, _] = arguments(context);
+ if array == 0 {
+ return u64::from(TRAP_NULL_REFERENCE);
+ }
+ let (data, length, kind) = array_parts(array);
+ if !in_range(start, count, length) {
+ return u64::from(TRAP_ARRAY_OUT_OF_BOUNDS);
+ }
+ let low = match kind {
+ STORAGE_I8 => low & 0xff,
+ STORAGE_I16 => low & 0xffff,
+ _ => low,
+ };
+ let size = element_size(kind);
+ for index in start..start + count {
+ let element = data.add(index as usize * size).cast::<u64>();
+ element.write(low);
+ if kind == STORAGE_V128 {
+ element.add(1).write(high);
+ }
+ }
+ 0
+ }
+}
+
+unsafe extern "C" fn array_copy(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let &[destination, destination_start, source, source_start, count, _] = arguments(context);
+ if source == 0 || destination == 0 {
+ return u64::from(TRAP_NULL_REFERENCE);
+ }
+ let (source_data, source_length, _) = array_parts(source);
+ let (destination_data, destination_length, kind) = array_parts(destination);
+ if !in_range(source_start, count, source_length) || !in_range(destination_start, count, destination_length) {
+ return u64::from(TRAP_ARRAY_OUT_OF_BOUNDS);
+ }
+ if count == 0 {
+ return 0;
+ }
+ let size = element_size(kind);
+ std::ptr::copy(
+ source_data.add(source_start as usize * size),
+ destination_data.add(destination_start as usize * size),
+ count as usize * size,
+ );
+ 0
+ }
+}
+
+unsafe extern "C" fn array_init_data(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let &[array, segment, destination, source, count, _] = arguments(context);
+ if array == 0 {
+ return u64::from(TRAP_NULL_REFERENCE);
+ }
+ let (data, length, kind) = array_parts(array);
+ if !in_range(destination, count, length) {
+ return u64::from(TRAP_ARRAY_OUT_OF_BOUNDS);
+ }
+ let segment = &*(segment as *const Segment);
+ let bytes = data_size(kind);
+ // NB: The count is below 2^32 and the size at most 16, so their product does not wrap.
+ if !in_range(source, count * bytes as u64, segment.length) {
+ return u64::from(TRAP_MEMORY_OUT_OF_BOUNDS);
+ }
+ let size = element_size(kind);
+ for index in 0..count as usize {
+ let from = segment.contents.add(source as usize + index * bytes);
+ let to = data.add((destination as usize + index) * size).cast::<u64>();
+ match kind {
+ STORAGE_I8 => to.write(u64::from(from.read())),
+ STORAGE_I16 => to.write(u64::from(from.cast::<u16>().read_unaligned())),
+ STORAGE_32 => to.write(u64::from(from.cast::<u32>().read_unaligned())),
+ STORAGE_V128 => {
+ to.write(from.cast::<u64>().read_unaligned());
+ to.add(1).write(from.cast::<u64>().add(1).read_unaligned());
+ }
+ _ => {
+ debug_assert_eq!(kind, STORAGE_64);
+ to.write(from.cast::<u64>().read_unaligned());
+ }
+ }
+ }
+ 0
+ }
+}
+
+unsafe extern "C" fn array_init_elem(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let &[array, segment, destination, source, count, _] = arguments(context);
+ if array == 0 {
+ return u64::from(TRAP_NULL_REFERENCE);
+ }
+ let (data, length, _) = array_parts(array);
+ if !in_range(destination, count, length) {
+ return u64::from(TRAP_ARRAY_OUT_OF_BOUNDS);
+ }
+ let segment = &*(segment as *const Segment);
+ if !in_range(source, count, segment.length) {
+ return u64::from(TRAP_TABLE_OUT_OF_BOUNDS);
+ }
+ if count == 0 {
+ return 0;
+ }
+ std::ptr::copy(
+ segment.contents.cast::<u64>().add(source as usize),
+ data.cast::<u64>().add(destination as usize),
+ count as usize,
+ );
+ 0
+ }
+}
+
+unsafe extern "C" fn segment_range(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let &[segment, start, count, unit, trap, _] = arguments(context);
+ let segment = &*(segment as *const Segment);
+ // NB: The count is below 2^32 and the unit at most 16, so their product does not wrap.
+ if in_range(start, count * unit, segment.length) {
+ 0
+ } else {
+ trap
+ }
+ }
+}
diff --git a/Libraries/LibWasm/JIT/src/stubs.rs b/Libraries/LibWasm/JIT/src/stubs.rs
index 36a9ee8c282..97637823276 100644
--- a/Libraries/LibWasm/JIT/src/stubs.rs
+++ b/Libraries/LibWasm/JIT/src/stubs.rs
@@ -247,6 +247,15 @@ pub fn trap_exit(handler: u64) -> Vec<u8> {
asm.finish().expect("stubs have no unbound labels")
}
+/// Continues where the `resume` of the context in `context` says, as the runtime set it after unwinding an
+/// exception: loads rsp and rbp and jumps.
+pub fn resume(asm: &mut Assembler, context: Gpr) {
+ let resume = field(offset_of!(ExecutionContext, resume));
+ asm.mov_rm(Width::W64, SP, &Address::new(context, resume));
+ asm.mov_rm(Width::W64, FP, &Address::new(context, resume + 8));
+ asm.jmp_m(&Address::new(context, resume + 16));
+}
+
/// 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();
@@ -263,8 +272,9 @@ fn copy_words(asm: &mut Assembler, from: Gpr, to: Gpr, count: Gpr, temp: Gpr) {
asm.bind(done);
}
-/// The entry trampoline, `extern "C" fn(*mut NativeCall)`.
-pub fn entry_trampoline() -> Vec<u8> {
+/// The entry trampoline, `extern "C" fn(*mut NativeCall)`, and the offset of the address its call of compiled code
+/// returns to, where an exception the compiled code does not handle continues (see `RuntimeInfo::throw`).
+pub fn entry_trampoline() -> (Vec<u8>, usize) {
let mut asm = Assembler::new();
let record = gpr(convention::R11);
let (rax, rcx, rdx, rsi, rdi) = (
@@ -326,6 +336,7 @@ pub fn entry_trampoline() -> Vec<u8> {
asm.mov_rm(Width::W64, gpr(register), &Address::new(record, field(offset)));
}
asm.call_m(&call_field(offset_of!(NativeCall, entry)));
+ let return_offset = asm.offset();
// 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)));
@@ -351,12 +362,16 @@ pub fn entry_trampoline() -> Vec<u8> {
}
asm.pop(FP);
asm.ret();
- asm.finish().expect("stubs have no unbound labels")
+ (asm.finish().expect("stubs have no unbound labels"), return_offset)
}
+/// What the runtime function of the adapter returns when the call threw an exception, which the runtime unwound: the
+/// adapter continues where the context's `resume` says.
+pub const ADAPTER_RESUME: u64 = u64::MAX;
+
/// 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.
+/// trap code, or `ADAPTER_RESUME`.
pub fn runtime_adapter(function: u64, runtime: &RuntimeInfo) -> Vec<u8> {
let mut asm = Assembler::new();
let instance = gpr(convention::INSTANCE_REGISTER);
@@ -403,8 +418,20 @@ pub fn runtime_adapter(function: u64, runtime: &RuntimeInfo) -> Vec<u8> {
asm.pop(FP);
asm.ret();
asm.bind(trap);
+ let unwound = asm.new_label();
+ asm.cmp_ri(Width::W64, gpr(convention::RAX), -1);
+ asm.jcc(Cond::Equal, unwound);
asm.mov_rr(Width::W32, gpr(convention::RDI), gpr(convention::RAX));
asm.mov_ri(SCRATCH, runtime.trap_exit);
asm.jmp_r(SCRATCH);
+ asm.bind(unwound);
+ 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))),
+ );
+ resume(&mut asm, context);
asm.finish().expect("stubs have no unbound labels")
}
diff --git a/Libraries/LibWasm/JIT/tests/harness/mod.rs b/Libraries/LibWasm/JIT/tests/harness/mod.rs
index 2714dd4869f..b06381cd9c5 100644
--- a/Libraries/LibWasm/JIT/tests/harness/mod.rs
+++ b/Libraries/LibWasm/JIT/tests/harness/mod.rs
@@ -133,13 +133,50 @@ fn trap_exit_code(state: *mut SessionState) -> Vec<u8> {
/// The code of functions the JIT did not compile.
fn not_compiled_code(trap_exit: u64) -> Vec<u8> {
+ trap_stub(trap_exit, TRAP_NOT_COMPILED)
+}
+
+/// Code that traps with `code`.
+fn trap_stub(trap_exit: u64, code: u32) -> Vec<u8> {
let mut asm = Assembler::new();
- asm.mov_ri32(Gpr(convention::RDI), TRAP_NOT_COMPILED);
+ asm.mov_ri32(Gpr(convention::RDI), code);
asm.mov_ri(Gpr(convention::R11), trap_exit);
asm.jmp_r(Gpr(convention::R11));
asm.finish().unwrap()
}
+/// `RuntimeInfo::throw` of the harness: unwinds the exception in `arguments[0]` from the compiled frame whose fp is
+/// `arguments[1]` to the first exception site its callers return to. An exception that leaves compiled code traps with
+/// TRAP_UNCAUGHT_EXCEPTION, as host functions that throw do here.
+unsafe extern "C" fn throw(context: *mut ExecutionContext) -> u64 {
+ unsafe {
+ let [exception, frame, ..] = (*context).arguments;
+ let read = |address: u64| *(address as *const u64);
+ with_session(|session| {
+ let mut callee = frame;
+ loop {
+ let return_address = read(callee - 8);
+ let caller = read(callee - 16);
+ if session.exception_sites.contains(&return_address) {
+ (*context).exception = exception;
+ (*context).resume = [callee, caller, return_address];
+ break;
+ }
+ if !session
+ .functions
+ .iter()
+ .any(|(start, end)| (*start..*end).contains(&return_address))
+ {
+ (*context).resume = [callee, callee, session.uncaught];
+ break;
+ }
+ callee = caller;
+ }
+ });
+ context as u64
+ }
+}
+
fn restore_and_return(asm: &mut Assembler, status: u32) {
asm.add_ri(Width::W64, Gpr(convention::RSP), 8);
for register in [
@@ -297,6 +334,11 @@ struct Session {
state: Box<SessionState>,
runtime: RuntimeInfo,
not_compiled: u64,
+ /// The stub that traps with TRAP_UNCAUGHT_EXCEPTION, where an exception that leaves compiled code continues.
+ uncaught: u64,
+ /// The code of compiled functions, and their calls that handle exceptions.
+ functions: Vec<(u64, u64)>,
+ exception_sites: std::collections::HashSet<u64>,
trampolines: HashMap<Signature, u64>,
host_stubs: HashMap<Signature, u64>,
}
@@ -309,6 +351,7 @@ impl Session {
// Every code space starts with its trap exit, which the fault handler sends faults to.
let trap_exit = space.add(&[&trap_exit_code(&raw mut *state)])[0];
let not_compiled = space.add(&[&not_compiled_code(trap_exit)])[0];
+ let uncaught = space.add(&[&trap_stub(trap_exit, libwasm_engine::abi::TRAP_UNCAUGHT_EXCEPTION)])[0];
CODE_RANGES
.lock()
.unwrap()
@@ -321,8 +364,16 @@ impl Session {
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,
+ allocate: helpers::wasm_runtime_allocate as *const () as u64,
+ wait: helpers::wasm_runtime_wait as *const () as u64,
+ notify: helpers::wasm_runtime_notify as *const () as u64,
+ allocate_exception: libwasm_engine::runtime::jit::wasm_runtime_allocate_exception as *const () as u64,
+ throw: throw as *const () as u64,
},
not_compiled,
+ uncaught,
+ functions: Vec::new(),
+ exception_sites: std::collections::HashSet::new(),
trampolines: HashMap::new(),
host_stubs: HashMap::new(),
}
@@ -400,13 +451,22 @@ impl CompiledModule {
options,
};
match libwasm_jit::compile(&mut context, &request) {
- Ok(compiled) => codes.push((index, compiled.code)),
+ Ok(compiled) => codes.push((index, compiled.code, compiled.exception_sites)),
Err(failure) => *slot = Some(failure),
}
}
- let slices = codes.iter().map(|(_, code)| code.as_slice()).collect::<Vec<_>>();
- let addresses = with_session(|session| session.space.add(&slices));
- for ((index, _), address) in codes.iter().zip(addresses) {
+ let slices = codes.iter().map(|(_, code, _)| code.as_slice()).collect::<Vec<_>>();
+ let addresses = with_session(|session| {
+ let addresses = session.space.add(&slices);
+ for ((_, code, sites), address) in codes.iter().zip(&addresses) {
+ session.functions.push((*address, *address + code.len() as u64));
+ session
+ .exception_sites
+ .extend(sites.iter().map(|offset| *address + u64::from(*offset)));
+ }
+ addresses
+ });
+ for ((index, _, _), address) in codes.iter().zip(addresses) {
entries[*index] = address;
}
// A function runs compiled if it and every function it calls directly compiled.
diff --git a/Libraries/LibWasm/JIT/tests/harness/script.rs b/Libraries/LibWasm/JIT/tests/harness/script.rs
index c8ff15fce78..f4bb9a7a8d4 100644
--- a/Libraries/LibWasm/JIT/tests/harness/script.rs
+++ b/Libraries/LibWasm/JIT/tests/harness/script.rs
@@ -77,7 +77,8 @@ pub fn same_value(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::F32(x), Value::F32(y)) => x == y || (f32::from_bits(*x).is_nan() && f32::from_bits(*y).is_nan()),
(Value::F64(x), Value::F64(y)) => x == y || (f64::from_bits(*x).is_nan() && f64::from_bits(*y).is_nan()),
- // NB: References are addresses, which differ between the stores.
+ // NB: References are addresses, which differ between the stores, but i31 references are their values.
+ (Value::Ref(x), Value::Ref(y)) if x & 1 != 0 || y & 1 != 0 => x == y,
(Value::Ref(x), Value::Ref(y)) => (*x == 0) == (*y == 0),
_ => a == b,
}
@@ -156,7 +157,12 @@ fn vector_argument(json: &Json) -> Option<Value> {
};
let mut vector = 0u128;
for (index, lane) in lanes.iter().enumerate() {
- let lane = lane.as_str()?.parse::<u64>().ok()?;
+ // NB: Some scripts write lanes as signed numbers.
+ let lane = lane.as_str()?;
+ let lane = lane
+ .parse::<u64>()
+ .ok()
+ .or_else(|| lane.parse::<i64>().ok().map(|lane| lane as u64))?;
let mask = if bits == 64 { u64::MAX } else { (1 << bits) - 1 };
vector |= u128::from(lane & mask) << (index * bits);
}
diff --git a/Libraries/LibWasm/Tests/Executor/test-gc-frames.js b/Libraries/LibWasm/Tests/Executor/test-gc-frames.js
new file mode 100644
index 00000000000..82b006964cf
--- /dev/null
+++ b/Libraries/LibWasm/Tests/Executor/test-gc-frames.js
@@ -0,0 +1,31 @@
+// References that frames hold while the collector runs, whichever tier runs them (see gc-frames.wat). Each round
+// allocates enough garbage that collections happen in the middle of the functions.
+
+const module = parseWebAssemblyModule(readBinaryWasmFile("Fixtures/Modules/gc-frames.wasm"));
+const call = (name, ...args) => module.invoke(module.getExport(name), ...args);
+const before = peakResidentMemorySize();
+
+test("a list held by a local survives collections", () => {
+ for (let round = 0; round < 3; ++round) expect(call("list", 200)).toBe(19900n);
+});
+
+test("references on the operand stack survive collections", () => {
+ for (let round = 0; round < 3; ++round) expect(call("operands", 100)).toBe(4950n + 100000n);
+});
+
+test("an array of references outside the heap survives collections", () => {
+ for (let round = 0; round < 3; ++round) expect(call("array", 1000)).toBe(499500n);
+});
+
+test("a large array of numbers survives collections", () => {
+ for (let round = 0; round < 3; ++round) expect(call("wide", 1000)).toBe(499500n + 599n);
+});
+
+test("vector, float, i31 and cast references survive collections", () => {
+ for (let round = 0; round < 3; ++round) expect(call("mixed", 300)).toBe(3n * 44850n + 1800n);
+});
+
+test("the garbage was collected", () => {
+ // The rounds above allocate and write more than 2 GiB.
+ expect(peakResidentMemorySize() - before).toBeLessThan(512 * 1024 * 1024);
+});
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/gc-frames.wasm b/Libraries/LibWasm/Tests/Fixtures/Modules/gc-frames.wasm
new file mode 100644
index 00000000000..21b0a905167
Binary files /dev/null and b/Libraries/LibWasm/Tests/Fixtures/Modules/gc-frames.wasm differ
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/gc-frames.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/gc-frames.wat
new file mode 100644
index 00000000000..6069a92742d
--- /dev/null
+++ b/Libraries/LibWasm/Tests/Fixtures/Modules/gc-frames.wat
@@ -0,0 +1,134 @@
+;; References that live in frames while the collector runs: in locals and on the operand stack across calls that
+;; allocate enough to collect, in inline and out-of-line objects, and as i31 values. Every function
+;; returns a checksum that is only right if nothing they still refer to was freed or overwritten.
+(module
+ (type $node (struct (field $value (mut i64)) (field $next (mut (ref null $node)))))
+ (type $nodes (array (mut (ref null $node))))
+ (type $bytes (array (mut i8)))
+ (type $vector (struct (field v128) (field (ref null $node)) (field f64)))
+ ;; 600 fields of 8 bytes: data outside the heap.
+ (type $wide (array (mut i64)))
+
+ ;; Allocates 32 KB of garbage per count, written so that it takes memory, so that collections happen during the
+ ;; calls below.
+ (func $churn (param $count i32)
+ (local $i i32)
+ (loop $again
+ (drop (array.new $bytes (i32.const 1) (i32.const 4096)))
+ (drop (struct.new $node (i64.const -1) (ref.null $node)))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br_if $again (i32.lt_u (local.get $i) (local.get $count)))))
+
+ ;; A list of $length nodes held only by a local, with garbage allocated between every two nodes.
+ (func (export "list") (param $length i32) (result i64)
+ (local $head (ref null $node))
+ (local $i i32)
+ (local $sum i64)
+ (loop $build
+ (local.set $head (struct.new $node (i64.extend_i32_u (local.get $i)) (local.get $head)))
+ (call $churn (i32.const 64))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br_if $build (i32.lt_u (local.get $i) (local.get $length))))
+ (block $done
+ (loop $walk
+ (br_if $done (ref.is_null (local.get $head)))
+ (local.set $sum (i64.add (local.get $sum) (struct.get $node $value (local.get $head))))
+ (local.set $head (struct.get $node $next (local.get $head)))
+ (br $walk)))
+ (local.get $sum))
+
+ ;; References on the operand stack across calls: struct.new's operands are evaluated with calls in between.
+ (func $make (param $value i64) (result (ref $node))
+ (call $churn (i32.const 32))
+ (struct.new $node (local.get $value) (ref.null $node)))
+
+ (func (export "operands") (param $rounds i32) (result i64)
+ (local $i i32)
+ (local $sum i64)
+ (local $pair (ref null $node))
+ (loop $again
+ (local.set $pair
+ (struct.new $node
+ (i64.const 0)
+ (struct.new $node
+ (struct.get $node $value (call $make (i64.extend_i32_u (local.get $i))))
+ (call $make (i64.const 1000)))))
+ (local.set $sum
+ (i64.add (local.get $sum)
+ (i64.add
+ (struct.get $node $value (struct.get $node $next (local.get $pair)))
+ (struct.get $node $value
+ (struct.get $node $next (struct.get $node $next (local.get $pair)))))))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br_if $again (i32.lt_u (local.get $i) (local.get $rounds))))
+ (local.get $sum))
+
+ ;; An array of references with its data outside the heap, filled across collections.
+ (func (export "array") (param $length i32) (result i64)
+ (local $array (ref null $nodes))
+ (local $i i32)
+ (local $sum i64)
+ (local.set $array (array.new_default $nodes (local.get $length)))
+ (loop $fill
+ (array.set $nodes (local.get $array) (local.get $i)
+ (struct.new $node (i64.extend_i32_u (local.get $i)) (ref.null $node)))
+ (call $churn (i32.const 16))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br_if $fill (i32.lt_u (local.get $i) (local.get $length))))
+ (local.set $i (i32.const 0))
+ (loop $walk
+ (local.set $sum
+ (i64.add (local.get $sum)
+ (struct.get $node $value (array.get $nodes (local.get $array) (local.get $i)))))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br_if $walk (i32.lt_u (local.get $i) (local.get $length))))
+ (local.get $sum))
+
+ ;; A large array of i64s (data outside the heap), written before and read after collections.
+ (func (export "wide") (param $rounds i32) (result i64)
+ (local $array (ref null $wide))
+ (local $i i32)
+ (local $sum i64)
+ (local.set $array (array.new $wide (i64.const 7) (i32.const 600)))
+ (loop $again
+ (array.set $wide (local.get $array) (i32.rem_u (local.get $i) (i32.const 600))
+ (i64.extend_i32_u (local.get $i)))
+ (call $churn (i32.const 16))
+ (local.set $sum
+ (i64.add (local.get $sum)
+ (array.get $wide (local.get $array) (i32.rem_u (local.get $i) (i32.const 600)))))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br_if $again (i32.lt_u (local.get $i) (local.get $rounds))))
+ (i64.add (local.get $sum) (array.get $wide (local.get $array) (i32.const 599))))
+
+ ;; Structs with v128 and f64 fields, and casts of what survived.
+ (func (export "mixed") (param $rounds i32) (result i64)
+ (local $i i32)
+ (local $sum i64)
+ (local $keep (ref null $vector))
+ (local $any anyref)
+ (loop $again
+ (local.set $keep
+ (struct.new $vector
+ (i64x2.splat (i64.extend_i32_u (local.get $i)))
+ (struct.new $node (i64.const 3) (ref.null $node))
+ (f64.convert_i32_u (local.get $i))))
+ (local.set $any (ref.i31 (local.get $i)))
+ (call $churn (i32.const 16))
+ (local.set $sum
+ (i64.add (local.get $sum)
+ (i64.add
+ (i64x2.extract_lane 1 (struct.get $vector 0 (local.get $keep)))
+ (i64.add
+ (struct.get $node $value (struct.get $vector 1 (local.get $keep)))
+ (i64.add
+ (i64.trunc_f64_u (struct.get $vector 2 (local.get $keep)))
+ (i64.extend_i32_u (i31.get_u (ref.cast (ref i31) (local.get $any)))))))))
+ (local.set $any (local.get $keep))
+ (call $churn (i32.const 4))
+ (local.set $sum
+ (i64.add (local.get $sum)
+ (struct.get $node $value (struct.get $vector 1 (ref.cast (ref $vector) (local.get $any))))))
+ (local.set $i (i32.add (local.get $i) (i32.const 1)))
+ (br_if $again (i32.lt_u (local.get $i) (local.get $rounds))))
+ (local.get $sum)))
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
index c9e4301eba1..314f60e9851 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
@@ -619,43 +619,38 @@ JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM& vm, Wasm
case Wasm::Runtime::ExternKind::Global: {
auto value_type = store.canonical_value_type(module, import.type.value_type);
Wasm::Runtime::Entity address = nullptr;
- // 3.5.1. If v is a Number or v is a BigInt,
- if (import_.is_number() || import_.is_bigint()) {
- // 3.5.1.1. If valtype is i64 and v is a Number,
- if (import_.is_number() && value_type.kind == ValueKind::I64) {
- // 3.5.1.1.1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Import resolution attempted to cast a Number to a BigInteger"sv);
- }
- // 3.5.1.2. If valtype is not i64 and v is a BigInt,
- if (import_.is_bigint() && value_type.kind != ValueKind::I64) {
- // 3.5.1.2.1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Import resolution attempted to cast a BigInteger to a Number"sv);
- }
- // 3.5.1.3. If valtype is v128,
- if (value_type.kind == ValueKind::V128) {
- // 3.5.1.3.1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Import resolution attempted to cast a Number or BigInt to a V128"sv);
- }
- // 3.5.1.4. Let value be ToWebAssemblyValue(v, valtype).
- auto cast_value = TRY(to_webassembly_value(vm, import_, value_type));
- // 3.5.1.5. Let store be the surrounding agent's associated store.
- // 3.5.1.6. Let (store, globaladdr) be global_alloc(store, const valtype, value).
- // 3.5.1.7. Set the surrounding agent's associated store to store.
- address = store.allocate_global(value_type, false, cast_value);
- }
- // 3.5.2. Otherwise, if v implements Global,
- else if (auto* global = import_.is_object() ? Bindings::global_from_value(import_) : nullptr) {
- // 3.5.2.1. Let globaladdr be v.[[Global]].
+ // 3.5.1. If v implements Global,
+ if (auto* global = Bindings::global_from_value(import_)) {
+ // 3.5.1.1. Let globaladdr be v.[[Global]].
address = global->address();
}
- // 3.5.3. Otherwise,
+ // 3.5.2. Otherwise,
else {
- // 3.5.3.1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Invalid value for global type"sv);
+ // 3.5.2.1. If valtype is i64 and v is not a BigInt, throw a LinkError exception.
+ if (value_type.kind == ValueKind::I64 && !import_.is_bigint())
+ return vm.throw_completion<LinkError>("Import resolution attempted to use a non-BigInt for an i64 global"sv);
+ // 3.5.2.2. If valtype is one of i32, f32 or f64 and v is not a Number, throw a LinkError exception.
+ if ((value_type.kind == ValueKind::I32 || value_type.kind == ValueKind::F32 || value_type.kind == ValueKind::F64) && !import_.is_number())
+ return vm.throw_completion<LinkError>("Import resolution attempted to use a non-Number for a numeric global"sv);
+ // 3.5.2.3. If valtype is v128, throw a LinkError exception.
+ if (value_type.kind == ValueKind::V128)
+ return vm.throw_completion<LinkError>("Import resolution attempted to use a value for a V128 global"sv);
+ // 3.5.2.4. If mut is var, throw a LinkError exception.
+ if (import.type.is_mutable)
+ return vm.throw_completion<LinkError>("Import resolution attempted to use a value for a mutable global"sv);
+ // 3.5.2.5. Let value be ToWebAssemblyValue(v, valtype). If this throws a TypeError, catch it, and throw
+ // a LinkError exception.
+ auto value = to_webassembly_value(vm, import_, value_type);
+ if (value.is_error())
+ return vm.throw_completion<LinkError>("Import resolution attempted to use a value of the wrong type for a global"sv);
+ // 3.5.2.6. Let store be the surrounding agent's associated store.
+ // 3.5.2.7. Let (store, globaladdr) be global_alloc(store, const valtype, value).
+ // 3.5.2.8. Set the surrounding agent's associated store to store.
+ address = store.allocate_global(value_type, false, value.release_value());
}
- // 3.5.4. Let externglobal be global globaladdr.
- // 3.5.5. Append externglobal to imports.
+ // 3.5.3. Let externglobal be global globaladdr.
+ // 3.5.4. Append externglobal to imports.
imports.unchecked_append({ Wasm::Runtime::ExternKind::Global, address });
break;
}
diff --git a/Libraries/LibWebView/Process.cpp b/Libraries/LibWebView/Process.cpp
index 3f7f7269e99..f1cc104856c 100644
--- a/Libraries/LibWebView/Process.cpp
+++ b/Libraries/LibWebView/Process.cpp
@@ -113,6 +113,7 @@ Vector<ByteString> Process::helper_process_environment(ProcessType type)
"LC_"sv,
"LIBGC_"sv,
"LIBJS_"sv,
+ "LIBWASM_"sv,
"LIBWEB_"sv,
"LSAN_"sv,
"RUST_"sv,
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-many-calls-from-javascript.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-many-calls-from-javascript.txt
new file mode 100644
index 00000000000..e3bf8b6ae40
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-many-calls-from-javascript.txt
@@ -0,0 +1 @@
+sum: 19999900000
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-reference-global-imports.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-reference-global-imports.txt
new file mode 100644
index 00000000000..b2b6af0b9f3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-reference-global-imports.txt
@@ -0,0 +1,3 @@
+externref: true, anyref: 42, funcref: null
+a value that does not convert: LinkError
+a value for a mutable global: LinkError
diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-many-calls-from-javascript.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-many-calls-from-javascript.html
new file mode 100644
index 00000000000..1040aa1787e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-many-calls-from-javascript.html
@@ -0,0 +1,20 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ // Each call from JavaScript enters WebAssembly anew, which once read /proc/self/maps every time and made this test
+ // time out.
+ // (module (func (export "f") (param i32) (result i32) (local.get 0)))
+ const bytes = new Uint8Array([
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,
+ 0x03, 0x02, 0x01, 0x00, 0x07, 0x05, 0x01, 0x01, 0x66, 0x00, 0x00, 0x0a, 0x06, 0x01, 0x04, 0x00,
+ 0x20, 0x00, 0x0b,
+ ]);
+
+ test(() => {
+ const f = new WebAssembly.Instance(new WebAssembly.Module(bytes)).exports.f;
+ let sum = 0;
+ for (let i = 0; i < 200000; ++i)
+ sum += f(i);
+ println(`sum: ${sum}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-reference-global-imports.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-reference-global-imports.html
new file mode 100644
index 00000000000..f0c91decfb6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-reference-global-imports.html
@@ -0,0 +1,44 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ // (module
+ // (global $e (import "m" "e") externref)
+ // (global $a (import "m" "a") anyref)
+ // (global $f (import "m" "f") funcref)
+ // (func (export "e") (result externref) (global.get $e))
+ // (func (export "a") (result anyref) (global.get $a))
+ // (func (export "f") (result funcref) (global.get $f)))
+ const globalsBytes = new Uint8Array([
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x0d, 0x03, 0x60, 0x00, 0x01, 0x6f, 0x60,
+ 0x00, 0x01, 0x6e, 0x60, 0x00, 0x01, 0x70, 0x02, 0x16, 0x03, 0x01, 0x6d, 0x01, 0x65, 0x03, 0x6f,
+ 0x00, 0x01, 0x6d, 0x01, 0x61, 0x03, 0x6e, 0x00, 0x01, 0x6d, 0x01, 0x66, 0x03, 0x70, 0x00, 0x03,
+ 0x04, 0x03, 0x00, 0x01, 0x02, 0x07, 0x0d, 0x03, 0x01, 0x65, 0x00, 0x00, 0x01, 0x61, 0x00, 0x01,
+ 0x01, 0x66, 0x00, 0x02, 0x0a, 0x10, 0x03, 0x04, 0x00, 0x23, 0x00, 0x0b, 0x04, 0x00, 0x23, 0x01,
+ 0x0b, 0x04, 0x00, 0x23, 0x02, 0x0b, 0x00, 0x11, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x07, 0x0a, 0x03,
+ 0x00, 0x01, 0x65, 0x01, 0x01, 0x61, 0x02, 0x01, 0x66,
+ ]);
+
+ // (module (global (import "m" "g") (mut externref)))
+ const mutableBytes = new Uint8Array([
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x02, 0x08, 0x01, 0x01, 0x6d, 0x01, 0x67, 0x03,
+ 0x6f, 0x01,
+ ]);
+
+ function tryInstantiate(bytes, imports) {
+ try {
+ return new WebAssembly.Instance(new WebAssembly.Module(bytes), imports).exports;
+ } catch (exception) {
+ return exception.constructor.name;
+ }
+ }
+
+ test(() => {
+ // Reference-typed globals can be imported from plain values, which convert to the global's type.
+ const object = { name: "object" };
+ const exports = tryInstantiate(globalsBytes, { m: { e: object, a: 42, f: null } });
+ println(`externref: ${exports.e() === object}, anyref: ${exports.a()}, funcref: ${exports.f()}`);
+
+ println(`a value that does not convert: ${tryInstantiate(globalsBytes, { m: { e: object, a: 42, f: () => {} } })}`);
+ println(`a value for a mutable global: ${tryInstantiate(mutableBytes, { m: { g: object } })}`);
+ });
+</script>