LLVM  mainline
LoopRotation.cpp
Go to the documentation of this file.
00001 //===- LoopRotation.cpp - Loop Rotation Pass ------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements Loop Rotation Pass.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Transforms/Scalar.h"
00015 #include "llvm/ADT/Statistic.h"
00016 #include "llvm/Analysis/AliasAnalysis.h"
00017 #include "llvm/Analysis/BasicAliasAnalysis.h"
00018 #include "llvm/Analysis/AssumptionCache.h"
00019 #include "llvm/Analysis/CodeMetrics.h"
00020 #include "llvm/Analysis/InstructionSimplify.h"
00021 #include "llvm/Analysis/GlobalsModRef.h"
00022 #include "llvm/Analysis/LoopPass.h"
00023 #include "llvm/Analysis/ScalarEvolution.h"
00024 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
00025 #include "llvm/Analysis/TargetTransformInfo.h"
00026 #include "llvm/Analysis/ValueTracking.h"
00027 #include "llvm/IR/CFG.h"
00028 #include "llvm/IR/Dominators.h"
00029 #include "llvm/IR/Function.h"
00030 #include "llvm/IR/IntrinsicInst.h"
00031 #include "llvm/IR/Module.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00036 #include "llvm/Transforms/Utils/Local.h"
00037 #include "llvm/Transforms/Utils/SSAUpdater.h"
00038 #include "llvm/Transforms/Utils/ValueMapper.h"
00039 using namespace llvm;
00040 
00041 #define DEBUG_TYPE "loop-rotate"
00042 
00043 static cl::opt<unsigned>
00044 DefaultRotationThreshold("rotation-max-header-size", cl::init(16), cl::Hidden,
00045        cl::desc("The default maximum header size for automatic loop rotation"));
00046 
00047 STATISTIC(NumRotated, "Number of loops rotated");
00048 
00049 /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
00050 /// old header into the preheader.  If there were uses of the values produced by
00051 /// these instruction that were outside of the loop, we have to insert PHI nodes
00052 /// to merge the two values.  Do this now.
00053 static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
00054                                             BasicBlock *OrigPreheader,
00055                                             ValueToValueMapTy &ValueMap) {
00056   // Remove PHI node entries that are no longer live.
00057   BasicBlock::iterator I, E = OrigHeader->end();
00058   for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
00059     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
00060 
00061   // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
00062   // as necessary.
00063   SSAUpdater SSA;
00064   for (I = OrigHeader->begin(); I != E; ++I) {
00065     Value *OrigHeaderVal = &*I;
00066 
00067     // If there are no uses of the value (e.g. because it returns void), there
00068     // is nothing to rewrite.
00069     if (OrigHeaderVal->use_empty())
00070       continue;
00071 
00072     Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
00073 
00074     // The value now exits in two versions: the initial value in the preheader
00075     // and the loop "next" value in the original header.
00076     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
00077     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
00078     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
00079 
00080     // Visit each use of the OrigHeader instruction.
00081     for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
00082          UE = OrigHeaderVal->use_end(); UI != UE; ) {
00083       // Grab the use before incrementing the iterator.
00084       Use &U = *UI;
00085 
00086       // Increment the iterator before removing the use from the list.
00087       ++UI;
00088 
00089       // SSAUpdater can't handle a non-PHI use in the same block as an
00090       // earlier def. We can easily handle those cases manually.
00091       Instruction *UserInst = cast<Instruction>(U.getUser());
00092       if (!isa<PHINode>(UserInst)) {
00093         BasicBlock *UserBB = UserInst->getParent();
00094 
00095         // The original users in the OrigHeader are already using the
00096         // original definitions.
00097         if (UserBB == OrigHeader)
00098           continue;
00099 
00100         // Users in the OrigPreHeader need to use the value to which the
00101         // original definitions are mapped.
00102         if (UserBB == OrigPreheader) {
00103           U = OrigPreHeaderVal;
00104           continue;
00105         }
00106       }
00107 
00108       // Anything else can be handled by SSAUpdater.
00109       SSA.RewriteUse(U);
00110     }
00111   }
00112 }
00113 
00114 /// Rotate loop LP. Return true if the loop is rotated.
00115 ///
00116 /// \param SimplifiedLatch is true if the latch was just folded into the final
00117 /// loop exit. In this case we may want to rotate even though the new latch is
00118 /// now an exiting branch. This rotation would have happened had the latch not
00119 /// been simplified. However, if SimplifiedLatch is false, then we avoid
00120 /// rotating loops in which the latch exits to avoid excessive or endless
00121 /// rotation. LoopRotate should be repeatable and converge to a canonical
00122 /// form. This property is satisfied because simplifying the loop latch can only
00123 /// happen once across multiple invocations of the LoopRotate pass.
00124 static bool rotateLoop(Loop *L, unsigned MaxHeaderSize, LoopInfo *LI,
00125                        const TargetTransformInfo *TTI, AssumptionCache *AC,
00126                        DominatorTree *DT, ScalarEvolution *SE,
00127                        bool SimplifiedLatch) {
00128   // If the loop has only one block then there is not much to rotate.
00129   if (L->getBlocks().size() == 1)
00130     return false;
00131 
00132   BasicBlock *OrigHeader = L->getHeader();
00133   BasicBlock *OrigLatch = L->getLoopLatch();
00134 
00135   BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
00136   if (!BI || BI->isUnconditional())
00137     return false;
00138 
00139   // If the loop header is not one of the loop exiting blocks then
00140   // either this loop is already rotated or it is not
00141   // suitable for loop rotation transformations.
00142   if (!L->isLoopExiting(OrigHeader))
00143     return false;
00144 
00145   // If the loop latch already contains a branch that leaves the loop then the
00146   // loop is already rotated.
00147   if (!OrigLatch)
00148     return false;
00149 
00150   // Rotate if either the loop latch does *not* exit the loop, or if the loop
00151   // latch was just simplified.
00152   if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch)
00153     return false;
00154 
00155   // Check size of original header and reject loop if it is very big or we can't
00156   // duplicate blocks inside it.
00157   {
00158     SmallPtrSet<const Value *, 32> EphValues;
00159     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
00160 
00161     CodeMetrics Metrics;
00162     Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
00163     if (Metrics.notDuplicatable) {
00164       DEBUG(dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
00165             << " instructions: "; L->dump());
00166       return false;
00167     }
00168     if (Metrics.NumInsts > MaxHeaderSize)
00169       return false;
00170   }
00171 
00172   // Now, this loop is suitable for rotation.
00173   BasicBlock *OrigPreheader = L->getLoopPreheader();
00174 
00175   // If the loop could not be converted to canonical form, it must have an
00176   // indirectbr in it, just give up.
00177   if (!OrigPreheader)
00178     return false;
00179 
00180   // Anything ScalarEvolution may know about this loop or the PHI nodes
00181   // in its header will soon be invalidated.
00182   if (SE)
00183     SE->forgetLoop(L);
00184 
00185   DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
00186 
00187   // Find new Loop header. NewHeader is a Header's one and only successor
00188   // that is inside loop.  Header's other successor is outside the
00189   // loop.  Otherwise loop is not suitable for rotation.
00190   BasicBlock *Exit = BI->getSuccessor(0);
00191   BasicBlock *NewHeader = BI->getSuccessor(1);
00192   if (L->contains(Exit))
00193     std::swap(Exit, NewHeader);
00194   assert(NewHeader && "Unable to determine new loop header");
00195   assert(L->contains(NewHeader) && !L->contains(Exit) &&
00196          "Unable to determine loop header and exit blocks");
00197 
00198   // This code assumes that the new header has exactly one predecessor.
00199   // Remove any single-entry PHI nodes in it.
00200   assert(NewHeader->getSinglePredecessor() &&
00201          "New header doesn't have one pred!");
00202   FoldSingleEntryPHINodes(NewHeader);
00203 
00204   // Begin by walking OrigHeader and populating ValueMap with an entry for
00205   // each Instruction.
00206   BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
00207   ValueToValueMapTy ValueMap;
00208 
00209   // For PHI nodes, the value available in OldPreHeader is just the
00210   // incoming value from OldPreHeader.
00211   for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
00212     ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
00213 
00214   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
00215 
00216   // For the rest of the instructions, either hoist to the OrigPreheader if
00217   // possible or create a clone in the OldPreHeader if not.
00218   TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
00219   while (I != E) {
00220     Instruction *Inst = &*I++;
00221 
00222     // If the instruction's operands are invariant and it doesn't read or write
00223     // memory, then it is safe to hoist.  Doing this doesn't change the order of
00224     // execution in the preheader, but does prevent the instruction from
00225     // executing in each iteration of the loop.  This means it is safe to hoist
00226     // something that might trap, but isn't safe to hoist something that reads
00227     // memory (without proving that the loop doesn't write).
00228     if (L->hasLoopInvariantOperands(Inst) &&
00229         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
00230         !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
00231         !isa<AllocaInst>(Inst)) {
00232       Inst->moveBefore(LoopEntryBranch);
00233       continue;
00234     }
00235 
00236     // Otherwise, create a duplicate of the instruction.
00237     Instruction *C = Inst->clone();
00238 
00239     // Eagerly remap the operands of the instruction.
00240     RemapInstruction(C, ValueMap,
00241                      RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
00242 
00243     // With the operands remapped, see if the instruction constant folds or is
00244     // otherwise simplifyable.  This commonly occurs because the entry from PHI
00245     // nodes allows icmps and other instructions to fold.
00246     // FIXME: Provide TLI, DT, AC to SimplifyInstruction.
00247     Value *V = SimplifyInstruction(C, DL);
00248     if (V && LI->replacementPreservesLCSSAForm(C, V)) {
00249       // If so, then delete the temporary instruction and stick the folded value
00250       // in the map.
00251       delete C;
00252       ValueMap[Inst] = V;
00253     } else {
00254       // Otherwise, stick the new instruction into the new block!
00255       C->setName(Inst->getName());
00256       C->insertBefore(LoopEntryBranch);
00257       ValueMap[Inst] = C;
00258     }
00259   }
00260 
00261   // Along with all the other instructions, we just cloned OrigHeader's
00262   // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
00263   // successors by duplicating their incoming values for OrigHeader.
00264   TerminatorInst *TI = OrigHeader->getTerminator();
00265   for (BasicBlock *SuccBB : TI->successors())
00266     for (BasicBlock::iterator BI = SuccBB->begin();
00267          PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
00268       PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
00269 
00270   // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
00271   // OrigPreHeader's old terminator (the original branch into the loop), and
00272   // remove the corresponding incoming values from the PHI nodes in OrigHeader.
00273   LoopEntryBranch->eraseFromParent();
00274 
00275   // If there were any uses of instructions in the duplicated block outside the
00276   // loop, update them, inserting PHI nodes as required
00277   RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap);
00278 
00279   // NewHeader is now the header of the loop.
00280   L->moveToHeader(NewHeader);
00281   assert(L->getHeader() == NewHeader && "Latch block is our new header");
00282 
00283 
00284   // At this point, we've finished our major CFG changes.  As part of cloning
00285   // the loop into the preheader we've simplified instructions and the
00286   // duplicated conditional branch may now be branching on a constant.  If it is
00287   // branching on a constant and if that constant means that we enter the loop,
00288   // then we fold away the cond branch to an uncond branch.  This simplifies the
00289   // loop in cases important for nested loops, and it also means we don't have
00290   // to split as many edges.
00291   BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
00292   assert(PHBI->isConditional() && "Should be clone of BI condbr!");
00293   if (!isa<ConstantInt>(PHBI->getCondition()) ||
00294       PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero())
00295           != NewHeader) {
00296     // The conditional branch can't be folded, handle the general case.
00297     // Update DominatorTree to reflect the CFG change we just made.  Then split
00298     // edges as necessary to preserve LoopSimplify form.
00299     if (DT) {
00300       // Everything that was dominated by the old loop header is now dominated
00301       // by the original loop preheader. Conceptually the header was merged
00302       // into the preheader, even though we reuse the actual block as a new
00303       // loop latch.
00304       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
00305       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
00306                                                    OrigHeaderNode->end());
00307       DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
00308       for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I)
00309         DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
00310 
00311       assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
00312       assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
00313 
00314       // Update OrigHeader to be dominated by the new header block.
00315       DT->changeImmediateDominator(OrigHeader, OrigLatch);
00316     }
00317 
00318     // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
00319     // thus is not a preheader anymore.
00320     // Split the edge to form a real preheader.
00321     BasicBlock *NewPH = SplitCriticalEdge(
00322         OrigPreheader, NewHeader,
00323         CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
00324     NewPH->setName(NewHeader->getName() + ".lr.ph");
00325 
00326     // Preserve canonical loop form, which means that 'Exit' should have only
00327     // one predecessor. Note that Exit could be an exit block for multiple
00328     // nested loops, causing both of the edges to now be critical and need to
00329     // be split.
00330     SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
00331     bool SplitLatchEdge = false;
00332     for (SmallVectorImpl<BasicBlock *>::iterator PI = ExitPreds.begin(),
00333                                                  PE = ExitPreds.end();
00334          PI != PE; ++PI) {
00335       // We only need to split loop exit edges.
00336       Loop *PredLoop = LI->getLoopFor(*PI);
00337       if (!PredLoop || PredLoop->contains(Exit))
00338         continue;
00339       if (isa<IndirectBrInst>((*PI)->getTerminator()))
00340         continue;
00341       SplitLatchEdge |= L->getLoopLatch() == *PI;
00342       BasicBlock *ExitSplit = SplitCriticalEdge(
00343           *PI, Exit, CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
00344       ExitSplit->moveBefore(Exit);
00345     }
00346     assert(SplitLatchEdge &&
00347            "Despite splitting all preds, failed to split latch exit?");
00348   } else {
00349     // We can fold the conditional branch in the preheader, this makes things
00350     // simpler. The first step is to remove the extra edge to the Exit block.
00351     Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
00352     BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
00353     NewBI->setDebugLoc(PHBI->getDebugLoc());
00354     PHBI->eraseFromParent();
00355 
00356     // With our CFG finalized, update DomTree if it is available.
00357     if (DT) {
00358       // Update OrigHeader to be dominated by the new header block.
00359       DT->changeImmediateDominator(NewHeader, OrigPreheader);
00360       DT->changeImmediateDominator(OrigHeader, OrigLatch);
00361 
00362       // Brute force incremental dominator tree update. Call
00363       // findNearestCommonDominator on all CFG predecessors of each child of the
00364       // original header.
00365       DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
00366       SmallVector<DomTreeNode *, 8> HeaderChildren(OrigHeaderNode->begin(),
00367                                                    OrigHeaderNode->end());
00368       bool Changed;
00369       do {
00370         Changed = false;
00371         for (unsigned I = 0, E = HeaderChildren.size(); I != E; ++I) {
00372           DomTreeNode *Node = HeaderChildren[I];
00373           BasicBlock *BB = Node->getBlock();
00374 
00375           pred_iterator PI = pred_begin(BB);
00376           BasicBlock *NearestDom = *PI;
00377           for (pred_iterator PE = pred_end(BB); PI != PE; ++PI)
00378             NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
00379 
00380           // Remember if this changes the DomTree.
00381           if (Node->getIDom()->getBlock() != NearestDom) {
00382             DT->changeImmediateDominator(BB, NearestDom);
00383             Changed = true;
00384           }
00385         }
00386 
00387       // If the dominator changed, this may have an effect on other
00388       // predecessors, continue until we reach a fixpoint.
00389       } while (Changed);
00390     }
00391   }
00392 
00393   assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
00394   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
00395 
00396   // Now that the CFG and DomTree are in a consistent state again, try to merge
00397   // the OrigHeader block into OrigLatch.  This will succeed if they are
00398   // connected by an unconditional branch.  This is just a cleanup so the
00399   // emitted code isn't too gross in this common case.
00400   MergeBlockIntoPredecessor(OrigHeader, DT, LI);
00401 
00402   DEBUG(dbgs() << "LoopRotation: into "; L->dump());
00403 
00404   ++NumRotated;
00405   return true;
00406 }
00407 
00408 /// Determine whether the instructions in this range may be safely and cheaply
00409 /// speculated. This is not an important enough situation to develop complex
00410 /// heuristics. We handle a single arithmetic instruction along with any type
00411 /// conversions.
00412 static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
00413                                   BasicBlock::iterator End, Loop *L) {
00414   bool seenIncrement = false;
00415   bool MultiExitLoop = false;
00416 
00417   if (!L->getExitingBlock())
00418     MultiExitLoop = true;
00419 
00420   for (BasicBlock::iterator I = Begin; I != End; ++I) {
00421 
00422     if (!isSafeToSpeculativelyExecute(&*I))
00423       return false;
00424 
00425     if (isa<DbgInfoIntrinsic>(I))
00426       continue;
00427 
00428     switch (I->getOpcode()) {
00429     default:
00430       return false;
00431     case Instruction::GetElementPtr:
00432       // GEPs are cheap if all indices are constant.
00433       if (!cast<GEPOperator>(I)->hasAllConstantIndices())
00434         return false;
00435       // fall-thru to increment case
00436     case Instruction::Add:
00437     case Instruction::Sub:
00438     case Instruction::And:
00439     case Instruction::Or:
00440     case Instruction::Xor:
00441     case Instruction::Shl:
00442     case Instruction::LShr:
00443     case Instruction::AShr: {
00444       Value *IVOpnd = !isa<Constant>(I->getOperand(0))
00445                           ? I->getOperand(0)
00446                           : !isa<Constant>(I->getOperand(1))
00447                                 ? I->getOperand(1)
00448                                 : nullptr;
00449       if (!IVOpnd)
00450         return false;
00451 
00452       // If increment operand is used outside of the loop, this speculation
00453       // could cause extra live range interference.
00454       if (MultiExitLoop) {
00455         for (User *UseI : IVOpnd->users()) {
00456           auto *UserInst = cast<Instruction>(UseI);
00457           if (!L->contains(UserInst))
00458             return false;
00459         }
00460       }
00461 
00462       if (seenIncrement)
00463         return false;
00464       seenIncrement = true;
00465       break;
00466     }
00467     case Instruction::Trunc:
00468     case Instruction::ZExt:
00469     case Instruction::SExt:
00470       // ignore type conversions
00471       break;
00472     }
00473   }
00474   return true;
00475 }
00476 
00477 /// Fold the loop tail into the loop exit by speculating the loop tail
00478 /// instructions. Typically, this is a single post-increment. In the case of a
00479 /// simple 2-block loop, hoisting the increment can be much better than
00480 /// duplicating the entire loop header. In the case of loops with early exits,
00481 /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
00482 /// canonical form so downstream passes can handle it.
00483 ///
00484 /// I don't believe this invalidates SCEV.
00485 static bool simplifyLoopLatch(Loop *L, LoopInfo *LI, DominatorTree *DT) {
00486   BasicBlock *Latch = L->getLoopLatch();
00487   if (!Latch || Latch->hasAddressTaken())
00488     return false;
00489 
00490   BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
00491   if (!Jmp || !Jmp->isUnconditional())
00492     return false;
00493 
00494   BasicBlock *LastExit = Latch->getSinglePredecessor();
00495   if (!LastExit || !L->isLoopExiting(LastExit))
00496     return false;
00497 
00498   BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
00499   if (!BI)
00500     return false;
00501 
00502   if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
00503     return false;
00504 
00505   DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
00506         << LastExit->getName() << "\n");
00507 
00508   // Hoist the instructions from Latch into LastExit.
00509   LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
00510                                  Latch->begin(), Jmp->getIterator());
00511 
00512   unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
00513   BasicBlock *Header = Jmp->getSuccessor(0);
00514   assert(Header == L->getHeader() && "expected a backward branch");
00515 
00516   // Remove Latch from the CFG so that LastExit becomes the new Latch.
00517   BI->setSuccessor(FallThruPath, Header);
00518   Latch->replaceSuccessorsPhiUsesWith(LastExit);
00519   Jmp->eraseFromParent();
00520 
00521   // Nuke the Latch block.
00522   assert(Latch->empty() && "unable to evacuate Latch");
00523   LI->removeBlock(Latch);
00524   if (DT)
00525     DT->eraseNode(Latch);
00526   Latch->eraseFromParent();
00527   return true;
00528 }
00529 
00530 /// Rotate \c L as many times as possible. Return true if the loop is rotated
00531 /// at least once.
00532 static bool iterativelyRotateLoop(Loop *L, unsigned MaxHeaderSize, LoopInfo *LI,
00533                                   const TargetTransformInfo *TTI,
00534                                   AssumptionCache *AC, DominatorTree *DT,
00535                                   ScalarEvolution *SE) {
00536   // Save the loop metadata.
00537   MDNode *LoopMD = L->getLoopID();
00538 
00539   // Simplify the loop latch before attempting to rotate the header
00540   // upward. Rotation may not be needed if the loop tail can be folded into the
00541   // loop exit.
00542   bool SimplifiedLatch = simplifyLoopLatch(L, LI, DT);
00543 
00544   // One loop can be rotated multiple times.
00545   bool MadeChange = false;
00546   while (rotateLoop(L, MaxHeaderSize, LI, TTI, AC, DT, SE, SimplifiedLatch)) {
00547     MadeChange = true;
00548     SimplifiedLatch = false;
00549   }
00550 
00551   // Restore the loop metadata.
00552   // NB! We presume LoopRotation DOESN'T ADD its own metadata.
00553   if ((MadeChange || SimplifiedLatch) && LoopMD)
00554     L->setLoopID(LoopMD);
00555 
00556   return MadeChange;
00557 }
00558 
00559 namespace {
00560 
00561 class LoopRotate : public LoopPass {
00562   unsigned MaxHeaderSize;
00563 
00564 public:
00565   static char ID; // Pass ID, replacement for typeid
00566   LoopRotate(int SpecifiedMaxHeaderSize = -1) : LoopPass(ID) {
00567     initializeLoopRotatePass(*PassRegistry::getPassRegistry());
00568     if (SpecifiedMaxHeaderSize == -1)
00569       MaxHeaderSize = DefaultRotationThreshold;
00570     else
00571       MaxHeaderSize = unsigned(SpecifiedMaxHeaderSize);
00572   }
00573 
00574   // LCSSA form makes instruction renaming easier.
00575   void getAnalysisUsage(AnalysisUsage &AU) const override {
00576     AU.addPreserved<AAResultsWrapperPass>();
00577     AU.addRequired<AssumptionCacheTracker>();
00578     AU.addPreserved<DominatorTreeWrapperPass>();
00579     AU.addRequired<LoopInfoWrapperPass>();
00580     AU.addPreserved<LoopInfoWrapperPass>();
00581     AU.addRequiredID(LoopSimplifyID);
00582     AU.addPreservedID(LoopSimplifyID);
00583     AU.addRequiredID(LCSSAID);
00584     AU.addPreservedID(LCSSAID);
00585     AU.addPreserved<ScalarEvolutionWrapperPass>();
00586     AU.addPreserved<SCEVAAWrapperPass>();
00587     AU.addRequired<TargetTransformInfoWrapperPass>();
00588     AU.addPreserved<BasicAAWrapperPass>();
00589     AU.addPreserved<GlobalsAAWrapperPass>();
00590   }
00591 
00592   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
00593     if (skipOptnoneFunction(L))
00594       return false;
00595     Function &F = *L->getHeader()->getParent();
00596 
00597     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00598     const auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
00599     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
00600     auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00601     auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
00602     auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
00603     auto *SE = SEWP ? &SEWP->getSE() : nullptr;
00604 
00605     return iterativelyRotateLoop(L, MaxHeaderSize, LI, TTI, AC, DT, SE);
00606   }
00607 };
00608 }
00609 
00610 char LoopRotate::ID = 0;
00611 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
00612 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
00613 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00614 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00615 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00616 INITIALIZE_PASS_DEPENDENCY(LCSSA)
00617 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
00618 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
00619 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
00620 INITIALIZE_PASS_END(LoopRotate, "loop-rotate", "Rotate Loops", false, false)
00621 
00622 Pass *llvm::createLoopRotatePass(int MaxHeaderSize) {
00623   return new LoopRotate(MaxHeaderSize);
00624 }