xref: /llvm-project/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp (revision 32b38d248fd3c75abc5c86ab6677b6cb08a703cc)
1 ///===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
10 #include "llvm/ADT/DenseMap.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/Sequence.h"
13 #include "llvm/ADT/SetVector.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/BlockFrequencyInfo.h"
20 #include "llvm/Analysis/CFG.h"
21 #include "llvm/Analysis/CodeMetrics.h"
22 #include "llvm/Analysis/GuardUtils.h"
23 #include "llvm/Analysis/LoopAnalysisManager.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/LoopIterator.h"
26 #include "llvm/Analysis/LoopPass.h"
27 #include "llvm/Analysis/MemorySSA.h"
28 #include "llvm/Analysis/MemorySSAUpdater.h"
29 #include "llvm/Analysis/MustExecute.h"
30 #include "llvm/Analysis/ProfileSummaryInfo.h"
31 #include "llvm/Analysis/ScalarEvolution.h"
32 #include "llvm/Analysis/TargetTransformInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/BasicBlock.h"
35 #include "llvm/IR/Constant.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/InstrTypes.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/IntrinsicInst.h"
44 #include "llvm/IR/PatternMatch.h"
45 #include "llvm/IR/Use.h"
46 #include "llvm/IR/Value.h"
47 #include "llvm/InitializePasses.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GenericDomTree.h"
54 #include "llvm/Support/InstructionCost.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Scalar/LoopPassManager.h"
57 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
58 #include "llvm/Transforms/Utils/Cloning.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include "llvm/Transforms/Utils/LoopUtils.h"
61 #include "llvm/Transforms/Utils/ValueMapper.h"
62 #include <algorithm>
63 #include <cassert>
64 #include <iterator>
65 #include <numeric>
66 #include <optional>
67 #include <utility>
68 
69 #define DEBUG_TYPE "simple-loop-unswitch"
70 
71 using namespace llvm;
72 using namespace llvm::PatternMatch;
73 
74 STATISTIC(NumBranches, "Number of branches unswitched");
75 STATISTIC(NumSwitches, "Number of switches unswitched");
76 STATISTIC(NumGuards, "Number of guards turned into branches for unswitching");
77 STATISTIC(NumTrivial, "Number of unswitches that are trivial");
78 STATISTIC(
79     NumCostMultiplierSkipped,
80     "Number of unswitch candidates that had their cost multiplier skipped");
81 
82 static cl::opt<bool> EnableNonTrivialUnswitch(
83     "enable-nontrivial-unswitch", cl::init(false), cl::Hidden,
84     cl::desc("Forcibly enables non-trivial loop unswitching rather than "
85              "following the configuration passed into the pass."));
86 
87 static cl::opt<int>
88     UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden,
89                       cl::desc("The cost threshold for unswitching a loop."));
90 
91 static cl::opt<bool> EnableUnswitchCostMultiplier(
92     "enable-unswitch-cost-multiplier", cl::init(true), cl::Hidden,
93     cl::desc("Enable unswitch cost multiplier that prohibits exponential "
94              "explosion in nontrivial unswitch."));
95 static cl::opt<int> UnswitchSiblingsToplevelDiv(
96     "unswitch-siblings-toplevel-div", cl::init(2), cl::Hidden,
97     cl::desc("Toplevel siblings divisor for cost multiplier."));
98 static cl::opt<int> UnswitchNumInitialUnscaledCandidates(
99     "unswitch-num-initial-unscaled-candidates", cl::init(8), cl::Hidden,
100     cl::desc("Number of unswitch candidates that are ignored when calculating "
101              "cost multiplier."));
102 static cl::opt<bool> UnswitchGuards(
103     "simple-loop-unswitch-guards", cl::init(true), cl::Hidden,
104     cl::desc("If enabled, simple loop unswitching will also consider "
105              "llvm.experimental.guard intrinsics as unswitch candidates."));
106 static cl::opt<bool> DropNonTrivialImplicitNullChecks(
107     "simple-loop-unswitch-drop-non-trivial-implicit-null-checks",
108     cl::init(false), cl::Hidden,
109     cl::desc("If enabled, drop make.implicit metadata in unswitched implicit "
110              "null checks to save time analyzing if we can keep it."));
111 static cl::opt<unsigned>
112     MSSAThreshold("simple-loop-unswitch-memoryssa-threshold",
113                   cl::desc("Max number of memory uses to explore during "
114                            "partial unswitching analysis"),
115                   cl::init(100), cl::Hidden);
116 static cl::opt<bool> FreezeLoopUnswitchCond(
117     "freeze-loop-unswitch-cond", cl::init(true), cl::Hidden,
118     cl::desc("If enabled, the freeze instruction will be added to condition "
119              "of loop unswitch to prevent miscompilation."));
120 
121 namespace {
122 struct NonTrivialUnswitchCandidate {
123   Instruction *TI = nullptr;
124   TinyPtrVector<Value *> Invariants;
125   std::optional<InstructionCost> Cost;
126   NonTrivialUnswitchCandidate(
127       Instruction *TI, ArrayRef<Value *> Invariants,
128       std::optional<InstructionCost> Cost = std::nullopt)
129       : TI(TI), Invariants(Invariants), Cost(Cost){};
130 };
131 } // end anonymous namespace.
132 
133 // Helper to skip (select x, true, false), which matches both a logical AND and
134 // OR and can confuse code that tries to determine if \p Cond is either a
135 // logical AND or OR but not both.
136 static Value *skipTrivialSelect(Value *Cond) {
137   Value *CondNext;
138   while (match(Cond, m_Select(m_Value(CondNext), m_One(), m_Zero())))
139     Cond = CondNext;
140   return Cond;
141 }
142 
143 /// Collect all of the loop invariant input values transitively used by the
144 /// homogeneous instruction graph from a given root.
145 ///
146 /// This essentially walks from a root recursively through loop variant operands
147 /// which have perform the same logical operation (AND or OR) and finds all
148 /// inputs which are loop invariant. For some operations these can be
149 /// re-associated and unswitched out of the loop entirely.
150 static TinyPtrVector<Value *>
151 collectHomogenousInstGraphLoopInvariants(const Loop &L, Instruction &Root,
152                                          const LoopInfo &LI) {
153   assert(!L.isLoopInvariant(&Root) &&
154          "Only need to walk the graph if root itself is not invariant.");
155   TinyPtrVector<Value *> Invariants;
156 
157   bool IsRootAnd = match(&Root, m_LogicalAnd());
158   bool IsRootOr  = match(&Root, m_LogicalOr());
159 
160   // Build a worklist and recurse through operators collecting invariants.
161   SmallVector<Instruction *, 4> Worklist;
162   SmallPtrSet<Instruction *, 8> Visited;
163   Worklist.push_back(&Root);
164   Visited.insert(&Root);
165   do {
166     Instruction &I = *Worklist.pop_back_val();
167     for (Value *OpV : I.operand_values()) {
168       // Skip constants as unswitching isn't interesting for them.
169       if (isa<Constant>(OpV))
170         continue;
171 
172       // Add it to our result if loop invariant.
173       if (L.isLoopInvariant(OpV)) {
174         Invariants.push_back(OpV);
175         continue;
176       }
177 
178       // If not an instruction with the same opcode, nothing we can do.
179       Instruction *OpI = dyn_cast<Instruction>(skipTrivialSelect(OpV));
180 
181       if (OpI && ((IsRootAnd && match(OpI, m_LogicalAnd())) ||
182                   (IsRootOr  && match(OpI, m_LogicalOr())))) {
183         // Visit this operand.
184         if (Visited.insert(OpI).second)
185           Worklist.push_back(OpI);
186       }
187     }
188   } while (!Worklist.empty());
189 
190   return Invariants;
191 }
192 
193 static void replaceLoopInvariantUses(const Loop &L, Value *Invariant,
194                                      Constant &Replacement) {
195   assert(!isa<Constant>(Invariant) && "Why are we unswitching on a constant?");
196 
197   // Replace uses of LIC in the loop with the given constant.
198   // We use make_early_inc_range as set invalidates the iterator.
199   for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
200     Instruction *UserI = dyn_cast<Instruction>(U.getUser());
201 
202     // Replace this use within the loop body.
203     if (UserI && L.contains(UserI))
204       U.set(&Replacement);
205   }
206 }
207 
208 /// Check that all the LCSSA PHI nodes in the loop exit block have trivial
209 /// incoming values along this edge.
210 static bool areLoopExitPHIsLoopInvariant(const Loop &L,
211                                          const BasicBlock &ExitingBB,
212                                          const BasicBlock &ExitBB) {
213   for (const Instruction &I : ExitBB) {
214     auto *PN = dyn_cast<PHINode>(&I);
215     if (!PN)
216       // No more PHIs to check.
217       return true;
218 
219     // If the incoming value for this edge isn't loop invariant the unswitch
220     // won't be trivial.
221     if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB)))
222       return false;
223   }
224   llvm_unreachable("Basic blocks should never be empty!");
225 }
226 
227 /// Copy a set of loop invariant values \p ToDuplicate and insert them at the
228 /// end of \p BB and conditionally branch on the copied condition. We only
229 /// branch on a single value.
230 static void buildPartialUnswitchConditionalBranch(
231     BasicBlock &BB, ArrayRef<Value *> Invariants, bool Direction,
232     BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, bool InsertFreeze,
233     const Instruction *I, AssumptionCache *AC, const DominatorTree &DT) {
234   IRBuilder<> IRB(&BB);
235 
236   SmallVector<Value *> FrozenInvariants;
237   for (Value *Inv : Invariants) {
238     if (InsertFreeze && !isGuaranteedNotToBeUndefOrPoison(Inv, AC, I, &DT))
239       Inv = IRB.CreateFreeze(Inv, Inv->getName() + ".fr");
240     FrozenInvariants.push_back(Inv);
241   }
242 
243   Value *Cond = Direction ? IRB.CreateOr(FrozenInvariants)
244                           : IRB.CreateAnd(FrozenInvariants);
245   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
246                    Direction ? &NormalSucc : &UnswitchedSucc);
247 }
248 
249 /// Copy a set of loop invariant values, and conditionally branch on them.
250 static void buildPartialInvariantUnswitchConditionalBranch(
251     BasicBlock &BB, ArrayRef<Value *> ToDuplicate, bool Direction,
252     BasicBlock &UnswitchedSucc, BasicBlock &NormalSucc, Loop &L,
253     MemorySSAUpdater *MSSAU) {
254   ValueToValueMapTy VMap;
255   for (auto *Val : reverse(ToDuplicate)) {
256     Instruction *Inst = cast<Instruction>(Val);
257     Instruction *NewInst = Inst->clone();
258     NewInst->insertInto(&BB, BB.end());
259     RemapInstruction(NewInst, VMap,
260                      RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
261     VMap[Val] = NewInst;
262 
263     if (!MSSAU)
264       continue;
265 
266     MemorySSA *MSSA = MSSAU->getMemorySSA();
267     if (auto *MemUse =
268             dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(Inst))) {
269       auto *DefiningAccess = MemUse->getDefiningAccess();
270       // Get the first defining access before the loop.
271       while (L.contains(DefiningAccess->getBlock())) {
272         // If the defining access is a MemoryPhi, get the incoming
273         // value for the pre-header as defining access.
274         if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess))
275           DefiningAccess =
276               MemPhi->getIncomingValueForBlock(L.getLoopPreheader());
277         else
278           DefiningAccess = cast<MemoryDef>(DefiningAccess)->getDefiningAccess();
279       }
280       MSSAU->createMemoryAccessInBB(NewInst, DefiningAccess,
281                                     NewInst->getParent(),
282                                     MemorySSA::BeforeTerminator);
283     }
284   }
285 
286   IRBuilder<> IRB(&BB);
287   Value *Cond = VMap[ToDuplicate[0]];
288   IRB.CreateCondBr(Cond, Direction ? &UnswitchedSucc : &NormalSucc,
289                    Direction ? &NormalSucc : &UnswitchedSucc);
290 }
291 
292 /// Rewrite the PHI nodes in an unswitched loop exit basic block.
293 ///
294 /// Requires that the loop exit and unswitched basic block are the same, and
295 /// that the exiting block was a unique predecessor of that block. Rewrites the
296 /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial
297 /// PHI nodes from the old preheader that now contains the unswitched
298 /// terminator.
299 static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB,
300                                                   BasicBlock &OldExitingBB,
301                                                   BasicBlock &OldPH) {
302   for (PHINode &PN : UnswitchedBB.phis()) {
303     // When the loop exit is directly unswitched we just need to update the
304     // incoming basic block. We loop to handle weird cases with repeated
305     // incoming blocks, but expect to typically only have one operand here.
306     for (auto i : seq<int>(0, PN.getNumOperands())) {
307       assert(PN.getIncomingBlock(i) == &OldExitingBB &&
308              "Found incoming block different from unique predecessor!");
309       PN.setIncomingBlock(i, &OldPH);
310     }
311   }
312 }
313 
314 /// Rewrite the PHI nodes in the loop exit basic block and the split off
315 /// unswitched block.
316 ///
317 /// Because the exit block remains an exit from the loop, this rewrites the
318 /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI
319 /// nodes into the unswitched basic block to select between the value in the
320 /// old preheader and the loop exit.
321 static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB,
322                                                       BasicBlock &UnswitchedBB,
323                                                       BasicBlock &OldExitingBB,
324                                                       BasicBlock &OldPH,
325                                                       bool FullUnswitch) {
326   assert(&ExitBB != &UnswitchedBB &&
327          "Must have different loop exit and unswitched blocks!");
328   Instruction *InsertPt = &*UnswitchedBB.begin();
329   for (PHINode &PN : ExitBB.phis()) {
330     auto *NewPN = PHINode::Create(PN.getType(), /*NumReservedValues*/ 2,
331                                   PN.getName() + ".split", InsertPt);
332 
333     // Walk backwards over the old PHI node's inputs to minimize the cost of
334     // removing each one. We have to do this weird loop manually so that we
335     // create the same number of new incoming edges in the new PHI as we expect
336     // each case-based edge to be included in the unswitched switch in some
337     // cases.
338     // FIXME: This is really, really gross. It would be much cleaner if LLVM
339     // allowed us to create a single entry for a predecessor block without
340     // having separate entries for each "edge" even though these edges are
341     // required to produce identical results.
342     for (int i = PN.getNumIncomingValues() - 1; i >= 0; --i) {
343       if (PN.getIncomingBlock(i) != &OldExitingBB)
344         continue;
345 
346       Value *Incoming = PN.getIncomingValue(i);
347       if (FullUnswitch)
348         // No more edge from the old exiting block to the exit block.
349         PN.removeIncomingValue(i);
350 
351       NewPN->addIncoming(Incoming, &OldPH);
352     }
353 
354     // Now replace the old PHI with the new one and wire the old one in as an
355     // input to the new one.
356     PN.replaceAllUsesWith(NewPN);
357     NewPN->addIncoming(&PN, &ExitBB);
358   }
359 }
360 
361 /// Hoist the current loop up to the innermost loop containing a remaining exit.
362 ///
363 /// Because we've removed an exit from the loop, we may have changed the set of
364 /// loops reachable and need to move the current loop up the loop nest or even
365 /// to an entirely separate nest.
366 static void hoistLoopToNewParent(Loop &L, BasicBlock &Preheader,
367                                  DominatorTree &DT, LoopInfo &LI,
368                                  MemorySSAUpdater *MSSAU, ScalarEvolution *SE) {
369   // If the loop is already at the top level, we can't hoist it anywhere.
370   Loop *OldParentL = L.getParentLoop();
371   if (!OldParentL)
372     return;
373 
374   SmallVector<BasicBlock *, 4> Exits;
375   L.getExitBlocks(Exits);
376   Loop *NewParentL = nullptr;
377   for (auto *ExitBB : Exits)
378     if (Loop *ExitL = LI.getLoopFor(ExitBB))
379       if (!NewParentL || NewParentL->contains(ExitL))
380         NewParentL = ExitL;
381 
382   if (NewParentL == OldParentL)
383     return;
384 
385   // The new parent loop (if different) should always contain the old one.
386   if (NewParentL)
387     assert(NewParentL->contains(OldParentL) &&
388            "Can only hoist this loop up the nest!");
389 
390   // The preheader will need to move with the body of this loop. However,
391   // because it isn't in this loop we also need to update the primary loop map.
392   assert(OldParentL == LI.getLoopFor(&Preheader) &&
393          "Parent loop of this loop should contain this loop's preheader!");
394   LI.changeLoopFor(&Preheader, NewParentL);
395 
396   // Remove this loop from its old parent.
397   OldParentL->removeChildLoop(&L);
398 
399   // Add the loop either to the new parent or as a top-level loop.
400   if (NewParentL)
401     NewParentL->addChildLoop(&L);
402   else
403     LI.addTopLevelLoop(&L);
404 
405   // Remove this loops blocks from the old parent and every other loop up the
406   // nest until reaching the new parent. Also update all of these
407   // no-longer-containing loops to reflect the nesting change.
408   for (Loop *OldContainingL = OldParentL; OldContainingL != NewParentL;
409        OldContainingL = OldContainingL->getParentLoop()) {
410     llvm::erase_if(OldContainingL->getBlocksVector(),
411                    [&](const BasicBlock *BB) {
412                      return BB == &Preheader || L.contains(BB);
413                    });
414 
415     OldContainingL->getBlocksSet().erase(&Preheader);
416     for (BasicBlock *BB : L.blocks())
417       OldContainingL->getBlocksSet().erase(BB);
418 
419     // Because we just hoisted a loop out of this one, we have essentially
420     // created new exit paths from it. That means we need to form LCSSA PHI
421     // nodes for values used in the no-longer-nested loop.
422     formLCSSA(*OldContainingL, DT, &LI, SE);
423 
424     // We shouldn't need to form dedicated exits because the exit introduced
425     // here is the (just split by unswitching) preheader. However, after trivial
426     // unswitching it is possible to get new non-dedicated exits out of parent
427     // loop so let's conservatively form dedicated exit blocks and figure out
428     // if we can optimize later.
429     formDedicatedExitBlocks(OldContainingL, &DT, &LI, MSSAU,
430                             /*PreserveLCSSA*/ true);
431   }
432 }
433 
434 // Return the top-most loop containing ExitBB and having ExitBB as exiting block
435 // or the loop containing ExitBB, if there is no parent loop containing ExitBB
436 // as exiting block.
437 static const Loop *getTopMostExitingLoop(const BasicBlock *ExitBB,
438                                          const LoopInfo &LI) {
439   const Loop *TopMost = LI.getLoopFor(ExitBB);
440   const Loop *Current = TopMost;
441   while (Current) {
442     if (Current->isLoopExiting(ExitBB))
443       TopMost = Current;
444     Current = Current->getParentLoop();
445   }
446   return TopMost;
447 }
448 
449 /// Unswitch a trivial branch if the condition is loop invariant.
450 ///
451 /// This routine should only be called when loop code leading to the branch has
452 /// been validated as trivial (no side effects). This routine checks if the
453 /// condition is invariant and one of the successors is a loop exit. This
454 /// allows us to unswitch without duplicating the loop, making it trivial.
455 ///
456 /// If this routine fails to unswitch the branch it returns false.
457 ///
458 /// If the branch can be unswitched, this routine splits the preheader and
459 /// hoists the branch above that split. Preserves loop simplified form
460 /// (splitting the exit block as necessary). It simplifies the branch within
461 /// the loop to an unconditional branch but doesn't remove it entirely. Further
462 /// cleanup can be done with some simplifycfg like pass.
463 ///
464 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
465 /// invalidated by this.
466 static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT,
467                                   LoopInfo &LI, ScalarEvolution *SE,
468                                   MemorySSAUpdater *MSSAU) {
469   assert(BI.isConditional() && "Can only unswitch a conditional branch!");
470   LLVM_DEBUG(dbgs() << "  Trying to unswitch branch: " << BI << "\n");
471 
472   // The loop invariant values that we want to unswitch.
473   TinyPtrVector<Value *> Invariants;
474 
475   // When true, we're fully unswitching the branch rather than just unswitching
476   // some input conditions to the branch.
477   bool FullUnswitch = false;
478 
479   Value *Cond = skipTrivialSelect(BI.getCondition());
480   if (L.isLoopInvariant(Cond)) {
481     Invariants.push_back(Cond);
482     FullUnswitch = true;
483   } else {
484     if (auto *CondInst = dyn_cast<Instruction>(Cond))
485       Invariants = collectHomogenousInstGraphLoopInvariants(L, *CondInst, LI);
486     if (Invariants.empty()) {
487       LLVM_DEBUG(dbgs() << "   Couldn't find invariant inputs!\n");
488       return false;
489     }
490   }
491 
492   // Check that one of the branch's successors exits, and which one.
493   bool ExitDirection = true;
494   int LoopExitSuccIdx = 0;
495   auto *LoopExitBB = BI.getSuccessor(0);
496   if (L.contains(LoopExitBB)) {
497     ExitDirection = false;
498     LoopExitSuccIdx = 1;
499     LoopExitBB = BI.getSuccessor(1);
500     if (L.contains(LoopExitBB)) {
501       LLVM_DEBUG(dbgs() << "   Branch doesn't exit the loop!\n");
502       return false;
503     }
504   }
505   auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx);
506   auto *ParentBB = BI.getParent();
507   if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) {
508     LLVM_DEBUG(dbgs() << "   Loop exit PHI's aren't loop-invariant!\n");
509     return false;
510   }
511 
512   // When unswitching only part of the branch's condition, we need the exit
513   // block to be reached directly from the partially unswitched input. This can
514   // be done when the exit block is along the true edge and the branch condition
515   // is a graph of `or` operations, or the exit block is along the false edge
516   // and the condition is a graph of `and` operations.
517   if (!FullUnswitch) {
518     if (ExitDirection ? !match(Cond, m_LogicalOr())
519                       : !match(Cond, m_LogicalAnd())) {
520       LLVM_DEBUG(dbgs() << "   Branch condition is in improper form for "
521                            "non-full unswitch!\n");
522       return false;
523     }
524   }
525 
526   LLVM_DEBUG({
527     dbgs() << "    unswitching trivial invariant conditions for: " << BI
528            << "\n";
529     for (Value *Invariant : Invariants) {
530       dbgs() << "      " << *Invariant << " == true";
531       if (Invariant != Invariants.back())
532         dbgs() << " ||";
533       dbgs() << "\n";
534     }
535   });
536 
537   // If we have scalar evolutions, we need to invalidate them including this
538   // loop, the loop containing the exit block and the topmost parent loop
539   // exiting via LoopExitBB.
540   if (SE) {
541     if (const Loop *ExitL = getTopMostExitingLoop(LoopExitBB, LI))
542       SE->forgetLoop(ExitL);
543     else
544       // Forget the entire nest as this exits the entire nest.
545       SE->forgetTopmostLoop(&L);
546     SE->forgetBlockAndLoopDispositions();
547   }
548 
549   if (MSSAU && VerifyMemorySSA)
550     MSSAU->getMemorySSA()->verifyMemorySSA();
551 
552   // Split the preheader, so that we know that there is a safe place to insert
553   // the conditional branch. We will change the preheader to have a conditional
554   // branch on LoopCond.
555   BasicBlock *OldPH = L.getLoopPreheader();
556   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
557 
558   // Now that we have a place to insert the conditional branch, create a place
559   // to branch to: this is the exit block out of the loop that we are
560   // unswitching. We need to split this if there are other loop predecessors.
561   // Because the loop is in simplified form, *any* other predecessor is enough.
562   BasicBlock *UnswitchedBB;
563   if (FullUnswitch && LoopExitBB->getUniquePredecessor()) {
564     assert(LoopExitBB->getUniquePredecessor() == BI.getParent() &&
565            "A branch's parent isn't a predecessor!");
566     UnswitchedBB = LoopExitBB;
567   } else {
568     UnswitchedBB =
569         SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI, MSSAU);
570   }
571 
572   if (MSSAU && VerifyMemorySSA)
573     MSSAU->getMemorySSA()->verifyMemorySSA();
574 
575   // Actually move the invariant uses into the unswitched position. If possible,
576   // we do this by moving the instructions, but when doing partial unswitching
577   // we do it by building a new merge of the values in the unswitched position.
578   OldPH->getTerminator()->eraseFromParent();
579   if (FullUnswitch) {
580     // If fully unswitching, we can use the existing branch instruction.
581     // Splice it into the old PH to gate reaching the new preheader and re-point
582     // its successors.
583     OldPH->splice(OldPH->end(), BI.getParent(), BI.getIterator());
584     BI.setCondition(Cond);
585     if (MSSAU) {
586       // Temporarily clone the terminator, to make MSSA update cheaper by
587       // separating "insert edge" updates from "remove edge" ones.
588       BI.clone()->insertInto(ParentBB, ParentBB->end());
589     } else {
590       // Create a new unconditional branch that will continue the loop as a new
591       // terminator.
592       BranchInst::Create(ContinueBB, ParentBB);
593     }
594     BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB);
595     BI.setSuccessor(1 - LoopExitSuccIdx, NewPH);
596   } else {
597     // Only unswitching a subset of inputs to the condition, so we will need to
598     // build a new branch that merges the invariant inputs.
599     if (ExitDirection)
600       assert(match(skipTrivialSelect(BI.getCondition()), m_LogicalOr()) &&
601              "Must have an `or` of `i1`s or `select i1 X, true, Y`s for the "
602              "condition!");
603     else
604       assert(match(skipTrivialSelect(BI.getCondition()), m_LogicalAnd()) &&
605              "Must have an `and` of `i1`s or `select i1 X, Y, false`s for the"
606              " condition!");
607     buildPartialUnswitchConditionalBranch(
608         *OldPH, Invariants, ExitDirection, *UnswitchedBB, *NewPH,
609         FreezeLoopUnswitchCond, OldPH->getTerminator(), nullptr, DT);
610   }
611 
612   // Update the dominator tree with the added edge.
613   DT.insertEdge(OldPH, UnswitchedBB);
614 
615   // After the dominator tree was updated with the added edge, update MemorySSA
616   // if available.
617   if (MSSAU) {
618     SmallVector<CFGUpdate, 1> Updates;
619     Updates.push_back({cfg::UpdateKind::Insert, OldPH, UnswitchedBB});
620     MSSAU->applyInsertUpdates(Updates, DT);
621   }
622 
623   // Finish updating dominator tree and memory ssa for full unswitch.
624   if (FullUnswitch) {
625     if (MSSAU) {
626       // Remove the cloned branch instruction.
627       ParentBB->getTerminator()->eraseFromParent();
628       // Create unconditional branch now.
629       BranchInst::Create(ContinueBB, ParentBB);
630       MSSAU->removeEdge(ParentBB, LoopExitBB);
631     }
632     DT.deleteEdge(ParentBB, LoopExitBB);
633   }
634 
635   if (MSSAU && VerifyMemorySSA)
636     MSSAU->getMemorySSA()->verifyMemorySSA();
637 
638   // Rewrite the relevant PHI nodes.
639   if (UnswitchedBB == LoopExitBB)
640     rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH);
641   else
642     rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB,
643                                               *ParentBB, *OldPH, FullUnswitch);
644 
645   // The constant we can replace all of our invariants with inside the loop
646   // body. If any of the invariants have a value other than this the loop won't
647   // be entered.
648   ConstantInt *Replacement = ExitDirection
649                                  ? ConstantInt::getFalse(BI.getContext())
650                                  : ConstantInt::getTrue(BI.getContext());
651 
652   // Since this is an i1 condition we can also trivially replace uses of it
653   // within the loop with a constant.
654   for (Value *Invariant : Invariants)
655     replaceLoopInvariantUses(L, Invariant, *Replacement);
656 
657   // If this was full unswitching, we may have changed the nesting relationship
658   // for this loop so hoist it to its correct parent if needed.
659   if (FullUnswitch)
660     hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
661 
662   if (MSSAU && VerifyMemorySSA)
663     MSSAU->getMemorySSA()->verifyMemorySSA();
664 
665   LLVM_DEBUG(dbgs() << "    done: unswitching trivial branch...\n");
666   ++NumTrivial;
667   ++NumBranches;
668   return true;
669 }
670 
671 /// Unswitch a trivial switch if the condition is loop invariant.
672 ///
673 /// This routine should only be called when loop code leading to the switch has
674 /// been validated as trivial (no side effects). This routine checks if the
675 /// condition is invariant and that at least one of the successors is a loop
676 /// exit. This allows us to unswitch without duplicating the loop, making it
677 /// trivial.
678 ///
679 /// If this routine fails to unswitch the switch it returns false.
680 ///
681 /// If the switch can be unswitched, this routine splits the preheader and
682 /// copies the switch above that split. If the default case is one of the
683 /// exiting cases, it copies the non-exiting cases and points them at the new
684 /// preheader. If the default case is not exiting, it copies the exiting cases
685 /// and points the default at the preheader. It preserves loop simplified form
686 /// (splitting the exit blocks as necessary). It simplifies the switch within
687 /// the loop by removing now-dead cases. If the default case is one of those
688 /// unswitched, it replaces its destination with a new basic block containing
689 /// only unreachable. Such basic blocks, while technically loop exits, are not
690 /// considered for unswitching so this is a stable transform and the same
691 /// switch will not be revisited. If after unswitching there is only a single
692 /// in-loop successor, the switch is further simplified to an unconditional
693 /// branch. Still more cleanup can be done with some simplifycfg like pass.
694 ///
695 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
696 /// invalidated by this.
697 static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT,
698                                   LoopInfo &LI, ScalarEvolution *SE,
699                                   MemorySSAUpdater *MSSAU) {
700   LLVM_DEBUG(dbgs() << "  Trying to unswitch switch: " << SI << "\n");
701   Value *LoopCond = SI.getCondition();
702 
703   // If this isn't switching on an invariant condition, we can't unswitch it.
704   if (!L.isLoopInvariant(LoopCond))
705     return false;
706 
707   auto *ParentBB = SI.getParent();
708 
709   // The same check must be used both for the default and the exit cases. We
710   // should never leave edges from the switch instruction to a basic block that
711   // we are unswitching, hence the condition used to determine the default case
712   // needs to also be used to populate ExitCaseIndices, which is then used to
713   // remove cases from the switch.
714   auto IsTriviallyUnswitchableExitBlock = [&](BasicBlock &BBToCheck) {
715     // BBToCheck is not an exit block if it is inside loop L.
716     if (L.contains(&BBToCheck))
717       return false;
718     // BBToCheck is not trivial to unswitch if its phis aren't loop invariant.
719     if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, BBToCheck))
720       return false;
721     // We do not unswitch a block that only has an unreachable statement, as
722     // it's possible this is a previously unswitched block. Only unswitch if
723     // either the terminator is not unreachable, or, if it is, it's not the only
724     // instruction in the block.
725     auto *TI = BBToCheck.getTerminator();
726     bool isUnreachable = isa<UnreachableInst>(TI);
727     return !isUnreachable ||
728            (isUnreachable && (BBToCheck.getFirstNonPHIOrDbg() != TI));
729   };
730 
731   SmallVector<int, 4> ExitCaseIndices;
732   for (auto Case : SI.cases())
733     if (IsTriviallyUnswitchableExitBlock(*Case.getCaseSuccessor()))
734       ExitCaseIndices.push_back(Case.getCaseIndex());
735   BasicBlock *DefaultExitBB = nullptr;
736   SwitchInstProfUpdateWrapper::CaseWeightOpt DefaultCaseWeight =
737       SwitchInstProfUpdateWrapper::getSuccessorWeight(SI, 0);
738   if (IsTriviallyUnswitchableExitBlock(*SI.getDefaultDest())) {
739     DefaultExitBB = SI.getDefaultDest();
740   } else if (ExitCaseIndices.empty())
741     return false;
742 
743   LLVM_DEBUG(dbgs() << "    unswitching trivial switch...\n");
744 
745   if (MSSAU && VerifyMemorySSA)
746     MSSAU->getMemorySSA()->verifyMemorySSA();
747 
748   // We may need to invalidate SCEVs for the outermost loop reached by any of
749   // the exits.
750   Loop *OuterL = &L;
751 
752   if (DefaultExitBB) {
753     // Clear out the default destination temporarily to allow accurate
754     // predecessor lists to be examined below.
755     SI.setDefaultDest(nullptr);
756     // Check the loop containing this exit.
757     Loop *ExitL = LI.getLoopFor(DefaultExitBB);
758     if (!ExitL || ExitL->contains(OuterL))
759       OuterL = ExitL;
760   }
761 
762   // Store the exit cases into a separate data structure and remove them from
763   // the switch.
764   SmallVector<std::tuple<ConstantInt *, BasicBlock *,
765                          SwitchInstProfUpdateWrapper::CaseWeightOpt>,
766               4> ExitCases;
767   ExitCases.reserve(ExitCaseIndices.size());
768   SwitchInstProfUpdateWrapper SIW(SI);
769   // We walk the case indices backwards so that we remove the last case first
770   // and don't disrupt the earlier indices.
771   for (unsigned Index : reverse(ExitCaseIndices)) {
772     auto CaseI = SI.case_begin() + Index;
773     // Compute the outer loop from this exit.
774     Loop *ExitL = LI.getLoopFor(CaseI->getCaseSuccessor());
775     if (!ExitL || ExitL->contains(OuterL))
776       OuterL = ExitL;
777     // Save the value of this case.
778     auto W = SIW.getSuccessorWeight(CaseI->getSuccessorIndex());
779     ExitCases.emplace_back(CaseI->getCaseValue(), CaseI->getCaseSuccessor(), W);
780     // Delete the unswitched cases.
781     SIW.removeCase(CaseI);
782   }
783 
784   if (SE) {
785     if (OuterL)
786       SE->forgetLoop(OuterL);
787     else
788       SE->forgetTopmostLoop(&L);
789   }
790 
791   // Check if after this all of the remaining cases point at the same
792   // successor.
793   BasicBlock *CommonSuccBB = nullptr;
794   if (SI.getNumCases() > 0 &&
795       all_of(drop_begin(SI.cases()), [&SI](const SwitchInst::CaseHandle &Case) {
796         return Case.getCaseSuccessor() == SI.case_begin()->getCaseSuccessor();
797       }))
798     CommonSuccBB = SI.case_begin()->getCaseSuccessor();
799   if (!DefaultExitBB) {
800     // If we're not unswitching the default, we need it to match any cases to
801     // have a common successor or if we have no cases it is the common
802     // successor.
803     if (SI.getNumCases() == 0)
804       CommonSuccBB = SI.getDefaultDest();
805     else if (SI.getDefaultDest() != CommonSuccBB)
806       CommonSuccBB = nullptr;
807   }
808 
809   // Split the preheader, so that we know that there is a safe place to insert
810   // the switch.
811   BasicBlock *OldPH = L.getLoopPreheader();
812   BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI, MSSAU);
813   OldPH->getTerminator()->eraseFromParent();
814 
815   // Now add the unswitched switch.
816   auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH);
817   SwitchInstProfUpdateWrapper NewSIW(*NewSI);
818 
819   // Rewrite the IR for the unswitched basic blocks. This requires two steps.
820   // First, we split any exit blocks with remaining in-loop predecessors. Then
821   // we update the PHIs in one of two ways depending on if there was a split.
822   // We walk in reverse so that we split in the same order as the cases
823   // appeared. This is purely for convenience of reading the resulting IR, but
824   // it doesn't cost anything really.
825   SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs;
826   SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap;
827   // Handle the default exit if necessary.
828   // FIXME: It'd be great if we could merge this with the loop below but LLVM's
829   // ranges aren't quite powerful enough yet.
830   if (DefaultExitBB) {
831     if (pred_empty(DefaultExitBB)) {
832       UnswitchedExitBBs.insert(DefaultExitBB);
833       rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH);
834     } else {
835       auto *SplitBB =
836           SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI, MSSAU);
837       rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB,
838                                                 *ParentBB, *OldPH,
839                                                 /*FullUnswitch*/ true);
840       DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB;
841     }
842   }
843   // Note that we must use a reference in the for loop so that we update the
844   // container.
845   for (auto &ExitCase : reverse(ExitCases)) {
846     // Grab a reference to the exit block in the pair so that we can update it.
847     BasicBlock *ExitBB = std::get<1>(ExitCase);
848 
849     // If this case is the last edge into the exit block, we can simply reuse it
850     // as it will no longer be a loop exit. No mapping necessary.
851     if (pred_empty(ExitBB)) {
852       // Only rewrite once.
853       if (UnswitchedExitBBs.insert(ExitBB).second)
854         rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH);
855       continue;
856     }
857 
858     // Otherwise we need to split the exit block so that we retain an exit
859     // block from the loop and a target for the unswitched condition.
860     BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB];
861     if (!SplitExitBB) {
862       // If this is the first time we see this, do the split and remember it.
863       SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
864       rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB,
865                                                 *ParentBB, *OldPH,
866                                                 /*FullUnswitch*/ true);
867     }
868     // Update the case pair to point to the split block.
869     std::get<1>(ExitCase) = SplitExitBB;
870   }
871 
872   // Now add the unswitched cases. We do this in reverse order as we built them
873   // in reverse order.
874   for (auto &ExitCase : reverse(ExitCases)) {
875     ConstantInt *CaseVal = std::get<0>(ExitCase);
876     BasicBlock *UnswitchedBB = std::get<1>(ExitCase);
877 
878     NewSIW.addCase(CaseVal, UnswitchedBB, std::get<2>(ExitCase));
879   }
880 
881   // If the default was unswitched, re-point it and add explicit cases for
882   // entering the loop.
883   if (DefaultExitBB) {
884     NewSIW->setDefaultDest(DefaultExitBB);
885     NewSIW.setSuccessorWeight(0, DefaultCaseWeight);
886 
887     // We removed all the exit cases, so we just copy the cases to the
888     // unswitched switch.
889     for (const auto &Case : SI.cases())
890       NewSIW.addCase(Case.getCaseValue(), NewPH,
891                      SIW.getSuccessorWeight(Case.getSuccessorIndex()));
892   } else if (DefaultCaseWeight) {
893     // We have to set branch weight of the default case.
894     uint64_t SW = *DefaultCaseWeight;
895     for (const auto &Case : SI.cases()) {
896       auto W = SIW.getSuccessorWeight(Case.getSuccessorIndex());
897       assert(W &&
898              "case weight must be defined as default case weight is defined");
899       SW += *W;
900     }
901     NewSIW.setSuccessorWeight(0, SW);
902   }
903 
904   // If we ended up with a common successor for every path through the switch
905   // after unswitching, rewrite it to an unconditional branch to make it easy
906   // to recognize. Otherwise we potentially have to recognize the default case
907   // pointing at unreachable and other complexity.
908   if (CommonSuccBB) {
909     BasicBlock *BB = SI.getParent();
910     // We may have had multiple edges to this common successor block, so remove
911     // them as predecessors. We skip the first one, either the default or the
912     // actual first case.
913     bool SkippedFirst = DefaultExitBB == nullptr;
914     for (auto Case : SI.cases()) {
915       assert(Case.getCaseSuccessor() == CommonSuccBB &&
916              "Non-common successor!");
917       (void)Case;
918       if (!SkippedFirst) {
919         SkippedFirst = true;
920         continue;
921       }
922       CommonSuccBB->removePredecessor(BB,
923                                       /*KeepOneInputPHIs*/ true);
924     }
925     // Now nuke the switch and replace it with a direct branch.
926     SIW.eraseFromParent();
927     BranchInst::Create(CommonSuccBB, BB);
928   } else if (DefaultExitBB) {
929     assert(SI.getNumCases() > 0 &&
930            "If we had no cases we'd have a common successor!");
931     // Move the last case to the default successor. This is valid as if the
932     // default got unswitched it cannot be reached. This has the advantage of
933     // being simple and keeping the number of edges from this switch to
934     // successors the same, and avoiding any PHI update complexity.
935     auto LastCaseI = std::prev(SI.case_end());
936 
937     SI.setDefaultDest(LastCaseI->getCaseSuccessor());
938     SIW.setSuccessorWeight(
939         0, SIW.getSuccessorWeight(LastCaseI->getSuccessorIndex()));
940     SIW.removeCase(LastCaseI);
941   }
942 
943   // Walk the unswitched exit blocks and the unswitched split blocks and update
944   // the dominator tree based on the CFG edits. While we are walking unordered
945   // containers here, the API for applyUpdates takes an unordered list of
946   // updates and requires them to not contain duplicates.
947   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
948   for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
949     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
950     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
951   }
952   for (auto SplitUnswitchedPair : SplitExitBBMap) {
953     DTUpdates.push_back({DT.Delete, ParentBB, SplitUnswitchedPair.first});
954     DTUpdates.push_back({DT.Insert, OldPH, SplitUnswitchedPair.second});
955   }
956 
957   if (MSSAU) {
958     MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
959     if (VerifyMemorySSA)
960       MSSAU->getMemorySSA()->verifyMemorySSA();
961   } else {
962     DT.applyUpdates(DTUpdates);
963   }
964 
965   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
966 
967   // We may have changed the nesting relationship for this loop so hoist it to
968   // its correct parent if needed.
969   hoistLoopToNewParent(L, *NewPH, DT, LI, MSSAU, SE);
970 
971   if (MSSAU && VerifyMemorySSA)
972     MSSAU->getMemorySSA()->verifyMemorySSA();
973 
974   ++NumTrivial;
975   ++NumSwitches;
976   LLVM_DEBUG(dbgs() << "    done: unswitching trivial switch...\n");
977   return true;
978 }
979 
980 /// This routine scans the loop to find a branch or switch which occurs before
981 /// any side effects occur. These can potentially be unswitched without
982 /// duplicating the loop. If a branch or switch is successfully unswitched the
983 /// scanning continues to see if subsequent branches or switches have become
984 /// trivial. Once all trivial candidates have been unswitched, this routine
985 /// returns.
986 ///
987 /// The return value indicates whether anything was unswitched (and therefore
988 /// changed).
989 ///
990 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
991 /// invalidated by this.
992 static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
993                                          LoopInfo &LI, ScalarEvolution *SE,
994                                          MemorySSAUpdater *MSSAU) {
995   bool Changed = false;
996 
997   // If loop header has only one reachable successor we should keep looking for
998   // trivial condition candidates in the successor as well. An alternative is
999   // to constant fold conditions and merge successors into loop header (then we
1000   // only need to check header's terminator). The reason for not doing this in
1001   // LoopUnswitch pass is that it could potentially break LoopPassManager's
1002   // invariants. Folding dead branches could either eliminate the current loop
1003   // or make other loops unreachable. LCSSA form might also not be preserved
1004   // after deleting branches. The following code keeps traversing loop header's
1005   // successors until it finds the trivial condition candidate (condition that
1006   // is not a constant). Since unswitching generates branches with constant
1007   // conditions, this scenario could be very common in practice.
1008   BasicBlock *CurrentBB = L.getHeader();
1009   SmallPtrSet<BasicBlock *, 8> Visited;
1010   Visited.insert(CurrentBB);
1011   do {
1012     // Check if there are any side-effecting instructions (e.g. stores, calls,
1013     // volatile loads) in the part of the loop that the code *would* execute
1014     // without unswitching.
1015     if (MSSAU) // Possible early exit with MSSA
1016       if (auto *Defs = MSSAU->getMemorySSA()->getBlockDefs(CurrentBB))
1017         if (!isa<MemoryPhi>(*Defs->begin()) || (++Defs->begin() != Defs->end()))
1018           return Changed;
1019     if (llvm::any_of(*CurrentBB,
1020                      [](Instruction &I) { return I.mayHaveSideEffects(); }))
1021       return Changed;
1022 
1023     Instruction *CurrentTerm = CurrentBB->getTerminator();
1024 
1025     if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1026       // Don't bother trying to unswitch past a switch with a constant
1027       // condition. This should be removed prior to running this pass by
1028       // simplifycfg.
1029       if (isa<Constant>(SI->getCondition()))
1030         return Changed;
1031 
1032       if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE, MSSAU))
1033         // Couldn't unswitch this one so we're done.
1034         return Changed;
1035 
1036       // Mark that we managed to unswitch something.
1037       Changed = true;
1038 
1039       // If unswitching turned the terminator into an unconditional branch then
1040       // we can continue. The unswitching logic specifically works to fold any
1041       // cases it can into an unconditional branch to make it easier to
1042       // recognize here.
1043       auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
1044       if (!BI || BI->isConditional())
1045         return Changed;
1046 
1047       CurrentBB = BI->getSuccessor(0);
1048       continue;
1049     }
1050 
1051     auto *BI = dyn_cast<BranchInst>(CurrentTerm);
1052     if (!BI)
1053       // We do not understand other terminator instructions.
1054       return Changed;
1055 
1056     // Don't bother trying to unswitch past an unconditional branch or a branch
1057     // with a constant value. These should be removed by simplifycfg prior to
1058     // running this pass.
1059     if (!BI->isConditional() ||
1060         isa<Constant>(skipTrivialSelect(BI->getCondition())))
1061       return Changed;
1062 
1063     // Found a trivial condition candidate: non-foldable conditional branch. If
1064     // we fail to unswitch this, we can't do anything else that is trivial.
1065     if (!unswitchTrivialBranch(L, *BI, DT, LI, SE, MSSAU))
1066       return Changed;
1067 
1068     // Mark that we managed to unswitch something.
1069     Changed = true;
1070 
1071     // If we only unswitched some of the conditions feeding the branch, we won't
1072     // have collapsed it to a single successor.
1073     BI = cast<BranchInst>(CurrentBB->getTerminator());
1074     if (BI->isConditional())
1075       return Changed;
1076 
1077     // Follow the newly unconditional branch into its successor.
1078     CurrentBB = BI->getSuccessor(0);
1079 
1080     // When continuing, if we exit the loop or reach a previous visited block,
1081     // then we can not reach any trivial condition candidates (unfoldable
1082     // branch instructions or switch instructions) and no unswitch can happen.
1083   } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
1084 
1085   return Changed;
1086 }
1087 
1088 /// Build the cloned blocks for an unswitched copy of the given loop.
1089 ///
1090 /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
1091 /// after the split block (`SplitBB`) that will be used to select between the
1092 /// cloned and original loop.
1093 ///
1094 /// This routine handles cloning all of the necessary loop blocks and exit
1095 /// blocks including rewriting their instructions and the relevant PHI nodes.
1096 /// Any loop blocks or exit blocks which are dominated by a different successor
1097 /// than the one for this clone of the loop blocks can be trivially skipped. We
1098 /// use the `DominatingSucc` map to determine whether a block satisfies that
1099 /// property with a simple map lookup.
1100 ///
1101 /// It also correctly creates the unconditional branch in the cloned
1102 /// unswitched parent block to only point at the unswitched successor.
1103 ///
1104 /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
1105 /// block splitting is correctly reflected in `LoopInfo`, essentially all of
1106 /// the cloned blocks (and their loops) are left without full `LoopInfo`
1107 /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
1108 /// blocks to them but doesn't create the cloned `DominatorTree` structure and
1109 /// instead the caller must recompute an accurate DT. It *does* correctly
1110 /// update the `AssumptionCache` provided in `AC`.
1111 static BasicBlock *buildClonedLoopBlocks(
1112     Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
1113     ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
1114     BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
1115     const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
1116     ValueToValueMapTy &VMap,
1117     SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
1118     DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU,
1119     ScalarEvolution *SE) {
1120   SmallVector<BasicBlock *, 4> NewBlocks;
1121   NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
1122 
1123   // We will need to clone a bunch of blocks, wrap up the clone operation in
1124   // a helper.
1125   auto CloneBlock = [&](BasicBlock *OldBB) {
1126     // Clone the basic block and insert it before the new preheader.
1127     BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
1128     NewBB->moveBefore(LoopPH);
1129 
1130     // Record this block and the mapping.
1131     NewBlocks.push_back(NewBB);
1132     VMap[OldBB] = NewBB;
1133 
1134     return NewBB;
1135   };
1136 
1137   // We skip cloning blocks when they have a dominating succ that is not the
1138   // succ we are cloning for.
1139   auto SkipBlock = [&](BasicBlock *BB) {
1140     auto It = DominatingSucc.find(BB);
1141     return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
1142   };
1143 
1144   // First, clone the preheader.
1145   auto *ClonedPH = CloneBlock(LoopPH);
1146 
1147   // Then clone all the loop blocks, skipping the ones that aren't necessary.
1148   for (auto *LoopBB : L.blocks())
1149     if (!SkipBlock(LoopBB))
1150       CloneBlock(LoopBB);
1151 
1152   // Split all the loop exit edges so that when we clone the exit blocks, if
1153   // any of the exit blocks are *also* a preheader for some other loop, we
1154   // don't create multiple predecessors entering the loop header.
1155   for (auto *ExitBB : ExitBlocks) {
1156     if (SkipBlock(ExitBB))
1157       continue;
1158 
1159     // When we are going to clone an exit, we don't need to clone all the
1160     // instructions in the exit block and we want to ensure we have an easy
1161     // place to merge the CFG, so split the exit first. This is always safe to
1162     // do because there cannot be any non-loop predecessors of a loop exit in
1163     // loop simplified form.
1164     auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI, MSSAU);
1165 
1166     // Rearrange the names to make it easier to write test cases by having the
1167     // exit block carry the suffix rather than the merge block carrying the
1168     // suffix.
1169     MergeBB->takeName(ExitBB);
1170     ExitBB->setName(Twine(MergeBB->getName()) + ".split");
1171 
1172     // Now clone the original exit block.
1173     auto *ClonedExitBB = CloneBlock(ExitBB);
1174     assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
1175            "Exit block should have been split to have one successor!");
1176     assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
1177            "Cloned exit block has the wrong successor!");
1178 
1179     // Remap any cloned instructions and create a merge phi node for them.
1180     for (auto ZippedInsts : llvm::zip_first(
1181              llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
1182              llvm::make_range(ClonedExitBB->begin(),
1183                               std::prev(ClonedExitBB->end())))) {
1184       Instruction &I = std::get<0>(ZippedInsts);
1185       Instruction &ClonedI = std::get<1>(ZippedInsts);
1186 
1187       // The only instructions in the exit block should be PHI nodes and
1188       // potentially a landing pad.
1189       assert(
1190           (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
1191           "Bad instruction in exit block!");
1192       // We should have a value map between the instruction and its clone.
1193       assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
1194 
1195       // Forget SCEVs based on exit phis in case SCEV looked through the phi.
1196       if (SE && isa<PHINode>(I))
1197         SE->forgetValue(&I);
1198 
1199       auto *MergePN =
1200           PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
1201                           &*MergeBB->getFirstInsertionPt());
1202       I.replaceAllUsesWith(MergePN);
1203       MergePN->addIncoming(&I, ExitBB);
1204       MergePN->addIncoming(&ClonedI, ClonedExitBB);
1205     }
1206   }
1207 
1208   // Rewrite the instructions in the cloned blocks to refer to the instructions
1209   // in the cloned blocks. We have to do this as a second pass so that we have
1210   // everything available. Also, we have inserted new instructions which may
1211   // include assume intrinsics, so we update the assumption cache while
1212   // processing this.
1213   for (auto *ClonedBB : NewBlocks)
1214     for (Instruction &I : *ClonedBB) {
1215       RemapInstruction(&I, VMap,
1216                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1217       if (auto *II = dyn_cast<AssumeInst>(&I))
1218         AC.registerAssumption(II);
1219     }
1220 
1221   // Update any PHI nodes in the cloned successors of the skipped blocks to not
1222   // have spurious incoming values.
1223   for (auto *LoopBB : L.blocks())
1224     if (SkipBlock(LoopBB))
1225       for (auto *SuccBB : successors(LoopBB))
1226         if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
1227           for (PHINode &PN : ClonedSuccBB->phis())
1228             PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
1229 
1230   // Remove the cloned parent as a predecessor of any successor we ended up
1231   // cloning other than the unswitched one.
1232   auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
1233   for (auto *SuccBB : successors(ParentBB)) {
1234     if (SuccBB == UnswitchedSuccBB)
1235       continue;
1236 
1237     auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
1238     if (!ClonedSuccBB)
1239       continue;
1240 
1241     ClonedSuccBB->removePredecessor(ClonedParentBB,
1242                                     /*KeepOneInputPHIs*/ true);
1243   }
1244 
1245   // Replace the cloned branch with an unconditional branch to the cloned
1246   // unswitched successor.
1247   auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1248   Instruction *ClonedTerminator = ClonedParentBB->getTerminator();
1249   // Trivial Simplification. If Terminator is a conditional branch and
1250   // condition becomes dead - erase it.
1251   Value *ClonedConditionToErase = nullptr;
1252   if (auto *BI = dyn_cast<BranchInst>(ClonedTerminator))
1253     ClonedConditionToErase = BI->getCondition();
1254   else if (auto *SI = dyn_cast<SwitchInst>(ClonedTerminator))
1255     ClonedConditionToErase = SI->getCondition();
1256 
1257   ClonedTerminator->eraseFromParent();
1258   BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1259 
1260   if (ClonedConditionToErase)
1261     RecursivelyDeleteTriviallyDeadInstructions(ClonedConditionToErase, nullptr,
1262                                                MSSAU);
1263 
1264   // If there are duplicate entries in the PHI nodes because of multiple edges
1265   // to the unswitched successor, we need to nuke all but one as we replaced it
1266   // with a direct branch.
1267   for (PHINode &PN : ClonedSuccBB->phis()) {
1268     bool Found = false;
1269     // Loop over the incoming operands backwards so we can easily delete as we
1270     // go without invalidating the index.
1271     for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1272       if (PN.getIncomingBlock(i) != ClonedParentBB)
1273         continue;
1274       if (!Found) {
1275         Found = true;
1276         continue;
1277       }
1278       PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1279     }
1280   }
1281 
1282   // Record the domtree updates for the new blocks.
1283   SmallPtrSet<BasicBlock *, 4> SuccSet;
1284   for (auto *ClonedBB : NewBlocks) {
1285     for (auto *SuccBB : successors(ClonedBB))
1286       if (SuccSet.insert(SuccBB).second)
1287         DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1288     SuccSet.clear();
1289   }
1290 
1291   return ClonedPH;
1292 }
1293 
1294 /// Recursively clone the specified loop and all of its children.
1295 ///
1296 /// The target parent loop for the clone should be provided, or can be null if
1297 /// the clone is a top-level loop. While cloning, all the blocks are mapped
1298 /// with the provided value map. The entire original loop must be present in
1299 /// the value map. The cloned loop is returned.
1300 static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1301                            const ValueToValueMapTy &VMap, LoopInfo &LI) {
1302   auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1303     assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1304     ClonedL.reserveBlocks(OrigL.getNumBlocks());
1305     for (auto *BB : OrigL.blocks()) {
1306       auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1307       ClonedL.addBlockEntry(ClonedBB);
1308       if (LI.getLoopFor(BB) == &OrigL)
1309         LI.changeLoopFor(ClonedBB, &ClonedL);
1310     }
1311   };
1312 
1313   // We specially handle the first loop because it may get cloned into
1314   // a different parent and because we most commonly are cloning leaf loops.
1315   Loop *ClonedRootL = LI.AllocateLoop();
1316   if (RootParentL)
1317     RootParentL->addChildLoop(ClonedRootL);
1318   else
1319     LI.addTopLevelLoop(ClonedRootL);
1320   AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1321 
1322   if (OrigRootL.isInnermost())
1323     return ClonedRootL;
1324 
1325   // If we have a nest, we can quickly clone the entire loop nest using an
1326   // iterative approach because it is a tree. We keep the cloned parent in the
1327   // data structure to avoid repeatedly querying through a map to find it.
1328   SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1329   // Build up the loops to clone in reverse order as we'll clone them from the
1330   // back.
1331   for (Loop *ChildL : llvm::reverse(OrigRootL))
1332     LoopsToClone.push_back({ClonedRootL, ChildL});
1333   do {
1334     Loop *ClonedParentL, *L;
1335     std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1336     Loop *ClonedL = LI.AllocateLoop();
1337     ClonedParentL->addChildLoop(ClonedL);
1338     AddClonedBlocksToLoop(*L, *ClonedL);
1339     for (Loop *ChildL : llvm::reverse(*L))
1340       LoopsToClone.push_back({ClonedL, ChildL});
1341   } while (!LoopsToClone.empty());
1342 
1343   return ClonedRootL;
1344 }
1345 
1346 /// Build the cloned loops of an original loop from unswitching.
1347 ///
1348 /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1349 /// operation. We need to re-verify that there even is a loop (as the backedge
1350 /// may not have been cloned), and even if there are remaining backedges the
1351 /// backedge set may be different. However, we know that each child loop is
1352 /// undisturbed, we only need to find where to place each child loop within
1353 /// either any parent loop or within a cloned version of the original loop.
1354 ///
1355 /// Because child loops may end up cloned outside of any cloned version of the
1356 /// original loop, multiple cloned sibling loops may be created. All of them
1357 /// are returned so that the newly introduced loop nest roots can be
1358 /// identified.
1359 static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1360                              const ValueToValueMapTy &VMap, LoopInfo &LI,
1361                              SmallVectorImpl<Loop *> &NonChildClonedLoops) {
1362   Loop *ClonedL = nullptr;
1363 
1364   auto *OrigPH = OrigL.getLoopPreheader();
1365   auto *OrigHeader = OrigL.getHeader();
1366 
1367   auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1368   auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1369 
1370   // We need to know the loops of the cloned exit blocks to even compute the
1371   // accurate parent loop. If we only clone exits to some parent of the
1372   // original parent, we want to clone into that outer loop. We also keep track
1373   // of the loops that our cloned exit blocks participate in.
1374   Loop *ParentL = nullptr;
1375   SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1376   SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1377   ClonedExitsInLoops.reserve(ExitBlocks.size());
1378   for (auto *ExitBB : ExitBlocks)
1379     if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1380       if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1381         ExitLoopMap[ClonedExitBB] = ExitL;
1382         ClonedExitsInLoops.push_back(ClonedExitBB);
1383         if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1384           ParentL = ExitL;
1385       }
1386   assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1387           ParentL->contains(OrigL.getParentLoop())) &&
1388          "The computed parent loop should always contain (or be) the parent of "
1389          "the original loop.");
1390 
1391   // We build the set of blocks dominated by the cloned header from the set of
1392   // cloned blocks out of the original loop. While not all of these will
1393   // necessarily be in the cloned loop, it is enough to establish that they
1394   // aren't in unreachable cycles, etc.
1395   SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1396   for (auto *BB : OrigL.blocks())
1397     if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1398       ClonedLoopBlocks.insert(ClonedBB);
1399 
1400   // Rebuild the set of blocks that will end up in the cloned loop. We may have
1401   // skipped cloning some region of this loop which can in turn skip some of
1402   // the backedges so we have to rebuild the blocks in the loop based on the
1403   // backedges that remain after cloning.
1404   SmallVector<BasicBlock *, 16> Worklist;
1405   SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1406   for (auto *Pred : predecessors(ClonedHeader)) {
1407     // The only possible non-loop header predecessor is the preheader because
1408     // we know we cloned the loop in simplified form.
1409     if (Pred == ClonedPH)
1410       continue;
1411 
1412     // Because the loop was in simplified form, the only non-loop predecessor
1413     // should be the preheader.
1414     assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1415                                            "header other than the preheader "
1416                                            "that is not part of the loop!");
1417 
1418     // Insert this block into the loop set and on the first visit (and if it
1419     // isn't the header we're currently walking) put it into the worklist to
1420     // recurse through.
1421     if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1422       Worklist.push_back(Pred);
1423   }
1424 
1425   // If we had any backedges then there *is* a cloned loop. Put the header into
1426   // the loop set and then walk the worklist backwards to find all the blocks
1427   // that remain within the loop after cloning.
1428   if (!BlocksInClonedLoop.empty()) {
1429     BlocksInClonedLoop.insert(ClonedHeader);
1430 
1431     while (!Worklist.empty()) {
1432       BasicBlock *BB = Worklist.pop_back_val();
1433       assert(BlocksInClonedLoop.count(BB) &&
1434              "Didn't put block into the loop set!");
1435 
1436       // Insert any predecessors that are in the possible set into the cloned
1437       // set, and if the insert is successful, add them to the worklist. Note
1438       // that we filter on the blocks that are definitely reachable via the
1439       // backedge to the loop header so we may prune out dead code within the
1440       // cloned loop.
1441       for (auto *Pred : predecessors(BB))
1442         if (ClonedLoopBlocks.count(Pred) &&
1443             BlocksInClonedLoop.insert(Pred).second)
1444           Worklist.push_back(Pred);
1445     }
1446 
1447     ClonedL = LI.AllocateLoop();
1448     if (ParentL) {
1449       ParentL->addBasicBlockToLoop(ClonedPH, LI);
1450       ParentL->addChildLoop(ClonedL);
1451     } else {
1452       LI.addTopLevelLoop(ClonedL);
1453     }
1454     NonChildClonedLoops.push_back(ClonedL);
1455 
1456     ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1457     // We don't want to just add the cloned loop blocks based on how we
1458     // discovered them. The original order of blocks was carefully built in
1459     // a way that doesn't rely on predecessor ordering. Rather than re-invent
1460     // that logic, we just re-walk the original blocks (and those of the child
1461     // loops) and filter them as we add them into the cloned loop.
1462     for (auto *BB : OrigL.blocks()) {
1463       auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1464       if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1465         continue;
1466 
1467       // Directly add the blocks that are only in this loop.
1468       if (LI.getLoopFor(BB) == &OrigL) {
1469         ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1470         continue;
1471       }
1472 
1473       // We want to manually add it to this loop and parents.
1474       // Registering it with LoopInfo will happen when we clone the top
1475       // loop for this block.
1476       for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1477         PL->addBlockEntry(ClonedBB);
1478     }
1479 
1480     // Now add each child loop whose header remains within the cloned loop. All
1481     // of the blocks within the loop must satisfy the same constraints as the
1482     // header so once we pass the header checks we can just clone the entire
1483     // child loop nest.
1484     for (Loop *ChildL : OrigL) {
1485       auto *ClonedChildHeader =
1486           cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1487       if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1488         continue;
1489 
1490 #ifndef NDEBUG
1491       // We should never have a cloned child loop header but fail to have
1492       // all of the blocks for that child loop.
1493       for (auto *ChildLoopBB : ChildL->blocks())
1494         assert(BlocksInClonedLoop.count(
1495                    cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1496                "Child cloned loop has a header within the cloned outer "
1497                "loop but not all of its blocks!");
1498 #endif
1499 
1500       cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1501     }
1502   }
1503 
1504   // Now that we've handled all the components of the original loop that were
1505   // cloned into a new loop, we still need to handle anything from the original
1506   // loop that wasn't in a cloned loop.
1507 
1508   // Figure out what blocks are left to place within any loop nest containing
1509   // the unswitched loop. If we never formed a loop, the cloned PH is one of
1510   // them.
1511   SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1512   if (BlocksInClonedLoop.empty())
1513     UnloopedBlockSet.insert(ClonedPH);
1514   for (auto *ClonedBB : ClonedLoopBlocks)
1515     if (!BlocksInClonedLoop.count(ClonedBB))
1516       UnloopedBlockSet.insert(ClonedBB);
1517 
1518   // Copy the cloned exits and sort them in ascending loop depth, we'll work
1519   // backwards across these to process them inside out. The order shouldn't
1520   // matter as we're just trying to build up the map from inside-out; we use
1521   // the map in a more stably ordered way below.
1522   auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
1523   llvm::sort(OrderedClonedExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1524     return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1525            ExitLoopMap.lookup(RHS)->getLoopDepth();
1526   });
1527 
1528   // Populate the existing ExitLoopMap with everything reachable from each
1529   // exit, starting from the inner most exit.
1530   while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1531     assert(Worklist.empty() && "Didn't clear worklist!");
1532 
1533     BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1534     Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1535 
1536     // Walk the CFG back until we hit the cloned PH adding everything reachable
1537     // and in the unlooped set to this exit block's loop.
1538     Worklist.push_back(ExitBB);
1539     do {
1540       BasicBlock *BB = Worklist.pop_back_val();
1541       // We can stop recursing at the cloned preheader (if we get there).
1542       if (BB == ClonedPH)
1543         continue;
1544 
1545       for (BasicBlock *PredBB : predecessors(BB)) {
1546         // If this pred has already been moved to our set or is part of some
1547         // (inner) loop, no update needed.
1548         if (!UnloopedBlockSet.erase(PredBB)) {
1549           assert(
1550               (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1551               "Predecessor not mapped to a loop!");
1552           continue;
1553         }
1554 
1555         // We just insert into the loop set here. We'll add these blocks to the
1556         // exit loop after we build up the set in an order that doesn't rely on
1557         // predecessor order (which in turn relies on use list order).
1558         bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1559         (void)Inserted;
1560         assert(Inserted && "Should only visit an unlooped block once!");
1561 
1562         // And recurse through to its predecessors.
1563         Worklist.push_back(PredBB);
1564       }
1565     } while (!Worklist.empty());
1566   }
1567 
1568   // Now that the ExitLoopMap gives as  mapping for all the non-looping cloned
1569   // blocks to their outer loops, walk the cloned blocks and the cloned exits
1570   // in their original order adding them to the correct loop.
1571 
1572   // We need a stable insertion order. We use the order of the original loop
1573   // order and map into the correct parent loop.
1574   for (auto *BB : llvm::concat<BasicBlock *const>(
1575            makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1576     if (Loop *OuterL = ExitLoopMap.lookup(BB))
1577       OuterL->addBasicBlockToLoop(BB, LI);
1578 
1579 #ifndef NDEBUG
1580   for (auto &BBAndL : ExitLoopMap) {
1581     auto *BB = BBAndL.first;
1582     auto *OuterL = BBAndL.second;
1583     assert(LI.getLoopFor(BB) == OuterL &&
1584            "Failed to put all blocks into outer loops!");
1585   }
1586 #endif
1587 
1588   // Now that all the blocks are placed into the correct containing loop in the
1589   // absence of child loops, find all the potentially cloned child loops and
1590   // clone them into whatever outer loop we placed their header into.
1591   for (Loop *ChildL : OrigL) {
1592     auto *ClonedChildHeader =
1593         cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1594     if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1595       continue;
1596 
1597 #ifndef NDEBUG
1598     for (auto *ChildLoopBB : ChildL->blocks())
1599       assert(VMap.count(ChildLoopBB) &&
1600              "Cloned a child loop header but not all of that loops blocks!");
1601 #endif
1602 
1603     NonChildClonedLoops.push_back(cloneLoopNest(
1604         *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1605   }
1606 }
1607 
1608 static void
1609 deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1610                        ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1611                        DominatorTree &DT, MemorySSAUpdater *MSSAU) {
1612   // Find all the dead clones, and remove them from their successors.
1613   SmallVector<BasicBlock *, 16> DeadBlocks;
1614   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1615     for (const auto &VMap : VMaps)
1616       if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1617         if (!DT.isReachableFromEntry(ClonedBB)) {
1618           for (BasicBlock *SuccBB : successors(ClonedBB))
1619             SuccBB->removePredecessor(ClonedBB);
1620           DeadBlocks.push_back(ClonedBB);
1621         }
1622 
1623   // Remove all MemorySSA in the dead blocks
1624   if (MSSAU) {
1625     SmallSetVector<BasicBlock *, 8> DeadBlockSet(DeadBlocks.begin(),
1626                                                  DeadBlocks.end());
1627     MSSAU->removeBlocks(DeadBlockSet);
1628   }
1629 
1630   // Drop any remaining references to break cycles.
1631   for (BasicBlock *BB : DeadBlocks)
1632     BB->dropAllReferences();
1633   // Erase them from the IR.
1634   for (BasicBlock *BB : DeadBlocks)
1635     BB->eraseFromParent();
1636 }
1637 
1638 static void
1639 deleteDeadBlocksFromLoop(Loop &L,
1640                          SmallVectorImpl<BasicBlock *> &ExitBlocks,
1641                          DominatorTree &DT, LoopInfo &LI,
1642                          MemorySSAUpdater *MSSAU,
1643                          ScalarEvolution *SE,
1644                          function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
1645   // Find all the dead blocks tied to this loop, and remove them from their
1646   // successors.
1647   SmallSetVector<BasicBlock *, 8> DeadBlockSet;
1648 
1649   // Start with loop/exit blocks and get a transitive closure of reachable dead
1650   // blocks.
1651   SmallVector<BasicBlock *, 16> DeathCandidates(ExitBlocks.begin(),
1652                                                 ExitBlocks.end());
1653   DeathCandidates.append(L.blocks().begin(), L.blocks().end());
1654   while (!DeathCandidates.empty()) {
1655     auto *BB = DeathCandidates.pop_back_val();
1656     if (!DeadBlockSet.count(BB) && !DT.isReachableFromEntry(BB)) {
1657       for (BasicBlock *SuccBB : successors(BB)) {
1658         SuccBB->removePredecessor(BB);
1659         DeathCandidates.push_back(SuccBB);
1660       }
1661       DeadBlockSet.insert(BB);
1662     }
1663   }
1664 
1665   // Remove all MemorySSA in the dead blocks
1666   if (MSSAU)
1667     MSSAU->removeBlocks(DeadBlockSet);
1668 
1669   // Filter out the dead blocks from the exit blocks list so that it can be
1670   // used in the caller.
1671   llvm::erase_if(ExitBlocks,
1672                  [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1673 
1674   // Walk from this loop up through its parents removing all of the dead blocks.
1675   for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
1676     for (auto *BB : DeadBlockSet)
1677       ParentL->getBlocksSet().erase(BB);
1678     llvm::erase_if(ParentL->getBlocksVector(),
1679                    [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1680   }
1681 
1682   // Now delete the dead child loops. This raw delete will clear them
1683   // recursively.
1684   llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
1685     if (!DeadBlockSet.count(ChildL->getHeader()))
1686       return false;
1687 
1688     assert(llvm::all_of(ChildL->blocks(),
1689                         [&](BasicBlock *ChildBB) {
1690                           return DeadBlockSet.count(ChildBB);
1691                         }) &&
1692            "If the child loop header is dead all blocks in the child loop must "
1693            "be dead as well!");
1694     DestroyLoopCB(*ChildL, ChildL->getName());
1695     if (SE)
1696       SE->forgetBlockAndLoopDispositions();
1697     LI.destroy(ChildL);
1698     return true;
1699   });
1700 
1701   // Remove the loop mappings for the dead blocks and drop all the references
1702   // from these blocks to others to handle cyclic references as we start
1703   // deleting the blocks themselves.
1704   for (auto *BB : DeadBlockSet) {
1705     // Check that the dominator tree has already been updated.
1706     assert(!DT.getNode(BB) && "Should already have cleared domtree!");
1707     LI.changeLoopFor(BB, nullptr);
1708     // Drop all uses of the instructions to make sure we won't have dangling
1709     // uses in other blocks.
1710     for (auto &I : *BB)
1711       if (!I.use_empty())
1712         I.replaceAllUsesWith(PoisonValue::get(I.getType()));
1713     BB->dropAllReferences();
1714   }
1715 
1716   // Actually delete the blocks now that they've been fully unhooked from the
1717   // IR.
1718   for (auto *BB : DeadBlockSet)
1719     BB->eraseFromParent();
1720 }
1721 
1722 /// Recompute the set of blocks in a loop after unswitching.
1723 ///
1724 /// This walks from the original headers predecessors to rebuild the loop. We
1725 /// take advantage of the fact that new blocks can't have been added, and so we
1726 /// filter by the original loop's blocks. This also handles potentially
1727 /// unreachable code that we don't want to explore but might be found examining
1728 /// the predecessors of the header.
1729 ///
1730 /// If the original loop is no longer a loop, this will return an empty set. If
1731 /// it remains a loop, all the blocks within it will be added to the set
1732 /// (including those blocks in inner loops).
1733 static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1734                                                                  LoopInfo &LI) {
1735   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1736 
1737   auto *PH = L.getLoopPreheader();
1738   auto *Header = L.getHeader();
1739 
1740   // A worklist to use while walking backwards from the header.
1741   SmallVector<BasicBlock *, 16> Worklist;
1742 
1743   // First walk the predecessors of the header to find the backedges. This will
1744   // form the basis of our walk.
1745   for (auto *Pred : predecessors(Header)) {
1746     // Skip the preheader.
1747     if (Pred == PH)
1748       continue;
1749 
1750     // Because the loop was in simplified form, the only non-loop predecessor
1751     // is the preheader.
1752     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1753                                "than the preheader that is not part of the "
1754                                "loop!");
1755 
1756     // Insert this block into the loop set and on the first visit and, if it
1757     // isn't the header we're currently walking, put it into the worklist to
1758     // recurse through.
1759     if (LoopBlockSet.insert(Pred).second && Pred != Header)
1760       Worklist.push_back(Pred);
1761   }
1762 
1763   // If no backedges were found, we're done.
1764   if (LoopBlockSet.empty())
1765     return LoopBlockSet;
1766 
1767   // We found backedges, recurse through them to identify the loop blocks.
1768   while (!Worklist.empty()) {
1769     BasicBlock *BB = Worklist.pop_back_val();
1770     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1771 
1772     // No need to walk past the header.
1773     if (BB == Header)
1774       continue;
1775 
1776     // Because we know the inner loop structure remains valid we can use the
1777     // loop structure to jump immediately across the entire nested loop.
1778     // Further, because it is in loop simplified form, we can directly jump
1779     // to its preheader afterward.
1780     if (Loop *InnerL = LI.getLoopFor(BB))
1781       if (InnerL != &L) {
1782         assert(L.contains(InnerL) &&
1783                "Should not reach a loop *outside* this loop!");
1784         // The preheader is the only possible predecessor of the loop so
1785         // insert it into the set and check whether it was already handled.
1786         auto *InnerPH = InnerL->getLoopPreheader();
1787         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1788                                       "but not contain the inner loop "
1789                                       "preheader!");
1790         if (!LoopBlockSet.insert(InnerPH).second)
1791           // The only way to reach the preheader is through the loop body
1792           // itself so if it has been visited the loop is already handled.
1793           continue;
1794 
1795         // Insert all of the blocks (other than those already present) into
1796         // the loop set. We expect at least the block that led us to find the
1797         // inner loop to be in the block set, but we may also have other loop
1798         // blocks if they were already enqueued as predecessors of some other
1799         // outer loop block.
1800         for (auto *InnerBB : InnerL->blocks()) {
1801           if (InnerBB == BB) {
1802             assert(LoopBlockSet.count(InnerBB) &&
1803                    "Block should already be in the set!");
1804             continue;
1805           }
1806 
1807           LoopBlockSet.insert(InnerBB);
1808         }
1809 
1810         // Add the preheader to the worklist so we will continue past the
1811         // loop body.
1812         Worklist.push_back(InnerPH);
1813         continue;
1814       }
1815 
1816     // Insert any predecessors that were in the original loop into the new
1817     // set, and if the insert is successful, add them to the worklist.
1818     for (auto *Pred : predecessors(BB))
1819       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1820         Worklist.push_back(Pred);
1821   }
1822 
1823   assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1824 
1825   // We've found all the blocks participating in the loop, return our completed
1826   // set.
1827   return LoopBlockSet;
1828 }
1829 
1830 /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1831 ///
1832 /// The removal may have removed some child loops entirely but cannot have
1833 /// disturbed any remaining child loops. However, they may need to be hoisted
1834 /// to the parent loop (or to be top-level loops). The original loop may be
1835 /// completely removed.
1836 ///
1837 /// The sibling loops resulting from this update are returned. If the original
1838 /// loop remains a valid loop, it will be the first entry in this list with all
1839 /// of the newly sibling loops following it.
1840 ///
1841 /// Returns true if the loop remains a loop after unswitching, and false if it
1842 /// is no longer a loop after unswitching (and should not continue to be
1843 /// referenced).
1844 static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1845                                      LoopInfo &LI,
1846                                      SmallVectorImpl<Loop *> &HoistedLoops,
1847                                      ScalarEvolution *SE) {
1848   auto *PH = L.getLoopPreheader();
1849 
1850   // Compute the actual parent loop from the exit blocks. Because we may have
1851   // pruned some exits the loop may be different from the original parent.
1852   Loop *ParentL = nullptr;
1853   SmallVector<Loop *, 4> ExitLoops;
1854   SmallVector<BasicBlock *, 4> ExitsInLoops;
1855   ExitsInLoops.reserve(ExitBlocks.size());
1856   for (auto *ExitBB : ExitBlocks)
1857     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1858       ExitLoops.push_back(ExitL);
1859       ExitsInLoops.push_back(ExitBB);
1860       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1861         ParentL = ExitL;
1862     }
1863 
1864   // Recompute the blocks participating in this loop. This may be empty if it
1865   // is no longer a loop.
1866   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1867 
1868   // If we still have a loop, we need to re-set the loop's parent as the exit
1869   // block set changing may have moved it within the loop nest. Note that this
1870   // can only happen when this loop has a parent as it can only hoist the loop
1871   // *up* the nest.
1872   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1873     // Remove this loop's (original) blocks from all of the intervening loops.
1874     for (Loop *IL = L.getParentLoop(); IL != ParentL;
1875          IL = IL->getParentLoop()) {
1876       IL->getBlocksSet().erase(PH);
1877       for (auto *BB : L.blocks())
1878         IL->getBlocksSet().erase(BB);
1879       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1880         return BB == PH || L.contains(BB);
1881       });
1882     }
1883 
1884     LI.changeLoopFor(PH, ParentL);
1885     L.getParentLoop()->removeChildLoop(&L);
1886     if (ParentL)
1887       ParentL->addChildLoop(&L);
1888     else
1889       LI.addTopLevelLoop(&L);
1890   }
1891 
1892   // Now we update all the blocks which are no longer within the loop.
1893   auto &Blocks = L.getBlocksVector();
1894   auto BlocksSplitI =
1895       LoopBlockSet.empty()
1896           ? Blocks.begin()
1897           : std::stable_partition(
1898                 Blocks.begin(), Blocks.end(),
1899                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1900 
1901   // Before we erase the list of unlooped blocks, build a set of them.
1902   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1903   if (LoopBlockSet.empty())
1904     UnloopedBlocks.insert(PH);
1905 
1906   // Now erase these blocks from the loop.
1907   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1908     L.getBlocksSet().erase(BB);
1909   Blocks.erase(BlocksSplitI, Blocks.end());
1910 
1911   // Sort the exits in ascending loop depth, we'll work backwards across these
1912   // to process them inside out.
1913   llvm::stable_sort(ExitsInLoops, [&](BasicBlock *LHS, BasicBlock *RHS) {
1914     return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1915   });
1916 
1917   // We'll build up a set for each exit loop.
1918   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1919   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1920 
1921   auto RemoveUnloopedBlocksFromLoop =
1922       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1923         for (auto *BB : UnloopedBlocks)
1924           L.getBlocksSet().erase(BB);
1925         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1926           return UnloopedBlocks.count(BB);
1927         });
1928       };
1929 
1930   SmallVector<BasicBlock *, 16> Worklist;
1931   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1932     assert(Worklist.empty() && "Didn't clear worklist!");
1933     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1934 
1935     // Grab the next exit block, in decreasing loop depth order.
1936     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1937     Loop &ExitL = *LI.getLoopFor(ExitBB);
1938     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1939 
1940     // Erase all of the unlooped blocks from the loops between the previous
1941     // exit loop and this exit loop. This works because the ExitInLoops list is
1942     // sorted in increasing order of loop depth and thus we visit loops in
1943     // decreasing order of loop depth.
1944     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1945       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1946 
1947     // Walk the CFG back until we hit the cloned PH adding everything reachable
1948     // and in the unlooped set to this exit block's loop.
1949     Worklist.push_back(ExitBB);
1950     do {
1951       BasicBlock *BB = Worklist.pop_back_val();
1952       // We can stop recursing at the cloned preheader (if we get there).
1953       if (BB == PH)
1954         continue;
1955 
1956       for (BasicBlock *PredBB : predecessors(BB)) {
1957         // If this pred has already been moved to our set or is part of some
1958         // (inner) loop, no update needed.
1959         if (!UnloopedBlocks.erase(PredBB)) {
1960           assert((NewExitLoopBlocks.count(PredBB) ||
1961                   ExitL.contains(LI.getLoopFor(PredBB))) &&
1962                  "Predecessor not in a nested loop (or already visited)!");
1963           continue;
1964         }
1965 
1966         // We just insert into the loop set here. We'll add these blocks to the
1967         // exit loop after we build up the set in a deterministic order rather
1968         // than the predecessor-influenced visit order.
1969         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1970         (void)Inserted;
1971         assert(Inserted && "Should only visit an unlooped block once!");
1972 
1973         // And recurse through to its predecessors.
1974         Worklist.push_back(PredBB);
1975       }
1976     } while (!Worklist.empty());
1977 
1978     // If blocks in this exit loop were directly part of the original loop (as
1979     // opposed to a child loop) update the map to point to this exit loop. This
1980     // just updates a map and so the fact that the order is unstable is fine.
1981     for (auto *BB : NewExitLoopBlocks)
1982       if (Loop *BBL = LI.getLoopFor(BB))
1983         if (BBL == &L || !L.contains(BBL))
1984           LI.changeLoopFor(BB, &ExitL);
1985 
1986     // We will remove the remaining unlooped blocks from this loop in the next
1987     // iteration or below.
1988     NewExitLoopBlocks.clear();
1989   }
1990 
1991   // Any remaining unlooped blocks are no longer part of any loop unless they
1992   // are part of some child loop.
1993   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1994     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1995   for (auto *BB : UnloopedBlocks)
1996     if (Loop *BBL = LI.getLoopFor(BB))
1997       if (BBL == &L || !L.contains(BBL))
1998         LI.changeLoopFor(BB, nullptr);
1999 
2000   // Sink all the child loops whose headers are no longer in the loop set to
2001   // the parent (or to be top level loops). We reach into the loop and directly
2002   // update its subloop vector to make this batch update efficient.
2003   auto &SubLoops = L.getSubLoopsVector();
2004   auto SubLoopsSplitI =
2005       LoopBlockSet.empty()
2006           ? SubLoops.begin()
2007           : std::stable_partition(
2008                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
2009                   return LoopBlockSet.count(SubL->getHeader());
2010                 });
2011   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
2012     HoistedLoops.push_back(HoistedL);
2013     HoistedL->setParentLoop(nullptr);
2014 
2015     // To compute the new parent of this hoisted loop we look at where we
2016     // placed the preheader above. We can't lookup the header itself because we
2017     // retained the mapping from the header to the hoisted loop. But the
2018     // preheader and header should have the exact same new parent computed
2019     // based on the set of exit blocks from the original loop as the preheader
2020     // is a predecessor of the header and so reached in the reverse walk. And
2021     // because the loops were all in simplified form the preheader of the
2022     // hoisted loop can't be part of some *other* loop.
2023     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
2024       NewParentL->addChildLoop(HoistedL);
2025     else
2026       LI.addTopLevelLoop(HoistedL);
2027   }
2028   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
2029 
2030   // Actually delete the loop if nothing remained within it.
2031   if (Blocks.empty()) {
2032     assert(SubLoops.empty() &&
2033            "Failed to remove all subloops from the original loop!");
2034     if (Loop *ParentL = L.getParentLoop())
2035       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
2036     else
2037       LI.removeLoop(llvm::find(LI, &L));
2038     // markLoopAsDeleted for L should be triggered by the caller (it is typically
2039     // done by using the UnswitchCB callback).
2040     if (SE)
2041       SE->forgetBlockAndLoopDispositions();
2042     LI.destroy(&L);
2043     return false;
2044   }
2045 
2046   return true;
2047 }
2048 
2049 /// Helper to visit a dominator subtree, invoking a callable on each node.
2050 ///
2051 /// Returning false at any point will stop walking past that node of the tree.
2052 template <typename CallableT>
2053 void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
2054   SmallVector<DomTreeNode *, 4> DomWorklist;
2055   DomWorklist.push_back(DT[BB]);
2056 #ifndef NDEBUG
2057   SmallPtrSet<DomTreeNode *, 4> Visited;
2058   Visited.insert(DT[BB]);
2059 #endif
2060   do {
2061     DomTreeNode *N = DomWorklist.pop_back_val();
2062 
2063     // Visit this node.
2064     if (!Callable(N->getBlock()))
2065       continue;
2066 
2067     // Accumulate the child nodes.
2068     for (DomTreeNode *ChildN : *N) {
2069       assert(Visited.insert(ChildN).second &&
2070              "Cannot visit a node twice when walking a tree!");
2071       DomWorklist.push_back(ChildN);
2072     }
2073   } while (!DomWorklist.empty());
2074 }
2075 
2076 static void unswitchNontrivialInvariants(
2077     Loop &L, Instruction &TI, ArrayRef<Value *> Invariants,
2078     IVConditionInfo &PartialIVInfo, DominatorTree &DT, LoopInfo &LI,
2079     AssumptionCache &AC,
2080     function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
2081     ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
2082     function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
2083   auto *ParentBB = TI.getParent();
2084   BranchInst *BI = dyn_cast<BranchInst>(&TI);
2085   SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
2086 
2087   // We can only unswitch switches, conditional branches with an invariant
2088   // condition, or combining invariant conditions with an instruction or
2089   // partially invariant instructions.
2090   assert((SI || (BI && BI->isConditional())) &&
2091          "Can only unswitch switches and conditional branch!");
2092   bool PartiallyInvariant = !PartialIVInfo.InstToDuplicate.empty();
2093   bool FullUnswitch =
2094       SI || (skipTrivialSelect(BI->getCondition()) == Invariants[0] &&
2095              !PartiallyInvariant);
2096   if (FullUnswitch)
2097     assert(Invariants.size() == 1 &&
2098            "Cannot have other invariants with full unswitching!");
2099   else
2100     assert(isa<Instruction>(skipTrivialSelect(BI->getCondition())) &&
2101            "Partial unswitching requires an instruction as the condition!");
2102 
2103   if (MSSAU && VerifyMemorySSA)
2104     MSSAU->getMemorySSA()->verifyMemorySSA();
2105 
2106   // Constant and BBs tracking the cloned and continuing successor. When we are
2107   // unswitching the entire condition, this can just be trivially chosen to
2108   // unswitch towards `true`. However, when we are unswitching a set of
2109   // invariants combined with `and` or `or` or partially invariant instructions,
2110   // the combining operation determines the best direction to unswitch: we want
2111   // to unswitch the direction that will collapse the branch.
2112   bool Direction = true;
2113   int ClonedSucc = 0;
2114   if (!FullUnswitch) {
2115     Value *Cond = skipTrivialSelect(BI->getCondition());
2116     (void)Cond;
2117     assert(((match(Cond, m_LogicalAnd()) ^ match(Cond, m_LogicalOr())) ||
2118             PartiallyInvariant) &&
2119            "Only `or`, `and`, an `select`, partially invariant instructions "
2120            "can combine invariants being unswitched.");
2121     if (!match(Cond, m_LogicalOr())) {
2122       if (match(Cond, m_LogicalAnd()) ||
2123           (PartiallyInvariant && !PartialIVInfo.KnownValue->isOneValue())) {
2124         Direction = false;
2125         ClonedSucc = 1;
2126       }
2127     }
2128   }
2129 
2130   BasicBlock *RetainedSuccBB =
2131       BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
2132   SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
2133   if (BI)
2134     UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
2135   else
2136     for (auto Case : SI->cases())
2137       if (Case.getCaseSuccessor() != RetainedSuccBB)
2138         UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
2139 
2140   assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
2141          "Should not unswitch the same successor we are retaining!");
2142 
2143   // The branch should be in this exact loop. Any inner loop's invariant branch
2144   // should be handled by unswitching that inner loop. The caller of this
2145   // routine should filter out any candidates that remain (but were skipped for
2146   // whatever reason).
2147   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
2148 
2149   // Compute the parent loop now before we start hacking on things.
2150   Loop *ParentL = L.getParentLoop();
2151   // Get blocks in RPO order for MSSA update, before changing the CFG.
2152   LoopBlocksRPO LBRPO(&L);
2153   if (MSSAU)
2154     LBRPO.perform(&LI);
2155 
2156   // Compute the outer-most loop containing one of our exit blocks. This is the
2157   // furthest up our loopnest which can be mutated, which we will use below to
2158   // update things.
2159   Loop *OuterExitL = &L;
2160   SmallVector<BasicBlock *, 4> ExitBlocks;
2161   L.getUniqueExitBlocks(ExitBlocks);
2162   for (auto *ExitBB : ExitBlocks) {
2163     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
2164     if (!NewOuterExitL) {
2165       // We exited the entire nest with this block, so we're done.
2166       OuterExitL = nullptr;
2167       break;
2168     }
2169     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
2170       OuterExitL = NewOuterExitL;
2171   }
2172 
2173   // At this point, we're definitely going to unswitch something so invalidate
2174   // any cached information in ScalarEvolution for the outer most loop
2175   // containing an exit block and all nested loops.
2176   if (SE) {
2177     if (OuterExitL)
2178       SE->forgetLoop(OuterExitL);
2179     else
2180       SE->forgetTopmostLoop(&L);
2181     SE->forgetBlockAndLoopDispositions();
2182   }
2183 
2184   bool InsertFreeze = false;
2185   if (FreezeLoopUnswitchCond) {
2186     ICFLoopSafetyInfo SafetyInfo;
2187     SafetyInfo.computeLoopSafetyInfo(&L);
2188     InsertFreeze = !SafetyInfo.isGuaranteedToExecute(TI, &DT, &L);
2189   }
2190 
2191   // If the edge from this terminator to a successor dominates that successor,
2192   // store a map from each block in its dominator subtree to it. This lets us
2193   // tell when cloning for a particular successor if a block is dominated by
2194   // some *other* successor with a single data structure. We use this to
2195   // significantly reduce cloning.
2196   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
2197   for (auto *SuccBB : llvm::concat<BasicBlock *const>(
2198            makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
2199     if (SuccBB->getUniquePredecessor() ||
2200         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2201           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
2202         }))
2203       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
2204         DominatingSucc[BB] = SuccBB;
2205         return true;
2206       });
2207 
2208   // Split the preheader, so that we know that there is a safe place to insert
2209   // the conditional branch. We will change the preheader to have a conditional
2210   // branch on LoopCond. The original preheader will become the split point
2211   // between the unswitched versions, and we will have a new preheader for the
2212   // original loop.
2213   BasicBlock *SplitBB = L.getLoopPreheader();
2214   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
2215 
2216   // Keep track of the dominator tree updates needed.
2217   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2218 
2219   // Clone the loop for each unswitched successor.
2220   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2221   VMaps.reserve(UnswitchedSuccBBs.size());
2222   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2223   for (auto *SuccBB : UnswitchedSuccBBs) {
2224     VMaps.emplace_back(new ValueToValueMapTy());
2225     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2226         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2227         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU, SE);
2228   }
2229 
2230   // Drop metadata if we may break its semantics by moving this instr into the
2231   // split block.
2232   if (TI.getMetadata(LLVMContext::MD_make_implicit)) {
2233     if (DropNonTrivialImplicitNullChecks)
2234       // Do not spend time trying to understand if we can keep it, just drop it
2235       // to save compile time.
2236       TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
2237     else {
2238       // It is only legal to preserve make.implicit metadata if we are
2239       // guaranteed no reach implicit null check after following this branch.
2240       ICFLoopSafetyInfo SafetyInfo;
2241       SafetyInfo.computeLoopSafetyInfo(&L);
2242       if (!SafetyInfo.isGuaranteedToExecute(TI, &DT, &L))
2243         TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
2244     }
2245   }
2246 
2247   // The stitching of the branched code back together depends on whether we're
2248   // doing full unswitching or not with the exception that we always want to
2249   // nuke the initial terminator placed in the split block.
2250   SplitBB->getTerminator()->eraseFromParent();
2251   if (FullUnswitch) {
2252     // Splice the terminator from the original loop and rewrite its
2253     // successors.
2254     SplitBB->splice(SplitBB->end(), ParentBB, TI.getIterator());
2255 
2256     // Keep a clone of the terminator for MSSA updates.
2257     Instruction *NewTI = TI.clone();
2258     NewTI->insertInto(ParentBB, ParentBB->end());
2259 
2260     // First wire up the moved terminator to the preheaders.
2261     if (BI) {
2262       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2263       BI->setSuccessor(ClonedSucc, ClonedPH);
2264       BI->setSuccessor(1 - ClonedSucc, LoopPH);
2265       Value *Cond = skipTrivialSelect(BI->getCondition());
2266       if (InsertFreeze) {
2267         if (!isGuaranteedNotToBeUndefOrPoison(Cond, &AC, BI, &DT))
2268           Cond = new FreezeInst(Cond, Cond->getName() + ".fr", BI);
2269       }
2270       BI->setCondition(Cond);
2271       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2272     } else {
2273       assert(SI && "Must either be a branch or switch!");
2274 
2275       // Walk the cases and directly update their successors.
2276       assert(SI->getDefaultDest() == RetainedSuccBB &&
2277              "Not retaining default successor!");
2278       SI->setDefaultDest(LoopPH);
2279       for (const auto &Case : SI->cases())
2280         if (Case.getCaseSuccessor() == RetainedSuccBB)
2281           Case.setSuccessor(LoopPH);
2282         else
2283           Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2284 
2285       if (InsertFreeze) {
2286         auto Cond = SI->getCondition();
2287         if (!isGuaranteedNotToBeUndefOrPoison(Cond, &AC, SI, &DT))
2288           SI->setCondition(new FreezeInst(Cond, Cond->getName() + ".fr", SI));
2289       }
2290       // We need to use the set to populate domtree updates as even when there
2291       // are multiple cases pointing at the same successor we only want to
2292       // remove and insert one edge in the domtree.
2293       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2294         DTUpdates.push_back(
2295             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2296     }
2297 
2298     if (MSSAU) {
2299       DT.applyUpdates(DTUpdates);
2300       DTUpdates.clear();
2301 
2302       // Remove all but one edge to the retained block and all unswitched
2303       // blocks. This is to avoid having duplicate entries in the cloned Phis,
2304       // when we know we only keep a single edge for each case.
2305       MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2306       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2307         MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2308 
2309       for (auto &VMap : VMaps)
2310         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2311                                    /*IgnoreIncomingWithNoClones=*/true);
2312       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2313 
2314       // Remove all edges to unswitched blocks.
2315       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2316         MSSAU->removeEdge(ParentBB, SuccBB);
2317     }
2318 
2319     // Now unhook the successor relationship as we'll be replacing
2320     // the terminator with a direct branch. This is much simpler for branches
2321     // than switches so we handle those first.
2322     if (BI) {
2323       // Remove the parent as a predecessor of the unswitched successor.
2324       assert(UnswitchedSuccBBs.size() == 1 &&
2325              "Only one possible unswitched block for a branch!");
2326       BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2327       UnswitchedSuccBB->removePredecessor(ParentBB,
2328                                           /*KeepOneInputPHIs*/ true);
2329       DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2330     } else {
2331       // Note that we actually want to remove the parent block as a predecessor
2332       // of *every* case successor. The case successor is either unswitched,
2333       // completely eliminating an edge from the parent to that successor, or it
2334       // is a duplicate edge to the retained successor as the retained successor
2335       // is always the default successor and as we'll replace this with a direct
2336       // branch we no longer need the duplicate entries in the PHI nodes.
2337       SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2338       assert(NewSI->getDefaultDest() == RetainedSuccBB &&
2339              "Not retaining default successor!");
2340       for (const auto &Case : NewSI->cases())
2341         Case.getCaseSuccessor()->removePredecessor(
2342             ParentBB,
2343             /*KeepOneInputPHIs*/ true);
2344 
2345       // We need to use the set to populate domtree updates as even when there
2346       // are multiple cases pointing at the same successor we only want to
2347       // remove and insert one edge in the domtree.
2348       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2349         DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2350     }
2351 
2352     // After MSSAU update, remove the cloned terminator instruction NewTI.
2353     ParentBB->getTerminator()->eraseFromParent();
2354 
2355     // Create a new unconditional branch to the continuing block (as opposed to
2356     // the one cloned).
2357     BranchInst::Create(RetainedSuccBB, ParentBB);
2358   } else {
2359     assert(BI && "Only branches have partial unswitching.");
2360     assert(UnswitchedSuccBBs.size() == 1 &&
2361            "Only one possible unswitched block for a branch!");
2362     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2363     // When doing a partial unswitch, we have to do a bit more work to build up
2364     // the branch in the split block.
2365     if (PartiallyInvariant)
2366       buildPartialInvariantUnswitchConditionalBranch(
2367           *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, L, MSSAU);
2368     else {
2369       buildPartialUnswitchConditionalBranch(
2370           *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH,
2371           FreezeLoopUnswitchCond, BI, &AC, DT);
2372     }
2373     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2374 
2375     if (MSSAU) {
2376       DT.applyUpdates(DTUpdates);
2377       DTUpdates.clear();
2378 
2379       // Perform MSSA cloning updates.
2380       for (auto &VMap : VMaps)
2381         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2382                                    /*IgnoreIncomingWithNoClones=*/true);
2383       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2384     }
2385   }
2386 
2387   // Apply the updates accumulated above to get an up-to-date dominator tree.
2388   DT.applyUpdates(DTUpdates);
2389 
2390   // Now that we have an accurate dominator tree, first delete the dead cloned
2391   // blocks so that we can accurately build any cloned loops. It is important to
2392   // not delete the blocks from the original loop yet because we still want to
2393   // reference the original loop to understand the cloned loop's structure.
2394   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
2395 
2396   // Build the cloned loop structure itself. This may be substantially
2397   // different from the original structure due to the simplified CFG. This also
2398   // handles inserting all the cloned blocks into the correct loops.
2399   SmallVector<Loop *, 4> NonChildClonedLoops;
2400   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2401     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
2402 
2403   // Now that our cloned loops have been built, we can update the original loop.
2404   // First we delete the dead blocks from it and then we rebuild the loop
2405   // structure taking these deletions into account.
2406   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU, SE,DestroyLoopCB);
2407 
2408   if (MSSAU && VerifyMemorySSA)
2409     MSSAU->getMemorySSA()->verifyMemorySSA();
2410 
2411   SmallVector<Loop *, 4> HoistedLoops;
2412   bool IsStillLoop =
2413       rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops, SE);
2414 
2415   if (MSSAU && VerifyMemorySSA)
2416     MSSAU->getMemorySSA()->verifyMemorySSA();
2417 
2418   // This transformation has a high risk of corrupting the dominator tree, and
2419   // the below steps to rebuild loop structures will result in hard to debug
2420   // errors in that case so verify that the dominator tree is sane first.
2421   // FIXME: Remove this when the bugs stop showing up and rely on existing
2422   // verification steps.
2423   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2424 
2425   if (BI && !PartiallyInvariant) {
2426     // If we unswitched a branch which collapses the condition to a known
2427     // constant we want to replace all the uses of the invariants within both
2428     // the original and cloned blocks. We do this here so that we can use the
2429     // now updated dominator tree to identify which side the users are on.
2430     assert(UnswitchedSuccBBs.size() == 1 &&
2431            "Only one possible unswitched block for a branch!");
2432     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2433 
2434     // When considering multiple partially-unswitched invariants
2435     // we cant just go replace them with constants in both branches.
2436     //
2437     // For 'AND' we infer that true branch ("continue") means true
2438     // for each invariant operand.
2439     // For 'OR' we can infer that false branch ("continue") means false
2440     // for each invariant operand.
2441     // So it happens that for multiple-partial case we dont replace
2442     // in the unswitched branch.
2443     bool ReplaceUnswitched =
2444         FullUnswitch || (Invariants.size() == 1) || PartiallyInvariant;
2445 
2446     ConstantInt *UnswitchedReplacement =
2447         Direction ? ConstantInt::getTrue(BI->getContext())
2448                   : ConstantInt::getFalse(BI->getContext());
2449     ConstantInt *ContinueReplacement =
2450         Direction ? ConstantInt::getFalse(BI->getContext())
2451                   : ConstantInt::getTrue(BI->getContext());
2452     for (Value *Invariant : Invariants) {
2453       assert(!isa<Constant>(Invariant) &&
2454              "Should not be replacing constant values!");
2455       // Use make_early_inc_range here as set invalidates the iterator.
2456       for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
2457         Instruction *UserI = dyn_cast<Instruction>(U.getUser());
2458         if (!UserI)
2459           continue;
2460 
2461         // Replace it with the 'continue' side if in the main loop body, and the
2462         // unswitched if in the cloned blocks.
2463         if (DT.dominates(LoopPH, UserI->getParent()))
2464           U.set(ContinueReplacement);
2465         else if (ReplaceUnswitched &&
2466                  DT.dominates(ClonedPH, UserI->getParent()))
2467           U.set(UnswitchedReplacement);
2468       }
2469     }
2470   }
2471 
2472   // We can change which blocks are exit blocks of all the cloned sibling
2473   // loops, the current loop, and any parent loops which shared exit blocks
2474   // with the current loop. As a consequence, we need to re-form LCSSA for
2475   // them. But we shouldn't need to re-form LCSSA for any child loops.
2476   // FIXME: This could be made more efficient by tracking which exit blocks are
2477   // new, and focusing on them, but that isn't likely to be necessary.
2478   //
2479   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2480   // loop nest and update every loop that could have had its exits changed. We
2481   // also need to cover any intervening loops. We add all of these loops to
2482   // a list and sort them by loop depth to achieve this without updating
2483   // unnecessary loops.
2484   auto UpdateLoop = [&](Loop &UpdateL) {
2485 #ifndef NDEBUG
2486     UpdateL.verifyLoop();
2487     for (Loop *ChildL : UpdateL) {
2488       ChildL->verifyLoop();
2489       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2490              "Perturbed a child loop's LCSSA form!");
2491     }
2492 #endif
2493     // First build LCSSA for this loop so that we can preserve it when
2494     // forming dedicated exits. We don't want to perturb some other loop's
2495     // LCSSA while doing that CFG edit.
2496     formLCSSA(UpdateL, DT, &LI, SE);
2497 
2498     // For loops reached by this loop's original exit blocks we may
2499     // introduced new, non-dedicated exits. At least try to re-form dedicated
2500     // exits for these loops. This may fail if they couldn't have dedicated
2501     // exits to start with.
2502     formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
2503   };
2504 
2505   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2506   // and we can do it in any order as they don't nest relative to each other.
2507   //
2508   // Also check if any of the loops we have updated have become top-level loops
2509   // as that will necessitate widening the outer loop scope.
2510   for (Loop *UpdatedL :
2511        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2512     UpdateLoop(*UpdatedL);
2513     if (UpdatedL->isOutermost())
2514       OuterExitL = nullptr;
2515   }
2516   if (IsStillLoop) {
2517     UpdateLoop(L);
2518     if (L.isOutermost())
2519       OuterExitL = nullptr;
2520   }
2521 
2522   // If the original loop had exit blocks, walk up through the outer most loop
2523   // of those exit blocks to update LCSSA and form updated dedicated exits.
2524   if (OuterExitL != &L)
2525     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2526          OuterL = OuterL->getParentLoop())
2527       UpdateLoop(*OuterL);
2528 
2529 #ifndef NDEBUG
2530   // Verify the entire loop structure to catch any incorrect updates before we
2531   // progress in the pass pipeline.
2532   LI.verify(DT);
2533 #endif
2534 
2535   // Now that we've unswitched something, make callbacks to report the changes.
2536   // For that we need to merge together the updated loops and the cloned loops
2537   // and check whether the original loop survived.
2538   SmallVector<Loop *, 4> SibLoops;
2539   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2540     if (UpdatedL->getParentLoop() == ParentL)
2541       SibLoops.push_back(UpdatedL);
2542   UnswitchCB(IsStillLoop, PartiallyInvariant, SibLoops);
2543 
2544   if (MSSAU && VerifyMemorySSA)
2545     MSSAU->getMemorySSA()->verifyMemorySSA();
2546 
2547   if (BI)
2548     ++NumBranches;
2549   else
2550     ++NumSwitches;
2551 }
2552 
2553 /// Recursively compute the cost of a dominator subtree based on the per-block
2554 /// cost map provided.
2555 ///
2556 /// The recursive computation is memozied into the provided DT-indexed cost map
2557 /// to allow querying it for most nodes in the domtree without it becoming
2558 /// quadratic.
2559 static InstructionCost computeDomSubtreeCost(
2560     DomTreeNode &N,
2561     const SmallDenseMap<BasicBlock *, InstructionCost, 4> &BBCostMap,
2562     SmallDenseMap<DomTreeNode *, InstructionCost, 4> &DTCostMap) {
2563   // Don't accumulate cost (or recurse through) blocks not in our block cost
2564   // map and thus not part of the duplication cost being considered.
2565   auto BBCostIt = BBCostMap.find(N.getBlock());
2566   if (BBCostIt == BBCostMap.end())
2567     return 0;
2568 
2569   // Lookup this node to see if we already computed its cost.
2570   auto DTCostIt = DTCostMap.find(&N);
2571   if (DTCostIt != DTCostMap.end())
2572     return DTCostIt->second;
2573 
2574   // If not, we have to compute it. We can't use insert above and update
2575   // because computing the cost may insert more things into the map.
2576   InstructionCost Cost = std::accumulate(
2577       N.begin(), N.end(), BBCostIt->second,
2578       [&](InstructionCost Sum, DomTreeNode *ChildN) -> InstructionCost {
2579         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2580       });
2581   bool Inserted = DTCostMap.insert({&N, Cost}).second;
2582   (void)Inserted;
2583   assert(Inserted && "Should not insert a node while visiting children!");
2584   return Cost;
2585 }
2586 
2587 /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2588 /// making the following replacement:
2589 ///
2590 ///   --code before guard--
2591 ///   call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2592 ///   --code after guard--
2593 ///
2594 /// into
2595 ///
2596 ///   --code before guard--
2597 ///   br i1 %cond, label %guarded, label %deopt
2598 ///
2599 /// guarded:
2600 ///   --code after guard--
2601 ///
2602 /// deopt:
2603 ///   call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2604 ///   unreachable
2605 ///
2606 /// It also makes all relevant DT and LI updates, so that all structures are in
2607 /// valid state after this transform.
2608 static BranchInst *turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2609                                        DominatorTree &DT, LoopInfo &LI,
2610                                        MemorySSAUpdater *MSSAU) {
2611   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2612   LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2613   BasicBlock *CheckBB = GI->getParent();
2614 
2615   if (MSSAU && VerifyMemorySSA)
2616      MSSAU->getMemorySSA()->verifyMemorySSA();
2617 
2618   // Remove all CheckBB's successors from DomTree. A block can be seen among
2619   // successors more than once, but for DomTree it should be added only once.
2620   SmallPtrSet<BasicBlock *, 4> Successors;
2621   for (auto *Succ : successors(CheckBB))
2622     if (Successors.insert(Succ).second)
2623       DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2624 
2625   Instruction *DeoptBlockTerm =
2626       SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2627   BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2628   // SplitBlockAndInsertIfThen inserts control flow that branches to
2629   // DeoptBlockTerm if the condition is true.  We want the opposite.
2630   CheckBI->swapSuccessors();
2631 
2632   BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2633   GuardedBlock->setName("guarded");
2634   CheckBI->getSuccessor(1)->setName("deopt");
2635   BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2636 
2637   if (MSSAU)
2638     MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2639 
2640   GI->moveBefore(DeoptBlockTerm);
2641   GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2642 
2643   // Add new successors of CheckBB into DomTree.
2644   for (auto *Succ : successors(CheckBB))
2645     DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2646 
2647   // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2648   // successors.
2649   for (auto *Succ : Successors)
2650     DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2651 
2652   // Make proper changes to DT.
2653   DT.applyUpdates(DTUpdates);
2654   // Inform LI of a new loop block.
2655   L.addBasicBlockToLoop(GuardedBlock, LI);
2656 
2657   if (MSSAU) {
2658     MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2659     MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator);
2660     if (VerifyMemorySSA)
2661       MSSAU->getMemorySSA()->verifyMemorySSA();
2662   }
2663 
2664   ++NumGuards;
2665   return CheckBI;
2666 }
2667 
2668 /// Cost multiplier is a way to limit potentially exponential behavior
2669 /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2670 /// candidates available. Also accounting for the number of "sibling" loops with
2671 /// the idea to account for previous unswitches that already happened on this
2672 /// cluster of loops. There was an attempt to keep this formula simple,
2673 /// just enough to limit the worst case behavior. Even if it is not that simple
2674 /// now it is still not an attempt to provide a detailed heuristic size
2675 /// prediction.
2676 ///
2677 /// TODO: Make a proper accounting of "explosion" effect for all kinds of
2678 /// unswitch candidates, making adequate predictions instead of wild guesses.
2679 /// That requires knowing not just the number of "remaining" candidates but
2680 /// also costs of unswitching for each of these candidates.
2681 static int CalculateUnswitchCostMultiplier(
2682     const Instruction &TI, const Loop &L, const LoopInfo &LI,
2683     const DominatorTree &DT,
2684     ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates) {
2685 
2686   // Guards and other exiting conditions do not contribute to exponential
2687   // explosion as soon as they dominate the latch (otherwise there might be
2688   // another path to the latch remaining that does not allow to eliminate the
2689   // loop copy on unswitch).
2690   const BasicBlock *Latch = L.getLoopLatch();
2691   const BasicBlock *CondBlock = TI.getParent();
2692   if (DT.dominates(CondBlock, Latch) &&
2693       (isGuard(&TI) ||
2694        llvm::count_if(successors(&TI), [&L](const BasicBlock *SuccBB) {
2695          return L.contains(SuccBB);
2696        }) <= 1)) {
2697     NumCostMultiplierSkipped++;
2698     return 1;
2699   }
2700 
2701   auto *ParentL = L.getParentLoop();
2702   int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2703                                : std::distance(LI.begin(), LI.end()));
2704   // Count amount of clones that all the candidates might cause during
2705   // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2706   int UnswitchedClones = 0;
2707   for (auto Candidate : UnswitchCandidates) {
2708     const Instruction *CI = Candidate.TI;
2709     const BasicBlock *CondBlock = CI->getParent();
2710     bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2711     if (isGuard(CI)) {
2712       if (!SkipExitingSuccessors)
2713         UnswitchedClones++;
2714       continue;
2715     }
2716     int NonExitingSuccessors =
2717         llvm::count_if(successors(CondBlock),
2718                        [SkipExitingSuccessors, &L](const BasicBlock *SuccBB) {
2719           return !SkipExitingSuccessors || L.contains(SuccBB);
2720         });
2721     UnswitchedClones += Log2_32(NonExitingSuccessors);
2722   }
2723 
2724   // Ignore up to the "unscaled candidates" number of unswitch candidates
2725   // when calculating the power-of-two scaling of the cost. The main idea
2726   // with this control is to allow a small number of unswitches to happen
2727   // and rely more on siblings multiplier (see below) when the number
2728   // of candidates is small.
2729   unsigned ClonesPower =
2730       std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2731 
2732   // Allowing top-level loops to spread a bit more than nested ones.
2733   int SiblingsMultiplier =
2734       std::max((ParentL ? SiblingsCount
2735                         : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2736                1);
2737   // Compute the cost multiplier in a way that won't overflow by saturating
2738   // at an upper bound.
2739   int CostMultiplier;
2740   if (ClonesPower > Log2_32(UnswitchThreshold) ||
2741       SiblingsMultiplier > UnswitchThreshold)
2742     CostMultiplier = UnswitchThreshold;
2743   else
2744     CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2745                               (int)UnswitchThreshold);
2746 
2747   LLVM_DEBUG(dbgs() << "  Computed multiplier  " << CostMultiplier
2748                     << " (siblings " << SiblingsMultiplier << " * clones "
2749                     << (1 << ClonesPower) << ")"
2750                     << " for unswitch candidate: " << TI << "\n");
2751   return CostMultiplier;
2752 }
2753 
2754 static bool collectUnswitchCandidates(
2755     SmallVectorImpl<NonTrivialUnswitchCandidate> &UnswitchCandidates,
2756     IVConditionInfo &PartialIVInfo, Instruction *&PartialIVCondBranch,
2757     const Loop &L, const LoopInfo &LI, AAResults &AA,
2758     const MemorySSAUpdater *MSSAU) {
2759   assert(UnswitchCandidates.empty() && "Should be!");
2760   // Whether or not we should also collect guards in the loop.
2761   bool CollectGuards = false;
2762   if (UnswitchGuards) {
2763     auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2764         Intrinsic::getName(Intrinsic::experimental_guard));
2765     if (GuardDecl && !GuardDecl->use_empty())
2766       CollectGuards = true;
2767   }
2768 
2769   for (auto *BB : L.blocks()) {
2770     if (LI.getLoopFor(BB) != &L)
2771       continue;
2772 
2773     if (CollectGuards)
2774       for (auto &I : *BB)
2775         if (isGuard(&I)) {
2776           auto *Cond =
2777               skipTrivialSelect(cast<IntrinsicInst>(&I)->getArgOperand(0));
2778           // TODO: Support AND, OR conditions and partial unswitching.
2779           if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2780             UnswitchCandidates.push_back({&I, {Cond}});
2781         }
2782 
2783     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2784       // We can only consider fully loop-invariant switch conditions as we need
2785       // to completely eliminate the switch after unswitching.
2786       if (!isa<Constant>(SI->getCondition()) &&
2787           L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
2788         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2789       continue;
2790     }
2791 
2792     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2793     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2794         BI->getSuccessor(0) == BI->getSuccessor(1))
2795       continue;
2796 
2797     Value *Cond = skipTrivialSelect(BI->getCondition());
2798     if (isa<Constant>(Cond))
2799       continue;
2800 
2801     if (L.isLoopInvariant(Cond)) {
2802       UnswitchCandidates.push_back({BI, {Cond}});
2803       continue;
2804     }
2805 
2806     Instruction &CondI = *cast<Instruction>(Cond);
2807     if (match(&CondI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()))) {
2808       TinyPtrVector<Value *> Invariants =
2809           collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2810       if (Invariants.empty())
2811         continue;
2812 
2813       UnswitchCandidates.push_back({BI, std::move(Invariants)});
2814       continue;
2815     }
2816   }
2817 
2818   if (MSSAU && !findOptionMDForLoop(&L, "llvm.loop.unswitch.partial.disable") &&
2819       !any_of(UnswitchCandidates, [&L](auto &TerminatorAndInvariants) {
2820          return TerminatorAndInvariants.TI == L.getHeader()->getTerminator();
2821        })) {
2822     MemorySSA *MSSA = MSSAU->getMemorySSA();
2823     if (auto Info = hasPartialIVCondition(L, MSSAThreshold, *MSSA, AA)) {
2824       LLVM_DEBUG(
2825           dbgs() << "simple-loop-unswitch: Found partially invariant condition "
2826                  << *Info->InstToDuplicate[0] << "\n");
2827       PartialIVInfo = *Info;
2828       PartialIVCondBranch = L.getHeader()->getTerminator();
2829       TinyPtrVector<Value *> ValsToDuplicate;
2830       llvm::append_range(ValsToDuplicate, Info->InstToDuplicate);
2831       UnswitchCandidates.push_back(
2832           {L.getHeader()->getTerminator(), std::move(ValsToDuplicate)});
2833     }
2834   }
2835   return !UnswitchCandidates.empty();
2836 }
2837 
2838 static bool isSafeForNoNTrivialUnswitching(Loop &L, LoopInfo &LI) {
2839   if (!L.isSafeToClone())
2840     return false;
2841   for (auto *BB : L.blocks())
2842     for (auto &I : *BB) {
2843       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
2844         return false;
2845       if (auto *CB = dyn_cast<CallBase>(&I)) {
2846         assert(!CB->cannotDuplicate() && "Checked by L.isSafeToClone().");
2847         if (CB->isConvergent())
2848           return false;
2849       }
2850     }
2851 
2852   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2853   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2854   // irreducible control flow into reducible control flow and introduce new
2855   // loops "out of thin air". If we ever discover important use cases for doing
2856   // this, we can add support to loop unswitch, but it is a lot of complexity
2857   // for what seems little or no real world benefit.
2858   LoopBlocksRPO RPOT(&L);
2859   RPOT.perform(&LI);
2860   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
2861     return false;
2862 
2863   SmallVector<BasicBlock *, 4> ExitBlocks;
2864   L.getUniqueExitBlocks(ExitBlocks);
2865   // We cannot unswitch if exit blocks contain a cleanuppad/catchswitch
2866   // instruction as we don't know how to split those exit blocks.
2867   // FIXME: We should teach SplitBlock to handle this and remove this
2868   // restriction.
2869   for (auto *ExitBB : ExitBlocks) {
2870     auto *I = ExitBB->getFirstNonPHI();
2871     if (isa<CleanupPadInst>(I) || isa<CatchSwitchInst>(I)) {
2872       LLVM_DEBUG(dbgs() << "Cannot unswitch because of cleanuppad/catchswitch "
2873                            "in exit block\n");
2874       return false;
2875     }
2876   }
2877 
2878   return true;
2879 }
2880 
2881 static NonTrivialUnswitchCandidate findBestNonTrivialUnswitchCandidate(
2882     ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates, const Loop &L,
2883     const DominatorTree &DT, const LoopInfo &LI, AssumptionCache &AC,
2884     const TargetTransformInfo &TTI, const IVConditionInfo &PartialIVInfo) {
2885   // Given that unswitching these terminators will require duplicating parts of
2886   // the loop, so we need to be able to model that cost. Compute the ephemeral
2887   // values and set up a data structure to hold per-BB costs. We cache each
2888   // block's cost so that we don't recompute this when considering different
2889   // subsets of the loop for duplication during unswitching.
2890   SmallPtrSet<const Value *, 4> EphValues;
2891   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2892   SmallDenseMap<BasicBlock *, InstructionCost, 4> BBCostMap;
2893 
2894   // Compute the cost of each block, as well as the total loop cost. Also, bail
2895   // out if we see instructions which are incompatible with loop unswitching
2896   // (convergent, noduplicate, or cross-basic-block tokens).
2897   // FIXME: We might be able to safely handle some of these in non-duplicated
2898   // regions.
2899   TargetTransformInfo::TargetCostKind CostKind =
2900       L.getHeader()->getParent()->hasMinSize()
2901       ? TargetTransformInfo::TCK_CodeSize
2902       : TargetTransformInfo::TCK_SizeAndLatency;
2903   InstructionCost LoopCost = 0;
2904   for (auto *BB : L.blocks()) {
2905     InstructionCost Cost = 0;
2906     for (auto &I : *BB) {
2907       if (EphValues.count(&I))
2908         continue;
2909       Cost += TTI.getInstructionCost(&I, CostKind);
2910     }
2911     assert(Cost >= 0 && "Must not have negative costs!");
2912     LoopCost += Cost;
2913     assert(LoopCost >= 0 && "Must not have negative loop costs!");
2914     BBCostMap[BB] = Cost;
2915   }
2916   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
2917 
2918   // Now we find the best candidate by searching for the one with the following
2919   // properties in order:
2920   //
2921   // 1) An unswitching cost below the threshold
2922   // 2) The smallest number of duplicated unswitch candidates (to avoid
2923   //    creating redundant subsequent unswitching)
2924   // 3) The smallest cost after unswitching.
2925   //
2926   // We prioritize reducing fanout of unswitch candidates provided the cost
2927   // remains below the threshold because this has a multiplicative effect.
2928   //
2929   // This requires memoizing each dominator subtree to avoid redundant work.
2930   //
2931   // FIXME: Need to actually do the number of candidates part above.
2932   SmallDenseMap<DomTreeNode *, InstructionCost, 4> DTCostMap;
2933   // Given a terminator which might be unswitched, computes the non-duplicated
2934   // cost for that terminator.
2935   auto ComputeUnswitchedCost = [&](Instruction &TI,
2936                                    bool FullUnswitch) -> InstructionCost {
2937     BasicBlock &BB = *TI.getParent();
2938     SmallPtrSet<BasicBlock *, 4> Visited;
2939 
2940     InstructionCost Cost = 0;
2941     for (BasicBlock *SuccBB : successors(&BB)) {
2942       // Don't count successors more than once.
2943       if (!Visited.insert(SuccBB).second)
2944         continue;
2945 
2946       // If this is a partial unswitch candidate, then it must be a conditional
2947       // branch with a condition of either `or`, `and`, their corresponding
2948       // select forms or partially invariant instructions. In that case, one of
2949       // the successors is necessarily duplicated, so don't even try to remove
2950       // its cost.
2951       if (!FullUnswitch) {
2952         auto &BI = cast<BranchInst>(TI);
2953         Value *Cond = skipTrivialSelect(BI.getCondition());
2954         if (match(Cond, m_LogicalAnd())) {
2955           if (SuccBB == BI.getSuccessor(1))
2956             continue;
2957         } else if (match(Cond, m_LogicalOr())) {
2958           if (SuccBB == BI.getSuccessor(0))
2959             continue;
2960         } else if ((PartialIVInfo.KnownValue->isOneValue() &&
2961                     SuccBB == BI.getSuccessor(0)) ||
2962                    (!PartialIVInfo.KnownValue->isOneValue() &&
2963                     SuccBB == BI.getSuccessor(1)))
2964           continue;
2965       }
2966 
2967       // This successor's domtree will not need to be duplicated after
2968       // unswitching if the edge to the successor dominates it (and thus the
2969       // entire tree). This essentially means there is no other path into this
2970       // subtree and so it will end up live in only one clone of the loop.
2971       if (SuccBB->getUniquePredecessor() ||
2972           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2973             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2974           })) {
2975         Cost += computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2976         assert(Cost <= LoopCost &&
2977                "Non-duplicated cost should never exceed total loop cost!");
2978       }
2979     }
2980 
2981     // Now scale the cost by the number of unique successors minus one. We
2982     // subtract one because there is already at least one copy of the entire
2983     // loop. This is computing the new cost of unswitching a condition.
2984     // Note that guards always have 2 unique successors that are implicit and
2985     // will be materialized if we decide to unswitch it.
2986     int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2987     assert(SuccessorsCount > 1 &&
2988            "Cannot unswitch a condition without multiple distinct successors!");
2989     return (LoopCost - Cost) * (SuccessorsCount - 1);
2990   };
2991 
2992   std::optional<NonTrivialUnswitchCandidate> Best;
2993   for (auto &Candidate : UnswitchCandidates) {
2994     Instruction &TI = *Candidate.TI;
2995     ArrayRef<Value *> Invariants = Candidate.Invariants;
2996     BranchInst *BI = dyn_cast<BranchInst>(&TI);
2997     InstructionCost CandidateCost = ComputeUnswitchedCost(
2998         TI, /*FullUnswitch*/ !BI ||
2999                 (Invariants.size() == 1 &&
3000                  Invariants[0] == skipTrivialSelect(BI->getCondition())));
3001     // Calculate cost multiplier which is a tool to limit potentially
3002     // exponential behavior of loop-unswitch.
3003     if (EnableUnswitchCostMultiplier) {
3004       int CostMultiplier =
3005           CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
3006       assert(
3007           (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
3008           "cost multiplier needs to be in the range of 1..UnswitchThreshold");
3009       CandidateCost *= CostMultiplier;
3010       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
3011                         << " (multiplier: " << CostMultiplier << ")"
3012                         << " for unswitch candidate: " << TI << "\n");
3013     } else {
3014       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
3015                         << " for unswitch candidate: " << TI << "\n");
3016     }
3017 
3018     if (!Best || CandidateCost < Best->Cost) {
3019       Best = Candidate;
3020       Best->Cost = CandidateCost;
3021     }
3022   }
3023   assert(Best && "Must be!");
3024   return *Best;
3025 }
3026 
3027 static bool unswitchBestCondition(
3028     Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
3029     AAResults &AA, TargetTransformInfo &TTI,
3030     function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
3031     ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
3032     function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
3033   // Collect all invariant conditions within this loop (as opposed to an inner
3034   // loop which would be handled when visiting that inner loop).
3035   SmallVector<NonTrivialUnswitchCandidate, 4> UnswitchCandidates;
3036   IVConditionInfo PartialIVInfo;
3037   Instruction *PartialIVCondBranch = nullptr;
3038   // If we didn't find any candidates, we're done.
3039   if (!collectUnswitchCandidates(UnswitchCandidates, PartialIVInfo,
3040                                  PartialIVCondBranch, L, LI, AA, MSSAU))
3041     return false;
3042 
3043   LLVM_DEBUG(
3044       dbgs() << "Considering " << UnswitchCandidates.size()
3045              << " non-trivial loop invariant conditions for unswitching.\n");
3046 
3047   NonTrivialUnswitchCandidate Best = findBestNonTrivialUnswitchCandidate(
3048       UnswitchCandidates, L, DT, LI, AC, TTI, PartialIVInfo);
3049 
3050   assert(Best.TI && "Failed to find loop unswitch candidate");
3051   assert(Best.Cost && "Failed to compute cost");
3052 
3053   if (*Best.Cost >= UnswitchThreshold) {
3054     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: " << *Best.Cost
3055                       << "\n");
3056     return false;
3057   }
3058 
3059   if (Best.TI != PartialIVCondBranch)
3060     PartialIVInfo.InstToDuplicate.clear();
3061 
3062   // If the best candidate is a guard, turn it into a branch.
3063   if (isGuard(Best.TI))
3064     Best.TI =
3065         turnGuardIntoBranch(cast<IntrinsicInst>(Best.TI), L, DT, LI, MSSAU);
3066 
3067   LLVM_DEBUG(dbgs() << "  Unswitching non-trivial (cost = " << Best.Cost
3068                     << ") terminator: " << *Best.TI << "\n");
3069   unswitchNontrivialInvariants(L, *Best.TI, Best.Invariants, PartialIVInfo, DT,
3070                                LI, AC, UnswitchCB, SE, MSSAU, DestroyLoopCB);
3071   return true;
3072 }
3073 
3074 /// Unswitch control flow predicated on loop invariant conditions.
3075 ///
3076 /// This first hoists all branches or switches which are trivial (IE, do not
3077 /// require duplicating any part of the loop) out of the loop body. It then
3078 /// looks at other loop invariant control flows and tries to unswitch those as
3079 /// well by cloning the loop if the result is small enough.
3080 ///
3081 /// The `DT`, `LI`, `AC`, `AA`, `TTI` parameters are required analyses that are
3082 /// also updated based on the unswitch. The `MSSA` analysis is also updated if
3083 /// valid (i.e. its use is enabled).
3084 ///
3085 /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
3086 /// true, we will attempt to do non-trivial unswitching as well as trivial
3087 /// unswitching.
3088 ///
3089 /// The `UnswitchCB` callback provided will be run after unswitching is
3090 /// complete, with the first parameter set to `true` if the provided loop
3091 /// remains a loop, and a list of new sibling loops created.
3092 ///
3093 /// If `SE` is non-null, we will update that analysis based on the unswitching
3094 /// done.
3095 static bool
3096 unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
3097              AAResults &AA, TargetTransformInfo &TTI, bool Trivial,
3098              bool NonTrivial,
3099              function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
3100              ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
3101              ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3102              function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
3103   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
3104          "Loops must be in LCSSA form before unswitching.");
3105 
3106   // Must be in loop simplified form: we need a preheader and dedicated exits.
3107   if (!L.isLoopSimplifyForm())
3108     return false;
3109 
3110   // Try trivial unswitch first before loop over other basic blocks in the loop.
3111   if (Trivial && unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
3112     // If we unswitched successfully we will want to clean up the loop before
3113     // processing it further so just mark it as unswitched and return.
3114     UnswitchCB(/*CurrentLoopValid*/ true, false, {});
3115     return true;
3116   }
3117 
3118   // Check whether we should continue with non-trivial conditions.
3119   // EnableNonTrivialUnswitch: Global variable that forces non-trivial
3120   //                           unswitching for testing and debugging.
3121   // NonTrivial: Parameter that enables non-trivial unswitching for this
3122   //             invocation of the transform. But this should be allowed only
3123   //             for targets without branch divergence.
3124   //
3125   // FIXME: If divergence analysis becomes available to a loop
3126   // transform, we should allow unswitching for non-trivial uniform
3127   // branches even on targets that have divergence.
3128   // https://bugs.llvm.org/show_bug.cgi?id=48819
3129   bool ContinueWithNonTrivial =
3130       EnableNonTrivialUnswitch || (NonTrivial && !TTI.hasBranchDivergence());
3131   if (!ContinueWithNonTrivial)
3132     return false;
3133 
3134   // Skip non-trivial unswitching for optsize functions.
3135   if (L.getHeader()->getParent()->hasOptSize())
3136     return false;
3137 
3138   // Skip cold loops, as unswitching them brings little benefit
3139   // but increases the code size
3140   if (PSI && PSI->hasProfileSummary() && BFI &&
3141       PSI->isFunctionColdInCallGraph(L.getHeader()->getParent(), *BFI)) {
3142     LLVM_DEBUG(dbgs() << " Skip cold loop: " << L << "\n");
3143     return false;
3144   }
3145 
3146   // Perform legality checks.
3147   if (!isSafeForNoNTrivialUnswitching(L, LI))
3148     return false;
3149 
3150   // For non-trivial unswitching, because it often creates new loops, we rely on
3151   // the pass manager to iterate on the loops rather than trying to immediately
3152   // reach a fixed point. There is no substantial advantage to iterating
3153   // internally, and if any of the new loops are simplified enough to contain
3154   // trivial unswitching we want to prefer those.
3155 
3156   // Try to unswitch the best invariant condition. We prefer this full unswitch to
3157   // a partial unswitch when possible below the threshold.
3158   if (unswitchBestCondition(L, DT, LI, AC, AA, TTI, UnswitchCB, SE, MSSAU,
3159                             DestroyLoopCB))
3160     return true;
3161 
3162   // No other opportunities to unswitch.
3163   return false;
3164 }
3165 
3166 PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
3167                                               LoopStandardAnalysisResults &AR,
3168                                               LPMUpdater &U) {
3169   Function &F = *L.getHeader()->getParent();
3170   (void)F;
3171   ProfileSummaryInfo *PSI = nullptr;
3172   if (auto OuterProxy =
3173           AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR)
3174               .getCachedResult<ModuleAnalysisManagerFunctionProxy>(F))
3175     PSI = OuterProxy->getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3176   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
3177                     << "\n");
3178 
3179   // Save the current loop name in a variable so that we can report it even
3180   // after it has been deleted.
3181   std::string LoopName = std::string(L.getName());
3182 
3183   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
3184                                         bool PartiallyInvariant,
3185                                         ArrayRef<Loop *> NewLoops) {
3186     // If we did a non-trivial unswitch, we have added new (cloned) loops.
3187     if (!NewLoops.empty())
3188       U.addSiblingLoops(NewLoops);
3189 
3190     // If the current loop remains valid, we should revisit it to catch any
3191     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
3192     if (CurrentLoopValid) {
3193       if (PartiallyInvariant) {
3194         // Mark the new loop as partially unswitched, to avoid unswitching on
3195         // the same condition again.
3196         auto &Context = L.getHeader()->getContext();
3197         MDNode *DisableUnswitchMD = MDNode::get(
3198             Context,
3199             MDString::get(Context, "llvm.loop.unswitch.partial.disable"));
3200         MDNode *NewLoopID = makePostTransformationMetadata(
3201             Context, L.getLoopID(), {"llvm.loop.unswitch.partial"},
3202             {DisableUnswitchMD});
3203         L.setLoopID(NewLoopID);
3204       } else
3205         U.revisitCurrentLoop();
3206     } else
3207       U.markLoopAsDeleted(L, LoopName);
3208   };
3209 
3210   auto DestroyLoopCB = [&U](Loop &L, StringRef Name) {
3211     U.markLoopAsDeleted(L, Name);
3212   };
3213 
3214   std::optional<MemorySSAUpdater> MSSAU;
3215   if (AR.MSSA) {
3216     MSSAU = MemorySSAUpdater(AR.MSSA);
3217     if (VerifyMemorySSA)
3218       AR.MSSA->verifyMemorySSA();
3219   }
3220   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.AA, AR.TTI, Trivial, NonTrivial,
3221                     UnswitchCB, &AR.SE, MSSAU ? &*MSSAU : nullptr, PSI, AR.BFI,
3222                     DestroyLoopCB))
3223     return PreservedAnalyses::all();
3224 
3225   if (AR.MSSA && VerifyMemorySSA)
3226     AR.MSSA->verifyMemorySSA();
3227 
3228   // Historically this pass has had issues with the dominator tree so verify it
3229   // in asserts builds.
3230   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
3231 
3232   auto PA = getLoopPassPreservedAnalyses();
3233   if (AR.MSSA)
3234     PA.preserve<MemorySSAAnalysis>();
3235   return PA;
3236 }
3237 
3238 void SimpleLoopUnswitchPass::printPipeline(
3239     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
3240   static_cast<PassInfoMixin<SimpleLoopUnswitchPass> *>(this)->printPipeline(
3241       OS, MapClassName2PassName);
3242 
3243   OS << "<";
3244   OS << (NonTrivial ? "" : "no-") << "nontrivial;";
3245   OS << (Trivial ? "" : "no-") << "trivial";
3246   OS << ">";
3247 }
3248 
3249 namespace {
3250 
3251 class SimpleLoopUnswitchLegacyPass : public LoopPass {
3252   bool NonTrivial;
3253 
3254 public:
3255   static char ID; // Pass ID, replacement for typeid
3256 
3257   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
3258       : LoopPass(ID), NonTrivial(NonTrivial) {
3259     initializeSimpleLoopUnswitchLegacyPassPass(
3260         *PassRegistry::getPassRegistry());
3261   }
3262 
3263   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
3264 
3265   void getAnalysisUsage(AnalysisUsage &AU) const override {
3266     AU.addRequired<AssumptionCacheTracker>();
3267     AU.addRequired<TargetTransformInfoWrapperPass>();
3268     AU.addRequired<MemorySSAWrapperPass>();
3269     AU.addPreserved<MemorySSAWrapperPass>();
3270     getLoopAnalysisUsage(AU);
3271   }
3272 };
3273 
3274 } // end anonymous namespace
3275 
3276 bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
3277   if (skipLoop(L))
3278     return false;
3279 
3280   Function &F = *L->getHeader()->getParent();
3281 
3282   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
3283                     << "\n");
3284   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3285   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3286   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3287   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
3288   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3289   MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
3290   MemorySSAUpdater MSSAU(MSSA);
3291 
3292   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
3293   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
3294 
3295   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid, bool PartiallyInvariant,
3296                                ArrayRef<Loop *> NewLoops) {
3297     // If we did a non-trivial unswitch, we have added new (cloned) loops.
3298     for (auto *NewL : NewLoops)
3299       LPM.addLoop(*NewL);
3300 
3301     // If the current loop remains valid, re-add it to the queue. This is
3302     // a little wasteful as we'll finish processing the current loop as well,
3303     // but it is the best we can do in the old PM.
3304     if (CurrentLoopValid) {
3305       // If the current loop has been unswitched using a partially invariant
3306       // condition, we should not re-add the current loop to avoid unswitching
3307       // on the same condition again.
3308       if (!PartiallyInvariant)
3309         LPM.addLoop(*L);
3310     } else
3311       LPM.markLoopAsDeleted(*L);
3312   };
3313 
3314   auto DestroyLoopCB = [&LPM](Loop &L, StringRef /* Name */) {
3315     LPM.markLoopAsDeleted(L);
3316   };
3317 
3318   if (VerifyMemorySSA)
3319     MSSA->verifyMemorySSA();
3320   bool Changed =
3321       unswitchLoop(*L, DT, LI, AC, AA, TTI, true, NonTrivial, UnswitchCB, SE,
3322                    &MSSAU, nullptr, nullptr, DestroyLoopCB);
3323 
3324   if (VerifyMemorySSA)
3325     MSSA->verifyMemorySSA();
3326 
3327   // Historically this pass has had issues with the dominator tree so verify it
3328   // in asserts builds.
3329   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
3330 
3331   return Changed;
3332 }
3333 
3334 char SimpleLoopUnswitchLegacyPass::ID = 0;
3335 INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
3336                       "Simple unswitch loops", false, false)
3337 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3338 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3339 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
3340 INITIALIZE_PASS_DEPENDENCY(LoopPass)
3341 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3342 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
3343 INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
3344                     "Simple unswitch loops", false, false)
3345 
3346 Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
3347   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
3348 }
3349