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