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