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

            Bug ID: 116414
           Summary: Missed optimization: Branch elimination and memory
                    writes
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: target
          Assignee: unassigned at gcc dot gnu.org
          Reporter: madhur4127 at gmail dot com
  Target Milestone: ---

Godbolt: https://godbolt.org/z/oKrGfh34z

Code:

```
#include <optional>
#include <cstdint>

std::optional<uint16_t> x(uint16_t x) 
    { return x <= 1 ? std::nullopt : std::optional{x}; }
```

GCC trunk generates a branch and uses memory writes whereas it could just use
`eax` like clang

```
x(unsigned short):
        cmp     di, 1
        jbe     .L5
        mov     WORD PTR [rsp-4], di
        mov     BYTE PTR [rsp-2], 1
        mov     eax, DWORD PTR [rsp-4]
        ret
.L5:
        mov     BYTE PTR [rsp-2], 0
        mov     eax, DWORD PTR [rsp-4]
        ret
```

clang:
```
x(unsigned short):
        xor     eax, eax
        cmp     di, 2
        setae   al
        shl     eax, 16
        or      eax, edi
        ret
```

Reply via email to