[llvm-bugs] [Bug 33329] New: [X86][SSE] Improve general memcmp support

via llvm-bugs llvm-bugs at lists.llvm.org
Tue Jun 6 10:07:01 PDT 2017


            Bug ID: 33329
           Summary: [X86][SSE] Improve general memcmp support
           Product: libraries
           Version: trunk
          Hardware: PC
                OS: Windows NT
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Backend: X86
          Assignee: unassignedbugs at nondot.org
          Reporter: llvm-dev at redking.me.uk
                CC: andrea.dibiagio at gmail.com, filcab at gmail.com,
                    llvm-bugs at lists.llvm.org, spatel+llvm at rotateright.com

Currently memcmp lowers to a libcall:

int cmp16(const char *a, const char *b) {
        return __builtin_memcmp(a, b, 16);

cmp16(char const*, char const*):
        movl    $16, %edx
        jmp     memcmp

Which depending on the lib implementation/shim calls can be quite slow. A
possible alternative would be to vectorize this, using a more complex version
of what we do for 'equality' memcmp (Bug #33325):

#include <x86intrin.h>
int cmp16(const char *a, const char *b) {
  __m128i va = _mm_loadu_si128((const __m128i*)a);
  __m128i vb = _mm_loadu_si128((const __m128i*)b);
  unsigned eq = _mm_movemask_epi8(_mm_cmpeq_epi8(va, vb));

  __m128i kSign = _mm_set1_epi8(0x80);
  va = _mm_xor_si128(va, kSign);
  vb = _mm_xor_si128(vb, kSign);
  unsigned gt = _mm_movemask_epi8(_mm_cmpgt_epi8(va, vb));
  unsigned lt = _mm_movemask_epi8(_mm_cmplt_epi8(va, vb));

  unsigned cgt = __tzcnt_u32(gt);
  unsigned clt = __tzcnt_u32(lt);
  return ((eq == 0xFFFF) ? 0 : (clt - cgt));

clang -g0 -O3 -march=btver2

cmp16(char const*, char const*):
        vmovdqu (%rdi), %xmm0
        vmovdqu (%rsi), %xmm1
        vpcmpeqb        %xmm1, %xmm0, %xmm2
        vpmovmskb       %xmm2, %ecx
        vmovdqa .LCPI0_0(%rip), %xmm2   # xmm2 =
        vpxor   %xmm2, %xmm0, %xmm0
        vpxor   %xmm2, %xmm1, %xmm1
        vpcmpgtb        %xmm1, %xmm0, %xmm2
        vpcmpgtb        %xmm0, %xmm1, %xmm0
        vpmovmskb       %xmm2, %eax
        vpmovmskb       %xmm0, %edx
        tzcntl  %eax, %eax
        tzcntl  %edx, %edx
        subl    %eax, %edx
        xorl    %eax, %eax
        cmpl    $65535, %ecx            # imm = 0xFFFF
        cmovnel %edx, %eax

You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20170606/3e630960/attachment.html>

More information about the llvm-bugs mailing list