Sub topic 7
Three-Address Code
Assume you know basic C-style expressions, parse trees, and syntax-directed translation. You should also be comfortable with temporary variables and simple control-flow labels.
Three-address code (TAC) is an intermediate representation in which each instruction contains at most three addresses: usually two operands and one result. An address can be a variable, constant, temporary, or label. TAC is simpler than source code and more structured than machine instructions, so later compiler phases can analyze and optimize it.
Basic instruction forms
Common TAC instructions include:
| Purpose | TAC form | Example |
|---|---|---|
| Binary operation | `x = y op z` | `t1 = a + b` |
| Unary operation | `x = op y` | `t2 = minus c` |
| Copy | `x = y` | `a = t2` |
| Conditional jump | `if x relop y goto L` | `if a < b goto L1` |
| Unconditional jump | `goto L` | `goto L2` |
A compiler introduces a new temporary for an intermediate result. This makes evaluation order explicit and gives each step a simple form.
Translating an expression
Consider this expression:
a = b * -c + b * -c;A direct TAC translation is:
t1 = minus c
t2 = b * t1
t3 = minus c
t4 = b * t3
t5 = t2 + t4
a = t5Each binary instruction has one operator and two operands. The two occurrences of b * -c are translated independently. A later optimization phase may recognize that they compute the same value and eliminate the repeated calculation, but the initial translation should preserve the source expression faithfully.
The following diagram shows how the expression is lowered into successive operations:
Translating statements
An assignment such as x = y + z * w becomes:
t1 = z * w
t2 = y + t1
x = t2For an array access, a compiler first computes the address or offset. For example, x = a[i] may become:
t1 = i * element_size
t2 = a + t1
x = *t2The exact representation depends on the target machine and type sizes. The important point is that address calculation and memory access become separate operations.
A conditional statement uses labels:
if x < y goto L_true
goto L_false
L_true:
z = 1
goto L_end
L_false:
z = 0
L_end:TAC labels identify possible control-flow destinations. Basic blocks and control-flow graphs can be built from these labels in a later compiler phase.
Exercise
Translate r = (p + q) * (p - q) into three-address code.
Show answer
t1 = p + q; t2 = p - q; t3 = t1 * t2; r = t3.