Skip to Content
V8-wasm

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 / Turboshaft

Narrow 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 via CallInterfaceDescriptor, 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::deque storage in TypeTable/ShapeTable to support arbitrary C/Fast-API signatures and f32/wasm64 value types.
  • Survey isolation ensures PushUniformBuiltinArgs emits zero constants for undeclared registers during register_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):

  1. 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.
  2. Multi-function module slabs (CodeDispatch::BatchScope): Installing one Wasm function per WebAssembly.Module pays a full OS VirtualMemory allocation (16 KiB on macOS arm64, 64 KiB on Windows), a ~2.5 KiB far jump table + I-cache flush, and a fresh WasmTrustedInstanceData. 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 distinct WebAssembly.Instance objects).
  3. Cached JS import table: Each thread caches its { v8 } import object in a WeakMap keyed by wasmExports, resolving table entries lazily from CodeRecord::function_import_indices instead of running WebAssembly.Module.imports() reflection on every install.
  4. Lock-free idle reclamation: Registry guards code-ID retirement with atomic published_epoch_ and published_requested_epoch_ counters so ThreadTable::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.
  • i64 bank: Dedicated 64-bit bank (kI64Bank) preserves 64-bit values such as code_start across C calls and enables pure 32-bit fast paths in Liftoff-wasm without 17-op pack/unpack round-trips.
  • f64 and v128 banks: SIMD128 local counts are patched in Assembler::End() via PatchSimd128LocalCount() only when SIMD registers are referenced, keeping scalar JS functions completely free of v128 locals.
  • Zero-redundant f32 lowering: LoadFp/StoreFp use i64.load32_u/i64.store32 and strip canceling f32/i32 reinterpret 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:

  • LoopUnrollingReducer sees a SwitchOp header and returns IterationCount::Unknown().
  • ValueNumberingReducer cannot CSE across sequential blocks because sibling switch arms do not dominate each other.
  • A single cold runtime call in any arm poisons LateLoadElimination for the entire function.
  • Every state transition executes a WasmStackCheck(kLoop) and flattens loop_depth to 1 during 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 on V8_TARGET_ARCH_WASM via a weak flag implication so functions tier directly from Ignition to structured Maglev/TurboFan (explicit --sparkplug and --always-sparkplug still enable Sparkplug cleanly). Emits linear single-pass Wasm bytecode with fused PrologueFillFrame, GC-safe new.target/context handoff, and BaselineBatchCompiler slab batching.
  • Maglev (src/maglev/wasm/): Implements all 110 IR codegen methods across 48 node classes, compiles eligible exception-handler-free functions (including OSR loops and CallSelf recursion) into whole-function structured Wasm CFG with shared out-of-line eager/lazy deopt stubs, tracks condition flags in kMaglevFlagsLocal, fuses Prologue/OSRPrologue with Wasm memory.fill for 4+ tagged slots, and emits BranchIfUnlikely on eager deopt and slow paths.
  • Fused SP prologues/epilogues & kHostStackLocal reuse: Host Turboshaft lowers mutable imported globals (__stack_pointer, v8_wasm_host_stack_used) to multiple memory loads per access. Fusing prologue and epilogue __stack_pointer adjustments into single global.set writes and reusing kHostStackLocal from BeginRestartFrameCatch cuts 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 exact HostFrameCharge() (derived from the function's actual call-shape parameter count and local frame cost) into the prologue/epilogue accounting against v8_wasm_host_stack_used.
  • StackOverflowCheck, Generate_InterpreterEntryTrampoline, Liftoff large-frame checks, and RegExp prologues all check unsigned wrap-safe linear stack bounds and PushHostStackAvailable(), entering StackFrame::INTERNAL before throwing from frameless stubs.
  • OSR entries (GenerateInterpreterDispatch) and Maglev deopt transitions call ReleaseHostFrame followed by a Wasm return_call tail-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-byte kSegmentStart relocation and indexed by CodeDispatch::ResumeSegmentForPc.
  • Entering a function with a non-zero v8_wasm_resume_segment global dispatches directly to the target segment via the entry switch, restoring register state (including masked live Simd128Register v128 locals saved across Deoptimizer::New on Wasm eager deopt).
  • TurboFan shares three out-of-line deopt stubs per function (eager, lazy, soft) rather than emitting ~80-byte inline AssembleDeoptimizationEntryCall sequences at every guard.
  • Fast API lazy-deopt checks explicitly test for RootIndex::kTerminationException and rethrow kExceptionTagIndex before clearing IsolateFieldId::kException, ensuring worker termination cannot be swallowed by guest try/catch.

On this page