[llvm] [polly] [SimpleLoopUnswitch] Reland "Generalize the notion of trivial unswitching" (PR #204934)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 23 07:59:27 PDT 2026


================
@@ -591,6 +592,46 @@ static bool unswitchTrivialBranch(Loop &L, CondBrInst &BI, DominatorTree &DT,
     }
   }
 
+  std::optional<int> LatchIdx = std::nullopt;
+  auto *LoopLatch = L.getLoopLatch();
+  auto *ULExit = L.getUniqueLatchExitBlock();
+  if (SE && FullUnswitch && ULExit) {
+    if (BI.getSuccessor(0) == LoopLatch && L.contains(BI.getSuccessor(1)))
+      LatchIdx = 0;
+    else if (BI.getSuccessor(1) == LoopLatch && L.contains(BI.getSuccessor(0)))
+      LatchIdx = 1;
+  }
+
+  bool ModifiedBranch = false;
+  if (LatchIdx && areLoopExitPHIsLoopInvariant(L, *LoopLatch, *ULExit) &&
+      !llvm::any_of(*LoopLatch,
+                    [](Instruction &I) { return I.mayHaveSideEffects(); })) {
+
+    // We need to prove the loop is finite, otherwise this change will convert
+    // it to a finite loop. This conservative check is good enough as we are
+    // mostly interested in perfect countable loop nests that perform
+    // calculations on arrays.
+    const SCEV *MaxBECount = SE->getConstantMaxBackedgeTakenCount(&L);
+    if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
+      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(), ULExit});
+      LoopLatch->removePredecessor(BI.getParent());
+      BI.setSuccessor(*LatchIdx, ULExit);
+      for (PHINode &PN : ULExit->phis()) {
+        Value *V = PN.getIncomingValueForBlock(LoopLatch);
+        PN.addIncoming(V, BI.getParent());
+      }
+      if (MSSAU)
+        MSSAU->applyUpdates(Updates, DT, true);
----------------
nikic wrote:

```suggestion
        MSSAU->applyUpdates(Updates, DT, /*UpdateDTFirst=*/true);
```

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


More information about the llvm-commits mailing list