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 "Support/DepthFirstIterator.h"
21 #include "Support/SetOperations.h"
24 //===----------------------------------------------------------------------===//
25 // ImmediateDominators Implementation
26 //===----------------------------------------------------------------------===//
28 // Immediate Dominators construction - This pass constructs immediate dominator
29 // information for a flow-graph based on the algorithm described in this
32 // A Fast Algorithm for Finding Dominators in a Flowgraph
33 // T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
35 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
36 // LINK, but it turns out that the theoretically slower O(n*log(n))
37 // implementation is actually faster than the "efficient" algorithm (even for
38 // large CFGs) because the constant overheads are substantially smaller. The
39 // lower-complexity version can be enabled with the following #define:
41 #define BALANCE_IDOM_TREE 0
43 //===----------------------------------------------------------------------===//
45 static RegisterAnalysis<ImmediateDominators>
46 C("idom", "Immediate Dominators Construction", true);
48 unsigned ImmediateDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
53 Vertex.push_back(V); // Vertex[n] = V;
54 //Info[V].Ancestor = 0; // Ancestor[n] = 0
55 //Child[V] = 0; // Child[v] = 0
56 VInfo.Size = 1; // Size[v] = 1
58 for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
59 InfoRec &SuccVInfo = Info[*SI];
60 if (SuccVInfo.Semi == 0) {
62 N = DFSPass(*SI, SuccVInfo, N);
68 void ImmediateDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
69 BasicBlock *VAncestor = VInfo.Ancestor;
70 InfoRec &VAInfo = Info[VAncestor];
71 if (VAInfo.Ancestor == 0)
74 Compress(VAncestor, VAInfo);
76 BasicBlock *VAncestorLabel = VAInfo.Label;
77 BasicBlock *VLabel = VInfo.Label;
78 if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
79 VInfo.Label = VAncestorLabel;
81 VInfo.Ancestor = VAInfo.Ancestor;
84 BasicBlock *ImmediateDominators::Eval(BasicBlock *V) {
85 InfoRec &VInfo = Info[V];
86 #if !BALANCE_IDOM_TREE
87 // Higher-complexity but faster implementation
88 if (VInfo.Ancestor == 0)
93 // Lower-complexity but slower implementation
94 if (VInfo.Ancestor == 0)
97 BasicBlock *VLabel = VInfo.Label;
99 BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
100 if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
103 return VAncestorLabel;
107 void ImmediateDominators::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
108 #if !BALANCE_IDOM_TREE
109 // Higher-complexity but faster implementation
112 // Lower-complexity but slower implementation
113 BasicBlock *WLabel = WInfo.Label;
114 unsigned WLabelSemi = Info[WLabel].Semi;
116 InfoRec *SInfo = &Info[S];
118 BasicBlock *SChild = SInfo->Child;
119 InfoRec *SChildInfo = &Info[SChild];
121 while (WLabelSemi < Info[SChildInfo->Label].Semi) {
122 BasicBlock *SChildChild = SChildInfo->Child;
123 if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
124 SChildInfo->Ancestor = S;
125 SInfo->Child = SChild = SChildChild;
126 SChildInfo = &Info[SChild];
128 SChildInfo->Size = SInfo->Size;
129 S = SInfo->Ancestor = SChild;
131 SChild = SChildChild;
132 SChildInfo = &Info[SChild];
136 InfoRec &VInfo = Info[V];
137 SInfo->Label = WLabel;
139 assert(V != W && "The optimization here will not work in this case!");
140 unsigned WSize = WInfo.Size;
141 unsigned VSize = (VInfo.Size += WSize);
144 std::swap(S, VInfo.Child);
156 bool ImmediateDominators::runOnFunction(Function &F) {
157 IDoms.clear(); // Reset from the last time we were run...
158 BasicBlock *Root = &F.getEntryBlock();
160 Roots.push_back(Root);
164 // Step #1: Number blocks in depth-first order and initialize variables used
165 // in later stages of the algorithm.
167 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
168 N = DFSPass(Roots[i], Info[Roots[i]], 0);
170 for (unsigned i = N; i >= 2; --i) {
171 BasicBlock *W = Vertex[i];
172 InfoRec &WInfo = Info[W];
174 // Step #2: Calculate the semidominators of all vertices
175 for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
176 if (Info.count(*PI)) { // Only if this predecessor is reachable!
177 unsigned SemiU = Info[Eval(*PI)].Semi;
178 if (SemiU < WInfo.Semi)
182 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
184 BasicBlock *WParent = WInfo.Parent;
185 Link(WParent, W, WInfo);
187 // Step #3: Implicitly define the immediate dominator of vertices
188 std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
189 while (!WParentBucket.empty()) {
190 BasicBlock *V = WParentBucket.back();
191 WParentBucket.pop_back();
192 BasicBlock *U = Eval(V);
193 IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
197 // Step #4: Explicitly define the immediate dominator of each vertex
198 for (unsigned i = 2; i <= N; ++i) {
199 BasicBlock *W = Vertex[i];
200 BasicBlock *&WIDom = IDoms[W];
201 if (WIDom != Vertex[Info[W].Semi])
202 WIDom = IDoms[WIDom];
205 // Free temporary memory used to construct idom's
207 std::vector<BasicBlock*>().swap(Vertex);
212 void ImmediateDominatorsBase::print(std::ostream &o) const {
213 for (const_iterator I = begin(), E = end(); I != E; ++I) {
214 o << " Immediate Dominator For Basic Block:";
216 WriteAsOperand(o, I->first, false);
218 o << " <<exit node>>";
221 WriteAsOperand(o, I->second, false);
223 o << " <<exit node>>";
231 //===----------------------------------------------------------------------===//
232 // DominatorSet Implementation
233 //===----------------------------------------------------------------------===//
235 static RegisterAnalysis<DominatorSet>
236 B("domset", "Dominator Set Construction", true);
238 // dominates - Return true if A dominates B. This performs the special checks
239 // necessary if A and B are in the same basic block.
241 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
242 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
243 if (BBA != BBB) return dominates(BBA, BBB);
245 // Loop through the basic block until we find A or B.
246 BasicBlock::iterator I = BBA->begin();
247 for (; &*I != A && &*I != B; ++I) /*empty*/;
249 // A dominates B if it is found first in the basic block...
254 // runOnFunction - This method calculates the forward dominator sets for the
255 // specified function.
257 bool DominatorSet::runOnFunction(Function &F) {
258 BasicBlock *Root = &F.getEntryBlock();
260 Roots.push_back(Root);
261 assert(pred_begin(Root) == pred_end(Root) &&
262 "Root node has predecessors in function!");
264 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
266 if (Roots.empty()) return false;
268 // Root nodes only dominate themselves.
269 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
270 Doms[Roots[i]].insert(Roots[i]);
272 // Loop over all of the blocks in the function, calculating dominator sets for
274 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
275 if (BasicBlock *IDom = ID[I]) { // Get idom if block is reachable
276 DomSetType &DS = Doms[I];
277 assert(DS.empty() && "Domset already filled in for this block?");
278 DS.insert(I); // Blocks always dominate themselves
280 // Insert all dominators into the set...
282 // If we have already computed the dominator sets for our immediate
283 // dominator, just use it instead of walking all the way up to the root.
284 DomSetType &IDS = Doms[IDom];
286 DS.insert(IDS.begin(), IDS.end());
294 // Ensure that every basic block has at least an empty set of nodes. This
295 // is important for the case when there is unreachable blocks.
303 static std::ostream &operator<<(std::ostream &o,
304 const std::set<BasicBlock*> &BBs) {
305 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
308 WriteAsOperand(o, *I, false);
310 o << " <<exit node>>";
315 void DominatorSetBase::print(std::ostream &o) const {
316 for (const_iterator I = begin(), E = end(); I != E; ++I) {
317 o << " DomSet For BB: ";
319 WriteAsOperand(o, I->first, false);
321 o << " <<exit node>>";
322 o << " is:\t" << I->second << "\n";
326 //===----------------------------------------------------------------------===//
327 // DominatorTree Implementation
328 //===----------------------------------------------------------------------===//
330 static RegisterAnalysis<DominatorTree>
331 E("domtree", "Dominator Tree Construction", true);
333 // DominatorTreeBase::reset - Free all of the tree node memory.
335 void DominatorTreeBase::reset() {
336 for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
342 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
343 assert(IDom && "No immediate dominator?");
344 if (IDom != NewIDom) {
345 std::vector<Node*>::iterator I =
346 std::find(IDom->Children.begin(), IDom->Children.end(), this);
347 assert(I != IDom->Children.end() &&
348 "Not in immediate dominator children set!");
349 // I am no longer your child...
350 IDom->Children.erase(I);
352 // Switch to new dominator
354 IDom->Children.push_back(this);
358 DominatorTreeBase::Node *DominatorTree::getNodeForBlock(BasicBlock *BB) {
359 Node *&BBNode = Nodes[BB];
360 if (BBNode) return BBNode;
362 // Haven't calculated this node yet? Get or calculate the node for the
363 // immediate dominator.
364 BasicBlock *IDom = getAnalysis<ImmediateDominators>()[BB];
365 Node *IDomNode = getNodeForBlock(IDom);
367 // Add a new tree node for this BasicBlock, and link it as a child of
369 return BBNode = IDomNode->addChild(new Node(BB, IDomNode));
372 void DominatorTree::calculate(const ImmediateDominators &ID) {
373 assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
374 BasicBlock *Root = Roots[0];
375 Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
377 // Loop over all of the reachable blocks in the function...
378 for (ImmediateDominators::const_iterator I = ID.begin(), E = ID.end();
380 Node *&BBNode = Nodes[I->first];
381 if (!BBNode) { // Haven't calculated this node yet?
382 // Get or calculate the node for the immediate dominator
383 Node *IDomNode = getNodeForBlock(I->second);
385 // Add a new tree node for this BasicBlock, and link it as a child of
387 BBNode = IDomNode->addChild(new Node(I->first, 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";