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