Fibonacci:
STR R7, R6, #1 ; store away the return address
LDR R0, R6, #3 ; load the parameter n
BRZ FIB_END ; n==0
ADD R0, R0, #-1 ;
BRZ FIB_END ; n==1
LDR R0, R6, #3 ; load the parameter n
ADD R0, R0, #-1 ; calculate n-1
STR R0, R6, #8 ; store input as first parameter
STR R6, R6, #7 ; store top of stack as the dynamic link
ADD R6, R6, #5 ; move the top of stack to new act record
JSR Fibonacci ; the call back to itself: Fibonacci(n-1)
LDR R0, R6, #5 ; read the return value
STR R0, R6, #4 ; store it to compiler generated temp value
LDR R0, R6, #3 ; load the parameter n
ADD R0, R0, #-2 ; calculate n-2
STR R0, R6, #8 ; store input as first parameter
STR R6, R6, #7 ; store top of stack as the dynamic link
ADD R6, R6, #5 ; move top of stack to new act record
JSR Fibonacci ; the call back to itself: Fibonacci(n-2)
LDR R0, R6, #5 ; read the return value
LDR R1, R6, #4 ; read the temporary value: Fibonacci(n-1)
ADD R0, R0, R1 ; Fibonacci(n-1) + Fibonacci(n-2)
STR R0, R6, #0 ; write the return value
LDR R6, R6, #2 ; load the dynamic link
RET
FIB_END:
AND R0, R0, #0 ; clear R0
ADD R0, R0, #1 ; R0 = 1
STR R0, R6, #0 ; write the return value
LDR R6, R6, #2 ; load the dynamic link
RET