I am having a bit of trouble writing a recursive function in assembly. I would like to model the C function here:
int power(int base, int exponent)
{
if (exponent==0)
return 1;
else {
/* return base * power(base, --exponent); -- in normal form, writing in long-form below*/
exponent--;
int tmp1 = power(base, exponent);
int tmp2 = base * tmp1;
return tmp2;
}
}
And what I have so far in assembly is as follows:
power:
// int power(int base=rdi, int exponent=rsi)
push %rbp
mov %rsp, %rbp
// if (exponent==0) return 1
cmp $0, %rsi
jnz exponentiate
return_one:
mov $1, %eax
jmp cleanup
exponentiate:
dec %rsi
push %rax
call power
pop %rbx
imul %rbx, %rax
cleanup:
mov %rbp, %rsp
pop %rbp
ret
This produces the result zero. I think my error is in the exponentiate
function, but am having a hard time debugging it. I know I can 'find the answer' using Compiler Explorer, but I'm wondering if someone could help point out the mistake I have in my code.
I've been able to simplify this to the following where I don't even have to set up a stack frame for the recursive case:
exponentiate:
dec %rsi
call power
imul %rdi, %rax
Why is this allowed? I thought for all recursive functions you need to set up its own stack frame, but why isn't it necessary in the above case?