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