Generating code for loops
Loops make a language powerful enough to perform the same operation several times, with limited lines of code. Loops are present in almost every language. This recipe demonstrates how loops are handled in the TOY language.
Getting ready
A loop typically has a start that initializes the induction variable, a step that indicates an increment or decrement in the induction variable, and an end condition for termination of the loop. The loop in our TOY language can be defined as follows:
for i = 1, i < n, 1 in x + y;
The start expression is the initialization of i = 1
. The end condition for the loop is i<n
. The first line of the code indicates i
be incremented by 1
.
As long as the end condition is true, the loop iterates and, after each iteration, the induction variable, i
, is incremented by 1. An interesting thing called PHI node comes into the picture to decide which value the induction variable, i
, will take. Remember that our IR is in the single static assignment...