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