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