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