Sub topic 11
Speculative Optimization: Betting on Past Behavior
This chapter assumes you already know three ideas from earlier chapters. V8 runs code through tiers: Ignition, Sparkplug, Maglev, and TurboFan. Objects have hidden classes, which V8 calls maps. Inline caches record type feedback in a function's feedback vector. This chapter explains how the optimizing tiers use that feedback to produce fast machine code. What happens when the feedback turns out to be wrong is covered only briefly here, because the next chapter is about deoptimization.
Why an Optimizer Has to Guess
JavaScript gives a compiler almost no static guarantees. Look at a + b. Depending on its operands, it can mean integer addition, floating-point addition, string concatenation, a BigInt add, or a call to a user-defined valueOf. A compiler that had to handle every case at every + would emit a large generic routine. That routine would be little faster than the interpreter.
Speculative optimization avoids that cost. The compiler does not prove what types will appear. It assumes that future executions will look like past ones, as recorded in the feedback vector. It then emits code for only those cases. Each assumption is protected by a cheap check, called a guard. If a guard fails, execution leaves the optimized code and returns to a tier that can handle anything.
The bet usually pays off because most real programs are type-stable. A function that received small integers ten thousand times will very likely receive small integers next time.
The Speculation Loop
What the Engine Speculates On
Each kind of feedback supports a matching kind of speculation. V8's optimizer works on an intermediate graph, and many of its nodes are named after the check they perform.
| Speculation | Feedback source | Guard in optimized code | Payoff |
|---|---|---|---|
| Operand is a Smi (small integer) | Binary operation feedback slot | Tag-bit check (`CheckSmi`) | Single machine add instead of generic `+` |
| Integer arithmetic does not overflow | Same slot, still "SignedSmall" | Overflow flag check after the add | Results stay untagged integers |
| Object has a known map | Property-load inline cache | Map comparison (`CheckMaps`) | Load from a fixed offset |
| Call target is a specific function | Call inline cache | Compare callee against expected function | Inlining the callee |
| Array has a known elements kind | Keyed-load inline cache | Map check (elements kind is encoded in the map) | Direct indexed load with no type dispatch |
A guard is usually a compare and a branch, which costs only a few instructions. The generic operation it replaces costs far more. And once a guard has passed, the compiler knows a fact it can reuse. After one CheckMaps on o, later loads of o.x and o.y in the same region need no further checks, provided nothing between them could change o's map.
Seeing Speculation Happen
The following script trains add on small integers and then forces optimization. Native syntax lets you skip the heuristics that normally decide when a function is hot.
// Run with: node --allow-natives-syntax --trace-opt --trace-deopt speculate.js
function add(a, b) {
return a + b;
}
%PrepareFunctionForOptimization(add);
add(1, 2);
add(3, 4); // feedback: both operands SignedSmall
%OptimizeFunctionOnNextCall(add);
console.log(add(5, 6)); // runs optimized code specialized for Smis
console.log(add(1.5, 2)); // a double breaks the Smi assumptionWith --trace-opt you will see a line reporting that add was compiled, normally by TurboFan here. The call with 1.5 then produces a --trace-deopt line whose reason mentions something like "not a Smi". Exact wording changes between V8 versions, so read it for meaning and don't depend on the precise text.
A Model of Guarded Code in Plain JavaScript
V8 emits machine code, not JavaScript. Still, the shape of speculative code can be written as a runnable JavaScript model. This version is what an optimizer conceptually builds from "both operands were small integers":
const SMI_MIN = -(2 ** 30);
const SMI_MAX = 2 ** 30 - 1;
function isSmi(v) {
return Number.isInteger(v) && v >= SMI_MIN && v <= SMI_MAX;
}
function deopt(reason, a, b) {
console.log(`deopt: ${reason}`);
return a + b; // fall back to fully generic semantics
}
function addOptimized(a, b) {
if (!isSmi(a)) return deopt('a is not a Smi', a, b); // guard
if (!isSmi(b)) return deopt('b is not a Smi', a, b); // guard
const r = a + b; // fast integer add
if (r > SMI_MAX || r < SMI_MIN) return deopt('overflow', a, b); // guard
return r;
}
console.log(addOptimized(2, 3)); // 5, fast path
console.log(addOptimized(2, 'x')); // deopt: b is not a Smi, then "2x"
console.log(addOptimized(SMI_MAX, 1)); // deopt: overflow, then 1073741824The Smi range shown is 31 bits, which V8 uses when pointer compression is enabled, as it is in Node.js builds. Two details matter. Every fallback still returns the correct JavaScript result, so speculation never changes what the program computes, only how fast. Also, the real deoptimizer does not just call a slow function. It rebuilds the interpreter's stack frame at the exact bytecode where the guard failed, as the next chapter explains.
Checks Versus Dependencies
Some assumptions are too expensive to check on every execution. One example is "no one has added a property named x to Point.prototype". Another is "this map is stable and will not transition". For these, V8 uses compilation dependencies instead of inline guards. The optimized code registers itself with the relevant map or prototype. If that object later changes in a way that breaks the assumption, V8 marks the dependent code for deoptimization, and the code is thrown away on its next entry or return.
This gives two failure modes:
- An eager deopt comes from an inline guard failing while the code runs.
- A lazy deopt comes from a dependency being invalidated by code elsewhere, often far from the optimized function.
Lazy deopts are harder to diagnose, because the code that triggers one, such as a monkey-patched prototype, never shows up in the stack trace of the slow function.
Gotchas and Failure Modes
- Insufficient feedback. If a branch never ran before optimization, its feedback slot is empty. The optimizer then inserts an unconditional deopt in that branch. Taking the rare branch later costs a deopt even though nothing was "wrong". Warm-up runs that skip error paths cause this often.
- Polymorphic feedback narrows the payoff. With two to four maps, the optimizer emits a chain of map checks. Megamorphic feedback usually makes it give up on specializing that access and call a generic stub.
- Speculation loops. If a function deopts, collects new feedback, and reoptimizes many times, V8 eventually stops optimizing it or settles for more generic code. One unlucky value can permanently lower a hot function's tier.
- Tier differences. Maglev speculates on the same feedback but does less analysis after its guards than TurboFan does. A function can therefore be "optimized" and still not be as fast as it could be.
Decision Criteria
Speculation rewards code where each operation sees one type and one shape, but only on hot paths. Before rewriting code for type stability, profile it and look for repeated deopts of the same function with --trace-deopt. A single deopt at startup is normal and costs little. A function that deopts thousands of times, or stops being optimized at all, is worth fixing.
Exercise
A function scale(v) returns v * 2. During warm-up it only ever receives integers, and it gets optimized. Later it receives 0.5. Which guard fails, and is the result returned to the caller still correct?
Show answer
The Smi check on v fails, because 0.5 is not a small integer. Execution deoptimizes to Ignition, which performs the generic multiplication and returns 1. The result is correct, since speculation only affects speed, never semantics.
Exercise
Optimized code for getX(p) loads p.x from a fixed offset. Another module then defines a getter for x on the prototype of p's class. No call to getX passes a different kind of object. Why can getX still deoptimize, and what kind of deopt is it?
Show answer
The optimized code depended on the prototype chain not providing x. Defining the getter invalidates that compilation dependency, so V8 marks getX for a lazy deopt. No inline guard failed. The change happened elsewhere and was caught through the dependency.
Exercise
Why might a function that handles errors in a rarely taken if branch deoptimize the first time an error happens in production, even though its types never change?
Show answer
The branch never ran before optimization, so its feedback slots were empty. The optimizer replaced that branch with an unconditional deopt instead of compiling code for it. Reaching the branch triggers a deopt for insufficient feedback.