LoopUnrollRuntime.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements some loop unrolling utilities for loops with run-time
  11. // trip counts. See LoopUnroll.cpp for unrolling loops with compile-time
  12. // trip counts.
  13. //
  14. // The functions in this file are used to generate extra code when the
  15. // run-time trip count modulo the unroll factor is not 0. When this is the
  16. // case, we need to generate code to execute these 'left over' iterations.
  17. //
  18. // The current strategy generates an if-then-else sequence prior to the
  19. // unrolled loop to execute the 'left over' iterations. Other strategies
  20. // include generate a loop before or after the unrolled loop.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/Transforms/Utils/UnrollLoop.h"
  24. #include "llvm/ADT/Statistic.h"
  25. #include "llvm/Analysis/LoopIterator.h"
  26. #include "llvm/Analysis/LoopPass.h"
  27. #include "llvm/Analysis/ScalarEvolution.h"
  28. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/Metadata.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  34. #include "llvm/Transforms/Utils/Cloning.h"
  35. #include <algorithm>
  36. using namespace llvm;
  37. #define DEBUG_TYPE "loop-unroll"
  38. STATISTIC(NumRuntimeUnrolled,
  39. "Number of loops unrolled with run-time trip counts");
  40. /// Connect the unrolling prolog code to the original loop.
  41. /// The unrolling prolog code contains code to execute the
  42. /// 'extra' iterations if the run-time trip count modulo the
  43. /// unroll count is non-zero.
  44. ///
  45. /// This function performs the following:
  46. /// - Create PHI nodes at prolog end block to combine values
  47. /// that exit the prolog code and jump around the prolog.
  48. /// - Add a PHI operand to a PHI node at the loop exit block
  49. /// for values that exit the prolog and go around the loop.
  50. /// - Branch around the original loop if the trip count is less
  51. /// than the unroll factor.
  52. ///
  53. static void ConnectProlog(Loop *L, Value *TripCount, unsigned Count,
  54. BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
  55. BasicBlock *OrigPH, BasicBlock *NewPH,
  56. ValueToValueMapTy &VMap, Pass *P) {
  57. BasicBlock *Latch = L->getLoopLatch();
  58. assert(Latch && "Loop must have a latch");
  59. // Create a PHI node for each outgoing value from the original loop
  60. // (which means it is an outgoing value from the prolog code too).
  61. // The new PHI node is inserted in the prolog end basic block.
  62. // The new PHI name is added as an operand of a PHI node in either
  63. // the loop header or the loop exit block.
  64. for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
  65. SBI != SBE; ++SBI) {
  66. for (BasicBlock::iterator BBI = (*SBI)->begin();
  67. PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
  68. // Add a new PHI node to the prolog end block and add the
  69. // appropriate incoming values.
  70. PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr",
  71. PrologEnd->getTerminator());
  72. // Adding a value to the new PHI node from the original loop preheader.
  73. // This is the value that skips all the prolog code.
  74. if (L->contains(PN)) {
  75. NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH);
  76. } else {
  77. NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH);
  78. }
  79. Value *V = PN->getIncomingValueForBlock(Latch);
  80. if (Instruction *I = dyn_cast<Instruction>(V)) {
  81. if (L->contains(I)) {
  82. V = VMap[I];
  83. }
  84. }
  85. // Adding a value to the new PHI node from the last prolog block
  86. // that was created.
  87. NewPN->addIncoming(V, LastPrologBB);
  88. // Update the existing PHI node operand with the value from the
  89. // new PHI node. How this is done depends on if the existing
  90. // PHI node is in the original loop block, or the exit block.
  91. if (L->contains(PN)) {
  92. PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN);
  93. } else {
  94. PN->addIncoming(NewPN, PrologEnd);
  95. }
  96. }
  97. }
  98. // Create a branch around the orignal loop, which is taken if the
  99. // trip count is less than the unroll factor.
  100. Instruction *InsertPt = PrologEnd->getTerminator();
  101. Instruction *BrLoopExit =
  102. new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, TripCount,
  103. ConstantInt::get(TripCount->getType(), Count));
  104. BasicBlock *Exit = L->getUniqueExitBlock();
  105. assert(Exit && "Loop must have a single exit block only");
  106. // Split the exit to maintain loop canonicalization guarantees
  107. SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
  108. if (!Exit->isLandingPad()) {
  109. SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", P);
  110. } else {
  111. SmallVector<BasicBlock*, 2> NewBBs;
  112. SplitLandingPadPredecessors(Exit, Preds, ".unr1-lcssa", ".unr2-lcssa",
  113. P, NewBBs);
  114. }
  115. // Add the branch to the exit block (around the unrolled loop)
  116. BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt);
  117. InsertPt->eraseFromParent();
  118. }
  119. /// Create a clone of the blocks in a loop and connect them together.
  120. /// If UnrollProlog is true, loop structure will not be cloned, otherwise a new
  121. /// loop will be created including all cloned blocks, and the iterator of it
  122. /// switches to count NewIter down to 0.
  123. ///
  124. static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog,
  125. BasicBlock *InsertTop, BasicBlock *InsertBot,
  126. std::vector<BasicBlock *> &NewBlocks,
  127. LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
  128. LoopInfo *LI) {
  129. BasicBlock *Preheader = L->getLoopPreheader();
  130. BasicBlock *Header = L->getHeader();
  131. BasicBlock *Latch = L->getLoopLatch();
  132. Function *F = Header->getParent();
  133. LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
  134. LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
  135. Loop *NewLoop = 0;
  136. Loop *ParentLoop = L->getParentLoop();
  137. if (!UnrollProlog) {
  138. NewLoop = new Loop();
  139. if (ParentLoop)
  140. ParentLoop->addChildLoop(NewLoop);
  141. else
  142. LI->addTopLevelLoop(NewLoop);
  143. }
  144. // For each block in the original loop, create a new copy,
  145. // and update the value map with the newly created values.
  146. for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
  147. BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F);
  148. NewBlocks.push_back(NewBB);
  149. if (NewLoop)
  150. NewLoop->addBasicBlockToLoop(NewBB, LI->getBase());
  151. else if (ParentLoop)
  152. ParentLoop->addBasicBlockToLoop(NewBB, LI->getBase());
  153. VMap[*BB] = NewBB;
  154. if (Header == *BB) {
  155. // For the first block, add a CFG connection to this newly
  156. // created block.
  157. InsertTop->getTerminator()->setSuccessor(0, NewBB);
  158. }
  159. if (Latch == *BB) {
  160. // For the last block, if UnrollProlog is true, create a direct jump to
  161. // InsertBot. If not, create a loop back to cloned head.
  162. VMap.erase((*BB)->getTerminator());
  163. BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
  164. BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
  165. if (UnrollProlog) {
  166. LatchBR->eraseFromParent();
  167. BranchInst::Create(InsertBot, NewBB);
  168. } else {
  169. PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter",
  170. FirstLoopBB->getFirstNonPHI());
  171. IRBuilder<> Builder(LatchBR);
  172. Value *IdxSub =
  173. Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
  174. NewIdx->getName() + ".sub");
  175. Value *IdxCmp =
  176. Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
  177. BranchInst::Create(FirstLoopBB, InsertBot, IdxCmp, NewBB);
  178. NewIdx->addIncoming(NewIter, InsertTop);
  179. NewIdx->addIncoming(IdxSub, NewBB);
  180. LatchBR->eraseFromParent();
  181. }
  182. }
  183. }
  184. // Change the incoming values to the ones defined in the preheader or
  185. // cloned loop.
  186. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  187. PHINode *NewPHI = cast<PHINode>(VMap[I]);
  188. if (UnrollProlog) {
  189. VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
  190. cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
  191. } else {
  192. unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
  193. NewPHI->setIncomingBlock(idx, InsertTop);
  194. BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
  195. idx = NewPHI->getBasicBlockIndex(Latch);
  196. Value *InVal = NewPHI->getIncomingValue(idx);
  197. NewPHI->setIncomingBlock(idx, NewLatch);
  198. if (VMap[InVal])
  199. NewPHI->setIncomingValue(idx, VMap[InVal]);
  200. }
  201. }
  202. if (NewLoop) {
  203. // Add unroll disable metadata to disable future unrolling for this loop.
  204. SmallVector<Metadata *, 4> MDs;
  205. // Reserve first location for self reference to the LoopID metadata node.
  206. MDs.push_back(nullptr);
  207. MDNode *LoopID = NewLoop->getLoopID();
  208. if (LoopID) {
  209. // First remove any existing loop unrolling metadata.
  210. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  211. bool IsUnrollMetadata = false;
  212. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  213. if (MD) {
  214. const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  215. IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
  216. }
  217. if (!IsUnrollMetadata)
  218. MDs.push_back(LoopID->getOperand(i));
  219. }
  220. }
  221. LLVMContext &Context = NewLoop->getHeader()->getContext();
  222. SmallVector<Metadata *, 1> DisableOperands;
  223. DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
  224. MDNode *DisableNode = MDNode::get(Context, DisableOperands);
  225. MDs.push_back(DisableNode);
  226. MDNode *NewLoopID = MDNode::get(Context, MDs);
  227. // Set operand 0 to refer to the loop id itself.
  228. NewLoopID->replaceOperandWith(0, NewLoopID);
  229. NewLoop->setLoopID(NewLoopID);
  230. }
  231. }
  232. /// Insert code in the prolog code when unrolling a loop with a
  233. /// run-time trip-count.
  234. ///
  235. /// This method assumes that the loop unroll factor is total number
  236. /// of loop bodes in the loop after unrolling. (Some folks refer
  237. /// to the unroll factor as the number of *extra* copies added).
  238. /// We assume also that the loop unroll factor is a power-of-two. So, after
  239. /// unrolling the loop, the number of loop bodies executed is 2,
  240. /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
  241. /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
  242. /// the switch instruction is generated.
  243. ///
  244. /// extraiters = tripcount % loopfactor
  245. /// if (extraiters == 0) jump Loop:
  246. /// else jump Prol
  247. /// Prol: LoopBody;
  248. /// extraiters -= 1 // Omitted if unroll factor is 2.
  249. /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
  250. /// if (tripcount < loopfactor) jump End
  251. /// Loop:
  252. /// ...
  253. /// End:
  254. ///
  255. bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI,
  256. LPPassManager *LPM) {
  257. // for now, only unroll loops that contain a single exit
  258. if (!L->getExitingBlock())
  259. return false;
  260. // Make sure the loop is in canonical form, and there is a single
  261. // exit block only.
  262. if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock())
  263. return false;
  264. // Use Scalar Evolution to compute the trip count. This allows more
  265. // loops to be unrolled than relying on induction var simplification
  266. if (!LPM)
  267. return false;
  268. ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
  269. if (!SE)
  270. return false;
  271. // Only unroll loops with a computable trip count and the trip count needs
  272. // to be an int value (allowing a pointer type is a TODO item)
  273. const SCEV *BECount = SE->getBackedgeTakenCount(L);
  274. if (isa<SCEVCouldNotCompute>(BECount) || !BECount->getType()->isIntegerTy())
  275. return false;
  276. // If BECount is INT_MAX, we can't compute trip-count without overflow.
  277. if (BECount->isAllOnesValue())
  278. return false;
  279. // Add 1 since the backedge count doesn't include the first loop iteration
  280. const SCEV *TripCountSC =
  281. SE->getAddExpr(BECount, SE->getConstant(BECount->getType(), 1));
  282. if (isa<SCEVCouldNotCompute>(TripCountSC))
  283. return false;
  284. // We only handle cases when the unroll factor is a power of 2.
  285. // Count is the loop unroll factor, the number of extra copies added + 1.
  286. if ((Count & (Count-1)) != 0)
  287. return false;
  288. // If this loop is nested, then the loop unroller changes the code in
  289. // parent loop, so the Scalar Evolution pass needs to be run again
  290. if (Loop *ParentLoop = L->getParentLoop())
  291. SE->forgetLoop(ParentLoop);
  292. BasicBlock *PH = L->getLoopPreheader();
  293. BasicBlock *Header = L->getHeader();
  294. BasicBlock *Latch = L->getLoopLatch();
  295. // It helps to splits the original preheader twice, one for the end of the
  296. // prolog code and one for a new loop preheader
  297. BasicBlock *PEnd = SplitEdge(PH, Header, LPM->getAsPass());
  298. BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), LPM->getAsPass());
  299. BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
  300. // Compute the number of extra iterations required, which is:
  301. // extra iterations = run-time trip count % (loop unroll factor + 1)
  302. SCEVExpander Expander(*SE, "loop-unroll");
  303. Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
  304. PreHeaderBR);
  305. IRBuilder<> B(PreHeaderBR);
  306. Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
  307. // Check if for no extra iterations, then jump to cloned/unrolled loop.
  308. // We have to check that the trip count computation didn't overflow when
  309. // adding one to the backedge taken count.
  310. Value *LCmp = B.CreateIsNotNull(ModVal, "lcmp.mod");
  311. Value *OverflowCheck = B.CreateIsNull(TripCount, "lcmp.overflow");
  312. Value *BranchVal = B.CreateOr(OverflowCheck, LCmp, "lcmp.or");
  313. // Branch to either the extra iterations or the cloned/unrolled loop
  314. // We will fix up the true branch label when adding loop body copies
  315. BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR);
  316. assert(PreHeaderBR->isUnconditional() &&
  317. PreHeaderBR->getSuccessor(0) == PEnd &&
  318. "CFG edges in Preheader are not correct");
  319. PreHeaderBR->eraseFromParent();
  320. Function *F = Header->getParent();
  321. // Get an ordered list of blocks in the loop to help with the ordering of the
  322. // cloned blocks in the prolog code
  323. LoopBlocksDFS LoopBlocks(L);
  324. LoopBlocks.perform(LI);
  325. //
  326. // For each extra loop iteration, create a copy of the loop's basic blocks
  327. // and generate a condition that branches to the copy depending on the
  328. // number of 'left over' iterations.
  329. //
  330. std::vector<BasicBlock *> NewBlocks;
  331. ValueToValueMapTy VMap;
  332. // If unroll count is 2 and we can't overflow in tripcount computation (which
  333. // is BECount + 1), then we don't need a loop for prologue, and we can unroll
  334. // it. We can be sure that we don't overflow only if tripcount is a constant.
  335. bool UnrollPrologue = (Count == 2 && isa<ConstantInt>(TripCount));
  336. // Clone all the basic blocks in the loop. If Count is 2, we don't clone
  337. // the loop, otherwise we create a cloned loop to execute the extra
  338. // iterations. This function adds the appropriate CFG connections.
  339. CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks,
  340. VMap, LI);
  341. // Insert the cloned blocks into function just before the original loop
  342. F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
  343. F->end());
  344. // Rewrite the cloned instruction operands to use the values
  345. // created when the clone is created.
  346. for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
  347. for (BasicBlock::iterator I = NewBlocks[i]->begin(),
  348. E = NewBlocks[i]->end();
  349. I != E; ++I) {
  350. RemapInstruction(I, VMap,
  351. RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  352. }
  353. }
  354. // Connect the prolog code to the original loop and update the
  355. // PHI functions.
  356. BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]);
  357. ConnectProlog(L, TripCount, Count, LastLoopBB, PEnd, PH, NewPH, VMap,
  358. LPM->getAsPass());
  359. NumRuntimeUnrolled++;
  360. return true;
  361. }