\documentclass[12pt]{report}
\usepackage{verbatim}
\usepackage{amsfonts}
\usepackage{indentfirst}
\usepackage{makeidx}
\usepackage{listings}
\usepackage{fancyhdr}
\newcommand{\EM}{EduMIPS64}
\newcommand{\EV}{0.5}
\newcommand{\MS}{MIPS64}
\newcommand{\SC}{\texttt{SYSCALL}}
\newcommand{\WARN}{\textbf{WARNING:} This is a deprecated instruction, that
does not belong to the \MS{} instruction set, but it is included in the instruction
set in order to maintain compatibility with other simulators.}
\newcommand{\MISN}{\textbf{NB:} The 'U' (stands for 'unsigned') in the instruction name is a misnomer; 
this operation threats operands as signed values, but does not trap on overflow.}
\newcommand{\OF}{\textbf{NB:} This listing needs that registry \$s2 contains the
file descriptor of the file to use (if you use this listing you will need to use
the code in listing~\ref{code:syscall1}}

% Per avere il bold typewriter
\DeclareFontShape{OT1}{cmtt}{bx}{n}{ <5><6><7><8><9><10><10.95><12><14.4><17.28><20.74><24.88>cmttb10}{}

\lstdefinestyle{mips}{
	language=java,
	basicstyle=\small,
	keywordstyle=\bfseries,
	identifierstyle=\ttfamily,
	stringstyle=\ttfamily,
	captionpos=b,
	abovecaptionskip=15pt,
	showstringspaces=false
}
\lstdefinestyle{java}{
	language=java,
	basicstyle=\small,
	keywordstyle=\bfseries,
	identifierstyle=\ttfamily,
	stringstyle=\ttfamily,
	captionpos=b,
	abovecaptionskip=15pt,
	showstringspaces=false
}

\usepackage{subfigure}
\usepackage[top=5.3cm, bottom=2cm, left=4cm, right=3cm]{geometry}

\makeindex

\author{<NAME>}
\title{EduMIPS64 \EV User Manual}

\begin{document}
\setlength{\baselineskip}{1.60\baselineskip} % interlinea
% START OF TITLEPAGE

\newlength{\centeroffset}
\setlength{\centeroffset}{-0.5\oddsidemargin}
\addtolength{\centeroffset}{0.5\evensidemargin}
%\addtolength{\textwidth}{-\centeroffset}
\thispagestyle{empty}
\vspace*{\stretch{1}}
\noindent\hspace*{\centeroffset}\makebox[0pt][l]{\begin{minipage}{\textwidth}
\flushright
{\Huge\bfseries EduMIPS64 User Manual 
}
\noindent\rule[-1ex]{\textwidth}{5pt}\\[2.5ex]
\end{minipage}}

\vspace{\stretch{1}}
\noindent\hspace*{\centeroffset}\makebox[0pt][l]{\begin{minipage}{\textwidth}
\flushright
{\bfseries 
by <NAME>\\[1.2ex]
and the EduMIPS64 Team\\[3ex]
} 
Version~1.3, 5th of June 2007
\end{minipage}}

%\addtolength{\textwidth}{\centeroffset}
\vspace{\stretch{2}}


\pagebreak
% END OF TITLEPAGE

\tableofcontents
\listoftables
\lstlistoflistings
\chapter*{Introduction}
\EM{} is a \MS{} Instruction Set Architecture (ISA) simulator. It is designed to
be used to execute small programs that use the subset of the \MS{} ISA
implemented by the simulator, allowing the user to see how instructions behave
in the pipeline, how stalls are handled by the CPU, the status of registers and
memory and much more. It is both a simulator and a visual debugger.

\EM{} is developed by a group of students of the University of Catania (Italy),
and started as a clone of WinMIPS64, even if now there are lots of differences
between the two simulators.

This manual will introduce you to \EM{}, and will cover some details on how to
use it.

The first chapter of this manual covers the format of source files accepted by
the simulator, describing the data types and the directives, in addition to
command line parameters. In the second chapter there's an overview of the subset
of the \MS{} instruction set that is accepted by \EM{}, with all the needed
parameters and indications to use them. The third chapter is a description of
the user interface of \EM{}, that explains the purpose of each frame and menu,
along with a description of the configuration dialog, the Dinero frontend
dialog, the Manual dialog and command line options. 

The fourth chapter contains some useful examples.

This manual refers to EduMIPS64 version \EV.

\chapter{Source files format}
\EM{} tries to follow the conventions used in other \MS{} and DLX simulators, so
that old time users will not be confused by its syntax.

\section{Sections}
\index{.data}\index{.code}
There are two sections in a source file, the \textbf{data} section and the
\textbf{code} section, introduced respectively by the \textbf{.data} and the
\textbf{.code} directives. In listing~\ref{code:sample} you can see a very basic
\EM{} program.

To distinguish the various parts of each source code line, any combination of
spaces and tabs can be used, as the parser ignores multiple spaces and only
detects whitespaces to separate tokens.

\begin{lstlisting}[caption={Sample \EM{} code}, label={code:sample}, style={mips}]
; This is a comment
        .data
label:  .word   15     ; This is an inline comment

        .code
        daddi   r1, r0, 0
        syscall 0
\end{lstlisting}

\index{comments}\index{;}
Comments can be specified using the ``;'' character, everything that follows
that character will be ignored. So a comment can be used ``inline'' (after the
directive) or on a row by itself.

\index{label} Labels can be used in the code to reference a memory cell or an
instruction.  They are case insensitive. Only a label for each source code line
can be used.  The label can be specified one or more rows above the effective
data declaration or instruction, provided that there's nothing, except for
comments and empty lines, between the label and the declaration. 

\subsection{The \texttt{.data} section}
\index{.data}
The \textbf{data} section contains commands that specify how the memory must be
filled before program execution starts. The general form of a \texttt{.data} command
is:

\begin{center}
	\texttt{[label:] \textbf{.datatype} value1 [, value2 [, ...]]}
\end{center}

\EM{} supports different data types, that are described in
table~\ref{table:datatypes}.

\index{data types}
\index{.byte}
\index{.word}
\index{.word16}
\index{.word32}
\index{.word64}
\begin{table}[!htb]
	\begin{centering}
		\begin{tabular}{lll}
			\hline
			\hline
			Type & Directive & Bits required\\
			\hline
			Byte & \texttt{.byte} & 8\\
			Half word & \texttt{.word16} & 16\\
			Word & \texttt{.word32} & 32\\
			Double Word & \texttt{.word} or \texttt{.word64} & 64
		\end{tabular}
		\caption{Basic data types}
		\label{table:datatypes}
	\end{centering}
\end{table}

Please note that a double word can be introduced either by the \texttt{.word}
directive or by the \texttt{.word64} directive.

\index{array} There's a big difference between declaring a list of data elements
using a single directive or by using multiple directives of the same type. \EM{}
starts writing from the next 64-bit double word as soon as it finds a datatype identifier,
so the first \texttt{.byte} statement in listing~\ref{code:data_array} will put
the numbers 1, 2, 3 and 4 in the space of 4 bytes, taking 32 bits, while code in
the next four rows will put each number in a different memory cell, occupying 32
bytes, as in table~\ref{table:effect}.

\begin{lstlisting}[caption={Adjacent bytes}, label={code:data_array}, style={mips}]
	.data
	.byte	1, 2, 3, 4
	.byte	1
	.byte	2
	.byte	3
	.byte	4
\end{lstlisting}

In table~\ref{table:effect}, the memory is represented using byte-sized cells
and each row is 64 bits wide. The address on the left side of each row of the
table refers to the right-most memory cell, that has the lowest address of the
eight cells in each line.

\begin{table}[htb]
	\begin{centering}
		\begin{tabular}{r|c|c|c|c|c|c|c|c|}
			\cline{2-9}
			0 & 0 & 0 & 0 & 0 &4 & 3 &2 &1 \\
			\cline{2-9}
			8 & 0 & 0 & 0 & 0 &0 & 0 &0 &1 \\
			\cline{2-9}
			16 & 0 & 0 & 0 & 0 &0 & 0 &0 &2 \\
			\cline{2-9}
			24 & 0 & 0 & 0 & 0 &0 & 0 &0 &3 \\
			\cline{2-9}
			36 & 0 & 0 & 0 & 0 &0 & 0 &0 &4\\ 
			\cline{2-9}
		\end{tabular}
		\caption{Memory status for Listing~\ref{code:data_array}}
		\label{table:effect}
	\end{centering}
\end{table}
There are some special directives that need to be discussed: \texttt{.space}, 
\texttt{.ascii} and \texttt{.asciiz}.
\index{.space}
The \texttt{.space} directive is used to leave some free space in memory. It
accepts as a parameter an integer, that indicates the number of bytes that must
be left empty. It is handy when you must save some space in memory for the
results of your computations.

\index{.ascii}
The \texttt{.ascii} directive accepts strings containing any of the ASCII
characters, and some special C-like escaping sequences, that are described in
table~\ref{table:escaping}, and puts those strings in memory.

\index{.asciiz}
The \texttt{.asciiz} directive behaves exactly like the \texttt{.ascii} command,
with the difference that it automatically ends the string with a null byte.

\begin{table}[!htb]
	\begin{tabular}{lll}
		\hline
		\hline
		Escaping sequence & Meaning & ASCII encoding\\
		\hline
		\texttt{$\backslash$0} & Null byte & 0\\
		\texttt{$\backslash$t} & Horizontal tabulation & 9\\
		\texttt{$\backslash$n} & Newline character & 10\\
		\texttt{$\backslash$"} & Literal quote character & 34\\
		\texttt{$\backslash\backslash$} & Literal backslash character & 92
	\end{tabular}
	\caption{Escaping sequences}
	\label{table:escaping}
\end{table}

\subsection{The \texttt{.code} section}
\index{.code}
The \textbf{code} section contains commands that specify how the memory must be
filled when the program will start. The general form of a \texttt{.code} command
is:

\index{syntax!instruction parameters}
\begin{center}
	\texttt{[label:] \textbf{instruction} [param1 [, param2 [, param3]]]}
\end{center}

\index{.text}
The \textbf{code} section can be specified with the \texttt{.text} alias.

The number and the type of parameters depends on the instruction itself.
%TODO: questa va sicuramente inserita.
%Please see table~\ref{table:segm-type} for the list of possible parameters.

Instructions can take three types of parameters:
\begin{itemize}
	\item \textbf{Registers} a register parameter is indicated by an uppercase
    or lowercase ``r'', or a \$, followed by the number of the register (between
	0 and 31), as in ``r4'', ``R4'' or ``\$4'';
	\item \textbf{Immediate values} an immediate value can be a number or a
	label; the number can be specified in base 10 or in base 16: base 10 numbers
	are simply inserted by writing the number, while base 16 number are inserted
	by putting before the number the prefix``0x''
	\item \textbf{Address} an address is composed by an immediate value followed
	by a register name enclosed in brackets. The value of the register will be 
	used as base, the value of the immediate will be the offset.
\end{itemize}

The size of immediate values is limited by the number of bits that are available
in the bit encoding of the instruction. 

You can use standard MIPS assembly aliases to address the first 32 registers,
appending the alias to one of the standard register prefixes like ``r'', ``\$''
and ``R''. See table~\ref{table:mips32-reg}.

\index{registers}
\begin{table}[!htb]
	\begin{centering}
		\begin{tabular}{ll}
			\hline
			\hline
			Register & Alias\\
			\hline
			0 & \texttt{zero}\\
			1 & \texttt{at}\\
			2 & \texttt{v0}\\
			3 & \texttt{v1}\\
			4 & \texttt{a0}\\
			5 & \texttt{a1}\\
			6 & \texttt{a2}\\
			7 & \texttt{a3}\\
			8 & \texttt{t0}\\
			9 & \texttt{t1}\\
			10 & \texttt{t2}\\
			11 & \texttt{t3}\\
			12 & \texttt{t4}\\
			13 & \texttt{t5}\\
			14 & \texttt{t6}\\
			15 & \texttt{t7}\\
			16 & \texttt{s0}\\
			17 & \texttt{s1}\\
			18 & \texttt{s2}\\
			19 & \texttt{s3}\\
			20 & \texttt{s4}\\
			21 & \texttt{s5}\\
			22 & \texttt{s6}\\
			23 & \texttt{s7}\\
			24 & \texttt{t8}\\
			25 & \texttt{t9}\\
			26 & \texttt{k0}\\
			27 & \texttt{k1}\\
			28 & \texttt{gp}\\
			29 & \texttt{sp}\\
			30 & \texttt{fp}\\
			31 & \texttt{ra}\\
		\end{tabular}
		\caption{Aliases for the first 32 registers}
		\label{table:mips32-reg}
	\end{centering}
\end{table}

% TODO: anche questa, ma nell'indice
%Please see~\cite{mips-2} for more details about how instruction are actually encoded.

The instructions that can be used in this section will be discussed in
section~\ref{instructions}

\subsection{The \texttt{\#include} command}
Source files can contain the \texttt{\textbf{\#include} filename} command, which has the
effect of putting in place of the command row the content of the file
\texttt{filename}.
It is useful if you want to include external routines, and it comes with a
loop-detection algorithm that will warn you if you try to do something like
``\texttt{\#include A.s}'' in file \texttt{B.s} and ``\texttt{\#include B.s}'' in
file \texttt{A.s}.

\chapter{The instruction set}
\label{instructions}
\index{instructions}

In this section we will the subset of the \MS{} instruction set that \EM{}
recognizes. We can operate two different taxonomic classification: one based on
the functionality of the instructions and one based on the type of the
parameters of the instructions. 

% Please refer to Section~\ref{mipsis} for more informations about those classifications.

The first classification divides instruction into three categories:
ALU instructions, Load/Store instructions, Flow control instructions. The next
three subsections will describe each category and every instruction that belongs
to those categories.

The fourth subsection will describe instructions that do not fit in any of the
three categories.

%For a more complete \MS{} instruction set reference, please refer to~\cite{mips-2}.


\section{ALU Instructions}
The Arithmetic Logic Unit (in short, ALU) is a part of the execution unit of a
CPU, that has the duty of doing arithmetical and logic operations. So in the ALU
instructions group we will find those instructions that do this kind of
operations.

ALU Instructions can be divided in two groups: \textbf{R-Type} and
\textbf{I-Type}. 

\index{instructions!ALU Instructions}
\index{LO}
\index{HI}
\index{registers!LO}
\index{registers!HI}
Four of those instructions make use of two special registers: LO and HI. They
are internal CPU registers, whose value can be accessed through the
\texttt{MFLO} and \texttt{MFHI} instructions.

Here's the list of R-Type ALU Instructions.

\begin{itemize}
	\index{AND}
	\index{instructions!AND}
	\item \texttt{AND rd, rs, rt}\\
	Executes a bitwise AND between rs and rt, and puts the result into rd.

	\index{ADD}
	\index{instructions!ADD}
	\item \texttt{ADD rd, rs, rt}\\
	Sums the content of 32-bits registers rs and rt, considering them as signed values, and puts
	the result into rd. If an overflow occurs then trap.

	\index{ADDU}
	\index{instructions!ADDU}
	\item \texttt{ADDU rd, rs, rt}\\
	Sums the content of 32-bits registers rs and rt, and puts the result into rd.
	No integer overflow occurs under any circumstances.
	\MISN{}

	\index{DADD}
	\index{instructions!DADD}
	\item \texttt{DADD rd, rs, rt}\\
	Sums the content of 64-bits registers rs and rt, considering them as signed values, and puts
	the result into rd. If an overflow occurs then trap.

	\index{DADDU}
	\index{instructions!DADDU}
	\item \texttt{DADDU rd, rs, rt}\\
	Sums the content of 64-bits registers rs and rt, and puts the result into rd.
	No integer overflow occurs under any circumstances.
	\MISN{}

	\index{DDIV}
	\index{instructions!DDIV}
	\item \texttt{DDIV rs, rt}\\
	Executes the division between 64-bits registers rs and rt, putting the 64-bits quotient in LO and the
	64-bits remainder in HI.

	\index{DDIVU}
	\index{instructions!DDIVU}
	\item \texttt{DDIVU rs, rt}\\
	Executes the division between 64-bits registers rs and rt, considering them as unsigned values
    	and putting the 64-bits quotient in LO and the 64-bits remainder in HI.
	
	\index{DIV}
	\index{instructions!DIV}
	\item \texttt{DIV rs, rt}\\
	Executes the division between 32-bits registers rs and rt, putting the 32-bits quotient in LO and the
	32-bits remainder in HI.

	\index{DIVU}
	\index{instructions!DIVU}
	\item \texttt{DIVU rs, rt}\\
	Executes the division between 32-bits registers rs and rt, considering them as unsigned values
    	and putting the 32-bits quotient in LO and the 32-bits remainder in HI.

	\index{DMULT}
	\index{instructions!DMULT}
	\item \texttt{DMULT rs, rt}\\
	Executes the multiplication between 64-bits registers rs and rt, putting the low-order 64-bits doubleword
	of the result into special register LO and the high-order 64-bits doubleword of the result into special
	register HI.

	\index{DMULTU}
	\index{instructions!DMULTU}
	\item \texttt{DMULTU rs, rt}\\
	Executes the multiplication between 64-bits registers rs and rt, considering them as unsigned
  	values and putting the low-order 64-bits doubleword of the result into special register LO 
	and the high-order 64-bits doubleword of the result into special register HI.
	
	\index{DSLL}
	\index{instructions!DSLL}
	\item \texttt{DSLL rd, rt, sa}\\
	Does a left shift of 64-bits register rt, by the amount specified in the
	immediate (positive) value sa, and puts the result into 64-bits register rd. Empty bits are padded with
	zeros.

	\index{DSLLV}
	\index{instructions!DSLLV}
	\item \texttt{DSLLV rd, rt, rs}\\
	Does a left shift of 64-bits register rt, by the amount specified in low-order 6-bits of rs threatd as unsigned value,
	and puts the result into 64-bits register rd. Empty bits are padded with zeros.

	\index{DSRA}
	\index{instructions!DSRA}
	\item \texttt{DSRA rd, rt, sa}\\
	Does a right shift of 64-bits register rt, by the amount specified in the immediate (positive) value sa,
	and puts the result into 64-bits register rd. Empty bits are padded with zeros if the leftmost bit
	of rt is zero, otherwise they are padded with ones.

	\index{DSRAV}
	\index{instructions!DSRAV}
	\item \texttt{DSRAV rd, rt, rs}\\
	Does a right shift of 64-bits register rt, by the amount specified in low-order 6-bits of rs threatd as unsigned value,
	and puts the result into 64-bits register rd. Empty bits are padded with zeros if the leftmost bit
	of rt is zero, otherwise they are padded with ones.

	\index{DSRL}
	\index{instructions!DSRL}
	\item \texttt{DSRL rd, rs, sa}\\
	Does a right shift of 64-bits register rs, by the amount specified in the immediate (positive) value sa,
	and puts the result into 64-bits register rd. Empty bits are padded with zeros.
	
	\index{DSRLV}
	\index{instructions!DSRLV}
	\item \texttt{DSRLV rd, rt, rs}\\
	Does a right shift of 64-bits register rt, by the amount specified in low-order 6-bits of rs threatd as unsigned value,
	and puts the result into 64-bits register rd. Empty bits are padded with zeros.

	\index{DSUB}
	\index{instructions!DSUB}
	\item \texttt{DSUB rd, rs, rt}\\
	Subtracts the value of 64-bits register rt to 64-bits register rs, considering them as signed values,
	and puts the result in rd. If an overflow occurs then trap.

	\index{DSUBU}
	\index{instructions!DSUBU}
	\item \texttt{DSUBU rd, rs, rt}\\
	Subtracts the value of 64-bits register rt to 64-bits register rs, and puts the result in rd.
	No integer overflow occurs under any circumstances.
	\MISN{}

	\index{MFLO}
	\index{instructions!MFLO}
	\item \texttt{MFLO rd}\\
	Moves the content of the special register LO into rd.

	\index{MFHI}
	\index{instructions!MFHI}
	\item \texttt{MFHI rd}\\
	Moves the content of the special register HI into rd.

	\index{MOVN}
	\index{instructions!MOVN}
	\item \texttt{MOVN rd, rs, rt}\\
	If rt is different from zero, then moves the content of rs into rd.

	\index{MOVZ}
	\index{instructions!MOVZ}
	\item \texttt{MOVZ rd, rs, rt}\\
	If rt is equal to zero, then moves the content of rs into rd.

	\index{MULT}
	\index{instructions!MULT}
	\item \texttt{MULT rs, rt}\\
	Executes the multiplication between 32-bits registers rs and rt, putting the low-order 32-bits word
	of the result into special register LO and the high-order 32-bits word of the result into special
	register HI.

	\index{MULTU}
	\index{instructions!MULTU}
	\item \texttt{MULTU rs, rt}\\
	Executes the multiplication between 32-bits registers rs and rt, considering them as unsigned
  	values and putting the low-order 32-bits word of the result into special register LO 
	and the high-order 32-bits word of the result into special register HI.
	
	\index{OR}
	\index{instructions!OR}
	\item \texttt{OR rd, rs, rt}\\
	Executes a bitwise OR between rs and rt, and puts the result into rd.

	\index{SLL}
	\index{instructions!SLL}
	\item \texttt{SLL rd, rt, sa}\\
	Does a left shift of 32-bits register rt, by the amount specified in the immediate (positive) value sa,
	and puts the result into 32-bits register rd. Empty bits are padded with zeros.

	\index{SLLV}
	\index{instructions!SLLV}
	\item \texttt{SLLV rd, rt, rs}\\
	Does a left shift of 32-bits register rt, by the amount specified in low-order 5-bits of rs threatd as unsigned value,
	and puts the result into 32-bits register rd. Empty bits are padded with zeros.

	\index{SRA}
	\index{instructions!SRA}
	\item \texttt{SRA rd, rt, sa}\\
	Does a right shift of 32-bits register rt, by the amount specified in the immediate (positive) value sa,
	and puts the result into 32-bits register rd. Empty bits are padded with zeros if the leftmost bit
	of rt is zero, otherwise they are padded with ones.

	\index{SRAV}
	\index{instructions!SRAV}
	\item \texttt{SRAV rd, rt, rs}\\
	Does a right shift of 32-bits register rt, by the amount specified in low-order 5-bits of rs threatd as unsigned value,
	and puts the result into 32-bits register rd. Empty bits are padded with zeros if the leftmost bit
	of rt is zero, otherwise they are padded with ones.

	\index{SRL}
	\index{instructions!SRL}
	\item \texttt{SRL rd, rs, sa}\\
	Does a right shift of 32-bits register rs, by the amount specified in the immediate (positive) value sa,
	and puts the result into 32-bits register rd. Empty bits are padded with zeros.
	
	\index{SRLV}
	\index{instructions!SRLV}
	\item \texttt{SRLV rd, rt, rs}\\
	Does a right shift of 32-bits register rt, by the amount specified in low-order 5-bits of rs threatd as unsigned value,
	and puts the result into 32-bits register rd. Empty bits are padded with zeros.

	\index{SUB}
	\index{instructions!SUB}
	\item \texttt{SUB rd, rs, rt}\\
	Subtracts the value of 32-bits register rt to 32-bits register rs, considering them as signed values, and
	puts the result in rd. If an overflow occurs then trap.

	\index{SUBU}
	\index{instructions!SUBU}
	\item \texttt{SUBU rd, rs, rt}\\
	Subtracts the value of 32-bits register rt to 32-bits register rs, and
	puts the result in rd. No integer overflow occurs under any circumstances.
	\MISN{}

	\index{SLT}
	\index{instructions!SLT}
	\item \texttt{SLT rd, rs, rt}\\
	Sets the value of rd to 1 if the value of rs is less than the value of rt,
	otherwise sets it to 0. This instruction performs a signed comparison.

	\index{SLTU}
	\index{instructions!SLTU}
	\item \texttt{SLTU rd, rs, rt}\\
	Sets the value of rd to 1 if the value of rs is less than the value of rt,
	otherwise sets it to 0. This instruction performs an unsigned comparison.

	\index{XOR}
	\index{instructions!XOR}
	\item \texttt{XOR rd, rs, rt}\\
	Executes a bitwise exclusive OR (XOR) between rs and rt, and puts the result into rd.
\end{itemize}

Here's the list of I-Type ALU Instructions.

\begin{itemize}
	\index{ADDI}
	\index{instructions!ADDI}
	\item \texttt{ADDI rt, rs, immediate}\\
	Executes the sum between 32-bits register rs and the immediate value, putting the result in rt.
	This instruction considers rs and the immediate value as signed values.
	If an overflow occurs then trap.

	\index{ADDIU}
	\index{instructions!ADDIU}
	\item \texttt{ADDIU rt, rs, immediate}\\
	Executes the sum between 32-bits register rs and the immediate value, putting the result in rt.
	No integer overflow occurs under any circumstances.
	\MISN{}

	\index{ANDI}
	\index{instructions!ANDI}
	\item \texttt{ANDI rt, rs, immediate}\\
	Executes the bitwise AND between rs and the immediate value, putting the result in rt.

	\index{DADDI}
	\index{instructions!DADDI}
	\item \texttt{DADDI rt, rs, immediate}\\
	Executes the sum between 64-bits register rs and the immediate value, putting the result in rt.
	This instruction considers rs and the immediate value as signed values.
	If an overflow occurs then trap.

	\index{DADDIU}
	\index{instructions!DADDIU}
	\item \texttt{DADDIU rt, rs, immediate}\\
	Executes the sum between 64-bits register rs and the immediate value, putting the result in rt.
	No integer overflow occurs under any circumstances.
	\MISN{}

	\index{DADDUI}
	\index{instructions!DADDUI}
	\item \texttt{DADDUI rt, rs, immediate}\\
	Executes the sum between 64-bits register rs and the immediate value, putting the result in rt.
	No integer overflow occurs under any circumstances.
	\MISN{}
    \WARN{}

	\index{LUI}
	\index{instructions!LUI}
	\item \texttt{LUI rt, immediate}\\
	Loads the constant defined in the immediate value in the upper half (16 bit) of the
	lower 32 bits of rt, sign-extending the upper 32 bits of the register.

	\index{ORI}
	\index{instructions!ORI}
	\item \texttt{ORI rt, rs, immediate}\\
	Executes the bitwise OR between rs and the immediate value, putting the
	result in rt.

	\index{SLTI}
	\index{instructions!SLTI}
	\item \texttt{SLTI rt, rs, immediate}\\
	Sets the value of rt to 1 if the value of rs is less than the value of the
	immediate, otherwise sets it to 0. This instruction performs a signed comparison.

	\index{SLTUI}
	\index{instructions!SLTUI}
	\item \texttt{SLTUI rt, rs, immediate}\\
	Sets the value of rt to 1 if the value of rs is less than the value of the
	immediate, otherwise sets it to 0. This instruction performs an unsigned comparison.

	\index{XORI}
	\index{instructions!XORI}
	\item \texttt{XORI rt, rs, immediate}\\
	Executes a bitwise exclusive OR (XOR) between rs and the immediate value,
	and puts the result into rt.

\end{itemize}

\section{Load/Store instructions}
This category contains all the instructions that operate transfers between
registers and the memory. All of these instructions are in the form

\begin{center}
	\texttt{[label:] \textbf{INSTRUCTION} rt, offset(base)}
\end{center}

Where rt is the source or destination register, depending if we are using a
store or a load instruction; offset is a label or an immediate value and base is
a register. The address is obtained by adding to the value of the register
\texttt{base} the immediate value \texttt{offset}.

The address specified must be aligned according to the data type that is
treated. Load instructions ending with ``U'' treat the content of the register
rt as an unsigned value.

List of load instructions:

\begin{itemize}
	\index{LB}
	\index{instructions!LB}
	\item \texttt{LB rt, offset(base)}\\
	Loads the content of the memory cell at address specified by offset
	and base in register rt, treating it as a signed byte.

	\index{LBU}
	\index{instructions!LBU}
	\item \texttt{LBU rt, offset(base)}\\
	Loads the content of the memory cell at address specified by offset
	and base in register rt, treating it as an unsigned byte.

	\index{LD}
	\index{instructions!LD}
	\item \texttt{LD rt, offset(base)}\\
	Loads the content of the memory cell at address specified by offset
	and base in register rt, treating it as a double word.

	\index{LH}
	\index{instructions!LH}
	\item \texttt{LH rt, offset(base)}\\
	Loads the content of the memory cell at address specified by offset
	and base in register rt, treating it as a signed half word.

	\index{LHU}
	\index{instructions!LHU}
	\item \texttt{LHU rt, offset(base)}\\
	Loads the content of the memory cell at address specified by offset
	and base in register rt, treating it as an unsigned half word.

	\index{LW}
	\index{instructions!LW}
	\item \texttt{LW rt, offset(base)}\\
	Loads the content of the memory cell at address specified by offset
	and base in register rt, treating it as a signed word.

	\index{LWU}
	\index{instructions!LWU}
	\item \texttt{LWU rt, offset(base)}\\
	Loads the content of the memory cell at address specified by offset
	and base in register rt, treating it as a signed word.
\end{itemize}

List of store instructions:

\begin{itemize}
	\index{SB}
	\index{instructions!SB}
	\item \texttt{SB rt, offset(base)}\\
	Stores the content of register rt in the memory cell specified by offset and
	base, treating it as a byte.

	\index{SD}
	\index{instructions!SD}
	\item \texttt{SD rt, offset(base)}\\
	Stores the content of register rt in the memory cell specified by offset and
	base, treating it as a double word.

	\index{SH}
	\index{instructions!SH}
	\item \texttt{SH rt, offset(base)}\\
	Stores the content of register rt in the memory cell specified by offset and
	base, treating it as a half word.

	\index{SW}
	\index{instructions!SW}
	\item \texttt{SW rt, offset(base)}\\
	Stores the content of register rt in the memory cell specified by offset and
	base, treating it as a word.
\end{itemize}

\section{Flow control instructions}
Flow control instructions are used to alter the order of instructions that are
fetched by the CPU. We can make a distinction between these instructions:
R-Type, I-Type and J-Type.

\index{stalls!branch taken}
Those instructions effectively executes the jump in the ID stage, so often an
useless fetch is executed. In this case, two instructions are removed from the
pipeline, and the branch taken stalls counter is incremented by two units.

List of R-Type flow control instructions:
\begin{itemize}
	\index{JALR}
	\index{instructions!JALR}
	\item \texttt{JALR rs}\\
	Puts the content of rs into the program counter, and puts into R31 the
	address of the instruction that follows the JALR instruction, the return
	value.

	\index{JR}
	\index{instructions!JR}
	\item \texttt{JR rs}\\
	Puts the content of rs into the program counter.
\end{itemize}

List of I-Type flow control instructions:

\begin{itemize}
	\index{B}
	\index{instructions!B}
	\item \texttt{B offset}\\
	Unconditionally jumps to offset

	\index{BEQ}
	\index{instructions!BEQ}
	\item \texttt{BEQ rs, rt, offset}\\
	Jumps to offset if rs is equal to rt.

	\index{BEQZ}
	\index{instructions!BEQZ}
	\item \texttt{BEQZ rs, offset}\\
	Jumps to offset if rs is equal to zero.\\
	\WARN

	\index{BGEZ}
	\index{instructions!BGEZ}
	\item \texttt{BGEZ rs, offset}\\
	If rs is greather than zero, does a PC-relative jump to offset.

	\index{BNE}
	\index{instructions!BNE}
	\item \texttt{BNE rs, rt, offset}\\
	Jumps to offset if rs is not equal to rt.

	\index{BNEZ}
	\index{instructions!BNEZ}
	\item \texttt{BNEZ rs}\\
	Jumps to offset if rs is not equal to zero.\\
	\WARN
\end{itemize}

List of J-Type flow control instructions:

\begin{itemize}
	\index{J}
	\index{instructions!J}
	\item \texttt{J target}\\
	Puts the immediate value target into the program counter.

	\index{JAL}
	\index{instructions!JAL}
	\item \texttt{JAL target}\\
	Puts the immediate value target into the program counter, and puts into R31 the
	address of the instruction that follows the JAL instruction, the return
	value.
\end{itemize}

\section{The \texttt{SYSCALL} instruction}
\index{SYSCALL}
\label{sysc-man}
\index{instructions!SYSCALL}
\index{system calls}
The SYSCALL instruction offers to the programmer an operating-system-like
interface, making available six different system calls.

System calls expect that the address of their parameters is stored in register
R14, and will put their return value in register R1.

System calls follow as much as possible the POSIX convention.

\index{system calls!exit()}
\subsection{\texttt{SYSCALL 0 - exit()}}
SYSCALL 0 does not expect any parameter, nor it returns anything. It simply stops
the simulator.

Note that if the simulator does not find SYSCALL 0 in the source code, or any of
its equivalents (HALT - TRAP 0), it will be added automatically at the end of
the source.

\index{system calls!open()}
\subsection{\texttt{SYSCALL 1 - open()}}
\label{sys1}
The SYSCALL 1 expects two parameters: a zero-terminated string that indicates
the pathname of the file that must be opened, and a double word containing an
integer that indicates the flags that must be used to specify how to open the
file.

This integer must be built summing the flags that you want to use, choosing them
from the following list:
\begin{itemize}
	\item \texttt{O\_RDONLY (0x01)} Opens the file in read only mode;
	\item \texttt{O\_WRONLY (0x02)} Opens the file in write only mode;
	\item \texttt{O\_RDWR (0x03)} Opens the file in read/write mode;
	\item \texttt{O\_CREAT (0x04)} Creates the file if it does not exist;
	\item \texttt{O\_APPEND (0x08)} In write mode, appends written text at the end of the file;
	\item \texttt{O\_TRUNC (0x08)} In write mode, deletes the content of the file as soon as it is opened.
\end{itemize}

It is mandatory to specify one of the first three modes. The fourth and the
fifth modes are exclusive, you can not specify O\_APPEND if you specify O\_TRUNC
(and vice versa). 

You can specify a combination of modes by simply adding the integer values of
those flags. For instance, if you want to open a file in write only mode and
append the written text to the end of file, you should specify the mode $2 + 8 = 10$.

The return value of the system call is the new file descriptor associated with
the file, that can be further used with the other system calls. If there is an
error, the return value will be -1.

\index{system calls!close()}
\subsection{\texttt{SYSCALL 2 - close()}}
SYSCALL 2 expects only one parameter, the file descriptor of the file that is
closed.

If the operation ends successfully, SYSCALL 2 will return 0, otherwise it will
return -1. Possible causes of failure are the attempt to close a non-existent
file descriptor or the attempt to close file descriptors 0, 1 or 2, that are
associated respectively to standard input, standard output and standard error.

\index{system calls!read()}
\subsection{\texttt{SYSCALL 3 - read()}}
SYSCALL 3 expects three parameters: the file descriptor to read from, the
address where the read data must be put into, the number of bytes to read.

If the first parameter is 0, the simulator will prompt the user for an input,
via an input dialog. If the length of the input is greater than the number of
bytes that have to be read, the simulator will show again the message dialog.

It returns the number of bytes that have effectively been read, or -1 if the
read operation fails. Possible causes of failure are the attempt to read from a
non-existent file descriptor, the attempt to read from file descriptors 1
(standard output) or 2 (standard error) or the attempt to read from a write-only
file descriptor.

\index{system calls!write()}
\subsection{\texttt{SYSCALL 4 - write()}}
SYSCALL 4 expects three parameters: the file descriptor to write to, the address
where the data must be read from, the number of bytes to write.

If the first parameter is two or three, the simulator will pop the input/output
frame, and write there the read data.

It returns the number of bytes that have been written, or -1 if the write
operation fails. Possible causes of failure are the attempt to write to a
non-existent file descriptor, the attempt to write to file descriptor 0
(standard input) or the attempt to write to a read-only file descriptor.

\index{system calls!printf()}
\subsection{\texttt{SYSCALL 5 - printf()}}
SYSCALL 5 expects a variable number of parameters, the first being the address
of the so-called ``format string''. In the format string can be included some
placeholders, described in the following list:
\begin{itemize}
	\item \texttt{\%s} indicates a string parameter;
	\item \texttt{\%i} indicates an integer parameter;
	\item \texttt{\%d} behaves like \texttt{\%i};
	\item \texttt{\%\%} literal \texttt{\%}
\end{itemize}

For each \texttt{\%s}, \texttt{\%d} or \texttt{\%i} placeholder, SYSCALL 5
expects a parameter, starting from the address of the previous one.

When the SYSCALL finds a placeholder for an integer parameter, it expects that
the corresponding parameter is an integer value, when if it finds a placeholder
for a string parameter, it expects as a parameter the address of the string.

The result is printed in the input/output frame, and the number of bytes
written is put into R1.

If there's an error, -1 is written to R1.

\section{Other instructions}
In this section there are instructions that do not fit in the previous 
categories.
\index{BREAK}
\index{instructions!BREAK}
\subsection{\texttt{BREAK}}
The BREAK instruction throws an exception that has the effect to stop the
execution if the simulator is running. It can be used for debugging purposes.

\index{NOP}
\index{instructions!NOP}
\subsection{\texttt{NOP}}
The NOP instruction does not do anything, and it's used to create gaps in the
source code.

\index{TRAP}
\index{instructions!TRAP}
\subsection{\texttt{TRAP}}
The TRAP instruction is a deprecated alias for the SYSCALL instruction.

\index{HALT}
\index{instructions!HALT}
\subsection{\texttt{HALT}}
The HALT instruction is a deprecated alias for the SYSCALL 0 instruction, that
halts the simulator.

\index{\EM{}!UI}
\index{\EM{}!GUI}
\chapter{The user interface}
The GUI of \EM{} is inspired to WinMIPS64 user interface. In fact, the main window
is identical, except for some menus. Please refer to
% chapter~\ref{mips-simulators} for an overview of some MIPS and DLX simulators
% (including WinMIPS64), and to
%\cite{winmips-web} for more information about WinMIPS64.

%In figure~\ref{fig:edumips-main} you can see the main window of \EM{}, composed by
The \EM{} main window is composed by
a menu bar and six frames, showing different aspects of the simulation. There's
also a status bar, that has the double purpose to show the content of memory
cells and registers when you click them and to notify the user that the
simulator is running when the simulation has been started but verbose mode is
not selected. There are more details in the following section.

\index{\EM{}!menu}
\section{The menu bar}
The menu bar contains six menus:

\index{\EM{}!menu!File}
\subsection{File}
The File menu contains menu items about opening files, resetting or shutting
down the simulator, writing trace files.
\begin{itemize}
	\item \textbf{Open...} Opens a dialog that allows the user to choose
	a source file to open.
	\item \textbf{Open recent} Shows the list of the recent files opened by the
	simulator, from which the user can choose the file to open
	\item \textbf{Reset} Resets the simulator, keeping open the file that was
	loaded but resetting the execution.
	\item \textbf{Write Dinero Tracefile...} Writes the memory access data to a
	file, in xdin format.
	\item \textbf{Exit} Closes the simulator.
\end{itemize}
The \textbf{Write Dinero Tracefile...} menu item is only available when a whole
source file has been executed and the end has been already reached.

\index{\EM{}!menu!Execute}
\subsection{Execute}
The Execute menu contains menu items regarding the execution flow of the
simulation.
\begin{itemize}
	\item \textbf{Single Cycle} Executes a single simulation step
	\item \textbf{Run} Starts the execution, stopping when the simulator reaches
	a \texttt{SYSCALL 0} (or equivalent) or a \texttt{BREAK} instruction, or
	when the user clicks the Stop menu item (or presses F9).
	\item \textbf{Multi Cycle} Executes some simulation steps. The number of
	steps executed can be configured through the Setting dialog.
	See~\ref{dialog-settings} for more details.
	\item \textbf{Stop} Stops the execution when the simulator is in ``Run''
	or ``Multi cycle'' mode, as described previously.
\end{itemize}
This menu is only available when a source file is loaded and the end of the
simulation is not reached. The \textbf{Stop} menu item is available only in
``Run'' or ``Multi Cycle'' mode.

\index{\EM{}!menu!Configure}
\subsection{Configure}
The Configure menu provides facilities for customizing \EM{} appearance and
behavior.
\begin{itemize}
	\item \textbf{Settings...} Opens the Settings dialog, described
	in~\ref{dialog-settings}
	\item \textbf{Change Language} Allows the user to change the language used
	by the user interface. Currently only English and Italian are supported.
	This change affects every aspect of the GUI, from the title of the frames to
	the online manual and warning/error messages.
\end{itemize}
The \texttt{Settings...} menu item is not available when the simulator is in
``Run'' or ``Multi Cycle'' mode, because of potential race conditions.

\index{\EM{}!menu!Tools}
\subsection{Tools}
This menu contains only an item, used to invoke the Dinero Frontend dialog.
\begin{itemize}
	\item \textbf{Dinero Frontend...} Opens the Dinero Frontend dialog.
	See~\ref{dialog-dinero}.
\end{itemize}
This menu is not available until you have not executed a program and the
execution has reached its end.

\index{\EM{}!menu!Window}
\subsection{Window}
This menu contains items related to operations with frames.
\begin{itemize}
	\item \textbf{Tile} Sorts the visible windows so that no more that three
	frames are put in a row. It tries to maximize the space occupied by every
	frame.
\end{itemize}
The other menu items simply toggle the status of each frame, making them visible
or minimizing them.

\index{\EM{}!menu!Help}
\subsection{Help}
This menu contains help-related menu items.
\begin{itemize}
	\item \textbf{Manual...} Shows the Help dialog. See~\ref{dialog-help}
	\item \textbf{About us...} Shows a cute dialog that contains the names of
	the project contributors, along with their roles.
\end{itemize}

\index{\EM{}!frames}
\section{Frames}
The GUI is composed by seven frames, six of which are visible by default, and
one (the I/O frame) is hidden.
\index{\EM{}!frames!Cycles}
\subsection{Cycles}
The Cycles frame shows the evolution of the execution flow during time, showing
for each time slot which instructions are in the pipeline, and in which stage of
the pipeline they're located.

\index{\EM{}!frames!Registers}
\subsection{Registers}
The Registers frame shows the content of each register. By left-clicking on them
you can see in the status bar their decimal (signed) value, while
double-clicking on them will pop up a dialog that allows the user to change the
value of the register.

\index{\EM{}!frames!Statistics}
\subsection{Statistics}
The Statistics frame shows some statistics about the program execution.

\index{\EM{}!frames!Pipeline}
\subsection{Pipeline}
The Pipeline frame shows the actual status of the pipeline, showing which
instruction is in which pipeline stage. Different colors highlight different
pipeline stages.

\index{\EM{}!frames!Memory}
\subsection{Memory}
The Memory frame shows memory cells content, along with labels and comments
taken from the source code. Memory cells content, like registers, can be modified
double-clicking on them, and clicking on them will show their decimal value in
the status bar.
The first column shows the hexadecimal address of the memory cell, and the
second column shows the value of the cell. Other columns show additional info
from the source code.

\index{\EM{}!frames!Code}
\subsection{Code}
The Code window shows the instructions loaded in memory. The first column shows
the address of the instruction, while the second column shows the hexadecimal
representation of the instructions. Other columns show additional info taken
from the source code.

\index{\EM{}!frames!Input/Output}
\subsection{Input/Output}
The Input/Output window provides an interface for the user to see the output
that the program creates through the SYSCALLs 4 and 5. Actually it is not 
used for input, as there's a dialog that pops up when a SYSCALL 3 tries to read
from standard input, but future versions will include an input text box.

\index{\EM{}!dialogs}
\section{Dialogs}
Dialogs are used by EduMIPS64 to interact with the user in many ways. Here's a
summary of the most important dialogs:

\index{\EM{}!dialogs!Settings}
\subsection{Settings}
\label{dialog-settings}
In the Settings dialog various aspects of the simulator can be configured.

The Main Settings tab allow to configure forwarding and the number of steps in the
Multi Cycle mode.

The Behavior tab allow to enable or disable warnings during the parsing phase,
the ``Sync graphics with CPU in multi-step execution'' option, when checked,
will synchronize the frames' graphical status with the internal status of the
simulator. This means that the simulation will be slower, but you'll have an
explicit graphical feedback of what is happening during the simulation. If this
option is checked, the ``Interval between cycles'' option will influence how
many milliseconds the simulator will wait before starting a new cycle.
Those options are effective only when the simulation is run using the
``Run'' or the ``Multi Cycle'' options from the Execute menu.

The last two options set the behavior of the simulator when a synchronous
exception is raised. If the ``Mask synchronous exceptions'' option is checked,
the simulator will ignore any Division by zero or Integer overflow exception. If
the ``Terminate on synchronous exception'' option is checked, the simulation
will be halted if a synchronous exception is raised. Please note that if
synchronous exceptions are masked, nothing will happen, even if the termination
option is checked. If exceptions are not masked and the termination option is not
checked, a dialog will pop out, but the simulation will go on as soon as the
dialog is closed. If exceptions are not masked and the termination option is
checked, the dialog will pop out, and the simulation will be stopped as soon as
the dialog is closed.

The last tab allows to change the colors that are associated to the different
pipeline stages through the frames. It's pretty useless, but it's cute.

\index{\EM{}!dialogs!Dinero Frontend}
\subsection{Dinero Frontend}
\label{dialog-dinero}
The Dinero Frontend dialog allows to feed a DineroIV process with the trace file
internally generated by the execution of the program. In the first text box
there is the path of the DineroIV executable, and in the second one there must
be the parameters of DineroIV. 

% Please see~\cite{dinero-web} for further informations about the DineroIV cache simulator.

The lower section contains the output of the DineroIV process, from which you
can take the data that you need.

\index{\EM{}!dialogs!Help}
\subsection{Help}
\label{dialog-help}
The Help dialog contains three tabs with some indications on how to use the
simulator. The first one is a brief introduction to \EM{}, the second one contains
informations about the GUI and the third contains a summary of the supported
instructions.

\index{\EM{}!command line options}
\section{Command line options}
Three command line options are available. They are described in the following
list, with the long name enclosed in round brackets. Long and short names can be
used in the same way.
\begin{itemize}
	\item \texttt{-h (--help)} shows a help message containing the
	simulator version and a brief summary of command line options
	\item \texttt{-f (--file) filename} opens \texttt{filename} in the simulator
	\item \texttt{-d (--debug)} enters Debug mode
\end{itemize}

The \texttt{--debug} flag has the effect to activate Debug mode. In this mode, a
new frame is available, the Debug frame, and it shows the log of internal
activities of \EM{}. It is not useful for the end user, it is meant to be used by
\EM{} developers.

\index{\EM{}!running}
\section{Running \EM{}}
The \EM{} \texttt{.jar} file can act both as a stand-alone executable
\texttt{.jar} file and as an applet, so it can be executed in both ways. Both
methods need the Java Runtime Environment, version 5 or later.

To run it as a stand-alone application, the \texttt{java} executable must be
issued in this way: \texttt{java -jar edumips64-version.jar}, where the
\texttt{version} string must be replaced with the actual version of the
simulator. On some systems, you may be able to execute it by just clicking on
the \texttt{.jar} file.

To embed it in an HTML, the \texttt{<applet>} tag must be used. The \EM{} web
site contains a page that already contains the applet, so
that everyone can execute it without the hassle of using the command line.

\chapter{Code Examples}
In this chapter you'll find some sample listings that will prove to be useful in
order to understand how the instructions accepted by \EM{} (version \EV{}) work.

\section{\SC{}}
For detailed informations about how \SC{} works, go to~\ref{sysc-man}. This
section will cover all the six \SC{} with some pratical examples.

It's important to understand that examples for \SC{} 1-4 refer to the
\texttt{print.s} file, that is the example for \SC{} 5. If you want to run the
examples, you should copy the content of that example in a file named
\texttt{print.s} and include it in your code.

Some examples use an already existing file descriptor, even if it doesn't truly
exist. If you want to run those examples, use the \SC{} 1 example to open a
file.

\subsection{\SC{} 0}
When \SC{} 0 it's called, it stops the execution of the program.
Example:
\begin{lstlisting}[caption={\SC{} 0 example}, label={code:syscall0}, style={mips}]
        .code
        daddi   r1, r0, 0	; saves 0 in R1
        syscall 0	    	; exits
\end{lstlisting}

\subsection{\SC{} 1}
Example program that opens a file:
\begin{lstlisting} [caption={\SC{} 1 example}, label={code:syscall1}, style={mips} ] 
                .data 
error_op:       .asciiz     "Error opening the file"    
ok_message:     .asciiz     "All right"
params_sys1:    .asciiz     "filename.txt"
                .word64     0xF                    

                .text
open:           daddi       r14, r0, params_sys1    
                syscall     1    
                daddi       $s0, r0, -1
                dadd        $s2, r0, r1        
                daddi       $a0,r0,ok_message            
                bne         r1,$s0,end            
                daddi       $a0,r0,error_op

end:            jal         print_string
                syscall 0
        
                #include    print.s      
\end{lstlisting}
In the first two rows we write to memory the strings containing the error
message and the success message that we will pass to print\_string function, and
we give them two labels. The print\_string function is included in the print.s
file.

Next, we write to memory the data required from \SC{} 1 (row 4, 5), the path of
the file to be opened (that must exist if we work in read or read/write mode)
and, in the next memory cell, an integer that defines the opening mode. For more
info about the opening mode of a file, please refer to \ref{sys1}.

In this example, the file was opened using the following modes: 
\texttt{O\_RDWR} \textbar{} \texttt{O\_CREAT} \textbar{} \texttt{O\_APPEND}. The
number $15$ (0xF in base $16$) comes from the sum of the values of these three
modes ($3 + 4 + 8$).

We give a label to this data so that we can use it later.

In the .text section, we save the address of params\_sys1 (that for the compiler
is a number) in register r14; next we can call \SC{} 1 and save the content of
r1 in \$s2, so that we can use it in the rest of the program (for instance, with
other \SC{}).

Then the print\_string function is called, passing error\_op as an argument if
r1 is equal to $-1$ (rows 13-14) or else passing ok\_message as an argument if
everything went smoothly (rows 12 and 16).

\subsection{\SC{} 2}
Example program that closes a file:
\begin{lstlisting}[caption={\SC{} 2 example}, label={code:syscall2}, style={mips}]
                .data
params_sys2:    .space 8
error_cl:       .asciiz     "Error closing the file"
ok_message:     .asciiz     "All right"

                .text
close:          daddi       r14, r0, params_sys2        
                sw          $s2, params_sys2(r0)    
                syscall     2            
                daddi       $s0, r0, -1        
                daddi       $a0, r0, ok_message            
                bne         r1, $s0, end            
                daddi       $a0, r0, error_cl

end:            jal         print_string
                syscall     0
    
                #include    print.s         
\end{lstlisting}
First we save some memory for the only argument of \SC{} 2, the file descriptor
of the file that must be closed (row 2), and we give it a label so that we can
access it later.

Next we put in memory the strings containing the error message and the success
message, that will be passed to the print\_string function (rows 3, 4).

In the .text section, we save the address of params\_sys2 in r14; then we can
call \SC{} 2.

Now we call the print\_string function using error\_cl as a parameter if r1
yields $-1$ (row 13), or we call it using ok\_message as a parameter if all went
smoothly (row 11).

\OF{}

\subsection{\SC{} 3}
Example program that reads 16 bytes from a file and saves them to memory:
\begin{lstlisting}[caption={\SC{} 3 example}, label={code:syscall3}, style={mips}]
                .data
params_sys3:    .space      8                
ind_value:      .space      8            
                .word64     16        
error_3:        .asciiz     "Error while reading from file"    
ok_message:     .asciiz     "All right"    

value:          .space      30                    

                .text
read:           daddi       r14, r0, params_sys3 
                sw          $s2, params_sys3(r0)
                daddi       $s1, r0, value            
                sw          $s1, ind_value(r0)            
                syscall     3            
                daddi       $s0, r0, -1            
                daddi       $a0, r0,ok_message            
                bne         r1, $s0,end            
                daddi       $a0, r0,error_3

end:            jal         print_string
                syscall     0
        
                #include    print.s 
\end{lstlisting}
The first 4 rows of the .data section contain the arguments of \SC{} 3, the file
descriptor of the from which we must read, the memory address where the \SC{}
must save the read data, the number of bytes to read. We give labels to those
parameters that must be accessed later.  Next we put, as usual, the strings
containing the error message and the success message.

In the .text section, we save the params\_sys3 address to register r14, we save
in the memory cells for the \SC{} parameters the file descriptor (that we
suppose to have in \$s2) and the address that we want to use to save the read
bytes.

Next we can call \SC{} 3, and then we call the print\_string function passing as
argument error\_3 or ok\_message, according to the success of the operation.

\OF{}

\subsection{\SC{} 4}
Example program that writes to a file a string:

\begin{lstlisting}[caption={\SC{} 4 example}, label={code:syscall4}, style={mips}]
                .data
params_sys4:    .space      8                
ind_value:      .space      8            
                .word64     16        
error_4:        .asciiz     "Error writing to file"    
ok_message:     .asciiz     "All right"    
value:          .space      30                    

                .text
            
write:          daddi       r14, r0,params_sys4        
                sw          $s2, params_sys4(r0)        
                daddi       $s1, r0,value            
                sw          $s1, ind_value(r0)            
                syscall     4                
                daddi       $s0, r0,-1
                daddi       $a0, r0,ok_message            
                bne         r1, $s0,end            
                daddi       $a0, r0,error_4

end:            jal         print_string
                syscall     0
        
                #include    print.s 
\end{lstlisting}

The first 4 rows of the .data section contain the arguments of \SC{} 4, the file
descriptor of the from which we must read, the memory address from where the \SC{}
must read the bytes to write, the number of bytes to write. We give labels to those
parameters that must be accessed later.  Next we put, as usual, the strings
containing the error message and the success message.

In the .text section, we save the params\_sys4 address to register r14, we save
in the memory cells for the \SC{} parameters the file descriptor (that we
suppose to have in \$s2) and the address from where we must take the bytes to
weite.

Next we can call \SC{} 3, and then we call the print\_string function passing as
argument error\_3 or ok\_message, according to the success of the operation.

\OF{}

\subsection{\SC{} 5}
Example program that contains a function that prints to standard output the
string contained in \$a0:
\begin{lstlisting}[caption={\SC{} 5 example}, label={code:syscall5}, style={mips}]
                .data
params_sys5:    .space  8

                .text
print_string:   
                sw      $a0, params_sys5(r0)    
                daddi   r14, r0, params_sys5
                syscall 5
                jr      r31
\end{lstlisting}
The second row is used to save space for the string that must be printed by the
\SC{}, that is filled by the first instruction of the .text section, that
assumes that in \$a0 there's the address of the string to be printed.

The next instruction puts in r14 the address of this string, and then we can
call \SC{} 5 and print the string. The last instruction sets the program counter
to the content of r31, as the usual MIPS calling convention states.

\subsection{A more complex usage example of \SC{} 5}
\SC{} 5 uses a not-so-simple arguments passing mechanism, that will be shown in
the following example:

\begin{lstlisting}[caption={More complex \SC{} 5 example}, label={code:printf}, style={mips}]
                .data
format_str:     .asciiz   "%dth of %s:\n%s version %i.%i is being tested!"
s1:             .asciiz   "June"
s2:             .asciiz   "EduMIPS64"
fs_addr:        .space    4
                .word     5    
s1_addr:        .space    4
s2_addr:        .space    4
                .word     0
                .word     5
test:
                .code
                daddi     r5, r0, format_str
                sw        r5, fs_addr(r0)
                daddi     r2, r0, s1
                daddi     r3, r0, s2
                sd        r2, s1_addr(r0)
                sd        r3, s2_addr(r0)
                daddi     r14, r0, fs_addr
                syscall   5
                syscall   0
\end{lstlisting}
The address of the format string is put into R5, whose content is then saved to
memory at address fs\_addr. The string parameters' addresses are saved into
s1\_addr and s2\_addr. Those two string parameters are the ones that match the
two \%s placeholders in the format string.

Looking at the memory, it's obvious that the parameters matching the
placeholders are stored immediately after the address of the format string:
numbers match integer parameters, while addresses match string parameters. In
the s1\_addr and s2\_addr locations there are the addresses of the two strings
that we want to print instead of the \%s placeholders.

The execution of the example will show how \SC{} 5 can handle complex format
strings like the one stored at format\_str.

\printindex
\end{document}
