http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48580

--- Comment #1 from joseph at codesourcery dot com <joseph at codesourcery dot 
com> 2011-04-12 20:18:13 UTC ---
On Tue, 12 Apr 2011, zackw at panix dot com wrote:

> To the best of my knowledge, this is the only safe way (without -fwrapv) to
> check whether the product of two signed integers overflowed:
> 
> bool product_does_not_overflow(signed x, signed y)
> {
>   unsigned tmp = x * unsigned(y);
> 
>   return signed(tmp) > 0 && tmp / x == unsigned(y);
> }

Two signed integers given that they are known to be positive, anyway.  
This may return unexpected results if either or both arguments are 
negative or zero.

I sort of think GCC should have built-in functions exposing C and C++ 
interfaces for: each basic arithmetic operation, defined to wrap; each 
basic arithmetic operation, defined to saturate; each basic arithmetic 
operation, defined to have undefined overflow; each basic arithmetic 
operation, with a separate overflow flag being set; each basic arithmetic 
operation, defined to trap on overflow.  All of these for both signed and 
unsigned and for any desired number of bits (up to the maximum number 
supported for arithmetic, so generally 1-64 bits on 32-bit configurations 
and 1-128 bits on 64-bit configurations); except for the defined-to-trap 
case, all would still have undefined behavior on division by 0.  You could 
then have optimizations mapping generic C idioms to such built-in 
operations where the target supports efficient code for the operations.  
But this rather relies on the no-undefined-overflow work being finished 
first so that some of the required operations actually exist inside GCC, 
before they can easily be exposed to the user.

> which is a pretty substantial micro-win, particularly in getting rid of a
> divide.

(If the function gets called with one constant operand, you can make it 
inline and use __builtin_constant_p to replace a divide with a range check 
on the other operand.  That's only useful for some cases of overflow 
checks, of course.)

Reply via email to