I'm trying to write a recursive factorial program in x64 assembly. For some reason, no matter what I do, I always get a result of 1. I realize that I don't necessarily need to declare a local variable, but I do it because I'm writing a compiler (for simplicity).
.section .data
outfmt: .asciz "%d\n"
.section .text
.extern printf
.global main
fact:
addq $16, %rsp
movq %rdi, 0(%rsp) # Convert parameter to local var.
movq 0(%rsp), %rax # Move rdi into rax.
movq $1, %rbx # Move 0 into rbx.
cmp %rax, %rbx # If rdi <= 1, return 1.
jle if
jmp else
else:
subq $1, 0(%rsp) # n = n - 1
call fact # Call fact
imulq 0(%rsp), %rax # Multiply n with fact n - 1
jmp factend
if:
movq $1, %rax # Return 1
jmp factend
factend:
subq $16, %rsp
ret
main:
movq $5, %rdi
call fact
movq %rax, %rsi
leaq outfmt, %rdi
movq $0, %rax
call printf
ret