0% found this document useful (0 votes)
22 views

SE-212L COA Lab Manual (Updated)

Uploaded by

maazhoney2243
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

SE-212L COA Lab Manual (Updated)

Uploaded by

maazhoney2243
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Laboratory Manual

SWE – 212L Computer Organization and


Architecture
Fall 2024

Name:______________________________
Roll No.: ___________________________
Section: ____________________________
Lab Teacher:________________________

Software Engineering Department


Sir Syed University of Engineering & Technology
Main University Road , Karachi 75300
http://www.ssuet.edu.pk
SE-212L Computer Organization & Architecture SSUET/QR/114

TABLE OF CONTENT
Lab Objective Signature Remarks
No.
1 To Understand and explore Visible Virtual Machine
(VVM).
2 To learn VVM Programming and simulate VVM
program using Basic I/O instructions.
3 To Perform basic Arithmetic Operations (Add and Sub)
using Visible Virtual Machine) VVM
4 To understand Branching and simulate VVM
Programs using ”BRP” , “BRZ” & “BR” instructions.
5 To introduce MIPS Assembly Language Programming
using MARS Software (MIPS simulator).
6 To get familiar with addressing modes of MIPS
architecture.
7 To Study and implement basic MIPs Arithmetic
Instructions (add,Sub,Mul and Div) using MARS
Simulator.
8 To Implement MIPS conditional instructions using
MARS Simulator
9 To Study and simulate MIPS bit manipulation
instructions OR & AND .
10 To Learn to use MIPS bit manipulation instructions
XOR.
11 To Study how to implement translation of“if then else”
control structures in MIPS assembly language.
12 To Study how to implement translation of“for
loop”control structures in MIPS assembly language.
13 To introduce how to implement array as an abstract data
structure in MIPS assembly language.
14 To Study how to implement translation of a “switch”
control structure in MIPS assembly language.

1
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 1
OBJECTIVE
To Understand and explore Visible Virtual Machine (VVM).

THEORY
Visible Virtual Machine (VVM)

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
mousedriven 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.

2
SE-212L Computer Organization & Architecture SSUET/QR/114

Hardware Components

The VVM machine comprises the following 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.

3
SE-212L Computer Organization & Architecture SSUET/QR/114

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:

1. The instruction cycle count (begins at 1)


2. The address from which the instruction was fetched
3. The instruction itself (in VVM Assembly Language format)
4. The current value of the Accumulator Register

VVM System Errors


Various conditions or events can cause VVM System Errors. The possible errors and
probable causes are as follows:

• 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.

LAB TASKS:

1. Write Detailed report on VVM.

4
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 2
OBJECTIVE
To learn VVM Programming and simulate VVM program using Basic I/O instructions.

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.

VVM programs can be written in Machine Language, in Assembly Language, or in a


combination of both. The Machine Language format is represented in decimal values,
so there is no need for the student user to interpret long binary machine codes. In the
Machine Language format, each instruction is a three-digit integer where the first digit
specifies the operation code (op code), and the remaining two digits represent the
operand. In the Assembly Language format, the operation code is replaced by a
threecharacter mnemonic code. The two-digit operand usually represents a memory
address. The sample program below is shown in both formats.

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 Language Instructions


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.

5
SE-212L Computer Organization & Architecture SSUET/QR/114

VVM Program Example 1

A simple VVM Assembly Language program which takes an input value and then
display it.
// A sample VVM Assembly program
IN Input number to be added
OUT Output result
HLT Halt (program ends here)

This same program could be written in VVM Machine Language format as follows:
// The Machine Language version
901 Input number to be added
902 Output result
000 Halt (program ends here)

STEP#1: Load VVM

6
SE-212L Computer Organization & Architecture SSUET/QR/114

STEP2: Copy the code and paste in the blue editor window.

STEP3: Press the Validate button.

7
SE-212L Computer Organization & Architecture SSUET/QR/114

STEP4: Press the Load button

STEP#5: Press the Step button

8
SE-212L Computer Organization & Architecture SSUET/QR/114

9
SE-212L Computer Organization & Architecture SSUET/QR/114

OUTPUT

Hardware View

Trace View

LAB TASK

1. Take your roll number as input.

2. Display the taken input on the screen.

10
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 3
OBJECTIVE
To Perform basic Arithmetic Operations (Add and Sub) using Visible Virtual Machine)
VVM

THEORY
The Language Instructions
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 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.)

Embedding Data in Programs

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

11
SE-212L Computer Organization & Architecture SSUET/QR/114

"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.

The VVM Load Directive

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.

VVM Program Example 2

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).

// A sample VVM Assembly program //


to add a number to the value -1.
IN Input number to be added
ADD 99 Add value stored at address 99 to input
OUT Output result
HLT Halt (program ends here)
*99 Next value loaded at address 99
DAT -001 Data value

This same program could be written in VVM Machine Language format as follows:

// The Machine Language version


901 Input number to be added
199 Add value stored at address 99 to input
902 Output result
000 Halt (program ends here)
*99 Next value loaded at address 99
-001 Data value

12
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB TASKS
1. Take an integer as input and another integer is predefined in any memory
location. Subtract them.
2. Take your Roll no. and Date of birth (day only in integer) as input and subtract
them.
3. Add the first three digits of your Roll no.
4. Solve: 25-15+38-20+21

13
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 4
OBJECTIVE
To understand branching and simulate 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 Jump to top of
loop hlt [10]
Simple looping example. Done Equivalent
to the following
BASIC
In Input A sto 99 Store A brp program:
04 [02] If A >= 0 then skip next br 10 INPUT A
Jump out of loop (Value < 0) brz 10 DO WHILE A > 0
[04] If A = 0 jump out of loop lda 99
PRINT A
Load value of A (don't need to)
out Print A in INPUT A
Input new A sto 99 Store LOOP
new value of A br 02 END

VVM Program example# 4

Sample program to print the square of any integer in the range 1-31.
14
SE-212L Computer Organization & Architecture SSUET/QR/114

in Input value to be squared sto


99 Store input at 99 lda 98 Load
current sum (top of loop) add 99 Add
value to sum sto 98 Store the sum lda
97 Load current index add 96 Add 1
to index sto 97 Store new index value
sub 99 Subtract value from index brz
11 Jump out if index = value br 02
Do it again (bottom of loop) lda 98
Done looping - load the sum
out Display the result hlt
Halt (end of program)
// Data used by program follows *96
Resume loading at address 96 dat 001
Constant for counting dat 000 Initial
index value dat 000 Initial sum

15
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB TASKS:

1. Take any integer as input.


If the number is greater than 5, print the number.
If the number is less than 5, halt.
If the number is equal to zero, halt.
2. Take two integers as input and subtract them.
If the result is positive, save and display it at the memory location of your roll
number.
3. Take two numbers as input and print the smaller number.
4. Take three numbers as input like x1, x2, x3.
Then solve: x1 + x2 – x3.
If the result is 0, save and print the result at the memory location 50.
5. Write a VVM program which take an integer input and display table of that
integer.
6. Design a simple loop using BRZ instruction in VVM.
7. Take any integer from user. If it’s positive, print the integer. Otherwise, program
should be closed.
Repeat the task, the no. of times of the last digit of your roll no.
8. Take square of any integer in range (1-20)

16
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 5
OBJECTIVE
To introduce MIPS Assembly Language Programming using MARS Software (MIPS
simulator).

THEORY

The MIPS Architecture


MIPS (originally an acronym for Microprocessor without Interlocked Pipeline Stages)
is a Reduced Instruction Set Computer (RISC). MIPS is a register based architecture,
meaning the CPU uses registers to perform operations on. Registers are memory just
like RAM, except registers are much smaller than RAM, and are much faster. In MIPS
the CPU can only do operations on registers, and special immediate values. MIPS
processors have 32 registers, but some of these are reserved. A fair number of registers
however are available for use.

MIPS and Its Storage:

One advantage of learning assembly language programming is that it directly exposes


many of the types of memory (heap, static data, text, stack and registers) used in a
program, and forces the programmer to deal with them.

Types of Storage:

To a programmer, storage in MIPS is divided into two main categories. The first
category, memory that exists in the Central Processing Unit (CPU) itself, is called
register memory or more commonly simply registers. Register memory is very limited
and contained in what is often called a register file on the CPU. This type of memory
will be called registers.

The second type of memory is what most novice programmers think of as memory and
is often just called memory. Memory for the purposes is where a programmer puts
instructions and data. So from a programmer's point of view, anything stored on a
computer is stored in memory.

Overview of a MIPS CPU

The following diagram shows a simple design for a 3-Address Load/Store computer,
which is applicable to a MIPS computer.

17
SE-212L Computer Organization & Architecture SSUET/QR/114

Figure 5.2: 3-address store/load computer architecture

All CPU architectures contain 3 main units. The first is the ALU, which performs all
calculations such as addition, multiplication, subtraction, division, bit-shifts, logical
operations, etc. Except for instructions which interface to units not on the CPU, such as
memory access or interactions with the user of disks, all operations use the ALU.

Registers are a limited amount of memory which exists on the CPU. No data can be
operated on in the CPU that is not stored in a register. Data from memory, the user, or
disk drives must first be loaded into a register before the CPU can use it. In the MIPS
CPU, there are only 32 registers, each of which can be used to store a single 32 bit
values. Because the number of these registers is so limited, it is vital that the
programmer use them effectively.

In order to use data from memory, the address and data to be read/written is placed on
the system bus using a load/store command and transferred to/from the memory to the
CPU. The data and address are normally placed on the system bus using a Load Word,
lw, or Store Word, sw, operation. The data is then read/written from/to memory to/from
a register. To use more than 32 data values in a program, the values must exist in
memory, and must be loaded to a register to use.

There is a second way to read/write data to/from a register. If the data to be accessed is
on an external device, such as a user terminal or disk drive, the syscall operator is used.
The syscall operator allows the CPU to talk to an I/O controller to retrieve/write
information to the user, disk drive, etc.
18
SE-212L Computer Organization & Architecture SSUET/QR/114

The final part of a CPU is the Control Unit (CU). A CU controls the mechanical settings
on the computer so that it can execute the commands. The CU is the focus of a class
which is often taught with assembly language, the class being Computer Architecture.
This class will not cover the CU in anything but passing detail.

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:

Figure 5.3 CPU Registers


Because the number of registers is very limited, they are carefully allocated and
controlled. Certain registers are to be used for certain purposes, and the rules governing
the role of the register should be followed. The preceding list is the 32 registers
(numbered 0..31) that exist in a MIPS CPU, and their purposes.

Types of MIPS memory:


MIPS implements a 32-bit flat memory model. This means as far as a programmer is
concerned, memory on a MIPS computer starts at address 0x00000000 and extends in
sequential, contiguous order to address 0xffffffff.
A 32 bit flat memory model says that a program can address (or find) 4 Gigabytes (4G)
of data. This does not mean that all of that memory is available to the programmer.
Some of that memory is used up by the operating system (called kernel data), some of
it used by the I/O subsystem, etc. But 4G of memory which is addressable. Figure 5.4
diagrams shows how the 4G of memory is configured in a MIPS computer.

19
SE-212L Computer Organization & Architecture SSUET/QR/114

Figure 5.4 MIPS Memory Configuration

20
SE-212L Computer Organization & Architecture SSUET/QR/114

Introduction to MIPS Assembly Language

# Title: Filename:
# Author: Date:
# Description:
# Input:
# Output:
################# Data segment #####################
.data
...
...
################# Code segment #####################
.text
.global main
main:
... # main program entry
...
li $v0, 10 # Exit program

Figure 5.5 Assembly Language Program Template


Assembly language instruction format

Assembly language programs are not compiled, they are assembled. So a program does
not consist of statements and blocks of statements as in a HLL, but a number of
instructions telling the computing machine how to execute. Assembly language source
code lines follow this format:

[label:] [instruction/directive] [operands] [#comment]

where [label] is an optional symbolic name; [instruction/directive] is either the


mnemonicforaninstructionorpseudo-instructionoradirective;[operands]containsa
combinationofone,two,orthreeconstants,memoryreferences,andregisterreferences, as
required by the particular instruction or directive; [#comment] is an optional comment.

Labels: Labels are nothing more than names used for referring to numbers and
character strings or memory locations within a program. Labels let you give names to
memory variables, values, and the locations of instructions. The label main is equivalent
to the address of the first instruction in program1.

Directives: Directives are instructions to the assembler, specifying an action to be


taken during the assembly process. One important use of directives is declaring or
reserving memory variables. In addition, directives are used to break up the program
into sections. Following are some commonly used directives of MIPS Assembly
Language:

Top-level Directives:

.text: indicates that following items are stored in the user text segment, typically
instructions.

.data: indicates that following data items are stored in the data segment.
Defines the data segment of a program containing data
21
SE-212L Computer Organization & Architecture SSUET/QR/114

• The program's variables should be defined under this directive


• Assembler will allocate and initialize the storage of variables
• You should place your memory variables in this segment. For example,

.DATA
First: .space 100 Second:
.word 1, 2, 3
Third: .byte 99, 2, 3

.globl sym: declare that symbol sym is global and can be referenced from other files.

• Global symbols can be referenced from other files


• We use this directive to declare main procedure of a program

Common Data Definitions:


.word: 32-bit integer
.half: 16-bit integer
.byte: 8-bit integer
.space: Uninitialized memory block
.ascii: ASCII string
.asciiz: Null-terminated ASCII string
Constants: Numeric constants in MIPS Assembly Language use the same syntax as
C, C++, and Java.

0x100 Hexadecimal integer


0100 Octal integer
100 Decimal integer
1.0 Decimal float or double

Pseudo-instructions:

Pseudo-instructions do not correspond to real MIPS instructions. Instead, the assembler,


would translate pseudo-instructions to real instructions (one on more instructions).
Pseudo-instructions not only make it easier to program, it can also add clarity to the
program, by making the intention of the programmer more clear. Here's a list of useful
pseudo-instructions.

• mov $t0, $t1: Copy contents of register t1 to register t0.


• li $s0, immed: Load immediate into to register s0. The way this is translated
depends on whether immed is 16 bits or 32 bits.
• la $s0, addr: Load address into to register s0.
• lw $t0, address: Load a word at address into register t0. Similar
pseudoinstructions exist for sw, etc.

MIPS Instructions:
22
SE-212L Computer Organization & Architecture SSUET/QR/114

Following categories of Instruction set are available with:

• Data Transfer
• Arithmetic and Logical
• Control
• Floating Point

Data Transfer Instructions:

Integer Load and Store Instructions:

Load and store instructions are the only instructions that can access memory. Their
purpose is to move data between a memory location and a CPU register. They are not
interchangeable with the move instruction. Load and store instructions take one register
operand and one memory address or immediate operand.
Instructions Description
la Rdest, var Load Address. Loads the address of var into Rdest.

23
SE-212L Computer Organization & Architecture SSUET/QR/114

li Rdest, imm Load Immediate. Loadsthe immediate value imm into


Rdest.
Input/Output: System Calls:

Input and output in MIPS is performed by system calls, which are calls to operating
system kernel subprograms. To initiate a system call, we load the system call
function code into $v0. If the function requires arguments, they go into the
argument registers, starting with $a0. The system call function codes are as follows:
Code in
Service $v0 Argument(s) Result(s)

$a0 = number to be
Print integer 1 printed
$a0 = address of string
Print String 4
in memory
Number returned in
Read Integer 5
$v0.
$a0=address of input
buffer in memory.
Read String 8 $a1 = length of buffer
(n)
Exit 10
Print Char 11 $a0 =character to print

Read Char 12 $v0 = character read

Introduction to MARS:

MARS, the Mips Assembly and Runtime Simulator, will assemble and simulate the
execution of MIPS assembly language programs. It can be used either from a command
line or through its integrated development environment (IDE).
MARS is the easiest to use, and provides the best tools for explaining how MIPS
assembly and the MIPS CUP work. MARS is an executable jar file, so you must have
the Java Runtime Environment (JRE) installed to run MARS. A link to Java is on the
MARS download page, so you should install Java if it is not on your computer. When
it is started, a page which is similar to the following should come up.

24
SE-212L Computer Organization & Architecture SSUET/QR/114

Figure 5.1 MARS IDE


MARS Integrated Development Environment (IDE)
The IDE is invoked from a graphical interface by double-clicking the mars.jar icon that
represents this executable JAR file. The IDE provides basic editing, assembling and
execution capabilities. Hopefully it is intuitive to use. Here are comments on some
features.

• 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
25
SE-212L Computer Organization & Architecture SSUET/QR/114

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 Coprocessor 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


################# Code segment #####################
.text
.globl main
main: # main program entry
li $v0, 5 # Read integer
syscall # $v0 = value read
move $a0, $v0 # $a0 = value to print
li $v0, 1 # Print integer
syscall

li $v0, 10 # Exit program


syscall

26
SE-212L Computer Organization & Architecture SSUET/QR/114

STEP#1: Load mars simulator, copy this code to the editor and save file with .asm
extension.

27
SE-212L Computer Organization & Architecture SSUET/QR/114

STEP# 2: Assemble program by pressing F3.

28
SE-212L Computer Organization & Architecture SSUET/QR/114

STEP# 3
Execute program by pressing F5.
Type any integer number for input.

LAB TASKS
1. Write an assembly program that Read and Print your Roll No.
2. Write an assembly program that Read and Print Last Alphabet of your Name.
3. Write an assembly program that Read and Print Your Full Name.

29
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 6
OBJECTIVE
To get familiar with addressing modes of MIPS architecture.

THEORY

MIPS Addressing Modes:


There are different ways to specify the address of the operands for any given operations
such as load, add or branch. The different ways of determining the address of the
operands are called addressing modes. In this lab, we are going to explore different
addressing modes of MIPS processor and learn how all instructions can fit into a single
word (32 bits).
MIPS Instruction Formats
There are three types of instruction format. They are Register Type, Immediate Type,
and Jump Type. For these type of Instructions there are different MIPS addressing
modes given as:
• Register addressing
• Immediate addressing
• Base addressing
• PC-relative addressing

MIPS Register addressing


Operands are in a Register. The simplest addressing mode is the register addressing.
Instructions using registers execute fast because they do not have the delay associated
with memory access. But, the number of registers is limited since only 5-bits are
reserved to select a register. Register addressing is a form of direct addressing. The
value in the register is an operand instead of being a memory address to an operand.
Example: mov $a0, $V0

MIPS Immediate addressing


The operand is embedded inside the encoded instruction. MIPS immediate addressing
means that one operand is a constant within the instruction itself. The advantage of
using it is that there is no need to have extra memory access to fetch the operand. But
keep in mind that the operand is limited to 16 bits in size.
Example: mov $V0, 05

MIPS Base addressing


The address of the operand is the sum of the immediate and the value in a register (rs).

30
SE-212L Computer Organization & Architecture SSUET/QR/114

In base register addressing we add a small constant to a pointer held in a register. The
register may point to a structure or some other collection of data, and we need to load a
value at a constant offset from the beginning of the structure. Because each MIPS
instruction fits in one word, the size of the constant is limited to 16 bits.
Example: lw $t1,4($t0)

MIPS PC-Relative addressing


the value in the immediate field is interpreted as an offset of the next instruction (PC+4
of current instruction). PC-relative addressing is used for conditional branches. The
address is the sum of the program counter and a constant in the instruction.
Example: beq $0,$3,Label

31
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 7
OBJECTIVE
To Study and implement basic MIPs Arithmetic Instructions (add,Sub,Mul and Div)
using MARS Simulator.

THEORY
Most MIPS operators take 3 registers as parameters, which is the reason it is called a
3-address machine. They are: the first input to the ALU, always Rs (the first source
register); the second input to the ALU, either Rt (the second source register) or an
immediate value; and the register to write the result to, Rd (the destination register).

ARITHMETIC INSTRUCTIONS

32
SE-212L Computer Organization & Architecture SSUET/QR/114

Addition Operators:
There are 4 real addition operators in MIPS assembly. They are:

add operator, which takes the value of the Rs and Rt registers containing integer
numbers, adds the numbers, and stores the value back to the Rd register. The format and
meaning are:
format: add Rd, Rs, Rt meaning:
Rd <- Rs + Rt

addi operator, which takes the value of Rs and adds the 16 bit immediate value in the
instruction, and stores the result back in Rt. The format and meaning are:
format: addi Rt, Rs, Immediate
meaning: Rt <- Rs + Immediate

addu operator, which is the same as the add operator, except that the values in the
registers are assumed to be unsigned, or whole, binary numbers. There are no negative
values, so the values run from 0..232-1. The format and the meaning are the same as the
add operator above:
format: addu Rd, Rs, Rt
meaning: Rd <- Rs + Rt

addiu operator, which is the same as the addi operator, but again the numbers are
assumed to be unsigned8:
format: addiu Rt, Rs, Immediate
meaning: Rt <- Rs + Immediate
Subtraction in MIPS assembly

Subtraction in MIPS assembly is similar to addition with one exception. The sub, subu
and subui behave like the add, addu, and addui operators. The only major difference
with subtraction is that the subi is not a real instruction. It is implemented as a pseudo
instruction, with the value to subtract loaded into the $at register, and then the R
instruction sub operator is used. This is the only difference between addition and
subtraction.

sub operator, which takes the value of the Rs and Rt registers containing integer
numbers, adds the numbers, and stores the value back to the Rd register. The format and
meaning are:
format: sub Rd, Rs, Rt meaning:
Rd <- Rs - Rt
33
SE-212L Computer Organization & Architecture SSUET/QR/114

sub pseudo operator, which takes the value of Rs, subtracts the 16 bit immediate value
in the instruction, and stores the result back in Rt. The format, meaning, and translation
are:
format: subi Rt, Rs, Immediate
meaning: Rt <- Rs - Immediate translation:
addi $at, $zero, Immediate
sub Rt, Rs, $at
subi pseudo operator, which takes the value of Rs, subtracts the 16 bit immediate value
in the instruction, and stores the result back in Rt. The format, meaning, and translation
are:
format: subi Rt, Rs, Immediate
meaning: Rt <- Rs - Immediate
translation: addi $at, $zero, Immediate
sub Rt, Rs, $at

subu operator, which is the same as the add operator, except that the values in the
registers are assumed to be unsigned, or whole, binary numbers. There are no negative
values, so the values run from 0..232-1. The format and the meaning are the same as the
add operator above:
format: subu Rd, Rs, Rt
meaning: Rd <- Rs + Rt

Multiplication in MIPS assembly

Multiplication and division are more complicated than addition and subtraction, and
require the use of two new, special purpose registers, the hi and lo registers. The hi
and lo registers are not included in the 32 general purpose registers which have been
used up to this point, and so are not directly under programmer control.
Since multiplication of two 32-bit numbers requires 64-bits, two 32-bit registers are
required. All computers require two registers to store the result of a multiplication,
though the actual implementation of those two registers is different. It MIPS, the hi
and lo registers are used, with the hi register being used to store the 32 bit larger part
of the multiplication, and the lo register being used to the store the 32 bit smaller part
of the multiplication.
In MIPS, all integer values must be 32 bits. So if there is a valid answer, it must be
contained in the lower 32 bits of the answer. Thus to implement multiplication in MIPS,
the two numbers must be multiplied using the mult operator, and the valid result moved
from the lo register. This is shown in the following code fragment which multiplies
the value in $t1 by the value in $t2, and stores the result in $t0.

34
SE-212L Computer Organization & Architecture SSUET/QR/114

mult $t1, $t2


mflo $t0
there are five MIPS multiplication operators which will be looked at. They are:

mult operator, which multiplies the values of Rs and Rt and saves it in the lo and hi
registers. The format and meaning of this operator is:
format: mult Rs, Rt meaning:
[hi,lo] <- Rs * Rt

mflo operator, which moves the value from the hi register into the Rd register. The
format and meaning of this operator is:
format: mflo Rd meaning:
Rd <- lo

mfhi operator, which moves the value from the hi register into the Rd register. The
format and meaning of this operator is:
format: mfhi Rd meaning:
Rd <- hi

mult operator, which multiples the values in Rs and Rt, and stores them in Rd. The
format and meaning of this operator is:
format: mult Rd, Rs, Rt
meaning: Rd <- Rs * Rt

Division in MIPS Assembly

Division, like multiplication requires two registers to produce an answer. The reason
for this has to do with how the hardware calculates the result, and is harder to explain
without considering the hardware used.

EXAMPLE PROGRAM #1
Sum of Two Integers ################# Data segment #####################
.data
prompt: .asciiz "Please enter two numbers: \n" sum_msg:
.asciiz "The sum is: "
################### Code segment ###################
.text
.globl main main: la$a0,prompt #
display prompt string
li $v0,4 syscall

35
SE-212L Computer Organization & Architecture SSUET/QR/114

li $v0,5 # read 1st integer into $t0


syscall move $t0,$v0
li $v0,5 # read 2nd integer into $t1 syscall
move $t1,$v0

addu $t0,$t0,$t1 # accumulate the sum

la $a0,sum_msg # write sum message li


$v0,4
syscall
move $a0,$t0 # output sum
li $v0,1 syscall li
$v0,10 #
exit syscall
Example Program 2:
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:

mult $t0, $t1 mflo $t3 # t3 = Lower 32-bits of product


mfhi $t4 # t4 = Higher 32-bits of product
################# Data segment #####################
.DATA
Prompt : .asciiz" resuit of multiplication is\n”

################# Code segment #####################


.text
.globl main # main program entry main:
li $t0,99#$t0=99
li $t1,99 #$t1=99

mult $t0, $t1 # $t0*$t1


mflo $t2# $t2 = Lower 32-bits of product

la $a0,prompt# Print message of prompt li


$v0,4
syscall

move $a0,$t2 #move value of #t2 into $a0 li


$v0,1# Print integer
syscall

li $v0,10# Exit program syscall

36
SE-212L Computer Organization & Architecture SSUET/QR/114

Example Program 3:
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:

div $t0, $t1 mflo $t2 # here lower register $t2 contain the quotient.
mfhi $t3 # here high register $t3 contain the remainder.
################# Data segment #####################

.DATA
prompt: .asciiz" Quotient is : " prompt1:
.asciiz"\nRemainder is: "

################# Code segment #####################

.text
.globl main # main program entry main:
li $t0,42 #$t0=42 li
$t1,2 #$t1=2

div $t0, $t1 mflo $t2 # here lower register $t2 contain
the quotient. mfhi $t3 # here high register $t3 contain
the remainder.

la $a0,prompt # Print message of prompt li


$v0,4
syscall

move $a0,$t2 #move value of #t2 into $a0 li


$v0,1 # Print value of quotient syscall

la $a0,prompt1 # Print message of prompt1


li $v0,4 syscall

move $a0,$t3 #move value of #t3 into $a0 li


$v0,1 # Print value of remainder
syscall

li $v0,10 # Exit program syscall

37
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB TASKS:

1. Write a MIPS Assembly program that Take three digits of your Roll Numbers
as inputs and add them.
2. Write a MIPS Assembly program that Take first and last digits of your Roll
Numbers and subtract them.
3. Write a MIPS Assembly program that takes an integer input and multiply that
number with last digit of your roll number.
4. Write a MIPS Assembly program that takes your three-digit roll number as input
and divide it with second digit of your roll number.

38
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 8
OBJECTIVE
To Implement MIPS conditional instructions. using MARS Simulator.

THEORY

Conditional Instructions

Unconditional Jumps:

blezRs, Label
Branch if Less Than or Equal to Zero.
if( Rs ≤ 0 ) go to Label.

39
SE-212L Computer Organization & Architecture SSUET/QR/114

bnezRs, Label
Branch if Not Equal to Zero.
if(Rs != 0) go to Label

PROGRAM #1
Write a MIPS assembly language program that calculates the sum of all positive
integers less than or equal to N and displays the result.

################### Data segment ###################


.data
prompt: .asciiz "\n Please Input a value for N = " result:
.asciiz " The sum of the integers from 1 to N is "
bye: .asciiz "\n **** Have a good day ****"
################### Code segment ###################
.text
.globl main main:
li $v0, 4 # system call code for Print String la
$a0, prompt # load address of prompt into $a0
syscall # print the prompt message

li $v0, 5 # system call code for Read Integer


syscall # reads the value of N into $v0
blez $v0, end # branch to end if $v0 < = 0 li $t0,
0 # clear register $t0 to zero

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

li $v0, 4 # system call code for Print String la


$a0, result # load address of message into $a0
syscall # print the string

li $v0, 1 # system call code for Print Integer


move $a0, $t0 # move value to be printed to $a0
syscall # print sum of integers

end:
li $v0, 4 # system call code for Print String la
$a0, bye # load address of msg. into $a0 syscall
# print the string

li $v0, 10 # terminate program run and syscall


# return control to system

40
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB TASKS:

1. Write a MIPS assembly language program that calculates the sum of all positive
even integers less than or equal to N and displays the result.
2. Write a MIPS Assembly program that takes an integer input and multiply that
number with last digit of your roll number. Display whether number is even or
odd.

41
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 9
OBJECTIVE
To Study and simulate MIPS bit manipulation instructions OR & AND.

THEORY

BITWISE LOGICAL INSTRUCTIONS


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 some selected bits in
the destination operand. To do this, a source bit pattern known as a 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

AND instruction:

The AND instruction can be used to CLEAR specific destination bits while preserving
the others. A 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. A one mask bit sets the corresponding destination bit; a zero mask bit
preserves the corresponding destination bit

EXAMPLE PROGRAM #1
Write a MIPS assembly program that take input value and perform bitwise AND
instruction with mask 1.

42
SE-212L Computer Organization & Architecture SSUET/QR/114

############# DATA SEGMENT ##################


.data
input: .asciiz "\n enter an integer value: " # VARIABLE DECLARATION result:
.asciiz "\n result is: "

############# TEXT SEGMENT ##################


.text
.globl main main:
li $t0,0xffffffff # 1 MASK

la $a0,input # PRINT INPUT MESSAGE


li $v0,4 syscall

li $v0,5 # USER INPUT syscall


move $t1,$v0

and $t2,$t1,$t0 # AND INSTRUCTION, $t2 = $t1 AND $t0

la $a0,result # PRINT RESULT MESSAGE


li $v0,4 syscall

move $a0,$t2 # MOVE AND INSTRUCTION RESULT IN $a0

li $v0,1 # PRINT VALUE OF $t2 syscall

li $v0,10 # EXIT PROGRAM syscall

OUTPUT:

43
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB TASKS:

1. Write a MIPS assembly program that take input value and perform bitwise AND
instruction with mask 0.
2. Write a MIPS assembly program that take input value and perform bitwise OR
instruction with mask 0.
3. Write a MIPS assembly program that take input value and perform bitwise OR
instruction with mask 1.
4. Clear the sign bit of $t0 while leaving the other bits unchanged?
5. Set the most significant and least significant bits of $t0 while preserving the
other bits?
6. Implement following circuit into MIPS Assembly Language using AND,OR
instructions.

44
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 10
OBJECTIVE
To Learn to use MIPS bit manipulation instructions XOR.

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 some selected bits in the destination operand. To do this a source bit pattern
known as a 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 specific destination bits while preserving
the others. A one mask bit inverts the corresponding destination bit; a zeromask 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
EXAMPLE PROGRAM #1
Write a MIPS assembly program that take input value and perform bitwise XOR
instruction with mask 1.
############# DATA SEGMENT ##################
.data

45
SE-212L Computer Organization & Architecture SSUET/QR/114

input: .asciiz "\n enter an integer value: " # VARIABLE DECLARATION result:
.asciiz "\n result is: "

############# TEXT SEGMENT ##################

.text
.globl main main:
li $t0,0xffffffff # 1 MASK

la $a0,input # PRINT INPUT MESSAGE li


$v0,4
syscall

li $v0,5 # USER INPUT syscall

move $t1,$v0

XOR $t2,$t1,$t0 # XOR INSTRUCTION, $t2 = $t1XOR $t0

la $a0,result # PRINT RESULT MESSAGE li


$v0,4
syscall

move $a0,$t2# MOVE AND INSTRUCTION RESULT IN $a0

li $v0,1 # PRINT VALUE OF $t2 syscall

li $v0,10 # EXIT PROGRAM syscall

OUTPUT:

46
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB TASKS:

1. Write a MIPS assembly program that take input value and perform bitwise XOR
instruction with mask 0.
2. Implement following circuits into MIPS Assembly Language using AND, OR
& XOR instructions.

47
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 11
OBJECTIVE
To Study how to implement translation of “if then else” control structures in MIPS
assembly language.

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.

if($t8 < 0) then


{$s0 = 0 - $t8;
$t1 = $t1 +1}
else {$s0 = $t8;
$t2 = $t2 + 1}

When the time comes to translate this pseudo code to MIPS assembly language the
results could 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
below help to make the connection back to the original pseudocode).

bgez $t8, else # if ($t8 is > or = zero) branch to else


sub $s0, $zero, $t8 # $s0 gets the negative of $t8
addi $t1, $t1, 1 # increment $t1 by 1
b next # branch around the else code
else:
ori $s0, $t8, 0 # $s0 gets a copy of $t8
addi $t2, $t2, 1 # increment $t2 by 1
next:
BRANCH IF GREATER THAN ZERO
bgez $v0,else # branch to else if $v0>=0
SHIFT LEFT LOGICAL
A shift left logical of one position moves each bit
to the left by one. The low-order bit (the right-
most bit) is replaced by a zero bit and the high-
order bit (the left-most bit) is discarded.

sll $t2,$v0,2 # set $t2 to result of shifting $v0 left by number specified by b
……………….immediate

48
SE-212L Computer Organization & Architecture SSUET/QR/114

SHIFT RIGHT LOGICAL


MIPS also has a shift right logical instruction. It
moves bits to the right by a number of positions
less than 32. The high-order bit gets zeros and
the low-order bits are discarded.

srl $t2,$v0,2 # set $t2 to result of shifting $v0 right by number specified by
………………immediate

Example Program#1:
Write a program in MIPS assembly language that translate IF-THEN ELSE control
structure.
################## DATA SEGMENT ########################
.data input: .asciiz "\n type any number"
rshift: .asciiz "\n number after right shift: "
lshift: .asciiz "\n number after left shift: "
################## TEXT SEGMENT ########################
.text
.globl main main: la $a0,input #
print input message
li $v0,4
syscall

la $v0,5 # read integer syscall

49
SE-212L Computer Organization & Architecture SSUET/QR/114

bgez $v0,else # if-else equilavent statement IF ($v<0) THEN


$t2=$v0>>2
srl $t2,$v0,2 # shift right logical Print: display $t2
la $a0,rshift # print value of rshift ELSE
li $v0,4 $t2=$v0<<2
syscall Print: display $t2
move $a0,$t2 # print value after right shift
li $v0,1
syscall
b end #branch to statement at end unconditionally

else: sll $t2,$v0,2 #shift left


logical la $a0,lshift # print value
of lshift li $v0,4
syscall

move $a0,$t2 # print value after left shift


li $v0,1 syscall

end: li $v0,10 # terminate


program syscall

OUTPUT:

50
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB TASKS:

1. Take any integer as input.


If the number is greater than 5, print the number.
If the number is less than 5, close program.
If the number is equal to zero, print statement that Number is Zero.
2. Take two integers as input and subtract them.
If the result is positive, save and display it at the memory location of your Name.
3. Write a program in MIPS assembly language that take input from user and print
whether input is greater or less than 10 and also shift input left and right 4 bits.

51
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 12
OBJECTIVE
To Study how to implement translation of “for loop” control structures in MIPS
assembly language.

THEORY
TRANSLATION OF A “FOR LOOP” CONTROL STRUCTURE
Obviously a “ for loop ” control structure is very useful. Let us suppose that a
programmer initially developed an algorithm containing the following pseudocode. In
one sentence, can you describe what this algorithm accomplishes?

$a0 = 0;
For ( $t0 =10; $t0 > 0; $t0 = $t0 -1)
do{$a0 = $a0 + $t0}

The following is a translation of the above “for-loop” pseudocode to MIPS assembly


language code.

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

BRANCH IF GREATER THAN ZERO


bgtz $t0,loop# branch to loop if $t0>0

52
SE-212L Computer Organization & Architecture SSUET/QR/114

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

la $a0,counter # print message of counter li


$v0,4
syscall

move $a0,$t0# print value of $t0


li $v0,1
syscall

addi $t0,$t0,-1# decrement loop variable counter

la $a0,tab # print tab


li $v0,4 syscall

la $a0,total # print message of total


li $v0,4 syscall

move $a0,$a2# print value of $a2


li $v0,1 syscall

bgtz $t0,loop# if($t0>0) branch to loop

end: li
$v0,10
syscall

53
SE-212L Computer Organization & Architecture SSUET/QR/114

OUTPUT:

LAB TASKS:

1. Take any integer from user. If it’s positive, print the integer. Otherwise,
program should be closed. Repeat the task, the no. of times of the last digit of
your roll no.
2. Show the result of following expression: 2n , Where n is last digit of your Roll
No.

54
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 13

OBJECTIVE
To introduce how to implement array as an abstract data structure in MIPS assembly
language

THEORY
Implementing arrays in MIPS Assembly language involves several steps, including
declaring the array in memory, accessing individual elements, and performing
operations on the elements. Here's a step-by-step guide on how to implement and use
arrays in MIPS Assembly:

Step 1: Declaring the Array

In the data section, you can declare an array and initialize it with values. For example:

.data
array: .word 10, 20, 30, 40, 50 # An array of 5 integers length:
.word 5 # Length of the array

Step 2: Accessing Array Elements

To access an element in the array, you need to calculate the address of the element.
Each integer (word) in MIPS is 4 bytes, so you multiply the index by 4 and add it to
the base address of the array.

Step 3: Example Operations

Let's create an example program that sums all the elements in the array.

Summing Array Elements


1. Load the base address of the array.
2. Load the length of the array.
3. Loop through each element, add it to a sum, and finally store or print the sum.

Here's a complete example in MIPS Assembly:

55
SE-212L Computer Organization & Architecture SSUET/QR/114

PROGRAM#1:
Write a program to implement array as an abstract data structure in MIPS assembly
language.

################## DATA SEGMENT ###################


.data array: .word 10, 20, 30, 40, 50 # An array of 5
integers length: .word 5 # Length of the array sum:
.word 0 # To store the sum
################## TEXT SEGMENT ###################
.text
.globl main main:
# Initialize pointers and counters la $t0, array #
Load base address of array into $t0 lw $t1, length
# Load length of array into $t1 li $t2, 0 #
Initialize sum to 0 ($t2) li $t3, 0 # Initialize
index to 0($t3) loop:
beq $t3, $t1, end # If index == length, exit loop sll
$t4, $t3, 2 # Calculate offset (index * 4) add
$t5, $t0, $t4 # Calculate address of array[index] lw
$t6, 0($t5) # Load array[index] into $t6 add $t2,
$t2, $t6 # Add array[index] to sum addi $t3, $t3, 1
# Increment index
j loop # Jump back to the beginning of the loop end:
sw $t2, sum # Store the sum in memory
################## EXIT PROGRAM ###################
li $v0, 10 # Load syscall code for exit syscall
# Make syscall

56
SE-212L Computer Organization & Architecture SSUET/QR/114

LAB # 14

OBJECTIVE
To study how to implement translation of a “switch” control structure in MIPS assembly
language

THEORY
Implementing a switch-case structure in MIPS that includes printing a value requires
integrating the logic for the switch-case with the syscall for printing. Below is an
example MIPS program that demonstrates this.

Here's a complete example in MIPS Assembly:

PROGRAM#1:
Write a program to implement translation of a “switch” control structure in MIPS assembly
language.
################## DATA SEGMENT ###################
.data case1_msg: .asciiz "Case 1: Value is
10\n" case2_msg: .asciiz "Case 2: Value is
20\n" case3_msg: .asciiz "Case 3: Value is
30\n" default_msg: .asciiz "Default case: Value
is 0\n" prompt: .asciiz "Enter an integer: "
################## TEXT SEGMENT ###################
.text
.globl main main:
# Print prompt
la $a0, prompt # Load address of prompt message
li $v0, 4 # Syscall code for printing string
syscall # Print the prompt message
# Read integer
li $v0, 5 # Syscall code for reading integer
syscall # Read the integer
move $t0, $v0 # Move the read integer to $t0

# Switch-case implementation
li $t1, 1 # Load immediate value 1 into $t1
57
SE-212L Computer Organization & Architecture SSUET/QR/114

beq $t0, $t1, case1 # If $t0 == 1, jump to case1 li $t1, 2


# Load immediate value 2 into $t1 beq $t0, $t1,
case2 # If $t0 == 2, jump to case2 li $t1, 3
# Load immediate value 3 into $t1 beq $t0, $t1,
case3 # If $t0 == 3, jump to case3
# Default case default_case:
la $a0, default_msg # Load address of default message
li $v0, 4 # Syscall code for printing string
syscall # Print the default message
j end_switch case1: # Jump to end of switch-case

la $a0, case1_msg # Load address of case1 message


li $v0, 4 # Syscall code for printing string
syscall # Print the case1 message
j end_switch case2: # Jump to end of switch-case

la $a0, case2_msg # Load address of case2 message


li $v0, 4 # Syscall code for printing string
syscall # Print the case2 message
j end_switch case3: # Jump to end of switch-case

la $a0, case3_msg # Load address of case3 message


li $v0, 4 # Syscall code for printing string
syscall # Print the case3 message
j end_switch # Jump to end of switch-case
end_switch:
# End of switch-case structure
# Exit the program
li $v0, 10 # Load the exit syscall code syscall
# Make the syscall to exit

58

You might also like