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 {
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.
302 static std::ostream &operator<<(std::ostream &o,
303 const std::set<BasicBlock*> &BBs) {
304 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
307 WriteAsOperand(o, *I, false);
309 o << " <<exit node>>";
314 void DominatorSetBase::print(std::ostream &o) const {
315 for (const_iterator I = begin(), E = end(); I != E; ++I) {
316 o << " DomSet For BB: ";
318 WriteAsOperand(o, I->first, false);
320 o << " <<exit node>>";
321 o << " is:\t" << I->second << "\n";
325 //===----------------------------------------------------------------------===//
326 // DominatorTree Implementation
327 //===----------------------------------------------------------------------===//
329 static RegisterAnalysis<DominatorTree>
330 E("domtree", "Dominator Tree Construction", true);
332 // DominatorTreeBase::reset - Free all of the tree node memory.
334 void DominatorTreeBase::reset() {
335 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
341 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
342 assert(IDom && "No immediate dominator?");
343 if (IDom != NewIDom) {
344 std::vector<Node*>::iterator I =
345 std::find(IDom->Children.begin(), IDom->Children.end(), this);
346 assert(I != IDom->Children.end() &&
347 "Not in immediate dominator children set!");
348 // I am no longer your child...
349 IDom->Children.erase(I);
351 // Switch to new dominator
353 IDom->Children.push_back(this);
357 DominatorTreeBase::Node *DominatorTree::getNodeForBlock(BasicBlock *BB) {
358 Node *&BBNode = Nodes[BB];
359 if (BBNode) return BBNode;
361 // Haven't calculated this node yet? Get or calculate the node for the
362 // immediate dominator.
363 BasicBlock *IDom = getAnalysis<ImmediateDominators>()[BB];
364 Node *IDomNode = getNodeForBlock(IDom);
366 // Add a new tree node for this BasicBlock, and link it as a child of
368 return BBNode = IDomNode->addChild(new Node(BB, IDomNode));
371 void DominatorTree::calculate(const ImmediateDominators &ID) {
372 assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
373 BasicBlock *Root = Roots[0];
374 Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
376 Function *F = Root->getParent();
377 // Loop over all of the reachable blocks in the function...
378 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
379 if (BasicBlock *ImmDom = ID.get(I)) { // Reachable block.
380 Node *&BBNode = Nodes[I];
381 if (!BBNode) { // Haven't calculated this node yet?
382 // Get or calculate the node for the immediate dominator
383 Node *IDomNode = getNodeForBlock(ImmDom);
385 // Add a new tree node for this BasicBlock, and link it as a child of
387 BBNode = IDomNode->addChild(new Node(I, IDomNode));
392 static std::ostream &operator<<(std::ostream &o,
393 const DominatorTreeBase::Node *Node) {
394 if (Node->getBlock())
395 WriteAsOperand(o, Node->getBlock(), false);
397 o << " <<exit node>>";
401 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
403 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
404 for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
406 PrintDomTree(*I, o, Lev+1);
409 void DominatorTreeBase::print(std::ostream &o) const {
410 o << "=============================--------------------------------\n"
411 << "Inorder Dominator Tree:\n";
412 PrintDomTree(getRootNode(), o, 1);
416 //===----------------------------------------------------------------------===//
417 // DominanceFrontier Implementation
418 //===----------------------------------------------------------------------===//
420 static RegisterAnalysis<DominanceFrontier>
421 G("domfrontier", "Dominance Frontier Construction", true);
423 const DominanceFrontier::DomSetType &
424 DominanceFrontier::calculate(const DominatorTree &DT,
425 const DominatorTree::Node *Node) {
426 // Loop over CFG successors to calculate DFlocal[Node]
427 BasicBlock *BB = Node->getBlock();
428 DomSetType &S = Frontiers[BB]; // The new set to fill in...
430 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
432 // Does Node immediately dominate this successor?
433 if (DT[*SI]->getIDom() != Node)
437 // At this point, S is DFlocal. Now we union in DFup's of our children...
438 // Loop through and visit the nodes that Node immediately dominates (Node's
439 // children in the IDomTree)
441 for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
443 DominatorTree::Node *IDominee = *NI;
444 const DomSetType &ChildDF = calculate(DT, IDominee);
446 DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
447 for (; CDFI != CDFE; ++CDFI) {
448 if (!Node->dominates(DT[*CDFI]))
456 void DominanceFrontierBase::print(std::ostream &o) const {
457 for (const_iterator I = begin(), E = end(); I != E; ++I) {
458 o << " DomFrontier for BB";
460 WriteAsOperand(o, I->first, false);
462 o << " <<exit node>>";
463 o << " is:\t" << I->second << "\n";