Sub topic 2
Three-Address Code
This chapter assumes you know C-style functions, stacks, graphs, parse trees, and set union, intersection, and difference.
Three-address code
Three-address code (TAC) is an intermediate form in which each instruction has at most one operator, two operands, and one result. Compilers create temporary names such as t1 to hold intermediate values. For example, a = b * -c + b * -c becomes:
t1 = minus c
t2 = b * t1
t3 = minus c
t4 = b * t3
t5 = t2 + t4
a = t5Quadruples, triples and indirect triples
These are three ways to store TAC in memory.
| Form | Fields | Trade-off |
|---|---|---|
| Quadruples | op, arg1, arg2, result | Easy to move or reorder instructions |
| Triples | op, arg1, arg2 | Saves space, but references use instruction positions, so moving code breaks them |
| Indirect triples | Triples plus a pointer list | Reorder by changing the pointer list only |
Translating control flow and boolean expressions
The compiler translates if (x < y && y < z) S with short-circuit jumps:
if x < y goto L2
goto Lfalse
L2: if y < z goto Ltrue
goto LfalseBackpatching
When a jump target is not yet known, the compiler emits the jump with an empty target and records its index in a list. Once the target label is known, the compiler fills in every recorded jump.
Basic blocks and control flow graphs
A basic block is a maximal run of instructions that the program enters only at its first instruction and leaves only at its last. A leader starts a block. The first instruction, every jump target, and every instruction after a jump is a leader. The control flow graph (CFG) links blocks by their possible transfers of control.
Local and peephole optimization
Local optimization works inside one basic block. Common subexpression elimination reuses a value that is already computed, constant folding evaluates 2 * 3 at compile time, and dead code elimination removes assignments whose results are never used. Peephole optimization examines a small window of instructions. It turns t = a + 0 into t = a.
Dominators and natural loops
Block d dominates block n if every path from the entry to n passes through d. A back edge goes from n to a block d that dominates n. The back edge and the blocks that reach n without passing through d form a natural loop with header d.
The data flow analysis framework
Each block B has a gen set (definitions it creates) and a kill set (definitions it overwrites). For reaching definitions, the equations are:
- IN[B] = union of OUT[P] for every predecessor P of B
- OUT[B] = gen[B] ∪ (IN[B] − kill[B])
Initialize all sets, then recompute them block by block until no set changes. That stable state is the fixed point.
Exercise
In the CFG above, does B2 loop back to itself, and which block does B1 flow into?
Show answer
B2 has a self-loop, and B1 flows into B2.