11.1 Preparation for Code Generation

11.2 Generation of Directives

11.3 Simple Code Generation from AST's

11.4 Standard Code Generation Strategies

11.5 Code Generator Generators

11.6 Register Allocation

11.7 A Better Code Generation Algorithm from AST's 11.8 Code Generation from DAG's

11.9 Retargetable Code Generation

11.10 Peephole Optimization

11.11 Summary

Web References

Exercises

11.3 Code Generation from Abstract Syntax Trees

A simple code generator can generate code from an abstract syntax tree merely by walking the tree.

Consider the following abstract syntax tree for the two assignment statements:

X1 := A + BB * 12;

X2 := A/2 + BB * 12;

from Module 1:

Using a tree walk which generates code for the subtrees first, then applies the parent operator, the following code can be easily produced:

Load BB, R1
Mult #12, R1
Store R1, Temp1
Load A, R1
Add Temp1, R1
Store R1, Temp2
Load Temp2, R1
Store R1, X1
Load A, R1
Div R1, #2
Store R1, Temp3
Load BB, R1
Mult #12, R1
Store T4, R1
Load T3, R1
Add T4, R1
Store T5, R1
Load T5,R1
Store R1,X1

For two leaf nodes, the method shown loads the left-most into a register. The right-most leaf node could just as well have been the one put into the register.

Exercise 3 asks the reader to write the algorithm for this method.

Notice that the code continually stores the value in the register into memory in order to reuse it for the next computation. This is called a register spill.

The example in this section generates code for assignment statements whose right-hand sides are expressions. The next section discusses code generation strategies for various other language constructs.