30
Function Calling Conventions 1 CS 64: Computer Organization and Design Logic Lecture #9 Ziad Matni Dept. of Computer Science, UCSB

Function Calling Conventions 1 - GitHub Pages

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Function Calling Conventions 1 - GitHub Pages

FunctionCallingConventions1

CS64:ComputerOrganizationandDesignLogicLecture#9

ZiadMatni

Dept.ofComputerScience,UCSB

Page 2: Function Calling Conventions 1 - GitHub Pages

LectureOutline

•  MoreonMIPSCallingConvention

– Functionscallingfunctions

– Theroleoftheconventionandhowtouseit

5/3/18 Matni,CS64,Sp18 2

Page 3: Function Calling Conventions 1 - GitHub Pages

MIPSCallingConventions

•  Whatwearetalkingabouttodayandthenextlecture

•  You*must*readthehandoutonMIPSCallingConventions– Foundonourwebpage

5/3/18 Matni,CS64,Sp18 3

Page 4: Function Calling Conventions 1 - GitHub Pages

AnyQuestionsFromLastLecture?

5/3/18 Matni,CS64,Sp18 4

Page 5: Function Calling Conventions 1 - GitHub Pages

CallingFunctionsonMIPS

•  Twocrucialinstructions:jalandjr•  Onespecializedregister:$ra

•  jal(jump-and-link)–  Simultaneouslyjumptoanaddress,andstorethelocationof

thenextinstructioninregister$ra

•  jr(jump-register)–  Jumptotheaddressstoredinaregister,often$ra

5/3/18 Matni,CS64,Sp18 5

Page 6: Function Calling Conventions 1 - GitHub Pages

PassingandReturningValuesinMIPS

•  Registers$a0thru$a3– Argumentregisters,forpassingfunctionarguments

•  Registers$v0and$v1– Returnregisters,forpassingreturnvalues

5/3/18 Matni,CS64,Sp18 6

Page 7: Function Calling Conventions 1 - GitHub Pages

FunctionCallsWithinFunctions…

Givenwhatwe’vesaidsofar…•  Whataboutthiscodemakesourpreviouslydiscussedsetupbreak?–  Youwouldneed

multiplecopiesof$ra

5/3/18 Matni,CS64,Sp18 7

•  You’dhavetocopythevalueof$ratoanotherregister(ortomem)beforecallinganotherfunction

•  Danger:Youcouldrunoutofregisters!

Page 8: Function Calling Conventions 1 - GitHub Pages

AnotherExample…

Whataboutthiscodemakesthissetupbreak?•  Can’tfitallvariablesinregistersatthesametime!

•  HowdoIknowwhichregistersareevenusablewithoutlookingatthecode?

5/3/18 Matni,CS64,Sp18 8

Page 9: Function Calling Conventions 1 - GitHub Pages

Solution??!!

•  Storecertaininformationinmemoryonlyatcertaintimes

•  Ultimately,thisiswherethecallstackcomesfrom

•  Sowhat(registers/memory)savewhat???

5/3/18 Matni,CS64,Sp18 9

Page 10: Function Calling Conventions 1 - GitHub Pages

WhatSavesWhat?•  ByMIPSconvention,certainregistersaredesignatedtobepreservedacrossacall

•  Preservedregistersaresavedbythefunctioncalled(e.g.,$s0-$s7)–  Sothesearesavedatthestartofeveryfunction

•  Non-preservedregistersaresavedbythecallerofthefunction(e.g.,$t0-$t9)–  Sothesearesavedbythefunction’scaller–  Ornot…(theycanbeignoredundercertaincircumstances)

5/3/18 Matni,CS64,Sp18 10

Page 11: Function Calling Conventions 1 - GitHub Pages

AndWhereisitSaved?

•  Registervaluesaresavedonthestack

•  Thetopofthestackisheldin$sp(stackpointer)

•  Thestackgrowsfromhighaddressestolowaddresses

5/3/18 Matni,CS64,Sp18 11

Page 12: Function Calling Conventions 1 - GitHub Pages

TheStack

Whenaprogramstartsexecuting,acertaincontiguoussectionofmemoryissetasidefortheprogramcalledthestack.

5/3/18 Matni,CS64,Sp18 12

Page 13: Function Calling Conventions 1 - GitHub Pages

TheStack•  Thestackpointerisaregister($sp)thatcontainsthetopofthestack.

•  $spcontainsthesmallestaddressxsuchthatanyaddresssmallerthanxisconsideredgarbage,andanyaddressgreaterthanorequaltoxisconsideredvalid.

5/3/18 Matni,CS64,Sp18 13

Page 14: Function Calling Conventions 1 - GitHub Pages

TheStack

•  Inthisexample,$spcontainsthevalue0x00001000.

•  Theshadedregionofthediagramrepresentsvalidpartsofthestack.

5/3/18 Matni,CS64,Sp18 14

Page 15: Function Calling Conventions 1 - GitHub Pages

TheStack•  StackBottom:The

largestvalidaddressofastack.

•  Whenastackisinitialized,$sppointstothestackbottom.

•  StackLimit:Thesmallestvalidaddressofastack.

•  If$spgetssmallerthanthis,thenthere'sastackoverflow

5/3/18 Matni,CS64,Sp18 15

Page 16: Function Calling Conventions 1 - GitHub Pages

5/3/18 Matni,CS64,Sp18 16

STACK(LIFO)PUSHANDPOP

Page 17: Function Calling Conventions 1 - GitHub Pages

StackPushandPop

•  PUSHoneormoreregisters– Subtract4timesthenumber

ofregisterstobepushed onthestackpointer• Why????

– Copytheregisterstothestack(doaswinstruction)Example:addi$sp,$sp,-8#2registerstosavesw$s0,4($sp)sw$s1,0($sp)

5/3/18 Matni,CS64,Sp18 17

Page 18: Function Calling Conventions 1 - GitHub Pages

StackPushandPop

•  POPoneormoreregisters–  Reverseprocessfrompush–  Copythedatafromthestacktotheregisters(doalwinstruction)

– Add4timesthenumberofregisters tobepoppedonthestack.

Example:lw$s0,4($sp)lw$s1,0($sp)addi$sp,$sp,8#2registerstorestore#Note:youcannotdotheaddifirst

5/3/18 Matni,CS64,Sp18 18

Page 19: Function Calling Conventions 1 - GitHub Pages

save_registers.asm•  Theprogramwilllookat2integers(a0,a1)andultimately

returns(a0+a0)+(a1+a1)viaafunctioncall(i.e.jal)

•  Thefunctionwillfirstcreateroomfor2wordsonthestack–  Itwillpush$s0&$s1ontothestack–  We’lluse$s0and$s1

b/cwewantthemtobepreservedacrossacall

•  Itwillcalculatethereturnedvalueandputtheresultin$v0

•  Wewillthenrestoretheoriginalregisters–  Itwillpop2wordsfromthestack&placethemin$s0&$s1

5/3/18 Matni,CS64,Sp18 19

Page 20: Function Calling Conventions 1 - GitHub Pages

.datasolution_text:.asciiz"Solution:"saved_text:.asciiz"Saved:”newline:.asciiz"\n”.text#$a0:firstinteger#$a1:secondinteger#Returns($a0+$a0)+($a1+$a1)in$v0.#Uses$s0and$s1aspartofthisprocessbecausethesearepreservedacrossacall.#add_intsmustthereforesavetheirvaluesinternallyusingthestack.add_ints:#save$s0and$s1onthestack(i.e.push)addi$sp,$sp,-8#makeroomfortwowordssw$s0,4($sp)#notethenon-zerooffsetsw$s1,0($sp)#calculatethevalueadd$s0,$a0,$a0add$s1,$a1,$a1add$v0,$s0,$s1#because$t0isassumedtonotbepreserved,wecanmodifyitdirectly(anditwillnotmatterb/cwe’llpopthesaved$t0outofthestacklater)li$t0,4242#restoretheregistersandreturn(i.e.pop)lw$s1,0($sp)lw$s0,4($sp)addi$sp,$sp,8jr$ra

save_registers.asm

Matni,CS64,Sp18 20

Page 21: Function Calling Conventions 1 - GitHub Pages

main:#We“happen”tohavethevalue1in$t0and2in$s0inthisexample#$t0and$s0areindependentofthefunction…

li$t0,1li$s0,2

#Wewanttocalladd_ints.Becausewewanttosavethevalueof$t0,inthiscase,#andbecauseit'snotpreservedacrossacall(wecan’tassumeitwillbe),itisour#(thecaller’s)responsibilitytostoreitonthestackandrestoreitafterwardsaddi$sp,$sp,-4

sw$t0,0($sp)

#setupthefunctioncallandmakeitli$a0,3li$a1,7jaladd_ints

#restore$t0–also,wecan“assume”that$s0stillhasthevalue2init#becausetheCCsaysthefunctionhastopreserve$sregisterslw$t0,0($sp)addi$sp,$sp,4

#printoutthesolutionpromptmove$t1,$v0li$v0,4la$a0,solution_textsyscall

#printoutthesolutionitselfli$v0,1move$a0,$t1syscall

#printoutanewlineandend(notshown)la$a0,newlineli$v0,4syscall

save_registers.asm

5/3/18 21

#saving$t0isthecaller’sresponsibility,$s0isthecallee’s…

Page 22: Function Calling Conventions 1 - GitHub Pages

WhatisaCallingConvention?•  It’saprotocolabouthowyoucallfunctions

andhowyouaresupposedtoreturnfromthem

•  EveryCPUarchitecturehasone–  Theycandifferfromonearch.toanother

•  3Reasonswhywecare:–  Becauseitmakesprogrammingaloteasierifeveryoneagreestothe

sameconsistent(i.e.reliable)methods–  Makestestingawholeloteasier–  Iwillaskyoutouseitinassignmentsandinexams!

•  Andyouloosemajorpoints(orallofthem)ifyoudon’t…

5/3/18 Matni,CS64,Sp18 22

Page 23: Function Calling Conventions 1 - GitHub Pages

Moreonthe“Why”•  Haveawayofimplementingfunctionsinassembly

–  Butnotaclear,easy-to-usewaytodocomplexfunctions

•  InMIPS,wedonothaveaninherentwayofdoingnested/recursivefunctions–  Example:Savinganarbitraryamountofvariables–  Example:Jumpingbacktoaplaceincoderecursively

•  Thereismorethanonewaytodothings–  Butweoftenneedaconventiontosetworkingparameters–  Helpsfacilitatethingsliketestingandinter-compatibility–  ThisispartlywhyMIPShasdifferentregistersfordifferentuses

5/3/18 Matni,CS64,Sp18 23

Page 24: Function Calling Conventions 1 - GitHub Pages

InstructionstoWatchOutFor•  jal<label>andjar$raalwaysgotogether

•  FunctionargumentshavetobestoredONLYin$a0thru$a3

•  FunctionreturnvalueshavetobestoredONLYin$v0and$v1

•  Iffunctionsneedadditionalregisterswhosevalueswedon’tcareaboutkeepingafterthecall,thentheycanuse$t0thru$t9

•  Whatabout$sregisters?AKAthepreservedregisters–  Hanginthere…willtalkabouttheminafewslides…

5/3/18 Matni,CS64,Sp18 24

Page 25: Function Calling Conventions 1 - GitHub Pages

MIPSC.C.forCS64:Assumptions•  Wewillnotutilize$fpand$gpregs

–  $fp:framepointer–  $gp:globalpointer

•  Assumethatfunctionswillnottakemorethan4argumentsandwillnotreturnmorethan2arguments–  Makesourlivesalittlesimpler…

•  Assumethatallvaluesonthestackarealways32-bits–  Thatis,nooverlylongdatatypesorcomplexdatastructureslike

C-Structs,Classes,etc…

5/3/18 Matni,CS64,Sp18 25

Page 26: Function Calling Conventions 1 - GitHub Pages

MIPSCallStack•  WeknowwhataStackis…•  A“CallStack”isusedforstoringthereturnaddressesofthevarious

functionswhichhavebeencalled

•  Whenyoucallafunction(e.g.jalfuncA),theaddressthatweneedtoreturntoispushedintothecallstack.

…funcAdoesitsthing…then…

…Thefunctionneedstoreturn.

So,theaddressispoppedoffthecallstack

5/3/18 Matni,CS64,Sp18 26

Page 27: Function Calling Conventions 1 - GitHub Pages

MIPSCallStack

5/3/18 Matni,CS64,Sp18 27

TopoftheStackAddressofwheresecondshould

returnto(i.e.after“jalsecond”)

fourth:jr$rathird:push$rajalfourthpop$rajr$rasecond:push$rajalthirdpop$rajr$rafirst:jalsecondli$v0,10syscal

Addressofwheresecondshould

returnto(i.e.after“jalsecond”)

Addressofwherethirdshould

returnto(i.e.after“jalthird”)

voidfirst(){second()return;}

voidsecond(){third();return;}

voidthird(){fourth();return;}

voidforth(){return;}

PUSH

POP

Page 28: Function Calling Conventions 1 - GitHub Pages

5/3/18 Matni,CS64,Sp18 28

fourth:jr$rathird:addiu$sp,$sp,-4sw$ra,0($sp)jalfourthlw$ra,0($sp)addiu$sp,$sp,4jr$rasecond:addiu$sp,$sp,-4sw$ra,0($sp)jalthirdlw$ra,0($sp)addiu$sp,$sp,4jr$rafirst:jalsecondli$v0,10syscall

fourth:jr$rathird:push$rajalfourthpop$rajr$rasecond:push$rajalthirdpop$rajr$rafirst:jalsecondli$v0,10syscal

Whyaddiu?Becausethereisnosuchthingas

anegativememoryaddress

ANDwewanttoavoid

triggeringaprocessor-levelexceptiononoverflow

Page 29: Function Calling Conventions 1 - GitHub Pages

YOURTO-DOs

•  MakesureyoureadthehandoutonMIPSCallingConventions

•  Finishassignment/Lab#4– AssignmentdueonFRIDAY

•  PrepforLab#5onMonday

5/3/18 Matni,CS64,Sp18 29

Page 30: Function Calling Conventions 1 - GitHub Pages

5/3/18 Matni,CS64,Sp18 30