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

            Bug ID: 102927
           Summary: Failure to optimize series of if-else to use array
                    when possible
           Product: gcc
           Version: 12.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: gabravier at gmail dot com
  Target Milestone: ---

int foo(int i) {
  if (i == 0)
    return 52;
  else if (i == 1)
    return 77;
  else if (i == 2)
    return 91;
  else if (i == 3)
    return 10;
  else
    return 42;
}

int bar(int i) {
  switch (i) {
  case 0:
    return 52;
  case 1:
    return 77;
  case 2:
    return 91;
  case 3:
    return 10;
  default:
    return 42;
  }
}

int baz(int i)
{
    static const int results[] = {52, 77, 91, 10};
    if (__builtin_expect_with_probability((unsigned)i < 4, 1, 0.5))
        return results[(unsigned)i];
    return 42;
}

foo can be optimized to be equivalent to baz (like bar is). This optimization
is done by LLVM, but not by GCC.

PS: I've observed that making the if-else chain longer triggers the
optimization. Is GCC considering the if-else chain to be faster than an array
access ? Because in that case, it seems like bar should be optimized to an
if-else chain (perhaps along with bar).

Reply via email to