

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


















In this project, we will finish generating the intermediate representation and will take care of some
other tasks (such as laying out the activation records and assigning offsets to local variables).
Generator.java
The following files can be found via the class web page or FTPed from:
~harry/public_html/compilers/p
IR.java
Changed to including additional printing.
Peephole.java
This file relates to an optional extension: a “peephole optimizer” for the IR instructions. If
you are not doing the extension, just copy this file into your directory and compile it, along
with the other classes. This file just contains a “dummy” class, which you can modify if
you have time after finishing the primary assignment. (The black box Main.jar uses this
dummy code.)
Main.java
Altered to call Peephole.optimize and to print the variable offsets.
Lexer.java
Parser.java
Checker.java
Files you created last term.
Lexer.class
Parser.class
Checker.class
Compiled versions.
Token.java
StringTable.java
SymbolTable.java
Ast.java
PrintAst.java
PrettyPrintAst.java
go
run
Unchanged.
makefile
Modified to deal with Peephole.java.
tst
runAll
Same as before, but altered for this project. All the test programs from Project 9 are
included, along with several new test files. (The output for the Project 9 test programs will
be different, due to new code added for this project.)
Main.jar
The new “black box” code.
In projects 8 and 9 we generated a lot of temporary variables. Too many!
The first place that we are generating temporaries unnecessarily is in assignments to simple
variables. Consider this source code:
i := j;
Previously, we generated this IR code:
t3 := &i
*t3 := j
This can be “optimized” to the following IR code:
i := j
This optimization can occur only if the thing on the left-hand side is a simple variable. If it is
something more complex (like an array or record dereference), then we will still need to generate
code as we did in projects 8 and 9, with the “indirect store” instruction.
To perform this optimization, this “invariant” will be relaxed a bit. Now genExpr() will return
either a variable (i.e., a pointer to a VarDecl or a Formal node as before) or a constant (i.e., a
pointer to an IntegerConst or RealConst node).
This optimization will affect these routines:
genIntegerConst()
genRealConst()
genBooleanConst() and
genNilConst()
(Some students may not have methods with these names. Instead, they may have put the code to
deal with IntegerConst , RealConst , BooleanConst , and NilConst nodes directly into the
genExpr() method.)
For the NIL constant, genExpr() should return a pointer to an IntegerConst node with iValue
equal to zero.
Earlier, I suggested that you create three AST node of class IntegerConst at the beginning of
generateIR() and fill them in with iValues of 0, 1, and 4. I suggested you call these constant0 ,
constant1 , and constant4. These nodes should be used as the return values of
genBooleanConst() and genNilConst().
For the “nil” value, you can just use the IntegerConst node with iValue of 0, since a null pointer
in PCAT will be implemented with a 32-bit integer equal to zero. When you are generating the
code for array dereferencing address calculations (as discussed later in this document), you’ll need
an IntegerConst with iValue equal to 4; you can use constant4 at that time.
The processing for BooleanConst s should be improved in the same way as for integer and real
constants, to eliminate unnecessary temporaries. For example, the following source:
b := true;
should now generate:
b := 1
instead of:
t2 := &b
t3 := 1
*t2 := t
More complicated stuff, like “IF b THEN...” and “b := (i<j):” is still handled the same way with
branches.
Several things can go wrong during program execution. For the PCAT language, the following five
errors may arise during runtime:
runtimeError1: Allocation failed
Memory allocation failed during array or record construction.
runtimeError2: Pointer is NIL
This may be detected during array dereferencing or during record dereferencing.
runtimeError3: READ statement failed
A call to the system routine to get input has failed.
runtimeError4: Array index out of bounds
During array dereferencing, the index expression was less than zero or too large.
runtimeError5: Count is not positive in array constructor
During array construction, the count expressions are evaluated. They must be >= 1.
We will handle runtime errors as follows. When producing the target “.s” file, we will include
some “boilerplate.” This is canned material which will always be included in every output file
produced by this compiler. It is “canned” in the sense that it is fixed and unchanging and could be
produced by a single, giant print statement.
Among other things, the boilerplate will contain 5 labels: runtimeError1 , runtimeError2 , ...
runtimeError5. After each label, the boilerplate will include code to print out a nasty little
message (like “Allocation failed” or “Pointer is NIL”) and terminate program execution.
During program execution, if anything goes wrong, we’ll simply branch to the appropriate label.
More precisely, the compiler will generate code to test and branch to labels such as runtimeError
if certain conditions are detected at runtime.
It is usually desirable to print out more information than just a fixed message when a runtime error
arises. At a minimum, the source code line number should be printed. (At least our PCAT system
will give a descriptive error message and terminate gracefully; I once heard of a language that would
either keep on executing or print out something cryptic and uninformative like “core dumped.”
“Core” was an ancient form of digital memory using small, doughnut-shaped magnets, used back
when this language was popular... I digress...)
When some unrecoverable error occurs during runtime execution, it is very helpful to the
programmer to print out a source code line number. One technique to print the line number works
as follows. A single register (or static storage location) is set aside to hold an integer. This word
will always contain the current source code line number. Every time the compiler begins to generate
code for a statement (e.g., in genStmts() ), it generates an instruction or two to save the number of
the current source line in this word. Happily, we have this information stored in the pos field of
each AST node. Our boilerplate might then contain code that, when a runtime error occurs, prints
the appropriate error message and also prints the value of this saved word under the rubric “Error
at source code line %d...” There are many variants on this scheme. If several source code files are
involved, additional words would be necessary to identify which source code file was involved at the
time of the error.
Consider the two definitions:
type MyArr is array of ...;
MyRec is record
f1: ...;
f2: ...;
...
fk: ...;
end;
var x: MyArr := ...;
var y: MyRec := ...;
Array-valued variables (like x ) and record-valued variables (like y ) will each be allocated 4 bytes. In
this example, the variables x and y are local variables, but we could have similar variables as formal
variables or as elements in other record and arrays. In any case, each variable will be given 4 bytes,
either in an activation record, or within another record or another array.
At runtime, x and y will either be NIL (i.e., zero) or will point to a block of words which have been
allocated in the heap. The only way to allocate words in the heap is with an array constructor (using
the T {{ ... }} syntax) or with a record constructor (using the T { ... } syntax).
At the time an array constructor is executed, we will know how many elements the array will have,
but we may not know this number until runtime (in PCAT, anyway). With record constructors, we
will know at compile-time how many bytes are to be allocated. It will be 4 times the number of
fields.
An array of N elements will be stored in N+1 words. The extra word will store the N, the size of
the array. This will be used in an “array index out-of-bounds check” every time the programmer
tries to access one of the elements using the array dereferencing (i.e., a[i] or “array indexing”).
The elements of an array are numbered from 0 to N-1. The diagram is drawn with higher (larger)
addresses toward the bottom of the page.
A record with K fields will be stored in K*4 bytes.
There are only three kinds of node that can appear wherever an L-value is allowed: Variable ,
ArrayDeref , and RecordDeref. Here is an example of source code corresponding to each of
these:
x
a[i]
r.f
Of course, each of these kinds of L-value can be used as an R-value. For example, in the following
source code, we see array dereferencing used as an R-value:
x := a [ (i+1)*3 ];
In the following source code, we see record dereferencing occurring in an L-value:
person.address := y;
Of course a variable by itself can occur as either an L-value (like x in the first example) or as an R-
value (like y in the second example).
If an L-value is used as an R-value, then the AST data structure will contain a ValueOf node. The
ValueOf node has an lValue field which will point to either a Variable , an ArrayDeref , or a
RecordDeref node.
The code generation for L-values is handled in genLValue(). The code generation for R-values is
handled in genValueOf().
In my own version of Generator.java , I did not have routines named genArrayDeref() or
genRecordDeref() or genVariable(). (Actually, I got rid of them.) Instead, it seemed clearer to
include the necessary code directly in genLValue() and genValueOf().
The simplest approach to genValueOf() is to do the following:
(1) Call genLValue() on the lValue field. It will return a temporary (call it temp1 ) after
generating the IR instructions to move an address into it.
(2) Create a new temporary. Call it temp.
(3) Generate a loadIndirect instruction to move the data at the address in temp1 into temp.
However, you should make an optimization when the L-value in question is a simple variable.
To accomplish this, put a switch statement into genValueOf() and take a look at what kind of node
the ValueOf is pointing to. There are three cases: Variable , ArrayDeref , and RecordDeref.
For the ArrayDeref and RecordDeref cases, you’ll need to do steps (1) (2) (3) above.
For the Variable case, simply return the variable (as represented by its VarDecl or Formal node),
avoiding the call to genLValue() and the loadIndirect instruction.
Next, look at a record dereference used as an L-value. Consider the following PCAT source code:
r.f3 := i + 123;
The variable r will be a word containing a pointer to a record stored in the heap, or possibly NIL.
The fields in a record are at offsets 0, 4, 8, 12, 16, ... For this record type, assume that f1 has been
assigned to offset 0, f2 to offset 4, f3 to offset 8, etc.
You should generate the following code:
! ASSIGNMENT STMT...
if r = 0 then goto runtimeError2 (integer)
t1 := r + 8 (integer)
t2 := i + 123 (integer)
*t1 := t
Lines 1-2 compute the address of a word containing a pointer to a record containing an f3 field and
store it in temporary t1. They are the result of the inner invocation of genLValue().
Look at how the outer invocation of genLValue() works. It begins by making the recursive call
(resulting in lines 1 and 2). Then, it needs to generate a loadIndirect instruction in line 3. Now t
contains a pointer to the record containing the f3 field. Then genLValue() generates instructions
(in lines 4-5) to compute the address of the f3 field in that record. Finally, genLValue() returns
this address in temporary t.
The remaining 2 instructions are produced by genExpr() and genAssignStmt().
Now consider the straightforward approach to generating code for following source code:
r.f3 := i + 123;
The method genAssignStmt() begins by calling genLValue() to deal with the left-hand side
(“ r.f3 ”). In the call to genLValue() , we see that we are dealing with a RecordDeref. To deal
with the lValue field in that node (“ r ”), the obvious thing to do is to make a recursive call to
genLValue(). But note that genLValue() will always load the address of the thing in question
into a temporary and will return that temporary, even if it is a simple variable like in this example.
Such a recursive invocation of genLValue() would move the address of r into a temporary, ( t1 in
the code below). Then the main call to genLValue() would have to generate a loadIndirect
instruction. This would produce the following IR sequence:
t1 := &r
t2 := *t
if t2 = 0 then goto runtimeError2 (integer)
t3 := t2 + 8 (integer)
t4 := i + 123 (integer)
*t3 := t
The first two instructions are pointless and you must avoid generating them. The desired code
(shown at the beginning of this section) just used r directly in the if-equal-goto instruction. You
can avoid generating these two unnecessary instructions by inserting a test in genLValue() when
handling a RecordDeref. Look to see if you have a simple Variable for the lValue. If so, just
use it; if not, you’ll need to call genLValue() recursively to handle whatever the lValue is. Then
you will have to generate a loadIndirect instruction.
Now look at an array dereference used as an L-Value. Consider the following source code:
a [i*3] := z;
First, genAssignStmt() will call genLValue() to handle the lefthand-side, which is an
ArrayDeref node. GenLValue() will need to call genExpr() to deal with the index expression
(“i*3”).
Here is the code you should generate for this source:
1.! ASSIGNMENT STMT...
First, in genLValue() we will generate a test to see if the current value of the variable a is NIL (i.e.
zero). If so, we must branch into the boilerplate code to deal with the error. Next, genLValue()
will call genExpr() to deal with the index expression (“ i3* ” in this example). genExpr() will
generate the assignment to t1 (line 3) and will return t1. Back in genLValue() , we will then
generate the instructions in lines 4-6 which test to make sure the computed index falls within 0 ≤
index < N.
Next, we need to generate instructions to compute the address of the correct word. At this point
(before line 7), t1 contains the index. We need to multiply it by 4 and add 4 to bump past the initial
word which stores the array size. Then, we add it to the address of the array in the heap in line 9.
Finally, we can return the temp containing the computed address from genLValue().
Also notice that t1 is whatever temporary got returned from genLValue() ’s call to genExpr().
Due to our optimization of temporaries, as discussed earlier, the thing that gets returned from
genExpr() might also, in general, be an IntegerConst instead of a variable. This is why we
created a new temporary ( t2 ) in genLValue() , instead of performing the computation directly in
the temporary returned from genExpr() (which was t1 ).
After returning from genLValue() , genAssignStmt() will generate the instructions to evaluate the
righthand-side (there are none needed in this example) and the finally store instruction in line 10.
An ArrayDeref node contains an lValue field, so in general you need to call genLValue() to deal
with it. Then you need to generate a loadIndirect instruction. However, it is often the case that the
lValue is a simple Variable (like “ a ” in this example). To avoid generating poor code, you
should include a special case test to see if the lValue field happens to point to a Variable node. If
so, you can use the variable directly, otherwise call genLValue() recursively and generate a
loadIndirect into a new temporary. This special case test is analogous to the test for
RecordDeref s discussed in the previous section.
The diagram titled “Activation Record Layout” shows where in the activation record we will store
the local variables and the formal parameters. Normal local variables (i.e., user-defined and
temporary variables) will be stored at offsets: -4, -8, -12, -16, ... Formal variables will be stored at
offsets: 68, 72, 76, 80, ...
Printing Offset Information...
MAIN BODY:
FrameSize = 128
Offsets of local variables:
-4 w
-8 x
-12 y
-16 z
-20 t
-24 t
-28 t
-32 t
PROCEDURE p1_foo1:
FrameSize = 112
Lex Level = 1
Offsets of formals:
68 a
72 b
76 c
Offsets of local variables:
-4 i
-8 j
-12 k
-16 t
-20 t
PROCEDURE p2_foo2:
...
A field called frameSize has been added to the Body node and you need to set it correctly. This
field will be used when you generate target code for procEntry and mainEntry in a later project.
At that time, you will take the frameSize and plug it directly into the “save” SPARC instruction
that you will generate.
You can perform the frameSize computation in genBody() using the global variable called
maxNumberOfArgsUsed. While processing the VarDecl s and the statements in a Body , you
will occasionally run into a CallStmt or a FunctionCall. You’ll need to count the arguments and
update maxNumberOfArgsUsed accordingly. When computing the frameSize , you might also
want to count the number of local variables (after the statements have been processed and all
temporaries have been created. You should also use the above constants.
Assume that routine foo calls bar. The activation record for foo must include enough space for the
arguments to bar. But the activation record for foo does not need to contain any room for the
formal parameters to foo since these will be stored in the frame of the routine that calls foo. After
processing all of the Body , maxNumberOfArgsUsed should tell how much space to allocate in
foo ’s frame for arguments to routines it calls. According to the calling conventions, you must
allocate at least 6 words here. (Since our target code will call scanf , printf , and calloc , we must
follow the “C” calling conventions.) [Clever hint: You can achieve this “max” function by
initializing maxNumberOfArgsUsed to 6 instead of 0!]
The optional alignment word will be either zero bytes or four bytes, as necessary to ensure that the
frame size is an even multiple of 8.
Each PCAT source-level procedure will need a label to act as the target of a SPARC call
instruction. We might consider using the name given by the programmer — this is what the “C”
language does. This approach works for “C” since routines are never nested and therefore must
each have a different name. However, in PCAT, routines may be nested. We might have several
routines named “foo” in the same program!
We also have another problem. Our final SPARC program will have a number of symbols, such
as:
runtimeError
runtimeError
runtimeError
...
Label_
Label_
Label_
...
str
str
str
...
float
float
float
...
What if the PCAT programmer happens to name one of his or her procedures “Label_4” or
“runtimeError2”? According to the language definition, these are legal procedure names, yet we
do not want to have a conflict with one of the labels our compiler is introducing.
One approach is to just rename all procedures with names like
proc
proc
proc
...
This guarantees that every name will be unique and will not conflict with other names, but it makes
the resulting SPARC code hard to read and/or debug. If the programmer tries to debug the
compiled code (say with “gdb” or “ddd”), the source level names would be nice to have.
The approach we will take is to combine the source name with an automatically generated name.
We’ll end up with names like:
The following IR instruction:
x := alloc (n)
will cause n bytes to be allocated on the heap and a pointer to the bytes to be stored in variable x. If
the allocation fails for any reason (such as “heap full”), zero will be stored in x.
You can create this instruction with the following:
IR.alloc (x, n);
The result field (e.g., “x”) should be a VarDecl node. The arg1 field (e.g., “n”) should be a
VarDecl or IntegerConst node.
This instruction will be used by array constructors and record constructors.
When we generate SPARC code, the alloc IR instruction will be translated into a call to the
“malloc” or “calloc” routines, which should be familiar to “C” programmers.
By the way, PCAT has no facility for explicitly “free”ing arrays or records, although you might
envision adding something like this to the language. More likely, we would run PCAT in an
environment with an automatic garbage collector.
In this course project, we will not worry about freeing storage. We will allocate and allocate, in the
hope that the heap will always be big enough. If any allocation should fail, we will at least get a
reasonable error message (runtimeError1: “Allocation failed”).
Consider the following source statement, involving a RecordConstructor expression:
rec := RecType { f1 := 123; f2 := 23.45; f3 := false };
For this, you should generate the following IR code:
t1 := alloc (12)
if t1 = 0 then goto runtimeError1 (integer)
t2 := t1 + 0 (integer)
*t2 := 123
t2 := t1 + 4 (integer)
*t2 := 23.
t2 := t1 + 8 (integer)
*t2 := 0
rec := t
The first two instructions allocate a block of memory on the heap and check to make sure that the
allocation succeeded. From the RecordConstructor node, you can get to the RecordType node
describing the record to be allocated (via myDef->TypeDecl.type ). The number of bytes to
allocate comes from the size field in this RecordType node.
The RecordType node also contains a pointer to a linked list of FieldDecl nodes, one for every
field in the type definition describing the record. Likewise, a RecordConstructor node points to a
linked list of FieldInit nodes, one for each field assignment in the record constructing expression.
There will be exactly one field assignment for every field in the record. (Fortunately, we checked
that during type checking!) Each FieldInit node therefore will correspond to exactly one
FieldDecl node. (Note that the two linked lists may be in different orders.)
Fortunately, during type checking, we saved a pointer from the FieldInit node to the corresponding
FieldDecl node in a field called myFieldDecl , in the FieldInit node. The myFieldDecl field of
each FieldInit should point to the FieldDecl node with the same field id.
Given the myFieldDecl field, generating the above instructions becomes easy!
In a loop, you’ll need to walk the list of FieldInit s. For each, first call genExpr() to generate the
code for the expression. Then generate the IRiadd instruction and the IRstore instruction.
Finally, genRecordConstructor() will need to return a temporary containing a pointer to the
newly allocated record.
Here are two examples showing array constructor usage in PCAT:
a1 := MyArray1 {{ 100 OF –1 }};
a2 := MyArray2 {{ 4.5, 6.1, 3.0, 2.3, 4.0 }};
In general, an array constructor expression will look like this:
Type {{ count 1 OF expr 1 , count 2 OF expr 2 , ..., countK OF exprK }}
Each of the counti and expri are nested sub-expressions. As such, they may contain arbitrary
computation, including calls to functions, and so on. The PCAT definition specifies that they must
be evaluated in the lexical order given. So you will need to call genExpr() for each of these 2K
expressions in exactly the order the corresponding sub-expressions appear in the source.
genExpr ( count 1 );
genExpr ( expr 1 );
genExpr ( count 2 );
genExpr ( expr 2 );
genExpr ( countK );
genExpr ( exprK );
Recall that an array constructor is represented by an ArrayConstructor node which points to a
linked list of ArrayValue nodes. Each ArrayValue node has pointer to a countExpr and a
through the array as you walk through it initializing all the elements. Just before you hit the second
box, t2 is pointing to the word containing N. You’ll need to increment t2 by 4 before using it each
time. (Alternatively, one could put the add instruction after the store, but this would result in an
extra add at the beginning, to get past the word containing N, and an unnecessary add at the end.)
Next, walk the linked list of ArrayValue nodes a second time. For each, you’ll generate the code
in the second box. Thus, the code in the second box (shown only once) will actually be repeated K
times. This means that you will create K new labels. For each count-value pair, you will generate a
small loop to initialize the right number of words in the array.
Notice that the first box is repeated for each of the K nodes in the ArrayValue s linked list. This
means that you’ll create K temporaries called tcnt and K temporaries called tval, during the first
walk. Next, you walked the linked list a second time and generated the instructions in the second
box K times. You’ll need to remember all these temporaries between their creation (during the first
walk) and use in the instructions in the second box (during the second walk).
The ArrayValue node has 2 fields (called tempCount and tempValue ) which are these just for
that purpose. In these fields, you may save the temporaries you create during the first walk of the
linked list for use during the second walk of the linked list.
Finally, genArrayConstructor() can return the pointer to the array ( t3 ).
Matters are somewhat complicated by the fact that the “count” expression may be missing. If so, a
value of 1 is assumed.
The code in the first box is modified to simply increment t1 by 1:
t1 := t1 + 1
tval := ...genExpr(valueExpri)...
The code in the second box is modified to:
t2 := t2 + 4
*t2 := tval
As an example, consider the following ArrayConstructor expression:
a1 := T1 {{ 11, 12, 13, 14, 15 }};
The above scheme will generate the following IR code:
t1 := 0
t1 := t1 + 1 (integer)
t1 := t1 + 1 (integer)
t1 := t1 + 1 (integer)
t1 := t1 + 1 (integer)
t1 := t1 + 1 (integer)
t2 := t1 * 4 (integer)
t2 := t2 + 4 (integer)
t2 := alloc (t2)
if t2 = 0 then goto runtimeError1 (integer)
t3 := t
*t2 := t
t2 := t2 + 4 (integer)
*t2 := 11
t2 := t2 + 4 (integer)
*t2 := 12
t2 := t2 + 4 (integer)
*t2 := 13
t2 := t2 + 4 (integer)
*t2 := 14
t2 := t2 + 4 (integer)
*t2 := 15
a1 := t
Obviously, there is room for optimization when the count expressions are missing, but we will not
be doing it here. At least this code will execute correctly. The optimizations we will discuss in
class should be able to clean this code up.
String constants can appear only in WRITE statements. Consider this source:
write ("Hello, world!");
write ("i = ", i);
When you generate the boilerplate, you’ll need to generate something like this:
str1: .asciz "Hello, world!"
str2: .asciz "i = "
In order to facilitate this later, I have added two new fields to StringConst called next and
nameOfConstant , which you must fill in.
In this project, you must assign a unique name to each string constant in the PCAT source by
storing a Java String in the nameOfConstant field of each StringConst node. You might create a
new method (perhaps called newStringName() ) by copying and modifying the code from
newLabel(). Each string name should be of the form “str N ” where N is an integer.