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/ADT/SetOperations.h"
45 #include "llvm/ADT/SetVector.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/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 // AA - If we have an alias analysis object to update, this is it, otherwise
62 virtual bool runOnFunction(Function &F);
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 // We need loop information to identify the loops...
66 AU.addRequired<LoopInfo>();
67 AU.addRequired<DominatorSet>();
68 AU.addRequired<DominatorTree>();
70 AU.addPreserved<LoopInfo>();
71 AU.addPreserved<DominatorSet>();
72 AU.addPreserved<ImmediateDominators>();
73 AU.addPreserved<ETForest>();
74 AU.addPreserved<DominatorTree>();
75 AU.addPreserved<DominanceFrontier>();
76 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
79 bool ProcessLoop(Loop *L);
80 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
81 const std::vector<BasicBlock*> &Preds);
82 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
83 void InsertPreheaderForLoop(Loop *L);
84 Loop *SeparateNestedLoop(Loop *L);
85 void InsertUniqueBackedgeBlock(Loop *L);
87 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
88 std::vector<BasicBlock*> &PredBlocks);
91 RegisterOpt<LoopSimplify>
92 X("loopsimplify", "Canonicalize natural loops", true);
95 // Publically exposed interface to pass...
96 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
97 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
99 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
100 /// it in any convenient order) inserting preheaders...
102 bool LoopSimplify::runOnFunction(Function &F) {
103 bool Changed = false;
104 LI = &getAnalysis<LoopInfo>();
105 AA = getAnalysisToUpdate<AliasAnalysis>();
107 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
108 Changed |= ProcessLoop(*I);
113 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
114 /// all loops have preheaders.
116 bool LoopSimplify::ProcessLoop(Loop *L) {
117 bool Changed = false;
118 // Canonicalize inner loops before outer loops. Inner loop canonicalization
119 // can provide work for the outer loop to canonicalize.
120 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
121 Changed |= ProcessLoop(*I);
123 // Check to see that no blocks (other than the header) in the loop have
124 // predecessors that are not in the loop. This is not valid for natural
125 // loops, but can occur if the blocks are unreachable. Since they are
126 // unreachable we can just shamelessly destroy their terminators to make them
127 // not branch into the loop!
128 assert(L->getBlocks()[0] == L->getHeader() &&
129 "Header isn't first block in loop?");
130 for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
131 BasicBlock *LoopBB = L->getBlocks()[i];
133 for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
135 if (!L->contains(*PI)) {
136 // This predecessor is not in the loop. Kill its terminator!
137 BasicBlock *DeadBlock = *PI;
138 for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
140 (*SI)->removePredecessor(DeadBlock); // Remove PHI node entries
142 // Delete the dead terminator.
143 if (AA) AA->deleteValue(&DeadBlock->back());
144 DeadBlock->getInstList().pop_back();
147 if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
148 RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
149 new ReturnInst(RetVal, DeadBlock);
150 goto Retry; // We just invalidated the pred_iterator. Retry.
154 // Does the loop already have a preheader? If so, don't modify the loop...
155 if (L->getLoopPreheader() == 0) {
156 InsertPreheaderForLoop(L);
161 // Next, check to make sure that all exit nodes of the loop only have
162 // predecessors that are inside of the loop. This check guarantees that the
163 // loop preheader/header will dominate the exit blocks. If the exit block has
164 // predecessors from outside of the loop, split the edge now.
165 std::vector<BasicBlock*> ExitBlocks;
166 L->getExitBlocks(ExitBlocks);
168 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
169 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
170 E = ExitBlockSet.end(); I != E; ++I) {
171 BasicBlock *ExitBlock = *I;
172 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
174 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
176 if (!L->contains(*PI)) {
177 RewriteLoopExitBlock(L, ExitBlock);
184 // If the header has more than two predecessors at this point (from the
185 // preheader and from multiple backedges), we must adjust the loop.
186 if (L->getNumBackEdges() != 1) {
188 // If this is really a nested loop, rip it out into a child loop.
189 if (Loop *NL = SeparateNestedLoop(L)) {
191 // This is a big restructuring change, reprocess the whole loop.
196 InsertUniqueBackedgeBlock(L);
201 // Scan over the PHI nodes in the loop header. Since they now have only two
202 // incoming values (the loop is canonicalized), we may have simplified the PHI
203 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
205 for (BasicBlock::iterator I = L->getHeader()->begin();
206 (PN = dyn_cast<PHINode>(I++)); )
207 if (Value *V = PN->hasConstantValue()) {
208 PN->replaceAllUsesWith(V);
209 PN->eraseFromParent();
215 /// SplitBlockPredecessors - Split the specified block into two blocks. We want
216 /// to move the predecessors specified in the Preds list to point to the new
217 /// block, leaving the remaining predecessors pointing to BB. This method
218 /// updates the SSA PHINode's, but no other analyses.
220 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
222 const std::vector<BasicBlock*> &Preds) {
224 // Create new basic block, insert right before the original block...
225 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
227 // The preheader first gets an unconditional branch to the loop header...
228 BranchInst *BI = new BranchInst(BB, NewBB);
230 // For every PHI node in the block, insert a PHI node into NewBB where the
231 // incoming values from the out of loop edges are moved to NewBB. We have two
232 // possible cases here. If the loop is dead, we just insert dummy entries
233 // into the PHI nodes for the new edge. If the loop is not dead, we move the
234 // incoming edges in BB into new PHI nodes in NewBB.
236 if (!Preds.empty()) { // Is the loop not obviously dead?
237 // Check to see if the values being merged into the new block need PHI
238 // nodes. If so, insert them.
239 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
240 PHINode *PN = cast<PHINode>(I);
243 // Check to see if all of the values coming in are the same. If so, we
244 // don't need to create a new PHI node.
245 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
246 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
247 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
252 // If the values coming into the block are not the same, we need a PHI.
254 // Create the new PHI node, insert it into NewBB at the end of the block
255 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
256 if (AA) AA->copyValue(PN, NewPHI);
258 // Move all of the edges from blocks outside the loop to the new PHI
259 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
260 Value *V = PN->removeIncomingValue(Preds[i], false);
261 NewPHI->addIncoming(V, Preds[i]);
265 // Remove all of the edges coming into the PHI nodes from outside of the
267 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
268 PN->removeIncomingValue(Preds[i], false);
271 // Add an incoming value to the PHI node in the loop for the preheader
273 PN->addIncoming(InVal, NewBB);
275 // Can we eliminate this phi node now?
276 if (Value *V = PN->hasConstantValue(true)) {
277 if (!isa<Instruction>(V) ||
278 getAnalysis<DominatorSet>().dominates(cast<Instruction>(V), PN)) {
279 PN->replaceAllUsesWith(V);
280 if (AA) AA->deleteValue(PN);
281 BB->getInstList().erase(PN);
286 // Now that the PHI nodes are updated, actually move the edges from
287 // Preds to point to NewBB instead of BB.
289 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
290 TerminatorInst *TI = Preds[i]->getTerminator();
291 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
292 if (TI->getSuccessor(s) == BB)
293 TI->setSuccessor(s, NewBB);
296 } else { // Otherwise the loop is dead...
297 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
298 PHINode *PN = cast<PHINode>(I);
299 // Insert dummy values as the incoming value...
300 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
306 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
307 /// preheader, this method is called to insert one. This method has two phases:
308 /// preheader insertion and analysis updating.
310 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
311 BasicBlock *Header = L->getHeader();
313 // Compute the set of predecessors of the loop that are not in the loop.
314 std::vector<BasicBlock*> OutsideBlocks;
315 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
317 if (!L->contains(*PI)) // Coming in from outside the loop?
318 OutsideBlocks.push_back(*PI); // Keep track of it...
320 // Split out the loop pre-header
322 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
324 //===--------------------------------------------------------------------===//
325 // Update analysis results now that we have performed the transformation
328 // We know that we have loop information to update... update it now.
329 if (Loop *Parent = L->getParentLoop())
330 Parent->addBasicBlockToLoop(NewBB, *LI);
332 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
333 DominatorTree &DT = getAnalysis<DominatorTree>();
336 // Update the dominator tree information.
337 // The immediate dominator of the preheader is the immediate dominator of
339 DominatorTree::Node *PHDomTreeNode =
340 DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
341 BasicBlock *oldHeaderIDom = DT.getNode(Header)->getIDom()->getBlock();
343 // Change the header node so that PNHode is the new immediate dominator
344 DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
347 // The blocks that dominate NewBB are the blocks that dominate Header,
348 // minus Header, plus NewBB.
349 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
350 DomSet.erase(Header); // Header does not dominate us...
351 DS.addBasicBlock(NewBB, DomSet);
353 // The newly created basic block dominates all nodes dominated by Header.
354 for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
355 E = df_end(PHDomTreeNode); DFI != E; ++DFI)
356 DS.addDominator((*DFI)->getBlock(), NewBB);
359 // Update immediate dominator information if we have it...
360 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
361 // Whatever i-dominated the header node now immediately dominates NewBB
362 ID->addNewBlock(NewBB, ID->get(Header));
364 // The preheader now is the immediate dominator for the header node...
365 ID->setImmediateDominator(Header, NewBB);
368 // Update ET Forest information if we have it...
369 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
370 // Whatever i-dominated the header node now immediately dominates NewBB
371 EF->addNewBlock(NewBB, oldHeaderIDom);
373 // The preheader now is the immediate dominator for the header node...
374 EF->setImmediateDominator(Header, NewBB);
377 // Update dominance frontier information...
378 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
379 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
380 // everything that Header does, and it strictly dominates Header in
382 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
383 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
384 NewDFSet.erase(Header);
385 DF->addBasicBlock(NewBB, NewDFSet);
387 // Now we must loop over all of the dominance frontiers in the function,
388 // replacing occurrences of Header with NewBB in some cases. If a block
389 // dominates a (now) predecessor of NewBB, but did not strictly dominate
390 // Header, it will have Header in it's DF set, but should now have NewBB in
392 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
393 // Get all of the dominators of the predecessor...
394 const DominatorSet::DomSetType &PredDoms =
395 DS.getDominators(OutsideBlocks[i]);
396 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
397 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
398 BasicBlock *PredDom = *PDI;
399 // If the loop header is in DF(PredDom), then PredDom didn't dominate
400 // the header but did dominate a predecessor outside of the loop. Now
401 // we change this entry to include the preheader in the DF instead of
403 DominanceFrontier::iterator DFI = DF->find(PredDom);
404 assert(DFI != DF->end() && "No dominance frontier for node?");
405 if (DFI->second.count(Header)) {
406 DF->removeFromFrontier(DFI, Header);
407 DF->addToFrontier(DFI, NewBB);
414 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
415 /// blocks. This method is used to split exit blocks that have predecessors
416 /// outside of the loop.
417 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
418 std::vector<BasicBlock*> LoopBlocks;
419 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
421 LoopBlocks.push_back(*I);
423 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
424 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
426 // Update Loop Information - we know that the new block will be in whichever
427 // loop the Exit block is in. Note that it may not be in that immediate loop,
428 // if the successor is some other loop header. In that case, we continue
429 // walking up the loop tree to find a loop that contains both the successor
430 // block and the predecessor block.
431 Loop *SuccLoop = LI->getLoopFor(Exit);
432 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
433 SuccLoop = SuccLoop->getParentLoop();
435 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
437 // Update dominator information (set, immdom, domtree, and domfrontier)
438 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
442 /// AddBlockAndPredsToSet - Add the specified block, and all of its
443 /// predecessors, to the specified set, if it's not already in there. Stop
444 /// predecessor traversal when we reach StopBlock.
445 static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
446 std::set<BasicBlock*> &Blocks) {
447 if (!Blocks.insert(BB).second) return; // already processed.
448 if (BB == StopBlock) return; // Stop here!
450 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
451 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
454 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
455 /// PHI node that tells us how to partition the loops.
456 static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorSet &DS,
458 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
459 PHINode *PN = cast<PHINode>(I);
461 if (Value *V = PN->hasConstantValue())
462 if (!isa<Instruction>(V) || DS.dominates(cast<Instruction>(V), PN)) {
463 // This is a degenerate PHI already, don't modify it!
464 PN->replaceAllUsesWith(V);
465 if (AA) AA->deleteValue(PN);
466 PN->eraseFromParent();
470 // Scan this PHI node looking for a use of the PHI node by itself.
471 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
472 if (PN->getIncomingValue(i) == PN &&
473 L->contains(PN->getIncomingBlock(i)))
474 // We found something tasty to remove.
480 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
481 /// them out into a nested loop. This is important for code that looks like
486 /// br cond, Loop, Next
488 /// br cond2, Loop, Out
490 /// To identify this common case, we look at the PHI nodes in the header of the
491 /// loop. PHI nodes with unchanging values on one backedge correspond to values
492 /// that change in the "outer" loop, but not in the "inner" loop.
494 /// If we are able to separate out a loop, return the new outer loop that was
497 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
498 PHINode *PN = FindPHIToPartitionLoops(L, getAnalysis<DominatorSet>(), AA);
499 if (PN == 0) return 0; // No known way to partition.
501 // Pull out all predecessors that have varying values in the loop. This
502 // handles the case when a PHI node has multiple instances of itself as
504 std::vector<BasicBlock*> OuterLoopPreds;
505 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
506 if (PN->getIncomingValue(i) != PN ||
507 !L->contains(PN->getIncomingBlock(i)))
508 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
510 BasicBlock *Header = L->getHeader();
511 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
513 // Update dominator information (set, immdom, domtree, and domfrontier)
514 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
516 // Create the new outer loop.
517 Loop *NewOuter = new Loop();
519 // Change the parent loop to use the outer loop as its child now.
520 if (Loop *Parent = L->getParentLoop())
521 Parent->replaceChildLoopWith(L, NewOuter);
523 LI->changeTopLevelLoop(L, NewOuter);
525 // This block is going to be our new header block: add it to this loop and all
527 NewOuter->addBasicBlockToLoop(NewBB, *LI);
529 // L is now a subloop of our outer loop.
530 NewOuter->addChildLoop(L);
532 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
533 NewOuter->addBlockEntry(L->getBlocks()[i]);
535 // Determine which blocks should stay in L and which should be moved out to
536 // the Outer loop now.
537 DominatorSet &DS = getAnalysis<DominatorSet>();
538 std::set<BasicBlock*> BlocksInL;
539 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
540 if (DS.dominates(Header, *PI))
541 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
544 // Scan all of the loop children of L, moving them to OuterLoop if they are
545 // not part of the inner loop.
546 for (Loop::iterator I = L->begin(); I != L->end(); )
547 if (BlocksInL.count((*I)->getHeader()))
548 ++I; // Loop remains in L
550 NewOuter->addChildLoop(L->removeChildLoop(I));
552 // Now that we know which blocks are in L and which need to be moved to
553 // OuterLoop, move any blocks that need it.
554 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
555 BasicBlock *BB = L->getBlocks()[i];
556 if (!BlocksInL.count(BB)) {
557 // Move this block to the parent, updating the exit blocks sets
558 L->removeBlockFromLoop(BB);
560 LI->changeLoopFor(BB, NewOuter);
570 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
571 /// has more than one backedge in it. If this occurs, revector all of these
572 /// backedges to target a new basic block and have that block branch to the loop
573 /// header. This ensures that loops have exactly one backedge.
575 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
576 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
578 // Get information about the loop
579 BasicBlock *Preheader = L->getLoopPreheader();
580 BasicBlock *Header = L->getHeader();
581 Function *F = Header->getParent();
583 // Figure out which basic blocks contain back-edges to the loop header.
584 std::vector<BasicBlock*> BackedgeBlocks;
585 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
586 if (*I != Preheader) BackedgeBlocks.push_back(*I);
588 // Create and insert the new backedge block...
589 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
590 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
592 // Move the new backedge block to right after the last backedge block.
593 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
594 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
596 // Now that the block has been inserted into the function, create PHI nodes in
597 // the backedge block which correspond to any PHI nodes in the header block.
598 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
599 PHINode *PN = cast<PHINode>(I);
600 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
602 NewPN->reserveOperandSpace(BackedgeBlocks.size());
603 if (AA) AA->copyValue(PN, NewPN);
605 // Loop over the PHI node, moving all entries except the one for the
606 // preheader over to the new PHI node.
607 unsigned PreheaderIdx = ~0U;
608 bool HasUniqueIncomingValue = true;
609 Value *UniqueValue = 0;
610 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
611 BasicBlock *IBB = PN->getIncomingBlock(i);
612 Value *IV = PN->getIncomingValue(i);
613 if (IBB == Preheader) {
616 NewPN->addIncoming(IV, IBB);
617 if (HasUniqueIncomingValue) {
618 if (UniqueValue == 0)
620 else if (UniqueValue != IV)
621 HasUniqueIncomingValue = false;
626 // Delete all of the incoming values from the old PN except the preheader's
627 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
628 if (PreheaderIdx != 0) {
629 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
630 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
632 // Nuke all entries except the zero'th.
633 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
634 PN->removeIncomingValue(e-i, false);
636 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
637 PN->addIncoming(NewPN, BEBlock);
639 // As an optimization, if all incoming values in the new PhiNode (which is a
640 // subset of the incoming values of the old PHI node) have the same value,
641 // eliminate the PHI Node.
642 if (HasUniqueIncomingValue) {
643 NewPN->replaceAllUsesWith(UniqueValue);
644 if (AA) AA->deleteValue(NewPN);
645 BEBlock->getInstList().erase(NewPN);
649 // Now that all of the PHI nodes have been inserted and adjusted, modify the
650 // backedge blocks to just to the BEBlock instead of the header.
651 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
652 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
653 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
654 if (TI->getSuccessor(Op) == Header)
655 TI->setSuccessor(Op, BEBlock);
658 //===--- Update all analyses which we must preserve now -----------------===//
660 // Update Loop Information - we know that this block is now in the current
661 // loop and all parent loops.
662 L->addBasicBlockToLoop(BEBlock, *LI);
664 // Update dominator information (set, immdom, domtree, and domfrontier)
665 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
668 /// UpdateDomInfoForRevectoredPreds - This method is used to update the four
669 /// different kinds of dominator information (dominator sets, immediate
670 /// dominators, dominator trees, and dominance frontiers) after a new block has
671 /// been added to the CFG.
673 /// This only supports the case when an existing block (known as "NewBBSucc"),
674 /// had some of its predecessors factored into a new basic block. This
675 /// transformation inserts a new basic block ("NewBB"), with a single
676 /// unconditional branch to NewBBSucc, and moves some predecessors of
677 /// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
678 /// PredBlocks, even though they are the same as
679 /// pred_begin(NewBB)/pred_end(NewBB).
681 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
682 std::vector<BasicBlock*> &PredBlocks) {
683 assert(!PredBlocks.empty() && "No predblocks??");
684 assert(succ_begin(NewBB) != succ_end(NewBB) &&
685 ++succ_begin(NewBB) == succ_end(NewBB) &&
686 "NewBB should have a single successor!");
687 BasicBlock *NewBBSucc = *succ_begin(NewBB);
688 DominatorSet &DS = getAnalysis<DominatorSet>();
690 // Update dominator information... The blocks that dominate NewBB are the
691 // intersection of the dominators of predecessors, plus the block itself.
693 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
694 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
695 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
696 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
697 DS.addBasicBlock(NewBB, NewBBDomSet);
699 // The newly inserted basic block will dominate existing basic blocks iff the
700 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
701 // the non-pred blocks, then they all must be the same block!
703 bool NewBBDominatesNewBBSucc = true;
705 BasicBlock *OnePred = PredBlocks[0];
706 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
707 if (PredBlocks[i] != OnePred) {
708 NewBBDominatesNewBBSucc = false;
712 if (NewBBDominatesNewBBSucc)
713 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
715 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
716 NewBBDominatesNewBBSucc = false;
721 // The other scenario where the new block can dominate its successors are when
722 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
724 if (!NewBBDominatesNewBBSucc) {
725 NewBBDominatesNewBBSucc = true;
726 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
728 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
729 NewBBDominatesNewBBSucc = false;
734 // If NewBB dominates some blocks, then it will dominate all blocks that
736 if (NewBBDominatesNewBBSucc) {
737 BasicBlock *PredBlock = PredBlocks[0];
738 Function *F = NewBB->getParent();
739 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
740 if (DS.dominates(NewBBSucc, I))
741 DS.addDominator(I, NewBB);
744 // Update immediate dominator information if we have it...
745 BasicBlock *NewBBIDom = 0;
746 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
747 // To find the immediate dominator of the new exit node, we trace up the
748 // immediate dominators of a predecessor until we find a basic block that
749 // dominates the exit block.
751 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
752 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
753 assert(Dom != 0 && "No shared dominator found???");
757 // Set the immediate dominator now...
758 ID->addNewBlock(NewBB, Dom);
759 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
761 // If NewBB strictly dominates other blocks, we need to update their idom's
762 // now. The only block that need adjustment is the NewBBSucc block, whose
763 // idom should currently be set to PredBlocks[0].
764 if (NewBBDominatesNewBBSucc)
765 ID->setImmediateDominator(NewBBSucc, NewBB);
768 // Update DominatorTree information if it is active.
769 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
770 // If we don't have ImmediateDominator info around, calculate the idom as
772 DominatorTree::Node *NewBBIDomNode;
774 NewBBIDomNode = DT->getNode(NewBBIDom);
776 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
777 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
778 NewBBIDomNode = NewBBIDomNode->getIDom();
779 assert(NewBBIDomNode && "No shared dominator found??");
781 NewBBIDom = NewBBIDomNode->getBlock();
784 // Create the new dominator tree node... and set the idom of NewBB.
785 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
787 // If NewBB strictly dominates other blocks, then it is now the immediate
788 // dominator of NewBBSucc. Update the dominator tree as appropriate.
789 if (NewBBDominatesNewBBSucc) {
790 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
791 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
795 // Update ET-Forest information if it is active.
796 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
797 EF->addNewBlock(NewBB, NewBBIDom);
798 if (NewBBDominatesNewBBSucc)
799 EF->setImmediateDominator(NewBBSucc, NewBB);
802 // Update dominance frontier information...
803 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
804 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
805 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
807 if (NewBBDominatesNewBBSucc) {
808 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
809 if (DFI != DF->end()) {
810 DominanceFrontier::DomSetType Set = DFI->second;
811 // Filter out stuff in Set that we do not dominate a predecessor of.
812 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
813 E = Set.end(); SetI != E;) {
814 bool DominatesPred = false;
815 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
817 if (DS.dominates(NewBB, *PI))
818 DominatesPred = true;
825 DF->addBasicBlock(NewBB, Set);
829 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
830 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
831 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
832 DominanceFrontier::DomSetType NewDFSet;
833 NewDFSet.insert(NewBBSucc);
834 DF->addBasicBlock(NewBB, NewDFSet);
837 // Now we must loop over all of the dominance frontiers in the function,
838 // replacing occurrences of NewBBSucc with NewBB in some cases. All
839 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
840 // their dominance frontier must be updated to contain NewBB instead.
842 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
843 BasicBlock *Pred = PredBlocks[i];
844 // Get all of the dominators of the predecessor...
845 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
846 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
847 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
848 BasicBlock *PredDom = *PDI;
850 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
851 // dominate NewBBSucc but did dominate a predecessor of it. Now we
852 // change this entry to include NewBB in the DF instead of NewBBSucc.
853 DominanceFrontier::iterator DFI = DF->find(PredDom);
854 assert(DFI != DF->end() && "No dominance frontier for node?");
855 if (DFI->second.count(NewBBSucc)) {
856 // If NewBBSucc should not stay in our dominator frontier, remove it.
857 // We remove it unless there is a predecessor of NewBBSucc that we
858 // dominate, but we don't strictly dominate NewBBSucc.
859 bool ShouldRemove = true;
860 if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
861 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
862 // Check to see if it dominates any predecessors of NewBBSucc.
863 for (pred_iterator PI = pred_begin(NewBBSucc),
864 E = pred_end(NewBBSucc); PI != E; ++PI)
865 if (DS.dominates(PredDom, *PI)) {
866 ShouldRemove = false;
872 DF->removeFromFrontier(DFI, NewBBSucc);
873 DF->addToFrontier(DFI, NewBB);