CS346 Code Generation II
CS346 Code Generation II
CS 346
Compiler Architecture
Intermediate
Intermediate
Language
Language
Symbol
Table
Register Allocation
.
Concept: Variable Liveness
• For some statement s, variable x is live if
– there is a statement t that uses x
– there is a path in the CFG from s to t
– there is no assignment to x on some path from s to t
• A variable is live at a given point in the source
code if it could be used before it is defined.
• Liveness tells us whether we care about the value
held by a variable
Example: When is a live?
a := b + c
t1 := a * a a is live
b := t1 + a
c := t1 * b
t2 := c + b
a := t2 + t2
t1 := a * a
b := t1 + a
c := t1 * b
t2 := c + b
a := t2 + t2
K=3 K=4
No color for
this node
Register Allocation and Graph
K-Coloring
a := b + c {b,c} a c
t1 := a * a {a} t1
b := t1 + a {t1,a}
c := t1 * b {b,t1} b t2
t2 := c + b {b,c}
a := t2 + t2 {b,c,t2}
{a,b,c}
Algorithm: K registers
3. Simplify-For any node m with fewer than K
neighbors,
a c
t1
b t2
a c
t1
b t2
a Remove a
t1
Example
Assume k = 3
a c
t1
b t2
b
a Remove b
t1
Example
Assume k = 3
a c
t1
c b t2
b
a Remove c
t1
Example
Assume k = 3
a c
t1
t2
c b t2
b
a Remove t2
t1
Rebuild the graph
Assume k = 3
c t2
b
a
t1
Example
Assume k = 3
t2
b
a
t1
Example
Assume k = 3
b t2
a
t1
Example
Assume k = 3
a c
b t2
t1
Example
Assume k = 3
a t0 a c
b t1 t1
c t2
b t2
t1 t2
t2 t0
Back to example
lw $t1,b
lw $t2,c
a := b + c add $t0,$t1,$t2
a t0
t1 := a * a mul $t2,$t0,$t0
b t1
b := t1 + a add $t1,$t2,$t0
c t2 mul $t2,$t2,$t1
c := t1 * b
t1 t2 add $t0,$t2,$t1
t2 := c + b
t2 t0 add $t0,$t0,$t0
a := t2 + t2
sw $t0,a
sw $t1,b
sw $t2,c
Generated code: Basic Generated Code: Coloring
lw $t0,b lw $t1,b
lw $t1,c lw $t2,c
add $t0,$t0,$t1 add $t0,$t1,$t2
mul $t1,$t0,$t0 mul $t2,$t0,$t0
add $t0,$t1,$t0 add $t1,$t2,$t0
mul $t1,$t1,$t0 mul $t2,$t2,$t1
add $t2,$t1,$t0 add $t0,$t2,$t1
add $t2,$t2,$t2 add $t0,$t0,$t0
sw $t2, a sw $t0,a
sw $t0,b sw $t1,b
sw $t1,c sw $t2,c
Example, k = 2
Assume k = 2
a c
t1
b t2
Remove b as spill
b*
Example
Assume k = 2
a c
t1
b t2
t1 Remove t1
b*
Example
Assume k = 2
a c
t1
b t2
a
t1 Remove a
b*
Example
Assume k = 2
a c
t1
c b t2
a
t1 Remove c
b*
Example
Assume k = 2
a c
t1
t2
c b t2
a
t1 Remove t2
b*
Example
Assume k = 2
Can flush b out to
memory, creating a
a c
smaller window
t1
a := b + c {b,c}
t1 := a * a {a} b t2
???
b := t1 + a {t1,a}
c := t1 * b {b,t1}
t2 := c + b {b,c}
a := t2 + t2 {b,c,t2}
{a,b,c}
After spilling b:
a := b + c {b,c} a c
t1 := a * a {a} t1
b := t1 + a {t1,a}
c := t1 * b {b,t1} b t2
b to memory
t2 := c + b {b,c}
a := t2 + t2 {c,t2}
{a, c}
After spilling b:
a c
t1
b t2
t2
After spilling b:
a c
t1
b t2
c*
t2 Have to choose c as a potential
spill node.
After spilling b:
a c
t1
b t2
b
c*
t2
After spilling b:
a c
t1
a b t2
b
c*
t2
After spilling b:
a c
t1
t1
a b t2
b
c*
t2
Now rebuild:
a c
t1
a b t2
b
c*
t2
Now rebuild:
a c
t1
b t2
b
c*
t2
Now rebuild:
a c
t1
b t2
c*
t2
Now rebuild:
a c
t1
b t2