[llvm-bugs] [Bug 52593] New: Missed optimization when summing every second number in unsigned

via llvm-bugs llvm-bugs at lists.llvm.org
Tue Nov 23 12:39:59 PST 2021


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

            Bug ID: 52593
           Summary: Missed optimization when summing every second number
                    in unsigned
           Product: new-bugs
           Version: trunk
          Hardware: PC
                OS: All
            Status: NEW
          Keywords: missing-feature
          Severity: enhancement
          Priority: P
         Component: new bugs
          Assignee: unassignedbugs at nondot.org
          Reporter: llvm-bugs at admitriev.name
                CC: htmldeveloper at gmail.com, llvm-bugs at lists.llvm.org

Suppose we have a function

template<class T>
double foo(const std::vector<double>& v) {
    double sum = 0;
    T size = v.size();
    for (T i = 0; i < size; i += 2) {
        sum += v[i];
    }
    return sum;
}


and call it as foo<uint64_t> and foo<int64_t>.

The signed version is 1.7 times faster (both with libstdc++ and libc++)
https://quick-bench.com/q/EQxNHHtqi9497mG3ovtfG7fQa6s

(Note that gcc generates code for both signed and unsigned version
approximately as fast as signed clang version
https://quick-bench.com/q/lDXyfset7rLDmOG2mGxjVb1h0Zw)

Indeed we can se on godbolt that code generated for different type is
different: https://godbolt.org/z/Kjv6q7dsr
But seemingly there's no reason why they should be different.

One can argue that one possible difference is we can assume no overflow for
signed version. But actually we can assume no overflow in unsigned version as
well at least for three reasons:
1) if there's overflow, then the loop is infinite without any side-effects
which is UB
2)  the size guaranteed to be less then v.max_size() which is way less then 2
** 64
3) size is calculated as difference of 2 pointers to 8byte type, so it's
bounded by 2**61 or so
Note that I tried few ways to use __builtin_assume() to "proof" to the compiler
there's no overflow which didn't help.

-- 
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/20211123/09e770ff/attachment.html>


More information about the llvm-bugs mailing list