Removed unneeded <iostream> #include.
[oota-llvm.git] / lib / Analysis / PostDominators.cpp
1 //===- PostDominators.cpp - Post-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 the post-dominator construction algorithms.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/PostDominators.h"
15 #include "llvm/Instructions.h"
16 #include "llvm/Support/CFG.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/SetOperations.h"
19 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 //  ImmediatePostDominators Implementation
23 //===----------------------------------------------------------------------===//
24
25 static RegisterPass<ImmediatePostDominators>
26 D("postidom", "Immediate Post-Dominators Construction", true);
27
28 unsigned ImmediatePostDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
29                                           unsigned N) {
30   std::vector<std::pair<BasicBlock *, InfoRec *> > workStack;
31   std::set<BasicBlock *> visited;
32   workStack.push_back(std::make_pair(V, &VInfo));
33
34   do {
35     BasicBlock *currentBB = workStack.back().first; 
36     InfoRec *currentVInfo = workStack.back().second;
37
38     // Visit each block only once.
39     if (visited.count(currentBB) == 0) {
40
41       visited.insert(currentBB);
42       currentVInfo->Semi = ++N;
43       currentVInfo->Label = currentBB;
44       
45       Vertex.push_back(currentBB);  // Vertex[n] = current;
46       // Info[currentBB].Ancestor = 0;     
47       // Ancestor[n] = 0
48       // Child[currentBB] = 0;
49       currentVInfo->Size = 1;       // Size[currentBB] = 1
50     }
51
52     // Visit children
53     bool visitChild = false;
54     for (pred_iterator PI = pred_begin(currentBB), PE = pred_end(currentBB); 
55          PI != PE && !visitChild; ++PI) {
56       InfoRec &SuccVInfo = Info[*PI];
57       if (SuccVInfo.Semi == 0) {
58         SuccVInfo.Parent = currentBB;
59         if (visited.count (*PI) == 0) {
60           workStack.push_back(std::make_pair(*PI, &SuccVInfo));   
61           visitChild = true;
62         }
63       }
64     }
65
66     // If all children are visited or if this block has no child then pop this
67     // block out of workStack.
68     if (!visitChild)
69       workStack.pop_back();
70
71   } while (!workStack.empty());
72
73   return N;
74 }
75
76 void ImmediatePostDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
77   BasicBlock *VAncestor = VInfo.Ancestor;
78   InfoRec &VAInfo = Info[VAncestor];
79   if (VAInfo.Ancestor == 0)
80     return;
81   
82   Compress(VAncestor, VAInfo);
83   
84   BasicBlock *VAncestorLabel = VAInfo.Label;
85   BasicBlock *VLabel = VInfo.Label;
86   if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
87     VInfo.Label = VAncestorLabel;
88   
89   VInfo.Ancestor = VAInfo.Ancestor;
90 }
91
92 BasicBlock *ImmediatePostDominators::Eval(BasicBlock *V) {
93   InfoRec &VInfo = Info[V];
94
95   // Higher-complexity but faster implementation
96   if (VInfo.Ancestor == 0)
97     return V;
98   Compress(V, VInfo);
99   return VInfo.Label;
100 }
101
102 void ImmediatePostDominators::Link(BasicBlock *V, BasicBlock *W, 
103                                    InfoRec &WInfo) {
104   // Higher-complexity but faster implementation
105   WInfo.Ancestor = V;
106 }
107
108 bool ImmediatePostDominators::runOnFunction(Function &F) {
109   IDoms.clear();     // Reset from the last time we were run...
110   Roots.clear();
111
112   // Step #0: Scan the function looking for the root nodes of the post-dominance
113   // relationships.  These blocks, which have no successors, end with return and
114   // unwind instructions.
115   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
116     if (succ_begin(I) == succ_end(I))
117       Roots.push_back(I);
118   
119   Vertex.push_back(0);
120   
121   // Step #1: Number blocks in depth-first order and initialize variables used
122   // in later stages of the algorithm.
123   unsigned N = 0;
124   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
125     N = DFSPass(Roots[i], Info[Roots[i]], N);
126   
127   for (unsigned i = N; i >= 2; --i) {
128     BasicBlock *W = Vertex[i];
129     InfoRec &WInfo = Info[W];
130     
131     // Step #2: Calculate the semidominators of all vertices
132     for (succ_iterator SI = succ_begin(W), SE = succ_end(W); SI != SE; ++SI)
133       if (Info.count(*SI)) {  // Only if this predecessor is reachable!
134         unsigned SemiU = Info[Eval(*SI)].Semi;
135         if (SemiU < WInfo.Semi)
136           WInfo.Semi = SemiU;
137       }
138         
139     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
140     
141     BasicBlock *WParent = WInfo.Parent;
142     Link(WParent, W, WInfo);
143     
144     // Step #3: Implicitly define the immediate dominator of vertices
145     std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
146     while (!WParentBucket.empty()) {
147       BasicBlock *V = WParentBucket.back();
148       WParentBucket.pop_back();
149       BasicBlock *U = Eval(V);
150       IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
151     }
152   }
153   
154   // Step #4: Explicitly define the immediate dominator of each vertex
155   for (unsigned i = 2; i <= N; ++i) {
156     BasicBlock *W = Vertex[i];
157     BasicBlock *&WIDom = IDoms[W];
158     if (WIDom != Vertex[Info[W].Semi])
159       WIDom = IDoms[WIDom];
160   }
161   
162   // Free temporary memory used to construct idom's
163   Info.clear();
164   std::vector<BasicBlock*>().swap(Vertex);
165   
166   return false;
167 }
168
169 //===----------------------------------------------------------------------===//
170 //  PostDominatorSet Implementation
171 //===----------------------------------------------------------------------===//
172
173 static RegisterPass<PostDominatorSet>
174 B("postdomset", "Post-Dominator Set Construction", true);
175
176 // Postdominator set construction.  This converts the specified function to only
177 // have a single exit node (return stmt), then calculates the post dominance
178 // sets for the function.
179 //
180 bool PostDominatorSet::runOnFunction(Function &F) {
181   // Scan the function looking for the root nodes of the post-dominance
182   // relationships.  These blocks end with return and unwind instructions.
183   // While we are iterating over the function, we also initialize all of the
184   // domsets to empty.
185   Roots.clear();
186   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
187     if (succ_begin(I) == succ_end(I))
188       Roots.push_back(I);
189
190   // If there are no exit nodes for the function, postdomsets are all empty.
191   // This can happen if the function just contains an infinite loop, for
192   // example.
193   ImmediatePostDominators &IPD = getAnalysis<ImmediatePostDominators>();
194   Doms.clear();   // Reset from the last time we were run...
195   if (Roots.empty()) return false;
196
197   // If we have more than one root, we insert an artificial "null" exit, which
198   // has "virtual edges" to each of the real exit nodes.
199   //if (Roots.size() > 1)
200   //  Doms[0].insert(0);
201
202   // Root nodes only dominate themselves.
203   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
204     Doms[Roots[i]].insert(Roots[i]);
205   
206   // Loop over all of the blocks in the function, calculating dominator sets for
207   // each function.
208   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
209     if (BasicBlock *IPDom = IPD[I]) {   // Get idom if block is reachable
210       DomSetType &DS = Doms[I];
211       assert(DS.empty() && "PostDomset already filled in for this block?");
212       DS.insert(I);  // Blocks always dominate themselves
213
214       // Insert all dominators into the set...
215       while (IPDom) {
216         // If we have already computed the dominator sets for our immediate post
217         // dominator, just use it instead of walking all the way up to the root.
218         DomSetType &IPDS = Doms[IPDom];
219         if (!IPDS.empty()) {
220           DS.insert(IPDS.begin(), IPDS.end());
221           break;
222         } else {
223           DS.insert(IPDom);
224           IPDom = IPD[IPDom];
225         }
226       }
227     } else {
228       // Ensure that every basic block has at least an empty set of nodes.  This
229       // is important for the case when there is unreachable blocks.
230       Doms[I];
231     }
232
233   return false;
234 }
235
236 //===----------------------------------------------------------------------===//
237 //  PostDominatorTree Implementation
238 //===----------------------------------------------------------------------===//
239
240 static RegisterPass<PostDominatorTree>
241 F("postdomtree", "Post-Dominator Tree Construction", true);
242
243 DominatorTreeBase::Node *PostDominatorTree::getNodeForBlock(BasicBlock *BB) {
244   Node *&BBNode = Nodes[BB];
245   if (BBNode) return BBNode;
246   
247   // Haven't calculated this node yet?  Get or calculate the node for the
248   // immediate postdominator.
249   BasicBlock *IPDom = getAnalysis<ImmediatePostDominators>()[BB];
250   Node *IPDomNode = getNodeForBlock(IPDom);
251   
252   // Add a new tree node for this BasicBlock, and link it as a child of
253   // IDomNode
254   return BBNode = IPDomNode->addChild(new Node(BB, IPDomNode));
255 }
256
257 void PostDominatorTree::calculate(const ImmediatePostDominators &IPD) {
258   if (Roots.empty()) return;
259
260   // Add a node for the root.  This node might be the actual root, if there is
261   // one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
262   // which postdominates all real exits if there are multiple exit blocks.
263   BasicBlock *Root = Roots.size() == 1 ? Roots[0] : 0;
264   Nodes[Root] = RootNode = new Node(Root, 0);
265   
266   Function *F = Roots[0]->getParent();
267   // Loop over all of the reachable blocks in the function...
268   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
269     if (BasicBlock *ImmPostDom = IPD.get(I)) {  // Reachable block.
270       Node *&BBNode = Nodes[I];
271       if (!BBNode) {  // Haven't calculated this node yet?
272                       // Get or calculate the node for the immediate dominator
273         Node *IPDomNode = getNodeForBlock(ImmPostDom);
274         
275         // Add a new tree node for this BasicBlock, and link it as a child of
276         // IDomNode
277         BBNode = IPDomNode->addChild(new Node(I, IPDomNode));
278       }
279     }
280 }
281
282 //===----------------------------------------------------------------------===//
283 // PostETForest Implementation
284 //===----------------------------------------------------------------------===//
285
286 static RegisterPass<PostETForest>
287 G("postetforest", "Post-ET-Forest Construction", true);
288
289 ETNode *PostETForest::getNodeForBlock(BasicBlock *BB) {
290   ETNode *&BBNode = Nodes[BB];
291   if (BBNode) return BBNode;
292
293   // Haven't calculated this node yet?  Get or calculate the node for the
294   // immediate dominator.
295   BasicBlock *IDom = getAnalysis<ImmediatePostDominators>()[BB];
296
297   // If we are unreachable, we may not have an immediate dominator.
298   if (!IDom)
299     return BBNode = new ETNode(BB);
300   else {
301     ETNode *IDomNode = getNodeForBlock(IDom);
302     
303     // Add a new tree node for this BasicBlock, and link it as a child of
304     // IDomNode
305     BBNode = new ETNode(BB);
306     BBNode->setFather(IDomNode);
307     return BBNode;
308   }
309 }
310
311 void PostETForest::calculate(const ImmediatePostDominators &ID) {
312   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
313     Nodes[Roots[i]] = new ETNode(Roots[i]); // Add a node for the root
314
315   // Iterate over all nodes in inverse depth first order.
316   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
317     for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
318            E = idf_end(Roots[i]); I != E; ++I) {
319     BasicBlock *BB = *I;
320     ETNode *&BBNode = Nodes[BB];
321     if (!BBNode) {  
322       ETNode *IDomNode =  NULL;
323
324       if (ID.get(BB))
325         IDomNode = getNodeForBlock(ID.get(BB));
326
327       // Add a new ETNode for this BasicBlock, and set it's parent
328       // to it's immediate dominator.
329       BBNode = new ETNode(BB);
330       if (IDomNode)          
331         BBNode->setFather(IDomNode);
332     }
333   }
334
335   int dfsnum = 0;
336   // Iterate over all nodes in depth first order...
337   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
338     for (idf_iterator<BasicBlock*> I = idf_begin(Roots[i]),
339            E = idf_end(Roots[i]); I != E; ++I) {
340         if (!getNodeForBlock(*I)->hasFather())
341           getNodeForBlock(*I)->assignDFSNumber(dfsnum);
342     }
343   DFSInfoValid = true;
344 }
345
346 //===----------------------------------------------------------------------===//
347 //  PostDominanceFrontier Implementation
348 //===----------------------------------------------------------------------===//
349
350 static RegisterPass<PostDominanceFrontier>
351 H("postdomfrontier", "Post-Dominance Frontier Construction", true);
352
353 const DominanceFrontier::DomSetType &
354 PostDominanceFrontier::calculate(const PostDominatorTree &DT,
355                                  const DominatorTree::Node *Node) {
356   // Loop over CFG successors to calculate DFlocal[Node]
357   BasicBlock *BB = Node->getBlock();
358   DomSetType &S = Frontiers[BB];       // The new set to fill in...
359   if (getRoots().empty()) return S;
360
361   if (BB)
362     for (pred_iterator SI = pred_begin(BB), SE = pred_end(BB);
363          SI != SE; ++SI)
364       // Does Node immediately dominate this predecessor?
365       if (DT[*SI]->getIDom() != Node)
366         S.insert(*SI);
367
368   // At this point, S is DFlocal.  Now we union in DFup's of our children...
369   // Loop through and visit the nodes that Node immediately dominates (Node's
370   // children in the IDomTree)
371   //
372   for (PostDominatorTree::Node::const_iterator
373          NI = Node->begin(), NE = Node->end(); NI != NE; ++NI) {
374     DominatorTree::Node *IDominee = *NI;
375     const DomSetType &ChildDF = calculate(DT, IDominee);
376
377     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
378     for (; CDFI != CDFE; ++CDFI) {
379       if (!Node->properlyDominates(DT[*CDFI]))
380         S.insert(*CDFI);
381     }
382   }
383
384   return S;
385 }
386
387 // Ensure that this .cpp file gets linked when PostDominators.h is used.
388 DEFINING_FILE_FOR(PostDominanceFrontier)