I have a macro used all over my code that in debug mode does:
#define contract(condition) \\
if (!(condition)) \\
throw exception(\"a contract ha
Is there a way to express that the condition in the contract has no side effect, so that it is always optimized out?
Not likely.
It's known that you cannot take a big collection of assertions, turn them into assumptions (via __builtin_unreachable
) and expect good results (e.g. Assertions Are Pessimistic, Assumptions Are Optimistic by John Regehr).
Some clues:
CLANG, while already having the __builtin_unreachable
intrinsic, introduced __builtin_assume exactly for this purpose.
N4425 - Generalized Dynamic Assumptions(*) notes that:
GCC does not explicitly provide a general assumption facility, but general assumptions can be encoded using a combination of control flow and the
__builtin_unreachable
intrinsic...
The existing implementations that provide generic assumptions use some keyword in the implementationreserved identifier space (
__assume
,__builtin_assume
, etc.). Because the expression argument is not evaluated (side effects are discarded), specifying this in terms of a special library function (e.g.std::assume
) seems difficult.
The Guidelines Support Library (GSL, hosted by Microsoft, but in no way Microsoft specific) has "merely" this code:
#ifdef _MSC_VER
#define GSL_ASSUME(cond) __assume(cond)
#elif defined(__clang__)
#define GSL_ASSUME(cond) __builtin_assume(cond)
#elif defined(__GNUC__)
#define GSL_ASSUME(cond) ((cond) ? static_cast(0) : __builtin_unreachable())
#else
#define GSL_ASSUME(cond) static_cast(!!(cond))
#endif
and notes that:
// GSL_ASSUME(cond)
//
// Tell the optimizer that the predicate cond must hold. It is unspecified
// whether or not cond is actually evaluated.
*) Paper rejected: EWG's guidance was to provide the functionality within the proposed contract facilities.