Move code to update dominator information after basic block is split
[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     static char ID; // Pass identification, replacement for typeid
58     LoopSimplify() : FunctionPass((intptr_t)&ID) {}
59
60     // AA - If we have an alias analysis object to update, this is it, otherwise
61     // this is null.
62     AliasAnalysis *AA;
63     LoopInfo *LI;
64     DominatorTree *DT;
65     virtual bool runOnFunction(Function &F);
66
67     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68       // We need loop information to identify the loops...
69       AU.addRequired<LoopInfo>();
70       AU.addRequired<DominatorTree>();
71
72       AU.addPreserved<LoopInfo>();
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
90   char LoopSimplify::ID = 0;
91   RegisterPass<LoopSimplify>
92   X("loopsimplify", "Canonicalize natural loops", true);
93 }
94
95 // Publically exposed interface to pass...
96 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
97 FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
98
99 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
100 /// it in any convenient order) inserting preheaders...
101 ///
102 bool LoopSimplify::runOnFunction(Function &F) {
103   bool Changed = false;
104   LI = &getAnalysis<LoopInfo>();
105   AA = getAnalysisToUpdate<AliasAnalysis>();
106   DT = &getAnalysis<DominatorTree>();
107
108   // Check to see that no blocks (other than the header) in loops have
109   // predecessors that are not in loops.  This is not valid for natural loops,
110   // but can occur if the blocks are unreachable.  Since they are unreachable we
111   // can just shamelessly destroy their terminators to make them not branch into
112   // the loop!
113   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
114     // This case can only occur for unreachable blocks.  Blocks that are
115     // unreachable can't be in loops, so filter those blocks out.
116     if (LI->getLoopFor(BB)) continue;
117     
118     bool BlockUnreachable = false;
119     TerminatorInst *TI = BB->getTerminator();
120
121     // Check to see if any successors of this block are non-loop-header loops
122     // that are not the header.
123     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
124       // If this successor is not in a loop, BB is clearly ok.
125       Loop *L = LI->getLoopFor(TI->getSuccessor(i));
126       if (!L) continue;
127       
128       // If the succ is the loop header, and if L is a top-level loop, then this
129       // is an entrance into a loop through the header, which is also ok.
130       if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
131         continue;
132       
133       // Otherwise, this is an entrance into a loop from some place invalid.
134       // Either the loop structure is invalid and this is not a natural loop (in
135       // which case the compiler is buggy somewhere else) or BB is unreachable.
136       BlockUnreachable = true;
137       break;
138     }
139     
140     // If this block is ok, check the next one.
141     if (!BlockUnreachable) continue;
142     
143     // Otherwise, this block is dead.  To clean up the CFG and to allow later
144     // loop transformations to ignore this case, we delete the edges into the
145     // loop by replacing the terminator.
146     
147     // Remove PHI entries from the successors.
148     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
149       TI->getSuccessor(i)->removePredecessor(BB);
150    
151     // Add a new unreachable instruction.
152     new UnreachableInst(TI);
153     
154     // Delete the dead terminator.
155     if (AA) AA->deleteValue(&BB->back());
156     BB->getInstList().pop_back();
157     Changed |= true;
158   }
159   
160   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
161     Changed |= ProcessLoop(*I);
162
163   return Changed;
164 }
165
166 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
167 /// all loops have preheaders.
168 ///
169 bool LoopSimplify::ProcessLoop(Loop *L) {
170   bool Changed = false;
171 ReprocessLoop:
172   
173   // Canonicalize inner loops before outer loops.  Inner loop canonicalization
174   // can provide work for the outer loop to canonicalize.
175   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
176     Changed |= ProcessLoop(*I);
177   
178   assert(L->getBlocks()[0] == L->getHeader() &&
179          "Header isn't first block in loop?");
180
181   // Does the loop already have a preheader?  If so, don't insert one.
182   if (L->getLoopPreheader() == 0) {
183     InsertPreheaderForLoop(L);
184     NumInserted++;
185     Changed = true;
186   }
187
188   // Next, check to make sure that all exit nodes of the loop only have
189   // predecessors that are inside of the loop.  This check guarantees that the
190   // loop preheader/header will dominate the exit blocks.  If the exit block has
191   // predecessors from outside of the loop, split the edge now.
192   std::vector<BasicBlock*> ExitBlocks;
193   L->getExitBlocks(ExitBlocks);
194     
195   SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
196   for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
197          E = ExitBlockSet.end(); I != E; ++I) {
198     BasicBlock *ExitBlock = *I;
199     for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
200          PI != PE; ++PI)
201       // Must be exactly this loop: no subloops, parent loops, or non-loop preds
202       // allowed.
203       if (!L->contains(*PI)) {
204         RewriteLoopExitBlock(L, ExitBlock);
205         NumInserted++;
206         Changed = true;
207         break;
208       }
209   }
210
211   // If the header has more than two predecessors at this point (from the
212   // preheader and from multiple backedges), we must adjust the loop.
213   unsigned NumBackedges = L->getNumBackEdges();
214   if (NumBackedges != 1) {
215     // If this is really a nested loop, rip it out into a child loop.  Don't do
216     // this for loops with a giant number of backedges, just factor them into a
217     // common backedge instead.
218     if (NumBackedges < 8) {
219       if (Loop *NL = SeparateNestedLoop(L)) {
220         ++NumNested;
221         // This is a big restructuring change, reprocess the whole loop.
222         ProcessLoop(NL);
223         Changed = true;
224         // GCC doesn't tail recursion eliminate this.
225         goto ReprocessLoop;
226       }
227     }
228
229     // If we either couldn't, or didn't want to, identify nesting of the loops,
230     // insert a new block that all backedges target, then make it jump to the
231     // loop header.
232     InsertUniqueBackedgeBlock(L);
233     NumInserted++;
234     Changed = true;
235   }
236
237   // Scan over the PHI nodes in the loop header.  Since they now have only two
238   // incoming values (the loop is canonicalized), we may have simplified the PHI
239   // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
240   PHINode *PN;
241   for (BasicBlock::iterator I = L->getHeader()->begin();
242        (PN = dyn_cast<PHINode>(I++)); )
243     if (Value *V = PN->hasConstantValue()) {
244         PN->replaceAllUsesWith(V);
245         PN->eraseFromParent();
246       }
247
248   return Changed;
249 }
250
251 /// SplitBlockPredecessors - Split the specified block into two blocks.  We want
252 /// to move the predecessors specified in the Preds list to point to the new
253 /// block, leaving the remaining predecessors pointing to BB.  This method
254 /// updates the SSA PHINode's, but no other analyses.
255 ///
256 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
257                                                  const char *Suffix,
258                                        const std::vector<BasicBlock*> &Preds) {
259
260   // Create new basic block, insert right before the original block...
261   BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
262
263   // The preheader first gets an unconditional branch to the loop header...
264   BranchInst *BI = new BranchInst(BB, NewBB);
265
266   // For every PHI node in the block, insert a PHI node into NewBB where the
267   // incoming values from the out of loop edges are moved to NewBB.  We have two
268   // possible cases here.  If the loop is dead, we just insert dummy entries
269   // into the PHI nodes for the new edge.  If the loop is not dead, we move the
270   // incoming edges in BB into new PHI nodes in NewBB.
271   //
272   if (!Preds.empty()) {  // Is the loop not obviously dead?
273     // Check to see if the values being merged into the new block need PHI
274     // nodes.  If so, insert them.
275     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
276       PHINode *PN = cast<PHINode>(I);
277       ++I;
278
279       // Check to see if all of the values coming in are the same.  If so, we
280       // don't need to create a new PHI node.
281       Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
282       for (unsigned i = 1, e = Preds.size(); i != e; ++i)
283         if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
284           InVal = 0;
285           break;
286         }
287
288       // If the values coming into the block are not the same, we need a PHI.
289       if (InVal == 0) {
290         // Create the new PHI node, insert it into NewBB at the end of the block
291         PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
292         if (AA) AA->copyValue(PN, NewPHI);
293
294         // Move all of the edges from blocks outside the loop to the new PHI
295         for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
296           Value *V = PN->removeIncomingValue(Preds[i], false);
297           NewPHI->addIncoming(V, Preds[i]);
298         }
299         InVal = NewPHI;
300       } else {
301         // Remove all of the edges coming into the PHI nodes from outside of the
302         // block.
303         for (unsigned i = 0, e = Preds.size(); i != e; ++i)
304           PN->removeIncomingValue(Preds[i], false);
305       }
306
307       // Add an incoming value to the PHI node in the loop for the preheader
308       // edge.
309       PN->addIncoming(InVal, NewBB);
310
311       // Can we eliminate this phi node now?
312       if (Value *V = PN->hasConstantValue(true)) {
313         Instruction *I = dyn_cast<Instruction>(V);
314         // If I is in NewBB, the Dominator call will fail, because NewBB isn't
315         // registered in DominatorTree yet.  Handle this case explicitly.
316         if (!I || (I->getParent() != NewBB &&
317                    getAnalysis<DominatorTree>().dominates(I, PN))) {
318           PN->replaceAllUsesWith(V);
319           if (AA) AA->deleteValue(PN);
320           BB->getInstList().erase(PN);
321         }
322       }
323     }
324
325     // Now that the PHI nodes are updated, actually move the edges from
326     // Preds to point to NewBB instead of BB.
327     //
328     for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
329       TerminatorInst *TI = Preds[i]->getTerminator();
330       for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
331         if (TI->getSuccessor(s) == BB)
332           TI->setSuccessor(s, NewBB);
333     }
334
335   } else {                       // Otherwise the loop is dead...
336     for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
337       PHINode *PN = cast<PHINode>(I);
338       // Insert dummy values as the incoming value...
339       PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
340     }
341   }
342
343   return NewBB;
344 }
345
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.
349 ///
350 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
351   BasicBlock *Header = L->getHeader();
352
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);
356        PI != PE; ++PI)
357     if (!L->contains(*PI))           // Coming in from outside the loop?
358       OutsideBlocks.push_back(*PI);  // Keep track of it...
359
360   // Split out the loop pre-header.
361   BasicBlock *NewBB =
362     SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
363   
364
365   //===--------------------------------------------------------------------===//
366   //  Update analysis results now that we have performed the transformation
367   //
368
369   // We know that we have loop information to update... update it now.
370   if (Loop *Parent = L->getParentLoop())
371     Parent->addBasicBlockToLoop(NewBB, *LI);
372
373   DT->splitBlock(NewBB);
374   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
375     DF->splitBlock(NewBB);
376
377   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
378   // code layout too horribly.
379   PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
380 }
381
382 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
383 /// blocks.  This method is used to split exit blocks that have predecessors
384 /// outside of the loop.
385 BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
386   std::vector<BasicBlock*> LoopBlocks;
387   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
388     if (L->contains(*I))
389       LoopBlocks.push_back(*I);
390
391   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
392   BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
393
394   // Update Loop Information - we know that the new block will be in whichever
395   // loop the Exit block is in.  Note that it may not be in that immediate loop,
396   // if the successor is some other loop header.  In that case, we continue 
397   // walking up the loop tree to find a loop that contains both the successor
398   // block and the predecessor block.
399   Loop *SuccLoop = LI->getLoopFor(Exit);
400   while (SuccLoop && !SuccLoop->contains(L->getHeader()))
401     SuccLoop = SuccLoop->getParentLoop();
402   if (SuccLoop)
403     SuccLoop->addBasicBlockToLoop(NewBB, *LI);
404
405   // Update Dominator Information
406   DT->splitBlock(NewBB);
407   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
408     DF->splitBlock(NewBB);
409
410   return NewBB;
411 }
412
413 /// AddBlockAndPredsToSet - Add the specified block, and all of its
414 /// predecessors, to the specified set, if it's not already in there.  Stop
415 /// predecessor traversal when we reach StopBlock.
416 static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
417                                   std::set<BasicBlock*> &Blocks) {
418   std::vector<BasicBlock *> WorkList;
419   WorkList.push_back(InputBB);
420   do {
421     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
422     if (Blocks.insert(BB).second && BB != StopBlock)
423       // If BB is not already processed and it is not a stop block then
424       // insert its predecessor in the work list
425       for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
426         BasicBlock *WBB = *I;
427         WorkList.push_back(WBB);
428       }
429   } while(!WorkList.empty());
430 }
431
432 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
433 /// PHI node that tells us how to partition the loops.
434 static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorTree *DT,
435                                         AliasAnalysis *AA) {
436   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
437     PHINode *PN = cast<PHINode>(I);
438     ++I;
439     if (Value *V = PN->hasConstantValue())
440       if (!isa<Instruction>(V) || DT->dominates(cast<Instruction>(V), PN)) {
441         // This is a degenerate PHI already, don't modify it!
442         PN->replaceAllUsesWith(V);
443         if (AA) AA->deleteValue(PN);
444         PN->eraseFromParent();
445         continue;
446       }
447
448     // Scan this PHI node looking for a use of the PHI node by itself.
449     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
450       if (PN->getIncomingValue(i) == PN &&
451           L->contains(PN->getIncomingBlock(i)))
452         // We found something tasty to remove.
453         return PN;
454   }
455   return 0;
456 }
457
458 // PlaceSplitBlockCarefully - If the block isn't already, move the new block to
459 // right after some 'outside block' block.  This prevents the preheader from
460 // being placed inside the loop body, e.g. when the loop hasn't been rotated.
461 void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
462                                             std::vector<BasicBlock*>&SplitPreds,
463                                             Loop *L) {
464   // Check to see if NewBB is already well placed.
465   Function::iterator BBI = NewBB; --BBI;
466   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
467     if (&*BBI == SplitPreds[i])
468       return;
469   }
470   
471   // If it isn't already after an outside block, move it after one.  This is
472   // always good as it makes the uncond branch from the outside block into a
473   // fall-through.
474   
475   // Figure out *which* outside block to put this after.  Prefer an outside
476   // block that neighbors a BB actually in the loop.
477   BasicBlock *FoundBB = 0;
478   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
479     Function::iterator BBI = SplitPreds[i];
480     if (++BBI != NewBB->getParent()->end() && 
481         L->contains(BBI)) {
482       FoundBB = SplitPreds[i];
483       break;
484     }
485   }
486   
487   // If our heuristic for a *good* bb to place this after doesn't find
488   // anything, just pick something.  It's likely better than leaving it within
489   // the loop.
490   if (!FoundBB)
491     FoundBB = SplitPreds[0];
492   NewBB->moveAfter(FoundBB);
493 }
494
495
496 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
497 /// them out into a nested loop.  This is important for code that looks like
498 /// this:
499 ///
500 ///  Loop:
501 ///     ...
502 ///     br cond, Loop, Next
503 ///     ...
504 ///     br cond2, Loop, Out
505 ///
506 /// To identify this common case, we look at the PHI nodes in the header of the
507 /// loop.  PHI nodes with unchanging values on one backedge correspond to values
508 /// that change in the "outer" loop, but not in the "inner" loop.
509 ///
510 /// If we are able to separate out a loop, return the new outer loop that was
511 /// created.
512 ///
513 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
514   PHINode *PN = FindPHIToPartitionLoops(L, DT, AA);
515   if (PN == 0) return 0;  // No known way to partition.
516
517   // Pull out all predecessors that have varying values in the loop.  This
518   // handles the case when a PHI node has multiple instances of itself as
519   // arguments.
520   std::vector<BasicBlock*> OuterLoopPreds;
521   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
522     if (PN->getIncomingValue(i) != PN ||
523         !L->contains(PN->getIncomingBlock(i)))
524       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
525
526   BasicBlock *Header = L->getHeader();
527   BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
528
529   // Update dominator information
530   DT->splitBlock(NewBB);
531   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
532     DF->splitBlock(NewBB);
533
534   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
535   // code layout too horribly.
536   PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
537   
538   // Create the new outer loop.
539   Loop *NewOuter = new Loop();
540
541   // Change the parent loop to use the outer loop as its child now.
542   if (Loop *Parent = L->getParentLoop())
543     Parent->replaceChildLoopWith(L, NewOuter);
544   else
545     LI->changeTopLevelLoop(L, NewOuter);
546
547   // This block is going to be our new header block: add it to this loop and all
548   // parent loops.
549   NewOuter->addBasicBlockToLoop(NewBB, *LI);
550
551   // L is now a subloop of our outer loop.
552   NewOuter->addChildLoop(L);
553
554   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
555     NewOuter->addBlockEntry(L->getBlocks()[i]);
556
557   // Determine which blocks should stay in L and which should be moved out to
558   // the Outer loop now.
559   std::set<BasicBlock*> BlocksInL;
560   for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
561     if (DT->dominates(Header, *PI))
562       AddBlockAndPredsToSet(*PI, Header, BlocksInL);
563
564
565   // Scan all of the loop children of L, moving them to OuterLoop if they are
566   // not part of the inner loop.
567   for (Loop::iterator I = L->begin(); I != L->end(); )
568     if (BlocksInL.count((*I)->getHeader()))
569       ++I;   // Loop remains in L
570     else
571       NewOuter->addChildLoop(L->removeChildLoop(I));
572
573   // Now that we know which blocks are in L and which need to be moved to
574   // OuterLoop, move any blocks that need it.
575   for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
576     BasicBlock *BB = L->getBlocks()[i];
577     if (!BlocksInL.count(BB)) {
578       // Move this block to the parent, updating the exit blocks sets
579       L->removeBlockFromLoop(BB);
580       if ((*LI)[BB] == L)
581         LI->changeLoopFor(BB, NewOuter);
582       --i;
583     }
584   }
585
586   return NewOuter;
587 }
588
589
590
591 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
592 /// has more than one backedge in it.  If this occurs, revector all of these
593 /// backedges to target a new basic block and have that block branch to the loop
594 /// header.  This ensures that loops have exactly one backedge.
595 ///
596 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
597   assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
598
599   // Get information about the loop
600   BasicBlock *Preheader = L->getLoopPreheader();
601   BasicBlock *Header = L->getHeader();
602   Function *F = Header->getParent();
603
604   // Figure out which basic blocks contain back-edges to the loop header.
605   std::vector<BasicBlock*> BackedgeBlocks;
606   for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
607     if (*I != Preheader) BackedgeBlocks.push_back(*I);
608
609   // Create and insert the new backedge block...
610   BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
611   BranchInst *BETerminator = new BranchInst(Header, BEBlock);
612
613   // Move the new backedge block to right after the last backedge block.
614   Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
615   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
616
617   // Now that the block has been inserted into the function, create PHI nodes in
618   // the backedge block which correspond to any PHI nodes in the header block.
619   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
620     PHINode *PN = cast<PHINode>(I);
621     PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
622                                  BETerminator);
623     NewPN->reserveOperandSpace(BackedgeBlocks.size());
624     if (AA) AA->copyValue(PN, NewPN);
625
626     // Loop over the PHI node, moving all entries except the one for the
627     // preheader over to the new PHI node.
628     unsigned PreheaderIdx = ~0U;
629     bool HasUniqueIncomingValue = true;
630     Value *UniqueValue = 0;
631     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
632       BasicBlock *IBB = PN->getIncomingBlock(i);
633       Value *IV = PN->getIncomingValue(i);
634       if (IBB == Preheader) {
635         PreheaderIdx = i;
636       } else {
637         NewPN->addIncoming(IV, IBB);
638         if (HasUniqueIncomingValue) {
639           if (UniqueValue == 0)
640             UniqueValue = IV;
641           else if (UniqueValue != IV)
642             HasUniqueIncomingValue = false;
643         }
644       }
645     }
646
647     // Delete all of the incoming values from the old PN except the preheader's
648     assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
649     if (PreheaderIdx != 0) {
650       PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
651       PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
652     }
653     // Nuke all entries except the zero'th.
654     for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
655       PN->removeIncomingValue(e-i, false);
656
657     // Finally, add the newly constructed PHI node as the entry for the BEBlock.
658     PN->addIncoming(NewPN, BEBlock);
659
660     // As an optimization, if all incoming values in the new PhiNode (which is a
661     // subset of the incoming values of the old PHI node) have the same value,
662     // eliminate the PHI Node.
663     if (HasUniqueIncomingValue) {
664       NewPN->replaceAllUsesWith(UniqueValue);
665       if (AA) AA->deleteValue(NewPN);
666       BEBlock->getInstList().erase(NewPN);
667     }
668   }
669
670   // Now that all of the PHI nodes have been inserted and adjusted, modify the
671   // backedge blocks to just to the BEBlock instead of the header.
672   for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
673     TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
674     for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
675       if (TI->getSuccessor(Op) == Header)
676         TI->setSuccessor(Op, BEBlock);
677   }
678
679   //===--- Update all analyses which we must preserve now -----------------===//
680
681   // Update Loop Information - we know that this block is now in the current
682   // loop and all parent loops.
683   L->addBasicBlockToLoop(BEBlock, *LI);
684
685   // Update dominator information
686   DT->splitBlock(BEBlock);
687   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>())
688     DF->splitBlock(BEBlock);
689 }
690
691