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