[llvm-bugs] [Bug 39675] Undefined behavior inside constexpr function

via llvm-bugs llvm-bugs at lists.llvm.org
Thu Nov 15 10:06:40 PST 2018


https://bugs.llvm.org/show_bug.cgi?id=39675

David Blaikie <dblaikie at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
         Resolution|---                         |INVALID
                 CC|                            |dblaikie at gmail.com

--- Comment #2 from David Blaikie <dblaikie at gmail.com> ---
As Eli mentioned - this is ill-formed, no diagnostic required. So Clang is
conforming here.

To see the error/reach the invalid case that Clang must diagnose/not accept,
you'd need to call the function in a constexpr context.

For instance, add "constexpr int i = b();" to main (or anywhere else) and clang
will diagnose this:

<source>:23:19: error: constexpr variable 'i' must be initialized by a constant
expression
    constexpr int i = b();
                  ^   ~~~
<source>:11:13: note: value 4294967294 is outside the range of representable
values of type 'int'
    return i*2/2;
            ^
<source>:18:12: note: in call to 'f(2147483647)'
    return f(i);
           ^
<source>:23:23: note: in call to 'b()'
    constexpr int i = b();
                      ^

https://godbolt.org/z/aSNE9N

For further, the following is a valid constexpr function that must not be
diagnosed at the point of definition:

  constexpr int i(bool b) { if (b) return 3/0; return 1; }

'constexpr' doesn't guarantee that all callers can (nor must) be evaluated as a
constant. Just that some callers may. And that all of /those/ callers (the ones
in a constexpr context) must do so in a way that is well defined.

So I can write "int x[i(false)];" and get an array of length 1 - this program
is still totally conforming.

If I write "int x[i(true)];" the compiler is required to reject this program.

If I write "int x = i(true);" the program has UB and the compiler isn't
required to do anything in particular (it's not required to reject the program,
it's not required to make the program do any .particular thing, etc)

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20181115/dc108204/attachment.html>


More information about the llvm-bugs mailing list