Professional Documents
Culture Documents
Code Optimization
Code Optimization
CODE OPTIMIZATION
1
AIM OF CODE OPTIMIZATION
3
PLACES FOR IMPROVEMENT
• Source Code
• User can profile program, change algorithm, transform loops
• Intermediate code
• Compiler can improve loops, procedure calls, address
calculations
• Target code
• Compiler can use registers, select instructions, peephole
transformations
4
CONSTRAINTS
5
ORGANIZATION OF CODE
OPTIMIZER
6
BASIC BLOCK
7
PARTITIONING INTO BASIC
BLOCKS
• Identify leaders
• First Statement
• Any statement that is the target of a conditional or
unconditional goto
• Any statement immediately following a goto / conditional goto
• Group all statements from one leader to next
8
9
10
TRANSFORMATIONS ON
BASIC BLOCKS
• Two Basic blocks are said to be equivalent if they
compute the same set of expressions
• Types of transformations
• Structure Preserving
• Algebraic
• Structure Preserving Transformations
• Common Sub-expression elimination
• Dead-code elimination
• Renaming Temporary variables
• Interchanging statements
11
COMMON SUB EXPRESSION
ELIMINATION
a:=b+c a:=b+c
b:=a–d b:=a–d
c:=b+c c:=b+c
d:=a–d d:=b
Before After
12
RENAMING TEMPORARY
VARIABLES
13
INTERCHANGE OF STATEMENTS
• Two statements
t1 : = b + c and
t2 : = x + y can be interchanged without
affecting the value of the block if and only if neither x
nor y is t1 and neither b nor c is t2.
14
ALGEBRAIC TRANSFORMATIONS
15
PRINCIPAL SOURCES OF
OPTIMIZATION
• Local Vs Global
• Function Preserving transformations
• Common Sub Expression Elimination
• Copy Propagation
• Dead code Elimination
• Constant folding
• Loop Optimization
• Code Motion
• Induction Variables and Reduction in Strength
16
Local Optimization – Common Sub
Expression Elimination 17
After Global
Common Sub
Expression
elimination
18
Strength Reduction
19
Copy
Propagation and
Dead Code
Elimination in
Blocks 5 and 6
20
PEEPHOLE OPTIMIZATION
23
FLOW OF CONTROL
OPTIMIZATIONS
• Elimination of Unnecessary jumps
goto L1 goto L2
L1: goto L2 L2: goto L2
Before After
if a < b goto L1 if a < b goto L2
L1: goto L2 L1: goto L2
Before After
24
OTHER OPTIMIZATIONS
• Algebraic Simplification
• Reduction in Strength
• Use of Machine Idioms
• Usage of auto increment and auto decrement modes
25