Sub topic 23
GATE problem patterns and solving strategies
This chapter assumes you have read the earlier chapters on activation records, scope, parameter passing, three-address code, basic blocks, and the data flow framework. GATE compiler-design questions fall into a few repeating patterns. For each one, this chapter gives a first move and the usual trap.
Choosing the first move
Most questions can be classified in a few seconds from the wording. Classifying first stops you from applying the wrong machinery.
Pattern 1: stack depth and frame contents
Count frames by following the call chain to its deepest point, and include main. In the fact(3) example, the deepest point holds main, fact(3), fact(2) and fact(1): four frames. For a call fact(n) from main with n >= 1, the maximum is n + 1 frames.
The trap is the question's wording. "Number of calls" and "maximum stack depth" are different quantities. For non-linear recursion such as Fibonacci, depth is the longest chain, not the total number of calls.
Pattern 2: scope and parameter passing
Trace the program by hand and write each variable's value after every statement. Under static scope, a name resolves in the text where the procedure was defined. Under dynamic scope, it resolves through the chain of callers at run time.
Parameter passing questions usually involve aliasing or an expression argument. Take swap(x, y) { t = x; x = y; y = t; } called as swap(i, a[i]) with i = 1, a[1] = 2, a[2] = 7.
| Mode | Result | Why |
|---|---|---|
| Call by reference | `i = 2`, `a[1] = 1`, `a[2] = 7` | The address of `a[1]` is fixed at the call. |
| Call by name | `i = 2`, `a[1] = 2`, `a[2] = 1` | `a[i]` is re-evaluated after `i` changes, so the last assignment writes `a[2]`. |
Call by value leaves i and a unchanged. Copy-restore copies values in, then copies results back in order at return, so aliasing can give a different answer from reference.
Pattern 3: counting in intermediate code
Questions ask for the number of temporaries, instructions, or DAG nodes. Translate the expression bottom-up, one operator per instruction.
- For three-address code, the count is the number of operators plus assignments, with one temporary per operator result.
- For a DAG, identical subexpressions share one node, as long as no operand was reassigned between them. Count only distinct operator and leaf nodes.
- Quadruples need four fields per instruction. Triples drop the result field and refer to earlier instructions by position. Indirect triples add a separate list of pointers, so reordering changes only that list.
The trap is reordering. If a question asks which form makes code motion cheapest, the answer is quadruples or indirect triples, because plain triples must have their references rewritten.
Pattern 4: basic blocks and leaders
Apply the three leader rules mechanically:
- The first instruction is a leader.
- Any jump target is a leader.
- Any instruction immediately after a jump is a leader.
Each block runs from one leader up to, but not including, the next. The following code applies the rules to a loop.
def leaders(code):
# code: list of (text, target); target is a 1-based index or None
found = {1}
for i, (_, target) in enumerate(code, start=1):
if target is not None:
found.add(target)
if i < len(code):
found.add(i + 1)
return sorted(found)
code = [
("i = 1", None),
("t1 = i * 4", None),
("a[t1] = 0", None),
("i = i + 1", None),
("if i <= 10 goto 2", 2),
("return", None),
]
starts = leaders(code)
print(starts) # [1, 2, 6]
bounds = starts + [len(code) + 1]
for s, e in zip(bounds, bounds[1:]):
print("block", [t for t, _ in code[s - 1:e - 1]])This gives three blocks: instruction 1, instructions 2 to 5, and instruction 6. The CFG has edges 1→2, 2→2 and 2→3.
Pattern 5: computing IN and OUT sets
Follow this routine for every data flow question.
- Compute gen and kill (or use and def) for each block first.
- Write the equations for the right direction and meet operator.
- Initialize. Reaching definitions and live variables start with empty sets. Available expressions start with the universal set everywhere except the entry block.
- Visit blocks in the natural order for the direction: reverse postorder for forward problems, the reverse of that for backward problems.
- Repeat until a full pass changes nothing.
Questions sometimes ask "how many passes" or "how many iterations". Check whether the convergence-confirming pass counts. Read the question's convention before answering.
Pattern 6: is the optimization safe?
Match each optimization to the fact that justifies it.
| Optimization | Justified by | Typical trap |
|---|---|---|
| Common subexpression elimination | The expression is available and no operand has been redefined | A redefinition on one path only |
| Dead code elimination | The assigned variable is not live after the assignment | Side effects, such as a call, are not dead code |
| Constant propagation | Only one definition reaches the use, and it assigns a constant | A second definition arriving around a loop |
| Loop-invariant code motion | Operands have no definitions inside the loop, and the block dominates the loop exits | Moving code that might never execute in the original |
Exercise
A program calls fact(5) from main, using the recursive fact shown in this tutorial. What is the maximum number of activation records on the control stack, and at which call is it reached?
Show answer
Six frames: main, fact(5), fact(4), fact(3), fact(2) and fact(1). The maximum is reached when fact(1) is running, because it returns 1 without making another call.
Exercise
In a CFG, block B2 has predecessors B1 and B3. Expression x+y is generated in B1 and killed in B3. Is x+y available at the entry of B2?
Show answer
No. Available expressions intersect OUT over all predecessors. The expression is in OUT[B1] but not in OUT[B3], so it is not in IN[B2].