Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler optimization: Java bytecode

I'm currently writing a toy compiler targeting Java bytecode in the translation.

I would like to know if there is some kind of catalog, maybe a summary, of various simple peephole optimizations that can be made in the emitted bytecode before writing the .class file. I actually am aware of some libraries that have this functionality, but I'd like to implement that myself.

like image 592
Giuliano Vilela Avatar asked Nov 05 '09 11:11

Giuliano Vilela


People also ask

Does Java compiler optimize code?

More importantly, the javac compiler does not perform simple optimizations like loop unrolling, algebraic simplification, strength reduction, and others. To get these benefits and other simple optimizations, the programmer must perform them on the Java source code and not rely on the javac compiler to perform them.

Does Java compiler generate bytecode?

Compiler converts the source code or the Java program into the Byte Code(or machine code), and secondly, the Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java Virtual Machine).

What are the advantages of Java bytecode?

Advantages of Bytecode Bytecodes are non-runnable codes that rely on the availability of an interpreter, this is where JVM comes into play. It is a machine-level language code that runs on the JVM. It adds portability to Java which resonates with the saying, “write once, read anywhere”.

How does a compiler optimize code?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.


1 Answers

You are aware of Proguard? http://proguard.sourceforge.net/

This is a great bytecode optimizer which implements a lot of optimizations. See the FAQ for a list: http://proguard.sourceforge.net/FAQ.html

  • Evaluate constant expressions.
  • Remove unnecessary field accesses and method calls.
  • Remove unnecessary branches.
  • Remove unnecessary comparisons and instanceof tests.
  • Remove unused code blocks.
  • Merge identical code blocks.
  • Reduce variable allocation.
  • Remove write-only fields and unused method parameters.
  • Inline constant fields, method parameters, and return values.
  • Inline methods that are short or only called once.
  • Simplify tail recursion calls.
  • Merge classes and interfaces.
  • Make methods private, static, and final when possible.
  • Make classes static and final when possible.
  • Replace interfaces that have single implementations.
  • Perform over 200 peephole optimizations, like replacing ...*2 by ...<<1.
  • Optionally remove logging code.

I'm sure you can further look into the source code to understand how they are implemented.

like image 81
Sean Owen Avatar answered Sep 28 '22 09:09

Sean Owen