Module 8 · 15 min read · Free chapter
Syntax-directed translation and intermediate code
A syntax-directed definition attaches attributes and rules to a grammar. Synthesised attributes flow up from children, inherited ones come from the parent or left siblings. S-attributed rules suit LR parsing, L-attributed rules suit LL parsing. Intermediate code is often three-address code, stored as quadruples or triples, and a DAG removes repeated subexpressions.
Start from zero: a shop bill that adds up
Look at a bill from a kirana shop. Each line has a quantity and a rate, and its amount is the product of the two. The total at the bottom is the sum of the line amounts. Values here travel upward, from the small parts to the whole.
Now suppose a festival discount of 10 percent is printed at the top of the bill. Every line must use that rate, so this value travels downward from the top to each line. A bill thus has two kinds of information: what a line computes from its own parts, and what a line receives from above.
A compiler attaches values to a parse tree in exactly these two ways. A synthesised attribute flows up from children to parent, like the total. An inherited attribute flows down from a parent, or across from a sibling, like the discount.
Why it matters. Attaching such rules to a grammar is how a compiler checks types, builds syntax trees and produces intermediate code while it parses. GATE asks you to evaluate such rules on an input and to classify them as S-attributed or L-attributed.
Syntax-directed definitions and annotated parse trees
A syntax-directed definition (SDD) is a grammar in which each symbol can carry attributes, and each production carries semantic rules that compute them. The attribute of a symbol is written . The standard example is a desk calculator.
| Meaning | Production | Semantic rule |
|---|---|---|
| Print the result | ||
| Add | ||
| Pass up | ||
| Multiply | ||
| Pass up | ||
| Brackets | ||
| Number from the lexer |
The subscript in only separates the two copies of in one production. Every rule here computes a parent's attribute from its children, so every attribute is synthesised. The value of a digit comes from the lexer as , and terminals never have inherited attributes.
Worked example. For the input 3 * 5 + 4, the parse tree has and at the bottom left, so . The right gives 4, and the top gives . A parse tree with such values written at its nodes is an annotated parse tree.
In what order should the rules run? Draw a dependency graph, with an edge from attribute to attribute whenever the rule for uses . Any topological order of this graph is a valid evaluation order, and if the graph has a cycle, no order works.
Why it matters. The annotated parse tree is how you answer "what value is printed?" questions. Drawing the tree first and filling values bottom-up avoids almost every error.
S-attributed and L-attributed definitions
Inherited attributes are needed when information must flow sideways or down. The classic case is a declaration such as float x, y, z, where the type is read first and must reach every name after it.
Here is inherited: it comes from the left sibling , and then down the chain of nodes. Each identifier's symbol-table entry receives the type through the call to .
Two classes of SDD can be evaluated while parsing, without building the whole tree first. An S-attributed SDD uses only synthesised attributes. It can be evaluated in post-order, which is exactly the order in which an LR parser performs reductions.
An L-attributed SDD allows inherited attributes too, under one condition. In , an inherited attribute of may depend only on inherited attributes of , on attributes of the left siblings , and on attributes of itself without forming a cycle. Information therefore flows from left to right, and a single depth-first, left-to-right walk evaluates everything, which suits top-down parsing.
Worked example. Classify with the rules , and . Every inherited attribute depends on the parent or a left sibling, so it is L-attributed but not S-attributed. If instead , then inherits from its right sibling, and the SDD is not L-attributed.
Why it matters. "Which of these SDDs is L-attributed?" is a common GATE question. Check each inherited rule and look only for a dependence on a right sibling or on the parent's synthesised attribute.
Translation schemes: actions inside productions
A syntax-directed translation scheme (SDT) writes program fragments, called semantic actions, inside the production bodies within braces. An action runs when the parser reaches its position, so the position matters. When all actions sit at the right ends of productions, the SDT is a postfix SDT, and an LR parser runs each action as it reduces.
Worked example (postfix output). The SDT below prints each operator after its operands.
E -> E + T { print('+') }
E -> E - T { print('-') }
E -> T
T -> digit { print(digit.lexval) }
For the input 9 - 5 + 2, the left-recursive grammar groups it as (9 - 5) + 2. The digits are printed as they are reduced and each operator after its right operand, so the output is 9 5 - 2 +, the postfix form. Moving the print actions to the front of the bodies would instead print the operators earlier, which is why the position of an action changes the output.
Worked example (a GATE-style evaluation). Consider this SDT, in which the symbols have unusual meanings.
Evaluate 2 # 3 & 5 # 6 & 4. The operator & sits lower in the grammar, so it binds tighter, even though it means addition. So the input groups as 2 # (3 & 5) # (6 & 4), and both operators group from the left.
Why it matters. GATE likes SDTs with strange operators precisely because students use the usual school precedence. Precedence comes only from the grammar's levels, and associativity from the side of the recursion.
Three-address code and its representations
Most compilers translate the syntax tree into three-address code, in which each instruction has at most one operator on its right side. A long expression is broken into steps, and the compiler invents temporaries to hold the partial results. The name comes from the general form , which mentions three addresses.
The usual instruction kinds are few. They are binary assignment x = y op z, unary assignment x = minus y, copy x = y, unconditional jump goto L, conditional jump if x relop y goto L, procedure calls with param x and call p, n, indexed assignments x = a[i] and a[i] = x, and address and pointer assignments x = &y, x = *p and *p = x.
Worked example (a loop). The C loop s = 0; for (i = 0; i < n; i++) s = s + a[i];, with 4-byte integers, becomes the code below.
1: s = 0
2: i = 0
3: if i >= n goto 9
4: t1 = 4 * i
5: t2 = a[t1]
6: s = s + t2
7: i = i + 1
8: goto 3
9: return s
Three-address code can be stored in three ways. Take a = b * -c + b * -c, whose code is t1 = minus c, t2 = b * t1, t3 = minus c, t4 = b * t3, t5 = t2 + t4 and a = t5.
| Position | op | arg1 | arg2 | Quadruple result | Triple arguments |
|---|---|---|---|---|---|
| (0) | minus | c | t1 | c | |
| (1) | times | b | t1 | t2 | b, (0) |
| (2) | minus | c | t3 | c | |
| (3) | times | b | t3 | t4 | b, (2) |
| (4) | plus | t2 | t4 | t5 | (1), (3) |
| (5) | assign | t5 | a | a, (4) |
Quadruples have four fields, op, arg1, arg2 and result, and name every temporary explicitly. Triples drop the result field and refer to a value by the position of the triple that computes it, so (1) means "the result of instruction 1". Indirect triples add a separate list of pointers to triples, so the optimiser can reorder the list without touching the triples.
Why it matters. Optimisers move instructions around all the time. With plain triples, moving an instruction changes positions and breaks every reference to it, which is why quadruples and indirect triples are preferred in optimising compilers.
Syntax trees, DAGs and SSA form
A syntax tree is a compact parse tree. Its interior nodes are operators and its leaves are operands, and chains such as are dropped. A DAG, or directed acyclic graph, goes one step further and gives each distinct subexpression a single node, shared by every place that uses it.
To build a DAG, look up a node before creating it. If a node with the same operator and the same children already exists, reuse it; otherwise create a new one. This lookup, usually done with hashing, is what finds common subexpressions.
Worked example. Count nodes for . The syntax tree has 7 leaves (, , , , , , ) and 6 operator nodes, so 13 nodes. In the DAG the leaves , , and appear once each, and is built once and shared, so there are 4 leaves and 5 operator nodes, which is 9 nodes.
For a = b * -c + b * -c, the DAG shares both minus c and b * t1. Its code needs only four instructions: t1 = minus c, t2 = b * t1, t3 = t2 + t2 and a = t3. The six-line code of the last section shrinks because the DAG found the repetition.
Static single-assignment (SSA) form is an intermediate code in which every variable is assigned exactly once. Each new assignment creates a new version, so x = a + b; x = x * 2; y = x + 1 becomes x1 = a + b; x2 = x1 * 2; y1 = x2 + 1. Each use then names exactly one definition, which makes many optimisations simpler.
When two control paths meet, a variable may have different versions on each path. SSA joins them with a φ-function: if one branch sets and the other sets , the join point gets . The φ-function picks the version from whichever path the program actually took.
Why it matters. GATE asks for the number of nodes in a DAG and for the minimum number of temporaries. The DAG is also the tool for local common-subexpression elimination, which the syllabus names directly.
Backpatching in brief
When a compiler translates if (x < 5 or y > 2) S, it must emit jumps to the start of and past it before it knows where those places are. One solution is two passes. Backpatching does it in one pass by leaving jump targets blank and filling them in later.
Each boolean expression carries two lists of instructions with blank targets. holds the jumps to take when is true, and the jumps for false. Three functions manage them: makes a new list containing instruction , joins two lists, and writes target into every jump on list .
The marker records , the number of the next instruction, which is where begins. If is false, control must go on to test , so 's false jumps are patched to . For and, the roles swap: 's true jumps are patched to the start of , and the false lists are merged.
Worked example. Starting at instruction 100, the condition gives the code below. The truelist is , patched to 104 where begins, and the falselist is , patched to the first instruction after .
100: if x < 5 goto _ (true: patched to 104)
101: goto 102 (false of x < 5: patched to start of y > 2)
102: if y > 2 goto _ (true: patched to 104)
103: goto _ (false: patched to after S)
Why it matters. Backpatching is how one-pass compilers produce correct jump code for conditions and loops. Exam questions usually ask what a list contains, or which target fills a blank.
Descriptive lens: how written papers ask this
Written papers for scientist posts and university examinations ask about this topic in four ways:
- Define and contrast synthesised and inherited attributes, and S-attributed and L-attributed definitions, with an example of each.
- Draw an annotated parse tree and a dependency graph for an input, and give an evaluation order.
- Translate a statement or a loop into three-address code, and show its quadruples, triples and indirect triples.
- Construct the DAG of an expression or a basic block, and use it to remove common subexpressions.
Practice questions (our own, not previous-year questions).
- Write an SDD for a desk calculator and draw the annotated parse tree for
(4 + 2) * 3. Is your SDD S-attributed? (10 marks) - Translate
x = (a + b) * (a + b) - cinto three-address code, and represent it as quadruples, triples and indirect triples. (15 marks) - Distinguish S-attributed and L-attributed definitions. Show, with the declaration
int p, q, r, why inherited attributes are needed. (10 marks)
Answer plan for question 3.
- Begin by defining synthesised and inherited attributes, with the direction in which each flows in the parse tree.
- Define an S-attributed SDD as one with only synthesised attributes, evaluated bottom-up in post-order during LR parsing.
- Define an L-attributed SDD by its condition that inherited attributes depend only on the parent's inherited attributes and on left siblings.
- Write the four declaration rules, with passed from to and down the list.
- Draw the annotated tree for
int p, q, r, and show placing the type integer in each symbol-table entry. - Conclude that the type is known only to the left sibling, so a purely synthesised scheme cannot pass it to the names without extra work.
Quick revision
- An SDD attaches attributes and semantic rules to a grammar, while an SDT places actions inside production bodies.
- Synthesised attributes come from children, inherited ones come from the parent or siblings, and terminals have only synthesised ones.
- S-attributed SDDs use only synthesised attributes and suit LR parsing, while L-attributed SDDs also allow inheritance from the parent and left siblings.
- Every S-attributed SDD is L-attributed, and a cycle in the dependency graph makes evaluation impossible.
- Precedence in an SDT comes from grammar levels, and associativity from the side of the recursion.
- Three-address code has at most one operator on the right side of each instruction.
- Quadruples have four fields, triples have three and refer by position, and indirect triples add a pointer list.
- A DAG gives one node to each distinct subexpression, so needs 9 nodes against 13.
- SSA gives each variable one assignment and uses φ-functions where paths meet.
- Backpatching leaves jump targets blank on truelists and falselists and fills them in later.