Allocation insts always have one operand
[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       }
65         
66       WorkingSet.insert(BB);           // A block always dominates itself
67       DomSetType &BBSet = Doms[BB];
68       if (BBSet != WorkingSet) {
69         BBSet.swap(WorkingSet);        // Constant time operation!
70         Changed = true;                // The sets changed.
71       }
72       WorkingSet.clear();              // Clear out the set for next iteration
73     }
74   } while (Changed);
75 }
76
77
78
79 // runOnFunction - This method calculates the forward dominator sets for the
80 // specified function.
81 //
82 bool DominatorSet::runOnFunction(Function &F) {
83   Doms.clear();   // Reset from the last time we were run...
84   Root = &F.getEntryNode();
85   assert(pred_begin(Root) == pred_end(Root) &&
86          "Root node has predecessors in function!");
87
88   // Calculate dominator sets for the reachable basic blocks...
89   calculateDominatorsFromBlock(Root);
90
91   // Every basic block in the function should at least dominate themselves, and
92   // thus every basic block should have an entry in Doms.  The one case where we
93   // miss this is when a basic block is unreachable.  To get these we now do an
94   // extra pass over the function, calculating dominator information for
95   // unreachable blocks.
96   //
97   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
98     if (Doms[I].empty()) {
99       calculateDominatorsFromBlock(I);
100     }
101
102   return false;
103 }
104
105
106 static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
107   for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
108        I != E; ++I) {
109     o << "  ";
110     WriteAsOperand(o, *I, false);
111     o << "\n";
112    }
113   return o;
114 }
115
116 void DominatorSetBase::print(std::ostream &o) const {
117   for (const_iterator I = begin(), E = end(); I != E; ++I)
118     o << "=============================--------------------------------\n"
119       << "\nDominator Set For Basic Block\n" << I->first
120       << "-------------------------------\n" << I->second << "\n";
121 }
122
123 //===----------------------------------------------------------------------===//
124 //  ImmediateDominators Implementation
125 //===----------------------------------------------------------------------===//
126
127 static RegisterAnalysis<ImmediateDominators>
128 C("idom", "Immediate Dominators Construction", true);
129
130 // calcIDoms - Calculate the immediate dominator mapping, given a set of
131 // dominators for every basic block.
132 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
133   // Loop over all of the nodes that have dominators... figuring out the IDOM
134   // for each node...
135   //
136   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end(); 
137        DI != DEnd; ++DI) {
138     BasicBlock *BB = DI->first;
139     const DominatorSet::DomSetType &Dominators = DI->second;
140     unsigned DomSetSize = Dominators.size();
141     if (DomSetSize == 1) continue;  // Root node... IDom = null
142
143     // Loop over all dominators of this node.  This corresponds to looping over
144     // nodes in the dominator chain, looking for a node whose dominator set is
145     // equal to the current nodes, except that the current node does not exist
146     // in it.  This means that it is one level higher in the dom chain than the
147     // current node, and it is our idom!
148     //
149     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
150     DominatorSet::DomSetType::const_iterator End = Dominators.end();
151     for (; I != End; ++I) {   // Iterate over dominators...
152       // All of our dominators should form a chain, where the number of elements
153       // in the dominator set indicates what level the node is at in the chain.
154       // We want the node immediately above us, so it will have an identical 
155       // dominator set, except that BB will not dominate it... therefore it's
156       // dominator set size will be one less than BB's...
157       //
158       if (DS.getDominators(*I).size() == DomSetSize - 1) {
159         IDoms[BB] = *I;
160         break;
161       }
162     }
163   }
164 }
165
166 void ImmediateDominatorsBase::print(std::ostream &o) const {
167   for (const_iterator I = begin(), E = end(); I != E; ++I)
168     o << "=============================--------------------------------\n"
169       << "\nImmediate Dominator For Basic Block\n" << *I->first
170       << "is: \n" << *I->second << "\n";
171 }
172
173
174 //===----------------------------------------------------------------------===//
175 //  DominatorTree Implementation
176 //===----------------------------------------------------------------------===//
177
178 static RegisterAnalysis<DominatorTree>
179 E("domtree", "Dominator Tree Construction", true);
180
181 // DominatorTreeBase::reset - Free all of the tree node memory.
182 //
183 void DominatorTreeBase::reset() { 
184   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
185     delete I->second;
186   Nodes.clear();
187 }
188
189
190 void DominatorTree::calculate(const DominatorSet &DS) {
191   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
192
193   // Iterate over all nodes in depth first order...
194   for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
195        I != E; ++I) {
196     BasicBlock *BB = *I;
197     const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
198     unsigned DomSetSize = Dominators.size();
199     if (DomSetSize == 1) continue;  // Root node... IDom = null
200       
201     // Loop over all dominators of this node. This corresponds to looping over
202     // nodes in the dominator chain, looking for a node whose dominator set is
203     // equal to the current nodes, except that the current node does not exist
204     // in it. This means that it is one level higher in the dom chain than the
205     // current node, and it is our idom!  We know that we have already added
206     // a DominatorTree node for our idom, because the idom must be a
207     // predecessor in the depth first order that we are iterating through the
208     // function.
209     //
210     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
211     DominatorSet::DomSetType::const_iterator End = Dominators.end();
212     for (; I != End; ++I) {   // Iterate over dominators...
213       // All of our dominators should form a chain, where the number of
214       // elements in the dominator set indicates what level the node is at in
215       // the chain.  We want the node immediately above us, so it will have
216       // an identical dominator set, except that BB will not dominate it...
217       // therefore it's dominator set size will be one less than BB's...
218       //
219       if (DS.getDominators(*I).size() == DomSetSize - 1) {
220         // We know that the immediate dominator should already have a node, 
221         // because we are traversing the CFG in depth first order!
222         //
223         Node *IDomNode = Nodes[*I];
224         assert(IDomNode && "No node for IDOM?");
225         
226         // Add a new tree node for this BasicBlock, and link it as a child of
227         // IDomNode
228         Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
229         break;
230       }
231     }
232   }
233 }
234
235
236 static std::ostream &operator<<(std::ostream &o,
237                                 const DominatorTreeBase::Node *Node) {
238   return o << Node->getNode()
239            << "\n------------------------------------------\n";
240 }
241
242 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
243                          unsigned Lev) {
244   o << "Level #" << Lev << ":  " << N;
245   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end(); 
246        I != E; ++I) {
247     PrintDomTree(*I, o, Lev+1);
248   }
249 }
250
251 void DominatorTreeBase::print(std::ostream &o) const {
252   o << "=============================--------------------------------\n"
253     << "Inorder Dominator Tree:\n";
254   PrintDomTree(Nodes.find(getRoot())->second, o, 1);
255 }
256
257
258 //===----------------------------------------------------------------------===//
259 //  DominanceFrontier Implementation
260 //===----------------------------------------------------------------------===//
261
262 static RegisterAnalysis<DominanceFrontier>
263 G("domfrontier", "Dominance Frontier Construction", true);
264
265 const DominanceFrontier::DomSetType &
266 DominanceFrontier::calculate(const DominatorTree &DT, 
267                              const DominatorTree::Node *Node) {
268   // Loop over CFG successors to calculate DFlocal[Node]
269   BasicBlock *BB = Node->getNode();
270   DomSetType &S = Frontiers[BB];       // The new set to fill in...
271
272   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
273        SI != SE; ++SI) {
274     // Does Node immediately dominate this successor?
275     if (DT[*SI]->getIDom() != Node)
276       S.insert(*SI);
277   }
278
279   // At this point, S is DFlocal.  Now we union in DFup's of our children...
280   // Loop through and visit the nodes that Node immediately dominates (Node's
281   // children in the IDomTree)
282   //
283   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
284        NI != NE; ++NI) {
285     DominatorTree::Node *IDominee = *NI;
286     const DomSetType &ChildDF = calculate(DT, IDominee);
287
288     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
289     for (; CDFI != CDFE; ++CDFI) {
290       if (!Node->dominates(DT[*CDFI]))
291         S.insert(*CDFI);
292     }
293   }
294
295   return S;
296 }
297
298 void DominanceFrontierBase::print(std::ostream &o) const {
299   for (const_iterator I = begin(), E = end(); I != E; ++I) {
300     o << "=============================--------------------------------\n"
301       << "\nDominance Frontier For Basic Block\n";
302     WriteAsOperand(o, I->first, false);
303     o << " is: \n" << I->second << "\n";
304   }
305 }