LoopUnroll.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. //===-- UnrollLoop.cpp - 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. It does not define any
  11. // actual pass or policy, but provides a single function to perform loop
  12. // unrolling.
  13. //
  14. // The process of unrolling can produce extraneous basic blocks linked with
  15. // unconditional branches. This will be corrected in the future.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Transforms/Utils/UnrollLoop.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/AssumptionCache.h"
  22. #include "llvm/Analysis/InstructionSimplify.h"
  23. #include "llvm/Analysis/LoopIterator.h"
  24. #include "llvm/Analysis/LoopPass.h"
  25. #include "llvm/Analysis/ScalarEvolution.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/Dominators.h"
  29. #include "llvm/IR/DiagnosticInfo.h"
  30. #include "llvm/IR/LLVMContext.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 "llvm/Transforms/Utils/Local.h"
  36. #include "llvm/Transforms/Utils/LoopUtils.h"
  37. #include "llvm/Transforms/Utils/SimplifyIndVar.h"
  38. using namespace llvm;
  39. #define DEBUG_TYPE "loop-unroll"
  40. // TODO: Should these be here or in LoopUnroll?
  41. STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
  42. STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
  43. /// RemapInstruction - Convert the instruction operands from referencing the
  44. /// current values into those specified by VMap.
  45. static inline void RemapInstruction(Instruction *I,
  46. ValueToValueMapTy &VMap) {
  47. for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
  48. Value *Op = I->getOperand(op);
  49. ValueToValueMapTy::iterator It = VMap.find(Op);
  50. if (It != VMap.end())
  51. I->setOperand(op, It->second);
  52. }
  53. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  54. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  55. ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
  56. if (It != VMap.end())
  57. PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
  58. }
  59. }
  60. }
  61. /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
  62. /// only has one predecessor, and that predecessor only has one successor.
  63. /// The LoopInfo Analysis that is passed will be kept consistent. If folding is
  64. /// successful references to the containing loop must be removed from
  65. /// ScalarEvolution by calling ScalarEvolution::forgetLoop because SE may have
  66. /// references to the eliminated BB. The argument ForgottenLoops contains a set
  67. /// of loops that have already been forgotten to prevent redundant, expensive
  68. /// calls to ScalarEvolution::forgetLoop. Returns the new combined block.
  69. static BasicBlock *
  70. FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI, LPPassManager *LPM,
  71. SmallPtrSetImpl<Loop *> &ForgottenLoops) {
  72. // Merge basic blocks into their predecessor if there is only one distinct
  73. // pred, and if there is only one distinct successor of the predecessor, and
  74. // if there are no PHI nodes.
  75. BasicBlock *OnlyPred = BB->getSinglePredecessor();
  76. if (!OnlyPred) return nullptr;
  77. if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
  78. return nullptr;
  79. DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
  80. // Resolve any PHI nodes at the start of the block. They are all
  81. // guaranteed to have exactly one entry if they exist, unless there are
  82. // multiple duplicate (but guaranteed to be equal) entries for the
  83. // incoming edges. This occurs when there are multiple edges from
  84. // OnlyPred to OnlySucc.
  85. FoldSingleEntryPHINodes(BB);
  86. // Delete the unconditional branch from the predecessor...
  87. OnlyPred->getInstList().pop_back();
  88. // Make all PHI nodes that referred to BB now refer to Pred as their
  89. // source...
  90. BB->replaceAllUsesWith(OnlyPred);
  91. // Move all definitions in the successor to the predecessor...
  92. OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
  93. // OldName will be valid until erased.
  94. StringRef OldName = BB->getName();
  95. // Erase basic block from the function...
  96. // ScalarEvolution holds references to loop exit blocks.
  97. if (LPM) {
  98. if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
  99. if (Loop *L = LI->getLoopFor(BB)) {
  100. if (ForgottenLoops.insert(L).second)
  101. SE->forgetLoop(L);
  102. }
  103. }
  104. }
  105. LI->removeBlock(BB);
  106. // Inherit predecessor's name if it exists...
  107. if (!OldName.empty() && !OnlyPred->hasName())
  108. OnlyPred->setName(OldName);
  109. BB->eraseFromParent();
  110. return OnlyPred;
  111. }
  112. /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
  113. /// if unrolling was successful, or false if the loop was unmodified. Unrolling
  114. /// can only fail when the loop's latch block is not terminated by a conditional
  115. /// branch instruction. However, if the trip count (and multiple) are not known,
  116. /// loop unrolling will mostly produce more code that is no faster.
  117. ///
  118. /// TripCount is generally defined as the number of times the loop header
  119. /// executes. UnrollLoop relaxes the definition to permit early exits: here
  120. /// TripCount is the iteration on which control exits LatchBlock if no early
  121. /// exits were taken. Note that UnrollLoop assumes that the loop counter test
  122. /// terminates LatchBlock in order to remove unnecesssary instances of the
  123. /// test. In other words, control may exit the loop prior to TripCount
  124. /// iterations via an early branch, but control may not exit the loop from the
  125. /// LatchBlock's terminator prior to TripCount iterations.
  126. ///
  127. /// Similarly, TripMultiple divides the number of times that the LatchBlock may
  128. /// execute without exiting the loop.
  129. ///
  130. /// The LoopInfo Analysis that is passed will be kept consistent.
  131. ///
  132. /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
  133. /// removed from the LoopPassManager as well. LPM can also be NULL.
  134. ///
  135. /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
  136. /// available from the Pass it must also preserve those analyses.
  137. bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
  138. bool AllowRuntime, unsigned TripMultiple, LoopInfo *LI,
  139. Pass *PP, LPPassManager *LPM, AssumptionCache *AC) {
  140. BasicBlock *Preheader = L->getLoopPreheader();
  141. if (!Preheader) {
  142. DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
  143. return false;
  144. }
  145. BasicBlock *LatchBlock = L->getLoopLatch();
  146. if (!LatchBlock) {
  147. DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
  148. return false;
  149. }
  150. // Loops with indirectbr cannot be cloned.
  151. if (!L->isSafeToClone()) {
  152. DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
  153. return false;
  154. }
  155. BasicBlock *Header = L->getHeader();
  156. BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
  157. if (!BI || BI->isUnconditional()) {
  158. // The loop-rotate pass can be helpful to avoid this in many cases.
  159. DEBUG(dbgs() <<
  160. " Can't unroll; loop not terminated by a conditional branch.\n");
  161. return false;
  162. }
  163. if (Header->hasAddressTaken()) {
  164. // The loop-rotate pass can be helpful to avoid this in many cases.
  165. DEBUG(dbgs() <<
  166. " Won't unroll loop: address of header block is taken.\n");
  167. return false;
  168. }
  169. if (TripCount != 0)
  170. DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
  171. if (TripMultiple != 1)
  172. DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
  173. // Effectively "DCE" unrolled iterations that are beyond the tripcount
  174. // and will never be executed.
  175. if (TripCount != 0 && Count > TripCount)
  176. Count = TripCount;
  177. // Don't enter the unroll code if there is nothing to do. This way we don't
  178. // need to support "partial unrolling by 1".
  179. if (TripCount == 0 && Count < 2)
  180. return false;
  181. assert(Count > 0);
  182. assert(TripMultiple > 0);
  183. assert(TripCount == 0 || TripCount % TripMultiple == 0);
  184. // Are we eliminating the loop control altogether?
  185. bool CompletelyUnroll = Count == TripCount;
  186. // We assume a run-time trip count if the compiler cannot
  187. // figure out the loop trip count and the unroll-runtime
  188. // flag is specified.
  189. bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
  190. if (RuntimeTripCount && !UnrollRuntimeLoopProlog(L, Count, LI, LPM))
  191. return false;
  192. // Notify ScalarEvolution that the loop will be substantially changed,
  193. // if not outright eliminated.
  194. ScalarEvolution *SE =
  195. PP ? PP->getAnalysisIfAvailable<ScalarEvolution>() : nullptr;
  196. if (SE)
  197. SE->forgetLoop(L);
  198. // If we know the trip count, we know the multiple...
  199. unsigned BreakoutTrip = 0;
  200. if (TripCount != 0) {
  201. BreakoutTrip = TripCount % Count;
  202. TripMultiple = 0;
  203. } else {
  204. // Figure out what multiple to use.
  205. BreakoutTrip = TripMultiple =
  206. (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
  207. }
  208. // Report the unrolling decision.
  209. DebugLoc LoopLoc = L->getStartLoc();
  210. Function *F = Header->getParent();
  211. LLVMContext &Ctx = F->getContext();
  212. if (CompletelyUnroll) {
  213. DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
  214. << " with trip count " << TripCount << "!\n");
  215. emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
  216. Twine("completely unrolled loop with ") +
  217. Twine(TripCount) + " iterations");
  218. } else {
  219. auto EmitDiag = [&](const Twine &T) {
  220. emitOptimizationRemark(Ctx, DEBUG_TYPE, *F, LoopLoc,
  221. "unrolled loop by a factor of " + Twine(Count) +
  222. T);
  223. };
  224. DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
  225. << " by " << Count);
  226. if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
  227. DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
  228. EmitDiag(" with a breakout at trip " + Twine(BreakoutTrip));
  229. } else if (TripMultiple != 1) {
  230. DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
  231. EmitDiag(" with " + Twine(TripMultiple) + " trips per branch");
  232. } else if (RuntimeTripCount) {
  233. DEBUG(dbgs() << " with run-time trip count");
  234. EmitDiag(" with run-time trip count");
  235. }
  236. DEBUG(dbgs() << "!\n");
  237. }
  238. bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
  239. BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
  240. // For the first iteration of the loop, we should use the precloned values for
  241. // PHI nodes. Insert associations now.
  242. ValueToValueMapTy LastValueMap;
  243. std::vector<PHINode*> OrigPHINode;
  244. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  245. OrigPHINode.push_back(cast<PHINode>(I));
  246. }
  247. std::vector<BasicBlock*> Headers;
  248. std::vector<BasicBlock*> Latches;
  249. Headers.push_back(Header);
  250. Latches.push_back(LatchBlock);
  251. // The current on-the-fly SSA update requires blocks to be processed in
  252. // reverse postorder so that LastValueMap contains the correct value at each
  253. // exit.
  254. LoopBlocksDFS DFS(L);
  255. DFS.perform(LI);
  256. // Stash the DFS iterators before adding blocks to the loop.
  257. LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
  258. LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
  259. for (unsigned It = 1; It != Count; ++It) {
  260. std::vector<BasicBlock*> NewBlocks;
  261. SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
  262. NewLoops[L] = L;
  263. for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
  264. ValueToValueMapTy VMap;
  265. BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
  266. Header->getParent()->getBasicBlockList().push_back(New);
  267. // Tell LI about New.
  268. if (*BB == Header) {
  269. assert(LI->getLoopFor(*BB) == L && "Header should not be in a sub-loop");
  270. L->addBasicBlockToLoop(New, *LI);
  271. } else {
  272. // Figure out which loop New is in.
  273. const Loop *OldLoop = LI->getLoopFor(*BB);
  274. assert(OldLoop && "Should (at least) be in the loop being unrolled!");
  275. Loop *&NewLoop = NewLoops[OldLoop];
  276. if (!NewLoop) {
  277. // Found a new sub-loop.
  278. assert(*BB == OldLoop->getHeader() &&
  279. "Header should be first in RPO");
  280. Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
  281. assert(NewLoopParent &&
  282. "Expected parent loop before sub-loop in RPO");
  283. NewLoop = new Loop;
  284. NewLoopParent->addChildLoop(NewLoop);
  285. // Forget the old loop, since its inputs may have changed.
  286. if (SE)
  287. SE->forgetLoop(OldLoop);
  288. }
  289. NewLoop->addBasicBlockToLoop(New, *LI);
  290. }
  291. if (*BB == Header)
  292. // Loop over all of the PHI nodes in the block, changing them to use
  293. // the incoming values from the previous block.
  294. for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
  295. PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
  296. Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
  297. if (Instruction *InValI = dyn_cast<Instruction>(InVal))
  298. if (It > 1 && L->contains(InValI))
  299. InVal = LastValueMap[InValI];
  300. VMap[OrigPHINode[i]] = InVal;
  301. New->getInstList().erase(NewPHI);
  302. }
  303. // Update our running map of newest clones
  304. LastValueMap[*BB] = New;
  305. for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
  306. VI != VE; ++VI)
  307. LastValueMap[VI->first] = VI->second;
  308. // Add phi entries for newly created values to all exit blocks.
  309. for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
  310. SI != SE; ++SI) {
  311. if (L->contains(*SI))
  312. continue;
  313. for (BasicBlock::iterator BBI = (*SI)->begin();
  314. PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
  315. Value *Incoming = phi->getIncomingValueForBlock(*BB);
  316. ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
  317. if (It != LastValueMap.end())
  318. Incoming = It->second;
  319. phi->addIncoming(Incoming, New);
  320. }
  321. }
  322. // Keep track of new headers and latches as we create them, so that
  323. // we can insert the proper branches later.
  324. if (*BB == Header)
  325. Headers.push_back(New);
  326. if (*BB == LatchBlock)
  327. Latches.push_back(New);
  328. NewBlocks.push_back(New);
  329. }
  330. // Remap all instructions in the most recent iteration
  331. for (unsigned i = 0; i < NewBlocks.size(); ++i)
  332. for (BasicBlock::iterator I = NewBlocks[i]->begin(),
  333. E = NewBlocks[i]->end(); I != E; ++I)
  334. ::RemapInstruction(I, LastValueMap);
  335. }
  336. // Loop over the PHI nodes in the original block, setting incoming values.
  337. for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
  338. PHINode *PN = OrigPHINode[i];
  339. if (CompletelyUnroll) {
  340. PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
  341. Header->getInstList().erase(PN);
  342. }
  343. else if (Count > 1) {
  344. Value *InVal = PN->removeIncomingValue(LatchBlock, false);
  345. // If this value was defined in the loop, take the value defined by the
  346. // last iteration of the loop.
  347. if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
  348. if (L->contains(InValI))
  349. InVal = LastValueMap[InVal];
  350. }
  351. assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
  352. PN->addIncoming(InVal, Latches.back());
  353. }
  354. }
  355. // Now that all the basic blocks for the unrolled iterations are in place,
  356. // set up the branches to connect them.
  357. for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
  358. // The original branch was replicated in each unrolled iteration.
  359. BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
  360. // The branch destination.
  361. unsigned j = (i + 1) % e;
  362. BasicBlock *Dest = Headers[j];
  363. bool NeedConditional = true;
  364. if (RuntimeTripCount && j != 0) {
  365. NeedConditional = false;
  366. }
  367. // For a complete unroll, make the last iteration end with a branch
  368. // to the exit block.
  369. if (CompletelyUnroll && j == 0) {
  370. Dest = LoopExit;
  371. NeedConditional = false;
  372. }
  373. // If we know the trip count or a multiple of it, we can safely use an
  374. // unconditional branch for some iterations.
  375. if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
  376. NeedConditional = false;
  377. }
  378. if (NeedConditional) {
  379. // Update the conditional branch's successor for the following
  380. // iteration.
  381. Term->setSuccessor(!ContinueOnTrue, Dest);
  382. } else {
  383. // Remove phi operands at this loop exit
  384. if (Dest != LoopExit) {
  385. BasicBlock *BB = Latches[i];
  386. for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
  387. SI != SE; ++SI) {
  388. if (*SI == Headers[i])
  389. continue;
  390. for (BasicBlock::iterator BBI = (*SI)->begin();
  391. PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
  392. Phi->removeIncomingValue(BB, false);
  393. }
  394. }
  395. }
  396. // Replace the conditional branch with an unconditional one.
  397. BranchInst::Create(Dest, Term);
  398. Term->eraseFromParent();
  399. }
  400. }
  401. // Merge adjacent basic blocks, if possible.
  402. SmallPtrSet<Loop *, 4> ForgottenLoops;
  403. for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
  404. BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
  405. if (Term->isUnconditional()) {
  406. BasicBlock *Dest = Term->getSuccessor(0);
  407. if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM,
  408. ForgottenLoops))
  409. std::replace(Latches.begin(), Latches.end(), Dest, Fold);
  410. }
  411. }
  412. // FIXME: We could register any cloned assumptions instead of clearing the
  413. // whole function's cache.
  414. AC->clear();
  415. DominatorTree *DT = nullptr;
  416. if (PP) {
  417. // FIXME: Reconstruct dom info, because it is not preserved properly.
  418. // Incrementally updating domtree after loop unrolling would be easy.
  419. if (DominatorTreeWrapperPass *DTWP =
  420. PP->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
  421. DT = &DTWP->getDomTree();
  422. DT->recalculate(*L->getHeader()->getParent());
  423. }
  424. // Simplify any new induction variables in the partially unrolled loop.
  425. if (SE && !CompletelyUnroll) {
  426. SmallVector<WeakVH, 16> DeadInsts;
  427. simplifyLoopIVs(L, SE, LPM, DeadInsts);
  428. // Aggressively clean up dead instructions that simplifyLoopIVs already
  429. // identified. Any remaining should be cleaned up below.
  430. while (!DeadInsts.empty())
  431. if (Instruction *Inst =
  432. dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
  433. RecursivelyDeleteTriviallyDeadInstructions(Inst);
  434. }
  435. }
  436. // At this point, the code is well formed. We now do a quick sweep over the
  437. // inserted code, doing constant propagation and dead code elimination as we
  438. // go.
  439. const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
  440. for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
  441. BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
  442. for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
  443. Instruction *Inst = I++;
  444. if (isInstructionTriviallyDead(Inst))
  445. (*BB)->getInstList().erase(Inst);
  446. else if (Value *V = SimplifyInstruction(Inst))
  447. if (LI->replacementPreservesLCSSAForm(Inst, V)) {
  448. Inst->replaceAllUsesWith(V);
  449. (*BB)->getInstList().erase(Inst);
  450. }
  451. }
  452. NumCompletelyUnrolled += CompletelyUnroll;
  453. ++NumUnrolled;
  454. Loop *OuterL = L->getParentLoop();
  455. // Remove the loop from the LoopPassManager if it's completely removed.
  456. if (CompletelyUnroll && LPM != nullptr)
  457. LPM->deleteLoopFromQueue(L);
  458. // If we have a pass and a DominatorTree we should re-simplify impacted loops
  459. // to ensure subsequent analyses can rely on this form. We want to simplify
  460. // at least one layer outside of the loop that was unrolled so that any
  461. // changes to the parent loop exposed by the unrolling are considered.
  462. if (PP && DT) {
  463. if (!OuterL && !CompletelyUnroll)
  464. OuterL = L;
  465. if (OuterL) {
  466. const DataLayout &DL = F->getParent()->getDataLayout();
  467. simplifyLoop(OuterL, DT, LI, PP, /*AliasAnalysis*/ nullptr, SE, &DL, AC);
  468. // LCSSA must be performed on the outermost affected loop. The unrolled
  469. // loop's last loop latch is guaranteed to be in the outermost loop after
  470. // deleteLoopFromQueue updates LoopInfo.
  471. Loop *LatchLoop = LI->getLoopFor(Latches.back());
  472. if (!OuterL->contains(LatchLoop))
  473. while (OuterL->getParentLoop() != LatchLoop)
  474. OuterL = OuterL->getParentLoop();
  475. formLCSSARecursively(*OuterL, *DT, LI, SE);
  476. }
  477. }
  478. return true;
  479. }
  480. /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
  481. /// node with the given name (for example, "llvm.loop.unroll.count"). If no
  482. /// such metadata node exists, then nullptr is returned.
  483. MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
  484. // First operand should refer to the loop id itself.
  485. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  486. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  487. for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
  488. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  489. if (!MD)
  490. continue;
  491. MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  492. if (!S)
  493. continue;
  494. if (Name.equals(S->getString()))
  495. return MD;
  496. }
  497. return nullptr;
  498. }