Re: Inconsistent shift operator

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Sam Mason <sam(at)samason(dot)me(dot)uk>
Cc: pgsql-bugs(at)postgresql(dot)org
Subject: Re: Inconsistent shift operator
Date: 2008-04-20 16:27:38
Message-ID: 21647.1208708858@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Sam Mason <sam(at)samason(dot)me(dot)uk> writes:
> Wouldn't it be easy to put some code like this in:

> if (arg2 < 16)
> return PG_RETURN_INT16(arg1 << arg2);
> return PG_RETURN_INT16(0);

This is a straw man. It covers *one* of the behaviors left undefined
by the C standard. I quote from C99:

[#3] The integer promotions are performed on each of the
operands. The type of the result is that of the promoted
left operand. If the value of the right operand is negative
or is greater than or equal to the width of the promoted
left operand, the behavior is undefined.

[#4] The result of E1 << E2 is E1 left-shifted E2 bit
positions; vacated bits are filled with zeros. If E1 has an
unsigned type, the value of the result is E1<<E2, reduced
modulo one more than the maximum value representable in the
result type. If E1 has a signed type and nonnegative value,
and E1<<E2 is representable in the result type, then that is
the resulting value; otherwise, the behavior is undefined.

[#5] The result of E1 >> E2 is E1 right-shifted E2 bit
positions. If E1 has an unsigned type or if E1 has a signed
type and a nonnegative value, the value of the result is the
integral part of the quotient of E1 divided by the quantity,
2 raised to the power E2. If E1 has a signed type and a
negative value, the resulting value is implementation-
defined.

We are shifting signed types so we are exposed to every one of these
unspecified behaviors. In particular, since we don't know whether the
behavior of >> will be zero-fill or sign-fill, it's not going to be
exactly trivial to make a consistent extension of it to shift values
greater than the word width.

By the time you get done replicating all this for the int2, int4,
and int8 shift operators, it's not looking like such a small patch
anymore. And I still find the premise entirely unconvincing.
Maybe the user *wants* to see the local behavior of shift, whatever
it might be. It's certainly not impossible that we'd break applications
that worked fine before (at least on the hardware they were being
used on).

regards, tom lane

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Peter Eisentraut 2008-04-20 17:08:00 Re: Inconsistent shift operator
Previous Message Peter Eisentraut 2008-04-20 15:31:51 Re: BUG #4115: PostgreSQL ISO format is not really ISO