split dom frontier handling stuff out to its own DominanceFrontier header,
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/DominanceFrontier.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/SetOperations.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Analysis/DominatorInternals.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/CommandLine.h"
30 #include <algorithm>
31 using namespace llvm;
32
33 // Always verify dominfo if expensive checking is enabled.
34 #ifdef XDEBUG
35 static bool VerifyDomInfo = true;
36 #else
37 static bool VerifyDomInfo = false;
38 #endif
39 static cl::opt<bool,true>
40 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
41                cl::desc("Verify dominator info (time consuming)"));
42
43 //===----------------------------------------------------------------------===//
44 //  DominatorTree Implementation
45 //===----------------------------------------------------------------------===//
46 //
47 // Provide public access to DominatorTree information.  Implementation details
48 // can be found in DominatorCalculation.h.
49 //
50 //===----------------------------------------------------------------------===//
51
52 TEMPLATE_INSTANTIATION(class llvm::DomTreeNodeBase<BasicBlock>);
53 TEMPLATE_INSTANTIATION(class llvm::DominatorTreeBase<BasicBlock>);
54
55 char DominatorTree::ID = 0;
56 INITIALIZE_PASS(DominatorTree, "domtree",
57                 "Dominator Tree Construction", true, true)
58
59 bool DominatorTree::runOnFunction(Function &F) {
60   DT->recalculate(F);
61   return false;
62 }
63
64 void DominatorTree::verifyAnalysis() const {
65   if (!VerifyDomInfo) return;
66
67   Function &F = *getRoot()->getParent();
68
69   DominatorTree OtherDT;
70   OtherDT.getBase().recalculate(F);
71   assert(!compare(OtherDT) && "Invalid DominatorTree info!");
72 }
73
74 void DominatorTree::print(raw_ostream &OS, const Module *) const {
75   DT->print(OS);
76 }
77
78 // dominates - Return true if A dominates a use in B. This performs the
79 // special checks necessary if A and B are in the same basic block.
80 bool DominatorTree::dominates(const Instruction *A, const Instruction *B) const{
81   const BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
82   
83   // If A is an invoke instruction, its value is only available in this normal
84   // successor block.
85   if (const InvokeInst *II = dyn_cast<InvokeInst>(A))
86     BBA = II->getNormalDest();
87   
88   if (BBA != BBB) return dominates(BBA, BBB);
89   
90   // It is not possible to determine dominance between two PHI nodes 
91   // based on their ordering.
92   if (isa<PHINode>(A) && isa<PHINode>(B)) 
93     return false;
94   
95   // Loop through the basic block until we find A or B.
96   BasicBlock::const_iterator I = BBA->begin();
97   for (; &*I != A && &*I != B; ++I)
98     /*empty*/;
99   
100   return &*I == A;
101 }
102
103
104
105 //===----------------------------------------------------------------------===//
106 //  DominanceFrontier Implementation
107 //===----------------------------------------------------------------------===//
108
109 char DominanceFrontier::ID = 0;
110 INITIALIZE_PASS_BEGIN(DominanceFrontier, "domfrontier",
111                 "Dominance Frontier Construction", true, true)
112 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
113 INITIALIZE_PASS_END(DominanceFrontier, "domfrontier",
114                 "Dominance Frontier Construction", true, true)
115
116 void DominanceFrontier::verifyAnalysis() const {
117   if (!VerifyDomInfo) return;
118
119   DominatorTree &DT = getAnalysis<DominatorTree>();
120
121   DominanceFrontier OtherDF;
122   const std::vector<BasicBlock*> &DTRoots = DT.getRoots();
123   OtherDF.calculate(DT, DT.getNode(DTRoots[0]));
124   assert(!compare(OtherDF) && "Invalid DominanceFrontier info!");
125 }
126
127 // NewBB is split and now it has one successor. Update dominance frontier to
128 // reflect this change.
129 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
130   assert(NewBB->getTerminator()->getNumSuccessors() == 1 &&
131          "NewBB should have a single successor!");
132   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
133
134   // NewBBSucc inherits original NewBB frontier.
135   DominanceFrontier::iterator NewBBI = find(NewBB);
136   if (NewBBI != end())
137     addBasicBlock(NewBBSucc, NewBBI->second);
138
139   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
140   // DF(NewBBSucc) without the stuff that the new block does not dominate
141   // a predecessor of.
142   DominatorTree &DT = getAnalysis<DominatorTree>();
143   DomTreeNode *NewBBNode = DT.getNode(NewBB);
144   DomTreeNode *NewBBSuccNode = DT.getNode(NewBBSucc);
145   if (DT.dominates(NewBBNode, NewBBSuccNode)) {
146     DominanceFrontier::iterator DFI = find(NewBBSucc);
147     if (DFI != end()) {
148       DominanceFrontier::DomSetType Set = DFI->second;
149       // Filter out stuff in Set that we do not dominate a predecessor of.
150       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
151              E = Set.end(); SetI != E;) {
152         bool DominatesPred = false;
153         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
154              PI != E; ++PI)
155           if (DT.dominates(NewBBNode, DT.getNode(*PI))) {
156             DominatesPred = true;
157             break;
158           }
159         if (!DominatesPred)
160           Set.erase(SetI++);
161         else
162           ++SetI;
163       }
164
165       if (NewBBI != end()) {
166         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
167                E = Set.end(); SetI != E; ++SetI) {
168           BasicBlock *SB = *SetI;
169           addToFrontier(NewBBI, SB);
170         }
171       } else 
172         addBasicBlock(NewBB, Set);
173     }
174     
175   } else {
176     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
177     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
178     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
179     DominanceFrontier::DomSetType NewDFSet;
180     NewDFSet.insert(NewBBSucc);
181     addBasicBlock(NewBB, NewDFSet);
182   }
183
184   // Now update dominance frontiers which either used to contain NewBBSucc
185   // or which now need to include NewBB.
186
187   // Collect the set of blocks which dominate a predecessor of NewBB or
188   // NewSuccBB and which don't dominate both. This is an initial
189   // approximation of the blocks whose dominance frontiers will need updates.
190   SmallVector<DomTreeNode *, 16> AllPredDoms;
191
192   // Compute the block which dominates both NewBBSucc and NewBB. This is
193   // the immediate dominator of NewBBSucc unless NewBB dominates NewBBSucc.
194   // The code below which climbs dominator trees will stop at this point,
195   // because from this point up, dominance frontiers are unaffected.
196   DomTreeNode *DominatesBoth = 0;
197   if (NewBBSuccNode) {
198     DominatesBoth = NewBBSuccNode->getIDom();
199     if (DominatesBoth == NewBBNode)
200       DominatesBoth = NewBBNode->getIDom();
201   }
202
203   // Collect the set of all blocks which dominate a predecessor of NewBB.
204   SmallPtrSet<DomTreeNode *, 8> NewBBPredDoms;
205   for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); PI != E; ++PI)
206     for (DomTreeNode *DTN = DT.getNode(*PI); DTN; DTN = DTN->getIDom()) {
207       if (DTN == DominatesBoth)
208         break;
209       if (!NewBBPredDoms.insert(DTN))
210         break;
211       AllPredDoms.push_back(DTN);
212     }
213
214   // Collect the set of all blocks which dominate a predecessor of NewSuccBB.
215   SmallPtrSet<DomTreeNode *, 8> NewBBSuccPredDoms;
216   for (pred_iterator PI = pred_begin(NewBBSucc),
217        E = pred_end(NewBBSucc); PI != E; ++PI)
218     for (DomTreeNode *DTN = DT.getNode(*PI); DTN; DTN = DTN->getIDom()) {
219       if (DTN == DominatesBoth)
220         break;
221       if (!NewBBSuccPredDoms.insert(DTN))
222         break;
223       if (!NewBBPredDoms.count(DTN))
224         AllPredDoms.push_back(DTN);
225     }
226
227   // Visit all relevant dominance frontiers and make any needed updates.
228   for (SmallVectorImpl<DomTreeNode *>::const_iterator I = AllPredDoms.begin(),
229        E = AllPredDoms.end(); I != E; ++I) {
230     DomTreeNode *DTN = *I;
231     iterator DFI = find((*I)->getBlock());
232
233     // Only consider nodes that have NewBBSucc in their dominator frontier.
234     if (DFI == end() || !DFI->second.count(NewBBSucc)) continue;
235
236     // If the block dominates a predecessor of NewBB but does not properly
237     // dominate NewBB itself, add NewBB to its dominance frontier.
238     if (NewBBPredDoms.count(DTN) &&
239         !DT.properlyDominates(DTN, NewBBNode))
240       addToFrontier(DFI, NewBB);
241
242     // If the block does not dominate a predecessor of NewBBSucc or
243     // properly dominates NewBBSucc itself, remove NewBBSucc from its
244     // dominance frontier.
245     if (!NewBBSuccPredDoms.count(DTN) ||
246         DT.properlyDominates(DTN, NewBBSuccNode))
247       removeFromFrontier(DFI, NewBBSucc);
248   }
249 }
250
251 namespace {
252   class DFCalculateWorkObject {
253   public:
254     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
255                           const DomTreeNode *N,
256                           const DomTreeNode *PN)
257     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
258     BasicBlock *currentBB;
259     BasicBlock *parentBB;
260     const DomTreeNode *Node;
261     const DomTreeNode *parentNode;
262   };
263 }
264
265 const DominanceFrontier::DomSetType &
266 DominanceFrontier::calculate(const DominatorTree &DT,
267                              const DomTreeNode *Node) {
268   BasicBlock *BB = Node->getBlock();
269   DomSetType *Result = NULL;
270
271   std::vector<DFCalculateWorkObject> workList;
272   SmallPtrSet<BasicBlock *, 32> visited;
273
274   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
275   do {
276     DFCalculateWorkObject *currentW = &workList.back();
277     assert (currentW && "Missing work object.");
278
279     BasicBlock *currentBB = currentW->currentBB;
280     BasicBlock *parentBB = currentW->parentBB;
281     const DomTreeNode *currentNode = currentW->Node;
282     const DomTreeNode *parentNode = currentW->parentNode;
283     assert (currentBB && "Invalid work object. Missing current Basic Block");
284     assert (currentNode && "Invalid work object. Missing current Node");
285     DomSetType &S = Frontiers[currentBB];
286
287     // Visit each block only once.
288     if (visited.count(currentBB) == 0) {
289       visited.insert(currentBB);
290
291       // Loop over CFG successors to calculate DFlocal[currentNode]
292       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
293            SI != SE; ++SI) {
294         // Does Node immediately dominate this successor?
295         if (DT[*SI]->getIDom() != currentNode)
296           S.insert(*SI);
297       }
298     }
299
300     // At this point, S is DFlocal.  Now we union in DFup's of our children...
301     // Loop through and visit the nodes that Node immediately dominates (Node's
302     // children in the IDomTree)
303     bool visitChild = false;
304     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
305            NE = currentNode->end(); NI != NE; ++NI) {
306       DomTreeNode *IDominee = *NI;
307       BasicBlock *childBB = IDominee->getBlock();
308       if (visited.count(childBB) == 0) {
309         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
310                                                  IDominee, currentNode));
311         visitChild = true;
312       }
313     }
314
315     // If all children are visited or there is any child then pop this block
316     // from the workList.
317     if (!visitChild) {
318
319       if (!parentBB) {
320         Result = &S;
321         break;
322       }
323
324       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
325       DomSetType &parentSet = Frontiers[parentBB];
326       for (; CDFI != CDFE; ++CDFI) {
327         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
328           parentSet.insert(*CDFI);
329       }
330       workList.pop_back();
331     }
332
333   } while (!workList.empty());
334
335   return *Result;
336 }
337
338 void DominanceFrontierBase::print(raw_ostream &OS, const Module* ) const {
339   for (const_iterator I = begin(), E = end(); I != E; ++I) {
340     OS << "  DomFrontier for BB ";
341     if (I->first)
342       WriteAsOperand(OS, I->first, false);
343     else
344       OS << " <<exit node>>";
345     OS << " is:\t";
346     
347     const std::set<BasicBlock*> &BBs = I->second;
348     
349     for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
350          I != E; ++I) {
351       OS << ' ';
352       if (*I)
353         WriteAsOperand(OS, *I, false);
354       else
355         OS << "<<exit node>>";
356     }
357     OS << "\n";
358   }
359 }
360
361 void DominanceFrontierBase::dump() const {
362   print(dbgs());
363 }
364