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