Issue with MIPS pow(x, y) function inside a For Loop

48 Views Asked by At

I've been working on a MIPS program to implement the sin(x) function using Taylor Series. To do so I had to create functions such as factorial (x!) and power (x^y), they work perfectly fine on their own (outside the For loop) but something fails the moment they are instantiated on the loop, whether its that nothing is printed or it prints the result infinitely. I've tried all kind of things to make it work but nothing seems to work. The loop works fine with sums and subtractions, the summation works but fails whenever the power function is called inside of it. Here's my code:

.text
main:
    jal loop
    
    addi $v0, $0, 10
    syscall

loop:
    
    addi $t0, $0, 0   # i = 0
    addi $t1, $0, 8   # n = 8
    add $t2, $0, 0   # sum = 0

for:
    beq $t0, $t1, endFor

    addi $a1, $0, 2   # x = 2
    addi $a2, $0, 3   # y = 3
    jal power
    add $t2, $t2, $v0 # sum += power(2**3)

    addi $t0, $t0, 1

    j for

endFor:
    addi $v0, $0, 1
    addi $a0, $t2, 0
    syscall

    addi $v0, $0, 10
    syscall

power:

    addi $t0, $0, 1   # result = 1
    add $t1, $a1, $0  # x
    add $t2, $a2, $0  # y

while:
    beq $t2, $0, endWhile

    mul $t0, $t0, $t1
    addi $t2, $t2, -1

    j while

endWhile:
    add $v0, $t0, $0
    jr $ra

Thanks in advance for your responses, no doubt they'll be real helpful!!

1

There are 1 best solutions below

0
sophontosaphes On

Are you familiar with stack frames for functions? There are necessary in order to maintain variable locality and the addresses for returning to the caller from the callee.

You can check the following post to see an example of the use of the stack pointer $sp and the function stack frame.

MIPS: relevant use for a stack pointer ($sp) and the stack