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 #include "llvm/Transforms/Utils/UnrollLoop.h"
00025 #include "llvm/ADT/Statistic.h"
00026 #include "llvm/Analysis/AliasAnalysis.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/IR/Dominators.h"
00033 #include "llvm/IR/Metadata.h"
00034 #include "llvm/Support/Debug.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Transforms/Scalar.h"
00037 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00038 #include "llvm/Transforms/Utils/Cloning.h"
00039 #include <algorithm>
00040 
00041 using namespace llvm;
00042 
00043 #define DEBUG_TYPE "loop-unroll"
00044 
00045 STATISTIC(NumRuntimeUnrolled,
00046           "Number of loops unrolled with run-time trip counts");
00047 
00048 /// Connect the unrolling prolog code to the original loop.
00049 /// The unrolling prolog code contains code to execute the
00050 /// 'extra' iterations if the run-time trip count modulo the
00051 /// unroll count is non-zero.
00052 ///
00053 /// This function performs the following:
00054 /// - Create PHI nodes at prolog end block to combine values
00055 ///   that exit the prolog code and jump around the prolog.
00056 /// - Add a PHI operand to a PHI node at the loop exit block
00057 ///   for values that exit the prolog and go around the loop.
00058 /// - Branch around the original loop if the trip count is less
00059 ///   than the unroll factor.
00060 ///
00061 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
00062                           BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
00063                           BasicBlock *OrigPH, BasicBlock *NewPH,
00064                           ValueToValueMapTy &VMap, AliasAnalysis *AA,
00065                           DominatorTree *DT, LoopInfo *LI, Pass *P) {
00066   BasicBlock *Latch = L->getLoopLatch();
00067   assert(Latch && "Loop must have a latch");
00068 
00069   // Create a PHI node for each outgoing value from the original loop
00070   // (which means it is an outgoing value from the prolog code too).
00071   // The new PHI node is inserted in the prolog end basic block.
00072   // The new PHI name is added as an operand of a PHI node in either
00073   // the loop header or the loop exit block.
00074   for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
00075        SBI != SBE; ++SBI) {
00076     for (BasicBlock::iterator BBI = (*SBI)->begin();
00077          PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
00078 
00079       // Add a new PHI node to the prolog end block and add the
00080       // appropriate incoming values.
00081       PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr",
00082                                        PrologEnd->getTerminator());
00083       // Adding a value to the new PHI node from the original loop preheader.
00084       // This is the value that skips all the prolog code.
00085       if (L->contains(PN)) {
00086         NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH);
00087       } else {
00088         NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH);
00089       }
00090 
00091       Value *V = PN->getIncomingValueForBlock(Latch);
00092       if (Instruction *I = dyn_cast<Instruction>(V)) {
00093         if (L->contains(I)) {
00094           V = VMap[I];
00095         }
00096       }
00097       // Adding a value to the new PHI node from the last prolog block
00098       // that was created.
00099       NewPN->addIncoming(V, LastPrologBB);
00100 
00101       // Update the existing PHI node operand with the value from the
00102       // new PHI node.  How this is done depends on if the existing
00103       // PHI node is in the original loop block, or the exit block.
00104       if (L->contains(PN)) {
00105         PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN);
00106       } else {
00107         PN->addIncoming(NewPN, PrologEnd);
00108       }
00109     }
00110   }
00111 
00112   // Create a branch around the orignal loop, which is taken if there are no
00113   // iterations remaining to be executed after running the prologue.
00114   Instruction *InsertPt = PrologEnd->getTerminator();
00115 
00116   assert(Count != 0 && "nonsensical Count!");
00117 
00118   // If BECount <u (Count - 1) then (BECount + 1) & (Count - 1) == (BECount + 1)
00119   // (since Count is a power of 2).  This means %xtraiter is (BECount + 1) and
00120   // and all of the iterations of this loop were executed by the prologue.  Note
00121   // that if BECount <u (Count - 1) then (BECount + 1) cannot unsigned-overflow.
00122   Instruction *BrLoopExit =
00123     new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, BECount,
00124                  ConstantInt::get(BECount->getType(), Count - 1));
00125   BasicBlock *Exit = L->getUniqueExitBlock();
00126   assert(Exit && "Loop must have a single exit block only");
00127   // Split the exit to maintain loop canonicalization guarantees
00128   SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
00129   SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", AA, DT, LI,
00130                          P->mustPreserveAnalysisID(LCSSAID));
00131   // Add the branch to the exit block (around the unrolled loop)
00132   BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt);
00133   InsertPt->eraseFromParent();
00134 }
00135 
00136 /// Create a clone of the blocks in a loop and connect them together.
00137 /// If UnrollProlog is true, loop structure will not be cloned, otherwise a new
00138 /// loop will be created including all cloned blocks, and the iterator of it
00139 /// switches to count NewIter down to 0.
00140 ///
00141 static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog,
00142                             BasicBlock *InsertTop, BasicBlock *InsertBot,
00143                             std::vector<BasicBlock *> &NewBlocks,
00144                             LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
00145                             LoopInfo *LI) {
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   Loop *NewLoop = 0;
00153   Loop *ParentLoop = L->getParentLoop();
00154   if (!UnrollProlog) {
00155     NewLoop = new Loop();
00156     if (ParentLoop)
00157       ParentLoop->addChildLoop(NewLoop);
00158     else
00159       LI->addTopLevelLoop(NewLoop);
00160   }
00161 
00162   // For each block in the original loop, create a new copy,
00163   // and update the value map with the newly created values.
00164   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
00165     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F);
00166     NewBlocks.push_back(NewBB);
00167 
00168     if (NewLoop)
00169       NewLoop->addBasicBlockToLoop(NewBB, *LI);
00170     else if (ParentLoop)
00171       ParentLoop->addBasicBlockToLoop(NewBB, *LI);
00172 
00173     VMap[*BB] = NewBB;
00174     if (Header == *BB) {
00175       // For the first block, add a CFG connection to this newly
00176       // created block.
00177       InsertTop->getTerminator()->setSuccessor(0, NewBB);
00178 
00179     }
00180     if (Latch == *BB) {
00181       // For the last block, if UnrollProlog is true, create a direct jump to
00182       // InsertBot. If not, create a loop back to cloned head.
00183       VMap.erase((*BB)->getTerminator());
00184       BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
00185       BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
00186       if (UnrollProlog) {
00187         LatchBR->eraseFromParent();
00188         BranchInst::Create(InsertBot, NewBB);
00189       } else {
00190         PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter",
00191                                           FirstLoopBB->getFirstNonPHI());
00192         IRBuilder<> Builder(LatchBR);
00193         Value *IdxSub =
00194             Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
00195                               NewIdx->getName() + ".sub");
00196         Value *IdxCmp =
00197             Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
00198         BranchInst::Create(FirstLoopBB, InsertBot, IdxCmp, NewBB);
00199         NewIdx->addIncoming(NewIter, InsertTop);
00200         NewIdx->addIncoming(IdxSub, NewBB);
00201         LatchBR->eraseFromParent();
00202       }
00203     }
00204   }
00205 
00206   // Change the incoming values to the ones defined in the preheader or
00207   // cloned loop.
00208   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00209     PHINode *NewPHI = cast<PHINode>(VMap[I]);
00210     if (UnrollProlog) {
00211       VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
00212       cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
00213     } else {
00214       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
00215       NewPHI->setIncomingBlock(idx, InsertTop);
00216       BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
00217       idx = NewPHI->getBasicBlockIndex(Latch);
00218       Value *InVal = NewPHI->getIncomingValue(idx);
00219       NewPHI->setIncomingBlock(idx, NewLatch);
00220       if (VMap[InVal])
00221         NewPHI->setIncomingValue(idx, VMap[InVal]);
00222     }
00223   }
00224   if (NewLoop) {
00225     // Add unroll disable metadata to disable future unrolling for this loop.
00226     SmallVector<Metadata *, 4> MDs;
00227     // Reserve first location for self reference to the LoopID metadata node.
00228     MDs.push_back(nullptr);
00229     MDNode *LoopID = NewLoop->getLoopID();
00230     if (LoopID) {
00231       // First remove any existing loop unrolling metadata.
00232       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
00233         bool IsUnrollMetadata = false;
00234         MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
00235         if (MD) {
00236           const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
00237           IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
00238         }
00239         if (!IsUnrollMetadata)
00240           MDs.push_back(LoopID->getOperand(i));
00241       }
00242     }
00243 
00244     LLVMContext &Context = NewLoop->getHeader()->getContext();
00245     SmallVector<Metadata *, 1> DisableOperands;
00246     DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
00247     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
00248     MDs.push_back(DisableNode);
00249 
00250     MDNode *NewLoopID = MDNode::get(Context, MDs);
00251     // Set operand 0 to refer to the loop id itself.
00252     NewLoopID->replaceOperandWith(0, NewLoopID);
00253     NewLoop->setLoopID(NewLoopID);
00254   }
00255 }
00256 
00257 /// Insert code in the prolog code when unrolling a loop with a
00258 /// run-time trip-count.
00259 ///
00260 /// This method assumes that the loop unroll factor is total number
00261 /// of loop bodes in the loop after unrolling. (Some folks refer
00262 /// to the unroll factor as the number of *extra* copies added).
00263 /// We assume also that the loop unroll factor is a power-of-two. So, after
00264 /// unrolling the loop, the number of loop bodies executed is 2,
00265 /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
00266 /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
00267 /// the switch instruction is generated.
00268 ///
00269 ///        extraiters = tripcount % loopfactor
00270 ///        if (extraiters == 0) jump Loop:
00271 ///        else jump Prol
00272 /// Prol:  LoopBody;
00273 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
00274 ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
00275 ///        if (tripcount < loopfactor) jump End
00276 /// Loop:
00277 /// ...
00278 /// End:
00279 ///
00280 bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI,
00281                                    LPPassManager *LPM) {
00282   // for now, only unroll loops that contain a single exit
00283   if (!L->getExitingBlock())
00284     return false;
00285 
00286   // Make sure the loop is in canonical form, and there is a single
00287   // exit block only.
00288   if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock())
00289     return false;
00290 
00291   // Use Scalar Evolution to compute the trip count.  This allows more
00292   // loops to be unrolled than relying on induction var simplification
00293   if (!LPM)
00294     return false;
00295   ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
00296   if (!SE)
00297     return false;
00298 
00299   // Only unroll loops with a computable trip count and the trip count needs
00300   // to be an int value (allowing a pointer type is a TODO item)
00301   const SCEV *BECountSC = SE->getBackedgeTakenCount(L);
00302   if (isa<SCEVCouldNotCompute>(BECountSC) ||
00303       !BECountSC->getType()->isIntegerTy())
00304     return false;
00305 
00306   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
00307 
00308   // Add 1 since the backedge count doesn't include the first loop iteration
00309   const SCEV *TripCountSC =
00310     SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
00311   if (isa<SCEVCouldNotCompute>(TripCountSC))
00312     return false;
00313 
00314   // We only handle cases when the unroll factor is a power of 2.
00315   // Count is the loop unroll factor, the number of extra copies added + 1.
00316   if (!isPowerOf2_32(Count))
00317     return false;
00318 
00319   // This constraint lets us deal with an overflowing trip count easily; see the
00320   // comment on ModVal below.  This check is equivalent to `Log2(Count) <
00321   // BEWidth`.
00322   if (static_cast<uint64_t>(Count) > (1ULL << BEWidth))
00323     return false;
00324 
00325   // If this loop is nested, then the loop unroller changes the code in
00326   // parent loop, so the Scalar Evolution pass needs to be run again
00327   if (Loop *ParentLoop = L->getParentLoop())
00328     SE->forgetLoop(ParentLoop);
00329 
00330   // Grab analyses that we preserve.
00331   auto *DTWP = LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00332   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
00333 
00334   BasicBlock *PH = L->getLoopPreheader();
00335   BasicBlock *Header = L->getHeader();
00336   BasicBlock *Latch = L->getLoopLatch();
00337   // It helps to splits the original preheader twice, one for the end of the
00338   // prolog code and one for a new loop preheader
00339   BasicBlock *PEnd = SplitEdge(PH, Header, DT, LI);
00340   BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), DT, LI);
00341   BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
00342 
00343   // Compute the number of extra iterations required, which is:
00344   //  extra iterations = run-time trip count % (loop unroll factor + 1)
00345   SCEVExpander Expander(*SE, "loop-unroll");
00346   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
00347                                             PreHeaderBR);
00348   Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
00349                                           PreHeaderBR);
00350 
00351   IRBuilder<> B(PreHeaderBR);
00352   Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
00353 
00354   // If ModVal is zero, we know that either
00355   //  1. there are no iteration to be run in the prologue loop
00356   // OR
00357   //  2. the addition computing TripCount overflowed
00358   //
00359   // If (2) is true, we know that TripCount really is (1 << BEWidth) and so the
00360   // number of iterations that remain to be run in the original loop is a
00361   // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
00362   // explicitly check this above).
00363 
00364   Value *BranchVal = B.CreateIsNotNull(ModVal, "lcmp.mod");
00365 
00366   // Branch to either the extra iterations or the cloned/unrolled loop
00367   // We will fix up the true branch label when adding loop body copies
00368   BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR);
00369   assert(PreHeaderBR->isUnconditional() &&
00370          PreHeaderBR->getSuccessor(0) == PEnd &&
00371          "CFG edges in Preheader are not correct");
00372   PreHeaderBR->eraseFromParent();
00373   Function *F = Header->getParent();
00374   // Get an ordered list of blocks in the loop to help with the ordering of the
00375   // cloned blocks in the prolog code
00376   LoopBlocksDFS LoopBlocks(L);
00377   LoopBlocks.perform(LI);
00378 
00379   //
00380   // For each extra loop iteration, create a copy of the loop's basic blocks
00381   // and generate a condition that branches to the copy depending on the
00382   // number of 'left over' iterations.
00383   //
00384   std::vector<BasicBlock *> NewBlocks;
00385   ValueToValueMapTy VMap;
00386 
00387   bool UnrollPrologue = Count == 2;
00388 
00389   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
00390   // the loop, otherwise we create a cloned loop to execute the extra
00391   // iterations. This function adds the appropriate CFG connections.
00392   CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks,
00393                   VMap, LI);
00394 
00395   // Insert the cloned blocks into function just before the original loop
00396   F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
00397                                 F->end());
00398 
00399   // Rewrite the cloned instruction operands to use the values
00400   // created when the clone is created.
00401   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
00402     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00403                               E = NewBlocks[i]->end();
00404          I != E; ++I) {
00405       RemapInstruction(I, VMap,
00406                        RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
00407     }
00408   }
00409 
00410   // Connect the prolog code to the original loop and update the
00411   // PHI functions.
00412   BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]);
00413   ConnectProlog(L, BECount, Count, LastLoopBB, PEnd, PH, NewPH, VMap,
00414                 /*AliasAnalysis*/ nullptr, DT, LI, LPM->getAsPass());
00415   NumRuntimeUnrolled++;
00416   return true;
00417 }