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

Antonio Frighetto via llvm-commits llvm-commits at lists.llvm.org
Mon Mar 2 01:26:47 PST 2026


================
@@ -2141,6 +2147,118 @@ 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");
+
+  // A small struct to record `*Ptr == Val` equality facts.
+  struct EqualityCond {
+    Value *Ptr;
+    Value *Val;
+    Instruction *LI;
+    EqualityCond(Value *Ptr, Value *Val, Instruction *LI)
+        : Ptr(Ptr), Val(Val), LI(LI) {}
+  };
+
+  // We maintain a stack of the active dominating conditions for a given node.
+  SmallVector<EqualityCond, 8> ActiveConditions;
+  auto GetDominatingCondition = [&](BasicBlock *BB)
+      -> std::optional<std::pair<EqualityCond, BasicBlock *>> {
+    auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
+    if (!BI || !BI->isConditional())
+      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;
+
+    unsigned ImpliedSuccIdx = (Pred == ICmpInst::ICMP_EQ) ? 0 : 1;
+    BasicBlock *ImpliedSucc = BI->getSuccessor(ImpliedSuccIdx);
+    return {{EqualityCond(StorePtr, StoreVal, ICmpL), ImpliedSucc}};
+  };
+
+  using NodePredicate = std::function<void(DomTreeNode *, unsigned)>;
+  NodePredicate VisitNode = [&](DomTreeNode *Node, unsigned Depth) {
+    if (Depth > MaxDepthRecursion)
+      return;
+
+    BasicBlock *BB = Node->getBlock();
+    // Check for redundant stores against active known conditions.
+    if (auto *Accesses = MSSA.getBlockDefs(BB)) {
+      for (auto &Access : make_early_inc_range(*Accesses)) {
+        auto *Def = dyn_cast<MemoryDef>(&Access);
+        if (!Def)
+          continue;
+
+        auto *SI = dyn_cast<StoreInst>(Def->getMemoryInst());
+        if (!SI || !SI->isUnordered())
----------------
antoniofrighetto wrote:

Added a few ones where the node is not a immediate dominator (we have already a few cases w/ dominating condition in the idom in `noop-stores.ll`).

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


More information about the llvm-commits mailing list