This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: is portable aliasing possible in C++?


Hi,

I tried to compile your function with g++ 4.6.2:
g++ -Wall foo.cpp -c -o foo.o -O3 -std=c++0


and here is objectdump's output:
   0:    48 8b 07                 mov    (%rdi),%rax
   3:    48 89 44 24 f0           mov    %rax,-0x10(%rsp)
   8:    f2 0f 10 44 24 f0        movsd  -0x10(%rsp),%xmm0
   e:    c3                       retq   


Do I need to get a newer gcc to observe the optimization you mentioned?

Thanks!




On Friday, September 12, 2014 4:32 PM, Andrew Haley <aph@redhat.com> wrote:
On 12/09/14 00:25, haynberg@yahoo.com wrote:
>>> msg *p = reinterpret_cast<msg*>(get_bytes());
>>
>> Why are you doing this?
> 
> For efficiency, by preventing a copy (imagine get_bytes() is getting
> bytes out of a socket buffer).

Firstly, char types alias everything.

Secondly, even if you call memcpy(), a compiler doesn't have to do any
copies if it can prove that the union you're reading into doesn't
escape.

Look at this:

double kludge(void *p) {
  union {
    char bytes[sizeof (double)];
    double d;
  } u;
  memcpy(u.bytes, p, sizeof u.bytes);
  return u.d;
}

which generates

kludge:
    ldr    d0, [x0]
    ret

and is completely portable, with no undefined behaviour.

> Putting alignment/padding concerns aside, it would be nice if there
> was a way to explicitly tell the compiler, I want to do this and,
> please donât reorder stores and loads, or perform other
> strict-aliasing optimizations, on the memory pointed to by this
> pointer (similar to the effect of a memcpy).  I believe the only way
> to do this is with the GCC may_alias attribute, or a more
> heavy-handed memory clobber.  I think the OP wanted to ask the GCC
> folks if there was another, possibly more portable, way; for
> example, placement new, but that turned out not to be an option.

Well, there isn't a more portable way, and we can't ignore alignment.
All that GCC can do is provide a way to do it; we can't make anyone
else comply.

> Another related, maybe more important, question is if GCC sees a
> reinterpet_cast like this (without a may_alias type), is it free to
> discard code or otherwise drastically change it due to the fact that
> itâs undefined by the standard?

Yes.  It may, and it does.

Andrew.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]