Q5Compiler Design
Question
Explain the concept of Intermediate Code Generation with examples (TAC, Quadruples, Triples).
Answer
Intermediate Code Generation produces a machine-independent IR (Three-Address Code, Quadruples, Triples) from the annotated parse tree, forming the bridge between the compiler's front end and back end.
TAC is the most common IR. Each instruction has the form: x = y op z (at most three addresses, one operator). Temporary variables (t1, t2, ...) are introduced as needed. TAC is easy to generate from an annotated parse tree and easy to translate to machine code.
Quadruples represent each TAC instruction as a 4-tuple: (operator, operand1, operand2, result). Example for t1 = b c: (, b, c, t1). For x = -b: (uminus, b, _, x). For goto L: (goto, _, _, L). Quadruples are easy to rearrange (for optimization) since the result is explicitly named.
Triples represent each instruction as a 3-tuple: (operator, operand1, operand2). The result is implicitly the instruction number, not stored explicitly. Example: instruction (0): (*, b, c) — result is (0). instruction (1): (+, a, (0)) — means a + result-of-instruction-0. Triples save space (no result field) but are harder to rearrange. Indirect triples add a level of indirection to facilitate rearrangement.
- TAC: t1 = c * d; t2 = b + t1; a = t2
- Quadruples: (*, c, d, t1); (+, b, t1, t2); (=, t2, _, a)
- Triples: (0): (*, c, d); (1): (+, b, (0)); (2): (=, a, (1))