CS 374 Compilers
Homework #7

Due: Thursday 4/12

Note: This work is to be done in assigned groups.  Each group will submit one assignment.  Although you may divide the work, both team members should be able to present/describe their partner's work upon request. 

Code Generation - Part II

At this point, we can generate code that prints compound arithmetic and logical expressions.  However, the main method of MiniJava doesn't allow us to declare variables (rats!).  In order to do so, we need to be able to (1) allocate new objects, (2) generate code for a method call, and (3) generate stack frame push/pop code for methods.  Our first goal is to create a trivial object with a single method that returns 123, call this method, and print the returned value.

1. Symbol Table Additions: You'll want to add to your symbol table such that it will be easy to:

2. Memory Allocation: Create a helper method alloc(int) in your translator that generates code to dynamically allocate the given number of words.  Syscall 9, given a number of bytes will do this for you conveniently.  Finally, clear the memory.  That is, set each allocated position to 0.

3. NewObject:  Each object will consist of an integer identifier and a certain number of fields.  Use the previous additions to generate code that allocates the needed memory and places the address of the allocated memory in $v0.

4. Simplified Call:  Add a field to syntaxtree.Call to keep track of the type of the object in the call.  Set this field at the appropriate point in your type-checking code.  Call this the call class.  (Note that the calling object may actually be of a different subclass.)  Use your symbol table to look up which method defining class actually defines the method for the call class.  Assume the method occurs at a label "<method defining class>.<method name>".  Now you can implement code generation for this simplified Call:

5. Tracking Scope, ClassDeclSimple, ClassDeclExtends, MethodDecl:  As in type-checking, it is important to track your scope in code generation.  Add fields to your class to track the current class and method.  Set these fields in the appropriate visitor methods.

6. Method Generation:  In MethodDecl,

You can now test your generated object creation and method call code with NewObject.java.

7. This: This, the address of the current object, will always be at the same position of the stack frame.  Emit code to load the address of "this" from the stack from into $v0.

8. Identifier: Load the address of the given identifier into $v0.  This is handled in three cases:

9. IdentifierExp:  This is similar to Identifier, except that instead of loading the address of the identifier, load the value stored in the identifier.  Instead of simply leaving the address of the identifier in $v0, you'll want to load the value at that address into $v0.

10. Assign: In Assign,

You can now test your generated code with Factorial.java.