<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/142707>142707</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
clang evaluates is_constant_evaluated incorrectly with narrowing conversion
</td>
</tr>
<tr>
<th>Labels</th>
<td>
clang
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
efriedma-quic
</td>
</tr>
</table>
<pre>
Consider the following example:
```
#include <type_traits>
struct X { unsigned u; };
void f(X x);
void g(int a) {
f({0xFFFFFFFFLL + std::is_constant_evaluated()});
}
```
The standard says the conversion is narrowing if "the source is a constant expression whose value after integral promotions will fit into the target type". gcc correctly rejects because of this: it treats the expression as a constant expression, then it fails to narrow. clang incorrectly accepts because isCXX11ConstantExpr() doesn't treat the evaluation as a constant context.
We have to be a little careful here... consider the following variant:
```
#include <type_traits>
struct X { unsigned u; };
void f(X x);
void g(int a) {
f({0x100000000LL - std::is_constant_evaluated()});
}
```
clang incorrectly rejects. gcc miscompiles: it checks the narrowing in a constant context, but then doesn't evaluate the actual expression in a constant context, so the integer overflows to 0.
(I don't expect anyone to intentionally do this... wrote some synthetic testcases while looking at isCXX11ConstantExpr() for other reasons.)
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJzMlE9v4zYQxT8NfRlEoCg7tg462Nk1UCDHAs1tQZEji12aVDkj__n2BSWlcbvZnnqoIMCGyZn3hu9naiJ3CoiN2BzE5stKj9zH1GCXHNqzfvpjdGbVRntvXmIgZzEB9whd9D5eXTgB3vR58CiqvZDT-yyXV-6FqlwwfrQIonrh-4DfOGnHJKqvQu6J02gY3kBsDzCGyYiFUVQHENsvojoIub9EZ6ETavcGN6Hqhx9PQu1cYNBC1bmDkHsAmPaK7UHejsvz-gpCHYDYZo_V3tE3EwOxDvwNL9qPmtHmIlVn1XeN_P0f08j9rz1CrrQ6WSB9p-kwTAwXTORiAEcQdErz0bgOhFJ5B8UxG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