Basic Blocks and Flow Graphs
Basic Blocks and Flow Graphs
Code Optimization
• A main goal is to achieve a better performance
source
Front End Intermediate Code Gen target
Code
Code Code
user Machine-
independent Machine-
Compiler dependent
optimizer Compiler
optimizer
• Two levels
T1:=4*I
T2:=addr(A)-4
T3:= T2[T1]
T4:= addr(B)-4 B2
T5:= T4[T1]
T6:= T3*T5
PROD:=PROD+T6
I:=I+1
If I ≤ 20 goto (3)
Quicksort
// assume an external input-output array: int a[]
void quicksort( int m, int n ) {
int i, j, v, x; // temps
if ( n <= m ) return;
i = m-1;
j = n;
v = a[n];
while(1) {
do i=i+1; while( a[i] < v );
do j=j-1; while( a[j] > v );
if ( i >= j ) break;
x = a[i]; a[i] = a[j]; a[j] = x;
} //end while
x = a[i]; a[i] =a [n]; a[n] = x;
quicksort( m, j );
quicksort( i+1, n );
} //end quicksort
Principle sources of optimization
• Local optimization: within a basic block
• Global optimization: otherwise
• Mixed
Function-Preserving Transformation
• Improving performance w/o changing fn.
• Techniques
– Common subexpression Elimination
– Copy Propagation
– Dead-code elimination
– Constant folding
Common subexpression Elimination
• An occurrence of an expression E is common
subexpression if E was previously computed
and the values of variables in E have not
changed since.
Copy Propagation
• An idea behind this technique is to use g for f
whenever possible after the copy of
f := g
before After
x := t3 x := t3
a[t7] := t5 a[t7] := t5
a[t10] := x a[t10] := t3
Goto b2 Goto b2
Dead code elimination
• Remove unreachable code
• If (debug) print …
• before after
• While ( I <= limit – 2). T = limit – 2
• While ( I <= t)
Induction-variable elimination & Reduction
in strength
• Look for induction variables for strength
reductions
• E.g. a pattern of changes in a lock step
B3: B3:
j = j - 1 j = j - 1
t4 = 4 *j t4 = t4 -4
t5 = a [ t4] t5 = a [ t4]
If t5 > v goto B3 If t5 > v goto B3
Others optimizations
• Optimizations for Basic blocks
• Reducible flow graph
• Global Data flow analysis
• Machine dependent Optimizations