CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer...
Transcript of CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer...
CS110ComputerArchitecture
Lecture5:MoreMIPS,MIPSFunctions
Instructor:SörenSchwertfeger
http://shtech.org/courses/ca/
School of Information Science and Technology SIST
ShanghaiTech University
1Slides based on UC Berkley's CS61C
LevelsofRepresentation/Interpretation
lw $t0,0($2)lw $t1,4($2)sw $t1,0($2)sw $t0,4($2)
HighLevelLanguageProgram(e.g.,C)
AssemblyLanguageProgram(e.g.,MIPS)
MachineLanguageProgram(MIPS)
HardwareArchitectureDescription(e.g.,blockdiagrams)
Compiler
Assembler
MachineInterpretation
temp=v[k];v[k]=v[k+1];v[k+1]=temp;
0000 1001 1100 0110 1010 1111 0101 10001010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111
ArchitectureImplementation
Anythingcanberepresentedasanumber,
i.e.,dataorinstructions
2
LogicCircuitDescription(CircuitSchematicDiagrams)
Fromlastlecture…• Computer“words”and“vocabulary”arecalledinstructions andinstructionsetrespectively
• MIPSisexampleRISCinstructionsetusedinCS61C• Rigidformat:1operation,2sourceoperands,1destination– add,sub,mul,div,and,or,sll,srl,sra– lw,sw,lb,sb tomovedatato/fromregistersfrom/tomemory
– beq, bne, j, slt, slti fordecision/flowcontrol• Simplemappingsfromarithmeticexpressions,arrayaccess,inCtoMIPSinstructions
3
Processor
Control
Datapath
Review:ComponentsofaComputer
4
ProgramCounter
Registers
Arithmetic&LogicUnit(ALU)
MemoryInput
Output
Bytes
Enable?Read/Write
Address
WriteData
ReadData
Processor-Memory Interface I/O-MemoryInterfaces
Program
Data
HowProgramisStored
5
Memory
Bytes
Program
Data
OneMIPSInstruction=32bits
AssemblertoMachineCode(morelaterincourse)
6
foo.S bar.S
Assembler Assembler
foo.o bar.o
Linker lib.o
a.out
Assemblersourcefiles(text)
Machinecodeobjectfiles
Pre-builtobjectfilelibraries
Machinecodeexecutablefile
Assemblerconvertshuman-readableassemblycodetoinstructionbitpatterns
Processor
Control
Datapath
ExecutingaProgram
7
PC
Registers
Arithmetic&LogicUnit(ALU)
Memory
BytesInstructionAddress
ReadInstructionBits
Program
Data
• ThePC(programcounter) isinternalregisterinsideprocessorholdingbyteaddressofnextinstruction tobeexecuted.
• Instructionisfetchedfrommemory, thencontrolunitexecutesinstructionusingdatapath andmemorysystem,andupdatesprogramcounter(defaultisadd+4bytestoPC,tomovetonextsequential instruction)
Reviewif-else Statement
• Assumingtranslationsbelow,compilef →$s0 g →$s1 h →$s2i →$s3 j →$s4
if (i == j) bne $s3,$s4,Else
f = g + h; add $s0,$s1,$s2
else j Exit
f = g – h; Else: sub $s0,$s1,$s2
Exit: 8
Control-flowGraphs:Avisualization
bne $s3,$s4,Else
add $s0,$s1,$s2 j Exit
Else:sub $s0,$s1,$s2Exit:
9
bne $s3,$s4,Else
add$s0,$s1,$s2jExit
Else:sub$s0,$s1,$s2
Exit:…
Question!
Whatisthecodeabove?A: whileloopB: do…whileloopC: forloopD: AorCE: Notaloop
addi $s0,$zero,0Start: slt $t0,$s0,$s1
beq $t0,$zero,Exitsll $t1,$s0,2addu $t1,$t1,$s5lw $t1,0($t1) add $s4,$s4,$t1addi $s0,$s0,1j Start
Exit:
10
MIPSboard
• Ifanybodyisinterested– Icanbuyoneortwoforexperimentation…
SixFundamentalStepsinCallingaFunction
1. Putparametersinaplacewherefunctioncanaccessthem
2. Transfercontroltofunction3. Acquire(local)storageresourcesneededfor
function4. Performdesiredtaskofthefunction5. Putresultvalueinaplacewherecallingcode
canaccessitandrestoreanyregistersyouused6. Returncontroltopointoforigin,sincea
functioncanbecalledfromseveralpointsinaprogram
12
MIPSFunctionCallConventions
• Registersfasterthanmemory,sousethem• $a0–$a3:fourargumentregisterstopassparameters($4- $7)
• $v0,$v1:twovalueregisterstoreturnvalues($2,$3)
• $ra:onereturnaddressregistertoreturntothepointoforigin($31)
13
InstructionSupportforFunctions(1/4)
... sum(a,b);... /* a,b:$s0,$s1 */}int sum(int x, int y) {return x+y;
}address (shown in decimal)1000 1004 1008 1012 1016 …2000 2004
C
MIPS
InMIPS,allinstructionsare4bytes,andstoredinmemoryjustlikedata.Sohereweshowtheaddressesofwheretheprogramsarestored.
14
InstructionSupportforFunctions(2/4)
... sum(a,b);... /* a,b:$s0,$s1 */}int sum(int x, int y) {return x+y;
}address (shown in decimal)1000 add $a0,$s0,$zero # x = a1004 add $a1,$s1,$zero # y = b1008 addi $ra,$zero,1016 # $ra=10161012 j sum # jump to sum1016 … # next instruction…2000 sum: add $v0,$a0,$a12004 jr $ra # new instr. “jump register”
C
MIPS
15
InstructionSupportforFunctions(3/4)
... sum(a,b);... /* a,b:$s0,$s1 */}int sum(int x, int y) {return x+y;
}
2000 sum: add $v0,$a0,$a12004 jr $ra # new instr. “jump register”
• Question:Whyuse jr here?Whynot usej?
• Answer:summightbecalledbymanyplaces,sowecan’treturntoafixedplace.Thecallingproctosummustbeabletosay“returnhere”somehow.
C
MIPS
16
InstructionSupportforFunctions(4/4)• Singleinstructiontojumpandsavereturnaddress:jumpandlink(jal)
• Before:1008 addi $ra,$zero,1016 # $ra=10161012 j sum # goto sum
• After:1008 jal sum # $ra=1012,goto sum
• Whyhaveajal?– Makethecommoncasefast:functioncalls verycommon.– Don’thavetoknowwhere codeis inmemorywithjal!
17
MIPSFunctionCallInstructions• Invokefunction:jumpandlinkinstruction(jal)
(reallyshouldbelaj “linkandjump”)– “link”meansformanaddressorlinkthatpointstocallingsitetoallowfunctiontoreturntoproperaddress
– Jumpstoaddressandsimultaneouslysavestheaddressofthefollowing instructioninregister$ra ($31)
jal FunctionLabel
• Returnfromfunction:jumpregisterinstruction(jr)– Unconditionaljumptoaddressspecifiedinregisterjr $ra
18
NotesonFunctions• Callingprogram(caller)putsparametersintoregisters$a0-$a3 andusesjal X toinvoke(callee)ataddresslabeledX
• Musthaveregisterincomputerwithaddressofcurrentlyexecutinginstruction– InsteadofInstructionAddressRegister (bettername),historicallycalledProgramCounter (PC)
– It’saprogram’scounter;itdoesn’tcountprograms!
• Whatvaluedoesjal X placeinto$ra?????• jr $ra putsaddressinside$ra backintoPC
19
WhereAreOldRegisterValuesSavedtoRestoreThemAfterFunctionCall?• Needaplacetosaveoldvaluesbeforecallfunction,restorethemwhenreturn,anddelete
• Idealisstack:last-in-first-outqueue(e.g.,stackofplates)– Push:placingdataontostack– Pop:removingdatafromstack
• Stackinmemory,soneedregistertopointtoit• $sp isthestackpointerinMIPS($29)• Conventionisgrowfromhightolowaddresses– Push decrements$sp,Pop increments$sp
20
Exampleint Leaf(int g, int h, int i, int j)
{int f;f = (g + h) – (i + j);return f;
}• Parametervariablesg,h,i,andj inargumentregisters$a0,$a1,$a2,and$a3,andf in$s0
• Assumeneedonetemporaryregister$t0
21
StackBefore,During,AfterFunction
22
• Needtosaveoldvaluesof$s0 and$t0
Contentsof$s0Contentsof$t0
MIPSCodeforLeaf()
23
Leaf: addi $sp,$sp,-8 # adjuststackfor2itemssw $t0, 4($sp) # save$t0foruseafterwardssw $s0, 0($sp) # save$s0foruseafterwards
add $s0,$a0,$a1 # f=g+hadd $t0,$a2,$a3 # t0=i +jsub $v0,$s0,$t0 # returnvalue(g+h)– (i +j)
lw $s0, 0($sp) # restoreregister$s0forcallerlw $t0, 4($sp) # restoreregister$t0forcalleraddi $sp,$sp,8 # adjuststacktodelete2itemsjr $ra # jumpbacktocallingroutine
Administrivia
• HW1wasdueyesterday– don’tpushafterthedeadlinetoavoidautomaticuseofslipdays(unlessyouhaveto)
• HW2hasbeenposted– duenextMonday• Useofslipdays…– Projectteamnumberofslipdays=min(#a,#b)
24
WhatIfaFunctionCallsaFunction?RecursiveFunctionCalls?
• Wouldclobbervaluesin$a0 to$a3 and$ra• Whatisthesolution?
25
NestedProcedures(1/2)
int sumSquare(int x, int y) {return mult(x,x)+ y;
}• SomethingcalledsumSquare,nowsumSquare iscallingmult
• Sothere’savaluein$ra thatsumSquarewantstojumpbackto,butthiswillbeoverwrittenbythecalltomult
26
NeedtosavesumSquare returnaddressbeforecalltomult
NestedProcedures(2/2)
• Ingeneral,mayneedtosavesomeotherinfoinadditionto$ra.
• WhenaCprogramisrun,thereare3importantmemoryareasallocated:– Static:Variablesdeclaredonceperprogram,ceasetoexistonlyafterexecutioncompletes- e.g.,Cglobals
– Heap:Variablesdeclareddynamicallyviamalloc– Stack:Spacetobeusedbyprocedureduringexecution;thisiswherewecansaveregistervalues
27
OptimizedFunctionConventionToreduceexpensiveloadsandstoresfromspillingandrestoringregisters,MIPSdividesregistersintotwocategories:
1. Preservedacrossfunctioncall– Callercanrelyonvaluesbeingunchanged– $sp,$gp,$fp,“savedregisters”$s0- $s7
2. Notpreservedacrossfunctioncall– Callercannotrelyonvaluesbeingunchanged– Returnvalueregisters$v0,$v1,Argumentregisters
$a0-$a3,“temporaryregisters”$t0-$t9,$ra28
Question
• WhichstatementisFALSE?
29
B: jal savesPC+1in$ra
C: Thecallee canusetemporaryregisters($ti)withoutsavingandrestoringthem
D: Thecallercanrelyonsaveregisters($si)withoutfearofcallee changingthem
A:MIPSusesjal toinvokeafunctionandjr toreturnfromafunction
AllocatingSpaceonStack• Chastwostorageclasses:automaticandstatic– Automatic variablesarelocaltofunctionanddiscardedwhenfunctionexits
– Staticvariablesexistacrossexitsfromandentriestoprocedures
• Usestackforautomatic(local)variablesthatdon’tfitinregisters
• Procedure frameor activationrecord:segmentofstackwithsavedregistersandlocalvariables
• SomeMIPScompilersuseaframepointer($fp)topointtofirstwordofframe
30
StackBefore,During,AfterCall
31
UsingtheStack(1/2)
• Sowehavearegister$sp whichalwayspointstothelastusedspaceinthestack.
• Tousestack,wedecrementthispointerbytheamountofspaceweneedandthenfillitwithinfo.
• So,howdowecompilethis?int sumSquare(int x, int y) {
return mult(x,x)+ y;}
32
UsingtheStack(2/2)
• Hand-compilesumSquare:
addi $sp,$sp,-8 # space on stacksw $ra, 4($sp) # save ret addrsw $a1, 0($sp) # save yadd $a1,$a0,$zero # mult(x,x)jal mult # call multlw $a1, 0($sp) # restore yadd $v0,$v0,$a1 # mult()+ylw $ra, 4($sp) # get ret addraddi $sp,$sp,8 # restore stackjr $ra
mult: ...
int sumSquare(int x, int y) {return mult(x,x)+ y; }
“push”
“pop”
33
BasicStructureofaFunction
entry_label: addi $sp,$sp, -framesizesw $ra, framesize-4($sp) # save $rasave other regs if need be
...
restore other regs if need belw $ra, framesize-4($sp) # restore $raaddi $sp,$sp, framesizejr $ra
Epilogue
Prologue
Body (call other functions…)
ra
memory
34
WhereistheStackinMemory?• MIPSconvention• Stackstartsinhighmemoryandgrowsdown– Hexadecimal(base16):7ffffffchex
• MIPSprograms(textsegment)inlowend– 00400000hex
• staticdatasegment(constantsandotherstaticvariables)abovetextforstaticvariables– MIPSconventionglobalpointer($gp)pointstostatic
• Heapabovestaticfordatastructuresthatgrowandshrink;growsuptohighaddresses
35
MIPSMemoryAllocation
36
RegisterAllocationandNumbering
37
AndinConclusion…
• Functionscalledwithjal,returnwithjr $ra.• Thestackisyourfriend:Useittosaveanythingyouneed.Just leaveitthewayyoufoundit!
• Instructionsweknowsofar…Arithmetic:add, addi, sub, addu, addiu, subuMemory: lw, sw, lb, sb
Decision: beq, bne, slt, slti, sltu, sltiuUnconditionalBranches(Jumps):j, jal, jr
• Registersweknowsofar– Allofthem!– $a0-$a3forfunctionarguments,$v0-$v1forreturnvalues– $sp,stackpointer,$fp framepointer,$ra returnaddress
38