Pathalogical divides
Geoff Keating
geoffk@cygnus.com
Sun Sep 24 22:53:00 GMT 2000
kenner@vlsi1.ultra.nyu.edu (Richard Kenner) writes:
> Consider the following program on x86:
>
> int rem (int a, int b) { return a % b; }
>
> int
> main ()
> {
> printf ("%d\n", rem (0x80000000, -1));;
> }
>
> When run, rather than producing zero, as expected, it gets a SIGFPE.
> This is because the division of the largest negative integer by negative one
> results in an overflow.
>
> So the first question is whether this is valid C behavior.
Yes. C interpreters are permitted to do anything they like when
signed integer arithmetic overflows, including producing a signal.
> Next, compile the above with -O3 on an x86 and notice that GCC gets a
> SIGFPE when constant-folding.
> Finally, consider:
>
> int
> foo (int a, int b)
> {
> return (a - ((a == 0x80000000 && b == -1) ? 0 : a % b)) / b;
> }
>
> This program when passed "normal" arguments does not get an overflow.
> But GCC pulls the conditional out of the subtraction and division and
> causes the compiler to run into the SIGFPE above.
Note that this code is valid C code, so we can't produce an _error_ in
this case. Thus I don't think we want to allow the signal to happen.
> I think the compiler crash needs to be fixed. We can do it either by
> protecting the integer part of simplify_binary_operation against SIGFPE
> just like the FP or explicitly testing for this case just like we
> check for divide by zero.
I suggest the second. We could then produce a helpful warning
message (but not an error).
> Any thoughts about whether we need a run-time test for this case
> in the "%" operator?
I don't think we do. (If we do, of course it's only necessary for x86.)
--
- Geoffrey Keating <geoffk@cygnus.com>
More information about the Gcc
mailing list