Optimisations and undefined behaviour

Florian Weimer fweimer@redhat.com
Mon Nov 9 12:10:00 GMT 2015


On 11/09/2015 11:11 AM, Andrew Haley wrote:
> On 08/11/15 19:34, Segher Boessenkool wrote:
>> The compiler is free to transform it to
>>
>> int foo(int x) {
>> 	int t = x*x*x;
>> 	if (x > 1290) {
>> 		printf("X is wrong here %d, but we don't care\n", x);
>> 	}
>> 	return t;
>> }
>>
>> because x*x*x does not have any observable behaviour, and then it is
>> obvious it _can_ remove the printf and conditional.

I'm not sure if this is a valid transformation for printf, even if
targets stdout and does not use any custom format specifiers.  Isn't it
a cancellation point?  But let's assume it's not.

> Yes, that is correct.  And, indeed, the hardware is free to do taht
> too.  With speculative execution, the "as if" rule is not limited to
> the compiler.

Can we disallow that optimization as a quality-of-implementation matter?
 What would be the benefit of such optimizations, other than
discouraging programmers from using C or C++?

I'm worried that this particular line of argument would also allow the
movement of undefined behavior which occurs after an infinite loop in
front of it, even if this loop performs I/O.

Florian



More information about the Gcc-help mailing list