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/Type.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/Dominators.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Support/CFG.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/ADT/SetOperations.h"
48 #include "llvm/ADT/SetVector.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/ADT/DepthFirstIterator.h"
53 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
54 STATISTIC(NumNested , "Number of nested loops split out");
57 struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
58 static char ID; // Pass identification, replacement for typeid
59 LoopSimplify() : FunctionPass((intptr_t)&ID) {}
61 // AA - If we have an alias analysis object to update, this is it, otherwise
66 virtual bool runOnFunction(Function &F);
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 // We need loop information to identify the loops...
70 AU.addRequired<LoopInfo>();
71 AU.addRequired<DominatorTree>();
73 AU.addPreserved<LoopInfo>();
74 AU.addPreserved<DominatorTree>();
75 AU.addPreserved<DominanceFrontier>();
76 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
79 /// verifyAnalysis() - Verify loop nest.
80 void verifyAnalysis() const {
82 LoopInfo *NLI = &getAnalysis<LoopInfo>();
83 for (LoopInfo::iterator I = NLI->begin(), E = NLI->end(); I != E; ++I)
89 bool ProcessLoop(Loop *L);
90 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
91 void InsertPreheaderForLoop(Loop *L);
92 Loop *SeparateNestedLoop(Loop *L);
93 void InsertUniqueBackedgeBlock(Loop *L);
94 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
95 SmallVectorImpl<BasicBlock*> &SplitPreds,
99 char LoopSimplify::ID = 0;
100 RegisterPass<LoopSimplify>
101 X("loopsimplify", "Canonicalize natural loops", true);
104 // Publically exposed interface to pass...
105 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
106 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
108 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
109 /// it in any convenient order) inserting preheaders...
111 bool LoopSimplify::runOnFunction(Function &F) {
112 bool Changed = false;
113 LI = &getAnalysis<LoopInfo>();
114 AA = getAnalysisToUpdate<AliasAnalysis>();
115 DT = &getAnalysis<DominatorTree>();
117 // Check to see that no blocks (other than the header) in loops have
118 // predecessors that are not in loops. This is not valid for natural loops,
119 // but can occur if the blocks are unreachable. Since they are unreachable we
120 // can just shamelessly destroy their terminators to make them not branch into
122 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
123 // This case can only occur for unreachable blocks. Blocks that are
124 // unreachable can't be in loops, so filter those blocks out.
125 if (LI->getLoopFor(BB)) continue;
127 bool BlockUnreachable = false;
129 // Check to see if any successors of this block are non-loop-header loops
130 // that are not the header.
131 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
132 // If this successor is not in a loop, BB is clearly ok.
133 Loop *L = LI->getLoopFor(*I);
136 // If the succ is the loop header, and if L is a top-level loop, then this
137 // is an entrance into a loop through the header, which is also ok.
138 if (L->getHeader() == *I && L->getParentLoop() == 0)
141 // Otherwise, this is an entrance into a loop from some place invalid.
142 // Either the loop structure is invalid and this is not a natural loop (in
143 // which case the compiler is buggy somewhere else) or BB is unreachable.
144 BlockUnreachable = true;
148 // If this block is ok, check the next one.
149 if (!BlockUnreachable) continue;
151 // Otherwise, this block is dead. To clean up the CFG and to allow later
152 // loop transformations to ignore this case, we delete the edges into the
153 // loop by replacing the terminator.
155 // Remove PHI entries from the successors.
156 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
157 (*I)->removePredecessor(BB);
159 // Add a new unreachable instruction before the old terminator.
160 TerminatorInst *TI = BB->getTerminator();
161 new UnreachableInst(TI);
163 // Delete the dead terminator.
164 if (AA) AA->deleteValue(TI);
165 if (!TI->use_empty())
166 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
167 TI->eraseFromParent();
171 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
172 Changed |= ProcessLoop(*I);
177 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
178 /// all loops have preheaders.
180 bool LoopSimplify::ProcessLoop(Loop *L) {
181 bool Changed = false;
184 // Canonicalize inner loops before outer loops. Inner loop canonicalization
185 // can provide work for the outer loop to canonicalize.
186 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
187 Changed |= ProcessLoop(*I);
189 assert(L->getBlocks()[0] == L->getHeader() &&
190 "Header isn't first block in loop?");
192 // Does the loop already have a preheader? If so, don't insert one.
193 if (L->getLoopPreheader() == 0) {
194 InsertPreheaderForLoop(L);
199 // Next, check to make sure that all exit nodes of the loop only have
200 // predecessors that are inside of the loop. This check guarantees that the
201 // loop preheader/header will dominate the exit blocks. If the exit block has
202 // predecessors from outside of the loop, split the edge now.
203 SmallVector<BasicBlock*, 8> ExitBlocks;
204 L->getExitBlocks(ExitBlocks);
206 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
207 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
208 E = ExitBlockSet.end(); I != E; ++I) {
209 BasicBlock *ExitBlock = *I;
210 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
212 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
214 if (!L->contains(*PI)) {
215 RewriteLoopExitBlock(L, ExitBlock);
222 // If the header has more than two predecessors at this point (from the
223 // preheader and from multiple backedges), we must adjust the loop.
224 unsigned NumBackedges = L->getNumBackEdges();
225 if (NumBackedges != 1) {
226 // If this is really a nested loop, rip it out into a child loop. Don't do
227 // this for loops with a giant number of backedges, just factor them into a
228 // common backedge instead.
229 if (NumBackedges < 8) {
230 if (Loop *NL = SeparateNestedLoop(L)) {
232 // This is a big restructuring change, reprocess the whole loop.
235 // GCC doesn't tail recursion eliminate this.
240 // If we either couldn't, or didn't want to, identify nesting of the loops,
241 // insert a new block that all backedges target, then make it jump to the
243 InsertUniqueBackedgeBlock(L);
248 // Scan over the PHI nodes in the loop header. Since they now have only two
249 // incoming values (the loop is canonicalized), we may have simplified the PHI
250 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
252 for (BasicBlock::iterator I = L->getHeader()->begin();
253 (PN = dyn_cast<PHINode>(I++)); )
254 if (Value *V = PN->hasConstantValue()) {
255 PN->replaceAllUsesWith(V);
256 PN->eraseFromParent();
262 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
263 /// preheader, this method is called to insert one. This method has two phases:
264 /// preheader insertion and analysis updating.
266 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
267 BasicBlock *Header = L->getHeader();
269 // Compute the set of predecessors of the loop that are not in the loop.
270 SmallVector<BasicBlock*, 8> OutsideBlocks;
271 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
273 if (!L->contains(*PI)) // Coming in from outside the loop?
274 OutsideBlocks.push_back(*PI); // Keep track of it...
276 // Split out the loop pre-header.
278 SplitBlockPredecessors(Header, &OutsideBlocks[0], OutsideBlocks.size(),
282 //===--------------------------------------------------------------------===//
283 // Update analysis results now that we have performed the transformation
286 // We know that we have loop information to update... update it now.
287 if (Loop *Parent = L->getParentLoop())
288 Parent->addBasicBlockToLoop(NewBB, LI->getBase());
290 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
291 // code layout too horribly.
292 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
295 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
296 /// blocks. This method is used to split exit blocks that have predecessors
297 /// outside of the loop.
298 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
299 SmallVector<BasicBlock*, 8> LoopBlocks;
300 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
302 LoopBlocks.push_back(*I);
304 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
305 BasicBlock *NewBB = SplitBlockPredecessors(Exit, &LoopBlocks[0],
306 LoopBlocks.size(), ".loopexit",
309 // Update Loop Information - we know that the new block will be in whichever
310 // loop the Exit block is in. Note that it may not be in that immediate loop,
311 // if the successor is some other loop header. In that case, we continue
312 // walking up the loop tree to find a loop that contains both the successor
313 // block and the predecessor block.
314 Loop *SuccLoop = LI->getLoopFor(Exit);
315 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
316 SuccLoop = SuccLoop->getParentLoop();
318 SuccLoop->addBasicBlockToLoop(NewBB, LI->getBase());
323 /// AddBlockAndPredsToSet - Add the specified block, and all of its
324 /// predecessors, to the specified set, if it's not already in there. Stop
325 /// predecessor traversal when we reach StopBlock.
326 static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
327 std::set<BasicBlock*> &Blocks) {
328 std::vector<BasicBlock *> WorkList;
329 WorkList.push_back(InputBB);
331 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
332 if (Blocks.insert(BB).second && BB != StopBlock)
333 // If BB is not already processed and it is not a stop block then
334 // insert its predecessor in the work list
335 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
336 BasicBlock *WBB = *I;
337 WorkList.push_back(WBB);
339 } while(!WorkList.empty());
342 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
343 /// PHI node that tells us how to partition the loops.
344 static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
346 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
347 PHINode *PN = cast<PHINode>(I);
349 if (Value *V = PN->hasConstantValue())
350 if (!isa<Instruction>(V) || DT->dominates(cast<Instruction>(V), PN)) {
351 // This is a degenerate PHI already, don't modify it!
352 PN->replaceAllUsesWith(V);
353 if (AA) AA->deleteValue(PN);
354 PN->eraseFromParent();
358 // Scan this PHI node looking for a use of the PHI node by itself.
359 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
360 if (PN->getIncomingValue(i) == PN &&
361 L->contains(PN->getIncomingBlock(i)))
362 // We found something tasty to remove.
368 // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
369 // right after some 'outside block' block. This prevents the preheader from
370 // being placed inside the loop body, e.g. when the loop hasn't been rotated.
371 void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
372 SmallVectorImpl<BasicBlock*> &SplitPreds,
374 // Check to see if NewBB is already well placed.
375 Function::iterator BBI = NewBB; --BBI;
376 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
377 if (&*BBI == SplitPreds[i])
381 // If it isn't already after an outside block, move it after one. This is
382 // always good as it makes the uncond branch from the outside block into a
385 // Figure out *which* outside block to put this after. Prefer an outside
386 // block that neighbors a BB actually in the loop.
387 BasicBlock *FoundBB = 0;
388 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
389 Function::iterator BBI = SplitPreds[i];
390 if (++BBI != NewBB->getParent()->end() &&
392 FoundBB = SplitPreds[i];
397 // If our heuristic for a *good* bb to place this after doesn't find
398 // anything, just pick something. It's likely better than leaving it within
401 FoundBB = SplitPreds[0];
402 NewBB->moveAfter(FoundBB);
406 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
407 /// them out into a nested loop. This is important for code that looks like
412 /// br cond, Loop, Next
414 /// br cond2, Loop, Out
416 /// To identify this common case, we look at the PHI nodes in the header of the
417 /// loop. PHI nodes with unchanging values on one backedge correspond to values
418 /// that change in the "outer" loop, but not in the "inner" loop.
420 /// If we are able to separate out a loop, return the new outer loop that was
423 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
424 PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
425 if (PN == 0) return 0; // No known way to partition.
427 // Pull out all predecessors that have varying values in the loop. This
428 // handles the case when a PHI node has multiple instances of itself as
430 SmallVector<BasicBlock*, 8> OuterLoopPreds;
431 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
432 if (PN->getIncomingValue(i) != PN ||
433 !L->contains(PN->getIncomingBlock(i)))
434 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
436 BasicBlock *Header = L->getHeader();
437 BasicBlock *NewBB = SplitBlockPredecessors(Header, &OuterLoopPreds[0],
438 OuterLoopPreds.size(),
441 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
442 // code layout too horribly.
443 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
445 // Create the new outer loop.
446 Loop *NewOuter = new Loop();
448 // Change the parent loop to use the outer loop as its child now.
449 if (Loop *Parent = L->getParentLoop())
450 Parent->replaceChildLoopWith(L, NewOuter);
452 LI->changeTopLevelLoop(L, NewOuter);
454 // This block is going to be our new header block: add it to this loop and all
456 NewOuter->addBasicBlockToLoop(NewBB, LI->getBase());
458 // L is now a subloop of our outer loop.
459 NewOuter->addChildLoop(L);
461 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
462 NewOuter->addBlockEntry(L->getBlocks()[i]);
464 // Determine which blocks should stay in L and which should be moved out to
465 // the Outer loop now.
466 std::set<BasicBlock*> BlocksInL;
467 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
468 if (DT->dominates(Header, *PI))
469 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
472 // Scan all of the loop children of L, moving them to OuterLoop if they are
473 // not part of the inner loop.
474 const std::vector<Loop*> &SubLoops = L->getSubLoops();
475 for (size_t I = 0; I != SubLoops.size(); )
476 if (BlocksInL.count(SubLoops[I]->getHeader()))
477 ++I; // Loop remains in L
479 NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
481 // Now that we know which blocks are in L and which need to be moved to
482 // OuterLoop, move any blocks that need it.
483 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
484 BasicBlock *BB = L->getBlocks()[i];
485 if (!BlocksInL.count(BB)) {
486 // Move this block to the parent, updating the exit blocks sets
487 L->removeBlockFromLoop(BB);
489 LI->changeLoopFor(BB, NewOuter);
499 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
500 /// has more than one backedge in it. If this occurs, revector all of these
501 /// backedges to target a new basic block and have that block branch to the loop
502 /// header. This ensures that loops have exactly one backedge.
504 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
505 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
507 // Get information about the loop
508 BasicBlock *Preheader = L->getLoopPreheader();
509 BasicBlock *Header = L->getHeader();
510 Function *F = Header->getParent();
512 // Figure out which basic blocks contain back-edges to the loop header.
513 std::vector<BasicBlock*> BackedgeBlocks;
514 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
515 if (*I != Preheader) BackedgeBlocks.push_back(*I);
517 // Create and insert the new backedge block...
518 BasicBlock *BEBlock = BasicBlock::Create(Header->getName()+".backedge", F);
519 BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
521 // Move the new backedge block to right after the last backedge block.
522 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
523 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
525 // Now that the block has been inserted into the function, create PHI nodes in
526 // the backedge block which correspond to any PHI nodes in the header block.
527 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
528 PHINode *PN = cast<PHINode>(I);
529 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".be",
531 NewPN->reserveOperandSpace(BackedgeBlocks.size());
532 if (AA) AA->copyValue(PN, NewPN);
534 // Loop over the PHI node, moving all entries except the one for the
535 // preheader over to the new PHI node.
536 unsigned PreheaderIdx = ~0U;
537 bool HasUniqueIncomingValue = true;
538 Value *UniqueValue = 0;
539 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
540 BasicBlock *IBB = PN->getIncomingBlock(i);
541 Value *IV = PN->getIncomingValue(i);
542 if (IBB == Preheader) {
545 NewPN->addIncoming(IV, IBB);
546 if (HasUniqueIncomingValue) {
547 if (UniqueValue == 0)
549 else if (UniqueValue != IV)
550 HasUniqueIncomingValue = false;
555 // Delete all of the incoming values from the old PN except the preheader's
556 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
557 if (PreheaderIdx != 0) {
558 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
559 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
561 // Nuke all entries except the zero'th.
562 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
563 PN->removeIncomingValue(e-i, false);
565 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
566 PN->addIncoming(NewPN, BEBlock);
568 // As an optimization, if all incoming values in the new PhiNode (which is a
569 // subset of the incoming values of the old PHI node) have the same value,
570 // eliminate the PHI Node.
571 if (HasUniqueIncomingValue) {
572 NewPN->replaceAllUsesWith(UniqueValue);
573 if (AA) AA->deleteValue(NewPN);
574 BEBlock->getInstList().erase(NewPN);
578 // Now that all of the PHI nodes have been inserted and adjusted, modify the
579 // backedge blocks to branch to the BEBlock instead of the header.
580 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
581 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
582 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
583 if (TI->getSuccessor(Op) == Header)
584 TI->setSuccessor(Op, BEBlock);
586 if (BackedgeBlocks[i]->getUnwindDest() == Header)
587 BackedgeBlocks[i]->setUnwindDest(BEBlock);
590 //===--- Update all analyses which we must preserve now -----------------===//
592 // Update Loop Information - we know that this block is now in the current
593 // loop and all parent loops.
594 L->addBasicBlockToLoop(BEBlock, LI->getBase());
596 // Update dominator information
597 DT->splitBlock(BEBlock);
598 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
599 DF->splitBlock(BEBlock);