From: Peter Dimov (pdimov_at_[hidden])
Date: 2006-10-15 08:09:11


Matt Gruenke wrote:

> Here's little tip about that. Some compilers (GCC 3.x, for example)
> don't perform dataflow analysis between certain pairs of types.
> Therefore, reading the bits of a float as an unsigned int by a
> construct like:
>
> unsigned int x_bits = *reinterpret_cast< unsigned int * >( &x )
>
> (or the reverse) may not generate all of the proper data dependencies.
> What's really pernicious about this is that because the bug is
> scheduling-dependent, inline functions which use these constructs may
> only fail in some cases.
>
> The reason compilers do this is because always making conservative
> decisions about aliasing yields slow code (lots of extra loads &
> stores). Because certain classes of aliasing are extremely rare (such
> as the same memory being accessed through both an int * and float *),
> such cases are excluded from alias analysis.

No, the reason compilers do this is because the standard labels accessing a
float as an int undefined behavior. You can legitimately access it as an
unsigned char[], though, and memcpy'ing a float into an int (under the
assumption that both are the same size) is also well-defined, although the
result may have its bytes swapped/reordered if the endianness of the two
doesn't match. (In practice. In theory it's more complicated.)