LoopSimplify.cpp 35 KB

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