I was playing with my toy program to better understand the assembly that GCC generated. I am not able to understand why the emitted assembly is allocating extra 8 bytes of space on the stack.
Here's the C++ code:
int func(int r, int r1, int r2, int r3, int r4, int r5, int r6, int r7, int r8)
{
int k = 23;
int dd = r + r1 + r2 + r3 + r4 + r5 + r6;
dd+= r7 + r8;
return dd;
}
int main() {
int s = func(1,2,3,4,5,6,7, 8,9);
return s;
}
And here's the assembly output of the func
:
func(int, int, int, int, int, int, int, int, int):
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-20], edi
mov DWORD PTR [rbp-24], esi
mov DWORD PTR [rbp-28], edx
mov DWORD PTR [rbp-32], ecx
mov DWORD PTR [rbp-36], r8d
mov DWORD PTR [rbp-40], r9d
mov DWORD PTR [rbp-4], 23
mov edx, DWORD PTR [rbp-20]
mov eax, DWORD PTR [rbp-24]
add edx, eax
mov eax, DWORD PTR [rbp-28]
add edx, eax
mov eax, DWORD PTR [rbp-32]
add edx, eax
mov eax, DWORD PTR [rbp-36]
add edx, eax
mov eax, DWORD PTR [rbp-40]
add edx, eax
mov eax, DWORD PTR [rbp+16]
add eax, edx
mov DWORD PTR [rbp-8], eax
mov edx, DWORD PTR [rbp+24]
mov eax, DWORD PTR [rbp+32]
add eax, edx
add DWORD PTR [rbp-8], eax
mov eax, DWORD PTR [rbp-8]
pop rbp
ret
And here's the link for those who like it more interactive: https://godbolt.org/g/zM8BMN
If you look at the assembly, all the arguments passed to the function which are not on the stack are allocated a space started from rbp-20 even though it could easily have been rbp-12. As far as I can see, the stack range : [rbp-16]..[rbp-8] is unused. So why compiler didn't use it?