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

后端 未结 3 1563
独厮守ぢ
独厮守ぢ 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:44

    There is no way to force optimize out code as-if it was dead-code, because GCC has to always be complaint with the standard.

    On the other hand the expression can be checked to not have any side effects by using the attribute error which will show an error whenever a function's call could not be optimized out.

    An example of a macro that checks whatever is optimized out and does UB propagation:

    #define _contract(condition) \
        {
            ([&]() __attribute__ ((noinline,error ("contract could not be optimized out"))) {
                if (condition) {} // using the condition in if seem to hide `unused` warnings.
            }());
            if (!(condition))
                __builtin_unreachable();
        }
    

    The error attribute does not work without optimization (so this macro can only be used for release\optimization mode compilation). Note that the error that indicates whatever the contract has side effects is shown during linkage.

    A test that shows an error with unoptimizable contract.

    A test that optimizes out a contract but, does UB propagation with it.

提交回复
热议问题