MIPS programming
Download
Report
Transcript MIPS programming
SPIM and MIPS programming
Review: Memory Organization
Large single-dimension array
A memory address is an index into the
array
Memory stores 8 bits in each address
Registers store 32 bits of information
– For example:
Li $t0, 0
lw $t0, 0($t1)
– Then $t0 will contain the data of
the first four memory locations
6
5
4
3
2
1
0
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
8 bits of data
Review: Registers
MIPS has 32 registers, each containing 32 bits
Some registers are listed below
–
–
–
–
–
–
$zero:
constant 0
$at:
reserved for the assembler
$v0 - $v1: function results
$a0 - $a3:function arguments
$t0 - $t9: temporary
$s0 - $s7: temporary
Arithmetic Instructions (1/2)
Some instructions include:
–
–
–
–
Add
Subtract
Multiply
Divide
Must break expression into simple operations
– use temporary registers ($t0 to $t9) to store
intermediate results
– use load to insert a value into a variable
– use store to assign a value to a variable
Instructions
Instruction
– add $s1, $s2, $s3
– sub $s1, $s2, $s3
– lw $s1, 100($s2)
– sw $s1, 100($s2)
Meaning
$s1 = $s2 + $s3
$s1 = $s2 – $s3
$s1 = Memory[$s2+100]
Memory[$s2+100] = $s1
Global variables
C program
Assembly Program
int variable = -42;
.data
variable: .word -42
int r1;
r1: .space 4
.space allocates empty space in bytes
.word allocates 4-byte value followed by the value to store
Assember Directives
All assembler directives have names that
begin with a period (`.').
– Examples:
.word w1
– allocate a 4-byte word
.half h1
– allocate 2-bytes
.byte b1
– allocate a single byte
.ascii “hello"
– allocate a sequence of bytes and store ASCII values
.asciiz “hello"
– allocate a sequence of bytes and store ASCII values. terminate
string with 0 byte (end of string)
.float
.double
Input/Output
On real machines (including real MIPS
computers), I/O is very complicated
– usually handled by operating system
In SPIM, I/O is managed by system calls
– syscall instruction
– SPIM suspends simulation to perform I/O,
then resumes simulation
System calls
Systems calls are used to interact with the
user
To make a system call
– determine which service you want
– put service’s call code in register $v0
– put arguments in registers $a0, $a1, etc.
– execute the syscall instruction
– results are in registers $v0, $v1
System calls
Input/Output: Numbers
value:
main:
.data
.space 4
.text
li $v0, 5
syscall
sw $v0, value
#Syscall 5: read int
#Number is in $v0
li $v0, 1
#Syscall 1: print int
lw $t0, value
mul $a0, $t0, $t0 #$a0 is what to print
syscall
li $v0, 10
syscall
#Exit
Input/Output: strings
msg:
buff:
main:
.data
.asciiz "Type a string: "
.space 20
.text
li $v0, 4
la $a0, msg
syscall
# print string
# $a0: address of string
li $v0, 8
la $a0, buff
li $a1, 20
syscall
# read string
# $a0: max length of buffer
# $a1: max length of string
li $v0, 4
la $a0, buff
syscall
li $v0, 10
syscall
# exit