I've been working on a project to write a recursive function in assembly, where it will calculate the Fibonacci number. To start off I made it in Java code:
public class Fibonacci {
public static int fibonacci(int n)
{
if(n <= 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
This recursive function worked perfectly fine. Although when trying to implement it in assembly code I didn't get the result I expected. After troubleshooting a while, I wrote (roughly) the equivalent code in Java:
static int n;
static int rec1;
static int result;
public static int asmFibonacci(int n)
{
if(n <= 1) {
result = n;
return 0;
}
n = n-1;
asmFibonacci(n);
rec1 = result;
n = n-1;
asmFibonacci(n);
result = rec1 + result;
return 0;
}
This function gets the same wrong result as the one I had in assembly code, although I still don't understand why, what am I missing? Both functions recur the same amount of times.
Results
asmFibonacci
0
1
1
2
2
3
3
4
4
5
Fibonacci
0
1
1
2
3
5
8
13
21
34
Any help would be much appreciated.
Update
After pushing rec1(R1) onto the stack as well, I got the Fibonacci subroutine in assembly to work as expected.
main
LDR R0, = 12
LDR R1, = 0
LDR R2, = 0
BL Fibonacci
STOP B STOP
Fibonacci
PUSH {LR, R0-R1}
CMP R0, #1
BLE RETURN
ADD R0, #-1
BL Fibonacci
MOV R1, R2
ADD R0, #-1
BL Fibonacci
ADD R0, R1, R2
RETURN
MOV R2, R0
POP {R0-R1, LR}
BX LR
END