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