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