Re: [PATCH v7 2/5] x86/asm: add volatile, clobbers and zero-length check in inline memcmp

"H. Peter Anvin" <[email protected]>
Newsgroups org.xenproject.lists.xen-devel,org.kernel.vger.linux-kernel
Message-ID <[email protected]>
On 2026-07-24 16:35, H. Peter Anvin wrote:
> On 2026-07-24 14:53, H. Peter Anvin wrote:
>>
>> It's pretty bloaty; I don't know exactly how much the rest of the code bloats.
>>
>> I would be fine with having mem[n]eq() though as an explicit API. For the out-of-line version used for compiler-generated memcmp() calls it doesn't matter. 
>>
>> Here is a very compact way the out-of-line version can be written (showing the 64-bit version; formatting apologies, on a phone):
>>
>> xor %eax,%eax    /* Sets ZF */
>> repe cmpsb
>> jr z,1f
>> movzbl -1(%rdi),%edi
>> mov -1(%rsi),%al
>> sub %edi,%eax
>> 1: ret
>>
> With a C wrapper to work in any mode:
> 
> int memcmp(const void *a, const void *b, size_t size)
> {
>         int diff;
> 
>         asm volatile("xor %0,%0 ;"      /* Sets ZF for the size = 0 case */
>                      "repe cmpsb ;"
>                      "jz 1f ;"          /* When size = 0 loading is unsafe */
>                      "movb -1(%2),%b0 ;"
>                      "movzbl -1(%1),%k1 ;"
>                      "sub %k1,%0 ;"
>                      "1:"
>                      : "=&q" (diff), "+D" (a), "+S" (b), "+c" (size)
>                      : : "memory");
>         return diff;
> }
> 

And of course I got the comparison backwards (negative means a < b, thus we
want a - b not b - a). Here is a fixed version.

int memcmp(const void *a, const void *b, size_t size)
{
        int diff;

        asm volatile("xor %0,%0 ;"      /* Sets ZF for the size = 0 case */
                     "repe cmpsb ;"
                     "jz 1f ;"          /* When size = 0 loading is unsafe */
                     "movb -1(%1),%b0 ;"
                     "movzbl -1(%2),%k2 ;"
                     "sub %k2,%0 ;"
                     "1:"
                     : "=&q" (diff), "+D" (a), "+S" (b), "+c" (size)
                     : : "memory");
        return diff;
}

	-hpa
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.