MIPS Assembly Language Programming Robert Britton download
MIPS Assembly Language Programming Robert Britton download
Britton download
https://ebookname.com/product/mips-assembly-language-programming-
robert-britton/
https://ebookname.com/product/the-art-of-assembly-language-2nd-
edition-randall-hyde/
https://ebookname.com/product/x86-assembly-language-and-c-
fundamentals-1st-edition-joseph-cavanagh/
https://ebookname.com/product/assembly-language-for-intel-based-
computers-4th-edition-kip-r-irvine/
https://ebookname.com/product/hard-zen-soft-heart-christopher-s-
hyatt/
Your Unseen World Datre 4 1st Edition Aona
https://ebookname.com/product/your-unseen-world-datre-4-1st-
edition-aona/
https://ebookname.com/product/standing-eight-the-inspiring-story-
of-jesus-el-matador-chavez-who-became-lightweight-champion-of-
the-world-1st-da-capo-press-ed-edition-pitluk/
https://ebookname.com/product/bard-of-the-bethel-the-life-and-
times-of-boston-s-father-taylor-1793-1871-1st-edition-wendy-
knickerbocker/
https://ebookname.com/product/chemical-process-and-design-
handbook-1st-edition-james-speight/
https://ebookname.com/product/hazardous-materials-
characterization-evaluation-methods-procedures-and-
considerations-1st-edition-edition-donald-a-shafer/
Meanings of Bandung Postcolonial Orders and Decolonial
Visions Qu■nh N. Ph■m
https://ebookname.com/product/meanings-of-bandung-postcolonial-
orders-and-decolonial-visions-quynh-n-pham/
25 Initialize loop counter
Memory
Out
Instruction Register
Control
Address
Logic
Rt
Data In
Register File
MIPS Assembly Language
Programming
MIPS Assembly Language
Programming
Robert Britton
PEARSON
--
Prentice
Hall
QA76.9.A73B79 2004
005.265-dc2 1
2003048273
All rights reserved. No part of this book may be reproduced, in any format or by any means, without permission in
writing from the publisher
The author and publisher of this book have used their best efforts in preparing this book. These efforts include the devel
opment, research, and testing of the theories and programs to determine their effectiveness. The author and publisher
make no warranty of any kind, expressed or implied, with regard to these programs or the documentation containe d in
this book. The author and publisher shall not be liable in any event for incidental or consequential damages in connec
tion with, or arising out of, the furnishing, performance, or use of these programs.
10 9 8 7 6 5 4 3 2 1
ISBN 0-13-142044-5
1 . 1 Introduction 1
1 .2 The Datapath Diagram 2
1 . 3 Basic Functional Components 2
1 .4 The Control Unit 3
1 .5 The MIPS Register File 3
1 .6 The Arithmetic and Logic Unit (ALU) 5
1 .7 The Program Counter (PC) 5
1 . 8 Memory 5
1 . 9 The Instruction Register (IR) 6
1 . 10 Instruction Set 7
1 . 1 1 Addressing Modes 8
1 . 12 The Fetch Execute Cycle 9
Exercises 10
2.1 Introduction 11
2.2 D evelop the Algorithm in Pseudocode 11
2.3 Register Usage Convention 12
2.4 Translation of Arithmetic Expressions 13
2.5 Translation of an if . . . then . . . else . . .
Control Structure 14
2.6 Translation of a while Control Structure 15
2.7 Translation of a for Loop Control Structure 15
2.8 Translation of a switch Control Structure 16
2.9 Encoding The MIPS Instruction Set 17
2.10 Assembler Directives 18
2 . 1 1 Input and Output 19
Exercises 22
vii
viii Contents
3 . 1 Introduction 24
3.2 Positional Notation 24
3.3 Converting Binary Numbers to Decimal Numbers 25
3 .4 Detecting whether a Binary Number Is Odd or Even 25
3.5 Multiplication by Constants That Are a Power of Two 26
3.6 The Double-and-Add Method 26
3 .7 Converting Decimal Numbers to Binary Numbers 27
3.8 The Two's Complement Number System 27
3.9 The Two's Complement Operation 28
3.10 A Shortcut for Finding the Two's Complement of Any Number 28
3 . 1 1 Sign Extension 28
3.12 Binary Addition 29
3.13 Binary Subtraction 29
3 . 14 Overflow Detection 29
3.15 Hexadecimal Numbers 31
Exercises 32
4.1 Introduction 35
4.2 Advantages of a Simulator 35
4.3 Using PCSpim 36
4.4 Analyzing the Text Segment 38
4.5 Analyzing the Data Segment 39
4.6 System I/O (Input/Output) 40
4.7 Deficiencies of the System I/O Services 41
Exercises 42
5 . 1 Introduction 44
5.2 Instructions That Perform Logical Operations 44
5.3 Instructions That Perform Shift Operations 46
5.4 Modular Program Design and Documentation 47
5.5 A Function to Print Values in Hexadecimal Representation 52
5. 6 A Function to Read Values in Hexadecimal Representation 53
5.7 A Function to Print Decimal Values Right Justified 54
5.8 A Function to Read Decimal Values and Detect Errors 54
Exercises 55
6. 1 Introduction 57
6.2 Three Different Memory Segments 57
6.3 Argument-Passing Convention 58
6.4 Nested Function Calls and Leaf Functions 58
6.5 Allocating Space on the Stack for Local Variables 60
Conte nts ix
7 . 1 Introduction 67
7.2 Rules for Writing Reentrant Code 68
7.3 Reentrant I/O Functions 68
7.4 Personal Computers 68
7.5 Recursive Functions 69
7.6 An Example Recursive Function Call 69
7.7 MIPS Memory Segments 71
Exercises 71
8 . 1 Introduction 73
8.2 Memory-Mapped I/O with PCSpim 74
8.3 Communicating With a Keyboard Controller 75
8.4 Communicating With the Display Controller 76
8.5 A Real-Time Clock 76
Exercises 77
9.1 Introduction 79
9.2 Exception Capabilities of PCSpim 80
9.3 CPU Exception Response 80
9.4 The Trap Handler 81
9.5 Enabling I/O Interrupts 82
9.6 Example Code to Enable Interrupts 82
9.7 A Random-Number Generator 84
9.8 Embedded Systems References 85
9.9 A Programmable Timer 86
Exercises 86
1 1 . 1 Introduction 98
1 1 .2 The Floating-Point Register File 99
1 1 .3 Examples 99
1 1 .4 Binary Floating-Point to Decimal Floating-Point Conversion 101
1 1 .5 Decimal Floating-Point to Binary Floating-Point Conversion 102
1 1 . 6 Th e IEEE 754 Floating-Point Standard 103
1 1 .7 Decoding Numbers: The IEEE 754 Floating-Point Standard 104
1 1 .8 A Small 8-Bit Floating-Point Format 105
1 1 .9 Decoding the Denormalized Representation 107
1 1 .10 Underflow and Overflow 108
Exercises 109
http://www.mips.coml
http://www.ecst.csuchico.edu/-britton
http://www.cs.wisc.edu/-Iarus/spim.html
http://www.downcastsystems.comlmipster.asp
http://www.cs. wisc.edu/-larus/SPIM/cod-appa. pdf
http://courses.cs.vt.edu/csonline/NumberSystems/Lessons/
http://www.d6.com/users/checker/pdfs/gdmfp. pdf
xi
Preface
This text is targeted for use in an introductory lower-division assembly language pro
gramming or computer organization course. After students are introduced to the MIPS
architecture using this textbook, they will be well prepared to go on to more advanced
courses in computer organization where any modern reduced instruction set computer
(RISC) is analyzed. This text provides a technique that will make MIPS assembly lan
guage programming a relatively easy task as compared to writing complex Intel™ x86
assembly language code. The skills learned, as a MIPS assembly language programmer,
will facilitate learning other more complex assembly languages if the need ever arises.
Students using this text will acquire an understanding of how the functional compo
nents of modern computers are put together, and how a computer works at the ma
chine language level. It is assumed that students using this text already have some
experience in developing algorithms, and running programs in a high-level language.
Chapter 1 provides an introduction to the basic MIPS architecture, which is a
modern RISe. Chapter 2 shows how to develop code targeted to run on a MIPS
processor using an intermediate pseudocode notation similar to the high-level lan
guage e. Once an algorithm is specified in this pseudocode notation it is a relatively
simple task to translate it to MIPS assembly language. Chapter 3 is an introduction to
the binary number system. This chapter provides simple procedures for converting val
ues from one number system to another. The rules for performing binary arithmetic
are explained. Students will learn how to detect when overflow occurs. Chapter 4 ex
plains the features of the PCSpim simulator for the MIPS architecture, which is avail
able for free.
Within the remaining chapters, a wealth of programming exercises are provided
that every student needs to become an accomplished assembly language programmer.
Instructors are provided with a set of PowerPoint slides. After students have had an op
portunity to develop their pseudocode and the corresponding MIPS assembly lan
guage code, they can be shown example solutions to each of the exercises via the
PowerPoint slides. In Chapter 5, students are presented with the classical input/output
(110) algorithms that involve converting numbers between their integer binary repre
sentation and their ASCII decimal and hexadecimal representation. The utility of logi
cal operators and shift operators are stressed.
In Chapter 6, a specific argument-passing protocol is defined. Most significant pro
gramming projects are a teamwork effort. Emphasis is placed on the important fact that
everyone involved in a teamwork project must adopt the same convention for parameter
xiii
xiv Preface
passing when calling functions. In the case of nested function calls, a specific conven
tion is defined for saving and restoring values in the temporary registers.
In Chapter 7, the necessity for reentrant code is explained, as well as the rules one
must follow to write such functions. In Chapter 8, students are introduced to memory
mapped I/O. The MIPS simulator provides a memory-mapped I/O feature so that stu
dents can gain experience in writing drivers that interface with physical devices. With
this PCSpim feature, students can gain experience in writing code to communicate char
acter by character with physical I/O devices. The code that communicates with a physi
cal device at this level is often referred to as a driver. This is a significant advantage of
using a simulator to learn assembly language programming. Students learning to write
native assembly language typically never have an opportunity to write code that inter
faces directly with the I/O devices. These students have to be satisfied with making calls
to Basic Input Output System (BIOS) procedures that handle the details of communi
cating with the I/O devices. Typically these students never experience the real-world
challenges that arise as a result of the communication and device time delays.
Chapter 9 introduces exceptions and exception processing. PCSpim responds to
interrupts generated by the memory-mapped keyboard and display terminal. Given
this feature, students have an opportunity to experience writing code to respond to in
terrupts. Once again this points out the advantage of using a simulator when learning
to write assembly language code. Students learning to write assembly language code
for their desktop computer typically never have an opportunity to write and run inter
rupt handlers that enable and disable the interrupt system. Typically these students
never experience the real-world challenges that arise in writing the code that resides at
the very heart of the operating system.
In Chapter 10 a pipelined implementation of the MIPS architecture is presented,
and the special programming considerations dealing with delayed loads and delayed
branches are discussed. PCSpim provides an option to run the simulator as if the code
were executing on a pipelined implementation of the MIPS architecture. Using this op
tion, students gain experience in writing assembly language code that will run on a
pipelined implementation. Chapter 1 1 provides a description of the floating-point fea
tures of the MIPS architecture, as well an introduction to the IEEE 754 floating-point
standard.
I would like to acknowledge Bary Pollack, James Gips, Doug Milhous, and Dwite
Brown who adopted the earlier draft versions of this textbook. I wish to express my
special appreciation to Bary Pollack and Tom Fountain for their thorough review of my
initial submission to Prentice Hall, and their many constructive recommendations for
improvements. The feedback from Seyed H. Hosseini, and Wagdy H. Mahmoud was
also quite helpful. I also wish to thank Petra Recter, senior computer science editor,
and John Keegan, production editor, both at Prentice Hall, who so effectively managed
this project. I am especially grateful to my wife, Jan, for her support and encourage
ment. She is my true helpmate and soul mate.
Robert Britton
April 2003
MIPS Assembly Language
Programming
CH APTER 1
1
2 C h a pt e r 1 T h e MIPS Arch itect u re
Memory
Out
Instruction Register
FIGURE 1.1
Interconnecting all of these functional components, except the control unit, are buses.
A bus is nothing more than a set of electrical conducting paths over which different sets
of binary values are transmitted. Most of the buses in the MIPS architecture are 32 bits
wide-in other words, 32 separate, tiny wires running from a source to a destination. In
this datapath diagram, we have the situation where we need to route information from
more than one source to a destination, such as the ALU. One way to accomplish this at
the hardware level is to use a multiplexer. Multiplexers are sometimes called data se
lectors. In Figure 1 . 1 , data selectors are represented by the triangle-shaped symbols.
Every data selector with two input buses must have a single control wire connected to
it. The control unit sends a control signal of zero or one to select which input bus should
be routed to the output. In Figure 1 . 1 , control signal wires are not shown, because it
would make the diagram overly complex. When the control signal to a data selector is
zero, the 32-bit value connected to input port zero will appear on the output of the data
selector. When the control signal is one, the 32-bit value connected to input port one
will appear on the output of the data selector. You will notice in Figure 1 . 1 that there
are two data selectors with three buses connected to their inputs. These data selectors
will have two input control wires. With a 2-bit control signal, it is possible to select be
tween four different input ports.
zero 0 Constant 0
at 1 Reserved for the assembler
vO 2 Used for return values from function calls
vI 3
aO 4 Used to pass arguments to functions
al 5
a2 6
a3 7
to 8 Temporary (Caller-saved, need not be saved by called functions)
t1 9
t2 10
t3 11
t4 12
t5 13
t6 14
t7 15
sO 16 Saved temporary (Callee-saved, called function must save and restore)
sl 17
s2 18
s3 19
s4 20
s5 21
s6 22
s7 23
t8 24 Temporary (Caller-saved, need not be saved by called function)
t9 25
kO 26 Reserved for OS kernel
kl 27
gp 28 Pointer to global area
sp 29 Stack pointer
fp 30 Frame pointer
ra 31 Return address for function calls
The MIPS architecture has a register file containing 32 registers. (See Table 1 . 1 . )
Each register has a capacity t o hold a 32-bit value. Th e range o f signed decimal values that
can be represented with 32 bits is -2,147,483,648 ( _2 31 ) to +2,147,483, 647 ( 2 3 1 - 1 ) .
The process of converting numbers between binary and decimal representation is ex
plained in Chapter 3. When writing at the assembly language level almost every instruc
tion requires that the programmer specify which register file locations will be accessed to
obtain operands, and the location in the register file where the result will be stored. A
convention has been adopted that specifies which registers are appropriate to use in spe
cific circumstances. The registers have been given names that help remind us about this
convention. All register names begin with the dollar-sign symbol in MIPS assembly lan
guage code. It is recommended that every time you see the dollar-sign symbol you say
"register." Register 0 is special; it is the source of the constant value zero. Nothing can be
stored in Register O. Register number 1 has the name Sat, which stands for assembler tem
porary. This register is used by the assembler to implement macro instructions and should
1 .8 Me m o ry 5
not be used by the assembly language programmer. The macro instructions are listed in
Appendix D. Registers $kO and $kl are used by the kernel of the operating system and
should not be used in a user program.
According to the convention, registers 2 and 3 (with the names $vO and $vl) are
used to return values from functions. Registers 4, 5, 6, and 7 with the names SaO, Sal,
$a2 and $a3 are used to pass arguments to functions. The 1 0 registers named $tO
through $t9 are used to hold temporary values. Programmers writing functions typi
cally use these registers. The 8 registers with names $sO through $s7 are used by pro
grammers when writing a main program to hold values that need to be saved (not
modified) while functions are being called. The stack pointer register, Ssp, is initialized
by the operating system to point to a segment of memory called the stack. The return
address register, $ra, is loaded with a return address every time the machine executes
an instruction to call a function. The register named $fp is the frame pointer. Program
mers writing functions use this register to establish a constant reference offset to local
variables and function parameters.
1.8 MEM O RY
Memory can be thought of as a large array of locations where binary information is
stored and from which binary information can be fetched, one "word" at a time. In the
case of the MIPS architecture, the term word refers to a 32-bit quantity. Each location
in memory has a 32-bit address. In the MIPS architecture, memory addresses range
from 0 to 4,294,967,295 ( 2 32 - 1) . The MIPS architecture uses the term half-word to
refer to a 16-bit value, and the term byte to refer to an 8-bit value. The MIPS architec
ture specifies that a word contains 4 bytes, and that the smallest addressable unit of in
formation that can be referenced in memory is a byte. The address of the first byte in a
word is also the address of the 32-bit word. All instrnctions in the MIPS architecture
are 32 bits in length. Therefore, the program counter is incremented by four after each
6 C h a pt e r 1 T h e MIPS Arch itect u re
instruction is fetched, so that the program counter will be pointing to the next instruc
tion in sequence.
The immediate format instructions have a 6-bit op-code field where the opera
tion code is stored to specify what operation should be performed by the MIPS
processor. The last 16 bits of the instruction word contains a binary value (a con
stant) that is used as one of the source operands. These instructions contain a 5-bit
field that specifies a register file location (Rs) from which a source operand value is
fetched and the register file location (Rt) where the result of the instruction opera
tion will be stored. Instructions of this format perform arithmetic or logical opera
tions between a variable in the register file and a constant value stored within the
instruction. Branch instructions, as well as load and store instructions, are encoded in
this format:
Op-Code R8 Rt Immediate
I ffffff I I
sssss ttttt l iiiiiiiiiiiiiiii I
The MIPS architecture defines two jump instructions that are encoded as follows:
Op-Code Target
I 00001f I tttttttttttttttttttttttttt l
When these instructions are executed, they perform the equivalent of a high-level lan
guage "go to" instruction. The lower 26 bits of the instruction are used to specify a lo
cation in memory to jump to where the next instruction will be found to execute.
1.10 Instruct i o n Set 7
Refer to Appendix A for a quick reference to the MIPS instruction set and other use
ful information. Appendix C provides a more detailed description of each of the inte
ger instructions for the MIPS architecture. Note that unique binary codes are assigned
to each instruction. In reviewing the list of instructions in Appendix A, you will find
that the machine has instructions to add and subtract. The operands (source values) for
these operations come from the register file and the results go back to the register file.
When programming in assembly language we use a mnemonic to specify which opera
tion we want the computer to perform, and we specify the register file locations using
the names of the register file locations.
Let us suppose that an assembly language programmer wants to add the contents
of register $a1 to the contents of register $51, and to place the result in register $v1. The
assembly language instruction to accomplish this is
Let us suppose that an assembly language programmer wants to subtract the con
tents of register $sl from the contents of register $50 and place the results in register
$57. The assembly language instruction to accomplish this is
Let us suppose that if the contents of register $56 is less than zero, in other words, neg
ative, we want to branch to a location in the program labeled "Quit." Otherwise (else)
we want to decrement the contents of register $s6. The assembly language instructions
to accomplish this are as follows:
Before concluding this chapter, a few words of record are due to the
two sons of one of the most gifted musicians of the present day. I
allude to the associate brothers Labitsky, who, after a training in the
Musical Conservatory at Prague, and subsequent studies prosecuted
at Leipsig, have become candidates for public favour in England,
where (for the present, at least) they appear to be settled. Their first
appeal to notice in this country took place at Her Majesty’s Theatre,
during the progress of the late Grand National Concerts. Their style
is said to be characterized by firmness and evenness in the bowing,
with a correspondent fulness and purity of intonation.
CHAPTER VI.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com