//---------------------------------------------------------------- // fact.s // // In this assembly language file we implement a "recursive" // function that returns N-factorial for N from zero to ten. // (It can be called by high-level language C/C++ programs.) // // assemble using: $ as fact.s -o fact.o // // programmer: ALLAN CRUSE // written on: 30 NOV 2003 // revised on: 15 APR 2008 -- to correct a comment statement // revised on: 11 MAY 2009 -- for the x86_64 Linux platform //---------------------------------------------------------------- .section .text #----------------------------------------------------------------- factorial: # # This procedure employs recursion to compute N-factorial for an # unsigned integer N whose value is placed in RDI by the caller. # Then this function's value will be returned in register RAX. # cmp $0, %rdi # base-case: n == 0? jne recur # no, do recursion mov $1, %rax # else load 1 into RAX jmp fini # and return to caller recur: push %rdx # preserve caller's RDX push %rdi # and caller's RDI dec %rdi # compute N-1 in RDI call factorial # to obtail (N-1)! pop %rdi # recovedr saved N mul %rdi # compute N * (N-1)! pop %rdx # recover saved RDX fini: ret # return to caller #----------------------------------------------------------------- .global factorial # make entry-point public .end # no more to be assembled