c++ is generating incorrect optimized code for xor operations on long long. Version which is affected is: g++ (GCC) 4.0.2 20051125 (Red Hat 4.0.2-8) Following (proper) code is inlined into bad assembly when optimization is turned on: namespace __gnu_cxx { /** hash specialization for uint64 */ template <> class hash<uint64> { public: size_t operator()(uint64 const & number) const { hash<uint32> uint32Hasher; uint32 const *p = (uint32 *)&number; return uint32Hasher(p[0]) ^ uint32Hasher(p[1]); } }; /** hash specialization for RequestId */ template<> class hash<RequestId> { public: size_t operator()(RequestId const & requestId) const { hash<uint64> uint64Hasher; return uint64Hasher(requestId.getV1()) ^ uint64Hasher(requestId.getV2()); } }; } Part of bad assembly: call _ZNK9RequestId5getV1Ev movl -20(%ebp), %ebx movl %esi, (%esp) movl %eax, -24(%ebp) movl -24(%ebp), %eax movl %edx, -20(%ebp) xorl %eax, %ebx call _ZNK9RequestId5getV2Ev movl -16(%ebp), %ecx movl %eax, -16(%ebp) movl -12(%ebp), %eax movl %edx, -12(%ebp) xorl %ecx, %eax and it probably should be something like: call _ZNK9RequestId5getV1Ev movl %eax, -24(%ebp) movl %edx, -20(%ebp) movl -20(%ebp), %ebx movl %esi, (%esp) movl -24(%ebp), %eax xorl %eax, %ebx call _ZNK9RequestId5getV2Ev movl %eax, -16(%ebp) movl %edx, -12(%ebp) movl -16(%ebp), %ecx movl -12(%ebp), %eax xorl %ecx, %eax It seems that compiler reads values from stack before setting them after call to getV1() or getV2(). Bug shows up only when optimization is turned on. I am attaching simple demo program which should run when optimization is set to 0 and crash when it is set to 2 or 3.
Created attachment 11212 [details] File containing hash specifications
Created attachment 11213 [details] Implementation of RequestId
After compilation: g++ test.cpp req.cpp -O0 program works fine. After compilation with: g++ test.cpp req.cpp -O2 it breaks with SIGABRT.
Subject: Re: c++ is generating incorrect optimized code for xor operations on long long All, Not a bug, this is yet another case of type pruning. Use -fno-strict-aliasing or fix your code. Graham
*** This bug has been marked as a duplicate of 21920 ***