Sub topic 15
Watching the Engine Work With V8 Flags and Native Syntax
Earlier chapters described hidden classes, inline caches, type feedback, and deoptimization as models. This chapter shows you how to check those models against a real engine. You will run Node.js with V8 flags that print what the engine decides, and use V8's native syntax to ask direct questions about objects and functions.
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, dictionary mode, inline caches, and deoptimization. The examples were written against recent Node.js releases (V8 11 and later). Flag names and output formats change between versions, so treat exact output text as an example, not a contract.
Two Kinds of Instruments
V8 gives you two broad tools:
- Command-line flags change engine behavior or make it log events.
--trace-optand--trace-deoptare examples. Node passes any V8 flag through to the engine. - Native syntax is a set of internal functions written with a
%prefix, such as%HaveSameMap(a, b). They only parse when you start Node with--allow-natives-syntax. Without that flag,%at the start of an expression is aSyntaxError.
You can list every flag your Node binary supports:
node --v8-options | grep -E "trace-(opt|deopt)|print-bytecode|allow-natives"Inspecting Objects
Comparing hidden classes
%HaveSameMap(a, b) returns true when two objects share a hidden class, which V8 calls a map. %HasFastProperties(o) returns false once an object has dropped into dictionary mode.
// Run with: node --allow-natives-syntax shapes.js
function Point(x, y) {
this.x = x;
this.y = y;
}
const a = new Point(1, 2);
const b = new Point(3, 4);
console.log('same map:', %HaveSameMap(a, b)); // true
const p = { x: 1, y: 2 };
const q = { y: 2, x: 1 };
console.log('order matters:', %HaveSameMap(p, q)); // false
const o = { a: 1, b: 2 };
console.log('fast before:', %HasFastProperties(o)); // true
delete o.a;
console.log('fast after:', %HasFastProperties(o)); // falseDumping internals with %DebugPrint
%DebugPrint(value) prints V8's internal view of a value: its map address, property storage, and for arrays the elements kind. Node's release builds print a fairly detailed dump. A V8 debug build prints even more.
// Run with: node --allow-natives-syntax debugprint.js
const arr = [1, 2, 3];
%DebugPrint(arr); // look for "elements kind: PACKED_SMI_ELEMENTS"
arr.push(4.5);
%DebugPrint(arr); // now PACKED_DOUBLE_ELEMENTSThe output is long. The lines worth reading are - map:, the [FastProperties] or [DictionaryProperties] marker, and - elements kind:. If two objects print the same map address, they share a hidden class.
Reading Bytecode
--print-bytecode prints the Ignition bytecode for every function that gets compiled, including Node's own startup code. Add --print-bytecode-filter to limit the output to one function name.
// bytecode.js
// Run with: node --print-bytecode --print-bytecode-filter=getX bytecode.js
function getX(o) {
return o.x;
}
getX({ x: 1 });The output includes a line similar to GetNamedProperty a0, [0], [0]. The last operand is a slot in the function's feedback vector. That slot is where the inline cache for o.x stores the maps it has seen. A function is compiled lazily, so you only see its bytecode if it is actually called.
Watching Optimization and Deoptimization
Trace flags
--trace-opt logs when V8 marks a function for optimization and when compilation finishes. --trace-deopt logs each deoptimization along with its reason.
// 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);
}
add('a', 'b');Expect lines that mention add, the compiler used (Maglev or TurboFan, depending on version and how hot the code is), and later a deopt line with a reason such as not a Smi or wrong call target. To keep the output small, filter it:
node --trace-opt --trace-deopt add.js | grep -E "add|deoptimiz|bailout"Forcing optimization deterministically
Waiting for a loop to get hot is slow and depends on heuristics. Native syntax lets you trigger optimization directly. Call %PrepareFunctionForOptimization first so V8 keeps the function's feedback, warm the function up so feedback exists, and then request optimization.
// Run with: node --allow-natives-syntax --trace-deopt force.js
function add(a, b) {
return a + b;
}
function isOptimized(fn) {
// Bit 4 (value 16) means "optimized" in recent V8 versions.
// The bit layout lives in V8's src/runtime/runtime-test.cc and can change.
return (%GetOptimizationStatus(fn) & 16) !== 0;
}
%PrepareFunctionForOptimization(add);
add(1, 2);
add(3, 4);
%OptimizeFunctionOnNextCall(add);
add(5, 6);
console.log('optimized after warm-up:', isOptimized(add)); // true
add('x', 'y'); // string arguments break the Smi assumption
console.log('optimized after strings:', isOptimized(add)); // falseOther useful functions in the same family are %NeverOptimizeFunction(fn), which keeps a function in the lower tiers, and %OptimizeMaglevOnNextCall(fn) in versions that ship Maglev.
Observing Inline Cache States
The old --trace-ic flag printed IC transitions to the console. Current V8 versions write them to a log instead:
node --log-ic --log-maps ic.jsThis creates a v8.log file (named isolate-*-v8.log in some versions) in the current directory. Open it in V8's web-based system analyzer at https://v8.github.io/tools/head/system-analyzer/. The analyzer lists each property access site with its transitions, for example from monomorphic (1) to polymorphic (P) to megamorphic (N). It also draws the map transition trees recorded by --log-maps. Run it on the getX example from the inline cache chapter and you should see the o.x site pass through those states.
Choosing the Right Tool
| Question | Tool | Needs natives syntax |
|---|---|---|
| Do two objects share a hidden class? | `%HaveSameMap` | Yes |
| Is an object in dictionary mode? | `%HasFastProperties`, `%DebugPrint` | Yes |
| What elements kind does an array have? | `%DebugPrint` | Yes |
| What bytecode did a function get? | `--print-bytecode-filter` | No |
| When and why did code optimize or deoptimize? | `--trace-opt`, `--trace-deopt` | No |
| Is a function optimized right now? | `%GetOptimizationStatus` | Yes |
| How polymorphic is a property access? | `--log-ic` with system analyzer | No |
Pitfalls When Measuring
- Forced optimization is not natural tiering.
%OptimizeFunctionOnNextCallskips the heuristics that decide whether to optimize. It shows what the optimizer does with the feedback it has. It does not show what happens in production. - Thin feedback misleads. If you warm up with only two calls, the optimizer specializes on those two calls alone. Warm up with inputs that look like your real data.
- Dead code gets removed. In a microbenchmark whose result is never used, TurboFan may delete the work you meant to measure. Use the result, for example by summing it and printing the sum.
- Natives syntax never ships. A file that contains
%calls is not valid JavaScript. Keep these probes in separate scratch scripts, not in application code or tests that other engines run. - Output format is unstable. Scripts that parse trace output break when you upgrade Node. Use the traces for investigation, not for CI assertions.
- Profile first. These tools explain why a hot function is slow. Use a profiler such as
node --cpu-profto find which function is hot before you go looking at shapes and deopts.
Exercise
You run a script with node --allow-natives-syntax and %HaveSameMap(u1, u2) prints false for two objects built by the same makeUser(name, email) factory. The factory sets email only when it is provided. Which tool would you use next, and what would you expect it to show?
Show answer
Use %DebugPrint(u1) and %DebugPrint(u2), or record with --log-maps and open the log in the system analyzer. The two map addresses will differ. One object's transition chain goes through name then email, and the other stops after name. That confirms the conditional assignment creates two shapes. Assigning email every time, even as null, gives both objects one map.
Exercise
A colleague writes %OptimizeFunctionOnNextCall(f); f(1); without calling %PrepareFunctionForOptimization(f) or warming f up, then says "f is fast, look, it's optimized." What is wrong with that conclusion?
Show answer
The function had almost no type feedback when it was optimized, and the warm-up did not reflect real inputs. So the optimized code is either generic or specialized on one call, and it may deoptimize as soon as realistic data arrives. Natural tiering would also make a different decision about whether and when to optimize. Prepare the function, warm it up with representative inputs, and check --trace-deopt during a realistic workload.
Exercise
Which flag combination, with no natives syntax, tells you whether add('a', 'b') in the add.js example caused a deoptimization and why?
Show answer
node --trace-opt --trace-deopt add.js. --trace-opt shows add being optimized during the loop. --trace-deopt then prints a deoptimization of add with a reason that refers to the failed number or Smi check.