Download presentation
1
MIPS Assembly Language
CPSC 321 Computer Architecture Andreas Klappenecker
2
Addressing modes lw $s1, addr # load $s1 from addr
lw $s1, 8($s0) # $s1 = Mem[$s0+8] register $s0 contains the base address access the address ($s0) possibly add an offset 8($s0)
3
Branch instructions beqz $s0, label if $s0==0 goto label
bnez $s0, label if $s0!=0 goto label bge $s0, $s1, label if $s0>=$s1 goto label ble $s0, $s1, label if $s0<=$s1 goto label blt $s0, $s1, label if $s0<$s1 goto label beq $s0, $s1, label if $s0==$s1 goto label bgez $s0, $s1, label if $s0>=0 goto label
4
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
5
Stack 8($sp) 4($sp) 0($sp) The stack can be used for high address
parameter passing storing return addresses storing result variables stack pointer $sp high address stack pointer $sp --> low address $sp = $sp - 12
6
Factorial Compute n! Recall that Store on the stack 0! = 1 1! = 1
n! = n(n-1)! Store on the stack $s0 = n, the parameter $ra, the return address
7
factorial: bgtz $a0, doit # if $a0>0 goto generic case li $v0, 1 # base case, 0! = 1 jr $ra # return doit: sub $sp,8 # make room for $s0 and $ra sw $s0,($sp) # store argument $s0=n sw $ra,4($sp) # store return address move $s0, $a0 # save argument sub $a0, 1 # factorial(n-1) jal factorial # v0 = (n-1)! mul $v0,$s0,$v0 # n*(n-1)! lw $s0,($sp) # restore $s0=n lw $ra,4($sp) # restore $ra add $sp,8 # reduce stack size jr $ra # return
8
Fibonacci fib(0) = 0 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2)
0, 1, 1, 2, 3, 5, 8, 13, 21,…
9
Fibonacci li $a0, 10 # call fib(10) jal fib #
move $s0, $v0 # $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
10
fib: subi $sp,$sp,12 # save registers on stack
sw $a0, 0($sp) # save $a0 = n sw $s0, 4($sp) # save $s0 sw $ra, 8($sp) # save return address $ra bgt $a0,1, gen # if n>1 then goto generic case move $v0,$a # output = input if n=0 or n=1 j rreg # goto restore registers gen: subi $a0,$a0, # param = n-1 jal fib # compute fib(n-1) move $s0,$v # save fib(n-1) sub $a0,$a0, # set param to n-2 jal fib # and make recursive call add $v0, $v0, $s # $v0 = fib(n-2)+fib(n-1) rreg: lw $a0, 0($sp) # restore registers from stack lw $s0, 4($sp) # lw $ra, 8($sp) # addi $sp, $sp, # decrease the stack size jr $ra
11
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.