LLVM  8.0.0svn
LoopRotationUtils.cpp
Go to the documentation of this file.
1 //===----------------- LoopRotationUtils.cpp -----------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides utilities to convert a loop into a loop with bottom test.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/IR/CFG.h"
31 #include "llvm/IR/DomTreeUpdater.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Module.h"
37 #include "llvm/Support/Debug.h"
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "loop-rotate"
47 
48 STATISTIC(NumRotated, "Number of loops rotated");
49 
50 namespace {
51 /// A simple loop rotation transformation.
52 class LoopRotate {
53  const unsigned MaxHeaderSize;
54  LoopInfo *LI;
55  const TargetTransformInfo *TTI;
56  AssumptionCache *AC;
57  DominatorTree *DT;
58  ScalarEvolution *SE;
59  MemorySSAUpdater *MSSAU;
60  const SimplifyQuery &SQ;
61  bool RotationOnly;
62  bool IsUtilMode;
63 
64 public:
65  LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
66  const TargetTransformInfo *TTI, AssumptionCache *AC,
68  const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode)
69  : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
70  MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
71  IsUtilMode(IsUtilMode) {}
72  bool processLoop(Loop *L);
73 
74 private:
75  bool rotateLoop(Loop *L, bool SimplifiedLatch);
76  bool simplifyLoopLatch(Loop *L);
77 };
78 } // end anonymous namespace
79 
80 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
81 /// old header into the preheader. If there were uses of the values produced by
82 /// these instruction that were outside of the loop, we have to insert PHI nodes
83 /// to merge the two values. Do this now.
85  BasicBlock *OrigPreheader,
87  SmallVectorImpl<PHINode*> *InsertedPHIs) {
88  // Remove PHI node entries that are no longer live.
89  BasicBlock::iterator I, E = OrigHeader->end();
90  for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
91  PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
92 
93  // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
94  // as necessary.
95  SSAUpdater SSA(InsertedPHIs);
96  for (I = OrigHeader->begin(); I != E; ++I) {
97  Value *OrigHeaderVal = &*I;
98 
99  // If there are no uses of the value (e.g. because it returns void), there
100  // is nothing to rewrite.
101  if (OrigHeaderVal->use_empty())
102  continue;
103 
104  Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
105 
106  // The value now exits in two versions: the initial value in the preheader
107  // and the loop "next" value in the original header.
108  SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
109  SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
110  SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
111 
112  // Visit each use of the OrigHeader instruction.
113  for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
114  UE = OrigHeaderVal->use_end();
115  UI != UE;) {
116  // Grab the use before incrementing the iterator.
117  Use &U = *UI;
118 
119  // Increment the iterator before removing the use from the list.
120  ++UI;
121 
122  // SSAUpdater can't handle a non-PHI use in the same block as an
123  // earlier def. We can easily handle those cases manually.
124  Instruction *UserInst = cast<Instruction>(U.getUser());
125  if (!isa<PHINode>(UserInst)) {
126  BasicBlock *UserBB = UserInst->getParent();
127 
128  // The original users in the OrigHeader are already using the
129  // original definitions.
130  if (UserBB == OrigHeader)
131  continue;
132 
133  // Users in the OrigPreHeader need to use the value to which the
134  // original definitions are mapped.
135  if (UserBB == OrigPreheader) {
136  U = OrigPreHeaderVal;
137  continue;
138  }
139  }
140 
141  // Anything else can be handled by SSAUpdater.
142  SSA.RewriteUse(U);
143  }
144 
145  // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
146  // intrinsics.
148  llvm::findDbgValues(DbgValues, OrigHeaderVal);
149  for (auto &DbgValue : DbgValues) {
150  // The original users in the OrigHeader are already using the original
151  // definitions.
152  BasicBlock *UserBB = DbgValue->getParent();
153  if (UserBB == OrigHeader)
154  continue;
155 
156  // Users in the OrigPreHeader need to use the value to which the
157  // original definitions are mapped and anything else can be handled by
158  // the SSAUpdater. To avoid adding PHINodes, check if the value is
159  // available in UserBB, if not substitute undef.
160  Value *NewVal;
161  if (UserBB == OrigPreheader)
162  NewVal = OrigPreHeaderVal;
163  else if (SSA.HasValueForBlock(UserBB))
164  NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
165  else
166  NewVal = UndefValue::get(OrigHeaderVal->getType());
167  DbgValue->setOperand(0,
168  MetadataAsValue::get(OrigHeaderVal->getContext(),
169  ValueAsMetadata::get(NewVal)));
170  }
171  }
172 }
173 
174 // Look for a phi which is only used outside the loop (via a LCSSA phi)
175 // in the exit from the header. This means that rotating the loop can
176 // remove the phi.
178  BasicBlock *Header = L->getHeader();
179  BasicBlock *HeaderExit = Header->getTerminator()->getSuccessor(0);
180  if (L->contains(HeaderExit))
181  HeaderExit = Header->getTerminator()->getSuccessor(1);
182 
183  for (auto &Phi : Header->phis()) {
184  // Look for uses of this phi in the loop/via exits other than the header.
185  if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
186  return cast<Instruction>(U)->getParent() != HeaderExit;
187  }))
188  continue;
189  return true;
190  }
191 
192  return false;
193 }
194 
195 /// Rotate loop LP. Return true if the loop is rotated.
196 ///
197 /// \param SimplifiedLatch is true if the latch was just folded into the final
198 /// loop exit. In this case we may want to rotate even though the new latch is
199 /// now an exiting branch. This rotation would have happened had the latch not
200 /// been simplified. However, if SimplifiedLatch is false, then we avoid
201 /// rotating loops in which the latch exits to avoid excessive or endless
202 /// rotation. LoopRotate should be repeatable and converge to a canonical
203 /// form. This property is satisfied because simplifying the loop latch can only
204 /// happen once across multiple invocations of the LoopRotate pass.
205 bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
206  // If the loop has only one block then there is not much to rotate.
207  if (L->getBlocks().size() == 1)
208  return false;
209 
210  BasicBlock *OrigHeader = L->getHeader();
211  BasicBlock *OrigLatch = L->getLoopLatch();
212 
213  BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
214  if (!BI || BI->isUnconditional())
215  return false;
216 
217  // If the loop header is not one of the loop exiting blocks then
218  // either this loop is already rotated or it is not
219  // suitable for loop rotation transformations.
220  if (!L->isLoopExiting(OrigHeader))
221  return false;
222 
223  // If the loop latch already contains a branch that leaves the loop then the
224  // loop is already rotated.
225  if (!OrigLatch)
226  return false;
227 
228  // Rotate if either the loop latch does *not* exit the loop, or if the loop
229  // latch was just simplified. Or if we think it will be profitable.
230  if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
232  return false;
233 
234  // Check size of original header and reject loop if it is very big or we can't
235  // duplicate blocks inside it.
236  {
238  CodeMetrics::collectEphemeralValues(L, AC, EphValues);
239 
241  Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
242  if (Metrics.notDuplicatable) {
243  LLVM_DEBUG(
244  dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
245  << " instructions: ";
246  L->dump());
247  return false;
248  }
249  if (Metrics.convergent) {
250  LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
251  "instructions: ";
252  L->dump());
253  return false;
254  }
255  if (Metrics.NumInsts > MaxHeaderSize)
256  return false;
257  }
258 
259  // Now, this loop is suitable for rotation.
260  BasicBlock *OrigPreheader = L->getLoopPreheader();
261 
262  // If the loop could not be converted to canonical form, it must have an
263  // indirectbr in it, just give up.
264  if (!OrigPreheader || !L->hasDedicatedExits())
265  return false;
266 
267  // Anything ScalarEvolution may know about this loop or the PHI nodes
268  // in its header will soon be invalidated. We should also invalidate
269  // all outer loops because insertion and deletion of blocks that happens
270  // during the rotation may violate invariants related to backedge taken
271  // infos in them.
272  if (SE)
273  SE->forgetTopmostLoop(L);
274 
275  LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
276  if (MSSAU && VerifyMemorySSA)
277  MSSAU->getMemorySSA()->verifyMemorySSA();
278 
279  // Find new Loop header. NewHeader is a Header's one and only successor
280  // that is inside loop. Header's other successor is outside the
281  // loop. Otherwise loop is not suitable for rotation.
282  BasicBlock *Exit = BI->getSuccessor(0);
283  BasicBlock *NewHeader = BI->getSuccessor(1);
284  if (L->contains(Exit))
285  std::swap(Exit, NewHeader);
286  assert(NewHeader && "Unable to determine new loop header");
287  assert(L->contains(NewHeader) && !L->contains(Exit) &&
288  "Unable to determine loop header and exit blocks");
289 
290  // This code assumes that the new header has exactly one predecessor.
291  // Remove any single-entry PHI nodes in it.
292  assert(NewHeader->getSinglePredecessor() &&
293  "New header doesn't have one pred!");
294  FoldSingleEntryPHINodes(NewHeader);
295 
296  // Begin by walking OrigHeader and populating ValueMap with an entry for
297  // each Instruction.
298  BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
300 
301  // For PHI nodes, the value available in OldPreHeader is just the
302  // incoming value from OldPreHeader.
303  for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
304  ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
305 
306  // For the rest of the instructions, either hoist to the OrigPreheader if
307  // possible or create a clone in the OldPreHeader if not.
308  Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
309 
310  // Record all debug intrinsics preceding LoopEntryBranch to avoid duplication.
311  using DbgIntrinsicHash =
312  std::pair<std::pair<Value *, DILocalVariable *>, DIExpression *>;
313  auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
314  return {{D->getVariableLocation(), D->getVariable()}, D->getExpression()};
315  };
317  for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
318  I != E; ++I) {
319  if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&*I))
320  DbgIntrinsics.insert(makeHash(DII));
321  else
322  break;
323  }
324 
325  while (I != E) {
326  Instruction *Inst = &*I++;
327 
328  // If the instruction's operands are invariant and it doesn't read or write
329  // memory, then it is safe to hoist. Doing this doesn't change the order of
330  // execution in the preheader, but does prevent the instruction from
331  // executing in each iteration of the loop. This means it is safe to hoist
332  // something that might trap, but isn't safe to hoist something that reads
333  // memory (without proving that the loop doesn't write).
334  if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
335  !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
336  !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
337  Inst->moveBefore(LoopEntryBranch);
338  continue;
339  }
340 
341  // Otherwise, create a duplicate of the instruction.
342  Instruction *C = Inst->clone();
343 
344  // Eagerly remap the operands of the instruction.
345  RemapInstruction(C, ValueMap,
347 
348  // Avoid inserting the same intrinsic twice.
349  if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
350  if (DbgIntrinsics.count(makeHash(DII))) {
351  C->deleteValue();
352  continue;
353  }
354 
355  // With the operands remapped, see if the instruction constant folds or is
356  // otherwise simplifyable. This commonly occurs because the entry from PHI
357  // nodes allows icmps and other instructions to fold.
358  Value *V = SimplifyInstruction(C, SQ);
359  if (V && LI->replacementPreservesLCSSAForm(C, V)) {
360  // If so, then delete the temporary instruction and stick the folded value
361  // in the map.
362  ValueMap[Inst] = V;
363  if (!C->mayHaveSideEffects()) {
364  C->deleteValue();
365  C = nullptr;
366  }
367  } else {
368  ValueMap[Inst] = C;
369  }
370  if (C) {
371  // Otherwise, stick the new instruction into the new block!
372  C->setName(Inst->getName());
373  C->insertBefore(LoopEntryBranch);
374 
375  if (auto *II = dyn_cast<IntrinsicInst>(C))
376  if (II->getIntrinsicID() == Intrinsic::assume)
377  AC->registerAssumption(II);
378  }
379  }
380 
381  // Along with all the other instructions, we just cloned OrigHeader's
382  // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
383  // successors by duplicating their incoming values for OrigHeader.
384  for (BasicBlock *SuccBB : successors(OrigHeader))
385  for (BasicBlock::iterator BI = SuccBB->begin();
386  PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
387  PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
388 
389  // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
390  // OrigPreHeader's old terminator (the original branch into the loop), and
391  // remove the corresponding incoming values from the PHI nodes in OrigHeader.
392  LoopEntryBranch->eraseFromParent();
393 
394  // Update MemorySSA before the rewrite call below changes the 1:1
395  // instruction:cloned_instruction_or_value mapping in ValueMap.
396  if (MSSAU) {
397  ValueMap[OrigHeader] = OrigPreheader;
398  MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader, ValueMap);
399  }
400 
401  SmallVector<PHINode*, 2> InsertedPHIs;
402  // If there were any uses of instructions in the duplicated block outside the
403  // loop, update them, inserting PHI nodes as required
404  RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
405  &InsertedPHIs);
406 
407  // Attach dbg.value intrinsics to the new phis if that phi uses a value that
408  // previously had debug metadata attached. This keeps the debug info
409  // up-to-date in the loop body.
410  if (!InsertedPHIs.empty())
411  insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
412 
413  // NewHeader is now the header of the loop.
414  L->moveToHeader(NewHeader);
415  assert(L->getHeader() == NewHeader && "Latch block is our new header");
416 
417  // Inform DT about changes to the CFG.
418  if (DT) {
419  // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
420  // the DT about the removed edge to the OrigHeader (that got removed).
422  Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
423  Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
424  Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
425  DT->applyUpdates(Updates);
426 
427  if (MSSAU) {
428  MSSAU->applyUpdates(Updates, *DT);
429  if (VerifyMemorySSA)
430  MSSAU->getMemorySSA()->verifyMemorySSA();
431  }
432  }
433 
434  // At this point, we've finished our major CFG changes. As part of cloning
435  // the loop into the preheader we've simplified instructions and the
436  // duplicated conditional branch may now be branching on a constant. If it is
437  // branching on a constant and if that constant means that we enter the loop,
438  // then we fold away the cond branch to an uncond branch. This simplifies the
439  // loop in cases important for nested loops, and it also means we don't have
440  // to split as many edges.
441  BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
442  assert(PHBI->isConditional() && "Should be clone of BI condbr!");
443  if (!isa<ConstantInt>(PHBI->getCondition()) ||
444  PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
445  NewHeader) {
446  // The conditional branch can't be folded, handle the general case.
447  // Split edges as necessary to preserve LoopSimplify form.
448 
449  // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
450  // thus is not a preheader anymore.
451  // Split the edge to form a real preheader.
452  BasicBlock *NewPH = SplitCriticalEdge(
453  OrigPreheader, NewHeader,
454  CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
455  NewPH->setName(NewHeader->getName() + ".lr.ph");
456 
457  // Preserve canonical loop form, which means that 'Exit' should have only
458  // one predecessor. Note that Exit could be an exit block for multiple
459  // nested loops, causing both of the edges to now be critical and need to
460  // be split.
461  SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
462  bool SplitLatchEdge = false;
463  for (BasicBlock *ExitPred : ExitPreds) {
464  // We only need to split loop exit edges.
465  Loop *PredLoop = LI->getLoopFor(ExitPred);
466  if (!PredLoop || PredLoop->contains(Exit))
467  continue;
468  if (isa<IndirectBrInst>(ExitPred->getTerminator()))
469  continue;
470  SplitLatchEdge |= L->getLoopLatch() == ExitPred;
471  BasicBlock *ExitSplit = SplitCriticalEdge(
472  ExitPred, Exit,
473  CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
474  ExitSplit->moveBefore(Exit);
475  }
476  assert(SplitLatchEdge &&
477  "Despite splitting all preds, failed to split latch exit?");
478  } else {
479  // We can fold the conditional branch in the preheader, this makes things
480  // simpler. The first step is to remove the extra edge to the Exit block.
481  Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
482  BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
483  NewBI->setDebugLoc(PHBI->getDebugLoc());
484  PHBI->eraseFromParent();
485 
486  // With our CFG finalized, update DomTree if it is available.
487  if (DT) DT->deleteEdge(OrigPreheader, Exit);
488 
489  // Update MSSA too, if available.
490  if (MSSAU)
491  MSSAU->removeEdge(OrigPreheader, Exit);
492  }
493 
494  assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
495  assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
496 
497  if (MSSAU && VerifyMemorySSA)
498  MSSAU->getMemorySSA()->verifyMemorySSA();
499 
500  // Now that the CFG and DomTree are in a consistent state again, try to merge
501  // the OrigHeader block into OrigLatch. This will succeed if they are
502  // connected by an unconditional branch. This is just a cleanup so the
503  // emitted code isn't too gross in this common case.
505  MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
506 
507  if (MSSAU && VerifyMemorySSA)
508  MSSAU->getMemorySSA()->verifyMemorySSA();
509 
510  LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
511 
512  ++NumRotated;
513  return true;
514 }
515 
516 /// Determine whether the instructions in this range may be safely and cheaply
517 /// speculated. This is not an important enough situation to develop complex
518 /// heuristics. We handle a single arithmetic instruction along with any type
519 /// conversions.
521  BasicBlock::iterator End, Loop *L) {
522  bool seenIncrement = false;
523  bool MultiExitLoop = false;
524 
525  if (!L->getExitingBlock())
526  MultiExitLoop = true;
527 
528  for (BasicBlock::iterator I = Begin; I != End; ++I) {
529 
531  return false;
532 
533  if (isa<DbgInfoIntrinsic>(I))
534  continue;
535 
536  switch (I->getOpcode()) {
537  default:
538  return false;
539  case Instruction::GetElementPtr:
540  // GEPs are cheap if all indices are constant.
541  if (!cast<GEPOperator>(I)->hasAllConstantIndices())
542  return false;
543  // fall-thru to increment case
545  case Instruction::Add:
546  case Instruction::Sub:
547  case Instruction::And:
548  case Instruction::Or:
549  case Instruction::Xor:
550  case Instruction::Shl:
551  case Instruction::LShr:
552  case Instruction::AShr: {
553  Value *IVOpnd =
554  !isa<Constant>(I->getOperand(0))
555  ? I->getOperand(0)
556  : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
557  if (!IVOpnd)
558  return false;
559 
560  // If increment operand is used outside of the loop, this speculation
561  // could cause extra live range interference.
562  if (MultiExitLoop) {
563  for (User *UseI : IVOpnd->users()) {
564  auto *UserInst = cast<Instruction>(UseI);
565  if (!L->contains(UserInst))
566  return false;
567  }
568  }
569 
570  if (seenIncrement)
571  return false;
572  seenIncrement = true;
573  break;
574  }
575  case Instruction::Trunc:
576  case Instruction::ZExt:
577  case Instruction::SExt:
578  // ignore type conversions
579  break;
580  }
581  }
582  return true;
583 }
584 
585 /// Fold the loop tail into the loop exit by speculating the loop tail
586 /// instructions. Typically, this is a single post-increment. In the case of a
587 /// simple 2-block loop, hoisting the increment can be much better than
588 /// duplicating the entire loop header. In the case of loops with early exits,
589 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
590 /// canonical form so downstream passes can handle it.
591 ///
592 /// I don't believe this invalidates SCEV.
593 bool LoopRotate::simplifyLoopLatch(Loop *L) {
594  BasicBlock *Latch = L->getLoopLatch();
595  if (!Latch || Latch->hasAddressTaken())
596  return false;
597 
598  BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
599  if (!Jmp || !Jmp->isUnconditional())
600  return false;
601 
602  BasicBlock *LastExit = Latch->getSinglePredecessor();
603  if (!LastExit || !L->isLoopExiting(LastExit))
604  return false;
605 
606  BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
607  if (!BI)
608  return false;
609 
610  if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
611  return false;
612 
613  LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
614  << LastExit->getName() << "\n");
615 
616  // Hoist the instructions from Latch into LastExit.
617  Instruction *FirstLatchInst = &*(Latch->begin());
618  LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
619  Latch->begin(), Jmp->getIterator());
620 
621  // Update MemorySSA
622  if (MSSAU)
623  MSSAU->moveAllAfterMergeBlocks(Latch, LastExit, FirstLatchInst);
624 
625  unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
626  BasicBlock *Header = Jmp->getSuccessor(0);
627  assert(Header == L->getHeader() && "expected a backward branch");
628 
629  // Remove Latch from the CFG so that LastExit becomes the new Latch.
630  BI->setSuccessor(FallThruPath, Header);
631  Latch->replaceSuccessorsPhiUsesWith(LastExit);
632  Jmp->eraseFromParent();
633 
634  // Nuke the Latch block.
635  assert(Latch->empty() && "unable to evacuate Latch");
636  LI->removeBlock(Latch);
637  if (DT)
638  DT->eraseNode(Latch);
639  Latch->eraseFromParent();
640 
641  if (MSSAU && VerifyMemorySSA)
642  MSSAU->getMemorySSA()->verifyMemorySSA();
643 
644  return true;
645 }
646 
647 /// Rotate \c L, and return true if any modification was made.
648 bool LoopRotate::processLoop(Loop *L) {
649  // Save the loop metadata.
650  MDNode *LoopMD = L->getLoopID();
651 
652  bool SimplifiedLatch = false;
653 
654  // Simplify the loop latch before attempting to rotate the header
655  // upward. Rotation may not be needed if the loop tail can be folded into the
656  // loop exit.
657  if (!RotationOnly)
658  SimplifiedLatch = simplifyLoopLatch(L);
659 
660  bool MadeChange = rotateLoop(L, SimplifiedLatch);
661  assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
662  "Loop latch should be exiting after loop-rotate.");
663 
664  // Restore the loop metadata.
665  // NB! We presume LoopRotation DOESN'T ADD its own metadata.
666  if ((MadeChange || SimplifiedLatch) && LoopMD)
667  L->setLoopID(LoopMD);
668 
669  return MadeChange || SimplifiedLatch;
670 }
671 
672 
673 /// The utility to convert a loop into a loop with bottom test.
676  ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
677  const SimplifyQuery &SQ, bool RotationOnly = true,
678  unsigned Threshold = unsigned(-1),
679  bool IsUtilMode = true) {
680  if (MSSAU && VerifyMemorySSA)
681  MSSAU->getMemorySSA()->verifyMemorySSA();
682  LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
683  IsUtilMode);
684  if (MSSAU && VerifyMemorySSA)
685  MSSAU->getMemorySSA()->verifyMemorySSA();
686 
687  return LR.processLoop(L);
688 }
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop&#39;s ephemeral values (those used only by an assume or similar intrinsics in the loop)...
Definition: CodeMetrics.cpp:72
uint64_t CallInst * C
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:68
use_iterator use_end()
Definition: Value.h:347
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
Definition: BasicBlock.cpp:304
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:39
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:225
bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition: MemorySSA.cpp:84
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
This is the interface for a simple mod/ref and alias analysis over globals.
bool convergent
True if this function contains a call to a convergent function.
Definition: CodeMetrics.h:57
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type &#39;Ty&#39;.
Definition: SSAUpdater.cpp:54
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr)
Attempts to merge a block into its predecessor, if possible.
#define LLVM_FALLTHROUGH
Definition: Compiler.h:86
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Definition: LoopInfoImpl.h:86
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
Definition: SSAUpdater.cpp:72
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:379
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:174
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, BasicBlock::iterator End, Loop *L)
Determine whether the instructions in this range may be safely and cheaply speculated.
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
bool isTerminator() const
Definition: Instruction.h:129
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:99
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:864
reverse_iterator rend()
Definition: BasicBlock.h:276
reverse_iterator rbegin()
Definition: BasicBlock.h:274
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:138
bool notDuplicatable
True if this function cannot be duplicated.
Definition: CodeMetrics.h:54
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition: LoopInfo.cpp:64
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:269
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
This is the interface for a SCEV-based alias analysis.
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
Option class for critical edge splitting.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:286
BlockT * getHeader() const
Definition: LoopInfo.h:100
void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode *> &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
Definition: Local.cpp:1445
bool empty() const
Definition: BasicBlock.h:280
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Definition: Use.cpp:41
void findDbgValues(SmallVectorImpl< DbgValueInst *> &DbgValues, Value *V)
Finds the llvm.dbg.value intrinsics describing a value.
Definition: Local.cpp:1511
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
Definition: LoopInfo.cpp:239
This is the common base class for debug info intrinsics for variables.
Definition: IntrinsicInst.h:88
Memory SSA
Definition: MemorySSA.cpp:66
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:171
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:145
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:73
use_iterator_impl< Use > use_iterator
Definition: Value.h:332
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:106
void replaceSuccessorsPhiUsesWith(BasicBlock *New)
Update all phi nodes in this basic block&#39;s successors to refer to basic block New instead of to it...
Definition: BasicBlock.cpp:448
Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block...
Definition: SSAUpdater.cpp:100
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:308
void dump() const
Definition: LoopInfo.cpp:371
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:236
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:74
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
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:203
static bool shouldRotateLoopExitingLatch(Loop *L)
Conditional or Unconditional Branch instruction.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Machine Trace Metrics
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Definition: Instruction.h:562
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:113
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value *> &EphValues)
Add information about a block to the current state.
void splice(iterator where, iplist_impl &L2)
Definition: ilist.h:329
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1055
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)
Convert a loop into a loop with bottom test.
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:116
self_iterator getIterator()
Definition: ilist_node.h:82
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1392
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:392
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:334
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:110
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
Definition: MemorySSA.cpp:1701
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
iterator end()
Definition: BasicBlock.h:271
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:349
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition: CodeMetrics.h:42
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
DWARF expression.
void setOperand(unsigned i, Value *Val)
Definition: User.h:175
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
Implements a dense probed hash-table based set with some number of buckets stored inline...
Definition: DenseSet.h:268
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:941
iterator_range< user_iterator > users()
Definition: Value.h:400
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 FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
Definition: ValueMapper.h:91
use_iterator use_begin()
Definition: Value.h:339
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:546
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition: LoopInfo.cpp:215
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:311
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:459
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
Definition: LoopInfo.h:149
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:107
static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, BasicBlock *OrigPreheader, ValueToValueMapTy &ValueMap, SmallVectorImpl< PHINode *> *InsertedPHIs)
RewriteUsesOfClonedInstructions - We just cloned the instructions from the old header into the prehea...
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink &#39;this&#39; from the containing function and delete it.
Definition: BasicBlock.cpp:115
#define I(x, y, z)
Definition: MD5.cpp:58
bool mayReadFromMemory() const
Return true if this instruction may read memory.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:325
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:92
bool isUnconditional() const
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM Value Representation.
Definition: Value.h:73
succ_range successors(Instruction *I)
Definition: CFG.h:264
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:87
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This is the interface for LLVM&#39;s primary stateless and local alias analysis.
This pass exposes codegen information to IR-level passes.
#define LLVM_DEBUG(X)
Definition: Debug.h:123
unsigned NumInsts
Number of instructions in the analyzed blocks.
Definition: CodeMetrics.h:63
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
Definition: SSAUpdater.cpp:190
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:50
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition: BasicBlock.cpp:121
bool use_empty() const
Definition: Value.h:323
const BasicBlock * getParent() const
Definition: Instruction.h:67
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
Definition: SSAUpdater.cpp:63