@@ -3132,7 +3132,7 @@ Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
31323132
31333133 Value *Op0, *Op1;
31343134 Instruction *Ext0, *Ext1;
3135- const CmpInst::Predicate Pred = Cmp.getPredicate ();
3135+ const CmpPredicate Pred = Cmp.getCmpPredicate ();
31363136 if (match (Add,
31373137 m_Add (m_CombineAnd (m_Instruction (Ext0), m_ZExtOrSExt (m_Value (Op0))),
31383138 m_CombineAnd (m_Instruction (Ext1),
@@ -3167,14 +3167,11 @@ Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
31673167
31683168 // If the add does not wrap, we can always adjust the compare by subtracting
31693169 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3170- // are canonicalized to SGT/SLT/UGT/ULT.
3171- if ((Add->hasNoSignedWrap () &&
3172- (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
3173- (Add->hasNoUnsignedWrap () &&
3174- (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
3170+ // have been canonicalized to SGT/SLT/UGT/ULT.
3171+ if (Add->hasNoUnsignedWrap () &&
3172+ (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
31753173 bool Overflow;
3176- APInt NewC =
3177- Cmp.isSigned () ? C.ssub_ov (*C2, Overflow) : C.usub_ov (*C2, Overflow);
3174+ APInt NewC = C.usub_ov (*C2, Overflow);
31783175 // If there is overflow, the result must be true or false.
31793176 // TODO: Can we assert there is no overflow because InstSimplify always
31803177 // handles those cases?
@@ -3183,6 +3180,18 @@ Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
31833180 return new ICmpInst (Pred, X, ConstantInt::get (Ty, NewC));
31843181 }
31853182
3183+ CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate ();
3184+
3185+ if (Add->hasNoSignedWrap () &&
3186+ (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3187+ bool Overflow;
3188+ APInt NewC = C.ssub_ov (*C2, Overflow);
3189+ if (!Overflow)
3190+ // icmp samesign ugt/ult (add nsw X, C2), C
3191+ // -> icmp sgt/slt X, (C - C2)
3192+ return new ICmpInst (ChosenPred, X, ConstantInt::get (Ty, NewC));
3193+ }
3194+
31863195 if (ICmpInst::isUnsigned (Pred) && Add->hasNoSignedWrap () &&
31873196 C.isNonNegative () && (C - *C2).isNonNegative () &&
31883197 computeConstantRange (X, /* ForSigned=*/ true ).add (*C2).isAllNonNegative ())
0 commit comments