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

Kim Gräsman via llvm-dev llvm-dev at lists.llvm.org
Tue Aug 14 12:03:38 PDT 2018


On Tue, Aug 14, 2018 at 4:49 PM Andrew Haley <aph at redhat.com> wrote:
>
> On 08/14/2018 11:55 AM, Kim Gräsman wrote:
> > On Tue, Aug 14, 2018 at 11:51 AM Andrew Haley <aph at redhat.com> wrote:
> >>
> >> On 08/12/2018 02:19 PM, Kim Gräsman wrote:
> >>> I still feel a little uncomfortable, because I think Jonathan makes an
> >>> excellent point -- if GCC thinks there's a strict-aliasing violation
> >>> (whether the standard agrees or not) and classifies this as undefined
> >>> behavior, we might invoke the optimizers wrath. The warning is a nice
> >>> hint that this could happen.
> >>
> >> Indeed.  And I'm not convinced that the pointer cast is necessary anyway:
> >> if the type passed in is a union, why not simply take the union member of
> >> the appropriate type?
> >
> > As it turns out, Union is not a union ¯\_(ツ)_/¯. (I thought it was, up
> > until this point.)
> >
> > It's a template producing a char array suitably aligned for any number
> > of mutually exclusive types, much like
> > https://en.cppreference.com/w/cpp/types/aligned_union.
> >
> > I can't tell if that makes the waters less dangerous, but there's an
> > invariant for this code that it only reinterpret_casts out Ts from the
> > char buffer that it has previously put in there using placement new.
>
> So I think GCC is wrong here. The intent of aligned_union is clearly that
> it is a POD-type suitable for any of its declared types.
>
> So what exactly is the type Union?  It has a field called buffer.

Union is of type llvm::AlignedCharArrayUnion<...>. It looks like a
predecessor to aligned_union. If you're willing/allowed to look at
LLVM source code, it's declared here:
https://github.com/llvm-mirror/llvm/blob/master/include/llvm/Support/AlignOf.h#L138

As far as I can tell, it works like aligned_union, except instead of
declaring a nested type with the right alignment and size, it directly
declares a char buffer with the same qualities.

The union-ed types are:
llvm::AlignedCharArrayUnion<bool, double, int64_t, llvm::StringRef,
std::string, json::Array, json::Object> Union;

- Kim


More information about the llvm-dev mailing list