Created
November 15, 2017 06:40
-
-
Save kamontat/f8042a1d02796fac0fce84ec86ae2e74 to your computer and use it in GitHub Desktop.
example recursive function in MIPS assembly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.data # data section | |
spacebar: .asciiz " " | |
.text # text section | |
.globl main # call main by SPIM | |
my_recursive_func: | |
# shift for save return address | |
addiu $sp, $sp, -4 | |
sw $ra, 0($sp) | |
addiu $sp, $sp, -4 | |
sw $fp, 0($sp) | |
# change $fp to current $sp | |
addu $fp, $sp, $0 | |
# get first argument | |
lw $a0, 8($fp) | |
# base condition | |
slt $s7, $0, $a0 # 0 < $a0(first argument) | |
beq $s7, $0, end | |
# print integer in a0 | |
li $v0, 1 | |
syscall | |
# print spacebar | |
la $a0, spacebar | |
li $v0, 4 | |
syscall | |
#get first argument | |
lw $a0, 8($fp) | |
addiu $sp, $sp, -4 | |
# first argument - 2 | |
addiu $t0, $a0, -2 | |
# set new argument | |
sw $t0, 0($sp) | |
jal my_recursive_func | |
addiu $sp, $sp, 4 | |
#get first argument | |
lw $a0, 8($fp) | |
addiu $sp, $sp, -4 | |
# first argument - 3 | |
addiu $t0, $a0, -3 | |
sw $t0, 0($sp) | |
jal my_recursive_func | |
addiu $sp, $sp, 4 | |
#get first argument | |
lw $a0, 8($fp) | |
# print integer in a0 | |
li $v0, 1 | |
syscall | |
# print spacebar | |
la $a0, spacebar | |
li $v0, 4 | |
syscall | |
end: | |
# shift back | |
lw $fp, 0($sp) | |
addiu $sp, $sp, 4 | |
lw $ra, 0($sp) | |
addiu $sp, $sp, 4 | |
jr $ra | |
main: | |
# shift sp for 1 argument | |
addiu $sp, $sp, -4 | |
# first argument 6 | |
li $t0, 6 | |
sw $t0, 0($sp) | |
# call function | |
jal my_recursive_func | |
# back | |
addiu $sp, $sp, 4 | |
#end | |
li $v0 10 | |
syscall |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment