LLVM API Documentation

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