Avoid copying and recopying a std::set.
[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     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   if (DT.dominates(NewBB, NewBBSucc)) {
151     DominanceFrontier::iterator DFI = find(NewBBSucc);
152     if (DFI != end()) {
153       DominanceFrontier::DomSetType Set = DFI->second;
154       // Filter out stuff in Set that we do not dominate a predecessor of.
155       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
156              E = Set.end(); SetI != E;) {
157         bool DominatesPred = false;
158         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
159              PI != E; ++PI)
160           if (DT.dominates(NewBB, *PI)) {
161             DominatesPred = true;
162             break;
163           }
164         if (!DominatesPred)
165           Set.erase(SetI++);
166         else
167           ++SetI;
168       }
169
170       if (NewBBI != end()) {
171         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
172                E = Set.end(); SetI != E; ++SetI) {
173           BasicBlock *SB = *SetI;
174           addToFrontier(NewBBI, SB);
175         }
176       } else 
177         addBasicBlock(NewBB, Set);
178     }
179     
180   } else {
181     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
182     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
183     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
184     DominanceFrontier::DomSetType NewDFSet;
185     NewDFSet.insert(NewBBSucc);
186     addBasicBlock(NewBB, NewDFSet);
187   }
188   
189   // Now we must loop over all of the dominance frontiers in the function,
190   // replacing occurrences of NewBBSucc with NewBB in some cases.  All
191   // blocks that dominate a block in PredBlocks and contained NewBBSucc in
192   // their dominance frontier must be updated to contain NewBB instead.
193   //
194   for (Function::iterator FI = NewBB->getParent()->begin(),
195          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
196     DominanceFrontier::iterator DFI = find(FI);
197     if (DFI == end()) continue;  // unreachable block.
198     
199     // Only consider nodes that have NewBBSucc in their dominator frontier.
200     if (!DFI->second.count(NewBBSucc)) continue;
201
202     // Verify whether this block dominates a block in predblocks.  If not, do
203     // not update it.
204     bool BlockDominatesAny = false;
205     for (SmallVectorImpl<BasicBlock*>::const_iterator BI = PredBlocks.begin(), 
206            BE = PredBlocks.end(); BI != BE; ++BI) {
207       if (DT.dominates(FI, *BI)) {
208         BlockDominatesAny = true;
209         break;
210       }
211     }
212
213     // If NewBBSucc should not stay in our dominator frontier, remove it.
214     // We remove it unless there is a predecessor of NewBBSucc that we
215     // dominate, but we don't strictly dominate NewBBSucc.
216     bool ShouldRemove = true;
217     if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
218       // Okay, we know that PredDom does not strictly dominate NewBBSucc.
219       // Check to see if it dominates any predecessors of NewBBSucc.
220       for (pred_iterator PI = pred_begin(NewBBSucc),
221            E = pred_end(NewBBSucc); PI != E; ++PI)
222         if (DT.dominates(FI, *PI)) {
223           ShouldRemove = false;
224           break;
225         }
226     }
227     
228     if (ShouldRemove)
229       removeFromFrontier(DFI, NewBBSucc);
230     if (BlockDominatesAny && (&*FI == NewBB || !DT.dominates(FI, NewBB)))
231       addToFrontier(DFI, NewBB);
232   }
233 }
234
235 namespace {
236   class DFCalculateWorkObject {
237   public:
238     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
239                           const DomTreeNode *N,
240                           const DomTreeNode *PN)
241     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
242     BasicBlock *currentBB;
243     BasicBlock *parentBB;
244     const DomTreeNode *Node;
245     const DomTreeNode *parentNode;
246   };
247 }
248
249 const DominanceFrontier::DomSetType &
250 DominanceFrontier::calculate(const DominatorTree &DT,
251                              const DomTreeNode *Node) {
252   BasicBlock *BB = Node->getBlock();
253   DomSetType *Result = NULL;
254
255   std::vector<DFCalculateWorkObject> workList;
256   SmallPtrSet<BasicBlock *, 32> visited;
257
258   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
259   do {
260     DFCalculateWorkObject *currentW = &workList.back();
261     assert (currentW && "Missing work object.");
262
263     BasicBlock *currentBB = currentW->currentBB;
264     BasicBlock *parentBB = currentW->parentBB;
265     const DomTreeNode *currentNode = currentW->Node;
266     const DomTreeNode *parentNode = currentW->parentNode;
267     assert (currentBB && "Invalid work object. Missing current Basic Block");
268     assert (currentNode && "Invalid work object. Missing current Node");
269     DomSetType &S = Frontiers[currentBB];
270
271     // Visit each block only once.
272     if (visited.count(currentBB) == 0) {
273       visited.insert(currentBB);
274
275       // Loop over CFG successors to calculate DFlocal[currentNode]
276       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
277            SI != SE; ++SI) {
278         // Does Node immediately dominate this successor?
279         if (DT[*SI]->getIDom() != currentNode)
280           S.insert(*SI);
281       }
282     }
283
284     // At this point, S is DFlocal.  Now we union in DFup's of our children...
285     // Loop through and visit the nodes that Node immediately dominates (Node's
286     // children in the IDomTree)
287     bool visitChild = false;
288     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
289            NE = currentNode->end(); NI != NE; ++NI) {
290       DomTreeNode *IDominee = *NI;
291       BasicBlock *childBB = IDominee->getBlock();
292       if (visited.count(childBB) == 0) {
293         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
294                                                  IDominee, currentNode));
295         visitChild = true;
296       }
297     }
298
299     // If all children are visited or there is any child then pop this block
300     // from the workList.
301     if (!visitChild) {
302
303       if (!parentBB) {
304         Result = &S;
305         break;
306       }
307
308       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
309       DomSetType &parentSet = Frontiers[parentBB];
310       for (; CDFI != CDFE; ++CDFI) {
311         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
312           parentSet.insert(*CDFI);
313       }
314       workList.pop_back();
315     }
316
317   } while (!workList.empty());
318
319   return *Result;
320 }
321
322 void DominanceFrontierBase::print(raw_ostream &OS, const Module* ) const {
323   for (const_iterator I = begin(), E = end(); I != E; ++I) {
324     OS << "  DomFrontier for BB ";
325     if (I->first)
326       WriteAsOperand(OS, I->first, false);
327     else
328       OS << " <<exit node>>";
329     OS << " is:\t";
330     
331     const std::set<BasicBlock*> &BBs = I->second;
332     
333     for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
334          I != E; ++I) {
335       OS << ' ';
336       if (*I)
337         WriteAsOperand(OS, *I, false);
338       else
339         OS << "<<exit node>>";
340     }
341     OS << "\n";
342   }
343 }
344
345 void DominanceFrontierBase::dump() const {
346   print(dbgs());
347 }
348