Subject: Re: mk.conf & compiler flags
To: Florian Stoehr <netbsd@wolfnode.de>
From: Charles Swiger <cswiger@mac.com>
List: netbsd-users
Date: 02/03/2005 13:35:28
On Feb 3, 2005, at 9:16 AM, Florian Stoehr wrote:
[ ... ]
> As far as I remember, most (all?) pkgsrc code compiles with -O2 by
> default with 3.x without problems. Don't remember whether this uses
> -fno-strict-aliasing or not.
>
> Beside that, I'm interested in hearing about those problems, thinking 
> about my own codes.
>
> Can you give some link/details concerning those issues please?

Sure.  From "info gcc":

`-fstrict-aliasing'
      Allows the compiler to assume the strictest aliasing rules
      applicable to the language being compiled.  For C (and C++), this
      activates optimizations based on the type of expressions.  In
      particular, an object of one type is assumed never to reside at
      the same address as an object of a different type, unless the
      types are almost the same.  For example, an `unsigned int' can
      alias an `int', but not a `void*' or a `double'.  A character type
      may alias any other type.

      Pay special attention to code like this:
           union a_union {
             int i;
             double d;
           };

           int f() {
             a_union t;
             t.d = 3.0;
             return t.i;
           }

      The practice of reading from a different union member than the one
      most recently written to (called "type-punning") is common.  Even
      with `-fstrict-aliasing', type-punning is allowed, provided the
      memory is accessed through the union type.  So, the code above
      will work as expected.  However, this code might not:
           int f() {
             a_union t;
             int* ip;
             t.d = 3.0;
             ip = &t.i;
             return *ip;
           }

	-----

Unfortunately, in practice there exists a lot of code which does not 
access memory in a strictly type-safe fashion.  That code worked fine 
with gcc-2.x & -O2 but it may break once -fstrict-aliasing was enabled 
with -O2 under gcc-3.  You don't have to be using a union, either, 
dereferencing memory via a pointer type which does not "closely match" 
the actual data type there may also not work.

Note that the code will still compile and run, and it may be the case 
that nothing will be obviously wrong, but odd things will happen every 
once in a while because the assumption the compiler makes about 
type-saftey is violated.

-- 
-Chuck