CS 480: Translators

Winter Term, 2004, Professor Budd

Programming Assignment 5

Due Wednesday, March 3

Optimizations

When you are finished, hand in both the files Parser.java and Ast.java, which should be the only two files you modify for this assignment.

Start by adding the following method to the class Ast; you will subsequently override this in BinaryNode, UnaryNode, and FunctionCallNode:

class Ast { public Ast optimize () { return this; } }

Optimization

In this assignment you will fill in the optimize methods in the subclasses of Ast. These methods should optimize an abstract syntax tree, returning a new tree. A call on this routine will then be inserted before you generate code for the left and right sides of an assignment statement, before you generate code for a function call in functionOrAssign, the expression returned by a return statement, and before you test the conditions in an if or while statement. Here are some examples:

e.optimize().branchIfFalse(labOne); codeGen.genReturn(e.optimize()); codeGen.genAssign(e.optimize(), f.optimize());

In general the idea will be to try to combine integer constants at compile time, try to move constants to the right and the top of an expression tree (so that they might be combined with other constants).

The optimizations you should recognize are the following:

Consider an expression 3 + (4 + a) * 7. This would be optimized in the following fashion

3 + (4 + a) * 7 3 + (a + 4) * 7 3 + (a * 7) + 28 (a * 7) + 28 + 3 (a * 7) + 31

I have selected only the most common transformations. Others that a real compiler might consider include transformations on floating values, transformations on unary operators (negating a constant, for example), and transformations on relationals and logical operators. In lecture I will discuss many other types of optimizations.

Although most of the work will be in the optimize method for binary nodes, the optimize method will impact every node class.

Major Hint

You can make this assignment vastly easier by adding three protected functions to the class AST. The first returns true if the node is an integer constant, the second returns the integer value if it is a constant, and the third return a binary node if the receiver is a binary addition.