This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Efficient detection of signed overflow?
On Sun, Nov 29, 2009 at 8:53 PM, Florian Weimer <fw@deneb.enyo.de> wrote:
> * Mark Dickinson:
> [...]
>> if ((x^a) < 0 && (x^b) < 0)
>
> Would this test be better? ÂI think it's equivalent, and it saves a
> comparison.
>
> Âif (((x ^ a) & (x ^ b)) < 0)
Mmm. Quite possibly, yes. I'll do some timings.
>> Any suggestions for improvements over this?
>
> Use -fwrapv and your first version.
gcc isn't the only compiler that's going to have to compile
this code, so it still needs to be fixed to avoid undefined
behaviour (and I'm worried about -fwrapv inhibiting optimizations
elsewhere in the codebase). But I guess that casting everything in
sight to unsigned long and then casting the eventual result
back to long, as me22 suggests, would be pretty much equivalent.
On Sun, Nov 29, 2009 at 9:00 PM, me22 <me22.ca@gmail.com> wrote:
> What about using (long)((unsigned long)a + (unsigned long)b) or
> something to get around the UB?
Yep, that looks like the solution. Thanks!
Mark