Template DominatorTreeBase by node type. This is the next major step towards
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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);
58
59 // NewBB is split and now it has one successor. Update dominator tree to
60 // reflect this change.
61 void DominatorTree::splitBlock(BasicBlock *NewBB) {
62   assert(NewBB->getTerminator()->getNumSuccessors() == 1
63          && "NewBB should have a single successor!");
64   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
65
66   std::vector<BasicBlock*> PredBlocks;
67   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
68        PI != PE; ++PI)
69       PredBlocks.push_back(*PI);  
70
71   assert(!PredBlocks.empty() && "No predblocks??");
72
73   // The newly inserted basic block will dominate existing basic blocks iff the
74   // PredBlocks dominate all of the non-pred blocks.  If all predblocks dominate
75   // the non-pred blocks, then they all must be the same block!
76   //
77   bool NewBBDominatesNewBBSucc = true;
78   {
79     BasicBlock *OnePred = PredBlocks[0];
80     unsigned i = 1, e = PredBlocks.size();
81     for (i = 1; !isReachableFromEntry(OnePred); ++i) {
82       assert(i != e && "Didn't find reachable pred?");
83       OnePred = PredBlocks[i];
84     }
85     
86     for (; i != e; ++i)
87       if (PredBlocks[i] != OnePred && isReachableFromEntry(OnePred)) {
88         NewBBDominatesNewBBSucc = false;
89         break;
90       }
91
92     if (NewBBDominatesNewBBSucc)
93       for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
94            PI != E; ++PI)
95         if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
96           NewBBDominatesNewBBSucc = false;
97           break;
98         }
99   }
100
101   // The other scenario where the new block can dominate its successors are when
102   // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
103   // already.
104   if (!NewBBDominatesNewBBSucc) {
105     NewBBDominatesNewBBSucc = true;
106     for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
107          PI != E; ++PI)
108       if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
109         NewBBDominatesNewBBSucc = false;
110         break;
111       }
112   }
113
114   // Find NewBB's immediate dominator and create new dominator tree node for
115   // NewBB.
116   BasicBlock *NewBBIDom = 0;
117   unsigned i = 0;
118   for (i = 0; i < PredBlocks.size(); ++i)
119     if (isReachableFromEntry(PredBlocks[i])) {
120       NewBBIDom = PredBlocks[i];
121       break;
122     }
123   assert(i != PredBlocks.size() && "No reachable preds?");
124   for (i = i + 1; i < PredBlocks.size(); ++i) {
125     if (isReachableFromEntry(PredBlocks[i]))
126       NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
127   }
128   assert(NewBBIDom && "No immediate dominator found??");
129   
130   // Create the new dominator tree node... and set the idom of NewBB.
131   DomTreeNode *NewBBNode = addNewBlock(NewBB, NewBBIDom);
132   
133   // If NewBB strictly dominates other blocks, then it is now the immediate
134   // dominator of NewBBSucc.  Update the dominator tree as appropriate.
135   if (NewBBDominatesNewBBSucc) {
136     DomTreeNode *NewBBSuccNode = getNode(NewBBSucc);
137     changeImmediateDominator(NewBBSuccNode, NewBBNode);
138   }
139 }
140
141 bool DominatorTree::runOnFunction(Function &F) {
142   reset();     // Reset from the last time we were run...
143   
144   // Initialize roots
145   Roots.push_back(&F.getEntryBlock());
146   IDoms[&F.getEntryBlock()] = 0;
147   DomTreeNodes[&F.getEntryBlock()] = 0;
148   Vertex.push_back(0);
149   
150   Calculate<BasicBlock*, GraphTraits<BasicBlock*> >(*this, F);
151   
152   updateDFSNumbers();
153   
154   return false;
155 }
156
157 //===----------------------------------------------------------------------===//
158 //  DominanceFrontier Implementation
159 //===----------------------------------------------------------------------===//
160
161 char DominanceFrontier::ID = 0;
162 static RegisterPass<DominanceFrontier>
163 G("domfrontier", "Dominance Frontier Construction", true);
164
165 // NewBB is split and now it has one successor. Update dominace frontier to
166 // reflect this change.
167 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
168   assert(NewBB->getTerminator()->getNumSuccessors() == 1
169          && "NewBB should have a single successor!");
170   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
171
172   std::vector<BasicBlock*> PredBlocks;
173   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
174        PI != PE; ++PI)
175       PredBlocks.push_back(*PI);  
176
177   if (PredBlocks.empty())
178     // If NewBB does not have any predecessors then it is a entry block.
179     // In this case, NewBB and its successor NewBBSucc dominates all
180     // other blocks.
181     return;
182
183   // NewBBSucc inherits original NewBB frontier.
184   DominanceFrontier::iterator NewBBI = find(NewBB);
185   if (NewBBI != end()) {
186     DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
187     DominanceFrontier::DomSetType NewBBSuccSet;
188     NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
189     addBasicBlock(NewBBSucc, NewBBSuccSet);
190   }
191
192   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
193   // DF(PredBlocks[0]) without the stuff that the new block does not dominate
194   // a predecessor of.
195   DominatorTree &DT = getAnalysis<DominatorTree>();
196   if (DT.dominates(NewBB, NewBBSucc)) {
197     DominanceFrontier::iterator DFI = find(PredBlocks[0]);
198     if (DFI != end()) {
199       DominanceFrontier::DomSetType Set = DFI->second;
200       // Filter out stuff in Set that we do not dominate a predecessor of.
201       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
202              E = Set.end(); SetI != E;) {
203         bool DominatesPred = false;
204         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
205              PI != E; ++PI)
206           if (DT.dominates(NewBB, *PI))
207             DominatesPred = true;
208         if (!DominatesPred)
209           Set.erase(SetI++);
210         else
211           ++SetI;
212       }
213
214       if (NewBBI != end()) {
215         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
216                E = Set.end(); SetI != E; ++SetI) {
217           BasicBlock *SB = *SetI;
218           addToFrontier(NewBBI, SB);
219         }
220       } else 
221         addBasicBlock(NewBB, Set);
222     }
223     
224   } else {
225     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
226     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
227     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
228     DominanceFrontier::DomSetType NewDFSet;
229     NewDFSet.insert(NewBBSucc);
230     addBasicBlock(NewBB, NewDFSet);
231   }
232   
233   // Now we must loop over all of the dominance frontiers in the function,
234   // replacing occurrences of NewBBSucc with NewBB in some cases.  All
235   // blocks that dominate a block in PredBlocks and contained NewBBSucc in
236   // their dominance frontier must be updated to contain NewBB instead.
237   //
238   for (Function::iterator FI = NewBB->getParent()->begin(),
239          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
240     DominanceFrontier::iterator DFI = find(FI);
241     if (DFI == end()) continue;  // unreachable block.
242     
243     // Only consider nodes that have NewBBSucc in their dominator frontier.
244     if (!DFI->second.count(NewBBSucc)) continue;
245
246     // Verify whether this block dominates a block in predblocks.  If not, do
247     // not update it.
248     bool BlockDominatesAny = false;
249     for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(), 
250            BE = PredBlocks.end(); BI != BE; ++BI) {
251       if (DT.dominates(FI, *BI)) {
252         BlockDominatesAny = true;
253         break;
254       }
255     }
256     
257     if (!BlockDominatesAny)
258       continue;
259     
260     // If NewBBSucc should not stay in our dominator frontier, remove it.
261     // We remove it unless there is a predecessor of NewBBSucc that we
262     // dominate, but we don't strictly dominate NewBBSucc.
263     bool ShouldRemove = true;
264     if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
265       // Okay, we know that PredDom does not strictly dominate NewBBSucc.
266       // Check to see if it dominates any predecessors of NewBBSucc.
267       for (pred_iterator PI = pred_begin(NewBBSucc),
268            E = pred_end(NewBBSucc); PI != E; ++PI)
269         if (DT.dominates(FI, *PI)) {
270           ShouldRemove = false;
271           break;
272         }
273     }
274     
275     if (ShouldRemove)
276       removeFromFrontier(DFI, NewBBSucc);
277     addToFrontier(DFI, NewBB);
278   }
279 }
280
281 namespace {
282   class DFCalculateWorkObject {
283   public:
284     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
285                           const DomTreeNode *N,
286                           const DomTreeNode *PN)
287     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
288     BasicBlock *currentBB;
289     BasicBlock *parentBB;
290     const DomTreeNode *Node;
291     const DomTreeNode *parentNode;
292   };
293 }
294
295 const DominanceFrontier::DomSetType &
296 DominanceFrontier::calculate(const DominatorTree &DT,
297                              const DomTreeNode *Node) {
298   BasicBlock *BB = Node->getBlock();
299   DomSetType *Result = NULL;
300
301   std::vector<DFCalculateWorkObject> workList;
302   SmallPtrSet<BasicBlock *, 32> visited;
303
304   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
305   do {
306     DFCalculateWorkObject *currentW = &workList.back();
307     assert (currentW && "Missing work object.");
308
309     BasicBlock *currentBB = currentW->currentBB;
310     BasicBlock *parentBB = currentW->parentBB;
311     const DomTreeNode *currentNode = currentW->Node;
312     const DomTreeNode *parentNode = currentW->parentNode;
313     assert (currentBB && "Invalid work object. Missing current Basic Block");
314     assert (currentNode && "Invalid work object. Missing current Node");
315     DomSetType &S = Frontiers[currentBB];
316
317     // Visit each block only once.
318     if (visited.count(currentBB) == 0) {
319       visited.insert(currentBB);
320
321       // Loop over CFG successors to calculate DFlocal[currentNode]
322       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
323            SI != SE; ++SI) {
324         // Does Node immediately dominate this successor?
325         if (DT[*SI]->getIDom() != currentNode)
326           S.insert(*SI);
327       }
328     }
329
330     // At this point, S is DFlocal.  Now we union in DFup's of our children...
331     // Loop through and visit the nodes that Node immediately dominates (Node's
332     // children in the IDomTree)
333     bool visitChild = false;
334     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
335            NE = currentNode->end(); NI != NE; ++NI) {
336       DomTreeNode *IDominee = *NI;
337       BasicBlock *childBB = IDominee->getBlock();
338       if (visited.count(childBB) == 0) {
339         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
340                                                  IDominee, currentNode));
341         visitChild = true;
342       }
343     }
344
345     // If all children are visited or there is any child then pop this block
346     // from the workList.
347     if (!visitChild) {
348
349       if (!parentBB) {
350         Result = &S;
351         break;
352       }
353
354       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
355       DomSetType &parentSet = Frontiers[parentBB];
356       for (; CDFI != CDFE; ++CDFI) {
357         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
358           parentSet.insert(*CDFI);
359       }
360       workList.pop_back();
361     }
362
363   } while (!workList.empty());
364
365   return *Result;
366 }
367
368 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
369   for (const_iterator I = begin(), E = end(); I != E; ++I) {
370     o << "  DomFrontier for BB";
371     if (I->first)
372       WriteAsOperand(o, I->first, false);
373     else
374       o << " <<exit node>>";
375     o << " is:\t" << I->second << "\n";
376   }
377 }
378
379 void DominanceFrontierBase::dump() {
380   print (llvm::cerr);
381 }