LoopSimplify.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. #define DEBUG_TYPE "loopsimplify"
  40. #include "llvm/Transforms/Scalar.h"
  41. #include "llvm/Constants.h"
  42. #include "llvm/Instructions.h"
  43. #include "llvm/IntrinsicInst.h"
  44. #include "llvm/Function.h"
  45. #include "llvm/LLVMContext.h"
  46. #include "llvm/Type.h"
  47. #include "llvm/Analysis/AliasAnalysis.h"
  48. #include "llvm/Analysis/ScalarEvolution.h"
  49. #include "llvm/Analysis/Dominators.h"
  50. #include "llvm/Analysis/LoopPass.h"
  51. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  52. #include "llvm/Transforms/Utils/Local.h"
  53. #include "llvm/Support/CFG.h"
  54. #include "llvm/Support/Debug.h"
  55. #include "llvm/ADT/SetOperations.h"
  56. #include "llvm/ADT/SetVector.h"
  57. #include "llvm/ADT/Statistic.h"
  58. #include "llvm/ADT/DepthFirstIterator.h"
  59. using namespace llvm;
  60. STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
  61. STATISTIC(NumNested , "Number of nested loops split out");
  62. namespace {
  63. struct LoopSimplify : public LoopPass {
  64. static char ID; // Pass identification, replacement for typeid
  65. LoopSimplify() : LoopPass(ID) {}
  66. // AA - If we have an alias analysis object to update, this is it, otherwise
  67. // this is null.
  68. AliasAnalysis *AA;
  69. LoopInfo *LI;
  70. DominatorTree *DT;
  71. ScalarEvolution *SE;
  72. Loop *L;
  73. virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
  74. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  75. // We need loop information to identify the loops...
  76. AU.addRequired<DominatorTree>();
  77. AU.addPreserved<DominatorTree>();
  78. AU.addRequired<LoopInfo>();
  79. AU.addPreserved<LoopInfo>();
  80. AU.addPreserved<AliasAnalysis>();
  81. AU.addPreserved<ScalarEvolution>();
  82. AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
  83. AU.addPreserved<DominanceFrontier>();
  84. AU.addPreservedID(LCSSAID);
  85. }
  86. /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
  87. void verifyAnalysis() const;
  88. private:
  89. bool ProcessLoop(Loop *L, LPPassManager &LPM);
  90. BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
  91. BasicBlock *InsertPreheaderForLoop(Loop *L);
  92. Loop *SeparateNestedLoop(Loop *L, LPPassManager &LPM);
  93. BasicBlock *InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader);
  94. void PlaceSplitBlockCarefully(BasicBlock *NewBB,
  95. SmallVectorImpl<BasicBlock*> &SplitPreds,
  96. Loop *L);
  97. };
  98. }
  99. char LoopSimplify::ID = 0;
  100. INITIALIZE_PASS(LoopSimplify, "loopsimplify",
  101. "Canonicalize natural loops", true, false);
  102. // Publically exposed interface to pass...
  103. char &llvm::LoopSimplifyID = LoopSimplify::ID;
  104. Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
  105. /// runOnLoop - Run down all loops in the CFG (recursively, but we could do
  106. /// it in any convenient order) inserting preheaders...
  107. ///
  108. bool LoopSimplify::runOnLoop(Loop *l, LPPassManager &LPM) {
  109. L = l;
  110. bool Changed = false;
  111. LI = &getAnalysis<LoopInfo>();
  112. AA = getAnalysisIfAvailable<AliasAnalysis>();
  113. DT = &getAnalysis<DominatorTree>();
  114. SE = getAnalysisIfAvailable<ScalarEvolution>();
  115. Changed |= ProcessLoop(L, LPM);
  116. return Changed;
  117. }
  118. /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
  119. /// all loops have preheaders.
  120. ///
  121. bool LoopSimplify::ProcessLoop(Loop *L, LPPassManager &LPM) {
  122. bool Changed = false;
  123. ReprocessLoop:
  124. // Check to see that no blocks (other than the header) in this loop have
  125. // predecessors that are not in the loop. This is not valid for natural
  126. // loops, but can occur if the blocks are unreachable. Since they are
  127. // unreachable we can just shamelessly delete those CFG edges!
  128. for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
  129. BB != E; ++BB) {
  130. if (*BB == L->getHeader()) continue;
  131. SmallPtrSet<BasicBlock*, 4> BadPreds;
  132. for (pred_iterator PI = pred_begin(*BB),
  133. PE = pred_end(*BB); PI != PE; ++PI) {
  134. BasicBlock *P = *PI;
  135. if (!L->contains(P))
  136. BadPreds.insert(P);
  137. }
  138. // Delete each unique out-of-loop (and thus dead) predecessor.
  139. for (SmallPtrSet<BasicBlock*, 4>::iterator I = BadPreds.begin(),
  140. E = BadPreds.end(); I != E; ++I) {
  141. DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor ";
  142. WriteAsOperand(dbgs(), *I, false);
  143. dbgs() << "\n");
  144. // Inform each successor of each dead pred.
  145. for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
  146. (*SI)->removePredecessor(*I);
  147. // Zap the dead pred's terminator and replace it with unreachable.
  148. TerminatorInst *TI = (*I)->getTerminator();
  149. TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
  150. (*I)->getTerminator()->eraseFromParent();
  151. new UnreachableInst((*I)->getContext(), *I);
  152. Changed = true;
  153. }
  154. }
  155. // If there are exiting blocks with branches on undef, resolve the undef in
  156. // the direction which will exit the loop. This will help simplify loop
  157. // trip count computations.
  158. SmallVector<BasicBlock*, 8> ExitingBlocks;
  159. L->getExitingBlocks(ExitingBlocks);
  160. for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
  161. E = ExitingBlocks.end(); I != E; ++I)
  162. if (BranchInst *BI = dyn_cast<BranchInst>((*I)->getTerminator()))
  163. if (BI->isConditional()) {
  164. if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
  165. DEBUG(dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in ";
  166. WriteAsOperand(dbgs(), *I, false);
  167. dbgs() << "\n");
  168. BI->setCondition(ConstantInt::get(Cond->getType(),
  169. !L->contains(BI->getSuccessor(0))));
  170. Changed = true;
  171. }
  172. }
  173. // Does the loop already have a preheader? If so, don't insert one.
  174. BasicBlock *Preheader = L->getLoopPreheader();
  175. if (!Preheader) {
  176. Preheader = InsertPreheaderForLoop(L);
  177. if (Preheader) {
  178. ++NumInserted;
  179. Changed = true;
  180. }
  181. }
  182. // Next, check to make sure that all exit nodes of the loop only have
  183. // predecessors that are inside of the loop. This check guarantees that the
  184. // loop preheader/header will dominate the exit blocks. If the exit block has
  185. // predecessors from outside of the loop, split the edge now.
  186. SmallVector<BasicBlock*, 8> ExitBlocks;
  187. L->getExitBlocks(ExitBlocks);
  188. SmallSetVector<BasicBlock *, 8> ExitBlockSet(ExitBlocks.begin(),
  189. ExitBlocks.end());
  190. for (SmallSetVector<BasicBlock *, 8>::iterator I = ExitBlockSet.begin(),
  191. E = ExitBlockSet.end(); I != E; ++I) {
  192. BasicBlock *ExitBlock = *I;
  193. for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
  194. PI != PE; ++PI)
  195. // Must be exactly this loop: no subloops, parent loops, or non-loop preds
  196. // allowed.
  197. if (!L->contains(*PI)) {
  198. if (RewriteLoopExitBlock(L, ExitBlock)) {
  199. ++NumInserted;
  200. Changed = true;
  201. }
  202. break;
  203. }
  204. }
  205. // If the header has more than two predecessors at this point (from the
  206. // preheader and from multiple backedges), we must adjust the loop.
  207. BasicBlock *LoopLatch = L->getLoopLatch();
  208. if (!LoopLatch) {
  209. // If this is really a nested loop, rip it out into a child loop. Don't do
  210. // this for loops with a giant number of backedges, just factor them into a
  211. // common backedge instead.
  212. if (L->getNumBackEdges() < 8) {
  213. if (SeparateNestedLoop(L, LPM)) {
  214. ++NumNested;
  215. // This is a big restructuring change, reprocess the whole loop.
  216. Changed = true;
  217. // GCC doesn't tail recursion eliminate this.
  218. goto ReprocessLoop;
  219. }
  220. }
  221. // If we either couldn't, or didn't want to, identify nesting of the loops,
  222. // insert a new block that all backedges target, then make it jump to the
  223. // loop header.
  224. LoopLatch = InsertUniqueBackedgeBlock(L, Preheader);
  225. if (LoopLatch) {
  226. ++NumInserted;
  227. Changed = true;
  228. }
  229. }
  230. // Scan over the PHI nodes in the loop header. Since they now have only two
  231. // incoming values (the loop is canonicalized), we may have simplified the PHI
  232. // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
  233. PHINode *PN;
  234. for (BasicBlock::iterator I = L->getHeader()->begin();
  235. (PN = dyn_cast<PHINode>(I++)); )
  236. if (Value *V = PN->hasConstantValue(DT)) {
  237. if (AA) AA->deleteValue(PN);
  238. PN->replaceAllUsesWith(V);
  239. PN->eraseFromParent();
  240. }
  241. // If this loop has multiple exits and the exits all go to the same
  242. // block, attempt to merge the exits. This helps several passes, such
  243. // as LoopRotation, which do not support loops with multiple exits.
  244. // SimplifyCFG also does this (and this code uses the same utility
  245. // function), however this code is loop-aware, where SimplifyCFG is
  246. // not. That gives it the advantage of being able to hoist
  247. // loop-invariant instructions out of the way to open up more
  248. // opportunities, and the disadvantage of having the responsibility
  249. // to preserve dominator information.
  250. bool UniqueExit = true;
  251. if (!ExitBlocks.empty())
  252. for (unsigned i = 1, e = ExitBlocks.size(); i != e; ++i)
  253. if (ExitBlocks[i] != ExitBlocks[0]) {
  254. UniqueExit = false;
  255. break;
  256. }
  257. if (UniqueExit) {
  258. for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
  259. BasicBlock *ExitingBlock = ExitingBlocks[i];
  260. if (!ExitingBlock->getSinglePredecessor()) continue;
  261. BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
  262. if (!BI || !BI->isConditional()) continue;
  263. CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
  264. if (!CI || CI->getParent() != ExitingBlock) continue;
  265. // Attempt to hoist out all instructions except for the
  266. // comparison and the branch.
  267. bool AllInvariant = true;
  268. for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
  269. Instruction *Inst = I++;
  270. // Skip debug info intrinsics.
  271. if (isa<DbgInfoIntrinsic>(Inst))
  272. continue;
  273. if (Inst == CI)
  274. continue;
  275. if (!L->makeLoopInvariant(Inst, Changed,
  276. Preheader ? Preheader->getTerminator() : 0)) {
  277. AllInvariant = false;
  278. break;
  279. }
  280. }
  281. if (!AllInvariant) continue;
  282. // The block has now been cleared of all instructions except for
  283. // a comparison and a conditional branch. SimplifyCFG may be able
  284. // to fold it now.
  285. if (!FoldBranchToCommonDest(BI)) continue;
  286. // Success. The block is now dead, so remove it from the loop,
  287. // update the dominator tree and dominance frontier, and delete it.
  288. DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block ";
  289. WriteAsOperand(dbgs(), ExitingBlock, false);
  290. dbgs() << "\n");
  291. assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
  292. Changed = true;
  293. LI->removeBlock(ExitingBlock);
  294. DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>();
  295. DomTreeNode *Node = DT->getNode(ExitingBlock);
  296. const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
  297. Node->getChildren();
  298. while (!Children.empty()) {
  299. DomTreeNode *Child = Children.front();
  300. DT->changeImmediateDominator(Child, Node->getIDom());
  301. if (DF) DF->changeImmediateDominator(Child->getBlock(),
  302. Node->getIDom()->getBlock(),
  303. DT);
  304. }
  305. DT->eraseNode(ExitingBlock);
  306. if (DF) DF->removeBlock(ExitingBlock);
  307. BI->getSuccessor(0)->removePredecessor(ExitingBlock);
  308. BI->getSuccessor(1)->removePredecessor(ExitingBlock);
  309. ExitingBlock->eraseFromParent();
  310. }
  311. }
  312. return Changed;
  313. }
  314. /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
  315. /// preheader, this method is called to insert one. This method has two phases:
  316. /// preheader insertion and analysis updating.
  317. ///
  318. BasicBlock *LoopSimplify::InsertPreheaderForLoop(Loop *L) {
  319. BasicBlock *Header = L->getHeader();
  320. // Compute the set of predecessors of the loop that are not in the loop.
  321. SmallVector<BasicBlock*, 8> OutsideBlocks;
  322. for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
  323. PI != PE; ++PI) {
  324. BasicBlock *P = *PI;
  325. if (!L->contains(P)) { // Coming in from outside the loop?
  326. // If the loop is branched to from an indirect branch, we won't
  327. // be able to fully transform the loop, because it prohibits
  328. // edge splitting.
  329. if (isa<IndirectBrInst>(P->getTerminator())) return 0;
  330. // Keep track of it.
  331. OutsideBlocks.push_back(P);
  332. }
  333. }
  334. // Split out the loop pre-header.
  335. BasicBlock *NewBB =
  336. SplitBlockPredecessors(Header, &OutsideBlocks[0], OutsideBlocks.size(),
  337. ".preheader", this);
  338. DEBUG(dbgs() << "LoopSimplify: Creating pre-header ";
  339. WriteAsOperand(dbgs(), NewBB, false);
  340. dbgs() << "\n");
  341. // Make sure that NewBB is put someplace intelligent, which doesn't mess up
  342. // code layout too horribly.
  343. PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
  344. return NewBB;
  345. }
  346. /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
  347. /// blocks. This method is used to split exit blocks that have predecessors
  348. /// outside of the loop.
  349. BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
  350. SmallVector<BasicBlock*, 8> LoopBlocks;
  351. for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) {
  352. BasicBlock *P = *I;
  353. if (L->contains(P)) {
  354. // Don't do this if the loop is exited via an indirect branch.
  355. if (isa<IndirectBrInst>(P->getTerminator())) return 0;
  356. LoopBlocks.push_back(P);
  357. }
  358. }
  359. assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
  360. BasicBlock *NewBB = SplitBlockPredecessors(Exit, &LoopBlocks[0],
  361. LoopBlocks.size(), ".loopexit",
  362. this);
  363. DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block ";
  364. WriteAsOperand(dbgs(), NewBB, false);
  365. dbgs() << "\n");
  366. return NewBB;
  367. }
  368. /// AddBlockAndPredsToSet - Add the specified block, and all of its
  369. /// predecessors, to the specified set, if it's not already in there. Stop
  370. /// predecessor traversal when we reach StopBlock.
  371. static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
  372. std::set<BasicBlock*> &Blocks) {
  373. std::vector<BasicBlock *> WorkList;
  374. WorkList.push_back(InputBB);
  375. do {
  376. BasicBlock *BB = WorkList.back(); WorkList.pop_back();
  377. if (Blocks.insert(BB).second && BB != StopBlock)
  378. // If BB is not already processed and it is not a stop block then
  379. // insert its predecessor in the work list
  380. for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
  381. BasicBlock *WBB = *I;
  382. WorkList.push_back(WBB);
  383. }
  384. } while(!WorkList.empty());
  385. }
  386. /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
  387. /// PHI node that tells us how to partition the loops.
  388. static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
  389. AliasAnalysis *AA) {
  390. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
  391. PHINode *PN = cast<PHINode>(I);
  392. ++I;
  393. if (Value *V = PN->hasConstantValue(DT)) {
  394. // This is a degenerate PHI already, don't modify it!
  395. PN->replaceAllUsesWith(V);
  396. if (AA) AA->deleteValue(PN);
  397. PN->eraseFromParent();
  398. continue;
  399. }
  400. // Scan this PHI node looking for a use of the PHI node by itself.
  401. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  402. if (PN->getIncomingValue(i) == PN &&
  403. L->contains(PN->getIncomingBlock(i)))
  404. // We found something tasty to remove.
  405. return PN;
  406. }
  407. return 0;
  408. }
  409. // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
  410. // right after some 'outside block' block. This prevents the preheader from
  411. // being placed inside the loop body, e.g. when the loop hasn't been rotated.
  412. void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
  413. SmallVectorImpl<BasicBlock*> &SplitPreds,
  414. Loop *L) {
  415. // Check to see if NewBB is already well placed.
  416. Function::iterator BBI = NewBB; --BBI;
  417. for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
  418. if (&*BBI == SplitPreds[i])
  419. return;
  420. }
  421. // If it isn't already after an outside block, move it after one. This is
  422. // always good as it makes the uncond branch from the outside block into a
  423. // fall-through.
  424. // Figure out *which* outside block to put this after. Prefer an outside
  425. // block that neighbors a BB actually in the loop.
  426. BasicBlock *FoundBB = 0;
  427. for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
  428. Function::iterator BBI = SplitPreds[i];
  429. if (++BBI != NewBB->getParent()->end() &&
  430. L->contains(BBI)) {
  431. FoundBB = SplitPreds[i];
  432. break;
  433. }
  434. }
  435. // If our heuristic for a *good* bb to place this after doesn't find
  436. // anything, just pick something. It's likely better than leaving it within
  437. // the loop.
  438. if (!FoundBB)
  439. FoundBB = SplitPreds[0];
  440. NewBB->moveAfter(FoundBB);
  441. }
  442. /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
  443. /// them out into a nested loop. This is important for code that looks like
  444. /// this:
  445. ///
  446. /// Loop:
  447. /// ...
  448. /// br cond, Loop, Next
  449. /// ...
  450. /// br cond2, Loop, Out
  451. ///
  452. /// To identify this common case, we look at the PHI nodes in the header of the
  453. /// loop. PHI nodes with unchanging values on one backedge correspond to values
  454. /// that change in the "outer" loop, but not in the "inner" loop.
  455. ///
  456. /// If we are able to separate out a loop, return the new outer loop that was
  457. /// created.
  458. ///
  459. Loop *LoopSimplify::SeparateNestedLoop(Loop *L, LPPassManager &LPM) {
  460. PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
  461. if (PN == 0) return 0; // No known way to partition.
  462. // Pull out all predecessors that have varying values in the loop. This
  463. // handles the case when a PHI node has multiple instances of itself as
  464. // arguments.
  465. SmallVector<BasicBlock*, 8> OuterLoopPreds;
  466. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  467. if (PN->getIncomingValue(i) != PN ||
  468. !L->contains(PN->getIncomingBlock(i))) {
  469. // We can't split indirectbr edges.
  470. if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
  471. return 0;
  472. OuterLoopPreds.push_back(PN->getIncomingBlock(i));
  473. }
  474. DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
  475. // If ScalarEvolution is around and knows anything about values in
  476. // this loop, tell it to forget them, because we're about to
  477. // substantially change it.
  478. if (SE)
  479. SE->forgetLoop(L);
  480. BasicBlock *Header = L->getHeader();
  481. BasicBlock *NewBB = SplitBlockPredecessors(Header, &OuterLoopPreds[0],
  482. OuterLoopPreds.size(),
  483. ".outer", this);
  484. // Make sure that NewBB is put someplace intelligent, which doesn't mess up
  485. // code layout too horribly.
  486. PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
  487. // Create the new outer loop.
  488. Loop *NewOuter = new Loop();
  489. // Change the parent loop to use the outer loop as its child now.
  490. if (Loop *Parent = L->getParentLoop())
  491. Parent->replaceChildLoopWith(L, NewOuter);
  492. else
  493. LI->changeTopLevelLoop(L, NewOuter);
  494. // L is now a subloop of our outer loop.
  495. NewOuter->addChildLoop(L);
  496. // Add the new loop to the pass manager queue.
  497. LPM.insertLoopIntoQueue(NewOuter);
  498. for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
  499. I != E; ++I)
  500. NewOuter->addBlockEntry(*I);
  501. // Now reset the header in L, which had been moved by
  502. // SplitBlockPredecessors for the outer loop.
  503. L->moveToHeader(Header);
  504. // Determine which blocks should stay in L and which should be moved out to
  505. // the Outer loop now.
  506. std::set<BasicBlock*> BlocksInL;
  507. for (pred_iterator PI=pred_begin(Header), E = pred_end(Header); PI!=E; ++PI) {
  508. BasicBlock *P = *PI;
  509. if (DT->dominates(Header, P))
  510. AddBlockAndPredsToSet(P, Header, BlocksInL);
  511. }
  512. // Scan all of the loop children of L, moving them to OuterLoop if they are
  513. // not part of the inner loop.
  514. const std::vector<Loop*> &SubLoops = L->getSubLoops();
  515. for (size_t I = 0; I != SubLoops.size(); )
  516. if (BlocksInL.count(SubLoops[I]->getHeader()))
  517. ++I; // Loop remains in L
  518. else
  519. NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
  520. // Now that we know which blocks are in L and which need to be moved to
  521. // OuterLoop, move any blocks that need it.
  522. for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
  523. BasicBlock *BB = L->getBlocks()[i];
  524. if (!BlocksInL.count(BB)) {
  525. // Move this block to the parent, updating the exit blocks sets
  526. L->removeBlockFromLoop(BB);
  527. if ((*LI)[BB] == L)
  528. LI->changeLoopFor(BB, NewOuter);
  529. --i;
  530. }
  531. }
  532. return NewOuter;
  533. }
  534. /// InsertUniqueBackedgeBlock - This method is called when the specified loop
  535. /// has more than one backedge in it. If this occurs, revector all of these
  536. /// backedges to target a new basic block and have that block branch to the loop
  537. /// header. This ensures that loops have exactly one backedge.
  538. ///
  539. BasicBlock *
  540. LoopSimplify::InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader) {
  541. assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
  542. // Get information about the loop
  543. BasicBlock *Header = L->getHeader();
  544. Function *F = Header->getParent();
  545. // Unique backedge insertion currently depends on having a preheader.
  546. if (!Preheader)
  547. return 0;
  548. // Figure out which basic blocks contain back-edges to the loop header.
  549. std::vector<BasicBlock*> BackedgeBlocks;
  550. for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I){
  551. BasicBlock *P = *I;
  552. // Indirectbr edges cannot be split, so we must fail if we find one.
  553. if (isa<IndirectBrInst>(P->getTerminator()))
  554. return 0;
  555. if (P != Preheader) BackedgeBlocks.push_back(P);
  556. }
  557. // Create and insert the new backedge block...
  558. BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
  559. Header->getName()+".backedge", F);
  560. BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
  561. DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block ";
  562. WriteAsOperand(dbgs(), BEBlock, false);
  563. dbgs() << "\n");
  564. // Move the new backedge block to right after the last backedge block.
  565. Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
  566. F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
  567. // Now that the block has been inserted into the function, create PHI nodes in
  568. // the backedge block which correspond to any PHI nodes in the header block.
  569. for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
  570. PHINode *PN = cast<PHINode>(I);
  571. PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".be",
  572. BETerminator);
  573. NewPN->reserveOperandSpace(BackedgeBlocks.size());
  574. if (AA) AA->copyValue(PN, NewPN);
  575. // Loop over the PHI node, moving all entries except the one for the
  576. // preheader over to the new PHI node.
  577. unsigned PreheaderIdx = ~0U;
  578. bool HasUniqueIncomingValue = true;
  579. Value *UniqueValue = 0;
  580. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  581. BasicBlock *IBB = PN->getIncomingBlock(i);
  582. Value *IV = PN->getIncomingValue(i);
  583. if (IBB == Preheader) {
  584. PreheaderIdx = i;
  585. } else {
  586. NewPN->addIncoming(IV, IBB);
  587. if (HasUniqueIncomingValue) {
  588. if (UniqueValue == 0)
  589. UniqueValue = IV;
  590. else if (UniqueValue != IV)
  591. HasUniqueIncomingValue = false;
  592. }
  593. }
  594. }
  595. // Delete all of the incoming values from the old PN except the preheader's
  596. assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
  597. if (PreheaderIdx != 0) {
  598. PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
  599. PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
  600. }
  601. // Nuke all entries except the zero'th.
  602. for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
  603. PN->removeIncomingValue(e-i, false);
  604. // Finally, add the newly constructed PHI node as the entry for the BEBlock.
  605. PN->addIncoming(NewPN, BEBlock);
  606. // As an optimization, if all incoming values in the new PhiNode (which is a
  607. // subset of the incoming values of the old PHI node) have the same value,
  608. // eliminate the PHI Node.
  609. if (HasUniqueIncomingValue) {
  610. NewPN->replaceAllUsesWith(UniqueValue);
  611. if (AA) AA->deleteValue(NewPN);
  612. BEBlock->getInstList().erase(NewPN);
  613. }
  614. }
  615. // Now that all of the PHI nodes have been inserted and adjusted, modify the
  616. // backedge blocks to just to the BEBlock instead of the header.
  617. for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
  618. TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
  619. for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
  620. if (TI->getSuccessor(Op) == Header)
  621. TI->setSuccessor(Op, BEBlock);
  622. }
  623. //===--- Update all analyses which we must preserve now -----------------===//
  624. // Update Loop Information - we know that this block is now in the current
  625. // loop and all parent loops.
  626. L->addBasicBlockToLoop(BEBlock, LI->getBase());
  627. // Update dominator information
  628. DT->splitBlock(BEBlock);
  629. if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>())
  630. DF->splitBlock(BEBlock);
  631. return BEBlock;
  632. }
  633. void LoopSimplify::verifyAnalysis() const {
  634. // It used to be possible to just assert L->isLoopSimplifyForm(), however
  635. // with the introduction of indirectbr, there are now cases where it's
  636. // not possible to transform a loop as necessary. We can at least check
  637. // that there is an indirectbr near any time there's trouble.
  638. // Indirectbr can interfere with preheader and unique backedge insertion.
  639. if (!L->getLoopPreheader() || !L->getLoopLatch()) {
  640. bool HasIndBrPred = false;
  641. for (pred_iterator PI = pred_begin(L->getHeader()),
  642. PE = pred_end(L->getHeader()); PI != PE; ++PI)
  643. if (isa<IndirectBrInst>((*PI)->getTerminator())) {
  644. HasIndBrPred = true;
  645. break;
  646. }
  647. assert(HasIndBrPred &&
  648. "LoopSimplify has no excuse for missing loop header info!");
  649. }
  650. // Indirectbr can interfere with exit block canonicalization.
  651. if (!L->hasDedicatedExits()) {
  652. bool HasIndBrExiting = false;
  653. SmallVector<BasicBlock*, 8> ExitingBlocks;
  654. L->getExitingBlocks(ExitingBlocks);
  655. for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i)
  656. if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
  657. HasIndBrExiting = true;
  658. break;
  659. }
  660. assert(HasIndBrExiting &&
  661. "LoopSimplify has no excuse for missing exit block info!");
  662. }
  663. }