I have created a code generator for my coursework in a module compilers. It generates code in MIPS assembly code and seems to be working ok (ive tested very simple programs and expressions).
I tested the recursive Fibonacci program and it currently loops forever. The base cases, 0 and 1, work ok. But when I try fib(2) or more it keeps looping.
Not sure what the problem is, can anyone help me find it?
Here is the code:
main:
move $fp $sp
sw $ra 0($sp)
addiu $sp $sp -4
sw $fp 0($sp)
addiu $sp $sp -4
li $a0 2 #testing comment
sw $a0 0($sp)
addiu $sp $sp -4
jal fib_entry
lw $ra 4($sp)
addiu $sp $sp 8
lw $fp 0($sp)
li $v0, 10
syscall
fib_entry:
move $fp $sp
sw $ra 0($sp)
addiu $sp $sp -4
lw $a0 4($fp)
sw $a0 0($sp)
addiu $sp $sp -4
li $a0 0
lw $t1 4($sp)
addiu $sp $sp 4
beq $a0 $t1 thenBranch1
elseBranch1:
lw $a0 4($fp)
sw $a0 0($sp)
addiu $sp $sp -4
li $a0 1
lw $t1 4($sp)
addiu $sp $sp 4
beq $a0 $t1 thenBranch2
elseBranch2:
sw $fp 0($sp)
addiu $sp $sp -4
lw $a0 4($fp)
sw $a0 0($sp)
addiu $sp $sp -4
li $a0 1
lw $t1 4($sp)
sub $a0 $t1 $a0
addiu $sp $sp 4
sw $a0 0($sp)
addiu $sp $sp -4
jal fib_entry
sw $a0 0($sp)
addiu $sp $sp -4
sw $fp 0($sp)
addiu $sp $sp -4
lw $a0 4($fp)
sw $a0 0($sp)
addiu $sp $sp -4
li $a0 2
lw $t1 4($sp)
sub $a0 $t1 $a0
addiu $sp $sp 4
sw $a0 0($sp)
addiu $sp $sp -4
jal fib_entry
lw $t1 4($sp)
add $a0 $a0 $t1
addiu $sp $sp 4
b endIf2
thenBranch2:
li $a0 1
endIf2:
b endIf1
thenBranch1:
li $a0 0
endIf1:
lw $ra 4($sp)
addiu $sp $sp 12
lw $fp 0($sp)
jr $ra
Various problems with that code.
$spbefore you write to($sp)(although this is only by convention)$fpbefore you modify it (this is by common sense ;))course make up your own convention)
mainit’s unbalancedmainand not useexitsyscallYou should of course be able to write and debug asm code before you try to generate some.
Given an input structured something like this C implementation:
I would expect a not-too-clever compiler to produce code like this:
Note I have deliberately left it unoptimized. This kind of code should be simple enough to generate.