Translating to three-address code
How to translate high-level language constructs into target-independent three-address code (TAC), with representations (quadruples/triples), translation rules, and backpatching for control flow.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Translating source programs to three-address code (TAC) is a central step in the compiler back-end: an engineer uses this intermediate form to perform machine-independent optimisations (like constant folding, common subexpression elimination), and to generate target machine code. TAC is simple, low-level, and easy to analyze and transform before register allocation and final code emission.
Key ideas
Temporaries: temporary variables (often named t1, t2, ...) hold intermediate results. A function
newtemp()returns a fresh temporary name.Quadruples, triples, indirect triples: three representation styles for TAC.
- Quadruple: record with fields (op, arg1, arg2, result). Exact layout: draw a table with columns labeled "op | arg1 | arg2 | result" and each instruction as a row.
- Triple: record with fields (op, arg1, arg2) and results are referenced by instruction index. Draw a table "# | op | arg1 | arg2" and indicate that result of row i is referenced as i.
- Indirect triple: like triples but with an extra table of pointers so rows can be reordered without changing indices.
Syntax-directed translation: attach semantic actions to grammar productions to emit TAC. Define functions and data structures used by semantic actions:
newtemp()— returns fresh temporary name.newlabel()— returns fresh label name.emit(instruction)— append a TAC instruction to the instruction list.- For backpatching:
makelist(i)creates a list containing jump target position i;merge(l1,l2)concatenates lists;backpatch(list, label)patches all entries in list with label.
Backpatching: technique to handle forward jumps when the target label is not yet known. Use lists of jump-instruction indices to be patched later. Commonly used for boolean expressions and control statements (
if,while).Exact translation rules (assume grammar nonterminals hold attributes
place(result temporary) andtruelist/falselistornextlistfor backpatching):Arithmetic expressions: For production E -> E1 + E2
E.place = newtemp()emit(E.place " = " E1.place " + " E2.place)Same for -, *, / with corresponding op.
Relational expression for conditional jumps (use backpatch lists): For production E -> E1 < E2
emit('if ' + E1.place + ' < ' + E2.place + ' goto _')and let i be the index of this instruction // emits a conditional jump with unknown targetemit('goto _')and let j be the index of this instruction // a complementary unconditional jumpE.truelist = makelist(i)E.falselist = makelist(j)
If statement with else: S -> if (E) S1 else S2
- After computing E,
backpatch(E.truelist, L1)where L1 is the start label of S1 backpatch(E.falselist, L2)where L2 is the start label of S2- At the end of S1 emit
goto _to skip the else-part, and setS1.nextlist = makelist(index_of_that_goto) S.nextlist = merge(S1.nextlist, S2.nextlist)
- After computing E,
While loop: S -> while (E) S1
- Let L1 = newlabel() for loop entry and emit label L1.
- Compute E; let L2 be the start label of S1.
backpatch(E.truelist, L2)so true flows into the body;S.nextlist = E.falselist(to be patched to the exit label later). - Emit the body S1 starting at L2; after S1, emit
goto L1to re-evaluate E.
Boolean expression short-circuit: Translate
E1 && E2by backpatchingE1.truelistto the start of E2;E.truelist = E2.truelist;E.falselist = merge(E1.falselist, E2.falselist). ForE1 || E2, backpatchE1.falselistto the start of E2;E.truelist = merge(E1.truelist, E2.truelist);E.falselist = E2.falselist.What to draw (diagrams):
- For an expression tree: draw nodes labeled with operators (+, *, etc.) and leaves labeled by operands (a, b, c). Label each internal node with the temporary that will hold its value. Example: draw root
-with left child+and right childc; label left child with t1, root with t2. - For basic-block flow graph: draw boxes for basic blocks with their TAC instructions listed inside; draw directed edges for control flow (true/false exits). Label edges "true"/"false" where appropriate.
- For an expression tree: draw nodes labeled with operators (+, *, etc.) and leaves labeled by operands (a, b, c). Label each internal node with the temporary that will hold its value. Example: draw root
Assumptions: unlimited temporaries and labels, no machine-specific registers yet, side-effecting expressions are evaluated left-to-right unless language specifies otherwise.
Formulas
x = y op z — op is a binary operator (e.g., +, -, *, /); x,y,z are variables or temporaries. Applies to arithmetic/bitwise ops.
x = op y — unary op (e.g., -y, !y). x,y are variables/temporaries.
if x relop y goto L — conditional jump; relop is a relational operator (==, !=, <, >, <=, >=); L is a label.
goto L — unconditional jump to label L.
param x — push parameter x (used before call).
call f, n — call function f with n parameters; result commonly placed in a fresh temporary or a designated return place.
return x — return value x from current function.
label L: — defines a label L appearing on a separate line before an instruction.
For backpatching primitives:
makelist(i) — make a list containing instruction index i.
merge(l1, l2) — concatenate two lists of instruction indices.
backpatch(list, label) — for each index i in list, fill the target field of instruction i with label.
Worked examples
Example 1 — arithmetic expression: a + b * c
- Draw the expression tree: root
+with left leafaand right subtree*with leavesb,c. - Postorder generate:
- For
b * c:t1 = b * c(emitt1 = b * c) - For
a + t1:t2 = a + t1(emitt2 = a + t1)
- For
- Final TAC (order):
t1 = b * ct2 = a + t1
Example 2 — if-else: if (a < b) c = d + e; else c = d - e;
- Translate
a < binto conditional and complementary jump:- emit
if a < b goto _// index 1 - emit
goto _// index 2
- emit
- Label the then-part start L1, else-part start L2.
- backpatch truelist = {1} to L1, falselist = {2} to L2.
- Emit then-part at L1:
t1 = d + ec = t1- emit
goto L3// jump past else, index 5
- Emit else-part at L2:
t2 = d - ec = t2
- L3 is next label (after else). Backpatch as needed.
Resulting TAC (with labels):
L1:
t1 = d + e
c = t1
goto L3
L2:
t2 = d - e
c = t2
L3:
(continuation)
Example 3 — while loop with backpatching: while (i < n) i = i + 1;
- Let L1 = start label. Emit
label L1: - Evaluate
i < n: emitif i < n goto _(index 1); emitgoto _(index 2) - Backpatch truelist {1} to L2 (start of body), falselist {2} to L3 (exit)
- At L2: emit
t1 = i + 1;i = t1;goto L1 - L3: continuation
TAC sketch:
L1:
if i < n goto L2
goto L3
L2:
t1 = i + 1
i = t1
goto L1
L3:
(after loop)
Check: ensure jump indices used by backpatch are correctly recorded and patched.
Common mistakes
- Confusing truelist and falselist when translating
&&and||(short-circuit rules reversed). - Trying to evaluate boolean expressions to a single temporary before using short-circuit jumps — this may change semantics for side-effecting operands.
- In quadruples vs triples: forgetting that triples reference results by instruction index, so reordering instructions without updating references breaks code unless using indirect triples.
- Not emitting
gotoafter the then-part inif-else, leading to fall-through into the else-part.
For your exam
Question types you will see:
- Definitions: define TAC, quadruples, triples, temporaries, backpatching.
- Short notes: compare quadruples and triples; explain backpatching algorithm.
- Derivations: show syntax-directed translation rules for expressions and control flow with semantic actions and backpatching.
- Programs/algorithms: translate given high-level code to TAC (step-by-step), produce quadruple/table form.
- Diagrams: draw expression trees and basic-block flow graphs and label temporaries and edges.
What a full-marks answer includes:
- Precise definitions (bold the term), clear assumptions (e.g., unlimited temporaries), and the correct translation rules with semantic actions.
- For program translation: a clear stepwise trace, emitted TAC lines with instruction indices or labels, and a final table (quadruples or triples).
- For backpatching questions: show makelist/merge/backpatch calls and final patched targets.
- For representation comparisons: list pros/cons/when to use indirect triples.
Quick check
- What is a quadruple representation?
- How does backpatching handle forward jumps?
- Translate
x = (a + b) * (c - d)into TAC with temporaries.
Answers: 1) A record form (op, arg1, arg2, result) for each TAC instruction; 2) Record indices of jump instructions in lists (makelist), and when the target label is known call backpatch(list,label) to fill targets; 3) t1 = a + b \nt2 = c - d \nt3 = t1 * t2 \nx = t3.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?