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