Yass Programming Model 2 Tutorial
Yass Programming Model 2 Tutorial
Yass Programming Model 2 Tutorial
A.Introduction
Objectives
Attheendofthislabyoushouldbeableto:
Usedirectandindirectaddressingmodesofaccessingdatainmemory
Createaniterativeloopofinstructions
DisplaytextonconsoleusinganIOinstruction
Createasubroutine,callandreturnfromsubroutine
Passparameterstoasubroutine
B.Processor(CPU)Simulators
Thecomputerarchitecturetutorialsaresupportedbysimulators,whicharecreated
tounderpintheoreticalconceptsnormallycoveredduringthelectures.The
simulatorsprovidevisualandanimatedrepresentationofmechanismsinvolvedand
enablethestudentstoobservethehiddeninnerworkingsofsystems,whichwould
bedifficultorimpossibletodootherwise.Theaddedadvantageofusingsimulators
isthattheyallowthestudentstoexperimentandexploredifferenttechnological
aspectsofsystemswithouthavingtoinstallandconfiguretherealsystems.
C.BasicTheory
Theprogrammingmodelofcomputerarchitecturedefinesthoselowlevel
architecturalcomponents,whichincludethefollowing
CPUinstructionset
CPUregisters
Differentwaysofaddressinginstructionsanddataininstructions
Italsodefinesinteractionbetweentheabovecomponents.Itisthislowlevel
programmingmodelwhichmakesprogrammedcomputationspossible.Youshould
doadditionalreadinginordertoformabetterunderstandingofthedifferentparts
ofamodernCPUarchitecture(refertotherecommendedreadinglistavailableinthe
modulehandbookandontheBB).
D.SimulatorDetails
Thissectionincludessomebasicinformationonthesimulator,whichshouldenable
thestudentstousethesimulator.Thetutor(s)willbeavailabletohelpanyone
experiencingdifficultyinusingthesimulator.Thesimulatorforthislabisan
applicationrunningonaPCrunningMSWindowsoperatingsystem.
Themainsimulatorwindowiscomposedofseveralviews,whichrepresentdifferent
functionalpartsofthesimulatedprocessor.TheseareshowninImage1belowand
arecomposedof
1
CPUInstructionmemory
SpecialCPUregisters
CPU(generalpurpose)registers
Programstack
Programcreationandrunningfeatures
Memoryinwhichdataisstored
Input,outputconsole
Image1CPUSimulatorwindow
Thepartsofthesimulatorrelevanttothislabaredescribedbelow.Pleasereadthis
informationcarefullyandtrytoidentifythedifferentpartsontheCPUSimulator
windowBEFOREattemptingthefollowingexercises.Usetheinformationinthis
sectioninconjunctionwiththeexercisesthatfollow.
2
1.CPUinstructionmemoryview
Image2Instructionmemory
view
Thisviewcontainstheprogram
instructions. The instructions
are displayed as sequences of
lowlevel instruction
mnemonics (assemblerlevel
format)andnotasbinarycode.
This is done for clarity and
makes code more readable by
humans.
Each instruction is associated
with two addresses: the
physicaladdress(PAdd)andthe
logical address (LAdd). This
view also displays the base
address (Base) against each
instruction. The sequence of
instructions belonging to the
same program will have the
samebaseaddress.
2.SpecialCPUregistersview ThisviewshowsthesetofCPUregisters,
whichhavepredefinedspecialistfunctions:
PC:ProgramCountercontainstheaddress
ofthenextinstructiontobeexecuted.
IR:InstructionRegistercontainsthe
instructioncurrentlybeingexecuted.
SR:StatusRegistercontainsinformation
pertainingtotheresultofthelastexecuted
instruction.
SP:StackPointerregisterpointstothevalue
maintainedatthetopoftheprogramstack
(seebelow).
BR:BaseRegistercontainscurrentbase
address.
MAR:MemoryAddressRegistercontains
thememoryaddresscurrentlybeing
Image3SpecialCPU accessed.
registersview Statusbits:OV:Overflow;Z:Zero;N:
Negative
3
3.CPUregistersview
Image4 CPURegistersview
4
4.Programstackview
Image5Programstackview
Theprogramstackisanotherareawhich
maintains temporary values as the
instructions are executed. The stack is a
LIFO(lastinfirstout)datastructure.Itis
often used for efficient interrupt
handling and subroutine calls. Each
programhasitsownindividualstack.
TheCPUinstructionsPSH(push)andPOP
are used to store values on top of stack
and pop values from top of stack
respectively.
5.Programlistview
Image6 ProgramListView
6.Programcreation
Image7 Createprogramtab
Tocreateanewprogramenterits
nameintheProgramNamebox
anditsbaseaddressintheBase
AddressboxthenclickontheADD
button.Thenewprogramsname
willappearintheProgramListview
(seeImage6).
5
Image8Addprogram
instructionstab
7.Programdatamemoryview
Image9Programdatamemoryview
6
TheCPUinstructionsthataccessthatpartofthememorycontainingdatacanwrite
orreadthedatainaddressedlocations.Thisdatacanbeseeninthememorypages
windowshowninImage9above.YoucandisplaythiswindowbyclickingtheSHOW
PROGRAMDATAMEMORYbuttonshowninImage6above.TheLadd(logical
address)columnshowsthestartingaddressofeachlineinthedisplay.Eachlineof
thedisplayrepresents8bytesofdata.ColumnsB0throughtoB7representbytes0
to7oneachline.TheDatacolumnshowsthedisplayablecharacterscorresponding
tothe8bytes.Thosebytesthatcorrespondtonondisplayablecharactersareshown
asdots.Thedatabytesaredisplayedinhexformatonly.Forexample,inImage9,
therearenonzerodatabytesinaddresslocations19and37.Thesedatabytes
correspondtodisplayablecharacterscapitalAandB.
Tochangethevaluesofanybytes,firstselecttheline(s)containingthebytes.Then
usetheinformationintheInitializeDataframetomodifythevaluesofthebytesin
theselectedline(s)asInteger,BooleanorStringformats.Youneedtoclickthe
UPDATEbuttontomakethechange.
8.IOconsoleview
Image10Input,outputconsoleview
Image10aboveshowstheconsolewhichisusedbyprogramstowritemessagesto
andreaddatafrom.ItcanbedisplayedbyclickingontheINPUTOUTPUTbutton
showninImage1above.ClickontheSHOWKEYBDbuttontodisplayasmall
keyboardwindowwhichcanbeusedtoinputdatatoprogramsrequestinginput.
7
E. Lab Exercises - Investigate and Explore
Thelabexercisesareaseriesofactivities,whicharecarriedoutbythestudents
underbasicguidelines.So,howisthistutorialconducted?Thestudentsareexpected
tofollowtheinstructionsgiveninordertoidentifyandlocatetherequired
information,toactuponit,makenotesoftheirobservationsandofferexplanations
fortheseobservationswherethisrequested.Inordertobeabletodothese
activitiesyoushouldconsulttheinformationinSectionDaboveandalsofrequently
refertotheAppendixforinformationonvariousCPUinstructionsyouwillbeasked
tocreateanduse.Remember,youneedtocarefullyreadandunderstandthe
instructionsbeforeyouattempteachactivity.
Now,letusstart.FirstyouneedtoplacesomeinstructionsintheInstruction
MemoryView(seeImage2),representingtheRAMintherealmachine,before
executinganyinstructions.Todothis,followthestepsbelow:
IntheProgramtab(seeImage7),firstenteraProgramName,andthenenteraBase
Address(thiscanbeanynumber,butforthisexerciseuse100).ClickontheADD
button.AnewprogramnamewillbeenteredintheProgramListview(seeImage6).
YoucanusetheSAVEbuttontosaveinstructionsinafile.Youcanalsousethe
LOADbuttontoloadinstructionsfromafile.
YouarenowreadytoenterinstructionsintotheCPUSimulator.Youdothisby
clickingontheADDNEWbuttonintheInstructionstab(seeImage8).Thiswill
displaytheInstructions:CPU0window.Youusethiswindowtoselectandenterthe
CPUinstructions.Appendixlistssomeoftheinstructionsthissimulatorusesandalso
givesexamplesoftheirusage.
Now,haveagoatthefollowingactivities(enteryouranswersinthetextboxes
provided).Awordofcaution:Regularlysaveyourcodeinafileincasethesimulator
crashesinwhichcaseyoucanrestartthesimulatorandreloadyourfile.
8
1. IntheAppendixattheendofthisdocument,locatetheinstruction,whichis
usedtostoreonebyteofdatainamemorylocation.Useittostorenumber65in
addresslocation20(allnumbersareindecimal).Thisisanexampleofdirect
addressing.RefertoImage9toseehowtodisplaythecontentsofdatamemory.
Makeanotebelowoftheinstructionused:
2. Createaninstructiontomovedecimalnumber22toregisterR01andmakea
noteofitbelow.ExecutethisinstructionandverifytheresultinR01.
3. Createaninstructiontostoredecimalnumber51inmemorylocationthe
addressofwhichiscurrentlystoredinregisterR01.Thisisanexampleofindirect
addressing.Notetheuseofthe@prefixnexttoR01inthiscase.
4. Makeanoteofwhatyouseeindatamemorylocations20and22(refertoImage
9forhelpinformationonhowtodisplaythedatamemory).
5. Now,letscreatealoop.First,enterthefollowingcode.The#prefixisusedto
denotealiteralvaluethusdistinguishingitfromanaddressvaluewhichdoesnot
useit.R01representsanarbitraryregister;youcanuseanyoftheregistersfrom
R00toR31.
MOV #0, R01
ADD #1, R01
CMP #5, R01
JNE 0
HLT
6. Theabovecodeisnotquitereadyyet.TheJNEinstructionusesanumericvalue
astheaddresstojumpto.Inthiscaseitis0.Thismaynotalwaysbethecaseso
inordertomakethecodemoreflexiblewecanuselabelstorepresent
instructionaddresses.Thesimulatorallowsyoutodothis.Followthe
instructionsbelowforthis:
HighlighttheaboveMOVinstruction(i.e.theoneintheboxabove)
ClickontheINSERTBELOWbutton
9
TypelabelnameL0intheboxnexttotheENTERLABELbuttoninthe
windowyouusetoenterinstructions
ClicktheENTERLABELbutton
Thenewcodeshouldnowlooklikethis(modificationsareinredcolour):
MOV #0, R01
L0:
ADD #1, R01
CMP #5, R01
JNE 0
HLT
Next,highlighttheJNEinstruction
ClickontheEDITbutton
SelectL0inthedropdownlistundertheSourceOperandsectionbutton
inthewindowyouusetoenterinstructions
ClicktheEDITbutton
Thenewcodeshouldnowlooklikethis:
7. Asyoucansee,thelabelL0representstheaddressoftheinstruction
immediatelybelowit,i.e.theADDinstruction.SonowtheJNEinstructioncan
useL0astheaddresstojumpto.AsthelabelL0canrepresentanyaddressthis
codeshouldworkanywhereinmemorymakingitveryflexible.The$sign
indicatesthatL0isalabel.Theabovecodeisnowreadytorun.Torunthis
program,followtheinstructionsbelow:
ClickontheRESETPROGRAMbuttonintheCPUSimulatorwindow
HighlighttheMOVinstruction,i.e.thefirstinstructionoftheprogram
Adjustthespeedslidertoavalue,say,nearesttothevalue80
ClickontheRUNbutton
Afterashortwhiletheprogramshouldstop.Ifitappearstoruntoolong
thenclickontheSTOPbuttonandcheckyourcode.Correctitifnecessary
andrepeattheaboveinstructionsonceagain.
WhentheprogramstopsmakeanoteofthevalueinR01below
8. Nowyoullmakeaslightmodificationtotheaboveprogram.Changethe
programcodesothattheprogramloopisrepeatedaslongasthevalueofR01is
lessthanorequalto3(youmaywishtorefertotheAppendixforthis)andtest
10
it.WhenyougetitrightmakeanoteofthevalueinR01andcopythenewcode
below.Now,changethemodifiedinstructionsbacktotheoriginalinstructions
(youcanusetheUNDObuttonforthisseeImage8above).
9. Ok,letscreateasimplesubroutine.Enterthefollowingnewcode.Youneedto
createanewlabelL1atthestartofthesubroutine.Thislabelrepresentsthe
startingaddressofthesubroutine.YoumustenterthelabelusingtheENTER
LABELbuttononlyasexplainedin(6).Also,makesureyouselecttheDirectMem
radiobuttonwhenenteringthefirstoperandvalue24oftheOUTinstruction:
L1:
OUT 24, 0
RET
10. Theabovesubroutinecodesimplydisplaysthetextstartingatdatamemory
location24andreturns(seeRETinstructioninappendix).Forittoworkthere
needstobesometextindataaddresslocation24.Youcandothismanuallyby
followingthestepsbelow:
ClickontheSHOWPROGRAMDATAMEMORYbutton(seeImage6).
Inthedisplayedwindowhighlighttheline0024underLAddcolumn
UnderInitialiseDataclickontheStringradiobutton
EntersometextinthetextboxlabelledValue,e.g.MynameisBesim
ClicktheUPDATEbutton
11. Now,asubroutineisofnousebyitself.Forittobeusefulyourprogrammustcall
itusingtheinstructionsMSFfollowedbyCAL(refertotheAppendix).TheMSF
(MarkStackFrame)isneededtoreserveaplaceforthereturnaddressonthe
programstack.TheCALinstructionneedstospecifythestartingaddressofthe
calledsubroutine.Letsmodifyourcodesothatwhentheabovesubroutineis
calleditdisplaysthetextrepeatedlyinaloop.Forexample,usingthecodeadded
in(6)and(9)themodifiedprogramshouldlooksomethinglikethis:
MOV #0, R01
L0:
ADD #1, R01
MSF
CAL $L1
CMP #5, R01
JNE $L0
HLT
L1:
OUT 24, 0
RET
11
12. Theabovecodeisnowreadytorun.Inordertoseethedisplayedtextyouneed
toshowtheconsolewindow.ClickontheINPUTOUTPUTbutton(seeImage1)
whichwilldisplaythesimulatedconsolewindow.Torunthisprogram,followthe
instructionsbelow:
ClickontheRESETPROGRAMbutton
HighlighttheMOVinstruction,i.e.thefirstinstructionoftheprogram
Adjustthespeedslidertoavaluenearesttothevalue80
ClickontheRUNbutton
13. Weneedtomakeasmallchangetooursubroutine.CurrentlytheOUT
instructionusesdirectmemoryaddressing,i.e.thememoryaddress24ispartof
theinstruction.Wenowwishtomakeituseindirectaddressinginawaysimilar
tothatin(3).So,youllneedtoplacethememoryaddress24inaregister(any
spareregister).ThenyouneedtohavetheOUTinstructionusethisregister
indirectlyasthesourceoftheaddressofthetexttodisplay.Runthecodetotest
yourmodification.Makeanoteofthemodifiedpartoftheprogramcodebelow.
UsetheUNDObuttontorestoretheinstructionsbeforethismodification:
14. Ok,letsgetalittlebitmoreambitiousasachallenge.Letsconverttheloopinto
anothersubroutineandthencallit.So,nowwewillhavetwosubroutineswhere
onecallstheother.Thefollowingcoderepresentsthischange.Noticethatthe
HLTinstructionischangedtotheRETinstructionandthenewinstructionsMSF,
CALandHLTareaddedtogetherwiththenewlabelL2atthetopofthecode.
CAL$L2callsthesubroutinewiththeloopandCAL$L1callsthesubroutinethat
displaysthetext.
MSF
CAL $L2
HLT
L2:
MOV #0, R01
L0:
ADD #1, R01
MSF
CAL $L1
CMP #5, R01
JNE $L0
RET
L1:
OUT 24, 0
RET
Now,firstresettheprogramthenhighlightthefirstMSFinstruction.Runthe
programandverifytheresultintheconsolewindowasbefore.
12
15. Whystophere!Letsmakeitabitmoreinteresting.Theabovecodewilldothe
loop5timesandthisnumberisfixed.Forflexibilitywecanpassthenumberof
loopsasaparametertothesubroutine(startingatlabelL2).Forthiswewilluse
thePSHandPOPinstructions(seetheAppendix).Modifyyourcodetolooklike
theonebelowandrunitobservingthedisplaysontheconsole:
MSF
PSH #8
CAL $L2
HLT
L2:
POP R02
MOV #0, R01
L0:
ADD #1, R01
MSF
CAL $L1
CMP
R02, R01
JNE $L0
RET
L1:
OUT 24, 0
RET
16. Examinetheabovecodeandbrieflyexplainhowtheparameterpassingworks:
17. Finally,asarealchallenge,modifytheabovecodesothatasecondparameteris
passedtothesubroutine(startingatlabelL2)inthesamewayasthefirst
parameterispassed.ThesecondparameterisusedtoinitialisetheregisterR01
tothevalueofthissecondparameter.Copythemodifiedcodeonlytothepoint
ofthelastmodificationintheboxbelow:
13
AppendixSimulatorInstructionSubset
Inst Description
Datatransferinstructions
Movedatatoregister;moveregistertoregister
MOV e.g.
MOV#2,R01movesnumber2intoregisterR01
MOVR01,R03movescontentsofregisterR01intoregisterR03
Loadabytefrommemorytoregister
LDB e.g.
LDB1022,R03loadsabytefrommemoryaddress1022intoR03
LDB@R02,R05loadsabytefrommemorytheaddressofwhichisinR02
LDW Loadaword(2bytes)frommemorytoregister
SameasinLDBbutaword(i.e.2bytes)isloadedintoaregister
Storeabytefromregistertomemory
STB STBR07,2146storesabytefromR07intomemoryaddress2146
STBR04,@R08storesabytefromR04intomemoryaddressofwhichisin
R08
STW Storeaword(2bytes)fromregistertomemory
SameasinSTBbutaword(i.e.2bytes)isloadedstoredinmemory
Pushdatatotopofhardwarestack(TOS);pushregistertoTOS
PSH e.g.
PSH#6pushesnumber6ontopofthestack
PSHR03pushesthecontentsofregisterR03ontopofthestack
Popdatafromtopofhardwarestacktoregister
e.g.
POP POPR05popscontentsoftopofstackintoregisterR05
Note:IfyoutrytoPOPfromanemptystackyouwillgettheerrormessage
Stackunderflow.
Arithmeticinstructions
Addnumbertoregister;addregistertoregister
e.g.
ADD ADD#3,R02addsnumber3tocontentsofregisterR02andstoresthe
resultinregisterR02.
ADDR00,R01addscontentsofregisterR00tocontentsofregisterR01
andstorestheresultinregisterR01.
SUB Subtractnumberfromregister;subtractregisterfromregister
MUL Multiplynumberwithregister;multiplyregisterwithregister
DIV Dividenumberwithregister;divideregisterwithregister
Controltransferinstructions
Jumptoinstructionaddressunconditionally
JMP e.g.
JMP100unconditionallyjumpstoaddresslocation100wherethereis
anotherinstruction
14
JLT Jumptoinstructionaddressiflessthan(afterlastcomparison)
JGT Jumptoinstructionaddressifgreaterthan(afterlastcomparison)
Jumptoinstructionaddressifequal(afterlastcomparisoninstruction)
e.g.
JEQ JEQ200jumpstoaddresslocation200ifthepreviouscomparison
instructionresultindicatesthatthetwonumbersareequal,i.e.theZ
statusflagisset(theZboxwillbecheckedinthiscase).
JNE Jumptoinstructionaddressifnotequal(afterlastcomparison)
MarkStackFrameinstructionisusedinconjunctionwiththeCAL
instruction.
MSF e.g.
MSFreserveaspaceforthereturnaddressonprogramstack
CAL1456savethereturnaddressinthereservedspaceandjumpto
subroutineinaddresslocation1456
Jumptosubroutineaddress(savesthereturnaddressonprogramstack)
CAL ThisinstructionisusedinconjunctionwiththeMSFinstruction.Youll
needanMSFinstructionbeforetheCALinstruction.Seetheexample
above
RET Returnfromsubroutine(usesthereturnaddressonstack)
SWI Softwareinterrupt(usedtorequestOShelp)
HLT Haltsimulation
Comparisoninstruction
Comparenumberwithregister;compareregisterwithregister
e.g.
CMP#5,R02comparenumber5withthecontentsofregisterR02
CMPR01,R03comparethecontentsofregistersR01andR03
CMP Note:
IfR01=R03thenthestatusflagZwillbeset,i.e.theZboxischecked.
IfR03>R01thennonofthestatusflagswillbeset,i.e.noneofthestatus
flagboxesarechecked.
IfR01>R03thenthestatusflagNwillbeset,i.e.theNstatusboxis
checked.
Input,outputinstructions
IN Getinputdata(ifavailable)fromanexternalIOdevice
OutputdatatoanexternalIOdevice
OUT e.g.
OUT16,0outputscontentsofdatainlocation16totheconsole(the
secondparametermustalwaysbea0)
15