xref: /llvm-project/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp (revision 148861f579dcbdb3f85aec43e0b3a4056ab3e90f)
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       (void)Case;
695       if (!SkippedFirst) {
696         SkippedFirst = true;
697         continue;
698       }
699       CommonSuccBB->removePredecessor(BB,
700                                       /*DontDeleteUselessPHIs*/ true);
701     }
702     // Now nuke the switch and replace it with a direct branch.
703     SI.eraseFromParent();
704     BranchInst::Create(CommonSuccBB, BB);
705   } else if (DefaultExitBB) {
706     assert(SI.getNumCases() > 0 &&
707            "If we had no cases we'd have a common successor!");
708     // Move the last case to the default successor. This is valid as if the
709     // default got unswitched it cannot be reached. This has the advantage of
710     // being simple and keeping the number of edges from this switch to
711     // successors the same, and avoiding any PHI update complexity.
712     auto LastCaseI = std::prev(SI.case_end());
713     SI.setDefaultDest(LastCaseI->getCaseSuccessor());
714     SI.removeCase(LastCaseI);
715   }
716 
717   // Walk the unswitched exit blocks and the unswitched split blocks and update
718   // the dominator tree based on the CFG edits. While we are walking unordered
719   // containers here, the API for applyUpdates takes an unordered list of
720   // updates and requires them to not contain duplicates.
721   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
722   for (auto *UnswitchedExitBB : UnswitchedExitBBs) {
723     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedExitBB});
724     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedExitBB});
725   }
726   for (auto SplitUnswitchedPair : SplitExitBBMap) {
727     auto *UnswitchedBB = SplitUnswitchedPair.second;
728     DTUpdates.push_back({DT.Delete, ParentBB, UnswitchedBB});
729     DTUpdates.push_back({DT.Insert, OldPH, UnswitchedBB});
730   }
731   DT.applyUpdates(DTUpdates);
732   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
733 
734   // We may have changed the nesting relationship for this loop so hoist it to
735   // its correct parent if needed.
736   hoistLoopToNewParent(L, *NewPH, DT, LI);
737 
738   ++NumTrivial;
739   ++NumSwitches;
740   return true;
741 }
742 
743 /// This routine scans the loop to find a branch or switch which occurs before
744 /// any side effects occur. These can potentially be unswitched without
745 /// duplicating the loop. If a branch or switch is successfully unswitched the
746 /// scanning continues to see if subsequent branches or switches have become
747 /// trivial. Once all trivial candidates have been unswitched, this routine
748 /// returns.
749 ///
750 /// The return value indicates whether anything was unswitched (and therefore
751 /// changed).
752 ///
753 /// If `SE` is not null, it will be updated based on the potential loop SCEVs
754 /// invalidated by this.
755 static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT,
756                                          LoopInfo &LI, ScalarEvolution *SE) {
757   bool Changed = false;
758 
759   // If loop header has only one reachable successor we should keep looking for
760   // trivial condition candidates in the successor as well. An alternative is
761   // to constant fold conditions and merge successors into loop header (then we
762   // only need to check header's terminator). The reason for not doing this in
763   // LoopUnswitch pass is that it could potentially break LoopPassManager's
764   // invariants. Folding dead branches could either eliminate the current loop
765   // or make other loops unreachable. LCSSA form might also not be preserved
766   // after deleting branches. The following code keeps traversing loop header's
767   // successors until it finds the trivial condition candidate (condition that
768   // is not a constant). Since unswitching generates branches with constant
769   // conditions, this scenario could be very common in practice.
770   BasicBlock *CurrentBB = L.getHeader();
771   SmallPtrSet<BasicBlock *, 8> Visited;
772   Visited.insert(CurrentBB);
773   do {
774     // Check if there are any side-effecting instructions (e.g. stores, calls,
775     // volatile loads) in the part of the loop that the code *would* execute
776     // without unswitching.
777     if (llvm::any_of(*CurrentBB,
778                      [](Instruction &I) { return I.mayHaveSideEffects(); }))
779       return Changed;
780 
781     TerminatorInst *CurrentTerm = CurrentBB->getTerminator();
782 
783     if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
784       // Don't bother trying to unswitch past a switch with a constant
785       // condition. This should be removed prior to running this pass by
786       // simplify-cfg.
787       if (isa<Constant>(SI->getCondition()))
788         return Changed;
789 
790       if (!unswitchTrivialSwitch(L, *SI, DT, LI, SE))
791         // Couldn't unswitch this one so we're done.
792         return Changed;
793 
794       // Mark that we managed to unswitch something.
795       Changed = true;
796 
797       // If unswitching turned the terminator into an unconditional branch then
798       // we can continue. The unswitching logic specifically works to fold any
799       // cases it can into an unconditional branch to make it easier to
800       // recognize here.
801       auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator());
802       if (!BI || BI->isConditional())
803         return Changed;
804 
805       CurrentBB = BI->getSuccessor(0);
806       continue;
807     }
808 
809     auto *BI = dyn_cast<BranchInst>(CurrentTerm);
810     if (!BI)
811       // We do not understand other terminator instructions.
812       return Changed;
813 
814     // Don't bother trying to unswitch past an unconditional branch or a branch
815     // with a constant value. These should be removed by simplify-cfg prior to
816     // running this pass.
817     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
818       return Changed;
819 
820     // Found a trivial condition candidate: non-foldable conditional branch. If
821     // we fail to unswitch this, we can't do anything else that is trivial.
822     if (!unswitchTrivialBranch(L, *BI, DT, LI, SE))
823       return Changed;
824 
825     // Mark that we managed to unswitch something.
826     Changed = true;
827 
828     // If we only unswitched some of the conditions feeding the branch, we won't
829     // have collapsed it to a single successor.
830     BI = cast<BranchInst>(CurrentBB->getTerminator());
831     if (BI->isConditional())
832       return Changed;
833 
834     // Follow the newly unconditional branch into its successor.
835     CurrentBB = BI->getSuccessor(0);
836 
837     // When continuing, if we exit the loop or reach a previous visited block,
838     // then we can not reach any trivial condition candidates (unfoldable
839     // branch instructions or switch instructions) and no unswitch can happen.
840   } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second);
841 
842   return Changed;
843 }
844 
845 /// Build the cloned blocks for an unswitched copy of the given loop.
846 ///
847 /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and
848 /// after the split block (`SplitBB`) that will be used to select between the
849 /// cloned and original loop.
850 ///
851 /// This routine handles cloning all of the necessary loop blocks and exit
852 /// blocks including rewriting their instructions and the relevant PHI nodes.
853 /// Any loop blocks or exit blocks which are dominated by a different successor
854 /// than the one for this clone of the loop blocks can be trivially skipped. We
855 /// use the `DominatingSucc` map to determine whether a block satisfies that
856 /// property with a simple map lookup.
857 ///
858 /// It also correctly creates the unconditional branch in the cloned
859 /// unswitched parent block to only point at the unswitched successor.
860 ///
861 /// This does not handle most of the necessary updates to `LoopInfo`. Only exit
862 /// block splitting is correctly reflected in `LoopInfo`, essentially all of
863 /// the cloned blocks (and their loops) are left without full `LoopInfo`
864 /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned
865 /// blocks to them but doesn't create the cloned `DominatorTree` structure and
866 /// instead the caller must recompute an accurate DT. It *does* correctly
867 /// update the `AssumptionCache` provided in `AC`.
868 static BasicBlock *buildClonedLoopBlocks(
869     Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB,
870     ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB,
871     BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB,
872     const SmallDenseMap<BasicBlock *, BasicBlock *, 16> &DominatingSucc,
873     ValueToValueMapTy &VMap,
874     SmallVectorImpl<DominatorTree::UpdateType> &DTUpdates, AssumptionCache &AC,
875     DominatorTree &DT, LoopInfo &LI) {
876   SmallVector<BasicBlock *, 4> NewBlocks;
877   NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size());
878 
879   // We will need to clone a bunch of blocks, wrap up the clone operation in
880   // a helper.
881   auto CloneBlock = [&](BasicBlock *OldBB) {
882     // Clone the basic block and insert it before the new preheader.
883     BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent());
884     NewBB->moveBefore(LoopPH);
885 
886     // Record this block and the mapping.
887     NewBlocks.push_back(NewBB);
888     VMap[OldBB] = NewBB;
889 
890     return NewBB;
891   };
892 
893   // We skip cloning blocks when they have a dominating succ that is not the
894   // succ we are cloning for.
895   auto SkipBlock = [&](BasicBlock *BB) {
896     auto It = DominatingSucc.find(BB);
897     return It != DominatingSucc.end() && It->second != UnswitchedSuccBB;
898   };
899 
900   // First, clone the preheader.
901   auto *ClonedPH = CloneBlock(LoopPH);
902 
903   // Then clone all the loop blocks, skipping the ones that aren't necessary.
904   for (auto *LoopBB : L.blocks())
905     if (!SkipBlock(LoopBB))
906       CloneBlock(LoopBB);
907 
908   // Split all the loop exit edges so that when we clone the exit blocks, if
909   // any of the exit blocks are *also* a preheader for some other loop, we
910   // don't create multiple predecessors entering the loop header.
911   for (auto *ExitBB : ExitBlocks) {
912     if (SkipBlock(ExitBB))
913       continue;
914 
915     // When we are going to clone an exit, we don't need to clone all the
916     // instructions in the exit block and we want to ensure we have an easy
917     // place to merge the CFG, so split the exit first. This is always safe to
918     // do because there cannot be any non-loop predecessors of a loop exit in
919     // loop simplified form.
920     auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI);
921 
922     // Rearrange the names to make it easier to write test cases by having the
923     // exit block carry the suffix rather than the merge block carrying the
924     // suffix.
925     MergeBB->takeName(ExitBB);
926     ExitBB->setName(Twine(MergeBB->getName()) + ".split");
927 
928     // Now clone the original exit block.
929     auto *ClonedExitBB = CloneBlock(ExitBB);
930     assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 &&
931            "Exit block should have been split to have one successor!");
932     assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB &&
933            "Cloned exit block has the wrong successor!");
934 
935     // Remap any cloned instructions and create a merge phi node for them.
936     for (auto ZippedInsts : llvm::zip_first(
937              llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())),
938              llvm::make_range(ClonedExitBB->begin(),
939                               std::prev(ClonedExitBB->end())))) {
940       Instruction &I = std::get<0>(ZippedInsts);
941       Instruction &ClonedI = std::get<1>(ZippedInsts);
942 
943       // The only instructions in the exit block should be PHI nodes and
944       // potentially a landing pad.
945       assert(
946           (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) &&
947           "Bad instruction in exit block!");
948       // We should have a value map between the instruction and its clone.
949       assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!");
950 
951       auto *MergePN =
952           PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi",
953                           &*MergeBB->getFirstInsertionPt());
954       I.replaceAllUsesWith(MergePN);
955       MergePN->addIncoming(&I, ExitBB);
956       MergePN->addIncoming(&ClonedI, ClonedExitBB);
957     }
958   }
959 
960   // Rewrite the instructions in the cloned blocks to refer to the instructions
961   // in the cloned blocks. We have to do this as a second pass so that we have
962   // everything available. Also, we have inserted new instructions which may
963   // include assume intrinsics, so we update the assumption cache while
964   // processing this.
965   for (auto *ClonedBB : NewBlocks)
966     for (Instruction &I : *ClonedBB) {
967       RemapInstruction(&I, VMap,
968                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
969       if (auto *II = dyn_cast<IntrinsicInst>(&I))
970         if (II->getIntrinsicID() == Intrinsic::assume)
971           AC.registerAssumption(II);
972     }
973 
974   // Update any PHI nodes in the cloned successors of the skipped blocks to not
975   // have spurious incoming values.
976   for (auto *LoopBB : L.blocks())
977     if (SkipBlock(LoopBB))
978       for (auto *SuccBB : successors(LoopBB))
979         if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB)))
980           for (PHINode &PN : ClonedSuccBB->phis())
981             PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false);
982 
983   // Remove the cloned parent as a predecessor of any successor we ended up
984   // cloning other than the unswitched one.
985   auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB));
986   for (auto *SuccBB : successors(ParentBB)) {
987     if (SuccBB == UnswitchedSuccBB)
988       continue;
989 
990     auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB));
991     if (!ClonedSuccBB)
992       continue;
993 
994     ClonedSuccBB->removePredecessor(ClonedParentBB,
995                                     /*DontDeleteUselessPHIs*/ true);
996   }
997 
998   // Replace the cloned branch with an unconditional branch to the cloned
999   // unswitched successor.
1000   auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB));
1001   ClonedParentBB->getTerminator()->eraseFromParent();
1002   BranchInst::Create(ClonedSuccBB, ClonedParentBB);
1003 
1004   // If there are duplicate entries in the PHI nodes because of multiple edges
1005   // to the unswitched successor, we need to nuke all but one as we replaced it
1006   // with a direct branch.
1007   for (PHINode &PN : ClonedSuccBB->phis()) {
1008     bool Found = false;
1009     // Loop over the incoming operands backwards so we can easily delete as we
1010     // go without invalidating the index.
1011     for (int i = PN.getNumOperands() - 1; i >= 0; --i) {
1012       if (PN.getIncomingBlock(i) != ClonedParentBB)
1013         continue;
1014       if (!Found) {
1015         Found = true;
1016         continue;
1017       }
1018       PN.removeIncomingValue(i, /*DeletePHIIfEmpty*/ false);
1019     }
1020   }
1021 
1022   // Record the domtree updates for the new blocks.
1023   SmallPtrSet<BasicBlock *, 4> SuccSet;
1024   for (auto *ClonedBB : NewBlocks) {
1025     for (auto *SuccBB : successors(ClonedBB))
1026       if (SuccSet.insert(SuccBB).second)
1027         DTUpdates.push_back({DominatorTree::Insert, ClonedBB, SuccBB});
1028     SuccSet.clear();
1029   }
1030 
1031   return ClonedPH;
1032 }
1033 
1034 /// Recursively clone the specified loop and all of its children.
1035 ///
1036 /// The target parent loop for the clone should be provided, or can be null if
1037 /// the clone is a top-level loop. While cloning, all the blocks are mapped
1038 /// with the provided value map. The entire original loop must be present in
1039 /// the value map. The cloned loop is returned.
1040 static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL,
1041                            const ValueToValueMapTy &VMap, LoopInfo &LI) {
1042   auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) {
1043     assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!");
1044     ClonedL.reserveBlocks(OrigL.getNumBlocks());
1045     for (auto *BB : OrigL.blocks()) {
1046       auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB));
1047       ClonedL.addBlockEntry(ClonedBB);
1048       if (LI.getLoopFor(BB) == &OrigL)
1049         LI.changeLoopFor(ClonedBB, &ClonedL);
1050     }
1051   };
1052 
1053   // We specially handle the first loop because it may get cloned into
1054   // a different parent and because we most commonly are cloning leaf loops.
1055   Loop *ClonedRootL = LI.AllocateLoop();
1056   if (RootParentL)
1057     RootParentL->addChildLoop(ClonedRootL);
1058   else
1059     LI.addTopLevelLoop(ClonedRootL);
1060   AddClonedBlocksToLoop(OrigRootL, *ClonedRootL);
1061 
1062   if (OrigRootL.empty())
1063     return ClonedRootL;
1064 
1065   // If we have a nest, we can quickly clone the entire loop nest using an
1066   // iterative approach because it is a tree. We keep the cloned parent in the
1067   // data structure to avoid repeatedly querying through a map to find it.
1068   SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone;
1069   // Build up the loops to clone in reverse order as we'll clone them from the
1070   // back.
1071   for (Loop *ChildL : llvm::reverse(OrigRootL))
1072     LoopsToClone.push_back({ClonedRootL, ChildL});
1073   do {
1074     Loop *ClonedParentL, *L;
1075     std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val();
1076     Loop *ClonedL = LI.AllocateLoop();
1077     ClonedParentL->addChildLoop(ClonedL);
1078     AddClonedBlocksToLoop(*L, *ClonedL);
1079     for (Loop *ChildL : llvm::reverse(*L))
1080       LoopsToClone.push_back({ClonedL, ChildL});
1081   } while (!LoopsToClone.empty());
1082 
1083   return ClonedRootL;
1084 }
1085 
1086 /// Build the cloned loops of an original loop from unswitching.
1087 ///
1088 /// Because unswitching simplifies the CFG of the loop, this isn't a trivial
1089 /// operation. We need to re-verify that there even is a loop (as the backedge
1090 /// may not have been cloned), and even if there are remaining backedges the
1091 /// backedge set may be different. However, we know that each child loop is
1092 /// undisturbed, we only need to find where to place each child loop within
1093 /// either any parent loop or within a cloned version of the original loop.
1094 ///
1095 /// Because child loops may end up cloned outside of any cloned version of the
1096 /// original loop, multiple cloned sibling loops may be created. All of them
1097 /// are returned so that the newly introduced loop nest roots can be
1098 /// identified.
1099 static void buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks,
1100                              const ValueToValueMapTy &VMap, LoopInfo &LI,
1101                              SmallVectorImpl<Loop *> &NonChildClonedLoops) {
1102   Loop *ClonedL = nullptr;
1103 
1104   auto *OrigPH = OrigL.getLoopPreheader();
1105   auto *OrigHeader = OrigL.getHeader();
1106 
1107   auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH));
1108   auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader));
1109 
1110   // We need to know the loops of the cloned exit blocks to even compute the
1111   // accurate parent loop. If we only clone exits to some parent of the
1112   // original parent, we want to clone into that outer loop. We also keep track
1113   // of the loops that our cloned exit blocks participate in.
1114   Loop *ParentL = nullptr;
1115   SmallVector<BasicBlock *, 4> ClonedExitsInLoops;
1116   SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap;
1117   ClonedExitsInLoops.reserve(ExitBlocks.size());
1118   for (auto *ExitBB : ExitBlocks)
1119     if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB)))
1120       if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1121         ExitLoopMap[ClonedExitBB] = ExitL;
1122         ClonedExitsInLoops.push_back(ClonedExitBB);
1123         if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1124           ParentL = ExitL;
1125       }
1126   assert((!ParentL || ParentL == OrigL.getParentLoop() ||
1127           ParentL->contains(OrigL.getParentLoop())) &&
1128          "The computed parent loop should always contain (or be) the parent of "
1129          "the original loop.");
1130 
1131   // We build the set of blocks dominated by the cloned header from the set of
1132   // cloned blocks out of the original loop. While not all of these will
1133   // necessarily be in the cloned loop, it is enough to establish that they
1134   // aren't in unreachable cycles, etc.
1135   SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks;
1136   for (auto *BB : OrigL.blocks())
1137     if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)))
1138       ClonedLoopBlocks.insert(ClonedBB);
1139 
1140   // Rebuild the set of blocks that will end up in the cloned loop. We may have
1141   // skipped cloning some region of this loop which can in turn skip some of
1142   // the backedges so we have to rebuild the blocks in the loop based on the
1143   // backedges that remain after cloning.
1144   SmallVector<BasicBlock *, 16> Worklist;
1145   SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop;
1146   for (auto *Pred : predecessors(ClonedHeader)) {
1147     // The only possible non-loop header predecessor is the preheader because
1148     // we know we cloned the loop in simplified form.
1149     if (Pred == ClonedPH)
1150       continue;
1151 
1152     // Because the loop was in simplified form, the only non-loop predecessor
1153     // should be the preheader.
1154     assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop "
1155                                            "header other than the preheader "
1156                                            "that is not part of the loop!");
1157 
1158     // Insert this block into the loop set and on the first visit (and if it
1159     // isn't the header we're currently walking) put it into the worklist to
1160     // recurse through.
1161     if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader)
1162       Worklist.push_back(Pred);
1163   }
1164 
1165   // If we had any backedges then there *is* a cloned loop. Put the header into
1166   // the loop set and then walk the worklist backwards to find all the blocks
1167   // that remain within the loop after cloning.
1168   if (!BlocksInClonedLoop.empty()) {
1169     BlocksInClonedLoop.insert(ClonedHeader);
1170 
1171     while (!Worklist.empty()) {
1172       BasicBlock *BB = Worklist.pop_back_val();
1173       assert(BlocksInClonedLoop.count(BB) &&
1174              "Didn't put block into the loop set!");
1175 
1176       // Insert any predecessors that are in the possible set into the cloned
1177       // set, and if the insert is successful, add them to the worklist. Note
1178       // that we filter on the blocks that are definitely reachable via the
1179       // backedge to the loop header so we may prune out dead code within the
1180       // cloned loop.
1181       for (auto *Pred : predecessors(BB))
1182         if (ClonedLoopBlocks.count(Pred) &&
1183             BlocksInClonedLoop.insert(Pred).second)
1184           Worklist.push_back(Pred);
1185     }
1186 
1187     ClonedL = LI.AllocateLoop();
1188     if (ParentL) {
1189       ParentL->addBasicBlockToLoop(ClonedPH, LI);
1190       ParentL->addChildLoop(ClonedL);
1191     } else {
1192       LI.addTopLevelLoop(ClonedL);
1193     }
1194     NonChildClonedLoops.push_back(ClonedL);
1195 
1196     ClonedL->reserveBlocks(BlocksInClonedLoop.size());
1197     // We don't want to just add the cloned loop blocks based on how we
1198     // discovered them. The original order of blocks was carefully built in
1199     // a way that doesn't rely on predecessor ordering. Rather than re-invent
1200     // that logic, we just re-walk the original blocks (and those of the child
1201     // loops) and filter them as we add them into the cloned loop.
1202     for (auto *BB : OrigL.blocks()) {
1203       auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB));
1204       if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB))
1205         continue;
1206 
1207       // Directly add the blocks that are only in this loop.
1208       if (LI.getLoopFor(BB) == &OrigL) {
1209         ClonedL->addBasicBlockToLoop(ClonedBB, LI);
1210         continue;
1211       }
1212 
1213       // We want to manually add it to this loop and parents.
1214       // Registering it with LoopInfo will happen when we clone the top
1215       // loop for this block.
1216       for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop())
1217         PL->addBlockEntry(ClonedBB);
1218     }
1219 
1220     // Now add each child loop whose header remains within the cloned loop. All
1221     // of the blocks within the loop must satisfy the same constraints as the
1222     // header so once we pass the header checks we can just clone the entire
1223     // child loop nest.
1224     for (Loop *ChildL : OrigL) {
1225       auto *ClonedChildHeader =
1226           cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1227       if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader))
1228         continue;
1229 
1230 #ifndef NDEBUG
1231       // We should never have a cloned child loop header but fail to have
1232       // all of the blocks for that child loop.
1233       for (auto *ChildLoopBB : ChildL->blocks())
1234         assert(BlocksInClonedLoop.count(
1235                    cast<BasicBlock>(VMap.lookup(ChildLoopBB))) &&
1236                "Child cloned loop has a header within the cloned outer "
1237                "loop but not all of its blocks!");
1238 #endif
1239 
1240       cloneLoopNest(*ChildL, ClonedL, VMap, LI);
1241     }
1242   }
1243 
1244   // Now that we've handled all the components of the original loop that were
1245   // cloned into a new loop, we still need to handle anything from the original
1246   // loop that wasn't in a cloned loop.
1247 
1248   // Figure out what blocks are left to place within any loop nest containing
1249   // the unswitched loop. If we never formed a loop, the cloned PH is one of
1250   // them.
1251   SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet;
1252   if (BlocksInClonedLoop.empty())
1253     UnloopedBlockSet.insert(ClonedPH);
1254   for (auto *ClonedBB : ClonedLoopBlocks)
1255     if (!BlocksInClonedLoop.count(ClonedBB))
1256       UnloopedBlockSet.insert(ClonedBB);
1257 
1258   // Copy the cloned exits and sort them in ascending loop depth, we'll work
1259   // backwards across these to process them inside out. The order shouldn't
1260   // matter as we're just trying to build up the map from inside-out; we use
1261   // the map in a more stably ordered way below.
1262   auto OrderedClonedExitsInLoops = ClonedExitsInLoops;
1263   llvm::sort(OrderedClonedExitsInLoops.begin(), OrderedClonedExitsInLoops.end(),
1264              [&](BasicBlock *LHS, BasicBlock *RHS) {
1265                return ExitLoopMap.lookup(LHS)->getLoopDepth() <
1266                       ExitLoopMap.lookup(RHS)->getLoopDepth();
1267              });
1268 
1269   // Populate the existing ExitLoopMap with everything reachable from each
1270   // exit, starting from the inner most exit.
1271   while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) {
1272     assert(Worklist.empty() && "Didn't clear worklist!");
1273 
1274     BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val();
1275     Loop *ExitL = ExitLoopMap.lookup(ExitBB);
1276 
1277     // Walk the CFG back until we hit the cloned PH adding everything reachable
1278     // and in the unlooped set to this exit block's loop.
1279     Worklist.push_back(ExitBB);
1280     do {
1281       BasicBlock *BB = Worklist.pop_back_val();
1282       // We can stop recursing at the cloned preheader (if we get there).
1283       if (BB == ClonedPH)
1284         continue;
1285 
1286       for (BasicBlock *PredBB : predecessors(BB)) {
1287         // If this pred has already been moved to our set or is part of some
1288         // (inner) loop, no update needed.
1289         if (!UnloopedBlockSet.erase(PredBB)) {
1290           assert(
1291               (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) &&
1292               "Predecessor not mapped to a loop!");
1293           continue;
1294         }
1295 
1296         // We just insert into the loop set here. We'll add these blocks to the
1297         // exit loop after we build up the set in an order that doesn't rely on
1298         // predecessor order (which in turn relies on use list order).
1299         bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second;
1300         (void)Inserted;
1301         assert(Inserted && "Should only visit an unlooped block once!");
1302 
1303         // And recurse through to its predecessors.
1304         Worklist.push_back(PredBB);
1305       }
1306     } while (!Worklist.empty());
1307   }
1308 
1309   // Now that the ExitLoopMap gives as  mapping for all the non-looping cloned
1310   // blocks to their outer loops, walk the cloned blocks and the cloned exits
1311   // in their original order adding them to the correct loop.
1312 
1313   // We need a stable insertion order. We use the order of the original loop
1314   // order and map into the correct parent loop.
1315   for (auto *BB : llvm::concat<BasicBlock *const>(
1316            makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops))
1317     if (Loop *OuterL = ExitLoopMap.lookup(BB))
1318       OuterL->addBasicBlockToLoop(BB, LI);
1319 
1320 #ifndef NDEBUG
1321   for (auto &BBAndL : ExitLoopMap) {
1322     auto *BB = BBAndL.first;
1323     auto *OuterL = BBAndL.second;
1324     assert(LI.getLoopFor(BB) == OuterL &&
1325            "Failed to put all blocks into outer loops!");
1326   }
1327 #endif
1328 
1329   // Now that all the blocks are placed into the correct containing loop in the
1330   // absence of child loops, find all the potentially cloned child loops and
1331   // clone them into whatever outer loop we placed their header into.
1332   for (Loop *ChildL : OrigL) {
1333     auto *ClonedChildHeader =
1334         cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader()));
1335     if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader))
1336       continue;
1337 
1338 #ifndef NDEBUG
1339     for (auto *ChildLoopBB : ChildL->blocks())
1340       assert(VMap.count(ChildLoopBB) &&
1341              "Cloned a child loop header but not all of that loops blocks!");
1342 #endif
1343 
1344     NonChildClonedLoops.push_back(cloneLoopNest(
1345         *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI));
1346   }
1347 }
1348 
1349 static void
1350 deleteDeadClonedBlocks(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1351                        ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
1352                        DominatorTree &DT) {
1353   // Find all the dead clones, and remove them from their successors.
1354   SmallVector<BasicBlock *, 16> DeadBlocks;
1355   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1356     for (auto &VMap : VMaps)
1357       if (BasicBlock *ClonedBB = cast_or_null<BasicBlock>(VMap->lookup(BB)))
1358         if (!DT.isReachableFromEntry(ClonedBB)) {
1359           for (BasicBlock *SuccBB : successors(ClonedBB))
1360             SuccBB->removePredecessor(ClonedBB);
1361           DeadBlocks.push_back(ClonedBB);
1362         }
1363 
1364   // Drop any remaining references to break cycles.
1365   for (BasicBlock *BB : DeadBlocks)
1366     BB->dropAllReferences();
1367   // Erase them from the IR.
1368   for (BasicBlock *BB : DeadBlocks)
1369     BB->eraseFromParent();
1370 }
1371 
1372 static void
1373 deleteDeadBlocksFromLoop(Loop &L,
1374                          SmallVectorImpl<BasicBlock *> &ExitBlocks,
1375                          DominatorTree &DT, LoopInfo &LI) {
1376   // Find all the dead blocks, and remove them from their successors.
1377   SmallVector<BasicBlock *, 16> DeadBlocks;
1378   for (BasicBlock *BB : llvm::concat<BasicBlock *const>(L.blocks(), ExitBlocks))
1379     if (!DT.isReachableFromEntry(BB)) {
1380       for (BasicBlock *SuccBB : successors(BB))
1381         SuccBB->removePredecessor(BB);
1382       DeadBlocks.push_back(BB);
1383     }
1384 
1385   SmallPtrSet<BasicBlock *, 16> DeadBlockSet(DeadBlocks.begin(),
1386                                              DeadBlocks.end());
1387 
1388   // Filter out the dead blocks from the exit blocks list so that it can be
1389   // used in the caller.
1390   llvm::erase_if(ExitBlocks,
1391                  [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1392 
1393   // Walk from this loop up through its parents removing all of the dead blocks.
1394   for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) {
1395     for (auto *BB : DeadBlocks)
1396       ParentL->getBlocksSet().erase(BB);
1397     llvm::erase_if(ParentL->getBlocksVector(),
1398                    [&](BasicBlock *BB) { return DeadBlockSet.count(BB); });
1399   }
1400 
1401   // Now delete the dead child loops. This raw delete will clear them
1402   // recursively.
1403   llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) {
1404     if (!DeadBlockSet.count(ChildL->getHeader()))
1405       return false;
1406 
1407     assert(llvm::all_of(ChildL->blocks(),
1408                         [&](BasicBlock *ChildBB) {
1409                           return DeadBlockSet.count(ChildBB);
1410                         }) &&
1411            "If the child loop header is dead all blocks in the child loop must "
1412            "be dead as well!");
1413     LI.destroy(ChildL);
1414     return true;
1415   });
1416 
1417   // Remove the loop mappings for the dead blocks and drop all the references
1418   // from these blocks to others to handle cyclic references as we start
1419   // deleting the blocks themselves.
1420   for (auto *BB : DeadBlocks) {
1421     // Check that the dominator tree has already been updated.
1422     assert(!DT.getNode(BB) && "Should already have cleared domtree!");
1423     LI.changeLoopFor(BB, nullptr);
1424     BB->dropAllReferences();
1425   }
1426 
1427   // Actually delete the blocks now that they've been fully unhooked from the
1428   // IR.
1429   for (auto *BB : DeadBlocks)
1430     BB->eraseFromParent();
1431 }
1432 
1433 /// Recompute the set of blocks in a loop after unswitching.
1434 ///
1435 /// This walks from the original headers predecessors to rebuild the loop. We
1436 /// take advantage of the fact that new blocks can't have been added, and so we
1437 /// filter by the original loop's blocks. This also handles potentially
1438 /// unreachable code that we don't want to explore but might be found examining
1439 /// the predecessors of the header.
1440 ///
1441 /// If the original loop is no longer a loop, this will return an empty set. If
1442 /// it remains a loop, all the blocks within it will be added to the set
1443 /// (including those blocks in inner loops).
1444 static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L,
1445                                                                  LoopInfo &LI) {
1446   SmallPtrSet<const BasicBlock *, 16> LoopBlockSet;
1447 
1448   auto *PH = L.getLoopPreheader();
1449   auto *Header = L.getHeader();
1450 
1451   // A worklist to use while walking backwards from the header.
1452   SmallVector<BasicBlock *, 16> Worklist;
1453 
1454   // First walk the predecessors of the header to find the backedges. This will
1455   // form the basis of our walk.
1456   for (auto *Pred : predecessors(Header)) {
1457     // Skip the preheader.
1458     if (Pred == PH)
1459       continue;
1460 
1461     // Because the loop was in simplified form, the only non-loop predecessor
1462     // is the preheader.
1463     assert(L.contains(Pred) && "Found a predecessor of the loop header other "
1464                                "than the preheader that is not part of the "
1465                                "loop!");
1466 
1467     // Insert this block into the loop set and on the first visit and, if it
1468     // isn't the header we're currently walking, put it into the worklist to
1469     // recurse through.
1470     if (LoopBlockSet.insert(Pred).second && Pred != Header)
1471       Worklist.push_back(Pred);
1472   }
1473 
1474   // If no backedges were found, we're done.
1475   if (LoopBlockSet.empty())
1476     return LoopBlockSet;
1477 
1478   // We found backedges, recurse through them to identify the loop blocks.
1479   while (!Worklist.empty()) {
1480     BasicBlock *BB = Worklist.pop_back_val();
1481     assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!");
1482 
1483     // No need to walk past the header.
1484     if (BB == Header)
1485       continue;
1486 
1487     // Because we know the inner loop structure remains valid we can use the
1488     // loop structure to jump immediately across the entire nested loop.
1489     // Further, because it is in loop simplified form, we can directly jump
1490     // to its preheader afterward.
1491     if (Loop *InnerL = LI.getLoopFor(BB))
1492       if (InnerL != &L) {
1493         assert(L.contains(InnerL) &&
1494                "Should not reach a loop *outside* this loop!");
1495         // The preheader is the only possible predecessor of the loop so
1496         // insert it into the set and check whether it was already handled.
1497         auto *InnerPH = InnerL->getLoopPreheader();
1498         assert(L.contains(InnerPH) && "Cannot contain an inner loop block "
1499                                       "but not contain the inner loop "
1500                                       "preheader!");
1501         if (!LoopBlockSet.insert(InnerPH).second)
1502           // The only way to reach the preheader is through the loop body
1503           // itself so if it has been visited the loop is already handled.
1504           continue;
1505 
1506         // Insert all of the blocks (other than those already present) into
1507         // the loop set. We expect at least the block that led us to find the
1508         // inner loop to be in the block set, but we may also have other loop
1509         // blocks if they were already enqueued as predecessors of some other
1510         // outer loop block.
1511         for (auto *InnerBB : InnerL->blocks()) {
1512           if (InnerBB == BB) {
1513             assert(LoopBlockSet.count(InnerBB) &&
1514                    "Block should already be in the set!");
1515             continue;
1516           }
1517 
1518           LoopBlockSet.insert(InnerBB);
1519         }
1520 
1521         // Add the preheader to the worklist so we will continue past the
1522         // loop body.
1523         Worklist.push_back(InnerPH);
1524         continue;
1525       }
1526 
1527     // Insert any predecessors that were in the original loop into the new
1528     // set, and if the insert is successful, add them to the worklist.
1529     for (auto *Pred : predecessors(BB))
1530       if (L.contains(Pred) && LoopBlockSet.insert(Pred).second)
1531         Worklist.push_back(Pred);
1532   }
1533 
1534   assert(LoopBlockSet.count(Header) && "Cannot fail to add the header!");
1535 
1536   // We've found all the blocks participating in the loop, return our completed
1537   // set.
1538   return LoopBlockSet;
1539 }
1540 
1541 /// Rebuild a loop after unswitching removes some subset of blocks and edges.
1542 ///
1543 /// The removal may have removed some child loops entirely but cannot have
1544 /// disturbed any remaining child loops. However, they may need to be hoisted
1545 /// to the parent loop (or to be top-level loops). The original loop may be
1546 /// completely removed.
1547 ///
1548 /// The sibling loops resulting from this update are returned. If the original
1549 /// loop remains a valid loop, it will be the first entry in this list with all
1550 /// of the newly sibling loops following it.
1551 ///
1552 /// Returns true if the loop remains a loop after unswitching, and false if it
1553 /// is no longer a loop after unswitching (and should not continue to be
1554 /// referenced).
1555 static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks,
1556                                      LoopInfo &LI,
1557                                      SmallVectorImpl<Loop *> &HoistedLoops) {
1558   auto *PH = L.getLoopPreheader();
1559 
1560   // Compute the actual parent loop from the exit blocks. Because we may have
1561   // pruned some exits the loop may be different from the original parent.
1562   Loop *ParentL = nullptr;
1563   SmallVector<Loop *, 4> ExitLoops;
1564   SmallVector<BasicBlock *, 4> ExitsInLoops;
1565   ExitsInLoops.reserve(ExitBlocks.size());
1566   for (auto *ExitBB : ExitBlocks)
1567     if (Loop *ExitL = LI.getLoopFor(ExitBB)) {
1568       ExitLoops.push_back(ExitL);
1569       ExitsInLoops.push_back(ExitBB);
1570       if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL)))
1571         ParentL = ExitL;
1572     }
1573 
1574   // Recompute the blocks participating in this loop. This may be empty if it
1575   // is no longer a loop.
1576   auto LoopBlockSet = recomputeLoopBlockSet(L, LI);
1577 
1578   // If we still have a loop, we need to re-set the loop's parent as the exit
1579   // block set changing may have moved it within the loop nest. Note that this
1580   // can only happen when this loop has a parent as it can only hoist the loop
1581   // *up* the nest.
1582   if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) {
1583     // Remove this loop's (original) blocks from all of the intervening loops.
1584     for (Loop *IL = L.getParentLoop(); IL != ParentL;
1585          IL = IL->getParentLoop()) {
1586       IL->getBlocksSet().erase(PH);
1587       for (auto *BB : L.blocks())
1588         IL->getBlocksSet().erase(BB);
1589       llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) {
1590         return BB == PH || L.contains(BB);
1591       });
1592     }
1593 
1594     LI.changeLoopFor(PH, ParentL);
1595     L.getParentLoop()->removeChildLoop(&L);
1596     if (ParentL)
1597       ParentL->addChildLoop(&L);
1598     else
1599       LI.addTopLevelLoop(&L);
1600   }
1601 
1602   // Now we update all the blocks which are no longer within the loop.
1603   auto &Blocks = L.getBlocksVector();
1604   auto BlocksSplitI =
1605       LoopBlockSet.empty()
1606           ? Blocks.begin()
1607           : std::stable_partition(
1608                 Blocks.begin(), Blocks.end(),
1609                 [&](BasicBlock *BB) { return LoopBlockSet.count(BB); });
1610 
1611   // Before we erase the list of unlooped blocks, build a set of them.
1612   SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end());
1613   if (LoopBlockSet.empty())
1614     UnloopedBlocks.insert(PH);
1615 
1616   // Now erase these blocks from the loop.
1617   for (auto *BB : make_range(BlocksSplitI, Blocks.end()))
1618     L.getBlocksSet().erase(BB);
1619   Blocks.erase(BlocksSplitI, Blocks.end());
1620 
1621   // Sort the exits in ascending loop depth, we'll work backwards across these
1622   // to process them inside out.
1623   std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(),
1624                    [&](BasicBlock *LHS, BasicBlock *RHS) {
1625                      return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS);
1626                    });
1627 
1628   // We'll build up a set for each exit loop.
1629   SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks;
1630   Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop.
1631 
1632   auto RemoveUnloopedBlocksFromLoop =
1633       [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) {
1634         for (auto *BB : UnloopedBlocks)
1635           L.getBlocksSet().erase(BB);
1636         llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) {
1637           return UnloopedBlocks.count(BB);
1638         });
1639       };
1640 
1641   SmallVector<BasicBlock *, 16> Worklist;
1642   while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) {
1643     assert(Worklist.empty() && "Didn't clear worklist!");
1644     assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!");
1645 
1646     // Grab the next exit block, in decreasing loop depth order.
1647     BasicBlock *ExitBB = ExitsInLoops.pop_back_val();
1648     Loop &ExitL = *LI.getLoopFor(ExitBB);
1649     assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!");
1650 
1651     // Erase all of the unlooped blocks from the loops between the previous
1652     // exit loop and this exit loop. This works because the ExitInLoops list is
1653     // sorted in increasing order of loop depth and thus we visit loops in
1654     // decreasing order of loop depth.
1655     for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop())
1656       RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1657 
1658     // Walk the CFG back until we hit the cloned PH adding everything reachable
1659     // and in the unlooped set to this exit block's loop.
1660     Worklist.push_back(ExitBB);
1661     do {
1662       BasicBlock *BB = Worklist.pop_back_val();
1663       // We can stop recursing at the cloned preheader (if we get there).
1664       if (BB == PH)
1665         continue;
1666 
1667       for (BasicBlock *PredBB : predecessors(BB)) {
1668         // If this pred has already been moved to our set or is part of some
1669         // (inner) loop, no update needed.
1670         if (!UnloopedBlocks.erase(PredBB)) {
1671           assert((NewExitLoopBlocks.count(PredBB) ||
1672                   ExitL.contains(LI.getLoopFor(PredBB))) &&
1673                  "Predecessor not in a nested loop (or already visited)!");
1674           continue;
1675         }
1676 
1677         // We just insert into the loop set here. We'll add these blocks to the
1678         // exit loop after we build up the set in a deterministic order rather
1679         // than the predecessor-influenced visit order.
1680         bool Inserted = NewExitLoopBlocks.insert(PredBB).second;
1681         (void)Inserted;
1682         assert(Inserted && "Should only visit an unlooped block once!");
1683 
1684         // And recurse through to its predecessors.
1685         Worklist.push_back(PredBB);
1686       }
1687     } while (!Worklist.empty());
1688 
1689     // If blocks in this exit loop were directly part of the original loop (as
1690     // opposed to a child loop) update the map to point to this exit loop. This
1691     // just updates a map and so the fact that the order is unstable is fine.
1692     for (auto *BB : NewExitLoopBlocks)
1693       if (Loop *BBL = LI.getLoopFor(BB))
1694         if (BBL == &L || !L.contains(BBL))
1695           LI.changeLoopFor(BB, &ExitL);
1696 
1697     // We will remove the remaining unlooped blocks from this loop in the next
1698     // iteration or below.
1699     NewExitLoopBlocks.clear();
1700   }
1701 
1702   // Any remaining unlooped blocks are no longer part of any loop unless they
1703   // are part of some child loop.
1704   for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop())
1705     RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks);
1706   for (auto *BB : UnloopedBlocks)
1707     if (Loop *BBL = LI.getLoopFor(BB))
1708       if (BBL == &L || !L.contains(BBL))
1709         LI.changeLoopFor(BB, nullptr);
1710 
1711   // Sink all the child loops whose headers are no longer in the loop set to
1712   // the parent (or to be top level loops). We reach into the loop and directly
1713   // update its subloop vector to make this batch update efficient.
1714   auto &SubLoops = L.getSubLoopsVector();
1715   auto SubLoopsSplitI =
1716       LoopBlockSet.empty()
1717           ? SubLoops.begin()
1718           : std::stable_partition(
1719                 SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) {
1720                   return LoopBlockSet.count(SubL->getHeader());
1721                 });
1722   for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) {
1723     HoistedLoops.push_back(HoistedL);
1724     HoistedL->setParentLoop(nullptr);
1725 
1726     // To compute the new parent of this hoisted loop we look at where we
1727     // placed the preheader above. We can't lookup the header itself because we
1728     // retained the mapping from the header to the hoisted loop. But the
1729     // preheader and header should have the exact same new parent computed
1730     // based on the set of exit blocks from the original loop as the preheader
1731     // is a predecessor of the header and so reached in the reverse walk. And
1732     // because the loops were all in simplified form the preheader of the
1733     // hoisted loop can't be part of some *other* loop.
1734     if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader()))
1735       NewParentL->addChildLoop(HoistedL);
1736     else
1737       LI.addTopLevelLoop(HoistedL);
1738   }
1739   SubLoops.erase(SubLoopsSplitI, SubLoops.end());
1740 
1741   // Actually delete the loop if nothing remained within it.
1742   if (Blocks.empty()) {
1743     assert(SubLoops.empty() &&
1744            "Failed to remove all subloops from the original loop!");
1745     if (Loop *ParentL = L.getParentLoop())
1746       ParentL->removeChildLoop(llvm::find(*ParentL, &L));
1747     else
1748       LI.removeLoop(llvm::find(LI, &L));
1749     LI.destroy(&L);
1750     return false;
1751   }
1752 
1753   return true;
1754 }
1755 
1756 /// Helper to visit a dominator subtree, invoking a callable on each node.
1757 ///
1758 /// Returning false at any point will stop walking past that node of the tree.
1759 template <typename CallableT>
1760 void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) {
1761   SmallVector<DomTreeNode *, 4> DomWorklist;
1762   DomWorklist.push_back(DT[BB]);
1763 #ifndef NDEBUG
1764   SmallPtrSet<DomTreeNode *, 4> Visited;
1765   Visited.insert(DT[BB]);
1766 #endif
1767   do {
1768     DomTreeNode *N = DomWorklist.pop_back_val();
1769 
1770     // Visit this node.
1771     if (!Callable(N->getBlock()))
1772       continue;
1773 
1774     // Accumulate the child nodes.
1775     for (DomTreeNode *ChildN : *N) {
1776       assert(Visited.insert(ChildN).second &&
1777              "Cannot visit a node twice when walking a tree!");
1778       DomWorklist.push_back(ChildN);
1779     }
1780   } while (!DomWorklist.empty());
1781 }
1782 
1783 static bool unswitchNontrivialInvariants(
1784     Loop &L, TerminatorInst &TI, ArrayRef<Value *> Invariants,
1785     DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC,
1786     function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
1787     ScalarEvolution *SE) {
1788   auto *ParentBB = TI.getParent();
1789   BranchInst *BI = dyn_cast<BranchInst>(&TI);
1790   SwitchInst *SI = BI ? nullptr : cast<SwitchInst>(&TI);
1791 
1792   // We can only unswitch switches, conditional branches with an invariant
1793   // condition, or combining invariant conditions with an instruction.
1794   assert((SI || BI->isConditional()) &&
1795          "Can only unswitch switches and conditional branch!");
1796   bool FullUnswitch = SI || BI->getCondition() == Invariants[0];
1797   if (FullUnswitch)
1798     assert(Invariants.size() == 1 &&
1799            "Cannot have other invariants with full unswitching!");
1800   else
1801     assert(isa<Instruction>(BI->getCondition()) &&
1802            "Partial unswitching requires an instruction as the condition!");
1803 
1804   // Constant and BBs tracking the cloned and continuing successor. When we are
1805   // unswitching the entire condition, this can just be trivially chosen to
1806   // unswitch towards `true`. However, when we are unswitching a set of
1807   // invariants combined with `and` or `or`, the combining operation determines
1808   // the best direction to unswitch: we want to unswitch the direction that will
1809   // collapse the branch.
1810   bool Direction = true;
1811   int ClonedSucc = 0;
1812   if (!FullUnswitch) {
1813     if (cast<Instruction>(BI->getCondition())->getOpcode() != Instruction::Or) {
1814       assert(cast<Instruction>(BI->getCondition())->getOpcode() ==
1815                  Instruction::And &&
1816              "Only `or` and `and` instructions can combine invariants being "
1817              "unswitched.");
1818       Direction = false;
1819       ClonedSucc = 1;
1820     }
1821   }
1822 
1823   BasicBlock *RetainedSuccBB =
1824       BI ? BI->getSuccessor(1 - ClonedSucc) : SI->getDefaultDest();
1825   SmallSetVector<BasicBlock *, 4> UnswitchedSuccBBs;
1826   if (BI)
1827     UnswitchedSuccBBs.insert(BI->getSuccessor(ClonedSucc));
1828   else
1829     for (auto Case : SI->cases())
1830       if (Case.getCaseSuccessor() != RetainedSuccBB)
1831         UnswitchedSuccBBs.insert(Case.getCaseSuccessor());
1832 
1833   assert(!UnswitchedSuccBBs.count(RetainedSuccBB) &&
1834          "Should not unswitch the same successor we are retaining!");
1835 
1836   // The branch should be in this exact loop. Any inner loop's invariant branch
1837   // should be handled by unswitching that inner loop. The caller of this
1838   // routine should filter out any candidates that remain (but were skipped for
1839   // whatever reason).
1840   assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!");
1841 
1842   SmallVector<BasicBlock *, 4> ExitBlocks;
1843   L.getUniqueExitBlocks(ExitBlocks);
1844 
1845   // We cannot unswitch if exit blocks contain a cleanuppad instruction as we
1846   // don't know how to split those exit blocks.
1847   // FIXME: We should teach SplitBlock to handle this and remove this
1848   // restriction.
1849   for (auto *ExitBB : ExitBlocks)
1850     if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI()))
1851       return false;
1852 
1853   // Compute the parent loop now before we start hacking on things.
1854   Loop *ParentL = L.getParentLoop();
1855 
1856   // Compute the outer-most loop containing one of our exit blocks. This is the
1857   // furthest up our loopnest which can be mutated, which we will use below to
1858   // update things.
1859   Loop *OuterExitL = &L;
1860   for (auto *ExitBB : ExitBlocks) {
1861     Loop *NewOuterExitL = LI.getLoopFor(ExitBB);
1862     if (!NewOuterExitL) {
1863       // We exited the entire nest with this block, so we're done.
1864       OuterExitL = nullptr;
1865       break;
1866     }
1867     if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL))
1868       OuterExitL = NewOuterExitL;
1869   }
1870 
1871   // At this point, we're definitely going to unswitch something so invalidate
1872   // any cached information in ScalarEvolution for the outer most loop
1873   // containing an exit block and all nested loops.
1874   if (SE) {
1875     if (OuterExitL)
1876       SE->forgetLoop(OuterExitL);
1877     else
1878       SE->forgetTopmostLoop(&L);
1879   }
1880 
1881   // If the edge from this terminator to a successor dominates that successor,
1882   // store a map from each block in its dominator subtree to it. This lets us
1883   // tell when cloning for a particular successor if a block is dominated by
1884   // some *other* successor with a single data structure. We use this to
1885   // significantly reduce cloning.
1886   SmallDenseMap<BasicBlock *, BasicBlock *, 16> DominatingSucc;
1887   for (auto *SuccBB : llvm::concat<BasicBlock *const>(
1888            makeArrayRef(RetainedSuccBB), UnswitchedSuccBBs))
1889     if (SuccBB->getUniquePredecessor() ||
1890         llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
1891           return PredBB == ParentBB || DT.dominates(SuccBB, PredBB);
1892         }))
1893       visitDomSubTree(DT, SuccBB, [&](BasicBlock *BB) {
1894         DominatingSucc[BB] = SuccBB;
1895         return true;
1896       });
1897 
1898   // Split the preheader, so that we know that there is a safe place to insert
1899   // the conditional branch. We will change the preheader to have a conditional
1900   // branch on LoopCond. The original preheader will become the split point
1901   // between the unswitched versions, and we will have a new preheader for the
1902   // original loop.
1903   BasicBlock *SplitBB = L.getLoopPreheader();
1904   BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI);
1905 
1906   // Keep track of the dominator tree updates needed.
1907   SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
1908 
1909   // Clone the loop for each unswitched successor.
1910   SmallVector<std::unique_ptr<ValueToValueMapTy>, 4> VMaps;
1911   VMaps.reserve(UnswitchedSuccBBs.size());
1912   SmallDenseMap<BasicBlock *, BasicBlock *, 4> ClonedPHs;
1913   for (auto *SuccBB : UnswitchedSuccBBs) {
1914     VMaps.emplace_back(new ValueToValueMapTy());
1915     ClonedPHs[SuccBB] = buildClonedLoopBlocks(
1916         L, LoopPH, SplitBB, ExitBlocks, ParentBB, SuccBB, RetainedSuccBB,
1917         DominatingSucc, *VMaps.back(), DTUpdates, AC, DT, LI);
1918   }
1919 
1920   // The stitching of the branched code back together depends on whether we're
1921   // doing full unswitching or not with the exception that we always want to
1922   // nuke the initial terminator placed in the split block.
1923   SplitBB->getTerminator()->eraseFromParent();
1924   if (FullUnswitch) {
1925     // First we need to unhook the successor relationship as we'll be replacing
1926     // the terminator with a direct branch. This is much simpler for branches
1927     // than switches so we handle those first.
1928     if (BI) {
1929       // Remove the parent as a predecessor of the unswitched successor.
1930       assert(UnswitchedSuccBBs.size() == 1 &&
1931              "Only one possible unswitched block for a branch!");
1932       BasicBlock *UnswitchedSuccBB = *UnswitchedSuccBBs.begin();
1933       UnswitchedSuccBB->removePredecessor(ParentBB,
1934                                           /*DontDeleteUselessPHIs*/ true);
1935       DTUpdates.push_back({DominatorTree::Delete, ParentBB, UnswitchedSuccBB});
1936     } else {
1937       // Note that we actually want to remove the parent block as a predecessor
1938       // of *every* case successor. The case successor is either unswitched,
1939       // completely eliminating an edge from the parent to that successor, or it
1940       // is a duplicate edge to the retained successor as the retained successor
1941       // is always the default successor and as we'll replace this with a direct
1942       // branch we no longer need the duplicate entries in the PHI nodes.
1943       assert(SI->getDefaultDest() == RetainedSuccBB &&
1944              "Not retaining default successor!");
1945       for (auto &Case : SI->cases())
1946         Case.getCaseSuccessor()->removePredecessor(
1947             ParentBB,
1948             /*DontDeleteUselessPHIs*/ true);
1949 
1950       // We need to use the set to populate domtree updates as even when there
1951       // are multiple cases pointing at the same successor we only want to
1952       // remove and insert one edge in the domtree.
1953       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
1954         DTUpdates.push_back({DominatorTree::Delete, ParentBB, SuccBB});
1955     }
1956 
1957     // Now that we've unhooked the successor relationship, splice the terminator
1958     // from the original loop to the split.
1959     SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), TI);
1960 
1961     // Now wire up the terminator to the preheaders.
1962     if (BI) {
1963       BasicBlock *ClonedPH = ClonedPHs.begin()->second;
1964       BI->setSuccessor(ClonedSucc, ClonedPH);
1965       BI->setSuccessor(1 - ClonedSucc, LoopPH);
1966       DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
1967     } else {
1968       assert(SI && "Must either be a branch or switch!");
1969 
1970       // Walk the cases and directly update their successors.
1971       SI->setDefaultDest(LoopPH);
1972       for (auto &Case : SI->cases())
1973         if (Case.getCaseSuccessor() == RetainedSuccBB)
1974           Case.setSuccessor(LoopPH);
1975         else
1976           Case.setSuccessor(ClonedPHs.find(Case.getCaseSuccessor())->second);
1977 
1978       // We need to use the set to populate domtree updates as even when there
1979       // are multiple cases pointing at the same successor we only want to
1980       // remove and insert one edge in the domtree.
1981       for (BasicBlock *SuccBB : UnswitchedSuccBBs)
1982         DTUpdates.push_back(
1983             {DominatorTree::Insert, SplitBB, ClonedPHs.find(SuccBB)->second});
1984     }
1985 
1986     // Create a new unconditional branch to the continuing block (as opposed to
1987     // the one cloned).
1988     BranchInst::Create(RetainedSuccBB, ParentBB);
1989   } else {
1990     assert(BI && "Only branches have partial unswitching.");
1991     assert(UnswitchedSuccBBs.size() == 1 &&
1992            "Only one possible unswitched block for a branch!");
1993     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
1994     // When doing a partial unswitch, we have to do a bit more work to build up
1995     // the branch in the split block.
1996     buildPartialUnswitchConditionalBranch(*SplitBB, Invariants, Direction,
1997                                           *ClonedPH, *LoopPH);
1998     DTUpdates.push_back({DominatorTree::Insert, SplitBB, ClonedPH});
1999   }
2000 
2001   // Apply the updates accumulated above to get an up-to-date dominator tree.
2002   DT.applyUpdates(DTUpdates);
2003 
2004   // Now that we have an accurate dominator tree, first delete the dead cloned
2005   // blocks so that we can accurately build any cloned loops. It is important to
2006   // not delete the blocks from the original loop yet because we still want to
2007   // reference the original loop to understand the cloned loop's structure.
2008   deleteDeadClonedBlocks(L, ExitBlocks, VMaps, DT);
2009 
2010   // Build the cloned loop structure itself. This may be substantially
2011   // different from the original structure due to the simplified CFG. This also
2012   // handles inserting all the cloned blocks into the correct loops.
2013   SmallVector<Loop *, 4> NonChildClonedLoops;
2014   for (std::unique_ptr<ValueToValueMapTy> &VMap : VMaps)
2015     buildClonedLoops(L, ExitBlocks, *VMap, LI, NonChildClonedLoops);
2016 
2017   // Now that our cloned loops have been built, we can update the original loop.
2018   // First we delete the dead blocks from it and then we rebuild the loop
2019   // structure taking these deletions into account.
2020   deleteDeadBlocksFromLoop(L, ExitBlocks, DT, LI);
2021   SmallVector<Loop *, 4> HoistedLoops;
2022   bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops);
2023 
2024   // This transformation has a high risk of corrupting the dominator tree, and
2025   // the below steps to rebuild loop structures will result in hard to debug
2026   // errors in that case so verify that the dominator tree is sane first.
2027   // FIXME: Remove this when the bugs stop showing up and rely on existing
2028   // verification steps.
2029   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2030 
2031   if (BI) {
2032     // If we unswitched a branch which collapses the condition to a known
2033     // constant we want to replace all the uses of the invariants within both
2034     // the original and cloned blocks. We do this here so that we can use the
2035     // now updated dominator tree to identify which side the users are on.
2036     assert(UnswitchedSuccBBs.size() == 1 &&
2037            "Only one possible unswitched block for a branch!");
2038     BasicBlock *ClonedPH = ClonedPHs.begin()->second;
2039     ConstantInt *UnswitchedReplacement =
2040         Direction ? ConstantInt::getTrue(BI->getContext())
2041                   : ConstantInt::getFalse(BI->getContext());
2042     ConstantInt *ContinueReplacement =
2043         Direction ? ConstantInt::getFalse(BI->getContext())
2044                   : ConstantInt::getTrue(BI->getContext());
2045     for (Value *Invariant : Invariants)
2046       for (auto UI = Invariant->use_begin(), UE = Invariant->use_end();
2047            UI != UE;) {
2048         // Grab the use and walk past it so we can clobber it in the use list.
2049         Use *U = &*UI++;
2050         Instruction *UserI = dyn_cast<Instruction>(U->getUser());
2051         if (!UserI)
2052           continue;
2053 
2054         // Replace it with the 'continue' side if in the main loop body, and the
2055         // unswitched if in the cloned blocks.
2056         if (DT.dominates(LoopPH, UserI->getParent()))
2057           U->set(ContinueReplacement);
2058         else if (DT.dominates(ClonedPH, UserI->getParent()))
2059           U->set(UnswitchedReplacement);
2060       }
2061   }
2062 
2063   // We can change which blocks are exit blocks of all the cloned sibling
2064   // loops, the current loop, and any parent loops which shared exit blocks
2065   // with the current loop. As a consequence, we need to re-form LCSSA for
2066   // them. But we shouldn't need to re-form LCSSA for any child loops.
2067   // FIXME: This could be made more efficient by tracking which exit blocks are
2068   // new, and focusing on them, but that isn't likely to be necessary.
2069   //
2070   // In order to reasonably rebuild LCSSA we need to walk inside-out across the
2071   // loop nest and update every loop that could have had its exits changed. We
2072   // also need to cover any intervening loops. We add all of these loops to
2073   // a list and sort them by loop depth to achieve this without updating
2074   // unnecessary loops.
2075   auto UpdateLoop = [&](Loop &UpdateL) {
2076 #ifndef NDEBUG
2077     UpdateL.verifyLoop();
2078     for (Loop *ChildL : UpdateL) {
2079       ChildL->verifyLoop();
2080       assert(ChildL->isRecursivelyLCSSAForm(DT, LI) &&
2081              "Perturbed a child loop's LCSSA form!");
2082     }
2083 #endif
2084     // First build LCSSA for this loop so that we can preserve it when
2085     // forming dedicated exits. We don't want to perturb some other loop's
2086     // LCSSA while doing that CFG edit.
2087     formLCSSA(UpdateL, DT, &LI, nullptr);
2088 
2089     // For loops reached by this loop's original exit blocks we may
2090     // introduced new, non-dedicated exits. At least try to re-form dedicated
2091     // exits for these loops. This may fail if they couldn't have dedicated
2092     // exits to start with.
2093     formDedicatedExitBlocks(&UpdateL, &DT, &LI, /*PreserveLCSSA*/ true);
2094   };
2095 
2096   // For non-child cloned loops and hoisted loops, we just need to update LCSSA
2097   // and we can do it in any order as they don't nest relative to each other.
2098   //
2099   // Also check if any of the loops we have updated have become top-level loops
2100   // as that will necessitate widening the outer loop scope.
2101   for (Loop *UpdatedL :
2102        llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) {
2103     UpdateLoop(*UpdatedL);
2104     if (!UpdatedL->getParentLoop())
2105       OuterExitL = nullptr;
2106   }
2107   if (IsStillLoop) {
2108     UpdateLoop(L);
2109     if (!L.getParentLoop())
2110       OuterExitL = nullptr;
2111   }
2112 
2113   // If the original loop had exit blocks, walk up through the outer most loop
2114   // of those exit blocks to update LCSSA and form updated dedicated exits.
2115   if (OuterExitL != &L)
2116     for (Loop *OuterL = ParentL; OuterL != OuterExitL;
2117          OuterL = OuterL->getParentLoop())
2118       UpdateLoop(*OuterL);
2119 
2120 #ifndef NDEBUG
2121   // Verify the entire loop structure to catch any incorrect updates before we
2122   // progress in the pass pipeline.
2123   LI.verify(DT);
2124 #endif
2125 
2126   // Now that we've unswitched something, make callbacks to report the changes.
2127   // For that we need to merge together the updated loops and the cloned loops
2128   // and check whether the original loop survived.
2129   SmallVector<Loop *, 4> SibLoops;
2130   for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops))
2131     if (UpdatedL->getParentLoop() == ParentL)
2132       SibLoops.push_back(UpdatedL);
2133   UnswitchCB(IsStillLoop, SibLoops);
2134 
2135   ++NumBranches;
2136   return true;
2137 }
2138 
2139 /// Recursively compute the cost of a dominator subtree based on the per-block
2140 /// cost map provided.
2141 ///
2142 /// The recursive computation is memozied into the provided DT-indexed cost map
2143 /// to allow querying it for most nodes in the domtree without it becoming
2144 /// quadratic.
2145 static int
2146 computeDomSubtreeCost(DomTreeNode &N,
2147                       const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap,
2148                       SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) {
2149   // Don't accumulate cost (or recurse through) blocks not in our block cost
2150   // map and thus not part of the duplication cost being considered.
2151   auto BBCostIt = BBCostMap.find(N.getBlock());
2152   if (BBCostIt == BBCostMap.end())
2153     return 0;
2154 
2155   // Lookup this node to see if we already computed its cost.
2156   auto DTCostIt = DTCostMap.find(&N);
2157   if (DTCostIt != DTCostMap.end())
2158     return DTCostIt->second;
2159 
2160   // If not, we have to compute it. We can't use insert above and update
2161   // because computing the cost may insert more things into the map.
2162   int Cost = std::accumulate(
2163       N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) {
2164         return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap);
2165       });
2166   bool Inserted = DTCostMap.insert({&N, Cost}).second;
2167   (void)Inserted;
2168   assert(Inserted && "Should not insert a node while visiting children!");
2169   return Cost;
2170 }
2171 
2172 static bool
2173 unswitchBestCondition(Loop &L, DominatorTree &DT, LoopInfo &LI,
2174                       AssumptionCache &AC, TargetTransformInfo &TTI,
2175                       function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2176                       ScalarEvolution *SE) {
2177   // Collect all invariant conditions within this loop (as opposed to an inner
2178   // loop which would be handled when visiting that inner loop).
2179   SmallVector<std::pair<TerminatorInst *, TinyPtrVector<Value *>>, 4>
2180       UnswitchCandidates;
2181   for (auto *BB : L.blocks()) {
2182     if (LI.getLoopFor(BB) != &L)
2183       continue;
2184 
2185     if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2186       // We can only consider fully loop-invariant switch conditions as we need
2187       // to completely eliminate the switch after unswitching.
2188       if (!isa<Constant>(SI->getCondition()) &&
2189           L.isLoopInvariant(SI->getCondition()))
2190         UnswitchCandidates.push_back({SI, {SI->getCondition()}});
2191       continue;
2192     }
2193 
2194     auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
2195     if (!BI || !BI->isConditional() || isa<Constant>(BI->getCondition()) ||
2196         BI->getSuccessor(0) == BI->getSuccessor(1))
2197       continue;
2198 
2199     if (L.isLoopInvariant(BI->getCondition())) {
2200       UnswitchCandidates.push_back({BI, {BI->getCondition()}});
2201       continue;
2202     }
2203 
2204     Instruction &CondI = *cast<Instruction>(BI->getCondition());
2205     if (CondI.getOpcode() != Instruction::And &&
2206       CondI.getOpcode() != Instruction::Or)
2207       continue;
2208 
2209     TinyPtrVector<Value *> Invariants =
2210         collectHomogenousInstGraphLoopInvariants(L, CondI, LI);
2211     if (Invariants.empty())
2212       continue;
2213 
2214     UnswitchCandidates.push_back({BI, std::move(Invariants)});
2215   }
2216 
2217   // If we didn't find any candidates, we're done.
2218   if (UnswitchCandidates.empty())
2219     return false;
2220 
2221   // Check if there are irreducible CFG cycles in this loop. If so, we cannot
2222   // easily unswitch non-trivial edges out of the loop. Doing so might turn the
2223   // irreducible control flow into reducible control flow and introduce new
2224   // loops "out of thin air". If we ever discover important use cases for doing
2225   // this, we can add support to loop unswitch, but it is a lot of complexity
2226   // for what seems little or no real world benefit.
2227   LoopBlocksRPO RPOT(&L);
2228   RPOT.perform(&LI);
2229   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
2230     return false;
2231 
2232   LLVM_DEBUG(
2233       dbgs() << "Considering " << UnswitchCandidates.size()
2234              << " non-trivial loop invariant conditions for unswitching.\n");
2235 
2236   // Given that unswitching these terminators will require duplicating parts of
2237   // the loop, so we need to be able to model that cost. Compute the ephemeral
2238   // values and set up a data structure to hold per-BB costs. We cache each
2239   // block's cost so that we don't recompute this when considering different
2240   // subsets of the loop for duplication during unswitching.
2241   SmallPtrSet<const Value *, 4> EphValues;
2242   CodeMetrics::collectEphemeralValues(&L, &AC, EphValues);
2243   SmallDenseMap<BasicBlock *, int, 4> BBCostMap;
2244 
2245   // Compute the cost of each block, as well as the total loop cost. Also, bail
2246   // out if we see instructions which are incompatible with loop unswitching
2247   // (convergent, noduplicate, or cross-basic-block tokens).
2248   // FIXME: We might be able to safely handle some of these in non-duplicated
2249   // regions.
2250   int LoopCost = 0;
2251   for (auto *BB : L.blocks()) {
2252     int Cost = 0;
2253     for (auto &I : *BB) {
2254       if (EphValues.count(&I))
2255         continue;
2256 
2257       if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
2258         return false;
2259       if (auto CS = CallSite(&I))
2260         if (CS.isConvergent() || CS.cannotDuplicate())
2261           return false;
2262 
2263       Cost += TTI.getUserCost(&I);
2264     }
2265     assert(Cost >= 0 && "Must not have negative costs!");
2266     LoopCost += Cost;
2267     assert(LoopCost >= 0 && "Must not have negative loop costs!");
2268     BBCostMap[BB] = Cost;
2269   }
2270   LLVM_DEBUG(dbgs() << "  Total loop cost: " << LoopCost << "\n");
2271 
2272   // Now we find the best candidate by searching for the one with the following
2273   // properties in order:
2274   //
2275   // 1) An unswitching cost below the threshold
2276   // 2) The smallest number of duplicated unswitch candidates (to avoid
2277   //    creating redundant subsequent unswitching)
2278   // 3) The smallest cost after unswitching.
2279   //
2280   // We prioritize reducing fanout of unswitch candidates provided the cost
2281   // remains below the threshold because this has a multiplicative effect.
2282   //
2283   // This requires memoizing each dominator subtree to avoid redundant work.
2284   //
2285   // FIXME: Need to actually do the number of candidates part above.
2286   SmallDenseMap<DomTreeNode *, int, 4> DTCostMap;
2287   // Given a terminator which might be unswitched, computes the non-duplicated
2288   // cost for that terminator.
2289   auto ComputeUnswitchedCost = [&](TerminatorInst &TI, bool FullUnswitch) {
2290     BasicBlock &BB = *TI.getParent();
2291     SmallPtrSet<BasicBlock *, 4> Visited;
2292 
2293     int Cost = LoopCost;
2294     for (BasicBlock *SuccBB : successors(&BB)) {
2295       // Don't count successors more than once.
2296       if (!Visited.insert(SuccBB).second)
2297         continue;
2298 
2299       // If this is a partial unswitch candidate, then it must be a conditional
2300       // branch with a condition of either `or` or `and`. In that case, one of
2301       // the successors is necessarily duplicated, so don't even try to remove
2302       // its cost.
2303       if (!FullUnswitch) {
2304         auto &BI = cast<BranchInst>(TI);
2305         if (cast<Instruction>(BI.getCondition())->getOpcode() ==
2306             Instruction::And) {
2307           if (SuccBB == BI.getSuccessor(1))
2308             continue;
2309         } else {
2310           assert(cast<Instruction>(BI.getCondition())->getOpcode() ==
2311                      Instruction::Or &&
2312                  "Only `and` and `or` conditions can result in a partial "
2313                  "unswitch!");
2314           if (SuccBB == BI.getSuccessor(0))
2315             continue;
2316         }
2317       }
2318 
2319       // This successor's domtree will not need to be duplicated after
2320       // unswitching if the edge to the successor dominates it (and thus the
2321       // entire tree). This essentially means there is no other path into this
2322       // subtree and so it will end up live in only one clone of the loop.
2323       if (SuccBB->getUniquePredecessor() ||
2324           llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) {
2325             return PredBB == &BB || DT.dominates(SuccBB, PredBB);
2326           })) {
2327         Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap);
2328         assert(Cost >= 0 &&
2329                "Non-duplicated cost should never exceed total loop cost!");
2330       }
2331     }
2332 
2333     // Now scale the cost by the number of unique successors minus one. We
2334     // subtract one because there is already at least one copy of the entire
2335     // loop. This is computing the new cost of unswitching a condition.
2336     assert(Visited.size() > 1 &&
2337            "Cannot unswitch a condition without multiple distinct successors!");
2338     return Cost * (Visited.size() - 1);
2339   };
2340   TerminatorInst *BestUnswitchTI = nullptr;
2341   int BestUnswitchCost;
2342   ArrayRef<Value *> BestUnswitchInvariants;
2343   for (auto &TerminatorAndInvariants : UnswitchCandidates) {
2344     TerminatorInst &TI = *TerminatorAndInvariants.first;
2345     ArrayRef<Value *> Invariants = TerminatorAndInvariants.second;
2346     BranchInst *BI = dyn_cast<BranchInst>(&TI);
2347     int CandidateCost = ComputeUnswitchedCost(
2348         TI, /*FullUnswitch*/ !BI || (Invariants.size() == 1 &&
2349                                      Invariants[0] == BI->getCondition()));
2350     LLVM_DEBUG(dbgs() << "  Computed cost of " << CandidateCost
2351                       << " for unswitch candidate: " << TI << "\n");
2352     if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) {
2353       BestUnswitchTI = &TI;
2354       BestUnswitchCost = CandidateCost;
2355       BestUnswitchInvariants = Invariants;
2356     }
2357   }
2358 
2359   if (BestUnswitchCost >= UnswitchThreshold) {
2360     LLVM_DEBUG(dbgs() << "Cannot unswitch, lowest cost found: "
2361                       << BestUnswitchCost << "\n");
2362     return false;
2363   }
2364 
2365   LLVM_DEBUG(dbgs() << "  Trying to unswitch non-trivial (cost = "
2366                     << BestUnswitchCost << ") terminator: " << *BestUnswitchTI
2367                     << "\n");
2368   return unswitchNontrivialInvariants(
2369       L, *BestUnswitchTI, BestUnswitchInvariants, DT, LI, AC, UnswitchCB, SE);
2370 }
2371 
2372 /// Unswitch control flow predicated on loop invariant conditions.
2373 ///
2374 /// This first hoists all branches or switches which are trivial (IE, do not
2375 /// require duplicating any part of the loop) out of the loop body. It then
2376 /// looks at other loop invariant control flows and tries to unswitch those as
2377 /// well by cloning the loop if the result is small enough.
2378 ///
2379 /// The `DT`, `LI`, `AC`, `TTI` parameters are required analyses that are also
2380 /// updated based on the unswitch.
2381 ///
2382 /// If either `NonTrivial` is true or the flag `EnableNonTrivialUnswitch` is
2383 /// true, we will attempt to do non-trivial unswitching as well as trivial
2384 /// unswitching.
2385 ///
2386 /// The `UnswitchCB` callback provided will be run after unswitching is
2387 /// complete, with the first parameter set to `true` if the provided loop
2388 /// remains a loop, and a list of new sibling loops created.
2389 ///
2390 /// If `SE` is non-null, we will update that analysis based on the unswitching
2391 /// done.
2392 static bool unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI,
2393                          AssumptionCache &AC, TargetTransformInfo &TTI,
2394                          bool NonTrivial,
2395                          function_ref<void(bool, ArrayRef<Loop *>)> UnswitchCB,
2396                          ScalarEvolution *SE) {
2397   assert(L.isRecursivelyLCSSAForm(DT, LI) &&
2398          "Loops must be in LCSSA form before unswitching.");
2399   bool Changed = false;
2400 
2401   // Must be in loop simplified form: we need a preheader and dedicated exits.
2402   if (!L.isLoopSimplifyForm())
2403     return false;
2404 
2405   // Try trivial unswitch first before loop over other basic blocks in the loop.
2406   if (unswitchAllTrivialConditions(L, DT, LI, SE)) {
2407     // If we unswitched successfully we will want to clean up the loop before
2408     // processing it further so just mark it as unswitched and return.
2409     UnswitchCB(/*CurrentLoopValid*/ true, {});
2410     return true;
2411   }
2412 
2413   // If we're not doing non-trivial unswitching, we're done. We both accept
2414   // a parameter but also check a local flag that can be used for testing
2415   // a debugging.
2416   if (!NonTrivial && !EnableNonTrivialUnswitch)
2417     return false;
2418 
2419   // For non-trivial unswitching, because it often creates new loops, we rely on
2420   // the pass manager to iterate on the loops rather than trying to immediately
2421   // reach a fixed point. There is no substantial advantage to iterating
2422   // internally, and if any of the new loops are simplified enough to contain
2423   // trivial unswitching we want to prefer those.
2424 
2425   // Try to unswitch the best invariant condition. We prefer this full unswitch to
2426   // a partial unswitch when possible below the threshold.
2427   if (unswitchBestCondition(L, DT, LI, AC, TTI, UnswitchCB, SE))
2428     return true;
2429 
2430   // No other opportunities to unswitch.
2431   return Changed;
2432 }
2433 
2434 PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM,
2435                                               LoopStandardAnalysisResults &AR,
2436                                               LPMUpdater &U) {
2437   Function &F = *L.getHeader()->getParent();
2438   (void)F;
2439 
2440   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L
2441                     << "\n");
2442 
2443   // Save the current loop name in a variable so that we can report it even
2444   // after it has been deleted.
2445   std::string LoopName = L.getName();
2446 
2447   auto UnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid,
2448                                         ArrayRef<Loop *> NewLoops) {
2449     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2450     if (!NewLoops.empty())
2451       U.addSiblingLoops(NewLoops);
2452 
2453     // If the current loop remains valid, we should revisit it to catch any
2454     // other unswitch opportunities. Otherwise, we need to mark it as deleted.
2455     if (CurrentLoopValid)
2456       U.revisitCurrentLoop();
2457     else
2458       U.markLoopAsDeleted(L, LoopName);
2459   };
2460 
2461   if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, UnswitchCB,
2462                     &AR.SE))
2463     return PreservedAnalyses::all();
2464 
2465   // Historically this pass has had issues with the dominator tree so verify it
2466   // in asserts builds.
2467   assert(AR.DT.verify(DominatorTree::VerificationLevel::Fast));
2468   return getLoopPassPreservedAnalyses();
2469 }
2470 
2471 namespace {
2472 
2473 class SimpleLoopUnswitchLegacyPass : public LoopPass {
2474   bool NonTrivial;
2475 
2476 public:
2477   static char ID; // Pass ID, replacement for typeid
2478 
2479   explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false)
2480       : LoopPass(ID), NonTrivial(NonTrivial) {
2481     initializeSimpleLoopUnswitchLegacyPassPass(
2482         *PassRegistry::getPassRegistry());
2483   }
2484 
2485   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
2486 
2487   void getAnalysisUsage(AnalysisUsage &AU) const override {
2488     AU.addRequired<AssumptionCacheTracker>();
2489     AU.addRequired<TargetTransformInfoWrapperPass>();
2490     getLoopAnalysisUsage(AU);
2491   }
2492 };
2493 
2494 } // end anonymous namespace
2495 
2496 bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
2497   if (skipLoop(L))
2498     return false;
2499 
2500   Function &F = *L->getHeader()->getParent();
2501 
2502   LLVM_DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L
2503                     << "\n");
2504 
2505   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2506   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2507   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2508   auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2509 
2510   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
2511   auto *SE = SEWP ? &SEWP->getSE() : nullptr;
2512 
2513   auto UnswitchCB = [&L, &LPM](bool CurrentLoopValid,
2514                                ArrayRef<Loop *> NewLoops) {
2515     // If we did a non-trivial unswitch, we have added new (cloned) loops.
2516     for (auto *NewL : NewLoops)
2517       LPM.addLoop(*NewL);
2518 
2519     // If the current loop remains valid, re-add it to the queue. This is
2520     // a little wasteful as we'll finish processing the current loop as well,
2521     // but it is the best we can do in the old PM.
2522     if (CurrentLoopValid)
2523       LPM.addLoop(*L);
2524     else
2525       LPM.markLoopAsDeleted(*L);
2526   };
2527 
2528   bool Changed = unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, UnswitchCB, SE);
2529 
2530   // If anything was unswitched, also clear any cached information about this
2531   // loop.
2532   LPM.deleteSimpleAnalysisLoop(L);
2533 
2534   // Historically this pass has had issues with the dominator tree so verify it
2535   // in asserts builds.
2536   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
2537 
2538   return Changed;
2539 }
2540 
2541 char SimpleLoopUnswitchLegacyPass::ID = 0;
2542 INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2543                       "Simple unswitch loops", false, false)
2544 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2545 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2546 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
2547 INITIALIZE_PASS_DEPENDENCY(LoopPass)
2548 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2549 INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch",
2550                     "Simple unswitch loops", false, false)
2551 
2552 Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) {
2553   return new SimpleLoopUnswitchLegacyPass(NonTrivial);
2554 }
2555