LLVM  mainline
LoopSimplify.cpp
Go to the documentation of this file.
00001 //===- LoopSimplify.cpp - Loop Canonicalization 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 pass performs several transformations to transform natural loops into a
00011 // simpler form, which makes subsequent analyses and transformations simpler and
00012 // more effective.
00013 //
00014 // Loop pre-header insertion guarantees that there is a single, non-critical
00015 // entry edge from outside of the loop to the loop header.  This simplifies a
00016 // number of analyses and transformations, such as LICM.
00017 //
00018 // Loop exit-block insertion guarantees that all exit blocks from the loop
00019 // (blocks which are outside of the loop that have predecessors inside of the
00020 // loop) only have predecessors from inside of the loop (and are thus dominated
00021 // by the loop header).  This simplifies transformations such as store-sinking
00022 // that are built into LICM.
00023 //
00024 // This pass also guarantees that loops will have exactly one backedge.
00025 //
00026 // Indirectbr instructions introduce several complications. If the loop
00027 // contains or is entered by an indirectbr instruction, it may not be possible
00028 // to transform the loop and make these guarantees. Client code should check
00029 // that these conditions are true before relying on them.
00030 //
00031 // Note that the simplifycfg pass will clean up blocks which are split out but
00032 // end up being unnecessary, so usage of this pass should not pessimize
00033 // generated code.
00034 //
00035 // This pass obviously modifies the CFG, but updates loop information and
00036 // dominator information.
00037 //
00038 //===----------------------------------------------------------------------===//
00039 
00040 #include "llvm/Transforms/Scalar.h"
00041 #include "llvm/ADT/DepthFirstIterator.h"
00042 #include "llvm/ADT/SetOperations.h"
00043 #include "llvm/ADT/SetVector.h"
00044 #include "llvm/ADT/SmallVector.h"
00045 #include "llvm/ADT/Statistic.h"
00046 #include "llvm/Analysis/AliasAnalysis.h"
00047 #include "llvm/Analysis/AssumptionCache.h"
00048 #include "llvm/Analysis/DependenceAnalysis.h"
00049 #include "llvm/Analysis/InstructionSimplify.h"
00050 #include "llvm/Analysis/LoopInfo.h"
00051 #include "llvm/Analysis/ScalarEvolution.h"
00052 #include "llvm/IR/CFG.h"
00053 #include "llvm/IR/Constants.h"
00054 #include "llvm/IR/DataLayout.h"
00055 #include "llvm/IR/Dominators.h"
00056 #include "llvm/IR/Function.h"
00057 #include "llvm/IR/Instructions.h"
00058 #include "llvm/IR/IntrinsicInst.h"
00059 #include "llvm/IR/LLVMContext.h"
00060 #include "llvm/IR/Module.h"
00061 #include "llvm/IR/Type.h"
00062 #include "llvm/Support/Debug.h"
00063 #include "llvm/Support/raw_ostream.h"
00064 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00065 #include "llvm/Transforms/Utils/Local.h"
00066 #include "llvm/Transforms/Utils/LoopUtils.h"
00067 using namespace llvm;
00068 
00069 #define DEBUG_TYPE "loop-simplify"
00070 
00071 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
00072 STATISTIC(NumNested  , "Number of nested loops split out");
00073 
00074 // If the block isn't already, move the new block to right after some 'outside
00075 // block' block.  This prevents the preheader from being placed inside the loop
00076 // body, e.g. when the loop hasn't been rotated.
00077 static void placeSplitBlockCarefully(BasicBlock *NewBB,
00078                                      SmallVectorImpl<BasicBlock *> &SplitPreds,
00079                                      Loop *L) {
00080   // Check to see if NewBB is already well placed.
00081   Function::iterator BBI = NewBB; --BBI;
00082   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
00083     if (&*BBI == SplitPreds[i])
00084       return;
00085   }
00086 
00087   // If it isn't already after an outside block, move it after one.  This is
00088   // always good as it makes the uncond branch from the outside block into a
00089   // fall-through.
00090 
00091   // Figure out *which* outside block to put this after.  Prefer an outside
00092   // block that neighbors a BB actually in the loop.
00093   BasicBlock *FoundBB = nullptr;
00094   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
00095     Function::iterator BBI = SplitPreds[i];
00096     if (++BBI != NewBB->getParent()->end() &&
00097         L->contains(BBI)) {
00098       FoundBB = SplitPreds[i];
00099       break;
00100     }
00101   }
00102 
00103   // If our heuristic for a *good* bb to place this after doesn't find
00104   // anything, just pick something.  It's likely better than leaving it within
00105   // the loop.
00106   if (!FoundBB)
00107     FoundBB = SplitPreds[0];
00108   NewBB->moveAfter(FoundBB);
00109 }
00110 
00111 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
00112 /// preheader, this method is called to insert one.  This method has two phases:
00113 /// preheader insertion and analysis updating.
00114 ///
00115 BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, Pass *PP) {
00116   BasicBlock *Header = L->getHeader();
00117 
00118   // Get analyses that we try to update.
00119   auto *AA = PP->getAnalysisIfAvailable<AliasAnalysis>();
00120   auto *DTWP = PP->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00121   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
00122   auto *LIWP = PP->getAnalysisIfAvailable<LoopInfoWrapperPass>();
00123   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
00124   bool PreserveLCSSA = PP->mustPreserveAnalysisID(LCSSAID);
00125 
00126   // Compute the set of predecessors of the loop that are not in the loop.
00127   SmallVector<BasicBlock*, 8> OutsideBlocks;
00128   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
00129        PI != PE; ++PI) {
00130     BasicBlock *P = *PI;
00131     if (!L->contains(P)) {         // Coming in from outside the loop?
00132       // If the loop is branched to from an indirect branch, we won't
00133       // be able to fully transform the loop, because it prohibits
00134       // edge splitting.
00135       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
00136 
00137       // Keep track of it.
00138       OutsideBlocks.push_back(P);
00139     }
00140   }
00141 
00142   // Split out the loop pre-header.
00143   BasicBlock *PreheaderBB;
00144   PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
00145                                        AA, DT, LI, PreserveLCSSA);
00146 
00147   PreheaderBB->getTerminator()->setDebugLoc(
00148                                       Header->getFirstNonPHI()->getDebugLoc());
00149   DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
00150                << PreheaderBB->getName() << "\n");
00151 
00152   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
00153   // code layout too horribly.
00154   placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
00155 
00156   return PreheaderBB;
00157 }
00158 
00159 /// \brief Ensure that the loop preheader dominates all exit blocks.
00160 ///
00161 /// This method is used to split exit blocks that have predecessors outside of
00162 /// the loop.
00163 static BasicBlock *rewriteLoopExitBlock(Loop *L, BasicBlock *Exit,
00164                                         AliasAnalysis *AA, DominatorTree *DT,
00165                                         LoopInfo *LI, Pass *PP) {
00166   SmallVector<BasicBlock*, 8> LoopBlocks;
00167   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) {
00168     BasicBlock *P = *I;
00169     if (L->contains(P)) {
00170       // Don't do this if the loop is exited via an indirect branch.
00171       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
00172 
00173       LoopBlocks.push_back(P);
00174     }
00175   }
00176 
00177   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
00178   BasicBlock *NewExitBB = nullptr;
00179 
00180   bool PreserveLCSSA = PP->mustPreserveAnalysisID(LCSSAID);
00181 
00182   NewExitBB = SplitBlockPredecessors(Exit, LoopBlocks, ".loopexit", AA, DT,
00183                                      LI, PreserveLCSSA);
00184 
00185   DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
00186                << NewExitBB->getName() << "\n");
00187   return NewExitBB;
00188 }
00189 
00190 /// Add the specified block, and all of its predecessors, to the specified set,
00191 /// if it's not already in there.  Stop predecessor traversal when we reach
00192 /// StopBlock.
00193 static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
00194                                   std::set<BasicBlock*> &Blocks) {
00195   SmallVector<BasicBlock *, 8> Worklist;
00196   Worklist.push_back(InputBB);
00197   do {
00198     BasicBlock *BB = Worklist.pop_back_val();
00199     if (Blocks.insert(BB).second && BB != StopBlock)
00200       // If BB is not already processed and it is not a stop block then
00201       // insert its predecessor in the work list
00202       for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
00203         BasicBlock *WBB = *I;
00204         Worklist.push_back(WBB);
00205       }
00206   } while (!Worklist.empty());
00207 }
00208 
00209 /// \brief The first part of loop-nestification is to find a PHI node that tells
00210 /// us how to partition the loops.
00211 static PHINode *findPHIToPartitionLoops(Loop *L, AliasAnalysis *AA,
00212                                         DominatorTree *DT,
00213                                         AssumptionCache *AC) {
00214   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
00215   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
00216     PHINode *PN = cast<PHINode>(I);
00217     ++I;
00218     if (Value *V = SimplifyInstruction(PN, DL, nullptr, DT, AC)) {
00219       // This is a degenerate PHI already, don't modify it!
00220       PN->replaceAllUsesWith(V);
00221       if (AA) AA->deleteValue(PN);
00222       PN->eraseFromParent();
00223       continue;
00224     }
00225 
00226     // Scan this PHI node looking for a use of the PHI node by itself.
00227     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00228       if (PN->getIncomingValue(i) == PN &&
00229           L->contains(PN->getIncomingBlock(i)))
00230         // We found something tasty to remove.
00231         return PN;
00232   }
00233   return nullptr;
00234 }
00235 
00236 /// \brief If this loop has multiple backedges, try to pull one of them out into
00237 /// a nested loop.
00238 ///
00239 /// This is important for code that looks like
00240 /// this:
00241 ///
00242 ///  Loop:
00243 ///     ...
00244 ///     br cond, Loop, Next
00245 ///     ...
00246 ///     br cond2, Loop, Out
00247 ///
00248 /// To identify this common case, we look at the PHI nodes in the header of the
00249 /// loop.  PHI nodes with unchanging values on one backedge correspond to values
00250 /// that change in the "outer" loop, but not in the "inner" loop.
00251 ///
00252 /// If we are able to separate out a loop, return the new outer loop that was
00253 /// created.
00254 ///
00255 static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader,
00256                                 AliasAnalysis *AA, DominatorTree *DT,
00257                                 LoopInfo *LI, ScalarEvolution *SE, Pass *PP,
00258                                 AssumptionCache *AC) {
00259   // Don't try to separate loops without a preheader.
00260   if (!Preheader)
00261     return nullptr;
00262 
00263   // The header is not a landing pad; preheader insertion should ensure this.
00264   assert(!L->getHeader()->isLandingPad() &&
00265          "Can't insert backedge to landing pad");
00266 
00267   PHINode *PN = findPHIToPartitionLoops(L, AA, DT, AC);
00268   if (!PN) return nullptr;  // No known way to partition.
00269 
00270   // Pull out all predecessors that have varying values in the loop.  This
00271   // handles the case when a PHI node has multiple instances of itself as
00272   // arguments.
00273   SmallVector<BasicBlock*, 8> OuterLoopPreds;
00274   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00275     if (PN->getIncomingValue(i) != PN ||
00276         !L->contains(PN->getIncomingBlock(i))) {
00277       // We can't split indirectbr edges.
00278       if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
00279         return nullptr;
00280       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
00281     }
00282   }
00283   DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
00284 
00285   // If ScalarEvolution is around and knows anything about values in
00286   // this loop, tell it to forget them, because we're about to
00287   // substantially change it.
00288   if (SE)
00289     SE->forgetLoop(L);
00290 
00291   bool PreserveLCSSA = PP->mustPreserveAnalysisID(LCSSAID);
00292 
00293   BasicBlock *Header = L->getHeader();
00294   BasicBlock *NewBB = SplitBlockPredecessors(Header, OuterLoopPreds, ".outer",
00295                                              AA, DT, LI, PreserveLCSSA);
00296 
00297   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
00298   // code layout too horribly.
00299   placeSplitBlockCarefully(NewBB, OuterLoopPreds, L);
00300 
00301   // Create the new outer loop.
00302   Loop *NewOuter = new Loop();
00303 
00304   // Change the parent loop to use the outer loop as its child now.
00305   if (Loop *Parent = L->getParentLoop())
00306     Parent->replaceChildLoopWith(L, NewOuter);
00307   else
00308     LI->changeTopLevelLoop(L, NewOuter);
00309 
00310   // L is now a subloop of our outer loop.
00311   NewOuter->addChildLoop(L);
00312 
00313   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00314        I != E; ++I)
00315     NewOuter->addBlockEntry(*I);
00316 
00317   // Now reset the header in L, which had been moved by
00318   // SplitBlockPredecessors for the outer loop.
00319   L->moveToHeader(Header);
00320 
00321   // Determine which blocks should stay in L and which should be moved out to
00322   // the Outer loop now.
00323   std::set<BasicBlock*> BlocksInL;
00324   for (pred_iterator PI=pred_begin(Header), E = pred_end(Header); PI!=E; ++PI) {
00325     BasicBlock *P = *PI;
00326     if (DT->dominates(Header, P))
00327       addBlockAndPredsToSet(P, Header, BlocksInL);
00328   }
00329 
00330   // Scan all of the loop children of L, moving them to OuterLoop if they are
00331   // not part of the inner loop.
00332   const std::vector<Loop*> &SubLoops = L->getSubLoops();
00333   for (size_t I = 0; I != SubLoops.size(); )
00334     if (BlocksInL.count(SubLoops[I]->getHeader()))
00335       ++I;   // Loop remains in L
00336     else
00337       NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
00338 
00339   // Now that we know which blocks are in L and which need to be moved to
00340   // OuterLoop, move any blocks that need it.
00341   for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
00342     BasicBlock *BB = L->getBlocks()[i];
00343     if (!BlocksInL.count(BB)) {
00344       // Move this block to the parent, updating the exit blocks sets
00345       L->removeBlockFromLoop(BB);
00346       if ((*LI)[BB] == L)
00347         LI->changeLoopFor(BB, NewOuter);
00348       --i;
00349     }
00350   }
00351 
00352   return NewOuter;
00353 }
00354 
00355 /// \brief This method is called when the specified loop has more than one
00356 /// backedge in it.
00357 ///
00358 /// If this occurs, revector all of these backedges to target a new basic block
00359 /// and have that block branch to the loop header.  This ensures that loops
00360 /// have exactly one backedge.
00361 static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader,
00362                                              AliasAnalysis *AA,
00363                                              DominatorTree *DT, LoopInfo *LI) {
00364   assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
00365 
00366   // Get information about the loop
00367   BasicBlock *Header = L->getHeader();
00368   Function *F = Header->getParent();
00369 
00370   // Unique backedge insertion currently depends on having a preheader.
00371   if (!Preheader)
00372     return nullptr;
00373 
00374   // The header is not a landing pad; preheader insertion should ensure this.
00375   assert(!Header->isLandingPad() && "Can't insert backedge to landing pad");
00376 
00377   // Figure out which basic blocks contain back-edges to the loop header.
00378   std::vector<BasicBlock*> BackedgeBlocks;
00379   for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I){
00380     BasicBlock *P = *I;
00381 
00382     // Indirectbr edges cannot be split, so we must fail if we find one.
00383     if (isa<IndirectBrInst>(P->getTerminator()))
00384       return nullptr;
00385 
00386     if (P != Preheader) BackedgeBlocks.push_back(P);
00387   }
00388 
00389   // Create and insert the new backedge block...
00390   BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
00391                                            Header->getName()+".backedge", F);
00392   BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
00393 
00394   DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
00395                << BEBlock->getName() << "\n");
00396 
00397   // Move the new backedge block to right after the last backedge block.
00398   Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
00399   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
00400 
00401   // Now that the block has been inserted into the function, create PHI nodes in
00402   // the backedge block which correspond to any PHI nodes in the header block.
00403   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00404     PHINode *PN = cast<PHINode>(I);
00405     PHINode *NewPN = PHINode::Create(PN->getType(), BackedgeBlocks.size(),
00406                                      PN->getName()+".be", BETerminator);
00407     if (AA) AA->copyValue(PN, NewPN);
00408 
00409     // Loop over the PHI node, moving all entries except the one for the
00410     // preheader over to the new PHI node.
00411     unsigned PreheaderIdx = ~0U;
00412     bool HasUniqueIncomingValue = true;
00413     Value *UniqueValue = nullptr;
00414     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00415       BasicBlock *IBB = PN->getIncomingBlock(i);
00416       Value *IV = PN->getIncomingValue(i);
00417       if (IBB == Preheader) {
00418         PreheaderIdx = i;
00419       } else {
00420         NewPN->addIncoming(IV, IBB);
00421         if (HasUniqueIncomingValue) {
00422           if (!UniqueValue)
00423             UniqueValue = IV;
00424           else if (UniqueValue != IV)
00425             HasUniqueIncomingValue = false;
00426         }
00427       }
00428     }
00429 
00430     // Delete all of the incoming values from the old PN except the preheader's
00431     assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
00432     if (PreheaderIdx != 0) {
00433       PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
00434       PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
00435     }
00436     // Nuke all entries except the zero'th.
00437     for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
00438       PN->removeIncomingValue(e-i, false);
00439 
00440     // Finally, add the newly constructed PHI node as the entry for the BEBlock.
00441     PN->addIncoming(NewPN, BEBlock);
00442 
00443     // As an optimization, if all incoming values in the new PhiNode (which is a
00444     // subset of the incoming values of the old PHI node) have the same value,
00445     // eliminate the PHI Node.
00446     if (HasUniqueIncomingValue) {
00447       NewPN->replaceAllUsesWith(UniqueValue);
00448       if (AA) AA->deleteValue(NewPN);
00449       BEBlock->getInstList().erase(NewPN);
00450     }
00451   }
00452 
00453   // Now that all of the PHI nodes have been inserted and adjusted, modify the
00454   // backedge blocks to just to the BEBlock instead of the header.
00455   for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
00456     TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
00457     for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
00458       if (TI->getSuccessor(Op) == Header)
00459         TI->setSuccessor(Op, BEBlock);
00460   }
00461 
00462   //===--- Update all analyses which we must preserve now -----------------===//
00463 
00464   // Update Loop Information - we know that this block is now in the current
00465   // loop and all parent loops.
00466   L->addBasicBlockToLoop(BEBlock, *LI);
00467 
00468   // Update dominator information
00469   DT->splitBlock(BEBlock);
00470 
00471   return BEBlock;
00472 }
00473 
00474 /// \brief Simplify one loop and queue further loops for simplification.
00475 ///
00476 /// FIXME: Currently this accepts both lots of analyses that it uses and a raw
00477 /// Pass pointer. The Pass pointer is used by numerous utilities to update
00478 /// specific analyses. Rather than a pass it would be much cleaner and more
00479 /// explicit if they accepted the analysis directly and then updated it.
00480 static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist,
00481                             AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI,
00482                             ScalarEvolution *SE, Pass *PP,
00483                             AssumptionCache *AC) {
00484   bool Changed = false;
00485 ReprocessLoop:
00486 
00487   // Check to see that no blocks (other than the header) in this loop have
00488   // predecessors that are not in the loop.  This is not valid for natural
00489   // loops, but can occur if the blocks are unreachable.  Since they are
00490   // unreachable we can just shamelessly delete those CFG edges!
00491   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
00492        BB != E; ++BB) {
00493     if (*BB == L->getHeader()) continue;
00494 
00495     SmallPtrSet<BasicBlock*, 4> BadPreds;
00496     for (pred_iterator PI = pred_begin(*BB),
00497          PE = pred_end(*BB); PI != PE; ++PI) {
00498       BasicBlock *P = *PI;
00499       if (!L->contains(P))
00500         BadPreds.insert(P);
00501     }
00502 
00503     // Delete each unique out-of-loop (and thus dead) predecessor.
00504     for (BasicBlock *P : BadPreds) {
00505 
00506       DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
00507                    << P->getName() << "\n");
00508 
00509       // Inform each successor of each dead pred.
00510       for (succ_iterator SI = succ_begin(P), SE = succ_end(P); SI != SE; ++SI)
00511         (*SI)->removePredecessor(P);
00512       // Zap the dead pred's terminator and replace it with unreachable.
00513       TerminatorInst *TI = P->getTerminator();
00514        TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
00515       P->getTerminator()->eraseFromParent();
00516       new UnreachableInst(P->getContext(), P);
00517       Changed = true;
00518     }
00519   }
00520 
00521   // If there are exiting blocks with branches on undef, resolve the undef in
00522   // the direction which will exit the loop. This will help simplify loop
00523   // trip count computations.
00524   SmallVector<BasicBlock*, 8> ExitingBlocks;
00525   L->getExitingBlocks(ExitingBlocks);
00526   for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
00527        E = ExitingBlocks.end(); I != E; ++I)
00528     if (BranchInst *BI = dyn_cast<BranchInst>((*I)->getTerminator()))
00529       if (BI->isConditional()) {
00530         if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
00531 
00532           DEBUG(dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
00533                        << (*I)->getName() << "\n");
00534 
00535           BI->setCondition(ConstantInt::get(Cond->getType(),
00536                                             !L->contains(BI->getSuccessor(0))));
00537 
00538           // This may make the loop analyzable, force SCEV recomputation.
00539           if (SE)
00540             SE->forgetLoop(L);
00541 
00542           Changed = true;
00543         }
00544       }
00545 
00546   // Does the loop already have a preheader?  If so, don't insert one.
00547   BasicBlock *Preheader = L->getLoopPreheader();
00548   if (!Preheader) {
00549     Preheader = InsertPreheaderForLoop(L, PP);
00550     if (Preheader) {
00551       ++NumInserted;
00552       Changed = true;
00553     }
00554   }
00555 
00556   // Next, check to make sure that all exit nodes of the loop only have
00557   // predecessors that are inside of the loop.  This check guarantees that the
00558   // loop preheader/header will dominate the exit blocks.  If the exit block has
00559   // predecessors from outside of the loop, split the edge now.
00560   SmallVector<BasicBlock*, 8> ExitBlocks;
00561   L->getExitBlocks(ExitBlocks);
00562 
00563   SmallSetVector<BasicBlock *, 8> ExitBlockSet(ExitBlocks.begin(),
00564                                                ExitBlocks.end());
00565   for (SmallSetVector<BasicBlock *, 8>::iterator I = ExitBlockSet.begin(),
00566          E = ExitBlockSet.end(); I != E; ++I) {
00567     BasicBlock *ExitBlock = *I;
00568     for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
00569          PI != PE; ++PI)
00570       // Must be exactly this loop: no subloops, parent loops, or non-loop preds
00571       // allowed.
00572       if (!L->contains(*PI)) {
00573         if (rewriteLoopExitBlock(L, ExitBlock, AA, DT, LI, PP)) {
00574           ++NumInserted;
00575           Changed = true;
00576         }
00577         break;
00578       }
00579   }
00580 
00581   // If the header has more than two predecessors at this point (from the
00582   // preheader and from multiple backedges), we must adjust the loop.
00583   BasicBlock *LoopLatch = L->getLoopLatch();
00584   if (!LoopLatch) {
00585     // If this is really a nested loop, rip it out into a child loop.  Don't do
00586     // this for loops with a giant number of backedges, just factor them into a
00587     // common backedge instead.
00588     if (L->getNumBackEdges() < 8) {
00589       if (Loop *OuterL =
00590               separateNestedLoop(L, Preheader, AA, DT, LI, SE, PP, AC)) {
00591         ++NumNested;
00592         // Enqueue the outer loop as it should be processed next in our
00593         // depth-first nest walk.
00594         Worklist.push_back(OuterL);
00595 
00596         // This is a big restructuring change, reprocess the whole loop.
00597         Changed = true;
00598         // GCC doesn't tail recursion eliminate this.
00599         // FIXME: It isn't clear we can't rely on LLVM to TRE this.
00600         goto ReprocessLoop;
00601       }
00602     }
00603 
00604     // If we either couldn't, or didn't want to, identify nesting of the loops,
00605     // insert a new block that all backedges target, then make it jump to the
00606     // loop header.
00607     LoopLatch = insertUniqueBackedgeBlock(L, Preheader, AA, DT, LI);
00608     if (LoopLatch) {
00609       ++NumInserted;
00610       Changed = true;
00611     }
00612   }
00613 
00614   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
00615 
00616   // Scan over the PHI nodes in the loop header.  Since they now have only two
00617   // incoming values (the loop is canonicalized), we may have simplified the PHI
00618   // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
00619   PHINode *PN;
00620   for (BasicBlock::iterator I = L->getHeader()->begin();
00621        (PN = dyn_cast<PHINode>(I++)); )
00622     if (Value *V = SimplifyInstruction(PN, DL, nullptr, DT, AC)) {
00623       if (AA) AA->deleteValue(PN);
00624       if (SE) SE->forgetValue(PN);
00625       PN->replaceAllUsesWith(V);
00626       PN->eraseFromParent();
00627     }
00628 
00629   // If this loop has multiple exits and the exits all go to the same
00630   // block, attempt to merge the exits. This helps several passes, such
00631   // as LoopRotation, which do not support loops with multiple exits.
00632   // SimplifyCFG also does this (and this code uses the same utility
00633   // function), however this code is loop-aware, where SimplifyCFG is
00634   // not. That gives it the advantage of being able to hoist
00635   // loop-invariant instructions out of the way to open up more
00636   // opportunities, and the disadvantage of having the responsibility
00637   // to preserve dominator information.
00638   bool UniqueExit = true;
00639   if (!ExitBlocks.empty())
00640     for (unsigned i = 1, e = ExitBlocks.size(); i != e; ++i)
00641       if (ExitBlocks[i] != ExitBlocks[0]) {
00642         UniqueExit = false;
00643         break;
00644       }
00645   if (UniqueExit) {
00646     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
00647       BasicBlock *ExitingBlock = ExitingBlocks[i];
00648       if (!ExitingBlock->getSinglePredecessor()) continue;
00649       BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
00650       if (!BI || !BI->isConditional()) continue;
00651       CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
00652       if (!CI || CI->getParent() != ExitingBlock) continue;
00653 
00654       // Attempt to hoist out all instructions except for the
00655       // comparison and the branch.
00656       bool AllInvariant = true;
00657       bool AnyInvariant = false;
00658       for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
00659         Instruction *Inst = I++;
00660         // Skip debug info intrinsics.
00661         if (isa<DbgInfoIntrinsic>(Inst))
00662           continue;
00663         if (Inst == CI)
00664           continue;
00665         if (!L->makeLoopInvariant(Inst, AnyInvariant,
00666                                   Preheader ? Preheader->getTerminator()
00667                                             : nullptr)) {
00668           AllInvariant = false;
00669           break;
00670         }
00671       }
00672       if (AnyInvariant) {
00673         Changed = true;
00674         // The loop disposition of all SCEV expressions that depend on any
00675         // hoisted values have also changed.
00676         if (SE)
00677           SE->forgetLoopDispositions(L);
00678       }
00679       if (!AllInvariant) continue;
00680 
00681       // The block has now been cleared of all instructions except for
00682       // a comparison and a conditional branch. SimplifyCFG may be able
00683       // to fold it now.
00684       if (!FoldBranchToCommonDest(BI))
00685         continue;
00686 
00687       // Success. The block is now dead, so remove it from the loop,
00688       // update the dominator tree and delete it.
00689       DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
00690                    << ExitingBlock->getName() << "\n");
00691 
00692       // Notify ScalarEvolution before deleting this block. Currently assume the
00693       // parent loop doesn't change (spliting edges doesn't count). If blocks,
00694       // CFG edges, or other values in the parent loop change, then we need call
00695       // to forgetLoop() for the parent instead.
00696       if (SE)
00697         SE->forgetLoop(L);
00698 
00699       assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
00700       Changed = true;
00701       LI->removeBlock(ExitingBlock);
00702 
00703       DomTreeNode *Node = DT->getNode(ExitingBlock);
00704       const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
00705         Node->getChildren();
00706       while (!Children.empty()) {
00707         DomTreeNode *Child = Children.front();
00708         DT->changeImmediateDominator(Child, Node->getIDom());
00709       }
00710       DT->eraseNode(ExitingBlock);
00711 
00712       BI->getSuccessor(0)->removePredecessor(ExitingBlock);
00713       BI->getSuccessor(1)->removePredecessor(ExitingBlock);
00714       ExitingBlock->eraseFromParent();
00715     }
00716   }
00717 
00718   return Changed;
00719 }
00720 
00721 bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, Pass *PP,
00722                         AliasAnalysis *AA, ScalarEvolution *SE,
00723                         AssumptionCache *AC) {
00724   bool Changed = false;
00725 
00726   // Worklist maintains our depth-first queue of loops in this nest to process.
00727   SmallVector<Loop *, 4> Worklist;
00728   Worklist.push_back(L);
00729 
00730   // Walk the worklist from front to back, pushing newly found sub loops onto
00731   // the back. This will let us process loops from back to front in depth-first
00732   // order. We can use this simple process because loops form a tree.
00733   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
00734     Loop *L2 = Worklist[Idx];
00735     Worklist.append(L2->begin(), L2->end());
00736   }
00737 
00738   while (!Worklist.empty())
00739     Changed |= simplifyOneLoop(Worklist.pop_back_val(), Worklist, AA, DT, LI,
00740                                SE, PP, AC);
00741 
00742   return Changed;
00743 }
00744 
00745 namespace {
00746   struct LoopSimplify : public FunctionPass {
00747     static char ID; // Pass identification, replacement for typeid
00748     LoopSimplify() : FunctionPass(ID) {
00749       initializeLoopSimplifyPass(*PassRegistry::getPassRegistry());
00750     }
00751 
00752     // AA - If we have an alias analysis object to update, this is it, otherwise
00753     // this is null.
00754     AliasAnalysis *AA;
00755     DominatorTree *DT;
00756     LoopInfo *LI;
00757     ScalarEvolution *SE;
00758     AssumptionCache *AC;
00759 
00760     bool runOnFunction(Function &F) override;
00761 
00762     void getAnalysisUsage(AnalysisUsage &AU) const override {
00763       AU.addRequired<AssumptionCacheTracker>();
00764 
00765       // We need loop information to identify the loops...
00766       AU.addRequired<DominatorTreeWrapperPass>();
00767       AU.addPreserved<DominatorTreeWrapperPass>();
00768 
00769       AU.addRequired<LoopInfoWrapperPass>();
00770       AU.addPreserved<LoopInfoWrapperPass>();
00771 
00772       AU.addPreserved<AliasAnalysis>();
00773       AU.addPreserved<ScalarEvolution>();
00774       AU.addPreserved<DependenceAnalysis>();
00775       AU.addPreservedID(BreakCriticalEdgesID);  // No critical edges added.
00776     }
00777 
00778     /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
00779     void verifyAnalysis() const override;
00780   };
00781 }
00782 
00783 char LoopSimplify::ID = 0;
00784 INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
00785                 "Canonicalize natural loops", false, false)
00786 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00787 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00788 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00789 INITIALIZE_PASS_END(LoopSimplify, "loop-simplify",
00790                 "Canonicalize natural loops", false, false)
00791 
00792 // Publicly exposed interface to pass...
00793 char &llvm::LoopSimplifyID = LoopSimplify::ID;
00794 Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
00795 
00796 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
00797 /// it in any convenient order) inserting preheaders...
00798 ///
00799 bool LoopSimplify::runOnFunction(Function &F) {
00800   bool Changed = false;
00801   AA = getAnalysisIfAvailable<AliasAnalysis>();
00802   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00803   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00804   SE = getAnalysisIfAvailable<ScalarEvolution>();
00805   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
00806 
00807   // Simplify each loop nest in the function.
00808   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
00809     Changed |= simplifyLoop(*I, DT, LI, this, AA, SE, AC);
00810 
00811   return Changed;
00812 }
00813 
00814 // FIXME: Restore this code when we re-enable verification in verifyAnalysis
00815 // below.
00816 #if 0
00817 static void verifyLoop(Loop *L) {
00818   // Verify subloops.
00819   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
00820     verifyLoop(*I);
00821 
00822   // It used to be possible to just assert L->isLoopSimplifyForm(), however
00823   // with the introduction of indirectbr, there are now cases where it's
00824   // not possible to transform a loop as necessary. We can at least check
00825   // that there is an indirectbr near any time there's trouble.
00826 
00827   // Indirectbr can interfere with preheader and unique backedge insertion.
00828   if (!L->getLoopPreheader() || !L->getLoopLatch()) {
00829     bool HasIndBrPred = false;
00830     for (pred_iterator PI = pred_begin(L->getHeader()),
00831          PE = pred_end(L->getHeader()); PI != PE; ++PI)
00832       if (isa<IndirectBrInst>((*PI)->getTerminator())) {
00833         HasIndBrPred = true;
00834         break;
00835       }
00836     assert(HasIndBrPred &&
00837            "LoopSimplify has no excuse for missing loop header info!");
00838     (void)HasIndBrPred;
00839   }
00840 
00841   // Indirectbr can interfere with exit block canonicalization.
00842   if (!L->hasDedicatedExits()) {
00843     bool HasIndBrExiting = false;
00844     SmallVector<BasicBlock*, 8> ExitingBlocks;
00845     L->getExitingBlocks(ExitingBlocks);
00846     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
00847       if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
00848         HasIndBrExiting = true;
00849         break;
00850       }
00851     }
00852 
00853     assert(HasIndBrExiting &&
00854            "LoopSimplify has no excuse for missing exit block info!");
00855     (void)HasIndBrExiting;
00856   }
00857 }
00858 #endif
00859 
00860 void LoopSimplify::verifyAnalysis() const {
00861   // FIXME: This routine is being called mid-way through the loop pass manager
00862   // as loop passes destroy this analysis. That's actually fine, but we have no
00863   // way of expressing that here. Once all of the passes that destroy this are
00864   // hoisted out of the loop pass manager we can add back verification here.
00865 #if 0
00866   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
00867     verifyLoop(*I);
00868 #endif
00869 }