0

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!!

ronny
  • 41
  • 7
  • 1
    You are overwriting some of the registers used in the for loop. Change `$t0`, `$t1` and `$t2` in your power routine to some other unused registers or save/restore them when calling that subroutine – gusbro Jun 28 '23 at 16:59
  • The former comment by gusbro is spot on. But what is it you really want to know? Please ask a question about MIPS assembly or how the processor or simulator works. Help me is not really a good question here. If you can decompose your situation to a list of questions, you'll find that many have many answers here already, such as: [How function calling works on MIPS]([MIPS] function calling)? [How to use the debugger to debug your code](https://stackoverflow.com/a/65656215/471129)? You can break down what you have into smaller pieces that you can search/ask for common solution patterns. – Erik Eidt Jun 29 '23 at 00:27

1 Answers1

0

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