LoopSimplify.cpp 32 KB

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