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