Index: llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp =================================================================== --- llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp +++ llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp @@ -1530,8 +1530,19 @@ if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X)))) return replaceOperand(*II, 0, X); + // abs(x-y) --> y-x where x <= y + Value *Y; + if (match(IIOperand, m_NSWSub(m_Value(X), m_Value(Y)))) { + if (std::optional Known = + isImpliedByDomCondition(ICmpInst::ICMP_SLE, X, Y, II, DL)) { + if (!*Known) + return replaceInstUsesWith(*II, IIOperand); + return BinaryOperator::CreateNeg(IIOperand); + } + } + if (std::optional Sign = getKnownSign(IIOperand, II, DL, &AC, &DT)) { - // abs(x) -> x if x >= 0 + // abs(x) -> x if x >= 0 (include abs(x-y) --> x-y where x >= y) if (!*Sign) return replaceInstUsesWith(*II, IIOperand); Index: llvm/test/Transforms/InstCombine/abs-intrinsic.ll =================================================================== --- llvm/test/Transforms/InstCombine/abs-intrinsic.ll +++ llvm/test/Transforms/InstCombine/abs-intrinsic.ll @@ -512,11 +512,10 @@ ; CHECK-NEXT: [[CMP_NOT:%.*]] = icmp sgt i32 [[X:%.*]], [[Y:%.*]] ; CHECK-NEXT: br i1 [[CMP_NOT]], label [[COND_END:%.*]], label [[COND_TRUE:%.*]] ; CHECK: cond.true: -; CHECK-NEXT: [[SUB:%.*]] = sub nsw i32 [[X]], [[Y]] -; CHECK-NEXT: [[TMP0:%.*]] = call i32 @llvm.abs.i32(i32 [[SUB]], i1 true) +; CHECK-NEXT: [[SUB_NEG:%.*]] = sub i32 [[Y]], [[X]] ; CHECK-NEXT: br label [[COND_END]] ; CHECK: cond.end: -; CHECK-NEXT: [[R:%.*]] = phi i32 [ [[TMP0]], [[COND_TRUE]] ], [ 0, [[ENTRY:%.*]] ] +; CHECK-NEXT: [[R:%.*]] = phi i32 [ [[SUB_NEG]], [[COND_TRUE]] ], [ 0, [[ENTRY:%.*]] ] ; CHECK-NEXT: ret i32 [[R]] ; entry: