[llvm] 116670d - [InstCombine] add overflow checking on Add ~X + C --> (C-1) - X
via llvm-commits
llvm-commits at lists.llvm.org
Mon Jun 5 20:43:27 PDT 2023
Author: khei4
Date: 2023-06-06T12:24:45+09:00
New Revision: 116670d192c619e2233e092e210c920d004dbe33
URL: https://github.com/llvm/llvm-project/commit/116670d192c619e2233e092e210c920d004dbe33
DIFF: https://github.com/llvm/llvm-project/commit/116670d192c619e2233e092e210c920d004dbe33.diff
LOG: [InstCombine] add overflow checking on Add ~X + C --> (C-1) - X
Differential Revision: https://reviews.llvm.org/D152088
Added:
Modified:
llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
llvm/test/Transforms/InstCombine/add.ll
Removed:
################################################################################
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
index 29409e63ab8e0..d50b2d62dea88 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
@@ -880,8 +880,15 @@ Instruction *InstCombinerImpl::foldAddWithConstant(BinaryOperator &Add) {
return SelectInst::Create(X, InstCombiner::SubOne(Op1C), Op1);
// ~X + C --> (C-1) - X
- if (match(Op0, m_Not(m_Value(X))))
- return BinaryOperator::CreateSub(InstCombiner::SubOne(Op1C), X);
+ if (match(Op0, m_Not(m_Value(X)))) {
+ // ~X + C has NSW and (C-1) won't oveflow => (C-1)-X can have NSW
+ auto *COne = ConstantInt::get(Op1C->getType(), 1);
+ bool WillNotSOV = willNotOverflowSignedSub(Op1C, COne, Add);
+ BinaryOperator *Res =
+ BinaryOperator::CreateSub(ConstantExpr::getSub(Op1C, COne), X);
+ Res->setHasNoSignedWrap(Add.hasNoSignedWrap() && WillNotSOV);
+ return Res;
+ }
// (iN X s>> (N - 1)) + 1 --> zext (X > -1)
const APInt *C;
diff --git a/llvm/test/Transforms/InstCombine/add.ll b/llvm/test/Transforms/InstCombine/add.ll
index 7fac0e95b3b9f..f8b3c84ea713b 100644
--- a/llvm/test/Transforms/InstCombine/add.ll
+++ b/llvm/test/Transforms/InstCombine/add.ll
@@ -360,7 +360,7 @@ define i8 @test18(i8 %A) {
; ~X + -127 and (-128) - X with nsw are equally poisonous
define i8 @test18_nsw(i8 %A) {
; CHECK-LABEL: @test18_nsw(
-; CHECK-NEXT: [[C:%.*]] = sub i8 -128, [[A:%.*]]
+; CHECK-NEXT: [[C:%.*]] = sub nsw i8 -128, [[A:%.*]]
; CHECK-NEXT: ret i8 [[C]]
;
%B = xor i8 %A, -1
@@ -402,7 +402,7 @@ define <2 x i64> @test18vec(<2 x i64> %A) {
define <2 x i8> @test18vec_nsw(<2 x i8> %A) {
; CHECK-LABEL: @test18vec_nsw(
-; CHECK-NEXT: [[C:%.*]] = sub <2 x i8> <i8 -124, i8 -125>, [[A:%.*]]
+; CHECK-NEXT: [[C:%.*]] = sub nsw <2 x i8> <i8 -124, i8 -125>, [[A:%.*]]
; CHECK-NEXT: ret <2 x i8> [[C]]
;
%B = xor <2 x i8> %A, <i8 -1, i8 -1>
More information about the llvm-commits
mailing list