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/Instructions.h"
38 #include "llvm/Function.h"
39 #include "llvm/Type.h"
40 #include "llvm/Analysis/AliasAnalysis.h"
41 #include "llvm/Analysis/Dominators.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Support/CFG.h"
44 #include "llvm/Support/Visibility.h"
45 #include "llvm/ADT/SetOperations.h"
46 #include "llvm/ADT/SetVector.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/ADT/DepthFirstIterator.h"
53 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
55 NumNested("loopsimplify", "Number of nested loops split out");
57 struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
58 // AA - If we have an alias analysis object to update, this is it, otherwise
63 virtual bool runOnFunction(Function &F);
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 // We need loop information to identify the loops...
67 AU.addRequired<LoopInfo>();
68 AU.addRequired<DominatorSet>();
69 AU.addRequired<DominatorTree>();
71 AU.addPreserved<LoopInfo>();
72 AU.addPreserved<DominatorSet>();
73 AU.addPreserved<ImmediateDominators>();
74 AU.addPreserved<ETForest>();
75 AU.addPreserved<DominatorTree>();
76 AU.addPreserved<DominanceFrontier>();
77 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
80 bool ProcessLoop(Loop *L);
81 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
82 const std::vector<BasicBlock*> &Preds);
83 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
84 void InsertPreheaderForLoop(Loop *L);
85 Loop *SeparateNestedLoop(Loop *L);
86 void InsertUniqueBackedgeBlock(Loop *L);
88 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
89 std::vector<BasicBlock*> &PredBlocks);
92 RegisterOpt<LoopSimplify>
93 X("loopsimplify", "Canonicalize natural loops", true);
96 // Publically exposed interface to pass...
97 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
98 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
100 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
101 /// it in any convenient order) inserting preheaders...
103 bool LoopSimplify::runOnFunction(Function &F) {
104 bool Changed = false;
105 LI = &getAnalysis<LoopInfo>();
106 AA = getAnalysisToUpdate<AliasAnalysis>();
108 // Check to see that no blocks (other than the header) in loops have
109 // predecessors that are not in loops. This is not valid for natural loops,
110 // but can occur if the blocks are unreachable. Since they are unreachable we
111 // can just shamelessly destroy their terminators to make them not branch into
113 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
114 // This case can only occur for unreachable blocks. Blocks that are
115 // unreachable can't be in loops, so filter those blocks out.
116 if (LI->getLoopFor(BB)) continue;
118 bool BlockUnreachable = false;
119 TerminatorInst *TI = BB->getTerminator();
121 // Check to see if any successors of this block are non-loop-header loops
122 // that are not the header.
123 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
124 // If this successor is not in a loop, BB is clearly ok.
125 Loop *L = LI->getLoopFor(TI->getSuccessor(i));
128 // If the succ is the loop header, and if L is a top-level loop, then this
129 // is an entrance into a loop through the header, which is also ok.
130 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
133 // Otherwise, this is an entrance into a loop from some place invalid.
134 // Either the loop structure is invalid and this is not a natural loop (in
135 // which case the compiler is buggy somewhere else) or BB is unreachable.
136 BlockUnreachable = true;
140 // If this block is ok, check the next one.
141 if (!BlockUnreachable) continue;
143 // Otherwise, this block is dead. To clean up the CFG and to allow later
144 // loop transformations to ignore this case, we delete the edges into the
145 // loop by replacing the terminator.
147 // Remove PHI entries from the successors.
148 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
149 TI->getSuccessor(i)->removePredecessor(BB);
151 // Add a new unreachable instruction.
152 new UnreachableInst(TI);
154 // Delete the dead terminator.
155 if (AA) AA->deleteValue(&BB->back());
156 BB->getInstList().pop_back();
160 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
161 Changed |= ProcessLoop(*I);
166 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
167 /// all loops have preheaders.
169 bool LoopSimplify::ProcessLoop(Loop *L) {
170 bool Changed = false;
171 // Canonicalize inner loops before outer loops. Inner loop canonicalization
172 // can provide work for the outer loop to canonicalize.
173 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
174 Changed |= ProcessLoop(*I);
176 assert(L->getBlocks()[0] == L->getHeader() &&
177 "Header isn't first block in loop?");
179 // Does the loop already have a preheader? If so, don't insert one.
180 if (L->getLoopPreheader() == 0) {
181 InsertPreheaderForLoop(L);
186 // Next, check to make sure that all exit nodes of the loop only have
187 // predecessors that are inside of the loop. This check guarantees that the
188 // loop preheader/header will dominate the exit blocks. If the exit block has
189 // predecessors from outside of the loop, split the edge now.
190 std::vector<BasicBlock*> ExitBlocks;
191 L->getExitBlocks(ExitBlocks);
193 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
194 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
195 E = ExitBlockSet.end(); I != E; ++I) {
196 BasicBlock *ExitBlock = *I;
197 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
199 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
201 if (!L->contains(*PI)) {
202 RewriteLoopExitBlock(L, ExitBlock);
209 // If the header has more than two predecessors at this point (from the
210 // preheader and from multiple backedges), we must adjust the loop.
211 if (L->getNumBackEdges() != 1) {
213 // If this is really a nested loop, rip it out into a child loop.
214 if (Loop *NL = SeparateNestedLoop(L)) {
216 // This is a big restructuring change, reprocess the whole loop.
221 InsertUniqueBackedgeBlock(L);
226 // Scan over the PHI nodes in the loop header. Since they now have only two
227 // incoming values (the loop is canonicalized), we may have simplified the PHI
228 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
230 for (BasicBlock::iterator I = L->getHeader()->begin();
231 (PN = dyn_cast<PHINode>(I++)); )
232 if (Value *V = PN->hasConstantValue()) {
233 PN->replaceAllUsesWith(V);
234 PN->eraseFromParent();
240 /// SplitBlockPredecessors - Split the specified block into two blocks. We want
241 /// to move the predecessors specified in the Preds list to point to the new
242 /// block, leaving the remaining predecessors pointing to BB. This method
243 /// updates the SSA PHINode's, but no other analyses.
245 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
247 const std::vector<BasicBlock*> &Preds) {
249 // Create new basic block, insert right before the original block...
250 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
252 // The preheader first gets an unconditional branch to the loop header...
253 BranchInst *BI = new BranchInst(BB, NewBB);
255 // For every PHI node in the block, insert a PHI node into NewBB where the
256 // incoming values from the out of loop edges are moved to NewBB. We have two
257 // possible cases here. If the loop is dead, we just insert dummy entries
258 // into the PHI nodes for the new edge. If the loop is not dead, we move the
259 // incoming edges in BB into new PHI nodes in NewBB.
261 if (!Preds.empty()) { // Is the loop not obviously dead?
262 // Check to see if the values being merged into the new block need PHI
263 // nodes. If so, insert them.
264 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
265 PHINode *PN = cast<PHINode>(I);
268 // Check to see if all of the values coming in are the same. If so, we
269 // don't need to create a new PHI node.
270 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
271 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
272 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
277 // If the values coming into the block are not the same, we need a PHI.
279 // Create the new PHI node, insert it into NewBB at the end of the block
280 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
281 if (AA) AA->copyValue(PN, NewPHI);
283 // Move all of the edges from blocks outside the loop to the new PHI
284 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
285 Value *V = PN->removeIncomingValue(Preds[i], false);
286 NewPHI->addIncoming(V, Preds[i]);
290 // Remove all of the edges coming into the PHI nodes from outside of the
292 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
293 PN->removeIncomingValue(Preds[i], false);
296 // Add an incoming value to the PHI node in the loop for the preheader
298 PN->addIncoming(InVal, NewBB);
300 // Can we eliminate this phi node now?
301 if (Value *V = PN->hasConstantValue(true)) {
302 if (!isa<Instruction>(V) ||
303 getAnalysis<DominatorSet>().dominates(cast<Instruction>(V), PN)) {
304 PN->replaceAllUsesWith(V);
305 if (AA) AA->deleteValue(PN);
306 BB->getInstList().erase(PN);
311 // Now that the PHI nodes are updated, actually move the edges from
312 // Preds to point to NewBB instead of BB.
314 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
315 TerminatorInst *TI = Preds[i]->getTerminator();
316 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
317 if (TI->getSuccessor(s) == BB)
318 TI->setSuccessor(s, NewBB);
321 } else { // Otherwise the loop is dead...
322 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
323 PHINode *PN = cast<PHINode>(I);
324 // Insert dummy values as the incoming value...
325 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
331 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
332 /// preheader, this method is called to insert one. This method has two phases:
333 /// preheader insertion and analysis updating.
335 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
336 BasicBlock *Header = L->getHeader();
338 // Compute the set of predecessors of the loop that are not in the loop.
339 std::vector<BasicBlock*> OutsideBlocks;
340 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
342 if (!L->contains(*PI)) // Coming in from outside the loop?
343 OutsideBlocks.push_back(*PI); // Keep track of it...
345 // Split out the loop pre-header
347 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
349 //===--------------------------------------------------------------------===//
350 // Update analysis results now that we have performed the transformation
353 // We know that we have loop information to update... update it now.
354 if (Loop *Parent = L->getParentLoop())
355 Parent->addBasicBlockToLoop(NewBB, *LI);
357 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
358 DominatorTree &DT = getAnalysis<DominatorTree>();
361 // Update the dominator tree information.
362 // The immediate dominator of the preheader is the immediate dominator of
364 DominatorTree::Node *PHDomTreeNode =
365 DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
366 BasicBlock *oldHeaderIDom = DT.getNode(Header)->getIDom()->getBlock();
368 // Change the header node so that PNHode is the new immediate dominator
369 DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
372 // The blocks that dominate NewBB are the blocks that dominate Header,
373 // minus Header, plus NewBB.
374 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
375 DomSet.erase(Header); // Header does not dominate us...
376 DS.addBasicBlock(NewBB, DomSet);
378 // The newly created basic block dominates all nodes dominated by Header.
379 for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
380 E = df_end(PHDomTreeNode); DFI != E; ++DFI)
381 DS.addDominator((*DFI)->getBlock(), NewBB);
384 // Update immediate dominator information if we have it...
385 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
386 // Whatever i-dominated the header node now immediately dominates NewBB
387 ID->addNewBlock(NewBB, ID->get(Header));
389 // The preheader now is the immediate dominator for the header node...
390 ID->setImmediateDominator(Header, NewBB);
393 // Update ET Forest information if we have it...
394 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
395 // Whatever i-dominated the header node now immediately dominates NewBB
396 EF->addNewBlock(NewBB, oldHeaderIDom);
398 // The preheader now is the immediate dominator for the header node...
399 EF->setImmediateDominator(Header, NewBB);
402 // Update dominance frontier information...
403 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
404 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
405 // everything that Header does, and it strictly dominates Header in
407 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
408 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
409 NewDFSet.erase(Header);
410 DF->addBasicBlock(NewBB, NewDFSet);
412 // Now we must loop over all of the dominance frontiers in the function,
413 // replacing occurrences of Header with NewBB in some cases. If a block
414 // dominates a (now) predecessor of NewBB, but did not strictly dominate
415 // Header, it will have Header in it's DF set, but should now have NewBB in
417 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
418 // Get all of the dominators of the predecessor...
419 const DominatorSet::DomSetType &PredDoms =
420 DS.getDominators(OutsideBlocks[i]);
421 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
422 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
423 BasicBlock *PredDom = *PDI;
424 // If the loop header is in DF(PredDom), then PredDom didn't dominate
425 // the header but did dominate a predecessor outside of the loop. Now
426 // we change this entry to include the preheader in the DF instead of
428 DominanceFrontier::iterator DFI = DF->find(PredDom);
429 assert(DFI != DF->end() && "No dominance frontier for node?");
430 if (DFI->second.count(Header)) {
431 DF->removeFromFrontier(DFI, Header);
432 DF->addToFrontier(DFI, NewBB);
439 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
440 /// blocks. This method is used to split exit blocks that have predecessors
441 /// outside of the loop.
442 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
443 std::vector<BasicBlock*> LoopBlocks;
444 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
446 LoopBlocks.push_back(*I);
448 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
449 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
451 // Update Loop Information - we know that the new block will be in whichever
452 // loop the Exit block is in. Note that it may not be in that immediate loop,
453 // if the successor is some other loop header. In that case, we continue
454 // walking up the loop tree to find a loop that contains both the successor
455 // block and the predecessor block.
456 Loop *SuccLoop = LI->getLoopFor(Exit);
457 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
458 SuccLoop = SuccLoop->getParentLoop();
460 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
462 // Update dominator information (set, immdom, domtree, and domfrontier)
463 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
467 /// AddBlockAndPredsToSet - Add the specified block, and all of its
468 /// predecessors, to the specified set, if it's not already in there. Stop
469 /// predecessor traversal when we reach StopBlock.
470 static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
471 std::set<BasicBlock*> &Blocks) {
472 if (!Blocks.insert(BB).second) return; // already processed.
473 if (BB == StopBlock) return; // Stop here!
475 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
476 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
479 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
480 /// PHI node that tells us how to partition the loops.
481 static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorSet &DS,
483 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
484 PHINode *PN = cast<PHINode>(I);
486 if (Value *V = PN->hasConstantValue())
487 if (!isa<Instruction>(V) || DS.dominates(cast<Instruction>(V), PN)) {
488 // This is a degenerate PHI already, don't modify it!
489 PN->replaceAllUsesWith(V);
490 if (AA) AA->deleteValue(PN);
491 PN->eraseFromParent();
495 // Scan this PHI node looking for a use of the PHI node by itself.
496 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
497 if (PN->getIncomingValue(i) == PN &&
498 L->contains(PN->getIncomingBlock(i)))
499 // We found something tasty to remove.
505 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
506 /// them out into a nested loop. This is important for code that looks like
511 /// br cond, Loop, Next
513 /// br cond2, Loop, Out
515 /// To identify this common case, we look at the PHI nodes in the header of the
516 /// loop. PHI nodes with unchanging values on one backedge correspond to values
517 /// that change in the "outer" loop, but not in the "inner" loop.
519 /// If we are able to separate out a loop, return the new outer loop that was
522 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
523 PHINode *PN = FindPHIToPartitionLoops(L, getAnalysis<DominatorSet>(), AA);
524 if (PN == 0) return 0; // No known way to partition.
526 // Pull out all predecessors that have varying values in the loop. This
527 // handles the case when a PHI node has multiple instances of itself as
529 std::vector<BasicBlock*> OuterLoopPreds;
530 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
531 if (PN->getIncomingValue(i) != PN ||
532 !L->contains(PN->getIncomingBlock(i)))
533 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
535 BasicBlock *Header = L->getHeader();
536 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
538 // Update dominator information (set, immdom, domtree, and domfrontier)
539 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
541 // Create the new outer loop.
542 Loop *NewOuter = new Loop();
544 // Change the parent loop to use the outer loop as its child now.
545 if (Loop *Parent = L->getParentLoop())
546 Parent->replaceChildLoopWith(L, NewOuter);
548 LI->changeTopLevelLoop(L, NewOuter);
550 // This block is going to be our new header block: add it to this loop and all
552 NewOuter->addBasicBlockToLoop(NewBB, *LI);
554 // L is now a subloop of our outer loop.
555 NewOuter->addChildLoop(L);
557 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
558 NewOuter->addBlockEntry(L->getBlocks()[i]);
560 // Determine which blocks should stay in L and which should be moved out to
561 // the Outer loop now.
562 DominatorSet &DS = getAnalysis<DominatorSet>();
563 std::set<BasicBlock*> BlocksInL;
564 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
565 if (DS.dominates(Header, *PI))
566 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
569 // Scan all of the loop children of L, moving them to OuterLoop if they are
570 // not part of the inner loop.
571 for (Loop::iterator I = L->begin(); I != L->end(); )
572 if (BlocksInL.count((*I)->getHeader()))
573 ++I; // Loop remains in L
575 NewOuter->addChildLoop(L->removeChildLoop(I));
577 // Now that we know which blocks are in L and which need to be moved to
578 // OuterLoop, move any blocks that need it.
579 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
580 BasicBlock *BB = L->getBlocks()[i];
581 if (!BlocksInL.count(BB)) {
582 // Move this block to the parent, updating the exit blocks sets
583 L->removeBlockFromLoop(BB);
585 LI->changeLoopFor(BB, NewOuter);
595 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
596 /// has more than one backedge in it. If this occurs, revector all of these
597 /// backedges to target a new basic block and have that block branch to the loop
598 /// header. This ensures that loops have exactly one backedge.
600 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
601 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
603 // Get information about the loop
604 BasicBlock *Preheader = L->getLoopPreheader();
605 BasicBlock *Header = L->getHeader();
606 Function *F = Header->getParent();
608 // Figure out which basic blocks contain back-edges to the loop header.
609 std::vector<BasicBlock*> BackedgeBlocks;
610 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
611 if (*I != Preheader) BackedgeBlocks.push_back(*I);
613 // Create and insert the new backedge block...
614 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
615 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
617 // Move the new backedge block to right after the last backedge block.
618 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
619 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
621 // Now that the block has been inserted into the function, create PHI nodes in
622 // the backedge block which correspond to any PHI nodes in the header block.
623 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
624 PHINode *PN = cast<PHINode>(I);
625 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
627 NewPN->reserveOperandSpace(BackedgeBlocks.size());
628 if (AA) AA->copyValue(PN, NewPN);
630 // Loop over the PHI node, moving all entries except the one for the
631 // preheader over to the new PHI node.
632 unsigned PreheaderIdx = ~0U;
633 bool HasUniqueIncomingValue = true;
634 Value *UniqueValue = 0;
635 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
636 BasicBlock *IBB = PN->getIncomingBlock(i);
637 Value *IV = PN->getIncomingValue(i);
638 if (IBB == Preheader) {
641 NewPN->addIncoming(IV, IBB);
642 if (HasUniqueIncomingValue) {
643 if (UniqueValue == 0)
645 else if (UniqueValue != IV)
646 HasUniqueIncomingValue = false;
651 // Delete all of the incoming values from the old PN except the preheader's
652 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
653 if (PreheaderIdx != 0) {
654 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
655 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
657 // Nuke all entries except the zero'th.
658 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
659 PN->removeIncomingValue(e-i, false);
661 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
662 PN->addIncoming(NewPN, BEBlock);
664 // As an optimization, if all incoming values in the new PhiNode (which is a
665 // subset of the incoming values of the old PHI node) have the same value,
666 // eliminate the PHI Node.
667 if (HasUniqueIncomingValue) {
668 NewPN->replaceAllUsesWith(UniqueValue);
669 if (AA) AA->deleteValue(NewPN);
670 BEBlock->getInstList().erase(NewPN);
674 // Now that all of the PHI nodes have been inserted and adjusted, modify the
675 // backedge blocks to just to the BEBlock instead of the header.
676 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
677 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
678 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
679 if (TI->getSuccessor(Op) == Header)
680 TI->setSuccessor(Op, BEBlock);
683 //===--- Update all analyses which we must preserve now -----------------===//
685 // Update Loop Information - we know that this block is now in the current
686 // loop and all parent loops.
687 L->addBasicBlockToLoop(BEBlock, *LI);
689 // Update dominator information (set, immdom, domtree, and domfrontier)
690 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
693 /// UpdateDomInfoForRevectoredPreds - This method is used to update the four
694 /// different kinds of dominator information (dominator sets, immediate
695 /// dominators, dominator trees, and dominance frontiers) after a new block has
696 /// been added to the CFG.
698 /// This only supports the case when an existing block (known as "NewBBSucc"),
699 /// had some of its predecessors factored into a new basic block. This
700 /// transformation inserts a new basic block ("NewBB"), with a single
701 /// unconditional branch to NewBBSucc, and moves some predecessors of
702 /// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
703 /// PredBlocks, even though they are the same as
704 /// pred_begin(NewBB)/pred_end(NewBB).
706 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
707 std::vector<BasicBlock*> &PredBlocks) {
708 assert(!PredBlocks.empty() && "No predblocks??");
709 assert(succ_begin(NewBB) != succ_end(NewBB) &&
710 ++succ_begin(NewBB) == succ_end(NewBB) &&
711 "NewBB should have a single successor!");
712 BasicBlock *NewBBSucc = *succ_begin(NewBB);
713 DominatorSet &DS = getAnalysis<DominatorSet>();
715 // Update dominator information... The blocks that dominate NewBB are the
716 // intersection of the dominators of predecessors, plus the block itself.
718 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
719 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
720 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
721 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
722 DS.addBasicBlock(NewBB, NewBBDomSet);
724 // The newly inserted basic block will dominate existing basic blocks iff the
725 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
726 // the non-pred blocks, then they all must be the same block!
728 bool NewBBDominatesNewBBSucc = true;
730 BasicBlock *OnePred = PredBlocks[0];
731 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
732 if (PredBlocks[i] != OnePred) {
733 NewBBDominatesNewBBSucc = false;
737 if (NewBBDominatesNewBBSucc)
738 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
740 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
741 NewBBDominatesNewBBSucc = false;
746 // The other scenario where the new block can dominate its successors are when
747 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
749 if (!NewBBDominatesNewBBSucc) {
750 NewBBDominatesNewBBSucc = true;
751 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
753 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
754 NewBBDominatesNewBBSucc = false;
759 // If NewBB dominates some blocks, then it will dominate all blocks that
761 if (NewBBDominatesNewBBSucc) {
762 BasicBlock *PredBlock = PredBlocks[0];
763 Function *F = NewBB->getParent();
764 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
765 if (DS.dominates(NewBBSucc, I))
766 DS.addDominator(I, NewBB);
769 // Update immediate dominator information if we have it...
770 BasicBlock *NewBBIDom = 0;
771 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
772 // To find the immediate dominator of the new exit node, we trace up the
773 // immediate dominators of a predecessor until we find a basic block that
774 // dominates the exit block.
776 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
777 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
778 assert(Dom != 0 && "No shared dominator found???");
782 // Set the immediate dominator now...
783 ID->addNewBlock(NewBB, Dom);
784 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
786 // If NewBB strictly dominates other blocks, we need to update their idom's
787 // now. The only block that need adjustment is the NewBBSucc block, whose
788 // idom should currently be set to PredBlocks[0].
789 if (NewBBDominatesNewBBSucc)
790 ID->setImmediateDominator(NewBBSucc, NewBB);
793 // Update DominatorTree information if it is active.
794 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
795 // If we don't have ImmediateDominator info around, calculate the idom as
797 DominatorTree::Node *NewBBIDomNode;
799 NewBBIDomNode = DT->getNode(NewBBIDom);
801 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
802 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
803 NewBBIDomNode = NewBBIDomNode->getIDom();
804 assert(NewBBIDomNode && "No shared dominator found??");
806 NewBBIDom = NewBBIDomNode->getBlock();
809 // Create the new dominator tree node... and set the idom of NewBB.
810 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
812 // If NewBB strictly dominates other blocks, then it is now the immediate
813 // dominator of NewBBSucc. Update the dominator tree as appropriate.
814 if (NewBBDominatesNewBBSucc) {
815 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
816 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
820 // Update ET-Forest information if it is active.
821 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
822 EF->addNewBlock(NewBB, NewBBIDom);
823 if (NewBBDominatesNewBBSucc)
824 EF->setImmediateDominator(NewBBSucc, NewBB);
827 // Update dominance frontier information...
828 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
829 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
830 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
832 if (NewBBDominatesNewBBSucc) {
833 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
834 if (DFI != DF->end()) {
835 DominanceFrontier::DomSetType Set = DFI->second;
836 // Filter out stuff in Set that we do not dominate a predecessor of.
837 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
838 E = Set.end(); SetI != E;) {
839 bool DominatesPred = false;
840 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
842 if (DS.dominates(NewBB, *PI))
843 DominatesPred = true;
850 DF->addBasicBlock(NewBB, Set);
854 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
855 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
856 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
857 DominanceFrontier::DomSetType NewDFSet;
858 NewDFSet.insert(NewBBSucc);
859 DF->addBasicBlock(NewBB, NewDFSet);
862 // Now we must loop over all of the dominance frontiers in the function,
863 // replacing occurrences of NewBBSucc with NewBB in some cases. All
864 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
865 // their dominance frontier must be updated to contain NewBB instead.
867 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
868 BasicBlock *Pred = PredBlocks[i];
869 // Get all of the dominators of the predecessor...
870 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
871 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
872 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
873 BasicBlock *PredDom = *PDI;
875 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
876 // dominate NewBBSucc but did dominate a predecessor of it. Now we
877 // change this entry to include NewBB in the DF instead of NewBBSucc.
878 DominanceFrontier::iterator DFI = DF->find(PredDom);
879 assert(DFI != DF->end() && "No dominance frontier for node?");
880 if (DFI->second.count(NewBBSucc)) {
881 // If NewBBSucc should not stay in our dominator frontier, remove it.
882 // We remove it unless there is a predecessor of NewBBSucc that we
883 // dominate, but we don't strictly dominate NewBBSucc.
884 bool ShouldRemove = true;
885 if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
886 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
887 // Check to see if it dominates any predecessors of NewBBSucc.
888 for (pred_iterator PI = pred_begin(NewBBSucc),
889 E = pred_end(NewBBSucc); PI != E; ++PI)
890 if (DS.dominates(PredDom, *PI)) {
891 ShouldRemove = false;
897 DF->removeFromFrontier(DFI, NewBBSucc);
898 DF->addToFrontier(DFI, NewBB);