Compiler Design and Construction · Unit 4 · 16 hrs
Intermediate Code Generation, Code Generation and Optimization
Exam-focused notes for Intermediate Code Generation, Code Generation and Optimization (Compiler Design and Construction, CSC376): what the TU syllabus asks and how it has actually been tested, with 19 solved past questions from this unit.
Intermediate Code Generation, Code Generation and Optimization in short
This chapter follows a syntactically and semantically checked program the rest of the way through the compiler: into an intermediate representation, through code generation onto a target machine, and finally through the transformations that make the generated code faster and smaller.
What this unit covers
- Intermediate Code Generator: High-level and Low-level Intermediate representation
- Syntax tree & DAG representations
- Three-address code
- Quadruples
- Triples
- SDT for intermediate code
- Intermediate code generation for Declarations, Assignments, Control Flow, Boolean Expressions and Procedure Calls
- Back patching
- Code Generator: Factors affecting a code generator
- Target Language
- Basic blocks and flow graphs
- Dynamic programming code-generation algorithm
- Code Optimization: Need and criteria of Code Optimization
- Basic optimization techniques
- Case Studies of some compilers like C compiler, C++ complier
Intermediate Code Generator
2081 · 10 marks
What are the significances of intermediate code? Differentiate between DAG and Syntax tree. Represent the instruction A = B + C - D * E + G using quadruple and triple.[10]
Show solved answerHide answer
Intermediate Code, DAG vs Syntax Tree, and Quadruple/Triple Representation
Given Data (Extracted)
- Task 1: Significances of intermediate code (conceptual)
- Task 2: Differentiate DAG vs Syntax tree (conceptual)
- Task 3: Expression to represent using quadruple and triple: $$A = B + C - D * E + G$$
Operator precedence assumption: * binds tighter than +/-; + and - are left-associative and equal precedence, evaluated left to right. So the expression parses as:
$$A = ((B + C) - (D * E)) + G$$
1. Significances of Intermediate Code (3 marks)
Intermediate code (IC) is a machine-independent representation produced between the analysis (front end) and synthesis (back end) phases of a compiler.
| Significance | Explanation |
|---|---|
| Machine Independence | IC is not tied to any target CPU, keeping the front end portable. |
| Retargetability | One front end can serve many target machines by swapping only the back-end code generator. |
| Enables Optimization | Machine-independent optimizations (common subexpression elimination, constant folding, dead-code removal) are applied conveniently on IC. |
| Front-end Reuse for Many Languages | Several source-language front ends can share a single back end if they emit the same IC. |
| Modularity / Simpler Compiler Design | Clean separation of phases eases development, debugging, and maintenance. |
| Aids Error/Type Checking | Type mismatches and semantic issues can be handled while generating IC. |
2. Difference Between DAG and Syntax Tree (3 marks)
| Feature | Syntax Tree | DAG (Directed Acyclic Graph) |
|---|---|---|
| Definition | Tree with operators at internal nodes and operands at leaves. | Graph like a syntax tree but with common subexpressions shared as one node. |
| Common subexpressions | Repeated as separate subtrees. | Shared using a single node. |
| Node parents | Each node has exactly one parent. | A node may have multiple parents. |
| Space usage | More (duplication). | Less (sharing). |
| Redundancy detection | Does not expose redundant computation. | Explicitly reveals repeated computations. |
| Typical use | Semantic analysis, syntax-directed translation. | Code optimization (common subexpression elimination). |
Example: A + A * B
Syntax Tree (A duplicated):
+
/ \
A *
/ \
A B
DAG (A shared):
+
/ \
| *
\ / \
A B
3. Quadruples and Triples for A = B + C - D * E + G (4 marks)
Three-Address Code
$$ \begin{aligned} t_1 &= B + C \ t_2 &= D * E \ t_3 &= t_1 - t_2 \ t_4 &= t_3 + G \ A &= t_4 \end{aligned} $$
Quadruple Representation: (op, arg1, arg2, result)
| Index | op | arg1 | arg2 | result |
|---|---|---|---|---|
| (0) | + | B | C | $t_1$ |
| (1) | * | D | E | $t_2$ |
| (2) | - | $t_1$ | $t_2$ | $t_3$ |
| (3) | + | $t_3$ | G | $t_4$ |
| (4) | = | $t_4$ | - | A |
Triple Representation: (op, arg1, arg2) (result implied by position)
| Index | op | arg1 | arg2 |
|---|---|---|---|
| (0) | + | B | C |
| (1) | * | D | E |
| (2) | - | (0) | (1) |
| (3) | + | (2) | G |
| (4) | = | A | (3) |
Quadruple vs Triple
| Quadruple | Triple | |
|---|---|---|
| Result | Explicit named temporary | Implicit (position index) |
| Fields | 4 | 3 |
| Instruction reordering | Easy | Hard (position references break) |
2076 · 6 marks
Explain with example about different methods of intermediate code representation.[6]
Back patching
2081 · 10 marks
Illustrate the concept of backpatching with an example. Convert the regular expression a(a + b)a# to DFA.[10]
Show solved answerHide answer
Backpatching and RE to DFA Conversion
Part 1: Backpatching (5 marks)
Concept
Backpatching is a technique used during single-pass code generation for handling forward jumps whose target addresses are not yet known when the jump instruction is generated.
When we emit a conditional or unconditional jump, the destination label may still be undefined. Instead of making a second pass, we:
- Generate the jump with the target field left blank.
- Keep the instruction number in a list.
- When the target address becomes known, we go back and fill in all instructions in that list. This "going back to fill in" is backpatching.
Data Structures and Helper Functions
- truelist: jumps taken when a boolean is true.
- falselist: jumps taken when a boolean is false.
- nextlist: unconditional jumps to the statement following the current one.
| Function | Meaning |
|---|---|
makelist(i) | creates a new list with only instruction i |
merge(p1,p2) | concatenates two lists |
backpatch(p,i) | inserts i as the target of every jump in list p |
Example: if (a < b) then x = 1 else x = 2
Code is emitted with blank targets:
| Addr | Emitted code | List |
|---|---|---|
| 100 | if a < b goto ___ | truelist = {100} |
| 101 | goto ___ | falselist = {101} |
| 102 | x = 1 | (then-part) |
| 103 | goto ___ | nextlist = {103} |
| 104 | x = 2 | (else-part) |
| 105 | ... | next statement |
Backpatching actions:
- then-part begins at 102 →
backpatch(truelist,102)gives100: if a<b goto 102 - else-part begins at 104 →
backpatch(falselist,104)gives101: goto 104 - exit is 105 →
backpatch(nextlist,105)gives103: goto 105
Final patched code:
100: if a < b goto 102
101: goto 104
102: x = 1
103: goto 105
104: x = 2
105: ...
Backpatching therefore lets the compiler resolve forward addresses in a single pass.
Part 2: Convert a(a + b)a# to DFA (Direct / Syntax-Tree Method)
Step 1: Number the leaves
The augmented expression is $a \cdot (a+b) \cdot a \cdot #$. Numbering symbol positions:
$$a_1 \cdot (a_2 + b_3) \cdot a_4 \cdot #_5$$
Step 2: Syntax tree
. (root)
/ \
. #(5)
/ \
. a(4)
/ \
a(1) +
/ \
a(2) b(3)
Step 3: nullable / firstpos / lastpos
No leaf is nullable, so every node here is non-nullable.
| Node | nullable | firstpos | lastpos |
|---|---|---|---|
| 1 (a) | F | {1} | {1} |
| 2 (a) | F | {2} | {2} |
| 3 (b) | F | {3} | {3} |
| 2+3 | F | {2,3} | {2,3} |
| 1·(2+3) | F | {1} | {2,3} |
| 4 (a) | F | {4} | {4} |
| (…)·4 | F | {1} | {4} |
| 5 (#) | F | {5} | {5} |
| root | F | {1} | {5} |
Step 4: followpos
Rule for concatenation $c_1 \cdot c_2$: for each $i \in lastpos(c_1)$, $followpos(i) \mathrel{+}= firstpos(c_2)$.
| Concat node | lastpos(left) | firstpos(right) | effect |
|---|---|---|---|
| 1·(2+3) | {1} | {2,3} | followpos(1)={2,3} |
| (…)·4 | {2,3} | {4} | followpos(2)={4}, followpos(3)={4} |
| (…)·5 | {4} | {5} | followpos(4)={5} |
followpos table:
| Position | Symbol | followpos |
|---|---|---|
| 1 | a | {2,3} |
| 2 | a | {4} |
| 3 | b | {4} |
| 4 | a | {5} |
| 5 | # | ∅ |
Step 5: Construct the DFA
- Start state $A = firstpos(\text{root}) = {1}$.
- The accepting states are those containing position 5 (the
#).
From $A={1}$ (position 1 is a):
- on
a: union of followpos of positions in $A$ with symbola= followpos(1) = {2,3} → state $B={2,3}$. - on
b: none.
From $B={2,3}$ (2 is a, 3 is b):
- on
a: followpos(2) = {4} → state $C={4}$. - on
b: followpos(3) = {4} → state $C={4}$.
From $C={4}$ (position 4 is a):
- on
a: followpos(4) = {5} → state $D={5}$. - on
b: none.
From $D={5}$ (position 5 is #, contains #, so $D$ is the accepting state):
- followpos(5) = ∅ → no outgoing transitions.
DFA Transition Table
| State | Positions | on a | on b |
|---|---|---|---|
| →A | {1} | B | - |
| B | {2,3} | C | C |
| C | {4} | D | - |
| D* | {5} | - | - |
DFA Diagram
a a / b a
→(A) ------> (B) --------> (C) -------> ((D))
Accepting state: $D={5}$. The DFA accepts strings matching $a(a,|,b)a$, i.e. exactly aaa and aba, before the endmarker #.
Dynamic programming code-generation algorithm
2081 · 5 marks
Write the code generation algorithm for the instruction a = b op c. [5]
Basic optimization techniques
2081 · 5 marks
What are the techniques for compiler optimization? Explain. [5]
Basic blocks and flow graphs
2080 · 5 marks
How do you recognize basic block? Discuss about the factors that affect code generator. [5]
2081.1 · 10 marks
Explain the optimization techniques for code optimization. Convert the following program to basic block and control flow.
$M = A + B$
$N = C + D$
$\text{IF } (M > N) \rightarrow X = M - N;$
$\text{ELSE } E = M + N + X$
[10]
Code Optimization
2080 · 5 marks
Why code optimization is needed? Describe any two techniques for loop optimization. [5]
2078 · 5 marks
What is the advantages of code optimization? Explain about dead-code elimination. [5]
2076 · 6 marks
What is the purpose of code optimization? Explain different types of loop optimization techniques with example.[6]
2075 · 6 marks
Define code optimization. Discuss about any three code optimization techniques with example.[6]
Three-address code
2080 · 5 marks
What is three-address code? How high level code is converted to three address code? Illustrate with an example. [5]
2075 · 6 marks
Define three address codes. write three address codes for S = do m = n + p while a <= b [6]
Show solved answerHide answer
Three Address Code
Definition (Step 1 - Extract)
Given data (from the question):
- Statement to translate:
S = do m = n + p while a <= b - Structure: a
do ... whileloop with bodym = n + pand conditiona <= b.
No numeric matrices or values are involved; this is a compiler-design (intermediate code generation) problem.
Solution
Definition of Three Address Code
Three Address Code (TAC) is an intermediate code representation in which each instruction contains at most three addresses -- normally two operands and one result. The general form is:
$$x = y ; op ; z$$
where:
- $x, y, z$ are names, constants, or compiler-generated temporaries,
- $op$ is an operator (arithmetic, logical, relational, etc.).
It is called three address code because each statement references at most three "addresses." Complex expressions are broken into a sequence of such simple instructions using temporaries. TAC can be implemented using quadruples, triples, or indirect triples.
Common statement forms:
- Assignment:
x = y op z,x = op y,x = y - Unconditional jump:
goto L - Conditional jump:
if x relop y goto L - Labels:
L:
Translating: S = do m = n + p while a <= b
This is a do-while loop:
- Body:
m = n + p(executed at least once) - Condition:
a <= b(checked after each iteration; if true, repeat)
The body executes first, then the condition is tested. If the condition holds, control loops back to the beginning of the body.
Generated Three Address Code
| Line | Instruction | Meaning |
|---|---|---|
| 1 | L1: | Start of loop body (control always enters here first) |
| 2 | t1 = n + p | Evaluate n + p into temporary t1 |
| 3 | m = t1 | Assign result to m |
| 4 | if a <= b goto L1 | Test condition; if true, repeat the body |
| 5 | L2: | Exit point of the loop |
In pure sequential form:
L1: t1 = n + p
m = t1
if a <= b goto L1
L2: ...
Explanation
L1:marks the beginning of the body. Since it is ado-while, the body must run at least once, so control entersL1unconditionally.t1 = n + puses a new temporaryt1 = newtemp()to store the arithmetic result (three-address form: one operator, two operands, one result).m = t1completes the assignmentm = n + p.if a <= b goto L1evaluates the relational condition. If true, jump back toL1and repeat; if false, fall through.L2:is the loop-exit label, where execution continues after the loop.
Quadruple Representation (optional supporting form)
| # | op | arg1 | arg2 | result |
|---|---|---|---|---|
| (1) | + | n | p | t1 |
| (2) | = | t1 | - | m |
| (3) | if<= | a | b | L1 |
This confirms each instruction uses at most three addresses.
Quadruples
2078 · 5 marks
Define three address codes. Write down Quadruples for: $a = -b*(c+d)/e$. [5]
Show solved answerHide answer
Three Address Code and Quadruples
Given
- Expression to translate: $a = -b * (c + d) / e$
- Required output format: Quadruples
- Also required: Definition of three address code
No numeric data is involved; this is a code-generation problem. All required information is present.
Solution
Definition of Three Address Code
Three address code (TAC) is an intermediate representation of a program in which each statement contains at most three addresses (or operands): two for the operands and one for the result. The general form is:
$$x = y ; \text{op} ; z$$
where $x$, $y$, $z$ are names, constants, or compiler-generated temporary variables, and $\text{op}$ is an operator (arithmetic, logical, etc.). Each statement performs at most one operation, which makes it easy to translate into machine code and to optimize.
Three address code can be implemented in three ways: Quadruples, Triples, and Indirect Triples.
Breaking the Expression into Three-Address Statements
Expression: $a = -b * (c + d) / e$
Applying operator precedence (parentheses first, then unary minus, then $*$ and $/$ left to right):
| Step | Statement | Explanation |
|---|---|---|
| 1 | $t_1 = -b$ | unary minus on $b$ |
| 2 | $t_2 = c + d$ | evaluate parenthesis |
| 3 | $t_3 = t_1 * t_2$ | multiply |
| 4 | $t_4 = t_3 / e$ | divide by $e$ |
| 5 | $a = t_4$ | assign to $a$ |
Quadruple Representation
A quadruple has four fields: (op, arg1, arg2, result).
| Index | op | arg1 | arg2 | result |
|---|---|---|---|---|
| (0) | uminus | b | _ | $t_1$ |
| (1) | + | c | d | $t_2$ |
| (2) | * | $t_1$ | $t_2$ | $t_3$ |
| (3) | / | $t_3$ | e | $t_4$ |
| (4) | = | $t_4$ | _ | a |
Notes:
uminusdenotes the unary minus operator (distinguished from binary subtraction)._indicates an unused field.
Final Result
The expression $a = -b*(c+d)/e$ produces 5 quadruples using 4 temporary variables ($t_1, t_2, t_3, t_4$), matching the standard textbook decomposition.
Code Generator
2078 · 5 marks
Explain about the factors affecting target code generation. [5]
2076 · 6 marks
Discuss about the different factors affecting target code generation.[6]
2075 · 6 marks
Discuss about the different factors affecting target code generation.[6]
Syntax tree & DAG representations
2081.1 · 10 marks
Discuss about Directed Acyclic Graph with an example. Represent the expression A = (B + C) - (D - E) using 3AC, Quadruple and Triple.[10]
Intermediate code generation for Declarations, Assignments, Control Flow, Boolean Expressions and Procedure Calls
2081.1 · 5 marks
What are the advantages of intermediate code? How do you convert procedure call to 3AC? [5]
Make Unit 4 stick
Practice CSC376 with flashcards & quizzes