CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer...

38
CS 110 Computer Architecture Lecture 5: More MIPS, MIPS Functions Instructor: Sören Schwertfeger http://shtech.org/courses/ca/ School of Information Science and Technology SIST ShanghaiTech University 1 Slides based on UC Berkley's CS61C

Transcript of CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer...

Page 1: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 2: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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)

Page 3: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 4: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 5: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

HowProgramisStored

5

Memory

Bytes

Program

Data

OneMIPSInstruction=32bits

Page 6: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 7: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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)

Page 8: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 9: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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:…

Page 10: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 11: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

MIPSboard

• Ifanybodyisinterested– Icanbuyoneortwoforexperimentation…

Page 12: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

SixFundamentalStepsinCallingaFunction

1. Putparametersinaplacewherefunctioncanaccessthem

2. Transfercontroltofunction3. Acquire(local)storageresourcesneededfor

function4. Performdesiredtaskofthefunction5. Putresultvalueinaplacewherecallingcode

canaccessitandrestoreanyregistersyouused6. Returncontroltopointoforigin,sincea

functioncanbecalledfromseveralpointsinaprogram

12

Page 13: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

MIPSFunctionCallConventions

• Registersfasterthanmemory,sousethem• $a0–$a3:fourargumentregisterstopassparameters($4- $7)

• $v0,$v1:twovalueregisterstoreturnvalues($2,$3)

• $ra:onereturnaddressregistertoreturntothepointoforigin($31)

13

Page 14: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 15: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 16: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 17: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 18: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

MIPSFunctionCallInstructions• Invokefunction:jumpandlinkinstruction(jal)

(reallyshouldbelaj “linkandjump”)– “link”meansformanaddressorlinkthatpointstocallingsitetoallowfunctiontoreturntoproperaddress

– Jumpstoaddressandsimultaneouslysavestheaddressofthefollowing instructioninregister$ra ($31)

jal FunctionLabel

• Returnfromfunction:jumpregisterinstruction(jr)– Unconditionaljumptoaddressspecifiedinregisterjr $ra

18

Page 19: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 20: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 21: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 22: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

StackBefore,During,AfterFunction

22

• Needtosaveoldvaluesof$s0 and$t0

Contentsof$s0Contentsof$t0

Page 23: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 24: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

Administrivia

• HW1wasdueyesterday– don’tpushafterthedeadlinetoavoidautomaticuseofslipdays(unlessyouhaveto)

• HW2hasbeenposted– duenextMonday• Useofslipdays…– Projectteamnumberofslipdays=min(#a,#b)

24

Page 25: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

WhatIfaFunctionCallsaFunction?RecursiveFunctionCalls?

• Wouldclobbervaluesin$a0 to$a3 and$ra• Whatisthesolution?

25

Page 26: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 27: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

NestedProcedures(2/2)

• Ingeneral,mayneedtosavesomeotherinfoinadditionto$ra.

• WhenaCprogramisrun,thereare3importantmemoryareasallocated:– Static:Variablesdeclaredonceperprogram,ceasetoexistonlyafterexecutioncompletes- e.g.,Cglobals

– Heap:Variablesdeclareddynamicallyviamalloc– Stack:Spacetobeusedbyprocedureduringexecution;thisiswherewecansaveregistervalues

27

Page 28: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

OptimizedFunctionConventionToreduceexpensiveloadsandstoresfromspillingandrestoringregisters,MIPSdividesregistersintotwocategories:

1. Preservedacrossfunctioncall– Callercanrelyonvaluesbeingunchanged– $sp,$gp,$fp,“savedregisters”$s0- $s7

2. Notpreservedacrossfunctioncall– Callercannotrelyonvaluesbeingunchanged– Returnvalueregisters$v0,$v1,Argumentregisters

$a0-$a3,“temporaryregisters”$t0-$t9,$ra28

Page 29: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

Question

• WhichstatementisFALSE?

29

B: jal savesPC+1in$ra

C: Thecallee canusetemporaryregisters($ti)withoutsavingandrestoringthem

D: Thecallercanrelyonsaveregisters($si)withoutfearofcallee changingthem

A:MIPSusesjal toinvokeafunctionandjr toreturnfromafunction

Page 30: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

AllocatingSpaceonStack• Chastwostorageclasses:automaticandstatic– Automatic variablesarelocaltofunctionanddiscardedwhenfunctionexits

– Staticvariablesexistacrossexitsfromandentriestoprocedures

• Usestackforautomatic(local)variablesthatdon’tfitinregisters

• Procedure frameor activationrecord:segmentofstackwithsavedregistersandlocalvariables

• SomeMIPScompilersuseaframepointer($fp)topointtofirstwordofframe

30

Page 31: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

StackBefore,During,AfterCall

31

Page 32: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

UsingtheStack(1/2)

• Sowehavearegister$sp whichalwayspointstothelastusedspaceinthestack.

• Tousestack,wedecrementthispointerbytheamountofspaceweneedandthenfillitwithinfo.

• So,howdowecompilethis?int sumSquare(int x, int y) {

return mult(x,x)+ y;}

32

Page 33: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 34: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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

Page 35: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

WhereistheStackinMemory?• MIPSconvention• Stackstartsinhighmemoryandgrowsdown– Hexadecimal(base16):7ffffffchex

• MIPSprograms(textsegment)inlowend– 00400000hex

• staticdatasegment(constantsandotherstaticvariables)abovetextforstaticvariables– MIPSconventionglobalpointer($gp)pointstostatic

• Heapabovestaticfordatastructuresthatgrowandshrink;growsuptohighaddresses

35

Page 36: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

MIPSMemoryAllocation

36

Page 37: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

RegisterAllocationandNumbering

37

Page 38: CS 110 Computer Architecture Lecture 5 · 2019-03-19 · From last lecture … • Computer “words” and “vocabulary” are called instructions and instruction set respectively

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