Search code examples
compiler-constructioncode-generationregister-allocation

Register assignment for outer loops


I was going through the red dragon book and in the section Register Assignment for Outer Loops, I came across the following statement which is not quite clear to me.

If an outer loop L1 contains an inner loop L2, the names allocated registers in L2 need not be allocated registers in L1 - L2

What do they want to say? Are they talking about variables that are used in both L1 and L2 and these names are allocated registers in L2. I do not quite get the situation meant in the text.

Can anyone explain to me a possible example?

Block Diagram


Solution

  • A common optimisation is to keep variables used in a loop in registers for the duration of the loop. That can make a huge difference in tight loops because it avoids use of memory.

    As with any optimisation of this form, the register will need to be initialised with the value of the variable before the loop starts, which might mean reading it from memory. And if the variable is modified during the loop and still in use afterwards, it may be necessary to save it back to its memory location. Still, that's at most one memory read and one write, as opposed to reading and writing the variable's value in every iteration.

    The decision of which variables to optimise in this way is important. And here arises the possibility that a variable is used in an inner loop but not in the enclosing outer loop. In this case, it's possible that there are more beneficial uses of registers in the outer loop.

    So it is not necessary that a register reserved for an optimised variable in an inner loop will be also reserved in a containing loop. It might even be worthwhile to save the value of the register before starting the inner loop and restore it on inner loop exit. All of that depends on the optimiser's best guess of loop repetition counts, the number of optimisation use sites of the variable, and of course the number of registers available.