1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
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 defines the following classes:
11 // 1. ImmediateDominators: Calculates and holds a mapping between BasicBlocks
12 // and their immediate dominator.
13 // 2. DominatorTree: Represent the ImmediateDominator as an explicit tree
15 // 3. ETForest: Efficient data structure for dominance comparisons and
16 // nearest-common-ancestor queries.
17 // 4. DominanceFrontier: Calculate and hold the dominance frontier for a
20 // These data structures are listed in increasing order of complexity. It
21 // takes longer to calculate the dominator frontier, for example, than the
22 // ImmediateDominator mapping.
24 //===----------------------------------------------------------------------===//
26 #ifndef LLVM_ANALYSIS_DOMINATORS_H
27 #define LLVM_ANALYSIS_DOMINATORS_H
29 #include "llvm/Analysis/ET-Forest.h"
30 #include "llvm/Pass.h"
37 template <typename GraphType> struct GraphTraits;
39 //===----------------------------------------------------------------------===//
40 /// DominatorBase - Base class that other, more interesting dominator analyses
43 class DominatorBase : public FunctionPass {
45 std::vector<BasicBlock*> Roots;
46 const bool IsPostDominators;
48 inline DominatorBase(bool isPostDom) : Roots(), IsPostDominators(isPostDom) {}
50 /// getRoots - Return the root blocks of the current CFG. This may include
51 /// multiple blocks if we are computing post dominators. For forward
52 /// dominators, this will always be a single block (the entry node).
54 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
56 /// isPostDominator - Returns true if analysis based of postdoms
58 bool isPostDominator() const { return IsPostDominators; }
62 //===----------------------------------------------------------------------===//
63 /// ImmediateDominators - Calculate the immediate dominator for each node in a
66 class ImmediateDominatorsBase : public DominatorBase {
71 BasicBlock *Label, *Parent, *Child, *Ancestor;
73 std::vector<BasicBlock*> Bucket;
75 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){}
78 std::map<BasicBlock*, BasicBlock*> IDoms;
80 // Vertex - Map the DFS number to the BasicBlock*
81 std::vector<BasicBlock*> Vertex;
83 // Info - Collection of information used during the computation of idoms.
84 std::map<BasicBlock*, InfoRec> Info;
86 ImmediateDominatorsBase(bool isPostDom) : DominatorBase(isPostDom) {}
88 virtual void releaseMemory() { IDoms.clear(); }
90 // Accessor interface:
91 typedef std::map<BasicBlock*, BasicBlock*> IDomMapType;
92 typedef IDomMapType::const_iterator const_iterator;
93 inline const_iterator begin() const { return IDoms.begin(); }
94 inline const_iterator end() const { return IDoms.end(); }
95 inline const_iterator find(BasicBlock* B) const { return IDoms.find(B);}
97 /// operator[] - Return the idom for the specified basic block. The start
98 /// node returns null, because it does not have an immediate dominator.
100 inline BasicBlock *operator[](BasicBlock *BB) const {
104 /// dominates - Return true if A dominates B.
106 bool dominates(BasicBlock *A, BasicBlock *B) const;
108 /// properlyDominates - Return true if A dominates B and A != B.
110 bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
111 return A != B || properlyDominates(A, B);
114 /// get() - Synonym for operator[].
116 inline BasicBlock *get(BasicBlock *BB) const {
117 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB);
118 return I != IDoms.end() ? I->second : 0;
121 //===--------------------------------------------------------------------===//
122 // API to update Immediate(Post)Dominators information based on modifications
125 /// addNewBlock - Add a new block to the CFG, with the specified immediate
128 void addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
129 assert(get(BB) == 0 && "BasicBlock already in idom info!");
133 /// setImmediateDominator - Update the immediate dominator information to
134 /// change the current immediate dominator for the specified block to another
135 /// block. This method requires that BB already have an IDom, otherwise just
138 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom) {
139 assert(IDoms.find(BB) != IDoms.end() && "BB doesn't have idom yet!");
143 /// print - Convert to human readable form
145 virtual void print(std::ostream &OS, const Module* = 0) const;
146 void print(std::ostream *OS, const Module* M = 0) const {
147 if (OS) print(*OS, M);
151 //===-------------------------------------
152 /// ImmediateDominators Class - Concrete subclass of ImmediateDominatorsBase
153 /// that is used to compute a normal immediate dominator set.
155 class ImmediateDominators : public ImmediateDominatorsBase {
157 ImmediateDominators() : ImmediateDominatorsBase(false) {}
159 BasicBlock *getRoot() const {
160 assert(Roots.size() == 1 && "Should always have entry node!");
164 virtual bool runOnFunction(Function &F);
166 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
167 AU.setPreservesAll();
171 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N);
172 void Compress(BasicBlock *V, InfoRec &VInfo);
173 BasicBlock *Eval(BasicBlock *v);
174 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo);
178 //===----------------------------------------------------------------------===//
179 /// DominatorTree - Calculate the immediate dominator tree for a function.
181 class DominatorTreeBase : public DominatorBase {
185 std::map<BasicBlock*, Node*> Nodes;
187 typedef std::map<BasicBlock*, Node*> NodeMapType;
192 friend class DominatorTree;
193 friend struct PostDominatorTree;
194 friend class DominatorTreeBase;
197 std::vector<Node*> Children;
199 typedef std::vector<Node*>::iterator iterator;
200 typedef std::vector<Node*>::const_iterator const_iterator;
202 iterator begin() { return Children.begin(); }
203 iterator end() { return Children.end(); }
204 const_iterator begin() const { return Children.begin(); }
205 const_iterator end() const { return Children.end(); }
207 inline BasicBlock *getBlock() const { return TheBB; }
208 inline Node *getIDom() const { return IDom; }
209 inline const std::vector<Node*> &getChildren() const { return Children; }
211 /// properlyDominates - Returns true iff this dominates N and this != N.
212 /// Note that this is not a constant time operation!
214 bool properlyDominates(const Node *N) const {
216 if (this == 0 || N == 0) return false;
217 while ((IDom = N->getIDom()) != 0 && IDom != this)
218 N = IDom; // Walk up the tree
222 /// dominates - Returns true iff this dominates N. Note that this is not a
223 /// constant time operation!
225 inline bool dominates(const Node *N) const {
226 if (N == this) return true; // A node trivially dominates itself.
227 return properlyDominates(N);
231 inline Node(BasicBlock *BB, Node *iDom) : TheBB(BB), IDom(iDom) {}
232 inline Node *addChild(Node *C) { Children.push_back(C); return C; }
234 void setIDom(Node *NewIDom);
238 DominatorTreeBase(bool isPostDom) : DominatorBase(isPostDom) {}
239 ~DominatorTreeBase() { reset(); }
241 virtual void releaseMemory() { reset(); }
243 /// getNode - return the (Post)DominatorTree node for the specified basic
244 /// block. This is the same as using operator[] on this class.
246 inline Node *getNode(BasicBlock *BB) const {
247 NodeMapType::const_iterator i = Nodes.find(BB);
248 return (i != Nodes.end()) ? i->second : 0;
251 inline Node *operator[](BasicBlock *BB) const {
255 /// getRootNode - This returns the entry node for the CFG of the function. If
256 /// this tree represents the post-dominance relations for a function, however,
257 /// this root may be a node with the block == NULL. This is the case when
258 /// there are multiple exit nodes from a particular function. Consumers of
259 /// post-dominance information must be capable of dealing with this
262 Node *getRootNode() { return RootNode; }
263 const Node *getRootNode() const { return RootNode; }
265 //===--------------------------------------------------------------------===//
266 // API to update (Post)DominatorTree information based on modifications to
269 /// createNewNode - Add a new node to the dominator tree information. This
270 /// creates a new node as a child of IDomNode, linking it into the children
271 /// list of the immediate dominator.
273 Node *createNewNode(BasicBlock *BB, Node *IDomNode) {
274 assert(getNode(BB) == 0 && "Block already in dominator tree!");
275 assert(IDomNode && "Not immediate dominator specified for block!");
276 return Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
279 /// changeImmediateDominator - This method is used to update the dominator
280 /// tree information when a node's immediate dominator changes.
282 void changeImmediateDominator(Node *N, Node *NewIDom) {
283 assert(N && NewIDom && "Cannot change null node pointers!");
287 /// removeNode - Removes a node from the dominator tree. Block must not
288 /// dominate any other blocks. Invalidates any node pointing to removed
290 void removeNode(BasicBlock *BB) {
291 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
295 /// print - Convert to human readable form
297 virtual void print(std::ostream &OS, const Module* = 0) const;
298 void print(std::ostream *OS, const Module* M = 0) const {
299 if (OS) print(*OS, M);
303 //===-------------------------------------
304 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
305 /// compute a normal dominator tree.
307 class DominatorTree : public DominatorTreeBase {
309 DominatorTree() : DominatorTreeBase(false) {}
311 BasicBlock *getRoot() const {
312 assert(Roots.size() == 1 && "Should always have entry node!");
316 virtual bool runOnFunction(Function &F) {
317 reset(); // Reset from the last time we were run...
318 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
319 Roots = ID.getRoots();
324 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
325 AU.setPreservesAll();
326 AU.addRequired<ImmediateDominators>();
329 void calculate(const ImmediateDominators &ID);
330 Node *getNodeForBlock(BasicBlock *BB);
333 //===-------------------------------------
334 /// DominatorTree GraphTraits specialization so the DominatorTree can be
335 /// iterable by generic graph iterators.
337 template <> struct GraphTraits<DominatorTree::Node*> {
338 typedef DominatorTree::Node NodeType;
339 typedef NodeType::iterator ChildIteratorType;
341 static NodeType *getEntryNode(NodeType *N) {
344 static inline ChildIteratorType child_begin(NodeType* N) {
347 static inline ChildIteratorType child_end(NodeType* N) {
352 template <> struct GraphTraits<DominatorTree*>
353 : public GraphTraits<DominatorTree::Node*> {
354 static NodeType *getEntryNode(DominatorTree *DT) {
355 return DT->getRootNode();
360 //===-------------------------------------
361 /// ET-Forest Class - Class used to construct forwards and backwards
364 class ETForestBase : public DominatorBase {
366 ETForestBase(bool isPostDom) : DominatorBase(isPostDom), Nodes(),
367 DFSInfoValid(false), SlowQueries(0) {}
369 virtual void releaseMemory() { reset(); }
371 typedef std::map<BasicBlock*, ETNode*> ETMapType;
373 void updateDFSNumbers();
375 /// dominates - Return true if A dominates B.
377 inline bool dominates(BasicBlock *A, BasicBlock *B) {
381 ETNode *NodeA = getNode(A);
382 ETNode *NodeB = getNode(B);
385 return NodeB->DominatedBy(NodeA);
387 // If we end up with too many slow queries, just update the
388 // DFS numbers on the theory that we are going to keep querying.
390 if (SlowQueries > 32) {
392 return NodeB->DominatedBy(NodeA);
394 return NodeB->DominatedBySlow(NodeA);
398 // dominates - Return true if A dominates B. THis performs the
399 // special checks necessary if A and B are in the same basic block.
400 bool dominates(Instruction *A, Instruction *B);
402 /// properlyDominates - Return true if A dominates B and A != B.
404 bool properlyDominates(BasicBlock *A, BasicBlock *B) {
405 return dominates(A, B) && A != B;
408 /// Return the nearest common dominator of A and B.
409 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const {
410 ETNode *NodeA = getNode(A);
411 ETNode *NodeB = getNode(B);
413 ETNode *Common = NodeA->NCA(NodeB);
416 return Common->getData<BasicBlock>();
419 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
420 AU.setPreservesAll();
421 AU.addRequired<ImmediateDominators>();
423 //===--------------------------------------------------------------------===//
424 // API to update Forest information based on modifications
427 /// addNewBlock - Add a new block to the CFG, with the specified immediate
430 void addNewBlock(BasicBlock *BB, BasicBlock *IDom);
432 /// setImmediateDominator - Update the immediate dominator information to
433 /// change the current immediate dominator for the specified block
434 /// to another block. This method requires that BB for NewIDom
435 /// already have an ETNode, otherwise just use addNewBlock.
437 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom);
438 /// print - Convert to human readable form
440 virtual void print(std::ostream &OS, const Module* = 0) const;
441 void print(std::ostream *OS, const Module* M = 0) const {
442 if (OS) print(*OS, M);
445 /// getNode - return the (Post)DominatorTree node for the specified basic
446 /// block. This is the same as using operator[] on this class.
448 inline ETNode *getNode(BasicBlock *BB) const {
449 ETMapType::const_iterator i = Nodes.find(BB);
450 return (i != Nodes.end()) ? i->second : 0;
453 inline ETNode *operator[](BasicBlock *BB) const {
460 unsigned int SlowQueries;
464 //==-------------------------------------
465 /// ETForest Class - Concrete subclass of ETForestBase that is used to
466 /// compute a forwards ET-Forest.
468 class ETForest : public ETForestBase {
470 ETForest() : ETForestBase(false) {}
472 BasicBlock *getRoot() const {
473 assert(Roots.size() == 1 && "Should always have entry node!");
477 virtual bool runOnFunction(Function &F) {
478 reset(); // Reset from the last time we were run...
479 ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
480 Roots = ID.getRoots();
485 void calculate(const ImmediateDominators &ID);
486 ETNode *getNodeForBlock(BasicBlock *BB);
489 //===----------------------------------------------------------------------===//
490 /// DominanceFrontierBase - Common base class for computing forward and inverse
491 /// dominance frontiers for a function.
493 class DominanceFrontierBase : public DominatorBase {
495 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
496 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
498 DomSetMapType Frontiers;
500 DominanceFrontierBase(bool isPostDom) : DominatorBase(isPostDom) {}
502 virtual void releaseMemory() { Frontiers.clear(); }
504 // Accessor interface:
505 typedef DomSetMapType::iterator iterator;
506 typedef DomSetMapType::const_iterator const_iterator;
507 iterator begin() { return Frontiers.begin(); }
508 const_iterator begin() const { return Frontiers.begin(); }
509 iterator end() { return Frontiers.end(); }
510 const_iterator end() const { return Frontiers.end(); }
511 iterator find(BasicBlock *B) { return Frontiers.find(B); }
512 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
514 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
515 assert(find(BB) == end() && "Block already in DominanceFrontier!");
516 Frontiers.insert(std::make_pair(BB, frontier));
519 void addToFrontier(iterator I, BasicBlock *Node) {
520 assert(I != end() && "BB is not in DominanceFrontier!");
521 I->second.insert(Node);
524 void removeFromFrontier(iterator I, BasicBlock *Node) {
525 assert(I != end() && "BB is not in DominanceFrontier!");
526 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
527 I->second.erase(Node);
530 /// print - Convert to human readable form
532 virtual void print(std::ostream &OS, const Module* = 0) const;
533 void print(std::ostream *OS, const Module* M = 0) const {
534 if (OS) print(*OS, M);
539 //===-------------------------------------
540 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
541 /// used to compute a forward dominator frontiers.
543 class DominanceFrontier : public DominanceFrontierBase {
545 DominanceFrontier() : DominanceFrontierBase(false) {}
547 BasicBlock *getRoot() const {
548 assert(Roots.size() == 1 && "Should always have entry node!");
552 virtual bool runOnFunction(Function &) {
554 DominatorTree &DT = getAnalysis<DominatorTree>();
555 Roots = DT.getRoots();
556 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
557 calculate(DT, DT[Roots[0]]);
561 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
562 AU.setPreservesAll();
563 AU.addRequired<DominatorTree>();
566 const DomSetType &calculate(const DominatorTree &DT,
567 const DominatorTree::Node *Node);
571 } // End llvm namespace