使用" push"的mips代码没有" pop"

时间:2015-10-30 04:04:45

标签: c assembly mips

c:中的代码:

int recursive_power (int base, int power) 
{
    if (power <=0)
        return (-1);
    else    if (power ==1)
        return (base);
    else
        return (base*recursive_power (base, power-1)); } 

mips:

recursive_power:    addi $sp, $sp, -8   #Assign stack space
        sw $ra, 0($sp)  #Store current value of $ra
        sw $a1, 4($sp)  #Store current value of power
        slti $t0, $a1, 1    #if power<1, $t0==1, else $t0==0;
        beq $t0, $0, next   #power>0, continue ($t0==0)

        addi $v0, $0, -1    #power<=0, return -1
        j return2

    next:   addi $t1, $0, 1 #put ‘1’ in $t1
        beq $a1, $t1, return1   #if power==1, return(base)

        addi $a1, $a1, -1   #power=power-1
        jal recursive_power #call recursive_power (base,power-1)

        lw $ra, 0($sp)  #Restore original return address
        lw $a1, 4($sp)  #Restore original value of power
        mul $v0, $a0, $v0   #return value is $v0*base
        j return2

    return1:    addi $v0,$a0, 0 #$v0=base
    return2:    addi $sp, $sp, 8    #Restore stack
        jr $ra      #Return to caller address

制作&#34; return1&#34;是否正确? &#34; RETURN2&#34;因为它们出现在这段代码中,因为没有&#34; lw&#34;表彰?不使用堆栈 - &#34; push&#34;也需要&#34; pop&#34;?您可以帮助改进mips代码吗?

1 个答案:

答案 0 :(得分:0)

您已将流行音乐放在错误的位置。每次进入函数时,您都会将两个寄存器推入堆栈,因此每次从函数返回时都应该弹出它们:

    jal recursive_power #call recursive_power (base,power-1)
    mul $v0, $a0, $v0   #return value is $v0*base
    j return2

return1:    addi $v0,$a0, 0 #$v0=base
return2:
    lw $ra, 0($sp)  #Restore original return address
    lw $a1, 4($sp)  #Restore original value of power
    addi $sp, $sp, 8    #Restore stack
    jr $ra      #Return to caller address