[PATCH] Help compiler detect invalid code

Jonathan Wakely jwakely@redhat.com
Fri Sep 27 16:45:00 GMT 2019


On 27/09/19 18:24 +0200, François Dumont wrote:
>On 9/27/19 2:11 PM, Jonathan Wakely wrote:
>>On 19/09/19 22:27 +0200, François Dumont wrote:
>>>Hi
>>>
>>>    I start working on making recently added constexpr tests to 
>>>work in Debug mode.
>>
>>The attached patch seems to be necessary for that, right?
>>
>>
>On my side I had done this, almost the same.
>
>For the moment there is a FIXME in macros.h to find out how to 
>generate a nice compilation error when the condition is not meant.
>
>static_assert can't be called in this context, too bad.
>
>I also try to define a function with a 
>__attribute__((__error__("because"))) attribute. But when I make it 
>constexpr gcc complains about missing definition. When I provide a 
>definition gcc complains that this attribute must be on a declaration. 
>And when I split declaration and definition gcc does not produce the 
>expected compilation error.

Yes, I've tried similar things without success.

>Unless you have the solution I consider that we need help from the 
>front-end.
>
>For the moment if Debug mode finds a problem it will be reported as 
>_M_error function not being constexpr !

A reasonable workaround is to do:

#ifdef _GLIBCXX_HAVE_BUILTIN_IS_CONSTANT_EVALUATED
  if (__builtin_is_constant_evaluated())
    asm("Debug Mode assertion failed");
  else
#endif
  if (!(Cond))
    __gnu_debug::_Error_formatter::...

The builtin is available even for C++98, whereas
std::is_constant_evaluated() is only available for C++20.

This produces errors that include lines like:

asm.cc:12:17:   in ‘constexpr’ expansion of ‘f(-1)’
asm.cc:4:7: error: inline assembly is not a constant expression
    4 |       asm("debug mode assertion failed");
      |       ^~~
asm.cc:8:3: note: in expansion of macro ‘CHECK’
    8 |   _GLIBCXX_ASSERT(i > 0);
      |   ^~~~~
asm.cc:4:7: note: only unevaluated inline assembly is allowed in a ‘constexpr’ function in C++2a
    4 |       asm("debug mode assertion failed");
      |       ^~~
asm.cc:8:3: note: in expansion of macro ‘CHECK’
    8 |   CHECK(i > 0);
      |   ^~~~~

It's not ideal, but it does show the failed condition and the text
"debug mode assertion failed" (or whatever message you choose to use
there).




More information about the Gcc-patches mailing list