Fix LoopSimplify/2004-04-13-LoopSimplifyUpdateDomFrontier.ll
[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 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Constant.h"
37 #include "llvm/iTerminators.h"
38 #include "llvm/iPHINode.h"
39 #include "llvm/Function.h"
40 #include "llvm/Type.h"
41 #include "llvm/Analysis/Dominators.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Support/CFG.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "Support/SetOperations.h"
46 #include "Support/Statistic.h"
47 #include "Support/DepthFirstIterator.h"
48 using namespace llvm;
49
50 namespace {
51   Statistic<>
52   NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
53   Statistic<>
54   NumNested("loopsimplify", "Number of nested loops split out");
55
56   struct LoopSimplify : public FunctionPass {
57     virtual bool runOnFunction(Function &F);
58     
59     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60       // We need loop information to identify the loops...
61       AU.addRequired<LoopInfo>();
62       AU.addRequired<DominatorSet>();
63       AU.addRequired<DominatorTree>();
64
65       AU.addPreserved<LoopInfo>();
66       AU.addPreserved<DominatorSet>();
67       AU.addPreserved<ImmediateDominators>();
68       AU.addPreserved<DominatorTree>();
69       AU.addPreserved<DominanceFrontier>();
70       AU.addPreservedID(BreakCriticalEdgesID);  // No crit edges added....
71     }
72   private:
73     bool ProcessLoop(Loop *L);
74     BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
75                                        const std::vector<BasicBlock*> &Preds);
76     void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
77     void InsertPreheaderForLoop(Loop *L);
78     Loop *SeparateNestedLoop(Loop *L);
79     void InsertUniqueBackedgeBlock(Loop *L);
80
81     void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
82                                          std::vector<BasicBlock*> &PredBlocks);
83   };
84
85   RegisterOpt<LoopSimplify>
86   X("loopsimplify", "Canonicalize natural loops", true);
87 }
88
89 // Publically exposed interface to pass...
90 const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
91 Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
92
93 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
94 /// it in any convenient order) inserting preheaders...
95 ///
96 bool LoopSimplify::runOnFunction(Function &F) {
97   bool Changed = false;
98   LoopInfo &LI = getAnalysis<LoopInfo>();
99
100   for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
101     Changed |= ProcessLoop(*I);
102
103   return Changed;
104 }
105
106
107 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
108 /// all loops have preheaders.
109 ///
110 bool LoopSimplify::ProcessLoop(Loop *L) {
111   bool Changed = false;
112
113   // Check to see that no blocks (other than the header) in the loop have
114   // predecessors that are not in the loop.  This is not valid for natural
115   // loops, but can occur if the blocks are unreachable.  Since they are
116   // unreachable we can just shamelessly destroy their terminators to make them
117   // not branch into the loop!
118   assert(L->getBlocks()[0] == L->getHeader() &&
119          "Header isn't first block in loop?");
120   for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
121     BasicBlock *LoopBB = L->getBlocks()[i];
122   Retry:
123     for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
124          PI != E; ++PI)
125       if (!L->contains(*PI)) {
126         // This predecessor is not in the loop.  Kill its terminator!
127         BasicBlock *DeadBlock = *PI;
128         for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
129              SI != E; ++SI)
130           (*SI)->removePredecessor(DeadBlock);  // Remove PHI node entries
131
132         // Delete the dead terminator.
133         DeadBlock->getInstList().pop_back();
134
135         Value *RetVal = 0;
136         if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
137           RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
138         new ReturnInst(RetVal, DeadBlock);
139         goto Retry;  // We just invalidated the pred_iterator.  Retry.
140       }
141   }
142
143   // Does the loop already have a preheader?  If so, don't modify the loop...
144   if (L->getLoopPreheader() == 0) {
145     InsertPreheaderForLoop(L);
146     NumInserted++;
147     Changed = true;
148   }
149
150   // Next, check to make sure that all exit nodes of the loop only have
151   // predecessors that are inside of the loop.  This check guarantees that the
152   // loop preheader/header will dominate the exit blocks.  If the exit block has
153   // predecessors from outside of the loop, split the edge now.
154   for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i) {
155     BasicBlock *ExitBlock = L->getExitBlocks()[i];
156     for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
157          PI != PE; ++PI)
158       if (!L->contains(*PI)) {
159         RewriteLoopExitBlock(L, ExitBlock);
160         NumInserted++;
161         Changed = true;
162         break;
163       }
164     }
165
166   // If the header has more than two predecessors at this point (from the
167   // preheader and from multiple backedges), we must adjust the loop.
168   if (L->getNumBackEdges() != 1) {
169     // If this is really a nested loop, rip it out into a child loop.
170     if (Loop *NL = SeparateNestedLoop(L)) {
171       ++NumNested;
172       // This is a big restructuring change, reprocess the whole loop.
173       ProcessLoop(NL);
174       return true;
175     }
176
177     InsertUniqueBackedgeBlock(L);
178     NumInserted++;
179     Changed = true;
180   }
181
182   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
183     Changed |= ProcessLoop(*I);
184   return Changed;
185 }
186
187 /// SplitBlockPredecessors - Split the specified block into two blocks.  We want
188 /// to move the predecessors specified in the Preds list to point to the new
189 /// block, leaving the remaining predecessors pointing to BB.  This method
190 /// updates the SSA PHINode's, but no other analyses.
191 ///
192 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
193                                                  const char *Suffix,
194                                        const std::vector<BasicBlock*> &Preds) {
195   
196   // Create new basic block, insert right before the original block...
197   BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
198
199   // The preheader first gets an unconditional branch to the loop header...
200   BranchInst *BI = new BranchInst(BB, NewBB);
201   
202   // For every PHI node in the block, insert a PHI node into NewBB where the
203   // incoming values from the out of loop edges are moved to NewBB.  We have two
204   // possible cases here.  If the loop is dead, we just insert dummy entries
205   // into the PHI nodes for the new edge.  If the loop is not dead, we move the
206   // incoming edges in BB into new PHI nodes in NewBB.
207   //
208   if (!Preds.empty()) {  // Is the loop not obviously dead?
209     // Check to see if the values being merged into the new block need PHI
210     // nodes.  If so, insert them.
211     for (BasicBlock::iterator I = BB->begin();
212          PHINode *PN = dyn_cast<PHINode>(I); ) {
213       ++I;
214
215       // Check to see if all of the values coming in are the same.  If so, we
216       // don't need to create a new PHI node.
217       Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
218       for (unsigned i = 1, e = Preds.size(); i != e; ++i)
219         if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
220           InVal = 0;
221           break;
222         }
223       
224       // If the values coming into the block are not the same, we need a PHI.
225       if (InVal == 0) {
226         // Create the new PHI node, insert it into NewBB at the end of the block
227         PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
228         
229         // Move all of the edges from blocks outside the loop to the new PHI
230         for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
231           Value *V = PN->removeIncomingValue(Preds[i], false);
232           NewPHI->addIncoming(V, Preds[i]);
233         }
234         InVal = NewPHI;
235       } else {
236         // Remove all of the edges coming into the PHI nodes from outside of the
237         // block.
238         for (unsigned i = 0, e = Preds.size(); i != e; ++i)
239           PN->removeIncomingValue(Preds[i], false);
240       }
241
242       // Add an incoming value to the PHI node in the loop for the preheader
243       // edge.
244       PN->addIncoming(InVal, NewBB);
245
246       // Can we eliminate this phi node now?
247       if (Value *V = hasConstantValue(PN)) {
248         PN->replaceAllUsesWith(V);
249         BB->getInstList().erase(PN);
250       }
251     }
252     
253     // Now that the PHI nodes are updated, actually move the edges from
254     // Preds to point to NewBB instead of BB.
255     //
256     for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
257       TerminatorInst *TI = Preds[i]->getTerminator();
258       for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
259         if (TI->getSuccessor(s) == BB)
260           TI->setSuccessor(s, NewBB);
261     }
262     
263   } else {                       // Otherwise the loop is dead...
264     for (BasicBlock::iterator I = BB->begin();
265          PHINode *PN = dyn_cast<PHINode>(I); ++I)
266       // Insert dummy values as the incoming value...
267       PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
268   }  
269   return NewBB;
270 }
271
272 // ChangeExitBlock - This recursive function is used to change any exit blocks
273 // that use OldExit to use NewExit instead.  This is recursive because children
274 // may need to be processed as well.
275 //
276 static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
277   if (L->hasExitBlock(OldExit)) {
278     L->changeExitBlock(OldExit, NewExit);
279     for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
280       ChangeExitBlock(*I, OldExit, NewExit);
281   }
282 }
283
284
285 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
286 /// preheader, this method is called to insert one.  This method has two phases:
287 /// preheader insertion and analysis updating.
288 ///
289 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
290   BasicBlock *Header = L->getHeader();
291
292   // Compute the set of predecessors of the loop that are not in the loop.
293   std::vector<BasicBlock*> OutsideBlocks;
294   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
295        PI != PE; ++PI)
296       if (!L->contains(*PI))           // Coming in from outside the loop?
297         OutsideBlocks.push_back(*PI);  // Keep track of it...
298   
299   // Split out the loop pre-header
300   BasicBlock *NewBB =
301     SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
302   
303   //===--------------------------------------------------------------------===//
304   //  Update analysis results now that we have performed the transformation
305   //
306   
307   // We know that we have loop information to update... update it now.
308   if (Loop *Parent = L->getParentLoop())
309     Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
310
311   // If the header for the loop used to be an exit node for another loop, then
312   // we need to update this to know that the loop-preheader is now the exit
313   // node.  Note that the only loop that could have our header as an exit node
314   // is a sibling loop, ie, one with the same parent loop, or one if it's
315   // children.
316   //
317   LoopInfo::iterator ParentLoops, ParentLoopsE;
318   if (Loop *Parent = L->getParentLoop()) {
319     ParentLoops = Parent->begin();
320     ParentLoopsE = Parent->end();
321   } else {      // Must check top-level loops...
322     ParentLoops = getAnalysis<LoopInfo>().begin();
323     ParentLoopsE = getAnalysis<LoopInfo>().end();
324   }
325
326   // Loop over all sibling loops, performing the substitution (recursively to
327   // include child loops)...
328   for (; ParentLoops != ParentLoopsE; ++ParentLoops)
329     ChangeExitBlock(*ParentLoops, Header, NewBB);
330   
331   DominatorSet &DS = getAnalysis<DominatorSet>();  // Update dominator info
332   DominatorTree &DT = getAnalysis<DominatorTree>();
333     
334
335   // Update the dominator tree information.
336   // The immediate dominator of the preheader is the immediate dominator of
337   // the old header.
338   DominatorTree::Node *PHDomTreeNode =
339     DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
340
341   // Change the header node so that PNHode is the new immediate dominator
342   DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
343
344   {
345     // The blocks that dominate NewBB are the blocks that dominate Header,
346     // minus Header, plus NewBB.
347     DominatorSet::DomSetType DomSet = DS.getDominators(Header);
348     DomSet.erase(Header);  // Header does not dominate us...
349     DS.addBasicBlock(NewBB, DomSet);
350
351     // The newly created basic block dominates all nodes dominated by Header.
352     for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
353            E = df_end(PHDomTreeNode); DFI != E; ++DFI)
354       DS.addDominator((*DFI)->getBlock(), NewBB);
355   }
356   
357   // Update immediate dominator information if we have it...
358   if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
359     // Whatever i-dominated the header node now immediately dominates NewBB
360     ID->addNewBlock(NewBB, ID->get(Header));
361     
362     // The preheader now is the immediate dominator for the header node...
363     ID->setImmediateDominator(Header, NewBB);
364   }
365   
366   // Update dominance frontier information...
367   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
368     // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
369     // everything that Header does, and it strictly dominates Header in
370     // addition.
371     assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
372     DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
373     NewDFSet.erase(Header);
374     DF->addBasicBlock(NewBB, NewDFSet);
375
376     // Now we must loop over all of the dominance frontiers in the function,
377     // replacing occurrences of Header with NewBB in some cases.  If a block
378     // dominates a (now) predecessor of NewBB, but did not strictly dominate
379     // Header, it will have Header in it's DF set, but should now have NewBB in
380     // its set.
381     for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
382       // Get all of the dominators of the predecessor...
383       const DominatorSet::DomSetType &PredDoms =
384         DS.getDominators(OutsideBlocks[i]);
385       for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
386              PDE = PredDoms.end(); PDI != PDE; ++PDI) {
387         BasicBlock *PredDom = *PDI;
388         // If the loop header is in DF(PredDom), then PredDom didn't dominate
389         // the header but did dominate a predecessor outside of the loop.  Now
390         // we change this entry to include the preheader in the DF instead of
391         // the header.
392         DominanceFrontier::iterator DFI = DF->find(PredDom);
393         assert(DFI != DF->end() && "No dominance frontier for node?");
394         if (DFI->second.count(Header)) {
395           DF->removeFromFrontier(DFI, Header);
396           DF->addToFrontier(DFI, NewBB);
397         }
398       }
399     }
400   }
401 }
402
403 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
404 /// blocks.  This method is used to split exit blocks that have predecessors
405 /// outside of the loop.
406 void LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
407   DominatorSet &DS = getAnalysis<DominatorSet>();
408   assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
409          != L->getExitBlocks().end() && "Not a current exit block!");
410   
411   std::vector<BasicBlock*> LoopBlocks;
412   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
413     if (L->contains(*I))
414       LoopBlocks.push_back(*I);
415
416   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
417   BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
418
419   // Update Loop Information - we know that the new block will be in the parent
420   // loop of L.
421   if (Loop *Parent = L->getParentLoop())
422     Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
423
424   // Replace any instances of Exit with NewBB in this and any nested loops...
425   for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
426     if (I->hasExitBlock(Exit))
427       I->changeExitBlock(Exit, NewBB);   // Update exit block information
428
429   // Update dominator information (set, immdom, domtree, and domfrontier)
430   UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
431 }
432
433 /// AddBlockAndPredsToSet - Add the specified block, and all of its
434 /// predecessors, to the specified set, if it's not already in there.  Stop
435 /// predecessor traversal when we reach StopBlock.
436 static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
437                                   std::set<BasicBlock*> &Blocks) {
438   if (!Blocks.insert(BB).second) return;  // already processed.
439   if (BB == StopBlock) return;  // Stop here!
440
441   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
442     AddBlockAndPredsToSet(*I, StopBlock, Blocks);
443 }
444
445 static void ReplaceExitBlocksOfLoopAndParents(Loop *L, BasicBlock *Old,
446                                               BasicBlock *New) {
447   if (!L->hasExitBlock(Old)) return;
448   L->changeExitBlock(Old, New);
449   ReplaceExitBlocksOfLoopAndParents(L->getParentLoop(), Old, New);
450 }
451
452 /// VerifyExitBlocks - This is a function which can be useful for hacking on the
453 /// LoopSimplify Code.
454 static void VerifyExitBlocks(Loop *L) {
455   std::vector<BasicBlock*> ExitBlocks;
456   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
457     BasicBlock *BB = L->getBlocks()[i];
458     for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
459       if (!L->contains(*SI))
460         ExitBlocks.push_back(*SI);
461   }
462   
463   std::vector<BasicBlock*> EB = L->getExitBlocks();
464   std::sort(EB.begin(), EB.end());
465   std::sort(ExitBlocks.begin(), ExitBlocks.end());
466   assert(EB == ExitBlocks && "Exit blocks were incorrectly updated!");
467
468   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
469     VerifyExitBlocks(*I);
470 }
471
472 /// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
473 /// PHI node that tells us how to partition the loops.
474 static PHINode *FindPHIToPartitionLoops(Loop *L) {
475   for (BasicBlock::iterator I = L->getHeader()->begin();
476        PHINode *PN = dyn_cast<PHINode>(I); ) {
477     ++I;
478     if (Value *V = hasConstantValue(PN)) {
479       // This is a degenerate PHI already, don't modify it!
480       PN->replaceAllUsesWith(V);
481       PN->getParent()->getInstList().erase(PN);
482     } else {
483       // Scan this PHI node looking for a use of the PHI node by itself.
484       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
485         if (PN->getIncomingValue(i) == PN &&
486             L->contains(PN->getIncomingBlock(i)))
487           // We found something tasty to remove.
488           return PN;
489     }
490   }
491   return 0;
492 }
493
494 /// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
495 /// them out into a nested loop.  This is important for code that looks like
496 /// this:
497 ///
498 ///  Loop:
499 ///     ...
500 ///     br cond, Loop, Next
501 ///     ...
502 ///     br cond2, Loop, Out
503 ///
504 /// To identify this common case, we look at the PHI nodes in the header of the
505 /// loop.  PHI nodes with unchanging values on one backedge correspond to values
506 /// that change in the "outer" loop, but not in the "inner" loop.
507 ///
508 /// If we are able to separate out a loop, return the new outer loop that was
509 /// created.
510 ///
511 Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
512   PHINode *PN = FindPHIToPartitionLoops(L);
513   if (PN == 0) return 0;  // No known way to partition.
514
515   // Pull out all predecessors that have varying values in the loop.  This
516   // handles the case when a PHI node has multiple instances of itself as
517   // arguments.
518   std::vector<BasicBlock*> OuterLoopPreds;
519   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
520     if (PN->getIncomingValue(i) != PN ||
521         !L->contains(PN->getIncomingBlock(i)))
522       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
523
524   BasicBlock *Header = L->getHeader();
525   BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
526
527   // Update dominator information (set, immdom, domtree, and domfrontier)
528   UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
529
530   // Create the new outer loop.
531   Loop *NewOuter = new Loop();
532
533   LoopInfo &LI = getAnalysis<LoopInfo>();
534
535   // Change the parent loop to use the outer loop as its child now.
536   if (Loop *Parent = L->getParentLoop())
537     Parent->replaceChildLoopWith(L, NewOuter);
538   else
539     LI.changeTopLevelLoop(L, NewOuter);
540
541   // This block is going to be our new header block: add it to this loop and all
542   // parent loops.
543   NewOuter->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
544
545   // L is now a subloop of our outer loop.
546   NewOuter->addChildLoop(L);
547
548   // Add all of L's exit blocks to the outer loop.
549   for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
550     NewOuter->addExitBlock(L->getExitBlocks()[i]);
551
552   // Add temporary exit block entries for NewBB.  Add one for each edge in L
553   // that goes to NewBB.
554   for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); PI != E; ++PI)
555     if (L->contains(*PI))
556       L->addExitBlock(NewBB);
557
558   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
559     NewOuter->addBlockEntry(L->getBlocks()[i]);
560
561   // Determine which blocks should stay in L and which should be moved out to
562   // the Outer loop now.
563   DominatorSet &DS = getAnalysis<DominatorSet>();
564   std::set<BasicBlock*> BlocksInL;
565   for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
566     if (DS.dominates(Header, *PI))
567       AddBlockAndPredsToSet(*PI, Header, BlocksInL);
568
569
570   // Scan all of the loop children of L, moving them to OuterLoop if they are
571   // not part of the inner loop.
572   for (Loop::iterator I = L->begin(); I != L->end(); )
573     if (BlocksInL.count((*I)->getHeader()))
574       ++I;   // Loop remains in L
575     else
576       NewOuter->addChildLoop(L->removeChildLoop(I));
577
578   // Now that we know which blocks are in L and which need to be moved to
579   // OuterLoop, move any blocks that need it.
580   for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
581     BasicBlock *BB = L->getBlocks()[i];
582     if (!BlocksInL.count(BB)) {
583       // Move this block to the parent, updating the exit blocks sets
584       L->removeBlockFromLoop(BB);
585       if (LI[BB] == L)
586         LI.changeLoopFor(BB, NewOuter);
587       --i;
588     }
589   }
590
591   // Check all subloops of this loop, replacing any exit blocks that got
592   // revectored with the new basic block.
593   for (pred_iterator I = pred_begin(NewBB), E = pred_end(NewBB); I != E; ++I)
594     if (NewOuter->contains(*I)) {
595       // Change any exit blocks that used to go to Header to go to NewBB
596       // instead.
597       ReplaceExitBlocksOfLoopAndParents((Loop*)LI[*I], Header, NewBB);
598     }
599
600   //VerifyExitBlocks(NewOuter);
601   return NewOuter;
602 }
603
604
605
606 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
607 /// has more than one backedge in it.  If this occurs, revector all of these
608 /// backedges to target a new basic block and have that block branch to the loop
609 /// header.  This ensures that loops have exactly one backedge.
610 ///
611 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
612   assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
613
614   // Get information about the loop
615   BasicBlock *Preheader = L->getLoopPreheader();
616   BasicBlock *Header = L->getHeader();
617   Function *F = Header->getParent();
618
619   // Figure out which basic blocks contain back-edges to the loop header.
620   std::vector<BasicBlock*> BackedgeBlocks;
621   for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
622     if (*I != Preheader) BackedgeBlocks.push_back(*I);
623
624   // Create and insert the new backedge block...
625   BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
626   BranchInst *BETerminator = new BranchInst(Header, BEBlock);
627
628   // Move the new backedge block to right after the last backedge block.
629   Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
630   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
631   
632   // Now that the block has been inserted into the function, create PHI nodes in
633   // the backedge block which correspond to any PHI nodes in the header block.
634   for (BasicBlock::iterator I = Header->begin();
635        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
636     PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
637                                  BETerminator);
638     NewPN->op_reserve(2*BackedgeBlocks.size());
639
640     // Loop over the PHI node, moving all entries except the one for the
641     // preheader over to the new PHI node.
642     unsigned PreheaderIdx = ~0U;
643     bool HasUniqueIncomingValue = true;
644     Value *UniqueValue = 0;
645     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
646       BasicBlock *IBB = PN->getIncomingBlock(i);
647       Value *IV = PN->getIncomingValue(i);
648       if (IBB == Preheader) {
649         PreheaderIdx = i;
650       } else {
651         NewPN->addIncoming(IV, IBB);
652         if (HasUniqueIncomingValue) {
653           if (UniqueValue == 0)
654             UniqueValue = IV;
655           else if (UniqueValue != IV)
656             HasUniqueIncomingValue = false;
657         }
658       }
659     }
660       
661     // Delete all of the incoming values from the old PN except the preheader's
662     assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
663     if (PreheaderIdx != 0) {
664       PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
665       PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
666     }
667     PN->op_erase(PN->op_begin()+2, PN->op_end());
668
669     // Finally, add the newly constructed PHI node as the entry for the BEBlock.
670     PN->addIncoming(NewPN, BEBlock);
671
672     // As an optimization, if all incoming values in the new PhiNode (which is a
673     // subset of the incoming values of the old PHI node) have the same value,
674     // eliminate the PHI Node.
675     if (HasUniqueIncomingValue) {
676       NewPN->replaceAllUsesWith(UniqueValue);
677       BEBlock->getInstList().erase(NewPN);
678     }
679   }
680
681   // Now that all of the PHI nodes have been inserted and adjusted, modify the
682   // backedge blocks to just to the BEBlock instead of the header.
683   for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
684     TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
685     for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
686       if (TI->getSuccessor(Op) == Header)
687         TI->setSuccessor(Op, BEBlock);
688   }
689
690   //===--- Update all analyses which we must preserve now -----------------===//
691
692   // Update Loop Information - we know that this block is now in the current
693   // loop and all parent loops.
694   L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
695
696   // Replace any instances of Exit with NewBB in this and any nested loops...
697   for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
698     if (I->hasExitBlock(Header))
699       I->changeExitBlock(Header, BEBlock);   // Update exit block information
700
701   // Update dominator information (set, immdom, domtree, and domfrontier)
702   UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
703 }
704
705 /// UpdateDomInfoForRevectoredPreds - This method is used to update the four
706 /// different kinds of dominator information (dominator sets, immediate
707 /// dominators, dominator trees, and dominance frontiers) after a new block has
708 /// been added to the CFG.
709 ///
710 /// This only supports the case when an existing block (known as "NewBBSucc"),
711 /// had some of its predecessors factored into a new basic block.  This
712 /// transformation inserts a new basic block ("NewBB"), with a single
713 /// unconditional branch to NewBBSucc, and moves some predecessors of
714 /// "NewBBSucc" to now branch to NewBB.  These predecessors are listed in
715 /// PredBlocks, even though they are the same as
716 /// pred_begin(NewBB)/pred_end(NewBB).
717 ///
718 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
719                                          std::vector<BasicBlock*> &PredBlocks) {
720   assert(!PredBlocks.empty() && "No predblocks??");
721   assert(succ_begin(NewBB) != succ_end(NewBB) &&
722          ++succ_begin(NewBB) == succ_end(NewBB) &&
723          "NewBB should have a single successor!");
724   BasicBlock *NewBBSucc = *succ_begin(NewBB);
725   DominatorSet &DS = getAnalysis<DominatorSet>();
726
727   // Update dominator information...  The blocks that dominate NewBB are the
728   // intersection of the dominators of predecessors, plus the block itself.
729   //
730   DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
731   for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
732     set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
733   NewBBDomSet.insert(NewBB);  // All blocks dominate themselves...
734   DS.addBasicBlock(NewBB, NewBBDomSet);
735
736   // The newly inserted basic block will dominate existing basic blocks iff the
737   // PredBlocks dominate all of the non-pred blocks.  If all predblocks dominate
738   // the non-pred blocks, then they all must be the same block!
739   //
740   bool NewBBDominatesNewBBSucc = true;
741   {
742     BasicBlock *OnePred = PredBlocks[0];
743     for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
744       if (PredBlocks[i] != OnePred) {
745         NewBBDominatesNewBBSucc = false;
746         break;
747       }
748
749     if (NewBBDominatesNewBBSucc)
750       for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
751            PI != E; ++PI)
752         if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
753           NewBBDominatesNewBBSucc = false;
754           break;
755         }
756   }
757
758   // The other scenario where the new block can dominate its successors are when
759   // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
760   // already.
761   if (!NewBBDominatesNewBBSucc) {
762     NewBBDominatesNewBBSucc = true;
763     for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
764          PI != E; ++PI)
765       if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
766         NewBBDominatesNewBBSucc = false;
767         break;
768       }
769   }
770
771   // If NewBB dominates some blocks, then it will dominate all blocks that
772   // NewBBSucc does.
773   if (NewBBDominatesNewBBSucc) {
774     BasicBlock *PredBlock = PredBlocks[0];
775     Function *F = NewBB->getParent();
776     for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
777       if (DS.dominates(NewBBSucc, I))
778         DS.addDominator(I, NewBB);
779   }
780
781   // Update immediate dominator information if we have it...
782   BasicBlock *NewBBIDom = 0;
783   if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
784     // To find the immediate dominator of the new exit node, we trace up the
785     // immediate dominators of a predecessor until we find a basic block that
786     // dominates the exit block.
787     //
788     BasicBlock *Dom = PredBlocks[0];  // Some random predecessor...
789     while (!NewBBDomSet.count(Dom)) {  // Loop until we find a dominator...
790       assert(Dom != 0 && "No shared dominator found???");
791       Dom = ID->get(Dom);
792     }
793
794     // Set the immediate dominator now...
795     ID->addNewBlock(NewBB, Dom);
796     NewBBIDom = Dom;   // Reuse this if calculating DominatorTree info...
797
798     // If NewBB strictly dominates other blocks, we need to update their idom's
799     // now.  The only block that need adjustment is the NewBBSucc block, whose
800     // idom should currently be set to PredBlocks[0].
801     if (NewBBDominatesNewBBSucc)
802       ID->setImmediateDominator(NewBBSucc, NewBB);
803   }
804
805   // Update DominatorTree information if it is active.
806   if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
807     // If we don't have ImmediateDominator info around, calculate the idom as
808     // above.
809     DominatorTree::Node *NewBBIDomNode;
810     if (NewBBIDom) {
811       NewBBIDomNode = DT->getNode(NewBBIDom);
812     } else {
813       NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
814       while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
815         NewBBIDomNode = NewBBIDomNode->getIDom();
816         assert(NewBBIDomNode && "No shared dominator found??");
817       }
818     }
819
820     // Create the new dominator tree node... and set the idom of NewBB.
821     DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
822
823     // If NewBB strictly dominates other blocks, then it is now the immediate
824     // dominator of NewBBSucc.  Update the dominator tree as appropriate.
825     if (NewBBDominatesNewBBSucc) {
826       DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
827       DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
828     }
829   }
830
831   // Update dominance frontier information...
832   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
833     // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
834     // DF(PredBlocks[0]) without the stuff that the new block does not dominate
835     // a predecessor of.
836     if (NewBBDominatesNewBBSucc) {
837       DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
838       if (DFI != DF->end()) {
839         DominanceFrontier::DomSetType Set = DFI->second;
840         // Filter out stuff in Set that we do not dominate a predecessor of.
841         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
842                E = Set.end(); SetI != E;) {
843           bool DominatesPred = false;
844           for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
845                PI != E; ++PI)
846             if (DS.dominates(NewBB, *PI))
847               DominatesPred = true;
848           if (!DominatesPred)
849             Set.erase(SetI++);
850           else
851             ++SetI;
852         }
853
854         DF->addBasicBlock(NewBB, Set);
855       }
856
857     } else {
858       // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
859       // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
860       // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
861       DominanceFrontier::DomSetType NewDFSet;
862       NewDFSet.insert(NewBBSucc);
863       DF->addBasicBlock(NewBB, NewDFSet);
864     }
865
866     // Now we must loop over all of the dominance frontiers in the function,
867     // replacing occurrences of NewBBSucc with NewBB in some cases.  All
868     // blocks that dominate a block in PredBlocks and contained NewBBSucc in
869     // their dominance frontier must be updated to contain NewBB instead.
870     //
871     for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
872       BasicBlock *Pred = PredBlocks[i];
873       // Get all of the dominators of the predecessor...
874       const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
875       for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
876              PDE = PredDoms.end(); PDI != PDE; ++PDI) {
877         BasicBlock *PredDom = *PDI;
878         
879         // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
880         // dominate NewBBSucc but did dominate a predecessor of it.  Now we
881         // change this entry to include NewBB in the DF instead of NewBBSucc.
882         DominanceFrontier::iterator DFI = DF->find(PredDom);
883         assert(DFI != DF->end() && "No dominance frontier for node?");
884         if (DFI->second.count(NewBBSucc)) {
885           // If NewBBSucc should not stay in our dominator frontier, remove it.
886           // We remove it unless there is a predecessor of NewBBSucc that we
887           // dominate, but we don't strictly dominate NewBBSucc.
888           bool ShouldRemove = true;
889           if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
890             // Okay, we know that PredDom does not strictly dominate NewBBSucc.
891             // Check to see if it dominates any predecessors of NewBBSucc.
892             for (pred_iterator PI = pred_begin(NewBBSucc),
893                    E = pred_end(NewBBSucc); PI != E; ++PI)
894               if (DS.dominates(PredDom, *PI)) {
895                 ShouldRemove = false;
896                 break;
897               }
898           }
899             
900           if (ShouldRemove)
901             DF->removeFromFrontier(DFI, NewBBSucc);
902           DF->addToFrontier(DFI, NewBB);
903         }
904       }
905     }
906   }
907 }
908