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

            Bug ID: 119310
           Summary: Unnecessary instructions on std::bit_cast of an array
                    of 3 strongly-typed floats
           Product: gcc
           Version: 14.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: rtl-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: bernardo at bernardosulzbach dot com
  Target Milestone: ---

I looked at some 10 other std::bit_cast-related issues, but none of them seemed
to be the same issue as this.

This matters for code that creates strong types around primitives to prevent
programmer mistakes such as mixing up units.
Users might expect to be able to cast away these strong types cheaply if they
don't interfere with memory layout.

https://godbolt.org/z/PM16z9fj6 is a minimal example. Note that this is not
happening for n = 2 and n = 4.

```cpp
#include <array>
#include <bit>

using T = float;

struct StrongA {
    T value;
};

template <std::size_t n>
using Vec = std::array<T, n>;

auto bitCast(Vec<2> a) { return std::bit_cast<std::array<T, std::size(a)>>(a);
}
auto bitCast(Vec<3> a) { return std::bit_cast<std::array<T, std::size(a)>>(a);
}
auto bitCast(Vec<4> a) { return std::bit_cast<std::array<T, std::size(a)>>(a);
}
```

generates

```
bitCast(std::array<float, 3ul>):
        movd    DWORD PTR [rsp-32], xmm1
        movss   xmm1, DWORD PTR [rsp-32]
        movss   DWORD PTR [rsp-16], xmm1
        movd    xmm1, DWORD PTR [rsp-16]
        ret
```

for the n = 3 case, which seems to effectively do nothing other than `ret`.

Maybe some optimization rule isn't triggering because of the mix of movss and
movd?

I guessed the component, so "rtl-optimization" might be wrong.

Reply via email to