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