MIPS Assembly Language
CPSC 321 Computer Architecture Andreas Klappenecker
Addressing modes
lw $s1, addr lw $s1, 8($s0) # load $s1 from addr # $s1 = Mem[$s0+8]
register $s0 contains the base address access the address ($s0)
possibly add an offset 8($s0)
Branch instructions
beqz $s0, label bnez $s0, label bge $s0, $s1, label ble $s0, $s1, label blt $s0, $s1, label if $s0==0 if $s0!=0 goto label goto label
if $s0>=$s1 goto label if $s0<=$s1 goto label if $s0<$s1 if $s0>=0 goto label goto label
beq $s0, $s1, label
bgez $s0, $s1, label
if $s0==$s1 goto label
Non-leaf procedures
Suppose that a procedure procA calls another procedure jal procB Problem: jal stores return address of procedure procB and destroys return address of procedure procA Save $ra and all necessary variables onto the stack, call procB, and retore
Stack
The stack can be used for parameter passing storing return addresses storing result variables stack pointer $sp $sp = $sp - 12 stack pointer $sp --> high address
8($sp) 4($sp)
0($sp)
low address
Factorial
Compute n! Recall that
0! = 1 1! = 1 n! = n(n-1)! $s0 = n, the parameter $ra, the return address
Store on the stack
factorial: bgtz $a0, doit li $v0, 1 jr $ra doit: sub $sp,8 sw $s0,($sp) sw $ra,4($sp) move $s0, $a0 # if $a0>0 goto generic case # base case, 0! = 1 # return # make room for $s0 and $ra # store argument $s0=n # store return address # save argument
sub $a0, 1
jal factorial mul $v0,$s0,$v0
#
#
factorial(n-1)
v0 = (n-1)!
# n*(n-1)!
lw $s0,($sp)
lw $ra,4($sp) add $sp,8 jr $ra
# restore $s0=n
# restore $ra # reduce stack size # return
Fibonacci
fib(0) = 0 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) 0, 1, 1, 2, 3, 5, 8, 13, 21,
Fibonacci
li $a0, 10 jal fib move $s0, $v0 # call fib(10) # # $s0 = fib(10)
fib is a recursive procedure with one argument $a0
need to store argument $a0, temporary register $s0 for intermediate results, and return address $ra
fib:
subi $sp,$sp,12 sw $a0, 0($sp) sw $s0, 4($sp) sw $ra, 8($sp) bgt $a0,1, gen move $v0,$a0 j rreg
# save registers on stack # save $a0 = n # save $s0 # save return address $ra # if n>1 then goto generic case # output = input if n=0 or n=1 # goto restore registers # param = n-1 # compute fib(n-1) # save fib(n-1) # set param to n-2 # and make recursive call # $v0 = fib(n-2)+fib(n-1) # restore registers from stack # # # decrease the stack size
gen:
subi $a0,$a0,1 jal fib move $s0,$v0 sub $a0,$a0,1 jal fib add $v0, $v0, $s0
rreg:
lw lw lw
$a0, 0($sp) $s0, 4($sp) $ra, 8($sp)
addi $sp, $sp, 12 jr $ra
Practice, practice, practice!!!
Read Chapter 3 and Appendix A Write many programs and test them Get a thorough understanding of all assembly instructions Study the register conventions carefully