On Sat, Jan 8, 2022 at 12:33 AM Martin Uecker via Gcc <gcc@gcc.gnu.org> 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

The question becomes what is a trapping instruction vs an undefined instruction?
For floating point types, it is well defined what is a trapping
instruction while for integer types it is not well defined.
On some (many?) targets dividing by 0 is just undefined and does not
trap (powerpc, aarch64, arm and many others; MIPS it depends on the
options passed to GCC if the conditional trap should be inserted or
not).
The other side is if there is undefined code on the path, should
observable results happen first (stores to volatile/atomics, etc.)?

GCC assumes by default that divide is trappable but stores not are not
observable. This is where -fnon-call-exceptions come into play.

In the second case, GCC assumes reducing trappable instructions are
fine. Note I thought -fno-delete-dead-exceptions would fix the sink
but it didn't.

Thanks,
Andrew Pinski

>
> In this example a division is hoisted
> before the volatile store. (the division
> by zero which could trap is UB, of course).
>
> 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