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

            Bug ID: 63157
           Summary: may_alias doesn't work as expected in template nested
                    types
           Product: gcc
           Version: 4.9.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: haynberg at sig dot com

Basically, I want to build with strict aliasing enabled however I'd like a way
to *programmatically* prevent strict aliasing optimizations if needed.  I
believe may_alias is the only way one can do this (please let me know if there
are others).  

Here's an example where I know two different-typed pointers may alias.  I
wanted a helper class that I could a reuse.  Note: this is only for structs
which are POD (as you can't inherit from built-in types; I have another utility
for that).

In the example, may_alias works in the non-template case (case 2) and in the
template case if you use a reference (case 4); but not if you use a pointer
(case 3).  Do you know why?

$ cat t.cpp
extern "C" void abort();

struct msg {
   long seq_no;
};

struct msg_alias : msg {} __attribute__((may_alias));

template <typename T>
struct test_type {
   struct type : T {} __attribute__((may_alias));
};

void check(short *a, msg *b)
{
   *a = 5;

   // case 1: will abort
   // b->seq_no = 6;

   // case 2: will not abort; may_alias prevented strict aliasing optimizations
   // msg_alias *p = (msg_alias*) b;
   // p->seq_no = 6;

   // case 3: will abort (but should be the same as case 2)
   test_type<msg>::type *p = (test_type<msg>::type*) b;
   p->seq_no = 6;

   // case 4: will not abort; may_alias prevented strict aliasing optimizations
   // test_type<msg>::type &r = * (test_type<msg>::type*) b;
   // r.seq_no = 6;

   if (*a == 5)
     abort();
}

int main()
{
   msg m[1];
   check((short *) m, m);
}
$ g++ -O3 t.cpp && a.out
Aborted
$ g++ -v
gcc version 4.9.0 (GCC)
$ uname -irs
Linux 3.0.38-0.5-default x86_64

Reply via email to