Sub topic 14
Live Variable Analysis
Assume you know basic set operations, control-flow graphs, and three-address code. This chapter uses those ideas to determine whether a variable may be needed later in a program.
Working model
A variable is live at a program point if its current value may be read before the variable is assigned a new value. Otherwise, it is dead. A compiler uses this information to remove useless assignments, reuse registers, and reduce memory traffic.
Live-variable analysis is a backward analysis because future uses determine whether a current value matters. For each basic block, define:
use[B]: variables read inBbefore any definition inB.def[B]: variables assigned inB.IN[B]: variables live immediately beforeB.OUT[B]: variables live immediately afterB.
The transfer equations are:
OUT[B] = union of IN[S] for every successor S of B
IN[B] = use[B] union (OUT[B] - def[B])A definition kills the older value of that variable. A use adds the variable because its current value must survive until that use.
Worked example
Consider these blocks:
| Block | Statements | use | def |
|---|---|---|---|
| B1 | `a = 1; s = 0` | `{}` | `{a, s}` |
| B2 | `s = s + a` | `{s, a}` | `{s}` |
| B3 | `return s` | `{s}` | `{}` |
The exit block has no successors, so OUT[B3] = {}. Therefore:
IN[B3] = {s} union ({} - {}) = {s}For B2, the successors are B2 itself and B3. At the fixed point, OUT[B2] contains {s, a} because the loop may execute again and B3 needs s. Then:
IN[B2] = {s, a} union ({s, a} - {s})
= {s, a}B1 has B2 as its successor:
OUT[B1] = IN[B2] = {s, a}
IN[B1] = {} union ({s, a} - {a, s}) = {}A compact solver repeatedly applies these equations:
def live_variables(blocks, successors, use, defs):
live_in = {b: set() for b in blocks}
live_out = {b: set() for b in blocks}
changed = True
while changed:
changed = False
for block in reversed(blocks):
new_out = set()
for successor in successors[block]:
new_out |= live_in[successor]
new_in = use[block] | (new_out - defs[block])
if new_in != live_in[block] or new_out != live_out[block]:
live_in[block] = new_in
live_out[block] = new_out
changed = True
return live_in, live_outThe process stops at a fixed point, where another pass changes no set.
Exercise
A block contains x = 4; y = x + 1; return y. What are its use and def sets?
Show answer
use = {} because x is defined before it is read, and def = {x, y}.