When talking about register allocation, texts on compilation (for example, Engineering a Compiler by Cooper) often mention that values stored in registers need to be "safe" - otherwise they should be stored in memory.
What makes a value unsafe to be kept in a register?
Edit: Context from the book:
"In a memory-to-memory model, the allocator must determine which values can be kept safely in registers—that is, which values are unambiguous."
The most informative mention I could find is "Register promotion uses data-flow analysis of pointer values to determine when a pointer-based value can safely be kept in a register throughout a loop nest and to rewrite the code so that the value is kept in a newly introduced temporary variable."
So to clarify the question: why would a pointer value be unsafe to store in a register, and is this the only case when a value could not be safe to store in a register?
My understanding is that it's mostly a matter of aliases
. Aliases are two or more names that refer to the same object at some point in the program.
Aliases make it very difficult to perform some important optimizations. Consider the following C example:
int first, second, *p, *q;
...
first = *p; // store the value from the variable referred to by p in first
*q = 3; // assign to the variable referred to by q
second = *p; // store the value from the variable referred to by p in second
The initial assignment to first
will, on most machines, require that *p
is loaded into a register. Since accessing memory is expensive, the compiler will want to hang on to the loaded value, and reuse it in the assignment to second
. However, it will be unable to do so, unless it can verify that p
and q
do not refer to the same object (that *p
and *q
are not aliases).
The analysis done to verify that certain names are not aliases, is called alias analysis
, and determines when values can be safely cached in registers, computed "out of order" or accessed by concurrent threads.