Search code examples
jvmjvm-hotspot

HotSpot JIT, dead code elimination and side effects?


HotSpot can perform JIT optimisations to remove dead code, making the code faster and smaller.

How does it know that the code it is removing doesn't have side-effects, or if it calls into native code; say, through a HotSpot intrinsic such as System.nanoTime()? Does it avoid calling methods and rely on in-lining to know whether an expression has side-effects, or does it only work for eliminating if cases?


Solution

  • Many hotspot optimizations happen after inlining, so they only require local knowledge. DCE applies to branches and unused results.

    Dead branches are easy to prune because they cannot have side-effects when they're not reachable.

    Unused results can back-popagate their deadness until they either leave the local (after inlining!) scope or hit something that has side-effects, which is no different from a used result.

    Intrinsics are not native code in the same sense as JNI. The methods are declared native, but the point of an intrinsic is that the compiler has more knowledge about how to optimize it than arbitrary native code.