Docsity

PCAT Compiler Project: Generating SPARC Assembly Code from Intermediate Representation - P, Study Guides, Projects, Research of Computer Science

Toggle sidebar
bg1
CS-322 Compiler Design
Page 1
Project 11:
Target Code Generation
Due Date: Tuesday, May 14, 2006, Noon
Duration: Two weeks
Overview
The goal of this project is to finish the PCAT compiler by producing SPARC assembly code
instructions from the intermediate representation (IR). This target code can then be assembled and
executed.
File you are to create:
Emit.java
Files
The following files can be found via the class web page or FTPed from:
~harry/public_html/compilers/p11
Main.java
Altered to call Emit.java.
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.
Lexer.java
Parser.java
Checker.java
Generator.java
Files you created.
Lexer.class
Parser.class
Checker.class
Generator.class
Compiled versions.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download PCAT Compiler Project: Generating SPARC Assembly Code from Intermediate Representation - P and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!

Project 11:

Target Code Generation

Due Date: Tuesday, May 14, 2006, Noon

Duration: Two weeks

Overview

The goal of this project is to finish the PCAT compiler by producing SPARC assembly code instructions from the intermediate representation (IR). This target code can then be assembled and executed.

File you are to create:

Emit.java

Files

The following files can be found via the class web page or FTPed from:

~harry/public_html/compilers/p

Main.java Altered to call Emit.java.

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.

Lexer.java Parser.java Checker.java Generator.java Files you created.

Lexer.class Parser.class Checker.class Generator.class Compiled versions.

Token.java StringTable.java SymbolTable.java Ast.java PrintAst.java PrettyPrintAst.java IR.java run go Unchanged.

tst runAll Same as before, but altered for this project.

go New file. This shell script will compile, assemble, and execute the program. It will print out the source and the .s file before beginning execution.

pc New file. This shell script will compile and execute a PCAT program. “pc” stands for “PCAT Compile”.

run runAll These shell scripts are for testing other code generation algorithms. Like run and runAll , they will compile a test PCAT program from the tst directory. However, these scripts will ignore the .bak files. Instead, these scripts proceed to execute the program (using pc ) and make sure the output from the execution is correct.

makefile Modified to deal with Emit.java.

Main.jar The new “black box” code.

Organization

The goal is to run through the Intermediate Representation (IR) statements and produce target code, i.e., SPARC assembly code. This target code will be suitable for assembling and executing.

This document describes how to do this using “Code Generation Algorithm #1.” You are free to try a more sophisticated algorithm... after you get “Code Generation Algorithm #1” working!

You will create a file called Emit.java containing class Emit with a method called emitAll(). Main.java has been modified to create an Emit object and to invoke emitAll() on it. The emitAll() method takes no arguments and returns no result.

Your emitAll() method (and any methods it invokes) should just print the assembly code to stdout. Later, this will allow us to pipe the output of your compiler straight into the assembler.

simple.pcat simple.givenInput simple.givenOutput simple.givenOutput

which are included in the tst directory in this project.

The script called run2 will first compile and assemble the PCAT program (using pc ) and then run the executable. When running the executable, run2 will pipe characters from the givenInput file to the running program. Run2 will save the stdout and stderr output produced by the executable. After execution, run2 will compare the output from the execution to the files containing the expected output ( givenOutput1 and givenOutput2 ) and will print any differences. The run script will ignore the .out.bak and .err.bak files.

I have also provided a script called runAll2 , which is the same as runAll , except that it applies run2 to all of the test files, instead of run.

As long as you use Code Generation Algorithm #1 and follow the guidelines given in this document, your compiler should produce the same .s output file as expected. Therefore, you will not need to assemble or execute your output. If your output exactly matches the .out.bak and .err.bak files, it must necessarily assemble and execute in exactly the same way as expected. Therefore, you will not need to use run2 or runAll2 ; they are only provided in case you attempt to use a different code generation algorithm.

The “go2” Shell Script File

The go script is unchanged and works the same way as in previous projects. You can use it to run your compiler on one of the test files. The go script will print the source. It will then run your compiler and print the stdout , and the stderr , It will ignore the .out.bak and .err.bak files.

I am also providing a script called go2 , which will compile your program and then run it. For example, you can type:

go2 simple

This script is provided for anyone using something besides Code Generation Algorithm #1.

The go2 script will first print the PCAT source file and then invoke your compiler. The script then prints out the .s file before invoking the assembler, so you can look at what code your compiler generated. You will occasionally get assembler error messages if you don’t generate legal SPARC code. The listing of the .s file is useful when such errors occur. Next, the go2 script assembles the program into an executable file (with a name such as simple ). Finally, if both the compiler and the assembler finish without exit errors, the script will run your program.

Files in /tst

Several of the files in tst/ are PCAT programs requiring user input. They are: error3 , read1 , read2 , primes , and quicksort. These files will prompt for input, after telling the user what to enter.

The files fact , quicksort , and primes are programs that actually compute something, rather than just testing a single aspect of the compiler. In the lectures, we used “quicksort” as an example; the file quicksort.pcat is a working version of this program. The program fact.pcat computes factorial numbers and primes.pcat computes prime numbers.

The program speed.pcat is a compute-bound benchmark designed to determine how fast the compiled PCAT code runs. It is not an “official” test and is not included in the runAll script. You may run it, but don’t run it too often or you may irritate other users.

Strategy

You may adopt one of several code generation strategies. The black box compiler uses “code generation algorithm #1” and I recommend that approach as a good way to start. I expect that some students will try more complex code generation algorithms. Algorithm #1 is much simpler to implement but it generates many inefficient code sequences. The rest of this document discusses only code generation algorithm #1. The design of more complex code generation algorithms and optimizations is left entirely to you.

To do code generation algorithm #1, you need to walk the list of the IR instructions and, for each instruction, print out several SPARC instructions. The routine printIR() in IR.java happens to walk the list of instructions so I recommend using it as a starting skeleton for emitAll().

Comments

You probably noticed in projects 8, 9 and 10 how nice it was to have the comments in the output. It makes it easier to locate the section of output you are interested in.

In this project two types of comments are now included in the output. First, the original comments produced by calls to IR.comment() are printed. Second, since printIR() contains code to print the IR instructions, it makes sense to just leave these print statements in emitAll(). The only modification is to prefix each line with a exclamation (!) and three spaces. An example is shown below.

The original comments were all capitals so they stand out visually. As you can see, one source code construct (like a PCAT WRITE statement), translates into several IR instructions, and each instruction is then translated into several SPARC instructions.

! MAIN... ! mainEntry .global main main: save %sp,-136,%sp set display0,%o st %fp,[%o0] ! WRITE STMT... ! writeString str sethi %hi(str1),%o call printf or %o0,%lo(str1),%o ! writeNewline sethi %hi(strNL),%o call printf or %o0,%lo(strNL),%o

Originally, I thought we would be able to include floating-point constants as literal (i.e., immediate) values in the SPARC instructions, but there is apparently no way to do that, since there is apparently no way to move data from an integer register to a floating register without going through memory first. To deal with this problem, we must generate a single precision floating-point constant (using the .single directive) for each real constant (i.e., each RealConst node) that appears in the program. Recall that we have previously built a linked list of RealConst nodes (pointed to by floatList and linked on their next fields). We will walk the linked list of RealConst s and, for each, print out a .single directive, using its nameOfConstant and its rValue.

We also built a linked list of all the StringConst s in the program, using the next field in each StringConst. Next we run though this list and, for each string, print an .asciz directive for it. We have previously named each string and stored that name in the nameOfConstant field. Note that we end with an .align directive so that the SPARC instructions that follow will be aligned.

As you are coding this method, remember that you’ll need to escape the double quote character (") and the backslash character () with backslashes.

! ! PCAT Compiler Version 1. ! .global .div .global .rem ! ! Standard data fields ! .data .align 8 temp: .double 0 .text strNL: .asciz "\n" strInt: .asciz "%d" strFlt: .asciz "%g" strTrue: .asciz "TRUE" strFalse: .asciz "FALSE" message1: .asciz "Execution Error: Allocation failed!\n" message2: .asciz "Execution Error: Pointer is NIL!\n" message3: .asciz "Execution Error: Read statement failed!\n" message4: .asciz "Execution Error: Array index is out of bounds!\n" message5: .asciz "Execution Error: Count is not positive in array constructor!\n" .align 8

! ! runtimeError1- ! ! Branch to one of these labels to print an error message and abort. ! runtimeError1: set message1,%o call printf nop call exit mov 1,%o runtimeError2: set message2,%o call printf nop call exit mov 1,%o runtimeError3: set message3,%o call printf nop call exit mov 1,%o runtimeError4: set message4,%o call printf nop call exit mov 1,%o runtimeError5: set message5,%o call printf nop call exit mov 1,%o ! writeFlt ! ! This routine is passed a single precision floating number in %f0. ! It prints it by calling printf. It uses registers %f0, %f1. ! writeFlt: save %sp,-128,%sp fstod %f0,%f set temp,%l std %f0,[%l0] ldd [%l0],%o mov %o1,%o mov %o0,%o set strFlt,%o call printf nop ret restore

! ! PCAT Compiler Version 1. ! .global .div .global .rem ! ! Standard data fields ! .data .align 8 temp: .double 0 .text strNL: .asciz "\n" strInt: .asciz "%d" strFlt: .asciz "%g" strTrue: .asciz "TRUE" ...

Please try to make your compiler format its output as close to the .out.bak files as possible.

Useful Methods

I found that two methods made things much easier for me during code generation. They are: getIntoAnyReg() and storeFromAnyReg(). You may wish to create similar methods.

The idea is that you can call getIntoAnyReg() , passing it (1) a pointer to either a VarDecl , Formal , IntegerConst , or RealConst , and (2) the name of a register (such as “%o3”). It will generate whatever code is necessary to load the register.

Remember that a VarDecl may describe a local variable or a non-local variable. If you want to get the value of a local variable, you should generate code like this:

ld [%fp+-148],%reg

where “-148” is the offset of the variable in the activation record.

If the variable access is non-local, you should generate code that uses the appropriate display register. Assume the variable was declared at lexical level 7 and is used non-locally (say at lexical level 9). The code might look like this:

set display7,%reg ld [%reg2],%reg ld [%reg2+-148],%reg

In this case, a second register was necessary to hold addresses. The target register “reg” may be either an integer or float. Since addresses must always go into integer registers, the routine takes a third argument, “reg2,” which must name an integer register.

Note that the caller of getIntoAnyReg() may supply the same register for both “reg” and “reg2.” If, for example, it was called with reg=reg2=“%o0”, it would generate code this code:

set display7,%o ld [%o0],%o ld [%o0+-148],%o

To distinguish between locals and non-locals, you’ll have to know what the lexical level of the current routine is. Then you can compare it to the lexical level at which the variable was defined. If they are equal, this variable must be a local. (Also remember that in a VarDecl , lexLevel == - indicates the variable is a temporary. If the variable is a temporary, then it must be a local reference.)

These methods should generate the same code for Formal s (local or non-local) as they generate for VarDecl s (local or non-local).

The code generated by storeFromAnyReg() is the same as the code generated by getIntoAnyReg() , except that the final instruction is a st instead of a ld. For storeFromAnyReg() , “reg2” must be different from “reg.”

Here are the specifications for these methods:

// getIntoAnyReg (p, reg, reg2) // // This routine is passed p (a pointer to a VarDecl, Formal, // IntegerConst, or RealConst) and two registers. Each register will // be a String such as "%i3". This method generates instructions to // load the desired quantity into "reg." The register "reg" may be // either int or floating. The register "reg2" is an integer register // that will be used as necessary. This routine assumes that // IntegerConsts will only be loaded into integer regs, so it does not // check any mode information. //

void getIntoAnyReg (Ast.Node p, String reg, String reg2) ...

// storeFromAnyReg (p, reg, reg2) // // This method is passed p (a pointer to a VarDecl or Formal) and two // registers. Each register will be a String such as "%i3". This method // generates instructions to store the "reg" into the variable. // The register "reg2" must be an integer register and must be // different from "reg"; it will be used if necessary. //

void storeFromAnyReg (Ast.Node p, String reg, String reg2) ...

Approach to Implementing “Emit.java”

Here is the order in which I implemented the IR instructions.

The first test file to get working is simple.pcat. This PCAT program simply prints a couple of messages and it requires only four different IR instructions to function: IR.mainEntry , IR.mainExit , IR.writeString , and IR.writeNewline.

Next, work on compiling the file write.pcat , which additionally uses the IR.writeInt , IR.writeFloat , IR.writeBoolean , and IR.assign instructions.

! mainEntry .global main main: save %sp,-136,%sp set display0,%o st %fp,[%o0]

The frameSize here is “136,” but this number will vary in other PCAT programs. Thus, you’ll just need print statements to print the above 5 lines. To find the frameSize , just follow the arg field of the instruction to a Body node and use the frameSize that we saved in the Body in the previous project.

IR.mainExit

The code to be generated for the IR.mainExit instruction is this:

! mainExit ret restore

IR.writeString

The code to be generated for the IR.writeString instruction is this:

! writeString str sethi %hi(str123),%o call printf or %o0,%lo(str123),%o

The “str123” represents the name of the string being written and will vary among actual instructions. This code loads register %o0 with the one, and only, argument to printf() , which it then calls.

IR.writeNewline

A WRITE statement may print several things; these should all be followed by a single new-line. For example:

WRITE ("a = ", a, " b = ", b);

should produce a single line of output.

The code to be generated for the IR.writeNewline instruction is this:

! writeNewline sethi %hi(strNL),%o call printf or %o0,%lo(strNL),%o

IR.writeInt

The argument to the IR.writeInt instruction will be either an IntegerConst , VarDecl , or Formal. To generate code for this instruction, first call getIntoAnyReg() to load the value into %o1. In the example below, this produces the “set” instruction. Then produce the remaining three SPARC instructions, which call printf , passing strInt (the format string) as the first argument in %o0 and the integer value as the second argument in %o.

! writeInt 12345 set 12345,%o sethi %hi(strInt),%o call printf or %o0,%lo(strInt),%o

In this example, getIntoAnyReg() generated a single set instruction since the operand was an IntegerConst. If the operand had been a VarDecl or Formal , then getIntoAnyReg() would have generated several instructions to get it into %o1. (For writeInt , the operand will obviously never be a RealConst .) The routine getIntoAnyReg() requires two registers (called “reg” and “reg2”). We can just use reg = reg2 = %o.

Regardless of what instructions getIntoAnyReg() generates, the final three instructions (which set %o0 to point to the format string and call printf ) will always be the same.

IR.writeFloat

The code to be generated for the IR.writeFloat instruction will be something like this. (Refer to the comments about the list of floats in the “Boilerplate” section of this document.) From this example, you can see that the code was generated by first calling getIntoAnyReg() with reg = %f and reg2 = %o1. Then, the final two instruction (the “call” and the “nop”), which are always the same, were generated.

! writeFloat 654. set float2,%o ld [%o1],%f call writeFlt nop

IR.writeBoolean

The code to be generated for the IR.writeBoolean instruction will be something like this:

! writeBoolean 0 set 0,%o call writeBool nop

! return set display2,%o ld [%fp+64],%o st %o1,[%o0] ret restore

IR.goto

The code to be generated for the IR.goto instruction will be something like this:

! goto Label_ ba Label_ nop

IR.label

The code to be generated for the IR.label instruction will be something like this:

! Label_1: Label_1:

IR.gotoiLE

The code to be generated for the IR.gotoiLE instruction will be something like this. Note that the first two loads were generated by two calls to getIntoAnyReg() and would have be somewhat different if the operands had been different.

! if x <= t1 goto Label_2 (integer) ld [%fp+-8],%o ld [%fp+-12],%o cmp %o0,%o ble Label_ nop

The code for the other integer conditional branches is similar.

IR.gotofLE

The code to be generated for the IR.gotofLE instruction will be something like this. The code for the other floating point branches is similar. The “s” at the end of fcmps indicates single- precision. One can also use fcmpes to do the comparison and cause an exception if there are problems (e.g., one operand is NaN). Note that there is a nop instruction inserted between the compare and branch instructions.

! if x <= y goto Label_31 (float) ld [%fp+-4],%f ld [%fp+-8],%f fcmps %f0,%f nop fble Label_ nop

IR.iadd

The code to be generated for the IR.iadd instruction will be something like this. First, we call getIntoAnyReg() to get the first operand into %o0 (using reg2= %o0 as a work register if necessary). Then, we call getIntoAnyReg() to get the second operand into %o1 (using reg2= %o1 as a work register if necessary). Then, we generate the “add” operation, taking its arguments from %o0 and %o1 and placing its result in %o1. Finally, we call storeFromAnyReg() to generate code to move whatever is in %o1 to wherever the result should be (using %o0 as a work register if necessary).

If the two operands are local variables, we get something like this:

! t1 := y + z (integer) ld [%fp+-8],%o ld [%fp+-12],%o add %o0,%o1,%o st %o1,[%fp+-16]

If the two operands are in constants, we get something like this:

! t2 := 123 + 456 (integer) set 123,%o set 456,%o add %o0,%o1,%o st %o1,[%fp+-20]

If the two operands are non-locals, we get something like this:

! t3 := y + z (integer) set display0,%o ld [%o0],%o ld [%o0+-8],%o set display0,%o ld [%o1],%o ld [%o1+-12],%o add %o0,%o1,%o st %o1,[%fp+-4]

Other binary operators are similar. In the case of floating operations, we need to get the first operand into %f0 (using reg2= %o0 as a work register) and the second operand into %f1 (again using reg2= %o0 as a work register). The “fadds” operation will place its result in %f1 and

Ideally, one would like to call getIntoAnyReg() to move the integer value straight into %f0 , without messing with temp. There are better ways to generate a code sequence for this instruction, but I tried to keep the code as simple-minded as possible.

IR.formal

Originally, I had planned to pass parameters in registers %o0 - %o5 , following the SPARC conventions for the “C” language. This convention is very efficient if the subroutine can simply keep its parameters in the %o0 - %o5 registers and never move them into memory. Unfortunately, our simple-minded code generator would be significantly complicated by this approach. It is much easier to generate code if we can assume that all variables are stored in the activation record uniformly.

My original plan was to pass the first 6 arguments in the registers and then have the IR.formal instruction generate the code to move the argument values from the %o0 - %o5 registers into slots in the activation frame, where they would then be treated identically to the other local variables. Later, I realized that this plan would generate unnecessary loads and stores and that it would be simpler to have the caller just move all the arguments (into the caller’s frame, with instructions in the caller’s code). From there, they can be easily accessed by the callee’s code. One benefit of this plan is that we don’t have to distinguish between the first six parameters and the remaining parameters; they are all treated identically.

However, we still need to make sure that we allocate at least 6 words in each activation record for holding the first six parameters, regardless of whether we actually need the all six slots. (And we did this in the last project since it is the SPARC convention for calling “C” routines.) It might seem unnecessary if we only call routines with fewer than 6 arguments, but it is necessary since our PCAT routines may call “C” routines. (For example, we generate code that will call printf .) Our compiler makes sure there are always at least six slots present, just in case printf wants to make use of this space.

The bottom line is that all the arguments will be exactly where we want them–namely stored in the caller’s frame–by the time we get into the called subroutine. Thus, the IR.formal instruction expands into zero SPARC instructions. You should still copy the comment to the output, however.

! formal 1,x

Long discussion, short code sequence. I always like that.

IR.param

I implemented IR.param as shown by example below. I called getIntoAnyReg() to move the value into %o0. Then I generated a “st” instruction to move it into the correct slot in the caller’s activation record, depending on which parameter it is (e.g., parameter 1 goes into offset 68, parameter 2 goes into offset 72, etc.) Use the INITIAL_FORMAL_OFFSET and FORMAL_OFFSET_INCR constants.

! param 1, set 123,%o st %o0,[%sp+68] ! param 2, set 456,%o st %o0,[%sp+72]

IR.returnExpr and IR.resultTo

The test file call3.pcat tests the ability to return values from subroutines. To return values, we need the instructions IR.returnExpr and IR.resultTo.

The returned value can be returned in %o0 , which is called %i0 in the callee’s register window. To generate code for IR.returnExpr , we first call getIntoAnyReg() to move the returned value into %i0. Then, we generate code similar to IR.returnVoid to restore the display register and return. For example:

! return 123 set 123,%i set display2,%o ld [%fp+64],%o st %o1,[%o0] ret restore

Directly after an IR.call instruction, we will have an IR.resultTo instruction, which will tell us where to put the returned value. We can generate the SPARC code by calling storeFromAnyReg() to move the value from %o.

! resultTo t st %o0,[%fp+-8]

IR.readInt

The code generated for IR.readInt is almost identical to the code for IR.writeInt. In the following example, note that t1 will contain the address into which to store the result; we do not put the result in t1 itself. Also, we need to test the value returned by scanf() in %o0 to make sure it is non-zero. (The value is the number of characters scanned; if it is zero, there was an error in the input and no value was stored.)

! readInt t ld [%fp+-12],%o sethi %hi(strInt),%o call scanf or %o0,%lo(strInt),%o cmp %o0, be runtimeError nop