1 //===- DominatorSet.cpp - Dominator Set Calculation --------------*- C++ -*--=//
2 //
3 // This file provides a simple class to calculate the dominator set of a method.
4 //
5 //===----------------------------------------------------------------------===//
6 
7 #include "llvm/Analysis/Dominators.h"
8 #include "llvm/Analysis/SimplifyCFG.h"   // To get cfg::UnifyAllExitNodes
9 #include "llvm/CFG.h"
10 #include "llvm/Tools/STLExtras.h"
11 #include <algorithm>
12 
13 //===----------------------------------------------------------------------===//
14 //  Helper Template
15 //===----------------------------------------------------------------------===//
16 
17 // set_intersect - Identical to set_intersection, except that it works on
18 // set<>'s and is nicer to use.  Functionally, this iterates through S1,
19 // removing elements that are not contained in S2.
20 //
21 template <class Ty, class Ty2>
22 void set_intersect(set<Ty> &S1, const set<Ty2> &S2) {
23   for (typename set<Ty>::iterator I = S1.begin(); I != S1.end();) {
24     const Ty &E = *I;
25     ++I;
26     if (!S2.count(E)) S1.erase(E);   // Erase element if not in S2
27   }
28 }
29 
30 //===----------------------------------------------------------------------===//
31 //  DominatorBase Implementation
32 //===----------------------------------------------------------------------===//
33 
34 bool cfg::DominatorBase::isPostDominator() const {
35   return Root != Root->getParent()->front();
36 }
37 
38 
39 //===----------------------------------------------------------------------===//
40 //  DominatorSet Implementation
41 //===----------------------------------------------------------------------===//
42 
43 // DominatorSet ctor - Build either the dominator set or the post-dominator
44 // set for a method...
45 //
46 cfg::DominatorSet::DominatorSet(const Method *M) : DominatorBase(M->front()) {
47   calcForwardDominatorSet(M);
48 }
49 
50 // calcForwardDominatorSet - This method calculates the forward dominator sets
51 // for the specified method.
52 //
53 void cfg::DominatorSet::calcForwardDominatorSet(const Method *M) {
54   assert(Root && M && "Can't build dominator set of null method!");
55   bool Changed;
56   do {
57     Changed = false;
58 
59     DomSetType WorkingSet;
60     df_const_iterator It = df_begin(M), End = df_end(M);
61     for ( ; It != End; ++It) {
62       const BasicBlock *BB = *It;
63       pred_const_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
64       if (PI != PEnd) {                // Is there SOME predecessor?
65 	// Loop until we get to a predecessor that has had it's dom set filled
66 	// in at least once.  We are guaranteed to have this because we are
67 	// traversing the graph in DFO and have handled start nodes specially.
68 	//
69 	while (Doms[*PI].size() == 0) ++PI;
70 	WorkingSet = Doms[*PI];
71 
72 	for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
73 	  DomSetType &PredSet = Doms[*PI];
74 	  if (PredSet.size())
75 	    set_intersect(WorkingSet, PredSet);
76 	}
77       }
78 
79       WorkingSet.insert(BB);           // A block always dominates itself
80       DomSetType &BBSet = Doms[BB];
81       if (BBSet != WorkingSet) {
82 	BBSet.swap(WorkingSet);        // Constant time operation!
83 	Changed = true;                // The sets changed.
84       }
85       WorkingSet.clear();              // Clear out the set for next iteration
86     }
87   } while (Changed);
88 }
89 
90 // Postdominator set constructor.  This ctor converts the specified method to
91 // only have a single exit node (return stmt), then calculates the post
92 // dominance sets for the method.
93 //
94 cfg::DominatorSet::DominatorSet(Method *M, bool PostDomSet)
95   : DominatorBase(M->front()) {
96   if (!PostDomSet) { calcForwardDominatorSet(M); return; }
97 
98   Root = cfg::UnifyAllExitNodes(M);
99   assert(Root && "TODO: Don't handle case where there are no exit nodes yet!");
100 
101   bool Changed;
102   do {
103     Changed = false;
104 
105     set<const BasicBlock*> Visited;
106     DomSetType WorkingSet;
107     idf_const_iterator It = idf_begin(Root), End = idf_end(Root);
108     for ( ; It != End; ++It) {
109       const BasicBlock *BB = *It;
110       succ_const_iterator PI = succ_begin(BB), PEnd = succ_end(BB);
111       if (PI != PEnd) {                // Is there SOME predecessor?
112 	// Loop until we get to a successor that has had it's dom set filled
113 	// in at least once.  We are guaranteed to have this because we are
114 	// traversing the graph in DFO and have handled start nodes specially.
115 	//
116 	while (Doms[*PI].size() == 0) ++PI;
117 	WorkingSet = Doms[*PI];
118 
119 	for (++PI; PI != PEnd; ++PI) { // Intersect all of the successor sets
120 	  DomSetType &PredSet = Doms[*PI];
121 	  if (PredSet.size())
122 	    set_intersect(WorkingSet, PredSet);
123 	}
124       }
125 
126       WorkingSet.insert(BB);           // A block always dominates itself
127       DomSetType &BBSet = Doms[BB];
128       if (BBSet != WorkingSet) {
129 	BBSet.swap(WorkingSet);        // Constant time operation!
130 	Changed = true;                // The sets changed.
131       }
132       WorkingSet.clear();              // Clear out the set for next iteration
133     }
134   } while (Changed);
135 }
136 
137 
138 //===----------------------------------------------------------------------===//
139 //  ImmediateDominators Implementation
140 //===----------------------------------------------------------------------===//
141 
142 // calcIDoms - Calculate the immediate dominator mapping, given a set of
143 // dominators for every basic block.
144 void cfg::ImmediateDominators::calcIDoms(const DominatorSet &DS) {
145   // Loop over all of the nodes that have dominators... figuring out the IDOM
146   // for each node...
147   //
148   for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
149        DI != DEnd; ++DI) {
150     const BasicBlock *BB = DI->first;
151     const DominatorSet::DomSetType &Dominators = DI->second;
152     unsigned DomSetSize = Dominators.size();
153     if (DomSetSize == 1) continue;  // Root node... IDom = null
154 
155     // Loop over all dominators of this node.  This corresponds to looping over
156     // nodes in the dominator chain, looking for a node whose dominator set is
157     // equal to the current nodes, except that the current node does not exist
158     // in it.  This means that it is one level higher in the dom chain than the
159     // current node, and it is our idom!
160     //
161     DominatorSet::DomSetType::const_iterator I = Dominators.begin();
162     DominatorSet::DomSetType::const_iterator End = Dominators.end();
163     for (; I != End; ++I) {   // Iterate over dominators...
164       // All of our dominators should form a chain, where the number of elements
165       // in the dominator set indicates what level the node is at in the chain.
166       // We want the node immediately above us, so it will have an identical
167       // dominator set, except that BB will not dominate it... therefore it's
168       // dominator set size will be one less than BB's...
169       //
170       if (DS.getDominators(*I).size() == DomSetSize - 1) {
171 	IDoms[BB] = *I;
172 	break;
173       }
174     }
175   }
176 }
177 
178 
179 //===----------------------------------------------------------------------===//
180 //  DominatorTree Implementation
181 //===----------------------------------------------------------------------===//
182 
183 // DominatorTree dtor - Free all of the tree node memory.
184 //
185 cfg::DominatorTree::~DominatorTree() {
186   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
187     delete I->second;
188 }
189 
190 
191 cfg::DominatorTree::DominatorTree(const ImmediateDominators &IDoms)
192   : DominatorBase(IDoms.getRoot()) {
193   const Method *M = Root->getParent();
194 
195   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
196 
197   // Iterate over all nodes in depth first order...
198   for (df_const_iterator I = df_begin(M), E = df_end(M); I != E; ++I) {
199     const BasicBlock *BB = *I, *IDom = IDoms[*I];
200 
201     if (IDom != 0) {   // Ignore the root node and other nasty nodes
202       // We know that the immediate dominator should already have a node,
203       // because we are traversing the CFG in depth first order!
204       //
205       assert(Nodes[IDom] && "No node for IDOM?");
206       Node *IDomNode = Nodes[IDom];
207 
208       // Add a new tree node for this BasicBlock, and link it as a child of
209       // IDomNode
210       Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
211     }
212   }
213 }
214 
215 void cfg::DominatorTree::calculate(const DominatorSet &DS) {
216   Nodes[Root] = new Node(Root, 0);   // Add a node for the root...
217 
218   if (!isPostDominator()) {
219     // Iterate over all nodes in depth first order...
220     for (df_const_iterator I = df_begin(Root), E = df_end(Root); I != E; ++I) {
221       const BasicBlock *BB = *I;
222       const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
223       unsigned DomSetSize = Dominators.size();
224       if (DomSetSize == 1) continue;  // Root node... IDom = null
225 
226       // Loop over all dominators of this node.  This corresponds to looping over
227       // nodes in the dominator chain, looking for a node whose dominator set is
228       // equal to the current nodes, except that the current node does not exist
229       // in it.  This means that it is one level higher in the dom chain than the
230       // current node, and it is our idom!  We know that we have already added
231       // a DominatorTree node for our idom, because the idom must be a
232       // predecessor in the depth first order that we are iterating through the
233       // method.
234       //
235       DominatorSet::DomSetType::const_iterator I = Dominators.begin();
236       DominatorSet::DomSetType::const_iterator End = Dominators.end();
237       for (; I != End; ++I) {   // Iterate over dominators...
238 	// All of our dominators should form a chain, where the number of elements
239 	// in the dominator set indicates what level the node is at in the chain.
240 	// We want the node immediately above us, so it will have an identical
241 	// dominator set, except that BB will not dominate it... therefore it's
242 	// dominator set size will be one less than BB's...
243 	//
244 	if (DS.getDominators(*I).size() == DomSetSize - 1) {
245 	  // We know that the immediate dominator should already have a node,
246 	  // because we are traversing the CFG in depth first order!
247 	  //
248 	  Node *IDomNode = Nodes[*I];
249 	  assert(IDomNode && "No node for IDOM?");
250 
251 	  // Add a new tree node for this BasicBlock, and link it as a child of
252 	  // IDomNode
253 	  Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
254 	  break;
255 	}
256       }
257     }
258   } else {
259     // Iterate over all nodes in depth first order...
260     for (idf_const_iterator I = idf_begin(Root), E = idf_end(Root); I != E; ++I) {
261       const BasicBlock *BB = *I;
262       const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
263       unsigned DomSetSize = Dominators.size();
264       if (DomSetSize == 1) continue;  // Root node... IDom = null
265 
266       // Loop over all dominators of this node.  This corresponds to looping over
267       // nodes in the dominator chain, looking for a node whose dominator set is
268       // equal to the current nodes, except that the current node does not exist
269       // in it.  This means that it is one level higher in the dom chain than the
270       // current node, and it is our idom!  We know that we have already added
271       // a DominatorTree node for our idom, because the idom must be a
272       // predecessor in the depth first order that we are iterating through the
273       // method.
274       //
275       DominatorSet::DomSetType::const_iterator I = Dominators.begin();
276       DominatorSet::DomSetType::const_iterator End = Dominators.end();
277       for (; I != End; ++I) {   // Iterate over dominators...
278 	// All of our dominators should form a chain, where the number of elements
279 	// in the dominator set indicates what level the node is at in the chain.
280 	// We want the node immediately above us, so it will have an identical
281 	// dominator set, except that BB will not dominate it... therefore it's
282 	// dominator set size will be one less than BB's...
283 	//
284 	if (DS.getDominators(*I).size() == DomSetSize - 1) {
285 	  // We know that the immediate dominator should already have a node,
286 	  // because we are traversing the CFG in depth first order!
287 	  //
288 	  Node *IDomNode = Nodes[*I];
289 	  assert(IDomNode && "No node for IDOM?");
290 
291 	  // Add a new tree node for this BasicBlock, and link it as a child of
292 	  // IDomNode
293 	  Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
294 	  break;
295 	}
296       }
297     }
298   }
299 }
300 
301 
302 
303 //===----------------------------------------------------------------------===//
304 //  DominanceFrontier Implementation
305 //===----------------------------------------------------------------------===//
306 
307 const cfg::DominanceFrontier::DomSetType &
308 cfg::DominanceFrontier::calcDomFrontier(const DominatorTree &DT,
309 					const DominatorTree::Node *Node) {
310   // Loop over CFG successors to calculate DFlocal[Node]
311   const BasicBlock *BB = Node->getNode();
312   DomSetType &S = Frontiers[BB];       // The new set to fill in...
313 
314   for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
315        SI != SE; ++SI) {
316     // Does Node immediately dominate this successor?
317     if (DT[*SI]->getIDom() != Node)
318       S.insert(*SI);
319   }
320 
321   // At this point, S is DFlocal.  Now we union in DFup's of our children...
322   // Loop through and visit the nodes that Node immediately dominates (Node's
323   // children in the IDomTree)
324   //
325   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
326        NI != NE; ++NI) {
327     DominatorTree::Node *IDominee = *NI;
328     const DomSetType &ChildDF = calcDomFrontier(DT, IDominee);
329 
330     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
331     for (; CDFI != CDFE; ++CDFI) {
332       if (!Node->dominates(DT[*CDFI]))
333 	S.insert(*CDFI);
334     }
335   }
336 
337   return S;
338 }
339 
340 const cfg::DominanceFrontier::DomSetType &
341 cfg::DominanceFrontier::calcPostDomFrontier(const DominatorTree &DT,
342 					    const DominatorTree::Node *Node) {
343   // Loop over CFG successors to calculate DFlocal[Node]
344   const BasicBlock *BB = Node->getNode();
345   DomSetType &S = Frontiers[BB];       // The new set to fill in...
346 
347   for (pred_const_iterator SI = pred_begin(BB), SE = pred_end(BB);
348        SI != SE; ++SI) {
349     // Does Node immediately dominate this predeccessor?
350     if (DT[*SI]->getIDom() != Node)
351       S.insert(*SI);
352   }
353 
354   // At this point, S is DFlocal.  Now we union in DFup's of our children...
355   // Loop through and visit the nodes that Node immediately dominates (Node's
356   // children in the IDomTree)
357   //
358   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
359        NI != NE; ++NI) {
360     DominatorTree::Node *IDominee = *NI;
361     const DomSetType &ChildDF = calcDomFrontier(DT, IDominee);
362 
363     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
364     for (; CDFI != CDFE; ++CDFI) {
365       if (!Node->dominates(DT[*CDFI]))
366 	S.insert(*CDFI);
367     }
368   }
369 
370   return S;
371 }
372