Skip to content

Commit

Permalink
[InstCombine] avoid breaking up min/max (cmp+sel) idioms
Browse files Browse the repository at this point in the history
This is a quick fix for a motivating case that looks like this:
https://godbolt.org/z/GeMqzMc38

As noted, we might be able to restore the min/max patterns
with select folds, or we just wait for this to become easier
with canonicalization to min/max intrinsics.
  • Loading branch information
rotateright committed Aug 11, 2021
1 parent 5bf4ab0 commit a0a9c9e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
12 changes: 9 additions & 3 deletions llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
Expand Up @@ -5755,9 +5755,6 @@ Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
if (Instruction *Res = foldICmpWithDominatingICmp(I))
return Res;

if (Instruction *Res = foldICmpBinOp(I, Q))
return Res;

if (Instruction *Res = foldICmpUsingKnownBits(I))
return Res;

Expand Down Expand Up @@ -5803,6 +5800,15 @@ Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
}
}

// The folds in here may rely on wrapping flags and special constants, so
// they can break up min/max idioms in some cases but not seemingly similar
// patterns.
// FIXME: It may be possible to enhance select folding to make this
// unnecessary. It may also be moot if we canonicalize to min/max
// intrinsics.
if (Instruction *Res = foldICmpBinOp(I, Q))
return Res;

if (Instruction *Res = foldICmpInstWithConstant(I))
return Res;

Expand Down
13 changes: 6 additions & 7 deletions llvm/test/Transforms/InstCombine/icmp-add.ll
Expand Up @@ -972,17 +972,16 @@ define i1 @slt_offset_nsw(i8 %a, i8 %c) {
ret i1 %ov
}

; FIXME:
; In the following 4 tests, we could push the inc/dec
; through the min/max, but we should not break up the
; min/max idiom by using different icmp and select
; operands.

define i32 @increment_max(i32 %x) {
; CHECK-LABEL: @increment_max(
; CHECK-NEXT: [[A:%.*]] = add nsw i32 [[X:%.*]], 1
; CHECK-NEXT: [[C_INV:%.*]] = icmp slt i32 [[X]], 0
; CHECK-NEXT: [[S:%.*]] = select i1 [[C_INV]], i32 0, i32 [[A]]
; CHECK-NEXT: [[TMP1:%.*]] = icmp sgt i32 [[X:%.*]], -1
; CHECK-NEXT: [[TMP2:%.*]] = select i1 [[TMP1]], i32 [[X]], i32 -1
; CHECK-NEXT: [[S:%.*]] = add nsw i32 [[TMP2]], 1
; CHECK-NEXT: ret i32 [[S]]
;
%a = add nsw i32 %x, 1
Expand Down Expand Up @@ -1019,9 +1018,9 @@ define i32 @increment_min(i32 %x) {

define i32 @decrement_min(i32 %x) {
; CHECK-LABEL: @decrement_min(
; CHECK-NEXT: [[A:%.*]] = add nsw i32 [[X:%.*]], -1
; CHECK-NEXT: [[C_INV:%.*]] = icmp sgt i32 [[X]], 0
; CHECK-NEXT: [[S:%.*]] = select i1 [[C_INV]], i32 0, i32 [[A]]
; CHECK-NEXT: [[TMP1:%.*]] = icmp slt i32 [[X:%.*]], 1
; CHECK-NEXT: [[TMP2:%.*]] = select i1 [[TMP1]], i32 [[X]], i32 1
; CHECK-NEXT: [[S:%.*]] = add nsw i32 [[TMP2]], -1
; CHECK-NEXT: ret i32 [[S]]
;
%a = add nsw i32 %x, -1
Expand Down

0 comments on commit a0a9c9e

Please sign in to comment.