671b49425eeb6a18cd172859b87da4207105d252
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2 //
3 // This file implements simple dominator construction algorithms for finding
4 // forward dominators.  Postdominators are available in libanalysis, but are not
5 // included in libvmcore, because it's not needed.  Forward dominators are
6 // needed to support the Verifier pass.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Analysis/Dominators.h"
11 #include "llvm/Support/CFG.h"
12 #include "llvm/Assembly/Writer.h"
13 #include "Support/DepthFirstIterator.h"
14 #include "Support/SetOperations.h"
15
16 //===----------------------------------------------------------------------===//
17 //  DominatorSet Implementation
18 //===----------------------------------------------------------------------===//
19
20 static RegisterAnalysis<DominatorSet>
21 A("domset", "Dominator Set Construction", true);
22
23 // dominates - Return true if A dominates B.  This performs the special checks
24 // necessary if A and B are in the same basic block.
25 //
26 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
27   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
28   if (BBA != BBB) return dominates(BBA, BBB);
29   
30   // Loop through the basic block until we find A or B.
31   BasicBlock::iterator I = BBA->begin();
32   for (; &*I != A && &*I != B; ++I) /*empty*/;
33   
34   // A dominates B if it is found first in the basic block...
35   return &*I == A;
36 }
37
38
39 void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
40   bool Changed;
41   Doms[RootBB].insert(RootBB);  // Root always dominates itself...
42   do {
43     Changed = false;
44
45     DomSetType WorkingSet;
46     df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
47     for ( ; It != End; ++It) {
48       BasicBlock *BB = *It;
49       pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
50       if (PI != PEnd) {                // Is there SOME predecessor?
51         // Loop until we get to a predecessor that has had its dom set filled
52         // in at least once.  We are guaranteed to have this because we are
53         // traversing the graph in DFO and have handled start nodes specially,
54         // except when there are unreachable blocks.
55         //
56         while (PI != PEnd && Doms[*PI].empty()) ++PI;
57         if (PI != PEnd) {     // Not unreachable code case?
58           WorkingSet = Doms[*PI];
59
60           // Intersect all of the predecessor sets
61           for (++PI; PI != PEnd; ++PI) {
62             DomSetType &PredSet = Doms[*PI];
63             if (PredSet.size())
64               set_intersect(WorkingSet, PredSet);
65           }
66         }
67       } else {
68         assert(Roots.size() == 1 && BB == Roots[0] &&
69                "We got into unreachable code somehow!");
70       }
71         
72       WorkingSet.insert(BB);           // A block always dominates itself
73       DomSetType &BBSet = Doms[BB];
74       if (BBSet != WorkingSet) {
75         //assert(WorkingSet.size() > BBSet.size() && "Must only grow sets!");
76         BBSet.swap(WorkingSet);        // Constant time operation!
77         Changed = true;                // The sets changed.
78       }
79       WorkingSet.clear();              // Clear out the set for next iteration
80     }
81   } while (Changed);
82 }
83
84
85
86 // runOnFunction - This method calculates the forward dominator sets for the
87 // specified function.
88 //
89 bool DominatorSet::runOnFunction(Function &F) {
90   BasicBlock *Root = &F.getEntryBlock();
91   Roots.clear();
92   Roots.push_back(Root);
93   assert(pred_begin(Root) == pred_end(Root) &&
94          "Root node has predecessors in function!");
95   recalculate();
96   return false;
97 }
98
99 void DominatorSet::recalculate() {
100   assert(Roots.size() == 1 && "DominatorSet should have single root block!");
101   Doms.clear();   // Reset from the last time we were run...
102
103   // Calculate dominator sets for the reachable basic blocks...
104   calculateDominatorsFromBlock(Roots[0]);
105
106
107   // Loop through the function, ensuring that every basic block has at least an
108   // empty set of nodes.  This is important for the case when there is
109   // unreachable blocks.
110   Function *F = Roots[0]->getParent();
111   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) Doms[I];
112 }
113
114
115 static std::ostream &operator<<(std::ostream &o,
116                                 const std::set<BasicBlock*> &BBs) {
117   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
118        I != E; ++I)
119     if (*I)
120       WriteAsOperand(o, *I, false);
121     else
122       o << " <<exit node>>";
123   return o;
124 }
125
126 void DominatorSetBase::print(std::ostream &o) const {
127   for (const_iterator I = begin(), E = end(); I != E; ++I) {
128     o << "  DomSet For BB: ";
129     if (I->first)
130       WriteAsOperand(o, I->first, false);
131     else
132       o << " <<exit node>>";
133     o << " is:\t" << I->second << "\n";
134   }
135 }
136
137 //===----------------------------------------------------------------------===//
138 //  ImmediateDominators Implementation
139 //===----------------------------------------------------------------------===//
140
141 static RegisterAnalysis<ImmediateDominators>
142 C("idom", "Immediate Dominators Construction", true);
143
144 // calcIDoms - Calculate the immediate dominator mapping, given a set of
145 // dominators for every basic block.
146 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
147   // Loop over all of the nodes that have dominators... figuring out the IDOM
148   // for each node...
149   //
150   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end(); 
151        DI != DEnd; ++DI) {
152     BasicBlock *BB = DI->first;
153     const DominatorSet::DomSetType &Dominators = DI->second;
154     unsigned DomSetSize = Dominators.size();
155     if (DomSetSize == 1) continue;  // Root node... IDom = null
156
157     // Loop over all dominators of this node.  This corresponds to looping over
158     // nodes in the dominator chain, looking for a node whose dominator set is
159     // equal to the current nodes, except that the current node does not exist
160     // in it.  This means that it is one level higher in the dom chain than the
161     // current node, and it is our idom!
162     //
163     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
164     DominatorSet::DomSetType::const_iterator End = Dominators.end();
165     for (; I != End; ++I) {   // Iterate over dominators...
166       // All of our dominators should form a chain, where the number of elements
167       // in the dominator set indicates what level the node is at in the chain.
168       // We want the node immediately above us, so it will have an identical 
169       // dominator set, except that BB will not dominate it... therefore it's
170       // dominator set size will be one less than BB's...
171       //
172       if (DS.getDominators(*I).size() == DomSetSize - 1) {
173         IDoms[BB] = *I;
174         break;
175       }
176     }
177   }
178 }
179
180 void ImmediateDominatorsBase::print(std::ostream &o) const {
181   for (const_iterator I = begin(), E = end(); I != E; ++I) {
182     o << "  Immediate Dominator For Basic Block:";
183     if (I->first)
184       WriteAsOperand(o, I->first, false);
185     else
186       o << " <<exit node>>";
187     o << " is:";
188     if (I->second)
189       WriteAsOperand(o, I->second, false);
190     else
191       o << " <<exit node>>";
192     o << "\n";
193   }
194   o << "\n";
195 }
196
197
198 //===----------------------------------------------------------------------===//
199 //  DominatorTree Implementation
200 //===----------------------------------------------------------------------===//
201
202 static RegisterAnalysis<DominatorTree>
203 E("domtree", "Dominator Tree Construction", true);
204
205 // DominatorTreeBase::reset - Free all of the tree node memory.
206 //
207 void DominatorTreeBase::reset() { 
208   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
209     delete I->second;
210   Nodes.clear();
211   RootNode = 0;
212 }
213
214 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
215   assert(IDom && "No immediate dominator?");
216   if (IDom != NewIDom) {
217     std::vector<Node*>::iterator I =
218       std::find(IDom->Children.begin(), IDom->Children.end(), this);
219     assert(I != IDom->Children.end() &&
220            "Not in immediate dominator children set!");
221     // I am no longer your child...
222     IDom->Children.erase(I);
223
224     // Switch to new dominator
225     IDom = NewIDom;
226     IDom->Children.push_back(this);
227   }
228 }
229
230
231
232 void DominatorTree::calculate(const DominatorSet &DS) {
233   assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
234   BasicBlock *Root = Roots[0];
235   Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
236
237   // Iterate over all nodes in depth first order...
238   for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
239        I != E; ++I) {
240     BasicBlock *BB = *I;
241     const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
242     unsigned DomSetSize = Dominators.size();
243     if (DomSetSize == 1) continue;  // Root node... IDom = null
244       
245     // Loop over all dominators of this node. This corresponds to looping over
246     // nodes in the dominator chain, looking for a node whose dominator set is
247     // equal to the current nodes, except that the current node does not exist
248     // in it. This means that it is one level higher in the dom chain than the
249     // current node, and it is our idom!  We know that we have already added
250     // a DominatorTree node for our idom, because the idom must be a
251     // predecessor in the depth first order that we are iterating through the
252     // function.
253     //
254     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
255     DominatorSet::DomSetType::const_iterator End = Dominators.end();
256     for (; I != End; ++I) {   // Iterate over dominators...
257       // All of our dominators should form a chain, where the number of
258       // elements in the dominator set indicates what level the node is at in
259       // the chain.  We want the node immediately above us, so it will have
260       // an identical dominator set, except that BB will not dominate it...
261       // therefore it's dominator set size will be one less than BB's...
262       //
263       if (DS.getDominators(*I).size() == DomSetSize - 1) {
264         // We know that the immediate dominator should already have a node, 
265         // because we are traversing the CFG in depth first order!
266         //
267         Node *IDomNode = Nodes[*I];
268         assert(IDomNode && "No node for IDOM?");
269         
270         // Add a new tree node for this BasicBlock, and link it as a child of
271         // IDomNode
272         Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
273         break;
274       }
275     }
276   }
277 }
278
279
280 static std::ostream &operator<<(std::ostream &o,
281                                 const DominatorTreeBase::Node *Node) {
282   if (Node->getBlock())
283     WriteAsOperand(o, Node->getBlock(), false);
284   else
285     o << " <<exit node>>";
286   return o << "\n";
287 }
288
289 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
290                          unsigned Lev) {
291   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
292   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
293        I != E; ++I)
294     PrintDomTree(*I, o, Lev+1);
295 }
296
297 void DominatorTreeBase::print(std::ostream &o) const {
298   o << "=============================--------------------------------\n"
299     << "Inorder Dominator Tree:\n";
300   PrintDomTree(getRootNode(), o, 1);
301 }
302
303
304 //===----------------------------------------------------------------------===//
305 //  DominanceFrontier Implementation
306 //===----------------------------------------------------------------------===//
307
308 static RegisterAnalysis<DominanceFrontier>
309 G("domfrontier", "Dominance Frontier Construction", true);
310
311 const DominanceFrontier::DomSetType &
312 DominanceFrontier::calculate(const DominatorTree &DT, 
313                              const DominatorTree::Node *Node) {
314   // Loop over CFG successors to calculate DFlocal[Node]
315   BasicBlock *BB = Node->getBlock();
316   DomSetType &S = Frontiers[BB];       // The new set to fill in...
317
318   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
319        SI != SE; ++SI) {
320     // Does Node immediately dominate this successor?
321     if (DT[*SI]->getIDom() != Node)
322       S.insert(*SI);
323   }
324
325   // At this point, S is DFlocal.  Now we union in DFup's of our children...
326   // Loop through and visit the nodes that Node immediately dominates (Node's
327   // children in the IDomTree)
328   //
329   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
330        NI != NE; ++NI) {
331     DominatorTree::Node *IDominee = *NI;
332     const DomSetType &ChildDF = calculate(DT, IDominee);
333
334     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
335     for (; CDFI != CDFE; ++CDFI) {
336       if (!Node->dominates(DT[*CDFI]))
337         S.insert(*CDFI);
338     }
339   }
340
341   return S;
342 }
343
344 void DominanceFrontierBase::print(std::ostream &o) const {
345   for (const_iterator I = begin(), E = end(); I != E; ++I) {
346     o << "  DomFrontier for BB";
347     if (I->first)
348       WriteAsOperand(o, I->first, false);
349     else
350       o << " <<exit node>>";
351     o << " is:\t" << I->second << "\n";
352   }
353 }