Peephole optimization

From Wikipedia, the free encyclopedia

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.

Contents

[edit] Replacement Rules[1]

  • 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.

[edit] 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 the aload X operation (which loads a local variable identified as X and pushes it on the stack).

Another example is to eliminate redundant load stores.

 a = b + c; 
 d = a + e;

is straightforwardly implemented as

MOV b, R0  # Copy b to the register
ADD c, R0  # Add  c to the register, the register is now b+c
MOV R0, a  # Copy the register to a
MOV a, R0  # Copy a to the register
ADD e, R0  # Add  e to the register, the register is now a+e [(b+c)+e]
MOV R0, d  # Copy the register to d 

but can be optimised to

MOV 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 a
ADD e, R0 # Add e to the register, which is now b+c+e [(a)+e]
MOV R0, d # Copy the register to d

Furthermore, if the compiler knew that the variable a was not used again, the middle operation could be omitted.

[edit] 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 a pattern matching algorithm.

[edit] References

  1. ^ Crafting a Compiler with C++, Fischer/LeBlanc

[edit] External links

The Wiktionary definition of Peephole optimization.