Skip to content

Instantly share code, notes, and snippets.

@laurelmay
Created January 17, 2019 22:08
Show Gist options
  • Save laurelmay/bca7859c3139fd9d9c19e9ac9c817a33 to your computer and use it in GitHub Desktop.
Save laurelmay/bca7859c3139fd9d9c19e9ac9c817a33 to your computer and use it in GitHub Desktop.
.data
n: .word 8
.text
main:
la t0, n
lw a0, 0(t0)
jal ra, factorial
addi a1, a0, 0
addi a0, x0, 1
ecall # Print result
addi a0, x0, 10
ecall # Exit
factorial:
# Save s0-s2 and the return address
addi sp, sp -16
sw ra, 12(sp)
sw s2, 8(sp)
sw s1, 4(sp)
sw s0, 0(sp)
# if x == 0: goto base_case
beq a0, x0, base_case
# Save a0 and calculate (a0 - 1)
mv s0, a0
addi s1, s0, -1
mv a0, s1
# s1 = factorial(s1 - 1)
jal ra, factorial
mv s1, a0
# calculate (s1 * s0) (or, (x * factorial(x - 1))
mul s2, s1, s0
mv a0, s2
# jump to epilogue
j fact_ret
base_case:
# return value is 1 if x == 0
li a0, 1
j fact_ret
fact_ret:
# restore the stack to how it was when we got it
lw s0, 0(sp)
lw s1, 4(sp)
lw s2, 8(sp)
lw ra, 12(sp)
addi sp, sp, 16
# return
jr ra
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment