I have the following macro,
#define assert(exp) ({ if(! (exp) ) __builtin_unreachable(); })
However it turned out that some (minority of) expressions generate code (gcc Redhat 5.2.1-2 -O2 -std=c++17).
That is certainly the case for assert(syscall(GET_TID)==tid);
And I assume would be the case for non-pure functions in general.
My second take:
#define assume(exp) \
({ \
auto __a = [&] () __attribute__((pure)) -> int { \
return !! (exp); \
}; \
if (!__a()) \
__builtin_unreachable(); \
})
This meant to either fool compiler into believing expression is pure to optimize it out or generate error if not. Unfortunately, no improvement seen.
Question.
Is there a way to force compiler to optimize out all the code. Or, alternatively can I detect the problem at compile time: that is whether expression generates code or is non-pure. Compile/link error is acceptable but I wish to think of these as last resort.
Update: More explanation.
- I want compiler to utilise hints from the expressions to optimize code further down the line.
- I want no extra code to be produced at the place assumption is checked (or at least be able to confirm that).
From checking briefly compiler output. It achieves (1) pretty neatly in many cases provided that expression is useful and transparent for the compiler (e.g. variable comparison, inline function calls, no side effects).
With (2) there is a problem. Compiler leaves code where expressions are non-transparent (or non-pure). These are actually the exact expressions compiler is unable to derive hints from.
I want to stop compiler doing (2) or generate warning on such an occurrence.