[llvm-bugs] [Bug 50140] New: UBSan safe leading/trailing zero counts can't simplify to zero-input correct variants

via llvm-bugs llvm-bugs at lists.llvm.org
Tue Apr 27 04:22:48 PDT 2021


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: unassignedbugs at nondot.org
          Reporter: llvm-dev at redking.me.uk
                CC: david.bolvansky at gmail.com, lebedev.ri at gmail.com,
                    llvm-bugs at lists.llvm.org, nikita.ppv at gmail.com,
                    spatel+llvm at rotateright.com

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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20210427/23533edf/attachment.html>


More information about the llvm-bugs mailing list