inst.eecs.berkeley.edu/~cs61c UCB CS61C : Machine Structurescs61c/sp08/... ·...
Transcript of inst.eecs.berkeley.edu/~cs61c UCB CS61C : Machine Structurescs61c/sp08/... ·...
inst.eecs.berkeley.edu/~cs61c UCBCS61C:MachineStructures
Lecture10–IntroductiontoMIPSDecisionsII
2008‐02‐13
Inwhatmayberegardedasthemostanticipatedgameinalongtime,EAwillbereleasingMaxis’SporeonPCs/Macs/NintendoDS™,andmobilephonesinthefall.Playerswillbeableto“createandevolvelife,establishtribes,buildcivilizations,sculptentireworldsandexploreothers’universes.”
LecturerSOEDanGarcia
www.spore.com
Obamasweeps8thstateinarow;it’sgettingtight!
CS61CL10IntroductiontoMIPS:DecisionsII(2) Garcia,Spring2008©UCB
Review
Memoryisbyte‐addressable,butlwandswaccessonewordatatime.
Apointer(usedbylwandsw)isjustamemoryaddress,sowecanaddtoitorsubtractfromit(usingoffset).
ADecisionallowsustodecidewhattoexecuteatrun‐timeratherthancompile‐time.
CDecisionsaremadeusingconditionalstatementswithinif,while,do while,for.
MIPSDecisionmakinginstructionsaretheconditionalbranches:beqandbne.
NewInstructions: lw, sw, beq, bne, j
CS61CL10IntroductiontoMIPS:DecisionsII(3) Garcia,Spring2008©UCB
Lasttime:Loading,Storingbytes1/2
Inadditiontoworddatatransfers(lw,sw),MIPShasbytedatatransfers: loadbyte:lb storebyte:sb
sameformataslw,sw E.g.,lb $s0, 3($s1)
contentsofmemorylocationwithaddress=sumof“3”+contentsofregisters1iscopiedtothelowbytepositionofregisters0.
CS61CL10IntroductiontoMIPS:DecisionsII(4) Garcia,Spring2008©UCB
x
Loading,Storingbytes2/2
Whatdowithother24bitsinthe32bitregister? lb:signextendstofillupper24bits
byteloaded…iscopiedto“sign‐extend”
Thisbit
xxxx xxxx xxxx xxxx xxxx xxxx zzz zzzz
Normallydon’twanttosignextendchars
MIPSinstructionthatdoesn’tsignextendwhenloadingbytes:
loadbyteunsigned:lbu
CS61CL10IntroductiontoMIPS:DecisionsII(5) Garcia,Spring2008©UCB
OverflowinArithmetic(1/2)
Reminder:Overflowoccurswhenthereisamistakeinarithmeticduetothelimitedprecisionincomputers.
Example(4‐bitunsignednumbers): +15 1111 +3 0011 +18 10010 Butwedon’thaveroomfor5‐bitsolution,sothesolutionwouldbe0010,whichis+2,andwrong.
CS61CL10IntroductiontoMIPS:DecisionsII(6) Garcia,Spring2008©UCB
OverflowinArithmetic(2/2)
Somelanguagesdetectoverflow(Ada),somedon’t(C)
MIPSsolutionis2kindsofarithmeticinstructs: Thesecauseoverflowtobedetected add(add) addimmediate(addi) subtract(sub)
Thesedonotcauseoverflowdetection addunsigned(addu) addimmediateunsigned(addiu) subtractunsigned(subu)
Compilerselectsappropriatearithmetic MIPSCcompilersproduceaddu,addiu,subu
CS61CL10IntroductiontoMIPS:DecisionsII(7) Garcia,Spring2008©UCB
Two“Logic”Instructions
Hereare2morenewinstructions ShiftLeft:sll $s1,$s2,2 #s1=s2<<2
Storein$s1thevaluefrom$s2shifted2bitstotheleft,inserting0’sonright;<<inC
Before:0000 0002hex0000 0000 0000 0000 0000 0000 0000 0010two
After: 0000 0008hex0000 0000 0000 0000 0000 0000 0000 1000two
Whatarithmeticeffectdoesshiftlefthave?
ShiftRight:srlisoppositeshift;>>
CS61CL10IntroductiontoMIPS:DecisionsII(8) Garcia,Spring2008©UCB
LoopsinC/Assembly(1/3)
SimpleloopinC;A[]isanarrayofints do { g = g + A[i]; i = i + j; } while (i != h);
Rewritethisas: Loop: g = g + A[i]; i = i + j; if (i != h) goto Loop;
Usethismapping: g, h, i, j, base of A $s1, $s2, $s3, $s4, $s5
CS61CL10IntroductiontoMIPS:DecisionsII(9) Garcia,Spring2008©UCB
LoopsinC/Assembly(2/3)
FinalcompiledMIPScode: Loop: sll $t1,$s3,2 # $t1= 4*I addu $t1,$t1,$s5 # $t1=addr A+4i lw $t1,0($t1) # $t1=A[i] addu $s1,$s1,$t1 # g=g+A[i] addu $s3,$s3,$s4 # i=i+j bne $s3,$s2,Loop # goto Loop # if i!=h
Originalcode: Loop: g = g + A[i]; i = i + j; if (i != h) goto Loop;
CS61CL10IntroductiontoMIPS:DecisionsII(10) Garcia,Spring2008©UCB
LoopsinC/Assembly(3/3)
TherearethreetypesofloopsinC: while do… while for
Eachcanberewrittenaseitheroftheothertwo,sothemethodusedinthepreviousexamplecanbeappliedtotheseloopsaswell.
KeyConcept:ThoughtherearemultiplewaysofwritingaloopinMIPS,thekeytodecision‐makingisconditionalbranch
CS61CL10IntroductiontoMIPS:DecisionsII(11) Garcia,Spring2008©UCB
Administrivia
Project1dueFriday! (ok,Saturday,buttellyourbrainit’sFriday!)
HowusefulwasFauxExam1? Otheradministrivia?
CS61CL10IntroductiontoMIPS:DecisionsII(12) Garcia,Spring2008©UCB
InequalitiesinMIPS(1/4)
Untilnow,we’veonlytestedequalities(== and!=inC).Generalprogramsneedtotest<and>aswell.
IntroduceMIPSInequalityInstruction: “SetonLessThan” Syntax:slt reg1,reg2,reg3 Meaning: if (reg2 < reg3) reg1 = 1; else reg1 = 0;
“set”means“changeto1”,“reset”means“changeto0”.
reg1 = (reg2 < reg3);
Samething…
CS61CL10IntroductiontoMIPS:DecisionsII(13) Garcia,Spring2008©UCB
InequalitiesinMIPS(2/4)
Howdoweusethis?Compilebyhand:if (g < h) goto Less; #g:$s0,h:$s1
Answer:compiledMIPScode… slt $t0,$s0,$s1 # $t0 = 1 if g<h bne $t0,$0,Less # goto Less # if $t0!=0 # (if (g<h)) Less:
Register$0alwayscontainsthevalue0,sobneandbeqoftenuseitforcomparisonafteransltinstruction.
Asltbnepairmeansif(… < …)goto…
CS61CL10IntroductiontoMIPS:DecisionsII(14) Garcia,Spring2008©UCB
InequalitiesinMIPS(3/4)
Nowwecanimplement<,buthowdoweimplement>,≤and≥?
Wecouldadd3moreinstructions,but: MIPSgoal:SimplerisBetter
Canweimplement≤inoneormoreinstructionsusingjustsltandbranches? Whatabout>? Whatabout≥?
CS61CL10IntroductiontoMIPS:DecisionsII(15) Garcia,Spring2008©UCB
InequalitiesinMIPS(4/4)
# a:$s0,b:$s1 slt $t0,$s0,$s1 # $t0 = 1 if a<b beq $t0,$0,skip # skip if a >= b <stuff> # do if a<b skip:
Twoindependentvariationspossible:Useslt $t0,$s1,$s0 insteadofslt $t0,$s0,$s1
Usebneinsteadofbeq
CS61CL10IntroductiontoMIPS:DecisionsII(16) Garcia,Spring2008©UCB
ImmediatesinInequalities
Thereisalsoanimmediateversionofslttotestagainstconstants:slti Helpfulinforloops
if (g >= 1) goto Loop Loop: . . .
slti $t0,$s0,1 # $t0 = 1 if # $s0<1 (g<1) beq $t0,$0,Loop # goto Loop # if $t0==0 # (if (g>=1))
C
MIPS
An slt beq pair means if(… ≥ …)goto…
CS61CL10IntroductiontoMIPS:DecisionsII(17) Garcia,Spring2008©UCB
Whataboutunsignednumbers?
Alsounsignedinequalityinstructions: sltu,sltiu…whichsetsresultto1or0dependingonunsignedcomparisons
Whatisvalueof$t0,$t1?($s0 = FFFF FFFAhex,$s1 = 0000 FFFAhex)
slt $t0, $s0, $s1 sltu $t1, $s0, $s1
CS61CL10IntroductiontoMIPS:DecisionsII(18) Garcia,Spring2008©UCB
MIPSSignedvs.Unsigned–diffmeanings!
MIPStermsSigned/Unsigned“overloaded”: Do/Don'tsignextend (lb, lbu)
Do/Don'toverflow (add, addi, sub, mult, div) (addu, addiu, subu, multu, divu)
Dosigned/unsignedcompare (slt, slti/sltu, sltiu)
CS61CL10IntroductiontoMIPS:DecisionsII(19) Garcia,Spring2008©UCB
WhatCcodeproperlyfillsintheblankinloopbelow?
PeerInstruction
do {i--;} while(__);
Loop:addi $s0,$s0,-1 # i = i - 1 slti $t0,$s1,2 # $t0 = (j < 2) beq $t0,$0 ,Loop # goto Loop if $t0 == 0 slt $t0,$s1,$s0 # $t0 = (j < i) bne $t0,$0 ,Loop # goto Loop if $t0 != 0
0: j < 2 && j < i 1: j ≥ 2 && j < i 2: j < 2 && j ≥ i 3: j ≥ 2 && j ≥ i 4: j > 2 && j < i 5: j < 2 || j < i 6: j ≥ 2 || j < i 7: j < 2 || j ≥ i 8: j ≥ 2 || j ≥ i 9: j > 2 || j < i
($s0=i, $s1=j)
CS61CL10IntroductiontoMIPS:DecisionsII(20) Garcia,Spring2008©UCB
“Andinconclusion…”
Tohelptheconditionalbranchesmakedecisionsconcerninginequalities,weintroduce:“SetonLessThan”calledslt,slti,sltu,sltiu
Onecanstoreandload(signedandunsigned)bytesaswellaswordswithlb,lbu
Unsignedadd/subdon’tcauseoverflow NewMIPSInstructions: sll, srl, lb, lbu slt, slti, sltu, sltiu addu, addiu, subu
CS61CL10IntroductiontoMIPS:DecisionsII(21) Garcia,Spring2008©UCB
BonusSlides
CS61CL10IntroductiontoMIPS:DecisionsII(22) Garcia,Spring2008©UCB
Example:TheCSwitchStatement(1/3)
Chooseamongfouralternativesdependingonwhetherkhasthevalue0,1,2or3.CompilethisCcode:
switch (k) { case 0: f=i+j; break; /* k=0 */ case 1: f=g+h; break; /* k=1 */ case 2: f=g–h; break; /* k=2 */ case 3: f=i–j; break; /* k=3 */ }
CS61CL10IntroductiontoMIPS:DecisionsII(23) Garcia,Spring2008©UCB
Example:TheCSwitchStatement(2/3)
Thisiscomplicated,sosimplify. Rewriteitasachainofif‐elsestatements,whichwealreadyknowhowtocompile:if(k==0) f=i+j; else if(k==1) f=g+h; else if(k==2) f=g–h; else if(k==3) f=i–j;
Usethismapping: f:$s0, g:$s1, h:$s2, i:$s3, j:$s4, k:$s5
CS61CL10IntroductiontoMIPS:DecisionsII(24) Garcia,Spring2008©UCB
Example:TheCSwitchStatement(3/3)
FinalcompiledMIPScode:bne $s5,$0,L1 # branch k!=0 add $s0,$s3,$s4 #k==0 so f=i+j j Exit # end of case so Exit L1: addi $t0,$s5,-1 # $t0=k-1 bne $t0,$0,L2 # branch k!=1 add $s0,$s1,$s2 #k==1 so f=g+h j Exit # end of case so Exit L2: addi $t0,$s5,-2 # $t0=k-2 bne $t0,$0,L3 # branch k!=2 sub $s0,$s1,$s2 #k==2 so f=g-h j Exit # end of case so Exit L3: addi $t0,$s5,-3 # $t0=k-3 bne $t0,$0,Exit # branch k!=3 sub $s0,$s3,$s4 #k==3 so f=i-j Exit: