LoopUnroll.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. //===-- UnrollLoop.cpp - 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. It does not define any
  10. // actual pass or policy, but provides a single function to perform loop
  11. // unrolling.
  12. //
  13. // The process of unrolling can produce extraneous basic blocks linked with
  14. // unconditional branches. This will be corrected in the future.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SetVector.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/ADT/Twine.h"
  25. #include "llvm/ADT/ilist_iterator.h"
  26. #include "llvm/ADT/iterator_range.h"
  27. #include "llvm/Analysis/AssumptionCache.h"
  28. #include "llvm/Analysis/DomTreeUpdater.h"
  29. #include "llvm/Analysis/InstructionSimplify.h"
  30. #include "llvm/Analysis/LoopInfo.h"
  31. #include "llvm/Analysis/LoopIterator.h"
  32. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  33. #include "llvm/Analysis/ScalarEvolution.h"
  34. #include "llvm/IR/BasicBlock.h"
  35. #include "llvm/IR/CFG.h"
  36. #include "llvm/IR/Constants.h"
  37. #include "llvm/IR/DebugInfoMetadata.h"
  38. #include "llvm/IR/DebugLoc.h"
  39. #include "llvm/IR/DiagnosticInfo.h"
  40. #include "llvm/IR/Dominators.h"
  41. #include "llvm/IR/Function.h"
  42. #include "llvm/IR/Instruction.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/IntrinsicInst.h"
  45. #include "llvm/IR/Metadata.h"
  46. #include "llvm/IR/Module.h"
  47. #include "llvm/IR/Use.h"
  48. #include "llvm/IR/User.h"
  49. #include "llvm/IR/ValueHandle.h"
  50. #include "llvm/IR/ValueMap.h"
  51. #include "llvm/Support/Casting.h"
  52. #include "llvm/Support/CommandLine.h"
  53. #include "llvm/Support/Debug.h"
  54. #include "llvm/Support/GenericDomTree.h"
  55. #include "llvm/Support/MathExtras.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  58. #include "llvm/Transforms/Utils/Cloning.h"
  59. #include "llvm/Transforms/Utils/Local.h"
  60. #include "llvm/Transforms/Utils/LoopSimplify.h"
  61. #include "llvm/Transforms/Utils/LoopUtils.h"
  62. #include "llvm/Transforms/Utils/SimplifyIndVar.h"
  63. #include "llvm/Transforms/Utils/UnrollLoop.h"
  64. #include "llvm/Transforms/Utils/ValueMapper.h"
  65. #include <algorithm>
  66. #include <assert.h>
  67. #include <numeric>
  68. #include <type_traits>
  69. #include <vector>
  70. namespace llvm {
  71. class DataLayout;
  72. class Value;
  73. } // namespace llvm
  74. using namespace llvm;
  75. #define DEBUG_TYPE "loop-unroll"
  76. // TODO: Should these be here or in LoopUnroll?
  77. STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
  78. STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
  79. STATISTIC(NumUnrolledNotLatch, "Number of loops unrolled without a conditional "
  80. "latch (completely or otherwise)");
  81. static cl::opt<bool>
  82. UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
  83. cl::desc("Allow runtime unrolled loops to be unrolled "
  84. "with epilog instead of prolog."));
  85. static cl::opt<bool>
  86. UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
  87. cl::desc("Verify domtree after unrolling"),
  88. #ifdef EXPENSIVE_CHECKS
  89. cl::init(true)
  90. #else
  91. cl::init(false)
  92. #endif
  93. );
  94. static cl::opt<bool>
  95. UnrollVerifyLoopInfo("unroll-verify-loopinfo", cl::Hidden,
  96. cl::desc("Verify loopinfo after unrolling"),
  97. #ifdef EXPENSIVE_CHECKS
  98. cl::init(true)
  99. #else
  100. cl::init(false)
  101. #endif
  102. );
  103. /// Check if unrolling created a situation where we need to insert phi nodes to
  104. /// preserve LCSSA form.
  105. /// \param Blocks is a vector of basic blocks representing unrolled loop.
  106. /// \param L is the outer loop.
  107. /// It's possible that some of the blocks are in L, and some are not. In this
  108. /// case, if there is a use is outside L, and definition is inside L, we need to
  109. /// insert a phi-node, otherwise LCSSA will be broken.
  110. /// The function is just a helper function for llvm::UnrollLoop that returns
  111. /// true if this situation occurs, indicating that LCSSA needs to be fixed.
  112. static bool needToInsertPhisForLCSSA(Loop *L,
  113. const std::vector<BasicBlock *> &Blocks,
  114. LoopInfo *LI) {
  115. for (BasicBlock *BB : Blocks) {
  116. if (LI->getLoopFor(BB) == L)
  117. continue;
  118. for (Instruction &I : *BB) {
  119. for (Use &U : I.operands()) {
  120. if (const auto *Def = dyn_cast<Instruction>(U)) {
  121. Loop *DefLoop = LI->getLoopFor(Def->getParent());
  122. if (!DefLoop)
  123. continue;
  124. if (DefLoop->contains(L))
  125. return true;
  126. }
  127. }
  128. }
  129. }
  130. return false;
  131. }
  132. /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
  133. /// and adds a mapping from the original loop to the new loop to NewLoops.
  134. /// Returns nullptr if no new loop was created and a pointer to the
  135. /// original loop OriginalBB was part of otherwise.
  136. const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
  137. BasicBlock *ClonedBB, LoopInfo *LI,
  138. NewLoopsMap &NewLoops) {
  139. // Figure out which loop New is in.
  140. const Loop *OldLoop = LI->getLoopFor(OriginalBB);
  141. assert(OldLoop && "Should (at least) be in the loop being unrolled!");
  142. Loop *&NewLoop = NewLoops[OldLoop];
  143. if (!NewLoop) {
  144. // Found a new sub-loop.
  145. assert(OriginalBB == OldLoop->getHeader() &&
  146. "Header should be first in RPO");
  147. NewLoop = LI->AllocateLoop();
  148. Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
  149. if (NewLoopParent)
  150. NewLoopParent->addChildLoop(NewLoop);
  151. else
  152. LI->addTopLevelLoop(NewLoop);
  153. NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
  154. return OldLoop;
  155. } else {
  156. NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
  157. return nullptr;
  158. }
  159. }
  160. /// The function chooses which type of unroll (epilog or prolog) is more
  161. /// profitabale.
  162. /// Epilog unroll is more profitable when there is PHI that starts from
  163. /// constant. In this case epilog will leave PHI start from constant,
  164. /// but prolog will convert it to non-constant.
  165. ///
  166. /// loop:
  167. /// PN = PHI [I, Latch], [CI, PreHeader]
  168. /// I = foo(PN)
  169. /// ...
  170. ///
  171. /// Epilog unroll case.
  172. /// loop:
  173. /// PN = PHI [I2, Latch], [CI, PreHeader]
  174. /// I1 = foo(PN)
  175. /// I2 = foo(I1)
  176. /// ...
  177. /// Prolog unroll case.
  178. /// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
  179. /// loop:
  180. /// PN = PHI [I2, Latch], [NewPN, PreHeader]
  181. /// I1 = foo(PN)
  182. /// I2 = foo(I1)
  183. /// ...
  184. ///
  185. static bool isEpilogProfitable(Loop *L) {
  186. BasicBlock *PreHeader = L->getLoopPreheader();
  187. BasicBlock *Header = L->getHeader();
  188. assert(PreHeader && Header);
  189. for (const PHINode &PN : Header->phis()) {
  190. if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
  191. return true;
  192. }
  193. return false;
  194. }
  195. /// Perform some cleanup and simplifications on loops after unrolling. It is
  196. /// useful to simplify the IV's in the new loop, as well as do a quick
  197. /// simplify/dce pass of the instructions.
  198. void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
  199. ScalarEvolution *SE, DominatorTree *DT,
  200. AssumptionCache *AC,
  201. const TargetTransformInfo *TTI) {
  202. // Simplify any new induction variables in the partially unrolled loop.
  203. if (SE && SimplifyIVs) {
  204. SmallVector<WeakTrackingVH, 16> DeadInsts;
  205. simplifyLoopIVs(L, SE, DT, LI, TTI, DeadInsts);
  206. // Aggressively clean up dead instructions that simplifyLoopIVs already
  207. // identified. Any remaining should be cleaned up below.
  208. while (!DeadInsts.empty()) {
  209. Value *V = DeadInsts.pop_back_val();
  210. if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))
  211. RecursivelyDeleteTriviallyDeadInstructions(Inst);
  212. }
  213. }
  214. // At this point, the code is well formed. Perform constprop, instsimplify,
  215. // and dce.
  216. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  217. SmallVector<WeakTrackingVH, 16> DeadInsts;
  218. for (BasicBlock *BB : L->getBlocks()) {
  219. for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
  220. if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
  221. if (LI->replacementPreservesLCSSAForm(&Inst, V))
  222. Inst.replaceAllUsesWith(V);
  223. if (isInstructionTriviallyDead(&Inst))
  224. DeadInsts.emplace_back(&Inst);
  225. }
  226. // We can't do recursive deletion until we're done iterating, as we might
  227. // have a phi which (potentially indirectly) uses instructions later in
  228. // the block we're iterating through.
  229. RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
  230. }
  231. }
  232. /// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
  233. /// can only fail when the loop's latch block is not terminated by a conditional
  234. /// branch instruction. However, if the trip count (and multiple) are not known,
  235. /// loop unrolling will mostly produce more code that is no faster.
  236. ///
  237. /// If Runtime is true then UnrollLoop will try to insert a prologue or
  238. /// epilogue that ensures the latch has a trip multiple of Count. UnrollLoop
  239. /// will not runtime-unroll the loop if computing the run-time trip count will
  240. /// be expensive and AllowExpensiveTripCount is false.
  241. ///
  242. /// The LoopInfo Analysis that is passed will be kept consistent.
  243. ///
  244. /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
  245. /// DominatorTree if they are non-null.
  246. ///
  247. /// If RemainderLoop is non-null, it will receive the remainder loop (if
  248. /// required and not fully unrolled).
  249. LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
  250. ScalarEvolution *SE, DominatorTree *DT,
  251. AssumptionCache *AC,
  252. const TargetTransformInfo *TTI,
  253. OptimizationRemarkEmitter *ORE,
  254. bool PreserveLCSSA, Loop **RemainderLoop) {
  255. assert(DT && "DomTree is required");
  256. if (!L->getLoopPreheader()) {
  257. LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
  258. return LoopUnrollResult::Unmodified;
  259. }
  260. if (!L->getLoopLatch()) {
  261. LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
  262. return LoopUnrollResult::Unmodified;
  263. }
  264. // Loops with indirectbr cannot be cloned.
  265. if (!L->isSafeToClone()) {
  266. LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
  267. return LoopUnrollResult::Unmodified;
  268. }
  269. if (L->getHeader()->hasAddressTaken()) {
  270. // The loop-rotate pass can be helpful to avoid this in many cases.
  271. LLVM_DEBUG(
  272. dbgs() << " Won't unroll loop: address of header block is taken.\n");
  273. return LoopUnrollResult::Unmodified;
  274. }
  275. assert(ULO.Count > 0);
  276. // All these values should be taken only after peeling because they might have
  277. // changed.
  278. BasicBlock *Preheader = L->getLoopPreheader();
  279. BasicBlock *Header = L->getHeader();
  280. BasicBlock *LatchBlock = L->getLoopLatch();
  281. SmallVector<BasicBlock *, 4> ExitBlocks;
  282. L->getExitBlocks(ExitBlocks);
  283. std::vector<BasicBlock *> OriginalLoopBlocks = L->getBlocks();
  284. const unsigned MaxTripCount = SE->getSmallConstantMaxTripCount(L);
  285. const bool MaxOrZero = SE->isBackedgeTakenCountMaxOrZero(L);
  286. // Effectively "DCE" unrolled iterations that are beyond the max tripcount
  287. // and will never be executed.
  288. if (MaxTripCount && ULO.Count > MaxTripCount)
  289. ULO.Count = MaxTripCount;
  290. struct ExitInfo {
  291. unsigned TripCount;
  292. unsigned TripMultiple;
  293. unsigned BreakoutTrip;
  294. bool ExitOnTrue;
  295. BasicBlock *FirstExitingBlock = nullptr;
  296. SmallVector<BasicBlock *> ExitingBlocks;
  297. };
  298. DenseMap<BasicBlock *, ExitInfo> ExitInfos;
  299. SmallVector<BasicBlock *, 4> ExitingBlocks;
  300. L->getExitingBlocks(ExitingBlocks);
  301. for (auto *ExitingBlock : ExitingBlocks) {
  302. // The folding code is not prepared to deal with non-branch instructions
  303. // right now.
  304. auto *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
  305. if (!BI)
  306. continue;
  307. ExitInfo &Info = ExitInfos.try_emplace(ExitingBlock).first->second;
  308. Info.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
  309. Info.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
  310. if (Info.TripCount != 0) {
  311. Info.BreakoutTrip = Info.TripCount % ULO.Count;
  312. Info.TripMultiple = 0;
  313. } else {
  314. Info.BreakoutTrip = Info.TripMultiple =
  315. (unsigned)std::gcd(ULO.Count, Info.TripMultiple);
  316. }
  317. Info.ExitOnTrue = !L->contains(BI->getSuccessor(0));
  318. Info.ExitingBlocks.push_back(ExitingBlock);
  319. LLVM_DEBUG(dbgs() << " Exiting block %" << ExitingBlock->getName()
  320. << ": TripCount=" << Info.TripCount
  321. << ", TripMultiple=" << Info.TripMultiple
  322. << ", BreakoutTrip=" << Info.BreakoutTrip << "\n");
  323. }
  324. // Are we eliminating the loop control altogether? Note that we can know
  325. // we're eliminating the backedge without knowing exactly which iteration
  326. // of the unrolled body exits.
  327. const bool CompletelyUnroll = ULO.Count == MaxTripCount;
  328. const bool PreserveOnlyFirst = CompletelyUnroll && MaxOrZero;
  329. // There's no point in performing runtime unrolling if this unroll count
  330. // results in a full unroll.
  331. if (CompletelyUnroll)
  332. ULO.Runtime = false;
  333. // Go through all exits of L and see if there are any phi-nodes there. We just
  334. // conservatively assume that they're inserted to preserve LCSSA form, which
  335. // means that complete unrolling might break this form. We need to either fix
  336. // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
  337. // now we just recompute LCSSA for the outer loop, but it should be possible
  338. // to fix it in-place.
  339. bool NeedToFixLCSSA =
  340. PreserveLCSSA && CompletelyUnroll &&
  341. any_of(ExitBlocks,
  342. [](const BasicBlock *BB) { return isa<PHINode>(BB->begin()); });
  343. // The current loop unroll pass can unroll loops that have
  344. // (1) single latch; and
  345. // (2a) latch is unconditional; or
  346. // (2b) latch is conditional and is an exiting block
  347. // FIXME: The implementation can be extended to work with more complicated
  348. // cases, e.g. loops with multiple latches.
  349. BranchInst *LatchBI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
  350. // A conditional branch which exits the loop, which can be optimized to an
  351. // unconditional branch in the unrolled loop in some cases.
  352. bool LatchIsExiting = L->isLoopExiting(LatchBlock);
  353. if (!LatchBI || (LatchBI->isConditional() && !LatchIsExiting)) {
  354. LLVM_DEBUG(
  355. dbgs() << "Can't unroll; a conditional latch must exit the loop");
  356. return LoopUnrollResult::Unmodified;
  357. }
  358. // Loops containing convergent instructions cannot use runtime unrolling,
  359. // as the prologue/epilogue may add additional control-dependencies to
  360. // convergent operations.
  361. LLVM_DEBUG(
  362. {
  363. bool HasConvergent = false;
  364. for (auto &BB : L->blocks())
  365. for (auto &I : *BB)
  366. if (auto *CB = dyn_cast<CallBase>(&I))
  367. HasConvergent |= CB->isConvergent();
  368. assert((!HasConvergent || !ULO.Runtime) &&
  369. "Can't runtime unroll if loop contains a convergent operation.");
  370. });
  371. bool EpilogProfitability =
  372. UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
  373. : isEpilogProfitable(L);
  374. if (ULO.Runtime &&
  375. !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
  376. EpilogProfitability, ULO.UnrollRemainder,
  377. ULO.ForgetAllSCEV, LI, SE, DT, AC, TTI,
  378. PreserveLCSSA, RemainderLoop)) {
  379. if (ULO.Force)
  380. ULO.Runtime = false;
  381. else {
  382. LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "
  383. "generated when assuming runtime trip count\n");
  384. return LoopUnrollResult::Unmodified;
  385. }
  386. }
  387. using namespace ore;
  388. // Report the unrolling decision.
  389. if (CompletelyUnroll) {
  390. LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
  391. << " with trip count " << ULO.Count << "!\n");
  392. if (ORE)
  393. ORE->emit([&]() {
  394. return OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
  395. L->getHeader())
  396. << "completely unrolled loop with "
  397. << NV("UnrollCount", ULO.Count) << " iterations";
  398. });
  399. } else {
  400. LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "
  401. << ULO.Count);
  402. if (ULO.Runtime)
  403. LLVM_DEBUG(dbgs() << " with run-time trip count");
  404. LLVM_DEBUG(dbgs() << "!\n");
  405. if (ORE)
  406. ORE->emit([&]() {
  407. OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
  408. L->getHeader());
  409. Diag << "unrolled loop by a factor of " << NV("UnrollCount", ULO.Count);
  410. if (ULO.Runtime)
  411. Diag << " with run-time trip count";
  412. return Diag;
  413. });
  414. }
  415. // We are going to make changes to this loop. SCEV may be keeping cached info
  416. // about it, in particular about backedge taken count. The changes we make
  417. // are guaranteed to invalidate this information for our loop. It is tempting
  418. // to only invalidate the loop being unrolled, but it is incorrect as long as
  419. // all exiting branches from all inner loops have impact on the outer loops,
  420. // and if something changes inside them then any of outer loops may also
  421. // change. When we forget outermost loop, we also forget all contained loops
  422. // and this is what we need here.
  423. if (SE) {
  424. if (ULO.ForgetAllSCEV)
  425. SE->forgetAllLoops();
  426. else {
  427. SE->forgetTopmostLoop(L);
  428. SE->forgetBlockAndLoopDispositions();
  429. }
  430. }
  431. if (!LatchIsExiting)
  432. ++NumUnrolledNotLatch;
  433. // For the first iteration of the loop, we should use the precloned values for
  434. // PHI nodes. Insert associations now.
  435. ValueToValueMapTy LastValueMap;
  436. std::vector<PHINode*> OrigPHINode;
  437. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  438. OrigPHINode.push_back(cast<PHINode>(I));
  439. }
  440. std::vector<BasicBlock *> Headers;
  441. std::vector<BasicBlock *> Latches;
  442. Headers.push_back(Header);
  443. Latches.push_back(LatchBlock);
  444. // The current on-the-fly SSA update requires blocks to be processed in
  445. // reverse postorder so that LastValueMap contains the correct value at each
  446. // exit.
  447. LoopBlocksDFS DFS(L);
  448. DFS.perform(LI);
  449. // Stash the DFS iterators before adding blocks to the loop.
  450. LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
  451. LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
  452. std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
  453. // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
  454. // might break loop-simplified form for these loops (as they, e.g., would
  455. // share the same exit blocks). We'll keep track of loops for which we can
  456. // break this so that later we can re-simplify them.
  457. SmallSetVector<Loop *, 4> LoopsToSimplify;
  458. for (Loop *SubLoop : *L)
  459. LoopsToSimplify.insert(SubLoop);
  460. // When a FSDiscriminator is enabled, we don't need to add the multiply
  461. // factors to the discriminators.
  462. if (Header->getParent()->shouldEmitDebugInfoForProfiling() &&
  463. !EnableFSDiscriminator)
  464. for (BasicBlock *BB : L->getBlocks())
  465. for (Instruction &I : *BB)
  466. if (!isa<DbgInfoIntrinsic>(&I))
  467. if (const DILocation *DIL = I.getDebugLoc()) {
  468. auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
  469. if (NewDIL)
  470. I.setDebugLoc(*NewDIL);
  471. else
  472. LLVM_DEBUG(dbgs()
  473. << "Failed to create new discriminator: "
  474. << DIL->getFilename() << " Line: " << DIL->getLine());
  475. }
  476. // Identify what noalias metadata is inside the loop: if it is inside the
  477. // loop, the associated metadata must be cloned for each iteration.
  478. SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes;
  479. identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes);
  480. // We place the unrolled iterations immediately after the original loop
  481. // latch. This is a reasonable default placement if we don't have block
  482. // frequencies, and if we do, well the layout will be adjusted later.
  483. auto BlockInsertPt = std::next(LatchBlock->getIterator());
  484. for (unsigned It = 1; It != ULO.Count; ++It) {
  485. SmallVector<BasicBlock *, 8> NewBlocks;
  486. SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
  487. NewLoops[L] = L;
  488. for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
  489. ValueToValueMapTy VMap;
  490. BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
  491. Header->getParent()->insert(BlockInsertPt, New);
  492. assert((*BB != Header || LI->getLoopFor(*BB) == L) &&
  493. "Header should not be in a sub-loop");
  494. // Tell LI about New.
  495. const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
  496. if (OldLoop)
  497. LoopsToSimplify.insert(NewLoops[OldLoop]);
  498. if (*BB == Header)
  499. // Loop over all of the PHI nodes in the block, changing them to use
  500. // the incoming values from the previous block.
  501. for (PHINode *OrigPHI : OrigPHINode) {
  502. PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
  503. Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
  504. if (Instruction *InValI = dyn_cast<Instruction>(InVal))
  505. if (It > 1 && L->contains(InValI))
  506. InVal = LastValueMap[InValI];
  507. VMap[OrigPHI] = InVal;
  508. NewPHI->eraseFromParent();
  509. }
  510. // Update our running map of newest clones
  511. LastValueMap[*BB] = New;
  512. for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
  513. VI != VE; ++VI)
  514. LastValueMap[VI->first] = VI->second;
  515. // Add phi entries for newly created values to all exit blocks.
  516. for (BasicBlock *Succ : successors(*BB)) {
  517. if (L->contains(Succ))
  518. continue;
  519. for (PHINode &PHI : Succ->phis()) {
  520. Value *Incoming = PHI.getIncomingValueForBlock(*BB);
  521. ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
  522. if (It != LastValueMap.end())
  523. Incoming = It->second;
  524. PHI.addIncoming(Incoming, New);
  525. SE->forgetValue(&PHI);
  526. }
  527. }
  528. // Keep track of new headers and latches as we create them, so that
  529. // we can insert the proper branches later.
  530. if (*BB == Header)
  531. Headers.push_back(New);
  532. if (*BB == LatchBlock)
  533. Latches.push_back(New);
  534. // Keep track of the exiting block and its successor block contained in
  535. // the loop for the current iteration.
  536. auto ExitInfoIt = ExitInfos.find(*BB);
  537. if (ExitInfoIt != ExitInfos.end())
  538. ExitInfoIt->second.ExitingBlocks.push_back(New);
  539. NewBlocks.push_back(New);
  540. UnrolledLoopBlocks.push_back(New);
  541. // Update DomTree: since we just copy the loop body, and each copy has a
  542. // dedicated entry block (copy of the header block), this header's copy
  543. // dominates all copied blocks. That means, dominance relations in the
  544. // copied body are the same as in the original body.
  545. if (*BB == Header)
  546. DT->addNewBlock(New, Latches[It - 1]);
  547. else {
  548. auto BBDomNode = DT->getNode(*BB);
  549. auto BBIDom = BBDomNode->getIDom();
  550. BasicBlock *OriginalBBIDom = BBIDom->getBlock();
  551. DT->addNewBlock(
  552. New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
  553. }
  554. }
  555. // Remap all instructions in the most recent iteration
  556. remapInstructionsInBlocks(NewBlocks, LastValueMap);
  557. for (BasicBlock *NewBlock : NewBlocks)
  558. for (Instruction &I : *NewBlock)
  559. if (auto *II = dyn_cast<AssumeInst>(&I))
  560. AC->registerAssumption(II);
  561. {
  562. // Identify what other metadata depends on the cloned version. After
  563. // cloning, replace the metadata with the corrected version for both
  564. // memory instructions and noalias intrinsics.
  565. std::string ext = (Twine("It") + Twine(It)).str();
  566. cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks,
  567. Header->getContext(), ext);
  568. }
  569. }
  570. // Loop over the PHI nodes in the original block, setting incoming values.
  571. for (PHINode *PN : OrigPHINode) {
  572. if (CompletelyUnroll) {
  573. PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
  574. PN->eraseFromParent();
  575. } else if (ULO.Count > 1) {
  576. Value *InVal = PN->removeIncomingValue(LatchBlock, false);
  577. // If this value was defined in the loop, take the value defined by the
  578. // last iteration of the loop.
  579. if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
  580. if (L->contains(InValI))
  581. InVal = LastValueMap[InVal];
  582. }
  583. assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
  584. PN->addIncoming(InVal, Latches.back());
  585. }
  586. }
  587. // Connect latches of the unrolled iterations to the headers of the next
  588. // iteration. Currently they point to the header of the same iteration.
  589. for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
  590. unsigned j = (i + 1) % e;
  591. Latches[i]->getTerminator()->replaceSuccessorWith(Headers[i], Headers[j]);
  592. }
  593. // Update dominators of blocks we might reach through exits.
  594. // Immediate dominator of such block might change, because we add more
  595. // routes which can lead to the exit: we can now reach it from the copied
  596. // iterations too.
  597. if (ULO.Count > 1) {
  598. for (auto *BB : OriginalLoopBlocks) {
  599. auto *BBDomNode = DT->getNode(BB);
  600. SmallVector<BasicBlock *, 16> ChildrenToUpdate;
  601. for (auto *ChildDomNode : BBDomNode->children()) {
  602. auto *ChildBB = ChildDomNode->getBlock();
  603. if (!L->contains(ChildBB))
  604. ChildrenToUpdate.push_back(ChildBB);
  605. }
  606. // The new idom of the block will be the nearest common dominator
  607. // of all copies of the previous idom. This is equivalent to the
  608. // nearest common dominator of the previous idom and the first latch,
  609. // which dominates all copies of the previous idom.
  610. BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
  611. for (auto *ChildBB : ChildrenToUpdate)
  612. DT->changeImmediateDominator(ChildBB, NewIDom);
  613. }
  614. }
  615. assert(!UnrollVerifyDomtree ||
  616. DT->verify(DominatorTree::VerificationLevel::Fast));
  617. SmallVector<DominatorTree::UpdateType> DTUpdates;
  618. auto SetDest = [&](BasicBlock *Src, bool WillExit, bool ExitOnTrue) {
  619. auto *Term = cast<BranchInst>(Src->getTerminator());
  620. const unsigned Idx = ExitOnTrue ^ WillExit;
  621. BasicBlock *Dest = Term->getSuccessor(Idx);
  622. BasicBlock *DeadSucc = Term->getSuccessor(1-Idx);
  623. // Remove predecessors from all non-Dest successors.
  624. DeadSucc->removePredecessor(Src, /* KeepOneInputPHIs */ true);
  625. // Replace the conditional branch with an unconditional one.
  626. BranchInst::Create(Dest, Term);
  627. Term->eraseFromParent();
  628. DTUpdates.emplace_back(DominatorTree::Delete, Src, DeadSucc);
  629. };
  630. auto WillExit = [&](const ExitInfo &Info, unsigned i, unsigned j,
  631. bool IsLatch) -> std::optional<bool> {
  632. if (CompletelyUnroll) {
  633. if (PreserveOnlyFirst) {
  634. if (i == 0)
  635. return std::nullopt;
  636. return j == 0;
  637. }
  638. // Complete (but possibly inexact) unrolling
  639. if (j == 0)
  640. return true;
  641. if (Info.TripCount && j != Info.TripCount)
  642. return false;
  643. return std::nullopt;
  644. }
  645. if (ULO.Runtime) {
  646. // If runtime unrolling inserts a prologue, information about non-latch
  647. // exits may be stale.
  648. if (IsLatch && j != 0)
  649. return false;
  650. return std::nullopt;
  651. }
  652. if (j != Info.BreakoutTrip &&
  653. (Info.TripMultiple == 0 || j % Info.TripMultiple != 0)) {
  654. // If we know the trip count or a multiple of it, we can safely use an
  655. // unconditional branch for some iterations.
  656. return false;
  657. }
  658. return std::nullopt;
  659. };
  660. // Fold branches for iterations where we know that they will exit or not
  661. // exit.
  662. for (auto &Pair : ExitInfos) {
  663. ExitInfo &Info = Pair.second;
  664. for (unsigned i = 0, e = Info.ExitingBlocks.size(); i != e; ++i) {
  665. // The branch destination.
  666. unsigned j = (i + 1) % e;
  667. bool IsLatch = Pair.first == LatchBlock;
  668. std::optional<bool> KnownWillExit = WillExit(Info, i, j, IsLatch);
  669. if (!KnownWillExit) {
  670. if (!Info.FirstExitingBlock)
  671. Info.FirstExitingBlock = Info.ExitingBlocks[i];
  672. continue;
  673. }
  674. // We don't fold known-exiting branches for non-latch exits here,
  675. // because this ensures that both all loop blocks and all exit blocks
  676. // remain reachable in the CFG.
  677. // TODO: We could fold these branches, but it would require much more
  678. // sophisticated updates to LoopInfo.
  679. if (*KnownWillExit && !IsLatch) {
  680. if (!Info.FirstExitingBlock)
  681. Info.FirstExitingBlock = Info.ExitingBlocks[i];
  682. continue;
  683. }
  684. SetDest(Info.ExitingBlocks[i], *KnownWillExit, Info.ExitOnTrue);
  685. }
  686. }
  687. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
  688. DomTreeUpdater *DTUToUse = &DTU;
  689. if (ExitingBlocks.size() == 1 && ExitInfos.size() == 1) {
  690. // Manually update the DT if there's a single exiting node. In that case
  691. // there's a single exit node and it is sufficient to update the nodes
  692. // immediately dominated by the original exiting block. They will become
  693. // dominated by the first exiting block that leaves the loop after
  694. // unrolling. Note that the CFG inside the loop does not change, so there's
  695. // no need to update the DT inside the unrolled loop.
  696. DTUToUse = nullptr;
  697. auto &[OriginalExit, Info] = *ExitInfos.begin();
  698. if (!Info.FirstExitingBlock)
  699. Info.FirstExitingBlock = Info.ExitingBlocks.back();
  700. for (auto *C : to_vector(DT->getNode(OriginalExit)->children())) {
  701. if (L->contains(C->getBlock()))
  702. continue;
  703. C->setIDom(DT->getNode(Info.FirstExitingBlock));
  704. }
  705. } else {
  706. DTU.applyUpdates(DTUpdates);
  707. }
  708. // When completely unrolling, the last latch becomes unreachable.
  709. if (!LatchIsExiting && CompletelyUnroll) {
  710. // There is no need to update the DT here, because there must be a unique
  711. // latch. Hence if the latch is not exiting it must directly branch back to
  712. // the original loop header and does not dominate any nodes.
  713. assert(LatchBlock->getSingleSuccessor() && "Loop with multiple latches?");
  714. changeToUnreachable(Latches.back()->getTerminator(), PreserveLCSSA);
  715. }
  716. // Merge adjacent basic blocks, if possible.
  717. for (BasicBlock *Latch : Latches) {
  718. BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
  719. assert((Term ||
  720. (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&
  721. "Need a branch as terminator, except when fully unrolling with "
  722. "unconditional latch");
  723. if (Term && Term->isUnconditional()) {
  724. BasicBlock *Dest = Term->getSuccessor(0);
  725. BasicBlock *Fold = Dest->getUniquePredecessor();
  726. if (MergeBlockIntoPredecessor(Dest, /*DTU=*/DTUToUse, LI,
  727. /*MSSAU=*/nullptr, /*MemDep=*/nullptr,
  728. /*PredecessorWithTwoSuccessors=*/false,
  729. DTUToUse ? nullptr : DT)) {
  730. // Dest has been folded into Fold. Update our worklists accordingly.
  731. std::replace(Latches.begin(), Latches.end(), Dest, Fold);
  732. llvm::erase_value(UnrolledLoopBlocks, Dest);
  733. }
  734. }
  735. }
  736. if (DTUToUse) {
  737. // Apply updates to the DomTree.
  738. DT = &DTU.getDomTree();
  739. }
  740. assert(!UnrollVerifyDomtree ||
  741. DT->verify(DominatorTree::VerificationLevel::Fast));
  742. // At this point, the code is well formed. We now simplify the unrolled loop,
  743. // doing constant propagation and dead code elimination as we go.
  744. simplifyLoopAfterUnroll(L, !CompletelyUnroll && ULO.Count > 1, LI, SE, DT, AC,
  745. TTI);
  746. NumCompletelyUnrolled += CompletelyUnroll;
  747. ++NumUnrolled;
  748. Loop *OuterL = L->getParentLoop();
  749. // Update LoopInfo if the loop is completely removed.
  750. if (CompletelyUnroll)
  751. LI->erase(L);
  752. // LoopInfo should not be valid, confirm that.
  753. if (UnrollVerifyLoopInfo)
  754. LI->verify(*DT);
  755. // After complete unrolling most of the blocks should be contained in OuterL.
  756. // However, some of them might happen to be out of OuterL (e.g. if they
  757. // precede a loop exit). In this case we might need to insert PHI nodes in
  758. // order to preserve LCSSA form.
  759. // We don't need to check this if we already know that we need to fix LCSSA
  760. // form.
  761. // TODO: For now we just recompute LCSSA for the outer loop in this case, but
  762. // it should be possible to fix it in-place.
  763. if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
  764. NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
  765. // Make sure that loop-simplify form is preserved. We want to simplify
  766. // at least one layer outside of the loop that was unrolled so that any
  767. // changes to the parent loop exposed by the unrolling are considered.
  768. if (OuterL) {
  769. // OuterL includes all loops for which we can break loop-simplify, so
  770. // it's sufficient to simplify only it (it'll recursively simplify inner
  771. // loops too).
  772. if (NeedToFixLCSSA) {
  773. // LCSSA must be performed on the outermost affected loop. The unrolled
  774. // loop's last loop latch is guaranteed to be in the outermost loop
  775. // after LoopInfo's been updated by LoopInfo::erase.
  776. Loop *LatchLoop = LI->getLoopFor(Latches.back());
  777. Loop *FixLCSSALoop = OuterL;
  778. if (!FixLCSSALoop->contains(LatchLoop))
  779. while (FixLCSSALoop->getParentLoop() != LatchLoop)
  780. FixLCSSALoop = FixLCSSALoop->getParentLoop();
  781. formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
  782. } else if (PreserveLCSSA) {
  783. assert(OuterL->isLCSSAForm(*DT) &&
  784. "Loops should be in LCSSA form after loop-unroll.");
  785. }
  786. // TODO: That potentially might be compile-time expensive. We should try
  787. // to fix the loop-simplified form incrementally.
  788. simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
  789. } else {
  790. // Simplify loops for which we might've broken loop-simplify form.
  791. for (Loop *SubLoop : LoopsToSimplify)
  792. simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
  793. }
  794. return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
  795. : LoopUnrollResult::PartiallyUnrolled;
  796. }
  797. /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
  798. /// node with the given name (for example, "llvm.loop.unroll.count"). If no
  799. /// such metadata node exists, then nullptr is returned.
  800. MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
  801. // First operand should refer to the loop id itself.
  802. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  803. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  804. for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
  805. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  806. if (!MD)
  807. continue;
  808. MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  809. if (!S)
  810. continue;
  811. if (Name.equals(S->getString()))
  812. return MD;
  813. }
  814. return nullptr;
  815. }