# Calculate the factorial of an immediate value, and store the # result in memory. Based on code from # Patterson and Hennesy's Computer Organization and Design # (pp. 117-118 of the 4th edition, pp. 101-102 of the 5th edition) .data result: .word 0 .text .globl main main: addi $sp, $sp, -4 # adjust stack for 1 item sw $ra, 0($sp) # save return address addi $a0, $zero, 5 # set up argument to fact function jal fact sw $v0, result lw $ra, 0($sp) # restore the return address addi $sp, $sp, 4 # popped 1 items off stack jr $ra fact: addi $sp, $sp, -8 # adjust stack for 2 items sw $ra, 4($sp) # save return address sw $a0, 0($sp) # save the argument slti $t0, $a0, 1 # t0 = 1 if n < 1 beq $t0, $zero, L1 # go to L1 if n >= 1 addi $v0, $zero, 1 # return value = 1 addi $sp, $sp, 8 # restore the stack pointer jr $ra # return to instruction after jal L1: addi $a0, $a0, -1 # argument to recursive call is n - 1 jal fact # make recursive call lw $a0, 0($sp) # return from jal; restore arg n lw $ra, 4($sp) # restore the return address addi $sp, $sp, 8 # popped 2 items off stack mul $v0, $a0, $v0 # return value = n * fact (n - 1) jr $ra