Professional Documents
Culture Documents
MIPS Assembly Basic
MIPS Assembly Basic
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
MIPSAssembly/PrintVersion
MIPSAssembly/Cover
TheMIPSmicroprocessorparadigmwascreatedin1981fromworkdonebyJ.L.HennessyatStanford
University.Sincethattime,theMIPSparadigmhasbeensoinfluential,thatnearlyeverymodernday
processorfamilymakessomeuseoftheconceptsderivedfromthatoriginalresearch.Thisbookwill
discusstheMIPSarchitectureand(perhapsmostimportantly)MIPSassemblyprogramming.
Thisbookisinanearlystageofdevelopment.Anycontributionswouldbehelpfulandappreciated.
TheMIPSmicroprocessorparadigmwascreatedin1981fromworkdonebyJ.L.HennessyatStanford
University.Sincethattime,theMIPSparadigmhasbeensoinfluentialthatnearlyeverymodernday
processorfamilymakessomeuseoftheconceptsderivedfromthatoriginalresearch.Thisbookwill
discusstheMIPSarchitectureand(perhapsmoreimportantly)MIPSassemblyprogramming.
TableofContents
Introduction
Section1:IntroductiontoMIPS
MIPSArchitecture
MIPSProcessors
MIPSDetails
Section2:MIPSInstructions
MIPSInstructions
ArithmeticInstructions
ControlFlowInstructions
MemoryInstructions
FloatingPointInstructions
MiscellaneousInstructions
Section3:ProgrammingMIPS
MIPSAssemblers
MIPSEmulation
Subroutines
ProgrammingStyle
Section4:AdvancedMIPS
InstructionFormats
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
1/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
SystemInstructions
Pseudoinstructions
RegisterFile
Exceptions
ResourcesandLicensing
Resources
Licensing
Pleaseadd{{alphabetical}}onlytobooktitlepages.
Introduction
Thispageisgoingtoserveasageneralforewordaboutthisbook.
WhatThisBookisAbout
ThisbookisgoingtodiscusstheMIPSassemblylanguage.Thisbookwillcovernotonlythestraight
forwardfacetofthissubject(howtoprogramMIPS),butwillalsolookdeeper,anddiscussMIPSfroma
verylowlevel.Inthisway,thisbookshouldbeusefulbothforpeoplejustlearningtoprogramMIPS,and
alsotopeoplewhoarelookingtodoadvancedtasksinMIPS(suchaswriteaMIPSassemblerprogram,or
constructalowlevelOSkernelinMIPS).ThisbookwillnottalkaboutthespecificsofMIPShardware,
however.
WhoThisBookisFor
ThisbookisdesignedtobeareferenceforallpeoplewhoareinterestedinMIPS.Thisbookstartsoffwith
thebasicsbehindthelanguage,anddiscussesthevariousoperationsinsuchamannerthatbeginnerswillbe
abletogetahandleofMIPSprogramming.However,thisbookalsocontainsanumberofadvanced
sectionsforexperiencedprogrammerswhoarelookingatdoingadvancedprojectswiththeMIPS
architecture.
HowThisBookisOrganized
Thisbookisorganizedinsuchafashionthatthemostsimplematerialispresentedfirst,andthemost
advancedmaterialissavedtowardstheend.Thefirstsectionofthebookisreservedforhistoricaland
interestinginformationaboutMIPS,andlistingsofrealworldMIPSimplementations.Thesecondsection
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
2/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
isgoingtogointotheMIPSassemblylanguage,talkingabouteachinstructionindividually,andexplaining
howtousethem.Thethirdsectionisgoingtotalkaboutthetopicsofprogramming,assembling,and
emulatingMIPScode.Finally,thefourthsectionisgoingtotalkaboutadvancedtopics,suchastheinternal
machinecodeofMIPSmachines,thenatureofpseudoinstructions,someadvancedsysteminstructions,and
handlingexceptions.
WheretoGoFromHere
ThisbookwillserveasacompletereferencetoprogrammingMIPS.Whiletherearenowikimedia
resourcesspecificallydesignedtofollowthistext,thereadermaybenefitfromreadingabouthigherlevel
languages,orassemblers,oranotheradvancedprogrammingtopic.
FormoreinformationabouthowtodesignMIPSandothertypesofmicroprocessorsystems,see
MicroprocessorDesign.
MIPS
Architecture
Section1:
IntroductiontoMIPS
MIPSHistory
TheMIPSarchitecture
MIPSisaregisterbasedarchitecture,meaningtheCPUusesregisterstoperformoperationson.Thereare
othertypesofprocessorsoutthereaswell,suchasstackbasedprocessorsandaccumulatorbased
processors.
RegistersarememoryjustlikeRAM,exceptregistersaremuchsmallerthanRAM,andaremuchfaster.In
MIPStheCPUcanonlydooperationsonregisters,andspecialimmediatevalues.
MIPSprocessorshave32generalpurposeregisters,butsomeofthesearereserved.Afairnumberof
registershoweverareavailableforyouruse.Forexample,oneoftheseregisters,theprogramcounter,
containsthememoryaddressofthenextinstructiontobeexecuted.Astheprocessorexecutesthe
instruction,theprogramcounterisincremented,andthenextmemoryaddressisfetched,executed,andso
on.
WhyMIPS?
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
3/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
TheMIPSarchitectureisaReducedInstructionSetComputer(RISC).AsaRISCarchitecture,itdoesn't
assignindividualinstructionstocomplex,logicallyintensivetasks.Thisisincontrasttocomplex
instructionsetcomputer(CISC)architecturesliketheDECVAX,whichhadaninstructiontomultiply
polynomialsandanothertoperformacyclicredundancycheck(CRC),oftenusedinTCP/IP.Atthetime,it
wasthoughtthatimplementingsuchinstructionsinhardwarewouldresultinperformanceincreasefor
programsthatusedthem,evenifitresultedinhighlycomplexprocessordesign.MIPSandotherRISC
architectureswerebasedonthephilosophythat,amongotherthings,byonlyimplementingasmallcore
(onlyafewdozeninstructions,insteadofseveralhundred)ofthemostcommoninstructions,architects
couldsimplifythedesignandspeedupthemajorityofcommoninstructionssomuchthatthecostof
implementingcomplexprogramsasmultipleinstructionswouldbehidden.
MuchhasbeenwrittenontheRISCversusCISCdebate,[1][2][3][4]soforourpurposesweshallfocusonthe
consequencesoftheMIPSdesignchoices:
AllMIPSinstructionsare32bitslong.
Thismakeshardwareforaccessinganddecodinginstructionsstraightforward.
Thisalsomeansthereareafinitenumberofinstructions.
AllMIPSinstructionsbelongtooneofthreeinstructionformats.Thismakesdecodinginstructions
simpleforbothhumansandhardware.Sincetheinstructionformatisregular,itdoesn'ttakemuch
worktolearnmostoftheMIPSinstructionset.
MIPSPhilosophies
Simplicityfavorsregularity
Gooddesigndemandsgoodcompromise
Smallerisfaster
Makethecommontasksthefastest
MIPSProcessors
ThispageisgoingtotalkaboutsomeofthespecificMIPSimplementations,andMIPSrelatives.
MostMIPSimplementationsusetheclassic5stagepipeline:instructionfetch,instructiondecode/register
fetch,execute,memoryaccess,andregisterwriteback.
Furtherreading
TheMicrochipPIC32microcontrollersarebasedonaMIPS32M4KCore.
TheMIPSarchitectureisoneofseveralpopulararchitecturesinembeddedsystems.
ThePlayStationusesaMIPSprocessor.SeveralWikibooksdiscussprogrammingthePlayStation:
Emulation/OnPlaystation,LinuxGuide/PlayStation3,PSPProgramming,MapThis!.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
4/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
MIPSDetails
Registers
MIPShas32generalpurposeregistersandanother32floatingpointregisters.Registersallbeginwitha
dollarsymbol($).Thefloatingpointregistersarenamed$f0,$f1,...,$f31.Thegeneralpurposeregisters
havebothnamesandnumbers,andarelistedbelow.WhenprogramminginMIPSassembly,itisusually
besttousetheregisternames.
Number
Name
Comments
$0
$zero
Alwayszero
$1
$at
Reservedforassembler
$2,$3
$v0,$v1
Firstandsecondreturnvalues,respectively
$4,...,$7
$a0,...,$a3 Firstfourargumentstofunctions
$t8,$t9
Moretemporaryregisters
$26,$27
$k0,$k1
Reservedforkernel(operatingsystem)
$28
$gp
Globalpointer
$29
$sp
Stackpointer
$30
$fp
Framepointer
$31
$ra
Returnaddress
Ingeneral,therearemanyregistersthatcanbeusedinyourprograms:thetentemporaryregistersandthe
eightsavedregisters.Temporaryregistersaregeneralpurposeregistersthatcanbeusedforarithmeticand
otherinstructionsfreely,whilesavedregistersmustbesavedatprocedureentry,andrestoredatprocedure
exit.
Temporaryregisternamesallstartwitha$t.Forinstance,thereare$t0,$t1...$t9.thismeansthereare10
temporaryregistersthatcanbeusedwithoutworryingaboutsavingandrestoringtheircontents.Thesaved
registersarenamed$s0to$s7.
Thezeroregister,isnamed$zero($0),andisastaticregister:italwayscontainsthevaluezero.This
registermaynotbeusedasthetargetofastoreoperation,becauseitsvalueishardwiredin,andcannotbe
changedbytheprogram.
Therearealsoseveralregisterstowhichtheprogrammerdoesnothavedirectaccess.Amongthesearethe
ProgramCounter(PC),whichstorestheaddressoftheinstructionexecuting,andthe"hi"and"lo"registers,
whichareusedinmultiplicationanddivision,whichhaveresultslongerthan32bits(multiplicationmay
resultina64bitproductanddivisionresultsinaquotientandremainder).ProgrammerschangethePCon
branchesandjumps.Therearespecialinstructionstomovedatatoandfromthehiandloregisters.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
5/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
InstructionFormats
Thereare3differenttypesofinstructions:RInstructions,IInstructions,andJInstructions.
RInstructions
RInstructionstakethreearguments:twosourceregisters(rtandrs),andadestinationregister(rd).R
instructionsarewrittenusingthefollowingformat:
instructionrd,rs,rt
Forexample,
add$t0,$t1,$t2
Addsthevaluesof$t1and$t2andstorestheresultin$t0.
Whenassembledintomachinecode,anRinstructionisrepresentedasfollows:
opcode
6bits
rs
rt
rd
shamt func
ForRformatinstructions,theopcode,or"operationcode"isalwayszero.rs,rt,andrdcorrespondtothe
twosourceandonedestinationregisters,respectively.shamtisusedinshiftinstructionsinsteadofrtto
makethehardwaresimpler.Inassembly,toshiftthevaluein$t4twobitstotheleftandplacetheresultin
$t5:
sll$t5,$t4,2
SincetheopcodeiszeroforallRformatinstructions,funcspecifiestothehardwareexactlywhichR
formatinstructiontoexecute.Theaddexampleabovewouldbeencodedasfollows:
opcodersrtrdshamtfunct
00000001001010100100000000100000
SinceitisanRformatinstruction,thefirstsixbits(opcode)are0.Thenext5bitscorrespondtors,which
inthisexampleis$t1.Fromthetableabove,wefindthat$t1is$9,whichinbinaryis01001.Likewise,the
nextfivebitsencode$t2=$10=01010.Thedestinationis$t0=$8=01000.Wearenotperforminga
shift,soshamtis00000.Finally,sincethefuncfortheaddinstructionis100000.
Fortheshiftexampleabove,theopcodefieldisagain0sincethisisanRformatinstruction.Thersfieldis
unusedinshifts,soweleavethenextfivebitsat0.Thertfieldis$t4=$12=01100.Therdfieldis$t5=
$13=01101.Theshiftamount,shamt,is2=00010.Finally,thefuncfieldforsllis000000.Thus,the
encodingforsll$t5,$t4,2is:
opcodersrtrdshamtfunct
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
6/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
00000000000011000110100010000000
IInstructions
Iinstructionstaketworegisterargumentsanda16bit"immediate"value.Animmediateisavaluethatis
storedaspartoftheinstructioninsteadofinmemory.Thismakesaccessingconstantsmuchfasterthanif
wehadtoputconstantsinmemoryandthenloadthem(hencethename).Iformatinstructions,likeR
formatinstructions,specifythetargetregister(rt)first.Nextcomesonesourceregister(rs)andfinallythe
immediatevalue.
instructionrt,rs,imm
Forexample,let'ssaythatwewanttoaddthevalue5totheregister$t1,andstoretheresultin$t0:
addi$t0,$t1,5
Iformatinstructionsarerepresentedinmachinecodeasfollows:
opcode
6bits
rs
rt
imm
Theopcodespecifieswhichoperationisrequested.rsandrtarefivebitseach,asbefore,andinthesame
positionsastheRformatinstructions.Theimmfieldholdstheimmediatevalue.Dependingonthe
instruction,theimmediateconstantmayeitherbesignextendedorzeroextended.Ifa32bitimmediateis
needed,aspecialinstruction,lui("loadupperimmediate")existsforloadinganimmediateintotheupper16
bitsofaregister.ThatregistercanthenbelogicallyORedwithanother16bitimmediatetostorethefinal
valueinthatregister.ThatvaluecanthenbeusedinnormalRformatinstructions.Thefollowingsequence
ofinstructionsstoresthebitpattern010101010101...intoregister$t0:
lui$t0,0x5555
ori$t0,$t0,0x5555
Typically,theassemblerwillautomaticallysplit32bitconstantsinthiswaysotheprogrammerdoesn't
havetoworryaboutit.
Theaddiexamplefromabovewouldbeencodedasfollows.Theaddiinstructionhasanopcodeof001000.
Thesourceregister,$t1,isnumber9,or01001inbinary.Thetargetregister,$t0,isnumber8,or01000in
binary.Fiveis101inbinary,soaddi$t0,$t1,5inmachinecodeis:
opcodersrtimm
00100001001010000000000000000101
JInstructions
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
7/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
Jinstructionsareusedtotransferprogramflowtoagiven,hardcodedoffsetfromthecurrentvalueofthe
PCregister.Jinstructionsarealmostalwayswrittenwithlabels:theassemblerandlinkerwillconvertthe
labelintoanumericalvalue.AJinstructiontakesonlyoneargument:theaddresstojumpto.
instructionaddr
TherearetwoJformatinstructions:jandjal.Thelatterwillbediscussedlater.Thej("jump")instruction
tellstheprocessortoimmediatelyskiptotheinstructionaddressedbyaddr.Toexample,tojumptoa
label1:
jlabel1
AJformatinstructionisencodedas
opcode addr
6bits
26bits
OnMIPS32machines,addressesare32bitswide,so26bitsmaynotbeenoughtospecifywhich
instructiontojumpto.Fortunately,sinceallinstructionsare32bits(fourbytes)wide,wecanassumethat
allinstructionsstartatabytethat'sdivisibleby4(weareinfactguaranteedthisbytheloader).Inbinary,a
numberthatisdivisibleby4endswithtwozeros(justlikeanumberthat'sdivisibleby100indecimal
alwaysendsintwozeros).Therefore,wecanallowtheassemblertoleaveoutthelasttwozerosandhave
thehardwarereinsertthem.Thiseffectivelymakestheaddressfield28bits.Thefinalfourbitswillbe
borrowedfromtheaddressofthecurrentinstruction,sowecannotletaprogramstraddlea256MB
boundary,becauseajumpacrosstheboundarywouldrequireachangeinthe4uppermostbits.
Intheexampleabove,iflabel1specifiedaninstructionasaddress120,or1111000inbinary,wecan
encodethejumpexampleaboveinmachinecodeasfollows.Theopcodeforjis2,or10inbinary,andwe
mustchopoffthelasttwobitsofthejumpaddress,leavingitat11110.Thus,themachinecodeforj120is:
opcode|addr|
00001000000000000000000000011110
MIPS
Instructions
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
Section2:MIPS
Instructions
8/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
Writingassembly
code
Anassemblylanguageprogramhasafewcommonfeatures.Theseare:
labels
sections
directives
comments
commands
Comments
InMIPSassembly,commentsaredenotedwithanumbersign("#").Everythingafterthatsignonthesame
lineisacommentandisskippedbytheassembler'slexer.
Labels
Alabelissomethingtomakeyourlifesimple.Whenyoureferenceapieceofyourprogram,insteadof
havingtocountlines,youcanjustgiveitaname.Youusethisinloops,jumps,andvariablenames.
Labelsdon'tappearinyourfinalcode,they'reonlythereforconvenience,oneofthefewperksyou'llget
fromthetypicalMIPSassembler.Italsomakeslifeeasyfortheassembler,becauseitcannoweasilygo
aroundrelocatingandlinkingcode.Don'tworryifyoudon'tknowwhatthoseare,that'llcomelater.
LabelsinMIPSassembly,actuallyinmostvariantsofASMaswell,arecreatedbywriting
name:
wherenameisanameyouusetorefertothislabel.Notethat,youcan'tcreatealabelwiththesamename
asaMIPSinstruction.
LabelsarethesameastheirCcousins,thetargetsofgotooperators.
Sections
Asectionisawayofdividinganassemblylanguageprogramupintotheinstructionsandthedatalogically.
Sinceyourassemblyprogramisloadedintomemory,alltheprocessorneedstoknowisthestartof
execution(knownastheentrypoint)andmerelyjustincrementstheinstructionpointerandcontinues
along.Ifdataisinterspersedintheinstructioncodeinmemory,theprocessorneedstoknowwhatisdata
andwhatisinstructionswhichservesforamuchmorecomplicatedprocessor.Forsimplicity,thedatais
setoffinadifferentareathantheinstructions.Sectionsareusedforthispurpose.
TherearetwosectionsyouneedtobemindfulofinMIPSprogramming:thetextanddatasections.The
textsectionholdsyourassemblyprogram,andthedatasectionholdsyourdata.Onedesignatesatext
sectionbystartingwith.textandthestartofadatasectionby.data.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
9/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
Directives
Theprocessorassembler(oryouremulator)understandsafewspecialcommandsthatperformspecific
taskstomakeyourlifeeasier:forexamplecreatingmemoryspaceforyoutostoredatainvariables.
Ifyouwishtocreateavariableforanumberinyourassemblyprogram,youmaywantto:
1. switchtothedatasection
2. createalabeltocreateamemoryreferenceforyourvariable
3. giveitanappropriatename
4. allocatesomememoryforit
5. alignitproperlyinmemory.
6. switchbacktothetextsection
Fromwhatwehavelearned,wecanwritetheMIPSassemblycodeuptostep3:
.data
variable_name:
Butnowhowcanweallocatesomememory?Weusethe.spacedirective.Anintegertakesup4bytes,
usually,sowewrite
.data
variable_name:
.space4
Weneedtoalignthedatainmemorynow(we'llexplainthisbelow),soweusethe.aligndirective
.data
variable_name:
.space4
.align2
.text
Andwe'veswitchedbacktothetextsection.
MemorylocationsinMIPSassemblerneedtobealignedthatis,thatmemorylocationsmustbeginonthe
correctlocationotherwisetheprocessorwillcrash.4byteintegersmustbealignedevery4bytes,andso
on.The.alignndirectivealignsthedatatoamemorycellfitfor2nbytes.Therefore,for32bit(4byte)
integersweuse.align2for22or4bytes.Alignsthenextvariableorinstructiononabytethatisa
multipleofnumber.Toalignthespaceallocated,the'alignn'shouldcomebeforethe'spacex'declaration.
Forexample,hereisasampleforallocating6words(6x4=24bytes)inmemoryandaligningthemat
wordboundaries
.data
.align2
my_var_name:
.space24
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
10/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
ArithmeticInstructions
RegisterArithmeticInstructions
Instruction:
add
type:
RType
Thisinstructionaddsthetwooperandstogether,andstorestheresultinthedestinationregister.Negative
numbersarehandledautomaticallyusingtwo'scomplementnotation,sodifferentinstructionsdonotneed
tobeusedforsignedandunsignednumbers.
Instruction:
sub
type:
RType
Thesubinstructionsubtractsthesecondsourceoperandfromthefirstsourceoperand,andstorestheresult
inthedestinationoperand.Inpseudocode,theoperationperformsthefollowing:
rd:=rsrt
Bothaddandsubtrapifoverflowoccurs.However,someprogrammingsystems,likeC,ignoreinteger
overflow,sotoimproveperformance"unsigned"versionsoftheinstructionsdon'ttraponoverflow.
Instruction:
addu
type:
RType
Instruction:
subu
type:
RType
MultiplicationandDivision
Themultiplyanddivideoperationsareslightlydifferentfromotheroperations.EveniftheyareRtype
operations,theyonlytake2operands.Theresultisstoredinaspecial64bitresultregister.Wewilltalk
abouttheresultregisterafterthissection.
Instruction:
mult
type:
RType
Thisoperationmultipliesthetwooperandstogether,andstorestheresultinrd.Multiplicationoperations
mustdifferentiatebetweensignedandunsignedquantities,becausethesimplicityofTwo'sComplement
Notationdoesnotcarryovertomultiplication.Themultinstructionmultipliesandsignextendssigned
numbers.
Theresultofmultiplying232bitnumbersisa64bitresult.Wewilldiscussthe64bitresultsbelow.
Instruction:
multu
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
type:
11/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
RType
Themultuinstructionmultipliesthetwooperandstogether,andstorestheresultinrd.Thisinstructionis
forunsignednumbersonly,anddoesnotsignextendanegativeresult.Thisoperationalsocreatesa64bit
result.
Instruction:
div
type:
RType
Thedivinstructiondividesthefirstargumentbythesecondargument.Thequotientisstoredinthelowest
32bitsoftheresultregister.Theremainderisstoredinthehighest32bitsoftheresultregister.Like
multiplication,divisionrequiresadifferentiationbetweensignedandunsignednumbers.Thisoperation
usessignednumbers.
Instruction:
divu
type:
RType
Likethedivinstruction,thisoperationdividesthefirstoperandbythesecondoperand.Thequotientis
storedinthelowest32bitsoftheresult,andtheremainderisstoredinthehighest32bitsoftheresult.This
operanddividesunsignednumbers,andwillnotsignextendtheresult.
64BitResults
The64bitresultregisterisbrokenintotwo32bitsegments:HIandLO.Wecaninterfacewiththese
registersusingthemfhiandmflooperations,respectively.
Instruction:
mfhi
type:
RType
Takesonly1operand.Thisinstructionmovesthehigh32bitsoftheresultregisterintothetargetregister.
Instruction:
mflo
type:
RType
Alsotakesonly1operand.MovesthevaluefromtheLOpartoftheresultregisterintothespecified
register.
Iftheupper(mostsignificant)32bitsofaproductareunimportanttocomputation,programmersmaysave
astepbyusinginstructionsthatdiscardtheupper32bits.
Instruction:
mul
type:
RType
Thereisnounsignedversionofthemulinstruction.Themulinstructionmayalsoclobbertheexisting
valuesinHIandLO.
RegisterLogicInstructions
Theseoperationsperformbitwiselogicaloperationsontheiroperands.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
12/38
28/2/2015
Instruction:
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
and
type:
RType
PerformsabitwiseANDoperationonthetwooperands,andstorestheresultinrd.
Instruction:
or
type:
RType
type:
RType
PerformsabitwiseORoperationonthetwooperands,andstorestheresultinrd.
Instruction:
nor
PerformsabitwiseNORoperationonthetwooperands,andstorestheresultinrd.
Instruction:
xor
type:
RType
PerformsabitwiseXORoperationonthetwooperands,andstorestheresultinrd.
ImmediateArithmeticInstructions
Theseinstructionssignextendthe16bitimmediatevalueto32bitsandperformsthesameoperationasthe
instructionwithoutthetrailing"i".
Instruction:
addi
type:
IType
Instruction:
addiu
type:
IType
type:
IType
type:
IType
type:
IType
Tosubtract,useanegativeimmediate.
ImmediateLogicInstructions
Alllogicalfunctionszeroextendtheimmediate.
Instruction:
andi
TakesthebitwiseANDofrswiththeimmediateandstorestheresultinrt.
Instruction:
ori
TakesthebitwiseORofrswiththeimmediateandstorestheresultinrt.
Instruction:
xori
TakesthebitwiseXORofrswithatheimmediateandstorestheresultinrt.
Shiftinstructions
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
13/38
28/2/2015
Instruction:
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
sll
type:
RType
type:
RType
type:
RType
Logicalshiftleft:rdrt<<shamt.Fillsbitsfromrightwithzeros.
Instruction:
srl
Logicalshiftright:rdrt>>shamt.Fillsbitsfromleftwithzeros.
Instruction:
sra
Arithmeticshiftright.Ifrtisnegative,theleadingbitsarefilledinwithonesinsteadofzeros:rdrt>>
shamt.
Becausenotallshiftamountsareknowninadvance,MIPSdefinesversionsoftheseinstructionsthatshift
bytheamountinthersregister.Thebehaviorisotherwiseidentical.
Instruction:
sllv
type:
RType
Instruction:
srlv
type:
RType
Instruction:
srav
type:
RType
ControlFlowInstructions
JumpInstruction
ThejumpinstructionsloadanewvalueintothePCregister,whichstoresthevalueoftheinstructionbeing
executed.Thiscausesthenextinstructionreadfrommemorytoberetrievedfromanewlocation.
Instruction:
type:
JType
ThejinstructionloadsanimmediatevalueintothePCregister.Thisimmediatevalueiseitheranumeric
offsetoralabel(andtheassemblerconvertsthelabelintoanoffset).
Instruction:
jr
type:
RType
ThejrinstructionloadsthePCregisterwithavaluestoredinaregister.Assuch,thejrinstructioncanbe
calledassuch:
jr$t0
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
14/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
assumingthetargetjumplocationislocatedin$t0.
JumpandLink
JumpandLinkinstructionsaresimilartothejumpinstructions,exceptthattheystoretheaddressofthe
nextinstruction(theoneimmediatelyafterthejump)inthereturnaddress($ra$31)register.Thisallowsa
subroutinetoreturntothemainbodyroutineaftercompletion.
Instruction:
jal
type:
JType
Likethejinstruction,exceptthatthereturnaddressisloadedintothe$raregister.
Instruction:
jalr
type:
RType
Thesameasthejrinstruction,exceptthatthereturnaddressisloadedintothe$raregister.
Example
Let'ssaythatwehaveasubroutinethatstartswiththelabelMySub.Wecancallthesubroutineusingthe
followingline:
jalMySub
...
AndwecandefineMySubasfollowstoreturntothemainbodyoftheparentroutine:
jr$ra
BranchInstructions
Insteadofusingrtasadestinationoperand,rsandrtarebothusedassourceoperandsandtheimmediateis
signextendedandaddedtothePCtocalculatetheaddressoftheinstructiontojumptoifthebranchis
taken.
Instruction:
beq
type:
IType
type:
IType
type:
IType
Branchifrsandrtareequal.Ifrs=rt,PCPC+4+imm.
Instruction:
bne
Branchifrsandrtarenotequal.Ifrsrt,PCPC+4+imm.
Instruction:
bgez
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
15/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
Branchifrsisgreaterthanorequaltozero.Ifrs0,PCPC+4+imm.
Instruction:
blez
type:
IType
type:
IType
type:
IType
Branchifrsislessthanorequaltozero.Ifrs0,PCPC+4+imm.
Instruction:
bgtz
Branchifrsisgreaterthanzero.Ifrs>0,PCPC+4+imm.
Instruction:
bltz
Branchifrsislessthanzero.Ifrs<0,PCPC+4+imm.
SetInstructions
Theseinstructionssetrdto1iftheirconditionistrue.Theycanbeusedincombinationwithbeqandbne
and$zerotobranchbasedonthecomparisonoftworegisters.
Instruction:
slt
type:
RType
type:
IType
type:
RType
type:
IType
Ifrs<rt,rd1,else0.
Instruction:
slti
Ifrs<imm,rd1,else0.Theimmediateissignextended.
Instruction:
sltu
Ifrs<rt,rd1,else0.Treatrsandrtasunsignedintegers.
Instruction:
sltiu
Ifrs<imm,rd1,else0.Theimmediateissignextended,butbothrsandtheextendedimmediateare
treatedasunsignedintegers.Thesignextensionallowstheimmediatetorepresentbothverylargeandvery
smallunsignedintegers.
MemoryInstructions
Loadandstoreinstructionsuseaspecialsyntax:
instrrt,imm(rs)
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
16/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
Thememoryaddressusedfortheloadorstoreisrs+imm.Theimmediateissignextended.
LoadInstructions
Instruction:
lbu
type:
IType
type:
IType
Loadsabyteanddoesnotsignextendthevalue.
Instruction:
lhu
Loadsahalfword,ortwobytes,anddoesnotsignextendthevalue.Thehalfwordmustbealigned(i.e.,it
muststartatanevenaddress).
Instruction:
lw
type:
IType
Loadsaword(fourbytes)frommemory.Thewordmustbealigned(i.e.,thelasttwobitsoftheaddress
mustbezero).
StoreInstructions
Instruction:
sb
type:
IType
type:
IType
type:
IType
Storestheleastsignificant(rightmost)byteofrttomemory.
Instruction:
sh
Storestheleastsignificant(rightmost)halfwordofrttomemory.
Instruction:
sw
Storesthecontentsofrtinmemory.
FloatingPointInstructions
Arithmetic
Integerimplementationoffloatingpointaddition
#Initializevariables
add$s0,$t0,$zero#firstintegervalue
add$s1,$t1,$zero#secondintegervalue
add$s2,$zero,$zero#initializesumvariableto0
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
17/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
add$t3,$zero,$zero#initializeSUMOFSIGNIFICANDSvalueto0
#getEXPONENTfromvalues
sll$s5,$s0,1#gettingtheexponentvalue
srl$s5,$s5,24#$s5=firstvalueEXPONENT
sll$s6,$s1,1#gettingtheexponentvalue
srl$s6,$s6,24#$s6=secondvalueEXPONENT
#getSIGNfromvalues
srl$s3,$s0,31#$s3=firstvalueSIGN
srl$s4,$s1,31#$s4=secondvalueSIGN
#getFRACTIONfromvalues
sll$s7,$s0,9
srl$s7,$s0,9#$s7=firstvalueFRACTION
sll$t8,$s1,9
srl$t8,$s1,9#$t8=secondvalueFRACTION
#comparetheexponentsofthetwonumbers
compareExp:######################
beq$s5,$s6,addSig
blt$s5,$s6,shift1#iffirst<second,gotoshift1
blt$s6,$s5,shift2#ifsecond<first,gotoshift2
jcompareExp
shift1:#shiftthesmallernumbertotheright
srl$s7,$s7,1#shifttotheright1
addi$s5,$s5,1
jcompareExp
Compare
Load
Store
Branch
FurtherReading
FloatingPoint
MIPSAssemblers
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
18/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
Thispageisgoingtolist
someassemblersfor
programminginMIPS,and
willdiscusshowtoprogram
usingMIPSassemblers.
/editbyTillFischer,
UniversityofUlm
(Germany)
Section4:
ProgrammingMIPS
HeresalinktoaDownload
oftheMARS,anemulationAssemblerProgrambytheMissouriStateUniversity,weusethatoneinour
StudiesinordertolearnAssembler:http://courses.missouristate.edu/KenVollmar/MARS/
MIPSEmulation
ThispageisgoingtotalkaboutusingMIPSemulatorstotestMIPScodeonanonMIPScomputer.
AcommonMIPSEmulatorisSpimwhichisfullycrossplatform.AnotheroneisMIPSAssemblerand
Simulator(http://xavier.perseguers.ch/programmation/mipsassembler.html),whichhasbeensuccessfuly
deployedinusedinafewhighschools.QEMU(http://wiki.qemu.org/Main_Page)isanothercommon
emulatorenvironmentforMIPS.YetanotherEmulatorisMARS
(http://courses.missouristate.edu/KenVollmar/MARS/)acrossplatformJavaMIPSIDE.
OpenVirtualPlatforms(OVP)http://www.OVPworld.org(http://www.OVPworld2.org)includesthefreely
availablesimulatorOVPsim,alibraryofmodelsofprocessors,peripheralsandplatforms,andAPIswhich
enableuserstodeveloptheirownmodels.Themodelsinthelibraryareopensource,writteninC,and
includetheMIPS4K,24Kand34Kcores.ThesemodelsarecreatedandmaintainedbyImperas
http://www.imperas.comandinpartnershipwithMIPSTechnologieshavebeentestedandassignedthe
MIPSVerified(tm)mark.SampleMIPSbasedplatformsincludebothbaremetalenvironmentsand
platformsforbootingunmodifiedLinuxbinaryimages.Theseplatforms/emulatorsareavailableassource
orbinariesandarefast,free,andeasytouse.OVPsimisdevelopedandmaintainedbyImperasandisvery
fast(100sofmillioninstructionspersecond),andbuilttohandlemulticorearchitectures.Todownloadthe
MIPSOVPsimsimulators/emulatorsvisithttp://www.OVPworld.org/mips
(http://www.OVPworld2.org/mips).
Subroutines
ThispageisgoingtotalkaboutusingsubroutinestructuresinMIPSAssembly.Also,thispagewilltalk
aboutsomeofthecommonmethodsbywhichhigherlevellanguageconstructsandsubroutinesare
translatedintoMIPSassemblycode.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
19/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
SubroutineMechanics
InMIPS,thegeneralpurposeregistersaretypicallytakentobethefunctionparametersandthefunction
variables,asneeded.Previousvaluesofthegeneralpurposeregistersarestoredonthestack.Attheendofa
subroutine,thevaluesofallregistersstoredinthismannerarerestoredfromthestack.
MIPSusesthestacktopreservetheseregisters.Thestackpointerpointstothebottomofthestack,butthe
framepointerpointstothetopofthelocalframe.Offsettingfromthestackorframepointerscanretrieve
thevarioussavedvaluesandfunctionparameters,asneeded.
StemandLeaf
Inthefunctionhierarchy,afunctionthatcallsotherfunctionsisknownasastemfunction.Afunction
whichcallsnootherfunctionsisknownasaleaffunction.Stemfunctionsmustsavethevalueof$raonthe
stack,sothatitscontentispreservedacrosstheotherfunctioncalls,andsothecalledfunctioncanreturnto
thecallingfunction,oritsparentfunction.
Itisimportanttonotethataleaffunctiondoesnotneedtopreservethevalueofthe$raregisterbecauseit
doesnotcallanyotherchildfunctionandhenceitsreturnaddressispreservedin$ra.
StackFrame
Afunctionmaysetupastackframe,withthe$spregisterpointingtothebottomofthestack,andthe$fp
registerpointingtothetopofthestackatthestartofthesubroutine.Inthismanner,$fpwillbepointingto
thefunction'sinputarguments(ifanyareonthestack),and$spwillbepointingtothelocalvariablesfor
thefunction.
Thevalueof$fpneedstobepreservedacrossfunctioncalls,andstemfunctionsneedtosavethevalueof
$fpbeforecallingachildfunction,andrestoreitfromthestackaftercallingthechildfunction.
Thevalueof$spdoesnotneedtobestoredonthestack,butfunctionsneedtotakecaretoreturn$sptothe
valueithadatthebeginningofthefunction,beforethefunctionreturns.Thismeansthatatthebeginningof
asubroutine,valuescanbepushedontothestack,andattheendofthesubroutine,allthosevaluesneedto
bepoppedrightbackoffthestack.Ifthisisnotdonecorrectly,itwilldestroythestackframeoftheparent
function,andpossiblycausethecomputertocrash.
SavedRegisters
Thereareanumberofregistersthatmustbepreservedacrossasubroutinecall.Thismeansthatifthe
subroutinewantstousethoseregisters,itmustsavethepreviousvaluesontothestack(orsomeother
place),andthenreloadthosevaluesattheendofthefunction.The$txregistersarealltemporaryregisters
anddonotneedtobesaved.Likewise,the$axregistersareallfunctionarguments,anddonotneedtobe
saved.Thr$v0and$v1registersarebothfunctionreturnvalues,anddonotneedtobesaved.
Thefollowingregistersdoneedtobepreservedacrossafunctioncall,andshouldbesavedbythefunction
iftheyaregoingtobeusedinthefunction:
$sx
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
20/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
The"SavedTemporary"registers
MIPSandCLinkage
furtherreading
EmbeddedSystems/MixedCandAssemblyProgramming
ProgrammingStyle
ThispageisgoingtotalkaboutprogrammingstyleandcodeformattingtechniquesinMIPSAssembly.
Programmingstyleisanarbitraryconstructthatisdependantontheindividualprogrammer,butthispage
willshowsomecommonstylesanyway.
Good,consistentprogrammingstyleforassemblylanguagesingeneralisarguablymoreimportantthanfor
higherlevellanguages,asyoudon'thavetheluxuryofabstractingeventhesimplestofoperationsaway.
Forthatreason,commentsareevenmoreimportantthaninhigherlevellanguages!Thenecessityof
dealingwiththenittygrittymeansyourprogramwillgrowinlinesofcodeveryquickly,andsomeone's
goingtohavetoreadit.Whynotmaketheirlifeeasier?
Thereareseveralstylesandconventionsonemayadhereto.Doesn'tmattertoomuchwhichoneyouuse,
butbeconsistent!
Instruction
Formats
Section3:Advanced
MIPS
Thispageisgoingtodiscuss
theimplementationdetailsoftheMIPSinstructionformats.
RInstructions
Rinstructionsareusedwhenallthedatavaluesusedbytheinstructionarelocatedinregisters.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
21/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
AllRtypeinstructionshavethefollowingformat:
OPrd,rs,rt
Where"OP"isthemnemonicfortheparticularinstruction.rs,andrtarethesourceregisters,andrdisthe
destinationregister.Asanexample,theaddmnemoniccanbeusedas:
add$s1,$s2,$s3
Wherethevaluesin$s2and$s3areaddedtogether,andtheresultisstoredin$s1.Inthemainnarrativeof
thisbook,theoperandswillbedenotedbythesenames.
RFormat
ConvertinganRmnemonicintotheequivalentbinarymachinecodeisperformedinthefollowingway:
opcode rs rt rd shift(shamt) funct
opcode
Theopcodeisthemachinecoderepresentationoftheinstructionmnemonic.Severalrelated
instructionscanhavethesameopcode.Theopcodefieldis6bitslong(bit26tobit31).
rs,rt,rd
Thenumericrepresentationsofthesourceregistersandthedestinationregister.Thesenumbers
correspondtothe$Xrepresentationofaregister,suchas$0or$31.Eachofthesefieldsis5bits
long.(25to21,20to16,and15to11,respectively).Interestingly,ratherthanrsandrtbeingnamed
r1andr2(forsourceregister1and2),theregisterswerenamed"rs"and"rt"becausetcomesafters
inthealphabet.Thiswasmostlikelydonetoreducenumericalconfusion.
Shift(shamt)
Usedwiththeshiftandrotateinstructions,thisistheamountbywhichthesourceoperandrsis
rotated/shifted.Thisfieldis5bitslong(6to10).
Funct
Forinstructionsthatshareanopcode,thefunctparametercontainsthenecessarycontrolcodesto
differentiatethedifferentinstructions.6bitslong(0to5).Example:Opcode0x00accessestheALU,
andthefunctselectswhichALUfunctiontouse.
FunctionCodes
ShiftValues
IInstructions
Iinstructionsareusedwhentheinstructionmustoperateonanimmediatevalueandaregistervalue.
Immediatevaluesmaybeamaximumof16bitslong.Largernumbersmaynotbemanipulatedby
immediateinstructions.
Iinstructionsarecalledinthefollowingway:
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
22/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
OPrd,rs,IMM
Whererdisthedestinationregister,rsisthesourceregister,andIMMistheimmediatevalue.The
immediatevaluecanbeupto16bitslong.Forinstance,theaddiinstructioncanbecalledas:
addi$s1,$s2,100
Wherethevalueof$s2plus100isstoredin$s1.
IFormat
Iinstructionsareconvertedintomachinecodewordsinthefollowingformat:
opcode rs rt IMM
Opcode
The6bitopcodeoftheinstruction.InIinstructions,allmneumonicshaveaonetoone
correspondencewiththeunderlyingopcodes.Thisisbecausethereisnofunctparameterto
differentiateinstructionswithanidenticalopcode.6bits(26to31)
rs,rt
Thesourceanddestinationregisteroperands,respectively.5bitseach(21to25and16to20,
respectively).
IMM
The16bitimmediatevalue.16bits(0to15).Thisvalueisusuallyusedastheoffsetvalueinvarious
instructions,anddependingontheinstruction,maybeexpressedintwo'scomplement.
JInstructions
Jinstructionsareusedwhenajumpneedstobeperformed.TheJinstructionhasthemostspaceforan
immediatevalue,becauseaddressesarelargenumbers.
Jinstructionsarecalledinthefollowingway:
OPLABEL
WhereOPisthemneumonicfortheparticularjumpinstruction,andLABEListhetargetaddresstojump
to.
JFormat
Jinstructionshavethefollowingmachinecodeformat:
Opcode Address
Opcode
The6bitopcodecorrespondingtotheparticularjumpcommand.(26to31).
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
23/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
Address
A26bitaddressofthedestination.(0to25).
FRInstructions
FRinstructionsaresimilartotheRinstructionsdescribedabove,excepttheyarereservedforusewith
floatingpointnumbers:
Opcode fmt ft fs fd funct
FIInstructions
FIinstructionsaresimilartotheIinstructionsdescribedabove,excepttheyarereservedforusewith
floatingpointnumbers:
Opcode fmt ft Imm
Opcodes
ThefollowingtablecontainsalistingofMIPSinstructionsandthecorrespondingopcodes.Opcodeand
functnumbersarealllistedinhexadecimal.
Mnemonic
Meaning
Type
Opcode
Funct
add
Add
0x00
0x20
addi
AddImmediate
0x08
NA
addiu
AddUnsignedImmediate
0x09
NA
addu
AddUnsigned
0x00
0x21
and
BitwiseAND
0x00
0x24
andi
BitwiseANDImmediate
0x0C
NA
beq
BranchifEqual
0x04
NA
bne
BranchifNotEqual
0x05
NA
div
Divide
0x00
0x1A
divu
UnsignedDivide
0x00
0x1B
JumptoAddress
0x02
NA
jal
JumpandLink
0x03
NA
jr
JumptoAddressinRegister
0x00
0x08
lbu
LoadByteUnsigned
0x24
NA
lhu
LoadHalfwordUnsigned
0x25
NA
lui
LoadUpperImmediate
0x0F
NA
lw
LoadWord
0x23
NA
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
24/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
mfhi
MovefromHIRegister
0x00
0x10
mflo
MovefromLORegister
0x00
0x12
mfc0
MovefromCoprocessor0
0x10
NA
mult
Multiply
0x00
0x18
multu
UnsignedMultiply
0x00
0x19
nor
BitwiseNOR(NOTOR)
0x00
0x27
xor
BitwiseXOR(ExclusiveOR)
0x00
0x26
or
BitwiseOR
0x00
0x25
ori
BitwiseORImmediate
0x0D
NA
sb
StoreByte
0x28
NA
sh
StoreHalfword
0x29
NA
slt
Setto1ifLessThan
0x00
0x2A
slti
Setto1ifLessThanImmediate
0x0A
NA
sltiu
Setto1ifLessThanUnsignedImmediate I
0x0B
NA
sltu
Setto1ifLessThanUnsigned
0x00
0x2B
sll
LogicalShiftLeft
0x00
0x00
srl
LogicalShiftRight(0extended)
0x00
0x02
sra
ArithmeticShiftRight(signextended)
0x00
0x03
sub
Subtract
0x00
0x22
subu
UnsignedSubtract
0x00
0x23
sw
StoreWord
0x2B
NA
SystemInstructions
ThispageisgoingtodiscusssomeofthemoreadvancedMIPSinstructionsthatmightnotbeusedinevery
dayprogrammingtasks.
Instruction:
syscall
type:
RType
syscallallowsyoutocalluponthebasicsystemfunctions.Tousesyscall,firstset$v0withthecodeofthe
functionyouwanttocall,thenusesyscall.Theexactcodesavailablemaydependonthespecificsystem
used,butthefollowingareexamplesofcommonsytemcalls.
code call
arguments
$a0=integertoprint
printinteger
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
results
25/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
printfloat
$f12=floattoprint
printdouble
$f12=floattoprint
printstring
$a0=addressofbeginningofstring
readinteger
integerstoredin$v0
readfloat
floatstoredin$f0
readdouble
doublestoredin$f0
readstring
$a0=pointertobuffer,$a1=lengthof
buffer
stringstoredinbuffer
sbrk(allocatememory
buffer)
$a0=sizeneeded
$v0=addressof
buffer
10
exit
Example:printingthenumber12
li$a0,12;loadsthenumberwewantprinted,12inthiscase,intothefirstargumentregister
li$v0,1;storesthecodefortheprintintegercallinto$v0
syscall;Executessystemcall
Instruction:
break
type:
RType
Instruction:
sync
type:
RType
Instruction:
cache
type:
RType
Instruction:
pref
type:
RType
Pseudoinstructions
TheMIPSinstructionsetisverysmall,sotodomorecomplicatedtasksweneedtoemployassembler
macroscalledpseudoinstructions.
ListofPseudoinstructions
ThefollowingisalistofthestandardMIPSinstructionsthatareimplementedaspseudoinstructions:
blt
bgt
ble
neg
not
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
26/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
bge
li
la
move
sge
sgt
BranchPseudoinstructions
Branchiflessthan(blt)
Thebltinstructioncompares2registers,treatingthemassignedintegers,andtakesabranchifoneregister
islessthananother.
blt$8,$9,label
translatesto
slt$1,$8,$9
bne$1,$0,label
OtherPseudoinstructions
LoadImmediate(li)
Thelipseudoinstructionloadsanimmediatevalueintoaregister.
li$8,0x3BF20
translatesto
lui$8,0x0003
ori$8,$8,0xBF20
Move(move)
Themovepseudoinstructionmovesthecontentsofoneregisterintoanotherregister.
move$1,$2
translatesto
add$1,$2,$0
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
27/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
LoadAddress(la)
la$a0,address
translatesto
lui$at,4097(0x1001upper16bitsof$at).
ori$a0,$at,disp
wheretheimmediate(disp)isthenumberofbytesbetweenthefirstdatalocation(always0x10010000)
andtheaddressofthefirstbyteinthestring.
RegisterFile
Registers
MIPShas32generalpurposeregistersandanother32floatingpointregisters.Registersallbeginwitha
dollarsymbol($).Thefloatingpointregistersarenamed$f0,$f1,...,$f31.Thegeneralpurposeregisters
havebothnamesandnumbers,andarelistedbelow.WhenprogramminginMIPSassembly,itisusually
besttousetheregisternames.
Number
Name
Comments
$0
$zero
Alwayszero
$1
$at
Reservedforassembler
$2,$3
$v0,$v1
Firstandsecondreturnvalues,respectively
$4,...,$7
$a0,...,$a3 Firstfourargumentstofunctions
$t8,$t9
Moretemporaryregisters
$26,$27
$k0,$k1
Reservedforkernel(operatingsystem)
$28
$gp
Globalpointer
$29
$sp
Stackpointer
$30
$fp
Framepointer
$31
$ra
Returnaddress
ZeroRegister
Thezeroregister($zeroor$0)alwayscontainsavalueof0.Itisbuiltintothehardwareandtherefore
cannotbemodified.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
28/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
$atRegister
The$at(AssemblerTemporary)registerisusedfortemporaryvalueswithinpseudocommands.Itisnot
preservedacrossfunctioncalls.Forexample,withthe(slt$at,$a0,$s2)command,$atissettooneif$a0is
lessthan$t2,otherwiseitissettozero.
$vRegisters
The$vRegistersareusedforreturningvaluesfromfunctions.Theyarenotpreservedacrossfunctioncalls.
ArgumentRegisters
The$aregistersareusedforpassingargumentstofunctions.Theyarenotpreservedacrossfunctioncalls.
Temporaries
Thetemporaryregistersareusedbytheassemblerorassemblylanguageprogrammertostoreintermediate
values.Theyarenotpreservedacrossfunctioncalls.
SavedTemporaries
SavedTemporaryregistersareusedtostorelongerlastingvalues.Theyarepreservedacrossfunctioncalls.
$kRegisters
ThekregistersarereservedforusebytheOSkernel.
PointerRegisters
GlobalPointer($gp)
StackPointer($sp)Usedtostorethevalueofthestackpointer.
FramePointer($fp)Usedtostorethevalueoftheframepointer.
ReturnAddress($ra)Storesthereturnaddress(thelocationintheprogramthatafunctionneedsto
returnto).
AllPointerRegistersarepreservedaccrossfunctioncalls.
Exceptions
Thispageisgoingtotalkaboutexceptionhandling.Wewillalsotalkaboutwhatexceptionsare,andwhat
causesthem.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
29/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
ExceptionControlRegisters
ExceptionCodes
HandlingExceptions
Resources
Resourcesand
Licensing
Wikimedia
Resources
wikipedia:assembler
Programming:C
C++
OperatingSystemDesign
EmbeddedSystems
ReverseEngineering
MicroprocessorDesign
PSPProgrammingthePSPrunsMIPSassemblylanguage.
ExternalResources
ReverseEngineeringforBeginners(includingMIPSassembly)DennisYurichevfreeonlinebook
(http://beginners.re/RE_for_beginnersen.pdf).
AprogrammedIntroductiontoMIPSAssembly
(http://chortle.ccsu.edu/AssemblyTutorial/index.html)
OVPsimVirtualPlatformSimulator(http://www.ovpworld2.org/mips)
ASoftwareMIPSSimulator(http://xavier.perseguers.ch/programmation/mipsassembler.html)
SPIM:MIPSSimulator(http://www.cs.wisc.edu/~larus/spim.html)
PattersonandHennessy,ComputerOrganizationandDesign:TheHardware/SoftwareInterface,3rd
Edition.Elsevier,2005.ISBN1558606941
Paul,RichardP.SPARCArchitecture,AssemblyLanguageProgramming,andC,2ndEdition,
PrenticeHall,2000.ISBN0130255963
http://www.cs.tau.ac.il/~afek/MipsInstructionSetReference.pdf(theMIPS32instructionset)
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
30/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
Licensing
Thetextofthisbookisreleasedunderthefollowinglicense:
Permissionisgrantedtocopy,distributeand/ormodifythisdocumentunderthetermsoftheGNU
FreeDocumentationLicense,Version1.2oranylaterversionpublishedbytheFreeSoftware
FoundationwithnoInvariantSections,noFrontCoverTexts,andnoBackCoverTexts.Acopy
ofthelicenseisincludedinthesectionentitled"GNUFreeDocumentationLicense."
GNUFreeDocumentationLicense
Version1.3,3November2008Copyright(C)2000,2001,2002,2007,2008FreeSoftwareFoundation,Inc.
<http://fsf.org/>
Everyoneispermittedtocopyanddistributeverbatimcopiesofthislicensedocument,butchangingitis
notallowed.
0.PREAMBLE
ThepurposeofthisLicenseistomakeamanual,textbook,orotherfunctionalandusefuldocument"free"
inthesenseoffreedom:toassureeveryonetheeffectivefreedomtocopyandredistributeit,withorwithout
modifyingit,eithercommerciallyornoncommercially.Secondarily,thisLicensepreservesfortheauthor
andpublisherawaytogetcreditfortheirwork,whilenotbeingconsideredresponsibleformodifications
madebyothers.
ThisLicenseisakindof"copyleft",whichmeansthatderivativeworksofthedocumentmustthemselves
befreeinthesamesense.ItcomplementstheGNUGeneralPublicLicense,whichisacopyleftlicense
designedforfreesoftware.
WehavedesignedthisLicenseinordertouseitformanualsforfreesoftware,becausefreesoftwareneeds
freedocumentation:afreeprogramshouldcomewithmanualsprovidingthesamefreedomsthatthe
softwaredoes.ButthisLicenseisnotlimitedtosoftwaremanualsitcanbeusedforanytextualwork,
regardlessofsubjectmatterorwhetheritispublishedasaprintedbook.WerecommendthisLicense
principallyforworkswhosepurposeisinstructionorreference.
1.APPLICABILITYANDDEFINITIONS
ThisLicenseappliestoanymanualorotherwork,inanymedium,thatcontainsanoticeplacedbythe
copyrightholdersayingitcanbedistributedunderthetermsofthisLicense.Suchanoticegrantsaworld
wide,royaltyfreelicense,unlimitedinduration,tousethatworkundertheconditionsstatedherein.The
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
31/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
"Document",below,referstoanysuchmanualorwork.Anymemberofthepublicisalicensee,andis
addressedas"you".Youacceptthelicenseifyoucopy,modifyordistributetheworkinawayrequiring
permissionundercopyrightlaw.
A"ModifiedVersion"oftheDocumentmeansanyworkcontainingtheDocumentoraportionofit,either
copiedverbatim,orwithmodificationsand/ortranslatedintoanotherlanguage.
A"SecondarySection"isanamedappendixorafrontmattersectionoftheDocumentthatdeals
exclusivelywiththerelationshipofthepublishersorauthorsoftheDocumenttotheDocument'soverall
subject(ortorelatedmatters)andcontainsnothingthatcouldfalldirectlywithinthatoverallsubject.(Thus,
iftheDocumentisinpartatextbookofmathematics,aSecondarySectionmaynotexplainany
mathematics.)Therelationshipcouldbeamatterofhistoricalconnectionwiththesubjectorwithrelated
matters,oroflegal,commercial,philosophical,ethicalorpoliticalpositionregardingthem.
The"InvariantSections"arecertainSecondarySectionswhosetitlesaredesignated,asbeingthoseof
InvariantSections,inthenoticethatsaysthattheDocumentisreleasedunderthisLicense.Ifasectiondoes
notfittheabovedefinitionofSecondarythenitisnotallowedtobedesignatedasInvariant.TheDocument
maycontainzeroInvariantSections.IftheDocumentdoesnotidentifyanyInvariantSectionsthenthereare
none.
The"CoverTexts"arecertainshortpassagesoftextthatarelisted,asFrontCoverTextsorBackCover
Texts,inthenoticethatsaysthattheDocumentisreleasedunderthisLicense.AFrontCoverTextmaybe
atmost5words,andaBackCoverTextmaybeatmost25words.
A"Transparent"copyoftheDocumentmeansamachinereadablecopy,representedinaformatwhose
specificationisavailabletothegeneralpublic,thatissuitableforrevisingthedocumentstraightforwardly
withgenerictexteditorsor(forimagescomposedofpixels)genericpaintprogramsor(fordrawings)some
widelyavailabledrawingeditor,andthatissuitableforinputtotextformattersorforautomatictranslation
toavarietyofformatssuitableforinputtotextformatters.AcopymadeinanotherwiseTransparentfile
formatwhosemarkup,orabsenceofmarkup,hasbeenarrangedtothwartordiscouragesubsequent
modificationbyreadersisnotTransparent.AnimageformatisnotTransparentifusedforanysubstantial
amountoftext.Acopythatisnot"Transparent"iscalled"Opaque".
ExamplesofsuitableformatsforTransparentcopiesincludeplainASCIIwithoutmarkup,Texinfoinput
format,LaTeXinputformat,SGMLorXMLusingapubliclyavailableDTD,andstandardconforming
simpleHTML,PostScriptorPDFdesignedforhumanmodification.Examplesoftransparentimageformats
includePNG,XCFandJPG.Opaqueformatsincludeproprietaryformatsthatcanbereadandeditedonly
byproprietarywordprocessors,SGMLorXMLforwhichtheDTDand/orprocessingtoolsarenot
generallyavailable,andthemachinegeneratedHTML,PostScriptorPDFproducedbysomeword
processorsforoutputpurposesonly.
The"TitlePage"means,foraprintedbook,thetitlepageitself,plussuchfollowingpagesasareneededto
hold,legibly,thematerialthisLicenserequirestoappearinthetitlepage.Forworksinformatswhichdo
nothaveanytitlepageassuch,"TitlePage"meansthetextnearthemostprominentappearanceofthe
work'stitle,precedingthebeginningofthebodyofthetext.
The"publisher"meansanypersonorentitythatdistributescopiesoftheDocumenttothepublic.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
32/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
Asection"EntitledXYZ"meansanamedsubunitoftheDocumentwhosetitleeitherispreciselyXYZor
containsXYZinparenthesesfollowingtextthattranslatesXYZinanotherlanguage.(HereXYZstandsfor
aspecificsectionnamementionedbelow,suchas"Acknowledgements","Dedications","Endorsements",or
"History".)To"PreservetheTitle"ofsuchasectionwhenyoumodifytheDocumentmeansthatitremains
asection"EntitledXYZ"accordingtothisdefinition.
TheDocumentmayincludeWarrantyDisclaimersnexttothenoticewhichstatesthatthisLicenseapplies
totheDocument.TheseWarrantyDisclaimersareconsideredtobeincludedbyreferenceinthisLicense,
butonlyasregardsdisclaimingwarranties:anyotherimplicationthattheseWarrantyDisclaimersmayhave
isvoidandhasnoeffectonthemeaningofthisLicense.
2.VERBATIMCOPYING
YoumaycopyanddistributetheDocumentinanymedium,eithercommerciallyornoncommercially,
providedthatthisLicense,thecopyrightnotices,andthelicensenoticesayingthisLicenseappliestothe
Documentarereproducedinallcopies,andthatyouaddnootherconditionswhatsoevertothoseofthis
License.Youmaynotusetechnicalmeasurestoobstructorcontrolthereadingorfurthercopyingofthe
copiesyoumakeordistribute.However,youmayacceptcompensationinexchangeforcopies.Ifyou
distributealargeenoughnumberofcopiesyoumustalsofollowtheconditionsinsection3.
Youmayalsolendcopies,underthesameconditionsstatedabove,andyoumaypubliclydisplaycopies.
3.COPYINGINQUANTITY
Ifyoupublishprintedcopies(orcopiesinmediathatcommonlyhaveprintedcovers)oftheDocument,
numberingmorethan100,andtheDocument'slicensenoticerequiresCoverTexts,youmustenclosethe
copiesincoversthatcarry,clearlyandlegibly,alltheseCoverTexts:FrontCoverTextsonthefrontcover,
andBackCoverTextsonthebackcover.Bothcoversmustalsoclearlyandlegiblyidentifyyouasthe
publisherofthesecopies.Thefrontcovermustpresentthefulltitlewithallwordsofthetitleequally
prominentandvisible.Youmayaddothermaterialonthecoversinaddition.Copyingwithchangeslimited
tothecovers,aslongastheypreservethetitleoftheDocumentandsatisfytheseconditions,canbetreated
asverbatimcopyinginotherrespects.
Iftherequiredtextsforeithercoveraretoovoluminoustofitlegibly,youshouldputthefirstoneslisted(as
manyasfitreasonably)ontheactualcover,andcontinuetherestontoadjacentpages.
IfyoupublishordistributeOpaquecopiesoftheDocumentnumberingmorethan100,youmusteither
includeamachinereadableTransparentcopyalongwitheachOpaquecopy,orstateinorwitheach
Opaquecopyacomputernetworklocationfromwhichthegeneralnetworkusingpublichasaccessto
downloadusingpublicstandardnetworkprotocolsacompleteTransparentcopyoftheDocument,freeof
addedmaterial.Ifyouusethelatteroption,youmusttakereasonablyprudentsteps,whenyoubegin
distributionofOpaquecopiesinquantity,toensurethatthisTransparentcopywillremainthusaccessibleat
thestatedlocationuntilatleastoneyearafterthelasttimeyoudistributeanOpaquecopy(directlyor
throughyouragentsorretailers)ofthateditiontothepublic.
Itisrequested,butnotrequired,thatyoucontacttheauthorsoftheDocumentwellbeforeredistributingany
largenumberofcopies,togivethemachancetoprovideyouwithanupdatedversionoftheDocument.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
33/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
4.MODIFICATIONS
YoumaycopyanddistributeaModifiedVersionoftheDocumentundertheconditionsofsections2and3
above,providedthatyoureleasetheModifiedVersionunderpreciselythisLicense,withtheModified
VersionfillingtheroleoftheDocument,thuslicensingdistributionandmodificationoftheModified
Versiontowhoeverpossessesacopyofit.Inaddition,youmustdothesethingsintheModifiedVersion:
A. UseintheTitlePage(andonthecovers,ifany)atitledistinctfromthatoftheDocument,andfrom
thoseofpreviousversions(whichshould,iftherewereany,belistedintheHistorysectionofthe
Document).Youmayusethesametitleasapreviousversioniftheoriginalpublisherofthatversion
givespermission.
B. ListontheTitlePage,asauthors,oneormorepersonsorentitiesresponsibleforauthorshipofthe
modificationsintheModifiedVersion,togetherwithatleastfiveoftheprincipalauthorsofthe
Document(allofitsprincipalauthors,ifithasfewerthanfive),unlesstheyreleaseyoufromthis
requirement.
C. StateontheTitlepagethenameofthepublisheroftheModifiedVersion,asthepublisher.
D. PreserveallthecopyrightnoticesoftheDocument.
E. Addanappropriatecopyrightnoticeforyourmodificationsadjacenttotheothercopyrightnotices.
F. Include,immediatelyafterthecopyrightnotices,alicensenoticegivingthepublicpermissiontouse
theModifiedVersionunderthetermsofthisLicense,intheformshownintheAddendumbelow.
G. PreserveinthatlicensenoticethefulllistsofInvariantSectionsandrequiredCoverTextsgivenin
theDocument'slicensenotice.
H. IncludeanunalteredcopyofthisLicense.
I. PreservethesectionEntitled"History",PreserveitsTitle,andaddtoitanitemstatingatleastthe
title,year,newauthors,andpublisheroftheModifiedVersionasgivenontheTitlePage.Ifthereis
nosectionEntitled"History"intheDocument,createonestatingthetitle,year,authors,and
publisheroftheDocumentasgivenonitsTitlePage,thenaddanitemdescribingtheModified
Versionasstatedintheprevioussentence.
J. Preservethenetworklocation,ifany,givenintheDocumentforpublicaccesstoaTransparentcopy
oftheDocument,andlikewisethenetworklocationsgivenintheDocumentforpreviousversionsit
wasbasedon.Thesemaybeplacedinthe"History"section.Youmayomitanetworklocationfora
workthatwaspublishedatleastfouryearsbeforetheDocumentitself,oriftheoriginalpublisherof
theversionitreferstogivespermission.
K. ForanysectionEntitled"Acknowledgements"or"Dedications",PreservetheTitleofthesection,and
preserveinthesectionallthesubstanceandtoneofeachofthecontributoracknowledgementsand/or
dedicationsgiventherein.
L. PreservealltheInvariantSectionsoftheDocument,unalteredintheirtextandintheirtitles.Section
numbersortheequivalentarenotconsideredpartofthesectiontitles.
M. DeleteanysectionEntitled"Endorsements".SuchasectionmaynotbeincludedintheModified
version.
N. DonotretitleanyexistingsectiontobeEntitled"Endorsements"ortoconflictintitlewithany
InvariantSection.
O. PreserveanyWarrantyDisclaimers.
IftheModifiedVersionincludesnewfrontmattersectionsorappendicesthatqualifyasSecondary
SectionsandcontainnomaterialcopiedfromtheDocument,youmayatyouroptiondesignatesomeorall
ofthesesectionsasinvariant.Todothis,addtheirtitlestothelistofInvariantSectionsintheModified
Version'slicensenotice.Thesetitlesmustbedistinctfromanyothersectiontitles.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
34/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
YoumayaddasectionEntitled"Endorsements",provideditcontainsnothingbutendorsementsofyour
ModifiedVersionbyvariouspartiesforexample,statementsofpeerrevieworthatthetexthasbeen
approvedbyanorganizationastheauthoritativedefinitionofastandard.
YoumayaddapassageofuptofivewordsasaFrontCoverText,andapassageofupto25wordsasa
BackCoverText,totheendofthelistofCoverTextsintheModifiedVersion.OnlyonepassageofFront
CoverTextandoneofBackCoverTextmaybeaddedby(orthrougharrangementsmadeby)anyone
entity.IftheDocumentalreadyincludesacovertextforthesamecover,previouslyaddedbyyouorby
arrangementmadebythesameentityyouareactingonbehalfof,youmaynotaddanotherbutyoumay
replacetheoldone,onexplicitpermissionfromthepreviouspublisherthataddedtheoldone.
Theauthor(s)andpublisher(s)oftheDocumentdonotbythisLicensegivepermissiontousetheirnames
forpublicityforortoassertorimplyendorsementofanyModifiedVersion.
5.COMBININGDOCUMENTS
YoumaycombinetheDocumentwithotherdocumentsreleasedunderthisLicense,underthetermsdefined
insection4aboveformodifiedversions,providedthatyouincludeinthecombinationalloftheInvariant
Sectionsofalloftheoriginaldocuments,unmodified,andlistthemallasInvariantSectionsofyour
combinedworkinitslicensenotice,andthatyoupreservealltheirWarrantyDisclaimers.
ThecombinedworkneedonlycontainonecopyofthisLicense,andmultipleidenticalInvariantSections
maybereplacedwithasinglecopy.IftherearemultipleInvariantSectionswiththesamenamebut
differentcontents,makethetitleofeachsuchsectionuniquebyaddingattheendofit,inparentheses,the
nameoftheoriginalauthororpublisherofthatsectionifknown,orelseauniquenumber.Makethesame
adjustmenttothesectiontitlesinthelistofInvariantSectionsinthelicensenoticeofthecombinedwork.
Inthecombination,youmustcombineanysectionsEntitled"History"inthevariousoriginaldocuments,
formingonesectionEntitled"History"likewisecombineanysectionsEntitled"Acknowledgements",and
anysectionsEntitled"Dedications".YoumustdeleteallsectionsEntitled"Endorsements".
6.COLLECTIONSOFDOCUMENTS
YoumaymakeacollectionconsistingoftheDocumentandotherdocumentsreleasedunderthisLicense,
andreplacetheindividualcopiesofthisLicenseinthevariousdocumentswithasinglecopythatis
includedinthecollection,providedthatyoufollowtherulesofthisLicenseforverbatimcopyingofeachof
thedocumentsinallotherrespects.
Youmayextractasingledocumentfromsuchacollection,anddistributeitindividuallyunderthisLicense,
providedyouinsertacopyofthisLicenseintotheextracteddocument,andfollowthisLicenseinallother
respectsregardingverbatimcopyingofthatdocument.
7.AGGREGATIONWITHINDEPENDENTWORKS
AcompilationoftheDocumentoritsderivativeswithotherseparateandindependentdocumentsorworks,
inoronavolumeofastorageordistributionmedium,iscalledan"aggregate"ifthecopyrightresulting
fromthecompilationisnotusedtolimitthelegalrightsofthecompilation'susersbeyondwhatthe
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
35/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
individualworkspermit.WhentheDocumentisincludedinanaggregate,thisLicensedoesnotapplytothe
otherworksintheaggregatewhicharenotthemselvesderivativeworksoftheDocument.
IftheCoverTextrequirementofsection3isapplicabletothesecopiesoftheDocument,thenifthe
Documentislessthanonehalfoftheentireaggregate,theDocument'sCoverTextsmaybeplacedon
coversthatbrackettheDocumentwithintheaggregate,ortheelectronicequivalentofcoversifthe
Documentisinelectronicform.Otherwisetheymustappearonprintedcoversthatbracketthewhole
aggregate.
8.TRANSLATION
Translationisconsideredakindofmodification,soyoumaydistributetranslationsoftheDocumentunder
thetermsofsection4.ReplacingInvariantSectionswithtranslationsrequiresspecialpermissionfromtheir
copyrightholders,butyoumayincludetranslationsofsomeorallInvariantSectionsinadditiontothe
originalversionsoftheseInvariantSections.YoumayincludeatranslationofthisLicense,andallthe
licensenoticesintheDocument,andanyWarrantyDisclaimers,providedthatyoualsoincludetheoriginal
EnglishversionofthisLicenseandtheoriginalversionsofthosenoticesanddisclaimers.Incaseofa
disagreementbetweenthetranslationandtheoriginalversionofthisLicenseoranoticeordisclaimer,the
originalversionwillprevail.
IfasectionintheDocumentisEntitled"Acknowledgements","Dedications",or"History",therequirement
(section4)toPreserveitsTitle(section1)willtypicallyrequirechangingtheactualtitle.
9.TERMINATION
Youmaynotcopy,modify,sublicense,ordistributetheDocumentexceptasexpresslyprovidedunderthis
License.Anyattemptotherwisetocopy,modify,sublicense,ordistributeitisvoid,andwillautomatically
terminateyourrightsunderthisLicense.
However,ifyouceaseallviolationofthisLicense,thenyourlicensefromaparticularcopyrightholderis
reinstated(a)provisionally,unlessanduntilthecopyrightholderexplicitlyandfinallyterminatesyour
license,and(b)permanently,ifthecopyrightholderfailstonotifyyouoftheviolationbysomereasonable
meanspriorto60daysafterthecessation.
Moreover,yourlicensefromaparticularcopyrightholderisreinstatedpermanentlyifthecopyrightholder
notifiesyouoftheviolationbysomereasonablemeans,thisisthefirsttimeyouhavereceivednoticeof
violationofthisLicense(foranywork)fromthatcopyrightholder,andyoucuretheviolationpriorto30
daysafteryourreceiptofthenotice.
Terminationofyourrightsunderthissectiondoesnotterminatethelicensesofpartieswhohavereceived
copiesorrightsfromyouunderthisLicense.Ifyourrightshavebeenterminatedandnotpermanently
reinstated,receiptofacopyofsomeorallofthesamematerialdoesnotgiveyouanyrightstouseit.
10.FUTUREREVISIONSOFTHISLICENSE
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
36/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
TheFreeSoftwareFoundationmaypublishnew,revisedversionsoftheGNUFreeDocumentationLicense
fromtimetotime.Suchnewversionswillbesimilarinspirittothepresentversion,butmaydifferindetail
toaddressnewproblemsorconcerns.Seehttp://www.gnu.org/copyleft/.
EachversionoftheLicenseisgivenadistinguishingversionnumber.IftheDocumentspecifiesthata
particularnumberedversionofthisLicense"oranylaterversion"appliestoit,youhavetheoptionof
followingthetermsandconditionseitherofthatspecifiedversionorofanylaterversionthathasbeen
published(notasadraft)bytheFreeSoftwareFoundation.IftheDocumentdoesnotspecifyaversion
numberofthisLicense,youmaychooseanyversioneverpublished(notasadraft)bytheFreeSoftware
Foundation.IftheDocumentspecifiesthataproxycandecidewhichfutureversionsofthisLicensecanbe
used,thatproxy'spublicstatementofacceptanceofaversionpermanentlyauthorizesyoutochoosethat
versionfortheDocument.
11.RELICENSING
"MassiveMultiauthorCollaborationSite"(or"MMCSite")meansanyWorldWideWebserverthat
publishescopyrightableworksandalsoprovidesprominentfacilitiesforanybodytoeditthoseworks.A
publicwikithatanybodycaneditisanexampleofsuchaserver.A"MassiveMultiauthorCollaboration"
(or"MMC")containedinthesitemeansanysetofcopyrightableworksthuspublishedontheMMCsite.
"CCBYSA"meanstheCreativeCommonsAttributionShareAlike3.0licensepublishedbyCreative
CommonsCorporation,anotforprofitcorporationwithaprincipalplaceofbusinessinSanFrancisco,
California,aswellasfuturecopyleftversionsofthatlicensepublishedbythatsameorganization.
"Incorporate"meanstopublishorrepublishaDocument,inwholeorinpart,aspartofanotherDocument.
AnMMCis"eligibleforrelicensing"ifitislicensedunderthisLicense,andifallworksthatwerefirst
publishedunderthisLicensesomewhereotherthanthisMMC,andsubsequentlyincorporatedinwholeor
inpartintotheMMC,(1)hadnocovertextsorinvariantsections,and(2)werethusincorporatedpriorto
November1,2008.
TheoperatorofanMMCSitemayrepublishanMMCcontainedinthesiteunderCCBYSAonthesame
siteatanytimebeforeAugust1,2009,providedtheMMCiseligibleforrelicensing.
HowtousethisLicenseforyourdocuments
TousethisLicenseinadocumentyouhavewritten,includeacopyoftheLicenseinthedocumentandput
thefollowingcopyrightandlicensenoticesjustafterthetitlepage:
Copyright(c)YEARYOURNAME.
Permissionisgrantedtocopy,distributeand/ormodifythisdocument
underthetermsoftheGNUFreeDocumentationLicense,Version1.3
oranylaterversionpublishedbytheFreeSoftwareFoundation
withnoInvariantSections,noFrontCoverTexts,andnoBackCoverTexts.
Acopyofthelicenseisincludedinthesectionentitled"GNU
FreeDocumentationLicense".
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
37/38
28/2/2015
MIPSAssembly/PrintVersionWikibooks,openbooksforanopenworld
IfyouhaveInvariantSections,FrontCoverTextsandBackCoverTexts,replacethe"with...Texts."line
withthis:
withtheInvariantSectionsbeingLISTTHEIRTITLES,withthe
FrontCoverTextsbeingLIST,andwiththeBackCoverTextsbeingLIST.
IfyouhaveInvariantSectionswithoutCoverTexts,orsomeothercombinationofthethree,mergethose
twoalternativestosuitthesituation.
Ifyourdocumentcontainsnontrivialexamplesofprogramcode,werecommendreleasingtheseexamples
inparallelunderyourchoiceoffreesoftwarelicense,suchastheGNUGeneralPublicLicense,topermit
theiruseinfreesoftware.
1. JohnMasheyonRISC/CISC(http://userpages.umbc.edu/~vijay/mashey.on.risc.html)
2. RISCvs.CISC(http://wwwcsfaculty.stanford.edu/~eroberts/courses/soco/projects/2000
01/risc/risccisc/)
3. Patterson,D.A.&Ditzel,D.R.(1980).TheCasefortheReducedInstructionSetComputer.
SIGARCHComputerArchitectureNews,8(6),2533.
4. Clark,D.W.&StreckerW.D.(1980).Commentson'Thecaseforthereducedinstructionset
computer'byPattersonandDitzel.SIGARCHComputerArchitectureNews,8(6),3438.
Retrievedfrom"http://en.wikibooks.org/w/index.php?
title=MIPS_Assembly/Print_Version&oldid=2702191"
Thispagewaslastmodifiedon21September2014,at11:30.
TextisavailableundertheCreativeCommonsAttributionShareAlikeLicense.additionaltermsmay
apply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.
http://en.wikibooks.org/wiki/MIPS_Assembly/Print_Version
38/38