https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94082

            Bug ID: 94082
           Summary: __builtin_memcpy in constexpr context should compile
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: D.Bahadir at GMX dot de
  Target Milestone: ---

Compilation fails with the following code:

```
#include <array>
#include <cstdint>
#include <cstring>

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 in constexpr
context
    return val;
}
```

I would have expected that using `__builtin_memcpy` in a `constexpr` context
would compile just fine and be probably completely optimized out. However,
compilation fails.

Interestingly, GCC is able to fully optimize the above code when omitting the
`constexpr` in the marked line (and therefore not calling the function from a
`constexpr` context). (Whether the function is marked `constexpr`, `inline` or
neither does not matter. It will be fully optimized in non-`constexpr` context.

However, writing some similar `constexpr` function with `__builtin_bswap32` in
it and calling that from a `constexpr` context, succeeds and will be fully
optimized.

For demonstration of this issue and a nice comparison between
`__builtin_bswap32` and `__builtin_memcpy` in `constexpr` context see Compiler
Explorer: https://godbolt.org/z/qtMmqw

Note: The following StackOverflow question touches the same issue:
https://stackoverflow.com/q/60572199/3115457

Reply via email to