I would like to create a function that always returns zero, but this fact should not be obvious to the optimizer, so that subsequent calculations using the value won't constant-fold away due to the "known zero" status.
In the absence of link-time optimization, this is generally as simple as putting this in its own compilation unit:
int zero() {
return 0;
}
The optimizer can't see across units, so the always-zero nature of this function won't be discovered.
However, I need something that works with LTO and with as many possible future clever optimizations as well. I considered reading from a global:
int x;
int zero() {
return x;
}
... but it seems to me that a sufficiently smart compiler could notice that x
is never written to and still decide zero()
is always zero.
I considered using a volatile
, like:
int zero() {
volatile int x = 0;
return x;
}
... but the actual semantics of the required side effects of volatile reads aren't exactly clear, and would not seem to exclude the possibility that the function still returns zero.
Such an always-zero-but-not-at-compile-time value is useful in several scenarios, such as forcing a no-op dependency between two values. Something like: a += b & zero()
causes a
to depend on b
in the final binary, but doesn't change the value of a
.
Don't answer this by telling me the "standard doesn't guarantee any way to do this" - I'm well aware and I'm looking for a practical answer and not language from the standard.