1

I have been given an assignment to recreate from C in MIPS.

function1(n) = (3*n)-5 if n <= 3

function1(n) = (n-1)*function1(n-1) + function1(n-2) - n if n > 3

It is a recursive function which calls itself twice which is as follows:

int function1(int n)
{
    if (n <= 3)
     {
        int ans1 = (3*n)-5;
        return ans1;
     }
    else
     {
        int ans1 = (n-1)*function1(n-1) + function1(n-2) - n;
        return ans1;
     }
}

The main calls function1 by entering an integer given by a user.

  void main()
  {
    int ans, n;

    printf("Enter an integer:\n");

    // read an integer from user and store it in "n"
    scanf("%d", &n);

    ans = function1(n);

    // print out the solution computed by function 1
    printf("The solution is: %d\n", ans);

    return;
}

What I have so far in MIPS is:

.data
enterInt: .asciiz "Enter an integer:\n"
answer: .asciiz "The solution is: "

.text
.globl main

main:
li $v0, 4
la $a0, enterInt
syscall 
li $v0, 5
syscall
move $a0, $v0


jal function1

li $v0, 1   
syscall

jr $ra

function1:
addi $sp, $sp -4
sw $ra, 0($sp)
addi $sp, $sp, -4
sw $a0, 0($sp)


sle $t0, $a0, 3 #if n <= 3
beq $t0, $zero, else #if $t0 = 0, or when n > 3 exit to else

#basecase computation
addi $a0, $a0, -1


jal function1

else:   
#reversing the top
lw $a0, 0($sp)
addi $sp, $sp, 4
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra

addi $a0 $a0, -2

jal function1


lw $ra, 0($sp)
lw $s0, 4($sp)
addi $sp, $sp, 8
jr $ra

I know this is somewhat on the right track but, I honestly have no idea where to go from here. Any sort of direction will help. Thanks!

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 3
    I recommend writing similar functions in C in `foo.c`, compile them with some optimization into assembler code (e.g. using `mips-gcc -O1 -fverbose-asm -S foo.c` where `mips-gcc` is some variant of [GCC](http://gcc.gnu.org/) configured as a suitable cross-compiler), and look into the generated assembler. Study also the specification of the [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) relevant for you – Basile Starynkevitch Sep 21 '18 at 05:28

0 Answers0