This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: O2 Agressive Optimisation by GCC


On 07/20/2018 12:17 PM, Richard Biener wrote:
On July 20, 2018 7:59:10 PM GMT+02:00, Martin Sebor <msebor@gmail.com> wrote:
On 07/20/2018 06:19 AM, Umesh Kalappa wrote:
Hi All ,

We are looking at the C sample i.e

extern int i,j;

int test()
{
while(1)
{       i++;
        j=20;
}
return 0;
}

command used :(gcc 8.1.0)
gcc -S test.c -O2

the generated asm for x86

.L2:
        jmp     .L2

we understand that,the infinite loop is not  deterministic ,compiler
is free to treat as that as UB and do aggressive optimization ,but we
need keep the side effects like j=20 untouched by optimization .

Please note that using the volatile qualifier for i and j  or empty
asm("") in the while loop,will stop the optimizer ,but we don't want
do  that.

Anyone from the community ,please share their insights why above
transformation is right ?

The loop isn't necessarily undefined (and compilers don't look
for undefined behavior as opportunities to optimize code), but

The variable i overflows.

Good point!

It doesn't change the answer or the behavior of any compiler
I tested (although ICC and Oracle cc both emit the assignment
as well as the increment regardless of whether the variables
are signed).  I don't think it should change it either.

Going further, and as much value as I put on diagnosing bugs,
I also wouldn't see it as helpful to diagnose this kind of
eliminated undefined behavior (so long as the result of
the overflow wasn't used).  What might be helpful, though,
is diagnosing the infinite loop similarly to IBM xlc and
Oracle cc.  Maybe not in the constant case but in the non-
constant cases if might help catch bugs.

Martin


because it doesn't terminate it's not possible for a conforming
C program to detect the side-effects in its body.  The only way
to detect it is to examine the object code as you did.

I'm not sure we perform this kind of dead code elimination but yes, we could. Make i unsigned and check whether that changes behavior.

Compilers are allowed (and expected) to transform source code
into efficient object code as long as the transformations don't
change the observable effects of the program.  That's just what
happens in this case.

Martin



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]