1 //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs several transformations to transform natural loops into a
11 // simpler form, which makes subsequent analyses and transformations simpler and
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.
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.
24 // This pass also guarantees that loops will have exactly one backedge.
26 // Note that the simplifycfg pass will clean up blocks which are split out but
27 // end up being unnecessary, so usage of this pass should not pessimize
30 // This pass obviously modifies the CFG, but updates loop information and
31 // dominator information.
33 //===----------------------------------------------------------------------===//
35 #define DEBUG_TYPE "loopsimplify"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Constants.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Function.h"
40 #include "llvm/LLVMContext.h"
41 #include "llvm/Type.h"
42 #include "llvm/Analysis/AliasAnalysis.h"
43 #include "llvm/Analysis/Dominators.h"
44 #include "llvm/Analysis/LoopPass.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/ADT/SetOperations.h"
51 #include "llvm/ADT/SetVector.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/DepthFirstIterator.h"
56 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
57 STATISTIC(NumNested , "Number of nested loops split out");
60 struct VISIBILITY_HIDDEN LoopSimplify : public LoopPass {
61 static char ID; // Pass identification, replacement for typeid
62 LoopSimplify() : LoopPass(&ID) {}
64 // AA - If we have an alias analysis object to update, this is it, otherwise
70 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 // We need loop information to identify the loops...
74 AU.addRequiredTransitive<LoopInfo>();
75 AU.addRequiredTransitive<DominatorTree>();
77 AU.addPreserved<LoopInfo>();
78 AU.addPreserved<DominatorTree>();
79 AU.addPreserved<DominanceFrontier>();
80 AU.addPreserved<AliasAnalysis>();
81 AU.addPreserved<ScalarEvolution>();
82 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
85 /// verifyAnalysis() - Verify loop nest.
86 void verifyAnalysis() const {
87 assert(L->isLoopSimplifyForm() && "LoopSimplify form not preserved!");
91 bool ProcessLoop(Loop *L, LPPassManager &LPM);
92 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
93 BasicBlock *InsertPreheaderForLoop(Loop *L);
94 Loop *SeparateNestedLoop(Loop *L, LPPassManager &LPM);
95 void InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader);
96 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
97 SmallVectorImpl<BasicBlock*> &SplitPreds,
102 char LoopSimplify::ID = 0;
103 static RegisterPass<LoopSimplify>
104 X("loopsimplify", "Canonicalize natural loops", true);
106 // Publically exposed interface to pass...
107 const PassInfo *const llvm::LoopSimplifyID = &X;
108 Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
110 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
111 /// it in any convenient order) inserting preheaders...
113 bool LoopSimplify::runOnLoop(Loop *l, LPPassManager &LPM) {
115 bool Changed = false;
116 LI = &getAnalysis<LoopInfo>();
117 AA = getAnalysisIfAvailable<AliasAnalysis>();
118 DT = &getAnalysis<DominatorTree>();
120 Changed |= ProcessLoop(L, LPM);
125 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
126 /// all loops have preheaders.
128 bool LoopSimplify::ProcessLoop(Loop *L, LPPassManager &LPM) {
129 bool Changed = false;
132 // Check to see that no blocks (other than the header) in this loop that has
133 // predecessors that are not in the loop. This is not valid for natural
134 // loops, but can occur if the blocks are unreachable. Since they are
135 // unreachable we can just shamelessly delete those CFG edges!
136 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
138 if (*BB == L->getHeader()) continue;
140 SmallPtrSet<BasicBlock *, 4> BadPreds;
141 for (pred_iterator PI = pred_begin(*BB), PE = pred_end(*BB); PI != PE; ++PI)
142 if (!L->contains(*PI))
143 BadPreds.insert(*PI);
145 // Delete each unique out-of-loop (and thus dead) predecessor.
146 for (SmallPtrSet<BasicBlock *, 4>::iterator I = BadPreds.begin(),
147 E = BadPreds.end(); I != E; ++I) {
148 // Inform each successor of each dead pred.
149 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
150 (*SI)->removePredecessor(*I);
151 // Zap the dead pred's terminator and replace it with unreachable.
152 TerminatorInst *TI = (*I)->getTerminator();
153 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
154 (*I)->getTerminator()->eraseFromParent();
155 new UnreachableInst((*I)->getContext(), *I);
160 // Does the loop already have a preheader? If so, don't insert one.
161 BasicBlock *Preheader = L->getLoopPreheader();
163 Preheader = InsertPreheaderForLoop(L);
168 // Next, check to make sure that all exit nodes of the loop only have
169 // predecessors that are inside of the loop. This check guarantees that the
170 // loop preheader/header will dominate the exit blocks. If the exit block has
171 // predecessors from outside of the loop, split the edge now.
172 SmallVector<BasicBlock*, 8> ExitBlocks;
173 L->getExitBlocks(ExitBlocks);
175 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
176 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
177 E = ExitBlockSet.end(); I != E; ++I) {
178 BasicBlock *ExitBlock = *I;
179 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
181 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
183 if (!L->contains(*PI)) {
184 RewriteLoopExitBlock(L, ExitBlock);
191 // If the header has more than two predecessors at this point (from the
192 // preheader and from multiple backedges), we must adjust the loop.
193 unsigned NumBackedges = L->getNumBackEdges();
194 if (NumBackedges != 1) {
195 // If this is really a nested loop, rip it out into a child loop. Don't do
196 // this for loops with a giant number of backedges, just factor them into a
197 // common backedge instead.
198 if (NumBackedges < 8) {
199 if (SeparateNestedLoop(L, LPM)) {
201 // This is a big restructuring change, reprocess the whole loop.
203 // GCC doesn't tail recursion eliminate this.
208 // If we either couldn't, or didn't want to, identify nesting of the loops,
209 // insert a new block that all backedges target, then make it jump to the
211 InsertUniqueBackedgeBlock(L, Preheader);
216 // Scan over the PHI nodes in the loop header. Since they now have only two
217 // incoming values (the loop is canonicalized), we may have simplified the PHI
218 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
220 for (BasicBlock::iterator I = L->getHeader()->begin();
221 (PN = dyn_cast<PHINode>(I++)); )
222 if (Value *V = PN->hasConstantValue(DT)) {
223 if (AA) AA->deleteValue(PN);
224 PN->replaceAllUsesWith(V);
225 PN->eraseFromParent();
228 // If this loop has muliple exits and the exits all go to the same
229 // block, attempt to merge the exits. This helps several passes, such
230 // as LoopRotation, which do not support loops with multiple exits.
231 // SimplifyCFG also does this (and this code uses the same utility
232 // function), however this code is loop-aware, where SimplifyCFG is
233 // not. That gives it the advantage of being able to hoist
234 // loop-invariant instructions out of the way to open up more
235 // opportunities, and the disadvantage of having the responsibility
236 // to preserve dominator information.
237 if (ExitBlocks.size() > 1 && L->getUniqueExitBlock()) {
238 SmallVector<BasicBlock*, 8> ExitingBlocks;
239 L->getExitingBlocks(ExitingBlocks);
240 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
241 BasicBlock *ExitingBlock = ExitingBlocks[i];
242 if (!ExitingBlock->getSinglePredecessor()) continue;
243 BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
244 if (!BI || !BI->isConditional()) continue;
245 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
246 if (!CI || CI->getParent() != ExitingBlock) continue;
248 // Attempt to hoist out all instructions except for the
249 // comparison and the branch.
250 bool AllInvariant = true;
251 for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
252 Instruction *Inst = I++;
255 if (!L->makeLoopInvariant(Inst, Changed, Preheader->getTerminator())) {
256 AllInvariant = false;
260 if (!AllInvariant) continue;
262 // The block has now been cleared of all instructions except for
263 // a comparison and a conditional branch. SimplifyCFG may be able
265 if (!FoldBranchToCommonDest(BI)) continue;
267 // Success. The block is now dead, so remove it from the loop,
268 // update the dominator tree and dominance frontier, and delete it.
269 assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
271 LI->removeBlock(ExitingBlock);
273 DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>();
274 DomTreeNode *Node = DT->getNode(ExitingBlock);
275 const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
277 for (unsigned k = 0, g = Children.size(); k != g; ++k) {
278 DT->changeImmediateDominator(Children[k], Node->getIDom());
279 if (DF) DF->changeImmediateDominator(Children[k]->getBlock(),
280 Node->getIDom()->getBlock(),
283 DT->eraseNode(ExitingBlock);
284 if (DF) DF->removeBlock(ExitingBlock);
286 BI->getSuccessor(0)->removePredecessor(ExitingBlock);
287 BI->getSuccessor(1)->removePredecessor(ExitingBlock);
288 ExitingBlock->eraseFromParent();
295 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
296 /// preheader, this method is called to insert one. This method has two phases:
297 /// preheader insertion and analysis updating.
299 BasicBlock *LoopSimplify::InsertPreheaderForLoop(Loop *L) {
300 BasicBlock *Header = L->getHeader();
302 // Compute the set of predecessors of the loop that are not in the loop.
303 SmallVector<BasicBlock*, 8> OutsideBlocks;
304 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
306 if (!L->contains(*PI)) // Coming in from outside the loop?
307 OutsideBlocks.push_back(*PI); // Keep track of it...
309 // Split out the loop pre-header.
311 SplitBlockPredecessors(Header, &OutsideBlocks[0], OutsideBlocks.size(),
314 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
315 // code layout too horribly.
316 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
321 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
322 /// blocks. This method is used to split exit blocks that have predecessors
323 /// outside of the loop.
324 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
325 SmallVector<BasicBlock*, 8> LoopBlocks;
326 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
328 LoopBlocks.push_back(*I);
330 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
331 BasicBlock *NewBB = SplitBlockPredecessors(Exit, &LoopBlocks[0],
332 LoopBlocks.size(), ".loopexit",
338 /// AddBlockAndPredsToSet - Add the specified block, and all of its
339 /// predecessors, to the specified set, if it's not already in there. Stop
340 /// predecessor traversal when we reach StopBlock.
341 static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
342 std::set<BasicBlock*> &Blocks) {
343 std::vector<BasicBlock *> WorkList;
344 WorkList.push_back(InputBB);
346 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
347 if (Blocks.insert(BB).second && BB != StopBlock)
348 // If BB is not already processed and it is not a stop block then
349 // insert its predecessor in the work list
350 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
351 BasicBlock *WBB = *I;
352 WorkList.push_back(WBB);
354 } while(!WorkList.empty());
357 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
358 /// PHI node that tells us how to partition the loops.
359 static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
361 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
362 PHINode *PN = cast<PHINode>(I);
364 if (Value *V = PN->hasConstantValue(DT)) {
365 // This is a degenerate PHI already, don't modify it!
366 PN->replaceAllUsesWith(V);
367 if (AA) AA->deleteValue(PN);
368 PN->eraseFromParent();
372 // Scan this PHI node looking for a use of the PHI node by itself.
373 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
374 if (PN->getIncomingValue(i) == PN &&
375 L->contains(PN->getIncomingBlock(i)))
376 // We found something tasty to remove.
382 // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
383 // right after some 'outside block' block. This prevents the preheader from
384 // being placed inside the loop body, e.g. when the loop hasn't been rotated.
385 void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
386 SmallVectorImpl<BasicBlock*> &SplitPreds,
388 // Check to see if NewBB is already well placed.
389 Function::iterator BBI = NewBB; --BBI;
390 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
391 if (&*BBI == SplitPreds[i])
395 // If it isn't already after an outside block, move it after one. This is
396 // always good as it makes the uncond branch from the outside block into a
399 // Figure out *which* outside block to put this after. Prefer an outside
400 // block that neighbors a BB actually in the loop.
401 BasicBlock *FoundBB = 0;
402 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
403 Function::iterator BBI = SplitPreds[i];
404 if (++BBI != NewBB->getParent()->end() &&
406 FoundBB = SplitPreds[i];
411 // If our heuristic for a *good* bb to place this after doesn't find
412 // anything, just pick something. It's likely better than leaving it within
415 FoundBB = SplitPreds[0];
416 NewBB->moveAfter(FoundBB);
420 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
421 /// them out into a nested loop. This is important for code that looks like
426 /// br cond, Loop, Next
428 /// br cond2, Loop, Out
430 /// To identify this common case, we look at the PHI nodes in the header of the
431 /// loop. PHI nodes with unchanging values on one backedge correspond to values
432 /// that change in the "outer" loop, but not in the "inner" loop.
434 /// If we are able to separate out a loop, return the new outer loop that was
437 Loop *LoopSimplify::SeparateNestedLoop(Loop *L, LPPassManager &LPM) {
438 PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
439 if (PN == 0) return 0; // No known way to partition.
441 // Pull out all predecessors that have varying values in the loop. This
442 // handles the case when a PHI node has multiple instances of itself as
444 SmallVector<BasicBlock*, 8> OuterLoopPreds;
445 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
446 if (PN->getIncomingValue(i) != PN ||
447 !L->contains(PN->getIncomingBlock(i)))
448 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
450 BasicBlock *Header = L->getHeader();
451 BasicBlock *NewBB = SplitBlockPredecessors(Header, &OuterLoopPreds[0],
452 OuterLoopPreds.size(),
455 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
456 // code layout too horribly.
457 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
459 // Create the new outer loop.
460 Loop *NewOuter = new Loop();
462 // Change the parent loop to use the outer loop as its child now.
463 if (Loop *Parent = L->getParentLoop())
464 Parent->replaceChildLoopWith(L, NewOuter);
466 LI->changeTopLevelLoop(L, NewOuter);
468 // L is now a subloop of our outer loop.
469 NewOuter->addChildLoop(L);
471 // Add the new loop to the pass manager queue.
472 LPM.insertLoopIntoQueue(NewOuter);
474 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
476 NewOuter->addBlockEntry(*I);
478 // Now reset the header in L, which had been moved by
479 // SplitBlockPredecessors for the outer loop.
480 L->moveToHeader(Header);
482 // Determine which blocks should stay in L and which should be moved out to
483 // the Outer loop now.
484 std::set<BasicBlock*> BlocksInL;
485 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
486 if (DT->dominates(Header, *PI))
487 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
490 // Scan all of the loop children of L, moving them to OuterLoop if they are
491 // not part of the inner loop.
492 const std::vector<Loop*> &SubLoops = L->getSubLoops();
493 for (size_t I = 0; I != SubLoops.size(); )
494 if (BlocksInL.count(SubLoops[I]->getHeader()))
495 ++I; // Loop remains in L
497 NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
499 // Now that we know which blocks are in L and which need to be moved to
500 // OuterLoop, move any blocks that need it.
501 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
502 BasicBlock *BB = L->getBlocks()[i];
503 if (!BlocksInL.count(BB)) {
504 // Move this block to the parent, updating the exit blocks sets
505 L->removeBlockFromLoop(BB);
507 LI->changeLoopFor(BB, NewOuter);
517 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
518 /// has more than one backedge in it. If this occurs, revector all of these
519 /// backedges to target a new basic block and have that block branch to the loop
520 /// header. This ensures that loops have exactly one backedge.
522 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader) {
523 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
525 // Get information about the loop
526 BasicBlock *Header = L->getHeader();
527 Function *F = Header->getParent();
529 // Figure out which basic blocks contain back-edges to the loop header.
530 std::vector<BasicBlock*> BackedgeBlocks;
531 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
532 if (*I != Preheader) BackedgeBlocks.push_back(*I);
534 // Create and insert the new backedge block...
535 BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
536 Header->getName()+".backedge", F);
537 BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
539 // Move the new backedge block to right after the last backedge block.
540 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
541 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
543 // Now that the block has been inserted into the function, create PHI nodes in
544 // the backedge block which correspond to any PHI nodes in the header block.
545 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
546 PHINode *PN = cast<PHINode>(I);
547 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".be",
549 NewPN->reserveOperandSpace(BackedgeBlocks.size());
550 if (AA) AA->copyValue(PN, NewPN);
552 // Loop over the PHI node, moving all entries except the one for the
553 // preheader over to the new PHI node.
554 unsigned PreheaderIdx = ~0U;
555 bool HasUniqueIncomingValue = true;
556 Value *UniqueValue = 0;
557 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
558 BasicBlock *IBB = PN->getIncomingBlock(i);
559 Value *IV = PN->getIncomingValue(i);
560 if (IBB == Preheader) {
563 NewPN->addIncoming(IV, IBB);
564 if (HasUniqueIncomingValue) {
565 if (UniqueValue == 0)
567 else if (UniqueValue != IV)
568 HasUniqueIncomingValue = false;
573 // Delete all of the incoming values from the old PN except the preheader's
574 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
575 if (PreheaderIdx != 0) {
576 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
577 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
579 // Nuke all entries except the zero'th.
580 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
581 PN->removeIncomingValue(e-i, false);
583 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
584 PN->addIncoming(NewPN, BEBlock);
586 // As an optimization, if all incoming values in the new PhiNode (which is a
587 // subset of the incoming values of the old PHI node) have the same value,
588 // eliminate the PHI Node.
589 if (HasUniqueIncomingValue) {
590 NewPN->replaceAllUsesWith(UniqueValue);
591 if (AA) AA->deleteValue(NewPN);
592 BEBlock->getInstList().erase(NewPN);
596 // Now that all of the PHI nodes have been inserted and adjusted, modify the
597 // backedge blocks to just to the BEBlock instead of the header.
598 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
599 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
600 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
601 if (TI->getSuccessor(Op) == Header)
602 TI->setSuccessor(Op, BEBlock);
605 //===--- Update all analyses which we must preserve now -----------------===//
607 // Update Loop Information - we know that this block is now in the current
608 // loop and all parent loops.
609 L->addBasicBlockToLoop(BEBlock, LI->getBase());
611 // Update dominator information
612 DT->splitBlock(BEBlock);
613 if (DominanceFrontier *DF = getAnalysisIfAvailable<DominanceFrontier>())
614 DF->splitBlock(BEBlock);