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