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

            Bug ID: 88603
           Summary: optimization missed for saturation arithmetic add
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Keywords: missed-optimization
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: SztfG at yandex dot ru
  Target Milestone: ---
            Target: x86_64-linux-gnu

example:

#include <inttypes.h>

uint32_t saturation_add(uint32_t a, uint32_t b)
{
    const uint64_t tmp = (uint64_t)a + b;
    if (tmp > UINT32_MAX)
    {
        return UINT32_MAX;
    }
    return tmp;
}

output:
        mov     edx, esi
        mov     eax, edi
        add     edi, esi # Why need to add two times here
        add     rax, rdx # and here ?
        mov     edx, 4294967295
        cmp     rax, rdx
        mov     eax, -1 # Why? edx already have this value. -1 and 4294967295
are same
        cmovbe  eax, edi
        ret

better do something like this:
        add     edi, esi
        mov     eax, -1
        cmovae  eax, edi
        ret

Reply via email to