Article View: comp.arch
Article #1045Re: reassociation and undefined behaviour
From: David Brown
Date: Thu, 03 Dec 2026 14:10
Date: Thu, 03 Dec 2026 14:10
188 lines
8982 bytes
8982 bytes
On 03/12/2026 12:20, Anton Ertl wrote:
> David Brown <david.brown@hesbynett.no> writes:
>> On 03/12/2026 03:07, MitchAlsup wrote:
>>> David Brown <david.brown@hesbynett.no> posted:
>>>> In general, "(x<<n) | (x>>(32-n))" cannot be replaced with "undef"
>>>
>>> It should be replaced with::
>>>
>>> ROTW Rt,Rx,Rn
>>>
>>
>> Optimising compilers generally do implement such expressions with
>> rotation instructions, when "n" is a variable.
>
> I looked at this in 2015, and found that clang-3.5 generates:
>
> mov %sil,%cl
> rol %cl,%edi
>
> if it knows nothing about n, but code that produces 0 if it knows that
> n=0.
>
>> There are good reasons for such shifts being UB in C. Processors are
>> not consistent in how out-of-range shifts are handled. "x >> 32" might
>> give 0 or it might give x.
>
> If C specified that the result is 0 or x, then the result of the
> expression above for n=0 would be x (because (x|x)==x and (x|0)==x).
>
> So I think there is a good reason to specify that x>>32 is 0 or x, but
> not a good reason to make it undefined behaviour.
Yes, I suppose the standards could say that "x >> 32" (for 32-bit x) may
evaluate to either 0 or x, with the choice being unspecified.
(Unspecified, rather than implementation-defined, so that either could
be used at different times in the one compilation.) That would be ideal
for the case of the rotation expression, since either 0 or x would give
the desired final result. But outside of that use-case, I think it
would be unhelpful.
GCC's manual says that it does not leave this kind of thing as undefined
behaviour, yet fails to say how it /does/ define the behaviour. Given
the range of possible handling of shifts in different processors
(including software routines for processors without barrel shifters), I
think there is a good case to be made for leaving it UB in the C
standards and letting individual compilers document any specific
behaviour. But it would then be nice if the compilers improved their
documentation here!
>
>> So this is not something that can be fully defined behaviour in C, nor
>> something that can even be implementation-defined behaviour - results
>> calculated at compile time may differ from results calculated at run
>> time.
>
> If the language defines it as implementation-defined, a compiler that
> does not do what it documents as the implementation-defined behaviour
> would be buggy.
Sure.
> And of course a compiler can and should implement at
> compile time the same behaviour that it implements at run-time,
> whether the behaviour is defined or not; in the latter case it's not a
> requirement from the standard, but a quality-of-implementation issue.
Yes, that is certainly the case for implementation-defined behaviour.
For UB or unspecified behaviour, different behaviours are allowed.
Whether that's a good idea or not is another matter - user expectation
can vary. Some users might expect x >> 32 to be 0, others might expect
it to be x, some might expect it to depend on the target platform.
Different results from compile-time and run-time evaluation could
surprise people, but so could different results for different targets.
Making this all fully defined and target independent would be good for
consistency, but introduce inefficiencies on some targets. I don't
think there is a single good solution to all of this - hence the C
standard's choice of UB meaning "I don't want to answer this question".
>
>> A good solution is to use :
>>
>> inline uint32_t rol(uint32_t x, uint32_t n) {
>> return (n == 0) ? x : (x << n) | (x >> (32 - n));
>> }
>>
>> A good compiler will generate a single ROL for that
>
> I tried "n==0?x:((x<<n)|(x>>(32-n)))" with clang-3.5, and the code it
> generated is
>
> testl %esi, %esi
> je .LBB1_2
> movb %sil, %cl
> roll %cl, %edi
> .LBB1_2:
>
How old is clang 3.5 ? 15 years? More? Modern clang generates code
like modern gcc here, but I have not bothered trying to identify exact
versions of gcc and clang that handle this optimally.
It is an unfortunate reality in C programming that sometimes correct
code is less efficient on weaker or older compilers than "correct if we
assume the UB does what we want it to" code. There is no single best
way to handle this. One possible strategy is to have conditional
compilation that checks for specific compiler versions and uses faster
but non-portable code where you know it works, and falls back to generic
correct code otherwise. Of course that can be tedious and error-prone.
> I.e., clang-3.5
>
> * produces the best possible code for the common idiom "(x<<n) |
> (x>>(32-n))" if n is unknown.
>
> * produces worse code for the alternative you recommend (and that has
> been recommended in discussions I read in 2015 (that's why I threw
> this alternative at the compiler).
>
> If the compiler knows that n=0, the smallest code would be to just
> leave %edi unchanged (0 instructions), and it would have resulted in
> the intended behaviour (i.e. it produces the same result as invoking
> the code produced for the common idiom with n=0). Instead, clang-3.5
> invested extra effort to miscompile the common idiom into
>
> mov $0, %edi
>
> or somesuch.
>
I failed to reproduce that on godbolt, but maybe it depends on the exact
details of the test code. All my testing showed it compiled to "movl
%edi, %eax" - copying the "x" parameter to the return register in a test
function, which is optimal here.
>
> An alternative workaround for the shortcomings of the C standard and
> its implementation by gcc and clang is:
>
> (x<<n)|(x>>((-n)&31))
>
> However, gcc-4.8 compiles this to:
>
> movl %esi, %ecx
> negl %ecx
> shrl %cl, %eax
> movl %esi, %ecx
> sall %cl, %edi
> orl %edi, %eax
>
> A version of that that would work for any n and is nicely symmetric is
>
> (x<<(n&31))|(x>>((-n)&31))
>
A quick test of these two formulations shows gcc generates optimal code
for the first one from version 4.9, and for the second one from version
8 onwards. Clang handles them both optimally from 3.5. (There are
minor differences in instruction order - I am assuming these don't make
a difference.)
I appreciate that it is good, where practical, to write code that can be
compiled with reasonable efficiency across a wide range of tools. But
if you need efficient results then it is usually better to focus on code
that is matched to newer compilers that do a better overall job of
optimising.
> but I have not checked which compilers produce which code for that.
>
>> C2y will have a function "stdc_rotate_left" that is specified as though
>> it was (for 32-bit types) :
>>
>> uint32_t stdc_rotate_left(uint32_t x, uint32_t n) {
>> n &= 0x1f;
>> return (n == 0) ? x : (x << n) | (x >> (32 - n));
>> }
>
> Good.
>
Standard C does not change quickly, but it gets there in the end :-)
C++ has had std::rotl and std::rotr since C++20.
I think the right time to add these functions might have been C99 along
with the <stdint.h> types and generic macros.
Technical Details
Message-ID:
<11ert96$djq8$1@dont-email.me>Path:
mbox-mo1.pugleaf.net!srl.newsdeef.eu.MISMATCH!feed-eu-txt.newsdeef.eu!feed-eu-ch.newsdeef.eu!srl.newsdeef.eu!news.hispagatos.org!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mailReferences:
<11cpqih$acf5$1@dont-email.me> <86o6b6kaqf.fsf@linuxsc.com> <11ejr5e$nk8$1@reader2.panix.com> <11ejtoe$eoj7$1@dont-email.me> <11el2c1$q43$1@reader2.panix.com> <11emcgn$1k681$1@dont-email.me> <jwvbj74bzm4.fsf-monnier+comp.arch@gnu.org> <11eolqn$2peg5$1@dont-email.me> <2026Dec2.132411@mips.complang.tuwien.ac.at> <11epd07$362ph$1@dont-email.me> <1796263648-5857@newsgrouper.org> <11ergn7$6utu$1@dont-email.me> <2026Dec3.122036@mips.complang.tuwien.ac.at>Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!srl.newsdeef.eu.MISMATCH!feed-eu-txt.newsdeef.eu!feed-eu-ch.newsdeef.eu!srl.newsdeef.eu!news.hispagatos.org!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail From: David Brown <david.brown@hesbynett.no> Newsgroups: comp.arch Subject: Re: reassociation and undefined behaviour Date: Thu, 3 Dec 2026 15:10:46 +0100 Organization: A noiseless patient Spider Lines: 188 Message-ID: <11ert96$djq8$1@dont-email.me> References: <11cpqih$acf5$1@dont-email.me> <86o6b6kaqf.fsf@linuxsc.com> <11ejr5e$nk8$1@reader2.panix.com> <11ejtoe$eoj7$1@dont-email.me> <11el2c1$q43$1@reader2.panix.com> <11emcgn$1k681$1@dont-email.me> <jwvbj74bzm4.fsf-monnier+comp.arch@gnu.org> <11eolqn$2peg5$1@dont-email.me> <2026Dec2.132411@mips.complang.tuwien.ac.at> <11epd07$362ph$1@dont-email.me> <1796263648-5857@newsgrouper.org> <11ergn7$6utu$1@dont-email.me> <2026Dec3.122036@mips.complang.tuwien.ac.at> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 03 Dec 2026 14:10:47 +0000 (UTC) Injection-Info: dont-email.me; logging-data="446280"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19jZhwXxaujlWhRZzxg+k2rFtytFXzjxNA="; posting-host="afe1cf6b446da7dc61b87fcc2868235d" User-Agent: Mozilla Thunderbird Cancel-Lock: sha1:JnI4Z0nHx34pCzRy1CARsd4N9Es= sha256:hF32AiiAwPlkGO3Ldc6VnXdryqhoIFZLBdGQ4/AycTs= sha1:UYSaI1PUt3ZNN6C1fqV01L4+8HM= sha256:2IMDPAJhvZtmJTClQEKIoySPwmtcHvnVh+beXOgL9Dk= In-Reply-To: <2026Dec3.122036@mips.complang.tuwien.ac.at> Content-Language: en-GB, nb-NO