Sunteți pe pagina 1din 12

CH 9: CODE GENERATION PEEP HOLE Optimization

CMPUT 680 - Compiler Design and Optimization

Peephole Optimization
Goals: - improve performance - reduce memory footprint - reduce code size Method: 1. Exam short sequences of target instructions 2. Replacing the sequence by a more efficient one.
redundant-instruction elimination flow-of-control optimizations algebraic simplifications use of machine- Compiler Design CMPUT 680 idioms
and Optimization 2

Redundant Load and Stores

(1) LOAD R0, a (2) STORE a, R0

(1) LOAD R0, a

If there are no changes to a between (1) and (2), then the store (2) is redundant.
CMPUT 680 - Compiler Design and Optimization 3

Example
debug = 0 ... if(debug) { print debugging information }
debug = 0 ... if debug = 1 goto L1 goto L2 L1: print debugging information L2: CMPUT 680 - Compiler Design
and Optimization 4

Source Code:

Intermediate Code:

Eliminate Jump after Jump


debug = 0 ... if debug = 1 goto L1 goto L2 L1: print debugging information L2: debug = 0 ... if debug 1 goto L2 print debugging information

Before:

After:
L2:

CMPUT 680 - Compiler Design and Optimization

Constant Propagation
debug = 0 ... if debug 1 goto L2 print debugging information

Before: L2:

After:
L2:

debug = 0 ... if 0 1 goto L2 print debugging information


6

CMPUT 680 - Compiler Design and Optimization

Unreachable Code (dead code elimination)


debug = 0 ... if debug 1 goto L2 print debugging information

Before: L2:

After:

debug = 0 ...

CMPUT 680 - Compiler Design and Optimization

Flow-of-control optimizations
goto L1 ... L1: goto L2 goto L2 ... L1: goto L2

if a < b goto L1 ... L1: goto L2

if a < b goto L2 ... L1: goto L2

goto L1 if a < b goto L2 ... goto L3 L1: if a < b goto L2 ... CMPUT 680 - Compiler Design L3: L3:
and Optimization 8

Transformations on Basic Blocks


Structure-Preserving Transformations:
common subexpression elimination dead code elimination renaming of temporary variables interchange of two independent adjacent statements

CMPUT 680 - Compiler Design and Optimization

Examples of Transformations
Common subexpression elimination:

a := b + c b := a - d c := b + c d := a - d

a := b + c b := a - d c := b + c d := b

Dead code elimination:

if x is never referenced after the statement x = y+z, the statement can be safely eliminated.

CMPUT 680 - Compiler Design and Optimization

10

Examples of Transformations
Interchange of statements:

t1 := b + c t2 := x + y

t2 := x + y t1 := b + c

Renaming temporary variables: if there is a statement t := b + c, we can change it to u := b + c and change all uses of t to u.

CMPUT 680 - Compiler Design and Optimization

11

Examples of Transformations
Algebraic transformations:

x := x + 0 x := x * 1 x := y**2 z := 2*x

x := y*y z := x + x

Changes such as y**2 into y*y and 2*x into x+x are also known as strength reduction.
CMPUT 680 - Compiler Design and Optimization

12

S-ar putea să vă placă și