warning: right shift count >= width of type
Chris Jefferson
caj@cs.york.ac.uk
Mon Nov 29 17:38:00 GMT 2004
Dave Korn wrote:
>>-----Original Message-----
>>From: Dale Johannesen
>>Sent: 29 November 2004 16:31
>>
>>
>
>
>
>>On Nov 29, 2004, at 8:18 AM, Dave Korn wrote:
>>
>>
>>> Afternoon all. Here's something that's piqued my curiosity; it's
>>>probably
>>>owing to some language-lawyerly issue, but it isn't obvious to me.
>>>This is
>>>on gcc-3.3.3, (cygwin variant, but that's probably not relevant):
>>>
>>>-------------------------<snip!>-------------------------
>>>dk@mace /test/shift-test> cat foo.c
>>>
>>>unsigned int bar (unsigned int baz)
>>>{
>>>unsigned int quux;
>>>
>>> quux = baz >> 32;
>>> return quux;
>>>}
>>> Why isn't the shift operation optimised away and replaced with
>>>const_int
>>>0?
>>>
>>>
>>Because that's not what it means. Shifts by >= word size are
>>undefined
>>behavior
>>and will give different results depending on optimization
>>level and on
>>whether
>>the shift count is constant or variable. Don't do that. (If
>>you think
>>it ought to be 0,
>>reflect that most popular CPUs have only 5 bit shift counts, and
>>consider what the
>>code for x >> y would have to look like.)
>>
>>
>
>
> Absolutely so; my curiosity was piqued when I noticed that my
>cross-compiler was generating illegal assembler code with an out-of-range
>operand value that the assembler couldn't fit into the relevant opcode
>bitfield.
>
> So my question is really "Given that it's undefined, which means that
>whatever the compiler does is correct, and given that there's already code
>in there to detect the situation and issue a warning, which probably means
>that it would be very easy at such a point to replace the offending RTL with
>(const_int 0), is there any specific reason why not to?"
>
One reason (of course) not to would be if you are bit-shifting by a
variable. Adding a check at runtime to see if the value of this variable
is <32 and if not setting the variable to zero would be frowned upon by
many people, particuarily because the kind of people who undertake
bitshifting are doing it for performance-related reasons...
Chris
More information about the Gcc
mailing list