xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp (revision 7ef62cebc2f965b0f640263e179276928885e33d)
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            ArrayRef(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   // Perform the isGuaranteedNotToBeUndefOrPoison() query before the transform,
2192   // otherwise the branch instruction will have been moved outside the loop
2193   // already, and may imply that a poison condition is always UB.
2194   Value *FullUnswitchCond = nullptr;
2195   if (FullUnswitch) {
2196     FullUnswitchCond =
2197         BI ? skipTrivialSelect(BI->getCondition()) : SI->getCondition();
2198     if (InsertFreeze)
2199       InsertFreeze = !isGuaranteedNotToBeUndefOrPoison(
2200           FullUnswitchCond, &AC, L.getLoopPreheader()->getTerminator(), &DT);
2201   }
2202 
2203   // If the edge from this terminator to a successor dominates that successor,
2204   // store a map from each block in its dominator subtree to it. This lets us
2205   // tell when cloning for a particular successor if a block is dominated by
2206   // some *other* successor with a single data structure. We use this to
2207   // significantly reduce cloning.
2208   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
2209   for (auto *SuccBB : llvm::concat<BasicBlock *const>(ArrayRef(RetainedSuccBB),
2210                                                       UnswitchedSuccBBs))
2211     if (SuccBB->getUniquePredecessor() ||
2212         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2213           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
2214         }))
2215       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
2216         DominatingSucc[BB] = SuccBB;
2217         return true;
2218       });
2219 
2220   // Split the preheader, so that we know that there is a safe place to insert
2221   // the conditional branch. We will change the preheader to have a conditional
2222   // branch on LoopCond. The original preheader will become the split point
2223   // between the unswitched versions, and we will have a new preheader for the
2224   // original loop.
2225   BasicBlock *SplitBB = L.getLoopPreheader();
2226   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI, MSSAU);
2227 
2228   // Keep track of the dominator tree updates needed.
2229   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2230 
2231   // Clone the loop for each unswitched successor.
2232   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
2233   VMaps.reserve(UnswitchedSuccBBs.size());
2234   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
2235   for (auto *SuccBB : UnswitchedSuccBBs) {
2236     VMaps.emplace_back(new ValueToValueMapTy());
2237     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
2238         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
2239         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI, MSSAU, SE);
2240   }
2241 
2242   // Drop metadata if we may break its semantics by moving this instr into the
2243   // split block.
2244   if (TI.getMetadata(LLVMContext::MD_make_implicit)) {
2245     if (DropNonTrivialImplicitNullChecks)
2246       // Do not spend time trying to understand if we can keep it, just drop it
2247       // to save compile time.
2248       TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
2249     else {
2250       // It is only legal to preserve make.implicit metadata if we are
2251       // guaranteed no reach implicit null check after following this branch.
2252       ICFLoopSafetyInfo SafetyInfo;
2253       SafetyInfo.computeLoopSafetyInfo(&L);
2254       if (!SafetyInfo.isGuaranteedToExecute(TI, &DT, &L))
2255         TI.setMetadata(LLVMContext::MD_make_implicit, nullptr);
2256     }
2257   }
2258 
2259   // The stitching of the branched code back together depends on whether we're
2260   // doing full unswitching or not with the exception that we always want to
2261   // nuke the initial terminator placed in the split block.
2262   SplitBB->getTerminator()->eraseFromParent();
2263   if (FullUnswitch) {
2264     // Splice the terminator from the original loop and rewrite its
2265     // successors.
2266     SplitBB->splice(SplitBB->end(), ParentBB, TI.getIterator());
2267 
2268     // Keep a clone of the terminator for MSSA updates.
2269     Instruction *NewTI = TI.clone();
2270     NewTI->insertInto(ParentBB, ParentBB->end());
2271 
2272     // First wire up the moved terminator to the preheaders.
2273     if (BI) {
2274       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2275       BI->setSuccessor(ClonedSucc, ClonedPH);
2276       BI->setSuccessor(1 - ClonedSucc, LoopPH);
2277       if (InsertFreeze)
2278         FullUnswitchCond = new FreezeInst(
2279             FullUnswitchCond, FullUnswitchCond->getName() + ".fr", BI);
2280       BI->setCondition(FullUnswitchCond);
2281       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2282     } else {
2283       assert(SI && "Must either be a branch or switch!");
2284 
2285       // Walk the cases and directly update their successors.
2286       assert(SI->getDefaultDest() == RetainedSuccBB &&
2287              "Not retaining default successor!");
2288       SI->setDefaultDest(LoopPH);
2289       for (const auto &Case : SI->cases())
2290         if (Case.getCaseSuccessor() == RetainedSuccBB)
2291           Case.setSuccessor(LoopPH);
2292         else
2293           Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
2294 
2295       if (InsertFreeze)
2296         SI->setCondition(new FreezeInst(
2297             FullUnswitchCond, FullUnswitchCond->getName() + ".fr", SI));
2298 
2299       // We need to use the set to populate domtree updates as even when there
2300       // are multiple cases pointing at the same successor we only want to
2301       // remove and insert one edge in the domtree.
2302       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2303         DTUpdates.push_back(
2304             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
2305     }
2306 
2307     if (MSSAU) {
2308       DT.applyUpdates(DTUpdates);
2309       DTUpdates.clear();
2310 
2311       // Remove all but one edge to the retained block and all unswitched
2312       // blocks. This is to avoid having duplicate entries in the cloned Phis,
2313       // when we know we only keep a single edge for each case.
2314       MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, RetainedSuccBB);
2315       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2316         MSSAU->removeDuplicatePhiEdgesBetween(ParentBB, SuccBB);
2317 
2318       for (auto &VMap : VMaps)
2319         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2320                                    /*IgnoreIncomingWithNoClones=*/true);
2321       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2322 
2323       // Remove all edges to unswitched blocks.
2324       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2325         MSSAU->removeEdge(ParentBB, SuccBB);
2326     }
2327 
2328     // Now unhook the successor relationship as we'll be replacing
2329     // the terminator with a direct branch. This is much simpler for branches
2330     // than switches so we handle those first.
2331     if (BI) {
2332       // Remove the parent as a predecessor of the unswitched successor.
2333       assert(UnswitchedSuccBBs.size() == 1 &&
2334              "Only one possible unswitched block for a branch!");
2335       BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
2336       UnswitchedSuccBB->removePredecessor(ParentBB,
2337                                           /*KeepOneInputPHIs*/ true);
2338       DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
2339     } else {
2340       // Note that we actually want to remove the parent block as a predecessor
2341       // of *every* case successor. The case successor is either unswitched,
2342       // completely eliminating an edge from the parent to that successor, or it
2343       // is a duplicate edge to the retained successor as the retained successor
2344       // is always the default successor and as we'll replace this with a direct
2345       // branch we no longer need the duplicate entries in the PHI nodes.
2346       SwitchInst *NewSI = cast<SwitchInst>(NewTI);
2347       assert(NewSI->getDefaultDest() == RetainedSuccBB &&
2348              "Not retaining default successor!");
2349       for (const auto &Case : NewSI->cases())
2350         Case.getCaseSuccessor()->removePredecessor(
2351             ParentBB,
2352             /*KeepOneInputPHIs*/ true);
2353 
2354       // We need to use the set to populate domtree updates as even when there
2355       // are multiple cases pointing at the same successor we only want to
2356       // remove and insert one edge in the domtree.
2357       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
2358         DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
2359     }
2360 
2361     // After MSSAU update, remove the cloned terminator instruction NewTI.
2362     ParentBB->getTerminator()->eraseFromParent();
2363 
2364     // Create a new unconditional branch to the continuing block (as opposed to
2365     // the one cloned).
2366     BranchInst::Create(RetainedSuccBB, ParentBB);
2367   } else {
2368     assert(BI && "Only branches have partial unswitching.");
2369     assert(UnswitchedSuccBBs.size() == 1 &&
2370            "Only one possible unswitched block for a branch!");
2371     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2372     // When doing a partial unswitch, we have to do a bit more work to build up
2373     // the branch in the split block.
2374     if (PartiallyInvariant)
2375       buildPartialInvariantUnswitchConditionalBranch(
2376           *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH, L, MSSAU);
2377     else {
2378       buildPartialUnswitchConditionalBranch(
2379           *SplitBB, Invariants, Direction, *ClonedPH, *LoopPH,
2380           FreezeLoopUnswitchCond, BI, &AC, DT);
2381     }
2382     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
2383 
2384     if (MSSAU) {
2385       DT.applyUpdates(DTUpdates);
2386       DTUpdates.clear();
2387 
2388       // Perform MSSA cloning updates.
2389       for (auto &VMap : VMaps)
2390         MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, *VMap,
2391                                    /*IgnoreIncomingWithNoClones=*/true);
2392       MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMaps, DT);
2393     }
2394   }
2395 
2396   // Apply the updates accumulated above to get an up-to-date dominator tree.
2397   DT.applyUpdates(DTUpdates);
2398 
2399   // Now that we have an accurate dominator tree, first delete the dead cloned
2400   // blocks so that we can accurately build any cloned loops. It is important to
2401   // not delete the blocks from the original loop yet because we still want to
2402   // reference the original loop to understand the cloned loop's structure.
2403   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT, MSSAU);
2404 
2405   // Build the cloned loop structure itself. This may be substantially
2406   // different from the original structure due to the simplified CFG. This also
2407   // handles inserting all the cloned blocks into the correct loops.
2408   SmallVector<Loop *, 4> NonChildClonedLoops;
2409   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2410     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
2411 
2412   // Now that our cloned loops have been built, we can update the original loop.
2413   // First we delete the dead blocks from it and then we rebuild the loop
2414   // structure taking these deletions into account.
2415   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI, MSSAU, SE,DestroyLoopCB);
2416 
2417   if (MSSAU && VerifyMemorySSA)
2418     MSSAU->getMemorySSA()->verifyMemorySSA();
2419 
2420   SmallVector<Loop *, 4> HoistedLoops;
2421   bool IsStillLoop =
2422       rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops, SE);
2423 
2424   if (MSSAU && VerifyMemorySSA)
2425     MSSAU->getMemorySSA()->verifyMemorySSA();
2426 
2427   // This transformation has a high risk of corrupting the dominator tree, and
2428   // the below steps to rebuild loop structures will result in hard to debug
2429   // errors in that case so verify that the dominator tree is sane first.
2430   // FIXME: Remove this when the bugs stop showing up and rely on existing
2431   // verification steps.
2432   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2433 
2434   if (BI && !PartiallyInvariant) {
2435     // If we unswitched a branch which collapses the condition to a known
2436     // constant we want to replace all the uses of the invariants within both
2437     // the original and cloned blocks. We do this here so that we can use the
2438     // now updated dominator tree to identify which side the users are on.
2439     assert(UnswitchedSuccBBs.size() == 1 &&
2440            "Only one possible unswitched block for a branch!");
2441     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2442 
2443     // When considering multiple partially-unswitched invariants
2444     // we cant just go replace them with constants in both branches.
2445     //
2446     // For 'AND' we infer that true branch ("continue") means true
2447     // for each invariant operand.
2448     // For 'OR' we can infer that false branch ("continue") means false
2449     // for each invariant operand.
2450     // So it happens that for multiple-partial case we dont replace
2451     // in the unswitched branch.
2452     bool ReplaceUnswitched =
2453         FullUnswitch || (Invariants.size() == 1) || PartiallyInvariant;
2454 
2455     ConstantInt *UnswitchedReplacement =
2456         Direction ? ConstantInt::getTrue(BI->getContext())
2457                   : ConstantInt::getFalse(BI->getContext());
2458     ConstantInt *ContinueReplacement =
2459         Direction ? ConstantInt::getFalse(BI->getContext())
2460                   : ConstantInt::getTrue(BI->getContext());
2461     for (Value *Invariant : Invariants) {
2462       assert(!isa<Constant>(Invariant) &&
2463              "Should not be replacing constant values!");
2464       // Use make_early_inc_range here as set invalidates the iterator.
2465       for (Use &U : llvm::make_early_inc_range(Invariant->uses())) {
2466         Instruction *UserI = dyn_cast<Instruction>(U.getUser());
2467         if (!UserI)
2468           continue;
2469 
2470         // Replace it with the 'continue' side if in the main loop body, and the
2471         // unswitched if in the cloned blocks.
2472         if (DT.dominates(LoopPH, UserI->getParent()))
2473           U.set(ContinueReplacement);
2474         else if (ReplaceUnswitched &&
2475                  DT.dominates(ClonedPH, UserI->getParent()))
2476           U.set(UnswitchedReplacement);
2477       }
2478     }
2479   }
2480 
2481   // We can change which blocks are exit blocks of all the cloned sibling
2482   // loops, the current loop, and any parent loops which shared exit blocks
2483   // with the current loop. As a consequence, we need to re-form LCSSA for
2484   // them. But we shouldn't need to re-form LCSSA for any child loops.
2485   // FIXME: This could be made more efficient by tracking which exit blocks are
2486   // new, and focusing on them, but that isn't likely to be necessary.
2487   //
2488   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2489   // loop nest and update every loop that could have had its exits changed. We
2490   // also need to cover any intervening loops. We add all of these loops to
2491   // a list and sort them by loop depth to achieve this without updating
2492   // unnecessary loops.
2493   auto UpdateLoop = [&](Loop &UpdateL) {
2494 #ifndef NDEBUG
2495     UpdateL.verifyLoop();
2496     for (Loop *ChildL : UpdateL) {
2497       ChildL->verifyLoop();
2498       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2499              "Perturbed a child loop's LCSSA form!");
2500     }
2501 #endif
2502     // First build LCSSA for this loop so that we can preserve it when
2503     // forming dedicated exits. We don't want to perturb some other loop's
2504     // LCSSA while doing that CFG edit.
2505     formLCSSA(UpdateL, DT, &LI, SE);
2506 
2507     // For loops reached by this loop's original exit blocks we may
2508     // introduced new, non-dedicated exits. At least try to re-form dedicated
2509     // exits for these loops. This may fail if they couldn't have dedicated
2510     // exits to start with.
2511     formDedicatedExitBlocks(&UpdateL, &DT, &LI, MSSAU, /*PreserveLCSSA*/ true);
2512   };
2513 
2514   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2515   // and we can do it in any order as they don't nest relative to each other.
2516   //
2517   // Also check if any of the loops we have updated have become top-level loops
2518   // as that will necessitate widening the outer loop scope.
2519   for (Loop *UpdatedL :
2520        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2521     UpdateLoop(*UpdatedL);
2522     if (UpdatedL->isOutermost())
2523       OuterExitL = nullptr;
2524   }
2525   if (IsStillLoop) {
2526     UpdateLoop(L);
2527     if (L.isOutermost())
2528       OuterExitL = nullptr;
2529   }
2530 
2531   // If the original loop had exit blocks, walk up through the outer most loop
2532   // of those exit blocks to update LCSSA and form updated dedicated exits.
2533   if (OuterExitL != &L)
2534     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2535          OuterL = OuterL->getParentLoop())
2536       UpdateLoop(*OuterL);
2537 
2538 #ifndef NDEBUG
2539   // Verify the entire loop structure to catch any incorrect updates before we
2540   // progress in the pass pipeline.
2541   LI.verify(DT);
2542 #endif
2543 
2544   // Now that we've unswitched something, make callbacks to report the changes.
2545   // For that we need to merge together the updated loops and the cloned loops
2546   // and check whether the original loop survived.
2547   SmallVector<Loop *, 4> SibLoops;
2548   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2549     if (UpdatedL->getParentLoop() == ParentL)
2550       SibLoops.push_back(UpdatedL);
2551   UnswitchCB(IsStillLoop, PartiallyInvariant, SibLoops);
2552 
2553   if (MSSAU && VerifyMemorySSA)
2554     MSSAU->getMemorySSA()->verifyMemorySSA();
2555 
2556   if (BI)
2557     ++NumBranches;
2558   else
2559     ++NumSwitches;
2560 }
2561 
2562 /// Recursively compute the cost of a dominator subtree based on the per-block
2563 /// cost map provided.
2564 ///
2565 /// The recursive computation is memozied into the provided DT-indexed cost map
2566 /// to allow querying it for most nodes in the domtree without it becoming
2567 /// quadratic.
2568 static InstructionCost computeDomSubtreeCost(
2569     DomTreeNode &N,
2570     const SmallDenseMap<BasicBlock *, InstructionCost, 4> &BBCostMap,
2571     SmallDenseMap<DomTreeNode *, InstructionCost, 4> &DTCostMap) {
2572   // Don't accumulate cost (or recurse through) blocks not in our block cost
2573   // map and thus not part of the duplication cost being considered.
2574   auto BBCostIt = BBCostMap.find(N.getBlock());
2575   if (BBCostIt == BBCostMap.end())
2576     return 0;
2577 
2578   // Lookup this node to see if we already computed its cost.
2579   auto DTCostIt = DTCostMap.find(&N);
2580   if (DTCostIt != DTCostMap.end())
2581     return DTCostIt->second;
2582 
2583   // If not, we have to compute it. We can't use insert above and update
2584   // because computing the cost may insert more things into the map.
2585   InstructionCost Cost = std::accumulate(
2586       N.begin(), N.end(), BBCostIt->second,
2587       [&](InstructionCost Sum, DomTreeNode *ChildN) -> InstructionCost {
2588         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2589       });
2590   bool Inserted = DTCostMap.insert({&N, Cost}).second;
2591   (void)Inserted;
2592   assert(Inserted && "Should not insert a node while visiting children!");
2593   return Cost;
2594 }
2595 
2596 /// Turns a llvm.experimental.guard intrinsic into implicit control flow branch,
2597 /// making the following replacement:
2598 ///
2599 ///   --code before guard--
2600 ///   call void (i1, ...) @llvm.experimental.guard(i1 %cond) [ "deopt"() ]
2601 ///   --code after guard--
2602 ///
2603 /// into
2604 ///
2605 ///   --code before guard--
2606 ///   br i1 %cond, label %guarded, label %deopt
2607 ///
2608 /// guarded:
2609 ///   --code after guard--
2610 ///
2611 /// deopt:
2612 ///   call void (i1, ...) @llvm.experimental.guard(i1 false) [ "deopt"() ]
2613 ///   unreachable
2614 ///
2615 /// It also makes all relevant DT and LI updates, so that all structures are in
2616 /// valid state after this transform.
2617 static BranchInst *turnGuardIntoBranch(IntrinsicInst *GI, Loop &L,
2618                                        DominatorTree &DT, LoopInfo &LI,
2619                                        MemorySSAUpdater *MSSAU) {
2620   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
2621   LLVM_DEBUG(dbgs() << "Turning " << *GI << " into a branch.\n");
2622   BasicBlock *CheckBB = GI->getParent();
2623 
2624   if (MSSAU && VerifyMemorySSA)
2625      MSSAU->getMemorySSA()->verifyMemorySSA();
2626 
2627   // Remove all CheckBB's successors from DomTree. A block can be seen among
2628   // successors more than once, but for DomTree it should be added only once.
2629   SmallPtrSet<BasicBlock *, 4> Successors;
2630   for (auto *Succ : successors(CheckBB))
2631     if (Successors.insert(Succ).second)
2632       DTUpdates.push_back({DominatorTree::Delete, CheckBB, Succ});
2633 
2634   Instruction *DeoptBlockTerm =
2635       SplitBlockAndInsertIfThen(GI->getArgOperand(0), GI, true);
2636   BranchInst *CheckBI = cast<BranchInst>(CheckBB->getTerminator());
2637   // SplitBlockAndInsertIfThen inserts control flow that branches to
2638   // DeoptBlockTerm if the condition is true.  We want the opposite.
2639   CheckBI->swapSuccessors();
2640 
2641   BasicBlock *GuardedBlock = CheckBI->getSuccessor(0);
2642   GuardedBlock->setName("guarded");
2643   CheckBI->getSuccessor(1)->setName("deopt");
2644   BasicBlock *DeoptBlock = CheckBI->getSuccessor(1);
2645 
2646   if (MSSAU)
2647     MSSAU->moveAllAfterSpliceBlocks(CheckBB, GuardedBlock, GI);
2648 
2649   GI->moveBefore(DeoptBlockTerm);
2650   GI->setArgOperand(0, ConstantInt::getFalse(GI->getContext()));
2651 
2652   // Add new successors of CheckBB into DomTree.
2653   for (auto *Succ : successors(CheckBB))
2654     DTUpdates.push_back({DominatorTree::Insert, CheckBB, Succ});
2655 
2656   // Now the blocks that used to be CheckBB's successors are GuardedBlock's
2657   // successors.
2658   for (auto *Succ : Successors)
2659     DTUpdates.push_back({DominatorTree::Insert, GuardedBlock, Succ});
2660 
2661   // Make proper changes to DT.
2662   DT.applyUpdates(DTUpdates);
2663   // Inform LI of a new loop block.
2664   L.addBasicBlockToLoop(GuardedBlock, LI);
2665 
2666   if (MSSAU) {
2667     MemoryDef *MD = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(GI));
2668     MSSAU->moveToPlace(MD, DeoptBlock, MemorySSA::BeforeTerminator);
2669     if (VerifyMemorySSA)
2670       MSSAU->getMemorySSA()->verifyMemorySSA();
2671   }
2672 
2673   ++NumGuards;
2674   return CheckBI;
2675 }
2676 
2677 /// Cost multiplier is a way to limit potentially exponential behavior
2678 /// of loop-unswitch. Cost is multipied in proportion of 2^number of unswitch
2679 /// candidates available. Also accounting for the number of "sibling" loops with
2680 /// the idea to account for previous unswitches that already happened on this
2681 /// cluster of loops. There was an attempt to keep this formula simple,
2682 /// just enough to limit the worst case behavior. Even if it is not that simple
2683 /// now it is still not an attempt to provide a detailed heuristic size
2684 /// prediction.
2685 ///
2686 /// TODO: Make a proper accounting of "explosion" effect for all kinds of
2687 /// unswitch candidates, making adequate predictions instead of wild guesses.
2688 /// That requires knowing not just the number of "remaining" candidates but
2689 /// also costs of unswitching for each of these candidates.
2690 static int CalculateUnswitchCostMultiplier(
2691     const Instruction &TI, const Loop &L, const LoopInfo &LI,
2692     const DominatorTree &DT,
2693     ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates) {
2694 
2695   // Guards and other exiting conditions do not contribute to exponential
2696   // explosion as soon as they dominate the latch (otherwise there might be
2697   // another path to the latch remaining that does not allow to eliminate the
2698   // loop copy on unswitch).
2699   const BasicBlock *Latch = L.getLoopLatch();
2700   const BasicBlock *CondBlock = TI.getParent();
2701   if (DT.dominates(CondBlock, Latch) &&
2702       (isGuard(&TI) ||
2703        llvm::count_if(successors(&TI), [&L](const BasicBlock *SuccBB) {
2704          return L.contains(SuccBB);
2705        }) <= 1)) {
2706     NumCostMultiplierSkipped++;
2707     return 1;
2708   }
2709 
2710   auto *ParentL = L.getParentLoop();
2711   int SiblingsCount = (ParentL ? ParentL->getSubLoopsVector().size()
2712                                : std::distance(LI.begin(), LI.end()));
2713   // Count amount of clones that all the candidates might cause during
2714   // unswitching. Branch/guard counts as 1, switch counts as log2 of its cases.
2715   int UnswitchedClones = 0;
2716   for (auto Candidate : UnswitchCandidates) {
2717     const Instruction *CI = Candidate.TI;
2718     const BasicBlock *CondBlock = CI->getParent();
2719     bool SkipExitingSuccessors = DT.dominates(CondBlock, Latch);
2720     if (isGuard(CI)) {
2721       if (!SkipExitingSuccessors)
2722         UnswitchedClones++;
2723       continue;
2724     }
2725     int NonExitingSuccessors =
2726         llvm::count_if(successors(CondBlock),
2727                        [SkipExitingSuccessors, &L](const BasicBlock *SuccBB) {
2728           return !SkipExitingSuccessors || L.contains(SuccBB);
2729         });
2730     UnswitchedClones += Log2_32(NonExitingSuccessors);
2731   }
2732 
2733   // Ignore up to the "unscaled candidates" number of unswitch candidates
2734   // when calculating the power-of-two scaling of the cost. The main idea
2735   // with this control is to allow a small number of unswitches to happen
2736   // and rely more on siblings multiplier (see below) when the number
2737   // of candidates is small.
2738   unsigned ClonesPower =
2739       std::max(UnswitchedClones - (int)UnswitchNumInitialUnscaledCandidates, 0);
2740 
2741   // Allowing top-level loops to spread a bit more than nested ones.
2742   int SiblingsMultiplier =
2743       std::max((ParentL ? SiblingsCount
2744                         : SiblingsCount / (int)UnswitchSiblingsToplevelDiv),
2745                1);
2746   // Compute the cost multiplier in a way that won't overflow by saturating
2747   // at an upper bound.
2748   int CostMultiplier;
2749   if (ClonesPower > Log2_32(UnswitchThreshold) ||
2750       SiblingsMultiplier > UnswitchThreshold)
2751     CostMultiplier = UnswitchThreshold;
2752   else
2753     CostMultiplier = std::min(SiblingsMultiplier * (1 << ClonesPower),
2754                               (int)UnswitchThreshold);
2755 
2756   LLVM_DEBUG(dbgs() << "  Computed multiplier  " << CostMultiplier
2757                     << " (siblings " << SiblingsMultiplier << " * clones "
2758                     << (1 << ClonesPower) << ")"
2759                     << " for unswitch candidate: " << TI << "\n");
2760   return CostMultiplier;
2761 }
2762 
2763 static bool collectUnswitchCandidates(
2764     SmallVectorImpl<NonTrivialUnswitchCandidate> &UnswitchCandidates,
2765     IVConditionInfo &PartialIVInfo, Instruction *&PartialIVCondBranch,
2766     const Loop &L, const LoopInfo &LI, AAResults &AA,
2767     const MemorySSAUpdater *MSSAU) {
2768   assert(UnswitchCandidates.empty() && "Should be!");
2769   // Whether or not we should also collect guards in the loop.
2770   bool CollectGuards = false;
2771   if (UnswitchGuards) {
2772     auto *GuardDecl = L.getHeader()->getParent()->getParent()->getFunction(
2773         Intrinsic::getName(Intrinsic::experimental_guard));
2774     if (GuardDecl && !GuardDecl->use_empty())
2775       CollectGuards = true;
2776   }
2777 
2778   for (auto *BB : L.blocks()) {
2779     if (LI.getLoopFor(BB) != &L)
2780       continue;
2781 
2782     if (CollectGuards)
2783       for (auto &I : *BB)
2784         if (isGuard(&I)) {
2785           auto *Cond =
2786               skipTrivialSelect(cast<IntrinsicInst>(&I)->getArgOperand(0));
2787           // TODO: Support AND, OR conditions and partial unswitching.
2788           if (!isa<Constant>(Cond) && L.isLoopInvariant(Cond))
2789             UnswitchCandidates.push_back({&I, {Cond}});
2790         }
2791 
2792     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2793       // We can only consider fully loop-invariant switch conditions as we need
2794       // to completely eliminate the switch after unswitching.
2795       if (!isa<Constant>(SI->getCondition()) &&
2796           L.isLoopInvariant(SI->getCondition()) && !BB->getUniqueSuccessor())
2797         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2798       continue;
2799     }
2800 
2801     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2802     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2803         BI->getSuccessor(0) == BI->getSuccessor(1))
2804       continue;
2805 
2806     Value *Cond = skipTrivialSelect(BI->getCondition());
2807     if (isa<Constant>(Cond))
2808       continue;
2809 
2810     if (L.isLoopInvariant(Cond)) {
2811       UnswitchCandidates.push_back({BI, {Cond}});
2812       continue;
2813     }
2814 
2815     Instruction &CondI = *cast<Instruction>(Cond);
2816     if (match(&CondI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()))) {
2817       TinyPtrVector<Value *> Invariants =
2818           collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2819       if (Invariants.empty())
2820         continue;
2821 
2822       UnswitchCandidates.push_back({BI, std::move(Invariants)});
2823       continue;
2824     }
2825   }
2826 
2827   if (MSSAU && !findOptionMDForLoop(&L, "llvm.loop.unswitch.partial.disable") &&
2828       !any_of(UnswitchCandidates, [&L](auto &TerminatorAndInvariants) {
2829          return TerminatorAndInvariants.TI == L.getHeader()->getTerminator();
2830        })) {
2831     MemorySSA *MSSA = MSSAU->getMemorySSA();
2832     if (auto Info = hasPartialIVCondition(L, MSSAThreshold, *MSSA, AA)) {
2833       LLVM_DEBUG(
2834           dbgs() << "simple-loop-unswitch: Found partially invariant condition "
2835                  << *Info->InstToDuplicate[0] << "\n");
2836       PartialIVInfo = *Info;
2837       PartialIVCondBranch = L.getHeader()->getTerminator();
2838       TinyPtrVector<Value *> ValsToDuplicate;
2839       llvm::append_range(ValsToDuplicate, Info->InstToDuplicate);
2840       UnswitchCandidates.push_back(
2841           {L.getHeader()->getTerminator(), std::move(ValsToDuplicate)});
2842     }
2843   }
2844   return !UnswitchCandidates.empty();
2845 }
2846 
2847 static bool isSafeForNoNTrivialUnswitching(Loop &L, LoopInfo &LI) {
2848   if (!L.isSafeToClone())
2849     return false;
2850   for (auto *BB : L.blocks())
2851     for (auto &I : *BB) {
2852       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
2853         return false;
2854       if (auto *CB = dyn_cast<CallBase>(&I)) {
2855         assert(!CB->cannotDuplicate() && "Checked by L.isSafeToClone().");
2856         if (CB->isConvergent())
2857           return false;
2858       }
2859     }
2860 
2861   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2862   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2863   // irreducible control flow into reducible control flow and introduce new
2864   // loops "out of thin air". If we ever discover important use cases for doing
2865   // this, we can add support to loop unswitch, but it is a lot of complexity
2866   // for what seems little or no real world benefit.
2867   LoopBlocksRPO RPOT(&L);
2868   RPOT.perform(&LI);
2869   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
2870     return false;
2871 
2872   SmallVector<BasicBlock *, 4> ExitBlocks;
2873   L.getUniqueExitBlocks(ExitBlocks);
2874   // We cannot unswitch if exit blocks contain a cleanuppad/catchswitch
2875   // instruction as we don't know how to split those exit blocks.
2876   // FIXME: We should teach SplitBlock to handle this and remove this
2877   // restriction.
2878   for (auto *ExitBB : ExitBlocks) {
2879     auto *I = ExitBB->getFirstNonPHI();
2880     if (isa<CleanupPadInst>(I) || isa<CatchSwitchInst>(I)) {
2881       LLVM_DEBUG(dbgs() << "Cannot unswitch because of cleanuppad/catchswitch "
2882                            "in exit block\n");
2883       return false;
2884     }
2885   }
2886 
2887   return true;
2888 }
2889 
2890 static NonTrivialUnswitchCandidate findBestNonTrivialUnswitchCandidate(
2891     ArrayRef<NonTrivialUnswitchCandidate> UnswitchCandidates, const Loop &L,
2892     const DominatorTree &DT, const LoopInfo &LI, AssumptionCache &AC,
2893     const TargetTransformInfo &TTI, const IVConditionInfo &PartialIVInfo) {
2894   // Given that unswitching these terminators will require duplicating parts of
2895   // the loop, so we need to be able to model that cost. Compute the ephemeral
2896   // values and set up a data structure to hold per-BB costs. We cache each
2897   // block's cost so that we don't recompute this when considering different
2898   // subsets of the loop for duplication during unswitching.
2899   SmallPtrSet<const Value *, 4> EphValues;
2900   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2901   SmallDenseMap<BasicBlock *, InstructionCost, 4> BBCostMap;
2902 
2903   // Compute the cost of each block, as well as the total loop cost. Also, bail
2904   // out if we see instructions which are incompatible with loop unswitching
2905   // (convergent, noduplicate, or cross-basic-block tokens).
2906   // FIXME: We might be able to safely handle some of these in non-duplicated
2907   // regions.
2908   TargetTransformInfo::TargetCostKind CostKind =
2909       L.getHeader()->getParent()->hasMinSize()
2910       ? TargetTransformInfo::TCK_CodeSize
2911       : TargetTransformInfo::TCK_SizeAndLatency;
2912   InstructionCost LoopCost = 0;
2913   for (auto *BB : L.blocks()) {
2914     InstructionCost Cost = 0;
2915     for (auto &I : *BB) {
2916       if (EphValues.count(&I))
2917         continue;
2918       Cost += TTI.getInstructionCost(&I, CostKind);
2919     }
2920     assert(Cost >= 0 && "Must not have negative costs!");
2921     LoopCost += Cost;
2922     assert(LoopCost >= 0 && "Must not have negative loop costs!");
2923     BBCostMap[BB] = Cost;
2924   }
2925   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
2926 
2927   // Now we find the best candidate by searching for the one with the following
2928   // properties in order:
2929   //
2930   // 1) An unswitching cost below the threshold
2931   // 2) The smallest number of duplicated unswitch candidates (to avoid
2932   //    creating redundant subsequent unswitching)
2933   // 3) The smallest cost after unswitching.
2934   //
2935   // We prioritize reducing fanout of unswitch candidates provided the cost
2936   // remains below the threshold because this has a multiplicative effect.
2937   //
2938   // This requires memoizing each dominator subtree to avoid redundant work.
2939   //
2940   // FIXME: Need to actually do the number of candidates part above.
2941   SmallDenseMap<DomTreeNode *, InstructionCost, 4> DTCostMap;
2942   // Given a terminator which might be unswitched, computes the non-duplicated
2943   // cost for that terminator.
2944   auto ComputeUnswitchedCost = [&](Instruction &TI,
2945                                    bool FullUnswitch) -> InstructionCost {
2946     BasicBlock &BB = *TI.getParent();
2947     SmallPtrSet<BasicBlock *, 4> Visited;
2948 
2949     InstructionCost Cost = 0;
2950     for (BasicBlock *SuccBB : successors(&BB)) {
2951       // Don't count successors more than once.
2952       if (!Visited.insert(SuccBB).second)
2953         continue;
2954 
2955       // If this is a partial unswitch candidate, then it must be a conditional
2956       // branch with a condition of either `or`, `and`, their corresponding
2957       // select forms or partially invariant instructions. In that case, one of
2958       // the successors is necessarily duplicated, so don't even try to remove
2959       // its cost.
2960       if (!FullUnswitch) {
2961         auto &BI = cast<BranchInst>(TI);
2962         Value *Cond = skipTrivialSelect(BI.getCondition());
2963         if (match(Cond, m_LogicalAnd())) {
2964           if (SuccBB == BI.getSuccessor(1))
2965             continue;
2966         } else if (match(Cond, m_LogicalOr())) {
2967           if (SuccBB == BI.getSuccessor(0))
2968             continue;
2969         } else if ((PartialIVInfo.KnownValue->isOneValue() &&
2970                     SuccBB == BI.getSuccessor(0)) ||
2971                    (!PartialIVInfo.KnownValue->isOneValue() &&
2972                     SuccBB == BI.getSuccessor(1)))
2973           continue;
2974       }
2975 
2976       // This successor's domtree will not need to be duplicated after
2977       // unswitching if the edge to the successor dominates it (and thus the
2978       // entire tree). This essentially means there is no other path into this
2979       // subtree and so it will end up live in only one clone of the loop.
2980       if (SuccBB->getUniquePredecessor() ||
2981           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2982             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2983           })) {
2984         Cost += computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2985         assert(Cost <= LoopCost &&
2986                "Non-duplicated cost should never exceed total loop cost!");
2987       }
2988     }
2989 
2990     // Now scale the cost by the number of unique successors minus one. We
2991     // subtract one because there is already at least one copy of the entire
2992     // loop. This is computing the new cost of unswitching a condition.
2993     // Note that guards always have 2 unique successors that are implicit and
2994     // will be materialized if we decide to unswitch it.
2995     int SuccessorsCount = isGuard(&TI) ? 2 : Visited.size();
2996     assert(SuccessorsCount > 1 &&
2997            "Cannot unswitch a condition without multiple distinct successors!");
2998     return (LoopCost - Cost) * (SuccessorsCount - 1);
2999   };
3000 
3001   std::optional<NonTrivialUnswitchCandidate> Best;
3002   for (auto &Candidate : UnswitchCandidates) {
3003     Instruction &TI = *Candidate.TI;
3004     ArrayRef<Value *> Invariants = Candidate.Invariants;
3005     BranchInst *BI = dyn_cast<BranchInst>(&TI);
3006     InstructionCost CandidateCost = ComputeUnswitchedCost(
3007         TI, /*FullUnswitch*/ !BI ||
3008                 (Invariants.size() == 1 &&
3009                  Invariants[0] == skipTrivialSelect(BI->getCondition())));
3010     // Calculate cost multiplier which is a tool to limit potentially
3011     // exponential behavior of loop-unswitch.
3012     if (EnableUnswitchCostMultiplier) {
3013       int CostMultiplier =
3014           CalculateUnswitchCostMultiplier(TI, L, LI, DT, UnswitchCandidates);
3015       assert(
3016           (CostMultiplier > 0 && CostMultiplier <= UnswitchThreshold) &&
3017           "cost multiplier needs to be in the range of 1..UnswitchThreshold");
3018       CandidateCost *= CostMultiplier;
3019       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
3020                         << " (multiplier: " << CostMultiplier << ")"
3021                         << " for unswitch candidate: " << TI << "\n");
3022     } else {
3023       LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
3024                         << " for unswitch candidate: " << TI << "\n");
3025     }
3026 
3027     if (!Best || CandidateCost < Best->Cost) {
3028       Best = Candidate;
3029       Best->Cost = CandidateCost;
3030     }
3031   }
3032   assert(Best && "Must be!");
3033   return *Best;
3034 }
3035 
3036 static bool unswitchBestCondition(
3037     Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
3038     AAResults &AA, TargetTransformInfo &TTI,
3039     function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
3040     ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
3041     function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
3042   // Collect all invariant conditions within this loop (as opposed to an inner
3043   // loop which would be handled when visiting that inner loop).
3044   SmallVector<NonTrivialUnswitchCandidate, 4> UnswitchCandidates;
3045   IVConditionInfo PartialIVInfo;
3046   Instruction *PartialIVCondBranch = nullptr;
3047   // If we didn't find any candidates, we're done.
3048   if (!collectUnswitchCandidates(UnswitchCandidates, PartialIVInfo,
3049                                  PartialIVCondBranch, L, LI, AA, MSSAU))
3050     return false;
3051 
3052   LLVM_DEBUG(
3053       dbgs() << "Considering " << UnswitchCandidates.size()
3054              << " non-trivial loop invariant conditions for unswitching.\n");
3055 
3056   NonTrivialUnswitchCandidate Best = findBestNonTrivialUnswitchCandidate(
3057       UnswitchCandidates, L, DT, LI, AC, TTI, PartialIVInfo);
3058 
3059   assert(Best.TI && "Failed to find loop unswitch candidate");
3060   assert(Best.Cost && "Failed to compute cost");
3061 
3062   if (*Best.Cost >= UnswitchThreshold) {
3063     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: " << *Best.Cost
3064                       << "\n");
3065     return false;
3066   }
3067 
3068   if (Best.TI != PartialIVCondBranch)
3069     PartialIVInfo.InstToDuplicate.clear();
3070 
3071   // If the best candidate is a guard, turn it into a branch.
3072   if (isGuard(Best.TI))
3073     Best.TI =
3074         turnGuardIntoBranch(cast<IntrinsicInst>(Best.TI), L, DT, LI, MSSAU);
3075 
3076   LLVM_DEBUG(dbgs() << "  Unswitching non-trivial (cost = " << Best.Cost
3077                     << ") terminator: " << *Best.TI << "\n");
3078   unswitchNontrivialInvariants(L, *Best.TI, Best.Invariants, PartialIVInfo, DT,
3079                                LI, AC, UnswitchCB, SE, MSSAU, DestroyLoopCB);
3080   return true;
3081 }
3082 
3083 /// Unswitch control flow predicated on loop invariant conditions.
3084 ///
3085 /// This first hoists all branches or switches which are trivial (IE, do not
3086 /// require duplicating any part of the loop) out of the loop body. It then
3087 /// looks at other loop invariant control flows and tries to unswitch those as
3088 /// well by cloning the loop if the result is small enough.
3089 ///
3090 /// The `DT`, `LI`, `AC`, `AA`, `TTI` parameters are required analyses that are
3091 /// also updated based on the unswitch. The `MSSA` analysis is also updated if
3092 /// valid (i.e. its use is enabled).
3093 ///
3094 /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
3095 /// true, we will attempt to do non-trivial unswitching as well as trivial
3096 /// unswitching.
3097 ///
3098 /// The `UnswitchCB` callback provided will be run after unswitching is
3099 /// complete, with the first parameter set to `true` if the provided loop
3100 /// remains a loop, and a list of new sibling loops created.
3101 ///
3102 /// If `SE` is non-null, we will update that analysis based on the unswitching
3103 /// done.
3104 static bool
3105 unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
3106              AAResults &AA, TargetTransformInfo &TTI, bool Trivial,
3107              bool NonTrivial,
3108              function_ref<void(bool, bool, ArrayRef<Loop *>)> UnswitchCB,
3109              ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
3110              ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3111              function_ref<void(Loop &, StringRef)> DestroyLoopCB) {
3112   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
3113          "Loops must be in LCSSA form before unswitching.");
3114 
3115   // Must be in loop simplified form: we need a preheader and dedicated exits.
3116   if (!L.isLoopSimplifyForm())
3117     return false;
3118 
3119   // Try trivial unswitch first before loop over other basic blocks in the loop.
3120   if (Trivial && unswitchAllTrivialConditions(L, DT, LI, SE, MSSAU)) {
3121     // If we unswitched successfully we will want to clean up the loop before
3122     // processing it further so just mark it as unswitched and return.
3123     UnswitchCB(/*CurrentLoopValid*/ true, false, {});
3124     return true;
3125   }
3126 
3127   // Check whether we should continue with non-trivial conditions.
3128   // EnableNonTrivialUnswitch: Global variable that forces non-trivial
3129   //                           unswitching for testing and debugging.
3130   // NonTrivial: Parameter that enables non-trivial unswitching for this
3131   //             invocation of the transform. But this should be allowed only
3132   //             for targets without branch divergence.
3133   //
3134   // FIXME: If divergence analysis becomes available to a loop
3135   // transform, we should allow unswitching for non-trivial uniform
3136   // branches even on targets that have divergence.
3137   // https://bugs.llvm.org/show_bug.cgi?id=48819
3138   bool ContinueWithNonTrivial =
3139       EnableNonTrivialUnswitch || (NonTrivial && !TTI.hasBranchDivergence());
3140   if (!ContinueWithNonTrivial)
3141     return false;
3142 
3143   // Skip non-trivial unswitching for optsize functions.
3144   if (L.getHeader()->getParent()->hasOptSize())
3145     return false;
3146 
3147   // Skip cold loops, as unswitching them brings little benefit
3148   // but increases the code size
3149   if (PSI && PSI->hasProfileSummary() && BFI &&
3150       PSI->isFunctionColdInCallGraph(L.getHeader()->getParent(), *BFI)) {
3151     LLVM_DEBUG(dbgs() << " Skip cold loop: " << L << "\n");
3152     return false;
3153   }
3154 
3155   // Perform legality checks.
3156   if (!isSafeForNoNTrivialUnswitching(L, LI))
3157     return false;
3158 
3159   // For non-trivial unswitching, because it often creates new loops, we rely on
3160   // the pass manager to iterate on the loops rather than trying to immediately
3161   // reach a fixed point. There is no substantial advantage to iterating
3162   // internally, and if any of the new loops are simplified enough to contain
3163   // trivial unswitching we want to prefer those.
3164 
3165   // Try to unswitch the best invariant condition. We prefer this full unswitch to
3166   // a partial unswitch when possible below the threshold.
3167   if (unswitchBestCondition(L, DT, LI, AC, AA, TTI, UnswitchCB, SE, MSSAU,
3168                             DestroyLoopCB))
3169     return true;
3170 
3171   // No other opportunities to unswitch.
3172   return false;
3173 }
3174 
3175 PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
3176                                               LoopStandardAnalysisResults &AR,
3177                                               LPMUpdater &U) {
3178   Function &F = *L.getHeader()->getParent();
3179   (void)F;
3180   ProfileSummaryInfo *PSI = nullptr;
3181   if (auto OuterProxy =
3182           AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR)
3183               .getCachedResult<ModuleAnalysisManagerFunctionProxy>(F))
3184     PSI = OuterProxy->getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
3185   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
3186                     << "\n");
3187 
3188   // Save the current loop name in a variable so that we can report it even
3189   // after it has been deleted.
3190   std::string LoopName = std::string(L.getName());
3191 
3192   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
3193                                         bool PartiallyInvariant,
3194                                         ArrayRef<Loop *> NewLoops) {
3195     // If we did a non-trivial unswitch, we have added new (cloned) loops.
3196     if (!NewLoops.empty())
3197       U.addSiblingLoops(NewLoops);
3198 
3199     // If the current loop remains valid, we should revisit it to catch any
3200     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
3201     if (CurrentLoopValid) {
3202       if (PartiallyInvariant) {
3203         // Mark the new loop as partially unswitched, to avoid unswitching on
3204         // the same condition again.
3205         auto &Context = L.getHeader()->getContext();
3206         MDNode *DisableUnswitchMD = MDNode::get(
3207             Context,
3208             MDString::get(Context, "llvm.loop.unswitch.partial.disable"));
3209         MDNode *NewLoopID = makePostTransformationMetadata(
3210             Context, L.getLoopID(), {"llvm.loop.unswitch.partial"},
3211             {DisableUnswitchMD});
3212         L.setLoopID(NewLoopID);
3213       } else
3214         U.revisitCurrentLoop();
3215     } else
3216       U.markLoopAsDeleted(L, LoopName);
3217   };
3218 
3219   auto DestroyLoopCB = [&U](Loop &L, StringRef Name) {
3220     U.markLoopAsDeleted(L, Name);
3221   };
3222 
3223   std::optional<MemorySSAUpdater> MSSAU;
3224   if (AR.MSSA) {
3225     MSSAU = MemorySSAUpdater(AR.MSSA);
3226     if (VerifyMemorySSA)
3227       AR.MSSA->verifyMemorySSA();
3228   }
3229   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.AA, AR.TTI, Trivial, NonTrivial,
3230                     UnswitchCB, &AR.SE, MSSAU ? &*MSSAU : nullptr, PSI, AR.BFI,
3231                     DestroyLoopCB))
3232     return PreservedAnalyses::all();
3233 
3234   if (AR.MSSA && VerifyMemorySSA)
3235     AR.MSSA->verifyMemorySSA();
3236 
3237   // Historically this pass has had issues with the dominator tree so verify it
3238   // in asserts builds.
3239   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
3240 
3241   auto PA = getLoopPassPreservedAnalyses();
3242   if (AR.MSSA)
3243     PA.preserve<MemorySSAAnalysis>();
3244   return PA;
3245 }
3246 
3247 void SimpleLoopUnswitchPass::printPipeline(
3248     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
3249   static_cast<PassInfoMixin<SimpleLoopUnswitchPass> *>(this)->printPipeline(
3250       OS, MapClassName2PassName);
3251 
3252   OS << "<";
3253   OS << (NonTrivial ? "" : "no-") << "nontrivial;";
3254   OS << (Trivial ? "" : "no-") << "trivial";
3255   OS << ">";
3256 }
3257 
3258 namespace {
3259 
3260 class SimpleLoopUnswitchLegacyPass : public LoopPass {
3261   bool NonTrivial;
3262 
3263 public:
3264   static char ID; // Pass ID, replacement for typeid
3265 
3266   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
3267       : LoopPass(ID), NonTrivial(NonTrivial) {
3268     initializeSimpleLoopUnswitchLegacyPassPass(
3269         *PassRegistry::getPassRegistry());
3270   }
3271 
3272   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
3273 
3274   void getAnalysisUsage(AnalysisUsage &AU) const override {
3275     AU.addRequired<AssumptionCacheTracker>();
3276     AU.addRequired<TargetTransformInfoWrapperPass>();
3277     AU.addRequired<MemorySSAWrapperPass>();
3278     AU.addPreserved<MemorySSAWrapperPass>();
3279     getLoopAnalysisUsage(AU);
3280   }
3281 };
3282 
3283 } // end anonymous namespace
3284 
3285 bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
3286   if (skipLoop(L))
3287     return false;
3288 
3289   Function &F = *L->getHeader()->getParent();
3290 
3291   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
3292                     << "\n");
3293   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3294   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3295   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3296   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
3297   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3298   MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
3299   MemorySSAUpdater MSSAU(MSSA);
3300 
3301   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
3302   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
3303 
3304   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid, bool PartiallyInvariant,
3305                                ArrayRef<Loop *> NewLoops) {
3306     // If we did a non-trivial unswitch, we have added new (cloned) loops.
3307     for (auto *NewL : NewLoops)
3308       LPM.addLoop(*NewL);
3309 
3310     // If the current loop remains valid, re-add it to the queue. This is
3311     // a little wasteful as we'll finish processing the current loop as well,
3312     // but it is the best we can do in the old PM.
3313     if (CurrentLoopValid) {
3314       // If the current loop has been unswitched using a partially invariant
3315       // condition, we should not re-add the current loop to avoid unswitching
3316       // on the same condition again.
3317       if (!PartiallyInvariant)
3318         LPM.addLoop(*L);
3319     } else
3320       LPM.markLoopAsDeleted(*L);
3321   };
3322 
3323   auto DestroyLoopCB = [&LPM](Loop &L, StringRef /* Name */) {
3324     LPM.markLoopAsDeleted(L);
3325   };
3326 
3327   if (VerifyMemorySSA)
3328     MSSA->verifyMemorySSA();
3329   bool Changed =
3330       unswitchLoop(*L, DT, LI, AC, AA, TTI, true, NonTrivial, UnswitchCB, SE,
3331                    &MSSAU, nullptr, nullptr, DestroyLoopCB);
3332 
3333   if (VerifyMemorySSA)
3334     MSSA->verifyMemorySSA();
3335 
3336   // Historically this pass has had issues with the dominator tree so verify it
3337   // in asserts builds.
3338   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
3339 
3340   return Changed;
3341 }
3342 
3343 char SimpleLoopUnswitchLegacyPass::ID = 0;
3344 INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
3345                       "Simple unswitch loops", false, false)
3346 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3347 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3348 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
3349 INITIALIZE_PASS_DEPENDENCY(LoopPass)
3350 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3351 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
3352 INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
3353                     "Simple unswitch loops", false, false)
3354 
3355 Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
3356   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
3357 }
3358