//---------------------------------------------------------------- // fib.s // // Below is an implementation in assembly language for the // fibonacci function, which returns the value of the n-th // term in the famous Fibonacci sequence: // // 0, 1, 1, 2, 3, 5, 8, 13, 21, 33, 54, ... // // Each term in this sequence is the sum of the preceeding // pair of terms (except for the two initial terms). Here // is how this recursive function could be written in C++: // // unsigned int fib( unsigned int n ) // { // if ( n < 2 ) return n; // else return fib( n-2 ) + fib( n-1 ); // } // // programmer: ALLAN CRUSE // written on: 10 MAY 2005 //---------------------------------------------------------------- .text fib: pushl %ebp # save former frame-pointer movl %esp, %ebp # setup new frame-pointer cmpl $2, 8(%ebp) # test: is n < 2 ? jnl recur # no, do recursion movl 8(%ebp), %eax # setup current argument-value jmp fibx # and return as function-value recur: pushl %edx # preserve scratch register movl 8(%ebp), %eax # get value of argument n subl $1, %eax # compute n-1 pushl %eax # push argument n-1 call fib # recursive call to fib addl $4, %esp # discard function argument movl %eax, %edx # save function-value in EDX movl 8(%ebp), %eax # get value of argument n subl $2, %eax # compute n-2 pushl %eax # push argument n-2 call fib # recursive call to fib addl $4, %esp # discard function argument addl %edx, %eax # add fib( n-1 ) from EDX popl %edx # restore scratch register fibx: popl %ebp # recover saved frame-pointer ret # return control to caller .global fib # make the entry-point public .end # no more statements follow