10.2 Three-Address Code
Three-address code (TAC) is the workhorse IR shape. The rule is simple: each instruction performs at most one operation over a small number of operands, typically of the form t = a op b.
This flatness is the point. Nested expressions become explicit instruction sequences, intermediate results get names, and every later analysis sees a uniform format.
Temporaries and Order
Translating a + b * c cannot be one instruction. Precedence forces b * c first, into a temporary, then the addition:
t1 = b * c
t2 = a + t1Parentheses change the shape. (a + b) * c reverses the order. The temporaries are not noise; they encode evaluation order and define-use structure that optimizers depend on.
Why Flat Beats Tree
A tree hides instruction order; TAC makes it explicit. With each operation isolated and named, the compiler can move, fold, or delete instructions safely.
TAC is also the natural pre-SSA form: temporaries are about to become versioned values, and register allocation will later decide which temporaries share hardware registers.
The Common Instruction Forms
TAC is not only t = a op b. A small, regular instruction set covers most of a language:
- binary:
t = a op b
- unary:
t = op a
- copy:
x = y
- jump:
goto L
- conditional jump:
if x relop y goto L
- call:
param a; t = call f, n
- index/field:
t = a[i],a[i] = t
This regularity is the whole point. Optimizers and register allocators handle a dozen shapes, not a thousand grammar productions.
Representing TAC: Quadruples and Triples
Two classic encodings exist. A quadruple stores (op, arg1, arg2, result), naming each result explicitly. A triple omits the result name and refers to instructions by position. Quadruples are easier to reorder and are the usual choice; triples are denser but fragile when instructions move.
Worked Example: A Conditional
The source if (a < b) m = a; else m = b; lowers to roughly:
t1 = a < b
if t1 goto L1
m = b
goto L2
L1: m = a
L2:Notice how structured control flow becomes labels and jumps. That flattening is exactly what later turns into basic blocks and a control flow graph.