[llvm-bugs] [Bug 42257] New: Missed optimization when a constant is a power of two

via llvm-bugs llvm-bugs at lists.llvm.org
Wed Jun 12 07:23:59 PDT 2019


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

            Bug ID: 42257
           Summary: Missed optimization when a constant is a power of two
           Product: new-bugs
           Version: trunk
          Hardware: PC
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: new bugs
          Assignee: unassignedbugs at nondot.org
          Reporter: jameshamm1995 at gmail.com
                CC: htmldeveloper at gmail.com, llvm-bugs at lists.llvm.org

The following function is correctly treated as a no-op by clang(trunk, -Ofast
--march=skylake)


bool zero(bool b) {
    int x = 5;
    return (x * b) + (-x * b);
}

=>

zero(bool):
        xor     eax, eax
        ret


Messing around with this function on compiler explorer
(https://godbolt.org/z/grc5ZF), I noticed when the constant is set to a power
of two (where the power is not 0 or 1) or the negative of a power of two, the
code is no longer optimized away.

bool zero(bool b) {
    int x = 4;
    return (x * b) + (-x * b);
}

=>

zero(bool):
        shl     edi, 2
        cmp     edi, edi  ;; Always sets the ZF
        setne   al        ;; ZF is set, so al is always 0
        ret

This missed optimization still happens when the return type is an int, and the
missed optimization is not obvious from the assembly
(https://godbolt.org/z/ZEwONp).

// Completely optimized
int zero(bool b) {
    int x = 18;
    return (x * b) + (-x * b);
}

=>

zero(bool):
        xor     eax, eax
        ret


vs

// Missing opportunity
int zero(bool b) {
    int x = 4;
    return (x * b) + (-x * b);
}

=>

zero(bool):
        mov     eax, edi
        shl     eax, 2
        xor     dil, 1
        movzx   ecx, dil
        lea     eax, [rax + 4*rcx]
        add     eax, -4
        ret

The problem disappears if the function parameter is widened,

int zero(int b) {
    int x = 4;
    return (x * b) + (-x * b);
}

or if the intermediate values are close to overflowing
(https://godbolt.org/z/yHPjz2),

int zero(bool b) {
    int x = 1 << 31;
    return (x * b) + (-x * b);
}

or (as a comment on stackoverflow pointed out
https://stackoverflow.com/questions/56416747/missed-optimization-in-clang-only-on-powers-of-two#comment99429730_56416747)
if the value is not known.

int zero(bool b, int x) {
    return (x * b) + (-x * b);
}

All compile down to

zero(int):
        xor     eax, eax
        ret

-- 
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/20190612/9d361b9e/attachment.html>


More information about the llvm-bugs mailing list