leventov
leventov

Reputation: 15263

Does Hotspot JVM perform redundancy elimination of casts, unboxing and divisions?

For example, in this case

int x;
for (...) {
    ... some work, y and z not changed
    x = y / z;
    ... some code using x
}

Is JVM (actually JIT compiler) allowed to compute x = y / z once before the for loop and "some work" (with side effects probably or throwing different exceptions), if it couldn't prove that z is non-zero, to throw ArithmeticException at the "right" moment?

The same question about casts (which might result to ClassCastException) and unboxing (which might cause NullPointerException), still assuming in the certain case JVM/JIT compiler cannot prove that the object has appropriate class or unboxed value is non-null.

Upd. morgano said that this question is devoted to the JVM implementation. In this case, my question is about Hotspot JVM/JIT compiler implementation.

Upvotes: 2

Views: 476

Answers (1)

apangin
apangin

Reputation: 98284

Yes, HotSpot JVM can generally do this.

One of the key features of C2 JIT compiler is speculative optimization. This means JIT can compile with an assumption that runtime exception is not thrown. In this case it can easily apply Common Subexpression Elimination, Loop Invariant Hoisting and other relevant optimizations.

If at some point a speculative assumption happens to fail, JIT deoptimizes the method and continue execution in interpreted mode, so that runtime exception is thrown at the right place.

BTW, I've checked the generated assembly that HotSpot indeed calculates x = y / z just once in your example.

Upvotes: 2

Related Questions