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
- 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); - Hand-execute it. Make a table with columns for
i,sand the instruction number, and step through to termination. What does it print? - 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?
- Move the test to the bottom — body first, then condition, then a conditional jump back. Hand-execute with
i = 5initially. What changed, and what construct have you just implemented? - Nest two loops on paper. How many distinct labels do you need? What breaks if the label generator ever returns the same name twice?
- 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.