You are on page 1of 34

MARS - Mips Assembly and Runtime Simulator

Release 4.3
January 2013
1. Introduction
MARS, the Mips Assembly and Runtime Simulator, will assemble and simulate the
execution of MIPS assembly language programs. It can be used either from a command
line or through its integrated development environment I!"#. MARS is written in $ava
and re%uires at least Release &.' of the $(S" $ava Runtime "nvironment $R"# to wor). It
is distributed as an executable $AR file. *he MARS home page is
http://www.cs.missouristate.edu/MARS/. *his document is available for printing
there.
As of Release +.,, MARS assembles and simulates &'' basic instructions of the MIPS-.(
instruction set, approximately ./, pseudo-instructions or instruction variations, the &/
syscall functions mainly for console and file I01 defined by SPIM, and an additional ((
syscalls for other uses such as MI!I output, random number generation and more. *hese
are listed in separate help tabs. It supports seven different memory addressing modes for
load and store instructions2 label, immed, label+immed, ($reg), label($reg),
immed($reg), and label+immed($reg), where immed is an integer up to .( bits. A
setting is available to disallow use of pseudo-instructions and extended instruction
formats and memory addressing modes.
1ur guiding reference in implementing the instruction set has been Computer
Organization and Design, Fourth Edition by Patterson and 3ennessy, "lsevier - Morgan
4aufmann, (,,5. It summari6es the MIPS-.( instruction set and pseudo-instructions in
7igures ..(+ and ..(' on pages (/5-(8&, with details provided in the text and in
Appendix 9. MARS Releases ..( and above implement all the instructions in Appendix
9 and those figures except the delay branches from the left column of 7igure ..('. It also
implements all the system services syscalls# and assembler directives documented in
Appendix 9.
*he MARS I!" provides program editing and assembling but its real strength is its
support for interactive debugging. *he programmer can easily set and remove execution
brea)points or step through execution forward or bac)ward undo# while viewing and
directly editing register and memory contents.
Page &
2. Coni!uration Settin!s
Releases .., and later include a Settings menu. *he "ditor and "xception 3andler items
launch a dialog but the rest are each controlled by a chec)box for selecting or deselecting
it chec)ed means true, unchec)ed means false#. Settings and their default values are2
&. "isplay t#e $abels %indo% in t#e &'ecute tab. !efault value is alse. If
selected, the :abels window, which shows the name and associated address for
each label defined in the program, will be displayed to the right of the *ext
Segment.
(. (ro)ide pro!ram ar!uments to t#e MI(S pro!ram. !efault value is alse. ;ew
in Release ..'. If selected, a text field will appear at the top of the *ext Segment
!isplay. Any argument values in this text field at the time of program execution
will be stored in MIPS memory prior to execution. *he argument count argc# will
be placed in register <a,, and the address of an array of null-terminated strings
containing the arguments argv# will be placed in register <a&. *hese values are
also available on the runtime stac) <sp#.
.. (opup "ialo! or input syscalls *+,-,.,/,120. ;ew in Release +.,. !efault value
is alse. If selected, runtime console input will be entered using popup dialogs
this was the only option prior to Release +.,#. 1therwise, input is entered directly
into the Run I01 tab at the bottom of the screen.
+. "isplay memory addresses in #e'adecimal. !efault value is true. If deselected,
addresses will be displayed in decimal. *his setting can also be toggled in a
chec)box on the lower border of the !ata Segment =indow.
'. "isplay memory and re!ister contents in #e'adecimal. !efault value is true. If
deselected, vlaues will be displayed in decimal. *his setting can also be toggled in
a chec)box on the lower border of the !ata Segment =indow.
>. Assemble a ile automatically as soon as it is opened, and initiali6e the 7ile
1pen dialog with the most-recently opened file. !efault value is alse. *his is
convenient if you use an external editor for composing your programs.
/. Assemble applies to all iles in directory. !efault value is alse. If selected, the
file currently open in the editor will become the ?main? program in a multi-file
assemble-and-lin) operation involving all assembly files @.asmA @.s# in its
directory. If successful, execution will begin with the currently open file.
8. Assembler %arnin!s are considered errors. !efault value is alse. ;ew in
Release ..'. If selected, the assemble operation will fail if any warnings are
produced. At this time, all assembler warnings relate to unrecogni6ed or ignored
directives. MARS may be able to assemble code produced by compilers for other
MIPS assemblers if this setting is deselected.
5. Initiali1e (ro!ram Counter to !lobal 2main2 i deined. !efault value is alse.
;ew in Release ..8. If selected, the Program Bounter will be initiali6ed to the
address of the text segment statement with the global label CmainC if it exists. If it
does not exist or if the setting is not selected, the Program Bounter will be
initiali6ed to the default text segment starting address.
Page (
&,. (ermit pro!rams to use e'tended *pseudo0 instructions and ormats. !efault
value is true. *his includes all memory addressing modes other than the MIPS
native mode &> bit constant offset added to register content#.
&&. Assemble and e'ecute pro!rams usin! delayed branc#in!. !efault value is
alse. MIPS processors use delayed branches as part of the pipelined design, but it
can be confusing to programmers. =ith delayed branching, the instruction
following a branch or Dump instruction will always be executed even if the branch
condition is trueE Assemblers and, failing that, programmers, often deal with this
by following branches and Dumps with a ?nop? instruction. *he MARS assembler
does not insert a nop. =hen delayed branching was introduced in Release ..., the
machine code generated for a branch instruction depended on this setting since its
target value is relative to the Program Bounter PC-relative addressing#. Although
technically correct, this led to confusion in the MARS community because the
generated code did not match textboo) examples. Starting with Release ..+, the
relative branching offset is always calculated as if delayed branching is enabled
even when it is not. *he runtime simulation adDusts accordingly.
&(. 3#e &ditor dialo!. Fse it to view and modify editor font settings. ;ew with
Release ....
&.. 3#e 4i!#li!#tin! dialo!. Fse it to modify color and font settings for the
highlighting of table items in the *ext Segment window, !ata Segment window,
Registers window, Boprocessor, window and Boprocessor& window.
3ighlighting occurs during timed, stepped, and bac)stepped simulation. Bolor and
font for normal non-highlighted# display can also be set separately for even-
numbered and odd-numbered display rows but not individually by windows. ;ew
with Release ..>.
&+. 3#e &'ception 4andler dialo!. It has the setting2 Include this exception handler
in all assemble operations. !efault value is alse. If selected, a button to browse to
the desired file is enabled. ;ew with Release ..(
&'. 3#e Memory Coni!uration dialo!. Fse it to select from among available MIPS
address space configurations. *he default configuration is derived from SPIMA it
was only one available from MARS &., through MARS ..>. ;ew with Release
../.
9eginning with Release ..(, settings are retained from one interactive session to the next.
Settings are stored in a system-dependent way as specified by
java.util.prefs.Preferences. =indows systems use the Registry. *hese settings are
independent of command options given when using MARS from a command lineA neither
affects the other. =e anticipate future releases will include additional settings and
preferences.
Page .
3. S5SCA$$ unctions a)ailable in MARS
3.1. Introduction
A number of system services, mainly for input and output, are available for use by your
MIPS program. *hey are described in the table below.
MIPS register contents are not affected by a system call, except for result registers as
specified in the table below.
3.2. 4o% to use S5SCA$$ system ser)ices
Step &. :oad the service number in register <v,.
Step (. :oad argument values, if any, in <a,, <a&, <a(, or <f&( as specified.
Step .. Issue the SGSBA:: instruction.
Step +. Retrieve return values, if any, from result registers as specified.
&'ample6 display t#e )alue stored in 7t0 on t#e console
li $v0, 1 # service 1 is print integer
add $a0, $t0, $zero # load desired value into argument register
# $a0, using pseudoop
s!scall
3.3. 3able o A)ailable Ser)ices
Ser)ice
Code
in 7)0
Ar!uments Result
print integer & <a, H integer to print
print float ( <f&( H float to print
print double .
<f&( H double to
print

print string +
<a, H address of
null-terminated
string to print

read integer ' <v, contains integer read
read float > <f, contains float read
read double / <f, contains double read
read string 8
<a, H address of
input buffer
<a& H maximum
number of characters
to read
ee note below table
sbr) allocate heap
memory#
5
<a, H number of
bytes to allocate
<v, contains address of allocated
memory
exit terminate &,
Page +
execution#
print character &&
<a, H character to
print
ee note below table
read character &( <v, contains character read
open file &.
<a, H address of
null-terminated
string containing
filename
<a& H flags
<a( H mode
<v, contains file descriptor negative
if error#. ee note below table
read from file &+
<a, H file descriptor
<a& H address of
input buffer
<a( H maximum
number of characters
to read
<v, contains number of characters
read , if end-of-file, negative if
error#. ee note below table
write to file &'
<a, H file descriptor
<a& H address of
output buffer
<a( H number of
characters to write
<v, contains number of characters
written negative if error#. ee note
below table
close file &> <a, H file descriptor
exit( terminate with
value#
&/
<a, H termination
result
ee note below table
ervices ! through !" are compatible with the P#$ simulator, other than Open File %!&'
as described in the (otes below the table) ervices &* and higher are exclusive to $+,)
time system time# .,
<a, H low order .( bits of system
time
<a& H high order .( bits of system
time. ee note below table
MI!I out .&
<a, H pitch ,-&(/#
<a& H duration in
milliseconds
<a( H instrument ,-
&(/#
<a. H volume ,-
&(/#
Ienerate tone and return
immediately. ee note below table
sleep .( <a, H the length of
time to sleep in
milliseconds.
Bauses the MARS $ava thread to
sleep for at least# the specified
number of milliseconds. *his timing
will not be precise, as the $ava
implementation will add some
Page '
overhead.
MI!I out synchronous ..
<a, H pitch ,-&(/#
<a& H duration in
milliseconds
<a( H instrument ,-
&(/#
<a. H volume ,-
&(/#
Ienerate tone and return upon tone
completion. ee note below table
print integer in
hexadecimal
.+ <a, H integer to print
!isplayed value is 8 hexadecimal
digits, left-padding with 6eroes if
necessary.
print integer in binary .' <a, H integer to print
!isplayed value is .( bits, left-
padding with 6eroes if necessary.
print integer as
unsigned
.> <a, H integer to print
!isplayed as unsigned decimal
value.
not used# ./-.5
set seed +,
<a, H i.d. of
pseudorandom
number generator
any int#.
<a& H seed for
corresponding
pseudorandom
number generator.
;o values are returned. Sets the seed
of the corresponding underlying $ava
pseudorandom number generator
java.util."andom#. ee note
below table
random int +&
<a, H i.d. of
pseudorandom
number generator
any int#.
<a, contains the next pseudorandom,
uniformly distributed int value from
this random number generatorCs
se%uence. ee note below table
random int range +(
<a, H i.d. of
pseudorandom
number generator
any int#.
<a& H upper bound of
range of returned
values.
<a, contains pseudorandom,
uniformly distributed int value in the
range , JH KintL J Kupper boundL,
drawn from this random number
generatorCs se%uence. ee note below
table
random float +.
<a, H i.d. of
pseudorandom
number generator
any int#.
<f, contains the next pseudorandom,
uniformly distributed float value in
the range ,., JH f J &., from this
random number generatorCs
se%uence. ee note below table
random double ++ <a, H i.d. of
pseudorandom
number generator
<f, contains the next pseudorandom,
uniformly distributed double value in
the range ,., JH f J &., from this
Page >
any int#.
random number generatorCs
se%uence. ee note below table
not used# +'-+5
Bonfirm!ialog ',
<a, H address of
null-terminated
string that is the
message to user
<a, contains value of user-chosen
option
,2 Ges
&2 ;o
(2 Bancel
Input!ialogInt '&
<a, H address of
null-terminated
string that is the
message to user
<a, contains int read
<a& contains status value
,2 14 status
-&2 input data cannot be correctly
parsed
-(2 Bancel was chosen
-.2 14 was chosen but no data had
been input into field
Input!ialog7loat '(
<a, H address of
null-terminated
string that is the
message to user
<f, contains float read
<a& contains status value
,2 14 status
-&2 input data cannot be correctly
parsed
-(2 Bancel was chosen
-.2 14 was chosen but no data had
been input into field
Input!ialog!ouble '.
<a, H address of
null-terminated
string that is the
message to user
<f, contains double read
<a& contains status value
,2 14 status
-&2 input data cannot be correctly
parsed
-(2 Bancel was chosen
-.2 14 was chosen but no data had
been input into field
Input!ialogString '+ <a, H address of
null-terminated
string that is the
message to user
<a& H address of
input buffer
<a( H maximum
number of characters
to read
ee ervice - note below table
<a& contains status value
,2 14 status. 9uffer contains the
input string.
-(2 Bancel was chosen. ;o change to
buffer.
-.2 14 was chosen but no data had
been input into field. ;o change to
buffer.
-+2 length of the input string
exceeded the specified maximum.
9uffer contains the maximum
Page /
allowable input string plus a
terminating null.
Message!ialog ''
<a, H address of
null-terminated
string that is the
message to user
<a& H the type of
message to be
displayed2
,2 error message,
indicated by "rror
icon
&2 information
message, indicated
by Information icon
(2 warning message,
indicated by =arning
icon
.2 %uestion message,
indicated by
Muestion icon
other2 plain message
no icon displayed#
;0A
Message!ialogInt '>
<a, H address of
null-terminated
string that is an
information-type
message to user
<a& H int value to
display in string form
after the first string
;0A
Message!ialog7loat '/
<a, H address of
null-terminated
string that is an
information-type
message to user
<f&( H float value to
display in string form
after the first string
;0A
Message!ialog!ouble '8 <a, H address of
null-terminated
string that is an
information-type
message to user
<f&( H double value
;0A
Page 8
to display in string
form after the first
string
Message!ialogString '5
<a, H address of
null-terminated
string that is an
information-type
message to user
<a& H address of
null-terminated
string to display after
the first string
;0A
893&S6 Ser)ices numbered 30 and #i!#er are not pro)ided by S(IM
Ser)ice / - 7ollows semantics of F;IN CfgetsC. 7or specified length n, string can be no
longer than n-&. If less than that, adds newline to end. In either case, then pads with null
byte If n H &, input is ignored and null byte placed at buffer address. If n J &, input is
ignored and nothing is written to the buffer.
Ser)ice 11 - Prints ASBII character corresponding to contents of low-order byte.
Ser)ice 13 - MARS implements three flag values2 , for read-only, & for write-only with
create, and 5 for write-only with create and append. It ignores mode. *he returned file
descriptor will be negative if the operation failed. *he underlying file I01 implementation
uses java.io.#ile$nput%tream.read() to read and
java.io.#ile&utput%tream.'rite() to write. MARS maintains file descriptors
internally and allocates them starting with .. 7ile descriptors ,, & and ( are always open
for2 reading from standard input, writing to standard output, and writing to standard error,
respectively new in release +..#.
Ser)ices 13,14,1+ - In MARS ../, the result register was changed to <v, for SPIM
compatability. It was previously <a, as erroneously printed in Appendix 9 of Computer
Organization and Design,.
Ser)ice 1. - If the MIPS program is run under control of the MARS graphical interface
IFI#, the exit code in <a, is ignored.
Ser)ice 30 - System time comes from java.util.(ate.get)ime() as milliseconds
since & $anuary &5/,.
Ser)ices 31,33 - Simulate MI!I output through sound card. !etails below.
Ser)ices 40-44 use underlying $ava pseudorandom number generators provided by the
java.util."andom class. "ach stream identified by <a, contents# is modeled by a
different "andom obDect. *here are no default seed values, so use the Set Seed service +,#
if replicated random se%uences are desired.
3.4. &'ample o :ile I;9
*he sample MIPS program below will open a new file for writing, write text to it from a
memory buffer, then close it. *he file will be created in the directory in which MARS
was run.
# %ample *$P% program t+at 'rites to a ne' file.
# b! ,ennet+ -ollmar and Pete %anderson
Page 5
.data
fout. .asciiz /testout.t0t/ # filename for output
buffer. .asciiz /)+e 1uic2 bro'n fo0 jumps over t+e laz! dog./
.te0t
###############################################################
# &pen (for 'riting) a file t+at does not e0ist
li $v0, 13 # s!stem call for open file
la $a0, fout # output file name
li $a1, 1 # &pen for 'riting (flags are 0. read, 1. 'rite)
li $a4, 0 # mode is ignored
s!scall # open a file (file descriptor returned in $v0)
move $s5, $v0 # save t+e file descriptor
###############################################################
# 6rite to file just opened
li $v0, 17 # s!stem call for 'rite to file
move $a0, $s5 # file descriptor
la $a1, buffer # address of buffer from '+ic+ to 'rite
li $a4, 88 # +ardcoded buffer lengt+
s!scall # 'rite to file
###############################################################
# 9lose t+e file
li $v0, 15 # s!stem call for close file
move $a0, $s5 # file descriptor to close
s!scall # close file
###############################################################
3.+. <sin! S5SCA$$ system ser)ices 31 and 336 MI"I output
*hese system services are uni%ue to MARS, and provide a means of producing sound.
MI!I output is simulated by your system sound card, and the simulation is provided by
the java0.sound.midi pac)age.
Service .& will generate the tone then immediately return. Service .. will generate the
tone then sleep for the toneCs duration before returning. *hus it essentially combines
services .& and .(.
*his service re%uires four parameters as follows2
pitc# *7a00
Accepts a positive byte value ,-&(/# that denotes a pitch as it would be represented in
MI!I
"ach number is one semitone 0 half-step in the chromatic scale.
, represents a very low B and &(/ represents a very high I a standard 88 )ey piano
begins at 5-A and ends at &,8-B#.
If the parameter value is outside this range, it applies a default value >, which is the
same as middle B on a piano.
7rom middle B, all other pitches in the octave are as follows2
>& H BO or !b
>( H !
>. H !O or "b
>' H "O or 7
>> H 7O or Ib
>/ H I
>5 H A
/, H AO or 9b
/& H 9 or Bb
Page &,
>+ H " or 7b >8 H IO or Ab /( H 9O or B
*o produce these pitches in other octaves, add or subtract multiples of &(.
duration in milliseconds *7a10
Accepts a positive integer value that is the length of the tone in milliseconds.
If the parameter value is negative, it applies a default value of one second &,,,
milliseconds#.
instrument *7a20
Accepts a positive byte value ,-&(/# that denotes the Ieneral MI!I ?patch? used to play
the tone.
If the parameter is outside this range, it applies a default value , which is an +coustic
.rand Piano.
Ieneral MI!I standardi6es the number associated with each possible instrument often
referred to as program change numbers#, however it does not determine how the tone will
sound. *his is determined by the synthesi6er that is producing the sound. *hus a /uba patch
'8# on one computer may sound different than that same patch on another computer.
*he &(8 available patches are divided into instrument families of 82
,-/ Piano >+-/& Reed
8-&' Bhromatic Percussion /(-/5 Pipe
&>-(. 1rgan 8,-8/ Synth :ead
(+-.& Iuitar 88-5' Synth Pad
.(-.5 9ass 5>-&,. Synth "ffects
+,-+/ Strings &,+-&&& "thnic
+8-'' "nsemble &&(-&&5 Percussion
'>->. 9rass &(,-&(/ Sound "ffects
;ote that outside of $ava, Ieneral MI!I usually refers to patches &-&(8. =hen referring
to a list of Ieneral MI!I patches, & must be subtracted to play the correct patch. 7or a full
list of Ieneral MI!I instruments, see www.midi.org0about-midi0gm0gm&sound.shtml. *he
Ieneral MI!I channel &, percussion )ey map is not relevant to the toneIenerator method
because it always defaults to MI!I channel &.
)olume *7a30
Accepts a positive byte value ,-&(/# where &(/ is the loudest and , is silent. *his value
denotes MI!I velocity which refers to the initial attac) of the tone.
If the parameter value is outside this range, it applies a default value &,,.
MI!I velocity measures how hard a note on or note o00# message is played, perhaps on a
MI!I controller li)e a )eyboard. Most MI!I synthesi6ers will translate this into volume on a
logarithmic scale in which the difference in amplitude decreases as the velocity value
increases.
;ote that velocity value on more sophisticated synthesi6ers can also affect the timbre of
the tone as most instruments sound different when they are played louder or softer#.
System service .& was developed and documented by 1tterbein student *ony 9roc) in
$uly (,,/.
Page &&
4. <sin! MARS t#rou!# its Inte!rated "e)elopment &n)ironment
*I"&0
*he I!" is invo)ed when MARS is run with no command arguments, e.g. java jar
mars.jar. It may also be launched from a graphical interface by double-clic)ing the
mars.jar icon that represents this executable $AR file. *he I!" provides basic editing,
assembling and execution capabilities. 3opefully it is intuitive to use. 3ere are comments
on some features.
Menus and 3oolbar2 Most menu items have e%uivalent toolbar icons. If the
function of a toolbar icon is not obvious, Dust hover the mouse over it and a tool
tip will soon appear. ;early all menu items also have )eyboard shortcuts. Any
menu item not appropriate in a given situation is disabled.
&ditor2 MARS includes two integrated text editors. *he default editor, new in
Release +.,, features syntax-aware color highlighting of most MIPS language
elements and popup instruction guides. *he original, generic, text editor without
these features is still available and can be selected in the "ditor Settings dialog. It
supports a single font which can be modified in the "ditor Settings dialog. *he
bottom border of either editor includes the cursor line and column position and
there is a chec)box to display line numbers. *hey are displayed outside the
editing area. If you use an external editor, MARS provides a convenience setting
that will automatically assemble a file as soon as it is opened. See the Settings
menu.
Messa!e Areas2 *here are two tabbed message areas at the bottom of the screen.
*he ,un #1O tab is used at runtime for displaying console output and entering
console input as program execution progresses. Gou have the option of entering
console input into a pop-up dialog then echoes to the message area. *he $+,
$essages tab is used for other messages such as assembly or runtime errors and
informational messages. Gou can clic) on assembly error messages to select the
corresponding line of code in the editor.
MI(S Re!isters2 MIPS registers are displayed at all times, even when you are
editing and not running a program. =hile writing your program, this serves as a
useful reference for register names and their conventional uses hover mouse over
the register name to see tool tips#. *here are three register tabs2 the Register 7ile
integer registers <, through <.& plus :1, 3I and the Program Bounter#, selected
Boprocesor , registers exceptions and interrupts#, and Boprocessor & floating
point registers.
Assembly2 Select +ssemble from the ,un menu or the corresponding toolbar icon
to assemble the file currently in the "dit tab. Prior to Release ..&, only one file
could be assembled and run at a time. Releases ..& and later provide a primitive
ProDect capability. *o use it, go to the ettings menu and chec) +ssemble
operation applies to all 0iles in current directory) Subse%uently, the assembler will
assemble the current file as the ?main? program and also assemble all other
assembly files @.asmA @.s# in the same directory. *he results are lin)ed and if all
these operations were successful the program can be executed. :abels that are
declared global with the ?.globl? directive may be referenced in any of the other
files in the proDect. *here is also a setting that permits automatic loading and
Page &(
assembly of a selected exception handler file. MARS uses the MIPS.( starting
address for exception handlers2 ,x8,,,,&8,.
&'ecution2 1nce a MIPS program successfully assembles, the registers are
initiali6ed and three windows in the "xecute tab are filled2 /ext egment, Data
egment, and Program 2abels. *he maDor execution-time features are described
below.
$abels =indo%2 !isplay of the :abels window symbol table# is controlled
through the Settings menu. =hen displayed, you can clic) on any label or its
associated address to center and highlight the contents of that address in the *ext
Segment window or !ata Segment window as appropriate.
*he assembler and simulator are invo)ed from the I!" when you select the +ssemble,
.o, or tep operations from the ,un menu or their corresponding toolbar icons or
)eyboard shortcuts. MARS messages are displayed on the $+, $essages tab of the
message area at the bottom of the screen. Runtime console input and output is handled in
the ,un #1O tab.
+. Interacti)e "ebu!!in! :eatures
MARS provides many features for interactive debugging through its "xecute pane.
7eatures include2
In tep mode, the next instruction to be simulated is highlighted and memory
content displays are updated at each step.
Select the .o option if you want to simulate continually. It can also be used to
continue simulation from a paused step, brea)point, pause# state.
9rea)points are easily set and reset using the chec) boxes next to each instruction
displayed in the *ext Segment window. (ew in ,elease &)-3 Gou can temporarily
suspend brea)points using *oggle 9rea)points in the Run menu or by clic)ing the
?9)pt? column header in the *ext Segment window. Repeat, to re-activate.
=hen running in the .o mode, you can select the simulation speed using the Run
Speed slider. Available speeds range from .,' instructions per second (, seconds
between steps# up to ., instructions per second, then above this offers an
?unlimited? speed. =hen using ?unlimited? speed, code highlighting and memory
display updating are turned off while simulating but it executes really fastE#.
=hen a brea)point is reached, highlighting and updating occur. Run speed can be
adDusted while the program is running.
=hen running in the .o mode, you can pause or stop simulation at any time using
the Pause or top features. *he former will pause execution and update the
display, as if you were stepping or at a brea)point. *he latter will terminate
execution and display final memory and register values. If running at ?unlimited?
speed, the system may not respond immediately but it will respond.
Gou have the ability to interactively step ?bac)ward? through program execution
one instruction at a time to ?undo? execution steps. It will buffer up to (,,, of the
most recent execution steps this limit is stored in a properties file and can be
changed#. It will undo changes made to MIPS memory, registers or condition
Page &.
flags, but not console or file I01. *his should be a great debugging aid. It is
available anytime execution is paused and at termination even if terminated due
to exception#.
=hen program execution is paused or terminated, select ,eset to reset all memory
cells and registers to their initial post-assembly values. In fact, Reset is
implemented by re-assembling the program.
Memory addresses and values, and register values, can be viewed in either
decimal or hexadecimal format. All data are stored in little-endian byte order
each word consists of byte . followed by byte ( then & then ,#. ;ote that each
word can hold + characters of a string and those + characters will appear in the
reverse order from that of the string literal.
!ata segment contents are displayed '&( bytes at a time with scrolling# starting
with the data segment base address ,x&,,&,,,,#. ;avigation buttons are
provided to change the display to the next section of memory, the previous, or
bac) to the initial home# range. A combo box is also provided to view memory
contents in the vicinity of the stac) pointer contents of MIPS <sp register#, global
pointer contents of MIPS <gp register#, the heap base address ,x&,,+,,,,#,
.extern globals ,x&,,,,,,,#, the )ernel data segment ,x5,,,,,,,#, or memory-
mapped I1 MMI1, ,x7777,,,,#.
Bontents of any data segment memory word and almost any MIPS register can be
modified by editing its displayed table cell. !ouble-clic) on a cell to edit it and
press the "nter )ey when finished typing the new value. If you enter an invalid
.(-bit integer, the word I;PA:I! appears in the cell and memory0register
contents are not affected. Palues can be entered in either decimal or hexadecimal
leading ?,x?#. ;egative hexadecimal values can be entered in either twoCs
complement or signed format. ;ote that three of the integer registers 6ero,
program counter, return address# cannot be edited.
Bontents of cells representing floating point registers can be edited as described
above and will accept valid hexadecimal or decimal floating point values. Since
each double-precision register overlays two single-precision registers, any
changes to a double-precision register will affect one or both of the displayed
contents of its corresponding single-precision registers. Bhanges to a single-
precision register will affect the display of its corresponding double-precision
register. Palues entered in hexadecimal need to conform to I"""-/'+ format.
Palues entered in decimal are entered using decimal points and "-notation e.g.
&(.'e. is &(.' times &, cubed#.
Bell contents can be edited during program execution and once accepted will
apply starting with the next instruction to be executed.
Blic)ing on a :abels window entry will cause the location associated with that
label to be centered and highlighted in the *ext Segment or !ata Segment window
as appropriate. ;ote the :abels window is not displayed by default but can be by
selecting it from the Settings menu.
Reerence2http200courses.missouristate.edu0)envollmar0mars0help0Mars3elpIntro.html
Page &+
An Assembly Language I.D.E. To Engage Students Of All Levels
* A Tutorial *
Pete anderson, Otterbein College, Panderson4otterbein)edu
5en 6ollmar, $issouri tate 7niversity, 5en6ollmar4missouristate)edu
MARS is a software simulator for the MIPS assembly language intended for educational
use. =e will explore the capabilities of MARS release ..(.& in this three part tutorial.
MARS may be downloaded from '''.cs.missouristate.edu:*;"%.
(art 1 6 >asic MARS <se
*he example program is Fibonacci.asm to compute everyoneQs favorite number
se%uence.
&. Start MARS from the Start menu or des)top icon.
(. Fse the menubar 7ileR1pen or the 1pen icon to open 7ibonacci.asm in the
default folder. %+ll icons have menubar e8uivalents9 the remainder o0 these steps will
use the icon whenever possible)'
.. *he provided assembly program is complete. Assemble the program using the icon
+. Identify the location and values of the programQs initiali6ed data. Fse the chec)box to
toggle the display format between decimal and hexadecimal .
*he nineteen-element array fibs is initiali6ed to 6ero, at addresses ,x&,,&,,,,
R ,x&,,&,,+8.
*he data location size has value &5ten at ,x&,,&,,+c.
*he addresses ,x&,,&,,', R ,x&,,&,,>c contain null-terminated ASBII strings.
Fse the chec)box to toggle the display format between decimal and hexadecimal,
.
'. Fse the Settings menu to configure the MARS displays. *he settings will be retained
for the next MARS session.
Page &'
*he :abels display contains the addresses of the assembly code statements with a
label, but the default is to not show this display. Select the chec)box from the
Settings menu.
Select your preference for allowing pseudo-instructions programmer-friendly
instruction substitutions and shorthand#.
Select your preference for assembling only one file, or many files together all the
files in the current folder#. *his feature is useful for subroutines contained in
separate files, etc.
Select the startup display format of addresses and values decimal or
hexadecimal#.
>. :ocate the Registers display, which shows the .( common MIPS registers. 1ther tabs
in the Registers display show the floating-point registers Boproc &# and status codes
Boproc ,#.
/. Fse the slider bar to change the run speed to about &, instructions per second.
*his allows us to Swatch the actionT instead of the
assembly program finishing directly.
8. Bhoose how you will execute the program2
*he icon runs the program to completion. Fsing this icon, you should
observe the yellow highlight showing the programQs progress and the values of the
7ibonacci se%uence appearing in the !ata Segment display.
*he icon resets the program and simulator to initial values. Memory
contents are those specified within the program, and register contents are
generally 6ero.
*he icon is Ssingle-step.T Its complement is , Ssingle-step bac)wardsT
undoes each operation#.
5. 1bserve the output of the program in the Run I01 display window2
The Fibonacci numbers are:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
-- program is finished running --
&,. Modify the contents of memory. Modifying a register value is exactly the same.#
Set a brea)point at the first instruction of the subroutine which prints results. Fse
the chec)box at the left of the instruction whose address is ,x,,+,,,>, H
+&5++,,ten.
Page &>

Reset and re-run the program, which stops at the brea)point.
!ouble-clic) in one of the memory locations containing the computed 7ibonacci
numbers. *he cell will be highlighted and will accept )eyboard entry, similar to a
spreadsheet. "nter some noticeably different value, and use the "nter )ey or clic)
outside the cell to indicate that the change is complete. Example3 $emory address
*x!**!**:* ; :<-=*!*:> ten presently contains data *x******:: ; &> ten)
Blic) to continue from the brea)point. *he program output includes your
entered value instead of the computed 7ibonacci number.
&&. 1pen the 3elp for information on MIPS instructions, pseudoinstructions,
directives, and syscalls.
&(. Modify the program so that it prompts the user for the 7ibonacci se%uence length.
Select the "dit tab in the upper right to return to the program editor.
*he MIPS comment symbol is O. All characters on the line after the character O
are ignored.
Fn-comment lines &(-&5. *he newly exposed program fragment will prompt the
user for the length of the 7ibonacci se%uence to generate, in the range &5 ( x .
*he length of the se%uence must be limited to the si6e of the declared space for
result storage.#
!etermine the correct syscall parameter to perform Sread integerT from the user,
and insert the parameter at line *he correct syscall parameter may be found at
3elp R Syscall tabRread integer service. *he completed line will have the
form li $v! "# where in this case +( is not the right answer#.
Reset and re-run the program. *he program will stop at the brea)point
you inserted previously. Bontinue and finish with .
Page &/
(art 2 6 MARS 3ools
Gou may have noticed that MARS has a 3ools menu. *he capabilities provided through
this menu really catapult MARS into a different league of computer science educational
software.
=e call each of the items in the *ools menu a MARS *ool. A MARS *ool is best
described as a pop-up application that observes MIPS memory and0or register activity
during MIPS program execution then communicates that activity to the tool user to serve
a particular purpose. *his is best seen by example.
MARS 3ools Acti)ity 1 6 Runnin! t#e "ata Cac#e Simulator tool
&. Blose any MIPS programs you are currently using.
(. 1pen the program row$ma%or.asm from the <0amples folder. *his program
will traverse a &> by &> element integer matrix in row-maDor order, assigning
elements the values , through ('' in order. It performs the following algorithm2

for (ro' = 0> ro' ? 15> ro'++)
for (col = 0> col ? 15> col++)
data@ro'A@colA = value++>
.. Assemble the program.
+. 7rom the 3ools menu, select "ata Cac#e Simulator. A new frame will appear in the
middle of the screen.
Page &8
*his is a MARS *ool that will simulate the use and performance of cache memory
when the underlying MIPS program executes. ;otice its three maDor sections2
Cache Organization3 Gou can use the combo boxes to specify how the cache
will be configured for this run. 7eel free to explore the different settings, but
the default is fine for now.
Cache Per0ormance3 =ith each memory access during program execution,
the simulator will determine whether or not that access can be satisfied from
cache and update the performance display accordingly.
/ool Control3 *hese buttons perform generic control functions as described
by their labels.
'. Blic) the toolCs Connect to MI(S button. *his causes the tool to register as an
observer of MIPS memory and thus respond during program execution.
>. 9ac) in MARS, adDust the Run Speed slider to ., instructions per second. It is
located at the right side of the toolbar. *his slows execution so you can watch the
Bache Performance animation.
/. In MARS, run the program using the Run toolbar button , the menu item or
)eyboard shortcut. =atch the Bache Performance animate as it is updated with every
access to MIPS memory.
8. ?hat was the 0inal cache hit rate@ UUUUUUUUUUUUU. =ith each miss, a bloc) of +
words are written into the cache. In a row-maDor traversal, matrix elements are
accessed in the same order they are stored in memory. *hus each cache miss is
followed by . hits as the next . elements are found in the same cache bloc). *his is
followed by another miss when !irect Mapping maps to the next cache bloc), and the
patterns repeats itself. So . of every + memory accesses will be resolved in cache.
5. Iiven that explanation, what do you predict the hit rate will be i0 the blocA size is
increased 0rom > words to - words@ UUUUUUUUUUUUUU. Decreased 0rom > words to :
words@ UUUUUUUUUUU.
&,. Perify your predictions by modifying the bloc) si6e and re-running the program from
step /.
(O/E3 when you modify the Bache 1rgani6ation, the performance values are
automatically reset you can always use the toolCs Reset button#.
(O/E3 Gou have to reset the MIPS program before you can re-run it.
(O/E3 7eel free to adDust the Run Speed slider to maximum speed anytime you
want.
Page &5
&&. Repeat steps ( through &, for program column$ma%or.asm from the <0amples
folder. *his program will traverse a &> by &> element integer matrix in column-maDor
order, assigning elements the values , through ('' in order. It performs the following
algorithm2

for (col = 0> col ? 15> col++)
for (ro' = 0> ro' ? 15> ro'++)
data@ro'A@colA = value++>
(O/E3 Gou can leave the Bache Simulator in place, move it out of the way, or close
it. It will not interfere with the actions needed to open, assemble, or run this new
program and will remain connected to MIPS memory. If you do not close the tool,
then s)ip steps + and '.
&(. ?hat was the cache per0ormance 0or this program@ UUUUUUUUUUUU. *he problem is
the memory locations are now accessed not se%uentially as before, but each access is
&> words beyond the previous one circularly#. =ith the settings weCve used, no two
consecutive memory accesses occur in the same bloc) so every access is a miss.
&.. Bhange the bloc) si6e to &>. ;ote this will reset the tool.
&+. Breate a second instance of the Bache Simulator by once again selecting "ata Cac#e
Simulator from the 3ools menu. AdDust the two frames so you can view both at the
same time. Bonnect the new tool instance to MIPS, change its bloc) si6e to &> and
change its number of bloc)s to &>.
&'. Re-run the program. ?hat is the cache per0ormance o0 the original tool instance@
UUUUUUUUUUUU. 9loc) si6e &> didnCt help because there was still only one access to
each bloc), the initial miss, before that bloc) was replaced with a new one. ?hat is
the cache per0ormance o0 the second tool instance@ UUUUUUUUUUUU. At this point, the
entire matrix will fit into cache and so once a bloc) is read in it is never replaced.
1nly the first access to a bloc) results in a miss.
In what courses might an exercise li)e this one be useful for your studentsV I have used a
variation on this exercise as a student exercise in 1perating Systems, and for a lecture
illustration of the cache concept in 1tterbeinCs BS , course, ?*he Scope of Bomputer
Science?.
Page (,
MARS 3ools Acti)ity 2 6 Runnin! t#e Cac#e Simulator as a stand-alone
&. In command mode, traverse to the directory containing Mars.Dar and enter the
command2
java classpat+ *ars.jar mars.tools.9ac+e%imulator
(. *he cache simulator tool is launched. Its *ool Bontrol section is replaced by
Application Bontrol, which contains additional controls for loading, assembling and
running MIPS programs. It uses MARSC MIPS assembler and runtime simulator in
the bac)ground to control MIPS execution.
.. Blic) the 9pen MI(S pro!ram button and a 7ile 1pen dialog will pop up. 9rowse
to and select a MIPS program to run. Select row&ma%or.asm again if you wish.
+. *he Assemble and Run button is now enabled. Blic) it to assemble and run the
program. *he animation will be very rapid.
'. Fse the Run Speed slider to adDust the running speed, clic) the Reset button then
clic) Assemble and Run again. =hile the program is running, the Stop button is
enabled. Program status is updated in the single line text field.
=e plan to implement a small MARS *ool Suite application to simplify the selection and
launching of tools such as the Bache Simulator that are capable of running outside the
MARS integrated development environment.
Page (&
MARS 3ools Acti)ity 3 6 3#e Memory Reerence ?isuali1ation tool
&. 1pen the program row$ma%or.asm from the <0amples folder if it is not already
open.
(. Assemble the program.
.. 7rom the 3ools menu, select Memory Reerence ?isuali1ation. A new frame will
appear in the middle of the screen.
*his tool will paint a grid unit each time the corresponding MIPS memory word is
referenced. *he base address, the first static data segment .data directive# word,
corresponds to the upper-left grid unit. Address correspondence continues in row-
maDor order left to right, then next row down#.
*he color depends on the number of times the word has been referenced. 9lac) is ,,
blue is &, green is (, yellow is . and +, orange is ' through 5, red is &, or higher.
Piew the scale using the toolQs slider control. Gou can change the color but not the
reference count# by clic)ing on the color patch.
+. Blic) the toolCs Connect to MI(S button. *his causes the tool to register as an
observer of MIPS memory and thus respond during program execution.
'. 9ac) in MARS, adDust the Run Speed slider to ., instructions per second.
Page ((
>. Run the program. =atch the tool animate as it is updated with every access to MIPS
memory. Feel 0ree to stop the program at any time)
/. 3opefully you observed that the animation se%uence corresponded to the expected
memory access se%uence of the row-maDor.asm program. #0 you have trouble seeing
the blue, reset the tool, move the slider to position &, change the color to something
brighter, and re-run.
8. Repeat steps ( through /, for column$ma%or.asm. Gou should observe that the
animation se%uence corresponded to the expected memory access se%uence of this
program.
5. Repeat again for fibonacci.asm to observe the animated pattern of memory
references. AdDust the run speed and re-run if necessary.
&,. %Optional' Breate a new instance of the !ata Bache Simulator. Move the two frames
around so you can see both. Bonnect the cache simulator to MIPS and reset the
Memory Reference Pisuali6ation. Re-run the program. *his exercise illustrates that
two different tools can be used simultaneously.
*he Memory Reference Pisuali6ation tool could be useful in an operating systems course
to illustrate spatial and temporal locality and memory reference patterns in general.
Page (.
(art 3 6 &'tendin! MARS Capabilities
Our session today is not long enough 0or interactive activities in this area, but weBll
provide you with enough detail that you can pursue them on your own i0 you desire)
Abstract
MARS can be customi6ed and extended in four different ways2 &# writing new MARS
*ools, (# writing new MIPS system calls, .# writing new MIPS pseudo-instructions, and
+# writing new MIPS basic instructions. *echni%ues for all four are described here.
Gou have the ability to extend and customi6e certain MARS capabilities to ma)e it more
useful in your courses. *his document describes four different techni%ues for extending
MARS capabilities2
&. Ability to write MARS *ools for inclusion in the *ools menu and stand-alone use.
(. Ability to define and add new system calls for subse%uent use by MIPS programs.
.. Ability to customi6e the instruction set by adding, removing or modifying pseudo
macro# instruction specifications.
+. Ability to customi6e the basic instruction set by adding, removing or modifying
basic instruction specifications.
*hese procedures apply to MARS ..(.&, released $anuary (,,/. Some may be
streamlined in future releases.
*he ability to define and plug in new MARS *ools will be used to develop new learning
aids for students in a variety of computer science courses and provide micro-worlds for
assembly language students to target in their proDects. *hrough those tools it is possible
to deeply engage students in both settings.
*he ability to modify the set of system calls, basic instructions, and pseudo-instructions
can be used to define a complete instruction set for an alternative RISB architecture.
MARS was not designed with this in mind however, so support is uneven. 7or example,
instruction syntax analysis and code generation is driven by the example and template
provided with each instruction, whereas lexical analysis such as the recognition of
register names is embedded in program logic and cannot easily be modified. A
customi6ed instruction set has to use MIPS conventions for labeling, register naming, and
so forth. 3opefully MARS can be refactored in future releases to facilitate its use for
alternative instruction sets.
Page (+
1. =ritin! your o%n MARS 3ool and plu!!in! it into MARS
Abstract
If you thin) MARS *ools li)e the Bache Simulator are cool then why not develop your
ownV *here are two different ways to do so2 &# write a class that implements the
Mars*ool interface and is launched from the *ools menu in MARS, or (# write a class
that extends the AbstractMars*oolAndApplication class and runs either from the *ools
menu or as a free-standing application. Gou can also write a free-standing application
that uses the Mars API.
*his section describes two different techni%ues for developing your own MARS *ool.
&. =rite a class that implements the mars.tools.Mars'ool interface and )eep
it in the mars.tools pac)age. It will automatically be added to the 3ools menu
the next time MARS is run and launched when its menu item is selected.
(. =rite a class that extends
mars.tools.AbstractMars'oolAndApplication and )eep it in the
mars.tools pac)age. It will automatically be added to the 3ools menu the
next time MARS is run and launched when its menu item is selected. It can also
be launched from outside MARS as a free-standing $ava application that uses the
Mars API to control the assembly and execution of MIPS programs.
It is also possible to write your own application from scratch using the Mars API. *his
should be considered only for very speciali6ed applications and should be underta)en
with great care. *he ;bstract*ars)ool;nd;pplication class provides full
support for assembling and running MIPS programs in the bac)ground and is the
preferred approach.
My'ool implements Mars'ool approac#
&. "xtract the MARS distribution from its $AR file. *he $AR file does not have an
outermost folder to contain everything, so youCll want to create one and extract it into
that folder.
(. !evelop your class in the mars.tools pac)age mars:tools folder#.
.. Gour class must implement the Mars'ool interface, which is in that pac)age. *his
has only two methods2 %tring getBame() to return the name to be displayed in
Page ('
its *ools menu item, and void action() which is invo)ed when that menu item
is selected by the MARS user. *hese will assure its inclusion in the *ools menu when
MARS is launched.
+. *he user interface should be based on the %ava(.swin).*+ialo) class. *he
tool interacts with simulated MIPS memory and registers through the
mars.mips.hardware.Memory and mars.mips.hardware.Re)ister
classes, both of which extend %ava.util.,bservable. *he Memory class
provides several add1bserver# methods that permit an 1bserver to register for
selected memory addresses or ranges. $avadoc-produced documentation is available
in the doc folder of the MARS distribution.
'. After successful compilation, MARS will automatically include the new tool in its
*ools menu.
My'ool e(tends AbstractMars'oolAndApplication approac#
A better alternative is to extend the AbstractMars'oolAndApplication class,
which is also in the mars.tools pac)age. 9y doing so, you get the following elements2
ability to run either from the *ools menu or as a free-standing application
basic user interface $!ialog with *ool Bontrol section for tools#
basic user interface $7rame with Application Bontrol section for applications#
basic user interface layout 9order:ayout# and rendering algorithm
basic MIPS memory and register observer capabilities
&. "xtract the MARS distribution from its $AR file if you have not already done so.
(. !evelop your class in the mars.tools pac)age mars:tools folder#.
.. Gour class must extend the AbstractMars'oolAndApplication abstract
class, which is in that pac)age. ;ineteen of the (& methods in this class have default
implementations.
+. !efine at least the two abstract methods2 %tring getBame() to return the toolQs
display name, and C9omponent build*ain(ispla!;rea() to construct the
central area of the toolQs graphical user interface. It will automatically be placed in
the B";*"R of a 9order:ayout, with title information to its ;1R*3 and tool control
buttons to its S1F*3. Several addAs1bserver# methods are available for
registering as a memory and0or register observer.
Page (>
'. 1verride additional methods as desired. Some do nothing by default.
>. After successful compilation, MARS will automatically include the new tool in its
*ools menu.
/. *o run it as a stand-alone application, you either need to add a main() to create the
tool obDect and call its go() method or write a short external application to do the
same.
7or a better idea of the IFI elements that come with this abstract class, launch MARS
and select Introduction to 3ools from the *ools menu.
9y extending the provided abstract class
;bstract*ars)ool;nd;pplication, you
get everything in this figure except the
scrolled C)e0t;rea displayed in the
center.
Gou build the main user interface of your
tool by defining the inherited abstract
build*ain(ispla!;rea() method. *his
method returns a C9omponent that will
automatically be displayed in the center of
the default 9order:ayout.
$avadoc-produced documentation of the
;bstract*ars)ool;nd;pplicati
on class is available in the doc folder of
the MARS distribution.
Source code files for the MARS *ools are
included together with their bytecode files
in the mars:tools folder. 7eel free to
refer to them. All MARS source files,
including tools, are included in the src
folder.
If you develop a nifty MARS *ool, feel free to send it to us and with your permission
weCll post it on the MARS web site for others to useE
Page (/
2. =ritin! a system call *syscall0 and plu!!in! it into MARS
Abstract
MIPS System calls are functions that interface with the operating system to perform I01
and related operations. *hey are accessible to MIPS assembly programs through service
numbers and the syscall instruction. MARS provides the &/ system calls documented
in Computer Organization and Design /hird Edition, but you can develop and add your
own by writing a class that implements the Syscall interface or extends the
AbstractSyscall class.
MIPS system calls perform operating system functions and input0output operations in
particular. A system call is used in MIPS assembly by loading its identifier an integer#
into register <v,, loading any re%uired arguments into registers as specified by the callCs
protocol, then issuing the syscall instruction.
MARS supports the MIPS system call specifications given in Appendix A of Patterson
and 3ennessyCs Computer Organization and Design /hird Edition. *his appendix is
freely available on the web at http://www.cs.wisc.edu/-larus/./&AppA.pdf.
MARS provides all &/ of the system calls specified there.
Page (8
MySystem0all implements Syscall approac#
&. "xtract the MARS distribution from its $AR file, if you have not done so.
(. !evelop your class in the mars.mips.instructions.syscalls pac)age
mars:mips:instructions:s!scalls folder#.
.. Gour class must implement the Syscall interface, which is in that pac)age. *his
has four methods2 %tring getBame() to return an assigned name for this
service, setBumber() and getBumber() to set and get its associated service
number, and simulate() to simulate the execution of the system call at MIPS
runtime.
+. After your class compiles successfully, it will be automatically plugged in and
available to MIPS programs the next time you launch MARS.
MySystem0all e(tends AbstractSyscall approac#
&. "xtract the MARS distribution from its $AR file, if you have not done so.
(. !evelop your class in the mars.mips.instructions.syscalls pac)age
mars:mips:instructions:s!scalls folder#.
.. Gour class must extend the AbstractSyscall class, which is in that pac)age. It
provides a constructor and defines the three %!scall getter and setter methods. *he
simulate() method is abstract so you must define that yourself.
+. After your class compiles successfully, it will be automatically plugged in and
available to MIPS programs the next time you launch MARS.
Additional Inormation
Implementation of the simulate() method may re%uire access to one or more
simulated MIPS memory and register obDects. *he pertinent classes are
mars.mips.+ard'are.*emor! and mars.mips.+ard'are."egister#ile.
Also study the source code of existing system calls. Source code files for the &/ MARS
system calls are located in the src folder. 7ollow the folder hierarchy
mars:mips:instructions:s!scalls.
Page (5
*he MARS distribution includes a text file %!scall.properties which you can edit
to override any system service number assigned in a constructor. *his allows you to
change number assignments without re-compiling any $ava source files.
*he Syscalls help page is static at this time so it will not reflect any additional system
calls or renumbering.
If you develop a nifty system call, please send it to us and with your permission weCll post
it on the MARS web site for others to accessE
=e have had philosophical discussions concerning the development of additional system
calls and so far have resisted doing so. 1n one hand, it would be very useful to have a
small library of handy functions such as random number generators available through the
syscall mechanism. 1n the other hand, such functions are not considered operating
system operations that would be performed in )ernel mode and it would be misleading to
infer such status. :et us )now what you thin)E
Page .,
3. Modiyin! t#e set o pseudo *e'tended, macro0 instructions
Abstract
*o define a new pseudo-instruction, edit the Pseudo&ps.t0t file included in the
MARS distribution. *he instruction specification is one line long and consists of a tab-
separated list containing an example usage of the instruction followed by the one or more
basic instructions that the assembler will expand it to. Fse specification language
symbols to control the substitution of program statement operands into the generated
basic instructions#.
*he MIPS instruction set includes a large number of pseudo-instructions. *hese are
instructions that follow MIPS instruction syntax specifications but are not directly
supported by the MIPS architecture. *hey are instead expanded into a se%uence of one or
more basic instructions by the assembler. 7or this reason they are sometimes called
macro instructions.
*he classic example of a pseudo-instruction is la, or load address. 3ereCs an example2
la $t0, number
where number is the label for a data item. A corresponding MIPS machine instruction
would have to include the operation code, the ' bit register number and the .( bit
address. 9ut since machine instructions are only .( bits long, this is not possible. It
re%uires two instructions.
Pseudo-instructions are provided entirely for the programmerCs convenience, and MARS
includes an assembler setting that will disallow their use.
3o modiy t#e pseudo-instruction set, ollo% t#is process6
&. "xtract the MARS distribution from its $AR file if you have not already done so.
(. "dit Pseudo&ps.t0t appropriately. "ach pseudo-instruction and its macro
expansion are specified on one line in this file. !etails below.
.. :aunch MARS and test your instruction.
Page .&
3ereCs an example specification, for the absolute )alue instruction abs
&. "xample instruction use. *his instruction ta)es two register operands. *he <& and <(
represent generic registers and are used only to generate a to)en se%uence for syntax
analysis. /here is no relationship between register re0erences in the example
instruction %item !' and register re0erences in the macro expansions %items & and >'C
(. "ach item in the specification must be separated by a single *A9 character. 1nly the
first one is pointed out but there is also a *A9 between each of the remaining items.
.. *he first instruction of the macro expansion. RI& is a formal parameter that will be
replaced by the actual first register operand of the statement being assembled. RI( is
similarly replaced by the actual second register operand of the statement being
assembled.
+. Second and third instructions of the macro expansion. Perform similar substitutions.
tatement to assemble $acro expansion
abs $t3, $t8 addu $t3, $0, $t8
bgez $t8, 4
sub $t3, $0, $t8
*his example uses the simple substitutions RI& and RI(. 1ther macro substitution
symbols are more complex, such as -D4P3 which means to substitute the low order &>
bits of the .( bit value in source operand ( after adding . to it used in the expansion of
certain unaligned loads and stores#.
*he macro substitution language is described in detail in the file itself.
If you add any pseudo-instructions, they will automatically be included in the instruction
list produced by the 3elp featureCs &'tended *pseudo0 Instructions subtab. If the
instruction specification ends with a comment on the same line O is the comment mar)er,
Dust li)e in MIPS#, that comment will be included in the list along with the example
instruction use.
Page .(
abs $1!$# addu R21!$!R2# b)ez R2#!# sub R21!$!R2#
& ( .
+
4. Modiyin! t#e set o >asic Instructions
Abstract
It is possible to modify the basic instruction set recogni6ed by MARS. *his re%uires you
to edit and re-compile the mars.mips.instructions.$nstruction%et class.
*he specification of a basic instruction includes four components2 &# an example of
instruction use, (# the instruction format W R, I, or $, .# a template for generating the .(
bit machine code from a program statement, and +# a method to simulate the execution
of that program statement.
*his is the one type of MARS extension that re%uires re-compilation of a standard MARS
source file. Specifications for the MIPS basic instruction set are contained in the
mars.mips.instructions.$nstruction%et class. "ach specification follows
the same format. 3ere is an example, for the and instruction that performs logical A;!.
instruction3ist.add4new 5asic6nstruction4
7and $1!$#!$87! 1. example use
5asic6nstructionFormat.R&F,RMA'! 2. instruction format
7ssssstttttfffff117! 3. machine code template
new Simulation0ode49 4. execution simulator
:
public void simulate4/ro)ramStatement statement9
:
int;< operands = statement.)et,perands49>
Re)isterFile.updateRe)ister4
operands;<!
Re)isterFile.)et?alue4operands;1<9 @
Re)isterFile.)et?alue4operands;#<9 9>
A
A
99>
*he Easic$nstruction constructor ta)es four parameters, annotated on the
example2
&. "xample instruction use. *his instruction ta)es three register operands. *he <&, <(
and <. represent generic registers and are used only to generate a to)en se%uence for
syntax analysis.
Page ..
(. MIPS instruction format. MIPS defines the R-format wor)s with registers#, I-format
wor)s with immediate value#, and $-format Dump instruction#. MARS defines a
second version of the I-format called I-branch-format when the immediate value is
used in a branch instruction.
.. Machine code template. *his String of length .( consists of the characters 0, 1, f, s,
and t. =hen the MIPS program statement syntactically matches this instruction, the
.( bit machine code instruction is constructed by substituting low order bits from the
irst operand for f, low order bits from the second operand for s and low order bits
from the third operand for t. *he result is converted to .( bit binary. *his example
has register numbers which are ' bits because MIPS.( defines .( integer registers.
+. Bonstructs the obDect whose simulate() method will be called to simulate the
execution of the program statement at MIPS runtime. *he obDect is constructed from
an anonymous subclass of the %imulation9ode class defined right here. *he
simulate() method receives information about the program statement as a
parameter and manipulates MIPS registers and0or memory to carry out the instruction.
3o modiy t#e basic instruction set, ollo% t#is process6
&. "xtract the MARS distribution from its $AR file if you have not already done so.
(. Bopy $nstruction%et.java from the src:mars:mips:instructions
folder into the mars:mips:instructions folder.
.. Ma)e a bac)up copy of $nstruction%et.java for safe )eeping.
+. "dit $nstruction%et.java appropriately. Implementation of the
simulate() method will li)ely re%uire access to one or more simulated MIPS
memory and0or register obDects. *he pertinent classes are
mars.mips.+ard'are.*emor! and
mars.mips.+ard'are."egister#ile. $avadoc-generated documentation for
all MARS classes is provided in the distributionCs doc folder. Also study the source
code of existing instructions.
'. Bompile $nstruction%et.java and test your instruction.
893&6 *his techni%ue applies to MARS release ..(.&. It is possible that the techni%ue
for specifying basic instructions will change in a future release of MARS. If so, it would
be converted to a techni%ue similar to that now used for system calls.
Page .+

You might also like