Symbol coder

Friday, 2 September 2011

Fibonacci in assembler

Image: public domain

Last year, for training in my last exam about compilers I had to solve many problems about execution environments and assembler questions. One of them is this Fibonacci function written in recursive flat assembler for the WinEns2001 simulator, according to this algorithm in the ADA language:
 
function fib(n : integer) return integer is
begin
  if n < 2 then
    return n;
  else
    return fib(n-1) + fib(n-2);
  end if;
end fib;

and finally this is my solution in asm:

MOVE  #10000,.IX  ;Start address 
MOVE .IX,#12[.IX]  ;Link access 
MOVE #12,#11[.IX]  ;Input number 
ADD .IX,#10   ;Change execution environment 
MOVE .A,.IX 

ADD .PC,#4   ;Store branch in return address 
MOVE .A,#3[.IX] 
BR /FIBO   ;Jump to first Fibonacci sum 

EXIT: NOP 

SUB .IX,#10   ;Return to main execution environment 
MOVE .A,.IX 
WRSTR /LAB 
WRINT #10[.IX]   ;Display result 
HALT    ;Finish execution 

FIBO: NOP   ;First Fibonacci sum 

CMP #1[.IX],#3   ;Ready to finish if lower or equal than 2 
BN /EXITFIBO 

MOVE .IX,#12[.IX]  ;Update access link 
SUB #1[.IX],#1   ;fibo(n-1) 
MOVE .A,#11[.IX]  ;First sum's result in the next execution environment 
ADD .IX,#10   ;Change execution environment 
MOVE .A,.IX 
ADD .PC,#4   ;Prepare for the second sum 
MOVE .A,#3[.IX]  ;Store branch in return address 
BR /FIBO 

FIBO2: 

SUB .IX,#10   ;Restore execution environment 
MOVE .A,.IX 
MOVE #10[.IX],#8[.IX]  ;Move first base case 
MOVE .IX,#12[.IX]  ;Update access link 
SUB #1[.IX],#2   ;Calculates fibo(n-2) 
MOVE .A,#11[.IX]  ;Second sum's result 
ADD .IX,#10   ;Change execution environment 
MOVE .A,.IX 
ADD .PC,#4   ;Prepare for the the third sum 
MOVE .A,#3[.IX]  ;Store branch in return address 
BR /FIBO 

FIBO3: 

SUB .IX,#10   ;Restore execution environment 
MOVE .A,.IX 
ADD #10[.IX],#8[.IX]  ;Sum fibo(n-1) + fibo(n-2) 
MOVE .A,[.IX]   ;Restore return address 
ADD .IX,#3 
BR [.A] 

EXITFIBO: 

MOVE #1,[.IX]   ;Base case 
ADD .IX,#3   ;Return to return address 
BR [.A] 


LAB: DATA "THE FIBONACCI IS:"

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home