This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Left shift of negative value
- From: Richard Earnshaw <Richard dot Earnshaw at foss dot arm dot com>
- To: Andrew Haley <aph at redhat dot com>, "gcc-help at gcc dot gnu dot org" <gcc-help at gcc dot gnu dot org>
- Date: Tue, 1 Dec 2015 17:26:57 +0000
- Subject: Re: Left shift of negative value
- Authentication-results: sourceware.org; auth=none
- References: <565DC5B6 dot 8090606 at redhat dot com> <565DD273 dot 6070106 at foss dot arm dot com> <565DD3FC dot 5000101 at redhat dot com> <565DD486 dot 40106 at redhat dot com>
On 01/12/15 17:10, Andrew Haley wrote:
> On 12/01/2015 05:08 PM, Andrew Haley wrote:
>> On 12/01/2015 05:01 PM, Richard Earnshaw wrote:
>>> On 01/12/15 16:07, Andrew Haley wrote:
>>>> Do we support left shift of a negative value? Technically it's
>>>> undefined and ubsan warns about it. However, a ton of software would
>>>> surely break if we didn't do the obvious right thing. I can't find
>>>> anything in the GCC manual.
>>>
>>> I don't believe we do, or can as of today. Firstly, there are two
>>> possible 'obvious' behaviours: 1) The value is treated as signed and a
>>> negative shift turns into a positive shift in the other direction; 2)
>>> The value is treated as unsigned and the value is treated by a massive
>>> shift in the same direction that exceeds the normally supported range of
>>> the type. Which one is the default will probably depend on your hardware.
>>>
>>> Consider the case where the value is in a variable. To support negative
>>> shifts as reversed shifts on machines where they don't automatically
>>> convert negative values to reversed shifts you'd have to do an explicit
>>> range check before every shift using that value. Something I know we
>>> don't do today since I've never seen such checks come out on ARM, nor
>>> are there any hooks in the compiler to deal with it.
>>
>> No, a shift *of* a negative value, not a shift *by* a negative value!
>> i.e. an arithmetic right shift.
>
> That explanation was even more confusing. Sorry.
>
> I mean something like -12345 << 4
>
> Andrew.
>
>
Yeah, sorry, I mis-parsed your original email.
I'd expect that to work on practically all 2's complement machines. And
I'd also expect right shifts to work correctly with GCC by doing
sign-bit replication on a 2's complement machine.
R.