Module 8 · 18 min read · Free chapter
Runtime environments and optimisation
Each call gets an activation record on the stack with parameters, links, return address and locals. Static scoping follows the program text, dynamic scoping follows the calls. Optimisation splits code into basic blocks at leaders, removes common subexpressions with a DAG, and uses data-flow analysis: liveness backward, reaching definitions and constant propagation forward.
Start from zero: the pile of files on a clerk's desk
Picture a clerk in a district office. A file for a pension case is open on the desk, with a sticky note of working figures. Halfway through, the case needs a land record, so the clerk places that file on top and starts it, with a fresh note.
The land record in turn needs a birth certificate, and a third file goes on top. When the birth certificate is done, its file and note go away, and the clerk returns to the land record exactly where it was left. The newest file is always finished first.
A running program handles procedure calls in exactly this way. Each call gets an activation record on a stack, holding its parameters, local variables and the place to return to. The record is removed when the call returns, and the caller continues.
This chapter has two halves. The first is the runtime environment: how memory, scope and parameters work while a program runs. The second is optimisation: how a compiler studies the code it has produced and makes it faster without changing what it does.
Why it matters. GATE questions on scoping and parameter passing ask for the exact output of a program. Questions on optimisation ask you to count basic blocks, find live variables or fold constants, all of which need a clear picture of the code.
Memory layout and activation records
At run time, a program's memory has four areas. Code holds the instructions, and static data holds globals and constants whose size is known at compile time. The stack holds activation records, and the heap holds data created with malloc or new. The stack and heap usually grow towards each other from opposite ends of the free space.
An activation record, or stack frame, is pushed on each call and popped on return. Its usual fields, from the caller's side inwards, are listed below.
| Field | What it holds |
|---|---|
| Actual parameters | Values or addresses passed by the caller |
| Returned value | The result handed back to the caller |
| Control link | Pointer to the caller's activation record |
| Access link | Pointer to the record of the enclosing scope, for non-local names |
| Saved machine status | Return address and saved registers |
| Local data | Variables declared in the procedure |
| Temporaries | Intermediate values of expressions |
There are three ways to allocate storage. Static allocation fixes every address at compile time, which is fast but cannot support recursion, because two live calls of one procedure would share one set of locals. Stack allocation gives each call its own record, so recursion works, and the record vanishes on return.
Heap allocation is needed when data must outlive the call that created it, such as a linked-list node returned from a function. Heap blocks are freed explicitly, as with free in C, or reclaimed by a garbage collector. A pointer to a freed block is a dangling pointer, and a block nobody can reach but nobody freed is a memory leak.
Worked example. A recursive fact(n) that stops at is called from main as fact(3). At the deepest point the stack holds records for main, fact(3), fact(2) and fact(1), which is 4 records, and with depth the space used is .
Why it matters. Questions on recursion depth, stack overflow and dangling pointers all reduce to this picture of the stack and heap. Knowing the fields of a record also explains how a procedure returns and finds non-local names.
Static and dynamic scoping
When a procedure uses a name it did not declare, which declaration does the name mean? There are two answers, and they can give different outputs for the same program.
Static or lexical scoping looks at the program text: the name refers to the declaration in the nearest enclosing block. The compiler can decide this before the program runs, and at run time it follows access links. C, C++ and Java use static scoping.
Dynamic scoping looks at the calls: the name refers to the most recent declaration that is still active in the chain of calls. It is decided only at run time, by following control links back through callers.
int x = 10;
void show() { print(x); }
void test() { int x = 20; show(); }
int main() { test(); show(); }
Worked example. Under static scoping, show is written at the top level, where the only visible x is the global, so both calls print 10 and the output is 10 10. Under dynamic scoping, the first call to show comes from test, whose local x = 20 is the most recent active one, so it prints 20; the second call comes straight from main, so it prints 10. The output is 20 10.
Why it matters. GATE often gives a short program with a nested or global variable and asks for its output under both rules. Tracing the calls on paper, with a column for each active x, settles it quickly.
Parameter passing modes with outputs
How a parameter is passed decides whether the caller sees changes. There are four classic modes. Call by value copies the value, so the procedure works on its own copy. Call by reference passes the address, so the parameter is another name for the caller's variable.
Call by value-result, also called copy-in copy-out, copies the value in at the call and copies the final value back at the return. Call by name works like textual substitution: the argument expression replaces the parameter everywhere, and it is evaluated again at each use.
void f(int a, int b) { a = a + 1; b = b + a; }
int main() { int x = 5; f(x, x); print(x); }
int i = 1;
int arr[3] = {10, 20, 30};
void p(int y) { i = i + 1; print(y); }
int main2() { p(arr[i]); }
| Mode | f(x, x) prints | p(arr[i]) prints |
|---|---|---|
| Value | 5 | 20 |
| Reference | 12 | 20 |
| Value-result, copied back left to right | 11 | 20 |
| Name | 12 | 30 |
Working for f(x, x). By value, the procedure changes only its copies, so stays 5. By reference, and are both : the first line makes , and the second makes .
By value-result, and start as 5, then and . At return is copied to and then is copied to , so ; if the copies were done right to left, the answer would be 6. By name, and both become the text x, which behaves like reference here and gives 12.
Working for p(arr[i]). By value and by reference, is fixed to arr[1], which is 20, before i changes. By name, stands for the text arr[i], which is evaluated only at the print, after i has become 2, so it prints arr[2], which is 30.
Why it matters. Output questions on parameter passing appear often in GATE and in scientist exams. The two programs above show the only real differences: aliasing, copy-back order and late evaluation.
Basic blocks, flow graphs and local optimisation
An optimiser first cuts the three-address code into basic blocks. A basic block is a straight run of instructions that is always entered at its first instruction and left at its last, with no jump into or out of the middle. To find blocks, first mark the leaders.
- The first instruction of the program is a leader.
- Every instruction that is the target of a jump is a leader.
- Every instruction that comes right after a jump is a leader.
Each block runs from one leader up to, but not including, the next. In the flow graph, the blocks are nodes, and an edge joins to if can run right after , by a jump or by falling through.
Worked example. Take the summing loop again.
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
The leaders are 1 (the first instruction), 3 (the target of 8), 4 (right after the jump at 3) and 9 (the target of 3, and right after 8). So there are 4 blocks: is lines 1 and 2, is line 3, is lines 4 to 8, and is line 9. The edges are , , and the back edge , which marks the loop.
Local optimisation improves each block on its own. Constant folding computes constant expressions at compile time, so x = 4 * 2 becomes x = 8. Constant propagation replaces a variable known to hold a constant with that constant, and copy propagation replaces y with x after y = x.
Common subexpression elimination reuses a value already computed. Dead code elimination removes instructions whose results are never used. Algebraic simplification drops x + 0 and x * 1, and strength reduction replaces a costly operation by a cheaper one, such as x * 2 by x + x, or a multiplication in a loop by repeated addition.
Peephole optimisation slides a small window over the final instructions. It removes a load that follows a store to the same place, replaces a jump to a jump with a single jump, and deletes code that can never be reached.
Why it matters. Counting basic blocks is a direct GATE question, and the leader rules answer it in one pass. Every later analysis runs on the flow graph, so it must be right.
Common subexpressions and dead code with a DAG
Inside one basic block, a DAG finds repeated computations. Each variable's starting value is a leaf, marked with a subscript 0 such as . Each instruction either reuses an existing node with the same operator and the same children, or creates a new one, and the variable assigned is attached to that node as a label.
Worked example. Build the DAG for this block.
a = b + c
b = a - d
c = b + c
d = a - d
The first line creates node , labelled . The second creates , labelled , and the third creates , labelled ; this is a new node, because now means and not . The fourth line asks for , and both and still mean and , so it reuses , and joins its labels.
The rewritten block computes once and replaces the fourth line with a copy. A careless reader might also merge the first and third lines because both look like , but the DAG shows they are different, because changed in between.
Dead code shows up in the same picture. If a node's labels are all variables that are not live at the block's exit, and no other node uses it, the instruction that computes it can be removed. Constant folding fits in too: a node whose children are constants is replaced by its value.
Worked example (folding and dead code). In x = 4; y = x * 2; z = y + x; if z > 10 goto L1, propagation and folding give and . The test is always true, so the jump becomes goto L1, and the code that only ran when the test failed is now unreachable and can be deleted.
Why it matters. The syllabus names common subexpression elimination directly, and DAG questions on a block of four or five lines are common. Watch especially for variables reassigned in the middle of the block.
Data-flow analysis: reaching definitions and liveness
Local optimisation sees one block at a time. Data-flow analysis gathers facts across the whole flow graph by writing an equation for each block and solving all of them together. Each analysis has a direction, forward or backward, and a meet, union or intersection, for joining facts where paths meet.
Reaching definitions asks which assignments can reach a point without being overwritten. A block generates the definitions it makes, and kills other definitions of the same variables. It is a forward analysis with union as the meet.
Liveness asks which variables hold a value that may be used later. Here holds variables read in before any write in , and holds variables written before any read. Information flows from uses back to earlier points, so it is a backward analysis with union as the meet.
Both start with empty sets and repeat the equations until no set changes. Because sets only grow and are finite, the process always stops.
Worked example (liveness on the loop). For the four blocks of the summing loop, and ; ; and ; and . In , and are read before they are written, so they are in use, not def.
The first pass from the bottom gives , and . The second pass carries around the back edge into , giving , and a third pass changes nothing. Finally , so only and must be ready before the loop, and and are never live outside .
Worked example (reaching definitions). Name the definitions : s = 0, : i = 0, and in , : s = s + t2 and : i = i + 1. After the iteration settles, both and reach , so the value of at the return is not a single constant, which is exactly the fact constant propagation needs.
Why it matters. The syllabus names liveness analysis directly, and GATE asks for the live variables at a point or for IN and OUT of a block. Writing the use and def sets carefully is half the work.
Constant propagation and register allocation
Constant propagation across blocks asks, for each variable at each point, whether it always holds the same constant. Each variable takes one of three values: UNDEF (no definition has reached yet), a constant , or NAC (not a constant). It is a forward analysis, and at a join point the values meet by these rules.
| Meet of | Result |
|---|---|
| UNDEF and a constant c | c |
| c and the same c | c |
| Two different constants | NAC |
| NAC and anything | NAC |
For an instruction , if both and are constants, becomes their sum; if either is NAC, is NAC; otherwise is UNDEF. Worked example. If one branch sets and the other also sets , then is 3 after the join and y = x * 2 folds to y = 6. If the other branch sets instead, then is NAC and nothing folds.
| Analysis | Direction | Meet | Used for |
|---|---|---|---|
| Reaching definitions | Forward | Union | Use-definition chains, constant propagation |
| Liveness | Backward | Union | Register allocation, dead code |
| Available expressions | Forward | Intersection | Global common subexpressions |
| Constant propagation | Forward | Lattice meet | Constant folding across blocks |
Liveness leads directly to register allocation. Two variables interfere if they are live at the same point, so they cannot share a register. Draw an interference graph with a node per variable and an edge per interfering pair, and colour it so that no edge joins two nodes of the same colour; each colour is a register.
Worked example. In x = 2; y = x + 3; z = y * y; w = x + z, with only live at the end, the live sets after each line are , , and . The edges are – and –, and and never overlap, so they can share a register. Two colours suffice, and the code needs 2 registers, which matches the largest live set.
If the graph needs more colours than there are registers, some variable is spilled: it is kept in memory and loaded when needed. The compiler usually spills a variable that is used rarely and interferes with many others.
Why it matters. GATE asks for the minimum number of registers for a piece of code, and the answer comes from the largest live set. Constant propagation, liveness and common subexpressions are the three analyses the syllabus names, and this section completes them.
Descriptive lens: how written papers ask this
Written papers for scientist posts and university examinations ask about this topic in four ways:
- Describe the structure of an activation record and the storage allocation strategies, with a diagram of the stack during a recursive call.
- Trace a program under static and dynamic scoping, or under different parameter-passing modes, and give the output.
- Partition three-address code into basic blocks, draw the flow graph, and apply local optimisations.
- Set up and solve data-flow equations for reaching definitions, liveness or available expressions on a small flow graph.
Practice questions (our own, not previous-year questions).
- Draw the activation record of a procedure and explain each field. Why can static allocation not support recursion? (10 marks)
- For a procedure
swap(int a, int b)called asswap(i, arr[i]), explain the result under call by value, reference and name. (10 marks) - Write the data-flow equations for liveness analysis. Compute IN and OUT for each block of the summing loop given in this chapter. (15 marks)
Answer plan for question 3.
- Begin by defining a live variable as one whose current value may be read on some path before it is overwritten.
- Define use and def for a block, and note that a variable read before it is written belongs to use.
- Write the two equations with from use and , and as the union of the successors' IN sets.
- Explain that the analysis is backward with union as the meet, and that all sets start empty.
- List use and def for the four blocks, then show each pass of the iteration in a table until no set changes.
- Conclude with the final sets, noting that only and are live on entry and that the temporaries are never live across blocks.
Quick revision
- An activation record holds parameters, the returned value, control and access links, saved status, locals and temporaries.
- Static allocation cannot support recursion, the stack holds call records, and the heap holds data that outlives a call.
- Static scoping follows the program text through access links, while dynamic scoping follows the calls through control links.
- For
f(x, x)witha = a + 1; b = b + aand , value prints 5, reference and name print 12, and value-result prints 11. - Leaders are the first instruction, every jump target and every instruction after a jump.
- A DAG of a block reuses nodes for repeated computations only when no operand changed in between.
- Reaching definitions is forward with union, liveness is backward with union, and available expressions is forward with intersection.
- Constant propagation meets UNDEF with to give , and two different constants to give NAC.
- The fewest registers for straight-line code equals the largest number of values live at once.
- Spilling keeps a variable in memory when the interference graph needs more colours than registers.