LoopSimplify.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass performs several transformations to transform natural loops into a
  11. // simpler form, which makes subsequent analyses and transformations simpler and
  12. // more effective.
  13. //
  14. // Loop pre-header insertion guarantees that there is a single, non-critical
  15. // entry edge from outside of the loop to the loop header. This simplifies a
  16. // number of analyses and transformations, such as LICM.
  17. //
  18. // Loop exit-block insertion guarantees that all exit blocks from the loop
  19. // (blocks which are outside of the loop that have predecessors inside of the
  20. // loop) only have predecessors from inside of the loop (and are thus dominated
  21. // by the loop header). This simplifies transformations such as store-sinking
  22. // that are built into LICM.
  23. //
  24. // This pass also guarantees that loops will have exactly one backedge.
  25. //
  26. // Indirectbr instructions introduce several complications. If the loop
  27. // contains or is entered by an indirectbr instruction, it may not be possible
  28. // to transform the loop and make these guarantees. Client code should check
  29. // that these conditions are true before relying on them.
  30. //
  31. // Note that the simplifycfg pass will clean up blocks which are split out but
  32. // end up being unnecessary, so usage of this pass should not pessimize
  33. // generated code.
  34. //
  35. // This pass obviously modifies the CFG, but updates loop information and
  36. // dominator information.
  37. //
  38. //===----------------------------------------------------------------------===//
  39. #include "llvm/Transforms/Scalar.h"
  40. #include "llvm/ADT/DepthFirstIterator.h"
  41. #include "llvm/ADT/SetOperations.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/DependenceAnalysis.h"
  48. #include "llvm/Analysis/InstructionSimplify.h"
  49. #include "llvm/Analysis/LoopInfo.h"
  50. #include "llvm/Analysis/ScalarEvolution.h"
  51. #include "llvm/IR/CFG.h"
  52. #include "llvm/IR/Constants.h"
  53. #include "llvm/IR/DataLayout.h"
  54. #include "llvm/IR/Dominators.h"
  55. #include "llvm/IR/Function.h"
  56. #include "llvm/IR/Instructions.h"
  57. #include "llvm/IR/IntrinsicInst.h"
  58. #include "llvm/IR/LLVMContext.h"
  59. #include "llvm/IR/Module.h"
  60. #include "llvm/IR/Type.h"
  61. #include "llvm/Support/Debug.h"
  62. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  63. #include "llvm/Transforms/Utils/Local.h"
  64. #include "llvm/Transforms/Utils/LoopUtils.h"
  65. using namespace llvm;
  66. #define DEBUG_TYPE "loop-simplify"
  67. STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
  68. STATISTIC(NumNested , "Number of nested loops split out");
  69. // If the block isn't already, move the new block to right after some 'outside
  70. // block' block. This prevents the preheader from being placed inside the loop
  71. // body, e.g. when the loop hasn't been rotated.
  72. static void placeSplitBlockCarefully(BasicBlock *NewBB,
  73. SmallVectorImpl<BasicBlock *> &SplitPreds,
  74. Loop *L) {
  75. // Check to see if NewBB is already well placed.
  76. Function::iterator BBI = NewBB; --BBI;
  77. for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
  78. if (&*BBI == SplitPreds[i])
  79. return;
  80. }
  81. // If it isn't already after an outside block, move it after one. This is
  82. // always good as it makes the uncond branch from the outside block into a
  83. // fall-through.
  84. // Figure out *which* outside block to put this after. Prefer an outside
  85. // block that neighbors a BB actually in the loop.
  86. BasicBlock *FoundBB = nullptr;
  87. for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
  88. Function::iterator BBI = SplitPreds[i];
  89. if (++BBI != NewBB->getParent()->end() &&
  90. L->contains(BBI)) {
  91. FoundBB = SplitPreds[i];
  92. break;
  93. }
  94. }
  95. // If our heuristic for a *good* bb to place this after doesn't find
  96. // anything, just pick something. It's likely better than leaving it within
  97. // the loop.
  98. if (!FoundBB)
  99. FoundBB = SplitPreds[0];
  100. NewBB->moveAfter(FoundBB);
  101. }
  102. /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
  103. /// preheader, this method is called to insert one. This method has two phases:
  104. /// preheader insertion and analysis updating.
  105. ///
  106. BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, Pass *PP) {
  107. BasicBlock *Header = L->getHeader();
  108. // Get analyses that we try to update.
  109. auto *AA = PP->getAnalysisIfAvailable<AliasAnalysis>();
  110. auto *DTWP = PP->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  111. auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
  112. auto *LIWP = PP->getAnalysisIfAvailable<LoopInfoWrapperPass>();
  113. auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
  114. bool PreserveLCSSA = PP->mustPreserveAnalysisID(LCSSAID);
  115. // Compute the set of predecessors of the loop that are not in the loop.
  116. SmallVector<BasicBlock*, 8> OutsideBlocks;
  117. for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
  118. PI != PE; ++PI) {
  119. BasicBlock *P = *PI;
  120. if (!L->contains(P)) { // Coming in from outside the loop?
  121. // If the loop is branched to from an indirect branch, we won't
  122. // be able to fully transform the loop, because it prohibits
  123. // edge splitting.
  124. if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
  125. // Keep track of it.
  126. OutsideBlocks.push_back(P);
  127. }
  128. }
  129. // Split out the loop pre-header.
  130. BasicBlock *PreheaderBB;
  131. PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
  132. AA, DT, LI, PreserveLCSSA);
  133. PreheaderBB->getTerminator()->setDebugLoc(
  134. Header->getFirstNonPHI()->getDebugLoc());
  135. DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
  136. << PreheaderBB->getName() << "\n");
  137. // Make sure that NewBB is put someplace intelligent, which doesn't mess up
  138. // code layout too horribly.
  139. placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
  140. return PreheaderBB;
  141. }
  142. /// \brief Ensure that the loop preheader dominates all exit blocks.
  143. ///
  144. /// This method is used to split exit blocks that have predecessors outside of
  145. /// the loop.
  146. static BasicBlock *rewriteLoopExitBlock(Loop *L, BasicBlock *Exit,
  147. AliasAnalysis *AA, DominatorTree *DT,
  148. LoopInfo *LI, Pass *PP) {
  149. SmallVector<BasicBlock*, 8> LoopBlocks;
  150. for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) {
  151. BasicBlock *P = *I;
  152. if (L->contains(P)) {
  153. // Don't do this if the loop is exited via an indirect branch.
  154. if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
  155. LoopBlocks.push_back(P);
  156. }
  157. }
  158. assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
  159. BasicBlock *NewExitBB = nullptr;
  160. bool PreserveLCSSA = PP->mustPreserveAnalysisID(LCSSAID);
  161. NewExitBB = SplitBlockPredecessors(Exit, LoopBlocks, ".loopexit", AA, DT,
  162. LI, PreserveLCSSA);
  163. DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
  164. << NewExitBB->getName() << "\n");
  165. return NewExitBB;
  166. }
  167. /// Add the specified block, and all of its predecessors, to the specified set,
  168. /// if it's not already in there. Stop predecessor traversal when we reach
  169. /// StopBlock.
  170. static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
  171. std::set<BasicBlock*> &Blocks) {
  172. SmallVector<BasicBlock *, 8> Worklist;
  173. Worklist.push_back(InputBB);
  174. do {
  175. BasicBlock *BB = Worklist.pop_back_val();
  176. if (Blocks.insert(BB).second && BB != StopBlock)
  177. // If BB is not already processed and it is not a stop block then
  178. // insert its predecessor in the work list
  179. for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
  180. BasicBlock *WBB = *I;
  181. Worklist.push_back(WBB);
  182. }
  183. } while (!Worklist.empty());
  184. }
  185. /// \brief The first part of loop-nestification is to find a PHI node that tells
  186. /// us how to partition the loops.
  187. static PHINode *findPHIToPartitionLoops(Loop *L, AliasAnalysis *AA,
  188. DominatorTree *DT,
  189. AssumptionCache *AC) {
  190. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
  191. PHINode *PN = cast<PHINode>(I);
  192. ++I;
  193. if (Value *V = SimplifyInstruction(PN, nullptr, nullptr, DT, AC)) {
  194. // This is a degenerate PHI already, don't modify it!
  195. PN->replaceAllUsesWith(V);
  196. if (AA) AA->deleteValue(PN);
  197. PN->eraseFromParent();
  198. continue;
  199. }
  200. // Scan this PHI node looking for a use of the PHI node by itself.
  201. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  202. if (PN->getIncomingValue(i) == PN &&
  203. L->contains(PN->getIncomingBlock(i)))
  204. // We found something tasty to remove.
  205. return PN;
  206. }
  207. return nullptr;
  208. }
  209. /// \brief If this loop has multiple backedges, try to pull one of them out into
  210. /// a nested loop.
  211. ///
  212. /// This is important for code that looks like
  213. /// this:
  214. ///
  215. /// Loop:
  216. /// ...
  217. /// br cond, Loop, Next
  218. /// ...
  219. /// br cond2, Loop, Out
  220. ///
  221. /// To identify this common case, we look at the PHI nodes in the header of the
  222. /// loop. PHI nodes with unchanging values on one backedge correspond to values
  223. /// that change in the "outer" loop, but not in the "inner" loop.
  224. ///
  225. /// If we are able to separate out a loop, return the new outer loop that was
  226. /// created.
  227. ///
  228. static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader,
  229. AliasAnalysis *AA, DominatorTree *DT,
  230. LoopInfo *LI, ScalarEvolution *SE, Pass *PP,
  231. AssumptionCache *AC) {
  232. // Don't try to separate loops without a preheader.
  233. if (!Preheader)
  234. return nullptr;
  235. // The header is not a landing pad; preheader insertion should ensure this.
  236. assert(!L->getHeader()->isLandingPad() &&
  237. "Can't insert backedge to landing pad");
  238. PHINode *PN = findPHIToPartitionLoops(L, AA, DT, AC);
  239. if (!PN) return nullptr; // No known way to partition.
  240. // Pull out all predecessors that have varying values in the loop. This
  241. // handles the case when a PHI node has multiple instances of itself as
  242. // arguments.
  243. SmallVector<BasicBlock*, 8> OuterLoopPreds;
  244. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  245. if (PN->getIncomingValue(i) != PN ||
  246. !L->contains(PN->getIncomingBlock(i))) {
  247. // We can't split indirectbr edges.
  248. if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
  249. return nullptr;
  250. OuterLoopPreds.push_back(PN->getIncomingBlock(i));
  251. }
  252. }
  253. DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
  254. // If ScalarEvolution is around and knows anything about values in
  255. // this loop, tell it to forget them, because we're about to
  256. // substantially change it.
  257. if (SE)
  258. SE->forgetLoop(L);
  259. bool PreserveLCSSA = PP->mustPreserveAnalysisID(LCSSAID);
  260. BasicBlock *Header = L->getHeader();
  261. BasicBlock *NewBB = SplitBlockPredecessors(Header, OuterLoopPreds, ".outer",
  262. AA, DT, LI, PreserveLCSSA);
  263. // Make sure that NewBB is put someplace intelligent, which doesn't mess up
  264. // code layout too horribly.
  265. placeSplitBlockCarefully(NewBB, OuterLoopPreds, L);
  266. // Create the new outer loop.
  267. Loop *NewOuter = new Loop();
  268. // Change the parent loop to use the outer loop as its child now.
  269. if (Loop *Parent = L->getParentLoop())
  270. Parent->replaceChildLoopWith(L, NewOuter);
  271. else
  272. LI->changeTopLevelLoop(L, NewOuter);
  273. // L is now a subloop of our outer loop.
  274. NewOuter->addChildLoop(L);
  275. for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
  276. I != E; ++I)
  277. NewOuter->addBlockEntry(*I);
  278. // Now reset the header in L, which had been moved by
  279. // SplitBlockPredecessors for the outer loop.
  280. L->moveToHeader(Header);
  281. // Determine which blocks should stay in L and which should be moved out to
  282. // the Outer loop now.
  283. std::set<BasicBlock*> BlocksInL;
  284. for (pred_iterator PI=pred_begin(Header), E = pred_end(Header); PI!=E; ++PI) {
  285. BasicBlock *P = *PI;
  286. if (DT->dominates(Header, P))
  287. addBlockAndPredsToSet(P, Header, BlocksInL);
  288. }
  289. // Scan all of the loop children of L, moving them to OuterLoop if they are
  290. // not part of the inner loop.
  291. const std::vector<Loop*> &SubLoops = L->getSubLoops();
  292. for (size_t I = 0; I != SubLoops.size(); )
  293. if (BlocksInL.count(SubLoops[I]->getHeader()))
  294. ++I; // Loop remains in L
  295. else
  296. NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
  297. // Now that we know which blocks are in L and which need to be moved to
  298. // OuterLoop, move any blocks that need it.
  299. for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
  300. BasicBlock *BB = L->getBlocks()[i];
  301. if (!BlocksInL.count(BB)) {
  302. // Move this block to the parent, updating the exit blocks sets
  303. L->removeBlockFromLoop(BB);
  304. if ((*LI)[BB] == L)
  305. LI->changeLoopFor(BB, NewOuter);
  306. --i;
  307. }
  308. }
  309. return NewOuter;
  310. }
  311. /// \brief This method is called when the specified loop has more than one
  312. /// backedge in it.
  313. ///
  314. /// If this occurs, revector all of these backedges to target a new basic block
  315. /// and have that block branch to the loop header. This ensures that loops
  316. /// have exactly one backedge.
  317. static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader,
  318. AliasAnalysis *AA,
  319. DominatorTree *DT, LoopInfo *LI) {
  320. assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
  321. // Get information about the loop
  322. BasicBlock *Header = L->getHeader();
  323. Function *F = Header->getParent();
  324. // Unique backedge insertion currently depends on having a preheader.
  325. if (!Preheader)
  326. return nullptr;
  327. // The header is not a landing pad; preheader insertion should ensure this.
  328. assert(!Header->isLandingPad() && "Can't insert backedge to landing pad");
  329. // Figure out which basic blocks contain back-edges to the loop header.
  330. std::vector<BasicBlock*> BackedgeBlocks;
  331. for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I){
  332. BasicBlock *P = *I;
  333. // Indirectbr edges cannot be split, so we must fail if we find one.
  334. if (isa<IndirectBrInst>(P->getTerminator()))
  335. return nullptr;
  336. if (P != Preheader) BackedgeBlocks.push_back(P);
  337. }
  338. // Create and insert the new backedge block...
  339. BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
  340. Header->getName()+".backedge", F);
  341. BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
  342. DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
  343. << BEBlock->getName() << "\n");
  344. // Move the new backedge block to right after the last backedge block.
  345. Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
  346. F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
  347. // Now that the block has been inserted into the function, create PHI nodes in
  348. // the backedge block which correspond to any PHI nodes in the header block.
  349. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  350. PHINode *PN = cast<PHINode>(I);
  351. PHINode *NewPN = PHINode::Create(PN->getType(), BackedgeBlocks.size(),
  352. PN->getName()+".be", BETerminator);
  353. if (AA) AA->copyValue(PN, NewPN);
  354. // Loop over the PHI node, moving all entries except the one for the
  355. // preheader over to the new PHI node.
  356. unsigned PreheaderIdx = ~0U;
  357. bool HasUniqueIncomingValue = true;
  358. Value *UniqueValue = nullptr;
  359. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  360. BasicBlock *IBB = PN->getIncomingBlock(i);
  361. Value *IV = PN->getIncomingValue(i);
  362. if (IBB == Preheader) {
  363. PreheaderIdx = i;
  364. } else {
  365. NewPN->addIncoming(IV, IBB);
  366. if (HasUniqueIncomingValue) {
  367. if (!UniqueValue)
  368. UniqueValue = IV;
  369. else if (UniqueValue != IV)
  370. HasUniqueIncomingValue = false;
  371. }
  372. }
  373. }
  374. // Delete all of the incoming values from the old PN except the preheader's
  375. assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
  376. if (PreheaderIdx != 0) {
  377. PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
  378. PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
  379. }
  380. // Nuke all entries except the zero'th.
  381. for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
  382. PN->removeIncomingValue(e-i, false);
  383. // Finally, add the newly constructed PHI node as the entry for the BEBlock.
  384. PN->addIncoming(NewPN, BEBlock);
  385. // As an optimization, if all incoming values in the new PhiNode (which is a
  386. // subset of the incoming values of the old PHI node) have the same value,
  387. // eliminate the PHI Node.
  388. if (HasUniqueIncomingValue) {
  389. NewPN->replaceAllUsesWith(UniqueValue);
  390. if (AA) AA->deleteValue(NewPN);
  391. BEBlock->getInstList().erase(NewPN);
  392. }
  393. }
  394. // Now that all of the PHI nodes have been inserted and adjusted, modify the
  395. // backedge blocks to just to the BEBlock instead of the header.
  396. for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
  397. TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
  398. for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
  399. if (TI->getSuccessor(Op) == Header)
  400. TI->setSuccessor(Op, BEBlock);
  401. }
  402. //===--- Update all analyses which we must preserve now -----------------===//
  403. // Update Loop Information - we know that this block is now in the current
  404. // loop and all parent loops.
  405. L->addBasicBlockToLoop(BEBlock, *LI);
  406. // Update dominator information
  407. DT->splitBlock(BEBlock);
  408. return BEBlock;
  409. }
  410. /// \brief Simplify one loop and queue further loops for simplification.
  411. ///
  412. /// FIXME: Currently this accepts both lots of analyses that it uses and a raw
  413. /// Pass pointer. The Pass pointer is used by numerous utilities to update
  414. /// specific analyses. Rather than a pass it would be much cleaner and more
  415. /// explicit if they accepted the analysis directly and then updated it.
  416. static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist,
  417. AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI,
  418. ScalarEvolution *SE, Pass *PP, const DataLayout *DL,
  419. AssumptionCache *AC) {
  420. bool Changed = false;
  421. ReprocessLoop:
  422. // Check to see that no blocks (other than the header) in this loop have
  423. // predecessors that are not in the loop. This is not valid for natural
  424. // loops, but can occur if the blocks are unreachable. Since they are
  425. // unreachable we can just shamelessly delete those CFG edges!
  426. for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
  427. BB != E; ++BB) {
  428. if (*BB == L->getHeader()) continue;
  429. SmallPtrSet<BasicBlock*, 4> BadPreds;
  430. for (pred_iterator PI = pred_begin(*BB),
  431. PE = pred_end(*BB); PI != PE; ++PI) {
  432. BasicBlock *P = *PI;
  433. if (!L->contains(P))
  434. BadPreds.insert(P);
  435. }
  436. // Delete each unique out-of-loop (and thus dead) predecessor.
  437. for (BasicBlock *P : BadPreds) {
  438. DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
  439. << P->getName() << "\n");
  440. // Inform each successor of each dead pred.
  441. for (succ_iterator SI = succ_begin(P), SE = succ_end(P); SI != SE; ++SI)
  442. (*SI)->removePredecessor(P);
  443. // Zap the dead pred's terminator and replace it with unreachable.
  444. TerminatorInst *TI = P->getTerminator();
  445. TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
  446. P->getTerminator()->eraseFromParent();
  447. new UnreachableInst(P->getContext(), P);
  448. Changed = true;
  449. }
  450. }
  451. // If there are exiting blocks with branches on undef, resolve the undef in
  452. // the direction which will exit the loop. This will help simplify loop
  453. // trip count computations.
  454. SmallVector<BasicBlock*, 8> ExitingBlocks;
  455. L->getExitingBlocks(ExitingBlocks);
  456. for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
  457. E = ExitingBlocks.end(); I != E; ++I)
  458. if (BranchInst *BI = dyn_cast<BranchInst>((*I)->getTerminator()))
  459. if (BI->isConditional()) {
  460. if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
  461. DEBUG(dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
  462. << (*I)->getName() << "\n");
  463. BI->setCondition(ConstantInt::get(Cond->getType(),
  464. !L->contains(BI->getSuccessor(0))));
  465. // This may make the loop analyzable, force SCEV recomputation.
  466. if (SE)
  467. SE->forgetLoop(L);
  468. Changed = true;
  469. }
  470. }
  471. // Does the loop already have a preheader? If so, don't insert one.
  472. BasicBlock *Preheader = L->getLoopPreheader();
  473. if (!Preheader) {
  474. Preheader = InsertPreheaderForLoop(L, PP);
  475. if (Preheader) {
  476. ++NumInserted;
  477. Changed = true;
  478. }
  479. }
  480. // Next, check to make sure that all exit nodes of the loop only have
  481. // predecessors that are inside of the loop. This check guarantees that the
  482. // loop preheader/header will dominate the exit blocks. If the exit block has
  483. // predecessors from outside of the loop, split the edge now.
  484. SmallVector<BasicBlock*, 8> ExitBlocks;
  485. L->getExitBlocks(ExitBlocks);
  486. SmallSetVector<BasicBlock *, 8> ExitBlockSet(ExitBlocks.begin(),
  487. ExitBlocks.end());
  488. for (SmallSetVector<BasicBlock *, 8>::iterator I = ExitBlockSet.begin(),
  489. E = ExitBlockSet.end(); I != E; ++I) {
  490. BasicBlock *ExitBlock = *I;
  491. for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
  492. PI != PE; ++PI)
  493. // Must be exactly this loop: no subloops, parent loops, or non-loop preds
  494. // allowed.
  495. if (!L->contains(*PI)) {
  496. if (rewriteLoopExitBlock(L, ExitBlock, AA, DT, LI, PP)) {
  497. ++NumInserted;
  498. Changed = true;
  499. }
  500. break;
  501. }
  502. }
  503. // If the header has more than two predecessors at this point (from the
  504. // preheader and from multiple backedges), we must adjust the loop.
  505. BasicBlock *LoopLatch = L->getLoopLatch();
  506. if (!LoopLatch) {
  507. // If this is really a nested loop, rip it out into a child loop. Don't do
  508. // this for loops with a giant number of backedges, just factor them into a
  509. // common backedge instead.
  510. if (L->getNumBackEdges() < 8) {
  511. if (Loop *OuterL =
  512. separateNestedLoop(L, Preheader, AA, DT, LI, SE, PP, AC)) {
  513. ++NumNested;
  514. // Enqueue the outer loop as it should be processed next in our
  515. // depth-first nest walk.
  516. Worklist.push_back(OuterL);
  517. // This is a big restructuring change, reprocess the whole loop.
  518. Changed = true;
  519. // GCC doesn't tail recursion eliminate this.
  520. // FIXME: It isn't clear we can't rely on LLVM to TRE this.
  521. goto ReprocessLoop;
  522. }
  523. }
  524. // If we either couldn't, or didn't want to, identify nesting of the loops,
  525. // insert a new block that all backedges target, then make it jump to the
  526. // loop header.
  527. LoopLatch = insertUniqueBackedgeBlock(L, Preheader, AA, DT, LI);
  528. if (LoopLatch) {
  529. ++NumInserted;
  530. Changed = true;
  531. }
  532. }
  533. // Scan over the PHI nodes in the loop header. Since they now have only two
  534. // incoming values (the loop is canonicalized), we may have simplified the PHI
  535. // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
  536. PHINode *PN;
  537. for (BasicBlock::iterator I = L->getHeader()->begin();
  538. (PN = dyn_cast<PHINode>(I++)); )
  539. if (Value *V = SimplifyInstruction(PN, nullptr, nullptr, DT, AC)) {
  540. if (AA) AA->deleteValue(PN);
  541. if (SE) SE->forgetValue(PN);
  542. PN->replaceAllUsesWith(V);
  543. PN->eraseFromParent();
  544. }
  545. // If this loop has multiple exits and the exits all go to the same
  546. // block, attempt to merge the exits. This helps several passes, such
  547. // as LoopRotation, which do not support loops with multiple exits.
  548. // SimplifyCFG also does this (and this code uses the same utility
  549. // function), however this code is loop-aware, where SimplifyCFG is
  550. // not. That gives it the advantage of being able to hoist
  551. // loop-invariant instructions out of the way to open up more
  552. // opportunities, and the disadvantage of having the responsibility
  553. // to preserve dominator information.
  554. bool UniqueExit = true;
  555. if (!ExitBlocks.empty())
  556. for (unsigned i = 1, e = ExitBlocks.size(); i != e; ++i)
  557. if (ExitBlocks[i] != ExitBlocks[0]) {
  558. UniqueExit = false;
  559. break;
  560. }
  561. if (UniqueExit) {
  562. for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
  563. BasicBlock *ExitingBlock = ExitingBlocks[i];
  564. if (!ExitingBlock->getSinglePredecessor()) continue;
  565. BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
  566. if (!BI || !BI->isConditional()) continue;
  567. CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
  568. if (!CI || CI->getParent() != ExitingBlock) continue;
  569. // Attempt to hoist out all instructions except for the
  570. // comparison and the branch.
  571. bool AllInvariant = true;
  572. bool AnyInvariant = false;
  573. for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
  574. Instruction *Inst = I++;
  575. // Skip debug info intrinsics.
  576. if (isa<DbgInfoIntrinsic>(Inst))
  577. continue;
  578. if (Inst == CI)
  579. continue;
  580. if (!L->makeLoopInvariant(Inst, AnyInvariant,
  581. Preheader ? Preheader->getTerminator()
  582. : nullptr)) {
  583. AllInvariant = false;
  584. break;
  585. }
  586. }
  587. if (AnyInvariant) {
  588. Changed = true;
  589. // The loop disposition of all SCEV expressions that depend on any
  590. // hoisted values have also changed.
  591. if (SE)
  592. SE->forgetLoopDispositions(L);
  593. }
  594. if (!AllInvariant) continue;
  595. // The block has now been cleared of all instructions except for
  596. // a comparison and a conditional branch. SimplifyCFG may be able
  597. // to fold it now.
  598. if (!FoldBranchToCommonDest(BI, DL)) continue;
  599. // Success. The block is now dead, so remove it from the loop,
  600. // update the dominator tree and delete it.
  601. DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
  602. << ExitingBlock->getName() << "\n");
  603. // Notify ScalarEvolution before deleting this block. Currently assume the
  604. // parent loop doesn't change (spliting edges doesn't count). If blocks,
  605. // CFG edges, or other values in the parent loop change, then we need call
  606. // to forgetLoop() for the parent instead.
  607. if (SE)
  608. SE->forgetLoop(L);
  609. assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
  610. Changed = true;
  611. LI->removeBlock(ExitingBlock);
  612. DomTreeNode *Node = DT->getNode(ExitingBlock);
  613. const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
  614. Node->getChildren();
  615. while (!Children.empty()) {
  616. DomTreeNode *Child = Children.front();
  617. DT->changeImmediateDominator(Child, Node->getIDom());
  618. }
  619. DT->eraseNode(ExitingBlock);
  620. BI->getSuccessor(0)->removePredecessor(ExitingBlock);
  621. BI->getSuccessor(1)->removePredecessor(ExitingBlock);
  622. ExitingBlock->eraseFromParent();
  623. }
  624. }
  625. return Changed;
  626. }
  627. bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, Pass *PP,
  628. AliasAnalysis *AA, ScalarEvolution *SE,
  629. const DataLayout *DL, AssumptionCache *AC) {
  630. bool Changed = false;
  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, AA, DT, LI,
  643. SE, PP, DL, AC);
  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. // AA - If we have an alias analysis object to update, this is it, otherwise
  653. // this is null.
  654. AliasAnalysis *AA;
  655. DominatorTree *DT;
  656. LoopInfo *LI;
  657. ScalarEvolution *SE;
  658. const DataLayout *DL;
  659. AssumptionCache *AC;
  660. bool runOnFunction(Function &F) override;
  661. void getAnalysisUsage(AnalysisUsage &AU) const override {
  662. AU.addRequired<AssumptionCacheTracker>();
  663. // We need loop information to identify the loops...
  664. AU.addRequired<DominatorTreeWrapperPass>();
  665. AU.addPreserved<DominatorTreeWrapperPass>();
  666. AU.addRequired<LoopInfoWrapperPass>();
  667. AU.addPreserved<LoopInfoWrapperPass>();
  668. AU.addPreserved<AliasAnalysis>();
  669. AU.addPreserved<ScalarEvolution>();
  670. AU.addPreserved<DependenceAnalysis>();
  671. AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
  672. }
  673. /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
  674. void verifyAnalysis() const override;
  675. };
  676. }
  677. char LoopSimplify::ID = 0;
  678. INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
  679. "Canonicalize natural loops", false, false)
  680. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  681. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  682. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  683. INITIALIZE_PASS_END(LoopSimplify, "loop-simplify",
  684. "Canonicalize natural loops", false, false)
  685. // Publicly exposed interface to pass...
  686. char &llvm::LoopSimplifyID = LoopSimplify::ID;
  687. Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
  688. /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
  689. /// it in any convenient order) inserting preheaders...
  690. ///
  691. bool LoopSimplify::runOnFunction(Function &F) {
  692. bool Changed = false;
  693. AA = getAnalysisIfAvailable<AliasAnalysis>();
  694. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  695. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  696. SE = getAnalysisIfAvailable<ScalarEvolution>();
  697. DL = &F.getParent()->getDataLayout();
  698. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  699. // Simplify each loop nest in the function.
  700. for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
  701. Changed |= simplifyLoop(*I, DT, LI, this, AA, SE, DL, AC);
  702. return Changed;
  703. }
  704. // FIXME: Restore this code when we re-enable verification in verifyAnalysis
  705. // below.
  706. #if 0
  707. static void verifyLoop(Loop *L) {
  708. // Verify subloops.
  709. for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
  710. verifyLoop(*I);
  711. // It used to be possible to just assert L->isLoopSimplifyForm(), however
  712. // with the introduction of indirectbr, there are now cases where it's
  713. // not possible to transform a loop as necessary. We can at least check
  714. // that there is an indirectbr near any time there's trouble.
  715. // Indirectbr can interfere with preheader and unique backedge insertion.
  716. if (!L->getLoopPreheader() || !L->getLoopLatch()) {
  717. bool HasIndBrPred = false;
  718. for (pred_iterator PI = pred_begin(L->getHeader()),
  719. PE = pred_end(L->getHeader()); PI != PE; ++PI)
  720. if (isa<IndirectBrInst>((*PI)->getTerminator())) {
  721. HasIndBrPred = true;
  722. break;
  723. }
  724. assert(HasIndBrPred &&
  725. "LoopSimplify has no excuse for missing loop header info!");
  726. (void)HasIndBrPred;
  727. }
  728. // Indirectbr can interfere with exit block canonicalization.
  729. if (!L->hasDedicatedExits()) {
  730. bool HasIndBrExiting = false;
  731. SmallVector<BasicBlock*, 8> ExitingBlocks;
  732. L->getExitingBlocks(ExitingBlocks);
  733. for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
  734. if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
  735. HasIndBrExiting = true;
  736. break;
  737. }
  738. }
  739. assert(HasIndBrExiting &&
  740. "LoopSimplify has no excuse for missing exit block info!");
  741. (void)HasIndBrExiting;
  742. }
  743. }
  744. #endif
  745. void LoopSimplify::verifyAnalysis() const {
  746. // FIXME: This routine is being called mid-way through the loop pass manager
  747. // as loop passes destroy this analysis. That's actually fine, but we have no
  748. // way of expressing that here. Once all of the passes that destroy this are
  749. // hoisted out of the loop pass manager we can add back verification here.
  750. #if 0
  751. for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
  752. verifyLoop(*I);
  753. #endif
  754. }