LLVM API Documentation

LoopUnrollRuntime.cpp
Go to the documentation of this file.
00001 //===-- UnrollLoopRuntime.cpp - Runtime 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 for loops with run-time
00011 // trip counts.  See LoopUnroll.cpp for unrolling loops with compile-time
00012 // trip counts.
00013 //
00014 // The functions in this file are used to generate extra code when the
00015 // run-time trip count modulo the unroll factor is not 0.  When this is the
00016 // case, we need to generate code to execute these 'left over' iterations.
00017 //
00018 // The current strategy generates an if-then-else sequence prior to the
00019 // unrolled loop to execute the 'left over' iterations.  Other strategies
00020 // include generate a loop before or after the unrolled loop.
00021 //
00022 //===----------------------------------------------------------------------===//
00023 
00024 #define DEBUG_TYPE "loop-unroll"
00025 #include "llvm/Transforms/Utils/UnrollLoop.h"
00026 #include "llvm/ADT/Statistic.h"
00027 #include "llvm/Analysis/LoopIterator.h"
00028 #include "llvm/Analysis/LoopPass.h"
00029 #include "llvm/Analysis/ScalarEvolution.h"
00030 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00031 #include "llvm/IR/BasicBlock.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/Support/raw_ostream.h"
00034 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00035 #include "llvm/Transforms/Utils/Cloning.h"
00036 #include <algorithm>
00037 
00038 using namespace llvm;
00039 
00040 STATISTIC(NumRuntimeUnrolled,
00041           "Number of loops unrolled with run-time trip counts");
00042 
00043 /// Connect the unrolling prolog code to the original loop.
00044 /// The unrolling prolog code contains code to execute the
00045 /// 'extra' iterations if the run-time trip count modulo the
00046 /// unroll count is non-zero.
00047 ///
00048 /// This function performs the following:
00049 /// - Create PHI nodes at prolog end block to combine values
00050 ///   that exit the prolog code and jump around the prolog.
00051 /// - Add a PHI operand to a PHI node at the loop exit block
00052 ///   for values that exit the prolog and go around the loop.
00053 /// - Branch around the original loop if the trip count is less
00054 ///   than the unroll factor.
00055 ///
00056 static void ConnectProlog(Loop *L, Value *TripCount, unsigned Count,
00057                           BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
00058                           BasicBlock *OrigPH, BasicBlock *NewPH,
00059                           ValueToValueMapTy &LVMap, Pass *P) {
00060   BasicBlock *Latch = L->getLoopLatch();
00061   assert(Latch != 0 && "Loop must have a latch");
00062 
00063   // Create a PHI node for each outgoing value from the original loop
00064   // (which means it is an outgoing value from the prolog code too).
00065   // The new PHI node is inserted in the prolog end basic block.
00066   // The new PHI name is added as an operand of a PHI node in either
00067   // the loop header or the loop exit block.
00068   for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
00069        SBI != SBE; ++SBI) {
00070     for (BasicBlock::iterator BBI = (*SBI)->begin();
00071          PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
00072 
00073       // Add a new PHI node to the prolog end block and add the
00074       // appropriate incoming values.
00075       PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr",
00076                                        PrologEnd->getTerminator());
00077       // Adding a value to the new PHI node from the original loop preheader.
00078       // This is the value that skips all the prolog code.
00079       if (L->contains(PN)) {
00080         NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH);
00081       } else {
00082         NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH);
00083       }
00084 
00085       Value *V = PN->getIncomingValueForBlock(Latch);
00086       if (Instruction *I = dyn_cast<Instruction>(V)) {
00087         if (L->contains(I)) {
00088           V = LVMap[I];
00089         }
00090       }
00091       // Adding a value to the new PHI node from the last prolog block
00092       // that was created.
00093       NewPN->addIncoming(V, LastPrologBB);
00094 
00095       // Update the existing PHI node operand with the value from the
00096       // new PHI node.  How this is done depends on if the existing
00097       // PHI node is in the original loop block, or the exit block.
00098       if (L->contains(PN)) {
00099         PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN);
00100       } else {
00101         PN->addIncoming(NewPN, PrologEnd);
00102       }
00103     }
00104   }
00105 
00106   // Create a branch around the orignal loop, which is taken if the
00107   // trip count is less than the unroll factor.
00108   Instruction *InsertPt = PrologEnd->getTerminator();
00109   Instruction *BrLoopExit =
00110     new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, TripCount,
00111                  ConstantInt::get(TripCount->getType(), Count));
00112   BasicBlock *Exit = L->getUniqueExitBlock();
00113   assert(Exit != 0 && "Loop must have a single exit block only");
00114   // Split the exit to maintain loop canonicalization guarantees
00115   SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
00116   if (!Exit->isLandingPad()) {
00117     SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", P);
00118   } else {
00119     SmallVector<BasicBlock*, 2> NewBBs;
00120     SplitLandingPadPredecessors(Exit, Preds, ".unr1-lcssa", ".unr2-lcssa",
00121                                 P, NewBBs);
00122   }
00123   // Add the branch to the exit block (around the unrolled loop)
00124   BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt);
00125   InsertPt->eraseFromParent();
00126 }
00127 
00128 /// Create a clone of the blocks in a loop and connect them together.
00129 /// This function doesn't create a clone of the loop structure.
00130 ///
00131 /// There are two value maps that are defined and used.  VMap is
00132 /// for the values in the current loop instance.  LVMap contains
00133 /// the values from the last loop instance.  We need the LVMap values
00134 /// to update the initial values for the current loop instance.
00135 ///
00136 static void CloneLoopBlocks(Loop *L,
00137                             bool FirstCopy,
00138                             BasicBlock *InsertTop,
00139                             BasicBlock *InsertBot,
00140                             std::vector<BasicBlock *> &NewBlocks,
00141                             LoopBlocksDFS &LoopBlocks,
00142                             ValueToValueMapTy &VMap,
00143                             ValueToValueMapTy &LVMap,
00144                             LoopInfo *LI) {
00145 
00146   BasicBlock *Preheader = L->getLoopPreheader();
00147   BasicBlock *Header = L->getHeader();
00148   BasicBlock *Latch = L->getLoopLatch();
00149   Function *F = Header->getParent();
00150   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
00151   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
00152   // For each block in the original loop, create a new copy,
00153   // and update the value map with the newly created values.
00154   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
00155     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".unr", F);
00156     NewBlocks.push_back(NewBB);
00157 
00158     if (Loop *ParentLoop = L->getParentLoop())
00159       ParentLoop->addBasicBlockToLoop(NewBB, LI->getBase());
00160 
00161     VMap[*BB] = NewBB;
00162     if (Header == *BB) {
00163       // For the first block, add a CFG connection to this newly
00164       // created block
00165       InsertTop->getTerminator()->setSuccessor(0, NewBB);
00166 
00167       // Change the incoming values to the ones defined in the
00168       // previously cloned loop.
00169       for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00170         PHINode *NewPHI = cast<PHINode>(VMap[I]);
00171         if (FirstCopy) {
00172           // We replace the first phi node with the value from the preheader
00173           VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
00174           NewBB->getInstList().erase(NewPHI);
00175         } else {
00176           // Update VMap with values from the previous block
00177           unsigned idx = NewPHI->getBasicBlockIndex(Latch);
00178           Value *InVal = NewPHI->getIncomingValue(idx);
00179           if (Instruction *I = dyn_cast<Instruction>(InVal))
00180             if (L->contains(I))
00181               InVal = LVMap[InVal];
00182           NewPHI->setIncomingValue(idx, InVal);
00183           NewPHI->setIncomingBlock(idx, InsertTop);
00184         }
00185       }
00186     }
00187 
00188     if (Latch == *BB) {
00189       VMap.erase((*BB)->getTerminator());
00190       NewBB->getTerminator()->eraseFromParent();
00191       BranchInst::Create(InsertBot, NewBB);
00192     }
00193   }
00194   // LastValueMap is updated with the values for the current loop
00195   // which are used the next time this function is called.
00196   for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
00197        VI != VE; ++VI) {
00198     LVMap[VI->first] = VI->second;
00199   }
00200 }
00201 
00202 /// Insert code in the prolog code when unrolling a loop with a
00203 /// run-time trip-count.
00204 ///
00205 /// This method assumes that the loop unroll factor is total number
00206 /// of loop bodes in the loop after unrolling. (Some folks refer
00207 /// to the unroll factor as the number of *extra* copies added).
00208 /// We assume also that the loop unroll factor is a power-of-two. So, after
00209 /// unrolling the loop, the number of loop bodies executed is 2,
00210 /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
00211 /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
00212 /// the switch instruction is generated.
00213 ///
00214 ///    extraiters = tripcount % loopfactor
00215 ///    if (extraiters == 0) jump Loop:
00216 ///    if (extraiters == loopfactor) jump L1
00217 ///    if (extraiters == loopfactor-1) jump L2
00218 ///    ...
00219 ///    L1:  LoopBody;
00220 ///    L2:  LoopBody;
00221 ///    ...
00222 ///    if tripcount < loopfactor jump End
00223 ///    Loop:
00224 ///    ...
00225 ///    End:
00226 ///
00227 bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI,
00228                                    LPPassManager *LPM) {
00229   // for now, only unroll loops that contain a single exit
00230   if (!L->getExitingBlock())
00231     return false;
00232 
00233   // Make sure the loop is in canonical form, and there is a single
00234   // exit block only.
00235   if (!L->isLoopSimplifyForm() || L->getUniqueExitBlock() == 0)
00236     return false;
00237 
00238   // Use Scalar Evolution to compute the trip count.  This allows more
00239   // loops to be unrolled than relying on induction var simplification
00240   if (!LPM)
00241     return false;
00242   ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
00243   if (SE == 0)
00244     return false;
00245 
00246   // Only unroll loops with a computable trip count and the trip count needs
00247   // to be an int value (allowing a pointer type is a TODO item)
00248   const SCEV *BECount = SE->getBackedgeTakenCount(L);
00249   if (isa<SCEVCouldNotCompute>(BECount) || !BECount->getType()->isIntegerTy())
00250     return false;
00251 
00252   // Add 1 since the backedge count doesn't include the first loop iteration
00253   const SCEV *TripCountSC =
00254     SE->getAddExpr(BECount, SE->getConstant(BECount->getType(), 1));
00255   if (isa<SCEVCouldNotCompute>(TripCountSC))
00256     return false;
00257 
00258   // We only handle cases when the unroll factor is a power of 2.
00259   // Count is the loop unroll factor, the number of extra copies added + 1.
00260   if ((Count & (Count-1)) != 0)
00261     return false;
00262 
00263   // If this loop is nested, then the loop unroller changes the code in
00264   // parent loop, so the Scalar Evolution pass needs to be run again
00265   if (Loop *ParentLoop = L->getParentLoop())
00266     SE->forgetLoop(ParentLoop);
00267 
00268   BasicBlock *PH = L->getLoopPreheader();
00269   BasicBlock *Header = L->getHeader();
00270   BasicBlock *Latch = L->getLoopLatch();
00271   // It helps to splits the original preheader twice, one for the end of the
00272   // prolog code and one for a new loop preheader
00273   BasicBlock *PEnd = SplitEdge(PH, Header, LPM->getAsPass());
00274   BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), LPM->getAsPass());
00275   BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
00276 
00277   // Compute the number of extra iterations required, which is:
00278   //  extra iterations = run-time trip count % (loop unroll factor + 1)
00279   SCEVExpander Expander(*SE, "loop-unroll");
00280   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
00281                                             PreHeaderBR);
00282   Type *CountTy = TripCount->getType();
00283   BinaryOperator *ModVal =
00284     BinaryOperator::CreateURem(TripCount,
00285                                ConstantInt::get(CountTy, Count),
00286                                "xtraiter");
00287   ModVal->insertBefore(PreHeaderBR);
00288 
00289   // Check if for no extra iterations, then jump to unrolled loop
00290   Value *BranchVal = new ICmpInst(PreHeaderBR,
00291                                   ICmpInst::ICMP_NE, ModVal,
00292                                   ConstantInt::get(CountTy, 0), "lcmp");
00293   // Branch to either the extra iterations or the unrolled loop
00294   // We will fix up the true branch label when adding loop body copies
00295   BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR);
00296   assert(PreHeaderBR->isUnconditional() &&
00297          PreHeaderBR->getSuccessor(0) == PEnd &&
00298          "CFG edges in Preheader are not correct");
00299   PreHeaderBR->eraseFromParent();
00300 
00301   ValueToValueMapTy LVMap;
00302   Function *F = Header->getParent();
00303   // These variables are used to update the CFG links in each iteration
00304   BasicBlock *CompareBB = 0;
00305   BasicBlock *LastLoopBB = PH;
00306   // Get an ordered list of blocks in the loop to help with the ordering of the
00307   // cloned blocks in the prolog code
00308   LoopBlocksDFS LoopBlocks(L);
00309   LoopBlocks.perform(LI);
00310 
00311   //
00312   // For each extra loop iteration, create a copy of the loop's basic blocks
00313   // and generate a condition that branches to the copy depending on the
00314   // number of 'left over' iterations.
00315   //
00316   for (unsigned leftOverIters = Count-1; leftOverIters > 0; --leftOverIters) {
00317     std::vector<BasicBlock*> NewBlocks;
00318     ValueToValueMapTy VMap;
00319 
00320     // Clone all the basic blocks in the loop, but we don't clone the loop
00321     // This function adds the appropriate CFG connections.
00322     CloneLoopBlocks(L, (leftOverIters == Count-1), LastLoopBB, PEnd, NewBlocks,
00323                     LoopBlocks, VMap, LVMap, LI);
00324     LastLoopBB = cast<BasicBlock>(VMap[Latch]);
00325 
00326     // Insert the cloned blocks into function just before the original loop
00327     F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(),
00328                                   NewBlocks[0], F->end());
00329 
00330     // Generate the code for the comparison which determines if the loop
00331     // prolog code needs to be executed.
00332     if (leftOverIters == Count-1) {
00333       // There is no compare block for the fall-thru case when for the last
00334       // left over iteration
00335       CompareBB = NewBlocks[0];
00336     } else {
00337       // Create a new block for the comparison
00338       BasicBlock *NewBB = BasicBlock::Create(CompareBB->getContext(), "unr.cmp",
00339                                              F, CompareBB);
00340       if (Loop *ParentLoop = L->getParentLoop()) {
00341         // Add the new block to the parent loop, if needed
00342         ParentLoop->addBasicBlockToLoop(NewBB, LI->getBase());
00343       }
00344 
00345       // The comparison w/ the extra iteration value and branch
00346       Value *BranchVal = new ICmpInst(*NewBB, ICmpInst::ICMP_EQ, ModVal,
00347                                       ConstantInt::get(CountTy, leftOverIters),
00348                                       "un.tmp");
00349       // Branch to either the extra iterations or the unrolled loop
00350       BranchInst::Create(NewBlocks[0], CompareBB,
00351                          BranchVal, NewBB);
00352       CompareBB = NewBB;
00353       PH->getTerminator()->setSuccessor(0, NewBB);
00354       VMap[NewPH] = CompareBB;
00355     }
00356 
00357     // Rewrite the cloned instruction operands to use the values
00358     // created when the clone is created.
00359     for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
00360       for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00361              E = NewBlocks[i]->end(); I != E; ++I) {
00362         RemapInstruction(I, VMap,
00363                          RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
00364       }
00365     }
00366   }
00367 
00368   // Connect the prolog code to the original loop and update the
00369   // PHI functions.
00370   ConnectProlog(L, TripCount, Count, LastLoopBB, PEnd, PH, NewPH, LVMap,
00371                 LPM->getAsPass());
00372   NumRuntimeUnrolled++;
00373   return true;
00374 }