[llvm-dev] GCC 5 and -Wstrict-aliasing in JSON.h

Liu Hao via llvm-dev llvm-dev at lists.llvm.org
Thu Aug 9 21:30:55 PDT 2018


在 2018-08-10 06:20, Kim Gräsman 写道:
> On Fri, Aug 10, 2018 at 12:02 AM, Jonathan Wakely <jwakely.gcc at gmail.com>
> wrote:
>>
>> If GCC 4.9.3 thinks there's an aliasing violation it might
>> misoptimise. It doesn't matter if it's right or not, it matters if it
>> treats the code as undefined or not.
>>
>> And apparently GCC does think there's a violation, because it warns.
>>
>> Unless you're sure that not only is the code OK, but GCC is just being
>> noisy and doesn't misoptimise, then I think using -fno-strict-aliasing
>> is safer than just suppressing the warning.
> 
> Good point, I can see how that would play out nicer.
> 
> So this would probably need to be addressed in the LLVM build system, I'll
> try and work up a patch tomorrow.
> 

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.


> Thanks,
> - Kim
> 


-- 
Best regards,
LH_Mouse



More information about the llvm-dev mailing list