Architecture
How V8-wasm compiles JavaScript to executable WebAssembly inside V8
WebAssembly enforces Harvard separation between linear memory and executable code: a Wasm module cannot jump into bytes written to linear memory. V8-wasm implements a dedicated wasm architecture backend inside V8 (src/codegen/wasm/, src/baseline/wasm/, src/maglev/wasm/, src/compiler/backend/wasm/, src/wasm/baseline/wasm/) that emits valid WebAssembly bytecode directly from V8's assemblers and installs it into the host browser's Wasm engine via WebAssembly.Module + WebAssembly.Instance.
Compilation Pipeline
JavaScript Source
│
▼
Ignition Bytecode (narrow 7-param Wasm handlers)
│ optional (--sparkplug) or direct tier-up (default)
▼
Maglev SSA JIT (whole-function structured Wasm CFG + memory.fill prologues)
│ sustained hot loops / OSR
▼
TurboFan / Turboshaft (O(V+E) Stackifier structured CFG + metadata.code.branch_hint)
│
▼
CodeDispatch::Install → Typed (ref $sig) Table → Host Chrome V8 Liftoff / TurboshaftNarrow 7-Parameter ABI and Call Shapes
Host V8's Liftoff compiler reserves register slot 0 for WasmTrustedInstanceData, leaving 5 GP + 6 FP parameter registers on x64 and 6 GP + 8 FP on arm64. Passing V8's entire virtual register file as a 31-parameter uniform signature forces an unrolled memory-to-memory PrepareTailCall copy loop on every return_call.
V8-wasm's call-shape system (call-shape-wasm.cc) replaces the uniform 31-parameter signature with descriptor-driven narrow call shapes:
- Ignition bytecode handlers pass only the registers specified by their interpreter descriptor (7 core parameters including accumulator
w0, bytecode array, offset, dispatch table, and frame state) instead of all 31 virtual registers. - JavaScript calls share one narrow JS linkage, with
kInterpreterAccumulatorRegister == w0 == kReturnRegister0. - Builtin and stub calls pass up to 5 register arguments (
w0,w1,w2,w3,w5) directly viaCallInterfaceDescriptor, matching host Liftoff's register budget without spilling 4-5 argument Torque/TFS builtins to linear memory. - On-demand C-call interning uses mutex-guarded
std::dequestorage inTypeTable/ShapeTableto support arbitrary C/Fast-API signatures andf32/wasm64value types. - Survey isolation ensures
PushUniformBuiltinArgsemits zero constants for undeclared registers duringregister_survey_, preventing a single cold uniform call from pulling all 32 virtual registers into a hot function's local bank.
Non-Null Typed call_ref Dispatch and Batched Code Slabs
Dynamic JIT code installation goes through CodeDispatch (src/codegen/wasm/code-dispatch-wasm.cc):
- Typed
(ref $sig)function tables: Dispatching through non-null typed function references eliminates both dynamic canonical signature checks and null checks in host Turboshaft (call_ref), while fixed-shape tables avoid dynamic length bounds loads. - Multi-function module slabs (
CodeDispatch::BatchScope): Installing one Wasm function perWebAssembly.Modulepays a full OSVirtualMemoryallocation (16 KiB on macOS arm64, 64 KiB on Windows), a ~2.5 KiB far jump table + I-cache flush, and a freshWasmTrustedInstanceData. Batching up to 64 functions per slab amortizes instantiation cost and unlocks host Turboshaft same-instance speculative inlining (Chrome's host compiler rejects speculative inlining across distinctWebAssembly.Instanceobjects). - Cached JS import table: Each thread caches its
{ v8 }import object in aWeakMapkeyed bywasmExports, resolving table entries lazily fromCodeRecord::function_import_indicesinstead of runningWebAssembly.Module.imports()reflection on every install. - Lock-free idle reclamation:
Registryguards code-ID retirement with atomicpublished_epoch_andpublished_requested_epoch_counters soThreadTable::Acknowledge()performs zero mutex acquisitions and zero heap allocations on idle ticks.
Lazy GP, i64, f64, and v128 Local Banks
Host Liftoff spills every local to the host stack if a function declares more than 4 non-parameter locals or declares any f64/v128/ref local. V8-wasm tracks register usage per function via WasmRegisterUse and emits local declarations lazily:
- GP bank: Only registers actually touched by the instruction stream (scanned across TurboFan instructions, parallel moves, and return locations in
AssembleCodeEntry()) are declared. i64bank: Dedicated 64-bit bank (kI64Bank) preserves 64-bit values such ascode_startacross C calls and enables pure 32-bit fast paths in Liftoff-wasm without 17-op pack/unpack round-trips.f64andv128banks: SIMD128 local counts are patched inAssembler::End()viaPatchSimd128LocalCount()only when SIMD registers are referenced, keeping scalar JS functions completely free ofv128locals.- Zero-redundant
f32lowering:LoadFp/StoreFpusei64.load32_u/i64.store32and strip cancelingf32/i32reinterpret round-trips.
Structured CFG Reconstruction and Branch Hinting
Early Wasm backends lowered arbitrary V8 CFGs into a flat top-level loop { block*N; br_table }. Inspection of host Chrome 154 Turboshaft reveals four severe penalties for flat br_table loops:
LoopUnrollingReducersees aSwitchOpheader and returnsIterationCount::Unknown().ValueNumberingReducercannot CSE across sequential blocks because sibling switch arms do not dominate each other.- A single cold runtime call in any arm poisons
LateLoadEliminationfor the entire function. - Every state transition executes a
WasmStackCheck(kLoop)and flattensloop_depthto1during register allocation.
V8-wasm reconstructs structured Wasm control flow (block/loop/if/br) via an O(V+E) Stackifier pass (TryAnalyzeBlockGraph + O(1) StructuredBranchDepth, capped cleanly below host V8's kV8MaxWasmFunctionControlDepth = 1000) in both TurboFan and Maglev (covering 70.5% of Octane 2.0 Maglev compiles including OSR loops and CallSelf recursion, with zero br_table loops and scoped forward/loop local labels), native Wasm loops in Irregexp (SkipUntilBitInTable, backreference checks), and structured branches in Liftoff write barriers.
Every Smi check, map check, overflow guard, write barrier, and eager deopt branch emits a Chrome 154 metadata.code.branch_hint custom section entry, mapping directly onto host Turboshaft BranchHint::kTrue and BranchHint::kFalse.
Sparkplug and Maglev Codegen
- Sparkplug (
src/baseline/wasm/): Disabled by default onV8_TARGET_ARCH_WASMvia a weak flag implication so functions tier directly from Ignition to structured Maglev/TurboFan (explicit--sparkplugand--always-sparkplugstill enable Sparkplug cleanly). Emits linear single-pass Wasm bytecode with fusedPrologueFillFrame, GC-safenew.target/context handoff, andBaselineBatchCompilerslab batching. - Maglev (
src/maglev/wasm/): Implements all 110 IR codegen methods across 48 node classes, compiles eligible exception-handler-free functions (including OSR loops andCallSelfrecursion) into whole-function structured Wasm CFG with shared out-of-line eager/lazy deopt stubs, tracks condition flags inkMaglevFlagsLocal, fusesPrologue/OSRProloguewith Wasmmemory.fillfor 4+ tagged slots, and emitsBranchIfUnlikelyon eager deopt and slow paths. - Fused SP prologues/epilogues &
kHostStackLocalreuse: Host Turboshaft lowers mutable imported globals (__stack_pointer,v8_wasm_host_stack_used) to multiple memory loads per access. Fusing prologue and epilogue__stack_pointeradjustments into singleglobal.setwrites and reusingkHostStackLocalfromBeginRestartFrameCatchcuts entry host-stack global reads from 3 down to 1 across both TurboFan and Maglev.
Host Stack Charging
Because V8-wasm maintains both a guest JS stack in linear memory (__stack_pointer) and a host Wasm call stack (capped at ~816 KiB on wasm32), deep recursion can overflow the host stack before hitting V8's linear-memory real_jslimit.
V8-wasm tracks host frame depth deterministically:
Assembler::End()patches each function's exactHostFrameCharge()(derived from the function's actual call-shape parameter count and local frame cost) into the prologue/epilogue accounting againstv8_wasm_host_stack_used.StackOverflowCheck,Generate_InterpreterEntryTrampoline, Liftoff large-frame checks, and RegExp prologues all check unsigned wrap-safe linear stack bounds andPushHostStackAvailable(), enteringStackFrame::INTERNALbefore throwing from frameless stubs.- OSR entries (
GenerateInterpreterDispatch) and Maglev deopt transitions callReleaseHostFramefollowed by a Wasmreturn_calltail-call so they never double-charge or pin a 1,254-byte host frame.
Deoptimization and Resume Segments
V8 deoptimization replaces an optimized frame with one or more unoptimized frames (Ignition, Sparkplug, or Liftoff) and resumes execution mid-function. WebAssembly has no arbitrary PC jump, so V8-wasm introduces resume segments:
- Each resume point (deopt continuation, OSR entry, Liftoff
deopt_resume) is marked with a zero-bytekSegmentStartrelocation and indexed byCodeDispatch::ResumeSegmentForPc. - Entering a function with a non-zero
v8_wasm_resume_segmentglobal dispatches directly to the target segment via the entry switch, restoring register state (including masked liveSimd128Registerv128locals saved acrossDeoptimizer::Newon Wasm eager deopt). - TurboFan shares three out-of-line deopt stubs per function (eager, lazy, soft) rather than emitting ~80-byte inline
AssembleDeoptimizationEntryCallsequences at every guard. - Fast API lazy-deopt checks explicitly test for
RootIndex::kTerminationExceptionand rethrowkExceptionTagIndexbefore clearingIsolateFieldId::kException, ensuring worker termination cannot be swallowed by guesttry/catch.