https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124884

            Bug ID: 124884
           Summary: Optimization: bitwise AND under a boolean variable
                    condition
           Product: gcc
           Version: 15.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: Explorer09 at gmail dot com
  Target Milestone: ---

```c
#include <stdbool.h>
bool pred();
int func1_and(int x) {
    bool cond = pred();
    int ret = x * 3;
    if (cond) {
        ret &= 10;
    }
    return ret;
}
int func1_and2(int x) {
    bool cond = pred();
    int ret = x * 3;
    int mask = 10;
    mask = cond ? 10 : ~0;
    ret &= mask;
    return ret;
}
```

Example assembly (x86-64 gcc with `-Os` option):

```assembly
func1_and:
        push    rbx
        mov     ebx, edi
        call    pred
        mov     edx, eax
        lea     eax, [rbx+rbx*2]
        test    dl, dl
        je      .L1
        and     eax, 10
.L1:
        pop     rbx
        ret
func1_and2:
        push    rbx
        lea     ebx, [rdi+rdi*2]
        call    pred
        cmp     al, 1
        sbb     eax, eax
        or      eax, 10
        and     eax, ebx
        pop     rbx
        ret
```

Compiler Explorer link:
https://godbolt.org/z/eTaG7as94

This missed optimization seems to happen only on the bitwise AND operation.

If I change the operation to either bitwise OR, bitwise XOR, bitwise NOT, or
addition, GCC know it can set the `mask` value to 0. For bitwise AND, GCC
didn't yet know it can set `mask` to -1 to do an equivalent no-op.

Reply via email to