On 11/06/2010 03:15 PM, Francis Moreau wrote:
Hello,
I'm trying to understand what '-fstrict-aliasing' actually means.
Looking at the man page, one can read:
-fstrict-aliasing
Allow the compiler to assume the strictest aliasing
rules applicable to the language being compiled. For C
[...]
What does "the strictest aliasing rules ..." means ?
- Does it mean that Gcc allows only a subset of the standard aliasing
rules (which I believe is defined in 6.5p7 ? In this case, which
ones ?
GCC allows them all.
That would mean that Gcc also miss compiled conforming programs.
- Does it mean that the C standard has some 'gray' areas (undefined
behaviours) about aliasing and Gcc choose to specify the behaviour
for optimisation purposes ?
- or something else ?
Also I don't really understand the examples provided by the man page. Ok
type punning using union is still allowed.
But the second example which is:
However, this code might not:
int f() {
union a_union t;
int* ip;
t.d = 3.0;
ip =&t.i;
return *ip;
}
_might_ not work. Why using 'might' ? Does it work or not ?
AFAIK, this type of aliasing is defined by the standard.
Might not means that it does something that breaks the
aliasing rules, but it might compile into code that
does what you want, but a later version of the compiler
might not. You can alias through the union is
guaranteed to work, but aliasing through pointers to
members of the union is not on the list in 6.5p7. You
don't want to rely on behavior that might not work.
The third example is:
Similarly, access by taking the address, casting the
resulting pointer and dereferencing the result has
undefined behavior, even if the cast uses a union type,
e.g.:
int f() {
double d = 3.0;
return ((union a_union *)&d)->i;
}
Again in my understanding of the standard, this is an undefined
behaviour. So why does man page mention this case ?
It mentions it because a lot of people said that they
thought the wording of the standard would allow this.
If you google for strict aliasing you find it all over
the place. Now people can't say that.
If you look on the boost wiki you find a discussion of
strict-aliasing and how gcc generates awesome code if
you do things right. (If you like it I wrote that
section, if you don't it was probably random cosmic rays).
https://svn.boost.org/trac/boost/wiki/Guidelines/WarningsGuidelines
In general, if it's almost the same thing it will just
work, otherwise use a union and don't try something
fancy like using pointers.
Patrick