How Bun's ahead-of-time compiler works

bun compile compiles a whole TypeScript or JavaScript program, npm packages included, to machine code and adds it to a copy of the Bun runtime. The runtime is still JavaScriptCore: the same JSValue encoding, Structures, GC, arrays, strings and interpreter. The JITs are not in the binary. This is a description of what the compiler does instead of profiling, OSR exit, watchpoints and repatched inline caches.

November 2026. The feature is experimental. Everything below is in the public trees of oven-sh/WebKit (Source/JavaScriptCore/aot) and oven-sh/bun (src/aot, src/sema); most figures are taken from IR tests there and link to them.

Pipeline

Bun, in RustJavaScriptCore, in C++Loadresolve, parseCheckTypeScript typesLowerSSA, block parametersSSA IRScanper function,in parallel:a summaryLinkinterproceduralfixpoint oversummariesPlanlayouts, slots,conventions,code unitsWalkoptimizer; SCCs,callers first;builds CodeEmitisel, blocks,regalloc,encodingImagelink,tablesBun, in RustJavaScriptCore, in C++IRLoadresolve, parseCheckTypeScript typesLowerSSA, block parametersScanper-function summariesLinkfixpoint over summariesPlanlayouts, conventions, unitsWalkoptimizer, callers firstEmitisel, regalloc, encodingImagelink, write tables
The front end builds SSA during lowering. The optimizer is one stage, Walk, followed by a backward dead code sweep. JavaScript doesn't go through B3 or Air; machine/ does instruction selection, block ordering, register allocation and encoding for x64 and arm64. WebAssembly goes through OMG. There is no profile input, no execution of user code at build time, and no cache between builds. aot/README.md

The IR is defined in AOTSchema.def. Each operation row declares its result rule, the abstract heaps it reads and writes, whether it can throw, collect or run user code, and which facts it proves or relies on. It plays the part of clobberize, mayExit and doesGC together, and the C++ and Rust for both repositories are generated from it.

Vocabulary for a JSC reader

DFG / FTLAOT
CheckStructureShapeTest, a 32-bit compare on the cell
GetByOffset / PutByOffsetGetSlot / PutSlot
GetById with an ICPropGet: a shared stub plus a per-site data record
MultiGetByOffsetone offset for the name across a union, or dispatch on the shape
CheckArray, ArrayModeIsPristine, HasArrayStorage
call variants, CheckIsConstantCallDirect, CallTable, IsClosureOf
CFA / abstract interpreterLink across functions, the walk's state within one
OSR exita generic arm, a second loop version, or SlowBody
watchpointa guard bit in memory that the code tests, or a frozen object
store barrier insertionBarrierEmitter::decide()
object allocation sinkingescape analysis in the walk; cells in the machine frame

Link: whole-program types

Scan reduces each function to a summary with no locals in it. Link runs a fixpoint over the summaries of all reachable functions. Its nodes are parameters, results, captures, module variables, the fields of each layout, and the Element, Key and Value contents of containers. A lattice value carries primitive bits with an integer range, a layout or set of layouts, and a function or set of functions. Each part widens to a top independently.

A field whose writers are all known gets the join of what they store as its proven type, and that type picks its slot representation. If an object of the layout escapes to code the build can't see, its fields go to anything.

Compiled programUnknown codepair = { x: 1.5, y: "two" }all stores visible32-byte cell, proven typesno extra-properties wordout = { p: 2.5, q: "three" }sink(out)48-byte cell, any value,extra-properties wordescapes through sink():may store any value· eval, new Function, node:vm· import() of a computed path· uncompiled modules· native addons, FFI· the inspector
Escape is tracked per layout. IR tests: cell layouts, escaping field.

Code from a string is parsed and run by LLInt in the same process on the same objects. There is no JIT behind it, so a library that generates its hot code with new Function runs slower than under bun run. One case is handled statically: if the build can evaluate the string from constants, it compiles the function and uses it when the run-time string matches.

Frozen built-ins

DFG can assume Array.prototype.push is the original because it can jettison the code when a watchpoint fires. AOT code can't be jettisoned, so the assumption is enforced: existing members of built-in prototypes and constructors are read-only, and so is what the language looks up implicitly.

Throws a TypeError

  • Array.prototype.push = f
  • delete Array.prototype.push
  • Object.prototype.extra = 1
  • Array.prototype[0] = 1
  • Array.prototype.then = f
  • globalThis.Array = List

Allowed

  • Array.prototype.last = f
  • Array.prototype.at ??= at
  • class List extends Array {}
  • Math.random = f
  • JSON.parse = f
  • globalThis.Promise = Bluebird

If the store is on every path from entry the build fails. Commonly patched functions (Date.now, Math.random, JSON.parse, fetch, timers, console) stay writable as long as the build can see the write. Compatibility page.

User-defined classes aren't frozen. Redefining a method clears a guard bit for that class and name and updates the method table. Code that resolved the method statically tests the bit (AreMembersUnchanged, which reads the MemberGuards heap), so the test hoists and CSEs like any other read.

TypeScript types are speculations

A declared type never removes a check. A value's type is proven by its definition, by a dominating check, by Link, or by what direct callers have proven about an argument. Declared types, and for JavaScript the types the checker infers, only choose what to speculate on. Every access has a knowledge level.

Proven

load [p+16]

No check.

Expected

isCell p
cmp  [p+12], shape
bne  generic
load [p+16]

Checked, hoisted if the loop allows it.

Unknown

call stub
  (p, site)

By-name lookup through the site cache.

Expectations also come from uses. If a loop reads several names off an untyped value and exactly one record layout in the program has all of them, that layout is speculated. The exception to "never trusted" is int32 from "bun": the build must prove every store in range, or it reports an error.

What a failed check does

There is no baseline frame to reconstruct, so there are no OSR exit value recoveries and no stack of exit sites. The failing edge goes to other compiled code. The compiler uses three shapes for it:

Diamond

ShapeTestGetSlotPropGetcontinue

Loop versions

typedversionsecondversionloop exit

Function versions

ParameterGuardBodySlowBodytail calls
The diamond's cost is the join: the generic arm clobbers the world and its result is a JSValue, so facts and unboxed representations are lost after it. The other two shapes avoid the join.

Function versions

When a body leans on declared parameter types and callers outside the program's view exist, the function gets three code units:

class Point { x = 1; y = 2; }
function area(point: Point, scale: number): number {
  const across = point.x * scale;
  const down = point.y * scale;
  return across * down + point.x;
}

ParameterGuard

(JSValue, JSValue)

TypeTest point, undefined|null|Point, then TypeTest scale, number, then Unbox. No frame and no stack check. The passing path falls through into Body.

Body

(JSValue, Double)

One RequireObjectCoercible, then GetSlot and double multiplies. No type checks.

SlowBody

(JSValue, JSValue)

PropGet and Mul form=Generic throughout. No speculation.

Callers that have already proven the argument types call Body directly and pass scale in an FPR. IR test: guard-fast-version-and-slow-version.

Loop versions and iteration restart

A loop that depends on speculation is compiled twice. The typed version has no generic arms, so nothing in it clobbers the checks and loads that were hoisted above it, and the induction values and reductions stay unboxed. A check inside it that fails has to leave the version.

It leaves by restarting the current iteration. If nothing observable has happened since the loop header, the failing edge passes the header's loop-carried values to the entry of the second version, which executes that iteration from the beginning. A store to a slot whose previous value is at hand doesn't block this: the edge stores the old value back first.

function tally(items: Item[]) {
  let total = 0;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    item.seen = item.seen + 1;
    total += item.price * items[0].count;
  }
  return total;
}
Typed versionSecond versionhead(sum: Double, i)item = GetArrayElement items, iShapeTest itemold = GetSlot item.seenPutSlot item.seen = old + 1TypeTest price, count: numbersum = sum + price * countundo:seen = oldentry(sum, i)re-executes iterationi from the headerand runs the restof the loopTyped versionhead(sum: Double, i)item = items[i]ShapeTest itemold = GetSlot item.seenPutSlot item.seen=old+1TypeTest price, countsum = sum + price*countPutSlot item.seen = oldSecond versionentry(sum, i)re-executes iteration i from theheader, then runs the rest ofthe loop
The second version keeps speculating, with diamonds, and execution doesn't return to the typed one. IR test: test-that-fails-behind-a-store.

After an observable effect, such as a store to a module variable or a call, a restart would repeat it, so checks past that point get a diamond instead. Whether an iteration is restartable is computed from the declared effects. The test switch CheckEffectsAtRunTime compiles in a dynamic check that a restarted iteration performed no effects.

Loop optimizations

Hoisting

An object's shape word is written once, so a ShapeTest on an invariant object hoists. In the typed version its field reads hoist as well, because the only potential writers were the generic arms.

Unswitching

When several array kinds or layouts reach a loop, the kind is tested in the preheader and each gets its own version.

Bounds checks

The header compares the induction variable with min(bound, length), so accesses under it are unchecked.

Unrolling

Counted loops are unrolled by 8 (turnsLaidOut in AOTCodeGenerator.cpp) with the original loop as the remainder. Small constant trip counts are fully unrolled in the walk, which then folds through them. Reductions over numbers stay in an FPR.

Choosing code size without a profile

Static position is the only frequency information. Every operation has up to three forms, and the schema states which one it takes in which kind of block.

Open

Inline fast path. Used in loops.

Closed

Call to a shared stub. Used in unlikely and rare blocks and run-once code.

Runtime

Call to a C++ operation.

Example rows: form = Closed ; openIn = Loop ; closedIn = UnlikelyBlock, RareBlock. A build counts the sites where an emitter disagreed with its row. operations.def

Object layout

A compiled object is AOT::Object, a JSObject with its own Structure subclass (CompiledStructure) and overridden property hooks, so the rest of JSC, N-API and the interpreter can use it. There is no butterfly pointer. Bytes 8 to 15 hold an order word (key order index, property count, frozen / sealed / non-extensible bits) and a shape word, the layout's program-wide number. The layouts of a declared union get consecutive numbers, so testing membership is a range check.

plain JSObject

header0
butterfly8
JSValue16
JSValue24

pair { x, y }

header0
order8
shape12
x16
y24

out { p, q }

header0
order8
shape12
extra16
p24
q32
Byte offsets. Link proves pair never gets another property, so it has no extra-properties word; if that turns out to happen, the object transitions to a Structure of its own. Arrays are unchanged JSArrays with Int32, Double or Contiguous butterflies.

Field types are enforced at stores

A store that isn't proven to match the field's type checks it, including stores from the interpreter and C++. On a mismatch the property leaves its slot and moves to the extra properties of that one object. A read that can't prove the slot filled tests for the absent marker.

label: "a"
slot"a"
extranone
h.label = 5
slotabsent
extralabel: 5
h.label = "b"
slot"b"
extraflag stays set
The test does this through Reflect.set, Proxy, Object.assign, defineProperty and delete.

Value representations

JSValue is unchanged. The walk also picks a representation per SSA value, parameter, result and slot: Boolean, Int32, Int64, Double, OptionalInt64, OptionalDouble, Cell, Cell32 or JSValue. Slots have narrower ones.

1 byte
BooleanInt8Uint8
2 bytes
Int16Uint16
4 bytes
Int32Uint32FloatCell32DeferredClosure
8 bytes
Int64DoubleCellJSValue
The Optional forms encode undefined, null and absent in bit patterns a purified number can't have; for OptionalDouble they are three NaN payloads. Cell32 is a 32-bit cell reference relative to a reserved cage, which limits a thread to 32 GB of objects; --aot-huge-heap uses 64-bit references. AOTSlotRepresentation.h

Calls

Callee knownCallDirect. Unboxed arguments in GPRs and FPRs, unboxed result. Inlined if small, with a larger budget in loops.
Receiver is one of a few layoutsCallTable. The shape word indexes a method table row; one load and an indirect call.
Few closures reach the callIsClosureOf, then a direct or inlined call. The last one needs no test if Link's set is closed.
Unknown function valueA stub decodes the closure's word (code offset, function number, parameter count) and enters the boxed entry point.
Method on unknown receiverCallMethodAtSite. One stub does the load and the call through the site cache.

The body returns numbers and booleans unboxed and a separate generic entry boxes them for calls by value. Method table: IR test.

By-name access

The call site loads an immediate that locates its 16-bit site index and calls a stub shared by all sites of that kind. The record caches a StructureID and a handler kind with its payload (own slot, holder slot, getter, transition, absent). Inside loops the structure compare is inline and only misses go to the stub. Records register with the objects on the prototype chain they depend on and are cleared when one changes. Code is never patched and no stub is generated at run time.

String building

let s = "";
for (let i = 0; i < n; i++) s += "k" + i + ",";
return s;

Ropes

roperoperope"k0,""k3,""k2,""k1,"

Stack string builder

k0,k1,k2,k3,cursorno allocation per append, one JSString at exit
The walk turns the accumulator's phi into a string builder in the frame: StackStringBuilderBegin in the preheader, AppendConstant / Append in the body, Finish on exit edges. The cursor is an SSA value, reloaded only after calls that can collect. IR test. If some path reads s, a string is materialized there. If every iteration reads it, the loop keeps ropes.

Generators and async functions

A generatormachine frameheapilimityield iilimitresume pointat defat yieldValues live across a yield are homed in aheap frame. Each resume point is an entry.An async functionmachine frameheapa: doubleo: cella: doubleo: cellawaitmicrotaskawait copies the machine frame into a cell,with a frame map. Doubles stay unboxed.
IR tests: generator frames, double live across await.
for (x of gen()), generator doesn't escapethe generator body is inlined into the loop and no generator object is allocated
await f(), f knownAwaitCallBySavingFrame enters f's body without allocating its promise
async callee with no suspension pointcalled as an ordinary function

Exceptions and GC

Handlers are table rows keyed by call site. Unwinding uses a frame record per function (size, callee saves). A throw to a local catch that ignores the value becomes a jump and the Error allocation is dead code.

Running frames have no stack maps; roots on the machine stack are found the way JSC already finds them. Frame maps are emitted only for suspension points, since those frames live in heap cells. Non-escaping objects are scalar replaced, or allocated in the machine frame as cells with a reserved cell state. The barrier after a store is skipped in these cases:

stored type has no cellsno barrier
owner is in the machine frameno barrier
owner allocated since the last safepoint and unaliasedmutator fence only
a later barrier on the same owner covers itno barrier
otherwisecell state compare, barrier stub

AOTBarrierEmitter.cpp

Built-ins, RegExp, WebAssembly

Built-ins are described in TypeScript tables (math.builtins.ts is a short one): argument and result types, effects, inline form, native symbol, range rules. Generators produce the C++ and Rust from them. The JavaScript parts of Bun and Node's modules are compiled with the program, only the parts it reaches. RegExp literals are compiled through Yarr at build time. Imported .wasm modules are compiled with OMG against fault-protected memory. BBQ is used for functions with SIMD, modules with GC types and functions OMG refuses, and for a second copy with explicit bounds checks in modules that have a memory. Wasm bytes produced at run time are interpreted. AOTWasmModules.cpp

The image

Functionsby code unit
Stubsshared
RegExpsYarr
Wasmmostly OMG
Positionsper call site
Frame mapssuspensions
Method tableby shape
Program tableslayouts, modules
Stringsidentifiers
Constantspools
Side tableshandlers, inlining
Textfor toString
Code is mapped from the file PROT_READ | PROT_EXEC and never written. Data is mapped read-only; a method table page is made writable if a member it covers changes. Positions and inline frames are in the image, so stack traces need no source map; --sourcemap=external moves them out. AOTImageFormat.h

bun test --aot

Test runs go through the same compiler with the same passes. The build reads the tests first to see which exports and built-in members they mock. Only those lose their proofs: a call to a mockable export becomes a load of the module variable, a compare against the original function, and a direct call on the match path.

IR test. Implicitly looked-up members, such as Array.prototype[Symbol.iterator], can't be mocked. The original of a mocked module runs from source.

Testing the compiler

one programas writtentype annotations erasedspeculation failures injectedproof checks onbun runidentical outputand exit code
Every whole-program test. The same comparison is run by hand over test262, JSTests, Node's and Bun's suites. Each stage prints and parses text, and there are FileCheck-style tests per optimization. tests/README.md

Every build also checks a value's type where it enters a place whose type is proven (parameters, fields, variables) and aborts with the source location on a mismatch. --aot-harden adds checks at reads and on every index.

Tradeoffs

Worse than the JIT

  • Untyped polymorphic code that Link can't resolve.
  • Code generated at run time, including Wasm.
  • Build time, with nothing cached between builds.
  • Code size in large programs: cold code is compiled too.
  • No breakpoints, no cross-compilation, frozen built-ins.

Better than the JIT

  • Startup: no parsing, no tiering.
  • Memory in large programs: no bytecode, profiles or JIT code.
  • Typed field access without a structure check.
  • Unboxed fields, arguments and results across functions.

When to stay with the JIT, in the docs.