Optimisations and undefined behaviour

Andrew Haley aph@redhat.com
Fri Nov 6 13:42:00 GMT 2015

On 11/06/2015 12:32 PM, David Brown wrote:

> Is it at least possible to put some restrictions or guarantees in
> how far the compiler will go in its optimisations, or how far it
> will go without warnings? 

AFAICS that is the intention of Appendix L.  I don't know how to bound
undefined behaviour in the way it suggests; it may turn out to be

> I don't want to limit the generation of code, I want it to be harder
> for there to be a mismatch between what the compiler generates and
> what the programmer intended.

I don't think you can have both.

> And when there /is/ a mismatch, I want it to be easier to find -
> applying undefined behaviour backwards in the code can make it
> extremely difficult for the programmer to find the real problem.

The undefinedness of integer overflow allows us to transform

   x*3/3 -> x

It's not a bug, it's a feature.

> This is merely an example - there are many other possible undefined
> behaviours.  And while it may be a simple solution to say "it's the
> programmer's fault - /skilled/ programmers would not do that", the fact
> is that there are many programmers out there who are not that skilled.
> The Principle of Least Astonishment is important here - the compiler
> should avoid surprising programmers.

C is a particular language which has been specified in a particular
way in order to allow these kinds of optimizations.  If people don't
want that kind of language there are plenty of others, most of which
don't have the same properties.

I really think you are talking to the wrong people.  If you want to
control what optimizations are allowed in a C implementation you
should appeal to the C standard technical committe, not compiler
writers.  Appendix L is interesting, and perhaps is a way forward for
those who agree with you.


More information about the Gcc-help mailing list