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

            Bug ID: 129001
           Summary: GCC compiler misses 64-bit little-endian load
                    optimization
           Product: gcc
           Version: 16.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: knapek.mar at gmail dot com
  Target Milestone: ---

GCC compiler version 16.2 is missing a trivial optimization when compiling
a C or C++ code. Consider this two functions [1], both are doing the same
thing, loading an 64bit unsigned integer. They result in this [2] and this [3]
assembly. The second assembly is sub-optimal. Clang optimizes both functions
just fine. Sincerely, Marek.

[1]

    #include <limits.h>
    #include <stdint.h>

    uint64_t load_le_u64_ver1(void const* ptr)
    {
            unsigned char const* input = ((unsigned char const*)(ptr));
            uint64_t ret =
                (((uint64_t)(input[0])) << (0 * CHAR_BIT)) |
                (((uint64_t)(input[1])) << (1 * CHAR_BIT)) |
                (((uint64_t)(input[2])) << (2 * CHAR_BIT)) |
                (((uint64_t)(input[3])) << (3 * CHAR_BIT)) |
                (((uint64_t)(input[4])) << (4 * CHAR_BIT)) |
                (((uint64_t)(input[5])) << (5 * CHAR_BIT)) |
                (((uint64_t)(input[6])) << (6 * CHAR_BIT)) |
                (((uint64_t)(input[7])) << (7 * CHAR_BIT));
            return ret;
    }

    uint64_t load_le_u64_ver2(void const* ptr)
    {
            unsigned char const* input = ((unsigned char const*)(ptr));
            uint64_t ret = 0;
            for(int i = 0; i != sizeof(uint64_t); ++i)
            {
                ret |= (((uint64_t)(input[i])) << (i * CHAR_BIT));
            }
            return ret;
    }

[2]

    mov rax, QWORD PTR [rdi]
    ret

[3]

    xor   eax, eax
    xor   esi, esi
    .L4:
    movzx  edx, BYTE PTR [rdi+rax]
    lea    ecx, [0+rax*8]
    add    rax, 1
    sal    rdx, cl
    or     rsi, rdx
    cmp    rax, 8
    jne    .L4
    mov    rax, rsi
    ret

Reply via email to