LoopUnrollRuntime.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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 before or after the
  20. // unrolled loop.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/Statistic.h"
  25. #include "llvm/Analysis/AliasAnalysis.h"
  26. #include "llvm/Analysis/LoopIterator.h"
  27. #include "llvm/Analysis/ScalarEvolution.h"
  28. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/Dominators.h"
  31. #include "llvm/IR/Metadata.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Transforms/Utils.h"
  36. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  37. #include "llvm/Transforms/Utils/Cloning.h"
  38. #include "llvm/Transforms/Utils/LoopUtils.h"
  39. #include "llvm/Transforms/Utils/UnrollLoop.h"
  40. #include <algorithm>
  41. using namespace llvm;
  42. #define DEBUG_TYPE "loop-unroll"
  43. STATISTIC(NumRuntimeUnrolled,
  44. "Number of loops unrolled with run-time trip counts");
  45. static cl::opt<bool> UnrollRuntimeMultiExit(
  46. "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
  47. cl::desc("Allow runtime unrolling for loops with multiple exits, when "
  48. "epilog is generated"));
  49. /// Connect the unrolling prolog code to the original loop.
  50. /// The unrolling prolog code contains code to execute the
  51. /// 'extra' iterations if the run-time trip count modulo the
  52. /// unroll count is non-zero.
  53. ///
  54. /// This function performs the following:
  55. /// - Create PHI nodes at prolog end block to combine values
  56. /// that exit the prolog code and jump around the prolog.
  57. /// - Add a PHI operand to a PHI node at the loop exit block
  58. /// for values that exit the prolog and go around the loop.
  59. /// - Branch around the original loop if the trip count is less
  60. /// than the unroll factor.
  61. ///
  62. static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
  63. BasicBlock *PrologExit,
  64. BasicBlock *OriginalLoopLatchExit,
  65. BasicBlock *PreHeader, BasicBlock *NewPreHeader,
  66. ValueToValueMapTy &VMap, DominatorTree *DT,
  67. LoopInfo *LI, bool PreserveLCSSA) {
  68. BasicBlock *Latch = L->getLoopLatch();
  69. assert(Latch && "Loop must have a latch");
  70. BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
  71. // Create a PHI node for each outgoing value from the original loop
  72. // (which means it is an outgoing value from the prolog code too).
  73. // The new PHI node is inserted in the prolog end basic block.
  74. // The new PHI node value is added as an operand of a PHI node in either
  75. // the loop header or the loop exit block.
  76. for (BasicBlock *Succ : successors(Latch)) {
  77. for (PHINode &PN : Succ->phis()) {
  78. // Add a new PHI node to the prolog end block and add the
  79. // appropriate incoming values.
  80. PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
  81. PrologExit->getFirstNonPHI());
  82. // Adding a value to the new PHI node from the original loop preheader.
  83. // This is the value that skips all the prolog code.
  84. if (L->contains(&PN)) {
  85. NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
  86. PreHeader);
  87. } else {
  88. NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader);
  89. }
  90. Value *V = PN.getIncomingValueForBlock(Latch);
  91. if (Instruction *I = dyn_cast<Instruction>(V)) {
  92. if (L->contains(I)) {
  93. V = VMap.lookup(I);
  94. }
  95. }
  96. // Adding a value to the new PHI node from the last prolog block
  97. // that was created.
  98. NewPN->addIncoming(V, PrologLatch);
  99. // Update the existing PHI node operand with the value from the
  100. // new PHI node. How this is done depends on if the existing
  101. // PHI node is in the original loop block, or the exit block.
  102. if (L->contains(&PN)) {
  103. PN.setIncomingValue(PN.getBasicBlockIndex(NewPreHeader), NewPN);
  104. } else {
  105. PN.addIncoming(NewPN, PrologExit);
  106. }
  107. }
  108. }
  109. // Make sure that created prolog loop is in simplified form
  110. SmallVector<BasicBlock *, 4> PrologExitPreds;
  111. Loop *PrologLoop = LI->getLoopFor(PrologLatch);
  112. if (PrologLoop) {
  113. for (BasicBlock *PredBB : predecessors(PrologExit))
  114. if (PrologLoop->contains(PredBB))
  115. PrologExitPreds.push_back(PredBB);
  116. SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
  117. nullptr, PreserveLCSSA);
  118. }
  119. // Create a branch around the original loop, which is taken if there are no
  120. // iterations remaining to be executed after running the prologue.
  121. Instruction *InsertPt = PrologExit->getTerminator();
  122. IRBuilder<> B(InsertPt);
  123. assert(Count != 0 && "nonsensical Count!");
  124. // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
  125. // This means %xtraiter is (BECount + 1) and all of the iterations of this
  126. // loop were executed by the prologue. Note that if BECount <u (Count - 1)
  127. // then (BECount + 1) cannot unsigned-overflow.
  128. Value *BrLoopExit =
  129. B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
  130. // Split the exit to maintain loop canonicalization guarantees
  131. SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
  132. SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
  133. nullptr, PreserveLCSSA);
  134. // Add the branch to the exit block (around the unrolled loop)
  135. B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
  136. InsertPt->eraseFromParent();
  137. if (DT)
  138. DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit);
  139. }
  140. /// Connect the unrolling epilog code to the original loop.
  141. /// The unrolling epilog code contains code to execute the
  142. /// 'extra' iterations if the run-time trip count modulo the
  143. /// unroll count is non-zero.
  144. ///
  145. /// This function performs the following:
  146. /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
  147. /// - Create PHI nodes at the unrolling loop exit to combine
  148. /// values that exit the unrolling loop code and jump around it.
  149. /// - Update PHI operands in the epilog loop by the new PHI nodes
  150. /// - Branch around the epilog loop if extra iters (ModVal) is zero.
  151. ///
  152. static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
  153. BasicBlock *Exit, BasicBlock *PreHeader,
  154. BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
  155. ValueToValueMapTy &VMap, DominatorTree *DT,
  156. LoopInfo *LI, bool PreserveLCSSA) {
  157. BasicBlock *Latch = L->getLoopLatch();
  158. assert(Latch && "Loop must have a latch");
  159. BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
  160. // Loop structure should be the following:
  161. //
  162. // PreHeader
  163. // NewPreHeader
  164. // Header
  165. // ...
  166. // Latch
  167. // NewExit (PN)
  168. // EpilogPreHeader
  169. // EpilogHeader
  170. // ...
  171. // EpilogLatch
  172. // Exit (EpilogPN)
  173. // Update PHI nodes at NewExit and Exit.
  174. for (PHINode &PN : NewExit->phis()) {
  175. // PN should be used in another PHI located in Exit block as
  176. // Exit was split by SplitBlockPredecessors into Exit and NewExit
  177. // Basicaly it should look like:
  178. // NewExit:
  179. // PN = PHI [I, Latch]
  180. // ...
  181. // Exit:
  182. // EpilogPN = PHI [PN, EpilogPreHeader]
  183. //
  184. // There is EpilogPreHeader incoming block instead of NewExit as
  185. // NewExit was spilt 1 more time to get EpilogPreHeader.
  186. assert(PN.hasOneUse() && "The phi should have 1 use");
  187. PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
  188. assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
  189. // Add incoming PreHeader from branch around the Loop
  190. PN.addIncoming(UndefValue::get(PN.getType()), PreHeader);
  191. Value *V = PN.getIncomingValueForBlock(Latch);
  192. Instruction *I = dyn_cast<Instruction>(V);
  193. if (I && L->contains(I))
  194. // If value comes from an instruction in the loop add VMap value.
  195. V = VMap.lookup(I);
  196. // For the instruction out of the loop, constant or undefined value
  197. // insert value itself.
  198. EpilogPN->addIncoming(V, EpilogLatch);
  199. assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
  200. "EpilogPN should have EpilogPreHeader incoming block");
  201. // Change EpilogPreHeader incoming block to NewExit.
  202. EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
  203. NewExit);
  204. // Now PHIs should look like:
  205. // NewExit:
  206. // PN = PHI [I, Latch], [undef, PreHeader]
  207. // ...
  208. // Exit:
  209. // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
  210. }
  211. // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
  212. // Update corresponding PHI nodes in epilog loop.
  213. for (BasicBlock *Succ : successors(Latch)) {
  214. // Skip this as we already updated phis in exit blocks.
  215. if (!L->contains(Succ))
  216. continue;
  217. for (PHINode &PN : Succ->phis()) {
  218. // Add new PHI nodes to the loop exit block and update epilog
  219. // PHIs with the new PHI values.
  220. PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
  221. NewExit->getFirstNonPHI());
  222. // Adding a value to the new PHI node from the unrolling loop preheader.
  223. NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
  224. // Adding a value to the new PHI node from the unrolling loop latch.
  225. NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
  226. // Update the existing PHI node operand with the value from the new PHI
  227. // node. Corresponding instruction in epilog loop should be PHI.
  228. PHINode *VPN = cast<PHINode>(VMap[&PN]);
  229. VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN);
  230. }
  231. }
  232. Instruction *InsertPt = NewExit->getTerminator();
  233. IRBuilder<> B(InsertPt);
  234. Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
  235. assert(Exit && "Loop must have a single exit block only");
  236. // Split the epilogue exit to maintain loop canonicalization guarantees
  237. SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
  238. SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
  239. PreserveLCSSA);
  240. // Add the branch to the exit block (around the unrolling loop)
  241. B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
  242. InsertPt->eraseFromParent();
  243. if (DT)
  244. DT->changeImmediateDominator(Exit, NewExit);
  245. // Split the main loop exit to maintain canonicalization guarantees.
  246. SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
  247. SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr,
  248. PreserveLCSSA);
  249. }
  250. /// Create a clone of the blocks in a loop and connect them together.
  251. /// If CreateRemainderLoop is false, loop structure will not be cloned,
  252. /// otherwise a new loop will be created including all cloned blocks, and the
  253. /// iterator of it switches to count NewIter down to 0.
  254. /// The cloned blocks should be inserted between InsertTop and InsertBot.
  255. /// If loop structure is cloned InsertTop should be new preheader, InsertBot
  256. /// new loop exit.
  257. /// Return the new cloned loop that is created when CreateRemainderLoop is true.
  258. static Loop *
  259. CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
  260. const bool UseEpilogRemainder, const bool UnrollRemainder,
  261. BasicBlock *InsertTop,
  262. BasicBlock *InsertBot, BasicBlock *Preheader,
  263. std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
  264. ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
  265. StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
  266. BasicBlock *Header = L->getHeader();
  267. BasicBlock *Latch = L->getLoopLatch();
  268. Function *F = Header->getParent();
  269. LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
  270. LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
  271. Loop *ParentLoop = L->getParentLoop();
  272. NewLoopsMap NewLoops;
  273. NewLoops[ParentLoop] = ParentLoop;
  274. if (!CreateRemainderLoop)
  275. NewLoops[L] = ParentLoop;
  276. // For each block in the original loop, create a new copy,
  277. // and update the value map with the newly created values.
  278. for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
  279. BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
  280. NewBlocks.push_back(NewBB);
  281. // If we're unrolling the outermost loop, there's no remainder loop,
  282. // and this block isn't in a nested loop, then the new block is not
  283. // in any loop. Otherwise, add it to loopinfo.
  284. if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
  285. addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
  286. VMap[*BB] = NewBB;
  287. if (Header == *BB) {
  288. // For the first block, add a CFG connection to this newly
  289. // created block.
  290. InsertTop->getTerminator()->setSuccessor(0, NewBB);
  291. }
  292. if (DT) {
  293. if (Header == *BB) {
  294. // The header is dominated by the preheader.
  295. DT->addNewBlock(NewBB, InsertTop);
  296. } else {
  297. // Copy information from original loop to unrolled loop.
  298. BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
  299. DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
  300. }
  301. }
  302. if (Latch == *BB) {
  303. // For the last block, if CreateRemainderLoop is false, create a direct
  304. // jump to InsertBot. If not, create a loop back to cloned head.
  305. VMap.erase((*BB)->getTerminator());
  306. BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
  307. BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
  308. IRBuilder<> Builder(LatchBR);
  309. if (!CreateRemainderLoop) {
  310. Builder.CreateBr(InsertBot);
  311. } else {
  312. PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
  313. suffix + ".iter",
  314. FirstLoopBB->getFirstNonPHI());
  315. Value *IdxSub =
  316. Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
  317. NewIdx->getName() + ".sub");
  318. Value *IdxCmp =
  319. Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
  320. Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
  321. NewIdx->addIncoming(NewIter, InsertTop);
  322. NewIdx->addIncoming(IdxSub, NewBB);
  323. }
  324. LatchBR->eraseFromParent();
  325. }
  326. }
  327. // Change the incoming values to the ones defined in the preheader or
  328. // cloned loop.
  329. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  330. PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
  331. if (!CreateRemainderLoop) {
  332. if (UseEpilogRemainder) {
  333. unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
  334. NewPHI->setIncomingBlock(idx, InsertTop);
  335. NewPHI->removeIncomingValue(Latch, false);
  336. } else {
  337. VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
  338. cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
  339. }
  340. } else {
  341. unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
  342. NewPHI->setIncomingBlock(idx, InsertTop);
  343. BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
  344. idx = NewPHI->getBasicBlockIndex(Latch);
  345. Value *InVal = NewPHI->getIncomingValue(idx);
  346. NewPHI->setIncomingBlock(idx, NewLatch);
  347. if (Value *V = VMap.lookup(InVal))
  348. NewPHI->setIncomingValue(idx, V);
  349. }
  350. }
  351. if (CreateRemainderLoop) {
  352. Loop *NewLoop = NewLoops[L];
  353. MDNode *LoopID = NewLoop->getLoopID();
  354. assert(NewLoop && "L should have been cloned");
  355. // Only add loop metadata if the loop is not going to be completely
  356. // unrolled.
  357. if (UnrollRemainder)
  358. return NewLoop;
  359. Optional<MDNode *> NewLoopID = makeFollowupLoopID(
  360. LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
  361. if (NewLoopID.hasValue()) {
  362. NewLoop->setLoopID(NewLoopID.getValue());
  363. // Do not setLoopAlreadyUnrolled if loop attributes have been defined
  364. // explicitly.
  365. return NewLoop;
  366. }
  367. // Add unroll disable metadata to disable future unrolling for this loop.
  368. NewLoop->setLoopAlreadyUnrolled();
  369. return NewLoop;
  370. }
  371. else
  372. return nullptr;
  373. }
  374. /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
  375. /// is populated with all the loop exit blocks other than the LatchExit block.
  376. static bool
  377. canSafelyUnrollMultiExitLoop(Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits,
  378. BasicBlock *LatchExit, bool PreserveLCSSA,
  379. bool UseEpilogRemainder) {
  380. // We currently have some correctness constrains in unrolling a multi-exit
  381. // loop. Check for these below.
  382. // We rely on LCSSA form being preserved when the exit blocks are transformed.
  383. if (!PreserveLCSSA)
  384. return false;
  385. SmallVector<BasicBlock *, 4> Exits;
  386. L->getUniqueExitBlocks(Exits);
  387. for (auto *BB : Exits)
  388. if (BB != LatchExit)
  389. OtherExits.push_back(BB);
  390. // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
  391. // UnrollRuntimeMultiExit is true. This will need updating the logic in
  392. // connectEpilog/connectProlog.
  393. if (!LatchExit->getSinglePredecessor()) {
  394. LLVM_DEBUG(
  395. dbgs() << "Bailout for multi-exit handling when latch exit has >1 "
  396. "predecessor.\n");
  397. return false;
  398. }
  399. // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
  400. // and L is an inner loop. This is because in presence of multiple exits, the
  401. // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
  402. // outer loop. This is automatically handled in the prolog case, so we do not
  403. // have that bug in prolog generation.
  404. if (UseEpilogRemainder && L->getParentLoop())
  405. return false;
  406. // All constraints have been satisfied.
  407. return true;
  408. }
  409. /// Returns true if we can profitably unroll the multi-exit loop L. Currently,
  410. /// we return true only if UnrollRuntimeMultiExit is set to true.
  411. static bool canProfitablyUnrollMultiExitLoop(
  412. Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
  413. bool PreserveLCSSA, bool UseEpilogRemainder) {
  414. #if !defined(NDEBUG)
  415. SmallVector<BasicBlock *, 8> OtherExitsDummyCheck;
  416. assert(canSafelyUnrollMultiExitLoop(L, OtherExitsDummyCheck, LatchExit,
  417. PreserveLCSSA, UseEpilogRemainder) &&
  418. "Should be safe to unroll before checking profitability!");
  419. #endif
  420. // Priority goes to UnrollRuntimeMultiExit if it's supplied.
  421. if (UnrollRuntimeMultiExit.getNumOccurrences())
  422. return UnrollRuntimeMultiExit;
  423. // The main pain point with multi-exit loop unrolling is that once unrolled,
  424. // we will not be able to merge all blocks into a straight line code.
  425. // There are branches within the unrolled loop that go to the OtherExits.
  426. // The second point is the increase in code size, but this is true
  427. // irrespective of multiple exits.
  428. // Note: Both the heuristics below are coarse grained. We are essentially
  429. // enabling unrolling of loops that have a single side exit other than the
  430. // normal LatchExit (i.e. exiting into a deoptimize block).
  431. // The heuristics considered are:
  432. // 1. low number of branches in the unrolled version.
  433. // 2. high predictability of these extra branches.
  434. // We avoid unrolling loops that have more than two exiting blocks. This
  435. // limits the total number of branches in the unrolled loop to be atmost
  436. // the unroll factor (since one of the exiting blocks is the latch block).
  437. SmallVector<BasicBlock*, 4> ExitingBlocks;
  438. L->getExitingBlocks(ExitingBlocks);
  439. if (ExitingBlocks.size() > 2)
  440. return false;
  441. // The second heuristic is that L has one exit other than the latchexit and
  442. // that exit is a deoptimize block. We know that deoptimize blocks are rarely
  443. // taken, which also implies the branch leading to the deoptimize block is
  444. // highly predictable.
  445. return (OtherExits.size() == 1 &&
  446. OtherExits[0]->getTerminatingDeoptimizeCall());
  447. // TODO: These can be fine-tuned further to consider code size or deopt states
  448. // that are captured by the deoptimize exit block.
  449. // Also, we can extend this to support more cases, if we actually
  450. // know of kinds of multiexit loops that would benefit from unrolling.
  451. }
  452. /// Insert code in the prolog/epilog code when unrolling a loop with a
  453. /// run-time trip-count.
  454. ///
  455. /// This method assumes that the loop unroll factor is total number
  456. /// of loop bodies in the loop after unrolling. (Some folks refer
  457. /// to the unroll factor as the number of *extra* copies added).
  458. /// We assume also that the loop unroll factor is a power-of-two. So, after
  459. /// unrolling the loop, the number of loop bodies executed is 2,
  460. /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
  461. /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
  462. /// the switch instruction is generated.
  463. ///
  464. /// ***Prolog case***
  465. /// extraiters = tripcount % loopfactor
  466. /// if (extraiters == 0) jump Loop:
  467. /// else jump Prol:
  468. /// Prol: LoopBody;
  469. /// extraiters -= 1 // Omitted if unroll factor is 2.
  470. /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
  471. /// if (tripcount < loopfactor) jump End:
  472. /// Loop:
  473. /// ...
  474. /// End:
  475. ///
  476. /// ***Epilog case***
  477. /// extraiters = tripcount % loopfactor
  478. /// if (tripcount < loopfactor) jump LoopExit:
  479. /// unroll_iters = tripcount - extraiters
  480. /// Loop: LoopBody; (executes unroll_iter times);
  481. /// unroll_iter -= 1
  482. /// if (unroll_iter != 0) jump Loop:
  483. /// LoopExit:
  484. /// if (extraiters == 0) jump EpilExit:
  485. /// Epil: LoopBody; (executes extraiters times)
  486. /// extraiters -= 1 // Omitted if unroll factor is 2.
  487. /// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
  488. /// EpilExit:
  489. bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
  490. bool AllowExpensiveTripCount,
  491. bool UseEpilogRemainder,
  492. bool UnrollRemainder, LoopInfo *LI,
  493. ScalarEvolution *SE, DominatorTree *DT,
  494. AssumptionCache *AC, bool PreserveLCSSA,
  495. Loop **ResultLoop) {
  496. LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
  497. LLVM_DEBUG(L->dump());
  498. LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
  499. : dbgs() << "Using prolog remainder.\n");
  500. // Make sure the loop is in canonical form.
  501. if (!L->isLoopSimplifyForm()) {
  502. LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
  503. return false;
  504. }
  505. // Guaranteed by LoopSimplifyForm.
  506. BasicBlock *Latch = L->getLoopLatch();
  507. BasicBlock *Header = L->getHeader();
  508. BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
  509. if (!LatchBR || LatchBR->isUnconditional()) {
  510. // The loop-rotate pass can be helpful to avoid this in many cases.
  511. LLVM_DEBUG(
  512. dbgs()
  513. << "Loop latch not terminated by a conditional branch.\n");
  514. return false;
  515. }
  516. unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
  517. BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
  518. if (L->contains(LatchExit)) {
  519. // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
  520. // targets of the Latch be an exit block out of the loop.
  521. LLVM_DEBUG(
  522. dbgs()
  523. << "One of the loop latch successors must be the exit block.\n");
  524. return false;
  525. }
  526. // These are exit blocks other than the target of the latch exiting block.
  527. SmallVector<BasicBlock *, 4> OtherExits;
  528. bool isMultiExitUnrollingEnabled =
  529. canSafelyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
  530. UseEpilogRemainder) &&
  531. canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
  532. UseEpilogRemainder);
  533. // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
  534. if (!isMultiExitUnrollingEnabled &&
  535. (!L->getExitingBlock() || OtherExits.size())) {
  536. LLVM_DEBUG(
  537. dbgs()
  538. << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
  539. "enabled!\n");
  540. return false;
  541. }
  542. // Use Scalar Evolution to compute the trip count. This allows more loops to
  543. // be unrolled than relying on induction var simplification.
  544. if (!SE)
  545. return false;
  546. // Only unroll loops with a computable trip count, and the trip count needs
  547. // to be an int value (allowing a pointer type is a TODO item).
  548. // We calculate the backedge count by using getExitCount on the Latch block,
  549. // which is proven to be the only exiting block in this loop. This is same as
  550. // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
  551. // exiting blocks).
  552. const SCEV *BECountSC = SE->getExitCount(L, Latch);
  553. if (isa<SCEVCouldNotCompute>(BECountSC) ||
  554. !BECountSC->getType()->isIntegerTy()) {
  555. LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
  556. return false;
  557. }
  558. unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
  559. // Add 1 since the backedge count doesn't include the first loop iteration.
  560. const SCEV *TripCountSC =
  561. SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
  562. if (isa<SCEVCouldNotCompute>(TripCountSC)) {
  563. LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
  564. return false;
  565. }
  566. BasicBlock *PreHeader = L->getLoopPreheader();
  567. BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
  568. const DataLayout &DL = Header->getModule()->getDataLayout();
  569. SCEVExpander Expander(*SE, DL, "loop-unroll");
  570. if (!AllowExpensiveTripCount &&
  571. Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) {
  572. LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
  573. return false;
  574. }
  575. // This constraint lets us deal with an overflowing trip count easily; see the
  576. // comment on ModVal below.
  577. if (Log2_32(Count) > BEWidth) {
  578. LLVM_DEBUG(
  579. dbgs()
  580. << "Count failed constraint on overflow trip count calculation.\n");
  581. return false;
  582. }
  583. // Loop structure is the following:
  584. //
  585. // PreHeader
  586. // Header
  587. // ...
  588. // Latch
  589. // LatchExit
  590. BasicBlock *NewPreHeader;
  591. BasicBlock *NewExit = nullptr;
  592. BasicBlock *PrologExit = nullptr;
  593. BasicBlock *EpilogPreHeader = nullptr;
  594. BasicBlock *PrologPreHeader = nullptr;
  595. if (UseEpilogRemainder) {
  596. // If epilog remainder
  597. // Split PreHeader to insert a branch around loop for unrolling.
  598. NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
  599. NewPreHeader->setName(PreHeader->getName() + ".new");
  600. // Split LatchExit to create phi nodes from branch above.
  601. SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit));
  602. NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa", DT, LI,
  603. nullptr, PreserveLCSSA);
  604. // NewExit gets its DebugLoc from LatchExit, which is not part of the
  605. // original Loop.
  606. // Fix this by setting Loop's DebugLoc to NewExit.
  607. auto *NewExitTerminator = NewExit->getTerminator();
  608. NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
  609. // Split NewExit to insert epilog remainder loop.
  610. EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
  611. EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
  612. } else {
  613. // If prolog remainder
  614. // Split the original preheader twice to insert prolog remainder loop
  615. PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
  616. PrologPreHeader->setName(Header->getName() + ".prol.preheader");
  617. PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
  618. DT, LI);
  619. PrologExit->setName(Header->getName() + ".prol.loopexit");
  620. // Split PrologExit to get NewPreHeader.
  621. NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
  622. NewPreHeader->setName(PreHeader->getName() + ".new");
  623. }
  624. // Loop structure should be the following:
  625. // Epilog Prolog
  626. //
  627. // PreHeader PreHeader
  628. // *NewPreHeader *PrologPreHeader
  629. // Header *PrologExit
  630. // ... *NewPreHeader
  631. // Latch Header
  632. // *NewExit ...
  633. // *EpilogPreHeader Latch
  634. // LatchExit LatchExit
  635. // Calculate conditions for branch around loop for unrolling
  636. // in epilog case and around prolog remainder loop in prolog case.
  637. // Compute the number of extra iterations required, which is:
  638. // extra iterations = run-time trip count % loop unroll factor
  639. PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
  640. Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
  641. PreHeaderBR);
  642. Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
  643. PreHeaderBR);
  644. IRBuilder<> B(PreHeaderBR);
  645. Value *ModVal;
  646. // Calculate ModVal = (BECount + 1) % Count.
  647. // Note that TripCount is BECount + 1.
  648. if (isPowerOf2_32(Count)) {
  649. // When Count is power of 2 we don't BECount for epilog case, however we'll
  650. // need it for a branch around unrolling loop for prolog case.
  651. ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
  652. // 1. There are no iterations to be run in the prolog/epilog loop.
  653. // OR
  654. // 2. The addition computing TripCount overflowed.
  655. //
  656. // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
  657. // the number of iterations that remain to be run in the original loop is a
  658. // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
  659. // explicitly check this above).
  660. } else {
  661. // As (BECount + 1) can potentially unsigned overflow we count
  662. // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
  663. Value *ModValTmp = B.CreateURem(BECount,
  664. ConstantInt::get(BECount->getType(),
  665. Count));
  666. Value *ModValAdd = B.CreateAdd(ModValTmp,
  667. ConstantInt::get(ModValTmp->getType(), 1));
  668. // At that point (BECount % Count) + 1 could be equal to Count.
  669. // To handle this case we need to take mod by Count one more time.
  670. ModVal = B.CreateURem(ModValAdd,
  671. ConstantInt::get(BECount->getType(), Count),
  672. "xtraiter");
  673. }
  674. Value *BranchVal =
  675. UseEpilogRemainder ? B.CreateICmpULT(BECount,
  676. ConstantInt::get(BECount->getType(),
  677. Count - 1)) :
  678. B.CreateIsNotNull(ModVal, "lcmp.mod");
  679. BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
  680. BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
  681. // Branch to either remainder (extra iterations) loop or unrolling loop.
  682. B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
  683. PreHeaderBR->eraseFromParent();
  684. if (DT) {
  685. if (UseEpilogRemainder)
  686. DT->changeImmediateDominator(NewExit, PreHeader);
  687. else
  688. DT->changeImmediateDominator(PrologExit, PreHeader);
  689. }
  690. Function *F = Header->getParent();
  691. // Get an ordered list of blocks in the loop to help with the ordering of the
  692. // cloned blocks in the prolog/epilog code
  693. LoopBlocksDFS LoopBlocks(L);
  694. LoopBlocks.perform(LI);
  695. //
  696. // For each extra loop iteration, create a copy of the loop's basic blocks
  697. // and generate a condition that branches to the copy depending on the
  698. // number of 'left over' iterations.
  699. //
  700. std::vector<BasicBlock *> NewBlocks;
  701. ValueToValueMapTy VMap;
  702. // For unroll factor 2 remainder loop will have 1 iterations.
  703. // Do not create 1 iteration loop.
  704. bool CreateRemainderLoop = (Count != 2);
  705. // Clone all the basic blocks in the loop. If Count is 2, we don't clone
  706. // the loop, otherwise we create a cloned loop to execute the extra
  707. // iterations. This function adds the appropriate CFG connections.
  708. BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
  709. BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
  710. Loop *remainderLoop = CloneLoopBlocks(
  711. L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
  712. InsertTop, InsertBot,
  713. NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
  714. // Insert the cloned blocks into the function.
  715. F->getBasicBlockList().splice(InsertBot->getIterator(),
  716. F->getBasicBlockList(),
  717. NewBlocks[0]->getIterator(),
  718. F->end());
  719. // Now the loop blocks are cloned and the other exiting blocks from the
  720. // remainder are connected to the original Loop's exit blocks. The remaining
  721. // work is to update the phi nodes in the original loop, and take in the
  722. // values from the cloned region. Also update the dominator info for
  723. // OtherExits and their immediate successors, since we have new edges into
  724. // OtherExits.
  725. SmallPtrSet<BasicBlock*, 8> ImmediateSuccessorsOfExitBlocks;
  726. for (auto *BB : OtherExits) {
  727. for (auto &II : *BB) {
  728. // Given we preserve LCSSA form, we know that the values used outside the
  729. // loop will be used through these phi nodes at the exit blocks that are
  730. // transformed below.
  731. if (!isa<PHINode>(II))
  732. break;
  733. PHINode *Phi = cast<PHINode>(&II);
  734. unsigned oldNumOperands = Phi->getNumIncomingValues();
  735. // Add the incoming values from the remainder code to the end of the phi
  736. // node.
  737. for (unsigned i =0; i < oldNumOperands; i++){
  738. Value *newVal = VMap.lookup(Phi->getIncomingValue(i));
  739. // newVal can be a constant or derived from values outside the loop, and
  740. // hence need not have a VMap value. Also, since lookup already generated
  741. // a default "null" VMap entry for this value, we need to populate that
  742. // VMap entry correctly, with the mapped entry being itself.
  743. if (!newVal) {
  744. newVal = Phi->getIncomingValue(i);
  745. VMap[Phi->getIncomingValue(i)] = Phi->getIncomingValue(i);
  746. }
  747. Phi->addIncoming(newVal,
  748. cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
  749. }
  750. }
  751. #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
  752. for (BasicBlock *SuccBB : successors(BB)) {
  753. assert(!(any_of(OtherExits,
  754. [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
  755. SuccBB == LatchExit) &&
  756. "Breaks the definition of dedicated exits!");
  757. }
  758. #endif
  759. // Update the dominator info because the immediate dominator is no longer the
  760. // header of the original Loop. BB has edges both from L and remainder code.
  761. // Since the preheader determines which loop is run (L or directly jump to
  762. // the remainder code), we set the immediate dominator as the preheader.
  763. if (DT) {
  764. DT->changeImmediateDominator(BB, PreHeader);
  765. // Also update the IDom for immediate successors of BB. If the current
  766. // IDom is the header, update the IDom to be the preheader because that is
  767. // the nearest common dominator of all predecessors of SuccBB. We need to
  768. // check for IDom being the header because successors of exit blocks can
  769. // have edges from outside the loop, and we should not incorrectly update
  770. // the IDom in that case.
  771. for (BasicBlock *SuccBB: successors(BB))
  772. if (ImmediateSuccessorsOfExitBlocks.insert(SuccBB).second) {
  773. if (DT->getNode(SuccBB)->getIDom()->getBlock() == Header) {
  774. assert(!SuccBB->getSinglePredecessor() &&
  775. "BB should be the IDom then!");
  776. DT->changeImmediateDominator(SuccBB, PreHeader);
  777. }
  778. }
  779. }
  780. }
  781. // Loop structure should be the following:
  782. // Epilog Prolog
  783. //
  784. // PreHeader PreHeader
  785. // NewPreHeader PrologPreHeader
  786. // Header PrologHeader
  787. // ... ...
  788. // Latch PrologLatch
  789. // NewExit PrologExit
  790. // EpilogPreHeader NewPreHeader
  791. // EpilogHeader Header
  792. // ... ...
  793. // EpilogLatch Latch
  794. // LatchExit LatchExit
  795. // Rewrite the cloned instruction operands to use the values created when the
  796. // clone is created.
  797. for (BasicBlock *BB : NewBlocks) {
  798. for (Instruction &I : *BB) {
  799. RemapInstruction(&I, VMap,
  800. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  801. }
  802. }
  803. if (UseEpilogRemainder) {
  804. // Connect the epilog code to the original loop and update the
  805. // PHI functions.
  806. ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
  807. EpilogPreHeader, NewPreHeader, VMap, DT, LI,
  808. PreserveLCSSA);
  809. // Update counter in loop for unrolling.
  810. // I should be multiply of Count.
  811. IRBuilder<> B2(NewPreHeader->getTerminator());
  812. Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
  813. BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
  814. B2.SetInsertPoint(LatchBR);
  815. PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
  816. Header->getFirstNonPHI());
  817. Value *IdxSub =
  818. B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
  819. NewIdx->getName() + ".nsub");
  820. Value *IdxCmp;
  821. if (LatchBR->getSuccessor(0) == Header)
  822. IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
  823. else
  824. IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
  825. NewIdx->addIncoming(TestVal, NewPreHeader);
  826. NewIdx->addIncoming(IdxSub, Latch);
  827. LatchBR->setCondition(IdxCmp);
  828. } else {
  829. // Connect the prolog code to the original loop and update the
  830. // PHI functions.
  831. ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
  832. NewPreHeader, VMap, DT, LI, PreserveLCSSA);
  833. }
  834. // If this loop is nested, then the loop unroller changes the code in the any
  835. // of its parent loops, so the Scalar Evolution pass needs to be run again.
  836. SE->forgetTopmostLoop(L);
  837. // Canonicalize to LoopSimplifyForm both original and remainder loops. We
  838. // cannot rely on the LoopUnrollPass to do this because it only does
  839. // canonicalization for parent/subloops and not the sibling loops.
  840. if (OtherExits.size() > 0) {
  841. // Generate dedicated exit blocks for the original loop, to preserve
  842. // LoopSimplifyForm.
  843. formDedicatedExitBlocks(L, DT, LI, PreserveLCSSA);
  844. // Generate dedicated exit blocks for the remainder loop if one exists, to
  845. // preserve LoopSimplifyForm.
  846. if (remainderLoop)
  847. formDedicatedExitBlocks(remainderLoop, DT, LI, PreserveLCSSA);
  848. }
  849. auto UnrollResult = LoopUnrollResult::Unmodified;
  850. if (remainderLoop && UnrollRemainder) {
  851. LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
  852. UnrollResult =
  853. UnrollLoop(remainderLoop, /*Count*/ Count - 1, /*TripCount*/ Count - 1,
  854. /*Force*/ false, /*AllowRuntime*/ false,
  855. /*AllowExpensiveTripCount*/ false, /*PreserveCondBr*/ true,
  856. /*PreserveOnlyFirst*/ false, /*TripMultiple*/ 1,
  857. /*PeelCount*/ 0, /*UnrollRemainder*/ false, LI, SE, DT, AC,
  858. /*ORE*/ nullptr, PreserveLCSSA);
  859. }
  860. if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
  861. *ResultLoop = remainderLoop;
  862. NumRuntimeUnrolled++;
  863. return true;
  864. }