I have learned that if any of the caller saved registers (rax rdx rcx rsi rdi r8 r9 r10 r11) is used by the callee, then it has to be saved before and restored after a call instruction by the caller.
Through the following example,
int read();
void print(int i);
int main()
{
int a = read();
int b = read();
int c = read();
int d = read();
int e = read();
int f = read();
int g = read();
print(a);
print(b);
print(c);
print(d);
print(e);
print(f);
print(g);
}
Note
The variables
a - gshould use all thecallee saved registers (rbp rsp rbx r12 r13 r14 r15). And we cannot use bothrbporrsp, since either has to be used for addressing the stack memory.The
readandprintare from some external compilation unit. Thus, we don't really know about their caller save registers usage when we compile the current compilation unit, specifically, during register allocation for themainfunction.
In godbolt with -O3 it compiles to the following
main:
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbp
pushq %rbx
subq $24, %rsp # spill here
call read()
movl %eax, 12(%rsp) # spill here
call read()
movl %eax, %ebx
call read()
movl %eax, %r15d
call read()
movl %eax, %r14d
call read()
movl %eax, %r13d
call read()
movl %eax, %r12d
call read()
movl 12(%rsp), %edi
movl %eax, %ebp
call print(int)
movl %ebx, %edi
call print(int)
movl %r15d, %edi
call print(int)
movl %r14d, %edi
call print(int)
movl %r13d, %edi
call print(int)
movl %r12d, %edi
call print(int)
movl %ebp, %edi
call print(int)
addq $24, %rsp
xorl %eax, %eax
popq %rbx
popq %rbp
popq %r12
popq %r13
popq %r14
popq %r15
ret
Note
The variable
ais spilled into12(%rsp).We don't need to do spill any of the
caller saved registerssince they are not used at all, which turns out to be more efficient here.
My questions
Look like we don't really need to deal with spilling the
caller saved registers, if we don't use them. Thus, when should we use thecaller saved registers?For callees like
readandprintsince we don't know about their register usage, how should we do the spilling for thecaller saved registers?
Thanks