Sub topic 13
Basic blocks and control flow graphs
This chapter assumes you can read three-address code (covered in the earlier chapters on three-address code and its storage forms). You should also know what a graph is and what a jump target is. Every data flow analysis later in this tutorial runs on the structure built here, so GATE questions on reaching definitions, live variables and available expressions all begin by drawing it.
What a basic block is
A basic block is a maximal sequence of consecutive three-address instructions with two properties:
- Control enters only at the first instruction.
- Control leaves only at the last instruction, with no halt or branch in the middle.
If the first instruction runs, every instruction in the block runs, in order. That guarantee lets a compiler reason about the block as one unit.
Finding the leaders
A leader is the first instruction of a basic block. Find the leaders with three rules:
| Rule | Which instruction is a leader |
|---|---|
| 1 | The first instruction of the program |
| 2 | Any instruction that is the target of a conditional or unconditional jump |
| 3 | Any instruction that immediately follows a conditional or unconditional jump |
Each block runs from one leader up to, but not including, the next leader. The last block ends at the end of the program.
Rule 3 also applies after a return, because the next instruction cannot be reached by falling through.
A worked example
Take this three-address code. It sums the squares of 1 to n.
(1) s = 0
(2) i = 1
(3) if i > n goto (8)
(4) t1 = i * i
(5) s = s + t1
(6) i = i + 1
(7) goto (3)
(8) return sApply the rules:
- Rule 1 makes (1) a leader.
- Rule 2 makes (8) a leader, because (3) jumps to it. It also makes (3) a leader, because (7) jumps to it.
- Rule 3 makes (4) a leader, because it follows the conditional jump at (3). Instruction (8) follows the jump at (7), so it is already a leader.
The leaders are (1), (3), (4) and (8). The blocks are:
- B1 = (1)–(2)
- B2 = (3)
- B3 = (4)–(7)
- B4 = (8)
Building the control flow graph
A control flow graph (CFG) has one node per basic block. It has a directed edge from block P to block Q if control can pass from the end of P to the start of Q. This happens in two ways:
- The last instruction of P is a jump (conditional or not) whose target is the first instruction of Q.
- Q immediately follows P in program order, and P does not end in an unconditional jump or a return. This is the fall-through edge.
Most CFGs add two empty nodes. Entry has an edge to the block holding the first instruction. Exit receives an edge from every block that ends the program.
B2 has two successors because it ends in a conditional jump: the jump target (B4) and the fall-through block (B3). B3 ends in an unconditional goto, so it has only the jump edge back to B2 and no fall-through edge. The edge from B3 to B2 is a back edge, and it marks a loop. The chapter on dominators and natural loops uses this.
Doing it in code
This Python program applies the leader rules and builds the edges for the example. Each instruction is a pair of its text and its jump target, or None if it has none. Positions are numbered from 1 to match the listing.
def build_cfg(code):
n = len(code)
leaders = {1}
for k, (text, target) in enumerate(code, start=1):
if target is not None:
leaders.add(target)
if k + 1 <= n:
leaders.add(k + 1)
elif text.startswith("return") and k + 1 <= n:
leaders.add(k + 1)
starts = sorted(leaders)
blocks = {}
for idx, st in enumerate(starts):
end = starts[idx + 1] - 1 if idx + 1 < len(starts) else n
blocks["B%d" % (idx + 1)] = (st, end)
by_start = {st: name for name, (st, end) in blocks.items()}
edges = []
for name, (st, end) in blocks.items():
text, target = code[end - 1]
if target is not None:
edges.append((name, by_start[target]))
falls = target is None or text.startswith("if")
if text.startswith("return"):
falls = False
if falls and end < n:
edges.append((name, by_start[end + 1]))
return blocks, edges
code = [
("s = 0", None),
("i = 1", None),
("if i > n goto 8", 8),
("t1 = i * i", None),
("s = s + t1", None),
("i = i + 1", None),
("goto 3", 3),
("return s", None),
]
blocks, edges = build_cfg(code)
print(blocks)
print(edges)It prints the four blocks B1 to B4 with ranges (1, 2), (3, 3), (4, 7) and (8, 8). The edges are B1→B2, B2→B4, B2→B3 and B3→B2.
Common errors
- Missing the leader after a conditional jump. Students often mark only jump targets. The instruction after
if ... gotois also a leader, because it is the fall-through entry. - Adding a fall-through edge after
goto. An unconditional jump never falls through. Only conditional jumps and ordinary instructions do. - Splitting a block at a label nobody jumps to. A label that is not a jump target does not create a leader.
- Counting instructions instead of blocks. GATE asks for the number of basic blocks or the number of edges. Count leaders first, then edges per block.
- Forgetting entry and exit. If the question includes them, the node and edge counts each go up.
Why this structure matters
Inside a block, control flow is fixed, so a compiler can do local optimization with simple tables. These include common subexpression elimination within a block and dead code removal. Between blocks, the CFG records every possible path. Data flow analysis computes facts at block boundaries. Each block gets a summary (gen and kill sets), and the edges say how facts pass from one block to the next.
Exercise
Find the basic blocks and the number of CFG edges (not counting Entry and Exit) for this code. (1) x = 1 (2) if x > 5 goto (6) (3) x = x + 1 (4) y = x * 2 (5) goto (2) (6) z = y
Show answer
Leaders: (1) by rule 1. (6) is a jump target. (2) is the target of the jump at (5). (3) follows the conditional jump at (2). (6) also follows the goto at (5). The leaders are (1), (2), (3) and (6). The blocks are B1 = (1), B2 = (2), B3 = (3)–(5), B4 = (6). The edges are B1→B2, B2→B4, B2→B3 and B3→B2. That makes 4 edges.
Exercise
Why does an instruction immediately after an unconditional goto become a leader, even if no jump targets it?
Show answer
Control cannot fall into it from the goto, so it can only be reached by some other path. Placing it in the same block as the goto would violate the rule that control leaves a block only at its last instruction. Rule 3 therefore starts a new block there.