Remove DominatorSet usage from LoopSimplify. Patch from Owen Anderson.
[oota-llvm.git] / lib / Transforms / Utils / LoopSimplify.cpp
1 //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs several transformations to transform natural loops into a
11 // simpler form, which makes subsequent analyses and transformations simpler and
12 // more effective.
13 //
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.
17 //
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.
23 //
24 // This pass also guarantees that loops will have exactly one backedge.
25 //
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
28 // generated code.
29 //
30 // This pass obviously modifies the CFG, but updates loop information and
31 // dominator information.
32 //
33 //===----------------------------------------------------------------------===//
34
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"
50 using namespace llvm;
51
52 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
53 STATISTIC(NumNested  , "Number of nested loops split out");
54
55 namespace {
56   struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
57     // AA - If we have an alias analysis object to update, this is it, otherwise
58     // this is null.
59     AliasAnalysis *AA;
60     LoopInfo *LI;
61
62     virtual bool runOnFunction(Function &F);
63
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>();
69
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.
76     }
77   private:
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,
87                                   Loop *L);
88       
89     void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
90                                          std::vector<BasicBlock*> &PredBlocks);
91   };
92
93   RegisterPass<LoopSimplify>
94   X("loopsimplify", "Canonicalize natural loops", true);
95 }
96
97 // Publically exposed interface to pass...
98 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
99 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
100
101 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
102 /// it in any convenient order) inserting preheaders...
103 ///
104 bool LoopSimplify::runOnFunction(Function &F) {
105   bool Changed = false;
106   LI = &getAnalysis<LoopInfo>();
107   AA = getAnalysisToUpdate<AliasAnalysis>();
108
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
113   // the loop!
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;
118     
119     bool BlockUnreachable = false;
120     TerminatorInst *TI = BB->getTerminator();
121
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));
127       if (!L) continue;
128       
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)
132         continue;
133       
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;
138       break;
139     }
140     
141     // If this block is ok, check the next one.
142     if (!BlockUnreachable) continue;
143     
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.
147     
148     // Remove PHI entries from the successors.
149     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
150       TI->getSuccessor(i)->removePredecessor(BB);
151    
152     // Add a new unreachable instruction.
153     new UnreachableInst(TI);
154     
155     // Delete the dead terminator.
156     if (AA) AA->deleteValue(&BB->back());
157     BB->getInstList().pop_back();
158     Changed |= true;
159   }
160   
161   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
162     Changed |= ProcessLoop(*I);
163
164   return Changed;
165 }
166
167 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
168 /// all loops have preheaders.
169 ///
170 bool LoopSimplify::ProcessLoop(Loop *L) {
171   bool Changed = false;
172 ReprocessLoop:
173   
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);
178   
179   assert(L->getBlocks()[0] == L->getHeader() &&
180          "Header isn't first block in loop?");
181
182   // Does the loop already have a preheader?  If so, don't insert one.
183   if (L->getLoopPreheader() == 0) {
184     InsertPreheaderForLoop(L);
185     NumInserted++;
186     Changed = true;
187   }
188
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);
195     
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);
201          PI != PE; ++PI)
202       // Must be exactly this loop: no subloops, parent loops, or non-loop preds
203       // allowed.
204       if (!L->contains(*PI)) {
205         RewriteLoopExitBlock(L, ExitBlock);
206         NumInserted++;
207         Changed = true;
208         break;
209       }
210   }
211
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)) {
221         ++NumNested;
222         // This is a big restructuring change, reprocess the whole loop.
223         ProcessLoop(NL);
224         Changed = true;
225         // GCC doesn't tail recursion eliminate this.
226         goto ReprocessLoop;
227       }
228     }
229
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
232     // loop header.
233     InsertUniqueBackedgeBlock(L);
234     NumInserted++;
235     Changed = true;
236   }
237
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'.
241   PHINode *PN;
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();
247       }
248
249   return Changed;
250 }
251
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.
256 ///
257 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
258                                                  const char *Suffix,
259                                        const std::vector<BasicBlock*> &Preds) {
260
261   // Create new basic block, insert right before the original block...
262   BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
263
264   // The preheader first gets an unconditional branch to the loop header...
265   BranchInst *BI = new BranchInst(BB, NewBB);
266
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.
272   //
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);
278       ++I;
279
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])) {
285           InVal = 0;
286           break;
287         }
288
289       // If the values coming into the block are not the same, we need a PHI.
290       if (InVal == 0) {
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);
294
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]);
299         }
300         InVal = NewPHI;
301       } else {
302         // Remove all of the edges coming into the PHI nodes from outside of the
303         // block.
304         for (unsigned i = 0, e = Preds.size(); i != e; ++i)
305           PN->removeIncomingValue(Preds[i], false);
306       }
307
308       // Add an incoming value to the PHI node in the loop for the preheader
309       // edge.
310       PN->addIncoming(InVal, NewBB);
311
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 || (I->getParent() != NewBB &&
316                    getAnalysis<ETForest>().dominates(I, PN))) {
317           PN->replaceAllUsesWith(V);
318           if (AA) AA->deleteValue(PN);
319           BB->getInstList().erase(PN);
320         }
321       }
322     }
323
324     // Now that the PHI nodes are updated, actually move the edges from
325     // Preds to point to NewBB instead of BB.
326     //
327     for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
328       TerminatorInst *TI = Preds[i]->getTerminator();
329       for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
330         if (TI->getSuccessor(s) == BB)
331           TI->setSuccessor(s, NewBB);
332     }
333
334   } else {                       // Otherwise the loop is dead...
335     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
336       PHINode *PN = cast<PHINode>(I);
337       // Insert dummy values as the incoming value...
338       PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
339     }
340   }
341   return NewBB;
342 }
343
344 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
345 /// preheader, this method is called to insert one.  This method has two phases:
346 /// preheader insertion and analysis updating.
347 ///
348 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
349   BasicBlock *Header = L->getHeader();
350
351   // Compute the set of predecessors of the loop that are not in the loop.
352   std::vector<BasicBlock*> OutsideBlocks;
353   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
354        PI != PE; ++PI)
355     if (!L->contains(*PI))           // Coming in from outside the loop?
356       OutsideBlocks.push_back(*PI);  // Keep track of it...
357
358   // Split out the loop pre-header.
359   BasicBlock *NewBB =
360     SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
361   
362
363   //===--------------------------------------------------------------------===//
364   //  Update analysis results now that we have performed the transformation
365   //
366
367   // We know that we have loop information to update... update it now.
368   if (Loop *Parent = L->getParentLoop())
369     Parent->addBasicBlockToLoop(NewBB, *LI);
370
371   UpdateDomInfoForRevectoredPreds(NewBB, OutsideBlocks);
372   
373   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
374   // code layout too horribly.
375   PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
376 }
377
378 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
379 /// blocks.  This method is used to split exit blocks that have predecessors
380 /// outside of the loop.
381 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
382   std::vector<BasicBlock*> LoopBlocks;
383   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
384     if (L->contains(*I))
385       LoopBlocks.push_back(*I);
386
387   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
388   BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
389
390   // Update Loop Information - we know that the new block will be in whichever
391   // loop the Exit block is in.  Note that it may not be in that immediate loop,
392   // if the successor is some other loop header.  In that case, we continue 
393   // walking up the loop tree to find a loop that contains both the successor
394   // block and the predecessor block.
395   Loop *SuccLoop = LI->getLoopFor(Exit);
396   while (SuccLoop && !SuccLoop->contains(L->getHeader()))
397     SuccLoop = SuccLoop->getParentLoop();
398   if (SuccLoop)
399     SuccLoop->addBasicBlockToLoop(NewBB, *LI);
400
401   // Update dominator information (set, immdom, domtree, and domfrontier)
402   UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
403   return NewBB;
404 }
405
406 /// AddBlockAndPredsToSet - Add the specified block, and all of its
407 /// predecessors, to the specified set, if it's not already in there.  Stop
408 /// predecessor traversal when we reach StopBlock.
409 static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
410                                   std::set<BasicBlock*> &Blocks) {
411   if (!Blocks.insert(BB).second) return;  // already processed.
412   if (BB == StopBlock) return;  // Stop here!
413
414   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
415     AddBlockAndPredsToSet(*I, StopBlock, Blocks);
416 }
417
418 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
419 /// PHI node that tells us how to partition the loops.
420 static PHINode *FindPHIToPartitionLoops(Loop *L, ETForest *EF, 
421                                         AliasAnalysis *AA) {
422   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
423     PHINode *PN = cast<PHINode>(I);
424     ++I;
425     if (Value *V = PN->hasConstantValue())
426       if (!isa<Instruction>(V) || EF->dominates(cast<Instruction>(V), PN)) {
427         // This is a degenerate PHI already, don't modify it!
428         PN->replaceAllUsesWith(V);
429         if (AA) AA->deleteValue(PN);
430         PN->eraseFromParent();
431         continue;
432       }
433
434     // Scan this PHI node looking for a use of the PHI node by itself.
435     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
436       if (PN->getIncomingValue(i) == PN &&
437           L->contains(PN->getIncomingBlock(i)))
438         // We found something tasty to remove.
439         return PN;
440   }
441   return 0;
442 }
443
444 // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
445 // right after some 'outside block' block.  This prevents the preheader from
446 // being placed inside the loop body, e.g. when the loop hasn't been rotated.
447 void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
448                                             std::vector<BasicBlock*>&SplitPreds,
449                                             Loop *L) {
450   // Check to see if NewBB is already well placed.
451   Function::iterator BBI = NewBB; --BBI;
452   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
453     if (&*BBI == SplitPreds[i])
454       return;
455   }
456   
457   // If it isn't already after an outside block, move it after one.  This is
458   // always good as it makes the uncond branch from the outside block into a
459   // fall-through.
460   
461   // Figure out *which* outside block to put this after.  Prefer an outside
462   // block that neighbors a BB actually in the loop.
463   BasicBlock *FoundBB = 0;
464   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
465     Function::iterator BBI = SplitPreds[i];
466     if (++BBI != NewBB->getParent()->end() && 
467         L->contains(BBI)) {
468       FoundBB = SplitPreds[i];
469       break;
470     }
471   }
472   
473   // If our heuristic for a *good* bb to place this after doesn't find
474   // anything, just pick something.  It's likely better than leaving it within
475   // the loop.
476   if (!FoundBB)
477     FoundBB = SplitPreds[0];
478   NewBB->moveAfter(FoundBB);
479 }
480
481
482 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
483 /// them out into a nested loop.  This is important for code that looks like
484 /// this:
485 ///
486 ///  Loop:
487 ///     ...
488 ///     br cond, Loop, Next
489 ///     ...
490 ///     br cond2, Loop, Out
491 ///
492 /// To identify this common case, we look at the PHI nodes in the header of the
493 /// loop.  PHI nodes with unchanging values on one backedge correspond to values
494 /// that change in the "outer" loop, but not in the "inner" loop.
495 ///
496 /// If we are able to separate out a loop, return the new outer loop that was
497 /// created.
498 ///
499 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
500   ETForest *EF = getAnalysisToUpdate<ETForest>();
501   PHINode *PN = FindPHIToPartitionLoops(L, EF, AA);
502   if (PN == 0) return 0;  // No known way to partition.
503
504   // Pull out all predecessors that have varying values in the loop.  This
505   // handles the case when a PHI node has multiple instances of itself as
506   // arguments.
507   std::vector<BasicBlock*> OuterLoopPreds;
508   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
509     if (PN->getIncomingValue(i) != PN ||
510         !L->contains(PN->getIncomingBlock(i)))
511       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
512
513   BasicBlock *Header = L->getHeader();
514   BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
515
516   // Update dominator information (set, immdom, domtree, and domfrontier)
517   UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
518
519   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
520   // code layout too horribly.
521   PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
522   
523   // Create the new outer loop.
524   Loop *NewOuter = new Loop();
525
526   // Change the parent loop to use the outer loop as its child now.
527   if (Loop *Parent = L->getParentLoop())
528     Parent->replaceChildLoopWith(L, NewOuter);
529   else
530     LI->changeTopLevelLoop(L, NewOuter);
531
532   // This block is going to be our new header block: add it to this loop and all
533   // parent loops.
534   NewOuter->addBasicBlockToLoop(NewBB, *LI);
535
536   // L is now a subloop of our outer loop.
537   NewOuter->addChildLoop(L);
538
539   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
540     NewOuter->addBlockEntry(L->getBlocks()[i]);
541
542   // Determine which blocks should stay in L and which should be moved out to
543   // the Outer loop now.
544   std::set<BasicBlock*> BlocksInL;
545   for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
546     if (EF->dominates(Header, *PI))
547       AddBlockAndPredsToSet(*PI, Header, BlocksInL);
548
549
550   // Scan all of the loop children of L, moving them to OuterLoop if they are
551   // not part of the inner loop.
552   for (Loop::iterator I = L->begin(); I != L->end(); )
553     if (BlocksInL.count((*I)->getHeader()))
554       ++I;   // Loop remains in L
555     else
556       NewOuter->addChildLoop(L->removeChildLoop(I));
557
558   // Now that we know which blocks are in L and which need to be moved to
559   // OuterLoop, move any blocks that need it.
560   for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
561     BasicBlock *BB = L->getBlocks()[i];
562     if (!BlocksInL.count(BB)) {
563       // Move this block to the parent, updating the exit blocks sets
564       L->removeBlockFromLoop(BB);
565       if ((*LI)[BB] == L)
566         LI->changeLoopFor(BB, NewOuter);
567       --i;
568     }
569   }
570
571   return NewOuter;
572 }
573
574
575
576 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
577 /// has more than one backedge in it.  If this occurs, revector all of these
578 /// backedges to target a new basic block and have that block branch to the loop
579 /// header.  This ensures that loops have exactly one backedge.
580 ///
581 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
582   assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
583
584   // Get information about the loop
585   BasicBlock *Preheader = L->getLoopPreheader();
586   BasicBlock *Header = L->getHeader();
587   Function *F = Header->getParent();
588
589   // Figure out which basic blocks contain back-edges to the loop header.
590   std::vector<BasicBlock*> BackedgeBlocks;
591   for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
592     if (*I != Preheader) BackedgeBlocks.push_back(*I);
593
594   // Create and insert the new backedge block...
595   BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
596   BranchInst *BETerminator = new BranchInst(Header, BEBlock);
597
598   // Move the new backedge block to right after the last backedge block.
599   Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
600   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
601
602   // Now that the block has been inserted into the function, create PHI nodes in
603   // the backedge block which correspond to any PHI nodes in the header block.
604   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
605     PHINode *PN = cast<PHINode>(I);
606     PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
607                                  BETerminator);
608     NewPN->reserveOperandSpace(BackedgeBlocks.size());
609     if (AA) AA->copyValue(PN, NewPN);
610
611     // Loop over the PHI node, moving all entries except the one for the
612     // preheader over to the new PHI node.
613     unsigned PreheaderIdx = ~0U;
614     bool HasUniqueIncomingValue = true;
615     Value *UniqueValue = 0;
616     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
617       BasicBlock *IBB = PN->getIncomingBlock(i);
618       Value *IV = PN->getIncomingValue(i);
619       if (IBB == Preheader) {
620         PreheaderIdx = i;
621       } else {
622         NewPN->addIncoming(IV, IBB);
623         if (HasUniqueIncomingValue) {
624           if (UniqueValue == 0)
625             UniqueValue = IV;
626           else if (UniqueValue != IV)
627             HasUniqueIncomingValue = false;
628         }
629       }
630     }
631
632     // Delete all of the incoming values from the old PN except the preheader's
633     assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
634     if (PreheaderIdx != 0) {
635       PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
636       PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
637     }
638     // Nuke all entries except the zero'th.
639     for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
640       PN->removeIncomingValue(e-i, false);
641
642     // Finally, add the newly constructed PHI node as the entry for the BEBlock.
643     PN->addIncoming(NewPN, BEBlock);
644
645     // As an optimization, if all incoming values in the new PhiNode (which is a
646     // subset of the incoming values of the old PHI node) have the same value,
647     // eliminate the PHI Node.
648     if (HasUniqueIncomingValue) {
649       NewPN->replaceAllUsesWith(UniqueValue);
650       if (AA) AA->deleteValue(NewPN);
651       BEBlock->getInstList().erase(NewPN);
652     }
653   }
654
655   // Now that all of the PHI nodes have been inserted and adjusted, modify the
656   // backedge blocks to just to the BEBlock instead of the header.
657   for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
658     TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
659     for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
660       if (TI->getSuccessor(Op) == Header)
661         TI->setSuccessor(Op, BEBlock);
662   }
663
664   //===--- Update all analyses which we must preserve now -----------------===//
665
666   // Update Loop Information - we know that this block is now in the current
667   // loop and all parent loops.
668   L->addBasicBlockToLoop(BEBlock, *LI);
669
670   // Update dominator information (set, immdom, domtree, and domfrontier)
671   UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
672 }
673
674 /// UpdateDomInfoForRevectoredPreds - This method is used to update the four
675 /// different kinds of dominator information (immediate dominators,
676 /// dominator trees, et-forest and dominance frontiers) after a new block has
677 /// been added to the CFG.
678 ///
679 /// This only supports the case when an existing block (known as "NewBBSucc"),
680 /// had some of its predecessors factored into a new basic block.  This
681 /// transformation inserts a new basic block ("NewBB"), with a single
682 /// unconditional branch to NewBBSucc, and moves some predecessors of
683 /// "NewBBSucc" to now branch to NewBB.  These predecessors are listed in
684 /// PredBlocks, even though they are the same as
685 /// pred_begin(NewBB)/pred_end(NewBB).
686 ///
687 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
688                                          std::vector<BasicBlock*> &PredBlocks) {
689   assert(!PredBlocks.empty() && "No predblocks??");
690   assert(succ_begin(NewBB) != succ_end(NewBB) &&
691          ++succ_begin(NewBB) == succ_end(NewBB) &&
692          "NewBB should have a single successor!");
693   BasicBlock *NewBBSucc = *succ_begin(NewBB);
694   ETForest& ETF = getAnalysis<ETForest>();
695   
696   // The newly inserted basic block will dominate existing basic blocks iff the
697   // PredBlocks dominate all of the non-pred blocks.  If all predblocks dominate
698   // the non-pred blocks, then they all must be the same block!
699   //
700   bool NewBBDominatesNewBBSucc = true;
701   {
702     BasicBlock *OnePred = PredBlocks[0];
703     unsigned i = 1, e = PredBlocks.size();
704     for (i = 1; !ETF.dominates(&OnePred->getParent()->getEntryBlock(), OnePred);
705          ++i) {
706       assert(i != e && "Didn't find reachable pred?");
707       OnePred = PredBlocks[i];
708     }
709     
710     for (; i != e; ++i)
711       if (PredBlocks[i] != OnePred &&
712           ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), OnePred)){
713         NewBBDominatesNewBBSucc = false;
714         break;
715       }
716
717     if (NewBBDominatesNewBBSucc)
718       for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
719            PI != E; ++PI)
720         if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
721           NewBBDominatesNewBBSucc = false;
722           break;
723         }
724   }
725
726   // The other scenario where the new block can dominate its successors are when
727   // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
728   // already.
729   if (!NewBBDominatesNewBBSucc) {
730     NewBBDominatesNewBBSucc = true;
731     for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
732          PI != E; ++PI)
733       if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
734         NewBBDominatesNewBBSucc = false;
735         break;
736       }
737   }
738
739   BasicBlock *NewBBIDom = 0;
740   
741   // Update immediate dominator information if we have it.
742   if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
743     unsigned i = 0;
744     for (i = 0; i < PredBlocks.size(); ++i)
745       if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i])) {
746         NewBBIDom = PredBlocks[i];
747         break;
748       }
749     assert(i != PredBlocks.size() && "No reachable preds?");
750     for (i = i + 1; i < PredBlocks.size(); ++i) {
751       if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i]))
752         NewBBIDom = ETF.nearestCommonDominator(NewBBIDom, PredBlocks[i]);
753     }
754     assert(NewBBIDom && "No immediate dominator found??");
755   
756     // Set the immediate dominator now...
757     ID->addNewBlock(NewBB, NewBBIDom);
758
759     // If NewBB strictly dominates other blocks, we need to update their idom's
760     // now.  The only block that need adjustment is the NewBBSucc block, whose
761     // idom should currently be set to PredBlocks[0].
762     if (NewBBDominatesNewBBSucc)
763       ID->setImmediateDominator(NewBBSucc, NewBB);
764   }
765
766   // Update DominatorTree information if it is active.
767   if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
768     // If we don't have ImmediateDominator info around, calculate the idom as
769     // above.
770     if (!NewBBIDom) {
771       unsigned i = 0;
772       for (i = 0; i < PredBlocks.size(); ++i)
773         if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i])) {
774           NewBBIDom = PredBlocks[i];
775           break;
776         }
777       assert(i != PredBlocks.size() && "No reachable preds?");
778       for (i = i + 1; i < PredBlocks.size(); ++i) {
779         if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i]))
780           NewBBIDom = ETF.nearestCommonDominator(NewBBIDom, PredBlocks[i]);
781       }
782       assert(NewBBIDom && "No immediate dominator found??");
783     }
784     DominatorTree::Node *NewBBIDomNode = DT->getNode(NewBBIDom);
785
786     // Create the new dominator tree node... and set the idom of NewBB.
787     DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
788
789     // If NewBB strictly dominates other blocks, then it is now the immediate
790     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
791     if (NewBBDominatesNewBBSucc) {
792       DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
793       DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
794     }
795   }
796
797   // Update ET-Forest information if it is active.
798   if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
799     EF->addNewBlock(NewBB, NewBBIDom);
800     if (NewBBDominatesNewBBSucc)
801       EF->setImmediateDominator(NewBBSucc, NewBB);
802   }
803
804   // Update dominance frontier information...
805   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
806     // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
807     // DF(PredBlocks[0]) without the stuff that the new block does not dominate
808     // a predecessor of.
809     if (NewBBDominatesNewBBSucc) {
810       DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
811       if (DFI != DF->end()) {
812         DominanceFrontier::DomSetType Set = DFI->second;
813         // Filter out stuff in Set that we do not dominate a predecessor of.
814         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
815                E = Set.end(); SetI != E;) {
816           bool DominatesPred = false;
817           for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
818                PI != E; ++PI)
819             if (ETF.dominates(NewBB, *PI))
820               DominatesPred = true;
821           if (!DominatesPred)
822             Set.erase(SetI++);
823           else
824             ++SetI;
825         }
826
827         DF->addBasicBlock(NewBB, Set);
828       }
829
830     } else {
831       // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
832       // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
833       // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
834       DominanceFrontier::DomSetType NewDFSet;
835       NewDFSet.insert(NewBBSucc);
836       DF->addBasicBlock(NewBB, NewDFSet);
837     }
838
839     // Now we must loop over all of the dominance frontiers in the function,
840     // replacing occurrences of NewBBSucc with NewBB in some cases.  All
841     // blocks that dominate a block in PredBlocks and contained NewBBSucc in
842     // their dominance frontier must be updated to contain NewBB instead.
843     //
844     for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
845       BasicBlock *Pred = PredBlocks[i];
846       // Get all of the dominators of the predecessor...
847       // FIXME: There's probably a better way to do this...
848       std::vector<BasicBlock*> PredDoms;
849       for (Function::iterator I = Pred->getParent()->begin(),
850            E = Pred->getParent()->end(); I != E; ++I)
851         if (ETF.dominates(&(*I), Pred))
852           PredDoms.push_back(I);
853       
854       for (std::vector<BasicBlock*>::const_iterator PDI = PredDoms.begin(),
855              PDE = PredDoms.end(); PDI != PDE; ++PDI) {
856         BasicBlock *PredDom = *PDI;
857
858         // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
859         // dominate NewBBSucc but did dominate a predecessor of it.  Now we
860         // change this entry to include NewBB in the DF instead of NewBBSucc.
861         DominanceFrontier::iterator DFI = DF->find(PredDom);
862         assert(DFI != DF->end() && "No dominance frontier for node?");
863         if (DFI->second.count(NewBBSucc)) {
864           // If NewBBSucc should not stay in our dominator frontier, remove it.
865           // We remove it unless there is a predecessor of NewBBSucc that we
866           // dominate, but we don't strictly dominate NewBBSucc.
867           bool ShouldRemove = true;
868           if (PredDom == NewBBSucc || !ETF.dominates(PredDom, NewBBSucc)) {
869             // Okay, we know that PredDom does not strictly dominate NewBBSucc.
870             // Check to see if it dominates any predecessors of NewBBSucc.
871             for (pred_iterator PI = pred_begin(NewBBSucc),
872                    E = pred_end(NewBBSucc); PI != E; ++PI)
873               if (ETF.dominates(PredDom, *PI)) {
874                 ShouldRemove = false;
875                 break;
876               }
877           }
878
879           if (ShouldRemove)
880             DF->removeFromFrontier(DFI, NewBBSucc);
881           DF->addToFrontier(DFI, NewBB);
882         }
883       }
884     }
885   }
886 }
887