Truly independent web browser
LibWasm: Add an optimizing JIT compiler
Andreas Kling4dee23d4f34b
diff --git a/Cargo.lock b/Cargo.lockindex c2176adab68..860a6e49c60 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -834,9 +834,26 @@ dependencies = ["flapc","ladybird_allocator","libc",+ "libwasm_module","rustc-demangle",]+[[package]]+name = "libwasm_jit"+version = "0.1.0"+dependencies = [+ "fARM64",+ "iced-x86",+ "libc",+ "libwasm_engine",+ "libwasm_module",+ "serde_json",+]++[[package]]+name = "libwasm_module"+version = "0.1.0"+[[package]]name = "libweb_bindings_rust"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 174ee3dbace..6e24bac4fab 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -15,6 +15,8 @@ members = ["Libraries/LibUnicode/Rust","Libraries/LibURL/Rust","Libraries/LibWasm/Engine",+ "Libraries/LibWasm/JIT",+ "Libraries/LibWasm/Module","Libraries/LibWeb/Bindings/Rust","Libraries/LibWeb/ContentBlocker/Rust","Libraries/LibWeb/Rust",diff --git a/Libraries/LibWasm/Engine/Cargo.toml b/Libraries/LibWasm/Engine/Cargo.tomlindex b1a22d8ad1f..12ac45441da 100644--- a/Libraries/LibWasm/Engine/Cargo.toml+++ b/Libraries/LibWasm/Engine/Cargo.toml@@ -12,6 +12,7 @@ crate-type = ["staticlib", "rlib"]ak = { path = "../../../AK/Rust" }ladybird_allocator = { path = "../../RustAllocator", optional = true }libc = "0.2"+libwasm_module = { path = "../Module" }rustc-demangle = "0.1"[features]diff --git a/Libraries/LibWasm/Engine/src/abi.rs b/Libraries/LibWasm/Engine/src/abi.rsindex 5248a3cb90b..0c3a8996c67 100644--- a/Libraries/LibWasm/Engine/src/abi.rs+++ b/Libraries/LibWasm/Engine/src/abi.rs@@ -86,6 +86,8 @@ pub struct FunctionHeader {/// For functions with v128 parameters or locals (FUNCTION_KIND_WASM_VECTOR), the offset from fp of each local's/// 16-byte storage, or zero for scalar locals. Null otherwise.pub vector_storage: *const u32,+ /// Where compiled code calls the function: its compiled code, or zero while it has none.+ pub native_entry: u64,}/// A memory, as the interpreter sees it.@@ -129,6 +131,8 @@ pub struct InstanceData {pub tags: *const u64,pub function_count: u32,pub memory_count: u32,+ /// The `ExecutionContext` of the store the instance belongs to, which compiled code finds the runtime through.+ pub context: *mut ExecutionContext,}/// A passive segment: its contents and their length, in bytes for data and in elements for element segments.@@ -277,6 +281,7 @@ pub fn layout_constants() -> String {field!("FUNCTION_LOCAL_COUNT", FunctionHeader, local_count);field!("FUNCTION_LOCALS_SIZE", FunctionHeader, locals_size);field!("FUNCTION_VECTOR_STORAGE", FunctionHeader, vector_storage);+ field!("FUNCTION_NATIVE_ENTRY", FunctionHeader, native_entry);field!("FUNCTION_FRAME_SIZE", FunctionHeader, frame_size);field!("FUNCTION_TYPE_IDENTITY", FunctionHeader, type_identity);field!("FUNCTION_HOST", FunctionHeader, host);@@ -297,6 +302,7 @@ pub fn layout_constants() -> String {field!("INSTANCE_ELEMENT_SEGMENTS", InstanceData, element_segments);field!("INSTANCE_MEMORY_COUNT", InstanceData, memory_count);field!("INSTANCE_TAGS", InstanceData, tags);+ field!("INSTANCE_CONTEXT", InstanceData, context);field!("SEGMENT_CONTENTS", Segment, contents);field!("SEGMENT_LENGTH", Segment, length);field!("CONTEXT_STACK_LIMIT", ExecutionContext, stack_limit);diff --git a/Libraries/LibWasm/Engine/src/lib.rs b/Libraries/LibWasm/Engine/src/lib.rsindex e1cbb1a7819..3caee26aa60 100644--- a/Libraries/LibWasm/Engine/src/lib.rs+++ b/Libraries/LibWasm/Engine/src/lib.rs@@ -18,26 +18,12 @@ mod rust_demangle;#[path = "../../../RustPanic.rs"]mod rust_panic;-pub mod abi;pub mod capi;-pub mod error;-pub mod instruction_tables;-pub mod module;-pub mod opcode;-pub mod parser;-pub mod quickening;-pub mod reader;pub mod runtime;-pub mod types;-pub mod validator;pub mod wasi;-pub use error::{Error, Result};-pub use module::Module;--/// Decode and validate a binary module.-pub fn compile(bytes: &[u8]) -> Result<Module> {- let mut module = parser::parse(bytes)?;- validator::validate(&mut module)?;- Ok(module)-}+// The module format is a crate of its own, which the JIT depends on too.+pub use libwasm_module::{+ Error, Module, Result, abi, compile, error, instruction_tables, module, opcode, parser, quickening, reader, types,+ validator,+};diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rsindex 573cca797c4..2d5d6492e8b 100644--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs@@ -554,6 +554,7 @@ impl Store {type_identity,host: std::ptr::null(),vector_storage: std::ptr::null(),+ native_entry: 0,},ty,vector_storage: Box::new([]),@@ -701,6 +702,7 @@ impl Store {tags: std::ptr::null(),function_count: 0,memory_count: 0,+ context: &raw mut *self.context,},module: module.clone(),functions: Vec::new(),@@ -802,6 +804,7 @@ impl Store {} else {std::ptr::null()},+ native_entry: 0,},ty,vector_storage,diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.mdnew file mode 100644index 00000000000..8959e5bb46a--- /dev/null+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md@@ -0,0 +1,301 @@+# The LibWasm optimizing JIT++This document describes how the WebAssembly JIT works. It is a living document: every change to the+compiler's structure updates it. Where it and the code disagree, one of them has a bug.++The compiler is the `libwasm_jit` crate (`Libraries/LibWasm/JIT`). It is a pure compiler: it takes+one function of a validated module and returns machine code, touching no heap and no store, so it+runs on any thread. Besides the compiler, the crate has what compiled code calls at run time: the+functions for bulk operations (`runtime.rs`) and the host stubs (`stubs.rs`). The runtime side+(tier-up, installing code, entering it) is not written yet.++## 1. Overview++A compile (`compile()`) runs these phases on one thread, with a `CompileContext` whose storage is+reused from one compile to the next:++| Phase | Where | What it does |+|---|---|---|+| Decode and build | `decode.rs`, `builder/` | One forward pass over the validated, quickened body. Produces typed SSA with phis, folding and value numbering as it goes. |+| Cleanup | `passes/cleanup.rs` | Removes trivial phis to a fixed point, dead pure nodes, and fuses branches with the comparisons only they use. |+| Loop invariant code motion | `passes/licm.rs` | Finds the nodes of call-free loops that compute the same value in every iteration. |+| Scheduling | `passes/schedule.rs` | Rebuilds the node arena in linear order without the dead nodes, with the invariant nodes at the end of their loop's preheader, optionally numbering values over the dominator tree on the way (`passes/gvn.rs`). |+| Liveness | `regalloc/liveness.rs` | One interval per value in linear order, extended over loops. |+| Allocation | `regalloc/` | One forward walk in linear order. Its verifier simulates every register. |+| Code generation | `codegen/x86_64/` | Lowers every node with its registers, then edge stubs, trap stubs, jump tables and constants. |++`Options::verify_ir` checks the IR after building and after cleanup (`ir/verify.rs`), and the+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+register pressure.++## 2. Decoding++`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.++## 3. The IR++A `Func` is a list of blocks in linear order, which is the order of the WebAssembly code. Every+forward edge goes to a later block, and every loop is a contiguous range of blocks (`Func::loops`)+that only its header is entered at. That makes linear order a topological order of the forward+edges, so dominators take one pass (`passes/dominators.rs`).++Nodes live in one arena and are named by their index, a `Value`. A `Node` is 16 bytes: an op, a+type, eight bits of flags and three 32-bit arguments, which are inputs or immediates as the op's+`Shape` says. Ops with more inputs keep them in `Func::operands`. A block owns a contiguous range of+nodes, its body, that ends with its terminator; nodes are created in order, so the index of a body+node is its position in linear order. Phis are linked into their block's list through their third+argument, and may sit anywhere in the arena. Successors and predecessors are ranges of flat arrays.++Types: i32, i64, f32, f64, v128, references (zero for null; a funcref is the function's+`FunctionHeader`) and pointers (for addresses the code computes). Constants,+parameters, the instance and the memory base have no code where they are: constants are+rematerialized at every use, and the others arrive in registers or slots at the entry. A node has+no room for a v128 constant, so `Const128` names one in `Func::constants`, as `Shuffle` does its lane+indices.++Effects (`Node::effect()`): `Pure` nodes compute a value and may be shared or removed; `Read` nodes+read memory or globals and may trap; `Write` nodes write state or may trap (division and trapping+truncations, unless their flags say they cannot), and are neither removed nor moved.++| Op | What it does |+|---|---|+| Const32, Const64 | A constant of the node's type (its bits in the arguments). |+| Const128 | A v128 constant, from `Func::constants`. |+| Param, Instance, MemoryBase | The function's parameters, its `InstanceData` and the base of its memory 0. |+| Phi | One input per predecessor, in predecessor order. |+| Forward | A phi that turned out trivial; gone after cleanup. |+| Add ... Rotr, DivS ... RemU, Clz, Ctz, Popcnt, Eqz, Extend*, Wrap | Integer arithmetic of the node's type. Division traps where the divisor is zero, and signed division where it overflows. |+| Compare | An integer comparison (flags: `IntCondition`), as an i32. |+| FAdd ... FNearest, FloatCompare | Float arithmetic and comparison (`FloatCondition`). |+| TruncS, TruncU, TruncSatS, TruncSatU, ConvertS, ConvertU, Demote, Promote, Reinterpret | Conversions to the node's type from the input's. The plain truncations trap on NaN and out of range values. |+| Select | Input 1 where input 0 is nonzero, else input 2. |+| InstanceField, LoadPointer | Pointers in instance data that never change, like `globals` and `globals[i]`, and type identities. |+| Offset | A pointer plus a constant, like the address of a segment. |+| 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. |+| 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. |+| CheckFunction, CheckNull | The checks of `call_indirect` (null, then type identity, then the subtype check of GC types) and of references that must not be null. |+| Call | A call through a `FunctionHeader`, direct or not; its value is the first result. |+| Helper | A call of a function of the runtime, which takes its operands in the context and may return a trap code. |+| CallResult | A further result of the call right before it. Never removed, since the results' places depend on them all. |+| Jump, Branch, BranchCompare, BranchFloatCompare, BrTable, Return, Trap, TailCall | Terminators. A branch goes to its first successor where its condition holds. |++## 4. Building SSA++The builder (`builder/mod.rs`) keeps an operand stack of values. Locals become SSA values with+Braun et al.'s algorithm ("Simple and Efficient Construction of SSA Form"), specialized for+structured control flow:++- The merge block of a `block` or `if` is created at its `end`, when every branch to it is known,+ so it is sealed from the start. Branches to a label whose block does not exist yet leave their+ successor slot open, and the `end` fills it in. Only loop headers are unsealed while their body is+ built; their `end` seals them.+- A read of a local first looks at a dense cache of each local's last definition, tagged with its+ block. Older definitions move into a function-wide table from (block, local) to value when the+ cache entry is overwritten. A read that finds neither walks the predecessors with an explicit+ stack, memoizing what it finds, and makes incomplete phis in unsealed loop headers.+- A merge a read cannot come back around to (one outside every loop whose header is sealed) gets a+ phi only if its predecessors' values differ; elsewhere the phi is made first, so that cycles end at+ it, and forwarded if it turns out trivial. A read that reaches a finished loop that never writes+ the local goes straight to the loop's entry: each loop records the locals it and the loops in it+ write. Large functions with many merges and loops otherwise spent most of their build time making+ and forwarding phis nobody needs.+- Phis that turn out trivial become `Forward` nodes, which cleanup removes to a fixed point.+- Values on the operand stack that flow into a merge become phis, as the block type says.+- Unreachable code is skipped by decoding, tracking only nesting.+- 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.++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+by constants that cannot trap. Floats are not folded, since NaN payloads are observable.++Pure nodes are value numbered in a table whose entries are undone when the construct that made them+ends, so every hit dominates its use. Constants are numbered function-wide. Global values are+numbered too, keyed by epochs that `global.set` of the global and calls advance; a loop advances+them at its header, since its body may write any global before the header runs again, and+`global.set` makes the stored value the global's known value.++The builder's maps are `table::Table`s, whose emptying costs nothing, so that small functions after+a large one do not pay for its capacity.++## 5. Cleanup++`passes/cleanup.rs` forwards trivial phis to a fixed point, rewrites every use of a forwarded phi,+counts uses, removes pure nodes without uses (transitively), and unlinks dead phis. Then a branch on+a comparison (or `eqz`) in its own block that nothing else uses compares itself+(`BranchCompare`, `BranchFloatCompare`).++## 6. Loop invariant code motion and scheduling++`passes/licm.rs` finds, for each node in a loop, the outermost loop it is invariant in: a pure node+none of whose inputs that loop defines (or each of which moves out of it too), or the value of a+global the loop does not set. Pure nodes never trap, so they may run where the loop would not have.+Memory loads stay, since one could trap. Loops that call keep everything: a call clobbers every+register, so a value computed before the loop would be reloaded from its slot in every iteration,+which costs what computing it again does.++`passes/schedule.rs` then rebuilds the node arena: the entry values first, in the entry block's+range, then every block's live body nodes in order, with the nodes that move to it before its+terminator (the block entering a loop always ends in a jump to its header), and the phis last,+outside every block's range. Inputs are renumbered, so a node's index is its position again, and+dead nodes are gone for the phases after it.++**Global value numbering** (`passes/gvn.rs`, with `Options::gvn`) runs in scheduling's walk: a node+computing what a node of a dominating block computed is replaced by it, keeping entries for as long+as their block dominates the walk, unlike the builder, which forgets what a construct numbered when+it ends. Reads are numbered by alias class, with epochs that the class's writes advance: memory+loads by one that stores and calls advance, global values by one per global that its `global.set`+advances and one that calls advance; a block continues the epochs of the previous block only if+that is its only predecessor. It is off by default: real modules have almost nothing for it, 0.1%+of godot's nodes, and it costs 7 to 16 ns per code byte.++## 7. Register allocation++The allocator (`regalloc/`) follows libjs_jit's: one forward walk over the blocks in linear order.++**Liveness** (`regalloc/liveness.rs`) is one interval per value: from its definition to its last+use, extended over every loop that uses it but does not contain its definition, since loops are+contiguous and entered at their header only. Positions: body node `n` is at `4n + 2`, phis are+defined at `4 * start` of their block, and the moves into a successor's phis happen at `4 * end - 1`,+after the terminator, so that a phi's input is still where the terminator left it. Intervals+over-approximate liveness in the "holes" of structured code, like an `else` arm between a+definition and its use. An interval can even span a merge that some paths reach without the+definition (a `block` the definition's branch skips); the value is dead there, so merges keep only+the values whose definitions dominate them.++**Register classes.** General purpose registers hold integers and pointers; xmm registers hold+floats and vectors alike. A v128 takes 16 bytes in memory: two slots, and 16-byte moves+(`Move::vector`). `Options::stress_registers` gives values only a few registers of each class, so+that most of them spill, for testing.++**The walk.** Each node's constraints (`constraints()`) say which inputs need registers, which may+be immediates, which need fixed registers, what it clobbers and where its output goes. Fixed inputs+and temps are placed first; an input of the same node in the way moves to another free register.+When no register is free, the value used furthest in the future is evicted. Inside a loop, the+values the rest of the iteration uses come first, then those the next iteration reads, then those+used after the loop. Values first used by a call argument or a return value prefer that register.++**Spilling** happens at the definition: a value that ever needs a stack slot gets one for its whole+life, and code generation stores it right after defining it, so a slot always holds its value once+it has one. Parameters use their home slots and the instance its frame header slot. Every value+live across a call gets a slot, since calls clobber every register.++**Blocks.** A block with one predecessor starts with that predecessor's registers. A merge starts+with those of its last predecessor (usually the fallthrough), and a loop header with those of the+block entering the loop, without the values the loop only carries through that have a slot already.+Their phis get registers free there, preferably the input's own from that predecessor. Every other+edge moves its values into place, as parallel moves with cycles broken through a slot; back edges+get theirs when their source block ends.++**The verifier** (`regalloc/verify.rs`) simulates every register from the state each block starts+with, checks that every input is where the allocation says, and that every edge's moves produce its+target's state, with phis replaced by their inputs.++## 8. Calls and frames++`convention.rs` defines the calling convention between compiled functions on x86-64:++- Integer parameters go in rdi, rsi, rdx, rcx, r8 and r9, float and vector ones in xmm0 to xmm7, in+ order. Every parameter has a home slot in the caller's outgoing area, at the callee's fp + 8 * the+ slots of the parameters before it (a v128 takes two, as on the interpreter's operand stack), where+ the parameters that do not fit in registers are passed.+- Integer results come back in rax and rdx, float and vector ones in xmm0 and xmm1. The others go to+ a result area whose address the caller passes in the slot after the parameters' home slots, each+ at 8 * the slots of the results before it.+- r14 holds the callee's instance, r15 the base of its memory 0, and r10 its `FunctionHeader`,+ whose native entry the call goes through.+- Every register but rsp and rbp is caller-saved, so the instance and memory base are SSA values+ the allocator may spill like any other. rsp is 16-byte aligned at the call.+- i32 values are zero-extended to 64 bits in registers and slots, so memory indices serve as they+ are; every i32 operation is a 32-bit instruction, which zero-extends its result.++A compiled frame has fp = the caller's rsp at the call: the return address at fp - 8, the caller's+fp at fp - 16 (the order the interpreter's frame headers will take, design section 6), the instance+at `FRAME_INSTANCE`, then the spill slots, and the outgoing area at rsp. After a call, rsp is+recomputed from fp, which also undoes whatever a callee's tail calls did to it.++The prologue writes the instance to the frame and checks the new rsp against the stack limit of+the store's `ExecutionContext`, which `InstanceData::context` points at, trapping with+`TRAP_STACK_EXHAUSTED`. `RuntimeInfo` has the trap exit.++**Calls.** Every call goes through `FunctionHeader::native_entry`. A direct call of a function of+the same instance passes the caller's instance and memory base; any other call (imports,+`call_indirect`, `call_ref`) passes the callee's, from its header (`CalleeInstance`). `call_indirect`+checks the index against the table's size, the element for null, and its type identity against the+expected one inline; a mismatch goes to an out-of-line check of the runtime types' displays, which+only GC modules' subtypes pass.++**Host functions** have a host stub of their signature as their native entry (`stubs.rs`). It+builds a frame like a compiled function's, lays the arguments out as the interpreter's operand stack+would hold them, calls `wasm_runtime_call_host`, and loads the results. A host function has no+instance, so it is called with the caller's, through which the stub finds the context. The frame it+passes as the one an exception unwinds from has no instance, so that the runtime does not walk+compiled frames.++**Tail calls** place their operands as a call does, then copy the stack arguments (and the result+area pointer, which the caller's caller passed) from the outgoing area into the incoming one, from+the highest slot down, since the incoming area is the higher one. If they need more slots than the+function was called with, the return address and saved fp move down first by the difference,+rounded to 16 bytes. Then they restore fp and jump to the callee's native entry.++**Runtime functions** (`Helper`) take the instance in rdi and their operands in the next argument+registers, which the code stores into the context's `arguments`; they clobber what the host ABI+does not preserve, so values stay in rbx and r12 to r15 across them. Growing calls the engine's+helpers; fill, copy and init of memories and tables call the JIT's (`runtime.rs`), which return 0 or+the trap code.++## 9. Code generation++`codegen/x86_64/` lowers the blocks in linear order with x86-64-v3 instructions (VEX three-operand+float arithmetic, BMI1/BMI2 shifts and rotates, lzcnt, tzcnt, popcnt, and AVX2 for vectors), from+libjs_jit's encoders and the additions in its `asm/x86_64/extended.rs`, whose `vex()` encodes any+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.++- **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+ of 32-bit offsets, with stubs for the edges that need moves.+- **Traps** jump to one stub per trap code, which puts the code in edi and jumps to+ `RuntimeInfo::trap_exit` with rbp still the trapping frame's fp. Memory accesses rely on guard+ pages: the runtime's fault handler turns faults in compiled code into the same trap exit.+- **Data**: float constants and masks live in a constant pool after the code, jump tables before+ it, both reached rip-relative, so the code is position independent. The runtime is reached+ through absolute addresses.++## 10. Testing++- `cargo test -p libwasm_jit`: unit tests, and the decoder and execution tests over the spec+ testsuite's modules when the build directory has them.+- `examples/spec_check.rs` (and `tests/execution.rs`, with and without `stress_registers`) runs the+ spec testsuite's scripts in two stores, one where calls into compiled functions run the compiled+ code, and compares results, traps, memories, tables (by which elements are null) and globals with+ the interpreter's. `tests/harness` has a session per thread: a code space whose start is the trap+ exit, a trampoline per signature, host stubs, and a stub for functions that did not compile, which+ traps with a code of its own; binding a module's instance points the engine's function headers at+ the code.+- `examples/smith_check.rs` does the same for random modules from `wasm-tools smith` in the subset+ the JIT compiles, calling every exported function with random arguments.+- `examples/run_kernel.rs` times calls of one function, compiled or interpreted, for the run time+ effect of optimizations while the JIT has no runtime; `examples/kernels/` has loops for them.+- `examples/compile_all.rs` compiles every function of modules and reports coverage, the CPU time+ of compiling the functions the JIT compiles on one thread and on several, per byte and per phase+ (`Options::stats`), the slowest large function, the cost of small ones, and nodes, slots and moves+ per byte; with `--verify` it checks every phase.diff --git a/Libraries/LibWasm/JIT/Cargo.toml b/Libraries/LibWasm/JIT/Cargo.tomlnew file mode 100644index 00000000000..6d224c8f5a8--- /dev/null+++ b/Libraries/LibWasm/JIT/Cargo.toml@@ -0,0 +1,30 @@+[package]+name = "libwasm_jit"+version = "0.1.0"+edition = "2024"++[lib]+crate-type = ["rlib"]++# After changing dependencies, regenerate the Flatpak sources:+# python3 Meta/CMake/flatpak/generate-cargo-sources.py+[dependencies]+libwasm_module = { path = "../Module" }++# The host's disassembler, for `dump-asm`. Tests use both.+[target.'cfg(target_arch = "x86_64")'.dependencies]+iced-x86 = { version = "1.21", default-features = false, features = ["decoder", "intel", "std"] }++[target.'cfg(target_arch = "aarch64")'.dependencies]+farm64 = { package = "fARM64", version = "0.0.2", features = ["alloc"] }++# The tests run compiled code against the engine's runtime.+[dev-dependencies]+libwasm_engine = { path = "../Engine" }+farm64 = { package = "fARM64", version = "0.0.2", features = ["alloc"] }+iced-x86 = { version = "1.21", default-features = false, features = ["decoder", "intel", "std"] }+libc = "0.2"+serde_json = "1.0"++[lints]+workspace = truediff --git a/Libraries/LibWasm/JIT/examples/compile_all.rs b/Libraries/LibWasm/JIT/examples/compile_all.rsnew file mode 100644index 00000000000..a6d1f28d233--- /dev/null+++ b/Libraries/LibWasm/JIT/examples/compile_all.rs@@ -0,0 +1,368 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Compiles every function of WebAssembly modules and reports how long it took.+//!+//! ```text+//! compile_all [--threads N] [--runs N] [--verify] [--stress-registers] [--no-licm] [--gvn] [--quiet]+//! [--dump-ir FUNCTION] [--dump-asm] MODULE|DIRECTORY...+//! ```+//!+//! A first pass finds the functions the JIT compiles; every measurement after it compiles only those, so that time+//! spent on functions that fail does not count. CPU time is the sum of every compile thread's own CPU time+//! (CLOCK_THREAD_CPUTIME_ID), taken once per thread after its last compile, the best of `--runs` runs, on one thread and on+//! `--threads`. A pass with phase timers (time stamp counter ticks) gives the time of each phase, the slowest+//! function per byte among those of at least 1 KiB, the cost of the smallest functions, and the nodes, stack slots+//! and moves per byte. Module decoding and validation are not included.++use libwasm_jit::{CompileContext, CompileFailure, CompileRequest, Options, PHASES, RuntimeInfo, Stats};+use std::collections::BTreeMap;+use std::sync::Arc;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::time::{Duration, Instant};++/// A runtime for code that never runs.+const RUNTIME: RuntimeInfo = RuntimeInfo {+ trap_exit: 0x7fff_0000_1000,+ memory_grow: 0x7fff_0000_2000,+ table_grow: 0x7fff_0000_3000,+ call_host: 0x7fff_0000_4000,+};++/// Functions at least this big count for the slowest function per byte.+const LARGE_FUNCTION: u32 = 1024;+/// Functions at most this big count for the cost per function.+const SMALL_FUNCTION: u32 = 32;++fn thread_cpu_ns() -> u64 {+ let mut time = libc::timespec { tv_sec: 0, tv_nsec: 0 };+ unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &raw mut time) };+ time.tv_sec as u64 * 1_000_000_000 + time.tv_nsec as u64+}++/// Time stamp counter ticks per nanosecond.+fn ticks_per_ns() -> f64 {+ let (start, start_ticks) = (Instant::now(), libwasm_jit::ticks());+ std::thread::sleep(Duration::from_millis(100));+ let ticks = libwasm_jit::ticks() - start_ticks;+ ticks as f64 / start.elapsed().as_nanos() as f64+}++struct Arguments {+ threads: usize,+ runs: usize,+ options: Options,+ dump: Option<u32>,+ quiet: bool,+ paths: Vec<String>,+}++fn parse_arguments() -> Arguments {+ let mut arguments = Arguments {+ threads: 1,+ runs: 3,+ options: Options::default(),+ dump: None,+ quiet: false,+ paths: Vec::new(),+ };+ let mut iterator = std::env::args().skip(1);+ while let Some(argument) = iterator.next() {+ match argument.as_str() {+ "--threads" => arguments.threads = iterator.next().and_then(|n| n.parse().ok()).expect("--threads N"),+ "--runs" => arguments.runs = iterator.next().and_then(|n| n.parse().ok()).expect("--runs N"),+ "--verify" => arguments.options.verify_ir = true,+ "--stress-registers" => arguments.options.stress_registers = true,+ "--no-licm" => arguments.options.no_licm = true,+ "--gvn" => arguments.options.gvn = true,+ "--quiet" => arguments.quiet = true,+ "--dump-asm" => arguments.options.dump_asm = true,+ "--dump-ir" => {+ arguments.dump = Some(+ iterator+ .next()+ .and_then(|n| n.parse().ok())+ .expect("--dump-ir FUNCTION"),+ );+ }+ _ => arguments.paths.push(argument),+ }+ }+ arguments+}++fn module_paths(paths: &[String]) -> Vec<std::path::PathBuf> {+ let mut result = Vec::new();+ for path in paths {+ let path = std::path::PathBuf::from(path);+ if path.is_dir() {+ let mut entries = std::fs::read_dir(&path)+ .expect("a readable directory")+ .filter_map(|entry| entry.ok().map(|entry| entry.path()))+ .filter(|path| path.extension().is_some_and(|extension| extension == "wasm"))+ .collect::<Vec<_>>();+ entries.sort();+ result.extend(entries);+ } else {+ result.push(path);+ }+ }+ result+}++/// Compiles `functions` (counting imports) of `module` on `threads` threads and returns the CPU time they took.+fn timed_compile(module: &Arc<libwasm_engine::Module>, functions: &[u32], threads: usize, options: Options) -> u64 {+ let next = AtomicUsize::new(0);+ std::thread::scope(|scope| {+ let handles = (0..threads)+ .map(|_| {+ scope.spawn(|| {+ let mut context = CompileContext::default();+ let start = thread_cpu_ns();+ loop {+ let index = next.fetch_add(1, Ordering::Relaxed);+ let Some(&function) = functions.get(index) else {+ break;+ };+ let request = CompileRequest {+ module: module.clone(),+ function,+ runtime: RUNTIME,+ options,+ };+ libwasm_jit::compile(&mut context, &request).expect("it compiled before");+ }+ thread_cpu_ns() - start+ })+ })+ .collect::<Vec<_>>();+ handles.into_iter().map(|handle| handle.join().unwrap()).sum()+ })+}++#[derive(Default)]+struct Totals {+ functions: usize,+ compiled: usize,+ code_bytes: u64,+ compiled_bytes: u64,+ cpu_ns: u64,+ threaded_cpu_ns: u64,+ failures: BTreeMap<&'static str, usize>,+}++fn main() {+ let arguments = parse_arguments();+ let ticks_per_ns = ticks_per_ns();+ let mut totals = Totals::default();+ for path in module_paths(&arguments.paths) {+ let Ok(bytes) = std::fs::read(&path) else {+ continue;+ };+ let Ok(module) = libwasm_engine::compile(&bytes) else {+ continue;+ };+ let module = Arc::new(module);+ let first = module.imported_function_count;+ if let Some(function) = arguments.dump {+ let mut context = CompileContext::default();+ let mut options = arguments.options;+ options.dump_ir = !arguments.quiet;+ options.stats = true;+ let request = CompileRequest {+ module: module.clone(),+ function,+ runtime: RUNTIME,+ options,+ };+ match libwasm_jit::compile(&mut context, &request) {+ Ok(compiled) => {+ let body = &module.code[(function - first) as usize];+ let bytes = f64::from(body.code.end - body.code.start);+ let phases = libwasm_jit::PHASES+ .iter()+ .zip(compiled.stats.ticks)+ .map(|(phase, ticks)| format!("{phase} {:.1}", ticks as f64 / ticks_per_ns / bytes))+ .collect::<Vec<_>>();+ println!(+ "function {function}: {bytes} bytes; phases (ns/byte): {}; {} nodes, {} slots, {} moves",+ phases.join(", "),+ compiled.stats.nodes,+ compiled.stats.slots,+ compiled.stats.moves+ );+ println!("{}", compiled.dump.unwrap_or_default());+ }+ Err(failure) => println!("{failure:?}"),+ }+ continue;+ }++ // Which functions compile.+ let mut context = CompileContext::default();+ let mut compiled = Vec::new();+ let mut failures: BTreeMap<&'static str, usize> = BTreeMap::new();+ for index in 0..module.code.len() as u32 {+ let request = CompileRequest {+ module: module.clone(),+ function: first + index,+ runtime: RUNTIME,+ options: arguments.options,+ };+ match libwasm_jit::compile(&mut context, &request) {+ Ok(_) => compiled.push(first + index),+ Err(CompileFailure::Unsupported { what, .. }) => *failures.entry(what).or_default() += 1,+ Err(CompileFailure::CodeGeneration) => *failures.entry("code generation failed").or_default() += 1,+ }+ }+ let size = |function: u32| {+ let body = &module.code[(function - first) as usize].code;+ body.end - body.start+ };++ // The phase timers, the slowest functions and the counts. Each function's time is its best of the runs, so+ // that a preemption does not make it the slowest.+ let mut stats = Stats::default();+ let mut best_ns = vec![f64::MAX; compiled.len()];+ let options = Options {+ stats: true,+ ..arguments.options+ };+ for run in 0..arguments.runs.max(1) {+ for (position, &function) in compiled.iter().enumerate() {+ let request = CompileRequest {+ module: module.clone(),+ function,+ runtime: RUNTIME,+ options,+ };+ let start = libwasm_jit::ticks();+ let result = libwasm_jit::compile(&mut context, &request).expect("it compiled before");+ let ns = (libwasm_jit::ticks() - start) as f64 / ticks_per_ns;+ best_ns[position] = best_ns[position].min(ns);+ if run > 0 {+ continue;+ }+ for (total, phase) in stats.ticks.iter_mut().zip(result.stats.ticks) {+ *total += phase;+ }+ stats.nodes += result.stats.nodes;+ stats.slots += result.stats.slots;+ stats.moves += result.stats.moves;+ stats.hoisted += result.stats.hoisted;+ stats.eliminated += result.stats.eliminated;+ }+ }+ let mut worst = (0.0, 0, 0);+ let mut small = Vec::new();+ for (position, &function) in compiled.iter().enumerate() {+ let (bytes, ns) = (size(function), best_ns[position]);+ if bytes >= LARGE_FUNCTION && ns / f64::from(bytes) > worst.0 {+ worst = (ns / f64::from(bytes), function, bytes);+ }+ if bytes <= SMALL_FUNCTION {+ small.push(ns);+ }+ }+ small.sort_by(f64::total_cmp);++ // CPU time.+ let best = |threads: usize| {+ (0..arguments.runs)+ .map(|_| timed_compile(&module, &compiled, threads, arguments.options))+ .min()+ .unwrap_or(0)+ };+ let cpu = best(1);+ let threaded = if arguments.threads > 1 {+ best(arguments.threads)+ } else {+ cpu+ };++ let code_bytes = module+ .code+ .iter()+ .map(|body| u64::from(body.code.end - body.code.start))+ .sum::<u64>();+ let compiled_bytes = compiled.iter().map(|function| u64::from(size(*function))).sum::<u64>();+ totals.functions += module.code.len();+ totals.compiled += compiled.len();+ totals.code_bytes += code_bytes;+ totals.compiled_bytes += compiled_bytes;+ totals.cpu_ns += cpu;+ totals.threaded_cpu_ns += threaded;+ for (what, count) in &failures {+ *totals.failures.entry(what).or_default() += count;+ }+ if arguments.quiet {+ continue;+ }+ let per_byte = |ns: f64| ns / compiled_bytes.max(1) as f64;+ println!("{}", path.display());+ println!(+ " compiled: {}/{} functions ({:.1}%), {}/{} bytes ({:.1}%)",+ compiled.len(),+ module.code.len(),+ 100.0 * compiled.len() as f64 / module.code.len().max(1) as f64,+ compiled_bytes,+ code_bytes,+ 100.0 * compiled_bytes as f64 / code_bytes.max(1) as f64+ );+ println!(+ " CPU: {:.3} ms on 1 thread, {:.1} ns/byte; {:.3} ms on {} threads, {:.1} ns/byte",+ cpu as f64 / 1e6,+ per_byte(cpu as f64),+ threaded as f64 / 1e6,+ arguments.threads,+ per_byte(threaded as f64)+ );+ let phases = PHASES+ .iter()+ .zip(stats.ticks)+ .map(|(name, ticks)| format!("{name} {:.1}", per_byte(ticks as f64 / ticks_per_ns)))+ .collect::<Vec<_>>();+ println!(" phases (ns/byte): {}", phases.join(", "));+ if worst.2 > 0 {+ println!(+ " slowest function of {LARGE_FUNCTION}+ bytes: {:.1} ns/byte (function {}, {} bytes)",+ worst.0, worst.1, worst.2+ );+ }+ if !small.is_empty() {+ println!(+ " functions of up to {SMALL_FUNCTION} bytes: {:.0} ns median, {} of them",+ small[small.len() / 2],+ small.len()+ );+ }+ println!(+ " per byte: {:.2} nodes, {:.3} slots, {:.3} moves; {} nodes hoisted out of loops, {} numbered away",+ stats.nodes as f64 / compiled_bytes.max(1) as f64,+ stats.slots as f64 / compiled_bytes.max(1) as f64,+ stats.moves as f64 / compiled_bytes.max(1) as f64,+ stats.hoisted,+ stats.eliminated+ );+ for (what, count) in &failures {+ println!(" unsupported: {count} x {what}");+ }+ }+ println!(+ "total: {}/{} functions, {}/{} bytes compiled, {:.3} ms CPU on 1 thread ({:.1} ns/byte), {:.3} ms on {}",+ totals.compiled,+ totals.functions,+ totals.compiled_bytes,+ totals.code_bytes,+ totals.cpu_ns as f64 / 1e6,+ totals.cpu_ns as f64 / totals.compiled_bytes.max(1) as f64,+ totals.threaded_cpu_ns as f64 / 1e6,+ arguments.threads+ );+ for (what, count) in &totals.failures {+ println!(" unsupported: {count} x {what}");+ }+}diff --git a/Libraries/LibWasm/JIT/examples/kernels/loops.wat b/Libraries/LibWasm/JIT/examples/kernels/loops.watnew file mode 100644index 00000000000..fd62cfcc8c5--- /dev/null+++ b/Libraries/LibWasm/JIT/examples/kernels/loops.wat@@ -0,0 +1,68 @@+;; Loops of the shapes loop invariant code motion and value numbering are for, as compilers emit them: calls in a+;; loop, which load their callee's FunctionHeader, globals the loop only reads, and repeated address arithmetic.+;; Build with `wasm-tools parse loops.wat -o loops.wasm` and time with examples/run_kernel.rs.+(module+ (memory 1)+ (global $offset (mut i32) (i32.const 3))+ (global $base (mut i32) (i32.const 1024))+ (global $scale (mut i32) (i32.const 7))++ (func $leaf (param i32) (result i32)+ local.get 0+ global.get $offset+ i32.add)++ ;; Function 1: n calls of a leaf in a loop.+ (func (export "calls") (param $n i32) (result i32)+ (local $i i32) (local $sum i32)+ loop $loop+ local.get $sum+ local.get $i+ call $leaf+ i32.add+ local.set $sum+ local.get $i+ i32.const 1+ i32.add+ local.tee $i+ local.get $n+ i32.lt_u+ br_if $loop+ end+ local.get $sum)++ ;; Function 2: a sum over memory at an address and with a factor that globals hold, n times over 256 words.+ (func (export "globals") (param $n i32) (result i32)+ (local $i i32) (local $j i32) (local $sum i32)+ loop $outer+ i32.const 0+ local.set $j+ loop $inner+ local.get $sum+ global.get $base+ local.get $j+ i32.const 2+ i32.shl+ i32.add+ i32.load+ global.get $scale+ i32.mul+ i32.add+ local.set $sum+ local.get $j+ i32.const 1+ i32.add+ local.tee $j+ i32.const 256+ i32.lt_u+ br_if $inner+ end+ local.get $i+ i32.const 1+ i32.add+ local.tee $i+ local.get $n+ i32.lt_u+ br_if $outer+ end+ local.get $sum))diff --git a/Libraries/LibWasm/JIT/examples/run_kernel.rs b/Libraries/LibWasm/JIT/examples/run_kernel.rsnew file mode 100644index 00000000000..6e9b6e9c96d--- /dev/null+++ b/Libraries/LibWasm/JIT/examples/run_kernel.rs@@ -0,0 +1,109 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Times calls of one function of a module, compiled and interpreted, for evidence of what an optimization does at+//! run time while the JIT has no runtime of its own. Imported functions are stubs that return zeros.+//!+//! ```text+//! run_kernel MODULE FUNCTION [--calls N] [--runs N] [--interpreter] [--no-licm] [--gvn] ARGUMENT...+//! ```+//!+//! Arguments are `i32:5`, `i64:-1`, `f32:1.5` or `f64:2`. The time is the best of `--runs` runs of `--calls` calls.++#[path = "../tests/harness/mod.rs"]+mod harness;++use harness::{CompiledModule, Outcome, TestBinding};+use libwasm_engine::module::ImportDescription;+use libwasm_engine::runtime::{ExternValue, HostCallback, Store, Value};+use libwasm_engine::types::ValType;+use libwasm_jit::Options;+use std::rc::Rc;+use std::sync::Arc;+use std::time::Instant;++fn parse(argument: &str) -> Value {+ let (ty, value) = argument.split_once(':').expect("TYPE:VALUE");+ match ty {+ "i32" => Value::I32(value.parse::<i64>().expect("an i32") as i32),+ "i64" => Value::I64(value.parse().expect("an i64")),+ "f32" => Value::F32(value.parse::<f32>().expect("an f32").to_bits()),+ "f64" => Value::F64(value.parse::<f64>().expect("an f64").to_bits()),+ _ => panic!("unknown type {ty}"),+ }+}++fn main() {+ let mut arguments = std::env::args().skip(1);+ let path = arguments.next().expect("MODULE");+ let function: u32 = arguments+ .next()+ .and_then(|function| function.parse().ok())+ .expect("FUNCTION");+ let (mut calls, mut runs, mut interpreter) = (100, 5, false);+ let mut options = Options::default();+ let mut values = Vec::new();+ while let Some(argument) = arguments.next() {+ match argument.as_str() {+ "--calls" => calls = arguments.next().and_then(|n| n.parse().ok()).expect("--calls N"),+ "--runs" => runs = arguments.next().and_then(|n| n.parse().ok()).expect("--runs N"),+ "--interpreter" => interpreter = true,+ "--no-licm" => options.no_licm = true,+ "--gvn" => options.gvn = true,+ _ => values.push(parse(&argument)),+ }+ }+ let module = Arc::new(libwasm_engine::compile(&std::fs::read(&path).unwrap()).unwrap());+ let mut store = Store::new();+ let mut imports = Vec::new();+ for import in &module.imports {+ let ImportDescription::Function(type_index) = import.description else {+ panic!("only function imports are stubbed");+ };+ let ty = module.types[type_index as usize].as_func().unwrap().clone();+ let results = ty.results.clone();+ let callback: HostCallback = Rc::new(move |_: &mut Store, _: &[Value]| {+ Ok(results+ .iter()+ .map(|result: &ValType| Value::default_for(*result))+ .collect())+ });+ imports.push(ExternValue::Function(store.allocate_host_function(ty, callback)));+ }+ let instance = store.instantiate(module.clone(), &imports).unwrap();+ let address = store.instance(instance).functions[function as usize];+ let compiled = CompiledModule::compile(module, options);+ let mut binding = TestBinding::new(&compiled, &store, instance);+ if !interpreter {+ assert!(+ compiled.runnable[function as usize],+ "function {function} does not run compiled"+ );+ }+ let mut best = f64::MAX;+ let mut last = None;+ for _ in 0..runs {+ let start = Instant::now();+ for _ in 0..calls {+ let outcome = if interpreter {+ match store.invoke(address, &values) {+ Ok(values) => Outcome::Values(values),+ Err(trap) => Outcome::Trap(harness::script::trap_code(&trap)),+ }+ } else {+ binding.call(&mut store, &compiled, function, &values)+ };+ last = Some(outcome);+ }+ best = best.min(start.elapsed().as_secs_f64());+ }+ println!(+ "{:.3} ms for {calls} calls ({:.1} us each), last outcome {:?}",+ best * 1e3,+ best * 1e6 / f64::from(calls),+ last.unwrap()+ );+}diff --git a/Libraries/LibWasm/JIT/examples/smith_check.rs b/Libraries/LibWasm/JIT/examples/smith_check.rsnew file mode 100644index 00000000000..70d3344f6da--- /dev/null+++ b/Libraries/LibWasm/JIT/examples/smith_check.rs@@ -0,0 +1,327 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Generates random modules in the subset the JIT compiles with `wasm-tools smith`, calls every exported function+//! the JIT compiled with random arguments, and compares results, traps, memories and globals with the interpreter.+//!+//! ```text+//! smith_check [--count N] [--seed S] [--keep DIRECTORY] [--wasm-tools PATH] [--stress-registers] [--no-licm] [--gvn]+//! ```++#[path = "../tests/harness/mod.rs"]+mod harness;++use harness::{CompiledModule, Outcome, TestBinding, function_index};+use libwasm_engine::runtime::{ExternValue, Store, Trap, Value};+use libwasm_engine::types::ValType;+use libwasm_jit::Options;+use std::io::Write;+use std::process::{Command, Stdio};+use std::sync::Arc;++// NB: NaN payloads may differ between implementations, and reinterpreting them makes the difference visible, so+// the modules canonicalize them.+const SMITH_FLAGS: &[&str] = &[+ "--ensure-termination",+ "--canonicalize-nans",+ "true",+ "--fuel",+ "1000000",+ "--max-imports",+ "0",+ "--max-tables",+ "4",+ "--max-memories",+ "1",+ "--max-memory32-bytes",+ "262144",+ "--bulk-memory-enabled",+ "true",+ "--reference-types-enabled",+ "true",+ "--relaxed-simd-enabled",+ "false",+ "--exceptions-enabled",+ "false",+ "--gc-enabled",+ "false",+ "--tail-call-enabled",+ "true",+ "--threads-enabled",+ "false",+ "--memory64-enabled",+ "false",+ "--custom-page-sizes-enabled",+ "false",+ "--wide-arithmetic-enabled",+ "false",+ "--multi-value-enabled",+ "true",+ "--saturating-float-to-int-enabled",+ "true",+ "--sign-extension-ops-enabled",+ "true",+ "--export-everything",+ "true",+ "--min-funcs",+ "4",+ "--max-funcs",+ "40",+];++/// xorshift64*.+struct Random(u64);++impl Random {+ fn next(&mut self) -> u64 {+ self.0 ^= self.0 >> 12;+ self.0 ^= self.0 << 25;+ self.0 ^= self.0 >> 27;+ self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)+ }++ fn below(&mut self, bound: u64) -> u64 {+ self.next() % bound+ }++ fn bits(&mut self, width: u32) -> u64 {+ const SPECIAL: [u64; 8] = [0, 1, 2, 3, 7, 0xff, 0x7fff_ffff, 0x8000_0000];+ let bits = match self.below(4) {+ 0 => SPECIAL[self.below(SPECIAL.len() as u64) as usize],+ 1 => self.below(64),+ 2 => self.next().wrapping_neg() & 0xffff,+ _ => self.next(),+ };+ if width == 32 { bits & 0xffff_ffff } else { bits }+ }++ fn argument(&mut self, ty: ValType) -> Option<Value> {+ Some(match ty {+ ValType::I32 => Value::I32(self.bits(32) as u32 as i32),+ ValType::I64 => Value::I64(self.bits(64) as i64),+ ValType::F32 => {+ const VALUES: [f32; 8] = [0.0, -0.0, 1.0, -1.5, 2147483648.0, f32::INFINITY, f32::NAN, 1e30];+ Value::F32(match self.below(3) {+ 0 => VALUES[self.below(8) as usize].to_bits(),+ 1 => (self.below(2000) as f32 - 1000.0).to_bits(),+ _ => self.next() as u32,+ })+ }+ ValType::F64 => {+ const VALUES: [f64; 8] = [0.0, -0.0, 1.0, -1.5, 9.3e18, f64::NEG_INFINITY, f64::NAN, 4294967296.0];+ Value::F64(match self.below(3) {+ 0 => VALUES[self.below(8) as usize].to_bits(),+ 1 => (self.below(2000) as f64 - 1000.0).to_bits(),+ _ => self.next(),+ })+ }+ ValType::V128 => Value::V128(u128::from(self.bits(64)) | (u128::from(self.bits(64)) << 64)),+ ValType::Ref(reference) if reference.nullable => Value::Ref(0),+ ValType::Ref(_) => return None,+ })+ }+}++fn outcome(result: Result<Vec<Value>, Trap>) -> Outcome {+ match result {+ Ok(values) => Outcome::Values(values),+ Err(trap) => Outcome::Trap(harness::script::trap_code(&trap)),+ }+}++#[derive(Default)]+struct Totals {+ modules: usize,+ functions: usize,+ compiled: usize,+ runnable: usize,+ cases: usize,+ failures: usize,+ not_compiled: usize,+ /// Why functions were not compiled, and how often.+ unsupported: std::collections::BTreeMap<&'static str, usize>,+}++fn main() {+ let mut count = 100;+ let mut seed = 1u64;+ let mut keep = None;+ let mut stress_registers = false;+ let mut no_licm = false;+ let mut gvn = false;+ let mut wasm_tools = std::env::var("HOME")+ .map(|home| format!("{home}/.cargo/bin/wasm-tools"))+ .unwrap_or_default();+ let mut arguments = std::env::args().skip(1);+ while let Some(argument) = arguments.next() {+ match argument.as_str() {+ "--count" => {+ count = arguments+ .next()+ .and_then(|value| value.parse().ok())+ .expect("--count N");+ }+ "--seed" => seed = arguments.next().and_then(|value| value.parse().ok()).expect("--seed S"),+ "--keep" => keep = arguments.next(),+ "--wasm-tools" => wasm_tools = arguments.next().expect("--wasm-tools PATH"),+ "--stress-registers" => stress_registers = true,+ "--no-licm" => no_licm = true,+ "--gvn" => gvn = true,+ _ => panic!("unknown argument {argument}"),+ }+ }+ let mut random = Random(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1);+ let mut totals = Totals::default();+ for iteration in 0..count {+ let input = (0..1000 + random.below(30000))+ .map(|_| random.next() as u8)+ .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" }])+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .expect("wasm-tools runs");+ child.stdin.take().unwrap().write_all(&input).unwrap();+ let output = child.wait_with_output().unwrap();+ if !output.status.success() {+ continue;+ }+ let bytes = output.stdout;+ let Ok(module) = libwasm_engine::compile(&bytes) else {+ continue;+ };+ let module = Arc::new(module);+ let mut interpreted = Store::new();+ let mut jit = Store::new();+ let (Ok(interpreted_instance), Ok(jit_instance)) = (+ interpreted.instantiate(module.clone(), &[]),+ jit.instantiate(module.clone(), &[]),+ ) else {+ continue;+ };+ if let Some(directory) = &keep {+ // NB: Where a crash leaves it.+ std::fs::write(format!("{directory}/current.wasm"), &bytes).unwrap();+ }+ let compiled = CompiledModule::compile(+ module.clone(),+ Options {+ verify_ir: true,+ stress_registers,+ no_licm,+ gvn,+ ..Options::default()+ },+ );+ let mut binding = TestBinding::new(&compiled, &jit, jit_instance);+ totals.modules += 1;+ totals.functions += module.code.len();+ let first = module.imported_function_count as usize;+ totals.compiled += compiled.entries[first..].iter().filter(|entry| **entry != 0).count();+ totals.runnable += compiled.runnable[first..].iter().filter(|runnable| **runnable).count();+ for failure in compiled.failures.iter().flatten() {+ let what = match failure {+ libwasm_jit::CompileFailure::Unsupported { what, .. } => *what,+ libwasm_jit::CompileFailure::CodeGeneration => "code generation",+ };+ *totals.unsupported.entry(what).or_default() += 1;+ }+ let mut exports = interpreted+ .instance(interpreted_instance)+ .exports+ .iter()+ .map(|(name, export)| (name.clone(), *export))+ .collect::<Vec<_>>();+ exports.sort_by(|a, b| a.0.cmp(&b.0));+ let mut failed = false;+ let mut stop = false;+ for (name, export) in exports {+ let ExternValue::Function(interpreted_function) = export else {+ continue;+ };+ let Some(ExternValue::Function(jit_function)) = jit.instance(jit_instance).export(&name) else {+ continue;+ };+ let Some(index) = function_index(&jit, jit_function, jit_instance) else {+ continue;+ };+ let ty = interpreted.function(interpreted_function).ty.clone();+ for _ in 0..4 {+ let Some(arguments) = ty+ .params+ .iter()+ .map(|ty| random.argument(*ty))+ .collect::<Option<Vec<_>>>()+ else {+ break;+ };+ let expected = outcome(interpreted.invoke(interpreted_function, &arguments));+ if !compiled.runnable[index as usize] {+ let _ = jit.invoke(jit_function, &arguments);+ continue;+ }+ totals.cases += 1;+ let actual = binding.call(&mut jit, &compiled, index, &arguments);+ if actual == Outcome::Trap(harness::TRAP_NOT_COMPILED) {+ totals.not_compiled += 1;+ stop = true;+ break;+ }+ let exhausted = Outcome::Trap(libwasm_engine::abi::TRAP_STACK_EXHAUSTED);+ if expected == exhausted || actual == exhausted {+ // NB: How deep the stack gets before it is exhausted differs between the tiers, and so does what+ // the code did on the way there, like how much of a fuel global it used. The stores differ+ // from here on.+ stop = true;+ break;+ }+ let mut problem = None;+ if !harness::script::same_outcome(&expected, &actual) {+ problem = Some(format!("{name}{arguments:?}: interpreter {expected:?}, JIT {actual:?}"));+ } else if let Some(difference) =+ harness::script::state_difference(&interpreted, interpreted_instance, &jit, jit_instance)+ {+ problem = Some(format!("{name}{arguments:?}: {difference}"));+ }+ if let Some(problem) = problem {+ totals.failures += 1;+ failed = true;+ println!("FAIL module {iteration}: {problem}");+ break;+ }+ }+ if failed || stop {+ break;+ }+ }+ if failed && let Some(directory) = &keep {+ let path = format!("{directory}/smith-{seed}-{iteration}.wasm");+ std::fs::write(&path, &bytes).unwrap();+ println!(" kept {path}");+ }+ }+ println!(+ "{} modules, {} functions: {} compiled, {} runnable; {} cases, {} failures, {} reached uncompiled code",+ totals.modules,+ totals.functions,+ totals.compiled,+ totals.runnable,+ totals.cases,+ totals.failures,+ totals.not_compiled+ );+ for (what, count) in &totals.unsupported {+ println!("{count:>8} not compiled: {what}");+ }+ if totals.failures > 0 {+ std::process::exit(1);+ }+}diff --git a/Libraries/LibWasm/JIT/examples/spec_check.rs b/Libraries/LibWasm/JIT/examples/spec_check.rsnew file mode 100644index 00000000000..a3234263e9f--- /dev/null+++ b/Libraries/LibWasm/JIT/examples/spec_check.rs@@ -0,0 +1,49 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Runs spec testsuite scripts with calls into compiled functions running compiled code, and compares everything+//! with the interpreter (see `tests/harness/script.rs`).+//!+//! ```text+//! spec_check [--verbose] [--stress-registers] [--no-licm] [--gvn] DIRECTORY|SCRIPT.json...+//! ```++#[path = "../tests/harness/mod.rs"]+mod harness;++fn main() {+ let mut verbose = false;+ let mut paths = Vec::new();+ let mut options = libwasm_jit::Options {+ verify_ir: true,+ ..Default::default()+ };+ for argument in std::env::args().skip(1) {+ match argument.as_str() {+ "--verbose" => verbose = true,+ "--stress-registers" => options.stress_registers = true,+ "--no-licm" => options.no_licm = true,+ "--gvn" => options.gvn = true,+ _ => paths.push(argument),+ }+ }+ let totals = harness::script::run(&paths, verbose, options);+ println!(+ "{} scripts, {} modules, {} functions: {} compiled, {} runnable, {} exercised; {} cases, {} failures, {} reached uncompiled code",+ totals.scripts,+ totals.modules,+ totals.functions,+ totals.compiled,+ totals.runnable,+ totals.exercised,+ totals.cases,+ totals.failures,+ totals.not_compiled+ );+ if totals.failures > 0 {+ std::process::exit(1);+ }+}diff --git a/Libraries/LibWasm/JIT/src/builder/calls.rs b/Libraries/LibWasm/JIT/src/builder/calls.rsnew file mode 100644index 00000000000..f9b649e556f--- /dev/null+++ b/Libraries/LibWasm/JIT/src/builder/calls.rs@@ -0,0 +1,218 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Calls, and the instance data they and tables reach.+//!+//! Every call goes through the callee's `FunctionHeader`. A direct call of one of the module's own functions passes+//! the caller's instance and memory base; any other call (of an import, or through a table or reference) passes+//! the callee's instance, found from its header, and that instance's memory base. Host functions have no instance;+//! they get the caller's, through which their stub finds the runtime.++use super::{Builder, instance_offset, ir_type, unsupported};+use crate::CompileFailure;+use crate::ir::{Func, NONE, Node, Op, Type, Value};+use libwasm_module::Module;+use libwasm_module::abi::{InstanceData, TRAP_NULL_REFERENCE, TRAP_UNDEFINED_ELEMENT, TRAP_UNINITIALIZED_ELEMENT};+use libwasm_module::types::FuncType;+use std::mem::offset_of;++/// How a call ends the code that makes it.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(super) enum CallKind {+ Normal,+ Tail,+}++impl Builder {+ /// A pointer field of the instance that never changes once it is instantiated.+ pub(super) fn instance_field(&mut self, func: &mut Func, offset: usize) -> Value {+ self.pure(+ func,+ Node::new(+ Op::InstanceField,+ Type::Pointer,+ 0,+ [self.instance, instance_offset(offset), 0],+ ),+ )+ }++ /// Element `index` of the pointer array of the instance at `offset`, which never changes either.+ pub(super) fn instance_pointer(&mut self, func: &mut Func, offset: usize, index: u32, ty: Type) -> Value {+ let array = self.instance_field(func, offset);+ self.pure(func, Node::new(Op::LoadPointer, ty, 0, [array, index * 8, 0]))+ }++ /// The store-wide identity of the module's type `type_index`.+ pub(super) fn type_identity(&mut self, func: &mut Func, type_index: u32) -> Value {+ let identities = self.instance_field(func, offset_of!(InstanceData, type_identities));+ self.pure(+ func,+ Node::new(Op::LoadPointer, Type::I32, 4, [identities, type_index * 4, 0]),+ )+ }++ /// The `TableData` of table `table`.+ pub(super) fn table_data(&mut self, func: &mut Func, table: u32) -> Value {+ self.instance_pointer(func, offset_of!(InstanceData, tables), table, Type::Pointer)+ }++ /// The `MemoryData` of memory `memory`.+ pub(super) fn memory_data(&mut self, func: &mut Func, memory: u32) -> Value {+ self.instance_pointer(func, offset_of!(InstanceData, memories), memory, Type::Pointer)+ }++ /// `ref.func`: the function's header, which is what a funcref is.+ pub(super) fn function_reference(&mut self, func: &mut Func, function: u32) -> Value {+ self.instance_pointer(func, offset_of!(InstanceData, functions), function, Type::Ref)+ }++ pub(super) fn call(+ &mut self,+ func: &mut Func,+ module: &Module,+ function: u32,+ kind: CallKind,+ pc: usize,+ ) -> Result<(), CompileFailure> {+ let ty = module.function_type(function).expect("functions have function types");+ let header = self.instance_pointer(func, offset_of!(InstanceData, functions), function, Type::Pointer);+ let (instance, memory_base) = if function < module.imported_function_count {+ self.callee_instance(func, header)+ } else {+ (self.instance, self.memory_base)+ };+ self.emit_call(func, ty, [header, instance, memory_base], function, kind, pc)+ }++ pub(super) fn call_indirect(+ &mut self,+ func: &mut Func,+ module: &Module,+ type_index: u32,+ table: u32,+ kind: CallKind,+ pc: usize,+ ) -> Result<(), CompileFailure> {+ let ty = module.types[type_index as usize]+ .as_func()+ .expect("call_indirect has a function type");+ let index = Self::resolve(func, self.pop());+ let table = self.table_data(func, table);+ let element = Self::append(+ func,+ Node::new(+ Op::TableElement,+ Type::Ref,+ TRAP_UNDEFINED_ELEMENT as u8,+ [table, index, 0],+ ),+ );+ let identity = self.type_identity(func, type_index);+ Self::append(+ func,+ Node::new(+ Op::CheckFunction,+ Type::None,+ TRAP_UNINITIALIZED_ELEMENT as u8,+ [element, identity, 0],+ ),+ );+ let (instance, memory_base) = self.callee_instance(func, element);+ self.emit_call(func, ty, [element, instance, memory_base], NONE, kind, pc)+ }++ pub(super) fn call_ref(+ &mut self,+ func: &mut Func,+ module: &Module,+ type_index: u32,+ kind: CallKind,+ pc: usize,+ ) -> Result<(), CompileFailure> {+ let ty = module.types[type_index as usize]+ .as_func()+ .expect("call_ref has a function type");+ let reference = Self::resolve(func, self.pop());+ Self::append(+ func,+ Node::new(Op::CheckNull, Type::None, TRAP_NULL_REFERENCE as u8, [reference, 0, 0]),+ );+ let (instance, memory_base) = self.callee_instance(func, reference);+ self.emit_call(func, ty, [reference, instance, memory_base], NONE, kind, pc)+ }++ /// The instance and memory base a call of the function whose header is `header` passes.+ fn callee_instance(&mut self, func: &mut Func, header: Value) -> (Value, Value) {+ let instance = self.pure(+ func,+ Node::new(Op::CalleeInstance, Type::Pointer, 0, [header, self.instance, 0]),+ );+ let memory_base = self.pure(+ func,+ Node::new(+ Op::InstanceField,+ Type::Pointer,+ 0,+ [instance, instance_offset(offset_of!(InstanceData, memory0_base)), 0],+ ),+ );+ (instance, memory_base)+ }++ fn emit_call(+ &mut self,+ func: &mut Func,+ ty: &FuncType,+ [header, instance, memory_base]: [Value; 3],+ function: u32,+ kind: CallKind,+ pc: usize,+ ) -> Result<(), CompileFailure> {+ if ty.results.iter().chain(&ty.params).any(|ty| ir_type(*ty).is_none()) {+ return unsupported(pc, "a call with values of a type the JIT does not compile");+ }+ let argument_count = ty.params.len();+ let start = func.operands.len() as u32;+ func.operands.extend_from_slice(&[header, instance, memory_base]);+ let top = self.stack.len() - argument_count;+ for position in top..self.stack.len() {+ let value = Self::resolve(func, self.stack[position]);+ func.operands.push(value);+ }+ self.stack.truncate(top);+ let first_result = ty+ .results+ .first()+ .and_then(|result| ir_type(*result))+ .unwrap_or(Type::None);+ let node = Node::new(Op::Call, first_result, 0, [start, 3 + argument_count as u32, function]);+ if kind == CallKind::Tail {+ self.terminate(+ func,+ Node {+ op: Op::TailCall,+ ty: Type::None,+ ..node+ },+ &[],+ );+ self.set_unreachable();+ return Ok(());+ }+ let call = Self::append(func, node);+ if !ty.results.is_empty() {+ self.push(call);+ }+ for (index, &result) in ty.results.iter().enumerate().skip(1) {+ let result_type = ir_type(result).expect("the results' types were checked");+ let value = Self::append(func, Node::new(Op::CallResult, result_type, 0, [call, index as u32, 0]));+ self.push(value);+ }+ self.call_epoch += 1;+ Ok(())+ }+}diff --git a/Libraries/LibWasm/JIT/src/builder/fold.rs b/Libraries/LibWasm/JIT/src/builder/fold.rsnew file mode 100644index 00000000000..489e441d43e--- /dev/null+++ b/Libraries/LibWasm/JIT/src/builder/fold.rs@@ -0,0 +1,179 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Local folding: constant folding and algebraic simplification of a node about to be created, from its inputs+//! alone. Floats are left alone: their results depend on NaN payloads the code may observe.++use crate::ir::{FLAG_CANNOT_TRAP, Func, IntCondition, Op, Type, Value};++/// What a node about to be created simplifies to.+pub enum Folded {+ /// An existing value.+ Value(Value),+ /// A constant of the node's type.+ Constant(u64),+ /// The node, possibly with its inputs swapped or its flags changed.+ Node { op: Op, flags: u8, a: Value, b: Value },+}++fn mask(ty: Type, bits: u64) -> u64 {+ if ty == Type::I32 { bits & 0xffff_ffff } else { bits }+}++fn width(ty: Type) -> u32 {+ if ty == Type::I32 { 32 } else { 64 }+}++/// The signed value of `bits` of type `ty`.+fn signed(ty: Type, bits: u64) -> i64 {+ if ty == Type::I32 {+ i64::from(bits as u32 as i32)+ } else {+ bits as i64+ }+}++fn evaluate_binary(op: Op, ty: Type, a: u64, b: u64, flags: u8) -> Option<u64> {+ let bits = width(ty);+ let shift = (b as u32) & (bits - 1);+ let result = match op {+ Op::Add => a.wrapping_add(b),+ Op::Sub => a.wrapping_sub(b),+ Op::Mul => a.wrapping_mul(b),+ Op::And => a & b,+ Op::Or => a | b,+ Op::Xor => a ^ b,+ Op::Shl => a << shift,+ Op::ShrS => (signed(ty, a) >> shift) as u64,+ Op::ShrU => mask(ty, a) >> shift,+ Op::Rotl if ty == Type::I32 => u64::from((a as u32).rotate_left(shift)),+ Op::Rotl => a.rotate_left(shift),+ Op::Rotr if ty == Type::I32 => u64::from((a as u32).rotate_right(shift)),+ Op::Rotr => a.rotate_right(shift),+ Op::DivU | Op::RemU | Op::DivS | Op::RemS if mask(ty, b) == 0 => return None,+ Op::DivU => mask(ty, a) / mask(ty, b),+ Op::RemU => mask(ty, a) % mask(ty, b),+ Op::DivS => {+ let (a, b) = (signed(ty, a), signed(ty, b));+ if b == -1 && a == signed(ty, 1 << (bits - 1)) {+ return None;+ }+ (a / b) as u64+ }+ Op::RemS => {+ let (a, b) = (signed(ty, a), signed(ty, b));+ if b == -1 { 0 } else { (a % b) as u64 }+ }+ Op::Compare => u64::from(IntCondition::from_flags(flags).evaluate(a, b, ty.is_64())),+ _ => return None,+ };+ Some(mask(ty, result))+}++/// Folds an integer binary op of type `ty` (for `Compare`, the operands' type) on `a` and `b`.+pub fn binary(func: &Func, op: Op, ty: Type, flags: u8, a: Value, b: Value) -> Folded {+ let constant_a = func.node(a).constant();+ let constant_b = func.node(b).constant();+ if let (Some(x), Some(y)) = (constant_a, constant_b)+ && let Some(result) = evaluate_binary(op, ty, x, y, flags)+ {+ return Folded::Constant(result);+ }+ // Constants go to the right.+ if constant_a.is_some() && constant_b.is_none() {+ if op.is_commutative() {+ return binary(func, op, ty, flags, b, a);+ }+ if op == Op::Compare {+ let swapped = IntCondition::from_flags(flags).swap() as u8;+ return binary(func, op, ty, swapped, b, a);+ }+ }+ let all_ones = mask(ty, u64::MAX);+ if let Some(y) = constant_b {+ let shift = (y as u32) & (width(ty) - 1);+ match op {+ Op::Add | Op::Sub | Op::Or | Op::Xor if y == 0 => return Folded::Value(a),+ Op::Shl | Op::ShrS | Op::ShrU | Op::Rotl | Op::Rotr if shift == 0 => return Folded::Value(a),+ Op::Mul | Op::DivS | Op::DivU if y == 1 => return Folded::Value(a),+ Op::Mul | Op::And if y == 0 => return Folded::Constant(0),+ Op::And if y == all_ones => return Folded::Value(a),+ Op::Or if y == all_ones => return Folded::Constant(all_ones),+ Op::RemU if y == 1 => return Folded::Constant(0),+ Op::RemS if y == 1 || y == all_ones => return Folded::Constant(0),+ Op::DivU | Op::RemU if y != 0 => {+ return Folded::Node {+ op,+ flags: flags | FLAG_CANNOT_TRAP,+ a,+ b,+ };+ }+ Op::DivS | Op::RemS if y != 0 && y != all_ones => {+ return Folded::Node {+ op,+ flags: flags | FLAG_CANNOT_TRAP,+ a,+ b,+ };+ }+ Op::Compare if y == 0 => match IntCondition::from_flags(flags) {+ IntCondition::LtU => return Folded::Constant(0),+ IntCondition::GeU => return Folded::Constant(1),+ _ => {}+ },+ _ => {}+ }+ }+ if a == b {+ match op {+ Op::Sub | Op::Xor => return Folded::Constant(0),+ Op::And | Op::Or => return Folded::Value(a),+ Op::Compare => {+ let holds = matches!(+ IntCondition::from_flags(flags),+ IntCondition::Eq | IntCondition::LeS | IntCondition::LeU | IntCondition::GeS | IntCondition::GeU+ );+ return Folded::Constant(u64::from(holds));+ }+ _ => {}+ }+ }+ Folded::Node { op, flags, a, b }+}++/// Folds an integer unary op producing `ty` on `a`.+pub fn unary(func: &Func, op: Op, ty: Type, a: Value) -> Option<Folded> {+ let input = func.node(a);+ if let Some(x) = input.constant() {+ let input_type = input.ty;+ let result = match op {+ Op::Clz if ty == Type::I32 => u64::from((x as u32).leading_zeros()),+ Op::Clz => u64::from(x.leading_zeros()),+ Op::Ctz if ty == Type::I32 => u64::from((x as u32).trailing_zeros()),+ Op::Ctz => u64::from(x.trailing_zeros()),+ Op::Popcnt => u64::from(x.count_ones()),+ Op::Eqz => u64::from(mask(input_type, x) == 0),+ Op::Extend8S => x as u8 as i8 as i64 as u64,+ Op::Extend16S => x as u16 as i16 as i64 as u64,+ Op::Extend32S | Op::ExtendI32S => x as u32 as i32 as i64 as u64,+ Op::ExtendI32U => u64::from(x as u32),+ Op::Wrap => x,+ _ => return None,+ };+ return Some(Folded::Constant(mask(ty, result)));+ }+ match (op, input.op) {+ (Op::Eqz, Op::Compare) => Some(Folded::Node {+ op: Op::Compare,+ flags: IntCondition::from_flags(input.flags).invert() as u8,+ a: input.args[0],+ b: input.args[1],+ }),+ (Op::Wrap, Op::ExtendI32S | Op::ExtendI32U) => Some(Folded::Value(input.args[0])),+ _ => None,+ }+}diff --git a/Libraries/LibWasm/JIT/src/builder/mod.rs b/Libraries/LibWasm/JIT/src/builder/mod.rsnew file mode 100644index 00000000000..48674be8844--- /dev/null+++ b/Libraries/LibWasm/JIT/src/builder/mod.rs@@ -0,0 +1,1653 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The builder: one forward pass over a validated, quickened function body that produces typed SSA.+//!+//! Locals become SSA values with the algorithm of Braun et al. ("Simple and Efficient Construction of SSA Form"),+//! specialized for structured control flow:+//!+//! - The merge block of a `block` or `if` is created at its `end`, when every branch to it is known, so it is sealed+//! from the start. Only loop headers are unsealed while their body is built: their back edges are the branches to+//! the loop inside it, and the loop's `end` seals them.+//! - Reading a local first looks at a dense per-local cache of the last definition, tagged with its block. Older+//! definitions move into one function-wide map from (block, local) to value when the cache entry is overwritten.+//! A read that finds neither walks the predecessors, with an explicit stack, memoizing what it finds; reads in an+//! unsealed loop header make incomplete phis.+//! - Phis that turn out trivial become `Forward` nodes. Cleanup removes the rest of them, to a fixed point.+//!+//! The operand stack holds values; values flowing into merges become explicit phis, as the block types say.+//! Unreachable code is skipped, only tracking nesting. Nodes fold as they are created (`fold`), and pure nodes are+//! value numbered in a table whose entries are undone when the construct that made them ends, so that every hit+//! dominates its use. Global values are numbered too, keyed by epochs that `global.set` and calls advance.++mod calls;+pub mod fold;+mod simd;+mod tables;++use crate::CompileFailure;+use crate::decode::{BlockType, Decoder, Instruction};+use crate::ir::{BlockId, Func, IntCondition, LoadKind, Loop, NONE, Node, Op, Type, Value};+use crate::ir::{FLAG_IMMUTABLE, FloatCondition};+use crate::table::Table;+use calls::CallKind;+use fold::Folded;+use libwasm_module::Module;+use libwasm_module::abi::{InstanceData, TRAP_NULL_REFERENCE};+use libwasm_module::opcode;+use libwasm_module::quickening;+use libwasm_module::types::{FuncType, ValType};+use std::mem::offset_of;++/// The IR type of a WebAssembly value type, if the JIT compiles values of it.+pub fn ir_type(value: ValType) -> Option<Type> {+ match value {+ ValType::I32 => Some(Type::I32),+ ValType::I64 => Some(Type::I64),+ ValType::F32 => Some(Type::F32),+ ValType::F64 => Some(Type::F64),+ ValType::V128 => Some(Type::V128),+ ValType::Ref(_) => Some(Type::Ref),+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ControlKind {+ Function,+ Block,+ Loop,+ If,+ Else,+}++/// The parameter and result types of a block, as ranges of `Builder::types`.+type Signature = ((u32, u32), (u32, u32));++/// A construct whose `end` is still ahead.+#[derive(Debug, Clone, Copy)]+struct Control {+ kind: ControlKind,+ /// The types of its parameters and results, in `Builder::types`.+ params: (u32, u32),+ results: (u32, u32),+ /// The height of the operand stack below its parameters.+ height: u32,+ /// The loop's header, or for `if` the block that branches on the condition.+ block: BlockId,+ /// The `else` edge of an `if`: its slot in `Func::successors`, or NONE once taken care of.+ else_slot: u32,+ /// For `if`, where its parameters start in `Builder::edge_values`, for the second arm.+ if_params: u32,+ /// The branches to the label, as a list through `Builder::edges`.+ edges: u32,+ /// The block that branched to the label last, so that a `br_table` adds one edge per block.+ last_edge_block: BlockId,+ /// Whether the rest of the construct is unreachable.+ unreachable: bool,+ /// Where the construct's entries start in the value numbering log.+ numbering_mark: u32,+ /// For loops, their index in `Func::loops` and the start of their incomplete phis.+ loop_index: u32,+ incomplete_start: u32,+}++impl Control {+ fn label_arity(&self) -> (u32, u32) {+ if self.kind == ControlKind::Loop {+ self.params+ } else {+ self.results+ }+ }+}++/// A branch to a label whose block may not exist yet: its source, the successor slot to fill, and the values it+/// carries, in `Builder::edge_values`.+#[derive(Debug, Clone, Copy)]+struct Edge {+ block: BlockId,+ slot: u32,+ values: u32,+ next: u32,+}++/// The key of a value numbering entry: a node's op, type and flags, then its arguments.+type NumberingKey = [u32; 4];++fn numbering_key(node: &Node) -> NumberingKey {+ [+ node.op as u32 | ((node.ty as u32) << 16) | (u32::from(node.flags) << 24),+ node.args[0],+ node.args[1],+ node.args[2],+ ]+}++/// A node of the explicit stack that `read_local_slow` walks predecessors with.+#[derive(Debug, Clone, Copy)]+struct ReadFrame {+ block: BlockId,+ /// The phi whose inputs are being read, or NONE.+ phi: Value,+ /// Where in `read_values` the values of the predecessors read so far start, for a merge whose phi is only made+ /// if they differ, or NONE.+ collected: u32,+ next_predecessor: u32,+}++/// The builder's state, kept between compiles so that its storage is reused.+#[derive(Default)]+pub struct Builder {+ local_types: Vec<Type>,+ /// The last definition of each local and its block.+ current: Vec<(BlockId, Value)>,+ definitions: Table<u64>,+ /// The locals each loop writes, itself or in loops in it: keyed by (loop, local), and as a list per loop of+ /// (local, next entry) from its entry in `loop_write_heads`.+ loop_writes: Table<u64>,+ loop_write_list: Vec<(u32, u32)>,+ loop_write_heads: Vec<u32>,+ sealed: Vec<bool>,+ /// (header, phi, local) of every incomplete phi of an unsealed loop header.+ incomplete: Vec<(BlockId, Value, u32)>,+ stack: Vec<Value>,+ controls: Vec<Control>,+ edges: Vec<Edge>,+ edge_values: Vec<Value>,+ types: Vec<Type>,+ /// Value numbers, and constants, which are never undone. A value of NONE is no entry.+ numbering: Table<NumberingKey>,+ numbering_log: Vec<(NumberingKey, Value)>,+ global_epochs: Vec<u32>,+ call_epoch: u32,+ read_stack: Vec<ReadFrame>,+ read_values: Vec<Value>,+ scratch_values: Vec<Value>,+ scratch_blocks: Vec<BlockId>,+ params: Vec<Value>,+ current_block: BlockId,+ instance: Value,+ memory_base: Value,+ /// The zero vector, which every v128 local starts as, once made.+ vector_zero: Value,+}++fn key(block: BlockId, local: u32) -> u64 {+ (u64::from(block) << 32) | u64::from(local)+}++fn unsupported<T>(pc: usize, what: &'static str) -> Result<T, CompileFailure> {+ Err(CompileFailure::Unsupported { pc: pc as u32, what })+}++fn instance_offset(offset: usize) -> u32 {+ offset as u32+}++impl Builder {+ fn clear(&mut self) {+ self.local_types.clear();+ self.current.clear();+ self.definitions.clear();+ self.loop_writes.clear();+ self.loop_write_list.clear();+ self.loop_write_heads.clear();+ self.sealed.clear();+ self.incomplete.clear();+ self.stack.clear();+ self.controls.clear();+ self.edges.clear();+ self.edge_values.clear();+ self.types.clear();+ self.numbering.clear();+ self.numbering_log.clear();+ self.global_epochs.clear();+ self.call_epoch = 0;+ self.read_stack.clear();+ self.read_values.clear();+ self.params.clear();+ self.vector_zero = NONE;+ }++ /// Builds the IR of the defined function `index` (counting imports) of `module` into `func`.+ pub fn build(&mut self, module: &Module, index: u32, func: &mut Func) -> Result<(), CompileFailure> {+ self.clear();+ func.clear();+ let defined = (index - module.imported_function_count) as usize;+ let body = &module.code[defined];+ let ty = module.function_type(index).expect("functions have function types");+ let start = body.code.start as usize;+ for ¶m in &ty.params {+ let Some(param) = ir_type(param) else {+ return unsupported(start, "a parameter of a type the JIT does not compile");+ };+ func.params.push(param);+ self.local_types.push(param);+ }+ for &result in &ty.results {+ let Some(result) = ir_type(result) else {+ return unsupported(start, "a result of a type the JIT does not compile");+ };+ func.results.push(result);+ }+ for &(count, local) in &body.locals {+ let Some(local) = ir_type(local) else {+ return unsupported(start, "a local of a type the JIT does not compile");+ };+ self.local_types.extend(std::iter::repeat_n(local, count as usize));+ }+ self.current.resize(self.local_types.len(), (NONE, NONE));+ self.global_epochs.resize(module.global_space.len(), 0);++ let entry = self.new_block(func);+ self.start_block(func, entry);+ self.sealed[entry as usize] = true;+ self.instance = self.entry_value(func, Op::Instance, Type::Pointer, 0);+ self.memory_base = self.entry_value(func, Op::MemoryBase, Type::Pointer, 0);+ for (param_index, ¶m) in func.params.clone().iter().enumerate() {+ let value = self.entry_value(func, Op::Param, param, param_index as u32);+ self.params.push(value);+ }+ let results = self.push_types(&ty.results)?;+ self.controls.push(Control {+ kind: ControlKind::Function,+ params: (0, 0),+ results,+ height: 0,+ block: entry,+ else_slot: NONE,+ if_params: 0,+ edges: NONE,+ last_edge_block: NONE,+ unreachable: false,+ numbering_mark: 0,+ loop_index: NONE,+ incomplete_start: 0,+ });++ let mut decoder = Decoder::new(&module.bytes, start, body.code.end as usize);+ while !self.controls.is_empty() {+ let pc = decoder.position();+ let instruction = decoder.decode();+ if self.controls.last().expect("there is a construct").unreachable {+ self.skip(func, module, &instruction, &mut decoder, pc)?;+ continue;+ }+ self.instruction(func, module, instruction, &decoder, pc)?;+ }+ Ok(())+ }++ // Blocks.++ fn new_block(&mut self, func: &mut Func) -> BlockId {+ let block = func.blocks.len() as BlockId;+ let loop_index = self+ .controls+ .iter()+ .rev()+ .find(|control| control.kind == ControlKind::Loop)+ .map_or(NONE, |control| control.loop_index);+ func.blocks.push(crate::ir::Block {+ loop_index,+ ..Default::default()+ });+ self.sealed.push(true);+ block+ }++ fn start_block(&mut self, func: &mut Func, block: BlockId) {+ func.blocks[block as usize].start = func.nodes.len() as u32;+ self.current_block = block;+ }++ fn set_predecessors(func: &mut Func, block: BlockId, predecessors: &[BlockId]) {+ let data = &mut func.blocks[block as usize];+ data.predecessors_start = func.predecessors.len() as u32;+ data.predecessor_count = predecessors.len() as u32;+ func.predecessors.extend_from_slice(predecessors);+ }++ /// Ends the current block with `node`, whose successors are `successors` (NONE for those not known yet).+ /// Returns the slot of the first successor.+ fn terminate(&mut self, func: &mut Func, node: Node, successors: &[BlockId]) -> u32 {+ func.nodes.push(node);+ let slot = func.successors.len() as u32;+ let block = &mut func.blocks[self.current_block as usize];+ block.end = func.nodes.len() as u32;+ block.successors_start = slot;+ block.successor_count = successors.len() as u32;+ func.successors.extend_from_slice(successors);+ slot+ }++ // Nodes.++ fn append(func: &mut Func, node: Node) -> Value {+ func.nodes.push(node);+ func.nodes.len() as Value - 1+ }++ fn entry_value(&mut self, func: &mut Func, op: Op, ty: Type, argument: u32) -> Value {+ Self::append(func, Node::new(op, ty, 0, [argument, 0, 0]))+ }++ fn constant(&mut self, func: &mut Func, ty: Type, bits: u64) -> Value {+ if ty == Type::V128 {+ if self.vector_zero == NONE {+ self.vector_zero = self.vector_constant(func, u128::from(bits));+ }+ debug_assert_eq!(bits, 0);+ return self.vector_zero;+ }+ let node = if ty.is_64() {+ Node::new(Op::Const64, ty, 0, [bits as u32, (bits >> 32) as u32, 0])+ } else {+ Node::new(Op::Const32, ty, 0, [bits as u32, 0, 0])+ };+ let key = numbering_key(&node);+ if let Some(value) = self.numbering.get(key) {+ return value;+ }+ let value = Self::append(func, node);+ // NB: Constants have no position, so they are never undone.+ self.numbering.insert(key, value);+ value+ }++ /// The value a forwarded phi stands for.+ fn resolve(func: &Func, mut value: Value) -> Value {+ while func.nodes[value as usize].op == Op::Forward {+ value = func.nodes[value as usize].args[0];+ }+ value+ }++ /// A pure node, or the value of an equal one that dominates the current position.+ fn pure(&mut self, func: &mut Func, node: Node) -> Value {+ let key = numbering_key(&node);+ if let Some(value) = self.numbering.get(key)+ && value != NONE+ {+ return value;+ }+ let value = Self::append(func, node);+ self.number(key, value);+ value+ }++ fn number(&mut self, key: NumberingKey, value: Value) {+ let previous = self.numbering.insert(key, value).unwrap_or(NONE);+ self.numbering_log.push((key, previous));+ }++ /// Undoes the value numbering entries made since `mark`.+ fn unnumber(&mut self, mark: u32) {+ while self.numbering_log.len() > mark as usize {+ let (key, previous) = self.numbering_log.pop().expect("the log is longer than the mark");+ self.numbering.insert(key, previous);+ }+ }++ fn binary(&mut self, func: &mut Func, op: Op, ty: Type, a: Value, b: Value) -> Value {+ self.binary_with_flags(func, op, ty, 0, a, b)+ }++ fn binary_with_flags(&mut self, func: &mut Func, op: Op, ty: Type, flags: u8, a: Value, b: Value) -> Value {+ let (a, b) = (Self::resolve(func, a), Self::resolve(func, b));+ let result_type = if op == Op::Compare { Type::I32 } else { ty };+ match fold::binary(func, op, ty, flags, a, b) {+ Folded::Value(value) => value,+ Folded::Constant(bits) => self.constant(func, result_type, bits),+ Folded::Node { op, flags, a, b } => {+ let node = Node::new(op, result_type, flags, [a, b, 0]);+ if node.effect() == crate::ir::Effect::Pure {+ self.pure(func, node)+ } else {+ Self::append(func, node)+ }+ }+ }+ }++ fn unary(&mut self, func: &mut Func, op: Op, ty: Type, a: Value) -> Value {+ let a = Self::resolve(func, a);+ match fold::unary(func, op, ty, a) {+ Some(Folded::Value(value)) => value,+ Some(Folded::Constant(bits)) => self.constant(func, ty, bits),+ Some(Folded::Node { op, flags, a, b }) => self.pure(func, Node::new(op, ty, flags, [a, b, 0])),+ None => {+ let node = Node::new(op, ty, 0, [a, 0, 0]);+ if node.effect() == crate::ir::Effect::Pure {+ self.pure(func, node)+ } else {+ Self::append(func, node)+ }+ }+ }+ }++ // Locals (see the module documentation).++ fn write_local(&mut self, local: u32, value: Value) {+ let (block, previous) = self.current[local as usize];+ if block != self.current_block && block != NONE {+ self.definitions.insert(key(block, local), previous);+ }+ self.current[local as usize] = (self.current_block, value);+ }++ fn note_loop_write(&mut self, loop_index: u32, local: u32) {+ if loop_index == NONE || self.loop_writes.insert(key(loop_index, local), 1).is_some() {+ return;+ }+ if self.loop_write_heads.len() <= loop_index as usize {+ self.loop_write_heads.resize(loop_index as usize + 1, NONE);+ }+ let next = self.loop_write_heads[loop_index as usize];+ self.loop_write_heads[loop_index as usize] = self.loop_write_list.len() as u32;+ self.loop_write_list.push((local, next));+ }++ /// Counts the locals a loop that has ended writes as written by the loop around it.+ fn propagate_loop_writes(&mut self, func: &Func, loop_index: u32) {+ let parent = func.loops[loop_index as usize].parent;+ let mut entry = self.loop_write_heads.get(loop_index as usize).copied().unwrap_or(NONE);+ while entry != NONE && parent != NONE {+ let (local, next) = self.loop_write_list[entry as usize];+ self.note_loop_write(parent, local);+ entry = next;+ }+ }++ /// Records `value` as the value of `local` at the end of `block`.+ fn memoize(&mut self, block: BlockId, local: u32, value: Value) {+ if block == self.current_block {+ self.write_local(local, value);+ } else {+ self.definitions.insert(key(block, local), value);+ }+ }++ fn lookup(&self, func: &Func, block: BlockId, local: u32) -> Option<Value> {+ let (cached_block, value) = self.current[local as usize];+ if cached_block == block {+ return Some(Self::resolve(func, value));+ }+ self.definitions+ .get(key(block, local))+ .map(|value| Self::resolve(func, value))+ }++ fn read_local(&mut self, func: &mut Func, block: BlockId, local: u32) -> Value {+ if let Some(value) = self.lookup(func, block, local) {+ return value;+ }+ self.read_local_slow(func, block, local)+ }++ fn new_phi(func: &mut Func, block: BlockId, ty: Type) -> Value {+ let first = func.blocks[block as usize].first_phi;+ let phi = Self::append(func, Node::new(Op::Phi, ty, 0, [0, 0, first]));+ func.blocks[block as usize].first_phi = phi;+ phi+ }++ /// The value of a local that a block is entered with: a parameter, or zero.+ fn initial_value(&mut self, func: &mut Func, local: u32) -> Value {+ if (local as usize) < self.params.len() {+ return self.params[local as usize];+ }+ let ty = self.local_types[local as usize];+ self.constant(func, ty, 0)+ }++ /// Whether a read of a local can be on a cycle through `block`: only if the block is in a loop whose header is+ /// sealed, so that reads go around the back edges.+ fn may_be_on_cycle(&self, func: &Func, block: BlockId) -> bool {+ let loop_index = func.blocks[block as usize].loop_index;+ loop_index != NONE && self.sealed[func.loops[loop_index as usize].header as usize]+ }++ fn read_local_slow(&mut self, func: &mut Func, block: BlockId, local: u32) -> Value {+ let ty = self.local_types[local as usize];+ let base = self.read_stack.len();+ self.read_stack.push(ReadFrame {+ block,+ phi: NONE,+ collected: NONE,+ next_predecessor: 0,+ });+ // The value the frame on top of the stack delivers, if it is done.+ let mut delivered: Option<Value> = None;+ loop {+ let top = self.read_stack.len() - 1;+ if let Some(value) = delivered.take() {+ let frame = &mut self.read_stack[top];+ if frame.collected != NONE {+ self.read_values.push(value);+ frame.next_predecessor += 1;+ } else if frame.phi != NONE {+ let phi = func.nodes[frame.phi as usize];+ func.operands[(phi.args[0] + frame.next_predecessor) as usize] = value;+ frame.next_predecessor += 1;+ } else {+ let frame_block = frame.block;+ self.read_stack.pop();+ self.memoize(frame_block, local, value);+ if self.read_stack.len() == base {+ return value;+ }+ delivered = Some(value);+ continue;+ }+ }+ let frame = self.read_stack[top];+ if frame.phi != NONE || frame.collected != NONE {+ let predecessors = func.predecessors(frame.block);+ if (frame.next_predecessor as usize) < predecessors.len() {+ let predecessor = predecessors[frame.next_predecessor as usize];+ if let Some(value) = self.lookup(func, predecessor, local) {+ delivered = Some(value);+ } else {+ self.read_stack.push(ReadFrame {+ block: predecessor,+ phi: NONE,+ collected: NONE,+ next_predecessor: 0,+ });+ }+ continue;+ }+ self.read_stack.pop();+ let value = if frame.phi != NONE {+ let value = Self::try_remove_trivial_phi(func, frame.phi);+ if value != frame.phi {+ self.memoize(frame.block, local, value);+ }+ value+ } else {+ let value = self.merge_collected(func, frame.block, ty, frame.collected);+ self.memoize(frame.block, local, value);+ value+ };+ if self.read_stack.len() == base {+ return value;+ }+ delivered = Some(value);+ continue;+ }+ // A frame visited for the first time.+ if let Some(value) = self.lookup(func, frame.block, local) {+ delivered = Some(value);+ continue;+ }+ if !self.sealed[frame.block as usize] {+ let phi = Self::new_phi(func, frame.block, ty);+ self.incomplete.push((frame.block, phi, local));+ delivered = Some(phi);+ continue;+ }+ let loop_index = func.blocks[frame.block as usize].loop_index;+ if self.may_be_on_cycle(func, frame.block) && self.loop_writes.get(key(loop_index, local)).is_none() {+ // OPTIMIZATION: Everywhere in a loop that does not write the local, it has the value it entered+ // the loop with. Reads after a loop would otherwise go around all of it.+ let header = func.loops[loop_index as usize].header;+ let entry = func.predecessors(header)[0];+ if let Some(value) = self.lookup(func, entry, local) {+ delivered = Some(value);+ } else {+ self.read_stack.push(ReadFrame {+ block: entry,+ phi: NONE,+ collected: NONE,+ next_predecessor: 0,+ });+ }+ continue;+ }+ let predecessors = func.predecessors(frame.block);+ match predecessors.len() {+ 0 => {+ let value = self.initial_value(func, local);+ delivered = Some(value);+ }+ 1 => {+ let predecessor = predecessors[0];+ if let Some(value) = self.lookup(func, predecessor, local) {+ delivered = Some(value);+ } else {+ self.read_stack.push(ReadFrame {+ block: predecessor,+ phi: NONE,+ collected: NONE,+ next_predecessor: 0,+ });+ }+ }+ // OPTIMIZATION: Where no read can come back around to the block, its phi is only made if the+ // predecessors' values differ. Most merges of large functions need no phi for most locals, and+ // making and forwarding them took most of the build time of such functions.+ _ if !self.may_be_on_cycle(func, frame.block) => {+ self.read_stack[top].collected = self.read_values.len() as u32;+ }+ count => {+ let phi = Self::new_phi(func, frame.block, ty);+ let start = func.operands.len() as u32;+ func.operands.extend(std::iter::repeat_n(phi, count));+ func.nodes[phi as usize].args[0] = start;+ func.nodes[phi as usize].args[1] = count as u32;+ // NB: Memoized before its inputs are read, so that cycles through it end at it.+ self.memoize(frame.block, local, phi);+ self.read_stack[top].phi = phi;+ }+ }+ }+ }++ /// The value of a local at the start of `block`, given its predecessors' values in `read_values` from `start`+ /// on, which it removes: their value if they are all the same, else a new phi of them.+ fn merge_collected(&mut self, func: &mut Func, block: BlockId, ty: Type, start: u32) -> Value {+ let values = &self.read_values[start as usize..];+ let first = Self::resolve(func, values[0]);+ let value = if values[1..].iter().all(|value| Self::resolve(func, *value) == first) {+ first+ } else {+ let phi = Self::new_phi(func, block, ty);+ let operands = func.operands.len() as u32;+ func.operands.extend_from_slice(values);+ func.nodes[phi as usize].args[0] = operands;+ func.nodes[phi as usize].args[1] = values.len() as u32;+ phi+ };+ self.read_values.truncate(start as usize);+ value+ }++ /// Forwards `phi` if its inputs are only itself and one other value, which it returns; returns `phi` otherwise.+ fn try_remove_trivial_phi(func: &mut Func, phi: Value) -> Value {+ let mut same = NONE;+ for &input in func.inputs(phi) {+ let input = Self::resolve(func, input);+ if input == phi || input == same {+ continue;+ }+ if same != NONE {+ return phi;+ }+ same = input;+ }+ if same == NONE {+ // Only reachable through itself: the loop is never entered with a value for it.+ return phi;+ }+ let node = &mut func.nodes[phi as usize];+ node.op = Op::Forward;+ node.args[0] = same;+ node.args[1] = 0;+ same+ }++ // Types and labels.++ fn push_types(&mut self, types: &[ValType]) -> Result<(u32, u32), CompileFailure> {+ let start = self.types.len() as u32;+ for &ty in types {+ let Some(ty) = ir_type(ty) else {+ return Err(CompileFailure::Unsupported {+ pc: 0,+ what: "a block of a type the JIT does not compile",+ });+ };+ self.types.push(ty);+ }+ Ok((start, types.len() as u32))+ }++ fn block_signature(&mut self, module: &Module, block_type: BlockType) -> Result<Signature, CompileFailure> {+ match block_type {+ BlockType::Empty => Ok(((0, 0), (0, 0))),+ BlockType::Value(value) => Ok(((0, 0), self.push_types(&[value])?)),+ BlockType::Function(index) => {+ let function: &FuncType = module.types[index as usize]+ .as_func()+ .expect("block types are functions");+ let params = self.push_types(&function.params)?;+ let results = self.push_types(&function.results)?;+ Ok((params, results))+ }+ }+ }++ /// Records a branch from the current block to the label of `controls[index]`, carrying the top values of the+ /// stack, through the successor `slot`.+ fn add_edge(&mut self, index: usize, slot: u32) {+ let control = self.controls[index];+ let (_, arity) = control.label_arity();+ let values = self.edge_values.len() as u32;+ let top = self.stack.len() - arity as usize;+ self.edge_values.extend_from_slice(&self.stack[top..]);+ self.edges.push(Edge {+ block: self.current_block,+ slot,+ values,+ next: control.edges,+ });+ let control = &mut self.controls[index];+ control.edges = self.edges.len() as u32 - 1;+ control.last_edge_block = self.current_block;+ }++ /// Collects the edges of a label in the order they were made, which is linear order, into `scratch_blocks`+ /// (their blocks) and returns the edges' indices in `scratch_values`.+ fn collect_edges(&mut self, head: u32) {+ self.scratch_blocks.clear();+ self.scratch_values.clear();+ let mut edge = head;+ while edge != NONE {+ self.scratch_values.push(edge);+ edge = self.edges[edge as usize].next;+ }+ self.scratch_values.reverse();+ for &edge in &self.scratch_values {+ self.scratch_blocks.push(self.edges[edge as usize].block);+ }+ }++ fn is_unreachable(&self) -> bool {+ self.controls.last().is_some_and(|control| control.unreachable)+ }++ fn set_unreachable(&mut self) {+ let control = self.controls.last_mut().expect("there is a construct");+ control.unreachable = true;+ self.stack.truncate(control.height as usize);+ }++ // Instructions.++ fn pop(&mut self) -> Value {+ self.stack.pop().expect("validated code does not underflow the stack")+ }++ fn push(&mut self, value: Value) {+ self.stack.push(value);+ }++ fn skip(+ &mut self,+ func: &mut Func,+ module: &Module,+ instruction: &Instruction,+ decoder: &mut Decoder<'_>,+ pc: usize,+ ) -> Result<(), CompileFailure> {+ match instruction {+ Instruction::Else | Instruction::End => 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;+ while depth > 0 {+ depth += crate::decode::nesting_change(&decoder.decode());+ }+ Ok(())+ }+ _ => Ok(()),+ }+ }++ fn instruction(+ &mut self,+ func: &mut Func,+ module: &Module,+ instruction: Instruction,+ decoder: &Decoder<'_>,+ pc: usize,+ ) -> Result<(), CompileFailure> {+ use Instruction as I;+ match instruction {+ I::Nop => {}+ I::Unreachable => {+ self.terminate(+ func,+ Node::new(Op::Trap, Type::None, 0, [libwasm_module::abi::TRAP_UNREACHABLE, 0, 0]),+ &[],+ );+ self.set_unreachable();+ }+ I::Block(block_type) => {+ let (params, results) = self.block_signature(module, block_type)?;+ self.push_control(ControlKind::Block, params, results, NONE);+ }+ I::Loop(block_type) => {+ let (params, results) = self.block_signature(module, block_type)?;+ self.begin_loop(func, params, results);+ }+ I::If(block_type) => {+ let (params, results) = self.block_signature(module, block_type)?;+ self.begin_if(func, params, results);+ }+ I::Else => self.begin_else(func),+ I::End => self.end(func),+ I::Br(depth) => {+ self.branch(func, depth);+ self.set_unreachable();+ }+ I::BrIf(depth) => {+ let condition = Self::resolve(func, self.pop());+ self.conditional_branch(func, depth, condition);+ }+ I::BrTable { .. } => {+ let index = Self::resolve(func, self.pop());+ self.branch_table(func, index, decoder.targets());+ self.set_unreachable();+ }+ I::Return => {+ let depth = self.controls.len() as u32 - 1;+ self.branch(func, depth);+ self.set_unreachable();+ }+ I::Call(function) => self.call(func, module, function, CallKind::Normal, pc)?,+ I::Drop => {+ self.pop();+ }+ I::Select | I::SelectTyped(_) => {+ let condition = Self::resolve(func, self.pop());+ let if_false = Self::resolve(func, self.pop());+ let if_true = Self::resolve(func, self.pop());+ let value = match func.node(condition).constant() {+ Some(0) => if_false,+ Some(_) => if_true,+ None if if_true == if_false => if_true,+ None => {+ let ty = func.node(if_true).ty;+ self.pure(func, Node::new(Op::Select, ty, 0, [condition, if_true, if_false]))+ }+ };+ self.push(value);+ }+ I::LocalGet(local) => {+ let block = self.current_block;+ let value = self.read_local(func, block, local);+ self.push(value);+ }+ I::LocalSet(local) => {+ let value = Self::resolve(func, self.pop());+ self.write_local(local, value);+ self.note_loop_write(func.blocks[self.current_block as usize].loop_index, local);+ }+ I::LocalTee(local) => {+ let value = Self::resolve(func, *self.stack.last().expect("validated code has an operand"));+ self.write_local(local, value);+ self.note_loop_write(func.blocks[self.current_block as usize].loop_index, local);+ }+ I::GlobalGet(global) => self.global_get(func, module, global, pc)?,+ I::GlobalSet(global) => self.global_set(func, global),+ I::Access { opcode, argument } => {+ debug_assert_eq!(argument.memory, 0, "plain accesses are of memory 0");+ let offset = argument.offset as u32;+ if opcode <= opcode::I64_LOAD32_U {+ let (kind, ty) = load_kind(opcode);+ let index = Self::resolve(func, self.pop());+ let value = Self::append(+ func,+ Node::new(Op::Load, ty, kind as u8, [self.memory_base, index, offset]),+ );+ self.push(value);+ } else {+ let value = Self::resolve(func, self.pop());+ let index = Self::resolve(func, self.pop());+ let size_log2 = store_size_log2(opcode);+ let start = func.operands.len() as u32;+ func.operands.extend_from_slice(&[self.memory_base, index, value]);+ Self::append(func, Node::new(Op::Store, Type::None, size_log2, [start, 3, offset]));+ }+ }+ I::I32Const(value) => {+ let value = self.constant(func, Type::I32, u64::from(value as u32));+ self.push(value);+ }+ I::I64Const(value) => {+ let value = self.constant(func, Type::I64, value as u64);+ self.push(value);+ }+ I::F32Const(bits) => {+ let value = self.constant(func, Type::F32, u64::from(bits));+ self.push(value);+ }+ I::F64Const(bits) => {+ let value = self.constant(func, Type::F64, bits);+ self.push(value);+ }+ I::Numeric(opcode) => self.numeric(func, opcode),+ I::Misc(sub_opcode) if sub_opcode <= opcode::misc::I64_TRUNC_SAT_F64_U => {+ let (op, ty) = match sub_opcode {+ opcode::misc::I32_TRUNC_SAT_F32_S | opcode::misc::I32_TRUNC_SAT_F64_S => (Op::TruncSatS, Type::I32),+ opcode::misc::I32_TRUNC_SAT_F32_U | opcode::misc::I32_TRUNC_SAT_F64_U => (Op::TruncSatU, Type::I32),+ opcode::misc::I64_TRUNC_SAT_F32_S | opcode::misc::I64_TRUNC_SAT_F64_S => (Op::TruncSatS, Type::I64),+ _ => (Op::TruncSatU, Type::I64),+ };+ let a = Self::resolve(func, self.pop());+ 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::MemorySize(memory) => self.memory_size(func, module, memory),+ I::MemoryGrow(memory) => self.memory_grow(func, module, memory),+ I::CallIndirect { type_index, table } => {+ self.call_indirect(func, module, type_index, table, CallKind::Normal, pc)?;+ }+ I::CallRef(type_index) => self.call_ref(func, module, type_index, CallKind::Normal, pc)?,+ I::ReturnCall(function) => self.call(func, module, function, CallKind::Tail, pc)?,+ I::ReturnCallIndirect { type_index, table } => {+ self.call_indirect(func, module, type_index, table, CallKind::Tail, pc)?;+ }+ I::ReturnCallRef(type_index) => self.call_ref(func, module, type_index, CallKind::Tail, pc)?,+ I::Throw(_) | I::ThrowRef | I::TryTable(_) => return unsupported(pc, "exception handling"),+ I::TableGet(table) => self.table_get(func, table),+ I::TableSet(table) => self.table_set(func, table),+ I::RefNull(_) => {+ let value = self.constant(func, Type::Ref, 0);+ self.push(value);+ }+ I::RefIsNull => {+ let a = self.pop();+ let value = self.unary(func, Op::Eqz, Type::I32, a);+ self.push(value);+ }+ I::RefEq => {+ let b = self.pop();+ let a = self.pop();+ let value = self.binary_with_flags(func, Op::Compare, Type::Ref, IntCondition::Eq as u8, a, b);+ self.push(value);+ }+ I::RefFunc(function) => {+ let value = self.function_reference(func, function);+ self.push(value);+ }+ I::RefAsNonNull => {+ let reference = Self::resolve(func, self.pop());+ Self::append(+ func,+ Node::new(Op::CheckNull, Type::None, TRAP_NULL_REFERENCE as u8, [reference, 0, 0]),+ );+ self.push(reference);+ }+ I::BrOnNull(depth) => {+ let reference = Self::resolve(func, self.pop());+ let is_null = self.unary(func, Op::Eqz, Type::I32, reference);+ self.conditional_branch(func, depth, is_null);+ if !self.is_unreachable() {+ self.push(reference);+ }+ }+ I::BrOnNonNull(depth) => {+ let reference = Self::resolve(func, *self.stack.last().expect("br_on_non_null has an operand"));+ let null = self.constant(func, Type::Ref, 0);+ let is_not_null =+ self.binary_with_flags(func, Op::Compare, Type::Ref, IntCondition::Ne as u8, reference, null);+ self.conditional_branch(func, depth, is_not_null);+ if !self.is_unreachable() {+ self.pop();+ }+ }+ I::Misc(sub_opcode) => self.bulk(func, module, sub_opcode, decoder.misc_indices()),+ I::Gc(_) => return unsupported(pc, "a GC instruction"),+ I::Vector { opcode, index } => {+ let plain = match opcode {+ quickening::LOCAL_GET_V128 => I::LocalGet(index),+ quickening::LOCAL_SET_V128 => I::LocalSet(index),+ quickening::LOCAL_TEE_V128 => I::LocalTee(index),+ quickening::GLOBAL_GET_V128 => I::GlobalGet(index),+ quickening::GLOBAL_SET_V128 => I::GlobalSet(index),+ quickening::DROP_V128 => I::Drop,+ _ => I::Select,+ };+ 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"),+ }+ Ok(())+ }++ fn numeric(&mut self, func: &mut Func, opcode: u8) {+ use Op::*;+ use Type::{F32, F64, I32, I64};+ let (op, ty, flags, arity) = match opcode {+ opcode::I32_EQZ => (Eqz, I32, 0, 1),+ opcode::I64_EQZ => (Eqz, I32, 0, 1),+ 0x46..=0x4f => (Compare, I32, opcode - 0x46, 2),+ 0x51..=0x5a => (Compare, I64, opcode - 0x51, 2),+ 0x5b..=0x60 => (FloatCompare, F32, opcode - 0x5b, 2),+ 0x61..=0x66 => (FloatCompare, F64, opcode - 0x61, 2),+ opcode::I32_CLZ => (Clz, I32, 0, 1),+ opcode::I32_CTZ => (Ctz, I32, 0, 1),+ opcode::I32_POPCNT => (Popcnt, I32, 0, 1),+ 0x6a..=0x78 => (INTEGER_BINARY[(opcode - 0x6a) as usize], I32, 0, 2),+ opcode::I64_CLZ => (Clz, I64, 0, 1),+ opcode::I64_CTZ => (Ctz, I64, 0, 1),+ opcode::I64_POPCNT => (Popcnt, I64, 0, 1),+ 0x7c..=0x8a => (INTEGER_BINARY[(opcode - 0x7c) as usize], I64, 0, 2),+ 0x8b..=0x91 => (FLOAT_UNARY[(opcode - 0x8b) as usize], F32, 0, 1),+ 0x92..=0x98 => (FLOAT_BINARY[(opcode - 0x92) as usize], F32, 0, 2),+ 0x99..=0x9f => (FLOAT_UNARY[(opcode - 0x99) as usize], F64, 0, 1),+ 0xa0..=0xa6 => (FLOAT_BINARY[(opcode - 0xa0) as usize], F64, 0, 2),+ opcode::I32_WRAP_I64 => (Wrap, I32, 0, 1),+ opcode::I32_TRUNC_F32_S | opcode::I32_TRUNC_F64_S => (TruncS, I32, 0, 1),+ opcode::I32_TRUNC_F32_U | opcode::I32_TRUNC_F64_U => (TruncU, I32, 0, 1),+ opcode::I64_EXTEND_I32_S => (ExtendI32S, I64, 0, 1),+ opcode::I64_EXTEND_I32_U => (ExtendI32U, I64, 0, 1),+ opcode::I64_TRUNC_F32_S | opcode::I64_TRUNC_F64_S => (TruncS, I64, 0, 1),+ opcode::I64_TRUNC_F32_U | opcode::I64_TRUNC_F64_U => (TruncU, I64, 0, 1),+ opcode::F32_CONVERT_I32_S | opcode::F32_CONVERT_I64_S => (ConvertS, F32, 0, 1),+ opcode::F32_CONVERT_I32_U | opcode::F32_CONVERT_I64_U => (ConvertU, F32, 0, 1),+ opcode::F32_DEMOTE_F64 => (Demote, F32, 0, 1),+ opcode::F64_CONVERT_I32_S | opcode::F64_CONVERT_I64_S => (ConvertS, F64, 0, 1),+ opcode::F64_CONVERT_I32_U | opcode::F64_CONVERT_I64_U => (ConvertU, F64, 0, 1),+ opcode::F64_PROMOTE_F32 => (Promote, F64, 0, 1),+ opcode::I32_REINTERPRET_F32 => (Reinterpret, I32, 0, 1),+ opcode::I64_REINTERPRET_F64 => (Reinterpret, I64, 0, 1),+ opcode::F32_REINTERPRET_I32 => (Reinterpret, F32, 0, 1),+ opcode::F64_REINTERPRET_I64 => (Reinterpret, F64, 0, 1),+ opcode::I32_EXTEND8_S => (Extend8S, I32, 0, 1),+ opcode::I32_EXTEND16_S => (Extend16S, I32, 0, 1),+ opcode::I64_EXTEND8_S => (Extend8S, I64, 0, 1),+ opcode::I64_EXTEND16_S => (Extend16S, I64, 0, 1),+ opcode::I64_EXTEND32_S => (Extend32S, I64, 0, 1),+ _ => unreachable!("only numeric opcodes are numeric instructions"),+ };+ let value = if arity == 2 {+ let b = self.pop();+ let a = self.pop();+ match op {+ Compare => self.binary_with_flags(func, op, ty, flags, a, b),+ FloatCompare => {+ let (a, b) = (Self::resolve(func, a), Self::resolve(func, b));+ self.pure(func, Node::new(op, I32, flags, [a, b, 0]))+ }+ _ if ty.is_float() => {+ let (a, b) = (Self::resolve(func, a), Self::resolve(func, b));+ self.pure(func, Node::new(op, ty, 0, [a, b, 0]))+ }+ _ => self.binary(func, op, ty, a, b),+ }+ } else {+ let a = self.pop();+ if ty.is_float() || matches!(op, TruncS | TruncU | Reinterpret) {+ let a = Self::resolve(func, a);+ let node = Node::new(op, ty, 0, [a, 0, 0]);+ if node.effect() == crate::ir::Effect::Pure {+ self.pure(func, node)+ } else {+ Self::append(func, node)+ }+ } else {+ self.unary(func, op, ty, a)+ }+ };+ self.push(value);+ }++ // Control.++ fn push_control(&mut self, kind: ControlKind, params: (u32, u32), results: (u32, u32), block: BlockId) {+ let height = self.stack.len() as u32 - params.1;+ self.controls.push(Control {+ kind,+ params,+ results,+ height,+ block,+ else_slot: NONE,+ if_params: 0,+ edges: NONE,+ last_edge_block: NONE,+ unreachable: false,+ numbering_mark: self.numbering_log.len() as u32,+ loop_index: NONE,+ incomplete_start: self.incomplete.len() as u32,+ });+ }++ fn begin_loop(&mut self, func: &mut Func, params: (u32, u32), results: (u32, u32)) {+ let header = self.new_block(func);+ // NB: The header is created before the loop's control, so it takes the enclosing loop; fixed up below.+ self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[header]);+ let entry = self.current_block;+ self.sealed[header as usize] = false;+ let loop_index = func.loops.len() as u32;+ let parent = func.blocks[header as usize].loop_index;+ let depth = if parent == NONE {+ 0+ } else {+ func.loops[parent as usize].depth + 1+ };+ func.loops.push(Loop {+ header,+ last: header,+ parent,+ depth,+ });+ func.blocks[header as usize].loop_index = loop_index;+ self.push_control(ControlKind::Loop, params, results, header);+ let control = self.controls.last_mut().expect("the loop was just pushed");+ control.loop_index = loop_index;+ // The edge from the entry is the first, before every back edge.+ let values = self.edge_values.len() as u32;+ let height = control.height as usize;+ self.edge_values.extend_from_slice(&self.stack[height..]);+ self.edges.push(Edge {+ block: entry,+ slot: NONE,+ values,+ next: NONE,+ });+ let control = self.controls.last_mut().expect("the loop was just pushed");+ control.edges = self.edges.len() as u32 - 1;+ self.start_block(func, header);+ for index in 0..params.1 {+ let ty = self.types[(params.0 + index) as usize];+ let phi = Self::new_phi(func, header, ty);+ self.stack[height + index as usize] = phi;+ }+ // Calls and global.set in the body may change globals before the header runs again.+ self.call_epoch += 1;+ }++ fn begin_if(&mut self, func: &mut Func, params: (u32, u32), results: (u32, u32)) {+ let condition = Self::resolve(func, self.pop());+ let then_block = self.new_block(func);+ let slot = self.terminate(+ func,+ Node::new(Op::Branch, Type::None, 0, [condition, 0, 0]),+ &[then_block, NONE],+ );+ let if_block = self.current_block;+ self.push_control(ControlKind::If, params, results, if_block);+ let if_params = self.edge_values.len() as u32;+ let height = self.controls.last().expect("the if was just pushed").height as usize;+ self.edge_values.extend_from_slice(&self.stack[height..]);+ let control = self.controls.last_mut().expect("the if was just pushed");+ control.else_slot = slot + 1;+ control.if_params = if_params;+ Self::set_predecessors(func, then_block, &[if_block]);+ self.start_block(func, then_block);+ }++ fn begin_else(&mut self, func: &mut Func) {+ let index = self.controls.len() - 1;+ 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.unnumber(control.numbering_mark);+ self.stack.truncate(control.height as usize);+ let else_block = self.new_block(func);+ func.successors[control.else_slot as usize] = else_block;+ Self::set_predecessors(func, else_block, &[control.block]);+ self.start_block(func, else_block);+ let params = control.if_params as usize;+ for index in 0..control.params.1 as usize {+ let value = self.edge_values[params + index];+ self.stack.push(value);+ }+ let control = &mut self.controls[index];+ control.kind = ControlKind::Else;+ control.else_slot = NONE;+ control.unreachable = false;+ }++ fn end(&mut self, func: &mut Func) {+ let index = self.controls.len() - 1;+ let control = self.controls[index];+ match control.kind {+ ControlKind::Function => {+ if !control.unreachable {+ let depth = self.controls.len() as u32 - 1;+ self.branch(func, depth);+ }+ self.controls.pop();+ }+ ControlKind::Loop => self.end_loop(func, index),+ ControlKind::Block | ControlKind::If | ControlKind::Else => self.end_block(func, index),+ }+ }++ fn end_block(&mut self, func: &mut Func, index: usize) {+ let control = self.controls[index];+ let arity = control.results.1 as usize;+ if control.kind == ControlKind::If {+ // Without an else arm, the condition's false edge carries the parameters to the end.+ let values = self.edge_values.len() as u32;+ for offset in 0..control.params.1 {+ let value = self.edge_values[(control.if_params + offset) as usize];+ self.edge_values.push(value);+ }+ self.edges.push(Edge {+ block: control.block,+ slot: control.else_slot,+ values,+ next: control.edges,+ });+ self.controls[index].edges = self.edges.len() as u32 - 1;+ }+ let control = self.controls[index];+ let reachable = !control.unreachable;+ self.unnumber(control.numbering_mark);+ if control.edges == NONE {+ // Only the fallthrough, if anything, reaches the end: the current block goes on.+ self.controls.pop();+ if !reachable {+ self.set_unreachable();+ }+ return;+ }+ if reachable {+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ self.add_edge(index, slot);+ }+ let control = self.controls[index];+ self.stack.truncate(control.height as usize);+ self.collect_edges(control.edges);+ let merge = self.new_block(func);+ let predecessors = std::mem::take(&mut self.scratch_blocks);+ Self::set_predecessors(func, merge, &predecessors);+ self.scratch_blocks = predecessors;+ for &edge in &self.scratch_values {+ func.successors[self.edges[edge as usize].slot as usize] = merge;+ }+ self.start_block(func, merge);+ for result in 0..arity {+ let first = self.edge_values[self.edges[self.scratch_values[0] as usize].values as usize + result];+ let first = Self::resolve(func, first);+ let all_same = self.scratch_values.iter().all(|edge| {+ let value = self.edge_values[self.edges[*edge as usize].values as usize + result];+ Self::resolve(func, value) == first+ });+ if all_same {+ self.stack.push(first);+ continue;+ }+ let ty = self.types[(control.results.0 + result as u32) as usize];+ let phi = Self::new_phi(func, merge, ty);+ 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 + result];+ 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;+ self.stack.push(phi);+ }+ self.controls.pop();+ }++ fn end_loop(&mut self, func: &mut Func, index: usize) {+ let control = self.controls[index];+ let header = control.block;+ let reachable = !control.unreachable;+ // The back edges are the loop label's edges but the first, which enters the loop.+ self.collect_edges(control.edges);+ let predecessors = std::mem::take(&mut self.scratch_blocks);+ Self::set_predecessors(func, header, &predecessors);+ self.scratch_blocks = predecessors;+ self.sealed[header as usize] = true;+ self.propagate_loop_writes(func, control.loop_index);+ // The parameters' phis.+ let edge_list = std::mem::take(&mut self.scratch_values);+ let mut phi = func.blocks[header as usize].first_phi;+ let mut params = Vec::new();+ while phi != NONE {+ params.push(phi);+ phi = func.nodes[phi as usize].args[2];+ }+ // NB: Phis are linked newest first; the parameters' phis are the oldest ones, in reverse order.+ let param_phis = ¶ms[params.len() - control.params.1 as usize..];+ for (offset, &phi) in param_phis.iter().rev().enumerate() {+ let start = func.operands.len() as u32;+ for &edge in &edge_list {+ let value = self.edge_values[self.edges[edge as usize].values as usize + offset];+ func.operands.push(Self::resolve(func, value));+ }+ func.nodes[phi as usize].args[0] = start;+ func.nodes[phi as usize].args[1] = edge_list.len() as u32;+ }+ self.scratch_values = edge_list;+ // The locals' incomplete phis.+ let mut incomplete_index = control.incomplete_start as usize;+ while incomplete_index < self.incomplete.len() {+ let (block, phi, local) = self.incomplete[incomplete_index];+ if block != header {+ incomplete_index += 1;+ continue;+ }+ self.incomplete.swap_remove(incomplete_index);+ let count = func.predecessors(header).len();+ let start = func.operands.len() as u32;+ func.operands.extend(std::iter::repeat_n(phi, count));+ func.nodes[phi as usize].args[0] = start;+ func.nodes[phi as usize].args[1] = count as u32;+ for predecessor_index in 0..count {+ let predecessor = func.predecessors(header)[predecessor_index];+ let value = self.read_local(func, predecessor, local);+ func.operands[start as usize + predecessor_index] = value;+ }+ Self::try_remove_trivial_phi(func, phi);+ }+ for &phi in param_phis {+ Self::try_remove_trivial_phi(func, phi);+ }+ self.unnumber(control.numbering_mark);+ let height = control.height as usize;+ let results = control.results;+ self.controls.pop();+ if reachable {+ // NB: The code after the loop goes in a block of its own, so that the loop's blocks end where it does.+ let after = self.new_block(func);+ let loop_index = control.loop_index as usize;+ func.loops[loop_index].last = func.blocks.len() as u32 - 2;+ self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[after]);+ let from = self.current_block;+ Self::set_predecessors(func, after, &[from]);+ self.start_block(func, after);+ debug_assert_eq!(self.stack.len(), height + results.1 as usize);+ } else {+ func.loops[control.loop_index as usize].last = func.blocks.len() as u32 - 1;+ self.set_unreachable();+ }+ }++ /// A branch to the label at `depth`, which ends the current block. The caller marks the rest unreachable.+ fn branch(&mut self, func: &mut Func, depth: u32) {+ let index = self.controls.len() - 1 - depth as usize;+ let control = self.controls[index];+ match control.kind {+ ControlKind::Function => {+ let count = control.results.1 as usize;+ let start = func.operands.len() as u32;+ let top = self.stack.len() - count;+ for position in top..self.stack.len() {+ let value = Self::resolve(func, self.stack[position]);+ func.operands.push(value);+ }+ self.terminate(+ func,+ Node::new(Op::Return, Type::None, 0, [start, count as u32, 0]),+ &[],+ );+ }+ ControlKind::Loop => {+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[control.block]);+ self.add_edge(index, slot);+ }+ _ => {+ let slot = self.terminate(func, Node::new(Op::Jump, Type::None, 0, [0; 3]), &[NONE]);+ self.add_edge(index, slot);+ }+ }+ }++ /// A branch to label `depth` if `condition` is nonzero. If it is a nonzero constant, what follows is unreachable.+ fn conditional_branch(&mut self, func: &mut Func, depth: u32, condition: Value) {+ match func.node(condition).constant() {+ Some(0) => {}+ Some(_) => {+ self.branch(func, depth);+ self.set_unreachable();+ }+ None => self.branch_if(func, depth, condition),+ }+ }++ fn branch_if(&mut self, func: &mut Func, depth: u32, condition: Value) {+ let index = self.controls.len() - 1 - depth as usize;+ let control = self.controls[index];+ let fallthrough = self.new_block(func);+ if control.kind == ControlKind::Function {+ // A conditional return: the taken edge goes to a block that returns.+ let returning = fallthrough;+ let after = self.new_block(func);+ let from = self.current_block;+ self.terminate(+ func,+ Node::new(Op::Branch, Type::None, 0, [condition, 0, 0]),+ &[returning, after],+ );+ Self::set_predecessors(func, returning, &[from]);+ Self::set_predecessors(func, after, &[from]);+ self.start_block(func, returning);+ let depth = self.controls.len() as u32 - 1;+ self.branch(func, depth);+ self.start_block(func, after);+ return;+ }+ let target = if control.kind == ControlKind::Loop {+ control.block+ } else {+ NONE+ };+ let slot = self.terminate(+ func,+ Node::new(Op::Branch, Type::None, 0, [condition, 0, 0]),+ &[target, fallthrough],+ );+ self.add_edge(index, slot);+ let from = self.current_block;+ Self::set_predecessors(func, fallthrough, &[from]);+ self.start_block(func, fallthrough);+ }++ fn branch_table(&mut self, func: &mut Func, index: Value, depths: &[u32]) {+ if let Some(bits) = func.node(index).constant() {+ let position = (bits as usize).min(depths.len() - 1);+ self.branch(func, depths[position]);+ return;+ }+ // The distinct labels, each with the index of its successor.+ let mut labels: Vec<(u32, u32)> = Vec::with_capacity(depths.len().min(16));+ let start = func.operands.len() as u32;+ let mut has_return = false;+ for &depth in depths {+ let successor = match labels.iter().position(|(label, _)| *label == depth) {+ Some(position) => labels[position].1,+ None => {+ let successor = labels.len() as u32;+ labels.push((depth, successor));+ has_return |= depth as usize == self.controls.len() - 1;+ successor+ }+ };+ func.operands.push(successor);+ }+ let mut successors = Vec::with_capacity(labels.len());+ let mut returning = NONE;+ for &(depth, _) in &labels {+ let control = &self.controls[self.controls.len() - 1 - depth as usize];+ successors.push(match control.kind {+ ControlKind::Loop => control.block,+ ControlKind::Function => {+ returning = func.blocks.len() as u32;+ // A block that returns, made below.+ returning+ }+ _ => NONE,+ });+ }+ if has_return {+ self.new_block(func);+ }+ let count = depths.len() as u32 - 1;+ let from = self.current_block;+ let slot = self.terminate(+ func,+ Node::new(Op::BrTable, Type::None, 0, [index, start, count]),+ &successors,+ );+ for (position, &(depth, _)) in labels.iter().enumerate() {+ let control_index = self.controls.len() - 1 - depth as usize;+ if self.controls[control_index].kind == ControlKind::Function {+ continue;+ }+ self.add_edge(control_index, slot + position as u32);+ }+ if has_return {+ Self::set_predecessors(func, returning, &[from]);+ self.start_block(func, returning);+ let depth = self.controls.len() as u32 - 1;+ self.branch(func, depth);+ }+ }++ // Globals and calls.++ /// The storage of a global: `globals[index]` of the instance.+ fn global_storage(&mut self, func: &mut Func, global: u32) -> Value {+ let globals = self.pure(+ func,+ Node::new(+ Op::InstanceField,+ Type::Pointer,+ 0,+ [self.instance, instance_offset(offset_of!(InstanceData, globals)), 0],+ ),+ );+ self.pure(+ func,+ Node::new(Op::LoadPointer, Type::Pointer, 0, [globals, global * 8, 0]),+ )+ }++ fn global_get(&mut self, func: &mut Func, module: &Module, global: u32, pc: usize) -> Result<(), CompileFailure> {+ let ty = module.global_space[global as usize];+ let Some(value_type) = ir_type(ty.value) else {+ return unsupported(pc, "a global of a type the JIT does not compile");+ };+ let storage = self.global_storage(func, global);+ let value = if ty.mutable {+ let key = numbering_key(&Node::new(+ Op::GlobalGet,+ value_type,+ 0,+ [global, self.global_epochs[global as usize], self.call_epoch],+ ));+ if let Some(value) = self.numbering.get(key)+ && value != NONE+ {+ value+ } else {+ let value = Self::append(func, Node::new(Op::GlobalGet, value_type, 0, [storage, global, 0]));+ self.number(key, value);+ value+ }+ } else {+ self.pure(+ func,+ Node::new(Op::GlobalGet, value_type, FLAG_IMMUTABLE, [storage, global, 0]),+ )+ };+ self.push(value);+ Ok(())+ }++ fn global_set(&mut self, func: &mut Func, global: u32) {+ let value = Self::resolve(func, self.pop());+ let storage = self.global_storage(func, global);+ let ty = func.node(value).ty;+ Self::append(func, Node::new(Op::GlobalSet, Type::None, 0, [storage, value, global]));+ self.global_epochs[global as usize] += 1;+ // The global holds the stored value until it changes again.+ let key = numbering_key(&Node::new(+ Op::GlobalGet,+ ty,+ 0,+ [global, self.global_epochs[global as usize], self.call_epoch],+ ));+ self.number(key, value);+ }+}++const INTEGER_BINARY: [Op; 15] = [+ Op::Add,+ Op::Sub,+ Op::Mul,+ Op::DivS,+ Op::DivU,+ Op::RemS,+ Op::RemU,+ Op::And,+ Op::Or,+ Op::Xor,+ Op::Shl,+ Op::ShrS,+ Op::ShrU,+ Op::Rotl,+ Op::Rotr,+];++const FLOAT_UNARY: [Op; 7] = [+ Op::FAbs,+ Op::FNeg,+ Op::FCeil,+ Op::FFloor,+ Op::FTrunc,+ Op::FNearest,+ Op::FSqrt,+];++const FLOAT_BINARY: [Op; 7] = [+ Op::FAdd,+ Op::FSub,+ Op::FMul,+ Op::FDiv,+ Op::FMin,+ Op::FMax,+ Op::FCopysign,+];++fn load_kind(opcode: u8) -> (LoadKind, Type) {+ match opcode {+ opcode::I32_LOAD => (LoadKind::I32, Type::I32),+ opcode::I64_LOAD => (LoadKind::I64, Type::I64),+ opcode::F32_LOAD => (LoadKind::F32, Type::F32),+ opcode::F64_LOAD => (LoadKind::F64, Type::F64),+ opcode::I32_LOAD8_S => (LoadKind::I32S8, Type::I32),+ opcode::I32_LOAD8_U => (LoadKind::I32U8, Type::I32),+ opcode::I32_LOAD16_S => (LoadKind::I32S16, Type::I32),+ opcode::I32_LOAD16_U => (LoadKind::I32U16, Type::I32),+ opcode::I64_LOAD8_S => (LoadKind::I64S8, Type::I64),+ opcode::I64_LOAD8_U => (LoadKind::I64U8, Type::I64),+ opcode::I64_LOAD16_S => (LoadKind::I64S16, Type::I64),+ opcode::I64_LOAD16_U => (LoadKind::I64U16, Type::I64),+ opcode::I64_LOAD32_S => (LoadKind::I64S32, Type::I64),+ _ => (LoadKind::I64U32, Type::I64),+ }+}++fn store_size_log2(opcode: u8) -> u8 {+ match opcode {+ opcode::I32_STORE8 | opcode::I64_STORE8 => 0,+ opcode::I32_STORE16 | opcode::I64_STORE16 => 1,+ opcode::I32_STORE | opcode::F32_STORE | opcode::I64_STORE32 => 2,+ _ => 3,+ }+}++#[allow(dead_code)]+fn condition_name(flags: u8) -> &'static str {+ IntCondition::from_flags(flags).name()+}++#[allow(dead_code)]+fn float_condition_name(flags: u8) -> &'static str {+ FloatCondition::from_flags(flags).name()+}diff --git a/Libraries/LibWasm/JIT/src/builder/simd.rs b/Libraries/LibWasm/JIT/src/builder/simd.rsnew file mode 100644index 00000000000..728f6cf86f8--- /dev/null+++ b/Libraries/LibWasm/JIT/src/builder/simd.rs@@ -0,0 +1,179 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! 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.++use super::{Builder, unsupported};+use crate::CompileFailure;+use crate::decode::Decoder;+use crate::ir::{Func, Node, Op, Type, Value};+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 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,+ })+}++impl Builder {+ pub(super) fn vector_constant(&mut self, func: &mut Func, bits: u128) -> Value {+ let index = func.constants.len() as u32;+ func.constants.push(bits);+ Self::append(func, Node::new(Op::Const128, Type::V128, 0, [index, 0, 0]))+ }++ pub(super) fn simd(+ &mut self,+ func: &mut Func,+ sub_opcode: u32,+ decoder: &Decoder<'_>,+ pc: usize,+ ) -> Result<(), CompileFailure> {+ let Some(shape) = shape(sub_opcode) else {+ return unsupported(pc, "a 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 index = Self::resolve(func, self.pop());+ Self::append(+ func,+ Node::new(+ Op::VectorLoad,+ Type::V128,+ sub_opcode as u8,+ [self.memory_base, index, argument.offset as u32],+ ),+ )+ }+ Shape::Store => {+ let argument = decoder.simd_argument();+ 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(+ func,+ Node::new(Op::Store, Type::None, 4, [start, 3, argument.offset as u32]),+ );+ return Ok(());+ }+ Shape::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());+ let index = func.constants.len() as u32;+ func.constants.push(u128::from_le_bytes(decoder.simd_bytes()));+ Self::append(func, Node::new(Op::Shuffle, Type::V128, 0, [a, b, index]))+ }+ Shape::Unary(result) => {+ let a = Self::resolve(func, self.pop());+ self.pure(func, Node::new(Op::VectorUnary, result, 0, [a, sub_opcode, 0]))+ }+ Shape::Binary => {+ 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 => {+ let c = Self::resolve(func, self.pop());+ let b = Self::resolve(func, self.pop());+ let a = Self::resolve(func, self.pop());+ self.pure(+ func,+ Node::new(Op::VectorTernary, Type::V128, sub_opcode as u8, [a, b, c]),+ )+ }+ Shape::ExtractLane(ty) => {+ 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]))+ }+ Shape::ReplaceLane => {+ let b = Self::resolve(func, self.pop());+ let a = Self::resolve(func, self.pop());+ let lane = u32::from(decoder.simd_lane());+ self.pure(+ func,+ Node::new(Op::ReplaceLane, Type::V128, 0, [a, b, sub_opcode | (lane << 16)]),+ )+ }+ };+ self.push(value);+ Ok(())+ }+}diff --git a/Libraries/LibWasm/JIT/src/builder/tables.rs b/Libraries/LibWasm/JIT/src/builder/tables.rsnew file mode 100644index 00000000000..50fe9140e7c--- /dev/null+++ b/Libraries/LibWasm/JIT/src/builder/tables.rs@@ -0,0 +1,214 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Tables, the sizes of memories, and the bulk operations on both. Sizes and table elements are read where the code+//! uses them, since growing changes them; the bulk operations and growing call the runtime (`Op::Helper`).++use super::Builder;+use crate::ir::{Func, Helper, Node, Op, Type, Value};+use libwasm_module::Module;+use libwasm_module::abi::{InstanceData, MemoryData, Segment, TRAP_TABLE_OUT_OF_BOUNDS, TableData};+use libwasm_module::opcode::misc;+use libwasm_module::types::AddressType;+use std::mem::offset_of;++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 {+ let start = func.operands.len() as u32;+ func.operands.push(self.instance);+ for &operand in operands {+ func.operands.push(Self::resolve(func, operand));+ }+ let value = Self::append(+ func,+ Node::new(Op::Helper, ty, 0, [start, 1 + operands.len() as u32, helper as u32]),+ );+ // NB: Growing a memory runs the embedder's callback, which may change globals.+ self.call_epoch += 1;+ value+ }++ /// 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 {+ let segments = self.instance_field(func, offset);+ self.pure(+ func,+ Node::new(+ Op::Offset,+ Type::Pointer,+ 0,+ [segments, index * size_of::<Segment>() as u32, 0],+ ),+ )+ }++ /// A size or previous size of a memory or table of `address_type`, as a value of that type.+ fn address_value(&mut self, func: &mut Func, address_type: AddressType, value: Value) -> Value {+ match address_type {+ AddressType::I32 => self.unary(func, Op::Wrap, Type::I32, value),+ AddressType::I64 => value,+ }+ }++ pub(super) fn memory_size(&mut self, func: &mut Func, module: &Module, memory: u32) {+ let data = self.memory_data(func, memory);+ let size = Self::append(+ func,+ Node::new(+ Op::ReadField,+ Type::I64,+ 8,+ [data, offset_of!(MemoryData, size) as u32, 0],+ ),+ );+ let shift = self.constant(func, Type::I64, PAGE_SHIFT);+ let pages = self.binary(func, Op::ShrU, Type::I64, size, shift);+ let value = self.address_value(func, module.memory_space[memory as usize].limits.address_type, pages);+ self.push(value);+ }++ pub(super) fn memory_grow(&mut self, func: &mut Func, module: &Module, memory: u32) {+ let address_type = module.memory_space[memory as usize].limits.address_type;+ let delta = self.pop();+ let data = self.memory_data(func, memory);+ let previous = self.helper(func, Helper::MemoryGrow, &[data, delta], Type::I64);+ let value = self.address_value(func, address_type, previous);+ self.push(value);+ }++ pub(super) fn table_get(&mut self, func: &mut Func, table: u32) {+ let index = Self::resolve(func, self.pop());+ let data = self.table_data(func, table);+ let value = Self::append(+ func,+ Node::new(+ Op::TableElement,+ Type::Ref,+ TRAP_TABLE_OUT_OF_BOUNDS as u8,+ [data, index, 0],+ ),+ );+ self.push(value);+ }++ pub(super) fn table_set(&mut self, func: &mut Func, table: u32) {+ let value = Self::resolve(func, self.pop());+ let index = Self::resolve(func, self.pop());+ let data = self.table_data(func, table);+ Self::append(+ func,+ Node::new(+ Op::TableStore,+ Type::None,+ TRAP_TABLE_OUT_OF_BOUNDS as u8,+ [data, index, value],+ ),+ );+ }++ /// The bulk memory and table instructions of the `0xFC` prefix, with their index immediates.+ pub(super) fn bulk(&mut self, func: &mut Func, module: &Module, sub_opcode: u32, [first, second]: [u32; 2]) {+ match sub_opcode {+ misc::MEMORY_INIT => {+ let (count, source, destination) = (self.pop(), self.pop(), self.pop());+ let segment = self.segment(func, offset_of!(InstanceData, data_segments), first);+ let memory = self.memory_data(func, second);+ self.helper(+ func,+ Helper::MemoryInit,+ &[memory, segment, destination, source, count],+ Type::None,+ );+ }+ misc::DATA_DROP | misc::ELEM_DROP => {+ let offset = if sub_opcode == misc::DATA_DROP {+ offset_of!(InstanceData, data_segments)+ } else {+ offset_of!(InstanceData, element_segments)+ };+ let segments = self.instance_field(func, offset);+ let zero = self.constant(func, Type::I64, 0);+ let field = first * size_of::<Segment>() as u32 + offset_of!(Segment, length) as u32;+ Self::append(func, Node::new(Op::WriteField, Type::None, 8, [segments, zero, field]));+ }+ misc::MEMORY_COPY => {+ let (count, source, destination) = (self.pop(), self.pop(), self.pop());+ let destination_memory = self.memory_data(func, first);+ let source_memory = self.memory_data(func, second);+ self.helper(+ func,+ Helper::MemoryCopy,+ &[destination_memory, source_memory, destination, source, count],+ Type::None,+ );+ }+ misc::MEMORY_FILL => {+ let (count, value, destination) = (self.pop(), self.pop(), self.pop());+ let memory = self.memory_data(func, first);+ self.helper(+ func,+ Helper::MemoryFill,+ &[memory, destination, value, count],+ Type::None,+ );+ }+ misc::TABLE_INIT => {+ let (count, source, destination) = (self.pop(), self.pop(), self.pop());+ let segment = self.segment(func, offset_of!(InstanceData, element_segments), first);+ let table = self.table_data(func, second);+ self.helper(+ func,+ Helper::TableInit,+ &[table, segment, destination, source, count],+ Type::None,+ );+ }+ misc::TABLE_COPY => {+ let (count, source, destination) = (self.pop(), self.pop(), self.pop());+ let destination_table = self.table_data(func, first);+ let source_table = self.table_data(func, second);+ self.helper(+ func,+ Helper::TableCopy,+ &[destination_table, source_table, destination, source, count],+ Type::None,+ );+ }+ misc::TABLE_GROW => {+ let address_type = module.table_space[first as usize].limits.address_type;+ let (delta, initial) = (self.pop(), self.pop());+ let table = self.table_data(func, first);+ let previous = self.helper(func, Helper::TableGrow, &[table, delta, initial], Type::I64);+ let value = self.address_value(func, address_type, previous);+ self.push(value);+ }+ misc::TABLE_SIZE => {+ let address_type = module.table_space[first as usize].limits.address_type;+ let table = self.table_data(func, first);+ let size = Self::append(+ func,+ Node::new(+ Op::ReadField,+ Type::I64,+ 8,+ [table, offset_of!(TableData, size) as u32, 0],+ ),+ );+ let value = self.address_value(func, address_type, size);+ self.push(value);+ }+ misc::TABLE_FILL => {+ let (count, value, destination) = (self.pop(), self.pop(), self.pop());+ let table = self.table_data(func, first);+ self.helper(func, Helper::TableFill, &[table, destination, value, count], Type::None);+ }+ _ => unreachable!("validated code has no unknown 0xFC instruction {sub_opcode:#x}"),+ }+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/mod.rs b/Libraries/LibWasm/JIT/src/codegen/mod.rsnew file mode 100644index 00000000000..0ba3e663c6f--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/mod.rs@@ -0,0 +1,9 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Code generation, one lowering per architecture.++pub mod x86_64;diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rsnew file mode 100644index 00000000000..6f7b53cf04b--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rs@@ -0,0 +1,139 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Calls between compiled functions (see `convention`). The allocator moved the arguments into place, so a call+//! only passes the result area, if any, calls through the callee's `FunctionHeader`, and puts rsp back where the+//! frame wants it, which also undoes whatever a callee's tail calls did to it.++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 libwasm_module::abi::FunctionHeader;+use std::mem::offset_of;++/// The slots of a call's arguments.+fn argument_slots(func: &Func, call: Value) -> u32 {+ func.inputs(call)[3..]+ .iter()+ .map(|argument| func.node(*argument).ty.slots())+ .sum()+}+use crate::regalloc::call_result_types;++impl CodeGenerator<'_> {+ pub(super) fn lower_call(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ match node.op {+ Op::Call => {+ let argument_slots = argument_slots(func, value);+ let results = call_result_types(func, value);+ if convention::has_result_area(&results) {+ let pointer = 8 * argument_slots as i32;+ self.asm.lea(Width::W64, SCRATCH, &Address::new(SP, pointer + 8));+ self.asm.mov_mr(Width::W64, &Address::new(SP, pointer), SCRATCH);+ }+ let callee = gpr(convention::CALLEE_REGISTER);+ self.asm+ .call_m(&Address::new(callee, offset_of!(FunctionHeader, native_entry) as i32));+ self.asm+ .lea(Width::W64, SP, &Address::new(FP, -(self.frame_size as i32)));+ }+ Op::CallResult => {+ let call = node.args[0];+ let index = node.args[1] as usize;+ let results = call_result_types(func, call);+ let mut places = Vec::with_capacity(results.len());+ convention::result_places(&results, &mut places);+ if let Place::Memory(slot) = places[index] {+ let output = self.allocation.node(value).output;+ let area = 8 * (argument_slots(func, call) as i32 + 1);+ let address = Address::new(SP, area + 8 * slot as i32);+ if node.ty == Type::V128 {+ self.load_vector(fpr(output).0, &address);+ } else if node.ty.is_float() {+ self.asm.vmovs_rm(precision(node.ty), fpr(output), &address);+ } else {+ self.asm.mov_rm(width(node.ty), gpr(output), &address);+ }+ }+ }+ _ => unreachable!("{} is no call", node.op.name()),+ }+ }++ /// A tail call: the allocator put the arguments where a call passes them, which this copies the stack arguments+ /// from into the incoming area (see `convention`).+ pub(super) fn lower_tail_call(&mut self, value: Value) {+ let func = self.func;+ let parameters = func.inputs(value)[3..]+ .iter()+ .map(|argument| func.node(*argument).ty)+ .collect::<Vec<_>>();+ let has_result_area = convention::has_result_area(&func.results);+ let callee_slots = convention::slots(¶meters);+ let own_slots = convention::slots(&func.params);+ let needed = callee_slots + u32::from(has_result_area);+ let available = own_slots + u32::from(has_result_area);+ let slide = if needed > available {+ (8 * (needed - available)).next_multiple_of(16) as i32+ } else {+ 0+ };+ // NB: The callee's operands are in their registers, which leaves rax and rbx free.+ let (return_address, saved_fp) = (Gpr(convention::RAX), Gpr(convention::RBX));+ if slide != 0 {+ self.asm.mov_rm(+ Width::W64,+ return_address,+ &Address::new(FP, convention::FRAME_RETURN_ADDRESS),+ );+ self.asm+ .mov_rm(Width::W64, saved_fp, &Address::new(FP, convention::FRAME_SAVED_FP));+ }+ let mut copied = Vec::new();+ let mut places = Vec::new();+ convention::parameter_places(¶meters, &mut places);+ for (index, place) in places.iter().enumerate() {+ if let Place::Memory(slot) = *place {+ copied.extend(slot..slot + parameters[index].slots());+ }+ }+ if has_result_area {+ // The function's caller gets the callee's results.+ let pointer = convention::home_slot_offset(convention::result_area_pointer(&func.params));+ self.asm.mov_rm(Width::W64, SCRATCH, &Address::new(FP, pointer));+ self.asm+ .mov_mr(Width::W64, &Address::new(SP, 8 * callee_slots as i32), SCRATCH);+ copied.push(callee_slots);+ }+ // The incoming area is above the outgoing one, so copying down from the top never overwrites a source.+ for &slot in copied.iter().rev() {+ self.asm.mov_rm(Width::W64, SCRATCH, &Address::new(SP, 8 * slot as i32));+ self.asm+ .mov_mr(Width::W64, &Address::new(FP, 8 * slot as i32 - slide), SCRATCH);+ }+ if slide != 0 {+ self.asm.mov_mr(+ Width::W64,+ &Address::new(FP, convention::FRAME_RETURN_ADDRESS - slide),+ return_address,+ );+ self.asm.mov_mr(+ Width::W64,+ &Address::new(FP, convention::FRAME_SAVED_FP - slide),+ saved_fp,+ );+ }+ self.asm+ .lea(Width::W64, SP, &Address::new(FP, convention::FRAME_SAVED_FP - slide));+ self.asm.pop(FP);+ let callee = gpr(convention::CALLEE_REGISTER);+ self.asm+ .jmp_m(&Address::new(callee, offset_of!(FunctionHeader, native_entry) as i32));+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/memory.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/memory.rsnew file mode 100644index 00000000000..33c0708deec--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/memory.rs@@ -0,0 +1,136 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Loads and stores of memory 0, globals and instance data.+//!+//! Memory 0 is a memory32 with guard pages: an access is at base + zero-extended index + offset, with no bounds+//! check, and faults in the guard region where it is out of bounds. i32 values are always zero-extended in+//! registers, so the index register serves as is.++use super::{CodeGenerator, SCRATCH, fpr, gpr, precision, width};+use crate::asm::{Address, Scale, Width};+use crate::convention::{self, Register};+use crate::ir::{LoadKind, Op, Type, Value};+use crate::regalloc::CONSTANT_INPUT;++impl CodeGenerator<'_> {+ /// The address of an access of memory 0 with base `base`, index input `index` and offset `offset`.+ fn memory_address(&mut self, value: Value, base: Register, index: Register, offset: u32) -> Address {+ let base = gpr(base);+ if index == CONSTANT_INPUT {+ let constant = self.immediate(value, 1) & 0xffff_ffff;+ return Address::new(base, (constant + u64::from(offset)) as i32);+ }+ if let Ok(offset) = i32::try_from(offset) {+ return Address::indexed(base, gpr(index), Scale::One, offset);+ }+ // NB: Offsets of 2^31 and up do not fit a displacement; the index and offset, both below 2^32, add up+ // without overflowing 64 bits.+ self.asm.mov_ri(SCRATCH, u64::from(offset));+ self.asm.add_rr(Width::W64, SCRATCH, gpr(index));+ Address::indexed(base, SCRATCH, Scale::One, 0)+ }++ pub(super) fn lower_memory(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let [a, b, c] = record.inputs;+ let output = record.output;+ match node.op {+ Op::Load => {+ let address = self.memory_address(value, a, b, node.args[2]);+ let dst = output;+ match LoadKind::from_flags(node.flags) {+ LoadKind::I32 | LoadKind::I64U32 => self.asm.mov_rm(Width::W32, gpr(dst), &address),+ LoadKind::I64 => self.asm.mov_rm(Width::W64, gpr(dst), &address),+ LoadKind::F32 => self+ .asm+ .vmovs_rm(crate::asm::x86_64::Precision::Single, fpr(dst), &address),+ LoadKind::F64 => self+ .asm+ .vmovs_rm(crate::asm::x86_64::Precision::Double, fpr(dst), &address),+ LoadKind::I32S8 => self.asm.movsx8_rm(Width::W32, gpr(dst), &address),+ LoadKind::I64S8 => self.asm.movsx8_rm(Width::W64, gpr(dst), &address),+ LoadKind::I32U8 | LoadKind::I64U8 => self.asm.movzx8_rm(gpr(dst), &address),+ LoadKind::I32S16 => self.asm.movsx16_rm(Width::W32, gpr(dst), &address),+ LoadKind::I64S16 => self.asm.movsx16_rm(Width::W64, gpr(dst), &address),+ LoadKind::I32U16 | LoadKind::I64U16 => self.asm.movzx16_rm(gpr(dst), &address),+ LoadKind::I64S32 => self.asm.movsxd_rm(gpr(dst), &address),+ }+ }+ Op::VectorLoad => {+ let address = self.memory_address(value, a, b, node.args[2]);+ self.vector_load(value, &address);+ }+ Op::Store => {+ let address = self.memory_address(value, a, b, node.args[2]);+ let stored = func.inputs(value)[2];+ self.store(stored, c, crate::ir::store_size(node.flags), &address);+ }+ Op::GlobalGet => {+ let address = Address::new(gpr(a), 0);+ if node.ty == Type::V128 {+ self.load_vector(fpr(output).0, &address);+ } else if node.ty.is_float() {+ self.asm.vmovs_rm(precision(node.ty), fpr(output), &address);+ } else {+ self.asm.mov_rm(width(node.ty), gpr(output), &address);+ }+ }+ Op::GlobalSet => {+ let address = Address::new(gpr(a), 0);+ let stored = node.args[1];+ let size = match func.node(stored).ty {+ Type::V128 => 16,+ ty if ty.is_64() => 8,+ _ => 4,+ };+ self.store(stored, b, size, &address);+ }+ Op::InstanceField | Op::LoadPointer => {+ let address = Address::new(gpr(a), node.args[1] as i32);+ self.asm.mov_rm(Width::W64, gpr(output), &address);+ }+ _ => unreachable!("{} is no memory op", node.op.name()),+ }+ }++ /// Stores `size` bytes of `stored`, which is in `register` or a constant immediate, at `address`.+ fn store(&mut self, stored: Value, register: Register, size: u32, address: &Address) {+ let ty = self.func.node(stored).ty;+ if register == CONSTANT_INPUT {+ let bits = self.func.node(stored).constant().expect("immediates are constants");+ match size {+ 1 => self.asm.mov8_mi(address, bits as u8),+ 2 => self.asm.mov16_mi(address, bits as u16),+ 4 => self.asm.mov_mi(Width::W32, address, bits as u32 as i32),+ _ => self.asm.mov_mi(Width::W64, address, bits as i64 as i32),+ }+ return;+ }+ if size == 16 {+ self.store_vector(register, address);+ return;+ }+ if convention::is_fpr(register) {+ let p = if size == 8 || ty == Type::F64 {+ crate::asm::x86_64::Precision::Double+ } else {+ crate::asm::x86_64::Precision::Single+ };+ self.asm.vmovs_mr(p, address, fpr(register));+ return;+ }+ let register = gpr(register);+ match size {+ 1 => self.asm.mov8_mr(address, register),+ 2 => self.asm.mov16_mr(address, register),+ 4 => self.asm.mov_mr(Width::W32, address, register),+ _ => self.asm.mov_mr(Width::W64, address, register),+ }+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rsnew file mode 100644index 00000000000..442862b02d9--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs@@ -0,0 +1,679 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! x86-64 code generation: the blocks in linear order, each node lowered with the registers the allocator gave it+//! (`numeric`, `memory`, `calls`), then the out-of-line code: stubs for edges that need moves, trap stubs, jump+//! tables and the constant pool. The code is position independent: it reaches the runtime through absolute+//! addresses and its own data through rip-relative operands.++mod calls;+mod memory;+mod numeric;+mod tables;+mod vector;++use crate::RuntimeInfo;+use crate::asm::x86_64::{Assembler, BitwiseOp, Cond, Precision, VexOperand};+use crate::asm::{Address, Fpr, Gpr, Label, Width};+use crate::convention::{self, Register};+use crate::ir::{BlockId, FloatCondition, Func, IntCondition, NONE, Op, Type, Value};+use crate::passes::cleanup::Liveliness;+use crate::regalloc::{Allocation, Location, Move, NO_REGISTER, NO_SLOT};+use libwasm_module::abi::{ExecutionContext, InstanceData};+use std::mem::offset_of;++pub(crate) fn gpr(register: Register) -> Gpr {+ debug_assert!(+ !convention::is_fpr(register),+ "r{register} is no general purpose register"+ );+ Gpr(register)+}++pub(crate) fn fpr(register: Register) -> Fpr {+ debug_assert!(convention::is_fpr(register), "r{register} is no xmm register");+ Fpr(register - convention::FPR_BASE)+}++pub(crate) fn width(ty: Type) -> Width {+ if ty.is_64() { Width::W64 } else { Width::W32 }+}++pub(crate) fn precision(ty: Type) -> Precision {+ if ty == Type::F64 {+ Precision::Double+ } else {+ Precision::Single+ }+}++const SCRATCH: Gpr = Gpr(convention::SCRATCH_GPR);+const SCRATCH_FPR: Fpr = Fpr(convention::SCRATCH_FPR - convention::FPR_BASE);+const FP: Gpr = Gpr(convention::RBP);+const SP: Gpr = Gpr(convention::RSP);++pub(crate) fn condition(condition: IntCondition) -> Cond {+ match condition {+ IntCondition::Eq => Cond::Equal,+ IntCondition::Ne => Cond::NotEqual,+ IntCondition::LtS => Cond::Less,+ IntCondition::LtU => Cond::Below,+ IntCondition::GtS => Cond::Greater,+ IntCondition::GtU => Cond::Above,+ IntCondition::LeS => Cond::LessOrEqual,+ IntCondition::LeU => Cond::BelowOrEqual,+ IntCondition::GeS => Cond::GreaterOrEqual,+ IntCondition::GeU => Cond::AboveOrEqual,+ }+}++/// What code generation produced.+#[derive(Debug, Default)]+pub struct Generated {+ pub code: Vec<u8>,+ pub frame_size: u32,+}++/// Out-of-line code for an edge that needs moves: its label, the edge's slot and its target.+struct EdgeStub {+ label: Label,+ slot: u32,+ target: BlockId,+}++pub struct CodeGenerator<'a> {+ func: &'a Func,+ liveliness: &'a Liveliness,+ allocation: &'a Allocation,+ runtime: &'a RuntimeInfo,+ asm: Assembler,+ block_labels: Vec<Label>,+ trap_labels: Vec<Option<Label>>,+ /// The trap with the code in eax, for the runtime's functions that return one.+ dynamic_trap: Option<Label>,+ subtype_checks: Vec<tables::SubtypeCheck>,+ edge_stubs: Vec<EdgeStub>,+ /// Jump tables: their label, and the label of each target.+ tables: Vec<(Label, Vec<Label>)>,+ constants: Vec<(u128, Label)>,+ frame_size: u32,+ /// The block whose code is being generated.+ block: BlockId,+}++impl<'a> CodeGenerator<'a> {+ pub fn new(+ func: &'a Func,+ liveliness: &'a Liveliness,+ allocation: &'a Allocation,+ runtime: &'a RuntimeInfo,+ ) -> Self {+ let size = convention::FRAME_HEADER_SIZE as u32 + 8 * allocation.slot_count + allocation.outgoing_size;+ Self {+ func,+ liveliness,+ allocation,+ runtime,+ asm: Assembler::new(),+ block_labels: Vec::new(),+ trap_labels: vec![None; 32],+ dynamic_trap: None,+ subtype_checks: Vec::new(),+ edge_stubs: Vec::new(),+ tables: Vec::new(),+ constants: Vec::new(),+ frame_size: size.next_multiple_of(16),+ block: 0,+ }+ }++ pub fn generate(mut self) -> Result<Generated, crate::CompileFailure> {+ let func = self.func;+ for _ in 0..func.blocks.len() {+ let label = self.asm.new_label();+ self.block_labels.push(label);+ }+ self.prologue();+ for block in 0..func.blocks.len() as BlockId {+ self.block = block;+ let label = self.block_labels[block as usize];+ self.asm.bind(label);+ // Phis in registers that have a slot too are stored there where they are defined.+ for phi in func.phis(block) {+ let record = self.allocation.node(phi);+ let slot = self.allocation.slots[phi as usize];+ if record.output != NO_REGISTER && slot != NO_SLOT {+ self.store_to_slot(record.output, slot, func.node(phi).ty == Type::V128);+ }+ }+ let data = func.blocks[block as usize];+ for value in data.start..data.end {+ let op = func.node(value).op;+ if self.liveliness.is_dead(value) || matches!(op, Op::Phi | Op::Forward) || op.is_entry_value() {+ continue;+ }+ for item in self.allocation.node_moves(value) {+ self.emit_move(item);+ }+ self.lower(value);+ let record = self.allocation.node(value);+ let slot = self.allocation.slots[value as usize];+ if record.output != NO_REGISTER && slot != NO_SLOT {+ self.store_to_slot(record.output, slot, func.node(value).ty == Type::V128);+ }+ }+ }+ self.out_of_line();+ let code = self.asm.finish().map_err(|_| crate::CompileFailure::CodeGeneration)?;+ Ok(Generated {+ code,+ frame_size: self.frame_size,+ })+ }++ // Frames.++ fn prologue(&mut self) {+ let func = self.func;+ self.asm.push(FP);+ self.asm.lea(Width::W64, FP, &Address::new(SP, 16));+ // NB: The instance goes in the frame before the stack check, which traps through the frame. It is in the+ // red zone until rsp moves below it.+ self.asm.mov_mr(+ Width::W64,+ &Address::new(FP, convention::FRAME_INSTANCE),+ gpr(convention::INSTANCE_REGISTER),+ );+ // NB: rax carries nothing into a function, so it is free here.+ let context = Gpr(convention::RAX);+ self.asm.mov_rm(+ Width::W64,+ context,+ &Address::new(+ gpr(convention::INSTANCE_REGISTER),+ offset_of!(InstanceData, context) as i32,+ ),+ );+ let below = self.frame_size as i32 - 16;+ self.asm.lea(Width::W64, SCRATCH, &Address::new(SP, -below));+ self.asm.alu_rm(+ crate::asm::x86_64::AluOp::Cmp,+ Width::W64,+ SCRATCH,+ &Address::new(context, offset_of!(ExecutionContext, stack_limit) as i32),+ );+ let overflow = self.trap_label(libwasm_module::abi::TRAP_STACK_EXHAUSTED);+ self.asm.jcc(Cond::Below, overflow);+ self.asm.mov_rr(Width::W64, SP, SCRATCH);+ // Values arriving in registers that have slots.+ let data = func.blocks[0];+ for value in data.start..data.end {+ let node = func.node(value);+ if self.liveliness.is_dead(value) || !matches!(node.op, Op::Param | Op::MemoryBase) {+ continue;+ }+ let record = self.allocation.node(value);+ let slot = self.allocation.slots[value as usize];+ if record.output != NO_REGISTER && slot != NO_SLOT {+ self.store_to_slot(record.output, slot, node.ty == Type::V128);+ }+ }+ }++ fn epilogue(&mut self) {+ self.asm+ .lea(Width::W64, SP, &Address::new(FP, convention::FRAME_SAVED_FP));+ self.asm.pop(FP);+ self.asm.ret();+ }++ fn trap_label(&mut self, code: u32) -> Label {+ if let Some(label) = self.trap_labels[code as usize] {+ return label;+ }+ let label = self.asm.new_label();+ self.trap_labels[code as usize] = Some(label);+ label+ }++ fn dynamic_trap_label(&mut self) -> Label {+ *self.dynamic_trap.get_or_insert_with(|| self.asm.new_label())+ }++ fn constant_label(&mut self, bits: u128) -> Label {+ if let Some((_, label)) = self.constants.iter().find(|(constant, _)| *constant == bits) {+ return *label;+ }+ let label = self.asm.new_label();+ self.constants.push((bits, label));+ label+ }++ fn out_of_line(&mut self) {+ self.subtype_checks();+ let stubs = std::mem::take(&mut self.edge_stubs);+ for stub in &stubs {+ self.asm.bind(stub.label);+ for item in self.allocation.edge(stub.slot) {+ self.emit_move(item);+ }+ let target = self.block_labels[stub.target as usize];+ self.asm.jmp(target);+ }+ for code in 0..self.trap_labels.len() {+ if let Some(label) = self.trap_labels[code] {+ self.asm.bind(label);+ self.asm.mov_ri32(Gpr(convention::RDI), code as u32);+ self.asm.mov_ri(SCRATCH, self.runtime.trap_exit);+ self.asm.jmp_r(SCRATCH);+ }+ }+ if let Some(label) = self.dynamic_trap {+ self.asm.bind(label);+ self.asm.mov_rr(Width::W32, Gpr(convention::RDI), Gpr(convention::RAX));+ self.asm.mov_ri(SCRATCH, self.runtime.trap_exit);+ self.asm.jmp_r(SCRATCH);+ }+ let tables = std::mem::take(&mut self.tables);+ for (table, targets) in &tables {+ self.asm.align_data(4);+ self.asm.bind(*table);+ let base = self.asm.label_offset(*table).expect("the table was just bound");+ for target in targets {+ let offset = self+ .asm+ .label_offset(*target)+ .expect("jump targets are bound before the tables");+ self.asm.data_u32((offset as i64 - base as i64) as i32 as u32);+ }+ }+ if !self.constants.is_empty() {+ self.asm.align_data(16);+ let constants = std::mem::take(&mut self.constants);+ for (bits, label) in constants {+ self.asm.bind(label);+ self.asm.data_u64(bits as u64);+ self.asm.data_u64((bits >> 64) as u64);+ }+ }+ }++ // Moves.++ fn store_to_slot(&mut self, register: Register, slot: i32, vector: bool) {+ let address = Address::new(FP, slot);+ if vector {+ self.store_vector(register, &address);+ } else if convention::is_fpr(register) {+ self.asm.vmovs_mr(Precision::Double, &address, fpr(register));+ } else {+ self.asm.mov_mr(Width::W64, &address, gpr(register));+ }+ }++ fn address(&self, location: Location) -> Address {+ match location {+ Location::Slot(slot) => Address::new(FP, slot),+ Location::Outgoing(index) => Address::new(SP, 8 * index as i32),+ _ => unreachable!("{location:?} is no frame location"),+ }+ }++ /// The bits of a constant of any type.+ fn constant_bits(&self, value: Value) -> u128 {+ let node = self.func.node(value);+ match node.op {+ Op::Const128 => self.func.constants[node.args[0] as usize],+ _ => u128::from(node.constant().expect("only constants have bits")),+ }+ }++ /// Loads the constant `bits` into the xmm register `register`, as 4, 8 or 16 bytes as `ty` says.+ fn load_constant(&mut self, ty: Type, bits: u128, register: Register) {+ let label = self.constant_label(bits);+ if ty == Type::V128 {+ self.asm+ .vex(vector::VMOVUPS_LOAD, fpr(register).0, 0, VexOperand::Label(label), None);+ } else {+ let p = if ty.is_64() {+ Precision::Double+ } else {+ Precision::Single+ };+ self.asm.vmovs_r_label(p, fpr(register), label);+ }+ }++ /// Materializes the constant `value` into `register`.+ fn materialize(&mut self, value: Value, register: Register) {+ let ty = self.func.node(value).ty;+ let bits = self.constant_bits(value);+ if convention::is_fpr(register) {+ if bits == 0 {+ let register = fpr(register);+ self.asm.vbitwise_rrr(BitwiseOp::Xor, register, register, register);+ } else {+ self.load_constant(ty, bits, register);+ }+ } else if bits == 0 {+ self.asm.xor_rr(Width::W32, gpr(register), gpr(register));+ } else {+ self.asm.mov_ri(gpr(register), bits as u64);+ }+ }++ /// Stores the constant `value` at `address`, as 8 bytes, or 16 for a vector.+ fn store_constant(&mut self, value: Value, address: &Address) {+ let node = self.func.node(value);+ if node.op == Op::Const128 {+ self.materialize(value, convention::SCRATCH_FPR);+ self.store_vector(convention::SCRATCH_FPR, address);+ return;+ }+ let bits = node.constant().expect("only constants are stored as constants");+ let bits = if node.ty.is_64() { bits } else { bits & 0xffff_ffff };+ if i32::try_from(bits as i64).is_ok() {+ self.asm.mov_mi(Width::W64, address, bits as i64 as i32);+ } else {+ self.asm.mov_ri(SCRATCH, bits);+ self.asm.mov_mr(Width::W64, address, SCRATCH);+ }+ }++ pub(crate) fn emit_move(&mut self, item: &Move) {+ match (item.from, item.to) {+ (Location::Register(from), Location::Register(to)) => {+ if from == to {+ return;+ }+ match (convention::is_fpr(from), convention::is_fpr(to)) {+ (true, true) => self.asm.vmovaps_rr(fpr(to), fpr(from)),+ (false, false) => self.asm.mov_rr(Width::W64, gpr(to), gpr(from)),+ (true, false) => self.asm.vmov_rx(Width::W64, gpr(to), fpr(from)),+ (false, true) => self.asm.vmov_xr(Width::W64, fpr(to), gpr(from)),+ }+ }+ (Location::Constant(value), Location::Register(to)) => self.materialize(value, to),+ (Location::Register(from), to @ (Location::Slot(_) | Location::Outgoing(_))) => {+ let address = self.address(to);+ if item.vector {+ self.store_vector(from, &address);+ } else if convention::is_fpr(from) {+ self.asm.vmovs_mr(Precision::Double, &address, fpr(from));+ } else {+ self.asm.mov_mr(Width::W64, &address, gpr(from));+ }+ }+ (from @ (Location::Slot(_) | Location::Outgoing(_)), Location::Register(to)) => {+ let address = self.address(from);+ if item.vector {+ self.load_vector(fpr(to).0, &address);+ } else if convention::is_fpr(to) {+ self.asm.vmovs_rm(Precision::Double, fpr(to), &address);+ } else {+ self.asm.mov_rm(Width::W64, gpr(to), &address);+ }+ }+ (Location::Constant(value), to @ (Location::Slot(_) | Location::Outgoing(_))) => {+ let address = self.address(to);+ self.store_constant(value, &address);+ }+ (from @ Location::Slot(_), to @ (Location::Slot(_) | Location::Outgoing(_))) => {+ let (from, to) = (self.address(from), self.address(to));+ if item.vector {+ self.load_vector(SCRATCH_FPR.0, &from);+ self.store_vector(convention::SCRATCH_FPR, &to);+ } else {+ self.asm.mov_rm(Width::W64, SCRATCH, &from);+ self.asm.mov_mr(Width::W64, &to, SCRATCH);+ }+ }+ (from, Location::ResultArea(index)) => {+ // The value goes through the scratch xmm register, since the area's address takes the scratch one.+ let source = match from {+ Location::Register(register) if convention::is_fpr(register) => fpr(register),+ Location::Register(register) => {+ self.asm.vmov_xr(Width::W64, SCRATCH_FPR, gpr(register));+ SCRATCH_FPR+ }+ Location::Slot(slot) => {+ self.load_vector(SCRATCH_FPR.0, &Address::new(FP, slot));+ SCRATCH_FPR+ }+ Location::Constant(value) => {+ self.materialize(value, convention::SCRATCH_FPR);+ SCRATCH_FPR+ }+ _ => unreachable!("results do not come from {from:?}"),+ };+ let pointer = convention::home_slot_offset(convention::result_area_pointer(&self.func.params));+ self.asm.mov_rm(Width::W64, SCRATCH, &Address::new(FP, pointer));+ let destination = Address::new(SCRATCH, 8 * index as i32);+ if item.vector {+ self.asm.vex(+ vector::VMOVUPS_STORE,+ source.0,+ 0,+ VexOperand::Memory(destination),+ None,+ );+ } else {+ self.asm.vmovs_mr(Precision::Double, &destination, source);+ }+ }+ (from, to) => unreachable!("no move from {from:?} to {to:?}"),+ }+ }++ // Control.++ /// The label an edge jumps to: its target's, or a stub's that moves values into place first.+ fn edge_label(&mut self, slot: u32, target: BlockId) -> Label {+ if self.allocation.edge(slot).is_empty() {+ return self.block_labels[target as usize];+ }+ let label = self.asm.new_label();+ self.edge_stubs.push(EdgeStub { label, slot, target });+ label+ }++ /// Ends the block on its edge `index` without a condition.+ fn jump(&mut self, index: usize) {+ let block = self.block;+ let slot = self.func.blocks[block as usize].successors_start + index as u32;+ let target = self.func.successors(block)[index];+ for item in self.allocation.edge(slot) {+ self.emit_move(item);+ }+ if target != block + 1 {+ let label = self.block_labels[target as usize];+ self.asm.jmp(label);+ }+ }++ /// Ends the block with a two-way branch whose flags `emit` sets up and whose condition is true for the first+ /// successor. `emit_jumps(generator, taken, not_taken)` jumps to `taken` where the condition holds and may jump+ /// to `not_taken`, which is bound right after, where it does not.+ fn branch(&mut self, emit_jumps: impl Fn(&mut Self, Label, Label)) {+ let block = self.block;+ let data = self.func.blocks[block as usize];+ let successors = self.func.successors(block);+ let (taken, fallthrough) = (successors[0], successors[1]);+ let taken_slot = data.successors_start;+ let fallthrough_slot = taken_slot + 1;+ let taken_label = self.edge_label(taken_slot, taken);+ let not_taken = self.asm.new_label();+ emit_jumps(self, taken_label, not_taken);+ self.asm.bind(not_taken);+ for item in self.allocation.edge(fallthrough_slot) {+ self.emit_move(item);+ }+ if fallthrough != block + 1 {+ let label = self.block_labels[fallthrough as usize];+ self.asm.jmp(label);+ }+ }++ /// A branch on an integer condition, inverted where the taken successor comes next and needs no moves.+ fn branch_on(&mut self, cond: Cond) {+ let block = self.block;+ let data = self.func.blocks[block as usize];+ let successors = self.func.successors(block);+ let (taken, fallthrough) = (successors[0], successors[1]);+ if taken == block + 1 && self.allocation.edge(data.successors_start).is_empty() {+ let label = self.edge_label(data.successors_start + 1, fallthrough);+ self.asm.jcc(cond.invert(), label);+ return;+ }+ self.branch(|generator, taken, _| generator.asm.jcc(cond, taken));+ }++ fn lower_terminator(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ match node.op {+ Op::Jump => self.jump(0),+ Op::Branch => {+ let register = gpr(record.inputs[0]);+ self.asm.test_rr(Width::W32, register, register);+ self.branch_on(Cond::NotEqual);+ }+ Op::BranchCompare => {+ let ty = func.node(node.args[0]).ty;+ self.compare(ty, record.inputs[0], record.inputs[1], node.args[1]);+ self.branch_on(condition(IntCondition::from_flags(node.flags)));+ }+ Op::BranchFloatCompare => {+ let ty = func.node(node.args[0]).ty;+ let (a, b) = (fpr(record.inputs[0]), fpr(record.inputs[1]));+ match FloatCondition::from_flags(node.flags) {+ FloatCondition::Gt => {+ self.asm.vucomis(precision(ty), a, b);+ self.branch_on(Cond::Above);+ }+ FloatCondition::Ge => {+ self.asm.vucomis(precision(ty), a, b);+ self.branch_on(Cond::AboveOrEqual);+ }+ FloatCondition::Lt => {+ self.asm.vucomis(precision(ty), b, a);+ self.branch_on(Cond::Above);+ }+ FloatCondition::Le => {+ self.asm.vucomis(precision(ty), b, a);+ self.branch_on(Cond::AboveOrEqual);+ }+ FloatCondition::Eq => {+ self.asm.vucomis(precision(ty), a, b);+ self.branch(|generator, taken, not_taken| {+ generator.asm.jcc(Cond::Parity, not_taken);+ generator.asm.jcc(Cond::Equal, taken);+ });+ }+ FloatCondition::Ne => {+ self.asm.vucomis(precision(ty), a, b);+ self.branch(|generator, taken, _| {+ generator.asm.jcc(Cond::Parity, taken);+ generator.asm.jcc(Cond::NotEqual, taken);+ });+ }+ }+ }+ Op::BrTable => self.branch_table(value),+ Op::Return => self.epilogue(),+ Op::TailCall => self.lower_tail_call(value),+ Op::Trap => {+ let label = self.trap_label(node.args[0]);+ self.asm.jmp(label);+ }+ _ => unreachable!("{} is no terminator", node.op.name()),+ }+ }++ fn branch_table(&mut self, value: Value) {+ let func = self.func;+ let block = self.block;+ let data = func.blocks[block as usize];+ let record = *self.allocation.node(value);+ let index = gpr(record.inputs[0]);+ let temp = gpr(record.temps[0]);+ let successors = func.successors(block);+ let mut labels = Vec::with_capacity(successors.len());+ for (position, &successor) in successors.iter().enumerate() {+ let label = self.edge_label(data.successors_start + position as u32, successor);+ labels.push(label);+ }+ let targets = func.table_targets(value);+ let (cases, default) = targets.split_at(targets.len() - 1);+ let default = labels[default[0] as usize];+ self.asm.cmp_ri(Width::W32, index, cases.len() as i32);+ self.asm.jcc(Cond::AboveOrEqual, default);+ let table = self.asm.new_label();+ self.asm.lea_label(SCRATCH, table);+ self.asm+ .movsxd_rm(temp, &Address::indexed(SCRATCH, index, crate::asm::Scale::Four, 0));+ self.asm.add_rr(Width::W64, temp, SCRATCH);+ self.asm.jmp_r(temp);+ let case_labels = cases.iter().map(|case| labels[*case as usize]).collect();+ self.tables.push((table, case_labels));+ }++ /// `cmp a, b` of type `ty`, `b` an immediate when it is the constant `b_value`.+ fn compare(&mut self, ty: Type, a: Register, b: Register, b_value: Value) {+ if b == crate::regalloc::CONSTANT_INPUT {+ let bits = self.func.node(b_value).constant().expect("a constant");+ self.asm.cmp_ri(width(ty), gpr(a), bits as i32);+ } else {+ self.asm.cmp_rr(width(ty), gpr(a), gpr(b));+ }+ }++ fn lower(&mut self, value: Value) {+ let node = self.func.node(value);+ match node.op {+ op if op.is_terminator() => self.lower_terminator(value),+ Op::Load | Op::Store | Op::GlobalGet | Op::GlobalSet | Op::InstanceField | Op::LoadPointer => {+ self.lower_memory(value);+ }+ Op::Call | Op::CallResult => self.lower_call(value),+ Op::Offset+ | Op::ReadField+ | Op::WriteField+ | Op::TableElement+ | Op::TableStore+ | Op::CalleeInstance+ | Op::CheckNull+ | Op::CheckFunction+ | Op::Helper => self.lower_runtime(value),+ Op::VectorLoad => self.lower_memory(value),+ Op::VectorUnary+ | Op::VectorBinary+ | Op::VectorTernary+ | Op::ExtractLane+ | Op::ReplaceLane+ | Op::Shuffle => self.lower_vector(value),+ _ => self.lower_numeric(value),+ }+ }++ /// The constant of input `index` of `value`, which code generation uses as an immediate.+ fn immediate(&self, value: Value, index: usize) -> u64 {+ let input = self.func.inputs(value)[index];+ self.func.node(input).constant().expect("immediates are constants")+ }+}++/// Generates the code of `func`.+pub fn generate(+ func: &Func,+ liveliness: &Liveliness,+ allocation: &Allocation,+ runtime: &RuntimeInfo,+) -> Result<Generated, crate::CompileFailure> {+ let _ = NONE;+ CodeGenerator::new(func, liveliness, allocation, runtime).generate()+}diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rsnew file mode 100644index 00000000000..4d2a6b5c9fa--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/numeric.rs@@ -0,0 +1,535 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Integer and float arithmetic, comparisons, selects and conversions.++use super::{CodeGenerator, SCRATCH, SCRATCH_FPR, condition, fpr, gpr, precision, width};+use crate::asm::x86_64::{AluOp, BitCount, BitwiseOp, Cond, FloatOp, Precision, Rounding, ShiftOp, ShiftX};+use crate::asm::{Address, Fpr, Gpr, Width};+use crate::convention::Register;+use crate::ir::{FLAG_CANNOT_TRAP, FloatCondition, IntCondition, Op, Type, Value};+use crate::regalloc::CONSTANT_INPUT;+use libwasm_module::abi::{TRAP_INTEGER_DIVIDE_BY_ZERO, TRAP_INTEGER_OVERFLOW, TRAP_INVALID_CONVERSION};++/// The sign bit of a float type.+fn sign_bit(ty: Type) -> u64 {+ if ty == Type::F64 { 1 << 63 } else { 1 << 31 }+}++fn float_bits(ty: Type, value: f64) -> u64 {+ if ty == Type::F64 {+ value.to_bits()+ } else {+ u64::from((value as f32).to_bits())+ }+}++impl CodeGenerator<'_> {+ pub(super) fn lower_numeric(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let [a, b, c] = record.inputs;+ let output = record.output;+ let ty = node.ty;+ match node.op {+ Op::Add => self.add(value, ty, output, a, b),+ Op::Sub => self.sub(value, ty, output, a, b),+ Op::And => self.logic(value, AluOp::And, ty, output, a, b),+ Op::Or => self.logic(value, AluOp::Or, ty, output, a, b),+ Op::Xor => self.logic(value, AluOp::Xor, ty, output, a, b),+ Op::Mul => {+ let (dst, a_register) = (gpr(output), gpr(a));+ if b == CONSTANT_INPUT {+ let immediate = self.immediate(value, 1) as i32;+ self.asm.imul_rri(width(ty), dst, a_register, immediate);+ } else if output == a {+ self.asm.imul_rr(width(ty), dst, gpr(b));+ } else if output == b {+ self.asm.imul_rr(width(ty), dst, a_register);+ } else {+ self.asm.mov_rr(width(ty), dst, a_register);+ self.asm.imul_rr(width(ty), dst, gpr(b));+ }+ }+ Op::Shl | Op::ShrS | Op::ShrU => {+ let (dst, source) = (gpr(output), gpr(a));+ if b == CONSTANT_INPUT {+ let amount = (self.immediate(value, 1) as u32 & (if ty == Type::I64 { 63 } else { 31 })) as u8;+ if output != a {+ self.asm.mov_rr(width(ty), dst, source);+ }+ let op = match node.op {+ Op::Shl => ShiftOp::Shl,+ Op::ShrS => ShiftOp::Sar,+ _ => ShiftOp::Shr,+ };+ self.asm.shift_ri(op, width(ty), dst, amount);+ } else {+ let op = match node.op {+ Op::Shl => ShiftX::Shl,+ Op::ShrS => ShiftX::Sar,+ _ => ShiftX::Shr,+ };+ self.asm.shiftx(op, width(ty), dst, source, gpr(b));+ }+ }+ Op::Rotl | Op::Rotr => {+ let (dst, source) = (gpr(output), gpr(a));+ let bits = if ty == Type::I64 { 64 } else { 32 };+ if b == CONSTANT_INPUT {+ let amount = self.immediate(value, 1) as u32 % bits;+ let right = if node.op == Op::Rotr {+ amount+ } else {+ (bits - amount) % bits+ };+ self.asm.rorx(width(ty), dst, source, right as u8);+ } else {+ if output != a {+ self.asm.mov_rr(width(ty), dst, source);+ }+ let op = if node.op == Op::Rotl {+ ShiftOp::Rol+ } else {+ ShiftOp::Ror+ };+ self.asm.shift_rcl(op, width(ty), dst);+ }+ }+ Op::DivS | Op::DivU | Op::RemS | Op::RemU => self.divide(value, ty, b),+ Op::Clz | Op::Ctz | Op::Popcnt => {+ let count = match node.op {+ Op::Clz => BitCount::Lzcnt,+ Op::Ctz => BitCount::Tzcnt,+ _ => BitCount::Popcnt,+ };+ self.asm.bit_count(count, width(ty), gpr(output), gpr(a));+ }+ Op::Eqz => {+ let input_type = func.node(node.args[0]).ty;+ let dst = gpr(output);+ self.asm.xor_rr(Width::W32, dst, dst);+ self.asm.test_rr(width(input_type), gpr(a), gpr(a));+ self.asm.setcc(Cond::Equal, dst);+ }+ Op::Compare => {+ let input_type = func.node(node.args[0]).ty;+ let dst = gpr(output);+ self.asm.xor_rr(Width::W32, dst, dst);+ self.compare(input_type, a, b, node.args[1]);+ self.asm.setcc(condition(IntCondition::from_flags(node.flags)), dst);+ }+ Op::Extend8S => self.asm.movsx8_rr(width(ty), gpr(output), gpr(a)),+ Op::Extend16S => self.asm.movsx16_rr(width(ty), gpr(output), gpr(a)),+ Op::Extend32S | Op::ExtendI32S => self.asm.movsxd_rr(gpr(output), gpr(a)),+ Op::ExtendI32U | Op::Wrap => self.asm.mov_rr(Width::W32, gpr(output), gpr(a)),+ Op::Select => {+ if ty.uses_xmm() {+ let skip = self.asm.new_label();+ self.asm.vmovaps_rr(fpr(output), fpr(c));+ self.asm.test_rr(Width::W32, gpr(a), gpr(a));+ self.asm.jcc(Cond::Equal, skip);+ self.asm.vmovaps_rr(fpr(output), fpr(b));+ self.asm.bind(skip);+ } else {+ self.asm.mov_rr(Width::W64, gpr(output), gpr(c));+ self.asm.test_rr(Width::W32, gpr(a), gpr(a));+ self.asm.cmovcc(Cond::NotEqual, Width::W64, gpr(output), gpr(b));+ }+ }+ Op::FAdd | Op::FSub | Op::FMul | Op::FDiv => {+ let op = match node.op {+ Op::FAdd => FloatOp::Add,+ Op::FSub => FloatOp::Sub,+ Op::FMul => FloatOp::Mul,+ _ => FloatOp::Div,+ };+ self.asm.vfloat_rrr(op, precision(ty), fpr(output), fpr(a), fpr(b));+ }+ Op::FSqrt => self+ .asm+ .vfloat_rrr(FloatOp::Sqrt, precision(ty), fpr(output), fpr(a), fpr(a)),+ Op::FMin | Op::FMax => self.min_max(node.op == Op::FMin, ty, output, a, b),+ Op::FCopysign => {+ let temp = fpr(record.temps[0]);+ self.load_float_constant(ty, sign_bit(ty), SCRATCH_FPR);+ self.asm.vbitwise_rrr(BitwiseOp::And, temp, SCRATCH_FPR, fpr(b));+ self.asm+ .vbitwise_rrr(BitwiseOp::AndNot, fpr(output), SCRATCH_FPR, fpr(a));+ self.asm.vbitwise_rrr(BitwiseOp::Or, fpr(output), fpr(output), temp);+ }+ Op::FAbs => {+ self.load_float_constant(ty, sign_bit(ty), SCRATCH_FPR);+ self.asm+ .vbitwise_rrr(BitwiseOp::AndNot, fpr(output), SCRATCH_FPR, fpr(a));+ }+ Op::FNeg => {+ self.load_float_constant(ty, sign_bit(ty), SCRATCH_FPR);+ self.asm.vbitwise_rrr(BitwiseOp::Xor, fpr(output), fpr(a), SCRATCH_FPR);+ }+ Op::FCeil | Op::FFloor | Op::FTrunc | Op::FNearest => {+ let rounding = match node.op {+ Op::FCeil => Rounding::Up,+ Op::FFloor => Rounding::Down,+ Op::FTrunc => Rounding::TowardZero,+ _ => Rounding::Nearest,+ };+ self.asm.vround(precision(ty), fpr(output), fpr(a), rounding);+ }+ Op::FloatCompare => self.float_compare(value, output, a, b, record.temps[0]),+ Op::TruncS | Op::TruncU => self.truncate(value, ty, output, a, record.temps[0]),+ Op::TruncSatS | Op::TruncSatU => self.truncate_saturating(value, ty, output, a, record.temps[0]),+ Op::ConvertS => {+ let input_type = func.node(node.args[0]).ty;+ let dst = fpr(output);+ self.asm.vbitwise_rrr(BitwiseOp::Xor, dst, dst, dst);+ self.asm.vcvtsi2s(precision(ty), width(input_type), dst, dst, gpr(a));+ }+ Op::ConvertU => self.convert_unsigned(value, ty, output, a, record.temps[0]),+ Op::Demote => self.asm.vcvtsd2ss(fpr(output), fpr(a), fpr(a)),+ Op::Promote => self.asm.vcvtss2sd(fpr(output), fpr(a), fpr(a)),+ Op::Reinterpret => {+ if ty.is_float() {+ self.asm.vmov_xr(width(ty), fpr(output), gpr(a));+ } else {+ self.asm.vmov_rx(width(ty), gpr(output), fpr(a));+ }+ }+ _ => unreachable!("{} is no numeric op", node.op.name()),+ }+ }++ fn add(&mut self, value: Value, ty: Type, output: Register, a: Register, b: Register) {+ let (dst, a_register) = (gpr(output), gpr(a));+ if b == CONSTANT_INPUT {+ let immediate = self.immediate(value, 1) as i32;+ if output == a {+ self.asm.add_ri(width(ty), dst, immediate);+ } else {+ self.asm.lea(width(ty), dst, &Address::new(a_register, immediate));+ }+ } else if output == a {+ self.asm.add_rr(width(ty), dst, gpr(b));+ } else if output == b {+ self.asm.add_rr(width(ty), dst, a_register);+ } else {+ self.asm.lea(+ width(ty),+ dst,+ &Address::indexed(a_register, gpr(b), crate::asm::Scale::One, 0),+ );+ }+ }++ fn sub(&mut self, value: Value, ty: Type, output: Register, a: Register, b: Register) {+ let (dst, a_register) = (gpr(output), gpr(a));+ if b == CONSTANT_INPUT {+ let immediate = self.immediate(value, 1) as i32;+ if output != a {+ self.asm.mov_rr(width(ty), dst, a_register);+ }+ self.asm.sub_ri(width(ty), dst, immediate);+ } else if output == a {+ self.asm.sub_rr(width(ty), dst, gpr(b));+ } else if output == b {+ self.asm.neg(width(ty), dst);+ self.asm.add_rr(width(ty), dst, a_register);+ } else {+ self.asm.mov_rr(width(ty), dst, a_register);+ self.asm.sub_rr(width(ty), dst, gpr(b));+ }+ }++ fn logic(&mut self, value: Value, op: AluOp, ty: Type, output: Register, a: Register, b: Register) {+ let (dst, a_register) = (gpr(output), gpr(a));+ if b == CONSTANT_INPUT {+ let immediate = self.immediate(value, 1) as i32;+ if output != a {+ self.asm.mov_rr(width(ty), dst, a_register);+ }+ self.asm.alu_ri(op, width(ty), dst, immediate);+ } else if output == a {+ self.asm.alu_rr(op, width(ty), dst, gpr(b));+ } else if output == b {+ self.asm.alu_rr(op, width(ty), dst, a_register);+ } else {+ self.asm.mov_rr(width(ty), dst, a_register);+ self.asm.alu_rr(op, width(ty), dst, gpr(b));+ }+ }++ /// Division and remainder: the dividend is in rax, the quotient goes to rax and the remainder to rdx.+ fn divide(&mut self, value: Value, ty: Type, divisor: Register) {+ let node = *self.func.node(value);+ let divisor = gpr(divisor);+ let w = width(ty);+ let rax = Gpr(crate::convention::RAX);+ let rdx = Gpr(crate::convention::RDX);+ let checked = node.flags & FLAG_CANNOT_TRAP == 0;+ if checked {+ let zero = self.trap_label(TRAP_INTEGER_DIVIDE_BY_ZERO);+ self.asm.test_rr(w, divisor, divisor);+ self.asm.jcc(Cond::Equal, zero);+ }+ match node.op {+ Op::DivU | Op::RemU => {+ self.asm.xor_rr(Width::W32, rdx, rdx);+ self.asm.div(w, divisor);+ }+ Op::DivS => {+ if checked {+ // INT_MIN / -1 overflows.+ let divide = self.asm.new_label();+ let overflow = self.trap_label(TRAP_INTEGER_OVERFLOW);+ self.asm.cmp_ri(w, divisor, -1);+ self.asm.jcc(Cond::NotEqual, divide);+ if ty == Type::I64 {+ self.asm.mov_ri(SCRATCH, 1 << 63);+ self.asm.cmp_rr(w, rax, SCRATCH);+ } else {+ self.asm.cmp_ri(w, rax, i32::MIN);+ }+ self.asm.jcc(Cond::Equal, overflow);+ self.asm.bind(divide);+ }+ self.asm.sign_extend_rax_into_rdx(w);+ self.asm.idiv(w, divisor);+ }+ _ => {+ if checked {+ // INT_MIN % -1 overflows idiv, but is 0.+ let divide = self.asm.new_label();+ let done = self.asm.new_label();+ self.asm.cmp_ri(w, divisor, -1);+ self.asm.jcc(Cond::NotEqual, divide);+ self.asm.xor_rr(Width::W32, rdx, rdx);+ self.asm.jmp(done);+ self.asm.bind(divide);+ self.asm.sign_extend_rax_into_rdx(w);+ self.asm.idiv(w, divisor);+ self.asm.bind(done);+ } else {+ self.asm.sign_extend_rax_into_rdx(w);+ self.asm.idiv(w, divisor);+ }+ }+ }+ }++ /// Loads a float type's constant `bits` into `register`.+ fn load_float_constant(&mut self, ty: Type, bits: u64, register: Fpr) {+ let label = self.constant_label(u128::from(bits));+ self.asm.vmovs_r_label(precision(ty), register, label);+ }++ fn min_max(&mut self, minimum: bool, ty: Type, output: Register, a: Register, b: Register) {+ let p = precision(ty);+ let (dst, a, b) = (fpr(output), fpr(a), fpr(b));+ let nan = self.asm.new_label();+ let ordinary = self.asm.new_label();+ let done = self.asm.new_label();+ self.asm.vucomis(p, a, b);+ self.asm.jcc(Cond::Parity, nan);+ self.asm.jcc(Cond::NotEqual, ordinary);+ // Equal values: only the signs of zeros may differ, and min takes the negative one.+ let op = if minimum { BitwiseOp::Or } else { BitwiseOp::And };+ self.asm.vbitwise_rrr(op, dst, a, b);+ self.asm.jmp(done);+ self.asm.bind(nan);+ self.asm.vfloat_rrr(FloatOp::Add, p, dst, a, b);+ self.asm.jmp(done);+ self.asm.bind(ordinary);+ let op = if minimum { FloatOp::Min } else { FloatOp::Max };+ self.asm.vfloat_rrr(op, p, dst, a, b);+ self.asm.bind(done);+ }++ fn float_compare(&mut self, value: Value, output: Register, a: Register, b: Register, temp: Register) {+ let node = *self.func.node(value);+ let ty = self.func.node(node.args[0]).ty;+ let p = precision(ty);+ let (dst, a, b) = (gpr(output), fpr(a), fpr(b));+ self.asm.xor_rr(Width::W32, dst, dst);+ match FloatCondition::from_flags(node.flags) {+ FloatCondition::Eq | FloatCondition::Ne => {+ let equal = FloatCondition::from_flags(node.flags) == FloatCondition::Eq;+ let temp = gpr(temp);+ self.asm.xor_rr(Width::W32, temp, temp);+ self.asm.vucomis(p, a, b);+ if equal {+ self.asm.setcc(Cond::Equal, dst);+ self.asm.setcc(Cond::NotParity, temp);+ self.asm.and_rr(Width::W32, dst, temp);+ } else {+ self.asm.setcc(Cond::NotEqual, dst);+ self.asm.setcc(Cond::Parity, temp);+ self.asm.or_rr(Width::W32, dst, temp);+ }+ }+ FloatCondition::Gt => {+ self.asm.vucomis(p, a, b);+ self.asm.setcc(Cond::Above, dst);+ }+ FloatCondition::Ge => {+ self.asm.vucomis(p, a, b);+ self.asm.setcc(Cond::AboveOrEqual, dst);+ }+ FloatCondition::Lt => {+ self.asm.vucomis(p, b, a);+ self.asm.setcc(Cond::Above, dst);+ }+ FloatCondition::Le => {+ self.asm.vucomis(p, b, a);+ self.asm.setcc(Cond::AboveOrEqual, dst);+ }+ }+ }++ /// Compares `source` with the float constant `bound` of type `input` (`vucomis source, bound`).+ fn compare_with_constant(&mut self, input: Type, source: Fpr, bound: f64, temp: Fpr) {+ self.load_float_constant(input, float_bits(input, bound), temp);+ self.asm.vucomis(precision(input), source, temp);+ }++ /// The trapping truncations of floats to integers.+ fn truncate(&mut self, value: Value, ty: Type, output: Register, source: Register, temp: Register) {+ let node = *self.func.node(value);+ let input = self.func.node(node.args[0]).ty;+ let (dst, source, temp) = (gpr(output), fpr(source), fpr(temp));+ let p = precision(input);+ let invalid = self.trap_label(TRAP_INVALID_CONVERSION);+ let overflow = self.trap_label(TRAP_INTEGER_OVERFLOW);+ self.asm.vucomis(p, source, source);+ self.asm.jcc(Cond::Parity, invalid);+ let signed = node.op == Op::TruncS;+ let bits = if ty == Type::I64 { 64 } else { 32 };+ let limit = 2f64.powi(if signed { bits - 1 } else { bits });+ // The lower bound: values at or below it overflow (or below it, where it is exact).+ let (lower, below_only) = match (signed, bits, input) {+ (true, 32, Type::F64) => (-limit - 1.0, false),+ (true, _, _) => (-limit, true),+ (false, _, _) => (-1.0, false),+ };+ self.compare_with_constant(input, source, lower, temp);+ self.asm+ .jcc(if below_only { Cond::Below } else { Cond::BelowOrEqual }, overflow);+ self.compare_with_constant(input, source, limit, temp);+ self.asm.jcc(Cond::AboveOrEqual, overflow);+ if signed {+ self.asm.vcvtts2si(p, width(ty), dst, source);+ } else if ty == Type::I32 {+ self.asm.vcvtts2si(p, Width::W64, dst, source);+ } else {+ self.truncate_u64(p, input, dst, source, temp);+ }+ }++ /// Truncates `source`, which is not negative and below 2^64, to a u64.+ fn truncate_u64(&mut self, p: Precision, input: Type, dst: Gpr, source: Fpr, temp: Fpr) {+ let large = self.asm.new_label();+ let done = self.asm.new_label();+ self.compare_with_constant(input, source, 2f64.powi(63), temp);+ self.asm.jcc(Cond::AboveOrEqual, large);+ self.asm.vcvtts2si(p, Width::W64, dst, source);+ self.asm.jmp(done);+ self.asm.bind(large);+ self.asm.vfloat_rrr(FloatOp::Sub, p, temp, source, temp);+ self.asm.vcvtts2si(p, Width::W64, dst, temp);+ self.asm.mov_ri(SCRATCH, 1 << 63);+ self.asm.xor_rr(Width::W64, dst, SCRATCH);+ self.asm.bind(done);+ }++ /// The saturating truncations of floats to integers.+ fn truncate_saturating(&mut self, value: Value, ty: Type, output: Register, source: Register, temp: Register) {+ let node = *self.func.node(value);+ let input = self.func.node(node.args[0]).ty;+ let (dst, source, temp) = (gpr(output), fpr(source), fpr(temp));+ let p = precision(input);+ let w = width(ty);+ let done = self.asm.new_label();+ let zero = self.asm.new_label();+ let maximum = self.asm.new_label();+ if node.op == Op::TruncSatS {+ // The conversion gives INT_MIN for NaN and out of range values; only some of those want another result.+ self.asm.vcvtts2si(p, w, dst, source);+ if ty == Type::I64 {+ self.asm.mov_ri(SCRATCH, 1 << 63);+ self.asm.cmp_rr(w, dst, SCRATCH);+ } else {+ self.asm.cmp_ri(w, dst, i32::MIN);+ }+ self.asm.jcc(Cond::NotEqual, done);+ self.asm.vucomis(p, source, source);+ self.asm.jcc(Cond::Parity, zero);+ self.asm.vbitwise_rrr(BitwiseOp::Xor, temp, temp, temp);+ self.asm.vucomis(p, source, temp);+ self.asm.jcc(Cond::Below, done);+ self.asm.bind(maximum);+ if ty == Type::I64 {+ self.asm.mov_ri(dst, i64::MAX as u64);+ } else {+ self.asm.mov_ri32(dst, i32::MAX as u32);+ }+ self.asm.jmp(done);+ } else {+ self.asm.vbitwise_rrr(BitwiseOp::Xor, temp, temp, temp);+ self.asm.vucomis(p, source, temp);+ self.asm.jcc(Cond::Parity, zero);+ self.asm.jcc(Cond::Below, zero);+ let bits = if ty == Type::I64 { 64 } else { 32 };+ self.compare_with_constant(input, source, 2f64.powi(bits), temp);+ self.asm.jcc(Cond::AboveOrEqual, maximum);+ if ty == Type::I32 {+ self.asm.vcvtts2si(p, Width::W64, dst, source);+ } else {+ self.truncate_u64(p, input, dst, source, temp);+ }+ self.asm.jmp(done);+ self.asm.bind(maximum);+ if ty == Type::I64 {+ self.asm.mov_ri(dst, u64::MAX);+ } else {+ self.asm.mov_ri32(dst, u32::MAX);+ }+ self.asm.jmp(done);+ }+ self.asm.bind(zero);+ self.asm.xor_rr(Width::W32, dst, dst);+ self.asm.bind(done);+ }++ fn convert_unsigned(&mut self, value: Value, ty: Type, output: Register, source: Register, temp: Register) {+ let node = *self.func.node(value);+ let input = self.func.node(node.args[0]).ty;+ let (dst, source) = (fpr(output), gpr(source));+ let p = precision(ty);+ self.asm.vbitwise_rrr(BitwiseOp::Xor, dst, dst, dst);+ if input == Type::I32 {+ // A zero-extended u32 is a nonnegative i64.+ self.asm.vcvtsi2s(p, Width::W64, dst, dst, source);+ return;+ }+ let temp = gpr(temp);+ let large = self.asm.new_label();+ let done = self.asm.new_label();+ self.asm.test_rr(Width::W64, source, source);+ self.asm.jcc(Cond::Sign, large);+ self.asm.vcvtsi2s(p, Width::W64, dst, dst, source);+ self.asm.jmp(done);+ self.asm.bind(large);+ // Halve, keeping the low bit for rounding, convert, and double.+ self.asm.mov_rr(Width::W64, temp, source);+ self.asm.shr_ri(Width::W64, temp, 1);+ self.asm.mov_rr(Width::W32, SCRATCH, source);+ self.asm.and_ri(Width::W32, SCRATCH, 1);+ self.asm.or_rr(Width::W64, temp, SCRATCH);+ self.asm.vcvtsi2s(p, Width::W64, dst, dst, temp);+ self.asm.vfloat_rrr(FloatOp::Add, p, dst, dst, dst);+ self.asm.bind(done);+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rsnew file mode 100644index 00000000000..5556c6a1358--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs@@ -0,0 +1,215 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Runtime data: fields of memories, tables and segments, table elements, the checks of indirect calls, and calls of+//! the runtime's functions.++use super::{CodeGenerator, FP, SCRATCH, gpr};+use crate::asm::x86_64::AluOp;+use crate::asm::x86_64::Cond;+use crate::asm::{Address, Gpr, Label, Scale, Width};+use crate::convention;+use crate::ir::{Helper, Op, Value};+use crate::regalloc::CONSTANT_INPUT;+use libwasm_module::abi::{+ ExecutionContext, FunctionHeader, InstanceData, Rtt, TRAP_INDIRECT_CALL_TYPE_MISMATCH, TableData,+};+use std::mem::offset_of;++/// The out-of-line part of a `CheckFunction`: whether a function whose type is not the expected one has a subtype of+/// it, which only GC modules can declare.+pub(super) struct SubtypeCheck {+ label: Label,+ back: Label,+ reference: Gpr,+ identity: Gpr,+ temps: [Gpr; 2],+}++fn field_width(bytes: u8) -> Width {+ if bytes == 4 { Width::W32 } else { Width::W64 }+}++impl CodeGenerator<'_> {+ pub(super) fn lower_runtime(&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::Offset => {+ self.asm.lea(+ Width::W64,+ gpr(record.output),+ &Address::new(input(0), node.args[1] as i32),+ );+ }+ Op::ReadField => {+ self.asm.mov_rm(+ field_width(node.flags),+ gpr(record.output),+ &Address::new(input(0), node.args[1] as i32),+ );+ }+ Op::WriteField => {+ let address = Address::new(input(0), node.args[2] as i32);+ let width = field_width(node.flags);+ if record.inputs[1] == CONSTANT_INPUT {+ let bits = self.immediate(value, 1);+ self.asm.mov_mi(width, &address, bits as i32);+ } else {+ self.asm.mov_mr(width, &address, input(1));+ }+ }+ Op::TableElement | Op::TableStore => {+ let (table, index) = (input(0), input(1));+ self.asm.alu_rm(+ AluOp::Cmp,+ Width::W64,+ index,+ &Address::new(table, offset_of!(TableData, size) as i32),+ );+ let out_of_bounds = self.trap_label(u32::from(node.flags));+ self.asm.jcc(Cond::AboveOrEqual, out_of_bounds);+ self.asm.mov_rm(+ Width::W64,+ SCRATCH,+ &Address::new(table, offset_of!(TableData, elements) as i32),+ );+ let element = Address::indexed(SCRATCH, index, Scale::Eight, 0);+ if node.op == Op::TableElement {+ self.asm.mov_rm(Width::W64, gpr(record.output), &element);+ } else {+ self.asm.mov_mr(Width::W64, &element, input(2));+ }+ }+ Op::CalleeInstance => {+ let (header, caller, output) = (input(0), input(1), gpr(record.output));+ self.asm.mov_rm(+ Width::W64,+ SCRATCH,+ &Address::new(header, offset_of!(FunctionHeader, instance) as i32),+ );+ if output != caller {+ self.asm.mov_rr(Width::W64, output, caller);+ }+ self.asm.test_rr(Width::W64, SCRATCH, SCRATCH);+ self.asm.cmovcc(Cond::NotEqual, Width::W64, output, SCRATCH);+ }+ Op::CheckNull => {+ let null = self.trap_label(u32::from(node.flags));+ self.asm.test_rr(Width::W64, input(0), input(0));+ self.asm.jcc(Cond::Equal, null);+ }+ Op::CheckFunction => {+ let (reference, identity) = (input(0), input(1));+ let null = self.trap_label(u32::from(node.flags));+ self.asm.test_rr(Width::W64, reference, reference);+ self.asm.jcc(Cond::Equal, null);+ self.asm.cmp_mr(+ Width::W32,+ &Address::new(reference, offset_of!(FunctionHeader, type_identity) as i32),+ identity,+ );+ let label = self.asm.new_label();+ let back = self.asm.new_label();+ self.asm.jcc(Cond::NotEqual, label);+ self.asm.bind(back);+ self.subtype_checks.push(SubtypeCheck {+ label,+ back,+ reference,+ identity,+ temps: [gpr(record.temps[0]), gpr(record.temps[1])],+ });+ }+ Op::Helper => {+ let helper = Helper::from_index(node.args[2]);+ let context = Gpr(convention::RDI);+ self.asm.mov_rm(+ Width::W64,+ context,+ &Address::new(context, offset_of!(InstanceData, context) as i32),+ );+ let arguments = offset_of!(ExecutionContext, arguments) as i32;+ for index in 1..func.inputs(value).len() {+ self.asm.mov_mr(+ Width::W64,+ &Address::new(context, arguments + 8 * (index as i32 - 1)),+ Gpr(convention::HELPER_REGISTERS[index]),+ );+ }+ let target = Gpr(convention::RAX);+ self.asm+ .mov_ri(target, crate::runtime::helper_address(helper, self.runtime));+ self.asm.call_r(target);+ if helper.may_trap() {+ let trap = self.dynamic_trap_label();+ self.asm.test_rr(Width::W64, target, target);+ self.asm.jcc(Cond::NotEqual, trap);+ }+ }+ _ => unreachable!("{} is no runtime operation", node.op.name()),+ }+ }++ pub(super) fn subtype_checks(&mut self) {+ let checks = std::mem::take(&mut self.subtype_checks);+ if checks.is_empty() {+ return;+ }+ let mismatch = self.trap_label(TRAP_INDIRECT_CALL_TYPE_MISMATCH);+ for check in checks {+ let [rtts, actual] = check.temps;+ self.asm.bind(check.label);+ self.asm+ .mov_rm(Width::W64, rtts, &Address::new(FP, convention::FRAME_INSTANCE));+ self.asm.mov_rm(+ Width::W64,+ rtts,+ &Address::new(rtts, offset_of!(InstanceData, context) as i32),+ );+ self.asm.mov_rm(+ Width::W64,+ rtts,+ &Address::new(rtts, offset_of!(ExecutionContext, rtts) as i32),+ );+ self.asm.mov_rm(+ Width::W32,+ SCRATCH,+ &Address::new(check.reference, offset_of!(FunctionHeader, type_identity) as i32),+ );+ self.asm+ .mov_rm(Width::W64, actual, &Address::indexed(rtts, SCRATCH, Scale::Eight, 0));+ self.asm.mov_rr(Width::W32, SCRATCH, check.identity);+ let target = rtts;+ self.asm+ .mov_rm(Width::W64, target, &Address::indexed(rtts, SCRATCH, Scale::Eight, 0));+ self.asm.mov_rm(+ Width::W32,+ SCRATCH,+ &Address::new(target, offset_of!(Rtt, depth) as i32),+ );+ // The expected type is a supertype if it is at its depth in the actual type's display.+ self.asm.cmp_mr(+ Width::W32,+ &Address::new(actual, offset_of!(Rtt, depth) as i32),+ SCRATCH,+ );+ self.asm.jcc(Cond::Below, mismatch);+ self.asm.mov_rm(+ Width::W64,+ actual,+ &Address::new(actual, offset_of!(Rtt, display) as i32),+ );+ self.asm+ .mov_rm(Width::W32, actual, &Address::indexed(actual, SCRATCH, Scale::Four, 0));+ self.asm.cmp_rr(Width::W32, actual, check.identity);+ self.asm.jcc(Cond::NotEqual, mismatch);+ self.asm.jmp(check.back);+ }+ }+}diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rsnew file mode 100644index 00000000000..96e0ade58d8--- /dev/null+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs@@ -0,0 +1,482 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Vectors: v128 loads, constants, lanes and SIMD arithmetic, as AVX2 instructions on xmm registers.++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 libwasm_module::opcode::simd::*;++const fn op(prefix: VexPrefix, map: VexMap, opcode: u8) -> VexOpcode {+ VexOpcode::new(prefix, map, opcode)+}++const fn op66(opcode: u8) -> VexOpcode {+ op(VexPrefix::OperandSize, VexMap::Map0F, opcode)+}++const fn op66_38(opcode: u8) -> VexOpcode {+ op(VexPrefix::OperandSize, VexMap::Map0F38, opcode)+}++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);+const VMOVD_LOAD: VexOpcode = op66(0x6e);+const VMOVQ_LOAD: VexOpcode = op(VexPrefix::Rep, VexMap::Map0F, 0x7e);+const VPXOR: VexOpcode = op66(0xef);+const VPAND: VexOpcode = op66(0xdb);+const VPANDN: VexOpcode = op66(0xdf);+const VPOR: VexOpcode = op66(0xeb);+const VPCMPEQD: VexOpcode = op66(0x76);+const VPTEST: VexOpcode = op66_38(0x17);+const VPSHUFB: VexOpcode = op66_38(0x00);+const VPADDUSB: VexOpcode = op66(0xdc);+const VPSUBB: VexOpcode = op66(0xf8);+const VPSUBW: VexOpcode = op66(0xf9);+const VPSUBD: VexOpcode = op66(0xfa);+const VPSUBQ: VexOpcode = op66(0xfb);+const VPBROADCASTB: VexOpcode = op66_38(0x78);+const VPBROADCASTW: VexOpcode = op66_38(0x79);+const VPBROADCASTD: VexOpcode = op66_38(0x58);+const VPBROADCASTQ: VexOpcode = op66_38(0x59);+const VBROADCASTSS: VexOpcode = op66_38(0x18);+const VMOVDDUP: VexOpcode = op(VexPrefix::Repne, VexMap::Map0F, 0x12);+const VPEXTRB: VexOpcode = op66_3a(0x14);+const VPEXTRW: VexOpcode = op66_3a(0x15);+const VPEXTRD: VexOpcode = op66_3a(0x16);+const VPINSRB: VexOpcode = op66_3a(0x20);+const VPINSRW: VexOpcode = op66(0xc4);+const VPINSRD: VexOpcode = op66_3a(0x22);+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 VPMOVMSKB: VexOpcode = op66(0xd7);+const VMOVMSKPS: VexOpcode = op(VexPrefix::None, VexMap::Map0F, 0x50);+const VMOVMSKPD: VexOpcode = op66(0x50);+const VANDNPS: VexOpcode = op(VexPrefix::None, VexMap::Map0F, 0x55);+const VXORPS: VexOpcode = op(VexPrefix::None, VexMap::Map0F, 0x57);++/// 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`.+struct Binary {+ opcode: VexOpcode,+ swap: bool,+ invert: bool,+ immediate: Option<u8>,+}++const fn plain(opcode: VexOpcode) -> Binary {+ Binary {+ opcode,+ swap: false,+ invert: false,+ immediate: None,+ }+}++fn binary(sub_opcode: u32) -> Option<Binary> {+ let swapped = |opcode| Binary {+ opcode,+ swap: true,+ invert: false,+ immediate: None,+ };+ let inverted = |opcode| Binary {+ opcode,+ swap: false,+ invert: true,+ immediate: None,+ };+ let compare = |opcode, swap, immediate| Binary {+ opcode,+ swap,+ invert: false,+ immediate: Some(immediate),+ };+ let ps = op(VexPrefix::None, VexMap::Map0F, 0xc2);+ let pd = op66(0xc2);+ 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_GT_S => plain(op66(0x64)),+ I16X8_GT_S => plain(op66(0x65)),+ I32X4_GT_S => plain(op66(0x66)),+ I64X2_GT_S => plain(op66_38(0x37)),+ 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)),+ F32X4_EQ => compare(ps, false, 0),+ F32X4_NE => compare(ps, false, 4),+ F32X4_LT => compare(ps, false, 1),+ F32X4_LE => compare(ps, false, 2),+ F32X4_GT => compare(ps, true, 1),+ F32X4_GE => compare(ps, true, 2),+ F64X2_EQ => compare(pd, false, 0),+ F64X2_NE => compare(pd, false, 4),+ F64X2_LT => compare(pd, false, 1),+ F64X2_LE => compare(pd, false, 2),+ F64X2_GT => compare(pd, true, 1),+ F64X2_GE => compare(pd, true, 2),+ I8X16_ADD => plain(op66(0xfc)),+ I16X8_ADD => plain(op66(0xfd)),+ I32X4_ADD => plain(op66(0xfe)),+ I64X2_ADD => plain(op66(0xd4)),+ I8X16_SUB => plain(VPSUBB),+ I16X8_SUB => plain(VPSUBW),+ I32X4_SUB => plain(VPSUBD),+ I64X2_SUB => plain(VPSUBQ),+ I8X16_ADD_SAT_S => plain(op66(0xec)),+ 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)),+ I32X4_MUL => plain(op66_38(0x40)),+ I8X16_MIN_S => plain(op66_38(0x38)),+ I8X16_MIN_U => plain(op66(0xda)),+ I8X16_MAX_S => plain(op66_38(0x3c)),+ I8X16_MAX_U => plain(op66(0xde)),+ I16X8_MIN_S => plain(op66(0xea)),+ I16X8_MIN_U => plain(op66_38(0x3a)),+ I16X8_MAX_S => plain(op66(0xee)),+ 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_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)),+ F64X2_DIV => plain(op66(0x5e)),+ _ => 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)> {+ 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),+ _ => return None,+ })+}++fn register(register: Register) -> VexOperand {+ VexOperand::Register(register_number(register))+}++/// The encoding of an allocator register, of either class.+fn register_number(register: Register) -> u8 {+ if crate::convention::is_fpr(register) {+ fpr(register).0+ } else {+ gpr(register).0+ }+}++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);+ }++ /// 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)+ }++ /// 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,+ );+ }++ pub(super) fn vector_load(&mut self, value: Value, address: &Address) {+ let node = *self.func.node(value);+ let dst = fpr(self.allocation.node(value).output).0;+ let memory = VexOperand::Memory(*address);+ let opcode = match u32::from(node.flags) {+ V128_LOAD => VMOVUPS_LOAD,+ V128_LOAD8X8_S => op66_38(0x20),+ V128_LOAD8X8_U => op66_38(0x30),+ V128_LOAD16X4_S => op66_38(0x23),+ V128_LOAD16X4_U => op66_38(0x33),+ V128_LOAD32X2_S => op66_38(0x25),+ V128_LOAD32X2_U => op66_38(0x35),+ V128_LOAD8_SPLAT => VPBROADCASTB,+ V128_LOAD16_SPLAT => VPBROADCASTW,+ V128_LOAD32_SPLAT => VPBROADCASTD,+ V128_LOAD64_SPLAT => VPBROADCASTQ,+ V128_LOAD32_ZERO => VMOVD_LOAD,+ _ => VMOVQ_LOAD,+ };+ self.asm.vex(opcode, dst, 0, memory, None);+ }++ pub(super) fn lower_vector(&mut self, value: Value) {+ let func = self.func;+ let node = *func.node(value);+ let record = *self.allocation.node(value);+ let [a, b, c] = record.inputs;+ let output = record.output;+ 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::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));+ }+ Op::ExtractLane => self.extract_lane(node.args[1], node.args[2] as u8, output, a),+ Op::ReplaceLane => {+ let sub_opcode = node.args[2] & 0xffff;+ let lane = (node.args[2] >> 16) as u8;+ let (dst, vector) = (fpr(output).0, fpr(a).0);+ match sub_opcode {+ I8X16_REPLACE_LANE => self.asm.vex(VPINSRB, dst, vector, register(b), Some(lane)),+ I16X8_REPLACE_LANE => self.asm.vex(VPINSRW, dst, vector, register(b), Some(lane)),+ I32X4_REPLACE_LANE => self.asm.vex(VPINSRD, dst, vector, register(b), Some(lane)),+ I64X2_REPLACE_LANE => self.asm.vex(VPINSRD.w1(), dst, vector, register(b), Some(lane)),+ 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));+ }+ }+ }+ 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));+ }+ _ => unreachable!("{} is no vector op", node.op.name()),+ }+ }++ fn vector_unary(&mut self, sub_opcode: u32, ty: Type, output: Register, a: Register, temp: Register) {+ 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 {+ Width::W32+ };+ self.asm.vmov_xr(width, fpr(output), gpr(a));+ let broadcast = match sub_opcode {+ I8X16_SPLAT => VPBROADCASTB,+ I16X8_SPLAT => VPBROADCASTW,+ I32X4_SPLAT => VPBROADCASTD,+ _ => VPBROADCASTQ,+ };+ self.asm.vex(broadcast, dst, 0, VexOperand::Register(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),+ 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);+ }+ I8X16_NEG | I16X8_NEG | I32X4_NEG | I64X2_NEG => {+ let subtract = match sub_opcode {+ I8X16_NEG => VPSUBB,+ I16X8_NEG => VPSUBW,+ 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));+ }+ 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+ } else {+ 0x8000_0000_0000_0000_8000_0000_0000_0000u128+ };+ 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);+ } else {+ self.asm+ .vex(VMOVUPS_LOAD, SCRATCH_XMM, 0, VexOperand::Label(label), None);+ self.vector_op(VANDNPS, fpr(output).0, SCRATCH_XMM, register(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,+ );+ }+ 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);+ }+ 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),+ };+ 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));+ 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:?}"),+ }+ }++ fn vector_binary(&mut self, sub_opcode: u32, output: Register, a: Register, b: 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));+ 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));+ 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)+ };+ 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));+ }+ }++ fn extract_lane(&mut self, sub_opcode: u32, lane: u8, output: Register, vector: Register) {+ let source = fpr(vector).0;+ match sub_opcode {+ I8X16_EXTRACT_LANE_S | I8X16_EXTRACT_LANE_U => {+ self.asm.vex(VPEXTRB, source, 0, register(output), Some(lane));+ if sub_opcode == I8X16_EXTRACT_LANE_S {+ self.asm.movsx8_rr(Width::W32, gpr(output), gpr(output));+ }+ }+ I16X8_EXTRACT_LANE_S | I16X8_EXTRACT_LANE_U => {+ self.asm.vex(VPEXTRW, source, 0, register(output), Some(lane));+ if sub_opcode == I16X8_EXTRACT_LANE_S {+ self.asm.movsx16_rr(Width::W32, gpr(output), gpr(output));+ }+ }+ I32X4_EXTRACT_LANE => self.asm.vex(VPEXTRD, source, 0, register(output), Some(lane)),+ I64X2_EXTRACT_LANE => self.asm.vex(VPEXTRD.w1(), source, 0, register(output), Some(lane)),+ F32X4_EXTRACT_LANE => self.asm.vex(VPERMILPS, fpr(output).0, 0, register(vector), Some(lane)),+ _ => self.asm.vex(VPERMILPD, fpr(output).0, 0, register(vector), Some(lane)),+ }+ }++ /// Stores the 16 bytes of the vector in `register` at `address`.+ pub(super) fn store_vector(&mut self, register: Register, address: &Address) {+ self.asm+ .vex(VMOVUPS_STORE, fpr(register).0, 0, VexOperand::Memory(*address), None);+ }++ /// Loads 16 bytes at `address` into the xmm register `register` (an encoding).+ pub(super) fn load_vector(&mut self, register: u8, address: &Address) {+ self.asm+ .vex(VMOVUPS_LOAD, register, 0, VexOperand::Memory(*address), None);+ }+}diff --git a/Libraries/LibWasm/JIT/src/convention.rs b/Libraries/LibWasm/JIT/src/convention.rsnew file mode 100644index 00000000000..8e0a900b92a--- /dev/null+++ b/Libraries/LibWasm/JIT/src/convention.rs@@ -0,0 +1,209 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The calling convention between compiled functions on x86-64, and the layout of their frames.+//!+//! - Parameters of integer types go in rdi, rsi, rdx, rcx, r8 and r9, in order, and those of float and vector types+//! in xmm0 to xmm7. Every parameter has a home slot in the caller's outgoing area, at the callee's fp + 8 * the+//! slots of the parameters before it (a v128 takes two, like on the interpreter's operand stack); the parameters+//! that do not fit in registers are passed there.+//! - Results of integer types come back in rax and rdx, and those of float and vector types in xmm0 and xmm1. The+//! results that do not fit go to a result area the caller provides, at 8 * the slots of the results before them;+//! the caller passes its address in the slot after the parameters' home slots.+//! - r14 holds the callee's instance and r15 the base of its memory 0 at the call, and r10 its `FunctionHeader`.+//! - Every register but rsp and rbp is caller-saved. rsp is 16-byte aligned at the call.+//! - A tail call writes its stack arguments into the incoming area and jumps to the callee. If they do not fit, it+//! slides the return address and saved fp down first; callers set rsp from fp after every call, which undoes it.+//! - i32 values are zero-extended to 64 bits in registers and slots; f32 values use the low 32 bits.+//!+//! A compiled frame:+//!+//! ```text+//! fp + 8 * i the parameters' home slots (the caller's outgoing area), then the result area pointer+//! fp - 8 return address+//! fp - 16 caller's fp+//! fp - 64..-16 the rest of the frame header, of which compiled code only writes FRAME_INSTANCE+//! below spill slots, 8 bytes each, two for a v128+//! rsp outgoing area of calls, 8 bytes per argument (and result area pointer, and result area)+//! ```+//!+//! fp is the caller's rsp at the call. The header's first two words are the reverse of the interpreter's current+//! frames; the interpreter moves to this order before compiled code runs in its frames (design, section 6).++use crate::ir::Type;++/// Registers as the register allocator numbers them: general purpose registers by their encoding, xmm registers+/// from `FPR_BASE` on.+pub type Register = u8;++pub const FPR_BASE: Register = 16;++pub const RAX: Register = 0;+pub const RCX: Register = 1;+pub const RDX: Register = 2;+pub const RBX: Register = 3;+pub const RSP: Register = 4;+pub const RBP: Register = 5;+pub const RSI: Register = 6;+pub const RDI: Register = 7;+pub const R8: Register = 8;+pub const R9: Register = 9;+pub const R10: Register = 10;+pub const R11: Register = 11;+pub const R12: Register = 12;+pub const R13: Register = 13;+pub const R14: Register = 14;+pub const R15: Register = 15;++pub const fn xmm(index: u8) -> Register {+ FPR_BASE + index+}++pub const GPR_ARGUMENTS: [Register; 6] = [RDI, RSI, RDX, RCX, R8, R9];+pub const FPR_ARGUMENTS: [Register; 8] = [xmm(0), xmm(1), xmm(2), xmm(3), xmm(4), xmm(5), xmm(6), xmm(7)];+pub const GPR_RESULTS: [Register; 2] = [RAX, RDX];+pub const FPR_RESULTS: [Register; 2] = [xmm(0), xmm(1)];++pub const INSTANCE_REGISTER: Register = R14;+pub const MEMORY_BASE_REGISTER: Register = R15;+pub const CALLEE_REGISTER: Register = R10;++/// Never allocated: moves between memory locations go through them, and lowerings may clobber them.+pub const SCRATCH_GPR: Register = R11;+pub const SCRATCH_FPR: Register = xmm(15);++/// The registers values may live in, in the order the allocator prefers them.+pub const ALLOCATABLE_GPRS: [Register; 13] = [RAX, RCX, RDX, RSI, RDI, R8, R9, R10, RBX, R12, R13, R14, R15];+pub const ALLOCATABLE_FPRS: [Register; 15] = [+ xmm(0),+ xmm(1),+ xmm(2),+ xmm(3),+ xmm(4),+ xmm(5),+ xmm(6),+ xmm(7),+ xmm(8),+ xmm(9),+ xmm(10),+ xmm(11),+ xmm(12),+ xmm(13),+ xmm(14),+];++/// Every allocatable register, as a mask.+pub const ALLOCATABLE: u32 = {+ let mut mask = 0;+ let mut index = 0;+ while index < ALLOCATABLE_GPRS.len() {+ mask |= 1 << ALLOCATABLE_GPRS[index];+ index += 1;+ }+ index = 0;+ while index < ALLOCATABLE_FPRS.len() {+ mask |= 1 << ALLOCATABLE_FPRS[index];+ index += 1;+ }+ mask+};++/// Where a call of a function of the runtime (`Op::Helper`) takes its operands: the instance, from which it finds the+/// context, then the operands, which it stores in the context's `arguments`.+pub const HELPER_REGISTERS: [Register; 7] = [RDI, RSI, RDX, RCX, R8, R9, R10];++/// The registers a call of a function of the runtime overwrites: those the host ABI does not preserve.+pub const HOST_CLOBBERS: u32 = {+ let preserved = (1 << RBX) | (1 << RSP) | (1 << RBP) | (1 << R12) | (1 << R13) | (1 << R14) | (1 << R15);+ !preserved+};++pub fn is_fpr(register: Register) -> bool {+ register >= FPR_BASE+}++/// The frame header, as offsets from fp (see the module documentation).+pub const FRAME_RETURN_ADDRESS: i32 = -8;+pub const FRAME_SAVED_FP: i32 = -16;+pub const FRAME_INSTANCE: i32 = libwasm_module::abi::FRAME_INSTANCE as i32;+pub const FRAME_HEADER_SIZE: i32 = libwasm_module::abi::FRAME_HEADER_SIZE as i32;++/// The fp offset of spill slot `index`.+pub fn spill_slot_offset(index: u32) -> i32 {+ -FRAME_HEADER_SIZE - 8 * (index as i32 + 1)+}++/// The fp offset of the home slot at `slot`, in 8-byte slots from fp.+pub fn home_slot_offset(slot: u32) -> i32 {+ 8 * slot as i32+}++/// Where a parameter or result goes.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Place {+ Register(Register),+ /// A parameter's home slot, or a result's place in the result area, in 8-byte slots from its start.+ Memory(u32),+}++/// Assigns registers of each class in order, and memory to the rest; every value's memory place is at the sum of+/// the slots of the values before it, so that each has one whether or not it is in a register.+fn places(types: &[Type], gprs: &[Register], xmms: &[Register], places: &mut Vec<Place>) {+ places.clear();+ let (mut gpr, mut xmm, mut slot) = (0, 0, 0);+ for ty in types {+ let register = if ty.uses_xmm() {+ xmm += 1;+ xmms.get(xmm - 1)+ } else {+ gpr += 1;+ gprs.get(gpr - 1)+ };+ places.push(register.map_or(Place::Memory(slot), |register| Place::Register(*register)));+ slot += ty.slots();+ }+}++/// Where each parameter of a function with parameter types `types` is passed.+pub fn parameter_places(types: &[Type], output: &mut Vec<Place>) {+ places(types, &GPR_ARGUMENTS, &FPR_ARGUMENTS, output);+}++/// Where each result of a function with result types `types` is returned.+pub fn result_places(types: &[Type], output: &mut Vec<Place>) {+ places(types, &GPR_RESULTS, &FPR_RESULTS, output);+}++/// The home slot of parameter `index` of a function with parameter types `types`, in slots from fp.+pub fn home_slot(types: &[Type], index: usize) -> u32 {+ types[..index].iter().map(|ty| ty.slots()).sum()+}++/// The slots of a list of values.+pub fn slots(types: &[Type]) -> u32 {+ types.iter().map(|ty| ty.slots()).sum()+}++/// Whether a function with these results takes a result area.+pub fn has_result_area(types: &[Type]) -> bool {+ let xmms = types.iter().filter(|ty| ty.uses_xmm()).count();+ xmms > FPR_RESULTS.len() || types.len() - xmms > GPR_RESULTS.len()+}++/// Where the pointer to the result area is, in slots from fp, for a function with these parameters.+pub fn result_area_pointer(params: &[Type]) -> u32 {+ slots(params)+}++/// The bytes of outgoing area a call with these parameter and result types needs: the home slots, and if the+/// results need a result area, its pointer and the area.+pub fn outgoing_size(params: &[Type], results: &[Type]) -> u32 {+ let mut total = slots(params);+ if has_result_area(results) {+ total += 1 + slots(results);+ }+ 8 * total+}diff --git a/Libraries/LibWasm/JIT/src/decode.rs b/Libraries/LibWasm/JIT/src/decode.rsnew file mode 100644index 00000000000..b2b6c6259d5--- /dev/null+++ b/Libraries/LibWasm/JIT/src/decode.rs@@ -0,0 +1,585 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The decoder: one instruction at a time from a validated, quickened function body (see+//! `libwasm_module::quickening`).+//!+//! Validation already checked every immediate, so decoding does not check them again. It reads every instruction of+//! every proposal the engine supports, including the quickened forms, so that the builder can skip the immediates of+//! instructions it does not compile in unreachable code. Instructions the JIT does not compile come out as coarse+//! variants that only tell how they nest.++use libwasm_module::instruction_tables::{AtomicKind, SimdKind, atomic_kind, simd_kind};+use libwasm_module::opcode;+use libwasm_module::quickening;+use libwasm_module::types::{HeapType, RefType, ValType};++/// The type of a block, loop, if or try_table.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BlockType {+ Empty,+ Value(ValType),+ /// The type index of a function type, whose parameters the block takes and whose results it produces.+ Function(u32),+}++/// The memory immediate of a load or store.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct MemoryArgument {+ pub memory: u32,+ pub offset: u64,+}++/// A decoded instruction. Numeric instructions without immediates are `Numeric` with their opcode.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Instruction {+ Unreachable,+ Nop,+ Block(BlockType),+ Loop(BlockType),+ If(BlockType),+ Else,+ End,+ Br(u32),+ BrIf(u32),+ /// `br_table` with `count` labels before the default; the decoder keeps the labels (see `Decoder::targets()`).+ BrTable {+ count: u32,+ },+ Return,+ Call(u32),+ CallIndirect {+ type_index: u32,+ table: u32,+ },+ ReturnCall(u32),+ ReturnCallIndirect {+ type_index: u32,+ table: u32,+ },+ CallRef(u32),+ ReturnCallRef(u32),+ Throw(u32),+ ThrowRef,+ /// A `try_table`, whose catch clauses the decoder skipped.+ TryTable(BlockType),+ Drop,+ Select,+ SelectTyped(ValType),+ LocalGet(u32),+ LocalSet(u32),+ LocalTee(u32),+ GlobalGet(u32),+ GlobalSet(u32),+ TableGet(u32),+ TableSet(u32),+ /// A core load or store (`opcode` from `I32_LOAD` to `I64_STORE32`) of memory 0, which is a memory32 with guard+ /// pages.+ Access {+ opcode: u8,+ argument: MemoryArgument,+ },+ /// The explicitly bounds-checked form of a core load or store (quickening rule 1).+ CheckedAccess {+ opcode: u8,+ argument: MemoryArgument,+ },+ MemorySize(u32),+ MemoryGrow(u32),+ I32Const(i32),+ I64Const(i64),+ /// The bits of an f32 constant.+ F32Const(u32),+ /// The bits of an f64 constant.+ F64Const(u64),+ /// An instruction from `I32_EQZ` to `I64_EXTEND32_S`, none of which has immediates.+ Numeric(u8),+ RefNull(HeapType),+ RefIsNull,+ RefFunc(u32),+ RefEq,+ RefAsNonNull,+ BrOnNull(u32),+ BrOnNonNull(u32),+ /// A `0xFC` instruction. The decoder keeps its index immediates (see `Decoder::misc_indices()`).+ Misc(u32),+ /// A `0xFB` instruction, its immediates skipped.+ 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()`).+ Simd {+ sub_opcode: u32,+ checked: bool,+ },+ /// A `0xFE` instruction, its immediates skipped.+ 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.+ Vector {+ opcode: u8,+ index: u32,+ },+}++/// The last fixed-width form of `i64.const` (quickening rule 3), for 10 bytes.+const I64_CONST_FIXED_LAST: u8 = quickening::I64_CONST_FIXED + 8;++/// A cursor over a function body.+pub struct Decoder<'a> {+ bytes: &'a [u8],+ position: usize,+ end: usize,+ targets: Vec<u32>,+ simd_argument: MemoryArgument,+ simd_lane: u8,+ simd_bytes: [u8; 16],+ misc_indices: [u32; 2],+}++impl<'a> Decoder<'a> {+ /// A decoder over `bytes[start..end]`, which must be a validated function body (or its instructions).+ pub fn new(bytes: &'a [u8], start: usize, end: usize) -> Self {+ Self {+ bytes,+ position: start,+ end,+ targets: Vec::new(),+ simd_argument: MemoryArgument { memory: 0, offset: 0 },+ simd_lane: 0,+ simd_bytes: [0; 16],+ misc_indices: [0; 2],+ }+ }++ /// Reuses the decoder's storage for another body.+ pub fn reset(&mut self, bytes: &'a [u8], start: usize, end: usize) {+ self.bytes = bytes;+ self.position = start;+ self.end = end;+ }++ /// The module offset of the next instruction.+ pub fn position(&self) -> usize {+ self.position+ }++ pub fn is_at_end(&self) -> bool {+ self.position >= self.end+ }++ /// The labels of the last `br_table`, the default last.+ pub fn targets(&self) -> &[u32] {+ &self.targets+ }++ /// The memory immediate of the last SIMD load or store.+ pub fn simd_argument(&self) -> MemoryArgument {+ self.simd_argument+ }++ /// The lane immediate of the last SIMD instruction with one.+ pub fn simd_lane(&self) -> u8 {+ self.simd_lane+ }++ /// The index immediates of the last `0xFC` instruction with any, in order: one, or two for memory.init,+ /// memory.copy, table.init and table.copy.+ pub fn misc_indices(&self) -> [u32; 2] {+ self.misc_indices+ }++ /// The 16 bytes of the last `v128.const` or `i8x16.shuffle`.+ pub fn simd_bytes(&self) -> [u8; 16] {+ self.simd_bytes+ }++ #[inline]+ fn byte(&mut self) -> u8 {+ let byte = self.bytes[self.position];+ self.position += 1;+ byte+ }++ #[inline]+ fn u32(&mut self) -> u32 {+ let byte = self.byte();+ if byte < 0x80 {+ return u32::from(byte);+ }+ self.u64_continued(byte) as u32+ }++ fn u64_continued(&mut self, first: u8) -> u64 {+ let mut result = u64::from(first & 0x7f);+ let mut shift = 7;+ loop {+ let byte = self.byte();+ result |= u64::from(byte & 0x7f) << shift;+ if byte & 0x80 == 0 {+ return result;+ }+ shift += 7;+ }+ }++ fn u64(&mut self) -> u64 {+ let byte = self.byte();+ if byte < 0x80 {+ return u64::from(byte);+ }+ self.u64_continued(byte)+ }++ fn signed(&mut self) -> i64 {+ let mut result = 0i64;+ let mut shift = 0;+ loop {+ let byte = self.byte();+ result |= i64::from(byte & 0x7f) << shift;+ shift += 7;+ if byte & 0x80 == 0 {+ if shift < 64 && byte & 0x40 != 0 {+ result |= -1i64 << shift;+ }+ return result;+ }+ }+ }++ /// The value of a fixed-width constant (quickening rule 3) of `length` bytes, for a type of `size` bytes: sign+ /// extended from its bytes, or its first `size` bytes where it has more.+ fn fixed_constant(&mut self, length: usize, size: usize) -> i64 {+ let bytes = &self.bytes[self.position..self.position + length];+ self.position += length;+ let stored = length.min(size);+ let mut value = 0u64;+ for (index, byte) in bytes[..stored].iter().enumerate() {+ value |= u64::from(*byte) << (8 * index);+ }+ let bits = 8 * stored as u32;+ if bits < 64 {+ let shift = 64 - bits;+ ((value << shift) as i64) >> shift+ } else {+ value as i64+ }+ }++ fn fixed_u32(&mut self) -> u32 {+ let bytes = &self.bytes[self.position..self.position + 4];+ self.position += 4;+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])+ }++ fn fixed_u64(&mut self) -> u64 {+ let mut bytes = [0; 8];+ bytes.copy_from_slice(&self.bytes[self.position..self.position + 8]);+ self.position += 8;+ u64::from_le_bytes(bytes)+ }++ fn heap_type(&mut self) -> HeapType {+ let byte = self.bytes[self.position];+ let heap = match byte {+ 0x70 => HeapType::Func,+ 0x73 => HeapType::NoFunc,+ 0x6f => HeapType::Extern,+ 0x72 => HeapType::NoExtern,+ 0x6e => HeapType::Any,+ 0x6d => HeapType::Eq,+ 0x6c => HeapType::I31,+ 0x6b => HeapType::Struct,+ 0x6a => HeapType::Array,+ 0x71 => HeapType::None,+ 0x69 => HeapType::Exn,+ 0x74 => HeapType::NoExn,+ _ => return HeapType::Concrete(self.signed() as u32),+ };+ self.position += 1;+ heap+ }++ fn value_type(&mut self) -> ValType {+ let value = match self.bytes[self.position] {+ 0x7f => ValType::I32,+ 0x7e => ValType::I64,+ 0x7d => ValType::F32,+ 0x7c => ValType::F64,+ 0x7b => ValType::V128,+ 0x63 => {+ self.position += 1;+ return ValType::Ref(RefType::new(true, self.heap_type()));+ }+ 0x64 => {+ self.position += 1;+ return ValType::Ref(RefType::new(false, self.heap_type()));+ }+ _ => return ValType::Ref(RefType::new(true, self.heap_type())),+ };+ self.position += 1;+ value+ }++ fn block_type(&mut self) -> BlockType {+ match self.bytes[self.position] {+ 0x40 => {+ self.position += 1;+ BlockType::Empty+ }+ 0x7f | 0x7e | 0x7d | 0x7c | 0x7b | 0x63 | 0x64 | 0x70 | 0x6f | 0x6e | 0x6d | 0x6c | 0x6b | 0x6a | 0x69+ | 0x71 | 0x72 | 0x73 | 0x74 => BlockType::Value(self.value_type()),+ _ => BlockType::Function(self.signed() as u32),+ }+ }++ fn memory_argument(&mut self) -> MemoryArgument {+ let alignment = self.u32();+ let memory = if alignment & 0x40 != 0 { self.u32() } else { 0 };+ MemoryArgument {+ memory,+ offset: self.u64(),+ }+ }++ /// Decodes the next instruction.+ pub fn decode(&mut self) -> Instruction {+ let opcode = self.byte();+ match opcode {+ opcode::UNREACHABLE => Instruction::Unreachable,+ opcode::NOP => Instruction::Nop,+ opcode::BLOCK => Instruction::Block(self.block_type()),+ opcode::LOOP => Instruction::Loop(self.block_type()),+ opcode::IF => Instruction::If(self.block_type()),+ opcode::ELSE => Instruction::Else,+ opcode::END => Instruction::End,+ opcode::BR => Instruction::Br(self.u32()),+ opcode::BR_IF => Instruction::BrIf(self.u32()),+ opcode::BR_TABLE => {+ let count = self.u32();+ self.targets.clear();+ for _ in 0..=count {+ let target = self.u32();+ self.targets.push(target);+ }+ Instruction::BrTable { count }+ }+ opcode::RETURN => Instruction::Return,+ opcode::CALL => Instruction::Call(self.u32()),+ opcode::CALL_INDIRECT => {+ let type_index = self.u32();+ Instruction::CallIndirect {+ type_index,+ table: self.u32(),+ }+ }+ opcode::RETURN_CALL => Instruction::ReturnCall(self.u32()),+ opcode::RETURN_CALL_INDIRECT => {+ let type_index = self.u32();+ Instruction::ReturnCallIndirect {+ type_index,+ table: self.u32(),+ }+ }+ opcode::CALL_REF => Instruction::CallRef(self.u32()),+ opcode::RETURN_CALL_REF => Instruction::ReturnCallRef(self.u32()),+ opcode::THROW => Instruction::Throw(self.u32()),+ opcode::THROW_REF => Instruction::ThrowRef,+ opcode::TRY_TABLE => {+ let block_type = self.block_type();+ let count = self.u32();+ for _ in 0..count {+ let kind = self.byte();+ if kind < 2 {+ self.u32();+ }+ self.u32();+ }+ Instruction::TryTable(block_type)+ }+ opcode::DROP => Instruction::Drop,+ opcode::SELECT => Instruction::Select,+ opcode::SELECT_TYPED => {+ self.u32();+ Instruction::SelectTyped(self.value_type())+ }+ opcode::LOCAL_GET => Instruction::LocalGet(self.u32()),+ opcode::LOCAL_SET => Instruction::LocalSet(self.u32()),+ opcode::LOCAL_TEE => Instruction::LocalTee(self.u32()),+ opcode::GLOBAL_GET => Instruction::GlobalGet(self.u32()),+ opcode::GLOBAL_SET => Instruction::GlobalSet(self.u32()),+ opcode::TABLE_GET => Instruction::TableGet(self.u32()),+ opcode::TABLE_SET => Instruction::TableSet(self.u32()),+ opcode::I32_LOAD..=opcode::I64_STORE32 => Instruction::Access {+ opcode,+ argument: self.memory_argument(),+ },+ opcode::MEMORY_SIZE => Instruction::MemorySize(self.u32()),+ opcode::MEMORY_GROW => Instruction::MemoryGrow(self.u32()),+ opcode::I32_CONST => Instruction::I32Const(self.signed() as i32),+ opcode::I64_CONST => Instruction::I64Const(self.signed()),+ opcode::F32_CONST => Instruction::F32Const(self.fixed_u32()),+ opcode::F64_CONST => Instruction::F64Const(self.fixed_u64()),+ opcode::I32_EQZ..=opcode::I64_EXTEND32_S => Instruction::Numeric(opcode),+ opcode::REF_NULL => Instruction::RefNull(self.heap_type()),+ opcode::REF_IS_NULL => Instruction::RefIsNull,+ opcode::REF_FUNC => Instruction::RefFunc(self.u32()),+ opcode::REF_EQ => Instruction::RefEq,+ opcode::REF_AS_NON_NULL => Instruction::RefAsNonNull,+ opcode::BR_ON_NULL => Instruction::BrOnNull(self.u32()),+ opcode::BR_ON_NON_NULL => Instruction::BrOnNonNull(self.u32()),+ opcode::PREFIX_MISC => self.misc(),+ opcode::PREFIX_GC => self.gc(),+ opcode::PREFIX_SIMD => {+ let sub_opcode = self.u32();+ self.simd_immediates(sub_opcode);+ Instruction::Simd {+ sub_opcode,+ checked: false,+ }+ }+ opcode::PREFIX_ATOMIC => {+ let sub_opcode = self.u32();+ match atomic_kind(sub_opcode) {+ Some(AtomicKind::Fence) => {+ self.byte();+ }+ Some(_) => {+ self.memory_argument();+ }+ None => unreachable!("validated code has no unknown atomic instructions"),+ }+ Instruction::Atomic(sub_opcode)+ }+ quickening::QUICK_PREFIX => self.quickened(),+ quickening::I32_CONST_FIXED..quickening::I64_CONST_FIXED => {+ let length = usize::from(opcode - quickening::I32_CONST_FIXED) + 2;+ Instruction::I32Const(self.fixed_constant(length, 4) as i32)+ }+ quickening::I64_CONST_FIXED..=I64_CONST_FIXED_LAST => {+ let length = usize::from(opcode - quickening::I64_CONST_FIXED) + 2;+ Instruction::I64Const(self.fixed_constant(length, 8))+ }+ quickening::LOCAL_GET_V128..=quickening::GLOBAL_SET_V128 => Instruction::Vector {+ opcode,+ index: self.u32(),+ },+ quickening::DROP_V128 | quickening::SELECT_V128 => Instruction::Vector { opcode, index: 0 },+ _ => unreachable!("validated code has no unknown opcode {opcode:#x}"),+ }+ }++ fn misc(&mut self) -> Instruction {+ let sub_opcode = self.u32();+ match sub_opcode {+ opcode::misc::I32_TRUNC_SAT_F32_S..=opcode::misc::I64_TRUNC_SAT_F64_U => {}+ // memory.init, memory.copy, table.init and table.copy take two indices.+ opcode::misc::MEMORY_INIT+ | opcode::misc::MEMORY_COPY+ | opcode::misc::TABLE_INIT+ | opcode::misc::TABLE_COPY => {+ self.misc_indices = [self.u32(), self.u32()];+ }+ _ => {+ self.misc_indices = [self.u32(), 0];+ }+ }+ Instruction::Misc(sub_opcode)+ }++ fn gc(&mut self) -> Instruction {+ use opcode::gc::*;+ let sub_opcode = self.u32();+ 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();+ }+ 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();+ }+ REF_TEST | REF_TEST_NULL | REF_CAST | REF_CAST_NULL => {+ self.heap_type();+ }+ BR_ON_CAST | BR_ON_CAST_FAIL => {+ self.byte();+ self.u32();+ self.heap_type();+ self.heap_type();+ }+ _ => {}+ }+ Instruction::Gc(sub_opcode)+ }++ fn simd_immediates(&mut self, sub_opcode: u32) {+ match simd_kind(sub_opcode) {+ Some(SimdKind::Load { .. } | SimdKind::Store { .. }) => {+ self.simd_argument = self.memory_argument();+ }+ Some(SimdKind::LoadLane { .. } | SimdKind::StoreLane { .. }) => {+ self.simd_argument = self.memory_argument();+ self.simd_lane = self.byte();+ }+ Some(SimdKind::Const | SimdKind::Shuffle) => {+ self.simd_bytes+ .copy_from_slice(&self.bytes[self.position..self.position + 16]);+ self.position += 16;+ }+ Some(SimdKind::ExtractLane { .. } | SimdKind::ReplaceLane { .. }) => {+ self.simd_lane = self.byte();+ }+ Some(_) => {}+ None => unreachable!("validated code has no unknown SIMD instructions"),+ }+ }++ fn quickened(&mut self) -> Instruction {+ let sub_opcode = self.byte();+ if sub_opcode < quickening::CHECKED_SIMD_ACCESS {+ let memory = if sub_opcode & quickening::CHECKED_ACCESS_HAS_MEMORY_INDEX != 0 {+ self.u32()+ } else {+ 0+ };+ return Instruction::CheckedAccess {+ opcode: sub_opcode & !quickening::CHECKED_ACCESS_HAS_MEMORY_INDEX,+ argument: MemoryArgument {+ memory,+ offset: self.u64(),+ },+ };+ }+ let index = sub_opcode - quickening::CHECKED_SIMD_ACCESS;+ let has_memory = index & quickening::CHECKED_SIMD_ACCESS_HAS_MEMORY_INDEX != 0;+ let simd = quickening::SIMD_ACCESSES[(index & !quickening::CHECKED_SIMD_ACCESS_HAS_MEMORY_INDEX) as usize];+ let memory = if has_memory { self.u32() } else { 0 };+ self.simd_argument = MemoryArgument {+ memory,+ offset: self.u64(),+ };+ if matches!(+ simd_kind(simd),+ Some(SimdKind::LoadLane { .. } | SimdKind::StoreLane { .. })+ ) {+ self.simd_lane = self.byte();+ }+ Instruction::Simd {+ sub_opcode: simd,+ checked: true,+ }+ }+}++/// How an instruction changes the nesting of blocks: +1 for those that open one, -1 for `end`.+pub fn nesting_change(instruction: &Instruction) -> i32 {+ match instruction {+ Instruction::Block(_) | Instruction::Loop(_) | Instruction::If(_) | Instruction::TryTable(_) => 1,+ Instruction::End => -1,+ _ => 0,+ }+}diff --git a/Libraries/LibWasm/JIT/src/ir/dump.rs b/Libraries/LibWasm/JIT/src/ir/dump.rsnew file mode 100644index 00000000000..f91c7a77fd2--- /dev/null+++ b/Libraries/LibWasm/JIT/src/ir/dump.rs@@ -0,0 +1,145 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The text form of the IR, for `dump-ir` and the IR tests.++use super::{FloatCondition, Func, IntCondition, LoadKind, Op, Shape, Type, Value};+use std::fmt::Write;++/// The value as text: a constant's value, or `vN`.+fn operand(func: &Func, value: Value) -> String {+ let node = func.node(value);+ match node.op {+ Op::Const32 if node.ty == Type::F32 => format!("{}f32", f32::from_bits(node.args[0])),+ Op::Const32 => format!("{}", node.args[0] as i32),+ Op::Const64 if node.ty == Type::F64 => {+ format!("{}f64", f64::from_bits(node.constant().expect("a constant")))+ }+ Op::Const64 => format!("{}i64", node.constant().expect("a constant") as i64),+ Op::Const128 => format!("{:#034x}v128", func.constants[node.args[0] as usize]),+ _ => format!("v{value}"),+ }+}++/// One node as text, without its value name.+pub fn node_text(func: &Func, value: Value) -> String {+ let node = func.node(value);+ let mut text = String::from(node.op.name());+ if node.ty != Type::None {+ write!(text, ".{}", node.ty.name()).unwrap();+ }+ match node.op {+ Op::Compare | Op::BranchCompare => write!(text, " {}", IntCondition::from_flags(node.flags).name()).unwrap(),+ Op::FloatCompare | Op::BranchFloatCompare => {+ write!(text, " {}", FloatCondition::from_flags(node.flags).name()).unwrap();+ }+ Op::Load => write!(text, " {}", LoadKind::from_flags(node.flags).name()).unwrap(),+ Op::Store => write!(text, " {}", 8 << node.flags).unwrap(),+ _ => {}+ }+ let inputs = func.inputs(value);+ if !inputs.is_empty() && node.op != Op::BrTable {+ let inputs = inputs.iter().map(|input| operand(func, *input)).collect::<Vec<_>>();+ write!(text, " {}", inputs.join(", ")).unwrap();+ }+ match node.op {+ Op::Const32 | Op::Const64 | Op::Const128 => write!(text, " {}", operand(func, value)).unwrap(),+ Op::VectorUnary | Op::ExtractLane => write!(text, " simd {:#x}", node.args[1]).unwrap(),+ Op::VectorBinary => write!(text, " simd {:#x}", node.args[2]).unwrap(),+ Op::ReplaceLane => write!(text, " simd {:#x} lane {}", node.args[2] & 0xffff, node.args[2] >> 16).unwrap(),+ Op::Shuffle => write!(text, " {:#034x}", func.constants[node.args[2] as usize]).unwrap(),+ Op::VectorLoad => write!(text, " simd {:#x} +{}", node.flags, node.args[2]).unwrap(),+ Op::VectorTernary => write!(text, " simd {:#x}", node.flags).unwrap(),+ Op::Param => write!(text, " {}", node.args[0]).unwrap(),+ Op::Forward => write!(text, " v{}", node.args[0]).unwrap(),+ Op::InstanceField | Op::LoadPointer => write!(text, " +{}", node.args[1]).unwrap(),+ Op::GlobalGet => write!(text, " global {}", node.args[1]).unwrap(),+ Op::GlobalSet => write!(text, " global {}", node.args[2]).unwrap(),+ Op::Load => write!(text, " +{}", node.args[2]).unwrap(),+ Op::Store => write!(text, " +{}", node.args[2]).unwrap(),+ Op::Call | Op::TailCall if node.args[2] != crate::ir::NONE => {+ write!(text, " function {}", node.args[2]).unwrap();+ }+ Op::Offset | Op::ReadField => write!(text, " +{}", node.args[1]).unwrap(),+ Op::WriteField => write!(text, " +{}", node.args[2]).unwrap(),+ Op::Helper => write!(text, " {}", crate::ir::Helper::from_index(node.args[2]).name()).unwrap(),+ Op::CallResult => write!(text, " v{} #{}", node.args[0], node.args[1]).unwrap(),+ Op::Trap => write!(text, " {}", node.args[0]).unwrap(),+ Op::BrTable => {+ let block = func+ .blocks+ .iter()+ .position(|block| block.end == value + 1)+ .expect("a br_table ends a block") as u32;+ let successors = func.successors(block);+ let targets = func+ .table_targets(value)+ .iter()+ .map(|target| format!("b{}", successors[*target as usize]))+ .collect::<Vec<_>>();+ write!(text, " {} [{}]", operand(func, node.args[0]), targets.join(", ")).unwrap();+ }+ _ => {}+ }+ if matches!(node.op.shape(), Shape::Fixed(_)) && node.flags & super::FLAG_CANNOT_TRAP != 0 {+ text.push_str(" (cannot trap)");+ }+ text+}++/// The whole function as text. Nodes for which `is_dead` holds are left out.+pub fn dump(func: &Func, is_dead: &dyn Fn(Value) -> bool) -> String {+ let mut out = String::new();+ let types = |types: &[Type]| types.iter().map(|ty| ty.name()).collect::<Vec<_>>().join(", ");+ writeln!(out, "function ({}) -> ({})", types(&func.params), types(&func.results)).unwrap();+ for (index, block) in func.blocks.iter().enumerate() {+ let block_id = index as u32;+ let list = |blocks: &[u32]| {+ blocks+ .iter()+ .map(|block| format!("b{block}"))+ .collect::<Vec<_>>()+ .join(", ")+ };+ write!(out, "b{index}:").unwrap();+ if !func.predecessors(block_id).is_empty() {+ write!(out, " <- {}", list(func.predecessors(block_id))).unwrap();+ }+ if block.loop_index != super::NONE {+ let loop_ = &func.loops[block.loop_index as usize];+ if loop_.header == block_id {+ write!(out, " (loop to b{})", loop_.last).unwrap();+ }+ }+ out.push('\n');+ for phi in func.phis(block_id) {+ if func.node(phi).op == Op::Phi && !is_dead(phi) {+ writeln!(out, " v{phi} = {}", node_text(func, phi)).unwrap();+ }+ }+ for value in block.start..block.end {+ let node = func.node(value);+ if is_dead(value)+ || (node.op.is_entry_value() && node.op != Op::Param)+ || matches!(node.op, Op::Phi | Op::Forward)+ {+ continue;+ }+ if node.op.is_terminator() {+ write!(out, " {}", node_text(func, value)).unwrap();+ if !func.successors(block_id).is_empty() && node.op != Op::BrTable {+ write!(out, " -> {}", list(func.successors(block_id))).unwrap();+ }+ out.push('\n');+ } else if node.ty == Type::None {+ writeln!(out, " {}", node_text(func, value)).unwrap();+ } else {+ writeln!(out, " v{value} = {}", node_text(func, value)).unwrap();+ }+ }+ }+ out+}diff --git a/Libraries/LibWasm/JIT/src/ir/mod.rs b/Libraries/LibWasm/JIT/src/ir/mod.rsnew file mode 100644index 00000000000..fb8b9fc576d--- /dev/null+++ b/Libraries/LibWasm/JIT/src/ir/mod.rs@@ -0,0 +1,797 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The IR: typed SSA in flat arenas.+//!+//! A `Func` is a list of blocks in linear order, which is the order of the WebAssembly code: every forward edge goes+//! to a later block, and every loop is a contiguous range of blocks that only its header is entered at. Nodes live in+//! one arena and are named by their index (`Value`). Each block owns a contiguous range of nodes, its body, which+//! ends with its terminator, and a list of phis. Nodes are created in order, so a body node's index is also its+//! position in linear order.+//!+//! A `Node` is 16 bytes: an op, a type, eight bits of flags and three 32-bit arguments, which are inputs or immediates+//! as the op says (`Op::shape()`). Ops with more inputs keep them in `Func::operands`.+//!+//! Constants, parameters, the instance and the memory base are values without code at their position: constants are+//! rematerialized at every use, and the others arrive in registers or slots at the entry.++pub mod dump;+pub mod verify;++/// A node, by its index in `Func::nodes`.+pub type Value = u32;++/// A block, by its index in `Func::blocks`.+pub type BlockId = u32;++/// No value or block.+pub const NONE: u32 = u32::MAX;++/// The type of a value.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]+#[repr(u8)]+pub enum Type {+ #[default]+ None,+ I32,+ I64,+ F32,+ F64,+ V128,+ /// A reference: zero for null, else what the runtime encodes it as (a `FunctionHeader` for funcref).+ Ref,+ /// A machine pointer, for addresses the code computes (the memory base, instance data).+ Pointer,+}++impl Type {+ pub fn is_float(self) -> bool {+ matches!(self, Type::F32 | Type::F64)+ }++ /// Whether values of this type live in xmm registers: floats and vectors.+ pub fn uses_xmm(self) -> bool {+ matches!(self, Type::F32 | Type::F64 | Type::V128)+ }++ /// The 8-byte slots a value of this type takes in memory.+ pub fn slots(self) -> u32 {+ if self == Type::V128 { 2 } else { 1 }+ }++ pub fn is_64(self) -> bool {+ matches!(self, Type::I64 | Type::F64 | Type::Ref | Type::Pointer)+ }++ pub fn name(self) -> &'static str {+ match self {+ Type::None => "none",+ Type::I32 => "i32",+ Type::I64 => "i64",+ Type::F32 => "f32",+ Type::F64 => "f64",+ Type::V128 => "v128",+ Type::Ref => "ref",+ Type::Pointer => "ptr",+ }+ }+}++/// Where an op finds its inputs.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Shape {+ /// The first `n` arguments are inputs; the others are immediates.+ Fixed(u8),+ /// `args[0]` is the start and `args[1]` the count of the inputs in `Func::operands`.+ Variadic,+}++/// What an op may do besides computing its value.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Effect {+ /// Nothing: equal nodes compute equal values anywhere their inputs are available, and unused ones go away.+ Pure,+ /// Reads state that stores and calls may change; may trap where it reads memory.+ Read,+ /// Writes state, or traps where its inputs say so (division, truncation): never removed or moved.+ Write,+ /// Ends a block.+ Terminator,+}++/// An integer comparison, in `Node::flags` of `Compare` and `BranchCompare`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[repr(u8)]+pub enum IntCondition {+ Eq,+ Ne,+ LtS,+ LtU,+ GtS,+ GtU,+ LeS,+ LeU,+ GeS,+ GeU,+}++impl IntCondition {+ pub const ALL: [IntCondition; 10] = [+ IntCondition::Eq,+ IntCondition::Ne,+ IntCondition::LtS,+ IntCondition::LtU,+ IntCondition::GtS,+ IntCondition::GtU,+ IntCondition::LeS,+ IntCondition::LeU,+ IntCondition::GeS,+ IntCondition::GeU,+ ];++ pub fn from_flags(flags: u8) -> Self {+ Self::ALL[flags as usize]+ }++ pub fn invert(self) -> Self {+ match self {+ IntCondition::Eq => IntCondition::Ne,+ IntCondition::Ne => IntCondition::Eq,+ IntCondition::LtS => IntCondition::GeS,+ IntCondition::LtU => IntCondition::GeU,+ IntCondition::GtS => IntCondition::LeS,+ IntCondition::GtU => IntCondition::LeU,+ IntCondition::LeS => IntCondition::GtS,+ IntCondition::LeU => IntCondition::GtU,+ IntCondition::GeS => IntCondition::LtS,+ IntCondition::GeU => IntCondition::LtU,+ }+ }++ /// The condition with the operands swapped.+ pub fn swap(self) -> Self {+ match self {+ IntCondition::Eq => IntCondition::Eq,+ IntCondition::Ne => IntCondition::Ne,+ IntCondition::LtS => IntCondition::GtS,+ IntCondition::LtU => IntCondition::GtU,+ IntCondition::GtS => IntCondition::LtS,+ IntCondition::GtU => IntCondition::LtU,+ IntCondition::LeS => IntCondition::GeS,+ IntCondition::LeU => IntCondition::GeU,+ IntCondition::GeS => IntCondition::LeS,+ IntCondition::GeU => IntCondition::LeU,+ }+ }++ pub fn evaluate(self, lhs: u64, rhs: u64, is_64: bool) -> bool {+ let (signed_lhs, signed_rhs) = if is_64 {+ (lhs as i64, rhs as i64)+ } else {+ (i64::from(lhs as u32 as i32), i64::from(rhs as u32 as i32))+ };+ let (lhs, rhs) = if is_64 {+ (lhs, rhs)+ } else {+ (u64::from(lhs as u32), u64::from(rhs as u32))+ };+ match self {+ IntCondition::Eq => lhs == rhs,+ IntCondition::Ne => lhs != rhs,+ IntCondition::LtS => signed_lhs < signed_rhs,+ IntCondition::LtU => lhs < rhs,+ IntCondition::GtS => signed_lhs > signed_rhs,+ IntCondition::GtU => lhs > rhs,+ IntCondition::LeS => signed_lhs <= signed_rhs,+ IntCondition::LeU => lhs <= rhs,+ IntCondition::GeS => signed_lhs >= signed_rhs,+ IntCondition::GeU => lhs >= rhs,+ }+ }++ pub fn name(self) -> &'static str {+ match self {+ IntCondition::Eq => "eq",+ IntCondition::Ne => "ne",+ IntCondition::LtS => "lt_s",+ IntCondition::LtU => "lt_u",+ IntCondition::GtS => "gt_s",+ IntCondition::GtU => "gt_u",+ IntCondition::LeS => "le_s",+ IntCondition::LeU => "le_u",+ IntCondition::GeS => "ge_s",+ IntCondition::GeU => "ge_u",+ }+ }+}++/// A float comparison, in `Node::flags` of `FloatCompare` and `BranchFloatCompare`. All are false for NaN but `Ne`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[repr(u8)]+pub enum FloatCondition {+ Eq,+ Ne,+ Lt,+ Gt,+ Le,+ Ge,+}++impl FloatCondition {+ pub const ALL: [FloatCondition; 6] = [+ FloatCondition::Eq,+ FloatCondition::Ne,+ FloatCondition::Lt,+ FloatCondition::Gt,+ FloatCondition::Le,+ FloatCondition::Ge,+ ];++ pub fn from_flags(flags: u8) -> Self {+ Self::ALL[flags as usize]+ }++ pub fn name(self) -> &'static str {+ match self {+ FloatCondition::Eq => "eq",+ FloatCondition::Ne => "ne",+ FloatCondition::Lt => "lt",+ FloatCondition::Gt => "gt",+ FloatCondition::Le => "le",+ FloatCondition::Ge => "ge",+ }+ }+}++/// How a load reads memory, in `Node::flags` of `Load`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[repr(u8)]+pub enum LoadKind {+ I32,+ I64,+ F32,+ F64,+ I32S8,+ I32U8,+ I32S16,+ I32U16,+ I64S8,+ I64U8,+ I64S16,+ I64U16,+ I64S32,+ I64U32,+}++impl LoadKind {+ pub const ALL: [LoadKind; 14] = [+ LoadKind::I32,+ LoadKind::I64,+ LoadKind::F32,+ LoadKind::F64,+ LoadKind::I32S8,+ LoadKind::I32U8,+ LoadKind::I32S16,+ LoadKind::I32U16,+ LoadKind::I64S8,+ LoadKind::I64U8,+ LoadKind::I64S16,+ LoadKind::I64U16,+ LoadKind::I64S32,+ LoadKind::I64U32,+ ];++ pub fn from_flags(flags: u8) -> Self {+ Self::ALL[flags as usize]+ }++ pub fn size(self) -> u32 {+ match self {+ LoadKind::I32S8 | LoadKind::I32U8 | LoadKind::I64S8 | LoadKind::I64U8 => 1,+ LoadKind::I32S16 | LoadKind::I32U16 | LoadKind::I64S16 | LoadKind::I64U16 => 2,+ LoadKind::I32 | LoadKind::F32 | LoadKind::I64S32 | LoadKind::I64U32 => 4,+ LoadKind::I64 | LoadKind::F64 => 8,+ }+ }++ pub fn name(self) -> &'static str {+ match self {+ LoadKind::I32 => "i32",+ LoadKind::I64 => "i64",+ LoadKind::F32 => "f32",+ LoadKind::F64 => "f64",+ LoadKind::I32S8 => "i32.s8",+ LoadKind::I32U8 => "i32.u8",+ LoadKind::I32S16 => "i32.s16",+ LoadKind::I32U16 => "i32.u16",+ LoadKind::I64S8 => "i64.s8",+ LoadKind::I64U8 => "i64.u8",+ LoadKind::I64S16 => "i64.s16",+ LoadKind::I64U16 => "i64.u16",+ LoadKind::I64S32 => "i64.s32",+ LoadKind::I64U32 => "i64.u32",+ }+ }+}++/// The runtime functions `Helper` calls, and their operands.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[repr(u32)]+pub enum Helper {+ /// memory data, delta in pages: the previous size, or u64::MAX.+ MemoryGrow,+ /// table data, delta, initial element: the previous size, or u64::MAX.+ TableGrow,+ /// memory data, destination, value, count.+ MemoryFill,+ /// destination memory data, source memory data, destination, source, count.+ MemoryCopy,+ /// memory data, segment, destination, source, count.+ MemoryInit,+ /// table data, destination, value, count.+ TableFill,+ /// destination table data, source table data, destination, source, count.+ TableCopy,+ /// table data, segment, destination, source, count.+ TableInit,+}++impl Helper {+ pub const ALL: [Helper; 8] = [+ Helper::MemoryGrow,+ Helper::TableGrow,+ Helper::MemoryFill,+ Helper::MemoryCopy,+ Helper::MemoryInit,+ Helper::TableFill,+ Helper::TableCopy,+ Helper::TableInit,+ ];++ pub fn from_index(index: u32) -> Self {+ Self::ALL[index as usize]+ }++ /// 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)+ }++ pub fn name(self) -> &'static str {+ match self {+ Helper::MemoryGrow => "memory_grow",+ Helper::TableGrow => "table_grow",+ Helper::MemoryFill => "memory_fill",+ Helper::MemoryCopy => "memory_copy",+ Helper::MemoryInit => "memory_init",+ Helper::TableFill => "table_fill",+ Helper::TableCopy => "table_copy",+ Helper::TableInit => "table_init",+ }+ }+}++/// How many bytes a store writes, in `Node::flags` of `Store`. The value's type says the rest.+pub fn store_size(flags: u8) -> u32 {+ 1 << flags+}++/// `Node::flags` bit of ops that may trap (division, truncation) once their inputs show they cannot.+pub const FLAG_CANNOT_TRAP: u8 = 0x80;++/// `Node::flags` bit of `GlobalGet` for globals no code can change.+pub const FLAG_IMMUTABLE: u8 = 0x40;++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.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+ #[repr(u16)]+ pub enum Op {+ $($(#[$meta])* $name,)*+ }++ const SHAPES: &[Shape] = &[$($shape,)*];+ const EFFECTS: &[Effect] = &[$(Effect::$effect,)*];++ impl Op {+ #[inline]+ pub fn shape(self) -> Shape {+ SHAPES[self as usize]+ }++ #[inline]+ pub fn base_effect(self) -> Effect {+ EFFECTS[self as usize]+ }++ pub fn name(self) -> &'static str {+ match self {+ $(Op::$name => $text,)*+ }+ }+ }+ };+}++use Shape::{Fixed, Variadic};++ops! {+ // Values without code at their position.+ Const32: Fixed(0), Pure, "const";+ Const64: Fixed(0), Pure, "const";+ /// args[0]: the index of the constant in `Func::constants`.+ Const128: Fixed(0), Pure, "const";+ Param: Fixed(0), Pure, "param";+ Instance: Fixed(0), Pure, "instance";+ MemoryBase: Fixed(0), Pure, "memory_base";+ Phi: Variadic, Pure, "phi";+ /// A phi that turned out trivial, forwarding to args[0]. Gone after cleanup.+ Forward: Fixed(0), Pure, "forward";++ // Integer arithmetic, on I32 or I64 as the node's type says.+ Add: Fixed(2), Pure, "add";+ Sub: Fixed(2), Pure, "sub";+ Mul: Fixed(2), Pure, "mul";+ And: Fixed(2), Pure, "and";+ Or: Fixed(2), Pure, "or";+ Xor: Fixed(2), Pure, "xor";+ Shl: Fixed(2), Pure, "shl";+ ShrS: Fixed(2), Pure, "shr_s";+ ShrU: Fixed(2), Pure, "shr_u";+ Rotl: Fixed(2), Pure, "rotl";+ Rotr: Fixed(2), Pure, "rotr";+ DivS: Fixed(2), Write, "div_s";+ DivU: Fixed(2), Write, "div_u";+ RemS: Fixed(2), Write, "rem_s";+ RemU: Fixed(2), Write, "rem_u";+ Clz: Fixed(1), Pure, "clz";+ Ctz: Fixed(1), Pure, "ctz";+ Popcnt: Fixed(1), Pure, "popcnt";+ Eqz: Fixed(1), Pure, "eqz";+ Extend8S: Fixed(1), Pure, "extend8_s";+ Extend16S: Fixed(1), Pure, "extend16_s";+ Extend32S: Fixed(1), Pure, "extend32_s";+ ExtendI32S: Fixed(1), Pure, "extend_i32_s";+ ExtendI32U: Fixed(1), Pure, "extend_i32_u";+ Wrap: Fixed(1), Pure, "wrap";+ Compare: Fixed(2), Pure, "compare";++ // Float arithmetic, on F32 or F64.+ FAdd: Fixed(2), Pure, "fadd";+ FSub: Fixed(2), Pure, "fsub";+ FMul: Fixed(2), Pure, "fmul";+ FDiv: Fixed(2), Pure, "fdiv";+ FMin: Fixed(2), Pure, "fmin";+ FMax: Fixed(2), Pure, "fmax";+ FCopysign: Fixed(2), Pure, "fcopysign";+ FAbs: Fixed(1), Pure, "fabs";+ FNeg: Fixed(1), Pure, "fneg";+ FSqrt: Fixed(1), Pure, "fsqrt";+ FCeil: Fixed(1), Pure, "fceil";+ FFloor: Fixed(1), Pure, "ffloor";+ FTrunc: Fixed(1), Pure, "ftrunc";+ FNearest: Fixed(1), Pure, "fnearest";+ FloatCompare: Fixed(2), Pure, "fcompare";++ // Conversions to the node's type from the input's.+ TruncS: Fixed(1), Write, "trunc_s";+ TruncU: Fixed(1), Write, "trunc_u";+ TruncSatS: Fixed(1), Pure, "trunc_sat_s";+ TruncSatU: Fixed(1), Pure, "trunc_sat_u";+ ConvertS: Fixed(1), Pure, "convert_s";+ ConvertU: Fixed(1), Pure, "convert_u";+ Demote: Fixed(1), Pure, "demote";+ Promote: Fixed(1), Pure, "promote";+ Reinterpret: Fixed(1), Pure, "reinterpret";++ /// args: condition, value if nonzero, value if zero.+ Select: Fixed(3), Pure, "select";++ // Vectors. The SIMD sub-opcode says which operation; the node's type is its result's.+ /// args: operand, sub-opcode. Splats, unary lane operations and the reductions to an i32.+ VectorUnary: Fixed(1), Pure, "vector_unary";+ /// args: lhs, rhs, sub-opcode. Binary lane operations, comparisons, and shifts by an i32.+ VectorBinary: Fixed(2), Pure, "vector_binary";+ /// args: three operands; flags: the sub-opcode's low byte (bitselect, or a relaxed operation from 0x100 on).+ VectorTernary: Fixed(3), Pure, "vector_ternary";+ /// args: vector, sub-opcode, lane.+ ExtractLane: Fixed(1), Pure, "extract_lane";+ /// args: vector, value, sub-opcode and lane << 16.+ ReplaceLane: Fixed(2), Pure, "replace_lane";+ /// args: lhs, rhs, the index of the lane indices in `Func::constants`.+ Shuffle: Fixed(2), Pure, "shuffle";+ /// args: base, index, offset; flags: the load's SIMD sub-opcode.+ VectorLoad: Fixed(2), Read, "vector_load";++ // Instance data.+ /// args: instance, byte offset. A pointer field of the instance data that never changes.+ InstanceField: Fixed(1), Pure, "instance_field";+ /// args: pointer, byte offset; flags: 4 for a u32, else a pointer. Data of the instance that never changes, like+ /// `globals[i]` or a type identity.+ LoadPointer: Fixed(1), Pure, "load_pointer";+ /// args: the global's storage, global index.+ GlobalGet: Fixed(1), Read, "global_get";+ /// args: the global's storage, value, global index.+ GlobalSet: Fixed(2), Write, "global_set";++ // Memory 0, a memory32 with guard pages: the access is at base + zero-extended index + offset.+ /// args: base, index, offset; flags: LoadKind.+ Load: Fixed(2), Read, "load";+ /// operands: base, index, value; args[2]: offset; flags: log2 of the size.+ Store: Variadic, Write, "store";++ /// args: pointer, byte offset. The address that far from the pointer.+ Offset: Fixed(1), Pure, "offset";+ /// args: pointer, byte offset; flags: the bytes it reads, 4 or 8. A field of runtime data that may change, like+ /// the size of a memory or table, read where it is.+ ReadField: Fixed(1), Read, "read_field";+ /// args: pointer, value, byte offset; flags: the bytes it writes, 4 or 8.+ WriteField: Fixed(2), Write, "write_field";++ // Tables. A table's `TableData` is a pointer of the instance's that never changes.+ /// args: table data, index; flags: the TRAP_* code for an index out of bounds. Element `index`.+ TableElement: Fixed(2), Read, "table_element";+ /// args: table data, index, value; flags: the TRAP_* code for an index out of bounds.+ TableStore: Fixed(3), Write, "table_store";++ // 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.+ CalleeInstance: Fixed(2), Pure, "callee_instance";+ /// args: function reference, the type identity it must have; flags: the TRAP_* code for null. Traps unless the+ /// reference is not null and of that type or a subtype.+ CheckFunction: Fixed(2), Write, "check_function";+ /// args: reference; flags: the TRAP_* code. Traps if the reference is null.+ CheckNull: Fixed(1), Write, "check_null";+ /// operands: callee FunctionHeader, its instance, its memory base, arguments; args[2]: the function index, or+ /// NONE for an indirect call. The value is the first result.+ Call: Variadic, Write, "call";+ /// operands: the instance, then up to six operands; args[2]: the `Helper`. A call of a function of the runtime+ /// that takes its operands in the `ExecutionContext`'s `arguments` and returns a u64.+ Helper: Variadic, Write, "helper";+ /// args: call, result index. A further result of the call right before it.+ CallResult: Fixed(0), Pure, "call_result";++ // Terminators. Successors are in the block (`Func::successors()`).+ Jump: Fixed(0), Terminator, "jump";+ /// args: condition. To the first successor if nonzero, else the second.+ Branch: Fixed(1), Terminator, "branch";+ /// args: lhs, rhs; flags: IntCondition. To the first successor if the comparison holds.+ BranchCompare: Fixed(2), Terminator, "branch_compare";+ /// args: lhs, rhs; flags: FloatCondition.+ BranchFloatCompare: Fixed(2), Terminator, "branch_fcompare";+ /// args: index, start of the targets in `Func::operands`, their count before the default (which comes last).+ /// Each target is the index of a successor of the block.+ BrTable: Fixed(1), Terminator, "br_table";+ /// operands: the results.+ Return: Variadic, Terminator, "return";+ /// args: the TRAP_* code.+ Trap: Fixed(0), Terminator, "trap";+ /// operands and args like `Call`. A call whose results are the function's.+ TailCall: Variadic, Terminator, "tail_call";+}++impl Op {+ pub fn is_terminator(self) -> bool {+ self.base_effect() == Effect::Terminator+ }++ /// Whether nodes of this op never have code where they are.+ pub fn is_entry_value(self) -> bool {+ matches!(+ self,+ Op::Const32 | Op::Const64 | Op::Const128 | Op::Param | Op::Instance | Op::MemoryBase+ )+ }++ pub fn is_constant(self) -> bool {+ matches!(self, Op::Const32 | Op::Const64 | Op::Const128)+ }++ pub fn is_commutative(self) -> bool {+ matches!(+ self,+ Op::Add | Op::Mul | Op::And | Op::Or | Op::Xor | Op::FAdd | Op::FMul+ )+ }+}++/// One node: 16 bytes.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+#[repr(C)]+pub struct Node {+ pub op: Op,+ pub ty: Type,+ pub flags: u8,+ pub args: [u32; 3],+}++const _: () = assert!(size_of::<Node>() == 16);++impl Node {+ pub fn new(op: Op, ty: Type, flags: u8, args: [u32; 3]) -> Self {+ Self { op, ty, flags, args }+ }++ /// What this node may do besides computing its value.+ pub fn effect(&self) -> Effect {+ match self.op {+ Op::GlobalGet if self.flags & FLAG_IMMUTABLE != 0 => Effect::Pure,+ Op::DivS | Op::DivU | Op::RemS | Op::RemU | Op::TruncS | Op::TruncU+ if self.flags & FLAG_CANNOT_TRAP != 0 =>+ {+ Effect::Pure+ }+ op => op.base_effect(),+ }+ }++ /// The constant bits of a scalar constant node. Vector constants are in `Func::constants`.+ pub fn constant(&self) -> Option<u64> {+ match self.op {+ Op::Const32 => Some(u64::from(self.args[0])),+ Op::Const64 => Some(u64::from(self.args[0]) | (u64::from(self.args[1]) << 32)),+ _ => None,+ }+ }+}++/// A block: its phis, its body and its edges.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Block {+ /// The body: nodes `start..end`, the last of which is the terminator.+ pub start: u32,+ pub end: u32,+ /// The first phi; each phi's `args[2]` links to the next one.+ pub first_phi: Value,+ pub predecessors_start: u32,+ pub predecessor_count: u32,+ pub successors_start: u32,+ pub successor_count: u32,+ /// The innermost loop this block is in, as an index into `Func::loops`.+ pub loop_index: u32,+}++impl Default for Block {+ fn default() -> Self {+ Self {+ start: 0,+ end: 0,+ first_phi: NONE,+ predecessors_start: 0,+ predecessor_count: 0,+ successors_start: 0,+ successor_count: 0,+ loop_index: NONE,+ }+ }+}++/// A loop: the contiguous blocks `header..=last`.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Loop {+ pub header: BlockId,+ pub last: BlockId,+ /// The loop around this one.+ pub parent: u32,+ pub depth: u32,+}++/// A function in the IR.+#[derive(Debug, Default)]+pub struct Func {+ pub blocks: Vec<Block>,+ pub nodes: Vec<Node>,+ /// The inputs of variadic nodes, and the targets of `BrTable`s.+ pub operands: Vec<u32>,+ /// Vector constants and shuffles' lane indices.+ pub constants: Vec<u128>,+ pub predecessors: Vec<BlockId>,+ pub successors: Vec<BlockId>,+ pub loops: Vec<Loop>,+ /// The type of each parameter and result.+ pub params: Vec<Type>,+ pub results: Vec<Type>,+}++impl Func {+ pub fn clear(&mut self) {+ self.blocks.clear();+ self.nodes.clear();+ self.operands.clear();+ self.constants.clear();+ self.predecessors.clear();+ self.successors.clear();+ self.loops.clear();+ self.params.clear();+ self.results.clear();+ }++ pub fn node(&self, value: Value) -> &Node {+ &self.nodes[value as usize]+ }++ /// The inputs of a node.+ #[inline]+ pub fn inputs(&self, value: Value) -> &[u32] {+ let node = &self.nodes[value as usize];+ match node.op.shape() {+ Shape::Fixed(count) => &node.args[..count as usize],+ Shape::Variadic => {+ let start = node.args[0] as usize;+ &self.operands[start..start + node.args[1] as usize]+ }+ }+ }++ pub fn inputs_mut(&mut self, value: Value) -> &mut [u32] {+ let node = &mut self.nodes[value as usize];+ match node.op.shape() {+ Shape::Fixed(count) => &mut node.args[..count as usize],+ Shape::Variadic => {+ let start = node.args[0] as usize;+ &mut self.operands[start..start + node.args[1] as usize]+ }+ }+ }++ pub fn predecessors(&self, block: BlockId) -> &[BlockId] {+ let block = &self.blocks[block as usize];+ let start = block.predecessors_start as usize;+ &self.predecessors[start..start + block.predecessor_count as usize]+ }++ pub fn successors(&self, block: BlockId) -> &[BlockId] {+ let block = &self.blocks[block as usize];+ let start = block.successors_start as usize;+ &self.successors[start..start + block.successor_count as usize]+ }++ pub fn terminator(&self, block: BlockId) -> Value {+ self.blocks[block as usize].end - 1+ }++ /// The phis of a block, forwarded ones included.+ pub fn phis(&self, block: BlockId) -> PhiIter<'_> {+ PhiIter {+ func: self,+ next: self.blocks[block as usize].first_phi,+ }+ }++ /// The targets of a `BrTable`, the default last, as indices into the block's successors.+ pub fn table_targets(&self, value: Value) -> &[BlockId] {+ let node = &self.nodes[value as usize];+ debug_assert_eq!(node.op, Op::BrTable);+ let start = node.args[1] as usize;+ &self.operands[start..start + node.args[2] as usize + 1]+ }++ /// Whether `block` is the header of a loop.+ pub fn is_loop_header(&self, block: BlockId) -> bool {+ let loop_index = self.blocks[block as usize].loop_index;+ loop_index != NONE && self.loops[loop_index as usize].header == block+ }+}++pub struct PhiIter<'a> {+ func: &'a Func,+ next: Value,+}++impl Iterator for PhiIter<'_> {+ type Item = Value;++ fn next(&mut self) -> Option<Value> {+ if self.next == NONE {+ return None;+ }+ let phi = self.next;+ self.next = self.func.nodes[phi as usize].args[2];+ Some(phi)+ }+}diff --git a/Libraries/LibWasm/JIT/src/ir/verify.rs b/Libraries/LibWasm/JIT/src/ir/verify.rsnew file mode 100644index 00000000000..c49bf6a557a--- /dev/null+++ b/Libraries/LibWasm/JIT/src/ir/verify.rs@@ -0,0 +1,282 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The IR verifier: checks the invariants every phase relies on. It runs under `verify-ir` and in tests.++use super::{Effect, Func, NONE, Op, Shape, Type, Value};++/// The immediate dominator of each block, with the entry its own. Linear order is a topological order of the+/// forward edges, so one pass over the blocks in it finds them; loops add back edges only.+pub fn immediate_dominators(func: &Func) -> Vec<u32> {+ let mut idom = vec![NONE; func.blocks.len()];+ if func.blocks.is_empty() {+ return idom;+ }+ idom[0] = 0;+ for block in 1..func.blocks.len() as u32 {+ let mut dominator = NONE;+ for &predecessor in func.predecessors(block) {+ if predecessor >= block || idom[predecessor as usize] == NONE {+ continue;+ }+ dominator = if dominator == NONE {+ predecessor+ } else {+ intersect(&idom, dominator, predecessor)+ };+ }+ idom[block as usize] = dominator;+ }+ idom+}++fn intersect(idom: &[u32], mut a: u32, mut b: u32) -> u32 {+ while a != b {+ while a > b {+ a = idom[a as usize];+ }+ while b > a {+ b = idom[b as usize];+ }+ }+ a+}++/// Whether block `a` dominates block `b`.+pub fn dominates(idom: &[u32], a: u32, mut b: u32) -> bool {+ loop {+ if a == b {+ return true;+ }+ if b == 0 || idom[b as usize] == NONE || b < a {+ return false;+ }+ b = idom[b as usize];+ }+}++/// Checks the function. `is_dead` tells which nodes cleanup removed; `after_cleanup` requires that no forwarded+/// phi is used.+pub fn verify(func: &Func, is_dead: &dyn Fn(Value) -> bool, after_cleanup: bool) -> Result<(), String> {+ let mut errors = Vec::new();+ let mut error = |message: String| {+ if errors.len() < 20 {+ errors.push(message);+ }+ };+ let idom = immediate_dominators(func);+ // The block of every body node and phi, to check dominance.+ let mut block_of = vec![NONE; func.nodes.len()];+ for (index, block) in func.blocks.iter().enumerate() {+ let block_id = index as u32;+ if block.start >= block.end {+ error(format!("b{index} has no terminator"));+ continue;+ }+ if index > 0 && idom[index] == NONE {+ error(format!("b{index} is unreachable"));+ }+ for value in block.start..block.end {+ let op = func.node(value).op;+ if matches!(op, Op::Phi | Op::Forward) || op.is_entry_value() {+ continue;+ }+ block_of[value as usize] = block_id;+ if op.is_terminator() != (value == block.end - 1) {+ error(format!("v{value} in b{index}: terminators end blocks and only they do"));+ }+ }+ for phi in func.phis(block_id) {+ block_of[phi as usize] = block_id;+ let node = func.node(phi);+ if node.op == Op::Phi && node.args[1] as usize != func.predecessors(block_id).len() {+ error(format!(+ "phi v{phi} of b{index} has {} inputs for {} predecessors",+ node.args[1],+ func.predecessors(block_id).len()+ ));+ }+ }+ for &successor in func.successors(block_id) {+ if successor as usize >= func.blocks.len() {+ error(format!("b{index} has an unknown successor b{successor}"));+ continue;+ }+ let count = func.successors(block_id).iter().filter(|s| **s == successor).count();+ let back = func.predecessors(successor).iter().filter(|p| **p == block_id).count();+ if count != 1 || back != 1 {+ error(format!(+ "the edge b{index} -> b{successor} is not listed once on each side"+ ));+ }+ }+ for &predecessor in func.predecessors(block_id) {+ if !func.successors(predecessor).contains(&block_id) {+ error(format!(+ "b{index} lists b{predecessor} as a predecessor, which does not branch to it"+ ));+ }+ }+ let terminator = func.terminator(block_id);+ 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),+ _ => None,+ };+ if let Some(expected) = expected_successors+ && func.successors(block_id).len() != expected+ {+ error(format!("b{index} has {} successors", func.successors(block_id).len()));+ }+ }++ let defined_before = |input: Value, block: u32, position: Value| -> bool {+ let node = func.node(input);+ if node.op.is_entry_value() {+ return true;+ }+ let definition = block_of[input as usize];+ if definition == NONE {+ return false;+ }+ if definition == block {+ return node.op == Op::Phi || input < position;+ }+ dominates(&idom, definition, block)+ };+ for (index, block) in func.blocks.iter().enumerate() {+ let block_id = index as u32;+ for value in (block.start..block.end).chain(func.phis(block_id)) {+ let node = func.node(value);+ if node.op.is_entry_value() || block_of[value as usize] != block_id || is_dead(value) {+ continue;+ }+ if after_cleanup && node.op == Op::Forward {+ continue;+ }+ for (input_index, &input) in func.inputs(value).iter().enumerate() {+ if input as usize >= func.nodes.len() {+ error(format!("v{value} uses an unknown value {input}"));+ continue;+ }+ let mut input = input;+ while !after_cleanup && func.node(input).op == Op::Forward {+ input = func.node(input).args[0];+ }+ let input_node = func.node(input);+ if input_node.ty == Type::None {+ error(format!("v{value} uses v{input}, which has no value"));+ }+ if after_cleanup && input_node.op == Op::Forward {+ error(format!("v{value} uses the forwarded phi v{input}"));+ }+ if is_dead(input) {+ error(format!("v{value} uses the dead v{input}"));+ }+ let (use_block, position) = if node.op == Op::Phi {+ let predecessor = func.predecessors(block_id)[input_index];+ (predecessor, func.blocks[predecessor as usize].end)+ } else {+ (block_id, value)+ };+ if !defined_before(input, use_block, position) {+ error(format!(+ "v{value} in b{index} uses v{input}, which does not dominate it"+ ));+ }+ }+ check_types(func, value, &mut error);+ }+ }+ if errors.is_empty() {+ Ok(())+ } else {+ Err(errors.join("\n"))+ }+}++fn check_types(func: &Func, value: Value, error: &mut impl FnMut(String)) {+ let node = func.node(value);+ let inputs = func.inputs(value);+ let input_type = |index: usize| func.node(inputs[index]).ty;+ let same = |ty: Type| inputs.iter().all(|input| func.node(*input).ty == ty);+ let ok = match node.op {+ Op::Add+ | Op::Sub+ | Op::Mul+ | Op::And+ | Op::Or+ | Op::Xor+ | Op::Shl+ | Op::ShrS+ | Op::ShrU+ | Op::Rotl+ | Op::Rotr+ | Op::DivS+ | Op::DivU+ | Op::RemS+ | Op::RemU+ | Op::Clz+ | Op::Ctz+ | Op::Popcnt+ | Op::Extend8S+ | Op::Extend16S+ | 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)+ }+ Op::FAdd+ | Op::FSub+ | Op::FMul+ | Op::FDiv+ | Op::FMin+ | Op::FMax+ | Op::FCopysign+ | Op::FAbs+ | Op::FNeg+ | Op::FSqrt+ | Op::FCeil+ | Op::FFloor+ | Op::FTrunc+ | Op::FNearest => node.ty.is_float() && same(node.ty),+ Op::FloatCompare | Op::BranchFloatCompare => input_type(0).is_float() && input_type(0) == input_type(1),+ Op::ExtendI32S | Op::ExtendI32U => node.ty == Type::I64 && input_type(0) == Type::I32,+ 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,+ 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::ReadField+ | Op::WriteField => input_type(0) == Type::Pointer,+ 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,+ Op::CheckNull => input_type(0) == Type::Ref,+ Op::CalleeInstance => matches!(input_type(0), Type::Ref | Type::Pointer) && input_type(1) == Type::Pointer,+ Op::Call | Op::TailCall => {+ matches!(input_type(0), Type::Ref | Type::Pointer)+ && input_type(1) == Type::Pointer+ && input_type(2) == Type::Pointer+ }+ Op::Helper => input_type(0) == Type::Pointer && inputs.len() <= 7,+ _ => true,+ };+ if !ok {+ error(format!("v{value} ({}) has inputs of the wrong types", node.op.name()));+ }+ if node.op.shape() == Shape::Variadic && node.op != Op::Phi && node.effect() == Effect::Pure {+ error(format!("v{value} is a pure variadic node"));+ }+}diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rsnew file mode 100644index 00000000000..2d6bebc0331--- /dev/null+++ b/Libraries/LibWasm/JIT/src/lib.rs@@ -0,0 +1,250 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The LibWasm optimizing JIT compiler.+//!+//! This crate is a pure compiler: it turns one function of a validated module into machine code and the metadata+//! the runtime needs to install and run it. It touches no heap and no store, so it runs on any thread. See+//! `ARCHITECTURE.md` for how it works.++// NB: The assemblers and the small data structures are libjs_jit's, until both JITs share them from a crate of+// their own. The test helpers of the assemblers' own tests are for libjs_jit's tests.+#[cfg_attr(test, allow(dead_code))]+#[path = "../../../LibJS/JIT/Rust/src/asm/mod.rs"]+pub mod asm;+#[path = "../../../LibJS/JIT/Rust/src/inline_vec.rs"]+pub mod inline_vec;++pub mod builder;+pub mod codegen;+pub mod convention;+pub mod decode;+pub mod ir;+pub mod passes;+pub mod regalloc;+pub mod runtime;+pub mod stubs;+pub mod table;++use libwasm_module::Module;+use std::sync::Arc;++/// Why a function was not compiled.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CompileFailure {+ /// The function uses something the JIT does not compile yet, at module offset `pc`.+ Unsupported { pc: u32, what: &'static str },+ /// The assembler could not finish the code.+ CodeGeneration,+}++/// Options of a compile.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct Options {+ /// Check the IR and the register allocation after every phase.+ pub verify_ir: bool,+ pub dump_ir: bool,+ pub dump_asm: bool,+ /// Measure the time of every phase (`Stats::ticks`), which includes verification if that is on too.+ pub stats: bool,+ /// Give values only a few registers, so that the allocator spills and reloads all the time.+ pub stress_registers: bool,+ /// Leave loop invariant code in its loop.+ pub no_licm: bool,+ /// Replace nodes that compute what a dominating node computed already, beyond what building does (`passes/gvn.rs`).+ /// Off by default: it finds about 0.1% of the nodes of real modules redundant, for 7 to 16 ns per code byte.+ pub gvn: bool,+}++/// The addresses of the runtime compiled code reaches, which are constants of the process.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct RuntimeInfo {+ /// Where code jumps to trap, with the TRAP_* code in edi and rbp the frame pointer of the trapping function.+ pub trap_exit: u64,+ /// The runtime's helpers (`wasm_runtime_memory_grow`, `wasm_runtime_table_grow` and `wasm_runtime_call_host`),+ /// which take the `ExecutionContext` with their operands in its `arguments`.+ pub memory_grow: u64,+ pub table_grow: u64,+ pub call_host: u64,+}++/// What to compile.+pub struct CompileRequest {+ pub module: Arc<Module>,+ /// The function, counting imports.+ pub function: u32,+ pub runtime: RuntimeInfo,+ pub options: Options,+}++/// The reusable state of one compile thread: every phase's storage, cleared between compiles.+#[derive(Default)]+pub struct CompileContext {+ pub func: ir::Func,+ builder: builder::Builder,+ pub liveliness: passes::cleanup::Liveliness,+ licm: passes::licm::Licm,+ scheduler: passes::schedule::Scheduler,+ gvn: passes::gvn::Gvn,+ allocator: regalloc::Allocator,+ pub allocation: regalloc::Allocation,+}++/// The phases of a compile, as `Stats::ticks` counts them.+pub const PHASES: [&str; 5] = ["build", "passes", "liveness", "allocation", "codegen"];++/// What a compile did.+#[derive(Debug, Clone, Copy, Default)]+pub struct Stats {+ /// The time stamp counter ticks of each phase (see `PHASES`), with `Options::stats`.+ pub ticks: [u64; PHASES.len()],+ /// The nodes the function's IR has, dead ones included.+ pub nodes: u32,+ /// The stack slots of the frame.+ pub slots: u32,+ /// The moves the allocator inserted, on edges and before nodes.+ pub moves: u32,+ /// The nodes loop invariant code motion moved out of loops.+ pub hoisted: u32,+ /// The nodes global value numbering replaced.+ pub eliminated: u32,+}++/// The time stamp counter, for the phase timers.+pub fn ticks() -> u64 {+ #[cfg(target_arch = "x86_64")]+ // SAFETY: rdtsc only reads a counter.+ unsafe {+ core::arch::x86_64::_rdtsc()+ }+ #[cfg(not(target_arch = "x86_64"))]+ 0+}++/// The result of a compile.+#[derive(Debug, Default)]+pub struct CompiledFunction {+ /// Position-independent machine code; the entry point is its start.+ pub code: Vec<u8>,+ /// The bytes between fp and rsp in the function's frame.+ pub frame_size: u32,+ pub stats: Stats,+ pub dump: Option<String>,+}++/// Compiles one function of a module.+pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Result<CompiledFunction, CompileFailure> {+ let module = &*request.module;+ let timed = request.options.stats;+ let mut stats = Stats::default();+ let mut last = if timed { ticks() } else { 0 };+ let mut lap = |phase: usize, stats: &mut Stats| {+ if timed {+ let now = ticks();+ stats.ticks[phase] += now - last;+ last = now;+ }+ };+ context.builder.build(module, request.function, &mut context.func)?;+ lap(0, &mut stats);+ if request.options.verify_ir+ && let Err(errors) = ir::verify::verify(&context.func, &|_| false, false)+ {+ panic!(+ "invalid IR after building function {}:\n{errors}\n{}",+ request.function,+ ir::dump::dump(&context.func, &|_| false)+ );+ }+ passes::cleanup::cleanup(&mut context.func, &mut context.liveliness);+ if request.options.no_licm {+ context.licm.home.clear();+ context.licm.home.resize(context.func.nodes.len(), ir::NONE);+ } else {+ context.licm.run(&context.func, &context.liveliness);+ }+ let gvn = request.options.gvn.then_some(&mut context.gvn);+ context.scheduler.run(+ &mut context.func,+ &mut context.liveliness,+ &context.licm.home,+ gvn,+ module.global_space.len(),+ );+ lap(1, &mut stats);+ let liveliness = &context.liveliness;+ if request.options.verify_ir+ && let Err(errors) = ir::verify::verify(&context.func, &|value| liveliness.is_dead(value), true)+ {+ panic!(+ "invalid IR after cleanup and scheduling of function {}:\n{errors}\n{}",+ request.function,+ ir::dump::dump(&context.func, &|value| liveliness.is_dead(value))+ );+ }+ context.allocator.allocate_with(+ &context.func,+ &context.liveliness,+ &mut context.allocation,+ request.options.stress_registers,+ );+ lap(3, &mut stats);+ if timed {+ // NB: Liveness runs first in the allocator, which times it.+ stats.ticks[2] = context.allocator.liveness_ticks;+ stats.ticks[3] = stats.ticks[3].saturating_sub(stats.ticks[2]);+ }+ if request.options.verify_ir+ && let Err(errors) = regalloc::verify::verify(&context.func, &context.liveliness, &context.allocation)+ {+ panic!(+ "invalid register allocation of function {}:\n{errors}\n{}\n{}",+ request.function,+ ir::dump::dump(&context.func, &|value| liveliness.is_dead(value)),+ regalloc::verify::dump(&context.func, &context.liveliness, &context.allocation)+ );+ }+ let generated = codegen::x86_64::generate(+ &context.func,+ &context.liveliness,+ &context.allocation,+ &request.runtime,+ )?;+ lap(4, &mut stats);+ stats.nodes = context.func.nodes.len() as u32;+ stats.slots = context.allocation.slot_count;+ stats.moves = context.allocation.moves.len() as u32;+ stats.hoisted = if request.options.no_licm {+ 0+ } else {+ context.licm.hoisted+ };+ stats.eliminated = if request.options.gvn { context.gvn.eliminated } else { 0 };+ let mut compiled = CompiledFunction {+ code: generated.code,+ frame_size: generated.frame_size,+ stats,+ dump: None,+ };+ if request.options.dump_ir || request.options.dump_asm {+ let mut text = String::new();+ if request.options.dump_ir {+ text.push_str(&ir::dump::dump(&context.func, &|value| liveliness.is_dead(value)));+ text.push_str(®alloc::verify::dump(+ &context.func,+ &context.liveliness,+ &context.allocation,+ ));+ }+ if request.options.dump_asm {+ for line in asm::disassembler::listing(asm::Architecture::X86_64, &compiled.code) {+ text.push_str(&format!("{:6x} {}\n", line.offset, line.text));+ }+ }+ compiled.dump = Some(text);+ }+ Ok(compiled)+}diff --git a/Libraries/LibWasm/JIT/src/passes/cleanup.rs b/Libraries/LibWasm/JIT/src/passes/cleanup.rsnew file mode 100644index 00000000000..b47881f1ae4--- /dev/null+++ b/Libraries/LibWasm/JIT/src/passes/cleanup.rs@@ -0,0 +1,204 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Cleanup after building: removes the phis that turned out trivial, to a fixed point, rewrites every use of a+//! forwarded phi, removes pure nodes nobody uses, and fuses branches with the comparisons only they use.++use crate::ir::{Effect, Func, IntCondition, NONE, Node, Op, Shape, Type, Value};++/// What cleanup leaves for the later phases: which nodes are gone, and how often each value is used.+#[derive(Default)]+pub struct Liveliness {+ pub dead: Vec<bool>,+ pub uses: Vec<u32>,+ worklist: Vec<Value>,+}++impl Liveliness {+ pub fn is_dead(&self, value: Value) -> bool {+ self.dead[value as usize]+ }+}++fn resolve(func: &Func, mut value: Value) -> Value {+ while func.nodes[value as usize].op == Op::Forward {+ value = func.nodes[value as usize].args[0];+ }+ value+}++/// Whether a phi's inputs are only itself and one other value.+fn trivial_input(func: &Func, phi: Value) -> Option<Value> {+ let mut same = NONE;+ for &input in func.inputs(phi) {+ let input = resolve(func, input);+ if input == phi || input == same {+ continue;+ }+ if same != NONE {+ return None;+ }+ same = input;+ }+ (same != NONE).then_some(same)+}++pub fn cleanup(func: &mut Func, state: &mut Liveliness) {+ // Trivial phis, to a fixed point over the phis only.+ loop {+ let mut changed = false;+ for block in 0..func.blocks.len() as u32 {+ let mut phi = func.blocks[block as usize].first_phi;+ while phi != NONE {+ let next = func.nodes[phi as usize].args[2];+ if func.nodes[phi as usize].op == Op::Phi+ && let Some(value) = trivial_input(func, phi)+ {+ let node = &mut func.nodes[phi as usize];+ node.op = Op::Forward;+ node.args[0] = value;+ node.args[1] = 0;+ changed = true;+ }+ phi = next;+ }+ }+ if !changed {+ break;+ }+ }+ // Every use of a forwarded phi becomes a use of its value, and every use is counted.+ let count = func.nodes.len();+ state.dead.clear();+ state.dead.resize(count, false);+ state.uses.clear();+ state.uses.resize(count, 0);+ for index in 0..count {+ let node = func.nodes[index];+ if node.op == Op::Forward {+ state.dead[index] = true;+ continue;+ }+ match node.op.shape() {+ Shape::Fixed(inputs) => {+ for slot in 0..inputs as usize {+ let input = resolve(func, node.args[slot]);+ func.nodes[index].args[slot] = input;+ state.uses[input as usize] += 1;+ }+ }+ Shape::Variadic => {+ let start = node.args[0] as usize;+ for slot in start..start + node.args[1] as usize {+ let input = resolve(func, func.operands[slot]);+ func.operands[slot] = input;+ state.uses[input as usize] += 1;+ }+ }+ }+ }++ // Dead code: pure nodes without uses.+ state.worklist.clear();+ for index in 0..count {+ // NB: Unused results of calls stay, since they tell how the call returns its results.+ let node = &func.nodes[index];+ if state.uses[index] == 0 && !state.dead[index] && node.effect() == Effect::Pure && node.op != Op::CallResult {+ state.worklist.push(index as Value);+ }+ }+ while let Some(value) = state.worklist.pop() {+ if state.dead[value as usize] {+ continue;+ }+ state.dead[value as usize] = true;+ for input_index in 0..func.inputs(value).len() {+ let input = func.inputs(value)[input_index];+ let uses = &mut state.uses[input as usize];+ *uses -= 1;+ let input_node = &func.nodes[input as usize];+ if *uses == 0 && input_node.effect() == Effect::Pure && input_node.op != Op::CallResult {+ state.worklist.push(input);+ }+ }+ }++ // Forwarded and dead phis leave their blocks.+ for block in 0..func.blocks.len() {+ let mut previous = NONE;+ let mut phi = func.blocks[block].first_phi;+ while phi != NONE {+ let next = func.nodes[phi as usize].args[2];+ if state.dead[phi as usize] {+ if previous == NONE {+ func.blocks[block].first_phi = next;+ } else {+ func.nodes[previous as usize].args[2] = next;+ }+ } else {+ previous = phi;+ }+ phi = next;+ }+ }++ fuse_branches(func, state);+}++/// A branch on a comparison that only it uses, in the same block, compares itself.+fn fuse_branches(func: &mut Func, state: &mut Liveliness) {+ for block in 0..func.blocks.len() {+ let terminator = func.blocks[block].end - 1;+ let node = func.nodes[terminator as usize];+ if node.op != Op::Branch {+ continue;+ }+ let condition = node.args[0];+ let condition_node = func.nodes[condition as usize];+ let in_block = condition >= func.blocks[block].start && condition < terminator;+ if !in_block || state.uses[condition as usize] != 1 {+ continue;+ }+ let fused = match condition_node.op {+ Op::Compare => Node::new(+ Op::BranchCompare,+ Type::None,+ condition_node.flags,+ [condition_node.args[0], condition_node.args[1], 0],+ ),+ Op::FloatCompare => Node::new(+ Op::BranchFloatCompare,+ Type::None,+ condition_node.flags,+ [condition_node.args[0], condition_node.args[1], 0],+ ),+ Op::Eqz => {+ let operand = condition_node.args[0];+ let ty = func.nodes[operand as usize].ty;+ let zero = if ty.is_64() {+ Node::new(Op::Const64, ty, 0, [0, 0, 0])+ } else {+ Node::new(Op::Const32, Type::I32, 0, [0, 0, 0])+ };+ func.nodes.push(zero);+ state.dead.push(false);+ state.uses.push(1);+ let zero = func.nodes.len() as Value - 1;+ Node::new(+ Op::BranchCompare,+ Type::None,+ IntCondition::Eq as u8,+ [operand, zero, 0],+ )+ }+ _ => continue,+ };+ func.nodes[terminator as usize] = fused;+ // The comparison's inputs are now the branch's.+ state.dead[condition as usize] = true;+ state.uses[condition as usize] = 0;+ }+}diff --git a/Libraries/LibWasm/JIT/src/passes/dominators.rs b/Libraries/LibWasm/JIT/src/passes/dominators.rsnew file mode 100644index 00000000000..824201890df--- /dev/null+++ b/Libraries/LibWasm/JIT/src/passes/dominators.rs@@ -0,0 +1,106 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The dominator tree. Linear order is a topological order of the forward edges and loops are entered at their+//! header only, so one pass over the blocks finds every immediate dominator. The tree is numbered in preorder, so+//! that a dominance query compares two numbers.++use crate::ir::{BlockId, Func, NONE};++#[derive(Default)]+pub struct Dominators {+ pub idom: Vec<BlockId>,+ /// The preorder number of each block, and the largest number in its subtree.+ pre: Vec<u32>,+ last: Vec<u32>,+ children_start: Vec<u32>,+ children: Vec<BlockId>,+ stack: Vec<(BlockId, u32)>,+}++impl Dominators {+ pub fn compute(&mut self, func: &Func) {+ let count = func.blocks.len();+ self.idom.clear();+ self.idom.resize(count, NONE);+ if count == 0 {+ return;+ }+ self.idom[0] = 0;+ for block in 1..count as BlockId {+ let mut dominator = NONE;+ for &predecessor in func.predecessors(block) {+ if predecessor >= block || self.idom[predecessor as usize] == NONE {+ continue;+ }+ dominator = if dominator == NONE {+ predecessor+ } else {+ let (mut a, mut b) = (dominator, predecessor);+ while a != b {+ while a > b {+ a = self.idom[a as usize];+ }+ while b > a {+ b = self.idom[b as usize];+ }+ }+ a+ };+ }+ self.idom[block as usize] = dominator;+ }+ // Children lists, then a preorder walk.+ self.children_start.clear();+ self.children_start.resize(count + 1, 0);+ for block in 1..count {+ let parent = self.idom[block];+ if parent != NONE {+ self.children_start[parent as usize + 1] += 1;+ }+ }+ for index in 0..count {+ self.children_start[index + 1] += self.children_start[index];+ }+ self.children.clear();+ self.children.resize(self.children_start[count] as usize, 0);+ let mut cursor = self.children_start.clone();+ for block in 1..count {+ let parent = self.idom[block];+ if parent != NONE {+ self.children[cursor[parent as usize] as usize] = block as BlockId;+ cursor[parent as usize] += 1;+ }+ }+ self.pre.clear();+ self.pre.resize(count, NONE);+ self.last.clear();+ self.last.resize(count, NONE);+ let mut number = 0;+ self.stack.clear();+ self.stack.push((0, self.children_start[0]));+ self.pre[0] = 0;+ while let Some(&mut (block, ref mut next)) = self.stack.last_mut() {+ if *next < self.children_start[block as usize + 1] {+ let child = self.children[*next as usize];+ *next += 1;+ number += 1;+ self.pre[child as usize] = number;+ self.stack.push((child, self.children_start[child as usize]));+ } else {+ self.last[block as usize] = number;+ self.stack.pop();+ }+ }+ }++ /// Whether block `a` dominates block `b`.+ #[inline]+ pub fn dominates(&self, a: BlockId, b: BlockId) -> bool {+ let (pre_a, pre_b) = (self.pre[a as usize], self.pre[b as usize]);+ pre_a <= pre_b && pre_b <= self.last[a as usize]+ }+}diff --git a/Libraries/LibWasm/JIT/src/passes/gvn.rs b/Libraries/LibWasm/JIT/src/passes/gvn.rsnew file mode 100644index 00000000000..b6a524ad9c7--- /dev/null+++ b/Libraries/LibWasm/JIT/src/passes/gvn.rs@@ -0,0 +1,129 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Global value numbering, over the dominator tree, as part of scheduling's walk in linear order: a node computing+//! what a node of a block that dominates it computed already is replaced by that node.+//!+//! The builder numbers values too, but forgets what a construct numbered when it ends, even where that dominates the+//! code after it (whatever a `block` computes before its first branch out, say). This pass keeps every entry for+//! as long as its block dominates the walk.+//!+//! Reads are numbered by alias class, with epochs that the writes of the class advance: memory loads by a memory+//! epoch that stores and calls advance, and global values by an epoch of their global that its `global.set`+//! advances and one of all globals that calls advance. A block continues the epochs of the block before it only if+//! that is its only predecessor, so that a read is only ever shared with one on every path to it.++use crate::ir::{BlockId, Effect, FLAG_IMMUTABLE, Func, NONE, Op, Shape, Value};+use crate::passes::dominators::Dominators;+use crate::table::Table;++type Key = [u32; 6];++#[derive(Default)]+pub struct Gvn {+ dominators: Dominators,+ table: Table<Key>,+ log: Vec<(Key, u32)>,+ /// The blocks whose entries are in the table, from the entry down the dominator tree, and where their entries+ /// start in the log.+ stack: Vec<(BlockId, u32)>,+ /// The node each node was replaced by, or itself.+ pub canon: Vec<Value>,+ memory_epoch: u32,+ global_epochs: Vec<u32>,+ globals_epoch: u32,+ previous: BlockId,+ /// How many nodes were replaced.+ pub eliminated: u32,+}++impl Gvn {+ pub fn start(&mut self, func: &Func, globals: usize) {+ self.dominators.compute(func);+ self.table.clear();+ self.log.clear();+ self.stack.clear();+ self.canon.clear();+ self.canon.extend(0..func.nodes.len() as Value);+ self.memory_epoch = 0;+ self.global_epochs.clear();+ self.global_epochs.resize(globals, 0);+ self.globals_epoch = 0;+ self.previous = NONE;+ self.eliminated = 0;+ }++ pub fn enter_block(&mut self, func: &Func, block: BlockId) {+ while let Some(&(top, mark)) = self.stack.last() {+ if self.dominators.dominates(top, block) {+ break;+ }+ while self.log.len() > mark as usize {+ let (key, previous) = self.log.pop().expect("the log is longer than the mark");+ self.table.insert(key, previous);+ }+ self.stack.pop();+ }+ if func.predecessors(block) != [self.previous] {+ self.memory_epoch += 1;+ self.globals_epoch += 1;+ }+ self.stack.push((block, self.log.len() as u32));+ self.previous = block;+ }++ /// Numbers `value`, and returns the node that computes the same, if one does.+ pub fn visit(&mut self, func: &Func, value: Value) -> Option<Value> {+ let node = func.node(value);+ let epochs = match node.op {+ Op::Store => {+ self.memory_epoch += 1;+ return None;+ }+ Op::GlobalSet => {+ self.global_epochs[node.args[2] as usize] += 1;+ return None;+ }+ Op::Call | Op::Helper => {+ self.memory_epoch += 1;+ self.globals_epoch += 1;+ return None;+ }+ Op::Load | Op::VectorLoad => [self.memory_epoch, 0],+ Op::GlobalGet if node.flags & FLAG_IMMUTABLE == 0 => {+ [self.global_epochs[node.args[1] as usize], self.globals_epoch]+ }+ Op::Phi | Op::Forward | Op::CallResult | Op::Const128 => return None,+ _ if node.effect() == Effect::Pure && !node.op.is_entry_value() => [0, 0],+ _ => return None,+ };+ let Shape::Fixed(inputs) = node.op.shape() else {+ return None;+ };+ let mut arguments = node.args;+ for argument in arguments.iter_mut().take(inputs as usize) {+ *argument = self.canon[*argument as usize];+ }+ let key = [+ node.op as u32 | ((node.ty as u32) << 16) | (u32::from(node.flags) << 24),+ arguments[0],+ arguments[1],+ arguments[2],+ epochs[0],+ epochs[1],+ ];+ if let Some(existing) = self.table.get(key)+ && existing != NONE+ {+ self.canon[value as usize] = existing;+ self.eliminated += 1;+ return Some(existing);+ }+ let previous = self.table.insert(key, value).unwrap_or(NONE);+ self.log.push((key, previous));+ None+ }+}diff --git a/Libraries/LibWasm/JIT/src/passes/licm.rs b/Libraries/LibWasm/JIT/src/passes/licm.rsnew file mode 100644index 00000000000..87fa280d096--- /dev/null+++ b/Libraries/LibWasm/JIT/src/passes/licm.rs@@ -0,0 +1,127 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Loop invariant code motion: finds the nodes of loops that compute the same value in every iteration, and the+//! outermost loop each one is invariant in. `schedule` then moves them to the end of that loop's preheader: the+//! block entering the loop, which always ends in a jump to its header.+//!+//! A pure node is invariant in a loop when none of its inputs is defined in the loop (or each was hoisted out of+//! it). Pure nodes never trap, so computing them where the loop might not have needs no proof that it would have.+//! A global's value is invariant in a loop that does not set it. Memory loads stay where they are, since moving one+//! out of a loop that would not have run it could trap.+//!+//! OPTIMIZATION: Nothing leaves a loop that calls: calls clobber every register, so a hoisted value would be reloaded+//! from its stack slot in every iteration, which costs about what computing it again does. In a loop that calls a+//! leaf 10 million times, hoisting the callee's `FunctionHeader` made it 16% slower.++use crate::ir::{BlockId, Effect, FLAG_IMMUTABLE, Func, NONE, Op, Value};+use crate::passes::cleanup::Liveliness;++#[derive(Default)]+pub struct Licm {+ /// The block each value moves to, or NONE.+ pub home: Vec<BlockId>,+ /// The block of each body node.+ block_of: Vec<BlockId>,+ /// Per loop: whether it calls, and the globals it sets.+ calls: Vec<bool>,+ globals_set: Vec<Vec<u32>>,+ /// How many nodes moved.+ pub hoisted: u32,+}++impl Licm {+ pub fn run(&mut self, func: &Func, liveliness: &Liveliness) {+ let count = func.nodes.len();+ self.home.clear();+ self.home.resize(count, NONE);+ self.hoisted = 0;+ if func.loops.is_empty() {+ return;+ }+ self.block_of.clear();+ self.block_of.resize(count, 0);+ self.calls.clear();+ self.calls.resize(func.loops.len(), false);+ for set in &mut self.globals_set {+ set.clear();+ }+ self.globals_set.resize_with(func.loops.len(), Vec::new);+ for (index, block) in func.blocks.iter().enumerate() {+ for value in block.start..block.end {+ self.block_of[value as usize] = index as BlockId;+ let node = func.node(value);+ if liveliness.is_dead(value) || block.loop_index == NONE {+ continue;+ }+ let global = match node.op {+ Op::Call | Op::Helper => None,+ Op::GlobalSet => Some(node.args[2]),+ _ => continue,+ };+ let mut loop_index = block.loop_index;+ while loop_index != NONE {+ match global {+ None => self.calls[loop_index as usize] = true,+ Some(global) => self.globals_set[loop_index as usize].push(global),+ }+ loop_index = func.loops[loop_index as usize].parent;+ }+ }+ }+ for phi_block in 0..func.blocks.len() as BlockId {+ for phi in func.phis(phi_block) {+ self.block_of[phi as usize] = phi_block;+ }+ }+ for block in &func.blocks {+ if block.loop_index == NONE {+ continue;+ }+ for value in block.start..block.end - 1 {+ let node = func.node(value);+ if liveliness.is_dead(value) || node.op.is_entry_value() || matches!(node.op, Op::Phi | Op::Forward) {+ continue;+ }+ let global = match node.effect() {+ Effect::Pure if node.op != Op::CallResult => None,+ Effect::Read if node.op == Op::GlobalGet && node.flags & FLAG_IMMUTABLE == 0 => Some(node.args[1]),+ _ => continue,+ };+ let mut target = NONE;+ let mut loop_index = block.loop_index;+ while loop_index != NONE {+ let loop_ = &func.loops[loop_index as usize];+ let outside = |input: &Value| {+ let input_node = func.node(*input);+ if input_node.op.is_entry_value() {+ return true;+ }+ let home = self.home[*input as usize];+ let block = if home == NONE {+ self.block_of[*input as usize]+ } else {+ home+ };+ block < loop_.header || block > loop_.last+ };+ let unwritten =+ global.is_none_or(|global| !self.globals_set[loop_index as usize].contains(&global));+ if self.calls[loop_index as usize] || !unwritten || !func.inputs(value).iter().all(outside) {+ break;+ }+ target = loop_index;+ loop_index = loop_.parent;+ }+ if target != NONE {+ let header = func.loops[target as usize].header;+ self.home[value as usize] = func.predecessors(header)[0];+ self.hoisted += 1;+ }+ }+ }+ }+}diff --git a/Libraries/LibWasm/JIT/src/passes/mod.rs b/Libraries/LibWasm/JIT/src/passes/mod.rsnew file mode 100644index 00000000000..a7201a51f61--- /dev/null+++ b/Libraries/LibWasm/JIT/src/passes/mod.rs@@ -0,0 +1,13 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The passes over the IR after building it.++pub mod cleanup;+pub mod dominators;+pub mod gvn;+pub mod licm;+pub mod schedule;diff --git a/Libraries/LibWasm/JIT/src/passes/schedule.rs b/Libraries/LibWasm/JIT/src/passes/schedule.rsnew file mode 100644index 00000000000..18b8e180fc8--- /dev/null+++ b/Libraries/LibWasm/JIT/src/passes/schedule.rs@@ -0,0 +1,143 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Scheduling: rebuilds the node arena in linear order, which leaves out the dead nodes and puts the nodes loop+//! invariant code motion moved (`Licm::home`) at the end of their new block, before its terminator. Every input is+//! renumbered, so a node's index is its position again.+//!+//! The entry values come first, in the range of the entry block, and the phis last, outside every block's range,+//! since they are defined where their block starts wherever they are. Global value numbering (`gvn`) runs in the+//! same walk and leaves out the nodes it replaces.++use crate::ir::{Func, NONE, Node, Op, Shape, Value};+use crate::passes::cleanup::Liveliness;+use crate::passes::gvn::Gvn;++#[derive(Default)]+pub struct Scheduler {+ order: Vec<Value>,+ renumbered: Vec<Value>,+ nodes: Vec<Node>,+ hoisted: Vec<Vec<Value>>,+}++impl Scheduler {+ /// Schedules `func`, moving nodes as `home` says, and numbering values with `gvn` if it is given, for a module+ /// with `globals` globals.+ pub fn run(+ &mut self,+ func: &mut Func,+ liveliness: &mut Liveliness,+ home: &[u32],+ mut gvn: Option<&mut Gvn>,+ globals: usize,+ ) {+ let count = func.nodes.len();+ if let Some(gvn) = gvn.as_deref_mut() {+ gvn.start(func, globals);+ }+ for list in &mut self.hoisted {+ list.clear();+ }+ self.hoisted.resize_with(func.blocks.len(), Vec::new);+ for (value, &block) in home.iter().enumerate() {+ if block != NONE {+ self.hoisted[block as usize].push(value as Value);+ }+ }+ self.order.clear();+ let live = |value: Value| !liveliness.is_dead(value);+ // The entry values, wherever cleanup or the builder put them.+ for value in 0..count as Value {+ if live(value) && func.nodes[value as usize].op.is_entry_value() {+ self.order.push(value);+ }+ }+ for block in 0..func.blocks.len() {+ let data = func.blocks[block];+ let start = if block == 0 { 0 } else { self.order.len() };+ if let Some(gvn) = gvn.as_deref_mut() {+ gvn.enter_block(func, block as u32);+ }+ let mut emit = |value: Value, order: &mut Vec<Value>| {+ if let Some(gvn) = gvn.as_deref_mut()+ && gvn.visit(func, value).is_some()+ {+ return;+ }+ order.push(value);+ };+ for value in data.start..data.end - 1 {+ let op = func.nodes[value as usize].op;+ if live(value)+ && !op.is_entry_value()+ && !matches!(op, Op::Phi | Op::Forward)+ && home[value as usize] == NONE+ {+ emit(value, &mut self.order);+ }+ }+ for index in 0..self.hoisted[block].len() {+ emit(self.hoisted[block][index], &mut self.order);+ }+ emit(data.end - 1, &mut self.order);+ func.blocks[block].start = start as u32;+ func.blocks[block].end = self.order.len() as u32;+ }+ for block in 0..func.blocks.len() {+ let mut phi = func.blocks[block].first_phi;+ while phi != NONE {+ self.order.push(phi);+ phi = func.nodes[phi as usize].args[2];+ }+ }++ self.renumbered.clear();+ self.renumbered.resize(count, NONE);+ for (index, value) in self.order.iter().enumerate() {+ self.renumbered[*value as usize] = index as Value;+ }+ if let Some(gvn) = gvn {+ for value in 0..count {+ let canon = gvn.canon[value];+ if canon as usize != value {+ self.renumbered[value] = self.renumbered[canon as usize];+ }+ }+ }+ self.nodes.clear();+ for &value in &self.order {+ let mut node = func.nodes[value as usize];+ match node.op.shape() {+ Shape::Fixed(inputs) => {+ for slot in 0..inputs as usize {+ node.args[slot] = self.renumbered[node.args[slot] as usize];+ }+ }+ Shape::Variadic => {+ let start = node.args[0] as usize;+ for slot in start..start + node.args[1] as usize {+ func.operands[slot] = self.renumbered[func.operands[slot] as usize];+ }+ }+ }+ match node.op {+ Op::CallResult => node.args[0] = self.renumbered[node.args[0] as usize],+ Op::Phi if node.args[2] != NONE => node.args[2] = self.renumbered[node.args[2] as usize],+ _ => {}+ }+ self.nodes.push(node);+ }+ for block in &mut func.blocks {+ if block.first_phi != NONE {+ block.first_phi = self.renumbered[block.first_phi as usize];+ }+ }+ std::mem::swap(&mut func.nodes, &mut self.nodes);+ liveliness.dead.clear();+ liveliness.dead.resize(func.nodes.len(), false);+ }+}diff --git a/Libraries/LibWasm/JIT/src/regalloc/liveness.rs b/Libraries/LibWasm/JIT/src/regalloc/liveness.rsnew file mode 100644index 00000000000..2b25f5fdd37--- /dev/null+++ b/Libraries/LibWasm/JIT/src/regalloc/liveness.rs@@ -0,0 +1,254 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Liveness as one interval per value in linear order, from its definition to its last use, extended over every+//! loop that uses it but does not define it.+//!+//! Linear order keeps every loop contiguous, and every definition dominates the positions between it and its uses,+//! so an interval is a sound approximation of where the value is live: it only adds the arms of `if`s and the+//! like that come between a definition and a use without leading to it (the "holes" of an interval). Loops are+//! entered only at their header, so a value used in a loop and defined before it is live in all of it.+//!+//! Positions: a body node `n` is at `4n + 2`, which is where it reads its inputs and writes its value. The phis of a+//! block are defined at `4 * start`, before its first node. The moves into a successor's phis happen at+//! `4 * end - 1`, after the block's terminator, so that the phis' inputs are still where the terminator left them.+//! Parameters, the instance and the memory base are defined at position 0.++use crate::convention::{self, Place, Register};+use crate::ir::{BlockId, Func, NONE, Op, Type, Value};+use crate::passes::cleanup::Liveliness;++pub fn node_position(value: Value) -> u32 {+ 4 * value + 2+}++pub fn block_start_position(func: &Func, block: BlockId) -> u32 {+ 4 * func.blocks[block as usize].start+}++pub fn edge_position(func: &Func, block: BlockId) -> u32 {+ 4 * func.blocks[block as usize].end - 1+}++#[derive(Default)]+pub struct Liveness {+ /// Where each value is defined, or NONE for values that need no location (constants, dead nodes).+ pub definition: Vec<u32>,+ /// The last position each value is live at.+ pub end: Vec<u32>,+ /// The block each value is defined in.+ pub block: Vec<BlockId>,+ /// The use positions of value `v`, in order: `positions[starts[v]..starts[v + 1]]`.+ pub starts: Vec<u32>,+ pub positions: Vec<u32>,+ /// The register a value's first fixed use wants, or NONE as u8.+ pub hint: Vec<u8>,+ /// The last position of each loop, with its back edges' moves.+ pub loop_ends: Vec<u32>,+ cursor: Vec<u32>,+ places: Vec<Place>,+}++pub const NO_HINT: u8 = u8::MAX;++/// Whether a node is a value the register allocator gives a location.+#[inline]+pub fn is_allocated(func: &Func, liveliness: &Liveliness, value: Value) -> bool {+ let node = func.node(value);+ node.ty != Type::None && !node.op.is_constant() && !liveliness.is_dead(value)+}++impl Liveness {+ pub fn uses(&self, value: Value) -> &[u32] {+ let start = self.starts[value as usize] as usize;+ let end = self.starts[value as usize + 1] as usize;+ &self.positions[start..end]+ }++ /// Whether `value` is live at `position`, after its definition.+ #[inline]+ pub fn is_live_at(&self, value: Value, position: u32) -> bool {+ let definition = self.definition[value as usize];+ definition != NONE && definition < position && self.end[value as usize] >= position+ }++ /// Whether `value` is still needed after `position`.+ #[inline]+ pub fn is_live_after(&self, value: Value, position: u32) -> bool {+ self.end[value as usize] > position+ }++ /// The first use of `value` after `position`.+ pub fn next_use(&self, value: Value, position: u32) -> Option<u32> {+ let uses = self.uses(value);+ let index = uses.partition_point(|use_position| *use_position <= position);+ uses.get(index).copied()+ }++ pub fn compute(&mut self, func: &Func, liveliness: &Liveliness) {+ let count = func.nodes.len();+ self.definition.clear();+ self.definition.resize(count, NONE);+ self.end.clear();+ self.end.resize(count, 0);+ self.block.clear();+ self.block.resize(count, 0);+ self.hint.clear();+ self.hint.resize(count, NO_HINT);+ self.starts.clear();+ self.starts.resize(count + 1, 0);++ self.loop_ends.clear();+ for loop_ in &func.loops {+ self.loop_ends.push(edge_position(func, loop_.last));+ }++ // Definitions, and the number of uses of each value.+ let counts = &mut self.starts;+ for block in 0..func.blocks.len() as BlockId {+ let data = &func.blocks[block as usize];+ for phi in func.phis(block) {+ self.definition[phi as usize] = block_start_position(func, block);+ self.block[phi as usize] = block;+ }+ for value in data.start..data.end {+ let node = func.node(value);+ if liveliness.is_dead(value) || matches!(node.op, Op::Phi | Op::Forward) {+ continue;+ }+ if node.op.is_entry_value() {+ if !node.op.is_constant() && node.ty != Type::None {+ self.definition[value as usize] = 0;+ self.block[value as usize] = 0;+ }+ continue;+ }+ if node.ty != Type::None {+ self.definition[value as usize] = node_position(value);+ self.block[value as usize] = block;+ }+ for &input in func.inputs(value) {+ counts[input as usize] += 1;+ }+ }+ for &successor in func.successors(block) {+ let index = predecessor_index(func, successor, block);+ for phi in func.phis(successor) {+ counts[func.inputs(phi)[index] as usize] += 1;+ }+ }+ }+ // Entry values outside block 0's range (cleanup's constants) were skipped above; they need no location.+ let mut total = 0;+ for value in 0..=count {+ let uses = self.starts[value];+ self.starts[value] = total;+ total += uses;+ }+ self.positions.clear();+ self.positions.resize(total as usize, 0);+ self.cursor.clear();+ self.cursor.extend_from_slice(&self.starts[..count]);++ // The uses, in order, and the ends of the intervals.+ for block in 0..func.blocks.len() as BlockId {+ let data = &func.blocks[block as usize];+ for value in data.start..data.end {+ let node = func.node(value);+ if liveliness.is_dead(value) || matches!(node.op, Op::Phi | Op::Forward) || node.op.is_entry_value() {+ continue;+ }+ let position = node_position(value);+ for &input in func.inputs(value) {+ self.add_use(func, input, position, block);+ }+ match node.op {+ Op::Call | Op::TailCall => self.hint_call_arguments(func, value),+ Op::Return => self.hint_results(func, value),+ _ => {}+ }+ }+ let position = edge_position(func, block);+ for &successor in func.successors(block) {+ let index = predecessor_index(func, successor, block);+ for phi in func.phis(successor) {+ let input = func.inputs(phi)[index];+ self.add_use(func, input, position, block);+ }+ }+ }+ }++ fn add_use(&mut self, func: &Func, value: Value, position: u32, block: BlockId) {+ let slot = &mut self.cursor[value as usize];+ self.positions[*slot as usize] = position;+ *slot += 1;+ let mut end = position;+ let definition_block = self.block[value as usize];+ let use_loop = func.blocks[block as usize].loop_index;+ if use_loop != NONE && use_loop != func.blocks[definition_block as usize].loop_index {+ // The outermost loop around the use that does not contain the definition keeps the value live.+ let mut loop_index = use_loop;+ while loop_index != NONE {+ let loop_ = &func.loops[loop_index as usize];+ if loop_.header <= definition_block && definition_block <= loop_.last {+ break;+ }+ end = end.max(self.loop_ends[loop_index as usize]);+ loop_index = loop_.parent;+ }+ }+ let current = &mut self.end[value as usize];+ *current = (*current).max(end);+ }++ fn hint_call_arguments(&mut self, func: &Func, call: Value) {+ let inputs = func.inputs(call);+ let callee = &inputs[3..];+ self.places.clear();+ let (mut gprs, mut fprs) = (0, 0);+ for &argument in callee {+ let register = if func.node(argument).ty.uses_xmm() {+ fprs += 1;+ convention::FPR_ARGUMENTS.get(fprs - 1)+ } else {+ gprs += 1;+ convention::GPR_ARGUMENTS.get(gprs - 1)+ };+ if let Some(®ister) = register+ && self.hint[argument as usize] == NO_HINT+ {+ self.hint[argument as usize] = register;+ }+ }+ }++ fn hint_results(&mut self, func: &Func, ret: Value) {+ let (mut gprs, mut fprs) = (0, 0);+ for &result in func.inputs(ret) {+ let register: Option<&Register> = if func.node(result).ty.uses_xmm() {+ fprs += 1;+ convention::FPR_RESULTS.get(fprs - 1)+ } else {+ gprs += 1;+ convention::GPR_RESULTS.get(gprs - 1)+ };+ if let Some(®ister) = register+ && self.hint[result as usize] == NO_HINT+ {+ self.hint[result as usize] = register;+ }+ }+ }+}++/// The index of `predecessor` among the predecessors of `block`, which is the index of its phis' inputs from it.+pub fn predecessor_index(func: &Func, block: BlockId, predecessor: BlockId) -> usize {+ func.predecessors(block)+ .iter()+ .position(|candidate| *candidate == predecessor)+ .expect("successors list their predecessors")+}diff --git a/Libraries/LibWasm/JIT/src/regalloc/mod.rs b/Libraries/LibWasm/JIT/src/regalloc/mod.rsnew file mode 100644index 00000000000..4b9c4c9b768--- /dev/null+++ b/Libraries/LibWasm/JIT/src/regalloc/mod.rs@@ -0,0 +1,1129 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The register allocator: one forward walk over the blocks in linear order, the approach of libjs_jit's+//! allocator on the WebAssembly IR.+//!+//! - Values get registers where their node is allocated, as the node's constraints say (`constraints()`). When no+//! register is free, the value needed furthest in the future is evicted. Inside a loop, the values the rest of+//! the iteration uses come first, then those the next iteration reads, then those only used after the loop.+//! - Spilling happens at the definition: a value that ever needs a stack slot gets one for its whole life, and code+//! generation stores it there right after defining it, so a slot always holds its value once it has one. Values+//! live across a call get one, since calls clobber every register.+//! - A block with one predecessor starts with that predecessor's registers. A merge starts with those of its last+//! predecessor, and a loop header with those of the block entering the loop, without the values the loop only+//! carries through that have a slot already. Their phis get registers that are free there, preferably those of+//! the inputs from that predecessor. Every other edge into them moves its values into place, as parallel moves.+//! Edges from blocks with several successors that need moves get a stub of their own in code generation.++pub mod liveness;+pub mod verify;++use crate::convention::{self, Place, Register};+use crate::ir::{BlockId, Func, NONE, Op, Type, Value};+use crate::passes::cleanup::Liveliness;+use liveness::{Liveness, NO_HINT, block_start_position, node_position, predecessor_index};++/// No register.+pub const NO_REGISTER: u8 = u8::MAX;+/// An input that code generation uses as an immediate.+pub const CONSTANT_INPUT: u8 = u8::MAX - 1;++/// No spill slot.+pub const NO_SLOT: i32 = i32::MIN;++const REGISTER_COUNT: usize = 32;++/// Where a value is, or where a move reads or writes.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum Location {+ Register(Register),+ /// A frame slot, by its offset from fp.+ Slot(i32),+ /// The outgoing area of a call: [rsp + 8 * index].+ Outgoing(u32),+ /// The result area of the function: [result area pointer + 8 * index].+ ResultArea(u32),+ /// A constant node, materialized where it is moved to. Only a source.+ Constant(Value),+}++/// A copy of a value. Moves between memory locations go through the scratch registers.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Move {+ pub from: Location,+ pub to: Location,+ /// Whether the value is a v128, which takes 16 bytes in memory.+ pub vector: bool,+}++/// How the allocator placed one node.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct NodeAllocation {+ /// The registers of the first three inputs, or CONSTANT_INPUT for immediates. Variadic nodes but stores get+ /// theirs moved into place instead.+ pub inputs: [u8; 3],+ pub output: u8,+ pub temps: [u8; 2],+ /// The moves before the node: `Allocation::moves[start..start + count]`.+ pub moves_start: u32,+ pub moves_count: u32,+}++impl Default for NodeAllocation {+ fn default() -> Self {+ Self {+ inputs: [NO_REGISTER; 3],+ output: NO_REGISTER,+ temps: [NO_REGISTER; 2],+ moves_start: 0,+ moves_count: 0,+ }+ }+}++#[derive(Default)]+pub struct Allocation {+ pub nodes: Vec<NodeAllocation>,+ pub moves: Vec<Move>,+ /// The moves of each edge, by its slot in `Func::successors`: (start, count) in `moves`.+ pub edge_moves: Vec<(u32, u32)>,+ /// The spill slot of each value, as an fp offset, or NO_SLOT.+ pub slots: Vec<i32>,+ pub slot_count: u32,+ /// The bytes of the outgoing area.+ pub outgoing_size: u32,+ /// The registers each block starts with, for the verifier: `block_states[block]`.+ pub block_states: Vec<[u32; REGISTER_COUNT]>,+ /// A slot for breaking cycles of edge moves.+ pub cycle_slot: i32,+}++impl Allocation {+ pub fn node(&self, value: Value) -> &NodeAllocation {+ &self.nodes[value as usize]+ }++ pub fn node_moves(&self, value: Value) -> &[Move] {+ let node = &self.nodes[value as usize];+ &self.moves[node.moves_start as usize..(node.moves_start + node.moves_count) as usize]+ }++ pub fn edge(&self, slot: u32) -> &[Move] {+ let (start, count) = self.edge_moves[slot as usize];+ &self.moves[start as usize..(start + count) as usize]+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Input {+ Register,+ Fixed(Register),+ /// A register, or the constant itself if it fits the instruction as an immediate.+ RegisterOrConstant,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Output {+ None,+ Register,+ Fixed(Register),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Temp {+ None,+ Gpr,+ Fpr,+ Fixed(Register),+}++struct Constraints {+ inputs: [Input; 3],+ output: Output,+ temps: [Temp; 2],+ /// The registers the node overwrites once it has read its inputs.+ clobbers: u32,+ /// Whether the output may take the first input's register where that input dies, as two-address instructions+ /// want.+ reuse_first: bool,+}++/// Whether constant `value` fits an instruction as an immediate: sign-extended 32 bits for 64-bit operations.+pub fn fits_immediate(func: &Func, value: Value) -> bool {+ let node = func.node(value);+ match node.constant() {+ Some(bits) if node.ty.is_64() => i32::try_from(bits as i64).is_ok(),+ Some(_) => true,+ None => false,+ }+}++/// Whether a constant index and offset of a memory access fit its displacement.+pub fn fits_displacement(func: &Func, index: Value, offset: u32) -> bool {+ func.node(index)+ .constant()+ .is_some_and(|bits| (bits & 0xffff_ffff) + u64::from(offset) <= i32::MAX as u64)+}++fn constraints(func: &Func, value: Value) -> Constraints {+ use convention::{RAX, RCX, RDX};+ let node = func.node(value);+ let output = if node.ty == Type::None {+ Output::None+ } else {+ Output::Register+ };+ let mut constraints = Constraints {+ inputs: [Input::Register; 3],+ output,+ temps: [Temp::None; 2],+ clobbers: 0,+ reuse_first: false,+ };+ let input_type = |index: usize| func.node(func.inputs(value)[index]).ty;+ match node.op {+ Op::Add | Op::Sub | Op::And | Op::Or | Op::Xor | Op::Mul => {+ constraints.inputs[1] = Input::RegisterOrConstant;+ constraints.reuse_first = true;+ }+ Op::Shl | Op::ShrS | Op::ShrU => constraints.inputs[1] = Input::RegisterOrConstant,+ Op::Rotl | Op::Rotr => {+ if func.node(node.args[1]).op.is_constant() {+ constraints.inputs[1] = Input::RegisterOrConstant;+ } else {+ constraints.inputs[1] = Input::Fixed(RCX);+ constraints.reuse_first = true;+ }+ }+ Op::DivS | Op::DivU | Op::RemS | Op::RemU => {+ // NB: The divisor may not be in rdx, which the dividend's extension writes first.+ constraints.inputs[0] = Input::Fixed(RAX);+ constraints.temps[0] = Temp::Fixed(RDX);+ constraints.clobbers = (1 << RAX) | (1 << RDX);+ let quotient = matches!(node.op, Op::DivS | Op::DivU);+ constraints.output = Output::Fixed(if quotient { RAX } else { RDX });+ }+ Op::Compare | Op::BranchCompare => constraints.inputs[1] = Input::RegisterOrConstant,+ Op::FloatCompare => {+ if matches!(+ crate::ir::FloatCondition::from_flags(node.flags),+ crate::ir::FloatCondition::Eq | crate::ir::FloatCondition::Ne+ ) {+ constraints.temps[0] = Temp::Gpr;+ }+ }+ Op::FCopysign => constraints.temps[0] = Temp::Fpr,+ Op::Select => {+ if !node.ty.uses_xmm() {+ constraints.reuse_first = false;+ }+ }+ Op::TruncS | Op::TruncU | Op::TruncSatS | Op::TruncSatU => {+ constraints.temps[0] = Temp::Fpr;+ }+ Op::ConvertU if input_type(0) == Type::I64 => {+ constraints.temps[0] = Temp::Gpr;+ }+ Op::Load => {+ if fits_displacement(func, node.args[1], node.args[2]) {+ constraints.inputs[1] = Input::RegisterOrConstant;+ }+ }+ Op::Store => {+ let inputs = func.inputs(value);+ if fits_displacement(func, inputs[1], node.args[2]) {+ constraints.inputs[1] = Input::RegisterOrConstant;+ }+ constraints.inputs[2] = Input::RegisterOrConstant;+ }+ 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+ 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;+ }+ _ => {}+ }+ constraints+}++/// The register class of values of a type: true for xmm registers.+fn is_float(ty: Type) -> bool {+ ty.uses_xmm()+}++/// The reusable state of the allocator.+#[derive(Default)]+pub struct Allocator {+ pub liveness: Liveness,+ /// The time stamp counter ticks the last liveness computation took.+ pub liveness_ticks: u64,+ dominators: crate::passes::dominators::Dominators,+ contents: [u32; REGISTER_COUNT],+ value_registers: Vec<u8>,+ end_states: Vec<[u32; REGISTER_COUNT]>,+ /// The registers each loop's header starts with, for its back edges.+ header_states: Vec<[u32; REGISTER_COUNT]>,+ position: u32,+ current_block: BlockId,+ pending: Vec<Move>,+ resolved: Vec<Move>,+ places: Vec<Place>,+ types: Vec<Type>,+ /// The inputs of the node being allocated, whose registers only it may take.+ inputs: Vec<Value>,+ /// The registers values may get of each class, in order of preference.+ gprs: &'static [Register],+ fprs: &'static [Register],+}++/// With `stress-registers`, the registers values get besides those of fixed constraints: few enough that most+/// values spill.+const STRESS_GPRS: [Register; 3] = [convention::RAX, convention::RBX, convention::R12];+const STRESS_FPRS: [Register; 2] = [convention::xmm(8), convention::xmm(9)];++impl Allocator {+ /// Allocates registers for `func` into `allocation`.+ /// Allocates registers for `func` into `allocation`, with only a few registers if `stress`.+ pub fn allocate_with(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation, stress: bool) {+ if stress {+ self.gprs = &STRESS_GPRS;+ self.fprs = &STRESS_FPRS;+ }+ self.allocate(func, liveliness, allocation);+ self.gprs = &convention::ALLOCATABLE_GPRS;+ self.fprs = &convention::ALLOCATABLE_FPRS;+ }++ pub fn allocate(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation) {+ if self.gprs.is_empty() {+ self.gprs = &convention::ALLOCATABLE_GPRS;+ self.fprs = &convention::ALLOCATABLE_FPRS;+ }+ let start = crate::ticks();+ self.liveness.compute(func, liveliness);+ self.liveness_ticks = crate::ticks() - start;+ self.dominators.compute(func);+ let count = func.nodes.len();+ allocation.nodes.clear();+ allocation.nodes.resize(count, NodeAllocation::default());+ allocation.moves.clear();+ allocation.edge_moves.clear();+ allocation.edge_moves.resize(func.successors.len(), (0, 0));+ allocation.slots.clear();+ allocation.slots.resize(count, NO_SLOT);+ allocation.slot_count = 0;+ allocation.outgoing_size = 0;+ allocation.block_states.clear();+ allocation+ .block_states+ .resize(func.blocks.len(), [NONE; REGISTER_COUNT]);+ allocation.cycle_slot = NO_SLOT;+ self.value_registers.clear();+ self.value_registers.resize(count, NO_REGISTER);+ self.contents = [NONE; REGISTER_COUNT];+ self.end_states.clear();+ self.end_states.resize(func.blocks.len(), [NONE; REGISTER_COUNT]);+ self.header_states.clear();+ self.header_states.resize(func.loops.len(), [NONE; REGISTER_COUNT]);++ for block in 0..func.blocks.len() as BlockId {+ self.current_block = block;+ self.start_block(func, liveliness, allocation, block);+ allocation.block_states[block as usize] = self.contents;+ let data = func.blocks[block as usize];+ for value in data.start..data.end {+ let op = func.node(value).op;+ if liveliness.is_dead(value) || matches!(op, Op::Phi | Op::Forward) || op.is_entry_value() {+ continue;+ }+ self.allocate_node(func, liveliness, allocation, value);+ }+ self.end_states[block as usize] = self.contents;+ let successors_start = data.successors_start;+ for (index, &successor) in func.successors(block).iter().enumerate() {+ if successor <= block {+ let loop_index = func.blocks[successor as usize].loop_index;+ let state = self.header_states[loop_index as usize];+ self.edge_moves(+ func,+ allocation,+ block,+ successor,+ successors_start + index as u32,+ &state,+ );+ }+ }+ }+ }++ // Register state.++ fn set_contents(&mut self, contents: [u32; REGISTER_COUNT]) {+ for value in self.contents {+ if value != NONE {+ self.value_registers[value as usize] = NO_REGISTER;+ }+ }+ self.contents = contents;+ for (register, value) in contents.iter().enumerate() {+ if *value != NONE {+ self.value_registers[*value as usize] = register as u8;+ }+ }+ }++ fn assign(&mut self, register: Register, value: Value) {+ debug_assert_eq!(self.contents[register as usize], NONE);+ self.contents[register as usize] = value;+ self.value_registers[value as usize] = register;+ }++ fn free(&mut self, register: Register) {+ let value = self.contents[register as usize];+ if value != NONE {+ self.value_registers[value as usize] = NO_REGISTER;+ self.contents[register as usize] = NONE;+ }+ }++ fn ensure_slot(func: &Func, allocation: &mut Allocation, value: Value) -> i32 {+ let slot = allocation.slots[value as usize];+ if slot != NO_SLOT {+ return slot;+ }+ let node = func.node(value);+ let slot = match node.op {+ Op::Param => convention::home_slot_offset(convention::home_slot(&func.params, node.args[0] as usize)),+ Op::Instance => convention::FRAME_INSTANCE,+ _ => {+ // NB: A v128 takes two slots, the lower of which has its address.+ allocation.slot_count += node.ty.slots();+ convention::spill_slot_offset(allocation.slot_count - 1)+ }+ };+ allocation.slots[value as usize] = slot;+ slot+ }++ /// Frees `register`, keeping its value in its slot if it is still needed.+ fn evict(&mut self, func: &Func, allocation: &mut Allocation, register: Register) {+ let value = self.contents[register as usize];+ if value == NONE {+ return;+ }+ if self.liveness.is_live_after(value, self.position) {+ Self::ensure_slot(func, allocation, value);+ }+ self.free(register);+ }++ fn location(&self, func: &Func, allocation: &Allocation, value: Value) -> Location {+ if func.node(value).op.is_constant() {+ return Location::Constant(value);+ }+ let register = self.value_registers[value as usize];+ if register != NO_REGISTER {+ return Location::Register(register);+ }+ let slot = allocation.slots[value as usize];+ debug_assert!(slot != NO_SLOT, "v{value} is neither in a register nor in a slot");+ Location::Slot(slot)+ }++ /// How soon `value` is needed again, as a key that orders the values by it (smaller is sooner).+ fn eviction_key(&self, func: &Func, value: Value) -> (u8, u32) {+ let next = self.liveness.next_use(value, self.position);+ let loop_index = func.blocks[self.current_block as usize].loop_index;+ if loop_index == NONE {+ return next.map_or((3, 0), |position| (0, position));+ }+ let loop_end = self.liveness.loop_ends[loop_index as usize];+ if let Some(position) = next+ && position <= loop_end+ {+ return (0, position);+ }+ let loop_start = block_start_position(func, func.loops[loop_index as usize].header);+ if self.liveness.definition[value as usize] < loop_start+ && let Some(position) = self.liveness.next_use(value, loop_start.saturating_sub(1))+ && position <= self.position+ {+ return (1, position - loop_start);+ }+ next.map_or((3, 0), |position| (2, position))+ }++ /// A register of the class that is not `blocked`, preferably `hint`, freeing one if necessary.+ fn pick(&mut self, func: &Func, allocation: &mut Allocation, blocked: u32, float: bool, hint: u8) -> Register {+ let candidates = if float { self.fprs } else { self.gprs };+ if hint != NO_HINT+ && hint != NO_REGISTER+ && convention::is_fpr(hint) == float+ && blocked & (1 << hint) == 0+ && self.contents[hint as usize] == NONE+ {+ return hint;+ }+ for ®ister in candidates {+ if blocked & (1 << register) == 0 && self.contents[register as usize] == NONE {+ return register;+ }+ }+ let mut victim = NO_REGISTER;+ let mut best = (0, 0);+ // NB: Under stress-registers, a node may need more registers than the few values get; then it takes others.+ let full: &[Register] = if float {+ &convention::ALLOCATABLE_FPRS+ } else {+ &convention::ALLOCATABLE_GPRS+ };+ for candidates in [candidates, full] {+ for ®ister in candidates {+ if blocked & (1 << register) != 0 || self.inputs.contains(&self.contents[register as usize]) {+ continue;+ }+ if self.contents[register as usize] == NONE {+ return register;+ }+ let key = self.eviction_key(func, self.contents[register as usize]);+ if victim == NO_REGISTER || key > best {+ victim = register;+ best = key;+ }+ }+ if victim != NO_REGISTER {+ break;+ }+ }+ assert!(victim != NO_REGISTER, "a node needs more registers than there are");+ self.evict(func, allocation, victim);+ victim+ }++ // Blocks.++ /// The registers of `state` that hold values live at the start of `block`. For merges, also only those whose+ /// definition dominates it: an interval can span a merge that some paths reach without its definition, where+ /// the value is dead, like a block the definition branches over.+ fn filtered(&self, func: &Func, state: &[u32; REGISTER_COUNT], block: BlockId) -> [u32; REGISTER_COUNT] {+ let position = block_start_position(func, block);+ let is_merge = func.predecessors(block).len() > 1;+ let mut result = *state;+ for value in &mut result {+ if *value != NONE+ && (!self.liveness.is_live_at(*value, position)+ || (is_merge && !self.dominators.dominates(self.liveness.block[*value as usize], block)))+ {+ *value = NONE;+ }+ }+ result+ }++ fn start_block(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation, block: BlockId) {+ self.position = block_start_position(func, block);+ if block == 0 {+ self.start_entry(func, liveliness, allocation);+ return;+ }+ let predecessors = func.predecessors(block);+ if func.is_loop_header(block) {+ let entry = predecessors[0];+ debug_assert!(entry < block);+ let mut state = self.filtered(func, &self.end_states[entry as usize], block);+ // The values the loop only carries through stay in their slots, if they have one, so that the loop can+ // use their registers.+ let loop_index = func.blocks[block as usize].loop_index;+ let loop_end = self.liveness.loop_ends[loop_index as usize];+ for value in &mut state {+ if *value != NONE+ && allocation.slots[*value as usize] != NO_SLOT+ && self+ .liveness+ .next_use(*value, self.position)+ .is_none_or(|position| position > loop_end)+ {+ *value = NONE;+ }+ }+ self.place_phis(func, allocation, block, entry, &mut state);+ let slot = edge_slot(func, entry, block);+ self.edge_moves(func, allocation, entry, block, slot, &state);+ self.header_states[loop_index as usize] = state;+ self.set_contents(state);+ return;+ }+ if predecessors.len() == 1 {+ let state = self.filtered(func, &self.end_states[predecessors[0] as usize], block);+ self.set_contents(state);+ return;+ }+ let state_predecessor = *predecessors.iter().max().expect("merges have predecessors");+ let mut state = self.filtered(func, &self.end_states[state_predecessor as usize], block);+ self.place_phis(func, allocation, block, state_predecessor, &mut state);+ for index in 0..func.predecessors(block).len() {+ let predecessor = func.predecessors(block)[index];+ let slot = edge_slot(func, predecessor, block);+ self.edge_moves(func, allocation, predecessor, block, slot, &state);+ }+ let _ = liveliness;+ self.set_contents(state);+ }++ fn start_entry(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation) {+ let mut state = [NONE; REGISTER_COUNT];+ self.places.clear();+ convention::parameter_places(&func.params, &mut self.places);+ let data = func.blocks[0];+ for value in data.start..data.end {+ let node = func.node(value);+ if liveliness.is_dead(value) {+ continue;+ }+ match node.op {+ Op::Instance => state[convention::INSTANCE_REGISTER as usize] = value,+ Op::MemoryBase => state[convention::MEMORY_BASE_REGISTER as usize] = value,+ Op::Param => match self.places[node.args[0] as usize] {+ Place::Register(register) => state[register as usize] = value,+ Place::Memory(index) => allocation.slots[value as usize] = convention::home_slot_offset(index),+ },+ _ => {}+ }+ }+ for (register, value) in state.iter().enumerate() {+ if *value != NONE {+ allocation.nodes[*value as usize].output = register as u8;+ }+ }+ self.set_contents(state);+ }++ /// Gives the phis of `block` their locations in `state`, which starts as the registers at the end of+ /// `predecessor`.+ fn place_phis(+ &mut self,+ func: &Func,+ allocation: &mut Allocation,+ block: BlockId,+ predecessor: BlockId,+ state: &mut [u32; REGISTER_COUNT],+ ) {+ let index = predecessor_index(func, block, predecessor);+ let end = &self.end_states[predecessor as usize];+ for phi in func.phis(block) {+ let float = is_float(func.node(phi).ty);+ let input = func.inputs(phi)[index];+ let mut register = NO_REGISTER;+ if let Some(own) = end.iter().position(|value| *value == input)+ && state[own] == NONE+ && convention::is_fpr(own as u8) == float+ {+ register = own as u8;+ }+ if register == NO_REGISTER {+ let candidates = if float { self.fprs } else { self.gprs };+ let hint = self.liveness.hint[phi as usize];+ if hint != NO_HINT && convention::is_fpr(hint) == float && state[hint as usize] == NONE {+ register = hint;+ } else if let Some(&free) = candidates.iter().find(|register| state[**register as usize] == NONE) {+ register = free;+ }+ }+ if register == NO_REGISTER {+ Self::ensure_slot(func, allocation, phi);+ } else {+ state[register as usize] = phi;+ }+ allocation.nodes[phi as usize].output = register;+ }+ }++ /// The moves on the edge from `from` (allocated, its registers in `end_states`, or the current ones for the+ /// current block) to `to`, which starts with `target`.+ fn edge_moves(+ &mut self,+ func: &Func,+ allocation: &mut Allocation,+ from: BlockId,+ to: BlockId,+ slot: u32,+ target: &[u32; REGISTER_COUNT],+ ) {+ let source = self.end_states[from as usize];+ let index = predecessor_index(func, to, from);+ let location_at_end = |value: Value, allocation: &Allocation| -> Location {+ if func.node(value).op.is_constant() {+ return Location::Constant(value);+ }+ if let Some(register) = source.iter().position(|candidate| *candidate == value) {+ return Location::Register(register as u8);+ }+ let slot = allocation.slots[value as usize];+ debug_assert!(+ slot != NO_SLOT,+ "v{value} is live on the edge b{from} -> b{to} but nowhere"+ );+ Location::Slot(slot)+ };+ self.pending.clear();+ for (register, &value) in target.iter().enumerate() {+ if value == NONE {+ continue;+ }+ let node = func.node(value);+ let vector = node.ty == Type::V128;+ let from_location = if node.op == Op::Phi && self.liveness.block[value as usize] == to {+ location_at_end(func.inputs(value)[index], allocation)+ } else {+ location_at_end(value, allocation)+ };+ let to_location = Location::Register(register as u8);+ if from_location != to_location {+ self.pending.push(Move {+ from: from_location,+ to: to_location,+ vector,+ });+ }+ }+ for phi in func.phis(to) {+ if allocation.nodes[phi as usize].output != NO_REGISTER {+ continue;+ }+ let from_location = location_at_end(func.inputs(phi)[index], allocation);+ let to_location = Location::Slot(allocation.slots[phi as usize]);+ if from_location != to_location {+ self.pending.push(Move {+ from: from_location,+ to: to_location,+ vector: func.node(phi).ty == Type::V128,+ });+ }+ }+ if self.pending.is_empty() {+ allocation.edge_moves[slot as usize] = (allocation.moves.len() as u32, 0);+ return;+ }+ let start = allocation.moves.len() as u32;+ self.resolve(func, allocation);+ allocation.edge_moves[slot as usize] = (start, allocation.moves.len() as u32 - start);+ }++ /// Orders the parallel moves in `pending` into a sequence with the same effect, appended to the allocation's+ /// moves. Cycles go through the cycle slot.+ fn resolve(&mut self, func: &Func, allocation: &mut Allocation) {+ let _ = func;+ self.resolved.clear();+ while !self.pending.is_empty() {+ let ready = self+ .pending+ .iter()+ .position(|candidate| self.pending.iter().all(|other| other.from != candidate.to));+ if let Some(index) = ready {+ let ready = self.pending.swap_remove(index);+ self.resolved.push(ready);+ continue;+ }+ // Every destination is still a source: the moves form cycles. Save one destination in the cycle slot.+ if allocation.cycle_slot == NO_SLOT {+ // NB: Two slots, in case the value is a v128.+ allocation.slot_count += 2;+ allocation.cycle_slot = convention::spill_slot_offset(allocation.slot_count - 1);+ }+ let saved = self.pending[0].to;+ let temp = Location::Slot(allocation.cycle_slot);+ let vector = self.pending[0].vector;+ self.resolved.push(Move {+ from: saved,+ to: temp,+ vector,+ });+ for pending in &mut self.pending {+ if pending.from == saved {+ pending.from = temp;+ }+ }+ }+ allocation.moves.extend_from_slice(&self.resolved);+ }++ // Nodes.++ fn allocate_node(&mut self, func: &Func, liveliness: &Liveliness, allocation: &mut Allocation, value: Value) {+ self.position = node_position(value);+ let node = *func.node(value);+ let moves_start = allocation.moves.len() as u32;+ self.inputs.clear();+ self.inputs.extend_from_slice(func.inputs(value));+ match node.op {+ Op::Call => self.allocate_call(func, allocation, value),+ Op::TailCall => self.place_call_operands(func, allocation, value),+ Op::Helper => self.allocate_helper(func, allocation, value),+ Op::Return => self.allocate_return(func, allocation, value),+ Op::CallResult => self.allocate_call_result(func, allocation, value),+ _ => self.allocate_simple(func, allocation, value),+ }+ let _ = liveliness;+ let record = &mut allocation.nodes[value as usize];+ record.moves_start = moves_start;+ record.moves_count = allocation.moves.len() as u32 - moves_start;+ }++ fn move_to(&mut self, allocation: &mut Allocation, from: Location, to: Location, vector: bool) {+ allocation.moves.push(Move { from, to, vector });+ }++ /// Frees `register` for the node being allocated. An input of the node in it moves to another register, or to+ /// its slot if none is free.+ fn make_room(&mut self, func: &Func, allocation: &mut Allocation, register: Register, blocked: u32) {+ let occupant = self.contents[register as usize];+ if occupant == NONE {+ return;+ }+ if !self.inputs.contains(&occupant) {+ self.evict(func, allocation, register);+ return;+ }+ let float = convention::is_fpr(register);+ let candidates = if float { self.fprs } else { self.gprs };+ let free = candidates.iter().copied().find(|candidate| {+ *candidate != register && blocked & (1 << candidate) == 0 && self.contents[*candidate as usize] == NONE+ });+ match free {+ Some(free) => {+ let vector = func.node(occupant).ty == Type::V128;+ self.move_to(+ allocation,+ Location::Register(register),+ Location::Register(free),+ vector,+ );+ self.free(register);+ self.assign(free, occupant);+ }+ None => {+ Self::ensure_slot(func, allocation, occupant);+ self.free(register);+ }+ }+ }++ /// Puts `input` in the fixed register `register` for a node, with the registers in `blocked` taken.+ fn fix_input(&mut self, func: &Func, allocation: &mut Allocation, input: Value, register: Register, blocked: u32) {+ if !func.node(input).op.is_constant() && self.value_registers[input as usize] == register {+ return;+ }+ self.make_room(func, allocation, register, blocked | (1 << register));+ let from = self.location(func, allocation, input);+ let vector = func.node(input).ty == Type::V128;+ self.move_to(allocation, from, Location::Register(register), vector);+ match from {+ Location::Register(previous) if blocked & (1 << previous) == 0 => {+ self.free(previous);+ self.assign(register, input);+ }+ Location::Slot(_) => self.assign(register, input),+ _ => {}+ }+ }++ /// Puts `input` in some register for a node, with the registers in `blocked` taken.+ fn register_input(&mut self, func: &Func, allocation: &mut Allocation, input: Value, blocked: u32) -> Register {+ let float = is_float(func.node(input).ty);+ if !func.node(input).op.is_constant() {+ let register = self.value_registers[input as usize];+ if register != NO_REGISTER {+ return register;+ }+ }+ let register = self.pick(func, allocation, blocked, float, NO_HINT);+ let from = self.location(func, allocation, input);+ let vector = func.node(input).ty == Type::V128;+ self.move_to(allocation, from, Location::Register(register), vector);+ if !func.node(input).op.is_constant() {+ self.assign(register, input);+ }+ register+ }++ fn free_dying_inputs(&mut self, func: &Func, value: Value) {+ for &input in func.inputs(value) {+ if func.node(input).op.is_constant() {+ continue;+ }+ let register = self.value_registers[input as usize];+ if register != NO_REGISTER && !self.liveness.is_live_after(input, self.position) {+ self.free(register);+ }+ }+ }++ fn define(&mut self, func: &Func, allocation: &mut Allocation, value: Value, register: Register) {+ self.assign(register, value);+ allocation.nodes[value as usize].output = register;+ if self.liveness.end[value as usize] <= self.position {+ self.free(register);+ }+ let _ = func;+ }++ fn allocate_simple(&mut self, func: &Func, allocation: &mut Allocation, value: Value) {+ let constraints = constraints(func, value);+ let node = *func.node(value);+ let inputs = func.inputs(value);+ let mut blocked = 0u32;+ let mut registers = [NO_REGISTER; 3];+ // Fixed temps first, then fixed inputs, so that other inputs do not take their registers.+ for temp in constraints.temps {+ if let Temp::Fixed(register) = temp {+ self.make_room(func, allocation, register, blocked | (1 << register));+ blocked |= 1 << register;+ }+ }+ for (index, &input) in inputs.iter().enumerate().take(3) {+ if let Input::Fixed(register) = constraints.inputs[index] {+ self.fix_input(func, allocation, input, register, blocked);+ blocked |= 1 << register;+ registers[index] = register;+ }+ }+ for (index, &input) in inputs.iter().enumerate().take(3) {+ match constraints.inputs[index] {+ Input::Fixed(_) => continue,+ Input::RegisterOrConstant if func.node(input).op.is_constant() && fits_immediate(func, input) => {+ registers[index] = CONSTANT_INPUT;+ }+ _ => {+ let register = self.register_input(func, allocation, input, blocked);+ blocked |= 1 << register;+ registers[index] = register;+ }+ }+ }+ for register in 0..REGISTER_COUNT as Register {+ if constraints.clobbers & (1 << register) != 0 {+ self.evict(func, allocation, register);+ }+ }+ let mut temps = [NO_REGISTER; 2];+ for (index, temp) in constraints.temps.iter().enumerate() {+ temps[index] = match temp {+ Temp::None => NO_REGISTER,+ Temp::Fixed(register) => *register,+ Temp::Gpr | Temp::Fpr => {+ let register = self.pick(func, allocation, blocked, *temp == Temp::Fpr, NO_HINT);+ blocked |= 1 << register;+ register+ }+ };+ }+ let output = match constraints.output {+ Output::None => NO_REGISTER,+ Output::Fixed(register) => {+ self.evict(func, allocation, register);+ register+ }+ Output::Register => {+ let first = inputs.first().copied().unwrap_or(NONE);+ let float = is_float(node.ty);+ if constraints.reuse_first+ && registers[0] != CONSTANT_INPUT+ && registers[0] != NO_REGISTER+ && !func.node(first).op.is_constant()+ && !self.liveness.is_live_after(first, self.position)+ && convention::is_fpr(registers[0]) == float+ && !inputs[1..].contains(&first)+ {+ registers[0]+ } else {+ self.pick(func, allocation, blocked, float, self.liveness.hint[value as usize])+ }+ }+ };+ self.free_dying_inputs(func, value);+ if output != NO_REGISTER {+ if self.contents[output as usize] != NONE {+ // The first input, which dies here.+ self.free(output);+ }+ self.define(func, allocation, value, output);+ }+ let record = &mut allocation.nodes[value as usize];+ record.inputs = registers;+ record.temps = temps;+ }++ fn allocate_call(&mut self, func: &Func, allocation: &mut Allocation, value: Value) {+ self.place_call_operands(func, allocation, value);+ // The call clobbers every register.+ for register in 0..REGISTER_COUNT as Register {+ if self.contents[register as usize] != NONE {+ self.evict(func, allocation, register);+ }+ }+ let node = func.node(value);+ if node.ty != Type::None {+ let register = if node.ty.uses_xmm() {+ convention::FPR_RESULTS[0]+ } else {+ convention::GPR_RESULTS[0]+ };+ self.define(func, allocation, value, register);+ }+ }++ fn allocate_helper(&mut self, func: &Func, allocation: &mut Allocation, value: Value) {+ let mut blocked = 0u32;+ for (index, &input) in func.inputs(value).iter().enumerate() {+ let register = convention::HELPER_REGISTERS[index];+ self.fix_input(func, allocation, input, register, blocked);+ blocked |= 1 << register;+ }+ for register in 0..REGISTER_COUNT as Register {+ if convention::HOST_CLOBBERS & (1 << register) != 0 && self.contents[register as usize] != NONE {+ self.evict(func, allocation, register);+ }+ }+ if func.node(value).ty != Type::None {+ self.define(func, allocation, value, convention::RAX);+ }+ }++ /// Moves the operands of a call or tail call where the convention wants them.+ fn place_call_operands(&mut self, func: &Func, allocation: &mut Allocation, value: Value) {+ let inputs = func.inputs(value);+ let (header, instance, memory_base) = (inputs[0], inputs[1], inputs[2]);+ let arguments = &inputs[3..];+ self.types.clear();+ self.types+ .extend(arguments.iter().map(|argument| func.node(*argument).ty));+ self.places.clear();+ convention::parameter_places(&self.types, &mut self.places);+ // Arguments passed in memory first: they only read the registers.+ for (index, &argument) in arguments.iter().enumerate() {+ if let Place::Memory(slot) = self.places[index] {+ let from = self.location(func, allocation, argument);+ let vector = func.node(argument).ty == Type::V128;+ self.move_to(allocation, from, Location::Outgoing(slot), vector);+ }+ }+ let mut blocked = 0u32;+ for (index, &argument) in arguments.iter().enumerate() {+ if let Place::Register(register) = self.places[index] {+ self.fix_input(func, allocation, argument, register, blocked);+ blocked |= 1 << register;+ }+ }+ for (input, register) in [+ (header, convention::CALLEE_REGISTER),+ (instance, convention::INSTANCE_REGISTER),+ (memory_base, convention::MEMORY_BASE_REGISTER),+ ] {+ self.fix_input(func, allocation, input, register, blocked);+ blocked |= 1 << register;+ }+ let mut parameters = std::mem::take(&mut self.types);+ parameters.clear();+ parameters.extend(arguments.iter().map(|argument| func.node(*argument).ty));+ let call_results = call_result_types(func, value);+ // NB: A tail call passes on the function's result area.+ let results: &[Type] = if func.node(value).op == Op::TailCall {+ &func.results+ } else {+ &call_results+ };+ allocation.outgoing_size = allocation+ .outgoing_size+ .max(convention::outgoing_size(¶meters, results));+ self.types = parameters;+ }++ fn allocate_call_result(&mut self, func: &Func, allocation: &mut Allocation, value: Value) {+ let node = func.node(value);+ let call = node.args[0];+ let index = node.args[1] as usize;+ let results = call_result_types(func, call);+ self.places.clear();+ convention::result_places(&results, &mut self.places);+ let register = match self.places[index] {+ Place::Register(register) => {+ self.evict(func, allocation, register);+ register+ }+ Place::Memory(_) => self.pick(+ func,+ allocation,+ 0,+ node.ty.uses_xmm(),+ self.liveness.hint[value as usize],+ ),+ };+ self.define(func, allocation, value, register);+ }++ fn allocate_return(&mut self, func: &Func, allocation: &mut Allocation, value: Value) {+ let inputs = func.inputs(value);+ self.places.clear();+ convention::result_places(&func.results, &mut self.places);+ for (index, &result) in inputs.iter().enumerate() {+ if let Place::Memory(slot) = self.places[index] {+ let from = self.location(func, allocation, result);+ let vector = func.node(result).ty == Type::V128;+ self.move_to(allocation, from, Location::ResultArea(slot), vector);+ }+ }+ let mut blocked = 0u32;+ for (index, &result) in inputs.iter().enumerate() {+ if let Place::Register(register) = self.places[index] {+ self.fix_input(func, allocation, result, register, blocked);+ blocked |= 1 << register;+ }+ }+ self.free_dying_inputs(func, value);+ }+}++/// The result types of a call, from its node and the `CallResult`s right after it, which cleanup keeps.+pub fn call_result_types(func: &Func, call: Value) -> crate::inline_vec::InlineVec<Type, 4> {+ let mut types = crate::inline_vec::InlineVec::new();+ let node = func.node(call);+ if node.ty != Type::None {+ types.push(node.ty);+ let mut next = call + 1;+ while (next as usize) < func.nodes.len()+ && func.node(next).op == Op::CallResult+ && func.node(next).args[0] == call+ {+ types.push(func.node(next).ty);+ next += 1;+ }+ }+ types+}++/// The slot in `Func::successors` of the edge from `from` to `to`.+pub fn edge_slot(func: &Func, from: BlockId, to: BlockId) -> u32 {+ let data = &func.blocks[from as usize];+ let index = func+ .successors(from)+ .iter()+ .position(|successor| *successor == to)+ .expect("predecessors list their successors");+ data.successors_start + index as u32+}diff --git a/Libraries/LibWasm/JIT/src/regalloc/verify.rs b/Libraries/LibWasm/JIT/src/regalloc/verify.rsnew file mode 100644index 00000000000..a6f7b78fd4e--- /dev/null+++ b/Libraries/LibWasm/JIT/src/regalloc/verify.rs@@ -0,0 +1,296 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The register allocation verifier. It simulates what every register holds through each block, from the state the+//! allocator says the block starts with, and checks that every input is where the allocation says, and that every+//! edge's moves turn the state at the end of its source into the state its target starts with (with phis replaced+//! by their inputs). Slots belong to one value each and are written where it is defined, so reading a value from+//! its own slot is always right.++use super::{Allocation, CONSTANT_INPUT, Location, NO_REGISTER, REGISTER_COUNT, call_result_types};+use crate::convention::{self, Place};+use crate::ir::{BlockId, Func, NONE, Op, Shape, Value};+use crate::passes::cleanup::Liveliness;+use crate::regalloc::liveness::predecessor_index;+use std::collections::HashMap;++struct Simulation<'a> {+ allocation: &'a Allocation,+ registers: [u32; REGISTER_COUNT],+ /// What moves wrote to slots other than the values' own: phi slots and the cycle slot.+ slots: HashMap<i32, Value>,+ /// The value each slot belongs to.+ owners: HashMap<i32, Value>,+ errors: Vec<String>,+}++impl Simulation<'_> {+ fn error(&mut self, message: String) {+ if self.errors.len() < 20 {+ self.errors.push(message);+ }+ }++ /// The value `location` holds, as far as the simulation knows.+ fn read(&self, location: Location) -> Option<Value> {+ match location {+ Location::Register(register) => Some(self.registers[register as usize]).filter(|value| *value != NONE),+ Location::Slot(slot) => self.slots.get(&slot).or_else(|| self.owners.get(&slot)).copied(),+ Location::Constant(value) => Some(value),+ Location::Outgoing(_) | Location::ResultArea(_) => None,+ }+ }++ fn apply(&mut self, moves: &[super::Move]) {+ for item in moves {+ let value = self.read(item.from).unwrap_or(NONE);+ match item.to {+ Location::Register(register) => self.registers[register as usize] = value,+ Location::Slot(slot) => {+ self.slots.insert(slot, value);+ }+ _ => {}+ }+ }+ }++ fn check_holds(&mut self, location: Location, value: Value, what: &str) {+ let ok = match location {+ Location::Register(register) => self.registers[register as usize] == value,+ Location::Slot(slot) => {+ self.slots.get(&slot) == Some(&value) || self.allocation.slots[value as usize] == slot+ }+ Location::Constant(constant) => constant == value,+ _ => true,+ };+ if !ok {+ self.error(format!("{what}: v{value} is not in {location:?}"));+ }+ }+}++pub fn verify(func: &Func, liveliness: &Liveliness, allocation: &Allocation) -> Result<(), String> {+ let mut simulation = Simulation {+ allocation,+ registers: [NONE; REGISTER_COUNT],+ slots: HashMap::new(),+ owners: HashMap::new(),+ errors: Vec::new(),+ };+ for (value, &slot) in allocation.slots.iter().enumerate() {+ if slot != super::NO_SLOT {+ simulation.owners.insert(slot, value as Value);+ }+ }+ let mut places = Vec::new();+ for block in 0..func.blocks.len() as BlockId {+ simulation.registers = allocation.block_states[block as usize];+ simulation.slots.clear();+ let data = func.blocks[block as usize];+ for value in data.start..data.end {+ let node = *func.node(value);+ if liveliness.is_dead(value) || matches!(node.op, Op::Phi | Op::Forward) || node.op.is_entry_value() {+ continue;+ }+ let record = *allocation.node(value);+ simulation.apply(allocation.node_moves(value));+ let inputs = func.inputs(value);+ match node.op {+ Op::Helper => {+ for (index, &input) in inputs.iter().enumerate() {+ let register = convention::HELPER_REGISTERS[index];+ simulation.check_holds(Location::Register(register), input, &format!("helper v{value}"));+ }+ for register in 0..REGISTER_COUNT {+ if convention::HOST_CLOBBERS & (1 << register) != 0 {+ simulation.registers[register] = NONE;+ }+ }+ }+ Op::Call | Op::TailCall => {+ let arguments = &inputs[3..];+ let types = arguments+ .iter()+ .map(|argument| func.node(*argument).ty)+ .collect::<Vec<_>>();+ convention::parameter_places(&types, &mut places);+ for (index, &argument) in arguments.iter().enumerate() {+ if let Place::Register(register) = places[index] {+ simulation.check_holds(Location::Register(register), argument, &format!("call v{value}"));+ }+ }+ for (input, register) in [+ (inputs[0], convention::CALLEE_REGISTER),+ (inputs[1], convention::INSTANCE_REGISTER),+ (inputs[2], convention::MEMORY_BASE_REGISTER),+ ] {+ simulation.check_holds(Location::Register(register), input, &format!("call v{value}"));+ }+ simulation.registers = [NONE; REGISTER_COUNT];+ let _ = call_result_types(func, value);+ }+ Op::Return => {+ convention::result_places(&func.results, &mut places);+ for (index, &result) in inputs.iter().enumerate() {+ if let Place::Register(register) = places[index] {+ simulation.check_holds(Location::Register(register), result, &format!("return v{value}"));+ }+ }+ }+ _ => {+ let count = match node.op.shape() {+ Shape::Fixed(count) => count as usize,+ Shape::Variadic => inputs.len().min(3),+ };+ for (index, &input) in inputs.iter().enumerate().take(count) {+ let register = record.inputs[index];+ if register == CONSTANT_INPUT {+ if !func.node(input).op.is_constant() {+ simulation.error(format!("v{value} takes v{input} as an immediate"));+ }+ continue;+ }+ if func.node(input).op.is_constant() {+ // Materialized into the register by the moves before the node.+ continue;+ }+ simulation.check_holds(Location::Register(register), input, &format!("v{value} input {index}"));+ }+ for temp in record.temps {+ if temp != NO_REGISTER {+ simulation.registers[temp as usize] = NONE;+ }+ }+ if matches!(node.op, Op::DivS | Op::DivU | Op::RemS | Op::RemU) {+ simulation.registers[convention::RAX as usize] = NONE;+ simulation.registers[convention::RDX as usize] = NONE;+ }+ }+ }+ if record.output != NO_REGISTER {+ simulation.registers[record.output as usize] = value;+ }+ }+ // The edges.+ let end_registers = simulation.registers;+ let end_slots = simulation.slots.clone();+ let successors_start = data.successors_start;+ for (index, &successor) in func.successors(block).iter().enumerate() {+ simulation.registers = end_registers;+ simulation.slots = end_slots.clone();+ simulation.apply(allocation.edge(successors_start + index as u32));+ let predecessor = predecessor_index(func, successor, block);+ let target = allocation.block_states[successor as usize];+ for (register, &value) in target.iter().enumerate() {+ if value == NONE {+ continue;+ }+ let expected = if func.node(value).op == Op::Phi && func.phis(successor).any(|phi| phi == value) {+ func.inputs(value)[predecessor]+ } else {+ value+ };+ let held = simulation.registers[register];+ if held != expected {+ simulation.error(format!(+ "edge b{block} -> b{successor}: r{register} holds v{held}, not v{expected}"+ ));+ }+ }+ for phi in func.phis(successor) {+ if allocation.node(phi).output != NO_REGISTER {+ continue;+ }+ let input = func.inputs(phi)[predecessor];+ let slot = allocation.slots[phi as usize];+ if simulation.slots.get(&slot) != Some(&input) && allocation.slots[input as usize] != slot {+ simulation.error(format!(+ "edge b{block} -> b{successor}: the slot of phi v{phi} lacks v{input}"+ ));+ }+ }+ }+ }+ if simulation.errors.is_empty() {+ Ok(())+ } else {+ Err(simulation.errors.join("\n"))+ }+}++/// The allocation as text, for `dump-ir` and failures.+pub fn dump(func: &Func, liveliness: &Liveliness, allocation: &Allocation) -> String {+ use std::fmt::Write;+ let name = |location: &Location| match location {+ Location::Register(register) if convention::is_fpr(*register) => {+ format!("xmm{}", register - convention::FPR_BASE)+ }+ Location::Register(register) => format!("r{register}"),+ Location::Slot(slot) => format!("[fp{slot:+}]"),+ Location::Outgoing(index) => format!("out{index}"),+ Location::ResultArea(index) => format!("result{index}"),+ Location::Constant(value) => format!("#v{value}"),+ };+ let register = |register: u8| match register {+ NO_REGISTER => "-".to_string(),+ CONSTANT_INPUT => "#".to_string(),+ _ => name(&Location::Register(register)),+ };+ let moves = |moves: &[super::Move]| {+ moves+ .iter()+ .map(|item| format!("{} -> {}", name(&item.from), name(&item.to)))+ .collect::<Vec<_>>()+ .join(", ")+ };+ let mut out = String::new();+ for block in 0..func.blocks.len() as BlockId {+ writeln!(out, "b{block}:").unwrap();+ for phi in func.phis(block) {+ let record = allocation.node(phi);+ writeln!(+ out,+ " v{phi} phi -> {} slot {}",+ register(record.output),+ allocation.slots[phi as usize]+ )+ .unwrap();+ }+ let data = func.blocks[block as usize];+ for value in data.start..data.end {+ let node = func.node(value);+ if liveliness.is_dead(value) || matches!(node.op, Op::Phi | Op::Forward) || node.op.is_entry_value() {+ continue;+ }+ let record = allocation.node(value);+ if record.moves_count > 0 {+ writeln!(out, " moves {}", moves(allocation.node_moves(value))).unwrap();+ }+ let inputs = record.inputs.iter().map(|input| register(*input)).collect::<Vec<_>>();+ write!(out, " v{value} {} ({})", node.op.name(), inputs.join(", ")).unwrap();+ if record.output != NO_REGISTER {+ write!(out, " -> {}", register(record.output)).unwrap();+ }+ if allocation.slots[value as usize] != super::NO_SLOT {+ write!(out, " spill [fp{:+}]", allocation.slots[value as usize]).unwrap();+ }+ out.push('\n');+ }+ for (index, &successor) in func.successors(block).iter().enumerate() {+ let edge = allocation.edge(data.successors_start + index as u32);+ if !edge.is_empty() {+ writeln!(out, " edge -> b{successor}: {}", moves(edge)).unwrap();+ }+ }+ }+ writeln!(+ out,+ "slots: {}, outgoing: {}",+ allocation.slot_count, allocation.outgoing_size+ )+ .unwrap();+ out+}diff --git a/Libraries/LibWasm/JIT/src/runtime.rs b/Libraries/LibWasm/JIT/src/runtime.rsnew file mode 100644index 00000000000..74f12242788--- /dev/null+++ b/Libraries/LibWasm/JIT/src/runtime.rs@@ -0,0 +1,149 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * 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.++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,+};++/// The address of the function `helper` calls.+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::MemoryFill => memory_fill,+ Helper::MemoryCopy => memory_copy,+ Helper::MemoryInit => memory_init,+ Helper::TableFill => table_fill,+ Helper::TableCopy => table_copy,+ Helper::TableInit => table_init,+ };+ function as usize as u64+}++/// Whether `count` items from `start` are within `size`. The operands of memory64 and table64 operations are+/// 64-bit, so the end can wrap around.+fn in_range(start: u64, count: u64, size: u64) -> bool {+ start.checked_add(count).is_some_and(|end| end <= size)+}++unsafe fn arguments<'a>(context: *mut ExecutionContext) -> &'a [u64; 6] {+ unsafe { &(*context).arguments }+}++unsafe extern "C" fn memory_fill(context: *mut ExecutionContext) -> u64 {+ unsafe {+ let &[memory, destination, value, count, ..] = arguments(context);+ let memory = &*(memory as *const MemoryData);+ if !in_range(destination, count, memory.size) {+ return u64::from(TRAP_MEMORY_OUT_OF_BOUNDS);+ }+ if count == 0 {+ return 0;+ }+ std::ptr::write_bytes(memory.base.add(destination as usize), value as u8, count as usize);+ 0+ }+}++unsafe extern "C" fn memory_copy(context: *mut ExecutionContext) -> u64 {+ unsafe {+ let &[destination_memory, source_memory, destination, source, count, _] = arguments(context);+ let destination_memory = &*(destination_memory as *const MemoryData);+ let source_memory = &*(source_memory as *const MemoryData);+ if !in_range(destination, count, destination_memory.size) || !in_range(source, count, source_memory.size) {+ return u64::from(TRAP_MEMORY_OUT_OF_BOUNDS);+ }+ if count == 0 {+ return 0;+ }+ std::ptr::copy(+ source_memory.base.add(source as usize),+ destination_memory.base.add(destination as usize),+ count as usize,+ );+ 0+ }+}++unsafe extern "C" fn memory_init(context: *mut ExecutionContext) -> u64 {+ unsafe {+ let &[memory, segment, destination, source, count, _] = arguments(context);+ let memory = &*(memory as *const MemoryData);+ let segment = &*(segment as *const Segment);+ if !in_range(source, count, segment.length) || !in_range(destination, count, memory.size) {+ return u64::from(TRAP_MEMORY_OUT_OF_BOUNDS);+ }+ if count == 0 {+ return 0;+ }+ std::ptr::copy(+ segment.contents.add(source as usize),+ memory.base.add(destination as usize),+ count as usize,+ );+ 0+ }+}++unsafe extern "C" fn table_fill(context: *mut ExecutionContext) -> u64 {+ unsafe {+ let &[table, destination, value, count, ..] = arguments(context);+ let table = &*(table as *const TableData);+ if !in_range(destination, count, table.size) {+ return u64::from(TRAP_TABLE_OUT_OF_BOUNDS);+ }+ for index in destination..destination + count {+ *table.elements.add(index as usize) = value;+ }+ 0+ }+}++unsafe extern "C" fn table_copy(context: *mut ExecutionContext) -> u64 {+ unsafe {+ let &[destination_table, source_table, destination, source, count, _] = arguments(context);+ let destination_table = &*(destination_table as *const TableData);+ let source_table = &*(source_table as *const TableData);+ if !in_range(destination, count, destination_table.size) || !in_range(source, count, source_table.size) {+ return u64::from(TRAP_TABLE_OUT_OF_BOUNDS);+ }+ if count == 0 {+ return 0;+ }+ std::ptr::copy(+ source_table.elements.add(source as usize),+ destination_table.elements.add(destination as usize),+ count as usize,+ );+ 0+ }+}++unsafe extern "C" fn table_init(context: *mut ExecutionContext) -> u64 {+ unsafe {+ let &[table, segment, destination, source, count, _] = arguments(context);+ let table = &*(table as *const TableData);+ let segment = &*(segment as *const Segment);+ if !in_range(source, count, segment.length) || !in_range(destination, count, table.size) {+ return u64::from(TRAP_TABLE_OUT_OF_BOUNDS);+ }+ if count == 0 {+ return 0;+ }+ std::ptr::copy(+ segment.contents.cast::<u64>().add(source as usize),+ table.elements.add(destination as usize),+ count as usize,+ );+ 0+ }+}diff --git a/Libraries/LibWasm/JIT/src/stubs.rs b/Libraries/LibWasm/JIT/src/stubs.rsnew file mode 100644index 00000000000..66b047b2938--- /dev/null+++ b/Libraries/LibWasm/JIT/src/stubs.rs@@ -0,0 +1,178 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Code that is not a compiled function but is called like one. A host function's `native_entry` is the host stub of+//! its signature, which lays the arguments out as the interpreter's operand stack would hold them, calls the host+//! function through the runtime's `wasm_runtime_call_host` like the interpreter does, and returns its results under the compiled+//! convention.++use crate::RuntimeInfo;+use crate::asm::x86_64::{Assembler, Cond, Precision, VexMap, VexOpcode, VexOperand, VexPrefix};+use crate::asm::{Address, Fpr, Gpr, Width};+use crate::convention::{self, Place, Register};+use crate::ir::Type;+use libwasm_module::abi::{ExecutionContext, InstanceData, TRAP_RUNTIME, TRAP_STACK_EXHAUSTED};+use std::mem::offset_of;++const VMOVUPS_LOAD: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x10);+const VMOVUPS_STORE: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x11);++const FP: Gpr = Gpr(convention::RBP);+const SP: Gpr = Gpr(convention::RSP);+const SCRATCH: Gpr = Gpr(convention::SCRATCH_GPR);+const SCRATCH_FPR: Register = convention::SCRATCH_FPR;++/// Loads (if `load`) or stores the value of type `ty` in `register` at `address`.+fn transfer(asm: &mut Assembler, ty: Type, register: Register, address: Address, load: bool) {+ if ty == Type::V128 {+ let opcode = if load { VMOVUPS_LOAD } else { VMOVUPS_STORE };+ asm.vex(+ opcode,+ register - convention::FPR_BASE,+ 0,+ VexOperand::Memory(address),+ None,+ );+ } else if convention::is_fpr(register) {+ let register = Fpr(register - convention::FPR_BASE);+ if load {+ asm.vmovs_rm(Precision::Double, register, &address);+ } else {+ asm.vmovs_mr(Precision::Double, &address, register);+ }+ } else if load {+ // NB: i32 values are zero-extended in registers.+ let width = if ty == Type::I32 { Width::W32 } else { Width::W64 };+ asm.mov_rm(width, Gpr(register), &address);+ } else {+ asm.mov_mr(Width::W64, &address, Gpr(register));+ }+}++/// Copies a value of type `ty` between memory locations.+fn copy(asm: &mut Assembler, ty: Type, from: Address, to: Address) {+ let register = if ty == Type::V128 || ty.is_float() {+ SCRATCH_FPR+ } else {+ SCRATCH.0+ };+ let ty = if ty.is_float() { Type::F64 } else { ty };+ transfer(asm, ty, register, from, true);+ transfer(asm, ty, register, to, false);+}++/// The host stub for functions with these parameter and result types.+pub fn host_stub(params: &[Type], results: &[Type], runtime: &RuntimeInfo) -> Vec<u8> {+ let mut asm = Assembler::new();+ let parameter_slots = convention::slots(params) as i32;+ let result_slots = convention::slots(results) as i32;+ let buffer_slots = parameter_slots.max(result_slots);+ // Below the frame header: a zero word, which makes the frame the runtime unwinds an exception from look like an+ // entry frame, and the operand stack image at rsp.+ let zero = -convention::FRAME_HEADER_SIZE - 8;+ let frame_size = (convention::FRAME_HEADER_SIZE as u32 + 8 + 8 * buffer_slots as u32).next_multiple_of(16) as i32;+ let context = Gpr(convention::RAX);+ let instance = Gpr(convention::INSTANCE_REGISTER);++ asm.push(FP);+ asm.lea(Width::W64, FP, &Address::new(SP, 16));+ asm.mov_mr(Width::W64, &Address::new(FP, convention::FRAME_INSTANCE), instance);+ asm.mov_rm(+ Width::W64,+ context,+ &Address::new(instance, offset_of!(InstanceData, context) as i32),+ );+ asm.lea(Width::W64, SCRATCH, &Address::new(SP, -(frame_size - 16)));+ asm.alu_rm(+ crate::asm::x86_64::AluOp::Cmp,+ Width::W64,+ SCRATCH,+ &Address::new(context, offset_of!(ExecutionContext, stack_limit) as i32),+ );+ let exhausted = asm.new_label();+ asm.jcc(Cond::Below, exhausted);+ asm.mov_rr(Width::W64, SP, SCRATCH);++ // The operand stack grows down, so the first argument is in the highest slots.+ let top = 8 * (buffer_slots - parameter_slots);+ let mut places = Vec::new();+ convention::parameter_places(params, &mut places);+ for (index, place) in places.iter().enumerate() {+ let home = convention::home_slot(params, index) as i32;+ let slot = parameter_slots - home - params[index].slots() as i32;+ let address = Address::new(SP, top + 8 * slot);+ match *place {+ Place::Register(register) => transfer(&mut asm, params[index], register, address, false),+ Place::Memory(home) => copy(&mut asm, params[index], Address::new(FP, 8 * home as i32), address),+ }+ }++ let arguments = offset_of!(ExecutionContext, arguments) as i32;+ asm.mov_mr(+ Width::W64,+ &Address::new(context, arguments),+ Gpr(convention::CALLEE_REGISTER),+ );+ asm.lea(Width::W64, SCRATCH, &Address::new(SP, top));+ asm.mov_mr(Width::W64, &Address::new(context, arguments + 8), SCRATCH);+ asm.mov_mi(Width::W64, &Address::new(context, arguments + 16), 0);+ asm.mov_mi(Width::W64, &Address::new(FP, zero), 0);+ asm.lea(+ Width::W64,+ SCRATCH,+ &Address::new(FP, zero - convention::FRAME_INSTANCE),+ );+ asm.mov_mr(Width::W64, &Address::new(context, arguments + 24), SCRATCH);+ asm.mov_rr(Width::W64, Gpr(convention::RDI), context);+ asm.mov_ri(SCRATCH, runtime.call_host);+ asm.call_r(SCRATCH);++ // 0 is a trap, which the runtime keeps; 1 would resume at a handler, which the zero word rules out.+ let failed = asm.new_label();+ asm.cmp_ri(Width::W64, Gpr(convention::RAX), 1);+ asm.jcc(Cond::BelowOrEqual, failed);+ let return_top = Gpr(convention::RAX);+ let area = Gpr(convention::R11);+ if convention::has_result_area(results) {+ asm.mov_rm(Width::W64, area, &Address::new(FP, 8 * parameter_slots));+ }+ convention::result_places(results, &mut places);+ // NB: Backwards, so that rax, which the first integer result goes to, is written last.+ for (index, place) in places.iter().enumerate().rev() {+ let home = convention::home_slot(results, index) as i32;+ let slot = result_slots - home - results[index].slots() as i32;+ let address = Address::new(return_top, 8 * slot);+ match *place {+ Place::Register(register) => transfer(&mut asm, results[index], register, address, true),+ Place::Memory(home) => {+ let to = Address::new(area, 8 * home as i32);+ let register = if results[index] == Type::V128 || results[index].is_float() {+ SCRATCH_FPR+ } else {+ convention::RCX+ };+ let ty = if results[index].is_float() {+ Type::F64+ } else {+ results[index]+ };+ transfer(&mut asm, ty, register, address, true);+ transfer(&mut asm, ty, register, to, false);+ }+ }+ }+ asm.lea(Width::W64, SP, &Address::new(FP, convention::FRAME_SAVED_FP));+ asm.pop(FP);+ asm.ret();++ for (label, code) in [(failed, TRAP_RUNTIME), (exhausted, TRAP_STACK_EXHAUSTED)] {+ asm.bind(label);+ asm.mov_ri32(Gpr(convention::RDI), code);+ asm.mov_ri(SCRATCH, runtime.trap_exit);+ asm.jmp_r(SCRATCH);+ }+ asm.finish().expect("stubs have no unbound labels")+}diff --git a/Libraries/LibWasm/JIT/src/table.rs b/Libraries/LibWasm/JIT/src/table.rsnew file mode 100644index 00000000000..fc4267b0a1a--- /dev/null+++ b/Libraries/LibWasm/JIT/src/table.rs@@ -0,0 +1,177 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A hash table for the compiler's per-compile maps, which emptying makes no work.+//!+//! OPTIMIZATION: Every compile starts with empty maps, and most functions are small, while a few are huge. A+//! general hash map's `clear()` touches its whole capacity, so after one huge function every small one would pay+//! for it. Here every slot carries the number of the compile that wrote it, and a slot of an older compile is empty:+//! emptying the table is one increment. Keys are never removed; callers that need removal store a value that means+//! none. Open addressing with linear probing, at most half full.++/// A key: hashes to 64 bits without a hasher object.+pub trait TableKey: Copy + Eq + Default {+ fn hash(&self) -> u64;+}++impl TableKey for u64 {+ #[inline]+ fn hash(&self) -> u64 {+ self.wrapping_mul(0x9e37_79b9_7f4a_7c15)+ }+}++impl TableKey for [u32; 4] {+ #[inline]+ fn hash(&self) -> u64 {+ let low = u64::from(self[0]) | (u64::from(self[1]) << 32);+ let high = u64::from(self[2]) | (u64::from(self[3]) << 32);+ (low.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ high).wrapping_mul(0xc2b2_ae3d_27d4_eb4f)+ }+}++impl TableKey for [u32; 6] {+ #[inline]+ fn hash(&self) -> u64 {+ let words = [+ u64::from(self[0]) | (u64::from(self[1]) << 32),+ u64::from(self[2]) | (u64::from(self[3]) << 32),+ u64::from(self[4]) | (u64::from(self[5]) << 32),+ ];+ let mut hash = 0u64;+ for word in words {+ hash = (hash.rotate_left(26) ^ word).wrapping_mul(0x9e37_79b9_7f4a_7c15);+ }+ hash+ }+}++#[derive(Clone, Copy, Default)]+struct Slot<K: TableKey> {+ key: K,+ value: u32,+ stamp: u32,+}++pub struct Table<K: TableKey> {+ slots: Vec<Slot<K>>,+ stamp: u32,+ len: usize,+ shift: u32,+}++impl<K: TableKey> Default for Table<K> {+ fn default() -> Self {+ Self {+ slots: Vec::new(),+ stamp: 1,+ len: 0,+ shift: 64,+ }+ }+}++const MINIMUM_CAPACITY: usize = 64;++impl<K: TableKey> Table<K> {+ /// Empties the table.+ pub fn clear(&mut self) {+ self.len = 0;+ self.stamp = self.stamp.wrapping_add(1);+ if self.stamp == 0 {+ // NB: Once in 2^32 compiles, the stamps start over, and the old ones must not look current.+ for slot in &mut self.slots {+ slot.stamp = 0;+ }+ self.stamp = 1;+ }+ }++ #[inline]+ fn index(&self, key: &K) -> usize {+ (key.hash() >> self.shift) as usize+ }++ #[inline]+ pub fn get(&self, key: K) -> Option<u32> {+ if self.slots.is_empty() {+ return None;+ }+ let mask = self.slots.len() - 1;+ let mut index = self.index(&key);+ loop {+ let slot = &self.slots[index];+ if slot.stamp != self.stamp {+ return None;+ }+ if slot.key == key {+ return Some(slot.value);+ }+ index = (index + 1) & mask;+ }+ }++ /// Sets the value of `key`, and returns its previous one.+ #[inline]+ pub fn insert(&mut self, key: K, value: u32) -> Option<u32> {+ if (self.len + 1) * 2 > self.slots.len() {+ self.grow();+ }+ let mask = self.slots.len() - 1;+ let mut index = self.index(&key);+ loop {+ let stamp = self.stamp;+ let slot = &mut self.slots[index];+ if slot.stamp != stamp {+ *slot = Slot { key, value, stamp };+ self.len += 1;+ return None;+ }+ if slot.key == key {+ let previous = slot.value;+ slot.value = value;+ return Some(previous);+ }+ index = (index + 1) & mask;+ }+ }++ fn grow(&mut self) {+ let capacity = (self.slots.len() * 2).max(MINIMUM_CAPACITY);+ let old = std::mem::replace(&mut self.slots, vec![Slot::default(); capacity]);+ let old_stamp = self.stamp;+ self.shift = 64 - capacity.trailing_zeros();+ self.stamp = 1;+ self.len = 0;+ for slot in old {+ if slot.stamp == old_stamp {+ self.insert(slot.key, slot.value);+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn inserts_finds_and_empties() {+ let mut table = Table::<u64>::default();+ for key in 0..1000u64 {+ assert_eq!(table.insert(key * 7, key as u32), None);+ }+ for key in 0..1000u64 {+ assert_eq!(table.get(key * 7), Some(key as u32));+ }+ assert_eq!(table.insert(14, 99), Some(2));+ assert_eq!(table.get(15), None);+ table.clear();+ assert_eq!(table.get(14), None);+ assert_eq!(table.insert(14, 5), None);+ assert_eq!(table.get(14), Some(5));+ }+}diff --git a/Libraries/LibWasm/JIT/tests/decode.rs b/Libraries/LibWasm/JIT/tests/decode.rsnew file mode 100644index 00000000000..ab437a566e5--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/decode.rs@@ -0,0 +1,48 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The decoder reads every body of the spec testsuite's valid modules to its end, with balanced nesting.++use libwasm_jit::decode::{Decoder, nesting_change};+use std::path::PathBuf;++/// The spec testsuite's modules, if the build directory has them.+pub fn spec_modules() -> Option<PathBuf> {+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..");+ let directory = std::env::var_os("LIBWASM_SPEC_MODULES")+ .map(PathBuf::from)+ .unwrap_or_else(|| root.join("Build/release/Libraries/LibWasm/Tests/Fixtures/SpecTests"));+ directory.is_dir().then_some(directory)+}++#[test]+fn decoded_lengths_match_every_spec_body() {+ let Some(directory) = spec_modules() else {+ eprintln!("no spec testsuite modules; skipped");+ return;+ };+ let mut bodies = 0;+ for entry in std::fs::read_dir(directory).unwrap() {+ let path = entry.unwrap().path();+ if path.extension().is_none_or(|extension| extension != "wasm") {+ continue;+ }+ let Ok(module) = libwasm_engine::compile(&std::fs::read(&path).unwrap()) else {+ continue;+ };+ for body in &module.code {+ let mut decoder = Decoder::new(&module.bytes, body.code.start as usize, body.code.end as usize);+ let mut depth = 1;+ while depth > 0 {+ assert!(!decoder.is_at_end(), "{}: the body ends early", path.display());+ depth += nesting_change(&decoder.decode());+ }+ assert_eq!(decoder.position(), body.code.end as usize, "{}", path.display());+ bodies += 1;+ }+ }+ assert!(bodies > 1000, "only {bodies} bodies");+}diff --git a/Libraries/LibWasm/JIT/tests/execution.rs b/Libraries/LibWasm/JIT/tests/execution.rsnew file mode 100644index 00000000000..346ab2be737--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/execution.rs@@ -0,0 +1,35 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Compiled code against the interpreter, over the spec testsuite's scripts (see `harness::script`).++#![cfg(all(target_arch = "x86_64", target_os = "linux"))]++mod harness;++use std::path::PathBuf;++#[test]+fn spec_scripts_run_the_same_compiled() {+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..");+ let directory = std::env::var_os("LIBWASM_SPEC_MODULES")+ .map(PathBuf::from)+ .unwrap_or_else(|| root.join("Build/release/Libraries/LibWasm/Tests/Fixtures/SpecTests"));+ if !directory.is_dir() {+ eprintln!("no spec testsuite scripts; skipped");+ return;+ }+ for stress_registers in [false, true] {+ let options = libwasm_jit::Options {+ verify_ir: true,+ stress_registers,+ ..Default::default()+ };+ let totals = harness::script::run(&[directory.to_string_lossy().into_owned()], false, options);+ assert!(totals.cases > 10_000, "only {} cases ran compiled", totals.cases);+ assert_eq!(totals.failures, 0);+ }+}diff --git a/Libraries/LibWasm/JIT/tests/harness/mod.rs b/Libraries/LibWasm/JIT/tests/harness/mod.rsnew file mode 100644index 00000000000..5e03c3c1a9e--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/harness/mod.rs@@ -0,0 +1,621 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Runs compiled code without the runtime: maps the code of a module's compiled functions executable, points the+//! `native_entry` of the engine's function headers at it, enters it through a trampoline per signature, and turns+//! traps and memory faults into results. Host functions get the JIT's host stubs, and functions the JIT did not+//! compile a stub that traps with `TRAP_NOT_COMPILED`. Each thread has a session of its own: a code space, whose+//! start is the trap exit, the trampolines and the stubs.++#![allow(dead_code)]++pub mod script;++use libwasm_engine::Module;+use libwasm_engine::abi::{ExecutionContext, InstanceData};+use libwasm_engine::runtime::{FunctionKind, InstanceAddress, Store, Value, helpers};+use libwasm_jit::asm::x86_64::{Assembler, Precision, VexMap, VexOpcode, VexOperand, VexPrefix};+use libwasm_jit::asm::{Address, Gpr, Width};+use libwasm_jit::convention::{self, Place};+use libwasm_jit::ir::Type;+use libwasm_jit::{CompileContext, CompileFailure, CompileRequest, Options, RuntimeInfo};+use std::cell::RefCell;+use std::collections::HashMap;+use std::mem::offset_of;+use std::sync::Arc;++/// The trap code of a call that reached a function the JIT did not compile.+pub const TRAP_NOT_COMPILED: u32 = 100;++/// Where the trap exit leaves the trampoline's stack pointer and the trap code.+#[repr(C)]+struct SessionState {+ entry_sp: u64,+ trap: u32,+}++const ENTRY_SP_OFFSET: i32 = offset_of!(SessionState, entry_sp) as i32;+const TRAP_OFFSET: i32 = offset_of!(SessionState, trap) as i32;++const CODE_SPACE_SIZE: usize = 1 << 30;++const VMOVUPS_LOAD: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x10);+const VMOVUPS_STORE: VexOpcode = VexOpcode::new(VexPrefix::None, VexMap::Map0F, 0x11);++/// Executable memory, reserved up front. Code is added in batches, which are written while their pages are not+/// executable.+pub struct CodeSpace {+ base: *mut u8,+ size: usize,+ used: usize,+}++const PAGE_SIZE: usize = 4096;++impl CodeSpace {+ fn new(size: usize) -> Self {+ let base = unsafe {+ libc::mmap(+ std::ptr::null_mut(),+ size,+ libc::PROT_NONE,+ libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,+ -1,+ 0,+ )+ };+ assert_ne!(base, libc::MAP_FAILED);+ Self {+ base: base.cast(),+ size,+ used: 0,+ }+ }++ /// Copies each piece of code in and returns their addresses.+ fn add(&mut self, codes: &[&[u8]]) -> Vec<u64> {+ let first_page = self.used / PAGE_SIZE * PAGE_SIZE;+ let mut end = self.used;+ let mut starts = Vec::with_capacity(codes.len());+ for code in codes {+ let start = end.next_multiple_of(16);+ starts.push(start);+ end = start + code.len();+ }+ assert!(end <= self.size, "the code space is full");+ let pages = end.next_multiple_of(PAGE_SIZE) - first_page;+ if pages == 0 {+ return starts.iter().map(|start| self.base as u64 + *start as u64).collect();+ }+ let region = unsafe { self.base.add(first_page) };+ unsafe {+ assert_eq!(+ libc::mprotect(region.cast(), pages, libc::PROT_READ | libc::PROT_WRITE),+ 0+ );+ for (code, start) in codes.iter().zip(&starts) {+ std::ptr::copy_nonoverlapping(code.as_ptr(), self.base.add(*start), code.len());+ }+ __clear_cache(region.cast(), region.add(pages).cast());+ assert_eq!(+ libc::mprotect(region.cast(), pages, libc::PROT_READ | libc::PROT_EXEC),+ 0+ );+ }+ self.used = end;+ starts.iter().map(|start| self.base as u64 + *start as u64).collect()+ }+}++impl Drop for CodeSpace {+ fn drop(&mut self) {+ unsafe { libc::munmap(self.base.cast(), self.size) };+ }+}++// The code spaces that exist, for the fault handler. Tests run on several threads.+static CODE_RANGES: std::sync::Mutex<Vec<(u64, u64)>> = std::sync::Mutex::new(Vec::new());++/// The trap exit, entered with the trap code in edi: returns 1 from the trampoline.+fn trap_exit_code(state: *mut SessionState) -> Vec<u8> {+ let mut asm = Assembler::new();+ let rax = Gpr(convention::RAX);+ let sp = Gpr(convention::RSP);+ asm.mov_ri(rax, state as u64);+ asm.mov_mr(Width::W32, &Address::new(rax, TRAP_OFFSET), Gpr(convention::RDI));+ asm.mov_rm(Width::W64, sp, &Address::new(rax, ENTRY_SP_OFFSET));+ restore_and_return(&mut asm, 1);+ asm.finish().unwrap()+}++/// The code of functions the JIT did not compile.+fn not_compiled_code(trap_exit: u64) -> Vec<u8> {+ let mut asm = Assembler::new();+ asm.mov_ri32(Gpr(convention::RDI), TRAP_NOT_COMPILED);+ asm.mov_ri(Gpr(convention::R11), trap_exit);+ asm.jmp_r(Gpr(convention::R11));+ asm.finish().unwrap()+}++fn restore_and_return(asm: &mut Assembler, status: u32) {+ asm.add_ri(Width::W64, Gpr(convention::RSP), 8);+ for register in [+ convention::R15,+ convention::R14,+ convention::R13,+ convention::R12,+ convention::RBX,+ convention::RBP,+ ] {+ asm.pop(Gpr(register));+ }+ asm.mov_ri32(Gpr(convention::RAX), status);+ asm.ret();+}++/// `extern "C" fn(entry, arguments, results, instance) -> u32`: calls `entry` with the arguments' slots under the+/// compiled convention, stores the results' slots, and returns 0, or 1 if the code trapped.+fn trampoline_code(params: &[Type], results: &[Type], state: *mut SessionState) -> Vec<u8> {+ let mut asm = Assembler::new();+ let g = Gpr;+ let (rdi, rsi, rdx, rcx) = (+ g(convention::RDI),+ g(convention::RSI),+ g(convention::RDX),+ g(convention::RCX),+ );+ let sp = g(convention::RSP);+ let scratch = g(convention::R11);+ for register in [+ convention::RBP,+ convention::RBX,+ convention::R12,+ convention::R13,+ convention::R14,+ convention::R15,+ ] {+ asm.push(g(register));+ }+ asm.sub_ri(Width::W64, sp, 8);+ asm.mov_mr(Width::W64, &Address::new(sp, 0), rdx);+ asm.mov_ri(scratch, state as u64);+ asm.mov_mr(Width::W64, &Address::new(scratch, ENTRY_SP_OFFSET), sp);+ let outgoing = convention::outgoing_size(params, results).next_multiple_of(16) as i32;+ if outgoing > 0 {+ asm.sub_ri(Width::W64, sp, outgoing);+ }+ let entry = g(convention::R10);+ asm.mov_rr(Width::W64, entry, rdi);+ asm.mov_rr(Width::W64, scratch, rsi);+ asm.mov_rr(Width::W64, g(convention::INSTANCE_REGISTER), rcx);+ asm.mov_rm(+ Width::W64,+ g(convention::MEMORY_BASE_REGISTER),+ &Address::new(rcx, offset_of!(InstanceData, memory0_base) as i32),+ );+ // Copies the 8 or 16 bytes of a value of type `ty` between memory locations, through xmm15.+ let copy = |asm: &mut Assembler, ty: Type, from: Address, to: Address| {+ if ty == Type::V128 {+ asm.vex(VMOVUPS_LOAD, 15, 0, VexOperand::Memory(from), None);+ asm.vex(VMOVUPS_STORE, 15, 0, VexOperand::Memory(to), None);+ } else {+ asm.vmovs_rm(Precision::Double, libwasm_jit::asm::Fpr(15), &from);+ asm.vmovs_mr(Precision::Double, &to, libwasm_jit::asm::Fpr(15));+ }+ };+ // Loads or stores a value of type `ty` in `register` (true) at `address`.+ let transfer = |asm: &mut Assembler, ty: Type, register: u8, address: Address, load: bool| {+ if ty == Type::V128 {+ let opcode = if load { VMOVUPS_LOAD } else { VMOVUPS_STORE };+ asm.vex(+ opcode,+ register - convention::FPR_BASE,+ 0,+ VexOperand::Memory(address),+ None,+ );+ } else if convention::is_fpr(register) {+ let register = libwasm_jit::asm::Fpr(register - convention::FPR_BASE);+ if load {+ asm.vmovs_rm(Precision::Double, register, &address);+ } else {+ asm.vmovs_mr(Precision::Double, &address, register);+ }+ } else if load {+ asm.mov_rm(Width::W64, g(register), &address);+ } else {+ asm.mov_mr(Width::W64, &address, g(register));+ }+ };+ let mut places = Vec::new();+ convention::parameter_places(params, &mut places);+ // Stack arguments first, then registers, so that rsi and the others are read before they are written. Argument+ // slots are laid out like home slots, so a parameter's slot is the same in both.+ for (index, place) in places.iter().enumerate() {+ if let Place::Memory(slot) = place {+ let from = Address::new(scratch, 8 * *slot as i32);+ copy(&mut asm, params[index], from, Address::new(sp, 8 * *slot as i32));+ }+ }+ for (index, place) in places.iter().enumerate() {+ if let Place::Register(register) = place {+ let slot = convention::home_slot(params, index);+ transfer(+ &mut asm,+ params[index],+ *register,+ Address::new(scratch, 8 * slot as i32),+ true,+ );+ }+ }+ let parameter_slots = convention::slots(params) as i32;+ if convention::has_result_area(results) {+ let pointer = 8 * parameter_slots;+ asm.lea(Width::W64, g(convention::RAX), &Address::new(sp, pointer + 8));+ asm.mov_mr(Width::W64, &Address::new(sp, pointer), g(convention::RAX));+ }+ asm.call_r(entry);+ // NB: Tail calls may have moved rsp.+ asm.mov_ri(scratch, state as u64);+ asm.mov_rm(Width::W64, sp, &Address::new(scratch, ENTRY_SP_OFFSET));+ if outgoing > 0 {+ asm.sub_ri(Width::W64, sp, outgoing);+ }+ asm.mov_rm(Width::W64, scratch, &Address::new(sp, outgoing));+ convention::result_places(results, &mut places);+ for (index, place) in places.iter().enumerate() {+ let slot = convention::home_slot(results, index);+ let address = Address::new(scratch, 8 * slot as i32);+ match place {+ Place::Register(register) => transfer(&mut asm, results[index], *register, address, false),+ Place::Memory(slot) => {+ let area = 8 * (parameter_slots + 1) + 8 * *slot as i32;+ copy(&mut asm, results[index], Address::new(sp, area), address);+ }+ }+ }+ if outgoing > 0 {+ asm.add_ri(Width::W64, sp, outgoing);+ }+ restore_and_return(&mut asm, 0);+ asm.finish().unwrap()+}++fn ir_types(types: &[libwasm_engine::types::ValType]) -> Option<Vec<Type>> {+ types.iter().map(|ty| libwasm_jit::builder::ir_type(*ty)).collect()+}++type Signature = (Vec<Type>, Vec<Type>);++/// What compiled code of a thread runs with.+struct Session {+ space: CodeSpace,+ state: Box<SessionState>,+ runtime: RuntimeInfo,+ not_compiled: u64,+ trampolines: HashMap<Signature, u64>,+ host_stubs: HashMap<Signature, u64>,+}++impl Session {+ fn new() -> Self {+ install_fault_handler();+ let mut space = CodeSpace::new(CODE_SPACE_SIZE);+ let mut state = Box::new(SessionState { entry_sp: 0, trap: 0 });+ // 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(&[¬_compiled_code(trap_exit)])[0];+ CODE_RANGES+ .lock()+ .unwrap()+ .push((space.base as u64, space.base as u64 + space.size as u64));+ Self {+ space,+ state,+ runtime: RuntimeInfo {+ trap_exit,+ memory_grow: helpers::wasm_runtime_memory_grow as *const () as u64,+ table_grow: helpers::wasm_runtime_table_grow as *const () as u64,+ call_host: helpers::wasm_runtime_call_host as *const () as u64,+ },+ not_compiled,+ trampolines: HashMap::new(),+ host_stubs: HashMap::new(),+ }+ }++ fn trampoline(&mut self, signature: &Signature) -> u64 {+ if let Some(address) = self.trampolines.get(signature) {+ return *address;+ }+ let code = trampoline_code(&signature.0, &signature.1, &raw mut *self.state);+ let address = self.space.add(&[&code])[0];+ self.trampolines.insert(signature.clone(), address);+ address+ }++ fn host_stub(&mut self, signature: &Signature) -> u64 {+ if let Some(address) = self.host_stubs.get(signature) {+ return *address;+ }+ let code = libwasm_jit::stubs::host_stub(&signature.0, &signature.1, &self.runtime);+ let address = self.space.add(&[&code])[0];+ self.host_stubs.insert(signature.clone(), address);+ address+ }+}++impl Drop for Session {+ fn drop(&mut self) {+ let start = self.space.base as u64;+ CODE_RANGES+ .lock()+ .unwrap()+ .retain(|(range_start, _)| *range_start != start);+ }+}++thread_local! {+ static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };+}++fn with_session<R>(f: impl FnOnce(&mut Session) -> R) -> R {+ SESSION.with(|session| f(session.borrow_mut().get_or_insert_with(Session::new)))+}++/// A module's functions compiled into the thread's code space.+pub struct CompiledModule {+ pub module: Arc<Module>,+ /// The native entry of each function (counting imports), or 0 if it was not compiled.+ pub entries: Vec<u64>,+ /// Why each function was not compiled.+ pub failures: Vec<Option<CompileFailure>>,+ /// Whether each function and everything it calls directly was compiled.+ pub runnable: Vec<bool>,+}++unsafe extern "C" {+ fn __clear_cache(start: *mut libc::c_char, end: *mut libc::c_char);+}++impl CompiledModule {+ pub fn compile(module: Arc<Module>, options: Options) -> Self {+ let runtime = with_session(|session| session.runtime);+ let total = module.total_function_count() as usize;+ let first = module.imported_function_count as usize;+ let mut entries = vec![0; total];+ let mut failures = vec![None; total];+ let mut codes = Vec::new();+ let mut context = CompileContext::default();+ for (index, slot) in failures.iter_mut().enumerate().skip(first) {+ let request = CompileRequest {+ module: module.clone(),+ function: index as u32,+ runtime,+ options,+ };+ match libwasm_jit::compile(&mut context, &request) {+ Ok(compiled) => codes.push((index, compiled.code)),+ 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) {+ entries[*index] = address;+ }+ // A function runs compiled if it and every function it calls directly compiled.+ let callees = (0..total)+ .map(|index| {+ if index < first {+ Vec::new()+ } else {+ direct_callees(&module, index as u32)+ }+ })+ .collect::<Vec<_>>();+ let mut runnable = (0..total)+ .map(|index| index < first || entries[index] != 0)+ .collect::<Vec<_>>();+ loop {+ let mut changed = false;+ for index in first..total {+ if runnable[index] && callees[index].iter().any(|callee| !runnable[*callee as usize]) {+ runnable[index] = false;+ changed = true;+ }+ }+ if !changed {+ break;+ }+ }+ for flag in runnable.iter_mut().take(first) {+ *flag = false;+ }+ Self {+ module,+ entries,+ failures,+ runnable,+ }+ }+}++/// The functions `index` calls directly.+fn direct_callees(module: &Module, index: u32) -> Vec<u32> {+ use libwasm_jit::decode::{Decoder, Instruction};+ let body = &module.code[(index - module.imported_function_count) as usize];+ let mut decoder = Decoder::new(&module.bytes, body.code.start as usize, body.code.end as usize);+ let mut callees = Vec::new();+ while !decoder.is_at_end() {+ if let Instruction::Call(callee) | Instruction::ReturnCall(callee) = decoder.decode() {+ callees.push(callee);+ }+ }+ callees+}++/// An engine instance whose functions run compiled.+pub struct TestBinding {+ instance: InstanceAddress,+ data: *const InstanceData,+}++/// The outcome of a call.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Outcome {+ Values(Vec<Value>),+ Trap(u32),+}++fn lowest_stack_address() -> u64 {+ unsafe {+ let mut attributes: libc::pthread_attr_t = std::mem::zeroed();+ assert_eq!(libc::pthread_getattr_np(libc::pthread_self(), &raw mut attributes), 0);+ let mut address = std::ptr::null_mut();+ let mut size = 0;+ libc::pthread_attr_getstack(&raw const attributes, &raw mut address, &raw mut size);+ libc::pthread_attr_destroy(&raw mut attributes);+ address as u64+ }+}++impl TestBinding {+ /// Points the instance's functions at their compiled code, and its host function imports at host stubs.+ pub fn new(compiled: &CompiledModule, store: &Store, instance: InstanceAddress) -> Self {+ let engine = store.instance(instance);+ let first = compiled.module.imported_function_count as usize;+ with_session(|session| {+ for (index, address) in engine.functions.iter().enumerate() {+ let function = store.function(*address);+ let entry = match &function.kind {+ FunctionKind::Host(_) => {+ let signature = (+ ir_types(&function.ty.params).expect("the JIT has a type for every value"),+ ir_types(&function.ty.results).expect("the JIT has a type for every value"),+ );+ session.host_stub(&signature)+ }+ _ if index < first => continue,+ _ if compiled.entries[index] != 0 => compiled.entries[index],+ _ => session.not_compiled,+ };+ // NB: The headers are the engine's; nothing else reads or writes this field yet.+ let header = engine.data.functions.wrapping_add(index);+ unsafe {+ let header = (*header).cast_mut();+ (&raw mut (*header).native_entry).write(entry);+ }+ }+ });+ Self {+ instance,+ data: &raw const engine.data,+ }+ }++ /// Calls compiled function `index` of the instance with `arguments`.+ pub fn call(&mut self, store: &mut Store, compiled: &CompiledModule, index: u32, arguments: &[Value]) -> Outcome {+ assert!(compiled.runnable[index as usize]);+ let ty = compiled.module.function_type(index).unwrap();+ let signature = (ir_types(&ty.params).unwrap(), ir_types(&ty.results).unwrap());+ let trampoline = with_session(|session| session.trampoline(&signature));+ let mut slots = Vec::with_capacity(arguments.len());+ for argument in arguments {+ argument.push_slots(&mut slots);+ }+ let result_count = ty.results.iter().map(|result| result.slot_count() as usize).sum();+ let mut result_slots = vec![0u64; result_count];+ unsafe {+ let context: *mut ExecutionContext = (*self.data).context;+ (*context).stack_limit = lowest_stack_address() + 256 * 1024;+ (*context).store = (store as *mut Store).cast();+ }+ let function: extern "C" fn(u64, *const u64, *mut u64, *const InstanceData) -> u32 =+ unsafe { std::mem::transmute(trampoline) };+ let status = function(+ compiled.entries[index as usize],+ slots.as_ptr(),+ result_slots.as_mut_ptr(),+ self.data,+ );+ if status != 0 {+ return Outcome::Trap(with_session(|session| session.state.trap));+ }+ Outcome::Values(+ ty.results+ .iter()+ .scan(0, |slot, ty| {+ let value = Value::from_slots(*ty, &result_slots[*slot..]);+ *slot += ty.slot_count() as usize;+ Some(value)+ })+ .collect(),+ )+ }+}++/// The module function index of an engine function, if it is a WebAssembly function of `instance`.+pub fn function_index(+ store: &Store,+ address: libwasm_engine::runtime::FunctionAddress,+ instance: InstanceAddress,+) -> Option<u32> {+ match &store.function(address).kind {+ FunctionKind::Wasm {+ index, instance: owner, ..+ } if *owner == instance => Some(*index),+ _ => None,+ }+}++// Memory faults in compiled code become traps through the trap exit.++static INSTALL: std::sync::Once = std::sync::Once::new();+static mut PREVIOUS: libc::sigaction = unsafe { std::mem::zeroed() };++extern "C" fn handle_fault(signal: i32, info: *mut libc::siginfo_t, context: *mut libc::c_void) {+ unsafe {+ let context = context.cast::<libc::ucontext_t>();+ let pc = (*context).uc_mcontext.gregs[libc::REG_RIP as usize] as u64;+ let address = (*info).si_addr() as usize;+ let exit = CODE_RANGES.try_lock().ok().and_then(|ranges| {+ ranges+ .iter()+ .find(|(start, end)| pc >= *start && pc < *end)+ .map(|(start, _)| *start)+ });+ if let Some(start) = exit+ && libwasm_engine::runtime::memory::is_in_any_reservation(address)+ {+ // Every code space starts with its trap exit.+ (*context).uc_mcontext.gregs[libc::REG_RIP as usize] = start as i64;+ (*context).uc_mcontext.gregs[libc::REG_RDI as usize] =+ i64::from(libwasm_engine::abi::TRAP_MEMORY_OUT_OF_BOUNDS);+ return;+ }+ let previous = std::ptr::read(&raw const PREVIOUS);+ if previous.sa_flags & libc::SA_SIGINFO != 0 && previous.sa_sigaction > libc::SIG_IGN {+ let handler: extern "C" fn(i32, *mut libc::siginfo_t, *mut libc::c_void) =+ std::mem::transmute(previous.sa_sigaction);+ handler(signal, info, context.cast());+ return;+ }+ libc::signal(signal, libc::SIG_DFL);+ }+}++fn install_fault_handler() {+ INSTALL.call_once(|| unsafe {+ // NB: The engine's handler, which goes first if it is installed, forwards faults it does not know to us.+ let mut action: libc::sigaction = std::mem::zeroed();+ action.sa_sigaction = handle_fault as *const () as usize;+ action.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK;+ libc::sigemptyset(&raw mut action.sa_mask);+ libc::sigaction(libc::SIGSEGV, &raw const action, &raw mut PREVIOUS);+ });+}diff --git a/Libraries/LibWasm/JIT/tests/harness/script.rs b/Libraries/LibWasm/JIT/tests/harness/script.rsnew file mode 100644index 00000000000..54e4eecf3b9--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/harness/script.rs@@ -0,0 +1,478 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Runs the spec testsuite's scripts (the .json files wast2json makes, with their modules next to them) against two+//! stores, one where every call into a function the JIT compiled runs the compiled code, and one where the+//! interpreter runs everything, and compares results, traps, memories and globals after every call.++use super::{CompiledModule, Outcome, TestBinding, function_index};+use libwasm_engine::runtime::{ExternValue, InstanceAddress, Store, Trap, Value};+use libwasm_engine::types::{FuncType, GlobalType, Limits, MemoryType, RefType, TableType, ValType};+use libwasm_jit::Options;+use serde_json::Value as Json;+use std::collections::{BTreeSet, HashMap};+use std::path::{Path, PathBuf};+use std::rc::Rc;+use std::sync::Arc;++#[derive(Default)]+pub struct Totals {+ pub scripts: usize,+ pub modules: usize,+ pub functions: usize,+ pub compiled: usize,+ pub runnable: usize,+ pub exercised: usize,+ pub cases: usize,+ pub failures: usize,+ /// Calls that reached a function the JIT did not compile, after which the module is not compared any more.+ pub not_compiled: usize,+}++type Exports = HashMap<String, ExternValue>;++struct LoadedModule {+ name: Option<String>,+ interpreted: InstanceAddress,+ jit: InstanceAddress,+ compiled: CompiledModule,+ binding: TestBinding,+ diverged: bool,+}++pub fn trap_code(trap: &Trap) -> u32 {+ use libwasm_engine::abi::*;+ match trap {+ Trap::Unreachable => TRAP_UNREACHABLE,+ Trap::StackExhausted => TRAP_STACK_EXHAUSTED,+ Trap::MemoryOutOfBounds => TRAP_MEMORY_OUT_OF_BOUNDS,+ Trap::IntegerDivideByZero => TRAP_INTEGER_DIVIDE_BY_ZERO,+ Trap::IntegerOverflow => TRAP_INTEGER_OVERFLOW,+ Trap::InvalidConversion => TRAP_INVALID_CONVERSION,+ Trap::UndefinedElement => TRAP_UNDEFINED_ELEMENT,+ Trap::UninitializedElement => TRAP_UNINITIALIZED_ELEMENT,+ Trap::IndirectCallTypeMismatch => TRAP_INDIRECT_CALL_TYPE_MISMATCH,+ Trap::TableOutOfBounds => TRAP_TABLE_OUT_OF_BOUNDS,+ Trap::NullReference => TRAP_NULL_REFERENCE,+ Trap::CastFailure => TRAP_CAST_FAILURE,+ Trap::ArrayOutOfBounds => TRAP_ARRAY_OUT_OF_BOUNDS,+ Trap::UnalignedAtomic => TRAP_UNALIGNED_ATOMIC,+ Trap::ExpectedSharedMemory => TRAP_EXPECTED_SHARED_MEMORY,+ Trap::Host(_) => TRAP_RUNTIME,+ Trap::UncaughtException(_) => TRAP_UNCAUGHT_EXCEPTION,+ }+}++fn outcome(result: Result<Vec<Value>, Trap>) -> Outcome {+ match result {+ Ok(values) => Outcome::Values(values),+ Err(trap) => Outcome::Trap(trap_code(&trap)),+ }+}++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.+ (Value::Ref(x), Value::Ref(y)) => (*x == 0) == (*y == 0),+ _ => a == b,+ }+}++pub fn same_outcome(a: &Outcome, b: &Outcome) -> bool {+ match (a, b) {+ (Outcome::Values(a), Outcome::Values(b)) => {+ a.len() == b.len() && a.iter().zip(b).all(|(a, b)| same_value(a, b))+ }+ (Outcome::Trap(a), Outcome::Trap(b)) => a == b,+ _ => false,+ }+}++/// How the memories and globals of two instances of a module differ, if they do.+pub fn state_difference(+ interpreted_store: &Store,+ interpreted: InstanceAddress,+ jit_store: &Store,+ jit: InstanceAddress,+) -> Option<String> {+ let (a, b) = (interpreted_store.instance(interpreted), jit_store.instance(jit));+ for (x, y) in a.memories.iter().zip(&b.memories) {+ let (x, y) = (interpreted_store.memory(*x).bytes(), jit_store.memory(*y).bytes());+ if x != y {+ let position = x+ .iter()+ .zip(y)+ .position(|(p, q)| p != q)+ .unwrap_or(x.len().min(y.len()));+ return Some(format!("memories differ at {position}"));+ }+ }+ for (position, (x, y)) in a.tables.iter().zip(&b.tables).enumerate() {+ let (x, y) = (&interpreted_store.table(*x).elements, &jit_store.table(*y).elements);+ // NB: Elements are addresses too, so only whether they are null can be compared.+ if x.len() != y.len() || x.iter().zip(y).any(|(p, q)| (*p == 0) != (*q == 0)) {+ return Some(format!("table {position} differs"));+ }+ }+ for (position, (x, y)) in a.globals.iter().zip(&b.globals).enumerate() {+ let (x, y) = (interpreted_store.global(*x).get(), jit_store.global(*y).get());+ // NB: References are addresses, which differ between the stores.+ if !matches!(x, Value::Ref(_)) && !same_value(&x, &y) {+ return Some(format!("global {position}: interpreter {x:?}, JIT {y:?}"));+ }+ }+ None+}++/// An argument of a scripted call, if the JIT handles its type.+fn argument(json: &Json) -> Option<Value> {+ if json.get("type")?.as_str()? == "v128" {+ return vector_argument(json);+ }+ let value = json.get("value")?.as_str()?;+ Some(match json.get("type")?.as_str()? {+ "i32" => Value::I32(value.parse::<u32>().ok()? as i32),+ "i64" => Value::I64(value.parse::<u64>().ok()? as i64),+ "f32" => Value::F32(value.parse::<u32>().ok()?),+ "f64" => Value::F64(value.parse::<u64>().ok()?),+ _ => return None,+ })+}++/// A v128 argument of a scripted call: its lanes, as `lane_type` says.+fn vector_argument(json: &Json) -> Option<Value> {+ let lanes = json.get("value")?.as_array()?;+ let bits = match json.get("lane_type")?.as_str()? {+ "i8" => 8,+ "i16" => 16,+ "i32" | "f32" => 32,+ "i64" | "f64" => 64,+ _ => return None,+ };+ let mut vector = 0u128;+ for (index, lane) in lanes.iter().enumerate() {+ let lane = lane.as_str()?.parse::<u64>().ok()?;+ let mask = if bits == 64 { u64::MAX } else { (1 << bits) - 1 };+ vector |= u128::from(lane & mask) << (index * bits);+ }+ Some(Value::V128(vector))+}++/// The spectest module's instance in `store`.+fn spectest(store: &mut Store) -> HashMap<String, ExternValue> {+ let mut exports = HashMap::new();+ let print = |params: Vec<ValType>| FuncType {+ params,+ results: Vec::new(),+ };+ let nothing: libwasm_engine::runtime::HostCallback = Rc::new(|_: &mut Store, _: &[Value]| Ok(Vec::new()));+ for (name, params) in [+ ("print", vec![]),+ ("print_i32", vec![ValType::I32]),+ ("print_i64", vec![ValType::I64]),+ ("print_f32", vec![ValType::F32]),+ ("print_f64", vec![ValType::F64]),+ ("print_i32_f32", vec![ValType::I32, ValType::F32]),+ ("print_f64_f64", vec![ValType::F64, ValType::F64]),+ ] {+ let function = store.allocate_host_function(print(params), nothing.clone());+ exports.insert(name.to_string(), ExternValue::Function(function));+ }+ let global = |value, initial| (GlobalType { value, mutable: false }, initial);+ for (name, (ty, initial)) in [+ ("global_i32", global(ValType::I32, Value::I32(666))),+ ("global_i64", global(ValType::I64, Value::I64(666))),+ ("global_f32", global(ValType::F32, Value::F32(666.6f32.to_bits()))),+ ("global_f64", global(ValType::F64, Value::F64(666.6f64.to_bits()))),+ ] {+ let address = store.allocate_global(ty, initial);+ exports.insert(name.to_string(), ExternValue::Global(address));+ }+ let limits = |min, max| Limits {+ min,+ max: Some(max),+ address_type: libwasm_engine::types::AddressType::I32,+ shared: false,+ };+ if let Some(table) = store.allocate_table(+ TableType {+ element: RefType::FUNCREF,+ limits: limits(10, 20),+ },+ 0,+ ) {+ exports.insert("table".to_string(), ExternValue::Table(table));+ }+ if let Some(memory) = store.allocate_memory(MemoryType { limits: limits(1, 2) }) {+ exports.insert("memory".to_string(), ExternValue::Memory(memory));+ }+ exports+}++struct Script<'a> {+ directory: PathBuf,+ interpreted: Store,+ jit: Store,+ /// The exports of the registered modules, in both stores.+ registered: HashMap<String, (Exports, Exports)>,+ modules: Vec<LoadedModule>,+ current: Option<usize>,+ totals: &'a mut Totals,+ verbose: bool,+ name: String,+ options: Options,+}++impl Script<'_> {+ fn exports(store: &Store, instance: InstanceAddress) -> HashMap<String, ExternValue> {+ store.instance(instance).exports.clone()+ }++ fn load(&mut self, name: Option<String>, filename: &str) {+ self.current = None;+ let Ok(bytes) = std::fs::read(self.directory.join(filename)) else {+ return;+ };+ let Ok(module) = libwasm_engine::compile(&bytes) else {+ return;+ };+ let module = Arc::new(module);+ let mut interpreted_imports = Vec::new();+ let mut jit_imports = Vec::new();+ for import in &module.imports {+ let Some((interpreted, jit)) = self.registered.get(&import.module) else {+ return;+ };+ let (Some(interpreted), Some(jit)) = (interpreted.get(&import.name), jit.get(&import.name)) else {+ return;+ };+ interpreted_imports.push(*interpreted);+ jit_imports.push(*jit);+ }+ let Ok(interpreted) = self.interpreted.instantiate(module.clone(), &interpreted_imports) else {+ return;+ };+ let Ok(jit) = self.jit.instantiate(module.clone(), &jit_imports) else {+ return;+ };+ let compiled = CompiledModule::compile(module.clone(), self.options);+ let binding = TestBinding::new(&compiled, &self.jit, jit);+ let defined = module.code.len();+ self.totals.modules += 1;+ self.totals.functions += defined;+ let first = module.imported_function_count as usize;+ self.totals.compiled += compiled.entries[first..].iter().filter(|entry| **entry != 0).count();+ self.totals.runnable += compiled.runnable[first..].iter().filter(|runnable| **runnable).count();+ self.modules.push(LoadedModule {+ name,+ interpreted,+ jit,+ compiled,+ binding,+ diverged: false,+ });+ self.current = Some(self.modules.len() - 1);+ }++ fn module_index(&self, name: Option<&str>) -> Option<usize> {+ match name {+ Some(name) => self+ .modules+ .iter()+ .rposition(|module| module.name.as_deref() == Some(name)),+ None => self.current,+ }+ }++ /// Runs an action in both stores and compares what happened.+ fn act(&mut self, action: &Json, line: u64, exercised: &mut BTreeSet<(usize, u32)>) {+ let Some(index) = self.module_index(action.get("module").and_then(|module| module.as_str())) else {+ return;+ };+ let Some(field) = action.get("field").and_then(|field| field.as_str()) else {+ return;+ };+ let loaded = &self.modules[index];+ if loaded.diverged {+ return;+ }+ let interpreted_exports = Self::exports(&self.interpreted, loaded.interpreted);+ let jit_exports = Self::exports(&self.jit, loaded.jit);+ match action.get("type").and_then(|kind| kind.as_str()) {+ Some("invoke") => {+ let (Some(ExternValue::Function(interpreted)), Some(ExternValue::Function(jit))) =+ (interpreted_exports.get(field), jit_exports.get(field))+ else {+ return;+ };+ let Some(arguments) = action+ .get("args")+ .and_then(|arguments| arguments.as_array())+ .and_then(|arguments| arguments.iter().map(argument).collect::<Option<Vec<_>>>())+ else {+ return;+ };+ let expected = outcome(self.interpreted.invoke(*interpreted, &arguments));+ let loaded = &mut self.modules[index];+ let function = function_index(&self.jit, *jit, loaded.jit);+ let actual = match function {+ Some(function) if loaded.compiled.runnable[function as usize] => {+ exercised.insert((index, function));+ self.totals.cases += 1;+ Some(+ loaded+ .binding+ .call(&mut self.jit, &loaded.compiled, function, &arguments),+ )+ }+ _ => None,+ };+ let Some(actual) = actual else {+ // Not compiled: the interpreter runs it in the other store too, so that both stay the same.+ let _ = self.jit.invoke(*jit, &arguments);+ return;+ };+ if actual == Outcome::Trap(super::TRAP_NOT_COMPILED) {+ // The stores differ from here on.+ self.totals.not_compiled += 1;+ self.modules[index].diverged = true;+ return;+ }+ if !same_outcome(&expected, &actual) {+ self.fail(format!(+ "line {line}: {field}{arguments:?}: interpreter {expected:?}, JIT {actual:?}"+ ));+ return;+ }+ // NB: How deep the stack gets before it is exhausted differs, and so does what the code did on the way.+ if expected != Outcome::Trap(libwasm_engine::abi::TRAP_STACK_EXHAUSTED) {+ self.compare_state(index, line, field);+ }+ }+ Some("get") => {+ let (Some(ExternValue::Global(a)), Some(ExternValue::Global(b))) =+ (interpreted_exports.get(field), jit_exports.get(field))+ else {+ return;+ };+ let (a, b) = (self.interpreted.global(*a).get(), self.jit.global(*b).get());+ if !same_value(&a, &b) {+ self.fail(format!("line {line}: global {field}: interpreter {a:?}, JIT {b:?}"));+ }+ }+ _ => {}+ }+ }++ /// Compares the memories and globals of a module's instances in both stores.+ fn compare_state(&mut self, index: usize, line: u64, field: &str) {+ let loaded = &self.modules[index];+ if let Some(difference) = state_difference(&self.interpreted, loaded.interpreted, &self.jit, loaded.jit) {+ self.fail(format!("line {line}: {field}: {difference}"));+ }+ }++ fn fail(&mut self, message: String) {+ self.totals.failures += 1;+ println!("FAIL {}: {message}", self.name);+ }++ fn run(&mut self, script: &Json) {+ let mut exercised = BTreeSet::new();+ let Some(commands) = script.get("commands").and_then(|commands| commands.as_array()) else {+ return;+ };+ for command in commands {+ let line = command.get("line").and_then(|line| line.as_u64()).unwrap_or(0);+ match command.get("type").and_then(|kind| kind.as_str()) {+ Some("module") => {+ let name = command.get("name").and_then(|name| name.as_str()).map(String::from);+ if let Some(filename) = command.get("filename").and_then(|filename| filename.as_str()) {+ self.load(name, filename);+ }+ }+ Some("register") => {+ let Some(alias) = command.get("as").and_then(|alias| alias.as_str()) else {+ continue;+ };+ let name = command.get("name").and_then(|name| name.as_str());+ if let Some(index) = self.module_index(name) {+ let loaded = &self.modules[index];+ let exports = (+ Self::exports(&self.interpreted, loaded.interpreted),+ Self::exports(&self.jit, loaded.jit),+ );+ self.registered.insert(alias.to_string(), exports);+ }+ }+ Some("action" | "assert_return" | "assert_trap" | "assert_exhaustion") => {+ if let Some(action) = command.get("action") {+ self.act(action, line, &mut exercised);+ }+ }+ _ => {}+ }+ }+ self.totals.exercised += exercised.len();+ if self.verbose {+ println!("{}: {} functions exercised", self.name, exercised.len());+ }+ }+}++pub fn scripts(paths: &[String]) -> Vec<PathBuf> {+ let mut result = Vec::new();+ for path in paths {+ let path = PathBuf::from(path);+ if path.is_dir() {+ let mut entries = std::fs::read_dir(&path)+ .unwrap()+ .filter_map(|entry| entry.ok().map(|entry| entry.path()))+ .filter(|path| path.extension().is_some_and(|extension| extension == "json"))+ .collect::<Vec<_>>();+ entries.sort();+ result.extend(entries);+ } else {+ result.push(path);+ }+ }+ result+}++/// Runs every script of `paths` (scripts or directories of them).+pub fn run(paths: &[String], verbose: bool, options: Options) -> Totals {+ let mut totals = Totals::default();+ for path in scripts(paths) {+ let Ok(text) = std::fs::read_to_string(&path) else {+ continue;+ };+ let Ok(script) = serde_json::from_str::<Json>(&text) else {+ continue;+ };+ totals.scripts += 1;+ let mut interpreted = Store::new();+ let mut jit = Store::new();+ let spectest = (spectest(&mut interpreted), spectest(&mut jit));+ let mut registered = HashMap::new();+ registered.insert("spectest".to_string(), spectest);+ let mut runner = Script {+ directory: path.parent().unwrap_or(Path::new(".")).to_path_buf(),+ interpreted,+ jit,+ registered,+ modules: Vec::new(),+ current: None,+ totals: &mut totals,+ verbose,+ name: path.file_name().unwrap().to_string_lossy().into_owned(),+ options,+ };+ runner.run(&script);+ }+ totals+}diff --git a/Libraries/LibWasm/Module/Cargo.toml b/Libraries/LibWasm/Module/Cargo.tomlnew file mode 100644index 00000000000..6f42d9508e6--- /dev/null+++ b/Libraries/LibWasm/Module/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "libwasm_module"+version = "0.1.0"+edition = "2024"++[lib]+crate-type = ["rlib"]++[dependencies]++[lints]+workspace = truediff --git a/Libraries/LibWasm/Module/src/lib.rs b/Libraries/LibWasm/Module/src/lib.rsnew file mode 100644index 00000000000..90023fd7914--- /dev/null+++ b/Libraries/LibWasm/Module/src/lib.rs@@ -0,0 +1,40 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The WebAssembly module format: the binary decoder, the validator and its side tables, quickening, and the layout+//! the interpreter and compiled code share (`abi`). It is the part of the engine both the engine and the JIT depend+//! on. The sources stay with the engine's, which re-exports them.++#[path = "../../Engine/src/abi.rs"]+pub mod abi;+#[path = "../../Engine/src/error.rs"]+pub mod error;+#[path = "../../Engine/src/instruction_tables.rs"]+pub mod instruction_tables;+#[path = "../../Engine/src/module.rs"]+pub mod module;+#[path = "../../Engine/src/opcode.rs"]+pub mod opcode;+#[path = "../../Engine/src/parser.rs"]+pub mod parser;+#[path = "../../Engine/src/quickening.rs"]+pub mod quickening;+#[path = "../../Engine/src/reader.rs"]+pub mod reader;+#[path = "../../Engine/src/types.rs"]+pub mod types;+#[path = "../../Engine/src/validator.rs"]+pub mod validator;++pub use error::{Error, Result};+pub use module::Module;++/// Decode and validate a binary module.+pub fn compile(bytes: &[u8]) -> Result<Module> {+ let mut module = parser::parse(bytes)?;+ validator::validate(&mut module)?;+ Ok(module)+}diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex b9603929d4a..29e7c6c499c 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -51,6 +51,11 @@ IN_ONE_LIBRARY = {{"libweb_bindings_rust"},"a dependency of libweb_bindings_rust alone, whose archive LibWeb's library links",),+ "libwasm_engine": (+ {"libwasm_jit"},+ "a dev-dependency of libwasm_jit alone, whose tests run compiled code against it; the engine is the one Rust "+ "archive of LibWasm's library (Libraries/LibWasm/CMakeLists.txt)",+ ),}# libweb_rust: `file:name` -> why the state is fine on a thread other than the document's.