Neural Sync Active
Intermediate Code Generation — TAC, 3-Address Code
Registry Synced
Intermediate Code Generation — TAC, 3-Address Code
624 words
3 min read
Reading compass
Now · 🎯 Learning Objectives
Intermediate Code Generation — TAC, 3-Address Code
🎯 Learning Objectives
- Translate expressions to three-address code
- Handle array references and pointer dereferences
- Generate TAC for control flow statements
- Use backpatching for boolean expressions
1. Three-Address Code (TAC)
1.1 Instruction Forms
| Form | Meaning | Example |
|---|---|---|
x = y op z | Binary operation | t1 = a + b |
x = op y | Unary operation | t2 = -t1 |
x = y | Copy | t3 = t2 |
goto L | Unconditional jump | goto L1 |
if x goto L | Conditional jump | if t1 < 0 goto L1 |
param x | Parameter passing | param a |
call f, n | Function call | call sum, 2 |
x = y[i] | Array access | t4 = arr[t3] |
x[i] = y | Array store | arr[t3] = t4 |
1.2 Translation Example
Source:
a = b * -c + b * -cpseudot1 = -c t2 = b * t1 t3 = -c t4 = b * t3 t5 = t2 + t4 a = t5
Optimized (common subexpression elimination):
pseudot1 = -c t2 = b * t1 t3 = t2 + t2 a = t3
2. Array Address Computation
2.1 1D Array
arr[i] → address = base + i × element_size
TAC:pseudot1 = i * 4 // element size = 4 bytes t2 = arr + t1 // base address + offset t3 = *t2 // load value
2.2 2D Array (Row-Major)
arr[i][j] → address = base + (i × num_cols + j) × element_size
TAC:pseudot1 = i * num_cols t2 = t1 + j t3 = t2 * 4 t4 = arr + t3 t5 = *t4
3. Control Flow Translation
3.1 If-Then-Else
Source:
cif (x < 100) { y = x + 1; } else { y = 0; }
TAC:
pseudoif x < 100 goto L1 goto L2 L1: t1 = x + 1 y = t1 goto L3 L2: y = 0 L3: ...
4. 📝 Practice Questions
Q1: Translatea = (b + c) * (d - e)to TAC.Answer:pseudot1 = b + c t2 = d - e t3 = t1 * t2 a = t3Q2: Explain the difference between TAC and AST.Answer: AST (Abstract Syntax Tree) is a tree representation of program syntax. TAC (Three-Address Code) is a linear sequence of simple instructions. TAC is closer to machine code, easier to optimize, and can be generated from AST by walking the tree. Q3: Generate TAC forfor (i=0; i<10; i++) sum += i;Answer:pseudoi = 0 L1: if i < 10 goto L2 goto L3 L2: t1 = sum + i sum = t1 t2 = i + 1 i = t2 goto L1 L3: ...Q4: What is backpatching?Answer: Backpatching is a technique for generating TAC for boolean expressions and control flow when jump targets are unknown at generation time. It leaves the target address empty and fills it in later when the label's location is known. This avoids multiple passes over the code. Q5: Translateif (a > b) x = 1; else x = 2;to TAC.Answer:pseudoif a > b goto L1 goto L2 L1: x = 1 goto L3 L2: x = 2 L3: ...
5. 🔗 Cross-References
- Week 9 - Optimization: Optimizing TAC
- Week 11 - Code Generation: Translating TAC to assembly
- Week 8 - Control Flow: Backpatching for boolean expressions Join Discord PreviousSemantic AnalysisNextCode Optimization