cs 61c: great ideas in computer architecture introduction to assembly language...

56
CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language and MIPS Instruction Set Architecture Instructors: Bernhard Boser & Randy H. Katz http://inst.eecs.Berkeley.edu/~cs61c/fa16 9/13/16 Fall 2016 - Lecture #5 1

Upload: others

Post on 25-Feb-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

CS61C:GreatIdeasinComputerArchitectureIntroductiontoAssemblyLanguageand

MIPSInstructionSetArchitectureInstructors:

BernhardBoser &RandyH.Katzhttp://inst.eecs.Berkeley.edu/~cs61c/fa16

9/13/16 Fall2016- Lecture#5 1

Page 2: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Outline

• AssemblyLanguage• MIPSArchitecture• Registersvs.Variables• MIPSInstructions• C-to-MIPSPatterns• AndinConclusion…

9/13/16 Fall2016- Lecture#5 2

Page 3: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Outline

• AssemblyLanguage• MIPSArchitecture• Registersvs.Variables• MIPSInstructions• C-to-MIPSPatterns• AndinConclusion…

9/13/16 Fall2016- Lecture#5 3

Page 4: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

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

LogicCircuitDescription(CircuitSchematicDiagrams)

9/13/16 Fall2016- Lecture#5 4

Page 5: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

5

Page 6: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

AssemblyLanguage• JobofaCPU(CentralProcessingUnit,akaCore):executeinstructions

• Instructions:CPU’sprimitivesoperations– Likeasentence:operations(verbs)appliedtooperands(objects)processedinsequence…

– Withadditionaloperationstochangethesequence• CPUsbelongto“families,”eachimplementingitsownsetofinstructions

• CPU’sparticularsetofinstructionsimplementsanInstructionSetArchitecture (ISA)– Examples:ARM,Intelx86,MIPS,RISC-V,IBM/MotorolaPowerPC(oldMac),IntelIA64,...

69/13/16 Fall2016- Lecture#5

Page 7: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

AssemblyLanguage HighLevelLanguage

79/13/16 Fall2016- Lecture#5

Page 8: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

AssemblyLanguage HighLevelLanguage

89/13/16 Fall2016- Lecture#5

Page 9: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Clicker/PeerInstruction

• Foragivenfunction,whichprogramminglanguagelikelytakesthemostlinesofcode(frommosttoleast)?A:Python>MIPS>CB:C>Python>MIPSC:MIPS>Python>CD:MIPS>C>Python

99/13/16 Fall2016- Lecture#5

Page 10: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

InstructionSetArchitectures

• Earlytrend:addmoreinstructionstonewCPUsforelaborateoperations– VAXarchitecturehadaninstructiontomultiplypolynomials!

• RISCphilosophy(Cocke IBM,Patterson,Hennessy,1980s)– ReducedInstructionSetComputing– Keeptheinstructionsetsmallandsimple,inordertobuildfasthardware

– Letsoftwaredocomplicatedoperationsbycomposingsimplerones

109/13/16 Fall2016- Lecture#5

Page 11: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

MIPSGreenCard

119/13/16 Fall2016- Lecture#5https://inst.eecs.berkeley.edu/~cs61c/resources/MIPS_Green_Sheet.pdf

Page 12: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

InspiredbytheIBM360

“GreenCard”

129/13/16 Fall2016- Lecture#5

Page 13: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Outline

• AssemblyLanguage• MIPSArchitecture• Registersvs.Variables• MIPSInstructions• C-to-MIPSPatterns• AndinConclusion…

9/13/16 Fall2016- Lecture#5 13

Page 14: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

MIPSArchitecture• MIPS:semiconductorcompanythatbuiltoneofthefirstcommercialRISCarchitectures(1984-2013,acquiredbyImaginationTechnologies)

• WhyMIPSinsteadofIntelx86(orARM)?– MIPSissimple,elegant;avoidgettingboggeddowningrittydetails

– MIPS(usedtobe)widelyusedinembeddedapps,e.g.,consumerelectronicsandnetworkrouters;x86littleusedinembeddedandlotsmoreembeddedcomputersthanPCs

– Nevertheless,cs61cmigratingtoARMnextsemester!

149/13/16 Fall2016- Lecture#5

Page 15: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

15

Page 16: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

MIPSDesignsCirca2010

169/13/16 Fall2016- Lecture#5

Page 17: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

AssemblyVariables:Registers

• UnlikeHLLlikeCorJava,assemblydoesnothavevariablesasyouknowandlovethem– Moreprimitive,closerwhatsimplehardwarecandirectlysupport

• Assemblyoperandsareobjectscalledregisters– Limitednumberofspecialplacestoholdvalues,builtdirectlyintothehardware

– Operationscanonlybeperformedonthese!• Benefit:Sinceregistersaredirectlyinhardware,theyareveryfast(fasterthan1ns- lighttravels1footin1ns!!!)

9/13/16 Fall2016- Lecture#5 17

Page 18: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Outline

• AssemblyLanguage• MIPSArchitecture• Registersvs.Variables• MIPSInstructions• C-to-MIPSPatterns• AndinConclusion…

9/13/16 Fall2016- Lecture#5 18

Page 19: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

NumberofMIPSRegisters

• Drawback:Sinceregistersareinhardware,therearealimitednumberofthem– Solution:MIPScodemustbecarefullywrittentotoefficientlyuseregisters

• 32registersinMIPS–Why32?Smallerisfaster,buttoosmallisbad.Goldilocksprinciple(“Thisporridgeistoohot;Thisporridgeistoocold;thisporridgeisjustright”)

• EachMIPSregisteris32bitswide– Groupsof32bitscalledaword inMIPSISA

9/13/16 Fall2016- Lecture#5 19

Page 20: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

NamesofMIPSRegisters

• Registersarenumberedfrom0to31• Eachregistercanbereferredtobynumberorname• Numberreferences:– $0,$1,$2,…$30,$31

• Fornow:– $16- $23è $s0- $s7 (canholdthingslikeCvariables)– $8- $15 è $t0- $t7 (canholdtemporaryvariables)– Laterwillexplainother16registernames

• Ingeneral,usenamestomakeyourcodemorereadable

9/13/16 Fall2016- Lecture#5 20

Page 21: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

C,JavaVariablesvs.Registers

• InC(andmostHLLs):– Variablesdeclaredandgivenatype• Example: int fahr, celsius;

char a, b, c, d, e;

– EachvariablecanONLYrepresentavalueofthetypeitwasdeclared(e.g.,cannotmixandmatchint andchar variables)

• InAssemblyLanguage:– Registershavenotype;– Operation determineshowregistercontentsareinterpreted

9/13/16 Fall2016- Lecture#5 21

Page 22: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Outline

• AssemblyLanguage• MIPSArchitecture• Registersvs.Variables• MIPSInstructions• C-to-MIPSPatterns• AndinConclusion…

9/13/16 Fall2016- Lecture#5 22

Page 23: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

AdditionandSubtractionofIntegers

• AdditioninAssembly– Example: add $s0,$s1,$s2 (inMIPS)– Equivalentto: a=b+c (inC)whereCvariables⇔MIPSregistersare:

a⇔ $s0,b⇔ $s1,c⇔ $s2• SubtractioninAssembly– Example: sub $s3,$s4,$s5 (inMIPS)– Equivalentto: d=e- f (inC)whereCvariables⇔MIPSregistersare:

d⇔ $s3,e⇔ $s4,f⇔ $s5

9/13/16 Fall2016- Lecture#5 23

Page 24: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

AdditionandSubtractionofIntegersExample1

• HowtodothefollowingCstatement?a=b+c+d- e;

• Breakintomultipleinstructionsadd $t0, $s1, $s2 # temp = b + cadd $t0, $t0, $s3 # temp = temp + dsub $s0, $t0, $s4 # a = temp - e

• AsinglelineofCmaybreakupintoseverallinesofMIPS• Noticetheuseoftemporaryregisters– don’twantto

modifythevariableregisters$s• Everythingafterthehashmarkoneachlineisignored

(comments)

9/13/16 Fall2016- Lecture#5 24

Page 25: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Immediates• Immediates arenumericalconstants• Theyappearoftenincode,sotherearespecialinstructionsforthem

• AddImmediate:addi $s0,$s1,-10 (inMIPS)

f=g- 10 (inC)whereMIPSregisters$s0,$s1 areassociatedwithCvariablesf,g

• Syntaxsimilartoadd instruction,exceptthatlastargumentisanumberinsteadofaregister

add $s0,$s1,$zero (inMIPS)f=g (inC)

9/13/16 Fall2016- Lecture#5 25

Page 26: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Overflow in Arithmetic• Reminder: Overflow occurs when there

is an error in arithmetic due to the limited precision in computers

• Example (4-bit unsigned numbers):15 1111

+ 3 + 001118 10010

• But we don’t have room for 5-bit solution, so the solution would be 0010, which is +2, and “wrong”

9/13/16 Fall2016- Lecture#5 26

Page 27: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Overflow handling in MIPS• Somelanguagesdetectoverflow(Ada),

somedon’t(mostCimplementations)• MIPSsolutionistwoalternativearithmeticinstructions:– Causeoverflowtobedetected(e.g.,calculations):

• add(add)• addimmediate(addi)• subtract(sub)

– Don’tcauseoverflowdetection(e.g.,pointerarithmetic)• addunsigned(addu)• addimmediateunsigned(addiu)• subtractunsigned(subu)

• Compilerselectsappropriatearithmetic–MIPSCcompilersproduceaddu,addiu,subu

9/13/16 Fall2016- Lecture#5 27

Page 28: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Break!

9/13/16 Fall2016- Lecture#5 28

Page 29: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Processor

Control

Datapath

DataTransfer:LoadfromandStoreto memory

PC

Registers

Arithmetic&LogicUnit(ALU)

MemoryInput

Output

Bytes

Enable?Read/Write

Address

WriteData=Storetomemory

ReadData=Loadfrommemory

Processor-Memory Interface I/O-MemoryInterfaces

Program

Data

9/13/16 Fall2016- Lecture#5 29

MuchlargerplaceToholdvalues,but

slowerthanregisters!

FastbutlimitedplaceToholdvalues

Page 30: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

0123…

MemoryAddressesareinBytes

• Datatypicallysmallerthan32bits,butrarelysmallerthan8bits(e.g.,chartype)–worksfineifeverythingisamultipleof8bits

• 8bitchunkiscalledabyte(1word=4bytes)

• Memoryaddressesarereallyinbytes,notwords

• Wordaddressesare4bytesapart– Wordaddressissameasaddressofleftmostbyte– mostsignificantbyte(i.e.Big-endianconvention)

9/13/16 Fall2016- Lecture#5 30

Mostsignificantbyteinaword

04812…

15913…

261014…

371115…

3124 2316 158 70Mostsignificantbytegetsthesmallestaddress

Page 31: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Transferfrom MemorytoRegister• Ccode

int A[100];g = h + A[3];

• UsingLoadWord(lw)inMIPS:lw $t0,12($s3) #Tempreg $t0getsA[3]add $s1,$s2,$t0 #g=h+A[3]

Note: $s3 – baseregister(pointer)12 – offsetinbytes

Offsetmustbeaconstantknownatassemblytime

9/13/16 Fall2016- Lecture#5 31

Page 32: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

TransferfromRegisterto Memory• Ccode

int A[100];A[10] = h + A[3];

• UsingStoreWord(sw)inMIPS:lw $t0,12($s3) #Tempreg $t0getsA[3]add $t0,$s2,$t0 #Tempreg $t0getsh+A[3]sw $t0,40($s3) #A[10]=h+A[3]

Note: $s3 – baseregister(pointer)12,40 – offsetsinbytes

$s3+12and$s3+40mustbemultiplesof49/13/16 Fall2016- Lecture#5 32

Page 33: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Loading and Storing Bytes• Inadditiontoworddatatransfers(lw,sw),MIPShasbytedatatransfers:– loadbyte:lb– storebyte:sb

• Sameformataslw,sw• E.g.,lb $s0,3($s1)– contentsofmemorylocationwithaddress=sumof“3”+contentsofregister$s1 iscopiedtothelowbytepositionofregister$s0.

33

byteloaded

zzz zzzzx

…is copied to “sign-extend”This bit

xxxx xxxx xxxx xxxx xxxx xxxx$s0:

9/13/16 Fall2016- Lecture#5

Page 34: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

SpeedofRegistersvs.Memory

• Giventhat– Registers:32words(128Bytes)– Memory:Billionsofbytes(2GBto8GBonlaptop)

• andtheRISCprincipleis…– Smallerisfaster

• Howmuchfasterareregistersthanmemory??• About100-500timesfaster!– intermsoflatencyofoneaccess

349/13/16 Fall2016- Lecture#5

Page 35: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Administrivia• HW#0duetonight!• Lab#1,Project#1published(soon)• GuerrillaReviewsessionstostartsoon,possiblynextweek

– Cpractice

• ThreeweekstoMidterm#1!– Wehavestartedworkingonit.

359/13/16 Fall2016- Lecture#5

Page 36: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Laptops,Revisted

9/13/16 Fall2016- Lecture#5 36

Page 37: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

37

http://financialaid.berkeley.edu/cost-attendance

Page 38: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

LastFiveMinutes,Please!

9/13/16 Fall2016- Lecture#5 38

Page 39: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

RedLetterDay• MedicalTricoder• HandheldCommunicator• Phaser• Anti-matterEngines• Transporter• SpeechRecognition• UniversalTranslator• CloakingDevice• ForceFieldhttps://www.youtube.com/watch?v=b0cDhFVpol8

399/13/16 Fall2016- Lecture#5

Page 40: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

40

Page 41: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Break!

9/13/16 Fall2016- Lecture#5 41

Page 42: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Outline

• AssemblyLanguage• MIPSArchitecture• Registersvs.Variables• MIPSInstructions• C-to-MIPSPatterns• AndinConclusion…

9/13/16 Fall2016- Lecture#5 42

Page 43: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

MIPSLogicalInstructions

Logical operations

Coperators

Java operators

MIPS instructions

Bit-by-bit AND & & andBit-by-bit OR | | orBit-by-bit NOT ~ ~ notShift left << << sllShift right >> >> srl

• Usefultooperateonfieldsofbitswithinaword− e.g.,characterswithinaword(8bits)

• Operationstopack/unpackbitsintowords• Calledlogicaloperations

9/13/16 Fall2016- Lecture#5 43

Page 44: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Logic Shifting• ShiftLeft:sll $s1,$s2,2 #s1=s2<<2

– Storein$s1 thevaluefrom$s2 shifted2bitstotheleft(theyfalloffend),inserting0’s onright;<<inC

Before:00000002hex00000000000000000000000000000010twoAfter: 00000008hex00000000000000000000000000001000two

Whatarithmeticeffectdoesshiftlefthave?

• ShiftRight:srl isoppositeshift;>>

9/13/16 Fall2016- Lecture#5 44

Page 45: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

ArithmeticShifting• Shiftrightarithmeticmovesn bitstotheright(inserthighordersignbitintoemptybits)

• Forexample,ifregister$s0contained11111111111111111111111111100111two=-25ten

• Ifexecutedsra $s0,$s0,4,resultis:11111111111111111111111111111110two=-2ten

• Unfortunately,thisisNOTsameasdividingby2n− Failsforoddnegativenumbers− Carithmeticsemanticsisthatdivisionshouldroundtowards0

9/13/16 Fall2016- Lecture#5 45

Page 46: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

ComputerDecisionMaking• Basedoncomputation,dosomethingdifferent• Inprogramminglanguages:if-statement

• MIPS:if-statementinstructionisbeq register1,register2,L1

means:gotostatementlabeledL1if(valueinregister1)==(valueinregister2)….otherwise,gotonextstatement

• beq standsforbranchifequal• Otherinstruction:bne forbranchifnotequal

9/13/16 Fall2016- Lecture#5 46

Page 47: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

TypesofBranches

• Branch – changeofcontrolflow

• ConditionalBranch – changecontrolflowdependingonoutcomeofcomparison– branchifequal(beq)orbranchifnot equal(bne)

• UnconditionalBranch – alwaysbranch– aMIPSinstructionforthis:jump(j)

9/13/16 Fall2016- Lecture#5 47

Page 48: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Exampleif Statement

• Assumingtranslationsbelow,compileif blockf →$s0 g →$s1 h →$s2i →$s3 j →$s4

if (i == j) bne $s3,$s4,Exit

f = g + h; add $s0,$s1,$s2

Exit:

• Mayneedtonegatebranchcondition9/13/16 Fall2016- Lecture#5 48

Page 49: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Exampleif-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: 9/13/16 Fall2016- Lecture#5 49

Page 50: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Inequalities in MIPS• Untilnow,we’veonlytestedequalities(==and!=inC);Generalprogramsneedtotest<and>aswell.

• IntroduceMIPSInequalityInstruction:“SetonLessThan”Syntax:slt reg1,reg2,reg3Meaning: if(reg2<reg3)

reg1=1;elsereg1=0;

“set”means“changeto1”,“reset”means“changeto0”.

9/13/16 Fall2016- Lecture#5 50

Page 51: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Inequalities in MIPS (cont)• Howdoweusethis?Compilebyhand:

if(g<h)goto Less; #g:$s0,h:$s1

• Answer:compiledMIPScode…#$t0=1if g<h#if$t0!=0goto Less

• Register$zero alwayscontainsthevalue0,sobne andbeqoftenuseitforcomparisonafteranslt instruction

• sltu treatsregistersasunsigned

9/13/16 Fall2016- Lecture#5 51

Page 52: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Inequalities in MIPS (cont)• Howdoweusethis?Compilebyhand:

if(g<h)goto Less; #g:$s0,h:$s1

• Answer:compiledMIPScode…slt $t0,$s0,$s1 #$t0=1if g<hbne $t0,$zero,Less #if$t0!=0goto Less

• Register$zero alwayscontainsthevalue0,sobne andbeqoftenuseitforcomparisonafteranslt instruction

• sltu treatsregistersasunsigned

9/13/16 Fall2016- Lecture#5 52

Page 53: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Immediates in Inequalities• slti an immediate version of slt to

test against constants

Loop: . . .

slti $t0,$s0,1 # $t0 = 1 if# $s0<1

beq $t0,$zero,Loop # goto Loop# if $t0==0# (if ($s0>=1))

9/13/16 Fall2016- Lecture#5 53

Page 54: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

Loops in C/Assembly• SimpleloopinC;A[] isanarrayofints

do { g = g + A[i];i = i + j;

} while (i != h);• Usethismapping: g, h,i,j,&A[0]

$s1,$s2,$s3,$s4,$s5

Loop: # $t1= 4*i# $t1=addr A+4i# $t1=A[i]# g=g+A[i]

# i=i+j# goto Loop

# if i!=h9/13/16 Fall2016- Lecture#5 54

Page 55: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

55

Page 56: CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language …cs61c/fa16/lec/05/L05.pdf · 2016. 9. 14. · Outline • Assembly Language • MIPS Architecture

AndInConclusion…• Computerwordsandvocabularyarecalledinstructionsandinstructionsetrespectively

• MIPSisanexampleRISCinstructionset• Rigidformat:oneoperation,twosourceoperands,onedestination– 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,if-then-elseinCtoMIPSinstructions

9/13/16 Fall2016- Lecture#5 56