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