[llvm] [SimplifyCFG] Hoist out implied conditions from successor (PR #158773)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 17 14:06:19 PDT 2025


================
@@ -1853,6 +1853,113 @@ static void hoistConditionalLoadsStores(
   }
 }
 
+static std::optional<bool>
+visitConditions(Value *V, const Value *baseCond, const BasicBlock *contextBB,
+                SmallVectorImpl<Instruction *> &impliedConditions,
+                const DataLayout &DL) {
+  if (!isa<Instruction>(V))
+    return std::nullopt;
+
+  Instruction *I = cast<Instruction>(V);
+  // we only care about conditions in the same basic block
+  if (contextBB != I->getParent())
+    return std::nullopt;
+
+  std::optional<bool> Imp = isImpliedCondition(V, baseCond, DL);
+  // TODO: Handle negated condition case.
+  if (Imp != true)
+    return std::nullopt;
+
+  std::optional<bool> LHS = visitConditions(I->getOperand(0), baseCond,
+                                            contextBB, impliedConditions, DL);
+  std::optional<bool> RHS = visitConditions(I->getOperand(1), baseCond,
+                                            contextBB, impliedConditions, DL);
+
+  if (!LHS.has_value() && !RHS.has_value()) {
+    impliedConditions.push_back(I);
+  }
+
+  return Imp;
+}
+
+static bool hoistImplyingConditions(BranchInst *BI, IRBuilder<> &Builder,
+                                    const DataLayout &DL) {
+  // Only look for CFG like
+  // A -> B, C
+  // B -> D, C
+  // or
+  // A -> B, C
+  // B -> C, D
+  // TODO: Handle the false branch case as well.
+  BasicBlock *parentTrueBB = BI->getSuccessor(0);
+  BasicBlock *parentFalseBB = BI->getSuccessor(1);
+
+  if (!isa<BranchInst>(parentTrueBB->getTerminator()))
+    return false;
+
+  BranchInst *childBI = cast<BranchInst>(parentTrueBB->getTerminator());
----------------
nikic wrote:

Use dyn_cast and check the result for null instead of separate isa.

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


More information about the llvm-commits mailing list