我正在研究mips编码并对某个特定问题有一个解决方案,我正在努力理解它并且已经根据我的知识定义了每一行,但是我并没有就如何解释他们主要工作的最后一行是fib(n-1)+ fib(n-2)如何返回?我看到在beq失败之后,并且bne失败t1变为0并且达到退出t1的值被存储到v0用于结果/表达式并且我们的(n)在被从堆栈中删除之前被重新加载但是我不是很看到fib(n-1)+ fib(n-2)?救命?谢谢!
C code:
int fib(int n){
if (n==0)
return 0;
else if (n == 1)
return 1;
else
fib(n-1) + fib(n–2);
新**答案/音译我的工作
# #fib function
loop:
addi $sp, $sp, -4 #creating item on stack -> int n given caller value
sw $ra, 0($sp) #saving address to stack
addi $t0, $zero, $zero #temp 0 is given value of 0
beq 0($sp), $t0, exit #if equal return 0 (if (n == 0)
addi $t1, $zero, 1 #temp1 gets value of 1
beq 0($sp), $t1, exit #if equal return 0 (else if(n==0)
lw $t2, 0($sp) #storing n to temp 2
sub $t2, $t2, 1 #n - 1
lw $t3, 0($sp) #storing n to temp 3
sub $t3, $t3, 2 #n-2
add $t4, $t2, $t3 # (fib(n-1) + fib( n-1)
sw 0($sp), $s4 #storing n's new value back to its original location
bne 0($sp), $zero, loop #jump to loop function with new value of n
exit: jr $ra #return value of register address to caller
// OLD ***部分正确答案但不正确的文件音译 // ---------------------------
compare:
addi $sp, $sp, –4 #add immediate adjusts stack for one more item
sw $ra, 0($sp) #saves return address on stack of our new item
add $s0, $a0, $0 #add, stores argument 0 + (0) to s0
add $s1, $a1, $0 #add, stores argument 0 + (0) to s1
jal sub #jump and link to subtract
addi $t1, $0, 1 #add immediate, temp 1 = add 0 + 1
beq $v0, $0, exit #branch on equal, if value in 0 is equal to zero go to -> exit
slt $t2, $0, $v0 #set less than, if 0 < value at 0 then temp2 equals 1 else 0
bne $t2, $0, exit #branch on not equal, if temp2 not equal to zero go to -> exit
addi $t1, $0, $0 #add immediate, temp1 = 0 + 0
exit:
add $v0, $t1, $0 #add value at 0 = t1 + 0
lw $ra, 0($sp) #loads register address from stack 0()
addi $sp, $sp, 4 #add immediate, deletes stack pointer pops it off stack
jr $ra #jump register, return to caller from return address
sub:
sub $v0, $a0, $a1 #subtract, value at 0 = argument 1 - argument 2
jr $ra #jump register, return to caller from return address
//
答案 0 :(得分:1)
这两个版本都不会按照建议运行。我没有测试下面的代码;但这样的事情应该有效(没有错误检查(假设$ a0非负);宽松的程序框架约定):
.text
fib: addi $sp, $sp, -24
sw $ra, 16($sp)
sw $a0, 20(sp) # recursive calls will overwrite original $a0
sw $s0. 0($sp) # holds fib(n-1)
# end prologue
slti $t0, $a0, 4 # fib(i) = i for i = 1, 2, 3; fib(0) = 0 by C code
beq $t0, $zero, L1
addi $v0, $a0, 0 # see prior comment (assumes $a0 non-negative integer)
j exit
# fib(n) = fib(n-1) + fib(n-2)
L1: addi $a0, $a0, -1
jal fib
addi $s0, $v0, 0 # $s0 = fib(n-1)
addi $a0, $a0, -1
jal fib # upon return, $v0 holds fib(n-2)
add $v0, $v0, $s0
exit: # unwind stack and return
lw $s0, 0($sp)
lw $a0, 20($sp)
lw $ra, 16($sp)
addi $sp, $sp, 24
jr $ra