Partial fix for PR1678: correct some parts of constant
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
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 file implements simple dominator construction algorithms for finding
11 // forward dominators.  Postdominators are available in libanalysis, but are not
12 // included in libvmcore, because it's not needed.  Forward dominators are
13 // needed to support the Verifier pass.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Support/Streams.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 namespace llvm {
30 static std::ostream &operator<<(std::ostream &o,
31                                 const std::set<BasicBlock*> &BBs) {
32   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
33        I != E; ++I)
34     if (*I)
35       WriteAsOperand(o, *I, false);
36     else
37       o << " <<exit node>>";
38   return o;
39 }
40 }
41
42 //===----------------------------------------------------------------------===//
43 //  DominatorTree Implementation
44 //===----------------------------------------------------------------------===//
45 //
46 // DominatorTree construction - This pass constructs immediate dominator
47 // information for a flow-graph based on the algorithm described in this
48 // document:
49 //
50 //   A Fast Algorithm for Finding Dominators in a Flowgraph
51 //   T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
52 //
53 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
54 // LINK, but it turns out that the theoretically slower O(n*log(n))
55 // implementation is actually faster than the "efficient" algorithm (even for
56 // large CFGs) because the constant overheads are substantially smaller.  The
57 // lower-complexity version can be enabled with the following #define:
58 //
59 #define BALANCE_IDOM_TREE 0
60 //
61 //===----------------------------------------------------------------------===//
62
63 char DominatorTree::ID = 0;
64 static RegisterPass<DominatorTree>
65 E("domtree", "Dominator Tree Construction", true);
66
67 // NewBB is split and now it has one successor. Update dominator tree to
68 // reflect this change.
69 void DominatorTree::splitBlock(BasicBlock *NewBB) {
70   assert(NewBB->getTerminator()->getNumSuccessors() == 1
71          && "NewBB should have a single successor!");
72   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
73
74   std::vector<BasicBlock*> PredBlocks;
75   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
76        PI != PE; ++PI)
77       PredBlocks.push_back(*PI);  
78
79   assert(!PredBlocks.empty() && "No predblocks??");
80
81   // The newly inserted basic block will dominate existing basic blocks iff the
82   // PredBlocks dominate all of the non-pred blocks.  If all predblocks dominate
83   // the non-pred blocks, then they all must be the same block!
84   //
85   bool NewBBDominatesNewBBSucc = true;
86   {
87     BasicBlock *OnePred = PredBlocks[0];
88     unsigned i = 1, e = PredBlocks.size();
89     for (i = 1; !isReachableFromEntry(OnePred); ++i) {
90       assert(i != e && "Didn't find reachable pred?");
91       OnePred = PredBlocks[i];
92     }
93     
94     for (; i != e; ++i)
95       if (PredBlocks[i] != OnePred && isReachableFromEntry(OnePred)) {
96         NewBBDominatesNewBBSucc = false;
97         break;
98       }
99
100     if (NewBBDominatesNewBBSucc)
101       for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
102            PI != E; ++PI)
103         if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
104           NewBBDominatesNewBBSucc = false;
105           break;
106         }
107   }
108
109   // The other scenario where the new block can dominate its successors are when
110   // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
111   // already.
112   if (!NewBBDominatesNewBBSucc) {
113     NewBBDominatesNewBBSucc = true;
114     for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
115          PI != E; ++PI)
116       if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
117         NewBBDominatesNewBBSucc = false;
118         break;
119       }
120   }
121
122   // Find NewBB's immediate dominator and create new dominator tree node for
123   // NewBB.
124   BasicBlock *NewBBIDom = 0;
125   unsigned i = 0;
126   for (i = 0; i < PredBlocks.size(); ++i)
127     if (isReachableFromEntry(PredBlocks[i])) {
128       NewBBIDom = PredBlocks[i];
129       break;
130     }
131   assert(i != PredBlocks.size() && "No reachable preds?");
132   for (i = i + 1; i < PredBlocks.size(); ++i) {
133     if (isReachableFromEntry(PredBlocks[i]))
134       NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
135   }
136   assert(NewBBIDom && "No immediate dominator found??");
137   
138   // Create the new dominator tree node... and set the idom of NewBB.
139   DomTreeNode *NewBBNode = addNewBlock(NewBB, NewBBIDom);
140   
141   // If NewBB strictly dominates other blocks, then it is now the immediate
142   // dominator of NewBBSucc.  Update the dominator tree as appropriate.
143   if (NewBBDominatesNewBBSucc) {
144     DomTreeNode *NewBBSuccNode = getNode(NewBBSucc);
145     changeImmediateDominator(NewBBSuccNode, NewBBNode);
146   }
147 }
148
149 unsigned DominatorTree::DFSPass(BasicBlock *V, unsigned N) {
150   // This is more understandable as a recursive algorithm, but we can't use the
151   // recursive algorithm due to stack depth issues.  Keep it here for
152   // documentation purposes.
153 #if 0
154   InfoRec &VInfo = Info[Roots[i]];
155   VInfo.Semi = ++N;
156   VInfo.Label = V;
157
158   Vertex.push_back(V);        // Vertex[n] = V;
159   //Info[V].Ancestor = 0;     // Ancestor[n] = 0
160   //Info[V].Child = 0;        // Child[v] = 0
161   VInfo.Size = 1;             // Size[v] = 1
162
163   for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
164     InfoRec &SuccVInfo = Info[*SI];
165     if (SuccVInfo.Semi == 0) {
166       SuccVInfo.Parent = V;
167       N = DFSPass(*SI, N);
168     }
169   }
170 #else
171   std::vector<std::pair<BasicBlock*, unsigned> > Worklist;
172   Worklist.push_back(std::make_pair(V, 0U));
173   while (!Worklist.empty()) {
174     BasicBlock *BB = Worklist.back().first;
175     unsigned NextSucc = Worklist.back().second;
176     
177     // First time we visited this BB?
178     if (NextSucc == 0) {
179       InfoRec &BBInfo = Info[BB];
180       BBInfo.Semi = ++N;
181       BBInfo.Label = BB;
182       
183       Vertex.push_back(BB);       // Vertex[n] = V;
184       //BBInfo[V].Ancestor = 0;   // Ancestor[n] = 0
185       //BBInfo[V].Child = 0;      // Child[v] = 0
186       BBInfo.Size = 1;            // Size[v] = 1
187     }
188     
189     // If we are done with this block, remove it from the worklist.
190     if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
191       Worklist.pop_back();
192       continue;
193     }
194     
195     // Otherwise, increment the successor number for the next time we get to it.
196     ++Worklist.back().second;
197     
198     // Visit the successor next, if it isn't already visited.
199     BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
200     
201     InfoRec &SuccVInfo = Info[Succ];
202     if (SuccVInfo.Semi == 0) {
203       SuccVInfo.Parent = BB;
204       Worklist.push_back(std::make_pair(Succ, 0U));
205     }
206   }
207 #endif
208   return N;
209 }
210
211 void DominatorTree::Compress(BasicBlock *VIn) {
212
213   std::vector<BasicBlock *> Work;
214   SmallPtrSet<BasicBlock *, 32> Visited;
215   BasicBlock *VInAncestor = Info[VIn].Ancestor;
216   InfoRec &VInVAInfo = Info[VInAncestor];
217
218   if (VInVAInfo.Ancestor != 0)
219     Work.push_back(VIn);
220   
221   while (!Work.empty()) {
222     BasicBlock *V = Work.back();
223     InfoRec &VInfo = Info[V];
224     BasicBlock *VAncestor = VInfo.Ancestor;
225     InfoRec &VAInfo = Info[VAncestor];
226
227     // Process Ancestor first
228     if (Visited.insert(VAncestor) &&
229         VAInfo.Ancestor != 0) {
230       Work.push_back(VAncestor);
231       continue;
232     } 
233     Work.pop_back(); 
234
235     // Update VInfo based on Ancestor info
236     if (VAInfo.Ancestor == 0)
237       continue;
238     BasicBlock *VAncestorLabel = VAInfo.Label;
239     BasicBlock *VLabel = VInfo.Label;
240     if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
241       VInfo.Label = VAncestorLabel;
242     VInfo.Ancestor = VAInfo.Ancestor;
243   }
244 }
245
246 BasicBlock *DominatorTree::Eval(BasicBlock *V) {
247   InfoRec &VInfo = Info[V];
248 #if !BALANCE_IDOM_TREE
249   // Higher-complexity but faster implementation
250   if (VInfo.Ancestor == 0)
251     return V;
252   Compress(V);
253   return VInfo.Label;
254 #else
255   // Lower-complexity but slower implementation
256   if (VInfo.Ancestor == 0)
257     return VInfo.Label;
258   Compress(V);
259   BasicBlock *VLabel = VInfo.Label;
260
261   BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
262   if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
263     return VLabel;
264   else
265     return VAncestorLabel;
266 #endif
267 }
268
269 void DominatorTree::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
270 #if !BALANCE_IDOM_TREE
271   // Higher-complexity but faster implementation
272   WInfo.Ancestor = V;
273 #else
274   // Lower-complexity but slower implementation
275   BasicBlock *WLabel = WInfo.Label;
276   unsigned WLabelSemi = Info[WLabel].Semi;
277   BasicBlock *S = W;
278   InfoRec *SInfo = &Info[S];
279
280   BasicBlock *SChild = SInfo->Child;
281   InfoRec *SChildInfo = &Info[SChild];
282
283   while (WLabelSemi < Info[SChildInfo->Label].Semi) {
284     BasicBlock *SChildChild = SChildInfo->Child;
285     if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
286       SChildInfo->Ancestor = S;
287       SInfo->Child = SChild = SChildChild;
288       SChildInfo = &Info[SChild];
289     } else {
290       SChildInfo->Size = SInfo->Size;
291       S = SInfo->Ancestor = SChild;
292       SInfo = SChildInfo;
293       SChild = SChildChild;
294       SChildInfo = &Info[SChild];
295     }
296   }
297
298   InfoRec &VInfo = Info[V];
299   SInfo->Label = WLabel;
300
301   assert(V != W && "The optimization here will not work in this case!");
302   unsigned WSize = WInfo.Size;
303   unsigned VSize = (VInfo.Size += WSize);
304
305   if (VSize < 2*WSize)
306     std::swap(S, VInfo.Child);
307
308   while (S) {
309     SInfo = &Info[S];
310     SInfo->Ancestor = V;
311     S = SInfo->Child;
312   }
313 #endif
314 }
315
316 void DominatorTree::calculate(Function &F) {
317   BasicBlock* Root = Roots[0];
318
319   // Add a node for the root...
320   DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0);
321
322   Vertex.push_back(0);
323
324   // Step #1: Number blocks in depth-first order and initialize variables used
325   // in later stages of the algorithm.
326   unsigned N = DFSPass(Root, 0);
327
328   for (unsigned i = N; i >= 2; --i) {
329     BasicBlock *W = Vertex[i];
330     InfoRec &WInfo = Info[W];
331
332     // Step #2: Calculate the semidominators of all vertices
333     for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
334       if (Info.count(*PI)) {  // Only if this predecessor is reachable!
335         unsigned SemiU = Info[Eval(*PI)].Semi;
336         if (SemiU < WInfo.Semi)
337           WInfo.Semi = SemiU;
338       }
339
340     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
341
342     BasicBlock *WParent = WInfo.Parent;
343     Link(WParent, W, WInfo);
344
345     // Step #3: Implicitly define the immediate dominator of vertices
346     std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
347     while (!WParentBucket.empty()) {
348       BasicBlock *V = WParentBucket.back();
349       WParentBucket.pop_back();
350       BasicBlock *U = Eval(V);
351       IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
352     }
353   }
354
355   // Step #4: Explicitly define the immediate dominator of each vertex
356   for (unsigned i = 2; i <= N; ++i) {
357     BasicBlock *W = Vertex[i];
358     BasicBlock *&WIDom = IDoms[W];
359     if (WIDom != Vertex[Info[W].Semi])
360       WIDom = IDoms[WIDom];
361   }
362
363   // Loop over all of the reachable blocks in the function...
364   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
365     if (BasicBlock *ImmDom = getIDom(I)) {  // Reachable block.
366       DomTreeNode *BBNode = DomTreeNodes[I];
367       if (BBNode) continue;  // Haven't calculated this node yet?
368
369       // Get or calculate the node for the immediate dominator
370       DomTreeNode *IDomNode = getNodeForBlock(ImmDom);
371
372       // Add a new tree node for this BasicBlock, and link it as a child of
373       // IDomNode
374       DomTreeNode *C = new DomTreeNode(I, IDomNode);
375       DomTreeNodes[I] = IDomNode->addChild(C);
376     }
377
378   // Free temporary memory used to construct idom's
379   Info.clear();
380   IDoms.clear();
381   std::vector<BasicBlock*>().swap(Vertex);
382
383   updateDFSNumbers();
384 }
385
386 void DominatorTreeBase::updateDFSNumbers() {
387   unsigned DFSNum = 0;
388
389   SmallVector<std::pair<DomTreeNode*, DomTreeNode::iterator>, 32> WorkStack;
390   
391   for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
392     DomTreeNode *ThisRoot = getNode(Roots[i]);
393     WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
394     ThisRoot->DFSNumIn = DFSNum++;
395     
396     while (!WorkStack.empty()) {
397       DomTreeNode *Node = WorkStack.back().first;
398       DomTreeNode::iterator ChildIt = WorkStack.back().second;
399
400       // If we visited all of the children of this node, "recurse" back up the
401       // stack setting the DFOutNum.
402       if (ChildIt == Node->end()) {
403         Node->DFSNumOut = DFSNum++;
404         WorkStack.pop_back();
405       } else {
406         // Otherwise, recursively visit this child.
407         DomTreeNode *Child = *ChildIt;
408         ++WorkStack.back().second;
409         
410         WorkStack.push_back(std::make_pair(Child, Child->begin()));
411         Child->DFSNumIn = DFSNum++;
412       }
413     }
414   }
415   
416   SlowQueries = 0;
417   DFSInfoValid = true;
418 }
419
420 /// isReachableFromEntry - Return true if A is dominated by the entry
421 /// block of the function containing it.
422 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
423   assert (!isPostDominator() 
424           && "This is not implemented for post dominators");
425   return dominates(&A->getParent()->getEntryBlock(), A);
426 }
427
428 // dominates - Return true if A dominates B. THis performs the
429 // special checks necessary if A and B are in the same basic block.
430 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
431   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
432   if (BBA != BBB) return dominates(BBA, BBB);
433   
434   // It is not possible to determine dominance between two PHI nodes 
435   // based on their ordering.
436   if (isa<PHINode>(A) && isa<PHINode>(B)) 
437     return false;
438
439   // Loop through the basic block until we find A or B.
440   BasicBlock::iterator I = BBA->begin();
441   for (; &*I != A && &*I != B; ++I) /*empty*/;
442   
443   if(!IsPostDominators) {
444     // A dominates B if it is found first in the basic block.
445     return &*I == A;
446   } else {
447     // A post-dominates B if B is found first in the basic block.
448     return &*I == B;
449   }
450 }
451
452 // DominatorTreeBase::reset - Free all of the tree node memory.
453 //
454 void DominatorTreeBase::reset() {
455   for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), 
456          E = DomTreeNodes.end(); I != E; ++I)
457     delete I->second;
458   DomTreeNodes.clear();
459   IDoms.clear();
460   Roots.clear();
461   Vertex.clear();
462   RootNode = 0;
463 }
464
465 /// findNearestCommonDominator - Find nearest common dominator basic block
466 /// for basic block A and B. If there is no such block then return NULL.
467 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A, 
468                                                           BasicBlock *B) {
469
470   assert (!isPostDominator() 
471           && "This is not implemented for post dominators");
472   assert (A->getParent() == B->getParent() 
473           && "Two blocks are not in same function");
474
475   // If either A or B is a entry block then it is nearest common dominator.
476   BasicBlock &Entry  = A->getParent()->getEntryBlock();
477   if (A == &Entry || B == &Entry)
478     return &Entry;
479
480   // If B dominates A then B is nearest common dominator.
481   if (dominates(B, A))
482     return B;
483
484   // If A dominates B then A is nearest common dominator.
485   if (dominates(A, B))
486     return A;
487
488   DomTreeNode *NodeA = getNode(A);
489   DomTreeNode *NodeB = getNode(B);
490
491   // Collect NodeA dominators set.
492   SmallPtrSet<DomTreeNode*, 16> NodeADoms;
493   NodeADoms.insert(NodeA);
494   DomTreeNode *IDomA = NodeA->getIDom();
495   while (IDomA) {
496     NodeADoms.insert(IDomA);
497     IDomA = IDomA->getIDom();
498   }
499
500   // Walk NodeB immediate dominators chain and find common dominator node.
501   DomTreeNode *IDomB = NodeB->getIDom();
502   while(IDomB) {
503     if (NodeADoms.count(IDomB) != 0)
504       return IDomB->getBlock();
505
506     IDomB = IDomB->getIDom();
507   }
508
509   return NULL;
510 }
511
512 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
513   assert(IDom && "No immediate dominator?");
514   if (IDom != NewIDom) {
515     std::vector<DomTreeNode*>::iterator I =
516       std::find(IDom->Children.begin(), IDom->Children.end(), this);
517     assert(I != IDom->Children.end() &&
518            "Not in immediate dominator children set!");
519     // I am no longer your child...
520     IDom->Children.erase(I);
521
522     // Switch to new dominator
523     IDom = NewIDom;
524     IDom->Children.push_back(this);
525   }
526 }
527
528 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
529   if (DomTreeNode *BBNode = DomTreeNodes[BB])
530     return BBNode;
531
532   // Haven't calculated this node yet?  Get or calculate the node for the
533   // immediate dominator.
534   BasicBlock *IDom = getIDom(BB);
535   DomTreeNode *IDomNode = getNodeForBlock(IDom);
536
537   // Add a new tree node for this BasicBlock, and link it as a child of
538   // IDomNode
539   DomTreeNode *C = new DomTreeNode(BB, IDomNode);
540   return DomTreeNodes[BB] = IDomNode->addChild(C);
541 }
542
543 static std::ostream &operator<<(std::ostream &o, const DomTreeNode *Node) {
544   if (Node->getBlock())
545     WriteAsOperand(o, Node->getBlock(), false);
546   else
547     o << " <<exit node>>";
548   
549   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
550   
551   return o << "\n";
552 }
553
554 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
555                          unsigned Lev) {
556   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
557   for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
558        I != E; ++I)
559     PrintDomTree(*I, o, Lev+1);
560 }
561
562 /// eraseNode - Removes a node from  the domiantor tree. Block must not
563 /// domiante any other blocks. Removes node from its immediate dominator's
564 /// children list. Deletes dominator node associated with basic block BB.
565 void DominatorTreeBase::eraseNode(BasicBlock *BB) {
566   DomTreeNode *Node = getNode(BB);
567   assert (Node && "Removing node that isn't in dominator tree.");
568   assert (Node->getChildren().empty() && "Node is not a leaf node.");
569
570     // Remove node from immediate dominator's children list.
571   DomTreeNode *IDom = Node->getIDom();
572   if (IDom) {
573     std::vector<DomTreeNode*>::iterator I =
574       std::find(IDom->Children.begin(), IDom->Children.end(), Node);
575     assert(I != IDom->Children.end() &&
576            "Not in immediate dominator children set!");
577     // I am no longer your child...
578     IDom->Children.erase(I);
579   }
580   
581   DomTreeNodes.erase(BB);
582   delete Node;
583 }
584
585 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
586   o << "=============================--------------------------------\n";
587   o << "Inorder Dominator Tree: ";
588   if (DFSInfoValid)
589     o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
590   o << "\n";
591   
592   PrintDomTree(getRootNode(), o, 1);
593 }
594
595 void DominatorTreeBase::dump() {
596   print(llvm::cerr);
597 }
598
599 bool DominatorTree::runOnFunction(Function &F) {
600   reset();     // Reset from the last time we were run...
601   Roots.push_back(&F.getEntryBlock());
602   calculate(F);
603   return false;
604 }
605
606 //===----------------------------------------------------------------------===//
607 //  DominanceFrontier Implementation
608 //===----------------------------------------------------------------------===//
609
610 char DominanceFrontier::ID = 0;
611 static RegisterPass<DominanceFrontier>
612 G("domfrontier", "Dominance Frontier Construction", true);
613
614 // NewBB is split and now it has one successor. Update dominace frontier to
615 // reflect this change.
616 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
617   assert(NewBB->getTerminator()->getNumSuccessors() == 1
618          && "NewBB should have a single successor!");
619   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
620
621   std::vector<BasicBlock*> PredBlocks;
622   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
623        PI != PE; ++PI)
624       PredBlocks.push_back(*PI);  
625
626   if (PredBlocks.empty())
627     // If NewBB does not have any predecessors then it is a entry block.
628     // In this case, NewBB and its successor NewBBSucc dominates all
629     // other blocks.
630     return;
631
632   // NewBBSucc inherits original NewBB frontier.
633   DominanceFrontier::iterator NewBBI = find(NewBB);
634   if (NewBBI != end()) {
635     DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
636     DominanceFrontier::DomSetType NewBBSuccSet;
637     NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
638     addBasicBlock(NewBBSucc, NewBBSuccSet);
639   }
640
641   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
642   // DF(PredBlocks[0]) without the stuff that the new block does not dominate
643   // a predecessor of.
644   DominatorTree &DT = getAnalysis<DominatorTree>();
645   if (DT.dominates(NewBB, NewBBSucc)) {
646     DominanceFrontier::iterator DFI = find(PredBlocks[0]);
647     if (DFI != end()) {
648       DominanceFrontier::DomSetType Set = DFI->second;
649       // Filter out stuff in Set that we do not dominate a predecessor of.
650       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
651              E = Set.end(); SetI != E;) {
652         bool DominatesPred = false;
653         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
654              PI != E; ++PI)
655           if (DT.dominates(NewBB, *PI))
656             DominatesPred = true;
657         if (!DominatesPred)
658           Set.erase(SetI++);
659         else
660           ++SetI;
661       }
662
663       if (NewBBI != end()) {
664         DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
665         NewBBSet.insert(Set.begin(), Set.end());
666       } else 
667         addBasicBlock(NewBB, Set);
668     }
669     
670   } else {
671     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
672     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
673     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
674     DominanceFrontier::DomSetType NewDFSet;
675     NewDFSet.insert(NewBBSucc);
676     addBasicBlock(NewBB, NewDFSet);
677   }
678   
679   // Now we must loop over all of the dominance frontiers in the function,
680   // replacing occurrences of NewBBSucc with NewBB in some cases.  All
681   // blocks that dominate a block in PredBlocks and contained NewBBSucc in
682   // their dominance frontier must be updated to contain NewBB instead.
683   //
684   for (Function::iterator FI = NewBB->getParent()->begin(),
685          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
686     DominanceFrontier::iterator DFI = find(FI);
687     if (DFI == end()) continue;  // unreachable block.
688     
689     // Only consider nodes that have NewBBSucc in their dominator frontier.
690     if (!DFI->second.count(NewBBSucc)) continue;
691
692     // Verify whether this block dominates a block in predblocks.  If not, do
693     // not update it.
694     bool BlockDominatesAny = false;
695     for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(), 
696            BE = PredBlocks.end(); BI != BE; ++BI) {
697       if (DT.dominates(FI, *BI)) {
698         BlockDominatesAny = true;
699         break;
700       }
701     }
702     
703     if (!BlockDominatesAny)
704       continue;
705     
706     // If NewBBSucc should not stay in our dominator frontier, remove it.
707     // We remove it unless there is a predecessor of NewBBSucc that we
708     // dominate, but we don't strictly dominate NewBBSucc.
709     bool ShouldRemove = true;
710     if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
711       // Okay, we know that PredDom does not strictly dominate NewBBSucc.
712       // Check to see if it dominates any predecessors of NewBBSucc.
713       for (pred_iterator PI = pred_begin(NewBBSucc),
714            E = pred_end(NewBBSucc); PI != E; ++PI)
715         if (DT.dominates(FI, *PI)) {
716           ShouldRemove = false;
717           break;
718         }
719     }
720     
721     if (ShouldRemove)
722       removeFromFrontier(DFI, NewBBSucc);
723     addToFrontier(DFI, NewBB);
724   }
725 }
726
727 namespace {
728   class DFCalculateWorkObject {
729   public:
730     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
731                           const DomTreeNode *N,
732                           const DomTreeNode *PN)
733     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
734     BasicBlock *currentBB;
735     BasicBlock *parentBB;
736     const DomTreeNode *Node;
737     const DomTreeNode *parentNode;
738   };
739 }
740
741 const DominanceFrontier::DomSetType &
742 DominanceFrontier::calculate(const DominatorTree &DT,
743                              const DomTreeNode *Node) {
744   BasicBlock *BB = Node->getBlock();
745   DomSetType *Result = NULL;
746
747   std::vector<DFCalculateWorkObject> workList;
748   SmallPtrSet<BasicBlock *, 32> visited;
749
750   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
751   do {
752     DFCalculateWorkObject *currentW = &workList.back();
753     assert (currentW && "Missing work object.");
754
755     BasicBlock *currentBB = currentW->currentBB;
756     BasicBlock *parentBB = currentW->parentBB;
757     const DomTreeNode *currentNode = currentW->Node;
758     const DomTreeNode *parentNode = currentW->parentNode;
759     assert (currentBB && "Invalid work object. Missing current Basic Block");
760     assert (currentNode && "Invalid work object. Missing current Node");
761     DomSetType &S = Frontiers[currentBB];
762
763     // Visit each block only once.
764     if (visited.count(currentBB) == 0) {
765       visited.insert(currentBB);
766
767       // Loop over CFG successors to calculate DFlocal[currentNode]
768       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
769            SI != SE; ++SI) {
770         // Does Node immediately dominate this successor?
771         if (DT[*SI]->getIDom() != currentNode)
772           S.insert(*SI);
773       }
774     }
775
776     // At this point, S is DFlocal.  Now we union in DFup's of our children...
777     // Loop through and visit the nodes that Node immediately dominates (Node's
778     // children in the IDomTree)
779     bool visitChild = false;
780     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
781            NE = currentNode->end(); NI != NE; ++NI) {
782       DomTreeNode *IDominee = *NI;
783       BasicBlock *childBB = IDominee->getBlock();
784       if (visited.count(childBB) == 0) {
785         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
786                                                  IDominee, currentNode));
787         visitChild = true;
788       }
789     }
790
791     // If all children are visited or there is any child then pop this block
792     // from the workList.
793     if (!visitChild) {
794
795       if (!parentBB) {
796         Result = &S;
797         break;
798       }
799
800       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
801       DomSetType &parentSet = Frontiers[parentBB];
802       for (; CDFI != CDFE; ++CDFI) {
803         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
804           parentSet.insert(*CDFI);
805       }
806       workList.pop_back();
807     }
808
809   } while (!workList.empty());
810
811   return *Result;
812 }
813
814 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
815   for (const_iterator I = begin(), E = end(); I != E; ++I) {
816     o << "  DomFrontier for BB";
817     if (I->first)
818       WriteAsOperand(o, I->first, false);
819     else
820       o << " <<exit node>>";
821     o << " is:\t" << I->second << "\n";
822   }
823 }
824
825 void DominanceFrontierBase::dump() {
826   print (llvm::cerr);
827 }