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