COA Lab Manual
COA Lab Manual
LAB # 1
INTRODUCTION TO VVM
OBJECTIVE
THEORY
The Visible Virtual Machine (VVM) is based on a model of a simple computer device called
the Little Man Computer which was originally developed by Stuart Madnick in 1965, and
revised in 1979. The revised Little Man Computer model is presented in detail in "The
Architecture of Computer Hardware and System Software" (2'nd), by Irv Englander (Wiley,
2000).
The VVM is a virtual machine because it only appears to be a functioning hardware device.
In reality, the VVM "hardware" is created through a software simulation. One important
simplifying feature of this machine is that it works in decimal rather than in the traditional
binary number system. Also, the VVM works with only one form of data - decimal integers.
VVM is a 32-bit application for use on a Windows platform. The application adheres to the
Windows style GUI guidelines and thus provides a short learning curve for experienced
Windows users. Online context-sensitive help is available throughout the application.
VVM includes a fully functional Windows-style VVM Program Editor for creating and
manipulating VVM programs. The editor provides a program syntax validating facility which
identifies errors and allows them to be corrected. Once the program has been validated, it can
be loaded into the VVM Virtual Hardware.
For simplicity, VVM works directly with decimal data and addresses rather than with binary
values. Furthermore, the virtual machine works with only one form of data: decimal integers
in the range ± 999. This design alleviates the need to interpret long binary strings or complex
hexadecimal codes.
When using VVM, the user is given total control over the execution of his or her program.
Execution speed of the program can be increased or decreased via a mouse-driven speed
control. The program can be paused and subsequently resumed at any point, at the discretion
of the user. Alternatively, the user can choose to step through the program one statement at a
time. As each program instruction is executed, all relevant hardware components (e.g.,
internal registers, RAM locations, output devices, etc.) are updated in full view of the user.
Hardware Components
I/O Log. This represents the system console which shows the details of relevant events in
the execution of the program. Examples of events are the program begins, the program
aborts, or input or output is generated.
Accumulator Register (Accum). This register holds the values used in arithmetic and
logical computations. It also serves as a buffer between input/output and memory.
Legitimate values are any integer between -999 and +999. Values outside of this range
will cause a fatal VVM Machine error. Non integer values are converted to integers
before being loaded into the register.
Instruction Cycle Display. This shows the number of instructions that have been
executed since the current program execution began.
Instruction Register (Instr. Reg.). This register holds the next instruction to be executed.
The register is divided into two parts: a one-digit operation code, and a two digit
operand. The Assembly Language mnemonic code for the operation code is displayed
below the register.
Program Counter Register (Prog. Ctr.). The two-digit integer value in this register
"points" to the next instruction to be fetched from RAM. Most instructions increment this
register during the execute phase of the instruction cycle. Legitimate values range from 00
to 99. A value beyond this range causes a fatal VVM Machine error.
RAM. The 100 data-word Random Access Storage is shown as a matrix of ten rows and
ten columns. The two-digit memory addresses increase sequentially across the rows and
run from 00 to 99. Each storage location can hold a three-digit integer value between -999
and +999.
Data and
Addresses
All data and address values are maintained as decimal integers. The 100 data-word memory is
addresses with two-digit addressed in the range 00-99. Each memory location holds one data-
word which is a decimal integer in the range -999 - +999. Data values beyond this range
cause a data overflow condition and trigger a VVM system error.
Trace View
The Trace View window provides a history of the execution of your program. Prior to the
execution of each statement, the window shows:
Data value out of range. This condition occurs when a data value exceeds the legitimate
range -999 - +999. The condition will be detected while the data resides in the
Accumulator Register. Probable causes are an improper addition or subtraction operation,
or invalid user input.
Undefined instruction. This occurs when the machine attempts to execute a three-digit
value in the Instruction Register which can not be interpreted as a valid instruction code.
See the help topic "VVM Language" for valid instruction codes and their meaning.
Probable causes of this error are attempting to use a data value as an instruction, an
improper Branch instruction, or failure to provide a Halt instruction in your program.
Program counter out of range. This occurs when the Program Counter Register is
incremented beyond the limit of 99. The likely cause is failure to include a Halt
instruction in your program, or a branch to a high memory address.
User cancel. The user pressed the "Cancel" button during an Input or Output operation.
A simple VVM Assembly Language program which adds an input value to the constant value
-1 is shown below (note that lines starting with "//" and characters to the right of program
statements are considered comments, and are ignored by the VVM machine).
This same program could be written in VVM Machine Language format as follows:
STEP2:
Copy the
code and
paste in
the blue
editor
window.
STEP4:
Press
the Load
button
STEP#5:
Press
the Step
button
OUTPUT
Hardware View
Trace View
LAB TASK
LAB # 2
INTRODUCTION TO VVM PROGRAMMING
OBJECTIVE
Learn VVM Programming and simulate VVM program.
THEORY
VVM Programming
VVM has its own simple Programming Language which supports such operations as
conditional and unconditional branching, addition and subtraction, and input and output,
among others. The language allows the student to create reasonably complex programs, and
yet the language is quite easy to learn and to understand -- only eleven unique operations are
provided. When VVM programs go awry, as in the case of endless loops or data overflows,
VVM (virtual) system errors are triggered before the user's eyes.
Following the automatic syntax validation process, VVM programs are converted to machine
language format and loaded into the 100 data-word virtual RAM which is fully visible to the
user during program execution.
The eleven operations of the VVM Language are described below. The Machine Language
codes are shown in parentheses, while the Assembly Language version is in square brackets.
o Load Accumulator (5nn) [LDA nn]The content of RAM address nn is copied to the
Accumulator Register, replacing the current content of the register. The content of
RAM address nn remains unchanged. The Program Counter Register is incremented
by one.
o Store Accumulator (3nn) [STO nn] (or [STA nn])The content of the Accumulator
Register is copied to RAM address nn, replacing the current content of the address.
The content of the Accumulator Register remains unchanged. The Program Counter
Register is incremented by one.
o Add (1nn) [ADD nn]The content of RAM address nn is added to the content of the
Accumulator Register, replacing the current content of the register. The content of
RAM address nn remains unchanged. The Program Counter Register is incremented
by one.
o Subtract (2nn) [SUB nn]The content of RAM address nn is subtracted from the
content of the Accumulator Register, replacing the current content of the register. The
content of RAM address nn remains unchanged. The Program Counter Register is
incremented by one.
o Input (901) [IN] (or [INP]) A value input by the user is stored in the Accumulator
Register, replacing the current content of the register. The Program Counter Register
is incremented by one.
o Output (902) [OUT] (or [PRN])The content of the Accumulator Register is output to
the user. The current content of the register remains unchanged. The Program Counter
Register is incremented by one.
o Halt (0nn) [HLT] (or [COB]) Program execution is terminated. The operand value
nn is ignored in this instruction and can be omitted in the Assembly Language format.
o Branch if Zero (7nn) [BRZ nn]This is a conditional branch instruction. If the value
in the Accumulator Register is zero, then the Program Counter Register is replaced by
the operand value nn. The result is that the next instruction to be executed will be
taken from address nn rather than from the next sequential address. Otherwise
(Accumulator <> 0), the Program Counter Register is incremented by one, and the
next sequential instruction is executed.
o Branch (6nn) [BR nn] (or [BRU nn] or [JMP nn])This is an unconditional branch
instruction. The current value of the Program Counter Register is
replaced by the operand value nn. The result is that the next instruction to be executed
will be taken from address nn rather than from the next sequential address. The value
of the Program Counter Register is not incremented with this instruction.
o No Operation (4nn) [NOP] (or [NUL])This instruction does nothing other than
increment the Program Counter Register by one. The operand value nn is ignored in
this instruction and can be omitted in the Assembly Language format. (This
instruction is unique to the VVM and is not part of the original Little Man Model.)
o
Data values used by a program can be loaded into memory along with the program. In
Machine or Assembly Language form simply use the format "snnn" where s is an
optional sign, and nnn is the three-digit data value. In Assembly Language, you can
specify "DAT snnn" for clarity.
By default, VVM programs are loaded into sequential memory addresses starting with
address 00. VVM programs can include an additional load directive which overrides
this default, indicating the location in which certain instructions and data should be
loaded in memory. The syntax of the Load Directive is "*nn" where nn represents an
address in memory. When this directive is encountered in a program, subsequent
program elements are loaded in sequential addresses beginning with address nn.
Equivalent BASIC
program:
Program#1 INPUT A
INPUT B
Simple conditional structure using “brp” IF A >= B THEN
& “br” instruction. C = A + B
ELSE
inInput A C = A - B
sto 98 Store A ENDIF
inInput B
sto 99 Store B
lda 98 Load value of A
sub 99 Subtract B from A
brp 11 If A >= B, branch to 11A is < B Find difference
lda 98 Load value of A
sub 99 Subtract value of B
sto 97 Store C
br 14 Jump to 14
lda 98 [11] Load A (A is >= B)
add 99 Add B
sta 97 Store C
out [14] Print result
hltDone
LAB TASKS
1. Take any integer as input,if the number is greater than 5 print it
If a>5, print a
Else if a=0,then Halt
Else if a<5,then halt
LAB # 3
VVM PROGRAMMING
OBJECTIVE
VVM Programs using ”BRP” , “BRZ” & “BR” instructions.
THEORY
BRP nn
Branch if Positive or Zero (8nn) [BRP nn]This is a conditional branch instruction. If the
value in the Accumulator Register is positive or zero, then the Program Counter Register is
replaced by the operand value nn. The result is that the next instruction to be executed will be
taken from address nn rather than from the next sequential address. Otherwise (Accumulator
< 0), the Program Counter Register is incremented by one, and the next sequential instruction
is executed.
BRZ nn
Branch if Zero (7nn) [BRZ nn]This is a conditional branch instruction. If the value in the
Accumulator Register is zero, then the Program Counter Register is replaced by the operand
value nn. The result is that the next instruction to be executed will be taken from address nn
rather than from the next sequential address. Otherwise (Accumulator <> 0), the Program
Counter Register is incremented by one, and the next sequential instruction is executed.
BR nn
Branch (6nn) [BR nn] (or [BRU nn] or [JMP nn])This is an unconditional branch
instruction. The current value of the Program Counter Register is replaced by the operand
value nn. The result is that the next instruction to be executed will be taken from address nn
rather than from the next sequential address. The value of the Program Counter Register is
not incremented with this instruction.
VVM Program # 3
In Input A
sto 99 Store A
brp 04 [02] If A >= 0 then skip next Equivalent to the following BASIC
br 10 Jump out of loop (Value < 0) program:
brz 10 [04] If A = 0 jump out of loop INPUT A
lda 99 Load value of A (don't need to) DO WHILE A > 0
out Print A PRINT A
in Input new A INPUT A
sto 99 Store new value of A LOOP
br 02 Jump to top of loop END
hlt [10] Done
Sample program to print the square of any integer in the range 1-31.
ASSIGNMENT
Write a VVM program which take an integer input and display table of that integer.
LAB # 4
INTRODUCTION TO MIPS ASSEMBLY LANGUAGE
OBJECTIVE
Introduction to MIPS Assembly language.
Simulating the given MIPS programusing MARS.
THEORY
The MIPS Architecture
MIPS: registers
The MIPS registers are arranged into a structure called a Register File. MIPS comes with 32
general purpose registers named $0. . . $31. Registers also have symbolic names reflecting
their conventional use:
# Title: Filename:
# Author: Date:
# Description:
# Input:
# Output:
################# Data segment #####################
.data
...
...
################# Code segment #####################
.text
.global main
main:
... # main program entry
...
li $v0, 10 # Exit program
syscall
Labels
Directives are required in every assembler program in order to define and control memory
space usage. Directivesonlyprovidetheframeworkforanassemblerprogram,though;youalso
need lines in your source code thatactually DO something, lines like
beq $v0, $0, end
.DATA directive
.DATA
First: .space 100
Second: .word 1, 2, 3
Third: .byte 99, 2, 3
.TEXT directive
Defines the code segment of a program containing instructions
.GLOBL directive
Declares a symbol as global
Global symbols can be referenced from other files
We use this directive to declare main procedure of a program
.ASCII Directive
Allocates a sequence of bytes for an ASCII string
.ASCIIZ Directive
Same as .ASCII directive, but adds a NULL char at end of string
Strings are null-terminated, as in the C programming language
.SPACEn Directive
Allocates space of n uninitialized bytes in the data segment
Pseudo-instructions
Pseudo-instructionsgiveMIPSarichersetofassemblylanguageinstructionsthan
thoseimplementedbythehardware.Forexample, one of the frequent steps needed in
programmingistocopythevalueofoneregisterintoanotherregister.Thisactuallycan be solved
easily by the instruction:
add $t0, $zero, $t1
Theassemblerconvertsthispseudo-instructionintothemachinelanguageequivalent of the
prior instruction.
MIPSINSTRUCTIONS
Instructions Description
la Rdest, var Load Address. Loads the address of var into Rdest.
li Rdest, imm Load Immediate. Loadsthe immediate value imm into
Rdest.
SYSTEMI/O(INPUT/OUTPUT)
Introduction to MARS
MARS, the MipsAssembly 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 (IDE). MARS is written in Java and requires at least
Release 1.5 of the J2SE Java Runtime Environment (JRE) to work.
MARS Editor
Menus and Toolbar: Most menu items have equivalent toolbar icons. If the function
of a toolbar icon is not obvious, just hover the mouse over it and a tool tip will soon
appear. Nearly all menu items also have keyboard shortcuts. Any menu item not
appropriate in a given situation is disabled.
Editor: MARS includes two integrated text editors. The default editor, new in Release
4.0, features syntax-aware color highlighting of most MIPS language elements and
popup instruction guides. The original, generic, text editor without these features is
still available and can be selected in the Editor Settings dialog. It supports a single
font which can be modified in the Editor Settings dialog. The bottom border of either
editor includes the cursor line and column position and there is a checkbox to display
line numbers. They 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.
Message Areas: There are two tabbed message areas at the bottom of the screen. The
Run I/O tab is used at runtime for displaying console output and entering console
input as program execution progresses. You have the option of entering console input
into a pop-up dialog then echoes to the message area. The MARS Messages tab is used
for other messages such as assembly or runtime errors and informational messages.
You can click on assembly error messages to select the corresponding line of code in
the editor.
MIPS Registers: MIPS registers are displayed at all times, even when you are editing
and not running a program. While 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). There are three register tabs: the Register File (integer
registers $0 through $31 plus LO, HI and the Program Counter), selected Coprocesor
0 registers (exceptions and interrupts), and Coprocessor 1 floating point registers.
Assembly: Select Assemble from the Run menu or the corresponding toolbar icon to
assemble the file currently in the Edit tab. Prior to Release 3.1, only one file could be
assembled and run at a time. Releases 3.1 and later provide a primitive Project
capability. To use it, go to the Settings menu and check Assemble operation applies to
all files in current directory. Subsequently, the assembler will assemble the current
file as the "main" program and also assemble all other assembly files (*.asm; *.s) in
the same directory. The results are linked and if all these operations were successful
the program can be executed. Labels that are declared global with the ".globl"
directive may be referenced in any of the other files in the project. There is also a
setting that permits automatic loading and assembly of a selected exception handler
file. MARS uses the MIPS32 starting address for exception handlers: 0x80000180.
Execution: Once a MIPS program successfully assembles, the registers are initialized
and three windows in the Execute tab are filled: Text Segment, Data Segment, and
Program Labels. The major execution-time features are described below.
Labels Window: Display of the Labels window (symbol table) is controlled through
the Settings menu. When displayed, you can click on any label or its associated
address to center and highlight the contents of that address in the Text Segment
window or Data Segment window as appropriate.
The assembler and simulator are invoked from the IDE when you select the Assemble, Go, or
Step operations from the Run menu or their corresponding toolbar icons or keyboard
shortcuts. MARS messages are displayed on the MARS Messages tab of the message area at
the bottom of the screen. Runtime console input and output is handled in the Run I/O tab.
Program#1:
Reading and Printing an Integer
STEP#1
Load mars simulator, copy this code to the editor and save file with .asm extension.
STEP#
2
STEP# 3
Execute program by pressing F5.
Type any integer number for input.
LAB TASK
1. Write an assembly program that Read and Print character.
TASK 1
TASK 2
LAB # 5
LOAD & CONSTANT MANIPULATING
INSTRUCTIONS IN MIPS
OBJECTIVE
Take three integer input and display Sum of Three Integers using “addu” instruction.
THEORY
la Rdest, var
Load Address. Loads the address of var into Rdest.
li Rdest, imm
Load Immediate. Loadsthe immediate value imm intoRdest.
addu Rdest,Rsrc1,Rsrc2
AddsthecontentsofRsrc1andRsrc2andstorestheresultinRdest.Thenumbersaretreatedasu n s i g n
e d integers. No overflow exception is needed.
PROGRAM #2
.text
.globl main
main:
la$a0,prompt # display prompt string
li $v0,4
syscall
LAB TASK
Write the same program with small variationi.e this time the program will ask for 3
integers twice and displays the result for each addition separately;
LAB # 6
ARITHMETIC INSTRUCTIONS IN MIPS
OBJECTIVE
Study Addition,Multiplication, DivisionInstructions.
THEORY
addu Rdest,Rsrc1,Rsrc2
AddsthecontentsofRsrc1andRsrc2andstorestheresultinRdest.Thenumbersaretreatedasu n s i g n
e d integers. No overflow exception is needed.
Multiplication:
The multiply instruction multiplies two 32-bit binary values and produces a
64-bit
product which is stored in two registers named High and Low. The
following code
segment shows how the lower 32 bits of the product of $t0 times $t1 can
be moved into $t3:
Example:
Multiply two numbers and display the result.
################# Data segment #####################
.DATA
Prompt : .asciiz"resuit of multiplication is\n”
la $a0,prompt# Print
RESUIT OF MULTIPLICATION IS message of
9801 prompt
li -- PROGRAM IS FINISHED RUNNING -- $v0,4
syscall
move $a0,$t2
#move value of #t2
into $a0
li $v0,1# Print integer
syscall
OUTPUT:
DIVISION:
Divide instruction divides the 32-bit binary value in register $t0 by the 32-
bit value in register $t1. The quotient is stored in the Low register and the
remainder is stored in the High register. The following code segment
shows how the quotient is moved into $t2 and the remainder is moved
into $t3:
Example:
.DATA
prompt: .asciiz"Quotient is : "
prompt1: .asciiz"\nRemainder is: "
.text
.globl main # main program entry
main:
li $t0,42 #$t0=42
li $t1,2 #$t1=2
OUTPUT:
CONDITIONALANDUNCONDITIONALBRANCHINSTRUCTIONS
Instructions Description
Branch if greater than or equal to zero
bgez rs, L if ( rs ≥ 0 ) go to L;
Branch if equal
LAB TASK
Write a MIPS Assembly program that takes an integer input and multiply that number with 3
and display the message that is the number is even or odd.
LAB # 7
CONTROL INSTRUCTIONS IN MIPS
OBJECTIVE
Write a MIPS assembly language programthat calculates the sumof all positive
integerslessthanorequaltoNanddisplaystheresult using ‘blez’ and ‘bnez’ instructions.
THEORY
blezRs, Label
Branch if Less Than or Equal to Zero.
if( Rs ≤ 0 ) go to Label.
bnezRs, Label
Branch if Not Equal to Zero.
if(Rs != 0) go to Label
PROGRAM #1
Write a MIPS assembly language programthat calculates the sumof all positive
integerslessthanorequaltoNanddisplaystheresult.
loop:
add $t0, $t0, $v0 # sum of integers in register $t0
addi $v0, $v0, -1 # summing integers in reverse order
bnez $v0, loop # branch to loop if $v0 is != zero
end:
li $v0, 4 # system call code for Print String
la $a0, bye # load address of msg. into $a0
syscall # print the string
LAB TASK
Write a MIPS assembly language programthat calculates the sumof all positive even
integerslessthanorequaltoNanddisplaystheresult.
LAB # 8
BIT MANIPULATION INSTRUCTIONS IN MIPS
OBJECTIVE
Learn to use MIPS bit manipulation instructions OR & AND in assembly language programs.
THEORY
BITWISELOGICALINSTRUCTIONS
Instructions Description
and rd, rs, rt rd = rs & rt
andi rt, rs, immediate rt = rs & immediate
or rd, rs, rt rd = rs | rt
ori rt, rs, immediate rd = rs | immediate
The main usage of bitwise logical instructions are:to set, to clear someselectedbitsinthe
destinationoperand.Todothis,asourcebitpatternknownasa mask is constructed. The Mask bits
are chosen based on the following properties of AND, OR, and XOR with Z represents a bit
(either 0 or 1):
AND OR
Z AND 0 = 0 Z OR 0 = Z
Z AND 1 = Z Z OR 1 = 1
ANDinstruction:
zero mask bit clears the corresponding destination bit; a one mask bit preserves the
corresponding destination bit.
OR instruction:
The OR instruction can be used to SET specific destination bits while preserving the
others.Aonemaskbitsetsthecorrespondingdestinationbit;azeromaskbitpreserves the
corresponding destination bit
PROGRAM #1
Write a MIPS assembly program that take input value and perform bitwise AND instruction
with mask 1.
.text
.globl main
main:
li $t0,0xffffffff # 1 MASK
OUTPUT:
12
12
PROGRAM #2
Write a MIPS assembly program that take input value and perform bitwise AND instruction
with mask 0.
.text
.globl main
main:
li $t0,0x00000000# 0 MASK
move $t1,$v0
OUTPUT:
PROGRAM #3
Write a MIPS assembly program that take input value and perform bitwise OR instruction
with mask 1.
move $t1,$v0
OUTPUT:
PROGRAM #4
Write a MIPS assembly program that take input value and perform bitwise OR instruction
with mask 0.
.text
.globl main
main:
li $t0,0x00000000# 0 MASK
move $t1,$v0
OUTPUT:
LAB TASK
LAB TASK:
Task#1:
Clear the sign bit of $t0 while leaving the other bits unchanged?
Task#2:
Set the most significant and least significant bits of $t0 while preserving the other bits?
Task#3:
Implement following circuit into MIPS Assembly Language using AND,OR instructions.
LAB # 9
BIT MANIPULATION INSTRUCTIONS IN MIPS
OBJECTIVE
Learn to use MIPS bit manipulation instructions XOR in assembly language programs.
THEORY
BITWISELOGICALINSTRUCTIONS
Instructions Description
and rd, rs, rt rd = rs&rt
andi rt, rs, immediate rt = rs& immediate
or rd, rs, rt rd = rs | rt
ori rt, rs, immediate rd = rs | immediate
nor rd, rs, rt rd = ! ( rs | rt )
xor rd, rs, rt To do a bitwise logical Exclusive OR.
xori rt, rs, immediate
The main usage of bitwise logical instructions are:to set, to clear, to invert, and to isolate
someselectedbitsinthe destinationoperand.Todothis,asourcebitpatternknownasa mask is
constructed. The Mask bits are chosen based on the following properties of AND, OR, and
XOR with Z represents a bit (either 0 or 1):
AND OR XOR
Z AND 0 = 0 Z OR 0 = Z Z XOR 0 = Z
Z AND 1 = Z Z OR 1 = 1 Z XOR 1 = ~Z
XOR instruction:
The XOR instruction can be used to INVERT specificdestinationbits whilepreserving the
others. A one mask bit inverts the corresponding destination bit; a zero mask bit preserves the
corresponding destination bit.
A. Example 1:
Change the sign bit of $t0?
Solution:
Use the XOR instruction with a mask of 80000000h.
xori $t1,$t0,0x80000000
PROGRAM #1
Write a MIPS assembly program that take input value and perform bitwise XOR instruction
with mask 1.
############# DATA SEGMENT ##################
.data
input: .asciiz "\n enter an integer value: " # VARIABLE DECLARATION
result: .asciiz "\n result is: "
.text
.globl main
main:
li $t0,0xffffffff # 1 MASK
move $t1,$v0
OUTPUT:
PROGRAM #2
Write a MIPS assembly program that take input value and perform bitwise XOR instruction
with mask 0.
move $t1,$v0
OUTPUT:
LAB TASK:
Implement following circuit into MIPS Assembly Language using AND,OR& XOR
instructions..
Diagram # 1
LAB # 10
IF THEN ELSE,CONTROL STRUCTURE IN MIPS
OBJECTIVE
Study how to implement translation of“if then else” control structures in MIPS assembly
langage.
THEORY
Translation of an “IF THEN ELSE” Control Structure
The “If (condition) then do {this block of code} else do {that block of code}” control
structure is probably the most widely used by programmers. Let us suppose that a
programmer initially developed an algorithm containing the following pseudocode.
When the time comes to translate this pseudo code to MIPS assembly language the
resultscould appear as shown below. In MIPS assembly language, anything on a line
following the number sign (#) is a comment. Notice how the comments in the code belowhelp
to make the connection back to the original pseudocode.
PROGRAM#1:
Write a program in MIPS assembly language that translateIF-THEN ELSE control structure.
else:
sll $t2,$v0,2 #shift left logical
la $a0,lshift # print value of lshift
li $v0,4
syscall
end:
li $v0,10 # terminate program
syscall
OUTPUT:
LAB TASK
Write a program in MIPS assembly language that take input from user and print whelther
input is greater or less than 10 and also shift input left and right 4 bits.
LAB # 11
FOR LOOP, CONTROL STRUCTURE IN MIPS
OBJECTIVE
Study how to implement translation of“for loop”control structures in MIPS assembly
langage.
THEORY
$a0 = 0;
For ( $t0 =10; $t0 > 0; $t0 = $t0 -1)
do{$a0 = $a0 + $t0}
li $a0, 0 # $a0 = 0
li $t0, 10 # Initialize loop counter to 10
loop:
add $a0, $a0, $t0
addi $t0, $t0, -1 # Decrement loop counter
bgtz $t0, loop # If ($t0 > 0) Branch to loop
PROGRAM#1:
Write a program in MIPS assembly language that translateFOR LOOP control structure.
################## DATA SEGMENT ###################
.data
counter: .asciiz"\n value of count, $t0: "
total: .asciiz"value of sum, $a0: "
tab: .asciiz"\t"
################## TEXT SEGMENT ###################
.text
.globl main
main:
li $a2,0 # $a2=0
li $t0,10 # initiallize loop variable counter $t0=10
loop:
add $a2,$a2,$t0
end:
li $v0,10
syscall
OUTPUT:
LAB TASK
Write a program in MIPS assembly language that take input and display whether number is
prime or not.
LAB # 12
MIPS ASSEMBLY LANGUAGE
OBJECTIVE
To introduce how to implement array as an abstract datastructure in MIPS assembly
language.
THEORY
Not like high level languages, Assembly language has no notion of an array at all.
Arrayslikevariablesaretreatedasablockofmemorythatcouldbeallocatedwitha single directive,
where the first element is given a label.
ARRAYDECLARATION:
1. A label name,
EXAMPLE:
.data
A01: .byte 'a', 'k', 'p', 5 # A01 is an array of 4 bytes: {'a', 'k','p', 5}
A02: .word 5, 6, -9, 7 # A02 is an array of 4 words: {5, 6, -9, 7}
B02: .space 40 #allocate40consecutivebytes,with storage uninitialized
# could be used as a 40-element character array, or a
# 10-element integer array;
# a comment should indicate which!
var1: .half 3 # create a single short integer variable with initial value 3
B03: .word -1:30 # allocate 40consecutive words with each element
# initialized with -1.
TRAVERSINGSINGLE-DIMENSIONALARRAY:
Toaccesseveryelementofanarray,wehave toknowtheaddressofthatelement.
Becauseallelementshavethesamesize,the addressofanelementofthearraycan be formulated as:
EXAMPLE:
The following code fragment is toaccess the sixth element of table1:
.data
table1:.word 4, 5, 6, 7, 8, 9, 10, 21
.text
la $t0, table1
lw $t1, 20($t0)
addiu $t2, $t0, 20
lw $t1, 0($t2)
LAB # 13
MIPS ASSEMBLY LANGUAGE
OBJECTIVE
Study how to implement translation of a “switch” control structurein MIPS assembly
langage.
THEORY
.align n
Align next data item on specified byte boundary (0=byte, 1=half, 2=word, 3=double)
Branch if less than or equal to zero: Branch to statement at label's address if $t1 is less than or
equal to zero
Branch if Greater Than: Branch to statement at label if $t1 is greater than $t2
lw $t2,0($t1)
jr $t2
b label
PROGRAM#1
Write a program in MIPS assembly language that translate SWITCH control structure.
li $t3,3
case2:
li $v0,4
la $a0,msg_2
syscall
b end
case3:
li $v0,4
la $a0,msg_3
syscall
end:
li $v0,10
syscall
OUTPUT:
LAB # 14
PROCEDURES IN MIPS
OBJECTIVE
Study how to implement “Procedures”in MIPS assembly langage.
THEORY
INTRODUCTION
Sofar,we'veonlylookedat programsconsistingofasinglelongchunkof code.Each programhas
startedat the top of thecode,executedeachinstructionin turn(withan occasionaldetourfor
loopingor decision-making),andthenendedat the bottomofthe code. That's fine for small
programs, but larger programs require a programming
constructknownasasubroutine/procedure.
Subroutinesletyoubuildprogramsinamodularfashion,withthesubroutineshiding
thedetailsofspecifictasksso youcanfocusontheoverallflowof theprogram. Subroutinescan
alsomakeprogramsfarmorecompact,sincea singlesubroutinecanbe calledfrommanyplacesina
program,andcanevenperformdifferentfunctionswhen passeddifferentvalues.Ina
largeprogram(whetherwritteninassembler,C,Pascal,or
someotherlanguage),subroutinesareessentialtocreatingorderly,maintainablecode.
HOWPROCEDURESWORK
1. Placeparametersinaplacewheretheprocedurecanaccessthem.
2. Transfercontroltotheprocedure
3. Acquirethestorageresourcesneededfortheprocedure.
4. Executetheprocedure
5. Placetheresultvalueinaplacewherethecallingprogramcanaccessit.
6. Returncontroltothepointoforigin.
$a0–$a3:fourargumentregistersinwhichtopassparameters
$v0–$v1:twovalueregistersinwhichtoreturnvalues
$ra:onereturnaddressregistertoreturntothepointoforigin
Thecodethatcallstheprocedureexecutesajalinstruction,whichsavestheaddress of the
followinginstruction(PC+4)in register$raandthenloadsPCwiththeaddressof the
desiredsubroutine,therebybranchingto the subroutine.The subroutinethenexecutes justasany
othercodewould.Procedurescan– andoftendo– containcallsto other
procedures;infact,properlydesignedsubroutinescanevencallthemselves,a practice
knownasrecursion.
Whenthesubroutinehasfinisheditstask,itexecutesajr$rainstruction,which
jumpstotheaddressstoredinregister$ra.Thiscausesexecutionof thecallingroutineto
resumeattheinstructionfollowingthejalXinstruction.
STACKMANIPULATION
TheMIPSarchitecturedoesnotexplicitlysupportstackoperations.InMIPS,wehave
tomanipulatethestackpointerregistertoimplementthestack.
A.PUSHoperation
Wehavetodecrement$sptomakeroomforthevaluebeingpushedontothestack.
Forexample,ifwewanttopushthecontentsof$a0,wehavetoreservefourbytesof
stackspaceandusetheswinstructiontopushthevalueasshownbelow:
B.POPoperation
Theoperationcanbeimplementedbyusingtheloadandaddinstructions.Forexample,
torestorethevalueof$a0fromthestack,weusethelwinstructiontocopythevalueand
increment$spby4asshownbelow:
lw $a0,0($sp) #restorethetworegisters
addiu $sp,$sp,-4 #clear4bytesofstack
HOWTOPRESERVEREGISTERS
Topreserveregistersefficiently,MIPSsoftwareseparates18oftheregistersintotwo groups:
$t0 – $t9: 10 temporary registers that are NOT preserved by the called procedureona
procedurecall.It isthecaller'sresponsibilitytopreserveanyof them.
$s0–$s7:8savedregistersthatmustbepreservedonaprocedurecall(ifused,
thecalledproceduresavesandrestoresthem).
NESTEDPROCEDURES
Proceduresthatdonotcallothersarecalledleafprocedures.Non-leafproceduresmust
pushallnecessaryregistersbeforecallingotherprocedures.
INSTRUCTIONS USED:
jal label
(Jump and link)
Copies the address of the next instruction into the register $ra(register 31) and then jumps to
the address label.
jr $ra
lw $t2,0($t1)
j label
Branch if less than or equal to zero: Branch to statement at label's address if $t1 is less than or
equal to zero
PROGRAM#1
Write a program in MIPS assembly language that display sum of positive and negative values
using procedure.
##################DATA SEGMENT ###################
.data
array: .word -4, 5, 8, -1 # 4,8,12,16
msg1: .asciiz "\n The sum of positive values= "
msg2: .asciiz "\n The sum of negative values= "
Sum:
addu $v0, $0, $0
addu $v0, $0, $0
Loop:
blez $a1,Return # Branch if less than or equal to zero
OUTPUT: