Issue 240716
Summary [InstCombine] Missed common-addend cancellation after X + X is folded to a shift
Labels new issue
Assignees
Reporter 134ARG
    In `llvm-opt-benchmark` (`ffmpeg/vorbisenc.bc`), FFmpeg's `residue_encode` retains redundant arithmetic in its equality checks under `-O3`. Before being inlined into `vorbis_encode_frame`, the relevant IR pattern looks like this (names shortened and unrelated instructions omitted):

```llvm
%twice = shl nsw i32 %n, 1
; ...
%sum = add nsw i32 %pos, %n
%equal = icmp eq i32 %sum, %twice
br i1 %equal, label %wrap, label %continue
```

Here, `%n` is a `noundef` parameter. Since `shl %n, 1` is equivalent to `%n + %n`, the common `%n` addend in `(%pos + %n) == (%n + %n)` can be cancelled out, simplifying the check to `%pos == %n`. Because this is an equality comparison, the cancellation holds under wrapping arithmetic as well and does not require any no-wrap flags. A similar missed fold shows up in a signed relational comparison in FFmpeg's `populate_ipred` (`ffmpeg/rv60dec.bc`), where `n <s (shl nsw n, 1)` could be simplified to `n >s 0`.

This looks like a gap in `InstCombine`'s `foldICmpBinOp()`. `InstCombine` canonicalizes `X + X` to `shl X, 1` early, so when `foldICmpBinOp()` tries to cancel common addends, it no longer recognizes `shl X, 1` as `X + X`. Teaching it to treat `shl X, 1` as two equal addends (when `X` is guaranteed not to be `undef`) might let the existing cancellation logic directly work. 

The following standalone reproducer still retains the `smin`, arithmetic, and `select` under `-O3` on current opt: https://godbolt.org/z/sY46xjbvq:

```llvm
define i8 @test(i8 noundef %x, i8 noundef %y) {
  %m = call i8 @llvm.smin.i8(i8 %y, i8 %x)
 %twice = add i8 %x, %x
  %sum = add i8 %x, %y
  %different = icmp ne i8 %twice, %sum
  %r = select i1 %different, i8 %x, i8 %m
  ret i8 %r
}
```
This entire function can simply fold to `ret i8 %x` (alive2: https://alive2.llvm.org/ce/z/pwZ-Si), but it doesn't.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to