LLVM API Documentation

LoopUnroll.cpp
Go to the documentation of this file.
00001 //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements some loop unrolling utilities. It does not define any
00011 // actual pass or policy, but provides a single function to perform loop
00012 // unrolling.
00013 //
00014 // The process of unrolling can produce extraneous basic blocks linked with
00015 // unconditional branches.  This will be corrected in the future.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #define DEBUG_TYPE "loop-unroll"
00020 #include "llvm/Transforms/Utils/UnrollLoop.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/InstructionSimplify.h"
00023 #include "llvm/Analysis/LoopIterator.h"
00024 #include "llvm/Analysis/LoopPass.h"
00025 #include "llvm/Analysis/ScalarEvolution.h"
00026 #include "llvm/IR/BasicBlock.h"
00027 #include "llvm/Support/Debug.h"
00028 #include "llvm/Support/raw_ostream.h"
00029 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00030 #include "llvm/Transforms/Utils/Cloning.h"
00031 #include "llvm/Transforms/Utils/Local.h"
00032 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
00033 using namespace llvm;
00034 
00035 // TODO: Should these be here or in LoopUnroll?
00036 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
00037 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
00038 
00039 /// RemapInstruction - Convert the instruction operands from referencing the
00040 /// current values into those specified by VMap.
00041 static inline void RemapInstruction(Instruction *I,
00042                                     ValueToValueMapTy &VMap) {
00043   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
00044     Value *Op = I->getOperand(op);
00045     ValueToValueMapTy::iterator It = VMap.find(Op);
00046     if (It != VMap.end())
00047       I->setOperand(op, It->second);
00048   }
00049 
00050   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00051     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00052       ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
00053       if (It != VMap.end())
00054         PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
00055     }
00056   }
00057 }
00058 
00059 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
00060 /// only has one predecessor, and that predecessor only has one successor.
00061 /// The LoopInfo Analysis that is passed will be kept consistent.
00062 /// Returns the new combined block.
00063 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
00064                                             LPPassManager *LPM) {
00065   // Merge basic blocks into their predecessor if there is only one distinct
00066   // pred, and if there is only one distinct successor of the predecessor, and
00067   // if there are no PHI nodes.
00068   BasicBlock *OnlyPred = BB->getSinglePredecessor();
00069   if (!OnlyPred) return 0;
00070 
00071   if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
00072     return 0;
00073 
00074   DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
00075 
00076   // Resolve any PHI nodes at the start of the block.  They are all
00077   // guaranteed to have exactly one entry if they exist, unless there are
00078   // multiple duplicate (but guaranteed to be equal) entries for the
00079   // incoming edges.  This occurs when there are multiple edges from
00080   // OnlyPred to OnlySucc.
00081   FoldSingleEntryPHINodes(BB);
00082 
00083   // Delete the unconditional branch from the predecessor...
00084   OnlyPred->getInstList().pop_back();
00085 
00086   // Make all PHI nodes that referred to BB now refer to Pred as their
00087   // source...
00088   BB->replaceAllUsesWith(OnlyPred);
00089 
00090   // Move all definitions in the successor to the predecessor...
00091   OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
00092 
00093   std::string OldName = BB->getName();
00094 
00095   // Erase basic block from the function...
00096 
00097   // ScalarEvolution holds references to loop exit blocks.
00098   if (LPM) {
00099     if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
00100       if (Loop *L = LI->getLoopFor(BB))
00101         SE->forgetLoop(L);
00102     }
00103   }
00104   LI->removeBlock(BB);
00105   BB->eraseFromParent();
00106 
00107   // Inherit predecessor's name if it exists...
00108   if (!OldName.empty() && !OnlyPred->hasName())
00109     OnlyPred->setName(OldName);
00110 
00111   return OnlyPred;
00112 }
00113 
00114 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
00115 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
00116 /// can only fail when the loop's latch block is not terminated by a conditional
00117 /// branch instruction. However, if the trip count (and multiple) are not known,
00118 /// loop unrolling will mostly produce more code that is no faster.
00119 ///
00120 /// TripCount is generally defined as the number of times the loop header
00121 /// executes. UnrollLoop relaxes the definition to permit early exits: here
00122 /// TripCount is the iteration on which control exits LatchBlock if no early
00123 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
00124 /// terminates LatchBlock in order to remove unnecesssary instances of the
00125 /// test. In other words, control may exit the loop prior to TripCount
00126 /// iterations via an early branch, but control may not exit the loop from the
00127 /// LatchBlock's terminator prior to TripCount iterations.
00128 ///
00129 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
00130 /// execute without exiting the loop.
00131 ///
00132 /// The LoopInfo Analysis that is passed will be kept consistent.
00133 ///
00134 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
00135 /// removed from the LoopPassManager as well. LPM can also be NULL.
00136 ///
00137 /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
00138 /// available it must also preserve those analyses.
00139 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
00140                       bool AllowRuntime, unsigned TripMultiple,
00141                       LoopInfo *LI, LPPassManager *LPM) {
00142   BasicBlock *Preheader = L->getLoopPreheader();
00143   if (!Preheader) {
00144     DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
00145     return false;
00146   }
00147 
00148   BasicBlock *LatchBlock = L->getLoopLatch();
00149   if (!LatchBlock) {
00150     DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
00151     return false;
00152   }
00153 
00154   // Loops with indirectbr cannot be cloned.
00155   if (!L->isSafeToClone()) {
00156     DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
00157     return false;
00158   }
00159 
00160   BasicBlock *Header = L->getHeader();
00161   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
00162 
00163   if (!BI || BI->isUnconditional()) {
00164     // The loop-rotate pass can be helpful to avoid this in many cases.
00165     DEBUG(dbgs() <<
00166              "  Can't unroll; loop not terminated by a conditional branch.\n");
00167     return false;
00168   }
00169 
00170   if (Header->hasAddressTaken()) {
00171     // The loop-rotate pass can be helpful to avoid this in many cases.
00172     DEBUG(dbgs() <<
00173           "  Won't unroll loop: address of header block is taken.\n");
00174     return false;
00175   }
00176 
00177   if (TripCount != 0)
00178     DEBUG(dbgs() << "  Trip Count = " << TripCount << "\n");
00179   if (TripMultiple != 1)
00180     DEBUG(dbgs() << "  Trip Multiple = " << TripMultiple << "\n");
00181 
00182   // Effectively "DCE" unrolled iterations that are beyond the tripcount
00183   // and will never be executed.
00184   if (TripCount != 0 && Count > TripCount)
00185     Count = TripCount;
00186 
00187   // Don't enter the unroll code if there is nothing to do. This way we don't
00188   // need to support "partial unrolling by 1".
00189   if (TripCount == 0 && Count < 2)
00190     return false;
00191 
00192   assert(Count > 0);
00193   assert(TripMultiple > 0);
00194   assert(TripCount == 0 || TripCount % TripMultiple == 0);
00195 
00196   // Are we eliminating the loop control altogether?
00197   bool CompletelyUnroll = Count == TripCount;
00198 
00199   // We assume a run-time trip count if the compiler cannot
00200   // figure out the loop trip count and the unroll-runtime
00201   // flag is specified.
00202   bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
00203 
00204   if (RuntimeTripCount && !UnrollRuntimeLoopProlog(L, Count, LI, LPM))
00205     return false;
00206 
00207   // Notify ScalarEvolution that the loop will be substantially changed,
00208   // if not outright eliminated.
00209   if (LPM) {
00210     ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
00211     if (SE)
00212       SE->forgetLoop(L);
00213   }
00214 
00215   // If we know the trip count, we know the multiple...
00216   unsigned BreakoutTrip = 0;
00217   if (TripCount != 0) {
00218     BreakoutTrip = TripCount % Count;
00219     TripMultiple = 0;
00220   } else {
00221     // Figure out what multiple to use.
00222     BreakoutTrip = TripMultiple =
00223       (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
00224   }
00225 
00226   if (CompletelyUnroll) {
00227     DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
00228           << " with trip count " << TripCount << "!\n");
00229   } else {
00230     DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
00231           << " by " << Count);
00232     if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
00233       DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
00234     } else if (TripMultiple != 1) {
00235       DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
00236     } else if (RuntimeTripCount) {
00237       DEBUG(dbgs() << " with run-time trip count");
00238     }
00239     DEBUG(dbgs() << "!\n");
00240   }
00241 
00242   std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
00243 
00244   bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
00245   BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
00246 
00247   // For the first iteration of the loop, we should use the precloned values for
00248   // PHI nodes.  Insert associations now.
00249   ValueToValueMapTy LastValueMap;
00250   std::vector<PHINode*> OrigPHINode;
00251   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00252     OrigPHINode.push_back(cast<PHINode>(I));
00253   }
00254 
00255   std::vector<BasicBlock*> Headers;
00256   std::vector<BasicBlock*> Latches;
00257   Headers.push_back(Header);
00258   Latches.push_back(LatchBlock);
00259 
00260   // The current on-the-fly SSA update requires blocks to be processed in
00261   // reverse postorder so that LastValueMap contains the correct value at each
00262   // exit.
00263   LoopBlocksDFS DFS(L);
00264   DFS.perform(LI);
00265 
00266   // Stash the DFS iterators before adding blocks to the loop.
00267   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
00268   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
00269 
00270   for (unsigned It = 1; It != Count; ++It) {
00271     std::vector<BasicBlock*> NewBlocks;
00272 
00273     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
00274       ValueToValueMapTy VMap;
00275       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
00276       Header->getParent()->getBasicBlockList().push_back(New);
00277 
00278       // Loop over all of the PHI nodes in the block, changing them to use the
00279       // incoming values from the previous block.
00280       if (*BB == Header)
00281         for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00282           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
00283           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
00284           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
00285             if (It > 1 && L->contains(InValI))
00286               InVal = LastValueMap[InValI];
00287           VMap[OrigPHINode[i]] = InVal;
00288           New->getInstList().erase(NewPHI);
00289         }
00290 
00291       // Update our running map of newest clones
00292       LastValueMap[*BB] = New;
00293       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
00294            VI != VE; ++VI)
00295         LastValueMap[VI->first] = VI->second;
00296 
00297       L->addBasicBlockToLoop(New, LI->getBase());
00298 
00299       // Add phi entries for newly created values to all exit blocks.
00300       for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
00301            SI != SE; ++SI) {
00302         if (L->contains(*SI))
00303           continue;
00304         for (BasicBlock::iterator BBI = (*SI)->begin();
00305              PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
00306           Value *Incoming = phi->getIncomingValueForBlock(*BB);
00307           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
00308           if (It != LastValueMap.end())
00309             Incoming = It->second;
00310           phi->addIncoming(Incoming, New);
00311         }
00312       }
00313       // Keep track of new headers and latches as we create them, so that
00314       // we can insert the proper branches later.
00315       if (*BB == Header)
00316         Headers.push_back(New);
00317       if (*BB == LatchBlock)
00318         Latches.push_back(New);
00319 
00320       NewBlocks.push_back(New);
00321     }
00322 
00323     // Remap all instructions in the most recent iteration
00324     for (unsigned i = 0; i < NewBlocks.size(); ++i)
00325       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00326            E = NewBlocks[i]->end(); I != E; ++I)
00327         ::RemapInstruction(I, LastValueMap);
00328   }
00329 
00330   // Loop over the PHI nodes in the original block, setting incoming values.
00331   for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
00332     PHINode *PN = OrigPHINode[i];
00333     if (CompletelyUnroll) {
00334       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
00335       Header->getInstList().erase(PN);
00336     }
00337     else if (Count > 1) {
00338       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
00339       // If this value was defined in the loop, take the value defined by the
00340       // last iteration of the loop.
00341       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
00342         if (L->contains(InValI))
00343           InVal = LastValueMap[InVal];
00344       }
00345       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
00346       PN->addIncoming(InVal, Latches.back());
00347     }
00348   }
00349 
00350   // Now that all the basic blocks for the unrolled iterations are in place,
00351   // set up the branches to connect them.
00352   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
00353     // The original branch was replicated in each unrolled iteration.
00354     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
00355 
00356     // The branch destination.
00357     unsigned j = (i + 1) % e;
00358     BasicBlock *Dest = Headers[j];
00359     bool NeedConditional = true;
00360 
00361     if (RuntimeTripCount && j != 0) {
00362       NeedConditional = false;
00363     }
00364 
00365     // For a complete unroll, make the last iteration end with a branch
00366     // to the exit block.
00367     if (CompletelyUnroll && j == 0) {
00368       Dest = LoopExit;
00369       NeedConditional = false;
00370     }
00371 
00372     // If we know the trip count or a multiple of it, we can safely use an
00373     // unconditional branch for some iterations.
00374     if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
00375       NeedConditional = false;
00376     }
00377 
00378     if (NeedConditional) {
00379       // Update the conditional branch's successor for the following
00380       // iteration.
00381       Term->setSuccessor(!ContinueOnTrue, Dest);
00382     } else {
00383       // Remove phi operands at this loop exit
00384       if (Dest != LoopExit) {
00385         BasicBlock *BB = Latches[i];
00386         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
00387              SI != SE; ++SI) {
00388           if (*SI == Headers[i])
00389             continue;
00390           for (BasicBlock::iterator BBI = (*SI)->begin();
00391                PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
00392             Phi->removeIncomingValue(BB, false);
00393           }
00394         }
00395       }
00396       // Replace the conditional branch with an unconditional one.
00397       BranchInst::Create(Dest, Term);
00398       Term->eraseFromParent();
00399     }
00400   }
00401 
00402   // Merge adjacent basic blocks, if possible.
00403   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
00404     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
00405     if (Term->isUnconditional()) {
00406       BasicBlock *Dest = Term->getSuccessor(0);
00407       if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM))
00408         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
00409     }
00410   }
00411 
00412   if (LPM) {
00413     // FIXME: Reconstruct dom info, because it is not preserved properly.
00414     // Incrementally updating domtree after loop unrolling would be easy.
00415     if (DominatorTree *DT = LPM->getAnalysisIfAvailable<DominatorTree>())
00416       DT->runOnFunction(*L->getHeader()->getParent());
00417 
00418     // Simplify any new induction variables in the partially unrolled loop.
00419     ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
00420     if (SE && !CompletelyUnroll) {
00421       SmallVector<WeakVH, 16> DeadInsts;
00422       simplifyLoopIVs(L, SE, LPM, DeadInsts);
00423 
00424       // Aggressively clean up dead instructions that simplifyLoopIVs already
00425       // identified. Any remaining should be cleaned up below.
00426       while (!DeadInsts.empty())
00427         if (Instruction *Inst =
00428             dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
00429           RecursivelyDeleteTriviallyDeadInstructions(Inst);
00430     }
00431   }
00432   // At this point, the code is well formed.  We now do a quick sweep over the
00433   // inserted code, doing constant propagation and dead code elimination as we
00434   // go.
00435   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
00436   for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
00437        BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
00438     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
00439       Instruction *Inst = I++;
00440 
00441       if (isInstructionTriviallyDead(Inst))
00442         (*BB)->getInstList().erase(Inst);
00443       else if (Value *V = SimplifyInstruction(Inst))
00444         if (LI->replacementPreservesLCSSAForm(Inst, V)) {
00445           Inst->replaceAllUsesWith(V);
00446           (*BB)->getInstList().erase(Inst);
00447         }
00448     }
00449 
00450   NumCompletelyUnrolled += CompletelyUnroll;
00451   ++NumUnrolled;
00452   // Remove the loop from the LoopPassManager if it's completely removed.
00453   if (CompletelyUnroll && LPM != NULL)
00454     LPM->deleteLoopFromQueue(L);
00455 
00456   return true;
00457 }