[llvm-dev] GCC 5 and -Wstrict-aliasing in JSON.h
Kim Gräsman via llvm-dev
llvm-dev at lists.llvm.org
Fri Aug 10 03:53:54 PDT 2018
Hi LH_Mouse,
Thanks!
On Fri, Aug 10, 2018 at 6:30 AM, Liu Hao <lh_mouse at 126.com> wrote:
>
> When I used to do such type punning in C, I got similar warnings. Then I
> looked for some solutions... I can't recall the principle now and I fail to
> find it in the C or C++ standard. Despite that, the solution is simple:
>
> Only an lvalue of a pointer to (possibly CV-qualified) `void` or a pointer
> to a character type (in C) / any of `char`, `unsigned char` or `std::byte`
> (in C++) can alias objects.
>
> That is to say, in order to eliminate the aliasing problem an intermediate
> lvalue pointer is required.
>
> Hence, altering
> ```
> return *reinterpret_cast<T *>(Union.buffer);
> ```
> to
> ```
> auto p = static_cast<void *>(Union.buffer);
> return *static_cast<T *>(p);
> ```
> will probably resolve this problem.
I'm worried that this might only serve to trick the compiler.
Explicitly using `-fno-strict-aliasing` for GCC < 6 would seem more
direct to me -- as Jonathan says, if the compiler classifies a strict
aliasing rule violation as undefined behavior, and that is further
used to optimize in an unexpected manner, it doesn't matter whether it
warns or not. Then again, I guess disabling strict aliasing would also
disable optimizations that are generally useful for LLVM as a whole.
I'm reading up on safe aliasing techniques, but so far nothing stands
out to me as applicable in this scenario.
- Kim
More information about the llvm-dev
mailing list