CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since...

56
CS 110 Computer Architecture RISC-V Instruction Formats 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 - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since...

Page 1: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

CS110ComputerArchitecture

RISC-VInstructionFormats

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 - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

Stack

• Stackframeincludes:• Return“instruction”address• Parameters• Spaceforotherlocalvariables

• Stackframescontiguousblocksofmemory;stackpointertellswherebottomofstackframeis

• Whenprocedureends,stackframeistossedoffthestack;freesmemoryforfuturestackframes

frame

frame

frame

frame

$sp

0xBFFFFFF0

Page 3: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

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

3

Page 4: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

WhereistheStackinMemory?• RV32convention(RV64andRV128havedifferentmemorylayouts)• Stackstartsinhighmemoryandgrowsdown

– Hexadecimal:bfff_fff0hex

– Stackmustbealignedon16-byteboundary(nottrueinpreviousexamples)

• RV32programs(textsegment)inlowend– 0001_0000hex

• staticdatasegment(constantsandotherstaticvariables)abovetextforstaticvariables– RISC-Vconventionglobalpointer(gp)pointstostatic– RV32gp =1000_0000hex

• Heapabovestaticfordatastructuresthatgrowandshrink;growsuptohighaddresses

Page 5: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

RV32MemoryAllocation

Page 6: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

RISC-V ISA so far…• Registersweknowsofar(Allofthem!)

– a0-a7forfunctionarguments,a0-a1forreturnvalues– sp,stackpointer,ra returnaddress– s0-s11savedregisters– t0-t6temporaries– zero

• Instructionsweknow:– Arithmetic:add,addi,sub– Logical:sll,srl,sla,slli,srli,slai,and,or,xor,andi,ori,xori– Decision:beq,bne,blt,bge– Unconditionalbranches(jumps):j,jr– Functionscalledwithjal,returnwithjr ra.

• Thestackisyourfriend:Useittosaveanythingyouneed.Justleaveitthewayyoufoundit!

Page 7: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

LevelsofRepresentation/Interpretation

lw xt0,0(x2)lw xt1,4(x2)sw xt1,0(x2)sw xt0,4(x2)

HighLevelLanguageProgram(e.g.,C)

AssemblyLanguageProgram(e.g.,RISC-V)

MachineLanguageProgram(RISC-V)

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

7

LogicCircuitDescription(CircuitSchematicDiagrams)

Page 8: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

BigIdea:Stored-Program

Computer

– Instructionsarerepresentedasbitpatterns- canthinkoftheseasnumbers

– Therefore,entireprogramscanbestoredinmemorytobereadorwrittenjustlikedata

– Canreprogramquickly(seconds),don’thavetorewirecomputer(days)

– Knownasthe“vonNeumann”computersafterwidelydistributedtechreportonEDVACproject

• Wrote-updiscussionsofEckertandMauchly• AnticipatedearlierbyTuringandZuse

FirstDraftofaReportontheEDVACby

JohnvonNeumannContractNo.W–670–ORD–4926

BetweentheUnitedStatesArmyOrdnanceDepartmentandthe

UniversityofPennsylvaniaMooreSchoolofElectricalEngineering

UniversityofPennsylvania

June 30,1945

8

Page 9: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

Consequence#1:EverythingAddressed

• Sinceallinstructionsanddataarestoredinmemory,everythinghasamemoryaddress:instructions,datawords– bothbranchesandjumpsusethese

• Cpointersarejustmemoryaddresses:theycanpointtoanythinginmemory– Unconstraineduseofaddressescanleadtonastybugs;upto

youinC;limitedinJavabylanguagedesign• Oneregisterkeepsaddressofinstructionbeingexecuted:

“ProgramCounter”(PC)– Basicallyapointertomemory:IntelcallsitInstructionPointer(a

bettername)

9

Page 10: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

Consequence#2:BinaryCompatibility

• Programsaredistributedinbinaryform– Programsboundtospecificinstructionset– DifferentversionforARM(phone)andPCs

• Newmachineswanttorunoldprograms(“binaries”)aswellasprogramscompiledtonewinstructions

• Leadsto“backward-compatible”instructionsetevolvingovertime

• SelectionofIntel8086in1981for1st IBMPCismajorreasonlatestPCsstilluse80x86instructionset;couldstillrunprogramfrom1981PCtoday

10

Page 11: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

InstructionsasNumbers(1/2)

• Currentlymostdataweworkwithisinwords(32-bitchunks):– Eachregisterisaword.– lw andsw bothaccessmemoryonewordatatime.

• Sohowdowerepresentinstructions?– Remember:Computeronlyunderstands1sand0s,so“add x10,x11,x0”ismeaningless.

– RISC-Vseekssimplicity:sincedataisinwords,makeinstructionsbefixed-size32-bitwords,too

• Same32-bitinstructionsusedforRV32,RV64,RV12811

Page 12: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

InstructionsasNumbers(2/2)• Onewordis32bits,sodivideinstructionwordinto“fields”.

• Eachfieldtellsprocessorsomethingaboutinstruction.• Wecoulddefinedifferentfieldsforeachinstruction,butRISC-Vseekssimplicity,sodefine6basictypesofinstructionformats:

– R-formatforregister-registerarithmeticoperations– I-formatforregister-immediatearithmeticoperationsandloads– S-formatforstores– B-formatforbranches(minorvariantofS-format,calledSBbefore)– U-formatfor20-bitupperimmediateinstructions– J-formatforjumps(minorvariantofU-format,calledUJbefore)

12

Page 13: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

R-FormatInstructionLayout

• 32-bitinstructionworddividedintosixfieldsofvaryingnumbersofbitseach:7+5+5+3+5+7=32

• Examples– opcode isa7-bitfieldthatlivesinbits6-0oftheinstruction– rs2isa5-bitfieldthatlivesinbits24-20oftheinstruction

Field’sbitpositions

NumberofbitsinfieldNameoffield

7 5 5 3 75

31 25 20 15 71224 19 14 11 6 0funct7 rs2 rs1 funct3 rd opcode

Page 14: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

R-FormatInstructionsopcode/funct fields

– opcode:partiallyspecifieswhatinstructionitis• Note:Thisfieldisequalto0110011two forallR-Formatregister-registerarithmeticinstructions

– funct7+funct3:combinedwithopcode,thesetwofieldsdescribewhatoperationtoperform

• Question:Youhavebeenprofessingsimplicity,sowhyaren’topcodeandfunct7 andfunct3 asingle17-bitfield?

– We’llanswerthislater

7 5 5 3 75

31 25 20 15 71224 19 14 11 6 0funct7 rs2 rs1 funct3 rd opcode

Page 15: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

R-FormatInstructionsregisterspecifiers

– rs1 (SourceRegister#1):specifiesregistercontainingfirstoperand

– rs2 : specifiessecondregisteroperand– rd (DestinationRegister):specifiesregisterwhichwillreceiveresultofcomputation

– Eachregisterfieldholdsa5-bitunsignedinteger(0-31)correspondingtoaregisternumber(x0-x31)

7 5 5 3 75

31 25 20 15 71224 19 14 11 6 0funct7 rs2 rs1 funct3 rd opcode

Page 16: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

R-FormatExample

• RISC-VAssemblyInstruction:add x18,x19,x10

0000000 01010 10011 000 10010 0110011

Reg-Reg OPrd=18addadd rs2=10 rs1=19

7 5 5 3 75

31 25 20 15 71224 19 14 11 6 0funct7 rs2 rs1 funct3 rd opcode

Page 17: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

AllRV32R-formatinstructions

Differentencodinginfunct7+funct3selectsdifferentoperations

0000000 rs2 rs1 000 rd 0110011

0100000 rs2 rs1 000 rd 0110011

0000000 rs2 rs1 001 rd 0110011

addsubsll

0000000 rs2 rs1 010 rd 0110011 slt0000000 rs2 rs1 011 rd 0110011 sltu0000000 rs2 rs1 100 rd 0110011 xor0000000 rs2 rs1 101 rd 0110011 srl0100000 rs2 rs1 101 rd 0110011 sra0000000 rs2 rs1 110 rd 01100110000000 rs2 rs1 111 rd 0110011

orand

Page 18: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

PeerInstruction• Whatiscorrectencodingofaddx4,x3,x2?A:40218233hexB:002182b3hexC:402182b3hexD:00218233hexE:00218234hex

0000000 rs2 rs1 000 rd 0110011

0100000 rs2 rs1 000 rd 0110011

addsub

0000000 rs2 rs1 100 rd 0110011 xor0000000 rs2 rs1 110 rd 01100110000000 rs2 rs1 111 rd 0110011

orand

31 25 20 15 71224 19 14 11 6 0

Page 19: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

I-FormatInstructions

• Whataboutinstructionswithimmediates?– 5-bitfieldonlyrepresentsnumbersuptothevalue31:immediates maybemuchlargerthanthis

– Ideally,RISC-Vwouldhaveonlyoneinstructionformat(forsimplicity):unfortunately,weneedtocompromise

• DefinenewinstructionformatthatismostlyconsistentwithR-format– Noticeifinstructionhasimmediate,thenusesatmost2registers(onesource,onedestination)

Page 20: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

I-FormatInstructionLayout

• OnlyonefieldisdifferentfromR-format,rs2andfunct7replacedby12-bitsignedimmediate,imm[11:0]

• Remainingfields(rs1,funct3,rd,opcode)sameasbefore• imm[11:0]canholdvaluesinrange[-2048ten ,+2047ten]• Immediateisalwayssign-extendedto32-bitsbeforeuse

inanarithmeticoperation• We’lllaterseehowtohandleimmediates >12bits

7 5 5 3 75

31 25 20 15 71224 19 14 11 6 0funct7 rs2 rs1 funct3 rd opcodeImm[11:0]

12

Page 21: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

I-FormatExample

• RISC-VAssemblyInstruction:addi x15,x1,-50

111111001110 00001 000 01111 0010011

OP-Immrd=15addimm=-50 rs1=1

5 3 75

31 20 15 71219 14 11 6 0rs1 funct3 rd opcodeimm[11:0]

12

Page 22: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

AllRV32I-formatArithmeticInstructions

“Shift-by-immediate”instructionsonlyuselower5bitsoftheimmediatevalueforshiftamount(canonlyshiftby0-31bitpositions)

Oneofthehigher-orderimmediatebitsisusedtodistinguish“shiftrightlogical”(SRLI)from“shiftrightarithmetic”(SRAI)

imm[11:0] rs1 000 rd 0010011

imm[11:0] rs1 010 rd 0010011

imm[11:0] rs1 011 rd 0010011

addisltisltiu

imm[11:0] rs1 100 rd 0010011 xoriimm[11:0] rs1 110 rd 0010011 oriimm[11:0] rs1 111 rd 0010011 andi

0000000 shamt rs1 001 rd 0010011 slli0000000 shamt rs1 101 rd 0010011 srli0100000 shamt rs1 101 rd 0010011 srai

Page 23: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

LoadInstructionsarealsoI-Type

• The12-bitsignedimmediateisaddedtothebaseaddressinregisterrs1 toformthememoryaddress– Thisisverysimilartotheadd-immediateoperationbutusedtocreate

addressnottocreatefinalresult

• Thevalueloadedfrommemoryisstoredinregisterrd

5 3 75

31 20 15 71219 14 11 6 0rs1 funct3 rd opcodeimm[11:0]

12offset[11:0] base width dest LOAD

Page 24: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

I-FormatLoadExample• RISC-VAssemblyInstruction:

lw x14, 8(x2)

000000001000 00010 010 01110 0000011

LOADrd=14lwimm=+8 rs1=2

(load word)

5 3 75

31 20 15 71219 14 11 6 0rs1 funct3 rd opcodeimm[11:0]

12offset[11:0] base width dest LOAD

Page 25: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

AllRV32LoadInstructions

• LBUis“loadunsignedbyte”• LHis“loadhalfword”,whichloads16bits(2bytes)andsign-extendstofilldestination32-

bitregister• LHUis“loadunsignedhalfword”,whichzero-extends16bitstofilldestination32-bit

register• ThereisnoLWUinRV32,becausethereisnosign/zeroextensionneededwhencopying

32bitsfromamemorylocationintoa32-bitregister

funct3fieldencodessizeand‘signedness’ofloaddata

imm[11:0] rs1 000 rd 0000011

imm[11:0] rs1 010 rd 0000011

imm[11:0] rs1 011 rd 0000011

lblhlw

imm[11:0] rs1 100 rd 0000011 lbuimm[11:0] rs1 110 rd 0000011 lhu

Page 26: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

S-FormatUsedforStores

• Storeneedstoreadtworegisters,rs1forbasememoryaddress,andrs2fordatatobestored,aswellimmediateoffset!

• Can’thavebothrs2andimmediateinsameplaceasotherinstructions!

• Notethatstoresdon’twriteavaluetotheregisterfile,nord!• RISC-Vdesigndecisionismovelow5bitsofimmediatetowhererd

fieldwasinotherinstructions– keeprs1/rs2fieldsinsameplace• registernamesmorecriticalthanimmediatebitsinhardwaredesign

7 5 5 3 75

31 25 20 15 71224 19 14 11 6 0Imm[11:5] rs2 rs1 funct3 imm[4:0] opcode

offset[11:5] base widthsrc STOREoffset[4:0]

Page 27: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

S-FormatExample• RISC-VAssemblyInstruction:

sw x14, 8(x2)

0000000 01110 00010 010 01000 0100011

STOREoffset[4:0]=8

SWoffset[11:5]=0

rs2=14 rs1=2

combined12-bitoffset=80000000 01000

7 5 5 3 75

31 25 20 15 71224 19 14 11 6 0Imm[11:5] rs2 rs1 funct3 imm[4:0] opcode

offset[11:5] base widthsrc STOREoffset[4:0]

Page 28: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

AllRV32StoreInstructions

Imm[11:5] rs2 rs1 000 imm[4:0] 0100011 sbshsw

Imm[11:5] rs2 rs1 001 imm[4:0] 0100011Imm[11:5] rs2 rs1 010 imm[4:0] 0100011

• Storebyte,halfword,wordwidth

Page 29: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

RISC-VConditionalBranches

• E.g.,BEQ x1, x2, Label• Branchesreadtworegistersbutdon’twritearegister(similartostores)

• Howtoencodelabel,i.e.,wheretobranchto?

Page 30: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

BranchingInstructionUsage

• Branchestypicallyusedforloops(if-else,while,for)– Loopsaregenerallysmall(<50instructions)– Functioncallsandunconditionaljumpshandledwithjumpinstructions(J-Format)

• Recall: Instructionsstoredinalocalizedareaofmemory(Code/Text)– Largestbranchdistancelimitedbysizeofcode– Addressofcurrentinstructionstoredintheprogramcounter(PC)

Page 31: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

PC-RelativeAddressing

• PC-RelativeAddressing: Usetheimmediatefieldasatwo’s-complementoffsettoPC– BranchesgenerallychangethePCbyasmallamount– Canspecify± 211 ‘unit’addressesfromthePC– (Wewillseeinabitthatwecanencode12-bitoffsetsasimmediates)

• WhynotusebyteasaunitofoffsetfromPC?– Becauseinstructionsare32-bits(4-bytes)– Wedon’tbranchintomiddleofinstruction

Page 32: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

ScalingBranchOffset

• Oneidea:Toimprovethereachofasinglebranchinstruction,multiplytheoffsetbyfourbytesbeforeaddingtoPC

• Thiswouldallowonebranchinstructiontoreach± 211× 32-bitinstructionseithersideofPC– Fourtimesgreaterreachthanusingbyteoffset

Page 33: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

BranchCalculation

• Ifwedon’t takethebranch:PC = PC + 4 (i.e.,nextinstruction)

• Ifwedo takethebranch:PC = PC + immediate*4

• Observations:– immediate isnumberofinstructionstojump(remember,specifieswords)eitherforward(+)orbackwards(–)

Page 34: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

RISC-VFeature,n×16-bitinstructions

• ExtensionstoRISC-VbaseISAsupport16-bitcompressedinstructionsandalsovariable-lengthinstructionsthataremultiplesof16-bitsinlength

• Toenablethis,RISC-Vscalesthebranchoffsetby2bytesevenwhenthereareno16-bitinstructions

• Reducesbranchreachbyhalfandmeansthat½ofpossibletargetswillbeerrorsonRISC-Vprocessorsthatonlysupport32-bitinstructions(asusedinthisclass)

• RISC-Vconditionalbranchescanonlyreach± 210 ×32-bitinstructionsoneithersideofPC

Page 35: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

RISC-VB-FormatforBranches

• B-formatismostlysameasS-Format,withtworegistersources(rs1/rs2)anda12-bitimmediateimm[12:1]

• Butnowimmediaterepresentsvalues-4096to+4094in2-byteincrements

• The12immediatebitsencodeeven 13-bitsignedbyteoffsets(lowestbitofoffsetisalwayszero,sononeedtostoreit)

1 6 5 3 74

31 30 24 15 71225 20 14 11 6 0imm[12] rs2 rs1 funct3 imm[4:1] opcodeimm[10:5] imm[11]

19 8

5 1

BRANCHoffset[12|10:5] rs1 funct3rs2 offset[4:1|11]

Page 36: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

BranchExample,DetermineOffset

• RISC-VCode:Loop: beq x19,x10,End

add x18,x18,x10addi x19,x19,-1j Loop

End: # target instruction

• Branchoffset=• (Branchwithoffsetof0,branchestoitself)

4×32-bitinstructions=16bytes

1234

Countinstructionsfrombranch

Page 37: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

BranchExample,DetermineOffset

• RISC-VCode:Loop: beq x19,x10,End

add x18,x18,x10addi x19,x19,-1j Loop

End: # target instruction

1234

Countinstructionsfrombranch

??????? 01010 10011 000 ????? 1100011

BRANCHimmBEQimm rs2=10 rs1=19

Page 38: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

BranchExample,EncodeOffset

• RISC-VCode:Loop: beq x19,x10,End

add x18,x18,x10addi x19,x19,-1j Loop

End: # target instruction

??????? 01010 10011 000 ????? 1100011

BRANCHimmBEQimm rs2=10 rs1=19

offset=16bytes=8x2bytes

Page 39: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

RISC-VImmediateEncodingInstructionencodings,inst[31:0]

32-bitimmediates produced,imm[31:0]

31 25 20 15 71224 19 14 11 6 0funct7 rs2 rs1 funct3 rd opcode

30 8

rs1 funct3 rd opcodeimm[11:0]

imm[11:5] rs2 rs1 funct3 imm[4:0] opcode

R-typeI-typeS-type

imm[12|10:5] rs2 rs1 funct3 imm[4:1|11] opcode B-type

Page 40: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

RISC-VImmediateEncodingInstructionencodings,inst[31:0]

32-bitimmediates produced,imm[31:0]

Onlybit7ofinstructionchangesroleinimmediatebetweenSandB

Upperbitssign-extendedfrominst[31]always

31 25 20 15 71224 19 14 11 6 0funct7 rs2 rs1 funct3 rd opcode

31 25 12 1524 11 10 4 0

30 8

rs1 funct3 rd opcodeimm[11:0]

imm[11:5] rs2 rs1 funct3 imm[4:0] opcode

R-typeI-typeS-type

imm[12|10:5] rs2 rs1 funct3 imm[4:1|11] opcode B-type

inst[30:25]inst[24:21] inst[20] I-imm.-inst[31]-

inst[30:25] inst[11:8] inst[7] S-imm.-inst[31]-

inst[30:25] inst[11:8] 0 B-imm.-inst[31]- inst[7]

Page 41: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

BranchExample,completeencoding

0 01010 10011 000 1000 11000110000000

BRANCHBEQrs2=10 rs1=19

beq x19,x10, offset = 16 bytes

13-bitimmediate,imm[12:0],withvalue16

0000000010000

imm[4:1]

imm[0]discarded,alwayszero

imm[10:5]

imm[11]imm[12]

Page 42: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

AllRISC-VBranchInstructions

imm[12|10:5] rs2 rs1 000 imm[4:1|11] 1100011 BEQimm[12|10:5] rs2 rs1 001 imm[4:1|11] 1100011 BNEimm[12|10:5] rs2 rs1 100 imm[4:1|11] 1100011 BLTimm[12|10:5] rs2 rs1 101 imm[4:1|11] 1100011 BGEimm[12|10:5] rs2 rs1 110 imm[4:1|11] 1100011 BLTUimm[12|10:5] rs2 rs1 111 imm[4:1|11] 1100011 BGEU

Page 43: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

QuestionsonPC-addressing

• Doesthevalueinbranchimmediatefieldchangeifwemovethecode?– Ifmovingindividuallinesofcode,thenyes– Ifmovingallofcode,thenno(‘position-independentcode’)

• Whatdowedoifdestinationis>210 instructionsawayfrombranch?– Otherinstructionssaveus

Page 44: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

QuestionsonPC-addressing

• Doesthevalueinbranchimmediatefieldchangeifwemovethecode?– Ifmovingindividuallinesofcode,thenyes– Ifmovingallofcode,thenno(becausePC-relativeoffsets)

• Whatdowedoifdestinationis>210 instructionsawayfrombranch?– Otherinstructionssaveus

beq x10,x0,far bne x10,x0,next# next instr à j far

next: # next instr

Page 45: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

U-Formatfor“UpperImmediate”Instructions

• Has20-bitimmediateinupper20bitsof32-bitinstructionword

• Onedestinationregister,rd• Usedfortwoinstructions

– LUI– LoadUpperImmediate– AUIPC– AddUpperImmediatetoPC

7

31 712 6 0opcodeimm[31:12] rd

11

20 5U-immediate[31:12] dest LUIU-immediate[31:12] dest AUIPC

Page 46: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

LUItoCreateLongImmediates

• LUIwritestheupper20bitsofthedestinationwiththeimmediatevalue,andclearsthelower12bits.

• TogetherwithanADDItosetlow12bits,cancreateany32-bitvalueinaregisterusingtwoinstructions(LUI/ADDI).

LUI x10, 0x87654 # x10 = 0x87654000

ADDI x10, x10, 0x321# x10 = 0x87654321

Page 47: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

OneCornerCase

Howtoset0xDEADBEEF?LUI x10, 0xDEADB # x10 = 0xDEADB000

ADDI x10, x10, 0xEEF# x10 = 0xDEADAEEF

ADDI12-bitimmediateisalwayssign-extended,iftopbitisset,willsubtract1fromupper20bits

Page 48: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

Solution

Howtoset0xDEADBEEF?LUI x10, 0xDEADC # x10 = 0xDEADC000ADDI x10, x10, 0xEEF# x10 = 0xDEADBEEF

Pre-incrementvalueplacedinupper20bits,ifsignbitwillbesetonimmediateinlower12bits.Assemblerpseudo-ophandlesallofthis:li x10, 0xDEADBEEF # Creates two instructions

Page 49: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

AUIPC

• AddsupperimmediatevaluetoPCandplacesresultindestinationregister

• UsedforPC-relativeaddressing

Label: AUIPC x10, 0 # Puts address of label in x10

Page 50: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

J-FormatforJumpInstructions

• JALsavesPC+4inregisterrd (thereturnaddress)– Assembler“j”jumpispseudo-instruction,usesJALbutsetsrd=x0 todiscardreturnaddress

• SetPC=PC+offset(PC-relativejump)• Targetsomewherewithin±219 locations,2bytesapart

– ±218 32-bitinstructions• Immediateencodingoptimizedsimilarlytobranchinstruction

toreducehardwarecost

7

31 712 6 0opcodeimm[10:1] rd

11

10 5offset[20:1] dest JAL

imm[20] imm[11] imm[19:12]1 1 8

19202130

Page 51: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

UsesofJAL# j pseudo-instruction

j Label = jal x0, Label # Discard return address

# Call function within 218 instructions of PC

jal ra, FuncName

Page 52: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

JALRInstruction(I-Format)

• JALRrd,rs,immediate– WritesPC+4tord (returnaddress)– SetsPC=rs +immediate– Usessameimmediates asarithmeticandloads

• nomultiplicationby2bytes• IncontrasttobranchesandJAL

7

31 712 6 0opcodeimm[11:0] rd

11

12 5offset[11:0] dest JALR

rs1 func35 3

151920 14

base 0

Page 53: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

UsesofJALR# ret and jr psuedo-instructions

ret = jr ra = jalr x0, ra, 0

# Call function at any 32-bit absolute address

lui x1, <hi20bits>

jalr ra, x1, <lo12bits>

# Jump PC-relative with 32-bit offset

auipc x1, <hi20bits>

jalr x0, x1, <lo12bits>

Page 54: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

SummaryofRISC-VInstructionFormats

31 25 20 15 71224 19 14 11 6 0funct7 rs2 rs1 funct3 rd opcode

30 821

rs1 funct3 rd opcodeimm[11:0]

imm[11:5] rs2 rs1 funct3 imm[4:0] opcode

I-typeS-type

imm[12|10:5] rs2 rs1 funct3 imm[4:1|11] opcode B-typeopcodeimm[31:12] rd U-type

R-type

opcodeimm[20|10:1|11]] rdimm[19:12] J-type

Page 55: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

CompleteRV32IISA

NotinCAlectures

Page 56: CS 110 Computer Architecture - ShanghaiTech · 2020. 6. 16. · –RISC-V seeks simplicity: since data is in words, make instructions be fixed-size 32-bit words, too •Same 32-bit

“AndinConclusion…”• SimplificationworksforRISC-V:Instructionsaresamesizeasdataword(oneword)sothattheycanusethesamememory.

• Computeractuallystoresprogramsasaseriesofthese32-bitnumbers.

• WehavecoveredallRISC-Vinstructionsandregisters– R-type,I-type,S-type,B-type,U-typeandJ-typeinstructions– Practiceassemblinganddisassembling