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

            Bug ID: 110492
           Summary: Attempted optimization of switch statement pessimizes
                    it instead
           Product: gcc
           Version: 13.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: qufanat at gmail dot com
  Target Milestone: ---

This happens on my local GCC 11.3, but you can also see it on 13.1 at this
godbolt link https://godbolt.org/z/G3qecWxPr

I'm creating a switch statement of hashed strings, which compiles to a binary
search on the hashes, all well and good.  However, with -O3 specified, GCC
peels back the last multiplication of the hash for some of the comparison
branches, but is unable to do it for others, resulting in longer assembly with
twice as many comparisons as is necessary.  Here is lines 15..19 in
get_choice_1()

    (end of the hash loop)
        imul    esi, eax, 16777619
        test    dl, dl
        jne     .L3
    (start of the switch)
        cmp     eax, 1954414351
        je      .L8
        cmp     esi, 1901626525
        ja      .L4

eax is the hash without the last imul, and esi is the final hash.  If we
prevent inlining of the hash function, the compiler can't make this
"optimization" and gives the assembly I expect.  Here is lines 90..93 in
get_choice_2()

        call    hash32_noinline(char const*)
        cmp     eax, 1901626525
        je      .L33
        jbe     .L46

Now it only does one comparison per entry and uses it for both the == and <=
branches.

This isn't that important to my program but I thought you'd like to know.

Reply via email to