LoopUnrollRuntime.cpp 42 KB

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