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/DataLayout.h"
00054 #include "llvm/IR/Dominators.h"
00055 #include "llvm/IR/Function.h"
00056 #include "llvm/IR/Instructions.h"
00057 #include "llvm/IR/IntrinsicInst.h"
00058 #include "llvm/IR/LLVMContext.h"
00059 #include "llvm/IR/Type.h"
00060 #include "llvm/Support/Debug.h"
00061 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00062 #include "llvm/Transforms/Utils/Local.h"
00063 #include "llvm/Transforms/Utils/LoopUtils.h"
00064 using namespace llvm;
00065 
00066 #define DEBUG_TYPE "loop-simplify"
00067 
00068 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
00069 STATISTIC(NumNested  , "Number of nested loops split out");
00070 
00071 // If the block isn't already, move the new block to right after some 'outside
00072 // block' block.  This prevents the preheader from being placed inside the loop
00073 // body, e.g. when the loop hasn't been rotated.
00074 static void placeSplitBlockCarefully(BasicBlock *NewBB,
00075                                      SmallVectorImpl<BasicBlock *> &SplitPreds,
00076                                      Loop *L) {
00077   // Check to see if NewBB is already well placed.
00078   Function::iterator BBI = NewBB; --BBI;
00079   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
00080     if (&*BBI == SplitPreds[i])
00081       return;
00082   }
00083 
00084   // If it isn't already after an outside block, move it after one.  This is
00085   // always good as it makes the uncond branch from the outside block into a
00086   // fall-through.
00087 
00088   // Figure out *which* outside block to put this after.  Prefer an outside
00089   // block that neighbors a BB actually in the loop.
00090   BasicBlock *FoundBB = nullptr;
00091   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
00092     Function::iterator BBI = SplitPreds[i];
00093     if (++BBI != NewBB->getParent()->end() &&
00094         L->contains(BBI)) {
00095       FoundBB = SplitPreds[i];
00096       break;
00097     }
00098   }
00099 
00100   // If our heuristic for a *good* bb to place this after doesn't find
00101   // anything, just pick something.  It's likely better than leaving it within
00102   // the loop.
00103   if (!FoundBB)
00104     FoundBB = SplitPreds[0];
00105   NewBB->moveAfter(FoundBB);
00106 }
00107 
00108 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
00109 /// preheader, this method is called to insert one.  This method has two phases:
00110 /// preheader insertion and analysis updating.
00111 ///
00112 BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, Pass *PP) {
00113   BasicBlock *Header = L->getHeader();
00114 
00115   // Compute the set of predecessors of the loop that are not in the loop.
00116   SmallVector<BasicBlock*, 8> OutsideBlocks;
00117   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
00118        PI != PE; ++PI) {
00119     BasicBlock *P = *PI;
00120     if (!L->contains(P)) {         // Coming in from outside the loop?
00121       // If the loop is branched to from an indirect branch, we won't
00122       // be able to fully transform the loop, because it prohibits
00123       // edge splitting.
00124       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
00125 
00126       // Keep track of it.
00127       OutsideBlocks.push_back(P);
00128     }
00129   }
00130 
00131   // Split out the loop pre-header.
00132   BasicBlock *PreheaderBB;
00133   if (!Header->isLandingPad()) {
00134     PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
00135                                          PP);
00136   } else {
00137     SmallVector<BasicBlock*, 2> NewBBs;
00138     SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader",
00139                                 ".split-lp", PP, NewBBs);
00140     PreheaderBB = NewBBs[0];
00141   }
00142 
00143   PreheaderBB->getTerminator()->setDebugLoc(
00144                                       Header->getFirstNonPHI()->getDebugLoc());
00145   DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
00146                << PreheaderBB->getName() << "\n");
00147 
00148   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
00149   // code layout too horribly.
00150   placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
00151 
00152   return PreheaderBB;
00153 }
00154 
00155 /// \brief Ensure that the loop preheader dominates all exit blocks.
00156 ///
00157 /// This method is used to split exit blocks that have predecessors outside of
00158 /// the loop.
00159 static BasicBlock *rewriteLoopExitBlock(Loop *L, BasicBlock *Exit, Pass *PP) {
00160   SmallVector<BasicBlock*, 8> LoopBlocks;
00161   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) {
00162     BasicBlock *P = *I;
00163     if (L->contains(P)) {
00164       // Don't do this if the loop is exited via an indirect branch.
00165       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
00166 
00167       LoopBlocks.push_back(P);
00168     }
00169   }
00170 
00171   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
00172   BasicBlock *NewExitBB = nullptr;
00173 
00174   if (Exit->isLandingPad()) {
00175     SmallVector<BasicBlock*, 2> NewBBs;
00176     SplitLandingPadPredecessors(Exit, LoopBlocks,
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, nullptr, nullptr, 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 nullptr;
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 nullptr;
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) return nullptr;  // 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 nullptr;
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 nullptr;
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 nullptr;
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 = nullptr;
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)
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                             const DataLayout *DL) {
00478   bool Changed = false;
00479 ReprocessLoop:
00480 
00481   // Check to see that no blocks (other than the header) in this loop have
00482   // predecessors that are not in the loop.  This is not valid for natural
00483   // loops, but can occur if the blocks are unreachable.  Since they are
00484   // unreachable we can just shamelessly delete those CFG edges!
00485   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
00486        BB != E; ++BB) {
00487     if (*BB == L->getHeader()) continue;
00488 
00489     SmallPtrSet<BasicBlock*, 4> BadPreds;
00490     for (pred_iterator PI = pred_begin(*BB),
00491          PE = pred_end(*BB); PI != PE; ++PI) {
00492       BasicBlock *P = *PI;
00493       if (!L->contains(P))
00494         BadPreds.insert(P);
00495     }
00496 
00497     // Delete each unique out-of-loop (and thus dead) predecessor.
00498     for (BasicBlock *P : BadPreds) {
00499 
00500       DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
00501                    << P->getName() << "\n");
00502 
00503       // Inform each successor of each dead pred.
00504       for (succ_iterator SI = succ_begin(P), SE = succ_end(P); SI != SE; ++SI)
00505         (*SI)->removePredecessor(P);
00506       // Zap the dead pred's terminator and replace it with unreachable.
00507       TerminatorInst *TI = P->getTerminator();
00508        TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
00509       P->getTerminator()->eraseFromParent();
00510       new UnreachableInst(P->getContext(), P);
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, nullptr, nullptr, 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()
00658                                             : nullptr)) {
00659           AllInvariant = false;
00660           break;
00661         }
00662       }
00663       if (AnyInvariant) {
00664         Changed = true;
00665         // The loop disposition of all SCEV expressions that depend on any
00666         // hoisted values have also changed.
00667         if (SE)
00668           SE->forgetLoopDispositions(L);
00669       }
00670       if (!AllInvariant) continue;
00671 
00672       // The block has now been cleared of all instructions except for
00673       // a comparison and a conditional branch. SimplifyCFG may be able
00674       // to fold it now.
00675       if (!FoldBranchToCommonDest(BI, DL)) continue;
00676 
00677       // Success. The block is now dead, so remove it from the loop,
00678       // update the dominator tree and delete it.
00679       DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
00680                    << ExitingBlock->getName() << "\n");
00681 
00682       // Notify ScalarEvolution before deleting this block. Currently assume the
00683       // parent loop doesn't change (spliting edges doesn't count). If blocks,
00684       // CFG edges, or other values in the parent loop change, then we need call
00685       // to forgetLoop() for the parent instead.
00686       if (SE)
00687         SE->forgetLoop(L);
00688 
00689       assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
00690       Changed = true;
00691       LI->removeBlock(ExitingBlock);
00692 
00693       DomTreeNode *Node = DT->getNode(ExitingBlock);
00694       const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
00695         Node->getChildren();
00696       while (!Children.empty()) {
00697         DomTreeNode *Child = Children.front();
00698         DT->changeImmediateDominator(Child, Node->getIDom());
00699       }
00700       DT->eraseNode(ExitingBlock);
00701 
00702       BI->getSuccessor(0)->removePredecessor(ExitingBlock);
00703       BI->getSuccessor(1)->removePredecessor(ExitingBlock);
00704       ExitingBlock->eraseFromParent();
00705     }
00706   }
00707 
00708   return Changed;
00709 }
00710 
00711 bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, Pass *PP,
00712                         AliasAnalysis *AA, ScalarEvolution *SE,
00713                         const DataLayout *DL) {
00714   bool Changed = false;
00715 
00716   // Worklist maintains our depth-first queue of loops in this nest to process.
00717   SmallVector<Loop *, 4> Worklist;
00718   Worklist.push_back(L);
00719 
00720   // Walk the worklist from front to back, pushing newly found sub loops onto
00721   // the back. This will let us process loops from back to front in depth-first
00722   // order. We can use this simple process because loops form a tree.
00723   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
00724     Loop *L2 = Worklist[Idx];
00725     for (Loop::iterator I = L2->begin(), E = L2->end(); I != E; ++I)
00726       Worklist.push_back(*I);
00727   }
00728 
00729   while (!Worklist.empty())
00730     Changed |= simplifyOneLoop(Worklist.pop_back_val(), Worklist, AA, DT, LI,
00731                                SE, PP, DL);
00732 
00733   return Changed;
00734 }
00735 
00736 namespace {
00737   struct LoopSimplify : public FunctionPass {
00738     static char ID; // Pass identification, replacement for typeid
00739     LoopSimplify() : FunctionPass(ID) {
00740       initializeLoopSimplifyPass(*PassRegistry::getPassRegistry());
00741     }
00742 
00743     // AA - If we have an alias analysis object to update, this is it, otherwise
00744     // this is null.
00745     AliasAnalysis *AA;
00746     DominatorTree *DT;
00747     LoopInfo *LI;
00748     ScalarEvolution *SE;
00749     const DataLayout *DL;
00750 
00751     bool runOnFunction(Function &F) override;
00752 
00753     void getAnalysisUsage(AnalysisUsage &AU) const override {
00754       // We need loop information to identify the loops...
00755       AU.addRequired<DominatorTreeWrapperPass>();
00756       AU.addPreserved<DominatorTreeWrapperPass>();
00757 
00758       AU.addRequired<LoopInfo>();
00759       AU.addPreserved<LoopInfo>();
00760 
00761       AU.addPreserved<AliasAnalysis>();
00762       AU.addPreserved<ScalarEvolution>();
00763       AU.addPreserved<DependenceAnalysis>();
00764       AU.addPreservedID(BreakCriticalEdgesID);  // No critical edges added.
00765     }
00766 
00767     /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
00768     void verifyAnalysis() const override;
00769   };
00770 }
00771 
00772 char LoopSimplify::ID = 0;
00773 INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
00774                 "Canonicalize natural loops", true, false)
00775 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00776 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
00777 INITIALIZE_PASS_END(LoopSimplify, "loop-simplify",
00778                 "Canonicalize natural loops", true, false)
00779 
00780 // Publicly exposed interface to pass...
00781 char &llvm::LoopSimplifyID = LoopSimplify::ID;
00782 Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
00783 
00784 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
00785 /// it in any convenient order) inserting preheaders...
00786 ///
00787 bool LoopSimplify::runOnFunction(Function &F) {
00788   bool Changed = false;
00789   AA = getAnalysisIfAvailable<AliasAnalysis>();
00790   LI = &getAnalysis<LoopInfo>();
00791   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00792   SE = getAnalysisIfAvailable<ScalarEvolution>();
00793   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00794   DL = DLP ? &DLP->getDataLayout() : nullptr;
00795 
00796   // Simplify each loop nest in the function.
00797   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
00798     Changed |= simplifyLoop(*I, DT, LI, this, AA, SE, DL);
00799 
00800   return Changed;
00801 }
00802 
00803 // FIXME: Restore this code when we re-enable verification in verifyAnalysis
00804 // below.
00805 #if 0
00806 static void verifyLoop(Loop *L) {
00807   // Verify subloops.
00808   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
00809     verifyLoop(*I);
00810 
00811   // It used to be possible to just assert L->isLoopSimplifyForm(), however
00812   // with the introduction of indirectbr, there are now cases where it's
00813   // not possible to transform a loop as necessary. We can at least check
00814   // that there is an indirectbr near any time there's trouble.
00815 
00816   // Indirectbr can interfere with preheader and unique backedge insertion.
00817   if (!L->getLoopPreheader() || !L->getLoopLatch()) {
00818     bool HasIndBrPred = false;
00819     for (pred_iterator PI = pred_begin(L->getHeader()),
00820          PE = pred_end(L->getHeader()); PI != PE; ++PI)
00821       if (isa<IndirectBrInst>((*PI)->getTerminator())) {
00822         HasIndBrPred = true;
00823         break;
00824       }
00825     assert(HasIndBrPred &&
00826            "LoopSimplify has no excuse for missing loop header info!");
00827     (void)HasIndBrPred;
00828   }
00829 
00830   // Indirectbr can interfere with exit block canonicalization.
00831   if (!L->hasDedicatedExits()) {
00832     bool HasIndBrExiting = false;
00833     SmallVector<BasicBlock*, 8> ExitingBlocks;
00834     L->getExitingBlocks(ExitingBlocks);
00835     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
00836       if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
00837         HasIndBrExiting = true;
00838         break;
00839       }
00840     }
00841 
00842     assert(HasIndBrExiting &&
00843            "LoopSimplify has no excuse for missing exit block info!");
00844     (void)HasIndBrExiting;
00845   }
00846 }
00847 #endif
00848 
00849 void LoopSimplify::verifyAnalysis() const {
00850   // FIXME: This routine is being called mid-way through the loop pass manager
00851   // as loop passes destroy this analysis. That's actually fine, but we have no
00852   // way of expressing that here. Once all of the passes that destroy this are
00853   // hoisted out of the loop pass manager we can add back verification here.
00854 #if 0
00855   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
00856     verifyLoop(*I);
00857 #endif
00858 }