don't print dominators every time it is computed with -debug.
[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/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Analysis/DominatorInternals.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Support/Streams.h"
27 #include <algorithm>
28 using namespace llvm;
29
30 namespace llvm {
31 static std::ostream &operator<<(std::ostream &o,
32                                 const std::set<BasicBlock*> &BBs) {
33   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
34        I != E; ++I)
35     if (*I)
36       WriteAsOperand(o, *I, false);
37     else
38       o << " <<exit node>>";
39   return o;
40 }
41 }
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 DomTreeNodeBase<BasicBlock>);
53 TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
54
55 char DominatorTree::ID = 0;
56 static RegisterPass<DominatorTree>
57 E("domtree", "Dominator Tree Construction", true, true);
58
59 bool DominatorTree::runOnFunction(Function &F) {
60   DT->recalculate(F);
61   return false;
62 }
63
64 //===----------------------------------------------------------------------===//
65 //  DominanceFrontier Implementation
66 //===----------------------------------------------------------------------===//
67
68 char DominanceFrontier::ID = 0;
69 static RegisterPass<DominanceFrontier>
70 G("domfrontier", "Dominance Frontier Construction", false, true);
71
72 // NewBB is split and now it has one successor. Update dominace frontier to
73 // reflect this change.
74 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
75   assert(NewBB->getTerminator()->getNumSuccessors() == 1
76          && "NewBB should have a single successor!");
77   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
78
79   std::vector<BasicBlock*> PredBlocks;
80   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
81        PI != PE; ++PI)
82       PredBlocks.push_back(*PI);  
83
84   if (PredBlocks.empty())
85     // If NewBB does not have any predecessors then it is a entry block.
86     // In this case, NewBB and its successor NewBBSucc dominates all
87     // other blocks.
88     return;
89
90   // NewBBSucc inherits original NewBB frontier.
91   DominanceFrontier::iterator NewBBI = find(NewBB);
92   if (NewBBI != end()) {
93     DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
94     DominanceFrontier::DomSetType NewBBSuccSet;
95     NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
96     addBasicBlock(NewBBSucc, NewBBSuccSet);
97   }
98
99   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
100   // DF(PredBlocks[0]) without the stuff that the new block does not dominate
101   // a predecessor of.
102   DominatorTree &DT = getAnalysis<DominatorTree>();
103   if (DT.dominates(NewBB, NewBBSucc)) {
104     DominanceFrontier::iterator DFI = find(PredBlocks[0]);
105     if (DFI != end()) {
106       DominanceFrontier::DomSetType Set = DFI->second;
107       // Filter out stuff in Set that we do not dominate a predecessor of.
108       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
109              E = Set.end(); SetI != E;) {
110         bool DominatesPred = false;
111         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
112              PI != E; ++PI)
113           if (DT.dominates(NewBB, *PI))
114             DominatesPred = true;
115         if (!DominatesPred)
116           Set.erase(SetI++);
117         else
118           ++SetI;
119       }
120
121       if (NewBBI != end()) {
122         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
123                E = Set.end(); SetI != E; ++SetI) {
124           BasicBlock *SB = *SetI;
125           addToFrontier(NewBBI, SB);
126         }
127       } else 
128         addBasicBlock(NewBB, Set);
129     }
130     
131   } else {
132     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
133     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
134     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
135     DominanceFrontier::DomSetType NewDFSet;
136     NewDFSet.insert(NewBBSucc);
137     addBasicBlock(NewBB, NewDFSet);
138   }
139   
140   // Now we must loop over all of the dominance frontiers in the function,
141   // replacing occurrences of NewBBSucc with NewBB in some cases.  All
142   // blocks that dominate a block in PredBlocks and contained NewBBSucc in
143   // their dominance frontier must be updated to contain NewBB instead.
144   //
145   for (Function::iterator FI = NewBB->getParent()->begin(),
146          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
147     DominanceFrontier::iterator DFI = find(FI);
148     if (DFI == end()) continue;  // unreachable block.
149     
150     // Only consider nodes that have NewBBSucc in their dominator frontier.
151     if (!DFI->second.count(NewBBSucc)) continue;
152
153     // Verify whether this block dominates a block in predblocks.  If not, do
154     // not update it.
155     bool BlockDominatesAny = false;
156     for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(), 
157            BE = PredBlocks.end(); BI != BE; ++BI) {
158       if (DT.dominates(FI, *BI)) {
159         BlockDominatesAny = true;
160         break;
161       }
162     }
163     
164     if (!BlockDominatesAny)
165       continue;
166     
167     // If NewBBSucc should not stay in our dominator frontier, remove it.
168     // We remove it unless there is a predecessor of NewBBSucc that we
169     // dominate, but we don't strictly dominate NewBBSucc.
170     bool ShouldRemove = true;
171     if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
172       // Okay, we know that PredDom does not strictly dominate NewBBSucc.
173       // Check to see if it dominates any predecessors of NewBBSucc.
174       for (pred_iterator PI = pred_begin(NewBBSucc),
175            E = pred_end(NewBBSucc); PI != E; ++PI)
176         if (DT.dominates(FI, *PI)) {
177           ShouldRemove = false;
178           break;
179         }
180     }
181     
182     if (ShouldRemove)
183       removeFromFrontier(DFI, NewBBSucc);
184     addToFrontier(DFI, NewBB);
185   }
186 }
187
188 namespace {
189   class DFCalculateWorkObject {
190   public:
191     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
192                           const DomTreeNode *N,
193                           const DomTreeNode *PN)
194     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
195     BasicBlock *currentBB;
196     BasicBlock *parentBB;
197     const DomTreeNode *Node;
198     const DomTreeNode *parentNode;
199   };
200 }
201
202 const DominanceFrontier::DomSetType &
203 DominanceFrontier::calculate(const DominatorTree &DT,
204                              const DomTreeNode *Node) {
205   BasicBlock *BB = Node->getBlock();
206   DomSetType *Result = NULL;
207
208   std::vector<DFCalculateWorkObject> workList;
209   SmallPtrSet<BasicBlock *, 32> visited;
210
211   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
212   do {
213     DFCalculateWorkObject *currentW = &workList.back();
214     assert (currentW && "Missing work object.");
215
216     BasicBlock *currentBB = currentW->currentBB;
217     BasicBlock *parentBB = currentW->parentBB;
218     const DomTreeNode *currentNode = currentW->Node;
219     const DomTreeNode *parentNode = currentW->parentNode;
220     assert (currentBB && "Invalid work object. Missing current Basic Block");
221     assert (currentNode && "Invalid work object. Missing current Node");
222     DomSetType &S = Frontiers[currentBB];
223
224     // Visit each block only once.
225     if (visited.count(currentBB) == 0) {
226       visited.insert(currentBB);
227
228       // Loop over CFG successors to calculate DFlocal[currentNode]
229       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
230            SI != SE; ++SI) {
231         // Does Node immediately dominate this successor?
232         if (DT[*SI]->getIDom() != currentNode)
233           S.insert(*SI);
234       }
235     }
236
237     // At this point, S is DFlocal.  Now we union in DFup's of our children...
238     // Loop through and visit the nodes that Node immediately dominates (Node's
239     // children in the IDomTree)
240     bool visitChild = false;
241     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
242            NE = currentNode->end(); NI != NE; ++NI) {
243       DomTreeNode *IDominee = *NI;
244       BasicBlock *childBB = IDominee->getBlock();
245       if (visited.count(childBB) == 0) {
246         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
247                                                  IDominee, currentNode));
248         visitChild = true;
249       }
250     }
251
252     // If all children are visited or there is any child then pop this block
253     // from the workList.
254     if (!visitChild) {
255
256       if (!parentBB) {
257         Result = &S;
258         break;
259       }
260
261       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
262       DomSetType &parentSet = Frontiers[parentBB];
263       for (; CDFI != CDFE; ++CDFI) {
264         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
265           parentSet.insert(*CDFI);
266       }
267       workList.pop_back();
268     }
269
270   } while (!workList.empty());
271
272   return *Result;
273 }
274
275 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
276   for (const_iterator I = begin(), E = end(); I != E; ++I) {
277     o << "  DomFrontier for BB";
278     if (I->first)
279       WriteAsOperand(o, I->first, false);
280     else
281       o << " <<exit node>>";
282     o << " is:\t" << I->second << "\n";
283   }
284 }
285
286 void DominanceFrontierBase::dump() {
287   print (llvm::cerr);
288 }