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