[llvm] [InstCombine] Infer nuw flags for `C-(X+C2)` -> `(C-C2)-X` (PR #72373)
via llvm-commits
llvm-commits at lists.llvm.org
Wed Nov 15 03:44:51 PST 2023
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-llvm-transforms
Author: Yingwei Zheng (dtcxzyw)
<details>
<summary>Changes</summary>
This patch improves https://reviews.llvm.org/D152068 by inferring NUW flags for sub insts.
It is worth noting that we don't need to check overflow for `C-C2`.
Alive2: https://alive2.llvm.org/ce/z/uutGpS
This missed optimization is discovered with the help of https://github.com/AliveToolkit/alive2/pull/962.
---
Full diff: https://github.com/llvm/llvm-project/pull/72373.diff
2 Files Affected:
- (modified) llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp (+4-2)
- (modified) llvm/test/Transforms/InstCombine/addsub-constant-folding.ll (+1-1)
``````````diff
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
index 2bd738c95ecaa7f..318992b55e4f9f8 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
@@ -2111,14 +2111,16 @@ Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
// C-(X+C2) --> (C-C2)-X
if (match(Op1, m_Add(m_Value(X), m_ImmConstant(C2)))) {
- // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW
- // => (C-C2)-X can have NSW
+ // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW/NUW
+ // => (C-C2)-X can have NSW/NUW
bool WillNotSOV = willNotOverflowSignedSub(C, C2, I);
BinaryOperator *Res =
BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
Res->setHasNoSignedWrap(I.hasNoSignedWrap() && OBO1->hasNoSignedWrap() &&
WillNotSOV);
+ Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() &&
+ OBO1->hasNoUnsignedWrap());
return Res;
}
}
diff --git a/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll b/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll
index 83a45e697e59e16..3a297880b794963 100644
--- a/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll
+++ b/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll
@@ -175,7 +175,7 @@ define i8 @add_nsw_const_const_sub_nsw_ov(i8 %arg) {
define i8 @add_nuw_const_const_sub_nuw(i8 %arg) {
; CHECK-LABEL: @add_nuw_const_const_sub_nuw(
-; CHECK-NEXT: [[T1:%.*]] = sub i8 -128, [[ARG:%.*]]
+; CHECK-NEXT: [[T1:%.*]] = sub nuw i8 -128, [[ARG:%.*]]
; CHECK-NEXT: ret i8 [[T1]]
;
%t0 = add nuw i8 %arg, 1
``````````
</details>
https://github.com/llvm/llvm-project/pull/72373
More information about the llvm-commits
mailing list