Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang optimization: && vs &: optimized vs. non-optimized (for certain values)

clang -O3 optimizes this code:

_Bool f1(char x)
{
    _Bool b1 = x == 4;
    _Bool b2 = x & 3;
    return b1 & b2;
}

to:

f1:
        xor     eax, eax
        ret

However, clang -O3 does not optimize this code:

_Bool f1(char x)
{
    _Bool b1 = x == 2;
    _Bool b2 = x & 1;
    return b1 & b2;
}
f1:
        cmp     dil, 2
        sete    al
        and     al, dil
        ret

Why?

Note: the & b1 & b2 is used intentionally. If && is used, then clang -O3 optimizes it to:

f1:
        xor     eax, eax
        ret

How it can be explained?

like image 810
pmor Avatar asked Oct 20 '25 04:10

pmor


1 Answers

Why?

Inefficient code generation (due to "missing narrowing transforms for bitwise logic").

like image 56
pmor Avatar answered Oct 21 '25 19:10

pmor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!