On 3/9/21 8:05 AM, Rasmus Villemoes via Gcc wrote:
Hi,
Consider some function now() which returns some kind of "current
timestamp" as a simple scalar. It could be a wrapper for
clock_gettime(CLOCK_MONOTONIC) which converts the timespec value to
nanoseconds, or in the linux kernel one of the ktime_get* family.
Then consider code like
start = now();
do_something();
end = now();
debug("something took %lu\n", end - start);
If debug() is a macro that expands to nothing (or an if(0) statement),
the now() calls are actually redundant. But AFAIU one can't mark now()
as pure, since gcc must not assume it returns the same value when
do_something() provably doesn't touch global memory.
Is there some way to specify that a function doesn't have any side
effects, but may return a different value each time it is called? I.e.,
if its return value is not used, it can be elided completely, but
consecutive calls can not be assumed to return the same value.
I don't believe there is one. I'm also not sure the concept
of having "no side effect" would fit a function that can return
a different value on each call with the same argument values.
The only way to do that is to read and/or write global or, more
likely in the case of a function like now(), volatile memory.
Those define the concept of a side effect (in C and C++).
I think we'd need a different concept (in addition to a better
name). It could apply not just to functions like now() above
but also to functions like malloc() calls to which GCC already
knows to eliminate if their result is unused.
Martin