Shift error

Michael Meissner meissner@cygnus.com
Tue Feb 1 08:13:00 GMT 2000


On Tue, Feb 01, 2000 at 03:14:15PM +0100, Vassilis Vlachoudis wrote:
> Hello the following program reports 2 different results for the same
> operation (shift left) using a variable or the value for the shift.
> 
> #include <stdio.h>
> main() {
>         long n, n2;
>         int shift;
>  
>         n = 1L << 32;
>  
>         shift = 32;
>         n2 = 1L << shift;
>  
>         printf("N1=%X N2=%X\n",n,n2);
>         return 0;
> }                                                                              
> 
> Normally both operation should shift the 1, 32 bits on the left resulting
> to zero

Wrong.  Shifts by any value outside of the range 0..<bitsize>-1 are not defined
(where <bitsize> is the number of bits in the shifted type after type
promotion).  So on 32-bit systems (like the i386), a compiler can produce any
answer it feels like.   As a GCC developer, I have run into machines that
produce the following behaviors:

	x << n == x << (n & 31)
	x << n == (n > 31 || n < 0) ? 0 : (x << n)
	x << n == (n > 31) ? (~(~0 << (n >> 5)) & (x << (n & 31))) : (x << n)
	x << n == (n < 0) ? x >> n : x << n

GCC 2.95.2 does warn of the first shift:

foo.c: In function `main':
foo.c:6: warning: left shift count >= width of type

but it doesn't warn of the second (it should under optimization, since
instruction combination willl fold the shift = 32 into the second shift.

-- 
Michael Meissner, Red Hat, Inc.
PMB 198, 174 Littleton Road #3, Westford, Massachusetts 01886
Work:	  meissner@redhat.com		phone: 978-486-9304 fax: 978-692-4482
Non-work: meissner@spectacle-pond.org


More information about the Gcc-bugs mailing list