https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94082
--- Comment #1 from Deniz Bahadir <D.Bahadir at GMX dot de> ---
Not: As due to the sourceware/gcc move it seems my original bug-report comment
got lost, I am here re-posting it.
Reading P0202 (wg21.link/p0202) (which made it into C++20) it sounds as if
`__builtin_memcpy` should be usable from a `constexpr` context. However, it is
not, as the following code demonstrates:
```
#include <array>
#include <cstdint>
constexpr std::uint32_t extract(const std::uint8_t* data) noexcept
{
std::uint32_t num;
__builtin_memcpy(&num, data, sizeof(std::uint32_t));
return num;
}
int main()
{
constexpr std::array<std::uint8_t, 4> a1 {{ 0xff, 0xff, 0xff, 0xff }};
constexpr auto val = extract(a1.data()); // <--- Error!
return val;
}
```
Compilation fails with:
```
<source>: In function 'int main()':
<source>:14:33: in 'constexpr' expansion of 'extract(a1.std::array<unsigned
char, 4>::data())'
<source>:7:21: error: '__builtin_memcpy(((void*)(& num)), ((const void*)(&
a1.std::array<unsigned char, 4>::_M_elems)), 4)' is not a constant expression
7 | __builtin_memcpy(&num, data, sizeof(std::uint32_t));
| ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
I would have expected this to compile and `__builtin_memcpy` being optimized
away.
Interestingly, removing the `constexpr` in front of the call to the function
and thereby not calling it from a `constexpr` context compiles just fine and
the optimizer is even able to optimize the call away and replace it by the
returned value (`-1`).
The `constexpr` keyword in front of the function definition seems then to just
be an indicator for inlining, similar to the `inline` keyword. But for this
simple example, the compiler is even able to optimize it without `inline` or
`constexpr` in front of the function definition.
I think a `constexpr` context should not prevent compilation and optimization,
as the optimizer seems to be able to do that.
BTW: Using e.g. `__builtin_bswap32` from a `constexpr` context is compiling and
optimizing just fine.
See Compiler Explorer for a demonstration of the described behavior:
https://godbolt.org/z/HaBt__