Skip to content

Commit c00d050

Browse files
committed
[InstCombine] Canonicalize (a + 1 == 0) ? -1 : a + 1 -> uadd.sat(a, 1)
This is because this actually is just: // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y) // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y) However, ult 1 is canonicalized to eq 0. Alive2: https://alive2.llvm.org/ce/z/Y4eHav
1 parent 479cc17 commit c00d050

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,12 +1013,19 @@ static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
10131013

10141014
// uge -1 is canonicalized to eq -1 and requires special handling
10151015
// (a == -1) ? -1 : a + 1 -> uadd.sat(a, 1)
1016+
// ult 1 is canonicalized to eq 0
1017+
// (a + 1 == 0) ? -1 : a + 1 -> uadd.sat(a, 1)
10161018
if (Pred == ICmpInst::ICMP_EQ) {
10171019
if (match(FVal, m_Add(m_Specific(Cmp0), m_One())) &&
1018-
match(Cmp1, m_AllOnes())) {
1020+
match(Cmp1, m_AllOnes()))
10191021
return Builder.CreateBinaryIntrinsic(
10201022
Intrinsic::uadd_sat, Cmp0, ConstantInt::get(Cmp0->getType(), 1));
1021-
}
1023+
1024+
if (match(Cmp1, m_Zero()) && match(Cmp0, m_Add(m_Value(X), m_One())) &&
1025+
match(FVal, m_Add(m_Specific(X), m_One())))
1026+
return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X,
1027+
ConstantInt::get(X->getType(), 1));
1028+
10221029
return nullptr;
10231030
}
10241031

llvm/test/Transforms/InstCombine/saturating-add-sub.ll

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2352,9 +2352,7 @@ define i8 @fold_add_umax_to_usub_multiuse(i8 %a) {
23522352

23532353
define i32 @add_check_zero(i32 %num) {
23542354
; CHECK-LABEL: @add_check_zero(
2355-
; CHECK-NEXT: [[ADD:%.*]] = add i32 [[NUM:%.*]], 1
2356-
; CHECK-NEXT: [[CMP:%.*]] = icmp eq i32 [[ADD]], 0
2357-
; CHECK-NEXT: [[COND:%.*]] = select i1 [[CMP]], i32 -1, i32 [[ADD]]
2355+
; CHECK-NEXT: [[COND:%.*]] = call i32 @llvm.uadd.sat.i32(i32 [[NUM:%.*]], i32 1)
23582356
; CHECK-NEXT: ret i32 [[COND]]
23592357
;
23602358
%add = add i32 %num, 1

0 commit comments

Comments
 (0)