From the beginning I was wondering about this flag in nim.cfg.

Can you give an example where -fno-strict-aliasing is really needed for Nim. Of course we may get problems when casting pointers and using pointers of different data types pointing to the same memory location. But where does that occur, is it used in Nim libs?

no-strict-aliasing reduces performance of my chess engine by 3%, that is really not much of course.

cat nim.cfg
# for gcc 6.3
gcc.options.speed = "-march=native  -O3  -flto -fno-strict-aliasing"

2017-04-20 07:45:17

The C standard says that accessing a value of one type through a pointer of a different type (except char) is undefined behavior (note: the actual semantics are a bit more involved, this is the ELI15 version).

So, if there's pointer casting going on under the hood, sufficiently aggressive optimization can lead to undefined behavior. This is a potential problem especially for a lot of memory allocators (not just in Nim), which do that kind of stuff a lot (the official way to do it in a defined way is to use a pointer to a union).

The reason why compilers are increasingly making use of it is that it gives them some guarantees about aliasing (or rather, lack thereof), which provides additional optimization opportunities. The problem is that a lot of code hasn't actually been written with these assumptions in mind.

Note that undefined behavior in the C/C++ standards is different from unspecified or implementation-defined behavior. Implementation-defined and unspecified behavior is still assumed to have some semantics, just not something that you can rely on (such as the value of sizeof(int)). Undefined behavior has been increasingly exploited by compiler writers to mean "this cannot happen" and create code based on the assumption that this is an impossibility. This is an issue both for people who write C/C++ code manually and for compilers that emit C/C++ code.

2017-04-20 09:02:04
The code generator is written with strict-aliasing rules in mind so things could just work . Except cast should go through a union in more places, arguably always.
2017-04-20 09:18:30