Re: A few cases of left shifting negative integers

From: Andres Freund <andres(at)anarazel(dot)de>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Piotr Stefaniak <postgres(at)piotr-stefaniak(dot)me>, pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: A few cases of left shifting negative integers
Date: 2015-08-21 18:00:24
Message-ID: 20150821180024.GF8552@awork2.anarazel.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 2015-08-21 13:27:22 -0400, Tom Lane wrote:
> Andres Freund <andres(at)anarazel(dot)de> writes:
> > On 2015-08-21 13:03:42 -0400, Tom Lane wrote:
> >> The behavior is well-defined, at least as long as we don't shift far
> >> enough to have integer overflow
>
> > Unfortunately not:
> > 5.8.2: The value of E1 << E2 is E1 left-shifted E2 bit positions;
> > vacated bits are zero-filled. If E1 has an unsigned type, the value of
> > the result is E1 2 E2 , reduced modulo one more than the maximum value
> > representable in the result type. Otherwise, if E1 has a signed type and
> > non-negative value, and E1 2 E2 is representable in the result type,
> > then that is the resulting value; >>otherwise, the behavior is undefined<<.
>
> [ rolls eyes... ] There isn't any machine in the world where the behavior
> isn't well-defined short of overflow.

> Why do the C spec authors persist in pretending otherwise?

Yea, it's way past time that C is redefined being based on 2-s
completement. And why this is declared undefined rather than
implementation defined is completely beyond me.

FWIW, icc apparently has been observed to recognize that a negative
value cannot be shifted and thus optimized based on the assumption that
the number is positive...

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Robert Haas 2015-08-21 18:08:36 Re: Reduce ProcArrayLock contention
Previous Message Peter Geoghegan 2015-08-21 17:55:00 Re: Using quicksort for every external sort run