Sub topic 10
Inlining and the optimizations it unlocks
This chapter assumes you know basic Java, can run java from the command line, and have read the earlier chapters on tiered compilation and profiling. You should know that C1 and C2 compile hot methods and that the JVM collects profile data (call sites, receiver types, branch counts) while code runs in the interpreter and in tier 3.
What inlining is
Inlining replaces a call with the body of the method being called. The compiler copies the callee's code into the caller and works on the combined result as one unit.
Calls are cheap on modern CPUs, so the saved call instruction is not the main gain. The gain is that the compiler can now see across the method boundary. Most of the big optimizations in C2 work only inside one compilation unit, so inlining is what lets them see enough code to do anything.
Take this source:
static int square(int x) {
return x * x;
}
static int sumSquares(int a, int b) {
return square(a) + square(b);
}After inlining, the compiler works with something like this:
static int sumSquares(int a, int b) {
return (a * a) + (b * b);
}You never write this form, and the JVM never changes your bytecode. The change exists only in the compiler's internal representation of the compiled method.
Optimizations that inlining unlocks
Once the callee's body sits inside the caller, several other optimizations become possible.
- Constant propagation and folding. If a caller passes a constant, the callee's logic can be evaluated at compile time.
square(3)becomes9. - Dead code elimination. If an inlined branch depends on a value now known, the untaken side is removed.
- Escape analysis. If an object is created in an inlined method and never leaves the compiled code, C2 can avoid allocating it on the heap. The object's fields may be kept in registers instead (scalar replacement). Without inlining, the object would escape through the call.
- Lock elision. If escape analysis shows a lock object never leaves the thread, the synchronization can be removed.
- Bounds-check and null-check elimination. The compiler can prove that an index is in range or a reference is non-null once it sees both the check and the use.
- Loop optimizations. Loop unrolling and range-check hoisting work better when the loop body has no opaque calls.
The following example shows escape analysis depending on inlining:
public class EscapeDemo {
static final class Point {
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
int sum() { return x + y; }
}
static int compute(int i) {
Point p = new Point(i, i + 1);
return p.sum();
}
public static void main(String[] args) {
long total = 0;
for (int i = 0; i < 100_000_000; i++) {
total += compute(i);
}
System.out.println(total);
}
}When C2 inlines the Point constructor and sum() into compute, the Point never escapes. C2 can typically skip the allocation and compute i + (i + 1) directly. Whether it does depends on the JVM version and the inlining decisions made, so treat this as what C2 usually can do, not as a guarantee.
How HotSpot decides what to inline
HotSpot does not inline everything. Inlining makes compiled code larger, and larger code uses code cache space, takes longer to compile, and can hurt instruction cache behavior. The compiler uses a set of heuristics. The numbers below are the usual defaults in JDK 11 on 64-bit platforms. Check them on your own JVM with -XX:+PrintFlagsFinal.
| Flag | Typical default | Meaning |
|---|---|---|
| `-XX:MaxInlineSize` | 35 bytes | Largest bytecode size of a method inlined even when it is not hot |
| `-XX:FreqInlineSize` | 325 bytes | Largest bytecode size of a hot method that will be inlined |
| `-XX:MaxInlineLevel` | 9 | Maximum depth of nested inlining |
| `-XX:InlineSmallCode` | 1000 bytes (2000 with tiered on some platforms) | Callee with already-compiled code larger than this is not inlined |
The rules work out roughly like this:
- A very small callee (under
MaxInlineSizebytecodes) is inlined almost always. - A larger callee is inlined only if its call site is hot, and only if the callee is under
FreqInlineSizebytecodes. - If the callee already has compiled code that is bigger than
InlineSmallCode, it is not inlined. - Nesting is limited by
MaxInlineLevel, and the caller's total size is also limited. - A callee that is too big, or a call site that is cold, is left as a normal call.
Bytecode size, not source lines, drives these limits. A short-looking method with many operations may still exceed 35 bytes. Because of this, splitting a large method into smaller ones often helps the JIT, and writing one very large method can prevent inlining of its callees.
Virtual calls and class hierarchy
Java methods are virtual by default, so s.area() could call any override. C2 has several tools to inline anyway.
- Static, private, and final methods have only one possible target, so they can be inlined directly.
- Class Hierarchy Analysis (CHA). The JVM knows which classes are loaded. If only one loaded class implements a method, the call can be treated as direct. If a new subclass is loaded later, the JVM discards the compiled code that assumed otherwise (deoptimization, covered in a later chapter).
- Monomorphic call sites. If profiling shows a call site has only ever seen one receiver type, C2 inlines that target and adds a cheap type check (a guard) in front of it.
- Bimorphic call sites. With two observed types, C2 can inline both behind two guards.
- Megamorphic call sites. With three or more types, HotSpot normally uses a virtual call through the method table and does not inline.
The last case is a common source of surprising slowdowns. A utility method called from many places with many different implementations of an interface tends to be megamorphic, and the code behind it is a real call that the optimizer cannot see through.
The guard is what ties inlining to the next chapters. If a guard fails, the compiled code must fall back, either by calling the real method or by hitting an uncommon trap that triggers deoptimization.
Seeing inlining decisions
HotSpot can print each inlining decision, but the flag is a diagnostic option and must be unlocked first:
javac EscapeDemo.java
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining EscapeDemoCombine it with -XX:+PrintCompilation so the inlining tree appears under each compiled method. Typical lines look like this:
@ 8 EscapeDemo$Point::<init> (15 bytes) inline (hot)
@ 15 EscapeDemo$Point::sum (10 bytes) inline (hot)Common reasons for a refusal you may see include too big, callee is too large, already compiled into a big method, no static binding, and not inlineable. The exact wording varies between JDK builds. Read these as hints about which limit stopped inlining.
Common mistakes
- Optimizing by hand for the JIT. Manually inlining methods in source usually adds nothing for small methods, because HotSpot already does it. It makes the code harder to read. Measure first.
- Assuming
finalis needed for inlining. HotSpot uses CHA and profile data, so non-final methods are often inlined. Marking a methodfinalis a design choice, not a performance trick. - Raising inline limits globally. Larger
FreqInlineSizeorMaxInlineLevelvalues can increase compile time and code cache use and sometimes make code slower. Change one flag at a time and measure with a proper benchmark harness. - Ignoring megamorphic sites in hot paths. If a hot loop calls through an interface with many implementations, consider restructuring so the hottest loop sees fewer types.
- Judging from a short run. Inlining decisions depend on profile data, which takes time to collect. Early results may not match steady state.
Summary of the key idea
Inlining is the optimization that makes other optimizations possible. It removes boundaries, so constant propagation, escape analysis, and lock elision can see through them. Profile data lets C2 inline even virtual calls, but only by speculating that the profile still holds.
Exercise
A hot loop calls shape.area() where shape is an interface type. During the first 100,000 iterations, only Square objects are passed in. Then Circle and Triangle objects start appearing as well. Describe what C2 likely did before and after, and name one way to keep the loop fast.
Show answer
At first the call site was monomorphic, so C2 inlined Square.area() behind a type guard, which allowed further optimization of the loop body. When Circle appears, the guard fails and the compiled code falls back or deoptimizes. After recompilation, the profile shows three types, so the site is megamorphic and C2 uses a normal virtual call without inlining. To keep the loop fast, restructure so the hot loop processes one shape type at a time (for example, by grouping or sorting objects by type), which keeps each call site monomorphic.
Exercise
Why can escape analysis fail to remove an allocation if the constructor of the object is too large to inline?
Show answer
Escape analysis works within one compilation unit. If the constructor (or a method that uses the object) is not inlined, the object reference is passed to code the compiler cannot see, so the compiler must assume the object escapes and allocates it on the heap.