Consider the following code:
int y = 1;
int* p = &y;
inline int f(int x) {
return x + x;
}
int g(void) {
return f(*p);
}
In this code, there is one explicit dereference.
Is a C compiler allowed to compile/optimize this code as, roughly:
int g(void) {
return *p + *p;
}
That is, while inlining f, can the compiler perform and use two separate accesses to the target memory, as opposed to the single access that was actually written? Are there specific sections in the C specification that allow or disallow this behavior? Note that in the example, p is not volatile, and the “optimized” code is at least functionally correct.
(Please note, the question is not “will a compiler do this” or “should a compiler do this”, but rather, according to the C specifications, can a compiler do this. Suppose register spillage makes a second dereference more efficient, or some such thing).
Referencing the C99 specification, I see some possible hints on required handling of parameters. I wonder about whether “each parameter is assigned the value of the corresponding argument” (6.5.2.2) or “its [the parameter’s] identifier is an lvalue” (6.9.1) might prevent this scenario, but that interpretation seems incompatible with some of the common parameter optimizations I have seen.
john smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.