On 08/01/2022 09:32, Martin Uecker via Gcc wrote:
> 
> Hi Richard,
> 
> I have a question regarding reodering of volatile
> accesses and trapping operations. My initial
> assumption (and  hope) was that compilers take
> care to avoid creating traps that are incorrectly
> ordered relative to observable behavior.
> 
> I had trouble finding examples, and my cursory
> glace at the code seemed to confirm that GCC
> carefully avoids this.  But then someone showed
> me this example, where this can happen in GCC:
> 
> 
> volatile int x;
> 
> int foo(int a, int b, _Bool store_to_x)
> {
>   if (!store_to_x)
>     return a / b;
>   x = b;
>   return a / b;
> }
> 
> 
> https://godbolt.org/z/vq3r8vjxr
> 
> In this example a division is hoisted 
> before the volatile store. (the division
> by zero which could trap is UB, of course).
> 

Doesn't this depend on whether the trap is considered "observable
behaviour", or "undefined behaviour" ?

If (on the given target cpu and OS, and with any relevant compiler
flags) dividing by zero is guaranteed to give a trap with specific known
behaviour, then it is observable behaviour and thus should be ordered
carefully with respect to the volatile accesses.

On the other hand, if division by 0 is considered undefined behaviour
(the C and C++ standards explicitly mark it as undefined, but a compiler
can of course define its behaviour) then the compiler can assume it does
not happen, or you don't care about the result of the program if it
happens.  Undefined behaviour can be freely re-ordered around volatile
accesses, as far as I understand it - though that can come as a surprise
to some people.


I don't know which of these views gcc takes - I think both are valid.
But it might be worth noting in the reference manual.

David



> As Martin Sebor pointed out this is done
> as part of redundancy elimination 
> in tree-ssa-pre.c and that this might
> simply be an oversight (and could then be
> fixed with a small change).
> 
> Could you clarify whether such reordering
> is intentional and could be exploited in
> general also in other optimizations or
> confirm that this is an oversight that
> affects only this specific case?
> 
> If this is intentional, are there examples
> where this is important for optimization?
> 
> 
> Martin
> 
> 
> 
> 
> 
> 
> 

Reply via email to