1 //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Constant.h"
37 #include "llvm/iTerminators.h"
38 #include "llvm/iPHINode.h"
39 #include "llvm/Function.h"
40 #include "llvm/Type.h"
41 #include "llvm/Analysis/Dominators.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Support/CFG.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "Support/SetOperations.h"
46 #include "Support/Statistic.h"
47 #include "Support/DepthFirstIterator.h"
52 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
54 NumNested("loopsimplify", "Number of nested loops split out");
56 struct LoopSimplify : public FunctionPass {
57 virtual bool runOnFunction(Function &F);
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 // We need loop information to identify the loops...
61 AU.addRequired<LoopInfo>();
62 AU.addRequired<DominatorSet>();
63 AU.addRequired<DominatorTree>();
65 AU.addPreserved<LoopInfo>();
66 AU.addPreserved<DominatorSet>();
67 AU.addPreserved<ImmediateDominators>();
68 AU.addPreserved<DominatorTree>();
69 AU.addPreserved<DominanceFrontier>();
70 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
73 bool ProcessLoop(Loop *L);
74 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
75 const std::vector<BasicBlock*> &Preds);
76 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
77 void InsertPreheaderForLoop(Loop *L);
78 Loop *SeparateNestedLoop(Loop *L);
79 void InsertUniqueBackedgeBlock(Loop *L);
81 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
82 std::vector<BasicBlock*> &PredBlocks);
85 RegisterOpt<LoopSimplify>
86 X("loopsimplify", "Canonicalize natural loops", true);
89 // Publically exposed interface to pass...
90 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
91 Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
93 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
94 /// it in any convenient order) inserting preheaders...
96 bool LoopSimplify::runOnFunction(Function &F) {
98 LoopInfo &LI = getAnalysis<LoopInfo>();
100 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
101 Changed |= ProcessLoop(*I);
107 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
108 /// all loops have preheaders.
110 bool LoopSimplify::ProcessLoop(Loop *L) {
111 bool Changed = false;
113 // Check to see that no blocks (other than the header) in the loop have
114 // predecessors that are not in the loop. This is not valid for natural
115 // loops, but can occur if the blocks are unreachable. Since they are
116 // unreachable we can just shamelessly destroy their terminators to make them
117 // not branch into the loop!
118 assert(L->getBlocks()[0] == L->getHeader() &&
119 "Header isn't first block in loop?");
120 for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
121 BasicBlock *LoopBB = L->getBlocks()[i];
123 for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
125 if (!L->contains(*PI)) {
126 // This predecessor is not in the loop. Kill its terminator!
127 BasicBlock *DeadBlock = *PI;
128 for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
130 (*SI)->removePredecessor(DeadBlock); // Remove PHI node entries
132 // Delete the dead terminator.
133 DeadBlock->getInstList().pop_back();
136 if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
137 RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
138 new ReturnInst(RetVal, DeadBlock);
139 goto Retry; // We just invalidated the pred_iterator. Retry.
143 // Does the loop already have a preheader? If so, don't modify the loop...
144 if (L->getLoopPreheader() == 0) {
145 InsertPreheaderForLoop(L);
150 // Next, check to make sure that all exit nodes of the loop only have
151 // predecessors that are inside of the loop. This check guarantees that the
152 // loop preheader/header will dominate the exit blocks. If the exit block has
153 // predecessors from outside of the loop, split the edge now.
154 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i) {
155 BasicBlock *ExitBlock = L->getExitBlocks()[i];
156 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
158 if (!L->contains(*PI)) {
159 RewriteLoopExitBlock(L, ExitBlock);
166 // If the header has more than two predecessors at this point (from the
167 // preheader and from multiple backedges), we must adjust the loop.
168 if (L->getNumBackEdges() != 1) {
169 // If this is really a nested loop, rip it out into a child loop.
170 if (Loop *NL = SeparateNestedLoop(L)) {
172 // This is a big restructuring change, reprocess the whole loop.
177 InsertUniqueBackedgeBlock(L);
182 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
183 Changed |= ProcessLoop(*I);
187 /// SplitBlockPredecessors - Split the specified block into two blocks. We want
188 /// to move the predecessors specified in the Preds list to point to the new
189 /// block, leaving the remaining predecessors pointing to BB. This method
190 /// updates the SSA PHINode's, but no other analyses.
192 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
194 const std::vector<BasicBlock*> &Preds) {
196 // Create new basic block, insert right before the original block...
197 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
199 // The preheader first gets an unconditional branch to the loop header...
200 BranchInst *BI = new BranchInst(BB, NewBB);
202 // For every PHI node in the block, insert a PHI node into NewBB where the
203 // incoming values from the out of loop edges are moved to NewBB. We have two
204 // possible cases here. If the loop is dead, we just insert dummy entries
205 // into the PHI nodes for the new edge. If the loop is not dead, we move the
206 // incoming edges in BB into new PHI nodes in NewBB.
208 if (!Preds.empty()) { // Is the loop not obviously dead?
209 // Check to see if the values being merged into the new block need PHI
210 // nodes. If so, insert them.
211 for (BasicBlock::iterator I = BB->begin();
212 PHINode *PN = dyn_cast<PHINode>(I); ) {
215 // Check to see if all of the values coming in are the same. If so, we
216 // don't need to create a new PHI node.
217 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
218 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
219 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
224 // If the values coming into the block are not the same, we need a PHI.
226 // Create the new PHI node, insert it into NewBB at the end of the block
227 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
229 // Move all of the edges from blocks outside the loop to the new PHI
230 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
231 Value *V = PN->removeIncomingValue(Preds[i], false);
232 NewPHI->addIncoming(V, Preds[i]);
236 // Remove all of the edges coming into the PHI nodes from outside of the
238 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
239 PN->removeIncomingValue(Preds[i], false);
242 // Add an incoming value to the PHI node in the loop for the preheader
244 PN->addIncoming(InVal, NewBB);
246 // Can we eliminate this phi node now?
247 if (Value *V = hasConstantValue(PN)) {
248 PN->replaceAllUsesWith(V);
249 BB->getInstList().erase(PN);
253 // Now that the PHI nodes are updated, actually move the edges from
254 // Preds to point to NewBB instead of BB.
256 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
257 TerminatorInst *TI = Preds[i]->getTerminator();
258 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
259 if (TI->getSuccessor(s) == BB)
260 TI->setSuccessor(s, NewBB);
263 } else { // Otherwise the loop is dead...
264 for (BasicBlock::iterator I = BB->begin();
265 PHINode *PN = dyn_cast<PHINode>(I); ++I)
266 // Insert dummy values as the incoming value...
267 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
272 // ChangeExitBlock - This recursive function is used to change any exit blocks
273 // that use OldExit to use NewExit instead. This is recursive because children
274 // may need to be processed as well.
276 static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
277 if (L->hasExitBlock(OldExit)) {
278 L->changeExitBlock(OldExit, NewExit);
279 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
280 ChangeExitBlock(*I, OldExit, NewExit);
285 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
286 /// preheader, this method is called to insert one. This method has two phases:
287 /// preheader insertion and analysis updating.
289 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
290 BasicBlock *Header = L->getHeader();
292 // Compute the set of predecessors of the loop that are not in the loop.
293 std::vector<BasicBlock*> OutsideBlocks;
294 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
296 if (!L->contains(*PI)) // Coming in from outside the loop?
297 OutsideBlocks.push_back(*PI); // Keep track of it...
299 // Split out the loop pre-header
301 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
303 //===--------------------------------------------------------------------===//
304 // Update analysis results now that we have performed the transformation
307 // We know that we have loop information to update... update it now.
308 if (Loop *Parent = L->getParentLoop())
309 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
311 // If the header for the loop used to be an exit node for another loop, then
312 // we need to update this to know that the loop-preheader is now the exit
313 // node. Note that the only loop that could have our header as an exit node
314 // is a sibling loop, ie, one with the same parent loop, or one if it's
317 LoopInfo::iterator ParentLoops, ParentLoopsE;
318 if (Loop *Parent = L->getParentLoop()) {
319 ParentLoops = Parent->begin();
320 ParentLoopsE = Parent->end();
321 } else { // Must check top-level loops...
322 ParentLoops = getAnalysis<LoopInfo>().begin();
323 ParentLoopsE = getAnalysis<LoopInfo>().end();
326 // Loop over all sibling loops, performing the substitution (recursively to
327 // include child loops)...
328 for (; ParentLoops != ParentLoopsE; ++ParentLoops)
329 ChangeExitBlock(*ParentLoops, Header, NewBB);
331 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
332 DominatorTree &DT = getAnalysis<DominatorTree>();
335 // Update the dominator tree information.
336 // The immediate dominator of the preheader is the immediate dominator of
338 DominatorTree::Node *PHDomTreeNode =
339 DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
341 // Change the header node so that PNHode is the new immediate dominator
342 DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
345 // The blocks that dominate NewBB are the blocks that dominate Header,
346 // minus Header, plus NewBB.
347 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
348 DomSet.erase(Header); // Header does not dominate us...
349 DS.addBasicBlock(NewBB, DomSet);
351 // The newly created basic block dominates all nodes dominated by Header.
352 for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
353 E = df_end(PHDomTreeNode); DFI != E; ++DFI)
354 DS.addDominator((*DFI)->getBlock(), NewBB);
357 // Update immediate dominator information if we have it...
358 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
359 // Whatever i-dominated the header node now immediately dominates NewBB
360 ID->addNewBlock(NewBB, ID->get(Header));
362 // The preheader now is the immediate dominator for the header node...
363 ID->setImmediateDominator(Header, NewBB);
366 // Update dominance frontier information...
367 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
368 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
369 // everything that Header does, and it strictly dominates Header in
371 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
372 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
373 NewDFSet.erase(Header);
374 DF->addBasicBlock(NewBB, NewDFSet);
376 // Now we must loop over all of the dominance frontiers in the function,
377 // replacing occurrences of Header with NewBB in some cases. If a block
378 // dominates a (now) predecessor of NewBB, but did not strictly dominate
379 // Header, it will have Header in it's DF set, but should now have NewBB in
381 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
382 // Get all of the dominators of the predecessor...
383 const DominatorSet::DomSetType &PredDoms =
384 DS.getDominators(OutsideBlocks[i]);
385 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
386 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
387 BasicBlock *PredDom = *PDI;
388 // If the loop header is in DF(PredDom), then PredDom didn't dominate
389 // the header but did dominate a predecessor outside of the loop. Now
390 // we change this entry to include the preheader in the DF instead of
392 DominanceFrontier::iterator DFI = DF->find(PredDom);
393 assert(DFI != DF->end() && "No dominance frontier for node?");
394 if (DFI->second.count(Header)) {
395 DF->removeFromFrontier(DFI, Header);
396 DF->addToFrontier(DFI, NewBB);
403 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
404 /// blocks. This method is used to split exit blocks that have predecessors
405 /// outside of the loop.
406 void LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
407 DominatorSet &DS = getAnalysis<DominatorSet>();
408 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
409 != L->getExitBlocks().end() && "Not a current exit block!");
411 std::vector<BasicBlock*> LoopBlocks;
412 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
414 LoopBlocks.push_back(*I);
416 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
417 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
419 // Update Loop Information - we know that the new block will be in the parent
421 if (Loop *Parent = L->getParentLoop())
422 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
424 // Replace any instances of Exit with NewBB in this and any nested loops...
425 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
426 if (I->hasExitBlock(Exit))
427 I->changeExitBlock(Exit, NewBB); // Update exit block information
429 // Update dominator information (set, immdom, domtree, and domfrontier)
430 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
433 /// AddBlockAndPredsToSet - Add the specified block, and all of its
434 /// predecessors, to the specified set, if it's not already in there. Stop
435 /// predecessor traversal when we reach StopBlock.
436 static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
437 std::set<BasicBlock*> &Blocks) {
438 if (!Blocks.insert(BB).second) return; // already processed.
439 if (BB == StopBlock) return; // Stop here!
441 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
442 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
445 static void ReplaceExitBlocksOfLoopAndParents(Loop *L, BasicBlock *Old,
447 if (!L->hasExitBlock(Old)) return;
448 L->changeExitBlock(Old, New);
449 ReplaceExitBlocksOfLoopAndParents(L->getParentLoop(), Old, New);
452 /// VerifyExitBlocks - This is a function which can be useful for hacking on the
453 /// LoopSimplify Code.
454 static void VerifyExitBlocks(Loop *L) {
455 std::vector<BasicBlock*> ExitBlocks;
456 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
457 BasicBlock *BB = L->getBlocks()[i];
458 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
459 if (!L->contains(*SI))
460 ExitBlocks.push_back(*SI);
463 std::vector<BasicBlock*> EB = L->getExitBlocks();
464 std::sort(EB.begin(), EB.end());
465 std::sort(ExitBlocks.begin(), ExitBlocks.end());
466 assert(EB == ExitBlocks && "Exit blocks were incorrectly updated!");
468 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
469 VerifyExitBlocks(*I);
472 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
473 /// PHI node that tells us how to partition the loops.
474 static PHINode *FindPHIToPartitionLoops(Loop *L) {
475 for (BasicBlock::iterator I = L->getHeader()->begin();
476 PHINode *PN = dyn_cast<PHINode>(I); ) {
478 if (Value *V = hasConstantValue(PN)) {
479 // This is a degenerate PHI already, don't modify it!
480 PN->replaceAllUsesWith(V);
481 PN->getParent()->getInstList().erase(PN);
483 // Scan this PHI node looking for a use of the PHI node by itself.
484 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
485 if (PN->getIncomingValue(i) == PN &&
486 L->contains(PN->getIncomingBlock(i)))
487 // We found something tasty to remove.
494 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
495 /// them out into a nested loop. This is important for code that looks like
500 /// br cond, Loop, Next
502 /// br cond2, Loop, Out
504 /// To identify this common case, we look at the PHI nodes in the header of the
505 /// loop. PHI nodes with unchanging values on one backedge correspond to values
506 /// that change in the "outer" loop, but not in the "inner" loop.
508 /// If we are able to separate out a loop, return the new outer loop that was
511 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
512 BasicBlock *Header = L->getHeader();
513 PHINode *PN = FindPHIToPartitionLoops(L);
514 if (PN == 0) return 0; // No known way to partition.
516 // Pull out all predecessors that have varying values in the loop. This
517 // handles the case when a PHI node has multiple instances of itself as
519 std::vector<BasicBlock*> OuterLoopPreds;
520 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
521 if (PN->getIncomingValue(i) != PN ||
522 !L->contains(PN->getIncomingBlock(i)))
523 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
525 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
527 // Update dominator information (set, immdom, domtree, and domfrontier)
528 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
530 // Create the new outer loop.
531 Loop *NewOuter = new Loop();
533 LoopInfo &LI = getAnalysis<LoopInfo>();
535 // Change the parent loop to use the outer loop as its child now.
536 if (Loop *Parent = L->getParentLoop())
537 Parent->replaceChildLoopWith(L, NewOuter);
539 LI.changeTopLevelLoop(L, NewOuter);
541 // This block is going to be our new header block: add it to this loop and all
543 NewOuter->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
545 // L is now a subloop of our outer loop.
546 NewOuter->addChildLoop(L);
548 // Add all of L's exit blocks to the outer loop.
549 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
550 NewOuter->addExitBlock(L->getExitBlocks()[i]);
552 // Add temporary exit block entries for NewBB. Add one for each edge in L
553 // that goes to NewBB.
554 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); PI != E; ++PI)
555 if (L->contains(*PI))
556 L->addExitBlock(NewBB);
558 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
559 NewOuter->addBlockEntry(L->getBlocks()[i]);
561 // Determine which blocks should stay in L and which should be moved out to
562 // the Outer loop now.
563 DominatorSet &DS = getAnalysis<DominatorSet>();
564 std::set<BasicBlock*> BlocksInL;
565 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
566 if (DS.dominates(Header, *PI))
567 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
570 // Scan all of the loop children of L, moving them to OuterLoop if they are
571 // not part of the inner loop.
572 for (Loop::iterator I = L->begin(); I != L->end(); )
573 if (BlocksInL.count((*I)->getHeader()))
574 ++I; // Loop remains in L
576 NewOuter->addChildLoop(L->removeChildLoop(I));
578 // Now that we know which blocks are in L and which need to be moved to
579 // OuterLoop, move any blocks that need it.
580 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
581 BasicBlock *BB = L->getBlocks()[i];
582 if (!BlocksInL.count(BB)) {
583 // Move this block to the parent, updating the exit blocks sets
584 L->removeBlockFromLoop(BB);
586 LI.changeLoopFor(BB, NewOuter);
591 // Check all subloops of this loop, replacing any exit blocks that got
592 // revectored with the new basic block.
593 for (pred_iterator I = pred_begin(NewBB), E = pred_end(NewBB); I != E; ++I)
594 if (NewOuter->contains(*I)) {
595 // Change any exit blocks that used to go to Header to go to NewBB
597 ReplaceExitBlocksOfLoopAndParents((Loop*)LI[*I], Header, NewBB);
600 //VerifyExitBlocks(NewOuter);
606 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
607 /// has more than one backedge in it. If this occurs, revector all of these
608 /// backedges to target a new basic block and have that block branch to the loop
609 /// header. This ensures that loops have exactly one backedge.
611 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
612 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
614 // Get information about the loop
615 BasicBlock *Preheader = L->getLoopPreheader();
616 BasicBlock *Header = L->getHeader();
617 Function *F = Header->getParent();
619 // Figure out which basic blocks contain back-edges to the loop header.
620 std::vector<BasicBlock*> BackedgeBlocks;
621 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
622 if (*I != Preheader) BackedgeBlocks.push_back(*I);
624 // Create and insert the new backedge block...
625 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
626 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
628 // Move the new backedge block to right after the last backedge block.
629 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
630 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
632 // Now that the block has been inserted into the function, create PHI nodes in
633 // the backedge block which correspond to any PHI nodes in the header block.
634 for (BasicBlock::iterator I = Header->begin();
635 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
636 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
638 NewPN->op_reserve(2*BackedgeBlocks.size());
640 // Loop over the PHI node, moving all entries except the one for the
641 // preheader over to the new PHI node.
642 unsigned PreheaderIdx = ~0U;
643 bool HasUniqueIncomingValue = true;
644 Value *UniqueValue = 0;
645 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
646 BasicBlock *IBB = PN->getIncomingBlock(i);
647 Value *IV = PN->getIncomingValue(i);
648 if (IBB == Preheader) {
651 NewPN->addIncoming(IV, IBB);
652 if (HasUniqueIncomingValue) {
653 if (UniqueValue == 0)
655 else if (UniqueValue != IV)
656 HasUniqueIncomingValue = false;
661 // Delete all of the incoming values from the old PN except the preheader's
662 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
663 if (PreheaderIdx != 0) {
664 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
665 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
667 PN->op_erase(PN->op_begin()+2, PN->op_end());
669 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
670 PN->addIncoming(NewPN, BEBlock);
672 // As an optimization, if all incoming values in the new PhiNode (which is a
673 // subset of the incoming values of the old PHI node) have the same value,
674 // eliminate the PHI Node.
675 if (HasUniqueIncomingValue) {
676 NewPN->replaceAllUsesWith(UniqueValue);
677 BEBlock->getInstList().erase(NewPN);
681 // Now that all of the PHI nodes have been inserted and adjusted, modify the
682 // backedge blocks to just to the BEBlock instead of the header.
683 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
684 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
685 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
686 if (TI->getSuccessor(Op) == Header)
687 TI->setSuccessor(Op, BEBlock);
690 //===--- Update all analyses which we must preserve now -----------------===//
692 // Update Loop Information - we know that this block is now in the current
693 // loop and all parent loops.
694 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
696 // Replace any instances of Exit with NewBB in this and any nested loops...
697 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
698 if (I->hasExitBlock(Header))
699 I->changeExitBlock(Header, BEBlock); // Update exit block information
701 // Update dominator information (set, immdom, domtree, and domfrontier)
702 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
705 /// UpdateDomInfoForRevectoredPreds - This method is used to update the four
706 /// different kinds of dominator information (dominator sets, immediate
707 /// dominators, dominator trees, and dominance frontiers) after a new block has
708 /// been added to the CFG.
710 /// This only supports the case when an existing block (known as "NewBBSucc"),
711 /// had some of its predecessors factored into a new basic block. This
712 /// transformation inserts a new basic block ("NewBB"), with a single
713 /// unconditional branch to NewBBSucc, and moves some predecessors of
714 /// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
715 /// PredBlocks, even though they are the same as
716 /// pred_begin(NewBB)/pred_end(NewBB).
718 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
719 std::vector<BasicBlock*> &PredBlocks) {
720 assert(!PredBlocks.empty() && "No predblocks??");
721 assert(succ_begin(NewBB) != succ_end(NewBB) &&
722 ++succ_begin(NewBB) == succ_end(NewBB) &&
723 "NewBB should have a single successor!");
724 BasicBlock *NewBBSucc = *succ_begin(NewBB);
725 DominatorSet &DS = getAnalysis<DominatorSet>();
727 // Update dominator information... The blocks that dominate NewBB are the
728 // intersection of the dominators of predecessors, plus the block itself.
730 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
731 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
732 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
733 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
734 DS.addBasicBlock(NewBB, NewBBDomSet);
736 // The newly inserted basic block will dominate existing basic blocks iff the
737 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
738 // the non-pred blocks, then they all must be the same block!
740 bool NewBBDominatesNewBBSucc = true;
742 BasicBlock *OnePred = PredBlocks[0];
743 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
744 if (PredBlocks[i] != OnePred) {
745 NewBBDominatesNewBBSucc = false;
749 if (NewBBDominatesNewBBSucc)
750 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
752 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
753 NewBBDominatesNewBBSucc = false;
758 // The other scenario where the new block can dominate its successors are when
759 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
761 if (!NewBBDominatesNewBBSucc) {
762 NewBBDominatesNewBBSucc = true;
763 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
765 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
766 NewBBDominatesNewBBSucc = false;
771 // If NewBB dominates some blocks, then it will dominate all blocks that
773 if (NewBBDominatesNewBBSucc) {
774 BasicBlock *PredBlock = PredBlocks[0];
775 Function *F = NewBB->getParent();
776 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
777 if (DS.dominates(NewBBSucc, I))
778 DS.addDominator(I, NewBB);
781 // Update immediate dominator information if we have it...
782 BasicBlock *NewBBIDom = 0;
783 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
784 // To find the immediate dominator of the new exit node, we trace up the
785 // immediate dominators of a predecessor until we find a basic block that
786 // dominates the exit block.
788 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
789 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
790 assert(Dom != 0 && "No shared dominator found???");
794 // Set the immediate dominator now...
795 ID->addNewBlock(NewBB, Dom);
796 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
798 // If NewBB strictly dominates other blocks, we need to update their idom's
799 // now. The only block that need adjustment is the NewBBSucc block, whose
800 // idom should currently be set to PredBlocks[0].
801 if (NewBBDominatesNewBBSucc)
802 ID->setImmediateDominator(NewBBSucc, NewBB);
805 // Update DominatorTree information if it is active.
806 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
807 // If we don't have ImmediateDominator info around, calculate the idom as
809 DominatorTree::Node *NewBBIDomNode;
811 NewBBIDomNode = DT->getNode(NewBBIDom);
813 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
814 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
815 NewBBIDomNode = NewBBIDomNode->getIDom();
816 assert(NewBBIDomNode && "No shared dominator found??");
820 // Create the new dominator tree node... and set the idom of NewBB.
821 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
823 // If NewBB strictly dominates other blocks, then it is now the immediate
824 // dominator of NewBBSucc. Update the dominator tree as appropriate.
825 if (NewBBDominatesNewBBSucc) {
826 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
827 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
831 // Update dominance frontier information...
832 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
833 // If NewBB dominates NewBBSucc, then the global dominance frontiers are not
834 // changed. DF(NewBB) is now going to be the DF(PredBlocks[0]) without the
835 // stuff that the new block does not dominate a predecessor of.
836 if (NewBBDominatesNewBBSucc) {
837 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
838 if (DFI != DF->end()) {
839 DominanceFrontier::DomSetType Set = DFI->second;
840 // Filter out stuff in Set that we do not dominate a predecessor of.
841 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
842 E = Set.end(); SetI != E;) {
843 bool DominatesPred = false;
844 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
846 if (DS.dominates(NewBB, *PI))
847 DominatesPred = true;
854 DF->addBasicBlock(NewBB, Set);
858 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
859 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
860 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
861 DominanceFrontier::DomSetType NewDFSet;
862 NewDFSet.insert(NewBBSucc);
863 DF->addBasicBlock(NewBB, NewDFSet);
865 // Now we must loop over all of the dominance frontiers in the function,
866 // replacing occurrences of NewBBSucc with NewBB in some cases. All
867 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
868 // their dominance frontier must be updated to contain NewBB instead.
870 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
871 BasicBlock *Pred = PredBlocks[i];
872 // Get all of the dominators of the predecessor...
873 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
874 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
875 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
876 BasicBlock *PredDom = *PDI;
878 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
879 // dominate NewBBSucc but did dominate a predecessor of it. Now we
880 // change this entry to include NewBB in the DF instead of NewBBSucc.
881 DominanceFrontier::iterator DFI = DF->find(PredDom);
882 assert(DFI != DF->end() && "No dominance frontier for node?");
883 if (DFI->second.count(NewBBSucc)) {
884 DF->removeFromFrontier(DFI, NewBBSucc);
885 DF->addToFrontier(DFI, NewBB);