You are on page 1of 175

CS2100 Computer Organisation

MIPS Programming

RECAP: BELOW YOUR PROGRAM

You write programs in high


level programming languages,
e.g., C, Java
A+B

Compiler translates this into


assembly language statement
add A,B

Assembler translates this


statement into machine
language instructions that the
processor can execute
1000110010100000

2011 Sem 1

MIPS Programming

INSTRUCTION EXECUTION CYCLE


Instruction execution cycle:
fetch, decode, execute.

Fetch: fetch next instruction

(using PC) from memory


into IR.
Decode: decode the
instruction.
Execute: execute
instruction.

Instruction
Fetch
Instruction
Decode
Operand
Fetch
Execute
Result
Store
Next
Instruction

2011 Sem 1

MIPS Programming

INSTRUCTION SET ARCHITECTURE (1/5)

Instruction Set Architecture (ISA): an abstraction on


the interface between the hardware and the lowlevel software.
Software
(to be translated to
the instruction set)
Instruction set architecture
Hardware
(implementing the
instruction set)

2011 Sem 1

MIPS Programming

INSTRUCTION SET ARCHITECTURE (2/5)

The ISA includes everything programmers need to know to


make the machine code work correctly.

It allows computer designers to talk about functions


independently from the hardware that performs them.

This abstraction allows many implementations of varying cost


and performance to run identical software.
Example: Intel x86/IA-32 ISA has been implemented by a range
of processors starting from 80386 [1985] to Pentium 4 [2005]
Other companies such as AMD and Transmeta have
implemented IA-32 ISA as well
A program compiled for IA-32 ISA can execute on any of these
implementations
2011 Sem 1

MIPS Programming

INSTRUCTION SET ARCHITECTURE (3/5)

ISA is determined by

Organization of programmable storage.


Data types and data structures: encoding and representations.
Instruction formats.
Instruction (or operation code, opcode) set.
Modes of addressing and accessing data items and instructions.
Exceptional conditions.

2011 Sem 1

MIPS Programming

INSTRUCTION SET ARCHITECTURE (4/5)


Instruction
Fetch

Instruction format or encoding

Instruction
Decode

Location of operands and result

Operand
Fetch
Execute
Result
Store
Next
Instruction
2011 Sem 1

how is it decoded?

where other than memory?


how many explicit operands?
how are memory operands located?
which can or cannot be in memory?

Data type and size


Operations
what are supported?

Successor instruction
jumps, conditions, branches

Fetch-decode-execute is always done


for any instruction!
MIPS Programming

INSTRUCTION SET ARCHITECTURE (5/5)

Instruction set: language of the machine.


More primitive than high-level languages (eg: no
sophisticated control flow).

More restrictive instructions.


We will study MIPS instruction set, used by NEC,
Nintendo, Silicon Graphics, Sony.

Bonus: hope to do a quickie on the x86 instruction


set.

2011 Sem 1

MIPS Programming

ASSEMBLY LANGUAGE

Machine code
Instructions are represented in binary
1000110010100000 is an instruction that tells one computer to add two
numbers
Hard and tedious for programmer

Assembly language

Symbolic version of machine code


Human readable
add A, B is equivalent to 1000110010100000
Assembler translates from assembly language to machine code
Assembly can provide pseudo-instructions. Example: In MIPS, move
$t0, $t1 is a pseudo-instructions; the actual instruction is add $t0, $t1,
$zero.
When considering performance, only real instructions are counted.
2011 Sem 1

MIPS Programming

RISC VERSUS CISC

Complex Instruction Set Computer (CISC) e.g. x86


Single instruction performs complex operation
VAX architecture had an instruction to multiply polynomials

Smaller program size as memory was premium


Complex implementation, no room for hardware optimization

Reduced Instruction Set Computer (RISC) e.g. MIPS


Keep the instruction set small and simple, makes it easier to
build/optimize hardware
Burden on software to combine simpler operations to implement
high-level language statements

Pentium 4 decomposes many x86 instructions into a series of


internal micro-operations that are executed by the processor
core
CISC ISA but internal RISC implementation

2011 Sem 1

MIPS Programming

10

CONCEPT #1:
DATA STORAGE
Memory Organization
Registers

Concept #1: Data Storage


Concept #2: Memory Addressing Modes
Concept #3: Operations in the Instruction Set
Concept #4: Instruction Formats
Concept #5: Encoding the Instruction Set
Concept #6: Compilers View
2011 Sem 1

MIPS Programming

11

MEMORY ORGANIZATION (1/2)


The main memory can be viewed as a

large, single-dimension array of


memory locations.
Each location of the memory has an
address, which is an index into the
array.
The memory map on the right
contains one byte (8 bits) in every
location/address.
Byte addressing means the index
points to a byte of memory.
Word addressing: see next slide.

2011 Sem 1

MIPS Programming

Address
0
1
2
3
4
5
6
7
8
9
10
11

Memory
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits

:
12

MEMORY ORGANIZATION (2/2)


A word is unit of transfer between
processor and memory.
Assuming 4-byte words and n-bit
address.

2n bytes with byte addresses from 0 to

2n 1.
2n-2 words with byte addresses 0, 4, 8,
, 2n 4.

Words are aligned.


What are the last two bits of the
address of a word, if each word
contains 4 bytes? Answer: 00

2011 Sem 1

MIPS Programming

Address
0

Memory
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits
8 bits

:
13

REGISTERS (1/3)

Fast memories in the processor.


Data are transferred from memory to registers for faster
processing.
Compiler associates variables in program with registers.
(What about programs with many variables?)
Registers have no type, unlike variables.
Code density improves.
Modern architectures predominantly use the load-store
register architecture.
Limited in number. A typical system has 16 to 32 registers.

2011 Sem 1

MIPS Programming

14

REGISTERS (2/3)

MIPS assembly language: 32 registers, referred to by a


number ($0, $1, , $31) or a name (eg: $a0, $t1).
Name

Register
number

Usage

Name

Register
number

Usage

$zero

Constant value 0

$t8-$t9

24-25

$v0-$v1

2-3

Values for results


and expression
evaluation

More
temporaries

$gp

28

Global pointer

$sp

29

Stack pointer

$a0-$a3

4-7

Arguments

$fp

30

Frame pointer

$t0-$t7

8-15

Temporaries

$ra

31

Return address

$s0-$s7

16-23

Program variables

$at (register 1) is reserved for the assembler.


$k0-$k1 (registers 26-27) are reserved for the operation system.

2011 Sem 1

MIPS Programming

15

REGISTERS (3/3)
Classifying general-purpose register computers:
ALU (Arithmetic-Logic Unit) instruction has two or three
operands?
Add R2, R1 (R2=R2+R1) or Add R3, R2, R1 (R3=R2+R1)

How many operands may be memory addresses in an ALU


instruction?
Zero? One? Two? Three?

What are the advantages and disadvantages of


each of these options?

2011 Sem 1

MIPS Programming

16

CONCEPT #2:
MEMORY ADDRESSING MODE
Memory Locations and Addresses
Memory Operations
Addressing Modes

Concept #1: Data Storage


Concept #2: Memory Addressing Modes
Concept #3: Operations in the Instruction Set
Concept #4: Instruction Formats
Concept #5: Encoding the Instruction Set
Concept #6: Compilers View
2011 Sem 1

MIPS Programming

17

MEMORY LOCATIONS AND ADDRESSES


(1/3)
Memory is viewed as a large one-dimensional array of bits.
Group of n bits to store or retrieve in a single operation
to/from the memory is a word.
A word is usually a multiple of bytes and typically 2, 4 or 8
bytes.
Memory is addressed to access a single word or a byte using
a distinct address.
Given k-bit address, the address space is of size 2k.

24-bit address generates 224 (= 16,777,216) addresses or


locations. This is 16M.

2011 Sem 1

MIPS Programming

18

MEMORY LOCATIONS AND ADDRESSES


(2/3)
Byte addressability: Successive memory addresses refer to
successive byte locations in the memory.
Big-endian: most significant byte stored in lowest address.

IBM 360/370, Motorola 68000, MIPS (Silicon Graphics), SPARC.

Little-endian: least significant byte stored in lowest address.


Intel 80x86, DEC VAX, DEC Alpha.
Example: 0xDEADBEEF
Big-endian: Most significant byte first: DE AD BE EF.
Little-endian: Least significant byte first: EF BE AD DE.

2011 Sem 1

MIPS Programming

19

MEMORY LOCATIONS AND ADDRESSES


(3/3)
Word alignment: Words are aligned in memory if they begin at
a byte address that is a multiple of the number of bytes in a
word.
Example: If a word consists of 4 bytes, then:
Address
0
1
2
3
4
5
6
7
2011 Sem 1

Byte 0
Byte 1
Byte 2
Byte 3
Byte 4
Byte 5
Byte 6
Byte 7

Aligned word
Mis-aligned word

MIPS Programming

20

MEMORY OPERATIONS (1/2)


Load (Read): Transfers the contents of a specific
memory location to the processor. The processor
sends address to the memory, and the memory
reads data at that address and sends to processor.

Store (Write): Data from the processor is written at


a specified memory location. Processor sends
address and data to the memory.

2011 Sem 1

MIPS Programming

21

MEMORY OPERATIONS (2/2)


Processor

Up to 2k
addressable
locations.

Address

k-bit address bus

MAR

Memory

0
1
2
3
4
5

n-bit data bus

MDR

Control lines
(R/W, etc.)

2011 Sem 1

MIPS Programming

22

ADDRESSING MODES
Addressing mode

Example

Meaning

Register

Add R4,R3

R4 R4+R3

Immediate

Add R4,#3

R4 R4+3

Displacement

Add R4,100(R1)

R4 R4+Mem[100+R1]

Register indirect

Add R4,(R1)

R4 R4+Mem[R1]

Indexed / Base

Add R3,(R1+R2)

R3 R3+Mem[R1+R2]

Direct or absolute

Add R1,(1001)

R1 R1+Mem[1001]

Memory indirect

Add R1,@(R3)

R1 R1+Mem[Mem[R3]]

Auto-increment

Add R1,(R2)+

R1 R1+Mem[R2]; R2 R2+d

Auto-decrement

Add R1,(R2)

R2 R2-d; R1 R1+Mem[R2]

Scaled

Add R1,100(R2)[R3]

R1 R1+Mem[100+R2+R3*d]

2011 Sem 1

MIPS Programming

23

MIPS ADDRESSING MODES (1/4)


Register (direct) mode
op

rs

rt

op: opcode
rs: first source register

rd

rt: second source register


register

rd: destination register

Example: add $r3, $r1, $r2


$r1 = 100

op

r1

r2

r3

100

2011 Sem 1

MIPS Programming

Note: For illustration


only. This is not the
exact MIPS syntax.

24

MIPS ADDRESSING MODES (2/4)

Immediate mode
op

rs

rt

op: opcode
immed

rs: source register


rt: destination register

Example: addi $r3, $r1, 12


op

2011 Sem 1

r1

r3

immed: constant

12

MIPS Programming

25

MIPS ADDRESSING MODES (3/4)


Displacement mode (base addressing)
op

rs

rt

Memory

immed

register

Example: lw $r1, 100($r2)

Memory

$r2 = 150; 100($r2) = 88


op

r2

r1

100
Address = 250

150
2011 Sem 1

MIPS Programming

250

88
26

MIPS ADDRESSING MODES (4/4)


PC-relative mode
op

rs

rt

immed

PC

Target address

Example: beq $r1, $r2, 6


op

r1

r2

PC

2011 Sem 1

MIPS Programming

Address = (PC +
4) + (6 4)
27

CONCEPT #3: OPERATIONS IN THE


INSTRUCTION SET
Standard Operations in an Instruction Set
Frequently Used Instructions
Instructions for Control Flow

Concept #1: Data Storage


Concept #2: Memory Addressing Modes
Concept #3: Operations in the Instruction Set
Concept #4: Instruction Formats
Concept #5: Encoding the Instruction Set
Concept #6: Compilers View
2011 Sem 1

MIPS Programming

28

STANDARD OPERATIONS

2011 Sem 1

Data Movement

load (from memory)


store (to memory)
memory-to-memory move
register-to-register move
input (from I/O device)
output (to I/O device)
push, pop (to/from stack)

Arithmetic

integer (binary + decimal) or FP


add, subtract, multiply, divide

Shift

shift left/right, rotate left/right

Logical

not, and, or, set, clear

Control flow

Jump (unconditional), Branch (conditional)

Subroutine Linkage

call, return

Interrupt

trap, return

Synchronization

test & set (atomic r-m-w)

String

search, move, compare

Graphics

pixel and vertex operations,


compression/decompression
MIPS Programming

29

FREQUENTLY USED INSTRUCTIONS


Rank instruction

Integer Average Percent total executed

load

22%

conditional branch

20%

compare

16%

store

12%

add

8%

and

6%

sub

5%

move register-register

4%

call

1%

10

return

1%

Total

96%

Make these instructions fast!


Amdahls law make the
common case fast!

Simple instructions dominate instruction frequency


2011 Sem 1

MIPS Programming

30

INSTRUCTIONS FOR CONTROL FLOW

Branch: conditional (if <condition> go to <address>)


Jump: unconditional (go to <address>)
Procedure calls/returns
Addressing modes for control-flow instructions:

PC-relative: destination address = displacement + value in PC

(When target address is near the current instruction, it requires


only a few bit. Code can run independently of where it is loaded
position independence.)
Register indirect jumps: a register is specified, which will
contain the target address.
(Value in the specified register is usually not known at compile
time, but is computed at run time.)

2011 Sem 1

MIPS Programming

31

CONCEPT #4:
INSTRUCTION FORMATS
Instruction Length
Instruction Fields
Type and Size of Operands

Concept #1: Data Storage


Concept #2: Memory Addressing Modes
Concept #3: Operations in the Instruction Set
Concept #4: Instruction Formats
Concept #5: Encoding the Instruction Set
Concept #6: Compilers View
2011 Sem 1

MIPS Programming

32

INSTRUCTION LENGTH
Variable-length instructions.
Intel 80x86: Instructions vary from 1 to 17
bytes long.
Digital VAX: Instructions vary from 1 to 54
bytes long.
Require multi-step fetch and decode.
Allow for a more flexible (but complex) and
compact instruction set.

Fixed-length instructions.

Used in most RISC (Reduced Instruction Set Computers)


MIPS, PowerPC: Instructions are 4 bytes long.
Allow for easy fetch and decode.
Simply pipelining and parallelism.
Instruction bits are scarce.

Hybrid instructions: a mix of variable- and fixed-length instructions.


2011 Sem 1

MIPS Programming

33

INSTRUCTION FIELDS
An instruction consists of opcode and a certain number
(possible zero) of operands.

Each instruction has a unique opcode, but:


How many operands?
Are the operands registers or memory?

Current high-end processors allow for three register


operands.

Hence if there are 32 registers, then 3 x 5 = 15 bits are used up


for the operands.

For every direct memory operand, at least one operand will be


taken away.

Example: LOAD/STORE instructions only have two operands.


2011 Sem 1

MIPS Programming

34

TYPE AND SIZE OF OPERANDS


Encoding in the opcode designates the type of an operand.
Add R3, R2, R1

Character (8 bits), half-word (eg: 16 bits), word (eg: 32 bits),


single-precision floating point (eg: 1 word), double-precision
floating point (eg: 2 words).

Expectations from any new 32-bit architecture:


Support for 8-, 16- and 32-bit integer and 32-bit and 64-bit
floating point operations. A 64-bit architecture would need to
support 64-bit integers as well.

2011 Sem 1

MIPS Programming

35

CONCEPT #5: ENCODING THE


INSTRUCTION SET
Instruction Encoding
Encoding for Fixed-Length Instructions

Concept #1: Data Storage


Concept #2: Memory Addressing Modes
Concept #3: Operations in the Instruction Set
Concept #4: Instruction Formats
Concept #5: Encoding the Instruction Set
Concept #6: Compilers View
2011 Sem 1

MIPS Programming

36

INSTRUCTION ENCODING (1/2)


How are instructions represented in binary format for
execution by the processor?

Issues:
Code size, speed/performance, design complexity.

Things to be decided:
Number of registers
Number of addressing modes
Number of operands in an instruction

The different competing forces:


Have many registers and addressing modes
Reduce code size
Have instruction length that is easy to handle (fixed-length
instructions are easy to handle)
2011 Sem 1

MIPS Programming

37

INSTRUCTION ENCODING (2/2)


Three encoding choices: variable, fixed, hybrid.

2011 Sem 1

MIPS Programming

38

ENCODING FOR FIXED-LENGTH INSTRUCTIONS


(1/4)

How to fit multiple sets of instruction types into a fixed-length


instruction format? Work out the most constrained set first.

An expanding opcode scheme is one where the opcode has


variable lengths for different instructions. This maximizes the
instruction bits.

Example: Given a fixed-length instruction set where each


instruction contains 16 bits. Some instructions (call it type-A)
require 2 operands, while other instructions (call it type-B)
require only 1 operand. Each operand takes up 5 bits.

2011 Sem 1

MIPS Programming

39

ENCODING FOR FIXED-LENGTH INSTRUCTIONS


(2/4)

If we assume the all opcodes must have the same size, to


allow for the maximum number of instructions, the opcodes
must be 6 bits long.
Type-A instructions

Type-B instructions

opcode

operand

operand

6 bits

5 bits

5 bits

opcode

operand

unused

6 bits

5 bits

5 bits

We see that there are wasted bits, and the maximum total
number of instructions is 26 or 64.

2011 Sem 1

MIPS Programming

40

ENCODING FOR FIXED-LENGTH INSTRUCTIONS


(3/4)

If we allow the opcode for type-B instructions to be 11 bits


long, we may have a bigger set of instructions.
Type-A instructions

Type-B instructions

opcode

operand

operand

6 bits

5 bits

5 bits

opcode

operand

11 bits

5 bits

This is known as expanding opcode.

Encoding concern: The first 6 bits of the opcode for any typeB instruction must not be identical to the opcode of any of the
type-A instructions. (Why?)

2011 Sem 1

MIPS Programming

41

ENCODING FOR FIXED-LENGTH INSTRUCTIONS


(4/4)

What is the maximum total number of instructions


possible?

Type-A instructions

opcode

operand

operand

6 bits

5 bits

5 bits

opcode

operand

11 bits

5 bits

Type-B instructions

Answer: 1 + (26 1) 25 = 1 + 6332 = 2017.

How? Let there be 1 type-A instruction (assume the opcode is


000000 the choice is arbitrary), then there are (26 1) valid
patterns for the first 6 bits of the type-B instructions, followed
by any 5 bits.

2011 Sem 1

MIPS Programming

42

EXAMPLE
Design an expanding opcode for the following to be encoded in a
36-bit instruction format. An address takes up 15 bits and a register
number 3 bits.
7 instructions with two addresses and one register number.
500 instructions with one address and one register number.
50 instructions with no address or register.
One
possible
answer:

3 bits

15 bits

15 bits

3 bits

000 110
opcode

address

address

register

111

000000 + 9 bits
opcode

address

register

unused

unused

111

2011 Sem 1

000001
:
+ 9 0s
110010
opcode
MIPS Programming

43

CONCEPT #6: COMPILERS VIEW

Considerations for Compiler

Concept #1: Data Storage


Concept #2: Memory Addressing Modes
Concept #3: Operations in the Instruction Set
Concept #4: Instruction Formats
Concept #5: Encoding the Instruction Set
Concept #6: Compilers View
2011 Sem 1

MIPS Programming

44

CONSIDERATIONS FOR COMPILER


Ease of compilation.
Orthogonality: no special registers, few special cases, all operand
modes available with any data type or instruction type.

Completeness: support for a wide range of operations and target


applications.

Regularity: no overloading for the meanings of instruction fields.


Streamlined: resource needs easily determined.
Provide at least 16 general-purpose registers plus separate floatingpoint registers.

Be sure all addressing modes apply to all data transfer instructions.


Aim for a minimalist instruction set.
2011 Sem 1

MIPS Programming

45

MIPS ASSEMBLY LANGUAGE

MIPS ASSEMBLY LANGUAGE


In MIPS assembly language, each instruction
executes a simple command
Each line of assembly code contains at most 1
instruction
Instructions are related to operations (+, -, *, /, =) in
C/Java
# is used for comments

Anything from # mark to end of line is a comment and will


be ignored
add $t0, $s1, $s2
sub $s0, $t0, $s3
2011 Sem 1

# tmp = b + c
# a = tmp - d

MIPS Programming

47

ARITHMETIC: ADDITION

Addition in assembly
C:
a = b + c;
MIPS: add $s0, $s1, $s2
$s0 variable a
$s1 variable b
$s2 variable c

Natural number of operands for an instruction is 3 (2 sources


+ 1 destination)

Why?
Keep the hardware simple
Design principle: Simplicity favors regularity

2011 Sem 1

MIPS Programming

48

INSTRUCTION SYNTAX
add

$s0, $s1, $s2


Source 2

Operation

Source 1
Destination
(gets the result)

$s0 = $s1 + $s2


2011 Sem 1

MIPS Programming

49

RECALL: MIPS REGISTERS

MIPS assembly language: 32 registers, referred to by a


number ($0, $1, , $31) or a name (eg: $a0, $t1).
Name

Register
number

Usage

Name

Register
number

Usage

$zero

Constant value 0

$t8-$t9

24-25

$v0-$v1

2-3

Values for results


and expression
evaluation

More
temporaries

$gp

28

Global pointer

$sp

29

Stack pointer

$a0-$a3

4-7

Arguments

$fp

30

Frame pointer

$t0-$t7

8-15

Temporaries

$ra

31

Return address

$s0-$s7

16-23

Program variables

$at (register 1) is reserved for the assembler.


$k0-$k1 (registers 26-27) are reserved for the operation system.

2011 Sem 1

MIPS Programming

50

ARITHMETIC: SUBTRACTION

Subtraction in assembly
C:
MIPS:

a = b c;
sub $s0, $s1, $s2

$s0 variable a
$s1 variable b
$s2 variable c

$s0 = $s1 - $s2

Positions of $s1 and $s2 (i.e., source1 and


source2) are important for subtraction

2011 Sem 1

MIPS Programming

51

COMPLEX STATEMENTS (1/2)

C statement
a = b + c - d;
A single instruction can handle at most two source operands.
Break it up into multiple instructions and use temporary
register $t0 $t7
add $t0, $s1, $s2 # tmp = b + c
sub $s0, $t0, $s3 # a = tmp - d
A single line of C statement may break up into several lines of
MIPS assembly
Who is doing this break up when you write high-level
language code?

2011 Sem 1

MIPS Programming

52

COMPLEX STATEMENTS (2/2)

C statement
f = (g + h) (i + j);

Break it up into multiple instructions

Replace variables by registers $s0 $s7

Use two temporary registers $t0, $t1


add $t0, $s1, $s2 # tmp0 = g + h
add $t1, $s3, $s4 # tmp1 = i + j
sub $s0, $t0, $t1 # a = tmp0 tmp1

2011 Sem 1

MIPS Programming

53

TRY IT YOURSELF

z = a + b + c + d;
a:$s0

b:$s1

c:$s2

add $t0, $s0, $s1


add $t1, $s2, $s3
add $s4, $t0, $t1

z:$s4

# tmp0 = a + b
# tmp1 = c + d
# z = tmp0 + tmp1

z = (a b) + c;
a:$s0

b:$s1

c:$s2

sub $t0, $s0, $s1


add $s4, $t0, $s2

d:$s3

2011 Sem 1

z:$s4

# tmp0 = a - b
# z = tmp0 + c

MIPS Programming

54

CONSTANT/IMMEDIATE OPERANDS
Immediates are numerical constants
They appear often in operations; so there is special instruction
for them
Add immediate (addi)

C:
a = a + 4;
MIPS: addi $s0, $s0, 4

# $s0 = $s0 + 4

Syntax is similar to add instruction; but source2 is a constant


instead of register
Design principle: Make common case fast
No subi instruction in MIPS why?

2011 Sem 1

MIPS Programming

55

REGISTER ZERO
One particular immediate, the number zero (0), appears very
often in code
Define register zero ($0 or $zero) to always have the value 0

C:
f = g;
MIPS: add $s0, $s1, $zero

where MIPS registers $s0 and $s1 are associated with


variables f and g
This instruction
add $zero, $zero, $s0

does not do anything!

2011 Sem 1

MIPS Programming

56

LOGICAL OPERATIONS

Arithmetic instructions view content of a register as a single quantity


(signed or unsigned integer)
New perspective: View register as 32 raw bits rather than as a
single 32-bit number
Consequence: Useful to operate on individual bytes or bits within a
word

Logical operation C operator Java operator


Shift Left

<<

<<

MIPS instruction
sll

Shift right

>>

>>, >>>

srl

Bitwise AND

&

&

and, andi

Bitwise OR

or, ori

Bitwise NOT

nor

2011 Sem 1

MIPS Programming

57

SHIFT INSTRUCTIONS (1/2)

Opcode: sll (shift left logical)


Move all the bits in a word to the left by a number of bits; fill the
emptied bits with zeroes

Example: register $s0 contains


0000 1000 0000 0000 0000 0000 0000 1001
sll $t2, $s0, 4 # $t2 = $s0<<4
shifts left by 4 bits results in content of register $t2
1000 0000 0000 0000 0000 0000 1001 0000

Q: Shifting left by n bits gives the same result as


n
multiplying by what value? Answer: 2

2011 Sem 1

MIPS Programming

58

SHIFT INSTRUCTIONS (2/2)

Opcode: srl (shift right logical)


Shifts right and fills emptied bits with zeroes

Q: Shifting right by n bits is the same as what


mathematical operation? Answer: Division by 2n

Shifting is faster than multiplication/division

Good compiler translates such multiplication/division


into shift instructions:
C:
MIPS:

2011 Sem 1

a = a * 8;
sll $s0, $s0, 3

MIPS Programming

59

BITWISE AND INSTRUCTION (1/2)


AND: bitwise operation that leaves a 1 only if both the
bits of the operands are 1
Example: and $t0, $t1, $t2

$t1: 0000 0000 0000 0000 0000 1101 0000 0000


$t2: 0000 0000 0000 0000 0011 1100 0000 0000
$t0: 0000 0000 0000 0000 0000 1100 0000 0000

AND can be used to create a mask. Force 0s into the


positions that you are not interested; other bits will
remain the same as the original.

2011 Sem 1

MIPS Programming

60

BITWISE AND INSTRUCTION (1/2)

Example: andi $t0, $t1, 0xFFF


$t1:
0000 1001 1100 0011 0101 1101 1001 1100
0xFFF: 0000 0000 0000 0000 0000 1111 1111 1111
$t0:
0000 0000 0000 0000 0000 1101 1001 1100

In the above example we are interested in the last


12 bits of the word in register $t1. So we use
0xFFF as the mask.

2011 Sem 1

MIPS Programming

61

BITWISE OR INSTRUCTION
OR: bitwise operation that places a 1 in the result if
either operand bit is 1
Can be used to force certain bits to 1s
Example: ori $t0, $t1, 0xFFF

$t1:
0000 1001 1100 0011 0101 1101 1001 1100
OxFFF: 0000 0000 0000 0000 0000 1111 1111 1111
$t0:
0000 1001 1100 0011 0101 1111 1111 1111

If both operands are registers then use or


Example: or $t0, $t1, $t2

2011 Sem 1

MIPS Programming

62

BITWISE NOR INSTRUCTION


Required operation is NOT; toggles the bits of an
operand (1 with 0, 0 with 1)
To maintain regularity (simplicity favors regularity),
MIPS uses NOR instead of NOT

If one operand of NOR is 0, then it is equivalent to NOT:


A NOR 0 = NOT(A OR 0) = NOT(A)

Example: nor $t0, $t1, $zero


$t1: 0000 1001 1100 0011 0101 1101 1001 1100
$t0: 1111 0110 0011 1100 1010 0010 0110 0011

There is no nori in MIPS why?

2011 Sem 1

MIPS Programming

63

READING ASSIGNMENT

Instructions: Language of the Computer


Read up COD Chapter 2, pages 46-53, 58-59, 68-71.

2011 Sem 1

MIPS Programming

64

Programming in MIPS
Assembly Code

2011 Sem 1

MIPS Programming

65

MIPS PROGRAMMING MODEL

Data

MIPS memory is an array of 232 bytes.


Each byte has a 32 bit address
User programs and data are restricted to the first 2 31 bytes
Second half of memory is used by operating system

Operations
Load: a word (4 bytes) is transferred from memory to register
Store: a word (4 bytes) is transferred from memory to a register
Arithmetic-logic operations
Between registers
Between registers and immediate operands

2011 Sem 1

MIPS Programming

66

REGISTERS
General

purpose registers: may contain


integers, or addresses
$0$31
Also denoted by functional mnemonics
$t0-$t10
$s0-$s7
$a0-$a3
$v0-$v1
$sp, $ra, $zero, etc

Floating
2011 Sem 1

point registers
MIPS Programming

67

REGISTERS AND THE ALU

2011 Sem 1

MIPS Programming

68

REGISTER USE CONVENTION

2011 Sem 1

MIPS Programming

69

MEMORY LAYOUT

Text Segment: holds the machine code of the user


program (the text).

Data Segment: data that the program operates on.


Static: size in bytes does not change during execution
Dynamic data: This is data that is allocated and deallocated as
the program executes.
In "C" dynamic allocation and deallocation is done with malloc()
and free().

Stack Segment: top of user address space is the stack.


local variables and parameters are pushed and popped on the
stack as procedures are activated and deactivated.

2011 Sem 1

MIPS Programming

70

MEMORY LAYOUT

2011 Sem 1

MIPS Programming

71

MEMORY ACCESS INSTRUCTIONS


Only load and store instructions can access memory data.
Example: Each array element occupies a word.
C code: A[7] = h + A[10];
MIPS code:

lw
$t0, 40($s3)
add
$t0, $s2, $t0
sw
$t0, 28($s3)
Each array element occupies a word (4 bytes).
$s3 contains the base address (address of first element) of
array A.

Remember arithmetic operands (for add) are registers, not


memory!
2011 Sem 1

MIPS Programming

72

LOAD WORD INSTRUCTION


Example: lw

$s0 + 4

$s0 = 8000

$t0, 4($s0)
8007
8006
8005
8004
8003
8002
8001
8000

Word at address
$s0 + 4

Register $t0

Load (read) the content from the memory word at


address $s0 + 4 to the register $t0.
2011 Sem 1

MIPS Programming

73

STORE WORD INSTRUCTION


Example: sw

$s0 + 12

$s0 = 8000

$t0, 12($s0)
8015
8014
8013
8012
:
8003
8002
8001
8000

Word at address
$s0 + 12
:

Register $t0

Store (write) the content of register $t0 to the


memory word at address $s0 + 12.
2011 Sem 1

MIPS Programming

74

OTHER LOAD/STORE INSTRUCTIONS (1/2)

Besides the load word (lw) and store word (sw)


instructions, there are also the load byte (lb) and
store byte (sb) instructions.

Similar in format:
lb
sb

$t1, 12($s3)
$t2, 13($s3)

Similar in working except that one byte, instead of


one word, is loaded or stored.

2011 Sem 1

MIPS Programming

75

OTHER LOAD/STORE INSTRUCTIONS (2/2)

MIPS disallows loading/storing a word that crosses


the word boundary. Use the unaligned load word
(ulw) and unaligned store word (usw) instructions
instead. These are pseudo-instructions.

There are other instructions such as


lh and sh: load halfword and store halfword
lwl, lwr, swl, swr: load word left, load word right, store word
left, store word right.
And others.

2011 Sem 1

MIPS Programming

76

ARRAYS (1/2)

Variable h is associated with register $s2. Array A


has starting (base) address in register $s3

C statement: A[3] = h + A[1];

Transfer A[1] from memory to register


lw

$t0, 4($s3)

# offset = 14 = 4

Perform addition; reuse temp register $t0


add $t0, $s2, $t0

Store the sum into A[3]


sw

2011 Sem 1

$t0, 12($s3) # offset = 34 = 12


MIPS Programming

77

ARRAYS (2/2)
A[3]
12($s3)

A[3] = h + A[1];

A[2]

lw $t0, 4($s3)
add $t0, $s2, $t0
sw $t0, 12($s3)

A[1]
4($s3)
A[0]
$s3

2011 Sem 1

MIPS Programming

78

ADDRESS VERSUS VALUE

Key concept: Registers do not have types

A register can hold any 32-bit number. That number


can be a value; but it can also be a memory
address.

If you write add $t2, $t1, $t0 then $t0 and


$t1 should contain data values.

If you write lw $t2,0($t0) then $t0 should


contain a memory address.

Do not mix these things up!

2011 Sem 1

MIPS Programming

79

BYTE VERSUS WORD

Impt: Consecutive word addresses in machines with


byte-addressing do not differ by 1.

Many an assembly language programmer has toiled


over errors made by assumption that the address of
the next word can be found by incrementing the
address in a register by 1 instead of by the word
size in bytes.

For both lw and sw the sum of base address and


offset must be multiple of 4.

2011 Sem 1

MIPS Programming

80

EXAMPLE
swap(int v[], int k)
$5 contains k.
{ int temp;
$2 contains 4k
temp = v[k]
(because each word
Base address
v[k] = v[k+1];
of array v in $4
contains 4 bytes)
v[k+1] = temp;
}
swap:
muli $2, $5, 4
add $2, $4, $2
lw $15, 0($2)
lw $16, 4($2)
sw $16, 0($2)
sw $15, 4($2)
jr $31
2011 Sem 1

MIPS Programming

81

CONSTANTS
Small constants are used quite frequently (50% of operands).
Examples:
A = A + 5;
B = B + 1;
C = C 18;

Solution:

Put typical constants in memory and load them.


Create hard-wired registers (like $zero) for constants like one.
Embed them into the instruction code.
For MIPS instructions, we use the immediate operand version:
addi
slti
andi
ori

2011 Sem 1

$29, $29, 4
$8, $18, 10
$29, $29, 6
$29, $29, 4
MIPS Programming

82

LARGE CONSTANTS (1/3)


Recall bit-wise operations: or, ori, and, andi.
Examples:
1010 or 1001 1011
1010
or

1010 and 1001


1000
1010

1001

and

1011

1001
1000

Question: How to load a 32-bit constant into a register?


Example: 1010101010101010 1111000011110000
2011 Sem 1

MIPS Programming

83

LARGE CONSTANTS (2/3)


Need to use two instructions: load upper immediate (lui)
and or immediate (ori):
lui $t0, 1010101010101010
1010101010101010

0000000000000000

Lower-order bits
filled with zeros.

Then to get the lower-order bits correct:


ori

ori

$t0, $t0, 1111000011110000

1010101010101010

0000000000000000

0000000000000000

1111000011110000

1010101010101010

1111000011110000

Question: Why do we use ori instead of addi?


2011 Sem 1

MIPS Programming

84

LARGE CONSTANTS (3/3)


The above are just illustration of the concept. In the actual
instruction, the value is entered as a decimal value or an
hexadecimal value (prefixed by 0x).

Example:
lui

$t0, 43690

# 4369010 = 10101010101010102

lui

$t0, 0xAAAA

# AAAA16 = 10101010101010102

or

Example: To add 0xABABCDCD to $t0:


lui
ori
add

2011 Sem 1

$at, 0xABAB
$at, $at, 0xCDCD
$t0, $t0, $at

$at is a special register


used by compiler to form
large constants

MIPS Programming

85

Load Address Pseudoinstruction

2011 Sem 1

MIPS Programming

86

LA Example

2011 Sem 1

MIPS Programming

87

Symbolic Address

2011 Sem 1

MIPS Programming

88

MAKING DECISIONS (1/2)

So far all the instructions only manipulate data


weve built a calculator

A computer needs the ability to make decisions

High-level language decisions


if and goto statements

MIPS decision making instructions are similar to if


statement with a goto

goto is discouraged in high-level languages but


necessary in assembly

2011 Sem 1

MIPS Programming

89

MAKING DECISIONS (2/2)

Decision-making instructions
Alter the control flow of the program
Change the next instruction to be executed

Two type of decision-making statements


Conditional (branch)
bne $t0, $t1, label
beq $t0, $t1, label
Unconditional (jump)
j label

2011 Sem 1

MIPS Programming

90

CONDITIONAL BRANCH

Processor follows the branch conditionally

beq $r1,$r2, L1
go to statement labeled L1 if the value in register $r1 equals the
value in register $r2
beq is branch if equal
C code: if (a == b) goto L1

bne $r1, $r2, L1


go to statement labeled L1 if the value in register $r1 does not
equal the value in register $r2
bne is branch if not equal
C code: if (a != b) goto L1

2011 Sem 1

MIPS Programming

91

UNCONDITIONAL JUMP

Processor always follows the branch

j L1
Jump to label L1 unconditionally
C code: goto L1

Technically equivalent to such statement


beq $s0, $s0, L1

2011 Sem 1

MIPS Programming

92

IF STATEMENT (1/2)

C statement: if (i == j) f = g + h;

Mapping f:$s0; g:$s1; h:$s2; i:$s3; j:$s4

MIPS statements:
bne $s3, $s4, Exit
add $s0, $s1, $s2
Exit:

# if (i!=j) Exit
# f = g + h

Why use bne instead of beq? For efficiency.


beq $s3, $s4, L1
j Exit
L1: add $s0, $s1, $s2
Exit:

2011 Sem 1

# if (i==j) goto L1
# goto Exit
# f = g + h

MIPS Programming

93

IF STATEMENT (2/2)

C statement:
if (i == j) f = g + h;
else f = g - h;

Mapping f:$s0; g:$s1; h:$s2; i:$s3; j:$s4

MIPS statements:
bne
add
j
Else: sub
Exit:

true

$s3, $s4, Else


$s0, $s1, $s2
Exit
$s0, $s1, $s2

false
Else:

f = g+h

Q: Rewrite using beq


2011 Sem 1

i==j?

f = g-h

Exit:
MIPS Programming

94

LOOPS (1/2)

C statement: while (j == k) i = i+1;

Rewrite code with if and goto statements


Loop: if (j != k) Exit;
i = i+1;
goto Loop;
Exit:

Key concept: The key to decision making is


conditional branches. Any form of loop can be written
in assembly with the help of conditional branches and
jumps.

2011 Sem 1

MIPS Programming

95

LOOPS (2/2)

Code:
Loop: if (j != k) Exit;
i = i+1;
goto Loop;
Exit:

Write MIPS statement using mapping i:$s3; j:$s4; k:$s5


Loop: bne $s4, $s5, Exit
addi $s3, $s3, 1
j
Loop
Exit:

2011 Sem 1

# if (j!= k) Exit
# repeat loop

MIPS Programming

96

INEQUALITIES (1/2)
We have beq and bne, what about branch-if-lessthan? We do not have a blt instruction.
Use slt (set on less than) or slti.

slt $t0, $s1, $s2

2011 Sem 1

MIPS Programming

if ($s1 < $s2)


$t0 = 1;
else
$t0 = 0;

97

INEQUALITIES (2/2)
To build

a blt $s1, $s2, L instruction:

slt $t0, $s1, $s2


bne $t0, $zero, L
C code: if (a < b) goto L;

2011 Sem 1

MIPS Programming

98

ARRAY AND LOOP


Typical example of accessing array elements in a
loop:

Initialization for result variables,


loop counter, and array pointers.

Label:

Work by:
1. Calculating address
2. Load data
3. Perform task

Update loop counter and array


pointers.

Compare and branch.

2011 Sem 1

MIPS Programming

99

ARRAY AND LOOP: EXAMPLE (1/3)


Given a word array A with 40 elements A[0], A[1], , A[39],
with the starting array address stored in $t0. Count the
number of array elements with value zero, and store the result
in $t8.
Answer 1:
addi
addi
L1: add
lw
bne
addi
L2: addi

$t8, $zero, 0
$t1, $zero, 0
$t2, $t0, $t1
$t3, 0($t2)
$zero, $t3, L2
$t8, $t8, 1
$t1, $t1, 4

# initialize counter to zero


# $t1 as index, init. to point to 1st element
# address of current element
# load current element from memory
# check if data is zero, if not, skip update
# increment counter
# point to next element

How to compare and loop back?


bne
2011 Sem 1

$t1, 160, L1 ? No immediate compare operand!


MIPS Programming

100

ARRAY AND LOOP: EXAMPLE (2/3)


Answer 2:
addi
addi
L1: add
lw
bne
addi
L2: addi
bne

$t8, $zero, 0
$t1, $zero, 156
$t2, $t0, $t1
$t3, 0($t2)
$zero, $t3, L2
$t8, $t8, 1
$t1, $t1, 4
$t1, $zero, L1

# initialize counter to zero


# $t1 as index, init. to pt to last element
# address of current element
# load current element from memory
# check if data is zero, if not, skip update
# increment counter
# point to previous element

How about the iteration for the first element?

2011 Sem 1

MIPS Programming

101

ARRAY AND LOOP: EXAMPLE (3/3)


Answer 3:
addi
addi
L1: add
lw
bne
addi
L2: addi
bne

$t8, $zero, 0
$t1, $zero, 160
$t2, $t0, $t1
$t3, 4($t2)
$zero, $t3, L2
$t8, $t8, 1
$t1, $t1, 4
$t1, $zero, L1

# initialize counter to zero


# $t1 as index, init. to point pass
# last element
# address of current element
# load preceding element from memory
# check if data is zero, if not, skip update
# increment counter
# point to previous element

Is this correct now?

2011 Sem 1

MIPS Programming

102

Calling procedures

PROCEDURE CALL
jal ProcedureAddress
jal = jump and link
First, PC + 4 is stored in $ra
Then, an unconditional jump is performed to
ProcedureAddress
At the end of the procedure, return with
jr $ra

2011 Sem 1

MIPS Programming

104

REGISTER USE
Registers

$s0-$s7: saved registers must


be preserved by callee, i.e. saved before
use, and then restored at the end of
procedure
Space to save: a stack, whose top is
stored in register $sp
Registers $t0-$t9: temporary registers, not
preserved by callee.
2011 Sem 1

MIPS Programming

105

Stack

2011 Sem 1

MIPS Programming

106

Upside-Down MIPS Stack

2011 Sem 1

MIPS Programming

107

Push

2011 Sem 1

MIPS Programming

108

Pop

2011 Sem 1

MIPS Programming

109

Callers and Callees

2011 Sem 1

MIPS Programming

110

Callers and Callees


The subroutine is only used once in the main
program because it always returns to the same
location.
A subroutine call is when a main routine passes
control to a subroutine. The main routine is said
to be the CALLER and the subroutine is said to
be the CALLEE. A return from a subroutine is
when a subroutine passes control back to its
CALLER.
When the CALLEE finishes execution it nearly
always returns control to its CALLER.

2011 Sem 1

MIPS Programming

111

Many Calls but One Return

2011 Sem 1

MIPS Programming

112

The jal Instruction

2011 Sem 1

MIPS Programming

113

The jal Instruction

2011 Sem 1

MIPS Programming

114

Example jal Instruction

2011 Sem 1

MIPS Programming

115

Example jal Instruction

2011 Sem 1

MIPS Programming

116

The jr Instruction

2011 Sem 1

MIPS Programming

117

Calling Convention

2011 Sem 1

MIPS Programming

118

Simple Linkage Convention

2011 Sem 1

MIPS Programming

119

Pushing the Return Address

2011 Sem 1

MIPS Programming

120

Chain of Calls

2011 Sem 1

MIPS Programming

121

Register Problem
Registers $s0$s7 must not be altered by a
subroutine.
This restriction creates a problem when
subroutines call other subroutines.
The solution is to allow a subroutine to use
$s0$s7. However, before using one of these
registers, the subroutine must save its value on
the stack.
Later, when the subroutine returns to its caller, it
must restore the register to its initial state.

2011 Sem 1

MIPS Programming

122

Stack Linkage

2011 Sem 1

MIPS Programming

123

Stack Linkage

2011 Sem 1

MIPS Programming

124

Nested Subroutine Calls

2011 Sem 1

MIPS Programming

125

Frame Pointer

2011 Sem 1

MIPS Programming

126

Frame-Based Linkage Convention

2011 Sem 1

MIPS Programming

127

Frame-Based Linkage Convention

2011 Sem 1

MIPS Programming

128

Frame-Based Linkage Convention

2011 Sem 1

MIPS Programming

129

NON-NESTED PROCEDURE
int leaf_example
(int g, int h, int i, int j) {
int f ;
f = (g+h)-(i+j) ;
return f ;
}

2011 Sem 1

MIPS Programming

130

MIPS TRANSLATION
Leaf_example:
addi $sp,$sp,-12 # room for 3 vars
sw $t1,8($sp)
sw $t0,4($sp)
sw $s0,0($sp)
add $t0,$a0,$a1 # $t0=g+h
add $t1,$a2,$a3 # $t1=i+j
sub $s0,$t0,$t1 # f = $t0-$t1
add $v0,$s0,$zero # returns the result in $v0
lw $s0,0($sp) # restore $s0
lw $t0,4($sp) # restore $t0
lw $t1,8($sp) # restore $t1
add $sp,$sp,12 # restore stack
jr $ra # jump back to calling routine

2011 Sem 1

MIPS Programming

131

NESTED PROCEDURE

int fact (int n) {


if ( n < 1 ) return 1 ;
else return n * fact(n-1) ;
}

2011 Sem 1

MIPS Programming

132

MIPS TRANSLATION
Fact: addi $sp,$sp,8 # make room for 2 items
sw $ra,4($sp) # save the return address
sw $a0,0($sp) # save the argument n
slti $t0,$a0,1 # test for n<1
beq $t0,$zero,L1 # if n>=1, to to L1
addi $v0,$zero,1 # return 1
addi $sp,$sp,8 # pop 2 items off stack
jr $ra # return to after jal
L1:
addi $a0,$a0,-1 # n>=1: argument gets (n-1)
jal fact
lw $a0,0($sp) # return from jal: restore arguments
lw $ra,4($sp)
addi $sp,$sp,8
mul $v0,$a0,$v0 # return n* fact(n-1)
jr $ra # return to caller
2011 Sem 1

MIPS Programming

133

STACK ALLOCATION
High address
$fp

$fp

$sp

Saved argument
registers (if any)
Saved return
address
Saved
registers (if any)

$sp

Activation record /
Stack frame

Local arrays and


structures (if any)

Low address

2011 Sem 1

MIPS Programming

134

SYSCALL

One of the main role of the operating system is to


provide user task access to shared resources like the
screen

User must rely on the OS for I/O

In MIPS, request to OS is done by the syscall instruction


li $v0, code


Syscall

2011 Sem 1

#
#
#
#
#

load $v0 with the request code for an OS service


put the parameters in where the OS service
expects it to be
invoke the OS
return value (if any) is in $v0 or $f0

MIPS Programming

135

IMPORTANT SYSCALL

2011 Sem 1

MIPS Programming

136

EXAMPLE: PRINT STRING

li
$v0, 4
la
$a0, string
syscall

.data
string:
.asciiz

2011 Sem 1

# code 4 print string


# $a0 contains address of string
# ask OS to perform requested
#service
Hello world!\n

MIPS Programming

137

AN EXAMPLE
Read integer
li
$v0, 5
syscall

#
#
#
#

code 5 read integer


read in one line of ascii characters
convert them into a 32 bit integer
$v0 <- twos complement of integer

Print integer
li
$v0, 1
Lw
$a0, int
syscall

2011 Sem 1

#
#
#
#

code 1 print integer


$a0 <- the integer to be printed
OS routine will convert the 32-bit integer
into characters and print it out

MIPS Programming

138

MIPS SIMULATOR
Try out PCSpim (MIPS simulator)
ftp://ftp.cs.wisc.edu/pub/spim/pcspim.exe or
http://www.cs.wisc.edu/~larus/spim.html

2011 Sem 1

MIPS Programming

139

MIPS INSTRUCTION FORMATS

MIPS INSTRUCTIONS
CLASSIFICATION
Instructions are classified according to their operands;
instructions with same operand types have same
representation
R-format (Register format)

add, sub, and, or, nor, slt require 2 source registers


and 1 destination register
srl, sll also belong here

I-format (Immediate format)


addi, subi, andi, ori, slti, lw, sw, beq, bne
require 1 source register, 1 immediate and 1 destination register

J-format (Jump format)


j instruction requires only one immediate

2011 Sem 1

MIPS Programming

141

R-FORMAT (1/2)

Define fields of the following number of bits each: 6 + 5 + 5 + 5


+ 5 + 6 = 32

For simplicity, each field has a name:

opcode

rs

rt

rd

shamt funct

A field is viewed as 5- or 6-bit unsigned integer, not as part of


32-bit integer
5-bit fields can represent any number 0-31
6-bit fields can represent any number 0-63

2011 Sem 1

MIPS Programming

142

R-FORMAT (2/2)

opcode

partially specifies what instruction it is


equal to 0 for all R-Format instructions

funct

combined with opcode exactly specifies the instruction

rs (Source Register)

used to specify register containing first operand

rt (Target Register)

used to specify register containing second operand (note that name is


misleading)

rd (Destination Register)

used to specify register which will receive result of computation

shamt

amount a shift instruction will shift by. Shifting a 32-bit word by more than 31 is
useless, so this field is only 5 bits (so it can represent the numbers 0-31)
set to 0 in all but the shift instructions

2011 Sem 1

MIPS Programming

143

R-FORMAT: EXAMPLE (1/3)

MIPS instruction:
add

$8, $9, $10

opcode = 0
funct

= 32

rd

= 8 (destination)

rs

= 9 (first operand)

rt

= 10 (second operand)

shamt

= 0 (not a shift)

2011 Sem 1

MIPS Programming

144

R-FORMAT: EXAMPLE (2/3)


MIPS

add

instruction:
$8, $9, $10

Field representation in decimal:


opcode

rs

rt

rd

10

shamt

funct

32

Field representation in binary:

000000 01001 01010 01000 00000 100000


Hexadecimal representation of instruction:

012A 402016
2011 Sem 1

MIPS Programming

145

R-FORMAT: EXAMPLE (3/3)


MIPS

sll

instruction:
$8, $9, 4

Field representation in decimal:


opcode

rs

rt

rd

shamt

funct

Field representation in binary:

000000 00000 01001 01000 00100 000000


Hexadecimal representation of instruction:

0009 410016
2011 Sem 1

MIPS Programming

146

I-FORMAT (1/4)

What about instructions with immediates?


5-bit shamt field only represents numbers up to the value
31
immediates (for example for lw, sw instructions) may be
much larger than this

Compromise: Define new instruction format partially


consistent with R-format:
If instruction has immediate, then it uses at most 2 registers

2011 Sem 1

MIPS Programming

147

I-FORMAT (2/4)
Define

fields of the following number of bits each:


6 + 5 + 5 + 16 = 32
6
5
5
16

Again, each field has a name:

opcode

rs

rt

immediate

Only one field is inconsistent with R-format.


opcode, rs, and st are still in the same locations.

2011 Sem 1

MIPS Programming

148

I-FORMAT (3/4)

opcode
same as before except that, since there is no funct field,
opcode uniquely specifies an instruction

rs
specifies the source register operand (if any)

rt
specifies register to receive result
note the difference from R-format instructions

2011 Sem 1

MIPS Programming

149

I-FORMAT (4/4)

The immediate field:


Treated as a signed integer
16 bits can be used to represent a constant up to 216
different values
This is large enough to handle the offset in a typical lw or
sw, plus a vast majority of values that will be used in the
addi,subi, slti instructions

2011 Sem 1

MIPS Programming

150

I-FORMAT: EXAMPLE (1/2)

MIPS instruction:
addi

$21, $22, -50

opcode

=8

rs

= 22 (register containing operand)

rt

= 21 (target register)

immediate = -50 (by default, this is decimal)

2011 Sem 1

MIPS Programming

151

I-FORMAT: EXAMPLE (2/2)

MIPS instruction:
addi

$21, $22, -50

Field representation in decimal:

22

21

-50

Field representation in binary:

001000 10110 10101 1111111111001110


Hexadecimal representation of instruction:

22D5 FFCE16
2011 Sem 1

MIPS Programming

152

INSTRUCTION ADDRESS

As instructions are stored in memory, they too have


addresses
beq, bne, j instructions use these addresses

As instructions are 32-bit long, instruction addresses


are word-aligned as well

One register keeps address of instruction being


executed: Program Counter (PC)

2011 Sem 1

MIPS Programming

153

BRANCHES: PC-RELATIVE
ADDRESSING (1/5)

Use I-Format

opcode

rs

rt

immediate

opcode specifies beq, bne


rs and rt specify registers to compare
What can immediate specify?

Immediate is only 16 bits


Memory address is 32-bit
So immediate cannot specify entire address to branch to

2011 Sem 1

MIPS Programming

154

BRANCHES: PC-RELATIVE
ADDRESSING (2/5)

How do we usually use branches?


Answer: if-else, while, for
Loops are generally small: typically up to 50 instructions
Unconditional jumps are done using jump instructions (j),
not the branches

Conclusion: may want to branch to


anywhere in memory, but a branch
often changes PC by a small amount

beq $9,$8,End

PC
End

2011 Sem 1

MIPS Programming

155

BRANCHES: PC-RELATIVE
ADDRESSING (3/5)
Solution: specify target address relative to the PC
Let the 16-bit immediate field be a signed twos complement
integer to be added to the PC if we take the branch.
Now we can branch 215 bytes from the PC, which should be
enough to cover almost any loop

End

beq $9,$8,End

PC

End
2011 Sem 1

MIPS Programming

156

BRANCHES: PC-RELATIVE
ADDRESSING (4/5)

Instructions are word-aligned


number of bytes to add to the PC will always be a multiple
of 4.
specify the immediate in words.

Now we can branch 215 words from the PC (or 217


bytes)

We can handle loops 4 times as large

2011 Sem 1

MIPS Programming

157

BRANCHES: PC-RELATIVE
ADDRESSING (5/5)

Branch Calculation:
If we dont take the branch:
PC = PC + 4
PC+4 = address of next instruction

If we do take the branch:


PC = (PC + 4) + (immediate 4)

Observations
immediate field specifies the number of words to jump,
which is simply the number of instructions to jump
immediate field can be positive or negative.
Due to hardware, add immediate to (PC+4), not to PC; will
be clearer why later in the course
2011 Sem 1

MIPS Programming

158

BRANCH: EXAMPLE (1/3)

MIPS Code:
Loop: beq
add
addi
j
End:

$9, $0, End


$8, $8, $10
$9, $9, -1
Loop

beq branch is I-Format:


opcode
rs
rt
immediate

2011 Sem 1

= 4 (look up in table)
= 9 (first operand)
= 0 (second operand)
= ???
MIPS Programming

159

BRANCH: EXAMPLE (2/3)

MIPS Code:
Loop: beq
add
addi
j
End:

$9, $0, End


$8, $8, $10
$9, $9, -1
Loop

#
#
#
#
#

rel
rel
rel
rel
rel

addr:
addr:
addr:
addr:
addr:

0
4
8
12
16

immediate field:
Number of instructions to add to (or subtract from) the PC,
starting at the instruction following the branch
In beq case, immediate = 3
End = (PC + 4) + (immediate 4)

2011 Sem 1

MIPS Programming

160

BRANCH: EXAMPLE (3/3)

MIPS Code:
Loop: beq
add
addi
j
End:

$9, $0, End


$8, $8, $10
$9, $9, -1
Loop

#
#
#
#
#

rel
rel
rel
rel
rel

addr:
addr:
addr:
addr:
addr:

0
4
8
12
16

Field representation in decimal:


opcode

rs

rt

immediate

00000

0000000000000011

Field representation in binary:

000100
2011 Sem 1

01001

MIPS Programming

161

J-FORMAT (1/5)

For branches, we assumed that we wont want to


branch too far, so we can specify change in PC.

For general jumps (j), we may jump to anywhere in


memory.

Ideally, we could specify a 32-bit memory address to


jump to

Unfortunately, we cant (why?)

2011 Sem 1

MIPS Programming

162

J-FORMAT (2/5)

Define fields of the following number of bits each:


6 bits

26 bits

As usual, each field has a name:


opcode

target address

Keep opcode field identical to R-format and I-format


for consistency
Combine all other fields to make room for larger
target address

2011 Sem 1

MIPS Programming

163

J-FORMAT (3/5)

We can specify 26 bits of 32-bit address

Optimization:
Just like with branches, jumps will only jump to wordaligned addresses, so last two bits are always 00 (in binary)
So lets just take this for granted and not even specify them

Now we can specify 28 bits of 32-bit address

2011 Sem 1

MIPS Programming

164

J-FORMAT (4/5)

Where do we get the other 4 bits?


By definition, take the 4 highest order bits from the PC
Technically, this means that we cannot jump to anywhere in
memory, but its adequate 99.9999% of the time, since
programs arent that long
only if straddle a 256 MB boundary

Special instruction if the program straddles 256MB


boundary
Look up jr instruction if you are interested
Target address is specified through a register

2011 Sem 1

MIPS Programming

165

J-FORMAT (5/5)

Summary:
New PC = { PC[31..28], target address, 00 }

Understand where each part came from!

Note: { , , } means concatenation


{ 4 bits , 26 bits , 2 bits } = 32 bit
Eg: {1010, 11111111111111111111111111, 00}
= 10101111111111111111111111111100
Assuming PC[31..28] = 1010
Target address = 11111111111111111111111111

2011 Sem 1

MIPS Programming

166

ADDRESSING FOR BRANCH (1/2)


000001000
000001001
000001010
000001011
000001100
000001101
000001110
000001111
000010000
000010001
000010010
000010011
000010100
000010101
000010110
000010111
000011000
000011001

2011 Sem 1

beq
add

addi
beq
:

PC
Loop: beq $9,$0,End
add $8,$8,$10
addi $9,$9,-1
beq $0, $0, Loop
End:

#Addr: 8
#Addr:12
#Addr:16
#Addr:20
#Addr:24

PC = 8
PC + 4 = 12
Distance between End and (PC+4)
= (24 12) bytes
= 12 bytes
= 3 words
immediate = 3
new PC = (PC+4) + (immediatex4)
= 12 + (3x4) = 24
MIPS Programming

167

ADDRESSING FOR BRANCH (2/2)


000001000
000001001
000001010
000001011
000001100
000001101
000001110
000001111
000010000
000010001
000010010
000010011
000010100
000010101
000010110
000010111
000011000
000011001

PC

2011 Sem 1

beq
add

addi
beq

Loop: beq $9,$0,End


add $8,$8,$10
addi $9,$9,-1
beq $0, $0, Loop
End:

#Addr: 8
#Addr:12
#Addr:16
#Addr:20
#Addr:24

PC = ?
PC + 4 = ?
Distance between Loop and (PC+4)
=
=
=
immediate =

:
MIPS Programming

168

ADDRESSING FOR JUMP (1/2)


0000
01000
0000
01001
0000
01010
0000
01011
0000
01100
0000
01101
0000
01110
0000
01111
0000
10000
0000
PC
10001
2011 Sem 1
0000
10010

beq
add

addi
j

Loop: beq
add
addi
j
End:
Loop

#Addr: 8
#Addr:12
#Addr:16
#Addr:20
#Addr:24

0000..01000
immediate =2 (26 bits)

PC
new PC

$9,$0,End
$8,$8,$10
$9,$9,-1
Loop

0000..10100
PC[31..28], immed, 00

MIPS Programming
0000

169
..01000

ADDRESSING FOR JUMP (2/2)


0000
01000
0000
01001
0000
01010
0000
01011
0000
01100
0000
01101
0000
01110
0000
01111
0000
10000
0000
PC
10001
2011
Sem 1
0000

beq
add

addi
j
:

Loop: beq
add
addi
j
End:

$9,$0,End
$8,$8,$10
$9,$9,-1
Far

#Addr: 8
#Addr:12
#Addr:16
#Addr:20
#Addr:24

Cannot jump to Far as


PC[31..28] Far[31..28]
PC

0000..10100

Far

0001..01000

MIPS Programming

170

BRANCHING FAR AWAY

Given the instruction


beq $s0, $s1, L1
Assume that the address L1 is farther away from the
PC than can be supported by beq and bne
instructions

Construct an equivalent code sequence with the help


of unconditional (j) and conditional branch (beq,
bne) instructions to accomplish this far away
branching

2011 Sem 1

MIPS Programming

171

ADDRESSING MODES (1/3)


Register
op

rs

addressing: operand is a register


rt

rd

funct
Register

Immediate

addressing: operand is a
constant within the instruction itself (addi,
andi, ori, slti)
op

2011 Sem 1

rs

rt

immediate
MIPS Programming

172

ADDRESSING MODES (2/3)

Base addressing (displacement addressing):


operand is at the memory location whose address is
sum of a register and a constant in the instruction
(lw, sw)
op

rs

rt
Register

2011 Sem 1

Memory

Address
+

MIPS Programming

word

173

ADDRESSING MODES (3/3)

PC-relative addressing: address is sum of PC and constant


in the instruction (beq, bne)
op

rs

rt
PC

Memory

Address
+

word

Pseudo-direct addressing: 26-bit of instruction concatenated


with upper 4-bits of PC (j)
op

PC
2011 Sem 1

Memory

Address
:
MIPS Programming

word
174

END

2011 Sem 1

MIPS Programming

175

You might also like