4.5 JIT Compilation and Deoptimization

INTERPRETERSTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18

Just-in-time (JIT) compilation compiles code to machine code while the program runs. The system starts by interpreting bytecode or walking a tree. When a function or loop runs hot (many times), the JIT compiler engages and translates that code to machine instructions. The next execution uses the compiled machine code. R uses the word for something narrower: compiler::enableJIT() compiles closures to bytecode, not machine code, as the end of this page explains.

4.5.1 Motivation

Interpretation is slow but fast to start. Compilation takes time but produces fast code. JIT aims for both: start fast by interpreting, then shift to compiled code for hot paths.

Most programs spend most of their time in a small part of their code, and the JIT focuses on that part. Cold code remains interpreted.

JIT has overhead. The compiler takes time and memory, and the runtime must track which functions are hot and collect type feedback. The JIT must decide when the cost of compilation is paid back by the speedup. Each system sets its own thresholds, counting calls and loop iterations, and a cheap tier usually starts sooner than an optimizing one.

4.5.2 Specialization and type feedback

At compile time, a static compiler sees the program source. It does not know what values the code will receive at runtime. A dynamic language’s JIT sees actual data.

The JIT can watch what types of values flow through the code. If a variable always holds integers, the JIT can emit machine code that assumes integers, drops the type-tag checks and the boxing, and keeps only the arithmetic.

This is called type feedback. The runtime collects data on the types that have been seen. The JIT uses this data to specialize code.

Code that specializes on types is fast. It avoids type checks and dispatch. It uses the machine’s native arithmetic. But it is only correct if the types remain the same.

4.5.3 Guards and deoptimization

Specialization requires assumptions. “This variable always holds an integer.” But what if later code changes the type?

The JIT emits a guard: a check that fails if the assumption is violated. If the guard passes, the specialized code runs. If it fails, the runtime deoptimizes.

Deoptimization moves the running call out of the compiled code and back into the interpreter at the matching point. The runtime rebuilds the interpreter’s frame, its local variables and operand stack, from the machine registers and stack slots, and execution continues in the interpreter, which is slower but correct. HotSpot’s glossary defines it the same way, as converting a compiled stack frame into an interpreted one. The compiled code is usually invalidated, and the JIT may compile the function again later with weaker assumptions.

flowchart TD
  interp["interpret"]
  prof["record types<br/>at each call"]
  comp["compile with<br/>a guard per assumption"]
  run["run machine code"]
  check{"guard holds?"}
  deopt["deoptimize"]
  interp --> prof
  prof -->|call count rises| comp
  comp --> run
  run --> check
  check -->|yes| run
  check -->|no| deopt
  deopt -->|throw the code away,<br/>weaken the assumption| interp

Every specialized run is provisional. The long edge running back up the side is the one that costs: the compiled code is discarded and the next attempt has to assume less.

A worked example

Suppose the JIT specializes on integers:

# Specialized code (assumes x and y are integers)
GUARD x is integer
GUARD y is integer
load x into r1
load y into r2
add r1, r2
return r1

On the first hundred calls, x and y are integers. The guards pass. The addition runs in machine code, fast.

On call 101, x becomes a string. The guard fails:

GUARD x is integer  -> FAIL
deoptimize()
  discard compiled code
  fall back to interpreter
  re-interpret with x as string
  integer addition becomes string concatenation

The call runs slowly. The JIT will decide to stop specializing, or to compile a new version that handles both integers and strings.

Speculation pays off when its assumptions hold most of the time. If guards fail frequently, the cost of deoptimizing and recompiling cancels the gain from specializing.

Each guard adds a condition to check. Each deoptimization is expensive (the JIT must throw away code, change assumptions, and recompile). The JIT must balance speculation (assume a type holds, emit a guard) with caution (check often, use less aggressive optimizations).

4.5.4 Inline caches

Many lookups give the same answer every time a given line runs. A JavaScript method call obj.f() finds f by searching the object and its prototype chain, and at one call site obj usually has the same shape every time.

An inline cache stores, at the call site, the result of the last lookup together with the key it depended on: in V8, the object’s hidden class, which V8 calls a map. The next execution compares the key and, if it matches, skips the lookup, so a search becomes one comparison. A site that always sees one shape is monomorphic. A site that sees many is megamorphic, and the cache stops helping there.

Inline caches do not need a JIT. CPython 3.11’s specializing interpreter (PEP 659) keeps them in plain bytecode, and a JIT can read the same caches as type feedback.

R’s bytecode interpreter keeps a related cache for variables. GETVAR remembers which binding cell it found for each name in the function’s own frame. Removing a variable leaves R_UnboundValue in its old cell, so a cached cell is still safe to check. Lookups that reach enclosing environments are not cached, because a new binding in any frame in between would make the cached answer wrong.

4.5.5 Compiling dynamic languages

Static languages like Rust and C are easier to compile well. The compiler sees all types at compile time and usually knows which function a call reaches, so it can inline and specialize without guards.

Dynamic languages are different. The runtime does not know the types. Functions can be redefined. New functions can be created. Anything can be modified at runtime.

A JIT for a dynamic language must be conservative. Every assumption must be guarded. Every type specialization is tentative. If an assumption fails, the code must be thrown away and reinterpreted.

R’s specific challenges

R has three properties that make it an especially hard JIT target:

Lazy evaluation. R arguments are not evaluated at the call site. Each argument becomes a promise: the expression plus the environment where it will later be evaluated. At the call, the JIT does not know the argument types, so it cannot specialize the call site on them. It has to speculate later, at the places in the body where each promise is forced, and those can be anywhere.

Non-standard evaluation. A function can inspect its own unevaluated arguments. It can call quote() on the argument, examine its structure, and decide whether to evaluate it. This means a JIT cannot assume that an argument will be evaluated. It cannot compile out the promise machinery or the environment chain. It must keep both available for inspection at runtime.

Redefinition at runtime. Almost anything can be redefined: builtins, operators, standard functions, even if and for. After `+` <- function(e1, e2) base::`-`(e1, e2) in the global environment, code that looks + up from there gets the new function. R’s own byte-code compiler shows what this costs a compiler. At its default optimization level it treats core language functions such as +, if and [ as fixed and compiles them into dedicated instructions with no run-time check, so a function compiled before that redefinition keeps adding, and one compiled after it subtracts. Other base functions it inlines only behind a guard that checks at run time whether the function has been masked, falling back to the AST interpreter if it has. A JIT that specializes on the builtin + has to guard against redefinition the same way, or accept the same limit.

Lazy evaluation and non-standard evaluation make R an especially difficult JIT target. The JIT cannot know argument types at the call site, so specialization has to wait for the use sites, guards multiply, and redefinition adds checks of its own.

Python and JavaScript are dynamic too, and both can evaluate code built at run time. What they lack is R’s lazy evaluation: their arguments are evaluated before the call, so a JIT sees the values at every call site. R also has first-class environments, which code can inspect and change at any time. Java is statically typed and eager. Each design point creates different JIT opportunities and costs.

See Why R Is Difficult to Parallelize for how these properties also constrain parallelization.

4.5.6 Differences between systems

Different language runtimes take different approaches to JIT:

JVM (HotSpot): Tiered compilation with two JIT compilers. C1 compiles quickly for low latency. C2 compiles slowly but optimizes hot code aggressively. A method starts in the interpreter, gets compiled by C1 with code that profiles it, and if it stays hot, C2 recompiles it using that profile.

V8 (JavaScript): Ignition interprets bytecode and collects type feedback. Sparkplug compiles bytecode to machine code almost instantly, without optimizing. Maglev is a fast optimizing compiler, and TurboFan produces the fastest, most speculative code. Hot functions move up the tiers. When a speculative check fails, the deoptimizer rebuilds the interpreter frame and execution continues unoptimized.

PyPy (Python alternative): A tracing JIT: it records the operations of a hot loop as it runs, then compiles that trace with a guard wherever the path could branch off. PyPy keeps a global interpreter lock, as CPython’s default build does. Its project page reports PyPy 3.12 as about four times faster than CPython 3.11 on average across its benchmarks.

CPython (standard Python): A specializing bytecode interpreter since 3.11 (PEP 659), with inline caches in the bytecode. Python 3.13 added an experimental copy-and-patch JIT (PEP 744), which is not part of the default build and is off by default.

GNU R has a JIT only in its own sense of the word: compiler::enableJIT() controls when closures and loops are compiled to bytecode. The bytecode compiler does some optimizations (constant folding, inlining of base functions), but the bytecode VM is an interpreter, and GNU R never produces machine code.

GNU R does not compile R code to machine code. The byte-code compiler is the compiler package, which ships with R, and enableJIT() sets when it runs (level 3 by default). bcEval in eval.c interprets its output.

Machine-code JITs for R have been built outside R Core. FastR <https://github.com/oracle/fastr> runs R on GraalVM, and Ř, a research JIT, speculates on types and deoptimizes much as V8 does (Flückiger et al., “R Melts Brains”, DLS 2019 <https://janvitek.org/pubs/dls19.pdf>). Both are large projects, and that size is the cost of a full JIT for R: complexity, memory, deoptimization machinery and guard overhead.

4.5.7 Failure modes

A common mistake is thinking that a JIT would fix R’s performance. Laziness and NSE make the main optimizations, type specialization at call sites and fixed dispatch for builtins, much harder to apply. To optimize R code, Ř had to design a new intermediate representation that models promises and first-class environments explicitly.

Another mistake comes from R’s naming. R’s documentation calls the automatic mode of its byte-code compiler a JIT, because enableJIT() compiles functions just in time, on their first or second call. Elsewhere on this page, and in HotSpot, V8 and PyPy, a JIT produces machine code. R has the first kind and not the second.

Where this appears

  • r-in-rust (rrs) Could add a JIT layer for hot code optimization in the future.

Where to go next

Back to top