Code Optimization III
Code Optimization III
[email protected] 07/07/2023 29
Common Subexpressions
● An occurrence of an expression E is called a common subexpression if E was
previously computed and the values of the variables in E have not changed
since the previous computation.
● Avoid re-computing an already computed value
● Common Subexpression can be local or global
[email protected] 07/07/2023 30
Common Subexpressions Elimination
t6 = 4*i
x = a[t6] t6 = 4*i
t7 = 4*i x = a[t6]
B5 t8 = 4*j B5 t8 = 4*j
t9 = a[t8] t9 = a[t8]
a[t7] = t9 a[t6] = t9
t10 = 4*j a[t8] = x
a[t10] = x goto B2
goto B 2
After
Before
[email protected] 07/07/2023 31
Common Subexpressions Elimination
As t5 = a[t4]
Before After
computed in block
B3 [email protected] 07/07/2023 33
Common Subexpressions Elimination
As t2 = 4*i and
t3=a[t2] computed in 34
[email protected] 07/07/2023
block B3
Common Subexpressions Elimination
t = d+e t = d+e
a = d+e b = d+e
a=t b=t
c = d+e c=t
x = t3 x = t3
B5 a[t2] = t5 a[t2] = t5
B5
a[t4] = x a[t4] = t3
goto B2 goto 2
Before
After
[email protected] 07/07/2023 37
Dead-Code Elimination
● A variable is live at a point in a program if its value can be used later in the
program, otherwise, it is dead at that point.
● Copy propagation often introduces dead code
z=x+y
z=x+y
p=x
w=x+y+z
w=x+y+z
Before After
x = t3 a[t2] = t5
B5 a[t2] = t5 a[t4] = t3
B5
a[t4] = t3 goto 2
goto 2
Before After
[email protected] 07/07/2023 39
Constant Folding
● Recognizing and evaluating constant expressions at compile time rather than
computing them at runtime.
a=2 a=2
b=a+2 b=4
c=6-a+3 c=7
Before After
[email protected] 07/07/2023 40