LLVM  14.0.0git
LoopRotationUtils.cpp
Go to the documentation of this file.
1 //===----------------- LoopRotationUtils.cpp -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides utilities to convert a loop into a loop with bottom test.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Debug.h"
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "loop-rotate"
46 
47 STATISTIC(NumNotRotatedDueToHeaderSize,
48  "Number of loops not rotated due to the header size");
49 STATISTIC(NumInstrsHoisted,
50  "Number of instructions hoisted into loop preheader");
51 STATISTIC(NumInstrsDuplicated,
52  "Number of instructions cloned into loop preheader");
53 STATISTIC(NumRotated, "Number of loops rotated");
54 
55 static cl::opt<bool>
56  MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
57  cl::desc("Allow loop rotation multiple times in order to reach "
58  "a better latch exit"));
59 
60 namespace {
61 /// A simple loop rotation transformation.
62 class LoopRotate {
63  const unsigned MaxHeaderSize;
64  LoopInfo *LI;
65  const TargetTransformInfo *TTI;
66  AssumptionCache *AC;
67  DominatorTree *DT;
68  ScalarEvolution *SE;
69  MemorySSAUpdater *MSSAU;
70  const SimplifyQuery &SQ;
71  bool RotationOnly;
72  bool IsUtilMode;
73  bool PrepareForLTO;
74 
75 public:
76  LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
79  const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
80  bool PrepareForLTO)
81  : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
82  MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
83  IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
84  bool processLoop(Loop *L);
85 
86 private:
87  bool rotateLoop(Loop *L, bool SimplifiedLatch);
88  bool simplifyLoopLatch(Loop *L);
89 };
90 } // end anonymous namespace
91 
92 /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
93 /// previously exist in the map, and the value was inserted.
95  bool Inserted = VM.insert({K, V}).second;
96  assert(Inserted);
97  (void)Inserted;
98 }
99 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
100 /// old header into the preheader. If there were uses of the values produced by
101 /// these instruction that were outside of the loop, we have to insert PHI nodes
102 /// to merge the two values. Do this now.
104  BasicBlock *OrigPreheader,
106  ScalarEvolution *SE,
107  SmallVectorImpl<PHINode*> *InsertedPHIs) {
108  // Remove PHI node entries that are no longer live.
109  BasicBlock::iterator I, E = OrigHeader->end();
110  for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
111  PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
112 
113  // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
114  // as necessary.
115  SSAUpdater SSA(InsertedPHIs);
116  for (I = OrigHeader->begin(); I != E; ++I) {
117  Value *OrigHeaderVal = &*I;
118 
119  // If there are no uses of the value (e.g. because it returns void), there
120  // is nothing to rewrite.
121  if (OrigHeaderVal->use_empty())
122  continue;
123 
124  Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
125 
126  // The value now exits in two versions: the initial value in the preheader
127  // and the loop "next" value in the original header.
128  SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
129  // Force re-computation of OrigHeaderVal, as some users now need to use the
130  // new PHI node.
131  if (SE)
132  SE->forgetValue(OrigHeaderVal);
133  SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
134  SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
135 
136  // Visit each use of the OrigHeader instruction.
137  for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
138  UE = OrigHeaderVal->use_end();
139  UI != UE;) {
140  // Grab the use before incrementing the iterator.
141  Use &U = *UI;
142 
143  // Increment the iterator before removing the use from the list.
144  ++UI;
145 
146  // SSAUpdater can't handle a non-PHI use in the same block as an
147  // earlier def. We can easily handle those cases manually.
148  Instruction *UserInst = cast<Instruction>(U.getUser());
149  if (!isa<PHINode>(UserInst)) {
150  BasicBlock *UserBB = UserInst->getParent();
151 
152  // The original users in the OrigHeader are already using the
153  // original definitions.
154  if (UserBB == OrigHeader)
155  continue;
156 
157  // Users in the OrigPreHeader need to use the value to which the
158  // original definitions are mapped.
159  if (UserBB == OrigPreheader) {
160  U = OrigPreHeaderVal;
161  continue;
162  }
163  }
164 
165  // Anything else can be handled by SSAUpdater.
166  SSA.RewriteUse(U);
167  }
168 
169  // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
170  // intrinsics.
172  llvm::findDbgValues(DbgValues, OrigHeaderVal);
173  for (auto &DbgValue : DbgValues) {
174  // The original users in the OrigHeader are already using the original
175  // definitions.
176  BasicBlock *UserBB = DbgValue->getParent();
177  if (UserBB == OrigHeader)
178  continue;
179 
180  // Users in the OrigPreHeader need to use the value to which the
181  // original definitions are mapped and anything else can be handled by
182  // the SSAUpdater. To avoid adding PHINodes, check if the value is
183  // available in UserBB, if not substitute undef.
184  Value *NewVal;
185  if (UserBB == OrigPreheader)
186  NewVal = OrigPreHeaderVal;
187  else if (SSA.HasValueForBlock(UserBB))
188  NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
189  else
190  NewVal = UndefValue::get(OrigHeaderVal->getType());
191  DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
192  }
193  }
194 }
195 
196 // Assuming both header and latch are exiting, look for a phi which is only
197 // used outside the loop (via a LCSSA phi) in the exit from the header.
198 // This means that rotating the loop can remove the phi.
200  BasicBlock *Header = L->getHeader();
201  BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
202  assert(BI && BI->isConditional() && "need header with conditional exit");
203  BasicBlock *HeaderExit = BI->getSuccessor(0);
204  if (L->contains(HeaderExit))
205  HeaderExit = BI->getSuccessor(1);
206 
207  for (auto &Phi : Header->phis()) {
208  // Look for uses of this phi in the loop/via exits other than the header.
209  if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
210  return cast<Instruction>(U)->getParent() != HeaderExit;
211  }))
212  continue;
213  return true;
214  }
215  return false;
216 }
217 
218 // Check that latch exit is deoptimizing (which means - very unlikely to happen)
219 // and there is another exit from the loop which is non-deoptimizing.
220 // If we rotate latch to that exit our loop has a better chance of being fully
221 // canonical.
222 //
223 // It can give false positives in some rare cases.
225  BasicBlock *Latch = L->getLoopLatch();
226  assert(Latch && "need latch");
227  BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
228  // Need normal exiting latch.
229  if (!BI || !BI->isConditional())
230  return false;
231 
232  BasicBlock *Exit = BI->getSuccessor(1);
233  if (L->contains(Exit))
234  Exit = BI->getSuccessor(0);
235 
236  // Latch exit is non-deoptimizing, no need to rotate.
237  if (!Exit->getPostdominatingDeoptimizeCall())
238  return false;
239 
241  L->getUniqueExitBlocks(Exits);
242  if (!Exits.empty()) {
243  // There is at least one non-deoptimizing exit.
244  //
245  // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
246  // as it can conservatively return false for deoptimizing exits with
247  // complex enough control flow down to deoptimize call.
248  //
249  // That means here we can report success for a case where
250  // all exits are deoptimizing but one of them has complex enough
251  // control flow (e.g. with loops).
252  //
253  // That should be a very rare case and false positives for this function
254  // have compile-time effect only.
255  return any_of(Exits, [](const BasicBlock *BB) {
256  return !BB->getPostdominatingDeoptimizeCall();
257  });
258  }
259  return false;
260 }
261 
262 /// Rotate loop LP. Return true if the loop is rotated.
263 ///
264 /// \param SimplifiedLatch is true if the latch was just folded into the final
265 /// loop exit. In this case we may want to rotate even though the new latch is
266 /// now an exiting branch. This rotation would have happened had the latch not
267 /// been simplified. However, if SimplifiedLatch is false, then we avoid
268 /// rotating loops in which the latch exits to avoid excessive or endless
269 /// rotation. LoopRotate should be repeatable and converge to a canonical
270 /// form. This property is satisfied because simplifying the loop latch can only
271 /// happen once across multiple invocations of the LoopRotate pass.
272 ///
273 /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
274 /// so to reach a suitable (non-deoptimizing) exit.
275 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
276  // If the loop has only one block then there is not much to rotate.
277  if (L->getBlocks().size() == 1)
278  return false;
279 
280  bool Rotated = false;
281  do {
282  BasicBlock *OrigHeader = L->getHeader();
283  BasicBlock *OrigLatch = L->getLoopLatch();
284 
285  BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
286  if (!BI || BI->isUnconditional())
287  return Rotated;
288 
289  // If the loop header is not one of the loop exiting blocks then
290  // either this loop is already rotated or it is not
291  // suitable for loop rotation transformations.
292  if (!L->isLoopExiting(OrigHeader))
293  return Rotated;
294 
295  // If the loop latch already contains a branch that leaves the loop then the
296  // loop is already rotated.
297  if (!OrigLatch)
298  return Rotated;
299 
300  // Rotate if either the loop latch does *not* exit the loop, or if the loop
301  // latch was just simplified. Or if we think it will be profitable.
302  if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
305  return Rotated;
306 
307  // Check size of original header and reject loop if it is very big or we can't
308  // duplicate blocks inside it.
309  {
311  CodeMetrics::collectEphemeralValues(L, AC, EphValues);
312 
314  Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
315  if (Metrics.notDuplicatable) {
316  LLVM_DEBUG(
317  dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
318  << " instructions: ";
319  L->dump());
320  return Rotated;
321  }
322  if (Metrics.convergent) {
323  LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
324  "instructions: ";
325  L->dump());
326  return Rotated;
327  }
328  if (Metrics.NumInsts > MaxHeaderSize) {
329  LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
330  << Metrics.NumInsts
331  << " instructions, which is more than the threshold ("
332  << MaxHeaderSize << " instructions): ";
333  L->dump());
334  ++NumNotRotatedDueToHeaderSize;
335  return Rotated;
336  }
337 
338  // When preparing for LTO, avoid rotating loops with calls that could be
339  // inlined during the LTO stage.
340  if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
341  return Rotated;
342  }
343 
344  // Now, this loop is suitable for rotation.
345  BasicBlock *OrigPreheader = L->getLoopPreheader();
346 
347  // If the loop could not be converted to canonical form, it must have an
348  // indirectbr in it, just give up.
349  if (!OrigPreheader || !L->hasDedicatedExits())
350  return Rotated;
351 
352  // Anything ScalarEvolution may know about this loop or the PHI nodes
353  // in its header will soon be invalidated. We should also invalidate
354  // all outer loops because insertion and deletion of blocks that happens
355  // during the rotation may violate invariants related to backedge taken
356  // infos in them.
357  if (SE)
358  SE->forgetTopmostLoop(L);
359 
360  LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
361  if (MSSAU && VerifyMemorySSA)
362  MSSAU->getMemorySSA()->verifyMemorySSA();
363 
364  // Find new Loop header. NewHeader is a Header's one and only successor
365  // that is inside loop. Header's other successor is outside the
366  // loop. Otherwise loop is not suitable for rotation.
367  BasicBlock *Exit = BI->getSuccessor(0);
368  BasicBlock *NewHeader = BI->getSuccessor(1);
369  if (L->contains(Exit))
370  std::swap(Exit, NewHeader);
371  assert(NewHeader && "Unable to determine new loop header");
372  assert(L->contains(NewHeader) && !L->contains(Exit) &&
373  "Unable to determine loop header and exit blocks");
374 
375  // This code assumes that the new header has exactly one predecessor.
376  // Remove any single-entry PHI nodes in it.
377  assert(NewHeader->getSinglePredecessor() &&
378  "New header doesn't have one pred!");
379  FoldSingleEntryPHINodes(NewHeader);
380 
381  // Begin by walking OrigHeader and populating ValueMap with an entry for
382  // each Instruction.
383  BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
384  ValueToValueMapTy ValueMap, ValueMapMSSA;
385 
386  // For PHI nodes, the value available in OldPreHeader is just the
387  // incoming value from OldPreHeader.
388  for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
390  PN->getIncomingValueForBlock(OrigPreheader));
391 
392  // For the rest of the instructions, either hoist to the OrigPreheader if
393  // possible or create a clone in the OldPreHeader if not.
394  Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
395 
396  // Record all debug intrinsics preceding LoopEntryBranch to avoid
397  // duplication.
398  using DbgIntrinsicHash =
399  std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
400  auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
401  auto VarLocOps = D->location_ops();
402  return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
403  D->getVariable()},
404  D->getExpression()};
405  };
407  for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
408  I != E; ++I) {
409  if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&*I))
410  DbgIntrinsics.insert(makeHash(DII));
411  else
412  break;
413  }
414 
415  // Remember the local noalias scope declarations in the header. After the
416  // rotation, they must be duplicated and the scope must be cloned. This
417  // avoids unwanted interaction across iterations.
418  SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
419  for (Instruction &I : *OrigHeader)
420  if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
421  NoAliasDeclInstructions.push_back(Decl);
422 
423  while (I != E) {
424  Instruction *Inst = &*I++;
425 
426  // If the instruction's operands are invariant and it doesn't read or write
427  // memory, then it is safe to hoist. Doing this doesn't change the order of
428  // execution in the preheader, but does prevent the instruction from
429  // executing in each iteration of the loop. This means it is safe to hoist
430  // something that might trap, but isn't safe to hoist something that reads
431  // memory (without proving that the loop doesn't write).
432  if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
433  !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
434  !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
435  Inst->moveBefore(LoopEntryBranch);
436  ++NumInstrsHoisted;
437  continue;
438  }
439 
440  // Otherwise, create a duplicate of the instruction.
441  Instruction *C = Inst->clone();
442  ++NumInstrsDuplicated;
443 
444  // Eagerly remap the operands of the instruction.
447 
448  // Avoid inserting the same intrinsic twice.
449  if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
450  if (DbgIntrinsics.count(makeHash(DII))) {
451  C->deleteValue();
452  continue;
453  }
454 
455  // With the operands remapped, see if the instruction constant folds or is
456  // otherwise simplifyable. This commonly occurs because the entry from PHI
457  // nodes allows icmps and other instructions to fold.
458  Value *V = SimplifyInstruction(C, SQ);
459  if (V && LI->replacementPreservesLCSSAForm(C, V)) {
460  // If so, then delete the temporary instruction and stick the folded value
461  // in the map.
463  if (!C->mayHaveSideEffects()) {
464  C->deleteValue();
465  C = nullptr;
466  }
467  } else {
469  }
470  if (C) {
471  // Otherwise, stick the new instruction into the new block!
472  C->setName(Inst->getName());
473  C->insertBefore(LoopEntryBranch);
474 
475  if (auto *II = dyn_cast<AssumeInst>(C))
476  AC->registerAssumption(II);
477  // MemorySSA cares whether the cloned instruction was inserted or not, and
478  // not whether it can be remapped to a simplified value.
479  if (MSSAU)
480  InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
481  }
482  }
483 
484  if (!NoAliasDeclInstructions.empty()) {
485  // There are noalias scope declarations:
486  // (general):
487  // Original: OrigPre { OrigHeader NewHeader ... Latch }
488  // after: (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
489  //
490  // with D: llvm.experimental.noalias.scope.decl,
491  // U: !noalias or !alias.scope depending on D
492  // ... { D U1 U2 } can transform into:
493  // (0) : ... { D U1 U2 } // no relevant rotation for this part
494  // (1) : ... D' { U1 U2 D } // D is part of OrigHeader
495  // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
496  //
497  // We now want to transform:
498  // (1) -> : ... D' { D U1 U2 D'' }
499  // (2) -> : ... D' U1' { D U2 D'' U1'' }
500  // D: original llvm.experimental.noalias.scope.decl
501  // D', U1': duplicate with replaced scopes
502  // D'', U1'': different duplicate with replaced scopes
503  // This ensures a safe fallback to 'may_alias' introduced by the rotate,
504  // as U1'' and U1' scopes will not be compatible wrt to the local restrict
505 
506  // Clone the llvm.experimental.noalias.decl again for the NewHeader.
507  Instruction *NewHeaderInsertionPoint = &(*NewHeader->getFirstNonPHI());
508  for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
509  LLVM_DEBUG(dbgs() << " Cloning llvm.experimental.noalias.scope.decl:"
510  << *NAD << "\n");
511  Instruction *NewNAD = NAD->clone();
512  NewNAD->insertBefore(NewHeaderInsertionPoint);
513  }
514 
515  // Scopes must now be duplicated, once for OrigHeader and once for
516  // OrigPreHeader'.
517  {
518  auto &Context = NewHeader->getContext();
519 
520  SmallVector<MDNode *, 8> NoAliasDeclScopes;
521  for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
522  NoAliasDeclScopes.push_back(NAD->getScopeList());
523 
524  LLVM_DEBUG(dbgs() << " Updating OrigHeader scopes\n");
525  cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
526  "h.rot");
527  LLVM_DEBUG(OrigHeader->dump());
528 
529  // Keep the compile time impact low by only adapting the inserted block
530  // of instructions in the OrigPreHeader. This might result in slightly
531  // more aliasing between these instructions and those that were already
532  // present, but it will be much faster when the original PreHeader is
533  // large.
534  LLVM_DEBUG(dbgs() << " Updating part of OrigPreheader scopes\n");
535  auto *FirstDecl =
536  cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
537  auto *LastInst = &OrigPreheader->back();
538  cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
539  Context, "pre.rot");
540  LLVM_DEBUG(OrigPreheader->dump());
541 
542  LLVM_DEBUG(dbgs() << " Updated NewHeader:\n");
543  LLVM_DEBUG(NewHeader->dump());
544  }
545  }
546 
547  // Along with all the other instructions, we just cloned OrigHeader's
548  // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
549  // successors by duplicating their incoming values for OrigHeader.
550  for (BasicBlock *SuccBB : successors(OrigHeader))
551  for (BasicBlock::iterator BI = SuccBB->begin();
552  PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
553  PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
554 
555  // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
556  // OrigPreHeader's old terminator (the original branch into the loop), and
557  // remove the corresponding incoming values from the PHI nodes in OrigHeader.
558  LoopEntryBranch->eraseFromParent();
559 
560  // Update MemorySSA before the rewrite call below changes the 1:1
561  // instruction:cloned_instruction_or_value mapping.
562  if (MSSAU) {
563  InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
564  MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
565  ValueMapMSSA);
566  }
567 
568  SmallVector<PHINode*, 2> InsertedPHIs;
569  // If there were any uses of instructions in the duplicated block outside the
570  // loop, update them, inserting PHI nodes as required
571  RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
572  &InsertedPHIs);
573 
574  // Attach dbg.value intrinsics to the new phis if that phi uses a value that
575  // previously had debug metadata attached. This keeps the debug info
576  // up-to-date in the loop body.
577  if (!InsertedPHIs.empty())
578  insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
579 
580  // NewHeader is now the header of the loop.
581  L->moveToHeader(NewHeader);
582  assert(L->getHeader() == NewHeader && "Latch block is our new header");
583 
584  // Inform DT about changes to the CFG.
585  if (DT) {
586  // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
587  // the DT about the removed edge to the OrigHeader (that got removed).
589  Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
590  Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
591  Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
592 
593  if (MSSAU) {
594  MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
595  if (VerifyMemorySSA)
596  MSSAU->getMemorySSA()->verifyMemorySSA();
597  } else {
598  DT->applyUpdates(Updates);
599  }
600  }
601 
602  // At this point, we've finished our major CFG changes. As part of cloning
603  // the loop into the preheader we've simplified instructions and the
604  // duplicated conditional branch may now be branching on a constant. If it is
605  // branching on a constant and if that constant means that we enter the loop,
606  // then we fold away the cond branch to an uncond branch. This simplifies the
607  // loop in cases important for nested loops, and it also means we don't have
608  // to split as many edges.
609  BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
610  assert(PHBI->isConditional() && "Should be clone of BI condbr!");
611  if (!isa<ConstantInt>(PHBI->getCondition()) ||
612  PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
613  NewHeader) {
614  // The conditional branch can't be folded, handle the general case.
615  // Split edges as necessary to preserve LoopSimplify form.
616 
617  // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
618  // thus is not a preheader anymore.
619  // Split the edge to form a real preheader.
620  BasicBlock *NewPH = SplitCriticalEdge(
621  OrigPreheader, NewHeader,
622  CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
623  NewPH->setName(NewHeader->getName() + ".lr.ph");
624 
625  // Preserve canonical loop form, which means that 'Exit' should have only
626  // one predecessor. Note that Exit could be an exit block for multiple
627  // nested loops, causing both of the edges to now be critical and need to
628  // be split.
630  bool SplitLatchEdge = false;
631  for (BasicBlock *ExitPred : ExitPreds) {
632  // We only need to split loop exit edges.
633  Loop *PredLoop = LI->getLoopFor(ExitPred);
634  if (!PredLoop || PredLoop->contains(Exit) ||
635  ExitPred->getTerminator()->isIndirectTerminator())
636  continue;
637  SplitLatchEdge |= L->getLoopLatch() == ExitPred;
638  BasicBlock *ExitSplit = SplitCriticalEdge(
639  ExitPred, Exit,
640  CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
641  ExitSplit->moveBefore(Exit);
642  }
643  assert(SplitLatchEdge &&
644  "Despite splitting all preds, failed to split latch exit?");
645  (void)SplitLatchEdge;
646  } else {
647  // We can fold the conditional branch in the preheader, this makes things
648  // simpler. The first step is to remove the extra edge to the Exit block.
649  Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
650  BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
651  NewBI->setDebugLoc(PHBI->getDebugLoc());
652  PHBI->eraseFromParent();
653 
654  // With our CFG finalized, update DomTree if it is available.
655  if (DT) DT->deleteEdge(OrigPreheader, Exit);
656 
657  // Update MSSA too, if available.
658  if (MSSAU)
659  MSSAU->removeEdge(OrigPreheader, Exit);
660  }
661 
662  assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
663  assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
664 
665  if (MSSAU && VerifyMemorySSA)
666  MSSAU->getMemorySSA()->verifyMemorySSA();
667 
668  // Now that the CFG and DomTree are in a consistent state again, try to merge
669  // the OrigHeader block into OrigLatch. This will succeed if they are
670  // connected by an unconditional branch. This is just a cleanup so the
671  // emitted code isn't too gross in this common case.
673  BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
674  bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
675  if (DidMerge)
676  RemoveRedundantDbgInstrs(PredBB);
677 
678  if (MSSAU && VerifyMemorySSA)
679  MSSAU->getMemorySSA()->verifyMemorySSA();
680 
681  LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
682 
683  ++NumRotated;
684 
685  Rotated = true;
686  SimplifiedLatch = false;
687 
688  // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
689  // Deoptimizing latch exit is not a generally typical case, so we just loop over.
690  // TODO: if it becomes a performance bottleneck extend rotation algorithm
691  // to handle multiple rotations in one go.
693 
694 
695  return true;
696 }
697 
698 /// Determine whether the instructions in this range may be safely and cheaply
699 /// speculated. This is not an important enough situation to develop complex
700 /// heuristics. We handle a single arithmetic instruction along with any type
701 /// conversions.
703  BasicBlock::iterator End, Loop *L) {
704  bool seenIncrement = false;
705  bool MultiExitLoop = false;
706 
707  if (!L->getExitingBlock())
708  MultiExitLoop = true;
709 
710  for (BasicBlock::iterator I = Begin; I != End; ++I) {
711 
713  return false;
714 
715  if (isa<DbgInfoIntrinsic>(I))
716  continue;
717 
718  switch (I->getOpcode()) {
719  default:
720  return false;
721  case Instruction::GetElementPtr:
722  // GEPs are cheap if all indices are constant.
723  if (!cast<GEPOperator>(I)->hasAllConstantIndices())
724  return false;
725  // fall-thru to increment case
727  case Instruction::Add:
728  case Instruction::Sub:
729  case Instruction::And:
730  case Instruction::Or:
731  case Instruction::Xor:
732  case Instruction::Shl:
733  case Instruction::LShr:
734  case Instruction::AShr: {
735  Value *IVOpnd =
736  !isa<Constant>(I->getOperand(0))
737  ? I->getOperand(0)
738  : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
739  if (!IVOpnd)
740  return false;
741 
742  // If increment operand is used outside of the loop, this speculation
743  // could cause extra live range interference.
744  if (MultiExitLoop) {
745  for (User *UseI : IVOpnd->users()) {
746  auto *UserInst = cast<Instruction>(UseI);
747  if (!L->contains(UserInst))
748  return false;
749  }
750  }
751 
752  if (seenIncrement)
753  return false;
754  seenIncrement = true;
755  break;
756  }
757  case Instruction::Trunc:
758  case Instruction::ZExt:
759  case Instruction::SExt:
760  // ignore type conversions
761  break;
762  }
763  }
764  return true;
765 }
766 
767 /// Fold the loop tail into the loop exit by speculating the loop tail
768 /// instructions. Typically, this is a single post-increment. In the case of a
769 /// simple 2-block loop, hoisting the increment can be much better than
770 /// duplicating the entire loop header. In the case of loops with early exits,
771 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
772 /// canonical form so downstream passes can handle it.
773 ///
774 /// I don't believe this invalidates SCEV.
775 bool LoopRotate::simplifyLoopLatch(Loop *L) {
776  BasicBlock *Latch = L->getLoopLatch();
777  if (!Latch || Latch->hasAddressTaken())
778  return false;
779 
780  BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
781  if (!Jmp || !Jmp->isUnconditional())
782  return false;
783 
784  BasicBlock *LastExit = Latch->getSinglePredecessor();
785  if (!LastExit || !L->isLoopExiting(LastExit))
786  return false;
787 
788  BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
789  if (!BI)
790  return false;
791 
792  if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
793  return false;
794 
795  LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
796  << LastExit->getName() << "\n");
797 
799  MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
800  /*PredecessorWithTwoSuccessors=*/true);
801 
802  if (MSSAU && VerifyMemorySSA)
803  MSSAU->getMemorySSA()->verifyMemorySSA();
804 
805  return true;
806 }
807 
808 /// Rotate \c L, and return true if any modification was made.
809 bool LoopRotate::processLoop(Loop *L) {
810  // Save the loop metadata.
811  MDNode *LoopMD = L->getLoopID();
812 
813  bool SimplifiedLatch = false;
814 
815  // Simplify the loop latch before attempting to rotate the header
816  // upward. Rotation may not be needed if the loop tail can be folded into the
817  // loop exit.
818  if (!RotationOnly)
819  SimplifiedLatch = simplifyLoopLatch(L);
820 
821  bool MadeChange = rotateLoop(L, SimplifiedLatch);
822  assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
823  "Loop latch should be exiting after loop-rotate.");
824 
825  // Restore the loop metadata.
826  // NB! We presume LoopRotation DOESN'T ADD its own metadata.
827  if ((MadeChange || SimplifiedLatch) && LoopMD)
828  L->setLoopID(LoopMD);
829 
830  return MadeChange || SimplifiedLatch;
831 }
832 
833 
834 /// The utility to convert a loop into a loop with bottom test.
837  ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
838  const SimplifyQuery &SQ, bool RotationOnly = true,
839  unsigned Threshold = unsigned(-1),
840  bool IsUtilMode = true, bool PrepareForLTO) {
841  LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
842  IsUtilMode, PrepareForLTO);
843  return LR.processLoop(L);
844 }
llvm::NoAliasScopeDeclInst
Definition: IntrinsicInst.h:1227
llvm::Instruction::isTerminator
bool isTerminator() const
Definition: Instruction.h:163
AssumptionCache.h
llvm::BasicBlock::end
iterator end()
Definition: BasicBlock.h:298
llvm::predecessors
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:127
llvm
This file implements support for optimizing divisions by a constant.
Definition: AllocatorList.h:23
ValueMapper.h
llvm::BasicBlock::iterator
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:90
llvm::isSafeToSpeculativelyExecute
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
Definition: ValueTracking.cpp:4609
llvm::BasicBlock::getParent
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:107
IntrinsicInst.h
llvm::SimplifyQuery
Definition: InstructionSimplify.h:94
MemorySSAUpdater.h
shouldSpeculateInstrs
static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, BasicBlock::iterator End, Loop *L)
Determine whether the instructions in this range may be safely and cheaply speculated.
Definition: LoopRotationUtils.cpp:702
llvm::Loop
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:530
llvm::Value::dump
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:4807
llvm::LoopBase::contains
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:122
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
Statistic.h
llvm::CodeMetrics
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition: CodeMetrics.h:30
llvm::TargetTransformInfo
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Definition: TargetTransformInfo.h:168
llvm::SmallDenseSet
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:286
DomTreeUpdater.h
llvm::ScalarEvolution
The main scalar evolution driver.
Definition: ScalarEvolution.h:460
ValueTracking.h
Local.h
llvm::Instruction::insertBefore
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
Definition: Instruction.cpp:84
llvm::DominatorTree
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:151
profitableToRotateLoopExitingLatch
static bool profitableToRotateLoopExitingLatch(Loop *L)
Definition: LoopRotationUtils.cpp:199
GlobalsModRef.h
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:143
ScalarEvolution.h
llvm::SplitCriticalEdge
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
Definition: BreakCriticalEdges.cpp:103
Module.h
llvm::DominatorTreeBase< BasicBlock, false >::Insert
static constexpr UpdateKind Insert
Definition: GenericDomTree.h:242
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:449
llvm::BasicBlock::getSinglePredecessor
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:268
llvm::DIExpression
DWARF expression.
Definition: DebugInfoMetadata.h:2586
llvm::successors
succ_range successors(Instruction *I)
Definition: CFG.h:262
llvm::detail::DenseSetImpl< ValueT, SmallDenseMap< ValueT, detail::DenseSetEmpty, 4, DenseMapInfo< ValueT >, detail::DenseSetPair< ValueT > >, DenseMapInfo< ValueT > >::insert
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:206
BasicAliasAnalysis.h
llvm::detail::DenseSetImpl< ValueT, SmallDenseMap< ValueT, detail::DenseSetEmpty, 4, DenseMapInfo< ValueT >, detail::DenseSetPair< ValueT > >, DenseMapInfo< ValueT > >::count
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:97
llvm::BasicBlock::rend
reverse_iterator rend()
Definition: BasicBlock.h:303
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
MultiRotate
static cl::opt< bool > MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden, cl::desc("Allow loop rotation multiple times in order to reach " "a better latch exit"))
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
Context
LLVMContext & Context
Definition: NVVMIntrRange.cpp:66
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
CommandLine.h
CodeMetrics.h
llvm::RemapInstruction
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:253
llvm::Value::use_iterator
use_iterator_impl< Use > use_iterator
Definition: Value.h:354
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::User
Definition: User.h:44
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::BasicBlock::begin
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:296
llvm::CriticalEdgeSplittingOptions
Option class for critical edge splitting.
Definition: BasicBlockUtils.h:136
llvm::PHINode::getIncomingValueForBlock
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Definition: Instructions.h:2818
llvm::LoopBase::getBlocks
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
Definition: LoopInfo.h:171
llvm::Instruction
Definition: Instruction.h:45
llvm::SimplifyInstruction
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Definition: InstructionSimplify.cpp:6328
llvm::BasicBlock::phis
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:354
llvm::STATISTIC
STATISTIC(NumFunctions, "Total number of functions")
llvm::Value::setName
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:376
llvm::UndefValue::get
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1796
llvm::DomTreeUpdater
Definition: DomTreeUpdater.h:28
llvm::Use::getUser
User * getUser() const
Returns the User that contains this Use.
Definition: Use.h:73
LoopUtils.h
llvm::BasicBlock::rbegin
reverse_iterator rbegin()
Definition: BasicBlock.h:301
llvm::CodeMetrics::collectEphemeralValues
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
Definition: CodeMetrics.cpp:70
llvm::LoopBase::getExitingBlock
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:49
llvm::BasicBlock::getFirstNonPHI
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:216
llvm::RemoveRedundantDbgInstrs
bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
Definition: BasicBlockUtils.cpp:432
llvm::Instruction::mayWriteToMemory
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
Definition: Instruction.cpp:584
llvm::RF_NoModuleLevelChanges
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:72
llvm::Value::use_empty
bool use_empty() const
Definition: Value.h:345
llvm::BasicBlock::getPostdominatingDeoptimizeCall
const CallInst * getPostdominatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize that is present either in current ...
Definition: BasicBlock.cpp:204
CFG.h
llvm::BranchInst::getCondition
Value * getCondition() const
Definition: Instructions.h:3149
llvm::cloneAndAdaptNoAliasScopes
void cloneAndAdaptNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, ArrayRef< BasicBlock * > NewBlocks, LLVMContext &Context, StringRef Ext)
Clone the specified noalias decl scopes.
Definition: CloneFunction.cpp:991
llvm::BasicBlock::hasAddressTaken
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition: BasicBlock.h:448
llvm::cl::opt< bool >
llvm::DbgVariableIntrinsic
This is the common base class for debug info intrinsics for variables.
Definition: IntrinsicInst.h:148
SSA
Memory SSA
Definition: MemorySSA.cpp:73
llvm::Instruction::eraseFromParent
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:78
llvm::LoopBase::moveToHeader
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
Definition: LoopInfo.h:443
D
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
llvm::MemorySSAUpdater
Definition: MemorySSAUpdater.h:56
llvm::LoopBase::getUniqueExitBlocks
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
Definition: LoopInfoImpl.h:122
llvm::PHINode::addIncoming
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Definition: Instructions.h:2783
llvm::BranchInst::Create
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
Definition: Instructions.h:3124
DebugInfo.h
I
#define I(x, y, z)
Definition: MD5.cpp:59
Cloning.h
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:441
Metrics
Machine Trace Metrics
Definition: MachineTraceMetrics.cpp:53
llvm::LoopBase::getLoopPreheader
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:167
RewriteUsesOfClonedInstructions
static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, BasicBlock *OrigPreheader, ValueToValueMapTy &ValueMap, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *InsertedPHIs)
RewriteUsesOfClonedInstructions - We just cloned the instructions from the old header into the prehea...
Definition: LoopRotationUtils.cpp:103
llvm::insertDebugValuesForPHIs
void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
Definition: Local.cpp:1614
llvm::findDbgValues
void findDbgValues(SmallVectorImpl< DbgValueInst * > &DbgValues, Value *V)
Finds the llvm.dbg.value intrinsics describing a value.
Definition: DebugInfo.cpp:76
llvm::Instruction::setDebugLoc
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:367
llvm::ScalarEvolution::forgetValue
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
Definition: ScalarEvolution.cpp:7585
llvm::LoopBase::getLoopLatch
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:216
llvm::LoopBase::hasDedicatedExits
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Definition: LoopInfoImpl.h:92
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::swap
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:840
llvm::ValueMap::insert
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: ValueMap.h:173
llvm::Value::use_begin
use_iterator use_begin()
Definition: Value.h:361
llvm::TTI
TargetTransformInfo TTI
Definition: TargetTransformInfo.h:163
llvm::MDNode
Metadata node.
Definition: Metadata.h:906
canRotateDeoptimizingLatchExit
static bool canRotateDeoptimizingLatchExit(Loop *L)
Definition: LoopRotationUtils.cpp:224
llvm::BranchInst::isUnconditional
bool isUnconditional() const
Definition: Instructions.h:3146
llvm::Instruction::clone
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
Definition: Instruction.cpp:850
llvm::LoopInfo
Definition: LoopInfo.h:1083
llvm::MergeBlockIntoPredecessor
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false)
Attempts to merge a block into its predecessor, if possible.
Definition: BasicBlockUtils.cpp:173
llvm::any_of
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:1558
llvm::AssumptionCache
A cache of @llvm.assume calls within a function.
Definition: AssumptionCache.h:41
LoopPass.h
llvm::Value::getType
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
LoopRotationUtils.h
llvm::BasicBlock::getUniquePredecessor
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:276
llvm::ilist_node_impl::getIterator
self_iterator getIterator()
Definition: ilist_node.h:81
llvm::Value::use_end
use_iterator use_end()
Definition: Value.h:369
llvm::DomTreeUpdater::UpdateStrategy::Eager
@ Eager
SSAUpdater.h
llvm::Instruction::mayReadFromMemory
bool mayReadFromMemory() const
Return true if this instruction may read memory.
Definition: Instruction.cpp:564
llvm::Loop::hasLoopInvariantOperands
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition: LoopInfo.cpp:70
LLVM_FALLTHROUGH
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:286
llvm::Value::getName
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
llvm::ValueMap< const Value *, WeakTrackingVH >
llvm::BasicBlock::getTerminator
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:152
llvm::RF_IgnoreMissingLocals
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition: ValueMapper.h:90
llvm::BasicBlock::getContext
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:36
llvm::Loop::setLoopID
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition: LoopInfo.cpp:527
llvm::Loop::getLoopID
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition: LoopInfo.cpp:503
llvm::LoopRotation
bool LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI, AssumptionCache *AC, DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU, const SimplifyQuery &SQ, bool RotationOnly, unsigned Threshold, bool IsUtilMode, bool PrepareForLTO=false)
Convert a loop into a loop with bottom test.
Definition: LoopRotationUtils.cpp:835
Function.h
llvm::LoopBase::getHeader
BlockT * getHeader() const
Definition: LoopInfo.h:104
llvm::Loop::dump
void dump() const
Definition: LoopInfo.cpp:669
ScalarEvolutionAliasAnalysis.h
llvm::MCID::Add
@ Add
Definition: MCInstrDesc.h:183
llvm::FoldSingleEntryPHINodes
bool FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
Definition: BasicBlockUtils.cpp:138
llvm::BasicBlock::back
const Instruction & back() const
Definition: BasicBlock.h:310
MemorySSA.h
llvm::BasicBlock::moveBefore
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition: BasicBlock.cpp:137
llvm::Instruction::getDebugLoc
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:370
Dominators.h
llvm::hash_combine_range
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:483
llvm::Instruction::getParent
const BasicBlock * getParent() const
Definition: Instruction.h:94
InstructionSimplify.h
TargetTransformInfo.h
llvm::PHINode
Definition: Instructions.h:2633
Threshold
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
llvm::BasicBlock::removePredecessor
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:325
llvm::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:43
InsertNewValueIntoMap
static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V)
Insert (K, V) pair into the ValueToValueMap, and verify the key did not previously exist in the map,...
Definition: LoopRotationUtils.cpp:94
llvm::LoopBase::isLoopExiting
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
Definition: LoopInfo.h:225
BB
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM BB
Definition: README.txt:39
llvm::ValueMap::lookup
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
llvm::VerifyMemorySSA
bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition: MemorySSA.cpp:91
llvm::cl::desc
Definition: CommandLine.h:412
llvm::BranchInst
Conditional or Unconditional Branch instruction.
Definition: Instructions.h:3068
raw_ostream.h
llvm::SSAUpdater
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:38
BasicBlockUtils.h
llvm::Value
LLVM Value Representation.
Definition: Value.h:75
Debug.h
llvm::Value::users
iterator_range< user_iterator > users()
Definition: Value.h:422
llvm::BranchInst::isConditional
bool isConditional() const
Definition: Instructions.h:3147
llvm::BranchInst::getSuccessor
BasicBlock * getSuccessor(unsigned i) const
Definition: Instructions.h:3161
llvm::DominatorTreeBase< BasicBlock, false >::Delete
static constexpr UpdateKind Delete
Definition: GenericDomTree.h:243
llvm::Instruction::moveBefore
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:97
llvm::Use
A Use represents the edge between a Value definition and its users.
Definition: Use.h:44