This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Is it OK that gcc optimizes away overflow check?
- From: Ian Lance Taylor <iant at google dot com>
- To: Agner Fog <agner at agner dot org>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Tue, 26 Jul 2011 07:43:10 -0700
- Subject: Re: Is it OK that gcc optimizes away overflow check?
- References: <4E2B2B72.9050504@agner.org> <mcr4o2arj57.fsf@coign.corp.google.com> <4E2E6CC6.3040106@agner.org>
Agner Fog <agner@agner.org> writes:
> Now, imagine doing something like this before every +, -, *, /,
> etc. in your code! If this is necessary then the C/C++ language is
> useless. We are in deep trouble now and we desperately need a better
> solution.
Nobody would suggest using that construction before every arithmetic
operation. One would only suggest using it before an operation which
may overflow.
You are writing as though wrapping overflow is always the right thing to
do, but that is false. In code written by a naive programmer, wrapping
on overflow will cause problems just as undefined overflow will.
> Your suggestion to use __attribute__ ((optimize
> ("-fno-strict-overflow"))); was an excellent idea. Unfortunately it
> doesn't work. The compiler says: warning: Ãoptimizeà attribute
> directive ignored.
When I compile this test case with current gcc mainline
#include <stdlib.h>
int f (int) __attribute__ ((optimize ("-fno-strict-overflow")));
int f (int i) { return abs (i) < 0; }
the comparison is not optimized away. So I think that the attribute
does work in current gcc.
> We need to be constructive here. We want the optimizations, but we
> also want to check if the optimizations go wrong. I think the compiler
> should be able to generate warnings for every unsafe optimization,
> especially when removing a branch. The compiler generates a warning
> when optimizing away if (a+5 < a) but not when optimizing away if
> (abs(a)<0).
When I compile this test case
#include <stdlib.h>
int f (int i) { return abs (i) < 0; }
with -O2 -Wstrict-overflow I see this warning:
foo.c:2: warning: assuming signed overflow does not occur when simplifying comparison of absolute value and zero
So I think the compiler does warn about optimizing that comparison away.
Ian