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: Option to make unsigned->signed conversion always well-defined?


On Thu, Oct 6, 2011 at 11:04 AM, Miles Bader <miles@gnu.org> wrote:
> How about:
>
>   bool overflowbit2(unsigned int a, unsigned int b)
>   {
>       const unsigned int sum = a + b;
>       return ~(a ^ b) & sum & 0x80;
>   }
>
> ?
>
> I thinnnnk it has the same results as your function...
> [I just made a table of all 8 possibilities, and checked!]

Miles, it is not the same. Take for example (0xff, 0xff). In 8-bit 2's
complement, this is (-1, -1) and does not overflow. Your function says
it does.


Em 06-10-2011 12:23, Jeremy Hall escreveu:
> bool overflow(int16_t a, int16_t b)
> {
>    const int16_t sum = a + b;
>    return sum > INT8_MAX || sum < INT8_MIN;
> }

Jeremy, here you are ignoring the problem of converting from the
unsigned int (in the range 0 to 0xff) to the signed integer that it
represents in 8-bit two's complement. Example: 0xff -> -1.

In practice, casting the unsigned int to int8_t works in most cases, but
it is compiler-defined. We are trying to find a always well-defined
approach that is efficient as well.


> Ops, should have been
> 
> return ~(a ^ b) & (a ^ sum) & 0x80
> 
> ~(a ^ b) gives 1 in the sign bit position if the signs are the same,
> and (a ^ sum) gives 1 if it's different in the sum.

This is good. Do you think this is suboptimal? How are you evaluating
efficiency? In x86 this generates pretty small code.

<overflow2>:
  400524:   8d 04 3e                lea    (%rsi,%rdi,1),%eax
  400527:   31 f8                   xor    %edi,%eax
  400529:   31 f7                   xor    %esi,%edi
  40052b:   f7 d7                   not    %edi
  40052d:   21 f8                   and    %edi,%eax
  40052f:   25 80 00 00 00          and    $0x80,%eax
  400534:   c3                      retq

-- 
Pedro Pedruzzi


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