https://bugs.llvm.org/show_bug.cgi?id=50140

            Bug ID: 50140
           Summary: UBSan safe leading/trailing zero counts can't simplify
                    to zero-input correct variants
           Product: libraries
           Version: trunk
          Hardware: PC
                OS: Windows NT
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Scalar Optimizations
          Assignee: [email protected]
          Reporter: [email protected]
                CC: [email protected], [email protected],
                    [email protected], [email protected],
                    [email protected]

https://simd.godbolt.org/z/KrahKsdhe

clang -g0 -O3 -march=haswell

#include <cstdint>
#include <climits>

auto lz(unsigned x) {
    int c = __builtin_clz( x );
    return x ? c : sizeof(x) * CHAR_BIT;
}

auto tz(unsigned x) {
    int c = __builtin_ctz( x );
    return x ? c : sizeof(x) * CHAR_BIT;
}

lz:
        lzcntl  %edi, %eax
        retq

tz:
        tzcntl  %edi, %eax
        retq

auto lz_ubsan(unsigned x) {
    int c = __builtin_clz( x ? x : ~0U );
    return x ? c : sizeof(x) * CHAR_BIT;
}

auto tz_ubsan(unsigned x) {
    int c = __builtin_ctz( x ? x : ~0U );
    return x ? c : sizeof(x) * CHAR_BIT;
}

lz_ubsan:
        xorl    %eax, %eax
        cmpl    $1, %edi
        sbbl    %eax, %eax
        orl     %edi, %eax
        lzcntl  %eax, %ecx
        testl   %edi, %edi
        movl    $32, %eax
        cmovnel %ecx, %eax
        retq

tz_ubsan:
        xorl    %eax, %eax
        cmpl    $1, %edi
        sbbl    %eax, %eax
        orl     %edi, %eax
        tzcntl  %eax, %ecx
        testl   %edi, %edi
        movl    $32, %eax
        cmovnel %ecx, %eax
        retq

To prevent ubsan warnings, we mustn't call the ctz/clz builtins with a
zero-value. So we typically insert an all-bits value to make it shutup 

Unfortunately this conflicts with the post-combine that recognise cases where
the zero-value input should be correctly handled (e.g tzcnt/lzcnt x86
instructions).

Funnily enough, gcc has better code from the ubsan-safe cases.....

-- 
You are receiving this mail because:
You are on the CC list for the bug.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to