Ignition Interpreter and JS Bytecode Tutorial

Master V8's Ignition interpreter and its bytecode execution model. Covers the dispatch loop, handler table, register file layout, stack frame structure, exception handling, generator support, and how Ignition feeds data to TurboFan for optimization.

JavaScriptadvanced
17 min read

Ignition is V8's bytecode interpreter. It compiles JavaScript to compact bytecodes and executes them through a dispatch loop, collecting runtime type information that feeds into TurboFan's optimization pipeline. This guide covers how Ignition works internally.

For the bytecode format itself, see JavaScript Bytecode Explained: Complete Guide.

The Dispatch Loop

Ignition executes bytecode through a dispatch loop. For each instruction, it reads the opcode, jumps to the handler for that opcode, executes it, and advances to the next instruction.

javascriptjavascript
// Simplified model of Ignition's dispatch loop
class IgnitionInterpreter {
  #bytecode;
  #pc = 0; // Program counter
  #accumulator = undefined;
  #registers = [];
  #constantPool = [];
  #feedbackVector = [];
 
  constructor(bytecodeArray, constantPool, registerCount) {
    this.#bytecode = bytecodeArray;
    this.#constantPool = constantPool;
    this.#registers = new Array(registerCount).fill(undefined);
  }
 
  run() {
    while (this.#pc < this.#bytecode.length) {
      const opcode = this.#bytecode[this.#pc];
      this.#dispatch(opcode);
    }
    return this.#accumulator;
  }
 
  #dispatch(opcode) {
    // Each opcode has a handler
    // Real V8 uses computed goto or tail calls for speed
    switch (opcode) {
      case 0x01: this.#handleLdaSmi(); break;
      case 0x02: this.#handleStar(); break;
      case 0x03: this.#handleLdar(); break;
      case 0x04: this.#handleAdd(); break;
      case 0x05: this.#handleReturn(); break;
      case 0x06: this.#handleJumpIfFalse(); break;
      case 0x07: this.#handleLdaConstant(); break;
      default: throw new Error(`Unknown opcode: ${opcode}`);
    }
  }
 
  #handleLdaSmi() {
    // LdaSmi [immediate]: Load small integer into accumulator
    this.#pc++;
    this.#accumulator = this.#bytecode[this.#pc];
    this.#pc++;
  }
 
  #handleStar() {
    // Star rN: Store accumulator to register N
    this.#pc++;
    const regIndex = this.#bytecode[this.#pc];
    this.#registers[regIndex] = this.#accumulator;
    this.#pc++;
  }
 
  #handleLdar() {
    // Ldar rN: Load register N into accumulator
    this.#pc++;
    const regIndex = this.#bytecode[this.#pc];
    this.#accumulator = this.#registers[regIndex];
    this.#pc++;
  }
 
  #handleAdd() {
    // Add rN, [slot]: accumulator = accumulator + register[N]
    this.#pc++;
    const regIndex = this.#bytecode[this.#pc];
    this.#pc++;
    const feedbackSlot = this.#bytecode[this.#pc];
    this.#pc++;
 
    const left = this.#registers[regIndex];
    const right = this.#accumulator;
 
    // Record type feedback
    this.#recordFeedback(feedbackSlot, typeof left, typeof right);
 
    this.#accumulator = left + right;
  }
 
  #handleReturn() {
    // Return: stop execution, accumulator holds the result
    this.#pc = this.#bytecode.length; // End the loop
  }
 
  #handleJumpIfFalse() {
    this.#pc++;
    const offset = this.#bytecode[this.#pc];
    this.#pc++;
    if (!this.#accumulator) {
      this.#pc += offset;
    }
  }
 
  #handleLdaConstant() {
    this.#pc++;
    const index = this.#bytecode[this.#pc];
    this.#accumulator = this.#constantPool[index];
    this.#pc++;
  }
 
  #recordFeedback(slot, ...types) {
    if (!this.#feedbackVector[slot]) {
      this.#feedbackVector[slot] = new Set();
    }
    types.forEach((t) => this.#feedbackVector[slot].add(t));
  }
}

Register File Layout

javascriptjavascript
// Ignition's register file is a contiguous block on the stack
// Registers are accessed by index relative to the frame pointer
 
// STACK FRAME LAYOUT for a function call:
//
// โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” High address
// โ”‚ Return address             โ”‚
// โ”‚ Caller's frame pointer     โ”‚
// โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค <- Frame pointer (fp)
// โ”‚ Bytecode array pointer     โ”‚ fp - 8
// โ”‚ Feedback vector pointer    โ”‚ fp - 16
// โ”‚ Context pointer            โ”‚ fp - 24
// โ”‚ Parameter count            โ”‚ fp - 32
// โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
// โ”‚ Register r0                โ”‚ fp - 40
// โ”‚ Register r1                โ”‚ fp - 48
// โ”‚ Register r2                โ”‚ fp - 56
// โ”‚ ...                        โ”‚
// โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ Low address (stack grows down)
//
// Parameters (a0, a1...) are above the frame pointer
// Registers (r0, r1...) are below the frame pointer
 
// Example: function with 3 locals and 2 parameters
function example(x, y) {  // a0=x, a1=y
  const a = x + 1;        // r0
  const b = y * 2;        // r1
  const c = a + b;        // r2
  return c;
}
 
// Register allocation:
// a0 (parameter x) = fp + 16
// a1 (parameter y) = fp + 24
// r0 (local a)     = fp - 40
// r1 (local b)     = fp - 48
// r2 (local c)     = fp - 56
 
// V8 uses a special "register allocator" during bytecode generation
// that maps source-level variables to register indices
 
// ACCUMULATOR OPTIMIZATION
// The accumulator is a dedicated CPU register (not on the stack)
// Most bytecodes implicitly use the accumulator, saving
// explicit register operands and reducing bytecode size
 
// Without accumulator (hypothetical):
//   Add r0, r1, r2    // r2 = r0 + r1 (3 operands = more bytes)
 
// With accumulator (actual Ignition):
//   Ldar r0           // acc = r0
//   Add r1, [slot]    // acc = acc + r1 (2 operands = fewer bytes)
//   Star r2           // r2 = acc
 
// The accumulator pattern reduces bytecode size by ~25%

Exception Handling

javascriptjavascript
// Ignition implements try-catch-finally through handler tables
 
function safeParse(json) {
  try {
    const result = JSON.parse(json);
    return { ok: true, data: result };
  } catch (error) {
    return { ok: false, error: error.message };
  } finally {
    console.log("parse attempt complete");
  }
}
 
// HANDLER TABLE for safeParse:
//
// Range [start, end) -> handler_offset, context, prediction
// [10, 25)           -> 30 (catch handler), ctx2, CAUGHT
// [10, 40)           -> 45 (finally handler), ctx2, UNCAUGHT
//
// When an exception occurs:
// 1. V8 checks the handler table for the current bytecode offset
// 2. If offset falls in [start, end), jump to handler_offset
// 3. The exception object is placed in the accumulator
// 4. The catch block receives it as a local variable
 
// Bytecode (simplified):
//   10: LdaGlobal "JSON"                // try block starts
//   13: LdaNamedProperty <acc>, "parse"
//   16: CallProperty1 <acc>, a0         // JSON.parse(json)
//   20: Star0                            // result = ...
//       ...                              // Build return object
//   25: Return                           // Normal exit
//
//   30: Star1                            // catch: r1 = error
//   32: LdaNamedProperty r1, "message"   // error.message
//       ...                              // Build error object
//   38: Return
//
//   45: LdaGlobal "console"             // finally block
//   48: CallProperty1 <acc>, "log", <msg>
//   52: ReThrow                          // Re-throw if uncaught
 
// The handler table enables efficient try-catch without
// runtime overhead when no exception occurs
// Cost: only a table entry, no extra bytecodes in the happy path
 
// NESTED TRY-CATCH
function nested() {
  try {
    try {
      riskyOp1();
    } catch (e1) {
      riskyOp2(); // This can also throw
    }
  } catch (e2) {
    handleError(e2);
  }
}
 
// Handler table has entries for both levels:
// riskyOp1's range -> inner catch handler
// riskyOp2's range -> outer catch handler
// Exceptions bubble outward through the handler table

Generator and Async Support

javascriptjavascript
// Ignition handles generators with SuspendGenerator and ResumeGenerator
 
function* counter(start) {
  let current = start;
  while (true) {
    yield current;
    current++;
  }
}
 
// Bytecode for generator body (simplified):
//
// RESUME POINT 0 (initial):
//   Ldar a0                    // Load 'start' parameter
//   Star0                       // r0 = current = start
//
// LOOP:
//   Ldar r0                    // Load current
//   SuspendGenerator r<gen>, [0], 1  // Yield current; save state
//       // At this point, execution pauses
//       // The generator's registers are saved to the heap
//       // Control returns to the caller
//
// RESUME POINT 1 (after yield):
//   ResumeGenerator r<gen>     // Restore registers from heap
//   Ldar r0                    // Load current
//   Inc [1]                    // current++
//   Star0                       // Store back
//   Jump [LOOP]                // Loop back
 
// GENERATOR STATE MACHINE
// Each yield point creates a resume point
// SuspendGenerator saves: registers, accumulator, bytecode offset
// ResumeGenerator restores them and continues from the saved offset
 
// ASYNC/AWAIT is implemented as generators + promises
async function fetchData(url) {
  const response = await fetch(url);
  const data = await response.json();
  return data;
}
 
// V8 desugars this to something like:
function fetchData(url) {
  return new Promise((resolve, reject) => {
    const gen = (function* () {
      const response = yield fetch(url);    // Suspend, wait for fetch
      const data = yield response.json();    // Suspend, wait for json
      return data;
    })();
 
    function step(value) {
      const result = gen.next(value);
      if (result.done) resolve(result.value);
      else result.value.then(step, reject);
    }
    step();
  });
}
 
// The bytecodes are the same suspend/resume pattern
// but V8 wraps them in promise resolution machinery

Ignition to TurboFan Handoff

javascriptjavascript
// Ignition collects profiling data that tells TurboFan what to optimize
 
// The handoff process:
// 1. Function reaches "hot" threshold (call count + loop iterations)
// 2. V8 passes the bytecodes + feedback vector to TurboFan
// 3. TurboFan compiles in background while Ignition continues
// 4. When done, V8 patches the function to use TurboFan code
// 5. Next call executes optimized machine code
 
function hotFunction(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i]; // Feedback: always Smi + Smi -> Smi
  }
  return sum;
}
 
// Ignition execution timeline:
//
// Call 1-100:    Ignition interprets bytecode
//               Feedback vector accumulates type data:
//               - arr[i]: always Smi (PACKED_SMI_ELEMENTS)
//               - sum += arr[i]: always Smi Add
//               - arr.length: monomorphic IC on Array
//
// Call ~100:     V8 triggers TurboFan compilation (background)
//               Ignition CONTINUES executing while TurboFan works
//
// Call ~120:     TurboFan code ready
//               V8 patches hotFunction to point to machine code
//
// Call 121+:     Executes optimized machine code
//               - No type checks for Smi (speculative)
//               - Loop unrolled
//               - Bounds check eliminated
//               - Direct memory access for arr[i]
 
// ON-STACK REPLACEMENT (OSR)
// If Ignition is inside a long-running loop, V8 can replace
// the interpreter frame with a TurboFan frame mid-loop
 
function longLoop() {
  let total = 0;
  for (let i = 0; i < 10_000_000; i++) {
    total += i * i;
    // After ~10,000 iterations, V8 triggers OSR
    // The loop counter JumpLoop bytecode increments an OSR counter
    // When it exceeds the threshold, TurboFan compiles this function
    // V8 replaces the Ignition stack frame with a TurboFan frame
    // Loop continues from the current iteration in optimized code
  }
  return total;
}
Ignition FeaturePurposePerformance Impact
Dispatch loopExecute bytecodes sequentiallyBaseline execution speed
Register fileStore local variables on stackFast access (CPU register width)
AccumulatorImplicit operand for most operationsReduces bytecode size by ~25%
Handler tableMap exception ranges to handlersZero cost on happy path
Feedback vectorProfile types at each bytecodeEnables TurboFan optimization
Suspend/ResumeSupport generators and async/awaitHeap-allocated state on suspend
Rune AI

Rune AI

Key Insights

  • The dispatch loop reads opcodes and jumps to handlers, advancing the program counter after each instruction: This is the core execution mechanism, trading speed for fast compilation and compact bytecode
  • The register file stores local variables on the stack with an implicit accumulator reducing bytecode size: Most instructions use the accumulator implicitly, saving operand bytes in the instruction encoding
  • Handler tables map bytecode offset ranges to exception handlers with zero performance cost on the normal path: V8 only consults the handler table when an exception actually occurs
  • Generators and async functions use SuspendGenerator/ResumeGenerator to save and restore execution state: Register contents are copied to the heap on suspension and restored on resumption
  • Feedback vectors collected during interpretation are the critical input to TurboFan optimization: Every operation profiles its operand types, enabling TurboFan to generate type-specialized machine code
RunePowered by Rune AI

Frequently Asked Questions

How fast is Ignition compared to TurboFan-optimized code?

Ignition typically runs 10-100x slower than TurboFan-optimized machine code. The dispatch loop overhead (read opcode, jump to handler, execute, advance) adds cycles to every operation. TurboFan eliminates this by generating native CPU instructions. However, Ignition compiles 10x faster than TurboFan, so for functions called only a few times, the total time (compilation + execution) is lower with Ignition.

What triggers the transition from Ignition to TurboFan?

V8 uses a combination of invocation count and backward jump count (loop iterations). Each function has a "ticks" counter incremented on calls and loop back-edges. When ticks exceed a threshold (which varies by V8 version, currently around 1000-6000), V8 queues the function for TurboFan compilation. Functions with tight hot loops trigger OSR after roughly 10,000 iterations of the loop.

How does Ignition handle the arguments object?

When a function uses the `arguments` keyword, Ignition allocates an arguments object on the heap containing copies of all parameters. This is expensive because it requires heap allocation and copying. Rest parameters (`...args`) are more efficient because V8 creates a proper Array directly. Modern V8 can sometimes avoid creating the arguments object entirely if it detects that only specific indexed accesses are used (arguments[0], arguments[1]).

Does Ignition run on a separate thread?

No. Ignition runs on the main JavaScript thread (the same thread as your code). It is the main execution engine until TurboFan takes over for hot functions. TurboFan compilation happens on background threads, but the resulting optimized code still runs on the main thread. The single-threaded execution model ensures that JavaScript semantics (single-threaded, run-to-completion) are preserved.

Conclusion

Ignition is V8's bytecode interpreter that provides fast startup and runtime type profiling. The dispatch loop executes compact bytecodes efficiently. The register file stores locals on the stack. Handler tables implement exception handling with zero overhead on the happy path. Feedback vectors bridge the gap to TurboFan optimization. For the bytecode instruction set, see JavaScript Bytecode Explained: Complete Guide. For how TurboFan uses Ignition's feedback data, explore TurboFan Compiler and JS Optimization Guide.