2008SpCS61C-L11-ddg-proceduresI-6up

2008SpCS61C-L11-ddg-proceduresI-6up -...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: UCBCS61C:MachineStructures Lecture11IntroductiontoMIPS ProceduresI LecturerSOE DanGarcia inst.eecs.berkeley.edu/~cs61c Review Inordertohelptheconditionalbranchesmake 20080215 Internet2,anonprofitadvancedUS networkingconsortium,isdesigninga "dynamiccircuitnetwork"whichwillprovide hugequantitiesofbandwidthondemand. Keyidea:ratherthaneachrouter determiningthebestconnectionperpacket, theroutewillbedeterminedonceperstream. www.technologyreview.com/Infotech/20277/ decisionsconcerninginequalities,we introduceasingleinstruction:"SetonLess Than"calledslt,slti,sltu,sltiu Onecanstoreandload(signedandunsigned) bytesaswellaswords Unsignedadd/subdon'tcauseoverflow NewMIPSInstructions: sll, srl, lb, sb slt, slti, sltu, sltiu addu, addiu, subu CS61CL11IntroductiontoMIPS:ProceduresI(2) Garcia,Spring2008UCB Cfunctions main() { int i,j,k,m; ... i = mult(j,k); ... m = mult(i,i); ... } /* really dumb mult function */ int mult (int mcand, int product = 0; while (mlier > 0) product = product mlier = mlier -1; return product; } CS61CL11IntroductiontoMIPS:ProceduresI(3) FunctionCallBookkeeping Whatinformationmust compiler/programmer keeptrackof? Registersplayamajorroleinkeeping trackofinformationforfunctioncalls. Registerconventions: Returnaddress Arguments Returnvalue Localvariables int mlier){ { + mcand; } Whatinstructionscan accomplishthis? $ra $a0, $a1, $a2, $a3 $v0, $v1 $s0, $s1, ... , $s7 Thestackisalsoused;morelater. Garcia,Spring2008UCB InstructionSupportforFunctions(1/6) C ... sum(a,b);... /* a,b:$s0,$s1 */ } int sum(int x, int y) { return x+y; } InstructionSupportforFunctions(2/6) C ... sum(a,b);... /* a,b:$s0,$s1 */ } int sum(int x, int y) { return x+y; } address(shownindecimal) 1000 M 1004 InMIPS,allinstructionsare4 I 1008 bytes,andstoredinmemory P 1012 justlikedata.Soherewe 1016 S showtheaddressesofwhere 2000 theprogramsarestored. 2004 CS61CL11IntroductiontoMIPS:ProceduresI(5) Garcia,Spring2008UCB address(shownindecimal) 1000 add $a0,$s0,$zero # x = a M 1004 add $a1,$s1,$zero # y = b I 1008 addi $ra,$zero,1016 #$ra=1016 sum #jump to sum P 1012 j 1016 ... S 2000 sum: add $v0,$a0,$a1 2004 jr $ra # new instruction CS61CL11IntroductiontoMIPS:ProceduresI(6) Garcia,Spring2008UCB InstructionSupportforFunctions(3/6) C ... sum(a,b);... /* a,b:$s0,$s1 */ } int sum(int x, int y) { return x+y; } Question:Whyusejrhere?Whynotusej? Answer:summightbecalledbymanyplaces,sowecan't returntoafixedplace.Thecallingproctosummustbe abletosay"returnhere"somehow. InstructionSupportforFunctions(4/6) Singleinstructiontojumpandsavereturnaddress: jumpandlink(jal) Before: M I P S 1008 addi $ra,$zero,1016 #$ra=1016 1012 j sum #goto sum After: 1008 jal sum # $ra=1012,goto sum Whyhaveajal? Makethecommoncasefast:functioncallsverycommon. Don'thavetoknowwherecodeisinmemorywithjal! 2000 sum: add $v0,$a0,$a1 2004 jr $ra # new instruction CS61CL11IntroductiontoMIPS:ProceduresI(7) Garcia,Spring2008UCB CS61CL11IntroductiontoMIPS:ProceduresI(8) Garcia,Spring2008UCB InstructionSupportforFunctions(5/6) Syntaxforjal(jumpandlink)issameas InstructionSupportforFunctions(6/6) Syntaxforjr(jumpregister): jr register forj(jump): jal label jalshouldreallybecalledlajfor Insteadofprovidingalabeltojumpto,thejr "linkandjump": into$ra Step1(link):Saveaddressofnextinstruction instructionprovidesaregisterwhichcontains anaddresstojumpto. Veryusefulforfunctioncalls: jalstoresreturnaddressinregister($ra) jr $rajumpsbacktothataddress Whynextinstruction?Whynotcurrentone? Step2(jump):Jumptothegivenlabel CS61CL11IntroductiontoMIPS:ProceduresI(9) Garcia,Spring2008UCB CS61CL11IntroductiontoMIPS:ProceduresI(10) Garcia,Spring2008UCB NestedProcedures(1/2) int sumSquare(int x, int y) { return mult(x,x)+ y; } SomethingcalledsumSquare,now sumSquareiscallingmult. Sothere'savaluein$rathatsumSquare wantstojumpbackto,butthiswillbe overwrittenbythecalltomult. NeedtosavesumSquarereturnaddress beforecalltomult. CS61CL11IntroductiontoMIPS:ProceduresI(11) Garcia,Spring2008UCB NestedProcedures(2/2) Ingeneral,mayneedtosavesomeotherinfo inadditionto$ra. WhenaCprogramisrun,thereare3 importantmemoryareasallocated: Static:Variablesdeclaredonceperprogram,cease toexistonlyafterexecutioncompletes.E.g.,C globals Heap:Variablesdeclareddynamicallyviamalloc Stack:Spacetobeusedbyprocedureduring execution;thisiswherewecansaveregistervalues CS61CL11IntroductiontoMIPS:ProceduresI(12) Garcia,Spring2008UCB CmemoryAllocationreview Address UsingtheStack(1/2) Sowehavearegister$spwhichalways Stack $sp stack pointer Spaceforsaved procedureinformation Explicitlycreatedspace, i.e.,malloc() Variablesdeclaredonceper program;e.g.,globals Program Garcia,Spring2008UCB pointstothelastusedspaceinthestack. Tousestack,wedecrementthispointerby Heap Static 0 Code theamountofspaceweneedandthenfillit withinfo. So,howdowecompilethis? int sumSquare(int x, int y) { return mult(x,x)+ y; } CS61CL11IntroductiontoMIPS:ProceduresI(13) CS61CL11IntroductiontoMIPS:ProceduresI(14) Garcia,Spring2008UCB UsingtheStack(2/2) Handcompile int sumSquare(int x, int y) { return mult(x,x)+ y; } sumSquare: addi $sp,$sp,-8 # space on stack "push" sw $ra, 4($sp) # save ret addr sw $a1, 0($sp) # save y add $a1,$a0,$zero # mult(x,x) jal mult # call mult "pop" lw $a1, 0($sp) add $v0,$v0,$a1 lw $ra, 4($sp) addi $sp,$sp,8 jr $ra mult: ... CS61CL11IntroductiontoMIPS:ProceduresI(15) StepsforMakingaProcedureCall 1. Savenecessaryvaluesontostack. 2. Assignargument(s),ifany. 3.jalcall 4. Restorevaluesfromstack. # # # # restore y mult()+y get ret addr restore stack Garcia,Spring2008UCB CS61CL11IntroductiontoMIPS:ProceduresI(16) Garcia,Spring2008UCB RulesforProcedures Calledwithajalinstruction, BasicStructureofaFunction Prologue entry_label: addi $sp,$sp, -framesize sw $ra, framesize-4($sp) # save $ra save other regs if need be returnswithajr $ra Acceptsupto4argumentsin $a0,$a1,$a2and$a3 Returnvalueisalwaysin$v0 (andifnecessaryin$v1) Mustfollowregisterconventions Sowhatarethey? ra Body(callotherfunctions...) ... Epilogue memory restore other regs if need be lw $ra, framesize-4($sp) # restore $ra addi $sp,$sp, framesize jr $ra Garcia,Spring2008UCB CS61CL11IntroductiontoMIPS:ProceduresI(18) Garcia,Spring2008UCB CS61CL11IntroductiontoMIPS:ProceduresI(17) MIPSRegisters Theconstant0 $0 $zero ReservedforAssembler $1 $at ReturnValues $2$3 $v0$v1 Arguments $4$7 $a0$a3 Temporary $8$15 $t0$t7 Saved $16$23 $s0$s7 MoreTemporary $24$25 $t8$t9 UsedbyKernel $2627 $k0$k1 GlobalPointer $28 $gp StackPointer $29 $sp FramePointer $30 $fp ReturnAddress $31 $ra (FromCOD3rdEd.greeninsert) Usenamesforregisterscodeisclearer! CS61CL11IntroductiontoMIPS:ProceduresI(19) Garcia,Spring2008UCB OtherRegisters $at:maybeusedbytheassembleratany time;unsafetouse time;unsafetouse $k0-$k1:maybeusedbytheOSatany $gp,$fp:don'tworryaboutthem Note:Feelfreetoreadupon$gpand$fp inAppendixA,butyoucanwriteperfectly goodMIPScodewithoutthem. CS61CL11IntroductiontoMIPS:ProceduresI(20) Garcia,Spring2008UCB PeerInstruction "AndinConclusion..." Functionscalledwithjal,returnwithjr $ra. Thestackisyourfriend:Useittosaveanything youneed.Justleaveitthewayyoufoundit! int fact(int n){ if(n == 0) return 1; else return(n*fact(n-1));} Instructionsweknowsofar... Arithmetic:add, addi, sub, addu, addiu, subu Memory: lw, sw, lb, sb Decision:beq, bne, slt, slti, sltu, sltiu UnconditionalBranches(Jumps):j, jal, jr WhentranslatingthistoMIPS... A. WeCOULDcopy$a0to$a1(&thennot store$a0or$a1onthestack)tostoren acrossrecursivecalls. B. WeMUSTsave$a0onthestacksinceit getschanged. C. WeMUSTsave$raonthestacksincewe needtoknowwheretoreturnto... CS61CL11IntroductiontoMIPS:ProceduresI(21) 0: 1: 2: 3: 4: 5: 6: 7: ABC FFF FFT FTF FTT TFF TFT TTF TTT Registersweknowsofar Allofthem! Garcia,Spring2008UCB CS61CL11IntroductiontoMIPS:ProceduresI(22) Garcia,Spring2008UCB ...
View Full Document

Ask a homework question - tutors are online