Вы находитесь на странице: 1из 26

[ReportSubmittedonWednesday,June20,2007]

Submittedby, Md.AbdusSalam,Roll11 AshisKumerBiswas,Roll19 4thYear,Session20042005

COMPILER PROJECT

[ Implementation of a compiler that translates programs written in PascalProgramminglanguageintocodeexecutablebySPIM.]

Submittedto, AminAhsanAli,Lecturer Md.RezaulKarim,AssociateProfessor

DepartmentofComputerScienceandEngineering, UniversityofDhaka

1|P a g e

TABLE OF CONTENTS PROBLEM DEFINITION ...................................................................................................................................... 3 Type variable .................................................................................................................................................................. 3 Form of Functions ........................................................................................................................................................... 3 No Nested functions ........................................................................................................................................................ 3 Recursive functions ......................................................................................................................................................... 3 Specification of the language used in this project ........................................................................................................... 3 Grammar specification ........................................................................................................................................................ 4 Lex specification used in this project .............................................................................................................................. 5 PHASES OF THE PROJECT ............................................................................................................................... 5 PHASE 1 .............................................................................................................................................................. 5 Objective: ........................................................................................................................................................................ 5 Pascal sample example source (bsearch) for testing our project in this phase ................................................................ 5 Designing the lexical analyzer ....................................................................................................................................... 6 Designing the syntactic analyzer..................................................................................................................................... 8 PHASE 2 ............................................................................................................................................................ 12 Objective ........................................................................................................................................................................... 12 Changes from the three address code generation in [Reference 1] ................................................................................... 13 Error checking ................................................................................................................................................................... 15 PHASE 3 ............................................................................................................................................................ 16 Objective ........................................................................................................................................................................... 16 Converting Three Address code to SPIM code ................................................................................................................. 16 Responsibilities of caller (during a function call) ............................................................................................................. 16 Responsibilities of callee .................................................................................................................................................. 17 Array indexing in SPIM .................................................................................................................................................... 18 Simulation result of the output file (s.s) ........................................................................................................................ 25 DISCUSSION ..................................................................................................................................................... 26 REFERENCES ................................................................................................................................................... 26

2|P a g e

ProjectName:
ImplementationofacompilerthattranslatesprogramswritteninPascalProgramminglanguageintocodeexecutableby SPIM.

ProblemDefinition
To implement the compiler, the following modules must be implemented: a lexical analyzer, a syntactical analyzer, a symbol table, a three address intermediate code generator, and a SPIM code generator. These tasks are divided over threedistinctivephases. Typevariable Therewillbetwotypesofvariables:integerandrealnumbers. FormofFunctions According to the project specification there will be procedures and functions. The procedure can take zero or more argumentsbutreturnsnovalue.Thefunctiontakesoneormoreargumentsandreturnsavalue. NoNestedfunctions Nonestedfunctionsareimplementedinthisproject. Recursivefunctions Recurrencerelationscanbedepictedthroughtherecursivefunctions. Specificationofthelanguageusedinthisproject Thegrammarhasthefollowingspecification
program program ID ( identifier_list ); declarations subprogram_declarations compound_statement idenfier_list ID | identifier_list , ID idenfier_list declarations var identifier_list: type; | type -> standard_type | array [ num .. num ] of standard_type standard_type | integer real

subprogram_declarations subprogram_declarations subprogram_declaration; | subprogram_declaration subprogram_head declarations compound_statement subprogram_head function id arguments: standard_type; | procedure id arguments;

3|P a g e

srguments `

( parameter_list ) |

parameter_list identifier_list: type | parameter_list; identifier_list: type compound_statement begin Compound_statement end optional_statement statement_list | statement_list statement | statement ; statement statement variable assignop expression | procedure_statement | compound_statement | if expression then statement else statement | if expression then statement | while expression do statement variable id | id [ expression ] procedure_statement id | id ( expression_list ) expression_list expression | expression_list, expression expression simple_expression | simple_expression RELOP simple_expression simple_expression -> term | + term | - term | simple_expression OR term | simple_expression + term | simple_expression - term term -> factor | term * factor | term / factor factor id | id ( expression_list ) | num | ( expression ) | id [ expression ] | not factor

Grammarspecification InPascal(accordingtothespecificationabove),aprogramconsistsofasequenceofglobaldatadeclarations,a sequence of procedures and function declarations, and a single compound statement that is the main program. Globaldataistobeallocatedstaticstorage. 4|P a g e

Datalocaltoproceduresandfunctionsisallocatedstorageonastack. Recursionispermitted. Functionparametersarepassedbycopy. Theprojectimplementsprint(address)callthatprintsthecontentsofavariablespecifiedbyaddress. This grammar contains a production statement if expression then statement that introduces the danglingelseambiguity,whichwaseliminatedusingprecedenceruledefinedintheYACCcode.

Lexspecificationusedinthisproject Commentsaresurroundedby{and},theymaynotcontaina{.Commentsmayappearafteranytoken.Theycan bemultiline. Tokenidforidentifiersmatchesaletterfollowedbylettersordigits:


letter [a-za-z] digit [ 0 9 ] id letter ( letter | digit ) *

Tokennummatchesunsignedintegerasfollows
digits digit digit * optional_fraction . digits | optional_exponent (e(+|-)digits)| num digits optional_fraction optional_exponent

Therelationaloperatorsare=,<>,<,>=,>,<=(RELOP) Theaddopsare+,andor Themulopsare*,/,mod,and Thelexemefortokenassignopis:=

Phasesoftheproject Phase1
Objective: Acompilerwhichcanparseagivencodefile, Anddetermineifthecodefileissyntacticallyandsemanticallycorrect The first phase of this assignment consists of the implementation of the lexical and syntax analyzer and the symbol table. TheprojectafterthisphasecanreadaprograminPascalandoutputthesymboltable.Beingcrucialforthenextphases ofthecompiler,thedesignofthefirstphaseneedstobewellstructuredanddesigned. Pascalsampleexamplesource(bsearch)fortestingourprojectinthisphase Figure1showsasamplePascalcodeforrecursiveBinarysearchonagivensortedarray.Itusesafunctionsearch()for performingbinarysearchoperation. Thesearch()functionreturns0ifthekeyvalueisnotfoundinthearrayindexedby0Nprovidedintheargumentsof thesearch()function.Itreturns1onsuccessfullyfindingthekeyvalue. 5|P a g e


Figure1:AsamplePascalprogramthatperformsrecursivebinarysearch

Designingthelexicalanalyzer After this step, our project can get all the lexemes and tokens and determine whether any lexical errors occur in the givensourceprogram. Wecouldinstallthesymbols(IDs)inthesymboltableinthisstep,butitwouldleadusinwrongway,causewedonot knowinthelexicalanalysisthatwhetherweareinstallingafunction,procedure,arrayoranyotherordinaryvariables withoutparsingthefiles.Weleavethejobofinstallingsymbols(IDs)andsymboltablemanagementinsyntaxanalysis step(Parser).

6|P a g e


Figure2:AsuccessfulLexicalandsyntacticanalysis

OurprojectoutputsthelineSuccessfullyparsedthesourcecodehighlightedinFigure2sincenosyntacticandlexical rulesareviolatedinthegivensourcecode.Incaseofsyntaxerror,thedefaultbehaviorofLexandYaccisadapted,that istoterminatefurtherparsingaftershowingamessagesyntaxerrortotheuser. ThelexicalruleswereimplementedusingLex,asamplelexfile(afterphase1)mightbe Definingsomelexvariablestobeusedinthespecification


blankCharacters letter digit digits optional_fraction optional_exponent [ \t]+ [a-zA-Z] [0-9] {digit}+ (\.{digits})? ([E][+-]?{digits})?

DefiningkeywordsofthePascalgrammar
program var array integer real function procedure begin end if of then else while { { { { { { { { { { { { { { return return return return return return return return return return return return return return PROGRAM;} VAR;} ARRAY;} INTEGER;} REAL;} FUNCTION;} PROCEDURE;} BBEGIN; //Since BEGIN is a keyword in Lex/Yacc,we used different name} END;} IF;} OF;} THEN;} ELSE;} WHILE;}

7|P a g e

do

{ return DO;}

Definingthelexspecification
\{([\r\n]|[^{])*\} := { ; } { } { yylval.value = strdup(yytext); return MULOP; or } { yylval.value = strdup(yytext); return ADDOP; } {letter}({letter}|{digit}){0,9} { yylval.value = strdup(yytext); return ID; } {digits}{optional_fraction}{optional_exponent} { yylval.value = strdup(yytext); return NUM; } =|<>|<|<=|>|>= { yylval.value = strdup(yytext); return RELOP; } {blankCharacters} { ; //Do nothing } [\n] { lineNum++; } . { //or any other character, just return it return yytext[0]; } //Multiline comments

return ASSIGNOP; [*/]|div|mod|and

Designingthesyntacticanalyzer Thesyntaxanalyzerparsesthesourcefileaccordingtothegrammarforanyactionstotakeplaceorgenerateanysyntax errormessagesthatwarnsaboutanygrammaticalerrors.Figure3showsusasampleparse.yfiletobepassedtothe Yaccparsergeneratorthatwillhandlethesyntacticanalysisjob. Besidesparsing,thisstepcontainsdefinitionsandsomemanagementfunctionstohandlethesymboltable,necessaryin allphasesofthecompilerdesign. ThesymboltableorganizationforthesamplebinarysearchprogramofFigure1isshowninFigure3.

8|P a g e

search

NumOfSymbols:= 12 tableSize:=68 bytes

main

NumOfSymbols:= 7 tableSize:=64 bytes

Figure3:SymboltablestructureforrecursivebinarysearchprograminPascal

ThefactaboutthesymboltableNameentriesofasymbolisthatthescopenameisconcatenatedwiththesymbol name,sothatduringcodegenerationwedonotneedtobotherinwhichscopethesymbolresides. InFigure3,theNode0(mainfunctionssymboltabletheheadnodeofthelinklistofsymboltable),itisshownthat searchisafunctionthattakes3argumentsandallthe3argumentstypesare0(integer).Alltemporariescreatedinany computation was installed in the corresponding symbol table. For example, during computation in search function temporariest#28,t#36,t#40,t#44,t#48,t#52,t#56,t#60,t#64arepresentinthesymboltableofsearchfunction(as showninFigure3).Thetemporariesarenamedwithastringt#andtheoffsetofitinitsactivationrecord,whichwill bemappeddirectlyduringcodegeneration.
//SymbolTable LinkedList: //First node: Global Symbol Table, //second..third...all are nodes are specific functions' symbol table // typedef struct LocalSymbolTable{ char *scopeName; //The name of the function SymbolTable tab[NSYMS]; //The symbol table int numOfSymbols; //number of symbols currently resides

9|P a g e

struct LocalSymbolTable *next; }LocalSymbolTable; /** Symbol Table structure */ typedef struct SymbolTable{ char *name; int type;

//pointer to the next symbol table

//name of the symbol //type of the symbol (0:integer, 1:real) //in case of a function this field indicates return type int offset; //offset in its activation record int lowerBound, upperBound; //in case of array type variables int numOfArguments; //in case of functions number of arguments int arguments[32]; //types of arguments in order (in case of func) }SymbolTable;

Wheneverasymbol(ID)isaskedinthegrammar,thatsymbolissearchedfirstinthecallerscopesnode,ifitisnot there,thenitwillbelookedupinNode0(globalnode).Ifagainitisnotthere,thencorrespondingerrormessagesgot printedinthestderrstream. Thefollowingfunctionsrelatedtothesymboltablewereimplemented


LocalSymbolTable *makeLocalSymbolTable(char *scope);

ThisfunctionmakesthefirstnodethesymboltableslinklistwiththescopeasthescopeNameandreturnsthepointer tothatnode.Thisprojectexpectsthescopetobemainhereinthiscase.

LocalSymbolTable *appendLocalSymbolTable(LocalSymbolTable **head, char *scope);

Thisfunctioncreatesanothernode(LocalSymbolTable)withthescopeNamescopeandappendsthenodeinthe existinglinklistpointedtobyhead.
LocalSymbolTable *returnLocalSymbolTable(LocalSymbolTable **head, char *scope);

ThisfunctionreturnsthecorrespondingLocalSymbolTablenodewithscopeName=scopeintheexistinglistpointedto byhead.

LocalSymbolTable *deleteLocalSymbolTable(LocalSymbolTable **head, char *scope);

ThisfunctiondeletesasymbolTablenodeofscopeName=scopefromtheexistinglistpointedtobyhead.Theproject doesnotactuallyrequirethisfunction,causewedonotneedtodeleteanynodebeforecodegenerationphase(thefinal phaseoftheproject).

SymbolTable * lookup(SymbolTable *st, int numOfSymbols, char *str);

ThisfunctionlooksupasymbolnamedstrinaspecificsymboltablestwithnumOfSymbolsinit.

int install(SymbolTable *st, int numOfSymbols, char *str);

installasymbol(str)inaspecificsymboltable(st)withnumOfSymbolsentriesinit. 10|P a g e

void printSymbolTable(SymbolTable *st, int numOfSymbols);

printaspecificsymboltable(st)withnumOfSymbolsentriesinit.
int getType(SymbolTable *st, int numOfSymbols, char *name);

ThisfunctionreturnsthetypeofasymbolnamednameinaspecificsymboltablestwithnumOfSymbolsentriesinit.It returns0iftypeisinteger,1ifreal,BADVALotherwise.
int getOffset(SymbolTable *st, int numOfSymbols, char *name);

ThisfunctionreturnstheoffsetofasymbolnamednameinaspecificsymboltablestwithnumOfSymbolsentriesinit. Itreturns0iftypeisinteger,1ifreal,BADVALotherwise.
int getFunctionArgumentTypeN(LocalSymbolTable *head, SymbolTable *st, int numOfSymbols, char *name, int N);

ThisfunctionreturnsthetypeofNthargumenttakenbyfunctionnamednameinaspecificsymboltablestwith numOfSymbolsentriesinit.Itreturns0iftypeisinteger,1ifreal,BADVALotherwise.

int getNumberOfArguments(SymbolTable *st, int numOfSymbols, char *name);

ThisfunctionreturnsthenumberofArgumentstakenbyafunctionnamednamefromthesymboltablestof numOfSymbolsentriesinit.Thisvaluecanbewithin031.

void printLocalSymbolTable(LocalSymbolTable **head);

Printthesymboltablelinkedlistasawhole.IteventuallycallsprintSymbolTable()function.

11|P a g e

Figure4:UsingSymbolTableandthefirstgrammarrule

Figure4showsasamplesnapshotofthesourcecodeparse.yoftheprojectthatshowsthesyntaxdirected translationsnecessaryforthefirstproduction. Sincethisproductionisthestartproduction,thenafterparsingthelastpartoftherulecompound_statement.,aline Successfullyparsedthesourcecodewillgetprintediftheparsingofasourcecodeiscorrect,thentwofunctionsare invoked printCode():printsthethreeaddresscodeforthesourcecodegivenwhichisimplementedinPhase#2ofthe project. convertToSpim():ConvertsthethreeaddresscodetoSPIMcode(copiedinthefiles.s)tobesimulatedwith SPIMsimulator.ThisisimplementedinPhase#3oftheproject.

Phase2
Objective DesigningacompilerthatcanparseagivenPascalsourcefileandtranslateitintointermediateform(Three AddressCode). HerethefunctionprintCode()isimplementedandtheoutputofthisfunctionfortheinputofFigure1isasfollows
0 1 2 search: if search:low > search:high goto Lbl3 goto Lbl5

12|P a g e

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

Lbl3: RETVAL := 0 goto Lbl33 Lbl5: search:t#28 = search:low + search:high search:t#36 = search:t#28 / 2 search:mid := search:t#36 search:t#40 := main:a[search:mid] if search:key = search:t#40 goto Lbl11 goto Lbl12 Lbl11: RETVAL := 1 Lbl12: search:t#44 := main:a[search:mid] if search:key < search:t#44 goto Lbl15 goto Lbl22 Lbl15: search:t#48 = search:mid - 1 param search:key param search:low param search:t#48 call search search search:t#52 := RETVAL RETVAL := search:t#52 Lbl22: search:t#56 := main:a[search:mid] if search:key > search:t#56 goto Lbl25 goto Lbl32 Lbl25: search:t#56 = search:mid + 1 param search:key param search:t#56 param search:high call search search search:t#64 := RETVAL RETVAL := search:t#64 Lbl32: JUMP search Lbl33: JUMP search main: main:a[0] := 12 main:a[1] := 23 main:a[2] := 100 main:a[3] := 234 main:a[4] := 311 param 311 param 0 param 4 call search main main:t#60 := RETVAL main:result := main:t#60

Changesfromthethreeaddresscodegenerationin[1] Thethreeaddresscodegenerationofthisphaseistotallyindifferentfromtheoutlineshownin[1].Butsomechanges havebeenmadetopreparethethreeaddresscodeforthephase3codegeneration. Thechangesarelistedbelow Allthevariablesareusedwithitsnamealongwithitsscopenamewhereitwasdeclared.Thisisextremely importantforphase3(codegeneration)becauseafterthisphasewecannotgetanyscopeinformationofa symbolofthesamenameintheplaceoftheiruse. IncaseofreturningavaluefromafunctionaspecialvariableRETVALisused.AnystatementoftypeRETVAL:= valueindicatesthatthisthereturnstatementforthefunctionandanyvalueassignedtoitwouldbereturned 13|P a g e

tothecaller.Thiscanbefoundinline11,21and31.Furtherusingthereturnvalueisdoneusingthevariable RETVALonlyascanbefoundinline20,30and44. ThelaststatementforafunctionisJUMPfunctionName.ThefunctionNamefieldisrequiredbecauseduring codegenerationphasewedonotknowwhoisreturningfromafunctionnow,soitisbettertostorethename ofthefunctionthatiscurrentlyreturning. Thecallingafunctionsequenceisadaptedfrom[1].Forexample,forthefollowingpascalcodeinvokedinthe bodyofthefunctionlcm() x:= a + gcd(1,20) + b thecorrespondingthreeaddresscodeis param 1 param 20 call gcd lcm t#1:= a + RETVAL t#2:= t#1 + b x:= t#2 Heretheparameters1and20arepassedusingthekeywordPARAM.Afterpassingalltheparameters,the functioniscalledusingthewordcall.Thefirstargumentofthecallstatementisthefunctionnamethatweare goingtocall.Butthesecondargumentisfoundtobeimportanttoo,thatisthenameoffunctionthatiscalling thefunction.Duringcodegeneration,itisdifficulttoresolvewhoiscallingthefunction,soweputextra informationhereinthisphase. Thegrammarthattheprojectisusingnowisfreefromtheproblemdanglingelse.Theproblemis Statement> | ifexpressionthenstatement ifexpressionthenstatementelsestatement

Theparsercannotdeterminetheelsepart,showingaconflictmessage.Thiscanbesolvedusingprecedence ruleratherthanchangingthegrammar. Firstwedeclareprecedenceatthetopoftheparse.yfile


%nonassoc LOWER_THAN_ELSE %nonassoc THEN %nonassoc ELSE

Theninthesyntaxdirectedtranslationweputthefollowingcode
Statement-> IF expression THEN M statement %prec LOWER_THAN_ELSE{ puts("statement -> IF expression THEN statement statementS"); backPatch($2->trueList, $4->quad); backPatch($2->falseList,nextQuad); $$ = (StatementNode *)malloc(sizeof(StatementNode)); $$->nextList = $5->nextList;

14|P a g e

| statement");

} IF expression THEN M statement ELSE N M statement { puts("statement -> IF expression THEN statement statement ELSE

backPatch($2->trueList,$4->quad); backPatch($2->falseList,$8->quad); $$ = (StatementNode *)malloc(sizeof(StatementNode)); $$->nextList = (int *)mergeList($5->nextList,(int *) mergeList($7->nextList,$9->nextList)); }

Preservingthethreeaddressbehaviorofthisphasewehaveeliminatedallfourormoreaddressstructureslike thefollowingPascalstatement

A[4]:= B[5] Thisstructureischangedasfollows

t#1 := B[5] A[4]:= t#1 Errorchecking Thereareseveraltypesoferrorcheckingimplementedinthisproject.Theerrormessagesgetprintedinstderr,sothat thestreamsoutputcanberedirectedtoafileseparatelyandlaterwecanjustseeifthefilessizeis0byteincaseofno error. Thefollowinglistshowstheerrormessagesfromtheproject


Undefined symbol \'%s\'

Thismessageisshownwhenanysymbolorfunctionorprocedureiscalledifitsentrycannotbedetermined.The sequencetosearchthesymbolisfirstcheckthesymbolincurrentscopesnodetable,ifnotfoundthenlookupinthe globaltable(node0),ifagainfailed,thenthiserrormessageisgenerated.


Function %s already defined (overloading of functions not supported)

Thismessageisgeneratedwhenanotherfunctiondefinitionofafunctionisencountered.
Procedure %s already defined (overloading of procedures not supported)

Thismessageisgeneratedwhenanotherproceduredefinitionofaprocedureisencountered.
Function %s can return only \'%s\' type

Thiserrormessageisshownwhenanyattempttoreturnanyvaluewhosetypedoesnotmatchwiththereturntypeof thefunctionasfoundintheglobalnode(Node0),sinceallthefunctiondeclarationsarestoredinthattable.
Procedure %s can not return any value

Ifanyreturnstatementisfoundintheproceduresbody,thenthistypeofmessageisshown.
Type mismatch - \'%s\'(%s) with \'%s\'(%s)

15|P a g e

Whenanyoperationlikeassignment,binaryoperations,thetypesoftheoperandsarecheckedfirst.Incaseofany mismatch,thistypeoferrormessageisshown.
array index must be integer \'%s[%s]\

Thiserrormessageisshownwhenanyarrayindexstypeisnotinteger.
Function %s can not convert arg %d from %s to %s

Thiserrormessageisshownwhenithargumentstypedoesnotmatchwiththeithparameterofthefunction.
Function %s does not take %d parameters

Thiserrormessageisshownwhenafunctioniscalledwithwrongnumberofarguments.

Phase3
Objective DesigningacompilerthatcanreadagivenPascalsourcecodefileandtranslatethisintosubsetMIPSassembler. ThisgeneratedassemblercodesshouldrunonaMIPSsimulator. ConvertingThreeAddresscodetoSPIMcode ConvertingthethreeaddresscodetoSPIMcodewasadaptedfromthedocument[2]withsomechangesfortheeaseof ourimplementationofphase2.Thechangesaredescribedbelow Figure5showstheorganizationofactivationrecordfortheexampleshowninFigure1. Theactivationrecordsizeofanyfunctioniscalculatedas
Activation Record size of function F := 4 + 4 + 4 + Number of temporaries * 4 + Number of locals * 4

Here,firstthree4bytesareforstoringreturnaddressofthefunction,returnvalueforthefunctionand activationrecordsizeofthecallerfunction.(AsshowninFigure5). Responsibilitiesofcaller(duringafunctioncall) Thefollowingpseudocodeexplainsthesequencesforafunctioncall. Step1:Storeparameteriforthefunctionatlocation-(12+4*i)($sp),wherei=0,1,2,,n. Forexampleparameter0willbestoredin12($sp),parameter1willbestoredin16($sp),andsoon. Step3:Jumptothecalleeslabelusingjalcommand.Forexample, 16|P a g e Step2:Storethesizeoftheactivationrecordofthecalleratlocation8($sp). Step3:Update$sp(stackpointer)and$fp(framepointer)asfollows
$sp = $sp activation record size of the callee $fp = $sp + activation record size of the callee

jal search Thisstatementunconditionallyjumpstotheinstructionatlabelsearchandsavestheaddressofthenext instructioninregister$ra. Thusthecodeforcallingfunctionsearch(311,0,4)frommainbecomesthefollowing


#storing parameters 311, 0 and 4 li $t0, 311 sw $t0, -12($sp) li $t0, 0 sw $t0, -16($sp) li $t0, 4 sw $t0, -20($sp) #t0 stores the size of the callee li $t0, 64 #t4 stores the size of the caller li $t4, 60 sw $t4, -8($sp) #updating stack and frame pointers sub $sp, $sp, $t0 add $fp, $sp, $t0 #jump to the label search jal search

Responsibilitiesofcallee Thefirststepofthecalleeistobackupthereturnaddressinits0thoffsetoftheframepointer.Forexample,the firststatementofthefunctionsearch()mightbe search:


#Backing up Return Address Register value $ra sw $ra, 0($fp)

Beforereturningfromafunctionthefunctionshouldstorethecomputedreturnvalue(ifpresent)atoffset4to theframepointer.Forexample,ifthesearchissuccessful,thenthesearchfunctionreturnsthevalue1tothe caller,soitstores1atlocation4($fp)asthereturnvalue.


#Preparing a return value of a function li $t0, 1 sw $t0, -4($fp)

Returningfromafunctionrequirestoloadthereturnaddressfromthe0offsettotheframepointerofthe functionsactivationrecord.Andthenupdatethestackpointerandframepointercomputedasbelow $sp=$sp+activationrecordsizeofthefunctionthatisreturning $fp=$sp+activationrecordsizeofthecallerofthefunction 17|P a g e

Thenunconditionallyjumpthereturnaddressstoredinregister$rausingjrstatementasbelow jr $ra

Soreturningfromafunctionyieldsthefollowingcode
#Returning from a function li $t0, 64 lw $ra, 0($fp) lw $t1, -8($fp) add $sp, $sp, $t0 add $fp, $sp, $t1 jr $ra

#the activation record size of the function #the size of the callers activation record

ArrayindexinginSPIM SupposewearetoconvertthefollowingthreeaddressstatementtoSPIM. search:t#40:=main:a[search:t#24] Thisistostorethecontentofthearrayadeclaredinmain()andoffsett#24(temporarystoredatoffset24totheframe pointerofthesearchfunction)inanothertemporaryt#40inthefunctionsearch(). Conversionstepsaregivenbelow Step1:Justloadtheoffsetvaluetoregister$t4 Step2:Multiplytheoffsetwiththesizeofthecontent(hereis4bytes) Step3:Addbaseaddressofthearraya(sincethearrayaisglobal,westoretheframepointerofmaininregister$s7)to themultiplicationresult. Step4:Thenloadthevaluetotheregister$t0 Step5:Storetheresultint#40temporarylocationofthesearchfunction. Alltheabovestepscanbesummedinthefollowingfragment
#This is an ordinrary assignment operation lw $t4, -24($fp) mul $t4, $t4, 4 add $t4, $t4, 12 sub $t4, $s7, $t4 lw $t0, ($t4) sw $t0, -40($fp)

18|P a g e


Figure5:ExampleofactivationRecordorganizationinSPIMmemoryforsubsequentfunctioncallsforthesourcecodeofFigure1

Allotherconversionspecificationsareadaptedfromthedocument[2]. 19|P a g e

ForefficientlyconvertingthethreeaddresscodetoSPIMcode,thisphaseimplementsconvertToSpim()function.The functiongeneratesafiles.sthatcontainstheresultantSPIMcode.Thesamplecontentofthefiles.sforthegiven inputofthebinarysearchalgorithmisgivenbelow


.data newline: .asciiz "\n" .text .globl main

#start of function search() search: L0: #Backing up Return Address Register value $ra sw $ra, 0($fp) L1: #Processing a Relational operation lw $t0, -16($fp) lw $t1, -20($fp) bgt $t0, $t1, L3 L2: #Unconditional JUMP j L5 L3: #Preparing a return value of a function li $t0, 0 sw $t0, -4($fp) L4: #Unconditional JUMP j L33 L5: #Performing ADD + operation lw $t0, -16($fp) lw $t1, -20($fp) add $t0, $t0, $t1 sw $t0, -28($fp) L6: #Performing DIV (/) operation lw $t0, -28($fp) li $t1, 2 div $t3, $t0, $t1 sw $t3, -36($fp) L7: #This is an ordinrary assignment operation lw $t0, -36($fp) sw $t0, -24($fp) L8:

20|P a g e

#This is an ordinrary assignment operation lw $t4, -24($fp) mul $t4, $t4, 4 add $t4, $t4, 12 sub $t4, $s7, $t4 lw $t0, ($t4) sw $t0, -40($fp) L9: #Processing a Relational operation lw $t0, -12($fp) lw $t1, -40($fp) beq $t0, $t1, L11 L10: #Unconditional JUMP j L12 L11: #Preparing a return value of a function li $t0, 1 sw $t0, -4($fp) L12: #This is an ordinrary assignment operation lw $t4, -24($fp) mul $t4, $t4, 4 add $t4, $t4, 12 sub $t4, $s7, $t4 lw $t0, ($t4) sw $t0, -44($fp) L13: #Processing a Relational operation lw $t0, -12($fp) lw $t1, -44($fp) blt $t0, $t1, L15 L14: #Unconditional JUMP j L22 L15: #Performing SUB (-) operation lw $t0, -24($fp) li $t1, 1 sub $t3, $t0, $t1 sw $t3, -48($fp) L16: #Calling a function / procedure lw $t0, -12($fp) sw $t0, -12($sp) lw $t0, -16($fp) sw $t0, -16($sp) lw $t0, -48($fp) sw $t0, -20($sp)

21|P a g e

li $t0, 64 li $t4, 64 sw $t4, -8($sp) sub $sp, $sp, $t0 add $fp, $sp, $t0 jal search L20: #Using functions's return value lw $t0, -4($sp) sw $t0, -52($fp) L21: #Preparing a return value of a function lw $t0, -52($fp) sw $t0, -4($fp) L22: #This is an ordinrary assignment operation lw $t4, -24($fp) mul $t4, $t4, 4 add $t4, $t4, 12 sub $t4, $s7, $t4 lw $t0, ($t4) sw $t0, -56($fp) L23: #Processing a Relational operation lw $t0, -12($fp) lw $t1, -56($fp) bgt $t0, $t1, L25 L24: #Unconditional JUMP j L32 L25: #Performing ADD + operation lw $t0, -24($fp) li $t1, 1 add $t0, $t0, $t1 sw $t0, -56($fp) L26: #Calling a function / procedure lw $t0, -12($fp) sw $t0, -12($sp) lw $t0, -56($fp) sw $t0, -16($sp) lw $t0, -20($fp) sw $t0, -20($sp) li $t0, 64 li $t4, 64 sw $t4, -8($sp) sub $sp, $sp, $t0 add $fp, $sp, $t0 jal search L30:

22|P a g e

#Using functions's return value lw $t0, -4($sp) sw $t0, -64($fp) L31: #Preparing a return value of a function lw $t0, -64($fp) sw $t0, -4($fp) L32: #Returning from a function li $t0, 64 lw $ra, 0($fp) lw $t1, -8($fp) add $sp, $sp, $t0 add $fp, $sp, $t1 jr $ra L33: #Returning from a function li $t0, 64 lw $ra, 0($fp) lw $t1, -8($fp) add $sp, $sp, $t0 add $fp, $sp, $t1 jr $ra main: L34: #Creating main's Activation Record space sub $sp, $sp, 60 add $fp, $sp, 60 move $s7, $fp #Backing up Return Address Register value $ra sw $ra, 0($fp) L35: #This is an ordinrary assignment operation li $t0, 12 li $t4, 0 mul $t4, $t4, 4 add $t4, $t4, 12 sub $t4, $s7, $t4 sw $t0, ($t4) L36: #This is an ordinrary assignment operation li $t0, 23 li $t4, 1 mul $t4, $t4, 4 add $t4, $t4, 12 sub $t4, $s7, $t4 sw $t0, ($t4) L37: #This is an ordinrary assignment operation li $t0, 100 li $t4, 2

23|P a g e

mul $t4, $t4, 4 add $t4, $t4, 12 sub $t4, $s7, $t4 sw $t0, ($t4) L38: #This is an ordinrary assignment operation li $t0, 234 li $t4, 3 mul $t4, $t4, 4 add $t4, $t4, 12 sub $t4, $s7, $t4 sw $t0, ($t4) L39: #This is an ordinrary assignment operation li $t0, 311 li $t4, 4 mul $t4, $t4, 4 add $t4, $t4, 12 sub $t4, $s7, $t4 sw $t0, ($t4) L40: #Calling a function / procedure li $t0, 311 sw $t0, -12($sp) li $t0, 0 sw $t0, -16($sp) li $t0, 4 sw $t0, -20($sp) li $t0, 64 li $t4, 60 sw $t4, -8($sp) sub $sp, $sp, $t0 add $fp, $sp, $t0 jal search L44: #Using functions's return value lw $t0, -4($sp) sw $t0, -60($s7) L45: #This is an ordinrary assignment operation lw $t0, -60($s7) sw $t0, -52($s7) #Print the result and a newline li $v0, 1 lw $a0, -52($fp) syscall li $v0, 4 la $a0, newline syscall L46: L47:

24|P a g e

#Exit.........syscall li $v0, 10 syscall

Simulationresultoftheoutputfile(s.s)
Ifweruntheabovecode(s.s)inSPIMsimulatorwegetthea1attheoutputindicatesthattheprogramsucceedsin findingthevalue311asindicatedinFigure6.

Figure6:simulatings.sfilewhenthesearchiscalledwith311askey.search(311,0,4)

Butifwechangethekeyvalueinsearch()functioncallto1,andgeneratetheSPIMcodeagainandfeedthecodetothe SPIMsimulator,wewillgeta0astheoutput,whichindicatesthattheprogramfailstosearchthevalue1.

25|P a g e


Figure7:Simulatings.sfilewhenthesearchiscalledwith1askey.search(1,0,4)

Discussion
Theprojectcompletedsofarhassomedeficiencies Floatingpointcalculationsisnotimplementedintheproject. Readinginputfromtheuserisnotalsoimplemented;rathertheinputcanbegiveninthesourcecode.Butthis isnotamajordeficiencybecausereadingfrominputcanbeimplementedusingSPIMsystemcalls.

Theprojectcansimulateanytypeofintegercalculationsandfunctionsthatwespecifiedintheproblemspecification section.

References
[1] [2] AlfredV.Aho,RaviSethi,JeffreyD.UllmanCompilersPrinciples,Techniquesandtools,PearsonEdition SaumyaDebray;NotesonTraslatingThreeAddressCodetoMIPSAssemblyCodeDepartmentofComputer Science;TheUniversityofArizona,Tucson JamesR.Larus;SPIMS20:AMIPSR2000Simulator. http://www.cs.wisc.edu/~larus/SPIM/spim_documentation.pdf AppendixA:Assemblers,Linkers,andtheSPIMSimulator(HP_APPA.pdf).Anoverviewandreferencemanualfor spimandtheMIPS32instructionset.

[3]

[4]

26|P a g e

Вам также может понравиться