diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp index 22fd3edc39acb..d390d3a581fca 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp @@ -1487,7 +1487,11 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) { return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B)); // -A + B --> B - A - return BinaryOperator::CreateSub(RHS, A); + auto *Sub = BinaryOperator::CreateSub(RHS, A); + auto *OB0 = dyn_cast(LHS); + Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OB0->hasNoSignedWrap()); + + return Sub; } // A + -B --> A - B diff --git a/llvm/test/Transforms/InstCombine/add.ll b/llvm/test/Transforms/InstCombine/add.ll index 7234fb39e566e..1079f4fab1cd8 100644 --- a/llvm/test/Transforms/InstCombine/add.ll +++ b/llvm/test/Transforms/InstCombine/add.ll @@ -120,6 +120,36 @@ define i32 @test5(i32 %A, i32 %B) { ret i32 %D } +define i32 @test5_both_nsw(i32 %A, i32 %B) { +; CHECK-LABEL: @test5_both_nsw( +; CHECK-NEXT: [[D:%.*]] = sub nsw i32 [[B:%.*]], [[A:%.*]] +; CHECK-NEXT: ret i32 [[D]] +; + %C = sub nsw i32 0, %A + %D = add nsw i32 %C, %B + ret i32 %D +} + +define i32 @test5_neg_nsw(i32 %A, i32 %B) { +; CHECK-LABEL: @test5_neg_nsw( +; CHECK-NEXT: [[D:%.*]] = sub i32 [[B:%.*]], [[A:%.*]] +; CHECK-NEXT: ret i32 [[D]] +; + %C = sub nsw i32 0, %A + %D = add i32 %C, %B + ret i32 %D +} + +define i32 @test5_add_nsw(i32 %A, i32 %B) { +; CHECK-LABEL: @test5_add_nsw( +; CHECK-NEXT: [[D:%.*]] = sub i32 [[B:%.*]], [[A:%.*]] +; CHECK-NEXT: ret i32 [[D]] +; + %C = sub i32 0, %A + %D = add nsw i32 %C, %B + ret i32 %D +} + define <2 x i8> @neg_op0_vec_undef_elt(<2 x i8> %a, <2 x i8> %b) { ; CHECK-LABEL: @neg_op0_vec_undef_elt( ; CHECK-NEXT: [[R:%.*]] = sub <2 x i8> [[B:%.*]], [[A:%.*]] diff --git a/llvm/test/Transforms/InstCombine/pr14365.ll b/llvm/test/Transforms/InstCombine/pr14365.ll index 5e8dca13fa1b4..3a09b55aba309 100644 --- a/llvm/test/Transforms/InstCombine/pr14365.ll +++ b/llvm/test/Transforms/InstCombine/pr14365.ll @@ -31,7 +31,7 @@ define i32 @test1(i32 %a0) { ; CHECK-LABEL: @test1( ; CHECK-NEXT: [[TMP1:%.*]] = lshr i32 [[A0:%.*]], 1 ; CHECK-NEXT: [[TMP2:%.*]] = and i32 [[TMP1]], 1431655765 -; CHECK-NEXT: [[TMP3:%.*]] = sub i32 [[A0]], [[TMP2]] +; CHECK-NEXT: [[TMP3:%.*]] = sub nsw i32 [[A0]], [[TMP2]] ; CHECK-NEXT: ret i32 [[TMP3]] ; %1 = ashr i32 %a0, 1 @@ -46,7 +46,7 @@ define <4 x i32> @test1_vec(<4 x i32> %a0) { ; CHECK-LABEL: @test1_vec( ; CHECK-NEXT: [[TMP1:%.*]] = lshr <4 x i32> [[A0:%.*]], ; CHECK-NEXT: [[TMP2:%.*]] = and <4 x i32> [[TMP1]], -; CHECK-NEXT: [[TMP3:%.*]] = sub <4 x i32> [[A0]], [[TMP2]] +; CHECK-NEXT: [[TMP3:%.*]] = sub nsw <4 x i32> [[A0]], [[TMP2]] ; CHECK-NEXT: ret <4 x i32> [[TMP3]] ; %1 = ashr <4 x i32> %a0,