Sub topic 15
Available Expressions
Assume you know basic blocks, control-flow graphs, and set operations. This chapter uses the terms gen, kill, IN, and OUT from the data-flow analysis framework.
An available expression is an expression whose value has already been computed on every path to a program point, and whose operands have not changed since that computation. The compiler can reuse the value instead of computing the expression again.
Available-expression analysis is a forward must-analysis:
- Forward means information moves from predecessors to successors.
- Must means an expression is available only when it is available along every incoming path.
- Therefore, the meet operation is set intersection.
For a basic block B:
IN[B] = intersection of OUT[P] for every predecessor P of B
OUT[B] = gen[B] union (IN[B] - kill[B])gen[B] contains expressions computed in B that remain valid when the block ends. kill[B] contains expressions invalidated because B assigns to one of their operands.
Worked control-flow example
At the start, assume no expression is available. Both branches compute a + b, and neither branch changes a or b.
| Block | gen | kill | IN | OUT |
|---|---|---|---|---|
| B2 | `{a + b}` | `{}` | `{}` | `{a + b}` |
| B3 | `{a + b}` | `{}` | `{}` | `{a + b}` |
| B4 | `{}` | `{}` | `{a + b}` | `{a + b}` |
At B4, intersection gives:
IN[B4] = OUT[B2] intersection OUT[B3]
= {a + b} intersection {a + b}
= {a + b}Thus, the compiler may replace z = a + b with a reuse of the earlier value, provided the intermediate representation preserves the value and the expression has no side effects.
Computing gen and kill
Suppose a block contains:
t1 = a + b
a = c
t2 = a + bThe first computation of a + b is no longer valid after a = c. The last computation can be generated by the block, so a + b belongs to gen[B]. Since the block assigns to a, every expression using a, including a + b, belongs to kill[B].
When scanning a block, later assignments can invalidate earlier computations. A safe analysis keeps only expressions whose operands remain unchanged at the block exit.
def available_out(in_set, gen_set, kill_set):
"""Apply the transfer equation for one basic block."""
return gen_set | (in_set - kill_set)
incoming = {"a + b", "c * d"}
generated = {"a + b"}
killed = {"a + b", "b - c"}
print(available_out(incoming, generated, killed))
# {'c * d', 'a + b'}The expression a + b is regenerated after being removed by the kill set.
Exercise
If OUT[B2] = {a + b, c * d} and OUT[B3] = {a + b, e - f}, what is IN[B4] when B2 and B3 are the predecessors of B4?
Show answer
IN[B4] = {a + b}, because available expressions use intersection across predecessors.