How to guide GCC optimizations based on assertions without runtime cost?

后端 未结 3 1491
独厮守ぢ
独厮守ぢ 2020-12-13 18:57

I have a macro used all over my code that in debug mode does:

#define contract(condition) \\
    if (!(condition)) \\
        throw exception(\"a contract ha         


        
3条回答
  •  囚心锁ツ
    2020-12-13 19:36

    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 implementation­reserved 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.

提交回复
热议问题