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