CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language...

Post on 25-Feb-2021

5 views 0 download

Transcript of CS 61C: Great Ideas in Computer Architecture Introduction to Assembly Language...

CS61C:GreatIdeasinComputerArchitectureIntroductiontoAssemblyLanguageand

MIPSInstructionSetArchitectureInstructors:

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

9/13/16 Fall2016- Lecture#5 1

Outline

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

9/13/16 Fall2016- Lecture#5 2

Outline

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

9/13/16 Fall2016- Lecture#5 3

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

5

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

AssemblyLanguage HighLevelLanguage

79/13/16 Fall2016- Lecture#5

AssemblyLanguage HighLevelLanguage

89/13/16 Fall2016- Lecture#5

Clicker/PeerInstruction

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

99/13/16 Fall2016- Lecture#5

InstructionSetArchitectures

• Earlytrend:addmoreinstructionstonewCPUsforelaborateoperations– VAXarchitecturehadaninstructiontomultiplypolynomials!

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

– Letsoftwaredocomplicatedoperationsbycomposingsimplerones

109/13/16 Fall2016- Lecture#5

MIPSGreenCard

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

InspiredbytheIBM360

“GreenCard”

129/13/16 Fall2016- Lecture#5

Outline

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

9/13/16 Fall2016- Lecture#5 13

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

15

MIPSDesignsCirca2010

169/13/16 Fall2016- Lecture#5

AssemblyVariables:Registers

• UnlikeHLLlikeCorJava,assemblydoesnothavevariablesasyouknowandlovethem– Moreprimitive,closerwhatsimplehardwarecandirectlysupport

• Assemblyoperandsareobjectscalledregisters– Limitednumberofspecialplacestoholdvalues,builtdirectlyintothehardware

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

9/13/16 Fall2016- Lecture#5 17

Outline

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

9/13/16 Fall2016- Lecture#5 18

NumberofMIPSRegisters

• Drawback:Sinceregistersareinhardware,therearealimitednumberofthem– Solution:MIPScodemustbecarefullywrittentotoefficientlyuseregisters

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

• EachMIPSregisteris32bitswide– Groupsof32bitscalledaword inMIPSISA

9/13/16 Fall2016- Lecture#5 19

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

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

Outline

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

9/13/16 Fall2016- Lecture#5 22

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

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

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

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

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

Break!

9/13/16 Fall2016- Lecture#5 28

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

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

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

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

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

SpeedofRegistersvs.Memory

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

• andtheRISCprincipleis…– Smallerisfaster

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

349/13/16 Fall2016- Lecture#5

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

– Cpractice

• ThreeweekstoMidterm#1!– Wehavestartedworkingonit.

359/13/16 Fall2016- Lecture#5

Laptops,Revisted

9/13/16 Fall2016- Lecture#5 36

37

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

LastFiveMinutes,Please!

9/13/16 Fall2016- Lecture#5 38

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

399/13/16 Fall2016- Lecture#5

40

Break!

9/13/16 Fall2016- Lecture#5 41

Outline

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

9/13/16 Fall2016- Lecture#5 42

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

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

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

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

TypesofBranches

• Branch – changeofcontrolflow

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

• UnconditionalBranch – alwaysbranch– aMIPSinstructionforthis:jump(j)

9/13/16 Fall2016- Lecture#5 47

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

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

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

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

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

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

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

55

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