1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements simple dominator construction algorithms for finding
11 // forward dominators. Postdominators are available in libanalysis, but are not
12 // included in libvmcore, because it's not needed. Forward dominators are
13 // needed to support the Verifier pass.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SetOperations.h"
25 //===----------------------------------------------------------------------===//
26 // ImmediateDominators Implementation
27 //===----------------------------------------------------------------------===//
29 // Immediate Dominators construction - This pass constructs immediate dominator
30 // information for a flow-graph based on the algorithm described in this
33 // A Fast Algorithm for Finding Dominators in a Flowgraph
34 // T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
36 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
37 // LINK, but it turns out that the theoretically slower O(n*log(n))
38 // implementation is actually faster than the "efficient" algorithm (even for
39 // large CFGs) because the constant overheads are substantially smaller. The
40 // lower-complexity version can be enabled with the following #define:
42 #define BALANCE_IDOM_TREE 0
44 //===----------------------------------------------------------------------===//
46 static RegisterAnalysis<ImmediateDominators>
47 C("idom", "Immediate Dominators Construction", true);
49 unsigned ImmediateDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
54 Vertex.push_back(V); // Vertex[n] = V;
55 //Info[V].Ancestor = 0; // Ancestor[n] = 0
56 //Child[V] = 0; // Child[v] = 0
57 VInfo.Size = 1; // Size[v] = 1
59 for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
60 InfoRec &SuccVInfo = Info[*SI];
61 if (SuccVInfo.Semi == 0) {
63 N = DFSPass(*SI, SuccVInfo, N);
69 void ImmediateDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
70 BasicBlock *VAncestor = VInfo.Ancestor;
71 InfoRec &VAInfo = Info[VAncestor];
72 if (VAInfo.Ancestor == 0)
75 Compress(VAncestor, VAInfo);
77 BasicBlock *VAncestorLabel = VAInfo.Label;
78 BasicBlock *VLabel = VInfo.Label;
79 if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
80 VInfo.Label = VAncestorLabel;
82 VInfo.Ancestor = VAInfo.Ancestor;
85 BasicBlock *ImmediateDominators::Eval(BasicBlock *V) {
86 InfoRec &VInfo = Info[V];
87 #if !BALANCE_IDOM_TREE
88 // Higher-complexity but faster implementation
89 if (VInfo.Ancestor == 0)
94 // Lower-complexity but slower implementation
95 if (VInfo.Ancestor == 0)
98 BasicBlock *VLabel = VInfo.Label;
100 BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
101 if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
104 return VAncestorLabel;
108 void ImmediateDominators::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
109 #if !BALANCE_IDOM_TREE
110 // Higher-complexity but faster implementation
113 // Lower-complexity but slower implementation
114 BasicBlock *WLabel = WInfo.Label;
115 unsigned WLabelSemi = Info[WLabel].Semi;
117 InfoRec *SInfo = &Info[S];
119 BasicBlock *SChild = SInfo->Child;
120 InfoRec *SChildInfo = &Info[SChild];
122 while (WLabelSemi < Info[SChildInfo->Label].Semi) {
123 BasicBlock *SChildChild = SChildInfo->Child;
124 if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
125 SChildInfo->Ancestor = S;
126 SInfo->Child = SChild = SChildChild;
127 SChildInfo = &Info[SChild];
129 SChildInfo->Size = SInfo->Size;
130 S = SInfo->Ancestor = SChild;
132 SChild = SChildChild;
133 SChildInfo = &Info[SChild];
137 InfoRec &VInfo = Info[V];
138 SInfo->Label = WLabel;
140 assert(V != W && "The optimization here will not work in this case!");
141 unsigned WSize = WInfo.Size;
142 unsigned VSize = (VInfo.Size += WSize);
145 std::swap(S, VInfo.Child);
157 bool ImmediateDominators::runOnFunction(Function &F) {
158 IDoms.clear(); // Reset from the last time we were run...
159 BasicBlock *Root = &F.getEntryBlock();
161 Roots.push_back(Root);
165 // Step #1: Number blocks in depth-first order and initialize variables used
166 // in later stages of the algorithm.
168 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
169 N = DFSPass(Roots[i], Info[Roots[i]], 0);
171 for (unsigned i = N; i >= 2; --i) {
172 BasicBlock *W = Vertex[i];
173 InfoRec &WInfo = Info[W];
175 // Step #2: Calculate the semidominators of all vertices
176 for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
177 if (Info.count(*PI)) { // Only if this predecessor is reachable!
178 unsigned SemiU = Info[Eval(*PI)].Semi;
179 if (SemiU < WInfo.Semi)
183 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
185 BasicBlock *WParent = WInfo.Parent;
186 Link(WParent, W, WInfo);
188 // Step #3: Implicitly define the immediate dominator of vertices
189 std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
190 while (!WParentBucket.empty()) {
191 BasicBlock *V = WParentBucket.back();
192 WParentBucket.pop_back();
193 BasicBlock *U = Eval(V);
194 IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
198 // Step #4: Explicitly define the immediate dominator of each vertex
199 for (unsigned i = 2; i <= N; ++i) {
200 BasicBlock *W = Vertex[i];
201 BasicBlock *&WIDom = IDoms[W];
202 if (WIDom != Vertex[Info[W].Semi])
203 WIDom = IDoms[WIDom];
206 // Free temporary memory used to construct idom's
208 std::vector<BasicBlock*>().swap(Vertex);
213 void ImmediateDominatorsBase::print(std::ostream &o, const Module* ) const {
214 Function *F = getRoots()[0]->getParent();
215 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
216 o << " Immediate Dominator For Basic Block:";
217 WriteAsOperand(o, I, false);
219 if (BasicBlock *ID = get(I))
220 WriteAsOperand(o, ID, false);
222 o << " <<exit node>>";
230 //===----------------------------------------------------------------------===//
231 // DominatorSet Implementation
232 //===----------------------------------------------------------------------===//
234 static RegisterAnalysis<DominatorSet>
235 B("domset", "Dominator Set Construction", true);
237 // dominates - Return true if A dominates B. This performs the special checks
238 // necessary if A and B are in the same basic block.
240 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
241 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
242 if (BBA != BBB) return dominates(BBA, BBB);
244 // Loop through the basic block until we find A or B.
245 BasicBlock::iterator I = BBA->begin();
246 for (; &*I != A && &*I != B; ++I) /*empty*/;
248 // A dominates B if it is found first in the basic block...
253 // runOnFunction - This method calculates the forward dominator sets for the
254 // specified function.
256 bool DominatorSet::runOnFunction(Function &F) {
257 BasicBlock *Root = &F.getEntryBlock();
259 Roots.push_back(Root);
260 assert(pred_begin(Root) == pred_end(Root) &&
261 "Root node has predecessors in function!");
263 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
265 if (Roots.empty()) return false;
267 // Root nodes only dominate themselves.
268 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
269 Doms[Roots[i]].insert(Roots[i]);
271 // Loop over all of the blocks in the function, calculating dominator sets for
273 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
274 if (BasicBlock *IDom = ID[I]) { // Get idom if block is reachable
275 DomSetType &DS = Doms[I];
276 assert(DS.empty() && "Domset already filled in for this block?");
277 DS.insert(I); // Blocks always dominate themselves
279 // Insert all dominators into the set...
281 // If we have already computed the dominator sets for our immediate
282 // dominator, just use it instead of walking all the way up to the root.
283 DomSetType &IDS = Doms[IDom];
285 DS.insert(IDS.begin(), IDS.end());
293 // Ensure that every basic block has at least an empty set of nodes. This
294 // is important for the case when there is unreachable blocks.
301 void DominatorSet::stub() {}
304 static std::ostream &operator<<(std::ostream &o,
305 const std::set<BasicBlock*> &BBs) {
306 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
309 WriteAsOperand(o, *I, false);
311 o << " <<exit node>>";
316 void DominatorSetBase::print(std::ostream &o, const Module* ) const {
317 for (const_iterator I = begin(), E = end(); I != E; ++I) {
318 o << " DomSet For BB: ";
320 WriteAsOperand(o, I->first, false);
322 o << " <<exit node>>";
323 o << " is:\t" << I->second << "\n";
327 //===----------------------------------------------------------------------===//
328 // DominatorTree Implementation
329 //===----------------------------------------------------------------------===//
331 static RegisterAnalysis<DominatorTree>
332 E("domtree", "Dominator Tree Construction", true);
334 // DominatorTreeBase::reset - Free all of the tree node memory.
336 void DominatorTreeBase::reset() {
337 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
343 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
344 assert(IDom && "No immediate dominator?");
345 if (IDom != NewIDom) {
346 std::vector<Node*>::iterator I =
347 std::find(IDom->Children.begin(), IDom->Children.end(), this);
348 assert(I != IDom->Children.end() &&
349 "Not in immediate dominator children set!");
350 // I am no longer your child...
351 IDom->Children.erase(I);
353 // Switch to new dominator
355 IDom->Children.push_back(this);
359 DominatorTreeBase::Node *DominatorTree::getNodeForBlock(BasicBlock *BB) {
360 Node *&BBNode = Nodes[BB];
361 if (BBNode) return BBNode;
363 // Haven't calculated this node yet? Get or calculate the node for the
364 // immediate dominator.
365 BasicBlock *IDom = getAnalysis<ImmediateDominators>()[BB];
366 Node *IDomNode = getNodeForBlock(IDom);
368 // Add a new tree node for this BasicBlock, and link it as a child of
370 return BBNode = IDomNode->addChild(new Node(BB, IDomNode));
373 void DominatorTree::calculate(const ImmediateDominators &ID) {
374 assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
375 BasicBlock *Root = Roots[0];
376 Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
378 Function *F = Root->getParent();
379 // Loop over all of the reachable blocks in the function...
380 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
381 if (BasicBlock *ImmDom = ID.get(I)) { // Reachable block.
382 Node *&BBNode = Nodes[I];
383 if (!BBNode) { // Haven't calculated this node yet?
384 // Get or calculate the node for the immediate dominator
385 Node *IDomNode = getNodeForBlock(ImmDom);
387 // Add a new tree node for this BasicBlock, and link it as a child of
389 BBNode = IDomNode->addChild(new Node(I, IDomNode));
394 static std::ostream &operator<<(std::ostream &o,
395 const DominatorTreeBase::Node *Node) {
396 if (Node->getBlock())
397 WriteAsOperand(o, Node->getBlock(), false);
399 o << " <<exit node>>";
403 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
405 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
406 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
408 PrintDomTree(*I, o, Lev+1);
411 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
412 o << "=============================--------------------------------\n"
413 << "Inorder Dominator Tree:\n";
414 PrintDomTree(getRootNode(), o, 1);
418 //===----------------------------------------------------------------------===//
419 // DominanceFrontier Implementation
420 //===----------------------------------------------------------------------===//
422 static RegisterAnalysis<DominanceFrontier>
423 G("domfrontier", "Dominance Frontier Construction", true);
425 const DominanceFrontier::DomSetType &
426 DominanceFrontier::calculate(const DominatorTree &DT,
427 const DominatorTree::Node *Node) {
428 // Loop over CFG successors to calculate DFlocal[Node]
429 BasicBlock *BB = Node->getBlock();
430 DomSetType &S = Frontiers[BB]; // The new set to fill in...
432 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
434 // Does Node immediately dominate this successor?
435 if (DT[*SI]->getIDom() != Node)
439 // At this point, S is DFlocal. Now we union in DFup's of our children...
440 // Loop through and visit the nodes that Node immediately dominates (Node's
441 // children in the IDomTree)
443 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
445 DominatorTree::Node *IDominee = *NI;
446 const DomSetType &ChildDF = calculate(DT, IDominee);
448 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
449 for (; CDFI != CDFE; ++CDFI) {
450 if (!Node->dominates(DT[*CDFI]))
458 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
459 for (const_iterator I = begin(), E = end(); I != E; ++I) {
460 o << " DomFrontier for BB";
462 WriteAsOperand(o, I->first, false);
464 o << " <<exit node>>";
465 o << " is:\t" << I->second << "\n";