[llvm] [polly] [SimpleLoopUnswitch] Generalize the notion of trivial unswitching (PR #193989)

Ehsan Amiri via llvm-commits llvm-commits at lists.llvm.org
Fri May 22 11:52:07 PDT 2026


================
@@ -591,6 +592,42 @@ static bool unswitchTrivialBranch(Loop &L, CondBrInst &BI, DominatorTree &DT,
     }
   }
 
+  std::optional<int> LatchIdx = std::nullopt;
+  if (FullUnswitch && L.getUniqueLatchExitBlock() != nullptr) {
+    if (BI.getSuccessor(0) == L.getLoopLatch() &&
+        L.contains(BI.getSuccessor(1))) {
+      LatchIdx = 0;
+    }
+    if (BI.getSuccessor(1) == L.getLoopLatch() &&
+        L.contains(BI.getSuccessor(0))) {
+      LatchIdx = 1;
+    }
+  }
+
+  bool ModifiedBranch = false;
+  if (LatchIdx &&
+      areLoopExitPHIsLoopInvariant(L, *L.getLoopLatch(),
+                                   *L.getUniqueLatchExitBlock()) &&
+      !llvm::any_of(*L.getLoopLatch(),
+                    [](Instruction &I) { return I.mayHaveSideEffects(); })) {
+
+    SmallVector<cfg::Update<BasicBlock *>, 2> Updates;
+    Updates.push_back(
+        {cfg::UpdateKind::Delete, BI.getParent(), BI.getSuccessor(*LatchIdx)});
+    Updates.push_back(
+        {cfg::UpdateKind::Insert, BI.getParent(), L.getUniqueLatchExitBlock()});
+    L.getLoopLatch()->removePredecessor(BI.getParent());
+    BI.setSuccessor(*LatchIdx, L.getUniqueLatchExitBlock());
+    for (PHINode &PN : L.getUniqueLatchExitBlock()->phis()) {
+      Value *V = PN.getIncomingValueForBlock(L.getLoopLatch());
+      PN.addIncoming(V, BI.getParent());
+    }
+    DT.applyUpdates(Updates);
----------------
amehsan wrote:

changed the code to update DT only when MSSAU doesn't exist.
@nikic this should be ready for review, both your comments are addressed.

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


More information about the llvm-commits mailing list