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