Issue 237771
Summary [InstCombine] Missed fold: two range checks differing by one bit, when each arm returns a value
Labels new issue
Assignees
Reporter benoithms
    LLVM misses a simplification when a value is tested against two ranges that differ by a single bit, and each case returns a value computed from the input. It keeps both tests and a branch. Setting that bit first (`c | 32` in the example below) makes one test and one computation enough. This pattern appears when parsing a hex digit.

#54680 is related, but it is about boolean results (`isalnum`, `isxdigit`). Here each range returns a value.

```c
#include <stdint.h>
int32_t f(uint8_t c) {
    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
    return -1;
}
```

```llvm
define i32 @src(i8 noundef zeroext %0) {
  %2 = zext i8 %0 to i32
  %3 = add i8 %0, -97
  %4 = icmp ult i8 %3, 6
  br i1 %4, label %5, label %7

5:
  %6 = add nsw i32 %2, -87
  br label %12

7:
  %8 = add i8 %0, -65
  %9 = icmp ult i8 %8, 6
  %10 = add nsw i32 %2, -55
  %11 = select i1 %9, i32 %10, i32 -1
  br label %12

12:
  %13 = phi i32 [ %6, %5 ], [ %11, %7 ]
  ret i32 %13
}

define i32 @tgt(i8 noundef zeroext %0) {
  %t1 = zext i8 %0 to i32
  %t2 = or i32 %t1, 32
  %t3 = add i32 %t2, -97
  %t4 = icmp ult i32 %t3, 6
  %t5 = add i32 %t2, -87
  %t6 = select i1 %t4, i32 %t5, i32 -1
 ret i32 %t6
}
```

Alive2: https://alive2.llvm.org/ce/z/5Pk2z5
`opt -O3` trunk leaves `@src` unchanged. Full three-range function on clang trunk: https://godbolt.org/z/jqbn3rWTY

Impact on this reduced case, estimated by llvm-mca (x86-64, `-mcpu=skylake`, LLVM b974545, 100 iterations): 13 to 8 instructions, 385 to 236 cycles, no branch left. llvm-mca does not model branch mispredictions.

On the full function with the `0`-`9` check (a rewrite of the same idea, not an implementation of this fold), measured speedup over clang -O3, lowest to highest of 5 launches, loop overhead included:

| | Call | Inlined |
|---|---:|---:|
| i7-9700K | 1.79x-1.80x | 1.09x-1.09x |
| i7-12700H | 2.00x-2.00x | 1.08x-1.11x |

This came out of [qed-superopt](https://github.com/benoithms/qed-superopt), an AI-guided superoptimizer, which found a faster rewrite of the full function, proven with Alive2. The reduced case above was derived from it and proven separately. I reviewed all of it, checked the proof and, having worked on compiler projects, understand the fold.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to