Let us say I have three functions, f1()
, f2()
, and f3()
. When f1
is called, it stores information in CPU registers (and I imagine there is other important information as well). Now, depending on a condition that is unknown at compile-time, f1
will call either f2
or f3
. f2
and f3
use very different registers, some of which may overlap with those used by f1
. Is the following reasoning correct?
The compiler knows which registers a particular function needs during its execution. Therefore, when f1
calls either f2
or f3
, the function call code preserves those registers that f2
or f3
use on the stack, regardless of whether or not they are being used by f1
.
Or is there some other mechanism by which the compiler preserves registers so that the function that is being returned to doesn't lose its data?
Recall that a programming language is a specification in a document. For C11, read n1570.
Registers do not exist in C (in other words, the nearly obsolete register
keyword is no more related to processor registers). They only matter in machine code (often generated by a C compiler).
However, the code generated by a given compiler (for a given instruction set and target system) obey to some conventions, notably the calling conventions and the ABI (read the system V x86-64 ABI governing Linux for an example). Thes conventions define how registers should be used, and which registers are callee-saved or caller-saved. Register allocation is a difficult part of an optimizing compiler's job.
Often the compiler would emit code to spill some of the registers content into the call stack. And a given register can be used for several things (e.g. it could keep two different variables, if they occur in different places in the same function).
In general the calling convention does not depend upon the called function (recall that you can make indirect calls thru function pointers), but mostly of its signature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With