Sub topic 12
Deoptimization: When the Bet Fails
The previous chapter showed how the optimizing compiler bets on past behavior. It reads type feedback, assumes the same types and shapes will keep showing up, and produces machine code that only works while those assumptions hold. This chapter covers what happens when an assumption turns out to be wrong. That process is called deoptimization. It is the safety net that lets JavaScript engines optimize aggressively and still run every program correctly.
This chapter assumes you can run scripts with Node.js from the command line. It also assumes you have read the earlier chapters on hidden classes, inline caches, type feedback, and speculative optimization. The examples use V8 as found in recent Node.js releases. Trace output differs between versions, so treat the sample output as an illustration of the format, not a promise of exact text.
What Deoptimization Is
Deoptimization ("deopt", sometimes called a bailout) means throwing away optimized machine code and continuing execution in a lower tier, usually the Ignition interpreter. The function does not restart. The engine resumes it at the exact bytecode instruction that matches the point where the optimized code stopped, with every local variable holding its current value.
Deoptimization makes speculation safe. Optimized code contains guards: cheap checks such as "is this value a small integer?" or "does this object have hidden class M?" When a guard fails, the optimized code cannot handle the situation, so it hands control back to code that handles every case.
The Mechanics: Translating a Frame
Optimized code and bytecode keep state in different places. The interpreter keeps values in a register file of virtual registers. Optimized code keeps values in machine registers and stack slots. It may also have removed some values completely, for example an object that escape analysis never allocated.
To deoptimize, V8 does the following:
- It stops at a deopt point. This is a location in the optimized code where the compiler recorded how to rebuild the interpreter state.
- It reads the translation (deopt data) stored for that point. The translation maps each interpreter register to its current location: a machine register, a stack slot, a constant, or a recipe for rebuilding an object that was never allocated.
- It builds one or more interpreter frames. When the failing code was inlined, the engine rebuilds a frame for each inlined function, so the call stack looks as if inlining never happened.
- It resumes in Ignition at the matching bytecode offset.
The rebuilt frames are why deoptimization costs more than a simple jump. The engine also discards the optimized code, so the function runs at interpreter speed until it warms up again.
Kinds of Deoptimization
V8 sorts deoptimizations by how they are triggered.
| Kind | Trigger | Typical example |
|---|---|---|
| Eager | A guard inside the running optimized code fails | `a + b` was compiled for small integers and receives strings |
| Lazy | Something outside the function invalidates an assumption the code depends on | A prototype method that was inlined gets replaced |
| Soft | The optimized code reaches a path that had no feedback when it was compiled | A branch that never ran during warm-up finally runs |
Eager deopts happen immediately, at the failing check. Lazy deopts work through dependencies. When the compiler relies on a fact such as "this hidden class is stable" or "this prototype property never changes", it registers the optimized code as dependent on that fact. If the fact changes, V8 marks the dependent code for deoptimization. Any frames currently running that code deoptimize when control returns to them, and future calls skip it.
Seeing an Eager Deopt
// Run with: node --trace-opt --trace-deopt add.js
function add(a, b) {
return a + b;
}
for (let i = 0; i < 1000000; i++) {
add(i, i); // feedback says: small integers
}
add('a', 'b'); // breaks the integer assumptionThe output should include a line marking add for optimization, followed later by a bailout line that looks roughly like this:
[bailout (kind: deopt-eager, reason: not a Smi): begin. deoptimizing add, ...]The reason string tells you which guard failed. "Smi" is V8's name for a small integer stored directly in a tagged value. Common reasons you will see include not a Smi, wrong map (the hidden class guard failed), out of bounds (an array index past the length), overflow (integer arithmetic left the Smi range), and Insufficient type feedback (a soft deopt).
Integer overflow often comes as a surprise, because the source code never changes type:
// Run with: node --trace-deopt overflow.js
function double(x) {
return x * 2;
}
for (let i = 0; i < 100000; i++) {
double(i);
}
// The result no longer fits in a small integer, so the
// overflow check in the optimized multiply fails.
double(2 ** 30);From JavaScript's point of view every value is a number. Internally, the optimized multiply was specialized for Smis and contained an overflow check. When the result needs a heap-allocated double, the check fails.
Seeing a Lazy Deopt
// Run with: node --trace-deopt lazy.js
class Counter {
constructor() {
this.n = 0;
}
inc() {
this.n++;
}
}
function run(c) {
for (let i = 0; i < 1000; i++) {
c.inc();
}
}
const c = new Counter();
for (let i = 0; i < 10000; i++) {
run(c);
}
// run was likely optimized with inc inlined.
// Replacing the method invalidates that dependency.
Counter.prototype.inc = function () {
this.n += 2;
};
run(c);
console.log(c.n);Nothing inside run fails a guard. The optimized run depended on Counter.prototype.inc staying the same, and assigning a new function broke that dependency. You should see a deopt-lazy line, or a message saying the code was marked for deoptimization because of a dependency change. The program still prints the correct total, because deoptimization never changes what the program computes.
After the Deopt: Feedback and Reoptimization
When execution returns to Ignition, the interpreter keeps updating the feedback vector. The add call site now records both "small integer" and "string". If add becomes hot again, the optimizing compiler builds new code from that wider feedback. The new code handles both cases, usually through a generic addition path that runs somewhat slower.
In most programs this cycle happens a few times during warm-up and then settles. One deopt during startup costs almost nothing.
Deopt Loops
The real problem is a function that keeps cycling through optimize, deopt, reoptimize, deopt. Each cycle pays for compilation and frame translation and then spends time running in the interpreter. V8 counts deopts per function and stops trying to optimize the function after too many, so the function stays in a lower tier. That cap protects the engine, but your hot function then runs slower than it would at the top tier.
Deopt loops usually come from one of these patterns:
- A single function receives values of different types in alternating phases, such as numbers for a while and then strings.
- Objects of many shapes flow through one property access, so
wrong mapkeeps firing until the site goes megamorphic. - Code patches prototypes or redefines methods while hot code runs, which causes repeated lazy deopts.
- Array code that reads past the end of an array, or that sometimes hits holes.
The usual fixes keep types and shapes stable at the hot site. You can split a function that serves two unrelated types into two functions. You can build objects through one constructor so they share a hidden class. You can keep numeric code within a single numeric representation. A later chapter covers these practices and explains when they are worth applying.
Common Mistakes When Reading Deopt Output
- Treating every deopt as a bug. Speculation is expected to fail sometimes. Measure before you change code.
- Ignoring the reason string. The reason (
wrong map,not a Smi,out of bounds) tells you which assumption broke. Start from it. - Benchmarking without warm-up. Short benchmarks mix interpreter time, compilation, and early deopts, so the numbers say little about steady-state speed.
- Assuming output is stable across versions. Flag names and message formats change between V8 releases. Check
node --v8-optionsfor your version.
Exercise
A function area(shape) is optimized after receiving only objects built by new Rect(w, h). Then it receives an object literal { w: 2, h: 3 }. Is the resulting deopt eager or lazy, and which reason would you expect in the trace?
Show answer
Eager. The optimized code checks the receiver's hidden class before it loads w and h. The object literal has a different hidden class from Rect instances, so that check fails inside the running code. Expect a reason such as wrong map.
Exercise
Why must V8 rebuild several interpreter frames, not just one, when a deopt happens inside code that was inlined from another function?
Show answer
Inlining merged the callee's code into the caller's optimized code, so only one machine frame exists. The interpreter expects one frame per function call. To resume correctly, the deoptimizer rebuilds a frame for the caller and a frame for each inlined callee from the deopt data, so the stack looks as if inlining never happened.
Exercise
Running node --trace-deopt on a server shows parseValue deoptimizing 40 times with reasons that alternate between not a Smi and not a String. What is going on, and what is one reasonable fix?
Show answer
parseValue is in a deopt loop. It receives numbers in some phases and strings in others. Each reoptimization specializes for whatever the recent feedback showed, and the next phase breaks that guess. One fix is to split it into parseNumber and parseString, so each call site sees one stable type. Another is to convert inputs to a single type before calling it. Profile again afterward to confirm that the deopts stopped and that the change made a measurable difference.