90 likes | 197 Views
CS 201 Compiler Construction. Lecture 5 Code Optimizations: Copy Propagation & Elimination. Global Code Optimizations. Copy Propagation & Elimination: copy assignments are eliminated by replacing lhs variable with rhs variable.
E N D
CS 201Compiler Construction Lecture 5 Code Optimizations: Copy Propagation & Elimination
Global Code Optimizations • Copy Propagation & Elimination: copy assignments are eliminated by replacing lhs variable with rhs variable. • Constant Folding & Propagation: constant assignments are exploited by substituting constant values for variables; if all operands of an expression are found to be constants, the expression can be computed at compile time. • Strength Reduction: replaces expensive operations with cheaper ones – multiplaction addition; exponentiation multiplication.
Global Code Optimizations • Partial Redundancy Elimination: eliminating repeated evaluation of the same expression. • Loop Invariant Code Motion (full redundancy) • Common Sub-Expression Elimination (full redundancy) • The idea applies to expressions, loads, and even conditional branches. • Partial Dead Code Elimination: avoiding execution of statements whose results are not used. • Dead Code Elimination • The idea applies to expressions and stores.
Copy Propagation & Elimination 1. Uses of A replaced by uses of B. 2. A=B is eliminated because no more uses of A are left.
Contd.. Conditions under which optimization can be performed: • Copy A=B is the only definition of A that reaches each use of A in def-use chain of A=B, i.e. no definition of A is encountered along the way. • There is no definition of B on any path from d to any use u including paths through u that do not pass through d again.
Data Flow Equations IN[B]: Copies that reach B’s entry. OUT[B]: Copies that reach B’s exit. GEN[B]: Copies in B that reach the end of the block, i.e., no redefinitions of variables used in the copy statement. KILL[B]: Copies not in B whose variables (lhs or rhs) are defined in B.
Data Flow Analysis The analysis propagates copies such that a copy reaches its use only if it can be propagated to the use. However, the copy can only be eliminated if it can be propagated to all of its uses.
Code Transformation Algorithm for each copy S: X=Y do OK = true for each use u on def-use(X,S) do if (s is in IN[B] where B contains a use of X) and (there is no redinifition of X or Y in B prior to u) then /* can propagate */ else OK = false endif /* cannot propagate */ endfor if Ok then replace all uses u of X in def-use(X,S) by use of Y; remove S endif endfor
Example A=B X=A+2 A=B X=B+2 Eliminated: D=A Not Eliminated: A=B Y=D W=A W=B A=3*M Y=B Z=B+2 W=B+3 D=A A=3*M Y=D Z=D+2 W=D+3 W=A Assume W,A,X,Y,Z Are live