A
Alf P. Steinbach /Usenet
* tni, on 11.09.2010 14:40:
OK, this is an optimizer problem/bug. The optimizer "knows" that 'a' has not
been modified, by assuming a little too much, and optimizes away 'a.x'. You can
use '-fno-strict-aliasing' to turn off that silliness, or, you can deny the
optimizer the knowledge about the particular instance 'a'.
E.g. in the OP's example the instance was allocated dynamically.
Like ...
<code>
#include <iostream>
typedef unsigned uint32_t;
struct A {
uint32_t x;
uint32_t y;
};
struct B {
uint32_t x;
uint32_t y;
};
int main() {
A& a = *new A();
B& b = *reinterpret_cast< B* >( &a );
b.x = 42;
std::cout << a.x << " " << b.x << std::endl;
}
</code>
.... which due to the new-ing (as in the OP's article) produces no strict
aliasing warning and the result "42 42".
About how the g++ optimizer's "strict aliasing" assumption is invalid: the Holy
Standard has no notion of strict aliasing.
Cheers & hth.,
- Alf
I can't give you a simple example, but what I have seen is similar to the
behavior in this case (in my complex case, the structs started with the same
sequence):
#include <iostream>
#include <stdint.h>
struct A {
uint32_t x;
uint32_t y;
};
struct B {
float x;
uint32_t y;
};
int main() {
A a = A();
B& b = *reinterpret_cast<B*>(&a);
b.x = 42;
std::cout << a.x << " " << b.x << std::endl;
return 0;
}
Output (g++ -O2):
0 42
OK, this is an optimizer problem/bug. The optimizer "knows" that 'a' has not
been modified, by assuming a little too much, and optimizes away 'a.x'. You can
use '-fno-strict-aliasing' to turn off that silliness, or, you can deny the
optimizer the knowledge about the particular instance 'a'.
E.g. in the OP's example the instance was allocated dynamically.
Like ...
<code>
#include <iostream>
typedef unsigned uint32_t;
struct A {
uint32_t x;
uint32_t y;
};
struct B {
uint32_t x;
uint32_t y;
};
int main() {
A& a = *new A();
B& b = *reinterpret_cast< B* >( &a );
b.x = 42;
std::cout << a.x << " " << b.x << std::endl;
}
</code>
.... which due to the new-ing (as in the OP's article) produces no strict
aliasing warning and the result "42 42".
About how the g++ optimizer's "strict aliasing" assumption is invalid: the Holy
Standard has no notion of strict aliasing.
Cheers & hth.,
- Alf