1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the DominatorTree class, which provides fast and efficient
11 // dominance queries.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_DOMINATORS_H
16 #define LLVM_ANALYSIS_DOMINATORS_H
17
18 #include "llvm/Pass.h"
19 #include "llvm/Function.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/GraphTraits.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29
30 namespace llvm {
31
32 //===----------------------------------------------------------------------===//
33 /// DominatorBase - Base class that other, more interesting dominator analyses
34 /// inherit from.
35 ///
36 template <class NodeT>
37 class DominatorBase {
38 protected:
39 std::vector<NodeT*> Roots;
40 const bool IsPostDominators;
DominatorBase(bool isPostDom)41 inline explicit DominatorBase(bool isPostDom) :
42 Roots(), IsPostDominators(isPostDom) {}
43 public:
44
45 /// getRoots - Return the root blocks of the current CFG. This may include
46 /// multiple blocks if we are computing post dominators. For forward
47 /// dominators, this will always be a single block (the entry node).
48 ///
getRoots()49 inline const std::vector<NodeT*> &getRoots() const { return Roots; }
50
51 /// isPostDominator - Returns true if analysis based of postdoms
52 ///
isPostDominator()53 bool isPostDominator() const { return IsPostDominators; }
54 };
55
56
57 //===----------------------------------------------------------------------===//
58 // DomTreeNode - Dominator Tree Node
59 template<class NodeT> class DominatorTreeBase;
60 struct PostDominatorTree;
61 class MachineBasicBlock;
62
63 template <class NodeT>
64 class DomTreeNodeBase {
65 NodeT *TheBB;
66 DomTreeNodeBase<NodeT> *IDom;
67 std::vector<DomTreeNodeBase<NodeT> *> Children;
68 int DFSNumIn, DFSNumOut;
69
70 template<class N> friend class DominatorTreeBase;
71 friend struct PostDominatorTree;
72 public:
73 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
74 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
75 const_iterator;
76
begin()77 iterator begin() { return Children.begin(); }
end()78 iterator end() { return Children.end(); }
begin()79 const_iterator begin() const { return Children.begin(); }
end()80 const_iterator end() const { return Children.end(); }
81
getBlock()82 NodeT *getBlock() const { return TheBB; }
getIDom()83 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
getChildren()84 const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
85 return Children;
86 }
87
DomTreeNodeBase(NodeT * BB,DomTreeNodeBase<NodeT> * iDom)88 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
89 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
90
addChild(DomTreeNodeBase<NodeT> * C)91 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
92 Children.push_back(C);
93 return C;
94 }
95
getNumChildren()96 size_t getNumChildren() const {
97 return Children.size();
98 }
99
clearAllChildren()100 void clearAllChildren() {
101 Children.clear();
102 }
103
compare(DomTreeNodeBase<NodeT> * Other)104 bool compare(DomTreeNodeBase<NodeT> *Other) {
105 if (getNumChildren() != Other->getNumChildren())
106 return true;
107
108 SmallPtrSet<NodeT *, 4> OtherChildren;
109 for (iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
110 NodeT *Nd = (*I)->getBlock();
111 OtherChildren.insert(Nd);
112 }
113
114 for (iterator I = begin(), E = end(); I != E; ++I) {
115 NodeT *N = (*I)->getBlock();
116 if (OtherChildren.count(N) == 0)
117 return true;
118 }
119 return false;
120 }
121
setIDom(DomTreeNodeBase<NodeT> * NewIDom)122 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
123 assert(IDom && "No immediate dominator?");
124 if (IDom != NewIDom) {
125 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
126 std::find(IDom->Children.begin(), IDom->Children.end(), this);
127 assert(I != IDom->Children.end() &&
128 "Not in immediate dominator children set!");
129 // I am no longer your child...
130 IDom->Children.erase(I);
131
132 // Switch to new dominator
133 IDom = NewIDom;
134 IDom->Children.push_back(this);
135 }
136 }
137
138 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
139 /// not call them.
getDFSNumIn()140 unsigned getDFSNumIn() const { return DFSNumIn; }
getDFSNumOut()141 unsigned getDFSNumOut() const { return DFSNumOut; }
142 private:
143 // Return true if this node is dominated by other. Use this only if DFS info
144 // is valid.
DominatedBy(const DomTreeNodeBase<NodeT> * other)145 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
146 return this->DFSNumIn >= other->DFSNumIn &&
147 this->DFSNumOut <= other->DFSNumOut;
148 }
149 };
150
151 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
152 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
153
154 template<class NodeT>
155 static raw_ostream &operator<<(raw_ostream &o,
156 const DomTreeNodeBase<NodeT> *Node) {
157 if (Node->getBlock())
158 WriteAsOperand(o, Node->getBlock(), false);
159 else
160 o << " <<exit node>>";
161
162 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
163
164 return o << "\n";
165 }
166
167 template<class NodeT>
PrintDomTree(const DomTreeNodeBase<NodeT> * N,raw_ostream & o,unsigned Lev)168 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
169 unsigned Lev) {
170 o.indent(2*Lev) << "[" << Lev << "] " << N;
171 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
172 E = N->end(); I != E; ++I)
173 PrintDomTree<NodeT>(*I, o, Lev+1);
174 }
175
176 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
177
178 //===----------------------------------------------------------------------===//
179 /// DominatorTree - Calculate the immediate dominator tree for a function.
180 ///
181
182 template<class FuncT, class N>
183 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
184 FuncT& F);
185
186 template<class NodeT>
187 class DominatorTreeBase : public DominatorBase<NodeT> {
188 protected:
189 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
190 DomTreeNodeMapType DomTreeNodes;
191 DomTreeNodeBase<NodeT> *RootNode;
192
193 bool DFSInfoValid;
194 unsigned int SlowQueries;
195 // Information record used during immediate dominators computation.
196 struct InfoRec {
197 unsigned DFSNum;
198 unsigned Parent;
199 unsigned Semi;
200 NodeT *Label;
201
InfoRecInfoRec202 InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(0) {}
203 };
204
205 DenseMap<NodeT*, NodeT*> IDoms;
206
207 // Vertex - Map the DFS number to the BasicBlock*
208 std::vector<NodeT*> Vertex;
209
210 // Info - Collection of information used during the computation of idoms.
211 DenseMap<NodeT*, InfoRec> Info;
212
reset()213 void reset() {
214 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
215 E = DomTreeNodes.end(); I != E; ++I)
216 delete I->second;
217 DomTreeNodes.clear();
218 IDoms.clear();
219 this->Roots.clear();
220 Vertex.clear();
221 RootNode = 0;
222 }
223
224 // NewBB is split and now it has one successor. Update dominator tree to
225 // reflect this change.
226 template<class N, class GraphT>
Split(DominatorTreeBase<typename GraphT::NodeType> & DT,typename GraphT::NodeType * NewBB)227 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
228 typename GraphT::NodeType* NewBB) {
229 assert(std::distance(GraphT::child_begin(NewBB),
230 GraphT::child_end(NewBB)) == 1 &&
231 "NewBB should have a single successor!");
232 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
233
234 std::vector<typename GraphT::NodeType*> PredBlocks;
235 typedef GraphTraits<Inverse<N> > InvTraits;
236 for (typename InvTraits::ChildIteratorType PI =
237 InvTraits::child_begin(NewBB),
238 PE = InvTraits::child_end(NewBB); PI != PE; ++PI)
239 PredBlocks.push_back(*PI);
240
241 assert(!PredBlocks.empty() && "No predblocks?");
242
243 bool NewBBDominatesNewBBSucc = true;
244 for (typename InvTraits::ChildIteratorType PI =
245 InvTraits::child_begin(NewBBSucc),
246 E = InvTraits::child_end(NewBBSucc); PI != E; ++PI) {
247 typename InvTraits::NodeType *ND = *PI;
248 if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
249 DT.isReachableFromEntry(ND)) {
250 NewBBDominatesNewBBSucc = false;
251 break;
252 }
253 }
254
255 // Find NewBB's immediate dominator and create new dominator tree node for
256 // NewBB.
257 NodeT *NewBBIDom = 0;
258 unsigned i = 0;
259 for (i = 0; i < PredBlocks.size(); ++i)
260 if (DT.isReachableFromEntry(PredBlocks[i])) {
261 NewBBIDom = PredBlocks[i];
262 break;
263 }
264
265 // It's possible that none of the predecessors of NewBB are reachable;
266 // in that case, NewBB itself is unreachable, so nothing needs to be
267 // changed.
268 if (!NewBBIDom)
269 return;
270
271 for (i = i + 1; i < PredBlocks.size(); ++i) {
272 if (DT.isReachableFromEntry(PredBlocks[i]))
273 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
274 }
275
276 // Create the new dominator tree node... and set the idom of NewBB.
277 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
278
279 // If NewBB strictly dominates other blocks, then it is now the immediate
280 // dominator of NewBBSucc. Update the dominator tree as appropriate.
281 if (NewBBDominatesNewBBSucc) {
282 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
283 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
284 }
285 }
286
287 public:
DominatorTreeBase(bool isPostDom)288 explicit DominatorTreeBase(bool isPostDom)
289 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
~DominatorTreeBase()290 virtual ~DominatorTreeBase() { reset(); }
291
292 /// compare - Return false if the other dominator tree base matches this
293 /// dominator tree base. Otherwise return true.
compare(DominatorTreeBase & Other)294 bool compare(DominatorTreeBase &Other) const {
295
296 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
297 if (DomTreeNodes.size() != OtherDomTreeNodes.size())
298 return true;
299
300 for (typename DomTreeNodeMapType::const_iterator
301 I = this->DomTreeNodes.begin(),
302 E = this->DomTreeNodes.end(); I != E; ++I) {
303 NodeT *BB = I->first;
304 typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
305 if (OI == OtherDomTreeNodes.end())
306 return true;
307
308 DomTreeNodeBase<NodeT>* MyNd = I->second;
309 DomTreeNodeBase<NodeT>* OtherNd = OI->second;
310
311 if (MyNd->compare(OtherNd))
312 return true;
313 }
314
315 return false;
316 }
317
releaseMemory()318 virtual void releaseMemory() { reset(); }
319
320 /// getNode - return the (Post)DominatorTree node for the specified basic
321 /// block. This is the same as using operator[] on this class.
322 ///
getNode(NodeT * BB)323 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
324 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
325 return I != DomTreeNodes.end() ? I->second : 0;
326 }
327
328 /// getRootNode - This returns the entry node for the CFG of the function. If
329 /// this tree represents the post-dominance relations for a function, however,
330 /// this root may be a node with the block == NULL. This is the case when
331 /// there are multiple exit nodes from a particular function. Consumers of
332 /// post-dominance information must be capable of dealing with this
333 /// possibility.
334 ///
getRootNode()335 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
getRootNode()336 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
337
338 /// properlyDominates - Returns true iff this dominates N and this != N.
339 /// Note that this is not a constant time operation!
340 ///
properlyDominates(const DomTreeNodeBase<NodeT> * A,const DomTreeNodeBase<NodeT> * B)341 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
342 const DomTreeNodeBase<NodeT> *B) const {
343 if (A == 0 || B == 0) return false;
344 return dominatedBySlowTreeWalk(A, B);
345 }
346
properlyDominates(const NodeT * A,const NodeT * B)347 inline bool properlyDominates(const NodeT *A, const NodeT *B) {
348 if (A == B)
349 return false;
350
351 // Cast away the const qualifiers here. This is ok since
352 // this function doesn't actually return the values returned
353 // from getNode.
354 return properlyDominates(getNode(const_cast<NodeT *>(A)),
355 getNode(const_cast<NodeT *>(B)));
356 }
357
dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> * A,const DomTreeNodeBase<NodeT> * B)358 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
359 const DomTreeNodeBase<NodeT> *B) const {
360 const DomTreeNodeBase<NodeT> *IDom;
361 if (A == 0 || B == 0) return false;
362 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
363 B = IDom; // Walk up the tree
364 return IDom != 0;
365 }
366
367
368 /// isReachableFromEntry - Return true if A is dominated by the entry
369 /// block of the function containing it.
isReachableFromEntry(const NodeT * A)370 bool isReachableFromEntry(const NodeT* A) {
371 assert(!this->isPostDominator() &&
372 "This is not implemented for post dominators");
373 return dominates(&A->getParent()->front(), A);
374 }
375
376 /// dominates - Returns true iff A dominates B. Note that this is not a
377 /// constant time operation!
378 ///
dominates(const DomTreeNodeBase<NodeT> * A,const DomTreeNodeBase<NodeT> * B)379 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
380 const DomTreeNodeBase<NodeT> *B) {
381 if (B == A)
382 return true; // A node trivially dominates itself.
383
384 if (A == 0 || B == 0)
385 return false;
386
387 // Compare the result of the tree walk and the dfs numbers, if expensive
388 // checks are enabled.
389 #ifdef XDEBUG
390 assert((!DFSInfoValid ||
391 (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
392 "Tree walk disagrees with dfs numbers!");
393 #endif
394
395 if (DFSInfoValid)
396 return B->DominatedBy(A);
397
398 // If we end up with too many slow queries, just update the
399 // DFS numbers on the theory that we are going to keep querying.
400 SlowQueries++;
401 if (SlowQueries > 32) {
402 updateDFSNumbers();
403 return B->DominatedBy(A);
404 }
405
406 return dominatedBySlowTreeWalk(A, B);
407 }
408
dominates(const NodeT * A,const NodeT * B)409 inline bool dominates(const NodeT *A, const NodeT *B) {
410 if (A == B)
411 return true;
412
413 // Cast away the const qualifiers here. This is ok since
414 // this function doesn't actually return the values returned
415 // from getNode.
416 return dominates(getNode(const_cast<NodeT *>(A)),
417 getNode(const_cast<NodeT *>(B)));
418 }
419
getRoot()420 NodeT *getRoot() const {
421 assert(this->Roots.size() == 1 && "Should always have entry node!");
422 return this->Roots[0];
423 }
424
425 /// findNearestCommonDominator - Find nearest common dominator basic block
426 /// for basic block A and B. If there is no such block then return NULL.
findNearestCommonDominator(NodeT * A,NodeT * B)427 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
428 assert(A->getParent() == B->getParent() &&
429 "Two blocks are not in same function");
430
431 // If either A or B is a entry block then it is nearest common dominator
432 // (for forward-dominators).
433 if (!this->isPostDominator()) {
434 NodeT &Entry = A->getParent()->front();
435 if (A == &Entry || B == &Entry)
436 return &Entry;
437 }
438
439 // If B dominates A then B is nearest common dominator.
440 if (dominates(B, A))
441 return B;
442
443 // If A dominates B then A is nearest common dominator.
444 if (dominates(A, B))
445 return A;
446
447 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
448 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
449
450 // Collect NodeA dominators set.
451 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
452 NodeADoms.insert(NodeA);
453 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
454 while (IDomA) {
455 NodeADoms.insert(IDomA);
456 IDomA = IDomA->getIDom();
457 }
458
459 // Walk NodeB immediate dominators chain and find common dominator node.
460 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
461 while (IDomB) {
462 if (NodeADoms.count(IDomB) != 0)
463 return IDomB->getBlock();
464
465 IDomB = IDomB->getIDom();
466 }
467
468 return NULL;
469 }
470
findNearestCommonDominator(const NodeT * A,const NodeT * B)471 const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
472 // Cast away the const qualifiers here. This is ok since
473 // const is re-introduced on the return type.
474 return findNearestCommonDominator(const_cast<NodeT *>(A),
475 const_cast<NodeT *>(B));
476 }
477
478 //===--------------------------------------------------------------------===//
479 // API to update (Post)DominatorTree information based on modifications to
480 // the CFG...
481
482 /// addNewBlock - Add a new node to the dominator tree information. This
483 /// creates a new node as a child of DomBB dominator node,linking it into
484 /// the children list of the immediate dominator.
addNewBlock(NodeT * BB,NodeT * DomBB)485 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
486 assert(getNode(BB) == 0 && "Block already in dominator tree!");
487 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
488 assert(IDomNode && "Not immediate dominator specified for block!");
489 DFSInfoValid = false;
490 return DomTreeNodes[BB] =
491 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
492 }
493
494 /// changeImmediateDominator - This method is used to update the dominator
495 /// tree information when a node's immediate dominator changes.
496 ///
changeImmediateDominator(DomTreeNodeBase<NodeT> * N,DomTreeNodeBase<NodeT> * NewIDom)497 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
498 DomTreeNodeBase<NodeT> *NewIDom) {
499 assert(N && NewIDom && "Cannot change null node pointers!");
500 DFSInfoValid = false;
501 N->setIDom(NewIDom);
502 }
503
changeImmediateDominator(NodeT * BB,NodeT * NewBB)504 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
505 changeImmediateDominator(getNode(BB), getNode(NewBB));
506 }
507
508 /// eraseNode - Removes a node from the dominator tree. Block must not
509 /// dominate any other blocks. Removes node from its immediate dominator's
510 /// children list. Deletes dominator node associated with basic block BB.
eraseNode(NodeT * BB)511 void eraseNode(NodeT *BB) {
512 DomTreeNodeBase<NodeT> *Node = getNode(BB);
513 assert(Node && "Removing node that isn't in dominator tree.");
514 assert(Node->getChildren().empty() && "Node is not a leaf node.");
515
516 // Remove node from immediate dominator's children list.
517 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
518 if (IDom) {
519 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
520 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
521 assert(I != IDom->Children.end() &&
522 "Not in immediate dominator children set!");
523 // I am no longer your child...
524 IDom->Children.erase(I);
525 }
526
527 DomTreeNodes.erase(BB);
528 delete Node;
529 }
530
531 /// removeNode - Removes a node from the dominator tree. Block must not
532 /// dominate any other blocks. Invalidates any node pointing to removed
533 /// block.
removeNode(NodeT * BB)534 void removeNode(NodeT *BB) {
535 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
536 DomTreeNodes.erase(BB);
537 }
538
539 /// splitBlock - BB is split and now it has one successor. Update dominator
540 /// tree to reflect this change.
splitBlock(NodeT * NewBB)541 void splitBlock(NodeT* NewBB) {
542 if (this->IsPostDominators)
543 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
544 else
545 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
546 }
547
548 /// print - Convert to human readable form
549 ///
print(raw_ostream & o)550 void print(raw_ostream &o) const {
551 o << "=============================--------------------------------\n";
552 if (this->isPostDominator())
553 o << "Inorder PostDominator Tree: ";
554 else
555 o << "Inorder Dominator Tree: ";
556 if (!this->DFSInfoValid)
557 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
558 o << "\n";
559
560 // The postdom tree can have a null root if there are no returns.
561 if (getRootNode())
562 PrintDomTree<NodeT>(getRootNode(), o, 1);
563 }
564
565 protected:
566 template<class GraphT>
567 friend typename GraphT::NodeType* Eval(
568 DominatorTreeBase<typename GraphT::NodeType>& DT,
569 typename GraphT::NodeType* V,
570 unsigned LastLinked);
571
572 template<class GraphT>
573 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
574 typename GraphT::NodeType* V,
575 unsigned N);
576
577 template<class FuncT, class N>
578 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
579 FuncT& F);
580
581 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
582 /// dominator tree in dfs order.
updateDFSNumbers()583 void updateDFSNumbers() {
584 unsigned DFSNum = 0;
585
586 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
587 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
588
589 DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
590
591 if (!ThisRoot)
592 return;
593
594 // Even in the case of multiple exits that form the post dominator root
595 // nodes, do not iterate over all exits, but start from the virtual root
596 // node. Otherwise bbs, that are not post dominated by any exit but by the
597 // virtual root node, will never be assigned a DFS number.
598 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
599 ThisRoot->DFSNumIn = DFSNum++;
600
601 while (!WorkStack.empty()) {
602 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
603 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
604 WorkStack.back().second;
605
606 // If we visited all of the children of this node, "recurse" back up the
607 // stack setting the DFOutNum.
608 if (ChildIt == Node->end()) {
609 Node->DFSNumOut = DFSNum++;
610 WorkStack.pop_back();
611 } else {
612 // Otherwise, recursively visit this child.
613 DomTreeNodeBase<NodeT> *Child = *ChildIt;
614 ++WorkStack.back().second;
615
616 WorkStack.push_back(std::make_pair(Child, Child->begin()));
617 Child->DFSNumIn = DFSNum++;
618 }
619 }
620
621 SlowQueries = 0;
622 DFSInfoValid = true;
623 }
624
getNodeForBlock(NodeT * BB)625 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
626 typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.find(BB);
627 if (I != this->DomTreeNodes.end() && I->second)
628 return I->second;
629
630 // Haven't calculated this node yet? Get or calculate the node for the
631 // immediate dominator.
632 NodeT *IDom = getIDom(BB);
633
634 assert(IDom || this->DomTreeNodes[NULL]);
635 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
636
637 // Add a new tree node for this BasicBlock, and link it as a child of
638 // IDomNode
639 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
640 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
641 }
642
getIDom(NodeT * BB)643 inline NodeT *getIDom(NodeT *BB) const {
644 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
645 return I != IDoms.end() ? I->second : 0;
646 }
647
addRoot(NodeT * BB)648 inline void addRoot(NodeT* BB) {
649 this->Roots.push_back(BB);
650 }
651
652 public:
653 /// recalculate - compute a dominator tree for the given function
654 template<class FT>
recalculate(FT & F)655 void recalculate(FT& F) {
656 reset();
657 this->Vertex.push_back(0);
658
659 if (!this->IsPostDominators) {
660 // Initialize root
661 this->Roots.push_back(&F.front());
662 this->IDoms[&F.front()] = 0;
663 this->DomTreeNodes[&F.front()] = 0;
664
665 Calculate<FT, NodeT*>(*this, F);
666 } else {
667 // Initialize the roots list
668 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
669 if (std::distance(GraphTraits<FT*>::child_begin(I),
670 GraphTraits<FT*>::child_end(I)) == 0)
671 addRoot(I);
672
673 // Prepopulate maps so that we don't get iterator invalidation issues later.
674 this->IDoms[I] = 0;
675 this->DomTreeNodes[I] = 0;
676 }
677
678 Calculate<FT, Inverse<NodeT*> >(*this, F);
679 }
680 }
681 };
682
683 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
684
685 //===-------------------------------------
686 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
687 /// compute a normal dominator tree.
688 ///
689 class DominatorTree : public FunctionPass {
690 public:
691 static char ID; // Pass ID, replacement for typeid
692 DominatorTreeBase<BasicBlock>* DT;
693
DominatorTree()694 DominatorTree() : FunctionPass(ID) {
695 initializeDominatorTreePass(*PassRegistry::getPassRegistry());
696 DT = new DominatorTreeBase<BasicBlock>(false);
697 }
698
~DominatorTree()699 ~DominatorTree() {
700 delete DT;
701 }
702
getBase()703 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
704
705 /// getRoots - Return the root blocks of the current CFG. This may include
706 /// multiple blocks if we are computing post dominators. For forward
707 /// dominators, this will always be a single block (the entry node).
708 ///
getRoots()709 inline const std::vector<BasicBlock*> &getRoots() const {
710 return DT->getRoots();
711 }
712
getRoot()713 inline BasicBlock *getRoot() const {
714 return DT->getRoot();
715 }
716
getRootNode()717 inline DomTreeNode *getRootNode() const {
718 return DT->getRootNode();
719 }
720
721 /// compare - Return false if the other dominator tree matches this
722 /// dominator tree. Otherwise return true.
compare(DominatorTree & Other)723 inline bool compare(DominatorTree &Other) const {
724 DomTreeNode *R = getRootNode();
725 DomTreeNode *OtherR = Other.getRootNode();
726
727 if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
728 return true;
729
730 if (DT->compare(Other.getBase()))
731 return true;
732
733 return false;
734 }
735
736 virtual bool runOnFunction(Function &F);
737
738 virtual void verifyAnalysis() const;
739
getAnalysisUsage(AnalysisUsage & AU)740 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
741 AU.setPreservesAll();
742 }
743
dominates(const DomTreeNode * A,const DomTreeNode * B)744 inline bool dominates(const DomTreeNode* A, const DomTreeNode* B) const {
745 return DT->dominates(A, B);
746 }
747
dominates(const BasicBlock * A,const BasicBlock * B)748 inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
749 return DT->dominates(A, B);
750 }
751
752 // dominates - Return true if A dominates B. This performs the
753 // special checks necessary if A and B are in the same basic block.
754 bool dominates(const Instruction *A, const Instruction *B) const;
755
properlyDominates(const DomTreeNode * A,const DomTreeNode * B)756 bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
757 return DT->properlyDominates(A, B);
758 }
759
properlyDominates(const BasicBlock * A,const BasicBlock * B)760 bool properlyDominates(const BasicBlock *A, const BasicBlock *B) const {
761 return DT->properlyDominates(A, B);
762 }
763
764 /// findNearestCommonDominator - Find nearest common dominator basic block
765 /// for basic block A and B. If there is no such block then return NULL.
findNearestCommonDominator(BasicBlock * A,BasicBlock * B)766 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
767 return DT->findNearestCommonDominator(A, B);
768 }
769
findNearestCommonDominator(const BasicBlock * A,const BasicBlock * B)770 inline const BasicBlock *findNearestCommonDominator(const BasicBlock *A,
771 const BasicBlock *B) {
772 return DT->findNearestCommonDominator(A, B);
773 }
774
775 inline DomTreeNode *operator[](BasicBlock *BB) const {
776 return DT->getNode(BB);
777 }
778
779 /// getNode - return the (Post)DominatorTree node for the specified basic
780 /// block. This is the same as using operator[] on this class.
781 ///
getNode(BasicBlock * BB)782 inline DomTreeNode *getNode(BasicBlock *BB) const {
783 return DT->getNode(BB);
784 }
785
786 /// addNewBlock - Add a new node to the dominator tree information. This
787 /// creates a new node as a child of DomBB dominator node,linking it into
788 /// the children list of the immediate dominator.
addNewBlock(BasicBlock * BB,BasicBlock * DomBB)789 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
790 return DT->addNewBlock(BB, DomBB);
791 }
792
793 /// changeImmediateDominator - This method is used to update the dominator
794 /// tree information when a node's immediate dominator changes.
795 ///
changeImmediateDominator(BasicBlock * N,BasicBlock * NewIDom)796 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
797 DT->changeImmediateDominator(N, NewIDom);
798 }
799
changeImmediateDominator(DomTreeNode * N,DomTreeNode * NewIDom)800 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
801 DT->changeImmediateDominator(N, NewIDom);
802 }
803
804 /// eraseNode - Removes a node from the dominator tree. Block must not
805 /// dominate any other blocks. Removes node from its immediate dominator's
806 /// children list. Deletes dominator node associated with basic block BB.
eraseNode(BasicBlock * BB)807 inline void eraseNode(BasicBlock *BB) {
808 DT->eraseNode(BB);
809 }
810
811 /// splitBlock - BB is split and now it has one successor. Update dominator
812 /// tree to reflect this change.
splitBlock(BasicBlock * NewBB)813 inline void splitBlock(BasicBlock* NewBB) {
814 DT->splitBlock(NewBB);
815 }
816
isReachableFromEntry(const BasicBlock * A)817 bool isReachableFromEntry(const BasicBlock* A) {
818 return DT->isReachableFromEntry(A);
819 }
820
821
releaseMemory()822 virtual void releaseMemory() {
823 DT->releaseMemory();
824 }
825
826 virtual void print(raw_ostream &OS, const Module* M= 0) const;
827 };
828
829 //===-------------------------------------
830 /// DominatorTree GraphTraits specialization so the DominatorTree can be
831 /// iterable by generic graph iterators.
832 ///
833 template <> struct GraphTraits<DomTreeNode*> {
834 typedef DomTreeNode NodeType;
835 typedef NodeType::iterator ChildIteratorType;
836
837 static NodeType *getEntryNode(NodeType *N) {
838 return N;
839 }
840 static inline ChildIteratorType child_begin(NodeType *N) {
841 return N->begin();
842 }
843 static inline ChildIteratorType child_end(NodeType *N) {
844 return N->end();
845 }
846
847 typedef df_iterator<DomTreeNode*> nodes_iterator;
848
849 static nodes_iterator nodes_begin(DomTreeNode *N) {
850 return df_begin(getEntryNode(N));
851 }
852
853 static nodes_iterator nodes_end(DomTreeNode *N) {
854 return df_end(getEntryNode(N));
855 }
856 };
857
858 template <> struct GraphTraits<DominatorTree*>
859 : public GraphTraits<DomTreeNode*> {
860 static NodeType *getEntryNode(DominatorTree *DT) {
861 return DT->getRootNode();
862 }
863
864 static nodes_iterator nodes_begin(DominatorTree *N) {
865 return df_begin(getEntryNode(N));
866 }
867
868 static nodes_iterator nodes_end(DominatorTree *N) {
869 return df_end(getEntryNode(N));
870 }
871 };
872
873
874 } // End llvm namespace
875
876 #endif
877