[llvm] [DSE] Introduce `eliminateRedundantStoresViaDominatingConditions` (PR #181709)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Thu Apr 2 09:09:00 PDT 2026


================
@@ -2133,6 +2140,116 @@ bool DSEState::eliminateDeadWritesAtEndOfFunction() {
   return MadeChange;
 }
 
+bool DSEState::eliminateRedundantStoresViaDominatingConditions() {
+  bool MadeChange = false;
+  LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs whose value being "
+                       "written is implied by a dominating condition\n");
+
+  using ConditionInfo = std::pair<Value *, Value *>;
+  using ScopedHTType = ScopedHashTable<ConditionInfo, Instruction *>;
+
+  // We maintain a scoped hash table of the active dominating conditions for a
+  // given node.
+  ScopedHTType ActiveConditions;
+  auto GetDominatingCondition = [&](BasicBlock *BB)
+      -> std::optional<std::tuple<ConditionInfo, Instruction *, BasicBlock *>> {
+    auto *BI = dyn_cast<CondBrInst>(BB->getTerminator());
+    if (!BI)
+      return std::nullopt;
+
+    // In case both blocks are the same, it is not possible to determine
+    // if optimization is possible. (We would not want to optimize a store
+    // in the FalseBB if condition is true and vice versa.)
+    if (BI->getSuccessor(0) == BI->getSuccessor(1))
+      return std::nullopt;
+
+    Instruction *ICmpL;
+    CmpPredicate Pred;
+    Value *StorePtr, *StoreVal;
+    if (!match(BI->getCondition(),
+               m_c_ICmp(Pred, m_Instruction(ICmpL, m_Load(m_Value(StorePtr))),
+                        m_Value(StoreVal))) ||
+        !ICmpInst::isEquality(Pred))
+      return std::nullopt;
+
+    // Ensure the replacement is allowed when comparing pointers, as
+    // the equality compares addresses only, not pointers' provenance.
+    if (StoreVal->getType()->isPointerTy() &&
+        !canReplacePointersIfEqual(StoreVal, ICmpL, DL))
+      return std::nullopt;
+
+    unsigned ImpliedSuccIdx = (Pred == ICmpInst::ICMP_EQ) ? 0 : 1;
----------------
dtcxzyw wrote:

```suggestion
    unsigned ImpliedSuccIdx = Pred == ICmpInst::ICMP_EQ ? 0 : 1;
```

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


More information about the llvm-commits mailing list