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