我正在研究 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***fibanocci 部分正确但音译不正确//---------------------------
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
//