templatetypedef
templatetypedef

Reputation: 373462

Disabling optimization in javac?

I'm writing my own copy of the JVM and would like to test its behavior on some simple numeric operations, such as additions, subtractions, numeric overflow, etc. Rather than writing the bytecode by hand, I thought it would be a good idea to just write plain Java code, have javac compile it down to bytecode, and then test the JVM on that bytecode.

The problem is that javac is making a lot of (very sensible!) inline optimizations that prevent the code from testing what I'd like it to test. For example, one test tries to verify that integral overflows are handled correctly for all types. Here's one snapshot:

byte min = (byte)-128;
byte max = (byte) 127;

assertTrue((byte)(max + 1) == min); // Should overflow and work correctly.

The generated .class file has the result of ((byte)max + 1) hardcoded as (byte) -128, which completely defeats the point of the test.

My question is this: is there a way to disable optimization in javac? I haven't been able to find a command-line switch to do this, though perhaps I just haven't looked hard enough. If there is no way to do this, is there another Java compiler that does have the ability to compile with all optimizations turned off?

Upvotes: 7

Views: 2745

Answers (2)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74800

I think most of the optimizations you seem to think of are actually mandated by the JLS, as these are constant expressions. So, make sure you don't have constant expressions, and javac can't optimize them away.

In your example, you may write it like this:

byte min = new Byte((byte)-128).byteValue();
byte max = new Byte((byte) 127).byteValue();

assertTrue((byte)(max + 1) == min); // Should overflow and work correctly.

Upvotes: 3

Phil Miller
Phil Miller

Reputation: 38158

Many production compilers, including the common Sun-derived javac, do that sort of simplification no matter what optimization is set to.

Have you looked at Jasmin, the Java bytecode 'assembler'?

Upvotes: 2

Related Questions