TExcelTAD
Home › x86-64 Assembly › Recursion

Recursion

A recursive function calls itself. In assembly there is nothing special about it: call pushes a return address, and as long as each invocation saves what it needs on the stack, every level keeps its own data. Writing recursion by hand is the best way to see how the call stack works.

Factorial

n! = n × (n − 1)!, with 0! = 1. Each level must remember its own n while the deeper call runs, so it pushes it:

nasm · try it yourself
section .text
global _start
_start:
    mov edi, 5
    call factorial
    mov rdi, rax
    call print_uint             ; 120

    mov edi, 20
    call factorial
    mov rdi, rax
    call print_uint             ; the largest factorial that fits in 64 bits

    mov eax, 60
    xor edi, edi
    syscall

; factorial(n) -> n!
factorial:
    cmp rdi, 1
    ja .recurse
    mov eax, 1                  ; base case: 0! = 1! = 1
    ret
.recurse:
    push rdi                    ; save n for after the call
    dec rdi
    call factorial              ; rax = (n - 1)!
    pop rdi                     ; get our n back
    imul rax, rdi               ; n * (n - 1)!
    ret

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
120
2432902008176640000

For factorial(3) the stack grows like this before the base case returns:

text
  [ return to _start ]
  [ n = 3 ]
  [ return into factorial ]     <- call factorial(2)
  [ n = 2 ]
  [ return into factorial ]     <- call factorial(1): base case, returns 1

Then the levels unwind: 1 × 2 = 2, then 2 × 3 = 6.

Fibonacci: two recursive calls

fib(n) = fib(n − 1) + fib(n − 2) makes two calls per level. Now each level has to keep n and the result of the first call. Using callee-saved registers is neat: save rbx and r12, then use them freely — every deeper level saves and restores them in turn:

nasm · try it yourself
section .text
global _start
_start:
    xor r13d, r13d              ; i = 0
.print_loop:
    mov edi, r13d
    call fib
    mov rdi, rax
    call print_uint
    inc r13d
    cmp r13d, 10
    jb .print_loop              ; fib(0) .. fib(9)

    mov eax, 60
    xor edi, edi
    syscall

; fib(n) -> the n-th Fibonacci number (naive recursion)
fib:
    cmp rdi, 2
    jae .recurse
    mov rax, rdi                ; fib(0) = 0, fib(1) = 1
    ret
.recurse:
    push rbx
    push r12
    mov rbx, rdi                ; rbx = n
    lea rdi, [rbx - 1]
    call fib
    mov r12, rax                ; r12 = fib(n - 1)
    lea rdi, [rbx - 2]
    call fib                    ; rax = fib(n - 2)
    add rax, r12
    pop r12
    pop rbx
    ret

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
0
1
1
2
3
5
8
13
21
34

Note: Naive Fibonacci is exponential: fib(40) makes over 300 million calls. Recursion is elegant for trees and divide-and-conquer, but a loop (or remembering previous results) is far better here.

Euclid's algorithm: a tail call

The greatest common divisor satisfies gcd(a, 0) = a and gcd(a, b) = gcd(b, a mod b). The recursive call is the last thing the function does, so instead of call gcd followed by ret we can just jmp gcd. This tail call reuses the current stack frame — the recursion becomes a loop and uses no stack at all:

nasm · try it yourself
section .text
global _start
_start:
    mov edi, 1071
    mov esi, 462
    call gcd
    mov rdi, rax
    call print_uint

    mov edi, 17
    mov esi, 5
    call gcd
    mov rdi, rax
    call print_uint

    mov eax, 60
    xor edi, edi
    syscall

; gcd(a, b) -> the greatest common divisor
gcd:
    test rsi, rsi
    jnz .step
    mov rax, rdi                ; gcd(a, 0) = a
    ret
.step:
    mov rax, rdi
    xor edx, edx
    div rsi                     ; rdx = a mod b
    mov rdi, rsi                ; new a = b
    mov rsi, rdx                ; new b = a mod b
    jmp gcd                     ; tail call: no new stack frame

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
21
1

Sum of digits

A recursive function that returns n mod 10 + digit_sum(n / 10). Each level saves the remainder before recursing:

nasm · try it yourself
section .text
global _start
_start:
    mov edi, 987654321
    call digit_sum
    mov rdi, rax
    call print_uint             ; 9+8+7+6+5+4+3+2+1

    mov eax, 60
    xor edi, edi
    syscall

; digit_sum(n) -> the sum of the decimal digits of n
digit_sum:
    test rdi, rdi
    jnz .recurse
    xor eax, eax                ; digit_sum(0) = 0
    ret
.recurse:
    mov rax, rdi
    xor edx, edx
    mov ecx, 10
    div rcx                     ; rax = n / 10, rdx = n % 10
    push rdx                    ; remember this level's digit
    mov rdi, rax
    call digit_sum              ; rax = digit_sum(n / 10)
    pop rdx
    add rax, rdx
    ret

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
45

Stack overflow

Recursion without a base case never stops pushing return addresses. After about 8 MB — roughly a million levels of 8 bytes each — the stack hits unmapped memory:

nasm · try it yourself
section .text
global _start
_start:
    call forever
    mov eax, 60
    xor edi, edi
    syscall

forever:
    call forever                ; no base case!
    ret
Program terminated with signal SIGSEGV (11)

Checklist for recursive functions

  1. Handle the base case first and return without recursing.
  2. Before each recursive call, save everything you need afterwards (push it, or keep it in a callee-saved register that you saved).
  3. Restore in reverse order and keep rsp balanced on every path.
  4. Turn a final call f + ret into jmp f when possible.

Test yourself

Why does the factorial function push rdi before the recursive call?

  1. To align the stack
  2. Because the recursive call changes rdi, and the level needs its own n afterwards
  3. Because imul requires it
  4. It is not necessary

What is a tail call?

  1. A call at the start of a function
  2. A recursive call that is the last action, which can be replaced by a jmp
  3. A call through a pointer
  4. A call to print_uint

What typically happens with infinite recursion?

  1. The program runs forever
  2. The CPU halts
  3. The stack runs out and the program receives SIGSEGV
  4. NASM refuses to assemble it