- Peephole optimization
In
compiler theory , peephole optimization is a kind of optimization performed over a very small set of instructions in a segment of generated code. The set is called a "peephole" or a "window". It works by recognising sets of instructions that don't actually do anything, or that can be replaced by a leaner set of instructions.Replacement Rules [Crafting a Compiler with C++, Fischer/LeBlanc]
* Constant Folding: Evaluate constant subexpressions in advance.
* Strength Reduction: Replace slow operations with faster equivalents.
* Null Sequences: Delete useless operations
* Combine Operations: Replace several operations with one equivalent.
* Algebraic Laws: Use algebraic laws to simplify or reorder instructions.
* Special Case Instructions: Use instructions designed for special operand cases.
* Address Mode Operations: Use address modes to simplify code.Of course there can be other types of peephole optimizations involving simplifying the target machine instructions, assuming that the target machine is known in advance. Advantages of a given architecture and instruction sets can be exploited in this case.
Example
The following Java assembler code
... aload 1 aload 1 mul ...
can be replaced by
... aload 1 dup mul ...
This kind of optimization, like most peephole optimizations, makes certain assumptions about the efficiency of instructions. For instance, in this case, it is assumed that the
dup
operation (which duplicates and pushes the top of the stack) is more efficient than theaload X
operation (which loads a localvariable identified asX
and pushes it on the stack).Another example is to eliminate redundant load stores. a = b + c; d = a + e;is straightforwardly implemented as
but can be optimised toMOV b, R0 # Copy b to the registerADD c, R0 # Add c to the register, the register is now b+cMOV R0, a # Copy the register to aMOV a, R0 # Copy a to the registerADD e, R0 # Add e to the register, the register is now a+e [(b+c)+e] MOV R0, d # Copy the register to d
Furthermore, if the compiler knew that the variableMOV b, R0 # Copy b to the register ADD c, R0 # Add c to the register, which is now b+c (a)MOV R0, a # Copy the register to aADD e, R0 # Add e to the register, which is now b+c+e [(a)+e] MOV R0, d # Copy the register to da
was not used again, the middle operation could be omitted.Implementation
Modern architectures typically allow for many hundreds of different kinds of peephole optimizations, and it is therefore often appropriate for
compiler programmers to implement them using apattern matching algorithm . Fact|date=July 2008References
External links
* [ftp://ftp.cs.princeton.edu/pub/lcc/contrib/copt.shar The copt general-purpose peephole optimizer by Christopher W. Fraser]
* [http://oarizo.com/downloads/misc/copt2.zip Source code for Vaughn Cato's peephole optimizer]
* [http://portal.acm.org/citation.cfm?id=365000 The original paper]
Wikimedia Foundation. 2010.