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