6. Bytecode Virtual Machines

Compiling to and executing bytecode

A tree-walking interpreter is simple but slow — every operation pays the cost of recursive dispatch and pointer chasing through the AST. A bytecode VM eliminates that overhead by compiling the AST into a flat array of instructions (bytecode) and executing them in a tight loop. This is how CPython, Lua, Ruby (since 1.9), the JVM, and the CLR all work.

What is bytecode?

Bytecode is a sequence of instructions for a virtual machine. Each instruction is one or two bytes: an opcode (what to do) followed by an optional operand (what to do it to). It's called "bytecode" because the opcodes are typically single bytes — giving you up to 256 instruction types.

OP_CONST 0    // push constants[0] onto the stack
OP_CONST 1    // push constants[1] onto the stack
OP_ADD        // pop two values, push their sum
OP_RETURN     // return the top of the stack

The expression 2 + 3 compiles to exactly those four instructions (where constants[0] is 2 and constants[1] is 3).

The constant pool

Literal values don't live in the bytecode stream — they'd waste too much space. Instead, the compiler collects all literals into a side table called the constant pool (or constant table). The bytecode refers to constants by index.

class Chunk {
  constructor() {
    this.code = [];      // bytecode instructions
    this.constants = [];  // constant pool
  }

  addConstant(value) {
    this.constants.push(value);
    return this.constants.length - 1;  // return the index
  }

  emit(op, operand) {
    this.code.push(op);
    if (operand !== undefined) this.code.push(operand);
  }
}

The compiler

The compiler is an AST visitor that emits bytecode instead of computing values. It's structurally similar to the tree-walking evaluator, but instead of doing the operation, it emits an instruction for the operation:

function compile(node, chunk) {
  switch (node.type) {
    case 'NumberLiteral': {
      const idx = chunk.addConstant(node.value);
      chunk.emit(OP_CONST, idx);
      break;
    }

    case 'BinaryExpr': {
      compile(node.left, chunk);    // left operand → stack
      compile(node.right, chunk);   // right operand → stack
      switch (node.op) {
        case '+': chunk.emit(OP_ADD); break;
        case '-': chunk.emit(OP_SUB); break;
        case '*': chunk.emit(OP_MUL); break;
        case '/': chunk.emit(OP_DIV); break;
      }
      break;
    }

    case 'UnaryExpr': {
      compile(node.operand, chunk);
      if (node.op === '-') chunk.emit(OP_NEGATE);
      break;
    }
  }
}

The key insight: the order of instructions matches the post-order traversal of the AST. Compile left, compile right, emit the operator. The stack naturally arranges things so the operands are in the right place when the operator runs.

The virtual machine

A bytecode VM is a loop that reads and executes instructions one at a time. Most bytecode VMs are stack machines: operands are pushed onto a stack, operators pop their inputs and push their result.

class VM {
  constructor(chunk) {
    this.chunk = chunk;
    this.ip = 0;         // instruction pointer
    this.stack = [];
  }

  run() {
    while (this.ip < this.chunk.code.length) {
      const op = this.chunk.code[this.ip++];

      switch (op) {
        case OP_CONST: {
          const idx = this.chunk.code[this.ip++];
          this.stack.push(this.chunk.constants[idx]);
          break;
        }
        case OP_ADD: {
          const b = this.stack.pop();
          const a = this.stack.pop();
          this.stack.push(a + b);
          break;
        }
        case OP_SUB: {
          const b = this.stack.pop();
          const a = this.stack.pop();
          this.stack.push(a - b);
          break;
        }
        case OP_MUL: {
          const b = this.stack.pop();
          const a = this.stack.pop();
          this.stack.push(a * b);
          break;
        }
        case OP_DIV: {
          const b = this.stack.pop();
          const a = this.stack.pop();
          this.stack.push(a / b);
          break;
        }
        case OP_NEGATE: {
          this.stack.push(-this.stack.pop());
          break;
        }
        case OP_RETURN: {
          return this.stack.pop();
        }
      }
    }
  }
}

This is the entire execution engine. No recursion, no tree traversal, no pointer chasing — just a flat array and a single while loop with a switch.

Variables

Variables in a bytecode VM come in two flavors:

Local variables live on the stack. The compiler knows each local's stack position at compile time, so it emits OP_GET_LOCAL slot and OP_SET_LOCAL slot instructions that read and write stack slots by index — no name lookup at runtime.

Global variables live in a hash table. The compiler emits OP_GET_GLOBAL name and OP_SET_GLOBAL name instructions that look up variables by name at runtime.

Locals are faster (array index vs. hash lookup), which is why compilers try to make as many variables local as possible.

Control flow

Bytecode has no if or while — it has jumps. The compiler translates structured control flow into jump instructions:

// if (condition) { then } else { alt }

  ...condition...
  OP_JUMP_IF_FALSE  →  alt
  ...then branch...
  OP_JUMP           →  end
alt:
  ...else branch...
end:

The compiler doesn't know the jump target when it emits OP_JUMP_IF_FALSE (it hasn't compiled the then branch yet, so it doesn't know how long it is). It emits a placeholder and patches it after compiling the then branch. This is called backpatching.

compileIf(node, chunk) {
  compile(node.condition, chunk);

  // Emit jump with placeholder
  const jumpIfFalse = chunk.code.length;
  chunk.emit(OP_JUMP_IF_FALSE, 0xFF);

  // Compile then branch
  compileBlock(node.then, chunk);
  const jumpOver = chunk.code.length;
  chunk.emit(OP_JUMP, 0xFF);

  // Patch the false jump to land here
  chunk.code[jumpIfFalse + 1] = chunk.code.length;

  // Compile else branch
  if (node.else_) compileBlock(node.else_, chunk);

  // Patch the jump-over to land here
  chunk.code[jumpOver + 1] = chunk.code.length;
}

Loops are the same idea in reverse — the backward jump target is already known (it's the top of the loop), so no patching is needed for the loop-back jump.

Functions and call frames

When the VM calls a function, it pushes a call frame onto a separate frame stack. Each frame tracks:

  • Which chunk of bytecode it's executing
  • Its own instruction pointer
  • Where its local variables start on the value stack (the frame pointer)
class CallFrame {
  constructor(chunk, ip, framePointer) {
    this.chunk = chunk;
    this.ip = ip;
    this.fp = framePointer;
  }
}

OP_CALL pushes a new frame. OP_RETURN pops a frame and restores the caller's state. This is exactly how a real CPU's call stack works — the bytecode VM is a software simulation of a processor.

Why bytecode is faster

Compared to tree-walking:

  1. No recursion overhead: the VM loop is a flat while/switch, not mutually recursive function calls.
  2. No pointer chasing: bytecode is a contiguous array of bytes — great for CPU cache prefetching. AST nodes are heap-allocated objects scattered in memory.
  3. No type-tag checking on the instruction: each opcode directly maps to an action. The tree-walker has to switch on node type and operator type.
  4. Compact: bytecode is typically 2-10x smaller than the AST it was compiled from, which means less memory and better cache utilization.

The typical speedup over tree-walking is 3-10x for a naive implementation. Real-world VMs add further optimizations: computed gotos (replacing the switch), NaN boxing (packing values into 64 bits), inline caching, and eventually JIT compilation to native code.

The full pipeline

With the bytecode VM, the complete language pipeline is:

source → tokenize → parse → AST → compile → bytecode → VM → result

This is the architecture used by most production language implementations. The tree-walking interpreter from the previous article is a stepping stone — useful for prototyping and understanding — but when performance matters, bytecode is where you go.

Try It Yourself — Bytecode Debugger

Type a program, see it compiled to bytecode, then watch the VM execute it instruction by instruction. The trace shows the instruction pointer, each opcode, and the stack state after every step.

Compiled Bytecode

Constant Pool

Output

Execution Trace