Java Reference
In-Depth Information
AST is transformed to represent this type conversion explicitly. Subse-
quent compiler passes (particularly code generation) can then assume a
type-consistent AST in which all operations are explicit.
The results of applying semantic analysis to the AST of Figure 2.9 are shown
in Figure 2.13.
2.8 Code Generation
The final task undertaken by a compiler is the formulation of target-machine
instructions that faithfully represent the semantics (i.e., meaning) of the source
program. This process is called code generation . Our translation exercise
consists of generating source code that is suitable for the dc program, which
is a simple calculator based on a stack machine model. In a stack machine ,
most instructions receive their input from the contents at or near the top of
an operand stack. The result of most instructions is pushed on the stack.
Programming languages such as C
and Java are frequently translated into a
portable, stack machine representation.
Chapters 11 and 13 discuss code generation in detail. Modern compilers
often generate code automatically, based on a description of the target ma-
chine's instruction set. Our translation task is su
ciently simple to allow an
ad hoc approach.
The AST was transformed and decorated with type information during
semantic analysis. Such information is required for selecting the proper in-
structions. For example, the instruction set on most computers distinguishes
between float and integer data types.
Code generation proceeds by traversing the AST, starting at its root and
working toward its leaves. As usual, we allow a visitor to apply methods
based on the node's type, as shown in Figure 2.14.
• visit
(Computing n ) generates code for plus and minus. First, the code
generator is called recursively to generate code for the left and right
subtrees. The resulting values will be at top-of-stack, so the appropriate
operator is then emitted (Marker 15 ) to perform the operation.
• visit
(Assigning n ) causes the expression to be evaluated. Code is then
emitted to store the value in the appropriate dc register. The calculator's
precision is then reset to integer by setting the fractional precision to zero
(Marker 14 )
• visit
(SymReferencing n ) causes a value to be retrieved from the appro-
priate dc register and pushed onto the stack.
 
 
Search WWH ::




Custom Search