Java Reference
In-Depth Information
•
The target of code generation here is
virtual machine
(VM) code, which
is fairly close in form and semantics to a source language. Chapter 13
considers machine-level targets that bear little resemblance to source lan-
guages. For example, the VMs considered in this chapter o
er intrinsic
treatment of objects, virtual method calls, and Java
TM
data types such
as String and boolean. In Chapter 13, translation strategies must be
introduced to implement such features properly.
ff
•
The resource issues that must be addressed in code generation are rel-
atively simple for VMs, but require a more sophisticated treatment in
Chapter 13. For example, the VMhere can reference an almost unlimited
number of registers, while the targets in Chapter 13 have a relatively
small number of architected registers.
While a reader concerned mostly with native code generation may be tempted
to skip this material and jump to Chapters 12 and 13, we recommend studying
this chapter first as a relatively gentle introduction to the techniques of code
generation and as a foundation for the material presented in Chapter 13.
Aswas the casewith semantic processing, code generationmakes extensive use
of the
visitor pattern
presented in Chapter 7, which allows method dispatch to
be based on a given visitor and the actual type of a given node. Code based on
the visitor pattern can be authored in a single class, so that the tasks ascribed
to a given visitor are easily aggregated across AST node types. The actual
code executed within a visitor is based on the runtime type of the visited node
(binary addition, local variable reference, etc.)
and
the type of the visitor itself.
A
reflective
mechanism for achieving such
double dispatch
is presented
in Section 7.7.3 on page 268. A review of that material may be helpful before
proceeding with this chapter.
A given visitor is typically tasked with performing a relatively narrow set
of activities. For the purposes of code generation, it is helpful to organize the
code-generating phase using the following visitors:
TopVisitor
is the top-level visitor for processing an AST's nodes. It is respon-
sible for processing class and method declarations, and it also initiates
processing of each method's contents.
MethodBodyVisitor
generates code for the constructs foundwithin amethod.
The visitor accepts a label at which the method's
postlude
code will be
generated, so that proper method termination can be achieved from any
point in the method.