Back to the 2026 paper

Module 4: Intermediate Code Generation, Code Improvement (optimization)

20267m

Explain the construction of basic blocks and control-flow graphs (CFGs) in compiler design using a suitable three-address code example.

Worked SolutionAI Assisted

Basic block

A basic block is a maximal sequence of consecutive three-address instructions with one entry point (only the first instruction can be reached from outside) and one exit point (control leaves only at the last instruction, with no jumps into or out of the middle).

Algorithm to find basic blocks

  1. Find the leaders (first instructions of blocks):
    • the first instruction of the program;
    • the target of any conditional or unconditional jump;
    • the instruction immediately after a jump (conditional or unconditional).
  2. For each leader, the basic block consists of the leader and all instructions up to (but not including) the next leader or the end of the program.

Example three-address code

1  sum = 0
2  i = 1
3  if i > 10 goto 8
4  t1 = i * 2
5  sum = sum + t1
6  i = i + 1
7  goto 3
8  print sum

Leaders: instruction 1 (first), 3 (target of the jump at 7), 4 (follows the conditional jump at 3), 8 (target of the jump at 3 and follows the jump at 7). So the leaders are {1,3,4,8}\{1, 3, 4, 8\}.

Block Instructions
B1B_1 1-2
B2B_2 3
B3B_3 4-7
B4B_4 8

Control-flow graph (CFG)

A CFG has the basic blocks as nodes. There is an edge Bi→BjB_i \to B_j if control can pass from the end of BiB_i to the start of BjB_j: either by a jump from the last instruction of BiB_i to the leader of BjB_j, or because BjB_j follows BiB_i in program order and BiB_i does not end in an unconditional jump.

MermaidDiagram
Rendering diagram…

Uses: the CFG exposes loops (here B2→B3→B2B_2 \to B_3 \to B_2), and is the basis for data-flow analysis, local optimizations inside a block, and global optimizations such as code motion and dead-code elimination.

Similar questions

Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.