This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Optimisations and undefined behaviour
- From: David Brown <david dot brown at hesbynett dot no>
- To: "gcc-help at gcc dot gnu dot org" <gcc-help at gcc dot gnu dot org>
- Date: Mon, 09 Nov 2015 14:12:59 +0100
- Subject: Re: Optimisations and undefined behaviour
- Authentication-results: sourceware.org; auth=none
- References: <563BC190 dot 7080406 at hesbynett dot no> <563C7EB6 dot 9050401 at redhat dot com> <563C9DD3 dot 9030407 at hesbynett dot no> <563F9E4C dot 5000504 at redhat dot com> <563FA2DF dot 4050008 at redhat dot com> <alpine dot DEB dot 2 dot 20 dot 1511082042570 dot 2160 at laptop-mg dot saclay dot inria dot fr> <20151109002734 dot GD5808 at zira dot vinc17 dot org> <20151109004946 dot GA2103 at gate dot crashing dot org> <20151109082849 dot GA5556 at zira dot vinc17 dot org> <20151109094012 dot GA12699 at gate dot crashing dot org> <20151109124255 dot GA17411 at zira dot vinc17 dot org>
On 09/11/15 13:42, Vincent Lefevre wrote:
> On 2015-11-09 03:40:12 -0600, Segher Boessenkool wrote:
>> On Mon, Nov 09, 2015 at 09:28:49AM +0100, Vincent Lefevre wrote:
>>> On 2015-11-08 18:49:46 -0600, Segher Boessenkool wrote:
>>>> On Mon, Nov 09, 2015 at 01:27:34AM +0100, Vincent Lefevre wrote:
>>>>>> Why not simply:
>>>>>> unsigned y = x;
>>>>>> return y*y*y;
>>>>>> ? This is an example where defined behavior is so easy to get...
>>>>>
>>>>> But what if the result of y*y*y (an unsigned int) does not fit in
>>>>> an int?
>>>>
>>>> That is implementation-defined. not undefined (6.3.1.3); GCC documents
>>>> it like this:
>>>>
>>>> For conversion to a type of width N, the value is reduced modulo
>>>> 2^N to be within range of the type; no signal is raised.
>>>
>>> That's what GCC does, but what if the user uses another compiler
>>> or GCC decides to change this behavior in the future?
>>
>> Then it is still not undefined behaviour. It can give different results
>> of course.
>
> ... including a signal, which is not acceptable for the OP, if I
> understand correctly ("we don't care about the result in such cases"
> doesn't imply that the program may terminate immediately).
>
Correct.
The ideal here is to get an /unspecified/ integer - without the risk of
a trap or undefined behaviour. Implementation-defined behaviour that is
known to be safe on gcc is a step forward - I am aware that the ideal
here is not possible in standard and portable C.
In this particular example, implementation-dependent behaviour is fine.
But in some circumstances, unspecified behaviour /may/ be even better
as it gives the compiler complete freedom for optimisation. Here the
compiler is required to generate a specific result, as calculated using
the implementation-specified rules.