Topic 4 · Class activity 1 · Week 9 · Wednesday

Lower a Loop, Then Draw Its Flow Graph

Labels and jumps on paper, hand-execute it, find the basic blocks and the back edge, then move the test to the bottom and see what you built.

Format pairsTime 45 minBring paper

The point

Lower a loop by hand before writing the code that does it. The pattern is short enough to memorise and general enough to reuse for every construct in Topic 5.

Do this

  1. Lower this by hand into TAC with labels and jumps:
    i = 0;
    s = 0;
    while (i < 5) {
        s = s + i;
        i = i + 1;
    }
    print(s);
  2. Hand-execute it. Make a table with columns for i, s and the instruction number, and step through to termination. What does it print?
  3. Now find the basic blocks. Apply the three leader rules to your listing and mark the boundaries. Draw the flow graph. Which edge is the back edge?
  4. Move the test to the bottom — body first, then condition, then a conditional jump back. Hand-execute with i = 5 initially. What changed, and what construct have you just implemented?
  5. Nest two loops on paper. How many distinct labels do you need? What breaks if the label generator ever returns the same name twice?
  6. Implement it and compare the compiler's TAC with your handwritten listing.

Deliverable

Your handwritten lowering, the execution trace, your flow graph with the back edge marked, your answer to step 4 naming the construct, and the compiler's output beside yours. Feeds Lab Question 17.