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

            Bug ID: 121674
           Summary: X ? C1 : C2 not optimized to (C1 - C2) + C1 * X for С1
                    > C2
           Product: gcc
           Version: 16.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: antoshkka at gmail dot com
  Target Milestone: ---

Consider the example:

int test0(bool cond) { return cond ? 10 : 2; }

GCC now generates the assembly:

"test0(bool)":
  cmp dil, 1
  sbb eax, eax
  and eax, -8
  add eax, 10
  ret


However a more optimal assembly can be generated:

test0(bool):
  lea eax, [8*rdi + 2]
  ret


Godbolt playground: https://godbolt.org/z/cGPhxx1Pv
More examples:

int test1(bool cond) { return cond ? 34 : 2; }
int test2(bool cond) { return cond ? 8 : 0; }
int test3(bool cond) { return cond ? 9 : 0; }
int test4(bool cond) { return !cond ? 0 : 9; }

and more optimal assemblies:

test1(bool):
  shl edi, 5
  lea eax, [rdi + 2]
  ret

test2(bool):
  lea eax, [8*rdi]
  ret

test3(bool):
  lea eax, [rdi + 8*rdi]
  ret

test4(bool):
  lea eax, [rdi + 8*rdi]
  ret

Reply via email to