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 #define DEBUG_TYPE "loopsimplify"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Constant.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Function.h"
40 #include "llvm/Type.h"
41 #include "llvm/Analysis/AliasAnalysis.h"
42 #include "llvm/Analysis/Dominators.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Support/CFG.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/ADT/SetOperations.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/DepthFirstIterator.h"
52 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
53 STATISTIC(NumNested , "Number of nested loops split out");
56 struct VISIBILITY_HIDDEN 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<DominatorTree>();
68 AU.addRequired<ETForest>();
70 AU.addPreserved<LoopInfo>();
71 AU.addPreserved<ImmediateDominators>();
72 AU.addPreserved<ETForest>();
73 AU.addPreserved<DominatorTree>();
74 AU.addPreserved<DominanceFrontier>();
75 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
78 bool ProcessLoop(Loop *L);
79 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
80 const std::vector<BasicBlock*> &Preds);
81 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
82 void InsertPreheaderForLoop(Loop *L);
83 Loop *SeparateNestedLoop(Loop *L);
84 void InsertUniqueBackedgeBlock(Loop *L);
85 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
86 std::vector<BasicBlock*> &SplitPreds,
89 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
90 std::vector<BasicBlock*> &PredBlocks);
93 RegisterPass<LoopSimplify>
94 X("loopsimplify", "Canonicalize natural loops", true);
97 // Publically exposed interface to pass...
98 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
99 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
101 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
102 /// it in any convenient order) inserting preheaders...
104 bool LoopSimplify::runOnFunction(Function &F) {
105 bool Changed = false;
106 LI = &getAnalysis<LoopInfo>();
107 AA = getAnalysisToUpdate<AliasAnalysis>();
109 // Check to see that no blocks (other than the header) in loops have
110 // predecessors that are not in loops. This is not valid for natural loops,
111 // but can occur if the blocks are unreachable. Since they are unreachable we
112 // can just shamelessly destroy their terminators to make them not branch into
114 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
115 // This case can only occur for unreachable blocks. Blocks that are
116 // unreachable can't be in loops, so filter those blocks out.
117 if (LI->getLoopFor(BB)) continue;
119 bool BlockUnreachable = false;
120 TerminatorInst *TI = BB->getTerminator();
122 // Check to see if any successors of this block are non-loop-header loops
123 // that are not the header.
124 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
125 // If this successor is not in a loop, BB is clearly ok.
126 Loop *L = LI->getLoopFor(TI->getSuccessor(i));
129 // If the succ is the loop header, and if L is a top-level loop, then this
130 // is an entrance into a loop through the header, which is also ok.
131 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
134 // Otherwise, this is an entrance into a loop from some place invalid.
135 // Either the loop structure is invalid and this is not a natural loop (in
136 // which case the compiler is buggy somewhere else) or BB is unreachable.
137 BlockUnreachable = true;
141 // If this block is ok, check the next one.
142 if (!BlockUnreachable) continue;
144 // Otherwise, this block is dead. To clean up the CFG and to allow later
145 // loop transformations to ignore this case, we delete the edges into the
146 // loop by replacing the terminator.
148 // Remove PHI entries from the successors.
149 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
150 TI->getSuccessor(i)->removePredecessor(BB);
152 // Add a new unreachable instruction.
153 new UnreachableInst(TI);
155 // Delete the dead terminator.
156 if (AA) AA->deleteValue(&BB->back());
157 BB->getInstList().pop_back();
161 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
162 Changed |= ProcessLoop(*I);
167 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
168 /// all loops have preheaders.
170 bool LoopSimplify::ProcessLoop(Loop *L) {
171 bool Changed = false;
174 // Canonicalize inner loops before outer loops. Inner loop canonicalization
175 // can provide work for the outer loop to canonicalize.
176 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
177 Changed |= ProcessLoop(*I);
179 assert(L->getBlocks()[0] == L->getHeader() &&
180 "Header isn't first block in loop?");
182 // Does the loop already have a preheader? If so, don't insert one.
183 if (L->getLoopPreheader() == 0) {
184 InsertPreheaderForLoop(L);
189 // Next, check to make sure that all exit nodes of the loop only have
190 // predecessors that are inside of the loop. This check guarantees that the
191 // loop preheader/header will dominate the exit blocks. If the exit block has
192 // predecessors from outside of the loop, split the edge now.
193 std::vector<BasicBlock*> ExitBlocks;
194 L->getExitBlocks(ExitBlocks);
196 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
197 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
198 E = ExitBlockSet.end(); I != E; ++I) {
199 BasicBlock *ExitBlock = *I;
200 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
202 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
204 if (!L->contains(*PI)) {
205 RewriteLoopExitBlock(L, ExitBlock);
212 // If the header has more than two predecessors at this point (from the
213 // preheader and from multiple backedges), we must adjust the loop.
214 unsigned NumBackedges = L->getNumBackEdges();
215 if (NumBackedges != 1) {
216 // If this is really a nested loop, rip it out into a child loop. Don't do
217 // this for loops with a giant number of backedges, just factor them into a
218 // common backedge instead.
219 if (NumBackedges < 8) {
220 if (Loop *NL = SeparateNestedLoop(L)) {
222 // This is a big restructuring change, reprocess the whole loop.
225 // GCC doesn't tail recursion eliminate this.
230 // If we either couldn't, or didn't want to, identify nesting of the loops,
231 // insert a new block that all backedges target, then make it jump to the
233 InsertUniqueBackedgeBlock(L);
238 // Scan over the PHI nodes in the loop header. Since they now have only two
239 // incoming values (the loop is canonicalized), we may have simplified the PHI
240 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
242 for (BasicBlock::iterator I = L->getHeader()->begin();
243 (PN = dyn_cast<PHINode>(I++)); )
244 if (Value *V = PN->hasConstantValue()) {
245 PN->replaceAllUsesWith(V);
246 PN->eraseFromParent();
252 /// SplitBlockPredecessors - Split the specified block into two blocks. We want
253 /// to move the predecessors specified in the Preds list to point to the new
254 /// block, leaving the remaining predecessors pointing to BB. This method
255 /// updates the SSA PHINode's, but no other analyses.
257 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
259 const std::vector<BasicBlock*> &Preds) {
261 // Create new basic block, insert right before the original block...
262 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
264 // The preheader first gets an unconditional branch to the loop header...
265 BranchInst *BI = new BranchInst(BB, NewBB);
267 // For every PHI node in the block, insert a PHI node into NewBB where the
268 // incoming values from the out of loop edges are moved to NewBB. We have two
269 // possible cases here. If the loop is dead, we just insert dummy entries
270 // into the PHI nodes for the new edge. If the loop is not dead, we move the
271 // incoming edges in BB into new PHI nodes in NewBB.
273 if (!Preds.empty()) { // Is the loop not obviously dead?
274 // Check to see if the values being merged into the new block need PHI
275 // nodes. If so, insert them.
276 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
277 PHINode *PN = cast<PHINode>(I);
280 // Check to see if all of the values coming in are the same. If so, we
281 // don't need to create a new PHI node.
282 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
283 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
284 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
289 // If the values coming into the block are not the same, we need a PHI.
291 // Create the new PHI node, insert it into NewBB at the end of the block
292 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
293 if (AA) AA->copyValue(PN, NewPHI);
295 // Move all of the edges from blocks outside the loop to the new PHI
296 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
297 Value *V = PN->removeIncomingValue(Preds[i], false);
298 NewPHI->addIncoming(V, Preds[i]);
302 // Remove all of the edges coming into the PHI nodes from outside of the
304 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
305 PN->removeIncomingValue(Preds[i], false);
308 // Add an incoming value to the PHI node in the loop for the preheader
310 PN->addIncoming(InVal, NewBB);
312 // Can we eliminate this phi node now?
313 if (Value *V = PN->hasConstantValue(true)) {
314 Instruction *I = dyn_cast<Instruction>(V);
315 // If I is in NewBB, the ETForest call will fail, because NewBB isn't
316 // registered in ETForest yet. Handle this case explicitly.
317 if (!I || (I->getParent() != NewBB &&
318 getAnalysis<ETForest>().dominates(I, PN))) {
319 PN->replaceAllUsesWith(V);
320 if (AA) AA->deleteValue(PN);
321 BB->getInstList().erase(PN);
326 // Now that the PHI nodes are updated, actually move the edges from
327 // Preds to point to NewBB instead of BB.
329 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
330 TerminatorInst *TI = Preds[i]->getTerminator();
331 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
332 if (TI->getSuccessor(s) == BB)
333 TI->setSuccessor(s, NewBB);
336 } else { // Otherwise the loop is dead...
337 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
338 PHINode *PN = cast<PHINode>(I);
339 // Insert dummy values as the incoming value...
340 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
346 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
347 /// preheader, this method is called to insert one. This method has two phases:
348 /// preheader insertion and analysis updating.
350 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
351 BasicBlock *Header = L->getHeader();
353 // Compute the set of predecessors of the loop that are not in the loop.
354 std::vector<BasicBlock*> OutsideBlocks;
355 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
357 if (!L->contains(*PI)) // Coming in from outside the loop?
358 OutsideBlocks.push_back(*PI); // Keep track of it...
360 // Split out the loop pre-header.
362 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
365 //===--------------------------------------------------------------------===//
366 // Update analysis results now that we have performed the transformation
369 // We know that we have loop information to update... update it now.
370 if (Loop *Parent = L->getParentLoop())
371 Parent->addBasicBlockToLoop(NewBB, *LI);
373 UpdateDomInfoForRevectoredPreds(NewBB, OutsideBlocks);
375 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
376 // code layout too horribly.
377 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
380 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
381 /// blocks. This method is used to split exit blocks that have predecessors
382 /// outside of the loop.
383 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
384 std::vector<BasicBlock*> LoopBlocks;
385 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
387 LoopBlocks.push_back(*I);
389 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
390 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
392 // Update Loop Information - we know that the new block will be in whichever
393 // loop the Exit block is in. Note that it may not be in that immediate loop,
394 // if the successor is some other loop header. In that case, we continue
395 // walking up the loop tree to find a loop that contains both the successor
396 // block and the predecessor block.
397 Loop *SuccLoop = LI->getLoopFor(Exit);
398 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
399 SuccLoop = SuccLoop->getParentLoop();
401 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
403 // Update dominator information (set, immdom, domtree, and domfrontier)
404 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
408 /// AddBlockAndPredsToSet - Add the specified block, and all of its
409 /// predecessors, to the specified set, if it's not already in there. Stop
410 /// predecessor traversal when we reach StopBlock.
411 static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
412 std::set<BasicBlock*> &Blocks) {
413 if (!Blocks.insert(BB).second) return; // already processed.
414 if (BB == StopBlock) return; // Stop here!
416 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
417 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
420 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
421 /// PHI node that tells us how to partition the loops.
422 static PHINode *FindPHIToPartitionLoops(Loop *L, ETForest *EF,
424 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
425 PHINode *PN = cast<PHINode>(I);
427 if (Value *V = PN->hasConstantValue())
428 if (!isa<Instruction>(V) || EF->dominates(cast<Instruction>(V), PN)) {
429 // This is a degenerate PHI already, don't modify it!
430 PN->replaceAllUsesWith(V);
431 if (AA) AA->deleteValue(PN);
432 PN->eraseFromParent();
436 // Scan this PHI node looking for a use of the PHI node by itself.
437 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
438 if (PN->getIncomingValue(i) == PN &&
439 L->contains(PN->getIncomingBlock(i)))
440 // We found something tasty to remove.
446 // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
447 // right after some 'outside block' block. This prevents the preheader from
448 // being placed inside the loop body, e.g. when the loop hasn't been rotated.
449 void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
450 std::vector<BasicBlock*>&SplitPreds,
452 // Check to see if NewBB is already well placed.
453 Function::iterator BBI = NewBB; --BBI;
454 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
455 if (&*BBI == SplitPreds[i])
459 // If it isn't already after an outside block, move it after one. This is
460 // always good as it makes the uncond branch from the outside block into a
463 // Figure out *which* outside block to put this after. Prefer an outside
464 // block that neighbors a BB actually in the loop.
465 BasicBlock *FoundBB = 0;
466 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
467 Function::iterator BBI = SplitPreds[i];
468 if (++BBI != NewBB->getParent()->end() &&
470 FoundBB = SplitPreds[i];
475 // If our heuristic for a *good* bb to place this after doesn't find
476 // anything, just pick something. It's likely better than leaving it within
479 FoundBB = SplitPreds[0];
480 NewBB->moveAfter(FoundBB);
484 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
485 /// them out into a nested loop. This is important for code that looks like
490 /// br cond, Loop, Next
492 /// br cond2, Loop, Out
494 /// To identify this common case, we look at the PHI nodes in the header of the
495 /// loop. PHI nodes with unchanging values on one backedge correspond to values
496 /// that change in the "outer" loop, but not in the "inner" loop.
498 /// If we are able to separate out a loop, return the new outer loop that was
501 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
502 ETForest *EF = getAnalysisToUpdate<ETForest>();
503 PHINode *PN = FindPHIToPartitionLoops(L, EF, AA);
504 if (PN == 0) return 0; // No known way to partition.
506 // Pull out all predecessors that have varying values in the loop. This
507 // handles the case when a PHI node has multiple instances of itself as
509 std::vector<BasicBlock*> OuterLoopPreds;
510 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
511 if (PN->getIncomingValue(i) != PN ||
512 !L->contains(PN->getIncomingBlock(i)))
513 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
515 BasicBlock *Header = L->getHeader();
516 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
518 // Update dominator information (set, immdom, domtree, and domfrontier)
519 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
521 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
522 // code layout too horribly.
523 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
525 // Create the new outer loop.
526 Loop *NewOuter = new Loop();
528 // Change the parent loop to use the outer loop as its child now.
529 if (Loop *Parent = L->getParentLoop())
530 Parent->replaceChildLoopWith(L, NewOuter);
532 LI->changeTopLevelLoop(L, NewOuter);
534 // This block is going to be our new header block: add it to this loop and all
536 NewOuter->addBasicBlockToLoop(NewBB, *LI);
538 // L is now a subloop of our outer loop.
539 NewOuter->addChildLoop(L);
541 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
542 NewOuter->addBlockEntry(L->getBlocks()[i]);
544 // Determine which blocks should stay in L and which should be moved out to
545 // the Outer loop now.
546 std::set<BasicBlock*> BlocksInL;
547 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
548 if (EF->dominates(Header, *PI))
549 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
552 // Scan all of the loop children of L, moving them to OuterLoop if they are
553 // not part of the inner loop.
554 for (Loop::iterator I = L->begin(); I != L->end(); )
555 if (BlocksInL.count((*I)->getHeader()))
556 ++I; // Loop remains in L
558 NewOuter->addChildLoop(L->removeChildLoop(I));
560 // Now that we know which blocks are in L and which need to be moved to
561 // OuterLoop, move any blocks that need it.
562 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
563 BasicBlock *BB = L->getBlocks()[i];
564 if (!BlocksInL.count(BB)) {
565 // Move this block to the parent, updating the exit blocks sets
566 L->removeBlockFromLoop(BB);
568 LI->changeLoopFor(BB, NewOuter);
578 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
579 /// has more than one backedge in it. If this occurs, revector all of these
580 /// backedges to target a new basic block and have that block branch to the loop
581 /// header. This ensures that loops have exactly one backedge.
583 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
584 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
586 // Get information about the loop
587 BasicBlock *Preheader = L->getLoopPreheader();
588 BasicBlock *Header = L->getHeader();
589 Function *F = Header->getParent();
591 // Figure out which basic blocks contain back-edges to the loop header.
592 std::vector<BasicBlock*> BackedgeBlocks;
593 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
594 if (*I != Preheader) BackedgeBlocks.push_back(*I);
596 // Create and insert the new backedge block...
597 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
598 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
600 // Move the new backedge block to right after the last backedge block.
601 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
602 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
604 // Now that the block has been inserted into the function, create PHI nodes in
605 // the backedge block which correspond to any PHI nodes in the header block.
606 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
607 PHINode *PN = cast<PHINode>(I);
608 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
610 NewPN->reserveOperandSpace(BackedgeBlocks.size());
611 if (AA) AA->copyValue(PN, NewPN);
613 // Loop over the PHI node, moving all entries except the one for the
614 // preheader over to the new PHI node.
615 unsigned PreheaderIdx = ~0U;
616 bool HasUniqueIncomingValue = true;
617 Value *UniqueValue = 0;
618 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
619 BasicBlock *IBB = PN->getIncomingBlock(i);
620 Value *IV = PN->getIncomingValue(i);
621 if (IBB == Preheader) {
624 NewPN->addIncoming(IV, IBB);
625 if (HasUniqueIncomingValue) {
626 if (UniqueValue == 0)
628 else if (UniqueValue != IV)
629 HasUniqueIncomingValue = false;
634 // Delete all of the incoming values from the old PN except the preheader's
635 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
636 if (PreheaderIdx != 0) {
637 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
638 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
640 // Nuke all entries except the zero'th.
641 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
642 PN->removeIncomingValue(e-i, false);
644 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
645 PN->addIncoming(NewPN, BEBlock);
647 // As an optimization, if all incoming values in the new PhiNode (which is a
648 // subset of the incoming values of the old PHI node) have the same value,
649 // eliminate the PHI Node.
650 if (HasUniqueIncomingValue) {
651 NewPN->replaceAllUsesWith(UniqueValue);
652 if (AA) AA->deleteValue(NewPN);
653 BEBlock->getInstList().erase(NewPN);
657 // Now that all of the PHI nodes have been inserted and adjusted, modify the
658 // backedge blocks to just to the BEBlock instead of the header.
659 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
660 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
661 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
662 if (TI->getSuccessor(Op) == Header)
663 TI->setSuccessor(Op, BEBlock);
666 //===--- Update all analyses which we must preserve now -----------------===//
668 // Update Loop Information - we know that this block is now in the current
669 // loop and all parent loops.
670 L->addBasicBlockToLoop(BEBlock, *LI);
672 // Update dominator information (set, immdom, domtree, and domfrontier)
673 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
676 // Returns true if BasicBlock A dominates at least one block in vector B
677 // Helper function for UpdateDomInfoForRevectoredPreds
678 static bool BlockDominatesAny(BasicBlock* A, const std::vector<BasicBlock*>& B, const ETForest& ETF) {
679 for (std::vector<BasicBlock*>::iterator BI = B.begin(), BE = B.end(); BI != BE; ++BI) {
680 if (ETF.dominates(A, *BI))
686 /// UpdateDomInfoForRevectoredPreds - This method is used to update the four
687 /// different kinds of dominator information (immediate dominators,
688 /// dominator trees, et-forest and dominance frontiers) after a new block has
689 /// been added to the CFG.
691 /// This only supports the case when an existing block (known as "NewBBSucc"),
692 /// had some of its predecessors factored into a new basic block. This
693 /// transformation inserts a new basic block ("NewBB"), with a single
694 /// unconditional branch to NewBBSucc, and moves some predecessors of
695 /// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
696 /// PredBlocks, even though they are the same as
697 /// pred_begin(NewBB)/pred_end(NewBB).
699 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
700 std::vector<BasicBlock*> &PredBlocks) {
701 assert(!PredBlocks.empty() && "No predblocks??");
702 assert(succ_begin(NewBB) != succ_end(NewBB) &&
703 ++succ_begin(NewBB) == succ_end(NewBB) &&
704 "NewBB should have a single successor!");
705 BasicBlock *NewBBSucc = *succ_begin(NewBB);
706 ETForest& ETF = getAnalysis<ETForest>();
708 // The newly inserted basic block will dominate existing basic blocks iff the
709 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
710 // the non-pred blocks, then they all must be the same block!
712 bool NewBBDominatesNewBBSucc = true;
714 BasicBlock *OnePred = PredBlocks[0];
715 unsigned i = 1, e = PredBlocks.size();
716 for (i = 1; !ETF.isReachableFromEntry(OnePred); ++i) {
717 assert(i != e && "Didn't find reachable pred?");
718 OnePred = PredBlocks[i];
722 if (PredBlocks[i] != OnePred && ETF.isReachableFromEntry(OnePred)){
723 NewBBDominatesNewBBSucc = false;
727 if (NewBBDominatesNewBBSucc)
728 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
730 if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
731 NewBBDominatesNewBBSucc = false;
736 // The other scenario where the new block can dominate its successors are when
737 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
739 if (!NewBBDominatesNewBBSucc) {
740 NewBBDominatesNewBBSucc = true;
741 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
743 if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
744 NewBBDominatesNewBBSucc = false;
749 BasicBlock *NewBBIDom = 0;
751 // Update immediate dominator information if we have it.
752 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
754 for (i = 0; i < PredBlocks.size(); ++i)
755 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i])) {
756 NewBBIDom = PredBlocks[i];
759 assert(i != PredBlocks.size() && "No reachable preds?");
760 for (i = i + 1; i < PredBlocks.size(); ++i) {
761 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i]))
762 NewBBIDom = ETF.nearestCommonDominator(NewBBIDom, PredBlocks[i]);
764 assert(NewBBIDom && "No immediate dominator found??");
766 // Set the immediate dominator now...
767 ID->addNewBlock(NewBB, NewBBIDom);
769 // If NewBB strictly dominates other blocks, we need to update their idom's
770 // now. The only block that need adjustment is the NewBBSucc block, whose
771 // idom should currently be set to PredBlocks[0].
772 if (NewBBDominatesNewBBSucc)
773 ID->setImmediateDominator(NewBBSucc, NewBB);
776 // Update DominatorTree information if it is active.
777 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
778 // If we don't have ImmediateDominator info around, calculate the idom as
782 for (i = 0; i < PredBlocks.size(); ++i)
783 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i])) {
784 NewBBIDom = PredBlocks[i];
787 assert(i != PredBlocks.size() && "No reachable preds?");
788 for (i = i + 1; i < PredBlocks.size(); ++i) {
789 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i]))
790 NewBBIDom = ETF.nearestCommonDominator(NewBBIDom, PredBlocks[i]);
792 assert(NewBBIDom && "No immediate dominator found??");
794 DominatorTree::Node *NewBBIDomNode = DT->getNode(NewBBIDom);
796 // Create the new dominator tree node... and set the idom of NewBB.
797 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
799 // If NewBB strictly dominates other blocks, then it is now the immediate
800 // dominator of NewBBSucc. Update the dominator tree as appropriate.
801 if (NewBBDominatesNewBBSucc) {
802 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
803 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
807 // Update ET-Forest information if it is active.
808 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
809 EF->addNewBlock(NewBB, NewBBIDom);
810 if (NewBBDominatesNewBBSucc)
811 EF->setImmediateDominator(NewBBSucc, NewBB);
814 // Update dominance frontier information...
815 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
816 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
817 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
819 if (NewBBDominatesNewBBSucc) {
820 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
821 if (DFI != DF->end()) {
822 DominanceFrontier::DomSetType Set = DFI->second;
823 // Filter out stuff in Set that we do not dominate a predecessor of.
824 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
825 E = Set.end(); SetI != E;) {
826 bool DominatesPred = false;
827 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
829 if (ETF.dominates(NewBB, *PI))
830 DominatesPred = true;
837 DF->addBasicBlock(NewBB, Set);
841 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
842 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
843 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
844 DominanceFrontier::DomSetType NewDFSet;
845 NewDFSet.insert(NewBBSucc);
846 DF->addBasicBlock(NewBB, NewDFSet);
849 // Now we must loop over all of the dominance frontiers in the function,
850 // replacing occurrences of NewBBSucc with NewBB in some cases. All
851 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
852 // their dominance frontier must be updated to contain NewBB instead.
854 for (Function::iterator FI = NewBB->getParent()->begin(),
855 FE = NewBB->getParent()->end(); FI != FE; ++FI) {
856 DominanceFrontier::iterator DFI = DF->find(FI);
857 if (DFI == DF->end()) continue; // unreachable block.
859 // Only consider dominators of NewBBSucc
860 if (!DFI->second.count(NewBBSucc)) continue;
862 if (BlockDominatesAny(FI, PredBlocks, ETF)) {
863 // If NewBBSucc should not stay in our dominator frontier, remove it.
864 // We remove it unless there is a predecessor of NewBBSucc that we
865 // dominate, but we don't strictly dominate NewBBSucc.
866 bool ShouldRemove = true;
867 if ((BasicBlock*)FI == NewBBSucc || !ETF.dominates(FI, NewBBSucc)) {
868 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
869 // Check to see if it dominates any predecessors of NewBBSucc.
870 for (pred_iterator PI = pred_begin(NewBBSucc),
871 E = pred_end(NewBBSucc); PI != E; ++PI)
872 if (ETF.dominates(FI, *PI)) {
873 ShouldRemove = false;
878 DF->removeFromFrontier(DFI, NewBBSucc);
879 DF->addToFrontier(DFI, NewBB);