1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
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.
8 //===----------------------------------------------------------------------===//
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"
17 //===----------------------------------------------------------------------===//
18 // DominatorSet Implementation
19 //===----------------------------------------------------------------------===//
21 static RegisterAnalysis<DominatorSet>
22 A("domset", "Dominator Set Construction", true);
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.
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);
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*/;
35 // A dominates B if it is found first in the basic block...
40 void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
42 Doms[RootBB].insert(RootBB); // Root always dominates itself...
46 DomSetType WorkingSet;
47 df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
48 for ( ; It != End; ++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.
56 while (Doms[*PI].empty()) ++PI;
57 WorkingSet = Doms[*PI];
59 for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
60 DomSetType &PredSet = Doms[*PI];
62 set_intersect(WorkingSet, PredSet);
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
72 // This allows for dominator properties to be built for unreachable code
73 // in a reasonable manner.
75 WorkingSet = Doms[Root];
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.
84 WorkingSet.clear(); // Clear out the set for next iteration
91 // runOnFunction - This method calculates the forward dominator sets for the
92 // specified function.
94 bool DominatorSet::runOnFunction(Function &F) {
95 Doms.clear(); // Reset from the last time we were run...
96 Root = &F.getEntryNode();
97 assert(pred_begin(Root) == pred_end(Root) &&
98 "Root node has predecessors in function!");
100 // Calculate dominator sets for the reachable basic blocks...
101 calculateDominatorsFromBlock(Root);
103 // Every basic block in the function should at least dominate themselves, and
104 // thus every basic block should have an entry in Doms. The one case where we
105 // miss this is when a basic block is unreachable. To get these we now do an
106 // extra pass over the function, calculating dominator information for
107 // unreachable blocks.
109 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
110 if (Doms[I].count(I) == 0)
111 calculateDominatorsFromBlock(I);
117 static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
118 for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
121 WriteAsOperand(o, *I, false);
127 void DominatorSetBase::print(std::ostream &o) const {
128 for (const_iterator I = begin(), E = end(); I != E; ++I) {
129 o << "=============================--------------------------------\n"
130 << "\nDominator Set For Basic Block: ";
131 WriteAsOperand(o, I->first, false);
132 o << "\n-------------------------------\n" << I->second << "\n";
136 //===----------------------------------------------------------------------===//
137 // ImmediateDominators Implementation
138 //===----------------------------------------------------------------------===//
140 static RegisterAnalysis<ImmediateDominators>
141 C("idom", "Immediate Dominators Construction", true);
143 // calcIDoms - Calculate the immediate dominator mapping, given a set of
144 // dominators for every basic block.
145 void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
146 // Loop over all of the nodes that have dominators... figuring out the IDOM
149 for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
151 BasicBlock *BB = DI->first;
152 const DominatorSet::DomSetType &Dominators = DI->second;
153 unsigned DomSetSize = Dominators.size();
154 if (DomSetSize == 1) continue; // Root node... IDom = null
156 // Loop over all dominators of this node. This corresponds to looping over
157 // nodes in the dominator chain, looking for a node whose dominator set is
158 // equal to the current nodes, except that the current node does not exist
159 // in it. This means that it is one level higher in the dom chain than the
160 // current node, and it is our idom!
162 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
163 DominatorSet::DomSetType::const_iterator End = Dominators.end();
164 for (; I != End; ++I) { // Iterate over dominators...
165 // All of our dominators should form a chain, where the number of elements
166 // in the dominator set indicates what level the node is at in the chain.
167 // We want the node immediately above us, so it will have an identical
168 // dominator set, except that BB will not dominate it... therefore it's
169 // dominator set size will be one less than BB's...
171 if (DS.getDominators(*I).size() == DomSetSize - 1) {
179 void ImmediateDominatorsBase::print(std::ostream &o) const {
180 for (const_iterator I = begin(), E = end(); I != E; ++I) {
181 o << "=============================--------------------------------\n"
182 << "\nImmediate Dominator For Basic Block:";
183 WriteAsOperand(o, I->first, false);
185 WriteAsOperand(o, I->second, false);
191 //===----------------------------------------------------------------------===//
192 // DominatorTree Implementation
193 //===----------------------------------------------------------------------===//
195 static RegisterAnalysis<DominatorTree>
196 E("domtree", "Dominator Tree Construction", true);
198 // DominatorTreeBase::reset - Free all of the tree node memory.
200 void DominatorTreeBase::reset() {
201 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
206 void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
207 assert(IDom && "No immediate dominator?");
208 if (IDom != NewIDom) {
209 std::vector<Node*>::iterator I =
210 std::find(IDom->Children.begin(), IDom->Children.end(), this);
211 assert(I != IDom->Children.end() &&
212 "Not in immediate dominator children set!");
213 // I am no longer your child...
214 IDom->Children.erase(I);
216 // Switch to new dominator
218 IDom->Children.push_back(this);
224 void DominatorTree::calculate(const DominatorSet &DS) {
225 Nodes[Root] = new Node(Root, 0); // Add a node for the root...
227 // Iterate over all nodes in depth first order...
228 for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
231 const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
232 unsigned DomSetSize = Dominators.size();
233 if (DomSetSize == 1) continue; // Root node... IDom = null
235 // Loop over all dominators of this node. This corresponds to looping over
236 // nodes in the dominator chain, looking for a node whose dominator set is
237 // equal to the current nodes, except that the current node does not exist
238 // in it. This means that it is one level higher in the dom chain than the
239 // current node, and it is our idom! We know that we have already added
240 // a DominatorTree node for our idom, because the idom must be a
241 // predecessor in the depth first order that we are iterating through the
244 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
245 DominatorSet::DomSetType::const_iterator End = Dominators.end();
246 for (; I != End; ++I) { // Iterate over dominators...
247 // All of our dominators should form a chain, where the number of
248 // elements in the dominator set indicates what level the node is at in
249 // the chain. We want the node immediately above us, so it will have
250 // an identical dominator set, except that BB will not dominate it...
251 // therefore it's dominator set size will be one less than BB's...
253 if (DS.getDominators(*I).size() == DomSetSize - 1) {
254 // We know that the immediate dominator should already have a node,
255 // because we are traversing the CFG in depth first order!
257 Node *IDomNode = Nodes[*I];
258 assert(IDomNode && "No node for IDOM?");
260 // Add a new tree node for this BasicBlock, and link it as a child of
262 Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
270 static std::ostream &operator<<(std::ostream &o,
271 const DominatorTreeBase::Node *Node) {
272 return o << Node->getNode()
273 << "\n------------------------------------------\n";
276 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
278 o << "Level #" << Lev << ": " << N;
279 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
281 PrintDomTree(*I, o, Lev+1);
285 void DominatorTreeBase::print(std::ostream &o) const {
286 o << "=============================--------------------------------\n"
287 << "Inorder Dominator Tree:\n";
288 PrintDomTree(Nodes.find(getRoot())->second, o, 1);
292 //===----------------------------------------------------------------------===//
293 // DominanceFrontier Implementation
294 //===----------------------------------------------------------------------===//
296 static RegisterAnalysis<DominanceFrontier>
297 G("domfrontier", "Dominance Frontier Construction", true);
299 const DominanceFrontier::DomSetType &
300 DominanceFrontier::calculate(const DominatorTree &DT,
301 const DominatorTree::Node *Node) {
302 // Loop over CFG successors to calculate DFlocal[Node]
303 BasicBlock *BB = Node->getNode();
304 DomSetType &S = Frontiers[BB]; // The new set to fill in...
306 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
308 // Does Node immediately dominate this successor?
309 if (DT[*SI]->getIDom() != Node)
313 // At this point, S is DFlocal. Now we union in DFup's of our children...
314 // Loop through and visit the nodes that Node immediately dominates (Node's
315 // children in the IDomTree)
317 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
319 DominatorTree::Node *IDominee = *NI;
320 const DomSetType &ChildDF = calculate(DT, IDominee);
322 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
323 for (; CDFI != CDFE; ++CDFI) {
324 if (!Node->dominates(DT[*CDFI]))
332 void DominanceFrontierBase::print(std::ostream &o) const {
333 for (const_iterator I = begin(), E = end(); I != E; ++I) {
334 o << "=============================--------------------------------\n"
335 << "\nDominance Frontier For Basic Block\n";
336 WriteAsOperand(o, I->first, false);
337 o << " is: \n" << I->second << "\n";