LoopSimplify.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
  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 pass performs several transformations to transform natural loops into a
  10. // simpler form, which makes subsequent analyses and transformations simpler and
  11. // more effective.
  12. //
  13. // Loop pre-header insertion guarantees that there is a single, non-critical
  14. // entry edge from outside of the loop to the loop header. This simplifies a
  15. // number of analyses and transformations, such as LICM.
  16. //
  17. // Loop exit-block insertion guarantees that all exit blocks from the loop
  18. // (blocks which are outside of the loop that have predecessors inside of the
  19. // loop) only have predecessors from inside of the loop (and are thus dominated
  20. // by the loop header). This simplifies transformations such as store-sinking
  21. // that are built into LICM.
  22. //
  23. // This pass also guarantees that loops will have exactly one backedge.
  24. //
  25. // Indirectbr instructions introduce several complications. If the loop
  26. // contains or is entered by an indirectbr instruction, it may not be possible
  27. // to transform the loop and make these guarantees. Client code should check
  28. // that these conditions are true before relying on them.
  29. //
  30. // Similar complications arise from callbr instructions, particularly in
  31. // asm-goto where blockaddress expressions are used.
  32. //
  33. // Note that the simplifycfg pass will clean up blocks which are split out but
  34. // end up being unnecessary, so usage of this pass should not pessimize
  35. // generated code.
  36. //
  37. // This pass obviously modifies the CFG, but updates loop information and
  38. // dominator information.
  39. //
  40. //===----------------------------------------------------------------------===//
  41. #include "llvm/Transforms/Utils/LoopSimplify.h"
  42. #include "llvm/ADT/DepthFirstIterator.h"
  43. #include "llvm/ADT/SetOperations.h"
  44. #include "llvm/ADT/SetVector.h"
  45. #include "llvm/ADT/SmallVector.h"
  46. #include "llvm/ADT/Statistic.h"
  47. #include "llvm/Analysis/AliasAnalysis.h"
  48. #include "llvm/Analysis/AssumptionCache.h"
  49. #include "llvm/Analysis/BasicAliasAnalysis.h"
  50. #include "llvm/Analysis/BranchProbabilityInfo.h"
  51. #include "llvm/Analysis/DependenceAnalysis.h"
  52. #include "llvm/Analysis/GlobalsModRef.h"
  53. #include "llvm/Analysis/InstructionSimplify.h"
  54. #include "llvm/Analysis/LoopInfo.h"
  55. #include "llvm/Analysis/MemorySSA.h"
  56. #include "llvm/Analysis/MemorySSAUpdater.h"
  57. #include "llvm/Analysis/ScalarEvolution.h"
  58. #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
  59. #include "llvm/IR/CFG.h"
  60. #include "llvm/IR/Constants.h"
  61. #include "llvm/IR/DataLayout.h"
  62. #include "llvm/IR/Dominators.h"
  63. #include "llvm/IR/Function.h"
  64. #include "llvm/IR/Instructions.h"
  65. #include "llvm/IR/IntrinsicInst.h"
  66. #include "llvm/IR/LLVMContext.h"
  67. #include "llvm/IR/Module.h"
  68. #include "llvm/IR/Type.h"
  69. #include "llvm/InitializePasses.h"
  70. #include "llvm/Support/Debug.h"
  71. #include "llvm/Support/raw_ostream.h"
  72. #include "llvm/Transforms/Utils.h"
  73. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  74. #include "llvm/Transforms/Utils/Local.h"
  75. #include "llvm/Transforms/Utils/LoopUtils.h"
  76. using namespace llvm;
  77. #define DEBUG_TYPE "loop-simplify"
  78. STATISTIC(NumNested , "Number of nested loops split out");
  79. // If the block isn't already, move the new block to right after some 'outside
  80. // block' block. This prevents the preheader from being placed inside the loop
  81. // body, e.g. when the loop hasn't been rotated.
  82. static void placeSplitBlockCarefully(BasicBlock *NewBB,
  83. SmallVectorImpl<BasicBlock *> &SplitPreds,
  84. Loop *L) {
  85. // Check to see if NewBB is already well placed.
  86. Function::iterator BBI = --NewBB->getIterator();
  87. for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
  88. if (&*BBI == SplitPreds[i])
  89. return;
  90. }
  91. // If it isn't already after an outside block, move it after one. This is
  92. // always good as it makes the uncond branch from the outside block into a
  93. // fall-through.
  94. // Figure out *which* outside block to put this after. Prefer an outside
  95. // block that neighbors a BB actually in the loop.
  96. BasicBlock *FoundBB = nullptr;
  97. for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
  98. Function::iterator BBI = SplitPreds[i]->getIterator();
  99. if (++BBI != NewBB->getParent()->end() && L->contains(&*BBI)) {
  100. FoundBB = SplitPreds[i];
  101. break;
  102. }
  103. }
  104. // If our heuristic for a *good* bb to place this after doesn't find
  105. // anything, just pick something. It's likely better than leaving it within
  106. // the loop.
  107. if (!FoundBB)
  108. FoundBB = SplitPreds[0];
  109. NewBB->moveAfter(FoundBB);
  110. }
  111. /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
  112. /// preheader, this method is called to insert one. This method has two phases:
  113. /// preheader insertion and analysis updating.
  114. ///
  115. BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, DominatorTree *DT,
  116. LoopInfo *LI, MemorySSAUpdater *MSSAU,
  117. bool PreserveLCSSA) {
  118. BasicBlock *Header = L->getHeader();
  119. // Compute the set of predecessors of the loop that are not in the loop.
  120. SmallVector<BasicBlock*, 8> OutsideBlocks;
  121. for (BasicBlock *P : predecessors(Header)) {
  122. if (!L->contains(P)) { // Coming in from outside the loop?
  123. // If the loop is branched to from an indirect terminator, we won't
  124. // be able to fully transform the loop, because it prohibits
  125. // edge splitting.
  126. if (P->getTerminator()->isIndirectTerminator())
  127. return nullptr;
  128. // Keep track of it.
  129. OutsideBlocks.push_back(P);
  130. }
  131. }
  132. // Split out the loop pre-header.
  133. BasicBlock *PreheaderBB;
  134. PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader", DT,
  135. LI, MSSAU, PreserveLCSSA);
  136. if (!PreheaderBB)
  137. return nullptr;
  138. LLVM_DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
  139. << PreheaderBB->getName() << "\n");
  140. // Make sure that NewBB is put someplace intelligent, which doesn't mess up
  141. // code layout too horribly.
  142. placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
  143. return PreheaderBB;
  144. }
  145. /// Add the specified block, and all of its predecessors, to the specified set,
  146. /// if it's not already in there. Stop predecessor traversal when we reach
  147. /// StopBlock.
  148. static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
  149. SmallPtrSetImpl<BasicBlock *> &Blocks) {
  150. SmallVector<BasicBlock *, 8> Worklist;
  151. Worklist.push_back(InputBB);
  152. do {
  153. BasicBlock *BB = Worklist.pop_back_val();
  154. if (Blocks.insert(BB).second && BB != StopBlock)
  155. // If BB is not already processed and it is not a stop block then
  156. // insert its predecessor in the work list
  157. append_range(Worklist, predecessors(BB));
  158. } while (!Worklist.empty());
  159. }
  160. /// The first part of loop-nestification is to find a PHI node that tells
  161. /// us how to partition the loops.
  162. static PHINode *findPHIToPartitionLoops(Loop *L, DominatorTree *DT,
  163. AssumptionCache *AC) {
  164. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  165. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
  166. PHINode *PN = cast<PHINode>(I);
  167. ++I;
  168. if (Value *V = SimplifyInstruction(PN, {DL, nullptr, DT, AC})) {
  169. // This is a degenerate PHI already, don't modify it!
  170. PN->replaceAllUsesWith(V);
  171. PN->eraseFromParent();
  172. continue;
  173. }
  174. // Scan this PHI node looking for a use of the PHI node by itself.
  175. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  176. if (PN->getIncomingValue(i) == PN &&
  177. L->contains(PN->getIncomingBlock(i)))
  178. // We found something tasty to remove.
  179. return PN;
  180. }
  181. return nullptr;
  182. }
  183. /// If this loop has multiple backedges, try to pull one of them out into
  184. /// a nested loop.
  185. ///
  186. /// This is important for code that looks like
  187. /// this:
  188. ///
  189. /// Loop:
  190. /// ...
  191. /// br cond, Loop, Next
  192. /// ...
  193. /// br cond2, Loop, Out
  194. ///
  195. /// To identify this common case, we look at the PHI nodes in the header of the
  196. /// loop. PHI nodes with unchanging values on one backedge correspond to values
  197. /// that change in the "outer" loop, but not in the "inner" loop.
  198. ///
  199. /// If we are able to separate out a loop, return the new outer loop that was
  200. /// created.
  201. ///
  202. static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader,
  203. DominatorTree *DT, LoopInfo *LI,
  204. ScalarEvolution *SE, bool PreserveLCSSA,
  205. AssumptionCache *AC, MemorySSAUpdater *MSSAU) {
  206. // Don't try to separate loops without a preheader.
  207. if (!Preheader)
  208. return nullptr;
  209. // Treat the presence of convergent functions conservatively. The
  210. // transformation is invalid if calls to certain convergent
  211. // functions (like an AMDGPU barrier) get included in the resulting
  212. // inner loop. But blocks meant for the inner loop will be
  213. // identified later at a point where it's too late to abort the
  214. // transformation. Also, the convergent attribute is not really
  215. // sufficient to express the semantics of functions that are
  216. // affected by this transformation. So we choose to back off if such
  217. // a function call is present until a better alternative becomes
  218. // available. This is similar to the conservative treatment of
  219. // convergent function calls in GVNHoist and JumpThreading.
  220. for (auto BB : L->blocks()) {
  221. for (auto &II : *BB) {
  222. if (auto CI = dyn_cast<CallBase>(&II)) {
  223. if (CI->isConvergent()) {
  224. return nullptr;
  225. }
  226. }
  227. }
  228. }
  229. // The header is not a landing pad; preheader insertion should ensure this.
  230. BasicBlock *Header = L->getHeader();
  231. assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
  232. PHINode *PN = findPHIToPartitionLoops(L, DT, AC);
  233. if (!PN) return nullptr; // No known way to partition.
  234. // Pull out all predecessors that have varying values in the loop. This
  235. // handles the case when a PHI node has multiple instances of itself as
  236. // arguments.
  237. SmallVector<BasicBlock*, 8> OuterLoopPreds;
  238. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  239. if (PN->getIncomingValue(i) != PN ||
  240. !L->contains(PN->getIncomingBlock(i))) {
  241. // We can't split indirect control flow edges.
  242. if (PN->getIncomingBlock(i)->getTerminator()->isIndirectTerminator())
  243. return nullptr;
  244. OuterLoopPreds.push_back(PN->getIncomingBlock(i));
  245. }
  246. }
  247. LLVM_DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
  248. // If ScalarEvolution is around and knows anything about values in
  249. // this loop, tell it to forget them, because we're about to
  250. // substantially change it.
  251. if (SE)
  252. SE->forgetLoop(L);
  253. BasicBlock *NewBB = SplitBlockPredecessors(Header, OuterLoopPreds, ".outer",
  254. DT, LI, MSSAU, PreserveLCSSA);
  255. // Make sure that NewBB is put someplace intelligent, which doesn't mess up
  256. // code layout too horribly.
  257. placeSplitBlockCarefully(NewBB, OuterLoopPreds, L);
  258. // Create the new outer loop.
  259. Loop *NewOuter = LI->AllocateLoop();
  260. // Change the parent loop to use the outer loop as its child now.
  261. if (Loop *Parent = L->getParentLoop())
  262. Parent->replaceChildLoopWith(L, NewOuter);
  263. else
  264. LI->changeTopLevelLoop(L, NewOuter);
  265. // L is now a subloop of our outer loop.
  266. NewOuter->addChildLoop(L);
  267. for (BasicBlock *BB : L->blocks())
  268. NewOuter->addBlockEntry(BB);
  269. // Now reset the header in L, which had been moved by
  270. // SplitBlockPredecessors for the outer loop.
  271. L->moveToHeader(Header);
  272. // Determine which blocks should stay in L and which should be moved out to
  273. // the Outer loop now.
  274. SmallPtrSet<BasicBlock *, 4> BlocksInL;
  275. for (BasicBlock *P : predecessors(Header)) {
  276. if (DT->dominates(Header, P))
  277. addBlockAndPredsToSet(P, Header, BlocksInL);
  278. }
  279. // Scan all of the loop children of L, moving them to OuterLoop if they are
  280. // not part of the inner loop.
  281. const std::vector<Loop*> &SubLoops = L->getSubLoops();
  282. for (size_t I = 0; I != SubLoops.size(); )
  283. if (BlocksInL.count(SubLoops[I]->getHeader()))
  284. ++I; // Loop remains in L
  285. else
  286. NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
  287. SmallVector<BasicBlock *, 8> OuterLoopBlocks;
  288. OuterLoopBlocks.push_back(NewBB);
  289. // Now that we know which blocks are in L and which need to be moved to
  290. // OuterLoop, move any blocks that need it.
  291. for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
  292. BasicBlock *BB = L->getBlocks()[i];
  293. if (!BlocksInL.count(BB)) {
  294. // Move this block to the parent, updating the exit blocks sets
  295. L->removeBlockFromLoop(BB);
  296. if ((*LI)[BB] == L) {
  297. LI->changeLoopFor(BB, NewOuter);
  298. OuterLoopBlocks.push_back(BB);
  299. }
  300. --i;
  301. }
  302. }
  303. // Split edges to exit blocks from the inner loop, if they emerged in the
  304. // process of separating the outer one.
  305. formDedicatedExitBlocks(L, DT, LI, MSSAU, PreserveLCSSA);
  306. if (PreserveLCSSA) {
  307. // Fix LCSSA form for L. Some values, which previously were only used inside
  308. // L, can now be used in NewOuter loop. We need to insert phi-nodes for them
  309. // in corresponding exit blocks.
  310. // We don't need to form LCSSA recursively, because there cannot be uses
  311. // inside a newly created loop of defs from inner loops as those would
  312. // already be a use of an LCSSA phi node.
  313. formLCSSA(*L, *DT, LI, SE);
  314. assert(NewOuter->isRecursivelyLCSSAForm(*DT, *LI) &&
  315. "LCSSA is broken after separating nested loops!");
  316. }
  317. return NewOuter;
  318. }
  319. /// This method is called when the specified loop has more than one
  320. /// backedge in it.
  321. ///
  322. /// If this occurs, revector all of these backedges to target a new basic block
  323. /// and have that block branch to the loop header. This ensures that loops
  324. /// have exactly one backedge.
  325. static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader,
  326. DominatorTree *DT, LoopInfo *LI,
  327. MemorySSAUpdater *MSSAU) {
  328. assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
  329. // Get information about the loop
  330. BasicBlock *Header = L->getHeader();
  331. Function *F = Header->getParent();
  332. // Unique backedge insertion currently depends on having a preheader.
  333. if (!Preheader)
  334. return nullptr;
  335. // The header is not an EH pad; preheader insertion should ensure this.
  336. assert(!Header->isEHPad() && "Can't insert backedge to EH pad");
  337. // Figure out which basic blocks contain back-edges to the loop header.
  338. std::vector<BasicBlock*> BackedgeBlocks;
  339. for (BasicBlock *P : predecessors(Header)) {
  340. // Indirect edges cannot be split, so we must fail if we find one.
  341. if (P->getTerminator()->isIndirectTerminator())
  342. return nullptr;
  343. if (P != Preheader) BackedgeBlocks.push_back(P);
  344. }
  345. // Create and insert the new backedge block...
  346. BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
  347. Header->getName() + ".backedge", F);
  348. BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
  349. BETerminator->setDebugLoc(Header->getFirstNonPHI()->getDebugLoc());
  350. LLVM_DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
  351. << BEBlock->getName() << "\n");
  352. // Move the new backedge block to right after the last backedge block.
  353. Function::iterator InsertPos = ++BackedgeBlocks.back()->getIterator();
  354. F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
  355. // Now that the block has been inserted into the function, create PHI nodes in
  356. // the backedge block which correspond to any PHI nodes in the header block.
  357. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  358. PHINode *PN = cast<PHINode>(I);
  359. PHINode *NewPN = PHINode::Create(PN->getType(), BackedgeBlocks.size(),
  360. PN->getName()+".be", BETerminator);
  361. // Loop over the PHI node, moving all entries except the one for the
  362. // preheader over to the new PHI node.
  363. unsigned PreheaderIdx = ~0U;
  364. bool HasUniqueIncomingValue = true;
  365. Value *UniqueValue = nullptr;
  366. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  367. BasicBlock *IBB = PN->getIncomingBlock(i);
  368. Value *IV = PN->getIncomingValue(i);
  369. if (IBB == Preheader) {
  370. PreheaderIdx = i;
  371. } else {
  372. NewPN->addIncoming(IV, IBB);
  373. if (HasUniqueIncomingValue) {
  374. if (!UniqueValue)
  375. UniqueValue = IV;
  376. else if (UniqueValue != IV)
  377. HasUniqueIncomingValue = false;
  378. }
  379. }
  380. }
  381. // Delete all of the incoming values from the old PN except the preheader's
  382. assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
  383. if (PreheaderIdx != 0) {
  384. PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
  385. PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
  386. }
  387. // Nuke all entries except the zero'th.
  388. for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
  389. PN->removeIncomingValue(e-i, false);
  390. // Finally, add the newly constructed PHI node as the entry for the BEBlock.
  391. PN->addIncoming(NewPN, BEBlock);
  392. // As an optimization, if all incoming values in the new PhiNode (which is a
  393. // subset of the incoming values of the old PHI node) have the same value,
  394. // eliminate the PHI Node.
  395. if (HasUniqueIncomingValue) {
  396. NewPN->replaceAllUsesWith(UniqueValue);
  397. BEBlock->getInstList().erase(NewPN);
  398. }
  399. }
  400. // Now that all of the PHI nodes have been inserted and adjusted, modify the
  401. // backedge blocks to jump to the BEBlock instead of the header.
  402. // If one of the backedges has llvm.loop metadata attached, we remove
  403. // it from the backedge and add it to BEBlock.
  404. unsigned LoopMDKind = BEBlock->getContext().getMDKindID("llvm.loop");
  405. MDNode *LoopMD = nullptr;
  406. for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
  407. Instruction *TI = BackedgeBlocks[i]->getTerminator();
  408. if (!LoopMD)
  409. LoopMD = TI->getMetadata(LoopMDKind);
  410. TI->setMetadata(LoopMDKind, nullptr);
  411. TI->replaceSuccessorWith(Header, BEBlock);
  412. }
  413. BEBlock->getTerminator()->setMetadata(LoopMDKind, LoopMD);
  414. //===--- Update all analyses which we must preserve now -----------------===//
  415. // Update Loop Information - we know that this block is now in the current
  416. // loop and all parent loops.
  417. L->addBasicBlockToLoop(BEBlock, *LI);
  418. // Update dominator information
  419. DT->splitBlock(BEBlock);
  420. if (MSSAU)
  421. MSSAU->updatePhisWhenInsertingUniqueBackedgeBlock(Header, Preheader,
  422. BEBlock);
  423. return BEBlock;
  424. }
  425. /// Simplify one loop and queue further loops for simplification.
  426. static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist,
  427. DominatorTree *DT, LoopInfo *LI,
  428. ScalarEvolution *SE, AssumptionCache *AC,
  429. MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
  430. bool Changed = false;
  431. if (MSSAU && VerifyMemorySSA)
  432. MSSAU->getMemorySSA()->verifyMemorySSA();
  433. ReprocessLoop:
  434. // Check to see that no blocks (other than the header) in this loop have
  435. // predecessors that are not in the loop. This is not valid for natural
  436. // loops, but can occur if the blocks are unreachable. Since they are
  437. // unreachable we can just shamelessly delete those CFG edges!
  438. for (BasicBlock *BB : L->blocks()) {
  439. if (BB == L->getHeader())
  440. continue;
  441. SmallPtrSet<BasicBlock*, 4> BadPreds;
  442. for (BasicBlock *P : predecessors(BB))
  443. if (!L->contains(P))
  444. BadPreds.insert(P);
  445. // Delete each unique out-of-loop (and thus dead) predecessor.
  446. for (BasicBlock *P : BadPreds) {
  447. LLVM_DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
  448. << P->getName() << "\n");
  449. // Zap the dead pred's terminator and replace it with unreachable.
  450. Instruction *TI = P->getTerminator();
  451. changeToUnreachable(TI, PreserveLCSSA,
  452. /*DTU=*/nullptr, MSSAU);
  453. Changed = true;
  454. }
  455. }
  456. if (MSSAU && VerifyMemorySSA)
  457. MSSAU->getMemorySSA()->verifyMemorySSA();
  458. // If there are exiting blocks with branches on undef, resolve the undef in
  459. // the direction which will exit the loop. This will help simplify loop
  460. // trip count computations.
  461. SmallVector<BasicBlock*, 8> ExitingBlocks;
  462. L->getExitingBlocks(ExitingBlocks);
  463. for (BasicBlock *ExitingBlock : ExitingBlocks)
  464. if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
  465. if (BI->isConditional()) {
  466. if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
  467. LLVM_DEBUG(dbgs()
  468. << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
  469. << ExitingBlock->getName() << "\n");
  470. BI->setCondition(ConstantInt::get(Cond->getType(),
  471. !L->contains(BI->getSuccessor(0))));
  472. Changed = true;
  473. }
  474. }
  475. // Does the loop already have a preheader? If so, don't insert one.
  476. BasicBlock *Preheader = L->getLoopPreheader();
  477. if (!Preheader) {
  478. Preheader = InsertPreheaderForLoop(L, DT, LI, MSSAU, PreserveLCSSA);
  479. if (Preheader)
  480. Changed = true;
  481. }
  482. // Next, check to make sure that all exit nodes of the loop only have
  483. // predecessors that are inside of the loop. This check guarantees that the
  484. // loop preheader/header will dominate the exit blocks. If the exit block has
  485. // predecessors from outside of the loop, split the edge now.
  486. if (formDedicatedExitBlocks(L, DT, LI, MSSAU, PreserveLCSSA))
  487. Changed = true;
  488. if (MSSAU && VerifyMemorySSA)
  489. MSSAU->getMemorySSA()->verifyMemorySSA();
  490. // If the header has more than two predecessors at this point (from the
  491. // preheader and from multiple backedges), we must adjust the loop.
  492. BasicBlock *LoopLatch = L->getLoopLatch();
  493. if (!LoopLatch) {
  494. // If this is really a nested loop, rip it out into a child loop. Don't do
  495. // this for loops with a giant number of backedges, just factor them into a
  496. // common backedge instead.
  497. if (L->getNumBackEdges() < 8) {
  498. if (Loop *OuterL = separateNestedLoop(L, Preheader, DT, LI, SE,
  499. PreserveLCSSA, AC, MSSAU)) {
  500. ++NumNested;
  501. // Enqueue the outer loop as it should be processed next in our
  502. // depth-first nest walk.
  503. Worklist.push_back(OuterL);
  504. // This is a big restructuring change, reprocess the whole loop.
  505. Changed = true;
  506. // GCC doesn't tail recursion eliminate this.
  507. // FIXME: It isn't clear we can't rely on LLVM to TRE this.
  508. goto ReprocessLoop;
  509. }
  510. }
  511. // If we either couldn't, or didn't want to, identify nesting of the loops,
  512. // insert a new block that all backedges target, then make it jump to the
  513. // loop header.
  514. LoopLatch = insertUniqueBackedgeBlock(L, Preheader, DT, LI, MSSAU);
  515. if (LoopLatch)
  516. Changed = true;
  517. }
  518. if (MSSAU && VerifyMemorySSA)
  519. MSSAU->getMemorySSA()->verifyMemorySSA();
  520. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  521. // Scan over the PHI nodes in the loop header. Since they now have only two
  522. // incoming values (the loop is canonicalized), we may have simplified the PHI
  523. // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
  524. PHINode *PN;
  525. for (BasicBlock::iterator I = L->getHeader()->begin();
  526. (PN = dyn_cast<PHINode>(I++)); )
  527. if (Value *V = SimplifyInstruction(PN, {DL, nullptr, DT, AC})) {
  528. if (SE) SE->forgetValue(PN);
  529. if (!PreserveLCSSA || LI->replacementPreservesLCSSAForm(PN, V)) {
  530. PN->replaceAllUsesWith(V);
  531. PN->eraseFromParent();
  532. Changed = true;
  533. }
  534. }
  535. // If this loop has multiple exits and the exits all go to the same
  536. // block, attempt to merge the exits. This helps several passes, such
  537. // as LoopRotation, which do not support loops with multiple exits.
  538. // SimplifyCFG also does this (and this code uses the same utility
  539. // function), however this code is loop-aware, where SimplifyCFG is
  540. // not. That gives it the advantage of being able to hoist
  541. // loop-invariant instructions out of the way to open up more
  542. // opportunities, and the disadvantage of having the responsibility
  543. // to preserve dominator information.
  544. auto HasUniqueExitBlock = [&]() {
  545. BasicBlock *UniqueExit = nullptr;
  546. for (auto *ExitingBB : ExitingBlocks)
  547. for (auto *SuccBB : successors(ExitingBB)) {
  548. if (L->contains(SuccBB))
  549. continue;
  550. if (!UniqueExit)
  551. UniqueExit = SuccBB;
  552. else if (UniqueExit != SuccBB)
  553. return false;
  554. }
  555. return true;
  556. };
  557. if (HasUniqueExitBlock()) {
  558. for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
  559. BasicBlock *ExitingBlock = ExitingBlocks[i];
  560. if (!ExitingBlock->getSinglePredecessor()) continue;
  561. BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
  562. if (!BI || !BI->isConditional()) continue;
  563. CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
  564. if (!CI || CI->getParent() != ExitingBlock) continue;
  565. // Attempt to hoist out all instructions except for the
  566. // comparison and the branch.
  567. bool AllInvariant = true;
  568. bool AnyInvariant = false;
  569. for (auto I = ExitingBlock->instructionsWithoutDebug().begin(); &*I != BI; ) {
  570. Instruction *Inst = &*I++;
  571. if (Inst == CI)
  572. continue;
  573. if (!L->makeLoopInvariant(
  574. Inst, AnyInvariant,
  575. Preheader ? Preheader->getTerminator() : nullptr, MSSAU)) {
  576. AllInvariant = false;
  577. break;
  578. }
  579. }
  580. if (AnyInvariant) {
  581. Changed = true;
  582. // The loop disposition of all SCEV expressions that depend on any
  583. // hoisted values have also changed.
  584. if (SE)
  585. SE->forgetLoopDispositions(L);
  586. }
  587. if (!AllInvariant) continue;
  588. // The block has now been cleared of all instructions except for
  589. // a comparison and a conditional branch. SimplifyCFG may be able
  590. // to fold it now.
  591. if (!FoldBranchToCommonDest(BI, /*DTU=*/nullptr, MSSAU))
  592. continue;
  593. // Success. The block is now dead, so remove it from the loop,
  594. // update the dominator tree and delete it.
  595. LLVM_DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
  596. << ExitingBlock->getName() << "\n");
  597. assert(pred_empty(ExitingBlock));
  598. Changed = true;
  599. LI->removeBlock(ExitingBlock);
  600. DomTreeNode *Node = DT->getNode(ExitingBlock);
  601. while (!Node->isLeaf()) {
  602. DomTreeNode *Child = Node->back();
  603. DT->changeImmediateDominator(Child, Node->getIDom());
  604. }
  605. DT->eraseNode(ExitingBlock);
  606. if (MSSAU) {
  607. SmallSetVector<BasicBlock *, 8> ExitBlockSet;
  608. ExitBlockSet.insert(ExitingBlock);
  609. MSSAU->removeBlocks(ExitBlockSet);
  610. }
  611. BI->getSuccessor(0)->removePredecessor(
  612. ExitingBlock, /* KeepOneInputPHIs */ PreserveLCSSA);
  613. BI->getSuccessor(1)->removePredecessor(
  614. ExitingBlock, /* KeepOneInputPHIs */ PreserveLCSSA);
  615. ExitingBlock->eraseFromParent();
  616. }
  617. }
  618. // Changing exit conditions for blocks may affect exit counts of this loop and
  619. // any of its paretns, so we must invalidate the entire subtree if we've made
  620. // any changes.
  621. if (Changed && SE)
  622. SE->forgetTopmostLoop(L);
  623. if (MSSAU && VerifyMemorySSA)
  624. MSSAU->getMemorySSA()->verifyMemorySSA();
  625. return Changed;
  626. }
  627. bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI,
  628. ScalarEvolution *SE, AssumptionCache *AC,
  629. MemorySSAUpdater *MSSAU, bool PreserveLCSSA) {
  630. bool Changed = false;
  631. #ifndef NDEBUG
  632. // If we're asked to preserve LCSSA, the loop nest needs to start in LCSSA
  633. // form.
  634. if (PreserveLCSSA) {
  635. assert(DT && "DT not available.");
  636. assert(LI && "LI not available.");
  637. assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
  638. "Requested to preserve LCSSA, but it's already broken.");
  639. }
  640. #endif
  641. // Worklist maintains our depth-first queue of loops in this nest to process.
  642. SmallVector<Loop *, 4> Worklist;
  643. Worklist.push_back(L);
  644. // Walk the worklist from front to back, pushing newly found sub loops onto
  645. // the back. This will let us process loops from back to front in depth-first
  646. // order. We can use this simple process because loops form a tree.
  647. for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
  648. Loop *L2 = Worklist[Idx];
  649. Worklist.append(L2->begin(), L2->end());
  650. }
  651. while (!Worklist.empty())
  652. Changed |= simplifyOneLoop(Worklist.pop_back_val(), Worklist, DT, LI, SE,
  653. AC, MSSAU, PreserveLCSSA);
  654. return Changed;
  655. }
  656. namespace {
  657. struct LoopSimplify : public FunctionPass {
  658. static char ID; // Pass identification, replacement for typeid
  659. LoopSimplify() : FunctionPass(ID) {
  660. initializeLoopSimplifyPass(*PassRegistry::getPassRegistry());
  661. }
  662. bool runOnFunction(Function &F) override;
  663. void getAnalysisUsage(AnalysisUsage &AU) const override {
  664. AU.addRequired<AssumptionCacheTracker>();
  665. // We need loop information to identify the loops...
  666. AU.addRequired<DominatorTreeWrapperPass>();
  667. AU.addPreserved<DominatorTreeWrapperPass>();
  668. AU.addRequired<LoopInfoWrapperPass>();
  669. AU.addPreserved<LoopInfoWrapperPass>();
  670. AU.addPreserved<BasicAAWrapperPass>();
  671. AU.addPreserved<AAResultsWrapperPass>();
  672. AU.addPreserved<GlobalsAAWrapperPass>();
  673. AU.addPreserved<ScalarEvolutionWrapperPass>();
  674. AU.addPreserved<SCEVAAWrapperPass>();
  675. AU.addPreservedID(LCSSAID);
  676. AU.addPreserved<DependenceAnalysisWrapperPass>();
  677. AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
  678. AU.addPreserved<BranchProbabilityInfoWrapperPass>();
  679. AU.addPreserved<MemorySSAWrapperPass>();
  680. }
  681. /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
  682. void verifyAnalysis() const override;
  683. };
  684. }
  685. char LoopSimplify::ID = 0;
  686. INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
  687. "Canonicalize natural loops", false, false)
  688. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  689. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  690. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  691. INITIALIZE_PASS_END(LoopSimplify, "loop-simplify",
  692. "Canonicalize natural loops", false, false)
  693. // Publicly exposed interface to pass...
  694. char &llvm::LoopSimplifyID = LoopSimplify::ID;
  695. Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
  696. /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
  697. /// it in any convenient order) inserting preheaders...
  698. ///
  699. bool LoopSimplify::runOnFunction(Function &F) {
  700. bool Changed = false;
  701. LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  702. DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  703. auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
  704. ScalarEvolution *SE = SEWP ? &SEWP->getSE() : nullptr;
  705. AssumptionCache *AC =
  706. &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  707. MemorySSA *MSSA = nullptr;
  708. std::unique_ptr<MemorySSAUpdater> MSSAU;
  709. auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
  710. if (MSSAAnalysis) {
  711. MSSA = &MSSAAnalysis->getMSSA();
  712. MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
  713. }
  714. bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
  715. // Simplify each loop nest in the function.
  716. for (auto *L : *LI)
  717. Changed |= simplifyLoop(L, DT, LI, SE, AC, MSSAU.get(), PreserveLCSSA);
  718. #ifndef NDEBUG
  719. if (PreserveLCSSA) {
  720. bool InLCSSA = all_of(
  721. *LI, [&](Loop *L) { return L->isRecursivelyLCSSAForm(*DT, *LI); });
  722. assert(InLCSSA && "LCSSA is broken after loop-simplify.");
  723. }
  724. #endif
  725. return Changed;
  726. }
  727. PreservedAnalyses LoopSimplifyPass::run(Function &F,
  728. FunctionAnalysisManager &AM) {
  729. bool Changed = false;
  730. LoopInfo *LI = &AM.getResult<LoopAnalysis>(F);
  731. DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
  732. ScalarEvolution *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F);
  733. AssumptionCache *AC = &AM.getResult<AssumptionAnalysis>(F);
  734. auto *MSSAAnalysis = AM.getCachedResult<MemorySSAAnalysis>(F);
  735. std::unique_ptr<MemorySSAUpdater> MSSAU;
  736. if (MSSAAnalysis) {
  737. auto *MSSA = &MSSAAnalysis->getMSSA();
  738. MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
  739. }
  740. // Note that we don't preserve LCSSA in the new PM, if you need it run LCSSA
  741. // after simplifying the loops. MemorySSA is preserved if it exists.
  742. for (auto *L : *LI)
  743. Changed |=
  744. simplifyLoop(L, DT, LI, SE, AC, MSSAU.get(), /*PreserveLCSSA*/ false);
  745. if (!Changed)
  746. return PreservedAnalyses::all();
  747. PreservedAnalyses PA;
  748. PA.preserve<DominatorTreeAnalysis>();
  749. PA.preserve<LoopAnalysis>();
  750. PA.preserve<ScalarEvolutionAnalysis>();
  751. PA.preserve<DependenceAnalysis>();
  752. if (MSSAAnalysis)
  753. PA.preserve<MemorySSAAnalysis>();
  754. // BPI maps conditional terminators to probabilities, LoopSimplify can insert
  755. // blocks, but it does so only by splitting existing blocks and edges. This
  756. // results in the interesting property that all new terminators inserted are
  757. // unconditional branches which do not appear in BPI. All deletions are
  758. // handled via ValueHandle callbacks w/in BPI.
  759. PA.preserve<BranchProbabilityAnalysis>();
  760. return PA;
  761. }
  762. // FIXME: Restore this code when we re-enable verification in verifyAnalysis
  763. // below.
  764. #if 0
  765. static void verifyLoop(Loop *L) {
  766. // Verify subloops.
  767. for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
  768. verifyLoop(*I);
  769. // It used to be possible to just assert L->isLoopSimplifyForm(), however
  770. // with the introduction of indirectbr, there are now cases where it's
  771. // not possible to transform a loop as necessary. We can at least check
  772. // that there is an indirectbr near any time there's trouble.
  773. // Indirectbr can interfere with preheader and unique backedge insertion.
  774. if (!L->getLoopPreheader() || !L->getLoopLatch()) {
  775. bool HasIndBrPred = false;
  776. for (BasicBlock *Pred : predecessors(L->getHeader()))
  777. if (isa<IndirectBrInst>(Pred->getTerminator())) {
  778. HasIndBrPred = true;
  779. break;
  780. }
  781. assert(HasIndBrPred &&
  782. "LoopSimplify has no excuse for missing loop header info!");
  783. (void)HasIndBrPred;
  784. }
  785. // Indirectbr can interfere with exit block canonicalization.
  786. if (!L->hasDedicatedExits()) {
  787. bool HasIndBrExiting = false;
  788. SmallVector<BasicBlock*, 8> ExitingBlocks;
  789. L->getExitingBlocks(ExitingBlocks);
  790. for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
  791. if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
  792. HasIndBrExiting = true;
  793. break;
  794. }
  795. }
  796. assert(HasIndBrExiting &&
  797. "LoopSimplify has no excuse for missing exit block info!");
  798. (void)HasIndBrExiting;
  799. }
  800. }
  801. #endif
  802. void LoopSimplify::verifyAnalysis() const {
  803. // FIXME: This routine is being called mid-way through the loop pass manager
  804. // as loop passes destroy this analysis. That's actually fine, but we have no
  805. // way of expressing that here. Once all of the passes that destroy this are
  806. // hoisted out of the loop pass manager we can add back verification here.
  807. #if 0
  808. for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
  809. verifyLoop(*I);
  810. #endif
  811. }