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