[llvm] [InstCombine] Fold values to 0 on eq-dominated paths (PR #174083)

via llvm-commits llvm-commits at lists.llvm.org
Wed Dec 31 03:21:16 PST 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-transforms

Author: None (arrowten)

<details>
<summary>Changes</summary>

InstCombine can miss simplifications when an instruction is only used in a block that is reachable only if `Op0 == Op1`. This patch folds such values to 0.

Fixes: #<!-- -->143658

---
Full diff: https://github.com/llvm/llvm-project/pull/174083.diff


2 Files Affected:

- (modified) llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp (+25) 
- (added) llvm/test/Transforms/InstCombine/fold-on-eq-branch.ll (+19) 


``````````diff
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
index 9bee523c7b7e5..b539c48489bf7 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
@@ -2292,6 +2292,31 @@ Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
 
   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
 
+  for (User *U : I.users()) {
+    auto *UseI = dyn_cast<Instruction>(U);
+
+    if (!UseI) continue;
+
+    BasicBlock *BB = UseI->getParent();
+    BasicBlock *Pred = BB->getSinglePredecessor();
+
+    if (!Pred) continue;
+
+    auto *Br = dyn_cast<BranchInst>(Pred->getTerminator());
+
+    if (!Br || !Br->isConditional()) continue;
+
+    auto *Cmp = dyn_cast<ICmpInst>(Br->getCondition());
+
+    if (!Cmp || Cmp->getPredicate() != ICmpInst::ICMP_EQ) continue;
+    if (!((Cmp->getOperand(0) == Op0 && Cmp->getOperand(1) == Op1) ||
+        (Cmp->getOperand(0) == Op1 && Cmp->getOperand(1) == Op0)))
+      continue;
+    if (Br->getSuccessor(0) != BB) continue;
+
+    UseI->replaceUsesOfWith(&I, ConstantInt::get(I.getType(), 0));
+  }
+
   // If this is a 'B = x-(-A)', change to B = x+A.
   // We deal with this without involving Negator to preserve NSW flag.
   if (Value *V = dyn_castNegVal(Op1)) {
diff --git a/llvm/test/Transforms/InstCombine/fold-on-eq-branch.ll b/llvm/test/Transforms/InstCombine/fold-on-eq-branch.ll
new file mode 100644
index 0000000000000..12ddf02703434
--- /dev/null
+++ b/llvm/test/Transforms/InstCombine/fold-on-eq-branch.ll
@@ -0,0 +1,19 @@
+; RUN: opt -passes='default<O1>' -S < %s | FileCheck %s
+; RUN: opt -passes='default<O2>' -S < %s | FileCheck %s
+; RUN: opt -passes='default<O3>' -S < %s | FileCheck %s
+
+declare void @use(i64)
+
+define i64 @ftp_state_list(i64 %0, i64 %1) {
+  %3 = sub i64 %0, %1
+  %4 = icmp eq i64 %0, %1
+  br i1 %4, label %5, label %common.ret
+
+5:
+; CHECK: tail call void @use(i64 0)
+  tail call void @use(i64 %3)
+  br label %common.ret
+
+common.ret:
+  ret i64 %3
+}

``````````

</details>


https://github.com/llvm/llvm-project/pull/174083


More information about the llvm-commits mailing list