Programming Search⌘K

Conceptcore

Bytecode

Also called byte code, p-code, portable code, intermediate code, virtual machine code.

Bytecode is a compact list of instructions for a virtual machine, which a program interprets one instruction at a time. A compiler produces it from the syntax tree, once, before the program runs.

Applies to
core-languages

Idea

A Tree-walking interpreter runs a program from its syntax tree. That is slow, because the nodes are separate objects scattered over the heap, and each step follows pointers and dispatches on the type of a node.2 Bytecode moves the work to an earlier point. A compiler walks the tree once and writes a flat, dense list of instructions. A virtual machine then runs the list in a loop.

The instruction set belongs to a machine that does not exist in hardware. It is an idealized instruction set that makes the work of the compiler writer easier, and a program written in a portable language, the virtual machine, emulates it one instruction at a time.1 In many formats each opcode fits in one byte, which gives bytecode its name.1 The Java Virtual Machine is an example. Its instructions are "a one-byte opcode specifying the operation to be performed, followed by zero or more operands".5

Bytecode sits between the two other ways to run a program. It keeps the portability of a tree-walker, because the virtual machine is an ordinary program. It is faster than a tree-walker, because the code is dense and linear, but it is slower than native machine code, because the emulation adds a layer.1

How it works

A stack machine

The bytecodes of the JVM and of .NET are designed for a stack machine. An instruction takes its operands from the top of a stack of values and pushes its result back. The JVM gives each method frame its own operand stack. Its iadd instruction pops two int values, adds them, and pushes the sum.4 The CIL of .NET works the same way: add pops two values and pushes the result onto the evaluation stack.11

An expression compiles to a stack machine in post-order. The compiler emits the code for the left operand, then for the right operand, then the operator. When the operator runs, the right operand is on top of the stack, so the first value it pops is the right one.13 a * b + c becomes LOAD a, LOAD b, MUL, LOAD c, ADD. No instruction names a temporary value, which keeps the instructions short.

Variables become slot numbers

A tree-walker looks up a variable by name in a chain of environments each time it runs. A bytecode compiler can resolve each name once, at compile time, to a slot number in the frame. The JVM records the number of local variable slots of each method, and the maximum depth of its operand stack, in the Code attribute of the class file.6

Jumps replace nested statements

A while loop has no nesting in bytecode. The compiler emits the condition, a conditional jump past the body, the body, and an unconditional jump back to the condition. The address of the exit is unknown when the compiler emits the conditional jump, so it writes a placeholder and patches it after the body.

The dispatch loop

The virtual machine is a loop. The JVM specification describes its inner loop in three steps: fetch an opcode, fetch its operands if it has any, and execute the action for the opcode.5 The program below is the whole pipeline: a compiler from a tree to bytecode, a disassembler, and the loop. The source program is the factorial loop that the Tree-walking interpreter page runs.

from enum import IntEnum


class Op(IntEnum):
    PUSH = 0
    LOAD = 1
    STORE = 2
    ADD = 3
    SUB = 4
    MUL = 5
    LT = 6
    JUMP_IF_FALSE = 7
    JUMP = 8
    PRINT = 9
    HALT = 10


HAS_ARG = {Op.PUSH, Op.LOAD, Op.STORE, Op.JUMP_IF_FALSE, Op.JUMP}
BINARY = {"+": Op.ADD, "-": Op.SUB, "*": Op.MUL, "<": Op.LT}


class Compiler:
    """Turns a tree of tuples into a flat list of numbers."""

    def __init__(self):
        self.code = []
        self.slots = {}  # variable name -> slot number, fixed at compile time

    def emit(self, op, arg=None):
        self.code.append(op)
        if arg is not None:
            self.code.append(arg)
        return len(self.code) - 1  # position of the last byte, used for patching

    def expr(self, node):
        match node:
            case ("num", value):
                self.emit(Op.PUSH, value)
            case ("var", name):
                self.emit(Op.LOAD, self.slots[name])
            case (op, left, right):
                self.expr(left)
                self.expr(right)
                self.emit(BINARY[op])

    def stmt(self, node):
        match node:
            case ("let", name, init):
                self.expr(init)
                slot = self.slots.setdefault(name, len(self.slots))
                self.emit(Op.STORE, slot)
            case ("set", name, value):
                self.expr(value)
                self.emit(Op.STORE, self.slots[name])
            case ("block", *body):
                for s in body:
                    self.stmt(s)
            case ("while", cond, body):
                start = len(self.code)
                self.expr(cond)
                hole = self.emit(Op.JUMP_IF_FALSE, 0)
                self.stmt(body)
                self.emit(Op.JUMP, start)
                self.code[hole] = len(self.code)  # patch the exit address
            case ("print", value):
                self.expr(value)
                self.emit(Op.PRINT)


def disassemble(code):
    pc = 0
    while pc < len(code):
        op = Op(code[pc])
        if op in HAS_ARG:
            print(f"{pc:4} {op.name:<13} {code[pc + 1]}")
            pc += 2
        else:
            print(f"{pc:4} {op.name}")
            pc += 1


def run(code, nslots):
    stack, slots, pc = [], [0] * nslots, 0
    executed = max_depth = 0
    while True:
        op = code[pc]
        executed += 1
        if op in HAS_ARG:
            arg = code[pc + 1]
            pc += 2
        else:
            pc += 1
        match op:
            case Op.PUSH:
                stack.append(arg)
            case Op.LOAD:
                stack.append(slots[arg])
            case Op.STORE:
                slots[arg] = stack.pop()
            case Op.ADD | Op.SUB | Op.MUL | Op.LT:
                b = stack.pop()  # the right operand is on top
                a = stack.pop()
                match op:
                    case Op.ADD:
                        stack.append(a + b)
                    case Op.SUB:
                        stack.append(a - b)
                    case Op.MUL:
                        stack.append(a * b)
                    case Op.LT:
                        stack.append(1 if a < b else 0)
            case Op.JUMP_IF_FALSE:
                if stack.pop() == 0:
                    pc = arg
            case Op.JUMP:
                pc = arg
            case Op.PRINT:
                print(stack.pop())
            case Op.HALT:
                return executed, max_depth
        max_depth = max(max_depth, len(stack))


# let n = 5; let acc = 1;
# while (0 < n) { let step = n; acc = acc * step; n = n - 1; }
# print acc;
program = ("block",
    ("let", "n", ("num", 5)),
    ("let", "acc", ("num", 1)),
    ("while", ("<", ("num", 0), ("var", "n")), ("block",
        ("let", "step", ("var", "n")),
        ("set", "acc", ("*", ("var", "acc"), ("var", "step"))),
        ("set", "n", ("-", ("var", "n"), ("num", 1))),
    )),
    ("print", ("var", "acc")),
)

compiler = Compiler()
compiler.stmt(program)
compiler.emit(Op.HALT)
disassemble(compiler.code)
executed, depth = run(compiler.code, len(compiler.slots))
print(f"bytes of code: {len(compiler.code)}")
print(f"instructions executed: {executed}, maximum stack depth: {depth}")
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2

The tree-walker on the other page visits 81 nodes for this program. The virtual machine executes a similar number of instructions. The gain is not in the count of steps but in their cost. Each instruction is a read from an array and one branch of the dispatch, with no recursive call. The tree-walker made 37 lookups by name that followed 25 parent links. The virtual machine makes no lookups by name, because the compiler replaced each name by a slot number.

In languages

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaNative
CIdiom
C#Native
JavaScriptIdiom
TypeScriptIdiom
GoIdiom
RustIdiom
KotlinNative
SQLDoes not applyA query language is not a host for a virtual machine with a loop over instructions.
BashIdiomAn indexed array can hold the code and a case statement inside a loop can run it, but every value is a string and each step is slow. Alternative: A virtual machine written in a general language, called from the script.
PowerShellIdiomAn array of integers can hold the code and a switch inside a loop can run it; no example file because PowerShell is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup does not execute instructions.
CSSDoes not applyStyle rules do not execute instructions.
Regular expressionsDoes not applyA pattern language has no arrays, loops or arithmetic to run instructions.

Some languages are defined, or always implemented, in terms of a bytecode, and their tools show it. In the others, a program that wants a bytecode builds one, as the examples do. Each example encodes the factorial program above as an array of numbers, disassembles it, runs it, and prints the same lines.

Language Verdict Form
Java native javac writes JVM bytecode into class files; javap -c disassembles them
Kotlin native the JVM target writes the same class files as Java
C# native the compiler writes CIL; ildasm disassembles it; MethodBody.GetILAsByteArray reads it at run time
Python stdlib CPython compiles each function to bytecode; the dis module disassembles it
JavaScript idiom the language defines no bytecode; V8 compiles functions to an internal register bytecode
TypeScript idiom as JavaScript; the type checker emits JavaScript, not bytecode
Go idiom compiles to machine code; a VM is an ordinary program
Rust idiom compiles to machine code; an enum of instructions or a byte array
C idiom compiles to machine code; a switch inside a loop
C++ idiom compiles to machine code; the same loop as C
PowerShell idiom a VM written as a script (no example: pwsh is not installed)
Bash idiom possible with arrays and a case statement, but slow
SQL n/a a query language, not a host for a VM
Regex n/a a pattern language
HTML/CSS n/a no execution

JVM. The JVM "knows nothing of the Java programming language, only of a particular binary format, the class file format". A class file holds JVM instructions, which the specification also calls bytecodes, and a symbol table. Any language that can be expressed as a valid class file can run on the JVM, which is how Kotlin runs there.3 Every class file starts with the magic number 0xCAFEBABE.18 javap disassembles class files, and its option -c prints the instructions of each method.8 The Java example compiles a small method at run time and calls javap on it.

CPython. CPython compiles every function to bytecode, and the dis module disassembles it. The documentation warns that bytecode "is an implementation detail of the CPython interpreter" and that instructions may be added, removed or changed between versions. Each instruction takes 2 bytes. The interpreter also adapts the bytecode at run time to specialize it, and dis shows the specialized form with adaptive=True.9 The Python example disassembles a function with dis; its output depends on the version of CPython that ran it.

.NET. A .NET compiler translates source code into common intermediate language (CIL), "a CPU-independent set of instructions". CIL has instructions for loads, stores, calls, arithmetic, control flow and exception handling. Before it runs, a just-in-time compiler usually converts it to native code.12 Ildasm.exe takes a portable executable file that contains IL and writes a text file that the IL assembler can read. It is installed with Visual Studio.10 A program can read the IL of its own methods with MethodBody.GetILAsByteArray.17 The C# example does this.

V8. V8's Ignition interpreter compiles JavaScript functions to a bytecode that is between 50% and 25% of the size of the equivalent baseline machine code. Ignition is a register machine with an accumulator, not a stack machine.16

PythonGitHub
from enum import IntEnum


class Op(IntEnum):
    PUSH = 0
    LOAD = 1
    STORE = 2
    ADD = 3
    SUB = 4
    MUL = 5
    LT = 6
    JUMP_IF_FALSE = 7
    JUMP = 8
    PRINT = 9
    HALT = 10


HAS_ARG = {Op.PUSH, Op.LOAD, Op.STORE, Op.JUMP_IF_FALSE, Op.JUMP}

# let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
# Slots: n = 0, acc = 1, step = 2.
code = bytes([
    0, 5, 2, 0, 0, 1, 2, 1,
    0, 0, 1, 0, 6, 7, 35,
    1, 0, 2, 2,
    1, 1, 1, 2, 5, 2, 1,
    1, 0, 0, 1, 4, 2, 0,
    8, 8,
    1, 1, 9, 10,
])

BINARY = {
    Op.ADD: lambda a, b: a + b,
    Op.SUB: lambda a, b: a - b,
    Op.MUL: lambda a, b: a * b,
    Op.LT: lambda a, b: 1 if a < b else 0,
}


def disassemble(code):
    pc = 0
    while pc < len(code):
        op = Op(code[pc])
        if op in HAS_ARG:
            print(f"{pc:4} {op.name:<13} {code[pc + 1]}")
            pc += 2
        else:
            print(f"{pc:4} {op.name}")
            pc += 1


def run(code, nslots):
    stack, slots, pc = [], [0] * nslots, 0
    executed = max_depth = 0
    while True:
        op = Op(code[pc])
        executed += 1
        arg = code[pc + 1] if op in HAS_ARG else None
        pc += 2 if op in HAS_ARG else 1
        if op is Op.PUSH:
            stack.append(arg)
        elif op is Op.LOAD:
            stack.append(slots[arg])
        elif op is Op.STORE:
            slots[arg] = stack.pop()
        elif op in BINARY:
            b = stack.pop()  # the right operand is on top
            a = stack.pop()
            stack.append(BINARY[op](a, b))
        elif op is Op.JUMP_IF_FALSE:
            if stack.pop() == 0:
                pc = arg
        elif op is Op.JUMP:
            pc = arg
        elif op is Op.PRINT:
            print(stack.pop())
        elif op is Op.HALT:
            return executed, max_depth
        max_depth = max(max_depth, len(stack))


disassemble(code)
executed, depth = run(code, 3)
print(f"bytes of code: {len(code)}")
print(f"instructions executed: {executed}, maximum stack depth: {depth}")
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2

The second program shows the bytecode that CPython itself made for a function. The instruction names and offsets depend on the version of CPython that recorded the output.

import dis
import sys


def fact(n):
    acc = 1
    while 0 < n:
        acc = acc * n
        n = n - 1
    return acc


print(f"fact(5) = {fact(5)}")
print(f"bytes of code: {len(fact.__code__.co_code)}")
print(f"local variables: {fact.__code__.co_varnames}")
print(f"version: {sys.version_info.major}.{sys.version_info.minor}")
dis.dis(fact)
Output
fact(5) = 120
bytes of code: 62
local variables: ('n', 'acc')
version: 3.14
  5           RESUME                   0

  6           LOAD_SMALL_INT           1
              STORE_FAST               1 (acc)

  7   L1:     LOAD_SMALL_INT           0
              LOAD_FAST_BORROW         0 (n)
              COMPARE_OP              18 (bool(<))
              POP_JUMP_IF_FALSE       20 (to L2)
              NOT_TAKEN

  8           LOAD_FAST_BORROW_LOAD_FAST_BORROW 16 (acc, n)
              BINARY_OP                5 (*)
              STORE_FAST               1 (acc)

  9           LOAD_FAST_BORROW         0 (n)
              LOAD_SMALL_INT           1
              BINARY_OP               10 (-)
              STORE_FAST               0 (n)
              JUMP_BACKWARD           26 (to L1)

 10   L2:     LOAD_FAST_BORROW         1 (acc)
              RETURN_VALUE
  • Verdict: stdlib. CPython compiles each function to bytecode in a code object, and the dis module in the standard library disassembles it.
  • The dis output shows a stack machine with numbered local slots. In the recorded output, LOAD_FAST_BORROW 0 (n) pushes local slot 0, and STORE_FAST 1 (acc) pops into slot 1, as LOAD and STORE do in the toy machine.
  • fact.__code__.co_code holds the raw bytes. The documentation calls the bytecode an implementation detail, so a program must not depend on the exact instructions.
  • A bytes object holds the toy program, so each opcode and each operand is one byte, as in co_code.
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <stdexcept>
#include <string_view>
#include <vector>

enum class Op : std::uint8_t { Push, Load, Store, Add, Sub, Mul, Lt, JumpIfFalse, Jump, Print, Halt };

constexpr std::array<std::string_view, 11> names{
    "PUSH", "LOAD", "STORE", "ADD", "SUB", "MUL", "LT", "JUMP_IF_FALSE", "JUMP", "PRINT", "HALT"};

constexpr bool has_arg(Op op) {
    return op == Op::Push || op == Op::Load || op == Op::Store || op == Op::JumpIfFalse || op == Op::Jump;
}

// let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
// Slots: n = 0, acc = 1, step = 2.
constexpr std::array<std::uint8_t, 39> code{
    0, 5, 2, 0, 0, 1, 2, 1,
    0, 0, 1, 0, 6, 7, 35,
    1, 0, 2, 2,
    1, 1, 1, 2, 5, 2, 1,
    1, 0, 0, 1, 4, 2, 0,
    8, 8,
    1, 1, 9, 10,
};

void disassemble(const auto& code) {
    for (std::size_t pc = 0; pc < code.size();) {
        auto op = static_cast<Op>(code[pc]);
        auto name = names.at(code[pc]);
        if (has_arg(op)) {
            std::printf("%4zu %-13.*s %d\n", pc, static_cast<int>(name.size()), name.data(), code[pc + 1]);
            pc += 2;
        } else {
            std::printf("%4zu %.*s\n", pc, static_cast<int>(name.size()), name.data());
            pc += 1;
        }
    }
}

struct Stats {
    int executed = 0;
    std::size_t max_depth = 0;
};

Stats run(const auto& code, std::size_t nslots) {
    std::vector<long> stack;
    std::vector<long> slots(nslots);
    auto pop = [&stack] {
        if (stack.empty()) throw std::runtime_error("stack underflow");
        long v = stack.back();
        stack.pop_back();
        return v;
    };
    Stats stats;
    std::size_t pc = 0;
    for (;;) {
        auto op = static_cast<Op>(code[pc]);
        ++stats.executed;
        std::size_t arg = has_arg(op) ? code[pc + 1] : 0;
        pc += has_arg(op) ? 2 : 1;
        switch (op) {
        case Op::Push: stack.push_back(static_cast<long>(arg)); break;
        case Op::Load: stack.push_back(slots[arg]); break;
        case Op::Store: slots[arg] = pop(); break;
        case Op::Add: case Op::Sub: case Op::Mul: case Op::Lt: {
            long b = pop(); // the right operand is on top
            long a = pop();
            stack.push_back(op == Op::Add ? a + b : op == Op::Sub ? a - b : op == Op::Mul ? a * b : a < b);
            break;
        }
        case Op::JumpIfFalse: if (pop() == 0) pc = arg; break;
        case Op::Jump: pc = arg; break;
        case Op::Print: std::printf("%ld\n", pop()); break;
        case Op::Halt: return stats;
        }
        stats.max_depth = std::max(stats.max_depth, stack.size());
    }
}

int main() {
    disassemble(code);
    Stats stats = run(code, 3);
    std::printf("bytes of code: %zu\n", code.size());
    std::printf("instructions executed: %d, maximum stack depth: %zu\n", stats.executed, stats.max_depth);
}
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2
  • Verdict: idiom. C++ compiles ahead of time to machine code, so the program builds its own bytecode.
  • enum class Op : std::uint8_t fixes the size of an opcode at one byte. static_cast<Op> turns a byte into an opcode without a check, so names.at does the range check in the disassembler.
  • pop checks for an empty stack and throws, where the C version reads out of bounds.
  • auto parameters make disassemble and run templates, so they take the std::array without a fixed length in the signature.
JavaGitHub
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    // The opcode numbers are the ordinals: PUSH = 0, LOAD = 1, ... HALT = 10.
    enum Op {
        PUSH(true), LOAD(true), STORE(true), ADD(false), SUB(false), MUL(false), LT(false),
        JUMP_IF_FALSE(true), JUMP(true), PRINT(false), HALT(false);

        final boolean hasArg;
        Op(boolean hasArg) { this.hasArg = hasArg; }
        static final Op[] ALL = values();
    }

    // let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
    // Slots: n = 0, acc = 1, step = 2.
    static final byte[] CODE = {
        0, 5, 2, 0, 0, 1, 2, 1,
        0, 0, 1, 0, 6, 7, 35,
        1, 0, 2, 2,
        1, 1, 1, 2, 5, 2, 1,
        1, 0, 0, 1, 4, 2, 0,
        8, 8,
        1, 1, 9, 10,
    };

    static void disassemble(byte[] code) {
        for (int pc = 0; pc < code.length; ) {
            Op op = Op.ALL[code[pc]];
            if (op.hasArg) {
                System.out.println(String.format("%4d %-13s %d", pc, op, code[pc + 1]));
                pc += 2;
            } else {
                System.out.println(String.format("%4d %s", pc, op));
                pc += 1;
            }
        }
    }

    public static void main(String[] args) {
        disassemble(CODE);
        Deque<Integer> stack = new ArrayDeque<>();
        int[] slots = new int[3];
        int pc = 0, executed = 0, maxDepth = 0;
        loop:
        for (;;) {
            Op op = Op.ALL[CODE[pc]];
            executed++;
            int arg = op.hasArg ? CODE[pc + 1] : 0;
            pc += op.hasArg ? 2 : 1;
            switch (op) {
                case PUSH -> stack.push(arg);
                case LOAD -> stack.push(slots[arg]);
                case STORE -> slots[arg] = stack.pop();
                case ADD, SUB, MUL, LT -> {
                    int b = stack.pop(); // the right operand is on top
                    int a = stack.pop();
                    stack.push(switch (op) {
                        case ADD -> a + b;
                        case SUB -> a - b;
                        case MUL -> a * b;
                        default -> a < b ? 1 : 0;
                    });
                }
                case JUMP_IF_FALSE -> { if (stack.pop() == 0) pc = arg; }
                case JUMP -> pc = arg;
                case PRINT -> System.out.println(stack.pop());
                case HALT -> { break loop; }
            }
            maxDepth = Math.max(maxDepth, stack.size());
        }
        System.out.println("bytes of code: " + CODE.length);
        System.out.println("instructions executed: " + executed + ", maximum stack depth: " + maxDepth);
    }
}
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2

The second program compiles a small class at run time with the compiler in javax.tools, then runs javap -c on the class file through java.util.spi.ToolProvider. Both tools ship with the JDK.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.spi.ToolProvider;
import java.util.stream.Stream;
import javax.tools.JavaCompiler;

public class Main {
    static final String SOURCE = """
        class Fact {
            static int fact(int n) {
                int acc = 1;
                while (0 < n) {
                    acc = acc * n;
                    n = n - 1;
                }
                return acc;
            }
        }
        """;

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("bytecode");
        try {
            Path src = dir.resolve("Fact.java");
            Files.writeString(src, SOURCE);
            JavaCompiler javac = javax.tools.ToolProvider.getSystemJavaCompiler();
            int status = javac.run(null, null, null, "-d", dir.toString(), src.toString());
            if (status != 0) throw new IllegalStateException("javac failed");

            byte[] bytes = Files.readAllBytes(dir.resolve("Fact.class"));
            System.out.printf("magic: %02X%02X%02X%02X%n", bytes[0], bytes[1], bytes[2], bytes[3]);

            ToolProvider javap = ToolProvider.findFirst("javap").orElseThrow();
            javap.run(System.out, System.err, "-c", dir.resolve("Fact.class").toString());
        } finally {
            try (Stream<Path> files = Files.walk(dir)) {
                files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
            }
        }
    }
}
Output
magic: CAFEBABE
Compiled from "Fact.java"
class Fact {
  Fact();
    Code:
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return

  static int fact(int);
    Code:
         0: iconst_1
         1: istore_1
         2: iconst_0
         3: iload_0
         4: if_icmpge     18
         7: iload_1
         8: iload_0
         9: imul
        10: istore_1
        11: iload_0
        12: iconst_1
        13: isub
        14: istore_0
        15: goto          2
        18: iload_1
        19: ireturn
}
  • Verdict: native. javac translates Java to JVM bytecode in class files, and the JVM runs that bytecode.
  • The JVM is a stack machine, as the javap output shows. iload_1 pushes local variable 1, imul pops two int values and pushes the product, and istore_1 pops into local 1. The method is static, so local 0 holds the argument n.
  • The JVM opcodes carry the type in their name: iload and imul work on int, dload and dmul on double. The toy machine has one type, so it needs only one LOAD and one MUL.
  • The VM uses an enum and an exhaustive switch. A byte in Java is signed, so an operand above 127 would need code[pc + 1] & 0xFF.
#include <stdio.h>
#include <stdlib.h>

enum op { PUSH, LOAD, STORE, ADD, SUB, MUL, LT, JUMP_IF_FALSE, JUMP, PRINT, HALT };

static const char *const names[] = {
    "PUSH", "LOAD", "STORE", "ADD", "SUB", "MUL", "LT", "JUMP_IF_FALSE", "JUMP", "PRINT", "HALT",
};

static int has_arg(unsigned char op) {
    return op == PUSH || op == LOAD || op == STORE || op == JUMP_IF_FALSE || op == JUMP;
}

/* let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
   Slots: n = 0, acc = 1, step = 2. */
static const unsigned char code[] = {
    PUSH, 5, STORE, 0, PUSH, 1, STORE, 1,
    PUSH, 0, LOAD, 0, LT, JUMP_IF_FALSE, 35,
    LOAD, 0, STORE, 2,
    LOAD, 1, LOAD, 2, MUL, STORE, 1,
    LOAD, 0, PUSH, 1, SUB, STORE, 0,
    JUMP, 8,
    LOAD, 1, PRINT, HALT,
};

static void disassemble(const unsigned char *code, size_t len) {
    for (size_t pc = 0; pc < len;) {
        if (has_arg(code[pc])) {
            printf("%4zu %-13s %d\n", pc, names[code[pc]], code[pc + 1]);
            pc += 2;
        } else {
            printf("%4zu %s\n", pc, names[code[pc]]);
            pc += 1;
        }
    }
}

enum { STACK_MAX = 16 };

static void run(const unsigned char *code, int *executed, int *max_depth) {
    long stack[STACK_MAX];
    long slots[3] = {0}; /* n, acc, step */
    int sp = 0; /* the number of values on the stack */
    size_t pc = 0;
    *executed = 0;
    *max_depth = 0;
    for (;;) {
        unsigned char op = code[pc];
        int arg = 0;
        ++*executed;
        if (has_arg(op)) {
            arg = code[pc + 1];
            pc += 2;
        } else {
            pc += 1;
        }
        switch (op) {
        case PUSH: stack[sp++] = arg; break;
        case LOAD: stack[sp++] = slots[arg]; break;
        case STORE: slots[arg] = stack[--sp]; break;
        case ADD: sp--; stack[sp - 1] = stack[sp - 1] + stack[sp]; break;
        case SUB: sp--; stack[sp - 1] = stack[sp - 1] - stack[sp]; break;
        case MUL: sp--; stack[sp - 1] = stack[sp - 1] * stack[sp]; break;
        case LT: sp--; stack[sp - 1] = stack[sp - 1] < stack[sp]; break;
        case JUMP_IF_FALSE: if (stack[--sp] == 0) pc = (size_t)arg; break;
        case JUMP: pc = (size_t)arg; break;
        case PRINT: printf("%ld\n", stack[--sp]); break;
        case HALT: return;
        default: fprintf(stderr, "bad opcode %d\n", op); exit(1);
        }
        if (sp > *max_depth) *max_depth = sp;
    }
}

int main(void) {
    int executed, max_depth;
    disassemble(code, sizeof code);
    run(code, &executed, &max_depth);
    printf("bytes of code: %zu\n", sizeof code);
    printf("instructions executed: %d, maximum stack depth: %d\n", executed, max_depth);
    return 0;
}
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2
  • Verdict: idiom. C compiles ahead of time to machine code, so the program builds its own bytecode.
  • The stack is a fixed array with an index sp. A binary operator pops one value and overwrites the new top in place, so it moves sp once instead of three times.
  • Nothing checks sp. Code that pops an empty stack reads before the array, which is undefined behaviour. A real VM verifies the code first, as the JVM does, or checks at run time.
  • The enum constants appear directly in the code array, so sizeof code gives the byte count without a separate length.
using System;
using System.Collections.Generic;

// let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
// Slots: n = 0, acc = 1, step = 2.
byte[] code = [
    0, 5, 2, 0, 0, 1, 2, 1,
    0, 0, 1, 0, 6, 7, 35,
    1, 0, 2, 2,
    1, 1, 1, 2, 5, 2, 1,
    1, 0, 0, 1, 4, 2, 0,
    8, 8,
    1, 1, 9, 10,
];

static bool HasArg(Op op) => op is Op.PUSH or Op.LOAD or Op.STORE or Op.JUMP_IF_FALSE or Op.JUMP;

for (int at = 0; at < code.Length; )
{
    var op = (Op)code[at];
    if (HasArg(op))
    {
        Console.WriteLine($"{at,4} {op,-13} {code[at + 1]}");
        at += 2;
    }
    else
    {
        Console.WriteLine($"{at,4} {op}");
        at += 1;
    }
}

var stack = new Stack<int>();
var slots = new int[3];
int pc = 0, executed = 0, maxDepth = 0;
bool running = true;
while (running)
{
    var op = (Op)code[pc];
    executed++;
    int arg = HasArg(op) ? code[pc + 1] : 0;
    pc += HasArg(op) ? 2 : 1;
    switch (op)
    {
        case Op.PUSH: stack.Push(arg); break;
        case Op.LOAD: stack.Push(slots[arg]); break;
        case Op.STORE: slots[arg] = stack.Pop(); break;
        case Op.ADD or Op.SUB or Op.MUL or Op.LT:
            int b = stack.Pop(); // the right operand is on top
            int a = stack.Pop();
            stack.Push(op switch
            {
                Op.ADD => a + b,
                Op.SUB => a - b,
                Op.MUL => a * b,
                _ => a < b ? 1 : 0,
            });
            break;
        case Op.JUMP_IF_FALSE: if (stack.Pop() == 0) pc = arg; break;
        case Op.JUMP: pc = arg; break;
        case Op.PRINT: Console.WriteLine(stack.Pop()); break;
        case Op.HALT: running = false; break;
        default: throw new InvalidOperationException($"bad opcode {op}");
    }
    maxDepth = Math.Max(maxDepth, stack.Count);
}
Console.WriteLine($"bytes of code: {code.Length}");
Console.WriteLine($"instructions executed: {executed}, maximum stack depth: {maxDepth}");

enum Op : byte { PUSH, LOAD, STORE, ADD, SUB, MUL, LT, JUMP_IF_FALSE, JUMP, PRINT, HALT }
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2

The second program reads the CIL of one of its own methods with MethodBody.GetILAsByteArray and decodes it with the OpCodes table from System.Reflection.Emit. The exact instructions depend on the compiler and on whether it optimized the build.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

var oneByte = new Dictionary<byte, OpCode>();
var twoByte = new Dictionary<byte, OpCode>();
foreach (var field in typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static))
{
    var opcode = (OpCode)field.GetValue(null)!;
    if (opcode.Size == 1) oneByte[(byte)opcode.Value] = opcode;
    else twoByte[(byte)(opcode.Value & 0xFF)] = opcode;
}

MethodInfo method = typeof(Fact).GetMethod(nameof(Fact.Compute))!;
byte[] il = method.GetMethodBody()!.GetILAsByteArray()!;
Console.WriteLine($"Fact.Compute(5) = {Fact.Compute(5)}");
Console.WriteLine($"bytes of IL: {il.Length}");

for (int pc = 0; pc < il.Length; )
{
    int start = pc;
    OpCode op = il[pc] == 0xFE ? twoByte[il[pc + 1]] : oneByte[il[pc]];
    pc += op.Size;
    string operand = "";
    switch (op.OperandType)
    {
        case OperandType.InlineNone:
            break;
        case OperandType.ShortInlineI:
            operand = ((sbyte)il[pc]).ToString();
            pc += 1;
            break;
        case OperandType.ShortInlineVar:
            operand = il[pc].ToString();
            pc += 1;
            break;
        case OperandType.ShortInlineBrTarget:
            operand = $"IL_{pc + 1 + (sbyte)il[pc]:X4}";
            pc += 1;
            break;
        case OperandType.InlineBrTarget:
            operand = $"IL_{pc + 4 + BitConverter.ToInt32(il, pc):X4}";
            pc += 4;
            break;
        case OperandType.InlineI:
            operand = BitConverter.ToInt32(il, pc).ToString();
            pc += 4;
            break;
        default:
            throw new NotSupportedException($"operand type {op.OperandType}");
    }
    Console.WriteLine($"IL_{start:X4}: {op.Name} {operand}".TrimEnd());
}

static class Fact
{
    public static int Compute(int n)
    {
        int acc = 1;
        while (0 < n)
        {
            acc = acc * n;
            n = n - 1;
        }
        return acc;
    }
}
Output
Fact.Compute(5) = 120
bytes of IL: 30
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0010
IL_0005: nop
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: mul
IL_0009: stloc.0
IL_000A: ldarg.0
IL_000B: ldc.i4.1
IL_000C: sub
IL_000D: starg.s 0
IL_000F: nop
IL_0010: ldc.i4.0
IL_0011: ldarg.0
IL_0012: clt
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brtrue.s IL_0005
IL_0018: ldloc.0
IL_0019: stloc.2
IL_001A: br.s IL_001C
IL_001C: ldloc.2
IL_001D: ret
  • Verdict: native. The C# compiler translates source code to CIL, and the runtime compiles the CIL to native code before it runs.
  • CIL is a stack machine, as the decoded method shows. ldarg.0 pushes the argument, mul pops two values and pushes the product, and stloc.0 pops into local 0.
  • Many CIL instructions have short forms. ldc.i4.1 pushes the constant 1 with no operand byte, and br.s takes a one-byte offset. The toy machine spends two bytes on each PUSH.
  • The VM casts each byte to the Op enum. A cast does not check the value, so a byte of 11 becomes an Op with no name, and the default case throws.
JavaScriptGitHub
const Op = Object.freeze({
  PUSH: 0, LOAD: 1, STORE: 2, ADD: 3, SUB: 4, MUL: 5, LT: 6,
  JUMP_IF_FALSE: 7, JUMP: 8, PRINT: 9, HALT: 10,
});
const NAMES = Object.keys(Op);
const HAS_ARG = new Set([Op.PUSH, Op.LOAD, Op.STORE, Op.JUMP_IF_FALSE, Op.JUMP]);

// let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
// Slots: n = 0, acc = 1, step = 2.
const code = Uint8Array.of(
  Op.PUSH, 5, Op.STORE, 0, Op.PUSH, 1, Op.STORE, 1,
  Op.PUSH, 0, Op.LOAD, 0, Op.LT, Op.JUMP_IF_FALSE, 35,
  Op.LOAD, 0, Op.STORE, 2,
  Op.LOAD, 1, Op.LOAD, 2, Op.MUL, Op.STORE, 1,
  Op.LOAD, 0, Op.PUSH, 1, Op.SUB, Op.STORE, 0,
  Op.JUMP, 8,
  Op.LOAD, 1, Op.PRINT, Op.HALT,
);

function disassemble(code) {
  for (let pc = 0; pc < code.length; ) {
    const name = NAMES[code[pc]];
    const at = String(pc).padStart(4);
    if (HAS_ARG.has(code[pc])) {
      console.log(`${at} ${name.padEnd(13)} ${code[pc + 1]}`);
      pc += 2;
    } else {
      console.log(`${at} ${name}`);
      pc += 1;
    }
  }
}

function run(code, nslots) {
  const stack = [];
  const slots = new Array(nslots).fill(0);
  let pc = 0, executed = 0, maxDepth = 0;
  for (;;) {
    const op = code[pc];
    executed++;
    let arg = 0;
    if (HAS_ARG.has(op)) {
      arg = code[pc + 1];
      pc += 2;
    } else {
      pc += 1;
    }
    switch (op) {
      case Op.PUSH: stack.push(arg); break;
      case Op.LOAD: stack.push(slots[arg]); break;
      case Op.STORE: slots[arg] = stack.pop(); break;
      case Op.ADD: case Op.SUB: case Op.MUL: case Op.LT: {
        const b = stack.pop(); // the right operand is on top
        const a = stack.pop();
        stack.push(op === Op.ADD ? a + b : op === Op.SUB ? a - b : op === Op.MUL ? a * b : a < b ? 1 : 0);
        break;
      }
      case Op.JUMP_IF_FALSE: if (stack.pop() === 0) pc = arg; break;
      case Op.JUMP: pc = arg; break;
      case Op.PRINT: console.log(stack.pop()); break;
      case Op.HALT: return { executed, maxDepth };
      default: throw new Error(`bad opcode ${op} at ${pc}`);
    }
    maxDepth = Math.max(maxDepth, stack.length);
  }
}

disassemble(code);
const { executed, maxDepth } = run(code, 3);
console.log(`bytes of code: ${code.length}`);
console.log(`instructions executed: ${executed}, maximum stack depth: ${maxDepth}`);
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2
  • Verdict: idiom. JavaScript defines no bytecode of its own. V8 compiles functions to an internal register bytecode, but a program cannot read it through the language.
  • A Uint8Array holds the code, so each opcode and each operand is one byte. An operand above 255 would need two bytes.
  • Object.freeze makes the opcode table read-only. Object.keys(Op) gives the names in the order of definition, which is also the order of the opcode numbers.
TypeScriptGitHub
const Op = {
  PUSH: 0, LOAD: 1, STORE: 2, ADD: 3, SUB: 4, MUL: 5, LT: 6,
  JUMP_IF_FALSE: 7, JUMP: 8, PRINT: 9, HALT: 10,
} as const;
type Opcode = (typeof Op)[keyof typeof Op];

const NAMES = Object.keys(Op) as (keyof typeof Op)[];
const HAS_ARG: ReadonlySet<number> = new Set([Op.PUSH, Op.LOAD, Op.STORE, Op.JUMP_IF_FALSE, Op.JUMP]);

// let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
// Slots: n = 0, acc = 1, step = 2.
const code: readonly number[] = [
  Op.PUSH, 5, Op.STORE, 0, Op.PUSH, 1, Op.STORE, 1,
  Op.PUSH, 0, Op.LOAD, 0, Op.LT, Op.JUMP_IF_FALSE, 35,
  Op.LOAD, 0, Op.STORE, 2,
  Op.LOAD, 1, Op.LOAD, 2, Op.MUL, Op.STORE, 1,
  Op.LOAD, 0, Op.PUSH, 1, Op.SUB, Op.STORE, 0,
  Op.JUMP, 8,
  Op.LOAD, 1, Op.PRINT, Op.HALT,
];

function disassemble(code: readonly number[]): void {
  for (let pc = 0; pc < code.length; ) {
    const name = NAMES[code[pc]];
    const at = String(pc).padStart(4);
    if (HAS_ARG.has(code[pc])) {
      console.log(`${at} ${name.padEnd(13)} ${code[pc + 1]}`);
      pc += 2;
    } else {
      console.log(`${at} ${name}`);
      pc += 1;
    }
  }
}

function binary(op: Opcode, a: number, b: number): number {
  switch (op) {
    case Op.ADD: return a + b;
    case Op.SUB: return a - b;
    case Op.MUL: return a * b;
    case Op.LT: return a < b ? 1 : 0;
    default: throw new Error(`not a binary opcode: ${op}`);
  }
}

function run(code: readonly number[], nslots: number): { executed: number; maxDepth: number } {
  const stack: number[] = [];
  const slots: number[] = new Array(nslots).fill(0);
  let pc = 0;
  let executed = 0;
  let maxDepth = 0;
  for (;;) {
    const op = code[pc] as Opcode;
    executed++;
    let arg = 0;
    if (HAS_ARG.has(op)) {
      arg = code[pc + 1];
      pc += 2;
    } else {
      pc += 1;
    }
    switch (op) {
      case Op.PUSH: stack.push(arg); break;
      case Op.LOAD: stack.push(slots[arg]); break;
      case Op.STORE: slots[arg] = stack.pop()!; break;
      case Op.ADD: case Op.SUB: case Op.MUL: case Op.LT: {
        const b = stack.pop()!; // the right operand is on top
        const a = stack.pop()!;
        stack.push(binary(op, a, b));
        break;
      }
      case Op.JUMP_IF_FALSE: if (stack.pop() === 0) pc = arg; break;
      case Op.JUMP: pc = arg; break;
      case Op.PRINT: console.log(stack.pop()); break;
      case Op.HALT: return { executed, maxDepth };
    }
    maxDepth = Math.max(maxDepth, stack.length);
  }
}

disassemble(code);
const { executed, maxDepth } = run(code, 3);
console.log(`bytes of code: ${code.length}`);
console.log(`instructions executed: ${executed}, maximum stack depth: ${maxDepth}`);
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2
  • Verdict: idiom. TypeScript compiles to JavaScript, so it has no bytecode of its own either.
  • as const keeps the literal opcode numbers in the type, and Opcode is the union 0 | 1 | ... | 10. A case with a number outside the union is a type error.
  • stack.pop()! asserts that the stack is not empty. The assertion is not checked at run time; a verifier, as in the main page's pitfall, would make it true.
package main

import "fmt"

type Op byte

// iota numbers the opcodes from 0: PUSH = 0, LOAD = 1, ... HALT = 10.
const (
	PUSH Op = iota
	LOAD
	STORE
	ADD
	SUB
	MUL
	LT
	JUMP_IF_FALSE
	JUMP
	PRINT
	HALT
)

var names = [...]string{"PUSH", "LOAD", "STORE", "ADD", "SUB", "MUL", "LT", "JUMP_IF_FALSE", "JUMP", "PRINT", "HALT"}

func (op Op) hasArg() bool {
	switch op {
	case PUSH, LOAD, STORE, JUMP_IF_FALSE, JUMP:
		return true
	}
	return false
}

// let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
// Slots: n = 0, acc = 1, step = 2.
var code = []byte{
	0, 5, 2, 0, 0, 1, 2, 1,
	0, 0, 1, 0, 6, 7, 35,
	1, 0, 2, 2,
	1, 1, 1, 2, 5, 2, 1,
	1, 0, 0, 1, 4, 2, 0,
	8, 8,
	1, 1, 9, 10,
}

func disassemble(code []byte) {
	for pc := 0; pc < len(code); {
		op := Op(code[pc])
		if op.hasArg() {
			fmt.Printf("%4d %-13s %d\n", pc, names[op], code[pc+1])
			pc += 2
		} else {
			fmt.Printf("%4d %s\n", pc, names[op])
			pc++
		}
	}
}

func run(code []byte, nslots int) (executed, maxDepth int) {
	stack := make([]int, 0, 16)
	slots := make([]int, nslots)
	pop := func() int {
		v := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		return v
	}
	pc := 0
	for {
		op := Op(code[pc])
		executed++
		arg := 0
		if op.hasArg() {
			arg = int(code[pc+1])
			pc += 2
		} else {
			pc++
		}
		switch op {
		case PUSH:
			stack = append(stack, arg)
		case LOAD:
			stack = append(stack, slots[arg])
		case STORE:
			slots[arg] = pop()
		case ADD, SUB, MUL, LT:
			b := pop() // the right operand is on top
			a := pop()
			var r int
			switch op {
			case ADD:
				r = a + b
			case SUB:
				r = a - b
			case MUL:
				r = a * b
			case LT:
				if a < b {
					r = 1
				}
			}
			stack = append(stack, r)
		case JUMP_IF_FALSE:
			if pop() == 0 {
				pc = arg
			}
		case JUMP:
			pc = arg
		case PRINT:
			fmt.Println(pop())
		case HALT:
			return executed, maxDepth
		default:
			panic(fmt.Sprintf("bad opcode %d at %d", op, pc))
		}
		maxDepth = max(maxDepth, len(stack))
	}
}

func main() {
	disassemble(code)
	executed, maxDepth := run(code, 3)
	fmt.Printf("bytes of code: %d\n", len(code))
	fmt.Printf("instructions executed: %d, maximum stack depth: %d\n", executed, maxDepth)
}
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2
  • Verdict: idiom. Go compiles ahead of time to machine code and has no bytecode, so the program builds its own.
  • A defined type Op byte with iota constants gives the opcodes names and keeps them one byte wide.
  • The stack is a slice. append pushes, and slicing off the last element pops. An empty stack makes pop panic with an index out of range.
RustGitHub
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
enum Op {
    Push, Load, Store, Add, Sub, Mul, Lt, JumpIfFalse, Jump, Print, Halt,
}

const OPS: [Op; 11] = [
    Op::Push, Op::Load, Op::Store, Op::Add, Op::Sub, Op::Mul, Op::Lt,
    Op::JumpIfFalse, Op::Jump, Op::Print, Op::Halt,
];
const NAMES: [&str; 11] = [
    "PUSH", "LOAD", "STORE", "ADD", "SUB", "MUL", "LT", "JUMP_IF_FALSE", "JUMP", "PRINT", "HALT",
];

impl Op {
    fn decode(byte: u8) -> Result<Op, String> {
        OPS.get(byte as usize).copied().ok_or(format!("bad opcode {byte}"))
    }
    fn has_arg(self) -> bool {
        matches!(self, Op::Push | Op::Load | Op::Store | Op::JumpIfFalse | Op::Jump)
    }
    fn name(self) -> &'static str {
        NAMES[self as usize]
    }
}

// let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
// Slots: n = 0, acc = 1, step = 2.
const CODE: [u8; 39] = [
    0, 5, 2, 0, 0, 1, 2, 1,
    0, 0, 1, 0, 6, 7, 35,
    1, 0, 2, 2,
    1, 1, 1, 2, 5, 2, 1,
    1, 0, 0, 1, 4, 2, 0,
    8, 8,
    1, 1, 9, 10,
];

fn disassemble(code: &[u8]) -> Result<(), String> {
    let mut pc = 0;
    while pc < code.len() {
        let op = Op::decode(code[pc])?;
        if op.has_arg() {
            println!("{pc:4} {:<13} {}", op.name(), code[pc + 1]);
            pc += 2;
        } else {
            println!("{pc:4} {}", op.name());
            pc += 1;
        }
    }
    Ok(())
}

fn run(code: &[u8], nslots: usize) -> Result<(usize, usize), String> {
    let mut stack: Vec<i64> = Vec::new();
    let mut slots = vec![0i64; nslots];
    let (mut pc, mut executed, mut max_depth) = (0usize, 0usize, 0usize);
    loop {
        let op = Op::decode(code[pc])?;
        executed += 1;
        let arg = if op.has_arg() { code[pc + 1] as usize } else { 0 };
        pc += if op.has_arg() { 2 } else { 1 };
        let mut pop = || stack.pop().ok_or(format!("stack underflow at {pc}"));
        match op {
            Op::Push => stack.push(arg as i64),
            Op::Load => stack.push(slots[arg]),
            Op::Store => slots[arg] = pop()?,
            Op::Add | Op::Sub | Op::Mul | Op::Lt => {
                let b = pop()?; // the right operand is on top
                let a = pop()?;
                stack.push(match op {
                    Op::Add => a + b,
                    Op::Sub => a - b,
                    Op::Mul => a * b,
                    _ => (a < b) as i64,
                });
            }
            Op::JumpIfFalse => {
                if pop()? == 0 {
                    pc = arg;
                }
            }
            Op::Jump => pc = arg,
            Op::Print => println!("{}", pop()?),
            Op::Halt => return Ok((executed, max_depth)),
        }
        max_depth = max_depth.max(stack.len());
    }
}

fn main() -> Result<(), String> {
    disassemble(&CODE)?;
    let (executed, max_depth) = run(&CODE, 3)?;
    println!("bytes of code: {}", CODE.len());
    println!("instructions executed: {executed}, maximum stack depth: {max_depth}");
    Ok(())
}
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2
  • Verdict: idiom. Rust compiles ahead of time to machine code and has no bytecode, so the program builds its own.
  • Op::decode returns a Result, so a byte that is not an opcode becomes an error value instead of an invalid enum. The match on Op has no default arm, and the compiler rejects it if a variant is missing.
  • pop returns an error on an empty stack, and ? passes the error up to main.
KotlinGitHub
// The opcode numbers are the ordinals: PUSH = 0, LOAD = 1, ... HALT = 10.
enum class Op(val hasArg: Boolean) {
    PUSH(true), LOAD(true), STORE(true), ADD(false), SUB(false), MUL(false), LT(false),
    JUMP_IF_FALSE(true), JUMP(true), PRINT(false), HALT(false),
}

// let n = 5; let acc = 1; while (0 < n) { let step = n; acc = acc * step; n = n - 1; } print acc;
// Slots: n = 0, acc = 1, step = 2.
val code = byteArrayOf(
    0, 5, 2, 0, 0, 1, 2, 1,
    0, 0, 1, 0, 6, 7, 35,
    1, 0, 2, 2,
    1, 1, 1, 2, 5, 2, 1,
    1, 0, 0, 1, 4, 2, 0,
    8, 8,
    1, 1, 9, 10,
)

fun disassemble(code: ByteArray) {
    var pc = 0
    while (pc < code.size) {
        val op = Op.entries[code[pc].toInt()]
        if (op.hasArg) {
            println("%4d %-13s %d".format(pc, op, code[pc + 1]))
            pc += 2
        } else {
            println("%4d %s".format(pc, op))
            pc += 1
        }
    }
}

fun main() {
    disassemble(code)
    val stack = ArrayDeque<Int>()
    val slots = IntArray(3)
    var pc = 0
    var executed = 0
    var maxDepth = 0
    while (true) {
        val op = Op.entries[code[pc].toInt()]
        executed++
        val arg = if (op.hasArg) code[pc + 1].toInt() else 0
        pc += if (op.hasArg) 2 else 1
        when (op) {
            Op.PUSH -> stack.addLast(arg)
            Op.LOAD -> stack.addLast(slots[arg])
            Op.STORE -> slots[arg] = stack.removeLast()
            Op.ADD, Op.SUB, Op.MUL, Op.LT -> {
                val b = stack.removeLast() // the right operand is on top
                val a = stack.removeLast()
                stack.addLast(
                    when (op) {
                        Op.ADD -> a + b
                        Op.SUB -> a - b
                        Op.MUL -> a * b
                        else -> if (a < b) 1 else 0
                    }
                )
            }
            Op.JUMP_IF_FALSE -> if (stack.removeLast() == 0) pc = arg
            Op.JUMP -> pc = arg
            Op.PRINT -> println(stack.removeLast())
            Op.HALT -> break
        }
        maxDepth = maxOf(maxDepth, stack.size)
    }
    println("bytes of code: ${code.size}")
    println("instructions executed: $executed, maximum stack depth: $maxDepth")
}
Output
   0 PUSH          5
   2 STORE         0
   4 PUSH          1
   6 STORE         1
   8 PUSH          0
  10 LOAD          0
  12 LT
  13 JUMP_IF_FALSE 35
  15 LOAD          0
  17 STORE         2
  19 LOAD          1
  21 LOAD          2
  23 MUL
  24 STORE         1
  26 LOAD          0
  28 PUSH          1
  30 SUB
  31 STORE         0
  33 JUMP          8
  35 LOAD          1
  37 PRINT
  38 HALT
120
bytes of code: 39
instructions executed: 86, maximum stack depth: 2

The second program reads its own class file. The Kotlin compiler for the JVM writes the same format as javac, so the file starts with the same magic number.

class Probe {
    fun twice(x: Int) = x * 2
}

fun main() {
    val bytes = Probe::class.java.getResourceAsStream("Probe.class")!!.use { it.readBytes() }
    println("magic: " + bytes.take(4).joinToString("") { "%02X".format(it) })
    println("twice(21) = ${Probe().twice(21)}")
}
Output
magic: CAFEBABE
twice(21) = 42
  • Verdict: native. On the JVM target, Kotlin compiles to class files that hold JVM bytecode, the same format that Java uses.
  • Op.entries turns an opcode number back into an enum constant. when over an enum needs no else branch when every constant has a case.
  • ArrayDeque from the Kotlin standard library serves as the operand stack, with addLast as push and removeLast as pop.
  • Register machines. In a register VM, an instruction names the slots of its inputs and its output. c = a + b becomes one instruction instead of four, with no pushes and pops. Each instruction is larger and harder to decode. Crafting Interpreters reports that Lua switched from a stack to a register instruction set for Lua 5.0 and noted a speed improvement. The book stays with a stack machine because register VMs are harder to write a compiler for.14
  • Measured tradeoff. Shi, Gregg, Beatty and Ertl translated JVM stack code into register code. The register form eliminated more than 47% of the executed VM instructions, and its code was about 25% larger. On a Pentium 4, the register machine took about 32.3% less time with a C switch for dispatch, and about 26.5% less with the more efficient threaded dispatch.15
  • Verification. A VM that loads code it did not produce must check it. The JVM verifies a class file before it runs it. After verification it knows, among other things, that there are no operand stack overflows or underflows.7
  • Just-in-time compilation. A VM can translate hot bytecode into machine code while the program runs. CIL is usually run this way.12 See Just-in-time compilation.

Pitfalls

Popping the operands in the wrong order

The compiler pushes the left operand first, so the right operand is on top. A VM that pops the left operand first swaps the operands of every operator that is not commutative.13 Addition and multiplication still give the right answers, so tests with only those operators do not find the bug.

This code runs but gives a wrong answer on purpose.

PUSH, SUB, PRINT, HALT = range(4)


def run(code):
    stack, pc = [], 0
    while True:
        op = code[pc]
        pc += 1
        if op == PUSH:
            stack.append(code[pc])
            pc += 1
        elif op == SUB:
            a = stack.pop()  # takes the right operand as the left one
            b = stack.pop()
            stack.append(a - b)
        elif op == PRINT:
            print(stack.pop())
        elif op == HALT:
            return


# 10 - 3: the compiler pushes the left operand first.
run([PUSH, 10, PUSH, 3, SUB, PRINT, HALT])
Output
-7

10 - 3 should be 7. The fix pops b, the right operand, first.

PUSH, SUB, PRINT, HALT = range(4)


def run(code):
    stack, pc = [], 0
    while True:
        op = code[pc]
        pc += 1
        if op == PUSH:
            stack.append(code[pc])
            pc += 1
        elif op == SUB:
            b = stack.pop()  # the right operand is on top
            a = stack.pop()
            stack.append(a - b)
        elif op == PRINT:
            print(stack.pop())
        elif op == HALT:
            return


# 10 - 3: the compiler pushes the left operand first.
run([PUSH, 10, PUSH, 3, SUB, PRINT, HALT])
Output
7

Trusting the bytecode

The VM assumes that the code was produced by a correct compiler. Bad code makes it pop from an empty stack. In Python that is an exception. In a VM written in C it reads memory below the stack, with no error at all.

This code raises IndexError, on purpose.

PUSH, ADD, PRINT, HALT = range(4)


def run(code):
    stack, pc = [], 0
    while True:
        op = code[pc]
        pc += 1
        if op == PUSH:
            stack.append(code[pc])
            pc += 1
        elif op == ADD:
            b = stack.pop()
            a = stack.pop()
            stack.append(a + b)
        elif op == PRINT:
            print(stack.pop())
        elif op == HALT:
            return


# A broken compiler forgot to push the left operand of 2 + 3.
run([PUSH, 3, ADD, PRINT, HALT])

The fix checks the code before it runs. The verifier below walks the instructions, tracks the depth of the stack, and rejects the code at the first instruction that would pop more values than the stack holds. It handles straight-line code only. A verifier for code with jumps must follow every path and check that the depths agree where paths meet, as the JVM's verifier does.7

PUSH, ADD, PRINT, HALT = range(4)
EFFECT = {PUSH: (0, 1), ADD: (2, 1), PRINT: (1, 0), HALT: (0, 0)}  # (pops, pushes)


def verify(code):
    """Check the stack depth of every instruction before anything runs."""
    depth, pc = 0, 0
    while pc < len(code):
        op = code[pc]
        pops, pushes = EFFECT[op]
        if depth < pops:
            raise ValueError(f"stack underflow at offset {pc}")
        depth += pushes - pops
        pc += 2 if op == PUSH else 1
    return depth


for code in ([PUSH, 2, PUSH, 3, ADD, PRINT, HALT], [PUSH, 3, ADD, PRINT, HALT]):
    try:
        verify(code)
        print("accepted")
    except ValueError as e:
        print(f"rejected: {e}")
Output
accepted
rejected: stack underflow at offset 2

Reading CPython bytecode as a stable format

Tools that read .pyc files or code objects break when CPython changes its instructions. The dis documentation says that no guarantee is made that bytecode will not be added, removed or changed between versions of Python.9 Use dis to learn and to debug. A tool that must work across versions should not depend on the exact instructions.

Cost

  • Size. Bytecode is dense. The example program is 39 bytes, against 22 objects with pointers for the tree. V8 reports that its bytecode is 25% to 50% of the size of baseline machine code.16
  • Dispatch. Each executed instruction costs one fetch and one indirect branch in the dispatch loop. A stack machine executes more instructions than a register machine for the same work, so it pays this cost more often.15
  • Locality. The instructions sit next to each other in memory, in the order that they run, which suits the CPU caches.12
  • Compile step. The compiler must walk the tree once before the first instruction runs.
  • Stack depth. The compiler knows the maximum depth of the operand stack of each method. The JVM determines it at compile time and stores it in the class file with the code of the method.46 The example needs a depth of 2.

History

  • 2005. Yunhe Shi, David Gregg, Andrew Beatty and M. Anton Ertl published "Virtual Machine Showdown: Stack Versus Registers" at VEE '05. They measured that register code eliminated more than 47% of executed VM instructions, at a cost of about 25% more code.15
  • 2016. The V8 team described Ignition, an interpreter for a register bytecode with an accumulator, built to execute code with less memory overhead than V8's baseline compiler.16

References

  1. Robert Nystrom, Crafting Interpreters, chapter 14, Chunks of Bytecode, 14.1.3 What is bytecode?
  2. Robert Nystrom, Crafting Interpreters, chapter 14, Chunks of Bytecode, 14.1.1 Why not walk the AST?
  3. The Java Virtual Machine Specification, Java SE 25 Edition, chapter 1, Introduction, 1.2 The Java Virtual Machine
  4. The Java Virtual Machine Specification, Java SE 25 Edition, chapter 2, The Structure of the Java Virtual Machine, 2.6.2 Operand Stacks
  5. The Java Virtual Machine Specification, Java SE 25 Edition, chapter 2, The Structure of the Java Virtual Machine, 2.11 Instruction Set Summary
  6. The Java Virtual Machine Specification, Java SE 25 Edition, chapter 4, The class File Format, 4.7.3 The Code Attribute (max_stack, max_locals)
  7. The Java Virtual Machine Specification, Java SE 25 Edition, chapter 4, The class File Format, 4.10 Verification of class Files
  8. The javap Command, Java SE 25 tool specifications, Synopsis and Options (-c)
  9. The Python Standard Library, dis, Disassembler for Python bytecode, Python 3.14, module introduction (CPython implementation detail; changes in 3.6 and 3.11)
  10. Microsoft Learn, Ildasm.exe (IL Disassembler), introduction
  11. Microsoft Learn, OpCodes.Add Field, Remarks (stack transitional behavior)
  12. Microsoft Learn, Managed execution process, Compile to CIL
  13. Robert Nystrom, Crafting Interpreters, chapter 15, A Virtual Machine, 15.3.1 Binary operators (the right operand is on top of the stack)
  14. Robert Nystrom, Crafting Interpreters, chapter 15, A Virtual Machine, Design Note, Register-Based Bytecode
  15. Yunhe Shi, David Gregg, Andrew Beatty and M. Anton Ertl, Virtual Machine Showdown, Stack Versus Registers, Proceedings of the 1st ACM/USENIX International Conference on Virtual Execution Environments (VEE '05), 2005, pages 153 to 163, Abstract; section 1, Introduction
  16. Ross McIlroy, Firing up the Ignition interpreter, V8 blog, 23 August 2016, paragraphs on bytecode size and on the register machine with an accumulator
  17. Microsoft Learn, MethodBody.GetILAsByteArray Method, Returns
  18. The Java Virtual Machine Specification, Java SE 25 Edition, chapter 4, The class File Format, 4.1 The ClassFile Structure (magic)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/PMBGFH/text.yaml