6d0e23d6427b52c148226cbbac066a726f3bd7aa
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
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 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.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Analysis/DominatorInternals.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 using namespace llvm;
29
30 //===----------------------------------------------------------------------===//
31 //  DominatorTree Implementation
32 //===----------------------------------------------------------------------===//
33 //
34 // Provide public access to DominatorTree information.  Implementation details
35 // can be found in DominatorCalculation.h.
36 //
37 //===----------------------------------------------------------------------===//
38
39 TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
40 TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
41
42 char DominatorTree::ID = 0;
43 static RegisterPass<DominatorTree>
44 E("domtree", "Dominator Tree Construction", true, true);
45
46 bool DominatorTree::runOnFunction(Function &F) {
47   DT->recalculate(F);
48   return false;
49 }
50
51 void DominatorTree::print(raw_ostream &OS, const Module *) const {
52   DT->print(OS);
53 }
54
55 // dominates - Return true if A dominates B. This performs the
56 // special checks necessary if A and B are in the same basic block.
57 bool DominatorTree::dominates(const Instruction *A, const Instruction *B) const{
58   const BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
59   if (BBA != BBB) return dominates(BBA, BBB);
60   
61   // It is not possible to determine dominance between two PHI nodes 
62   // based on their ordering.
63   if (isa<PHINode>(A) && isa<PHINode>(B)) 
64     return false;
65   
66   // Loop through the basic block until we find A or B.
67   BasicBlock::const_iterator I = BBA->begin();
68   for (; &*I != A && &*I != B; ++I)
69     /*empty*/;
70   
71   return &*I == A;
72 }
73
74
75
76 //===----------------------------------------------------------------------===//
77 //  DominanceFrontier Implementation
78 //===----------------------------------------------------------------------===//
79
80 char DominanceFrontier::ID = 0;
81 static RegisterPass<DominanceFrontier>
82 G("domfrontier", "Dominance Frontier Construction", true, true);
83
84 // NewBB is split and now it has one successor. Update dominace frontier to
85 // reflect this change.
86 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
87   assert(NewBB->getTerminator()->getNumSuccessors() == 1
88          && "NewBB should have a single successor!");
89   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
90
91   SmallVector<BasicBlock*, 8> PredBlocks;
92   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
93        PI != PE; ++PI)
94       PredBlocks.push_back(*PI);  
95
96   if (PredBlocks.empty())
97     // If NewBB does not have any predecessors then it is a entry block.
98     // In this case, NewBB and its successor NewBBSucc dominates all
99     // other blocks.
100     return;
101
102   // NewBBSucc inherits original NewBB frontier.
103   DominanceFrontier::iterator NewBBI = find(NewBB);
104   if (NewBBI != end()) {
105     DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
106     DominanceFrontier::DomSetType NewBBSuccSet;
107     NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
108     addBasicBlock(NewBBSucc, NewBBSuccSet);
109   }
110
111   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
112   // DF(PredBlocks[0]) without the stuff that the new block does not dominate
113   // a predecessor of.
114   DominatorTree &DT = getAnalysis<DominatorTree>();
115   if (DT.dominates(NewBB, NewBBSucc)) {
116     DominanceFrontier::iterator DFI = find(PredBlocks[0]);
117     if (DFI != end()) {
118       DominanceFrontier::DomSetType Set = DFI->second;
119       // Filter out stuff in Set that we do not dominate a predecessor of.
120       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
121              E = Set.end(); SetI != E;) {
122         bool DominatesPred = false;
123         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
124              PI != E; ++PI)
125           if (DT.dominates(NewBB, *PI))
126             DominatesPred = true;
127         if (!DominatesPred)
128           Set.erase(SetI++);
129         else
130           ++SetI;
131       }
132
133       if (NewBBI != end()) {
134         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
135                E = Set.end(); SetI != E; ++SetI) {
136           BasicBlock *SB = *SetI;
137           addToFrontier(NewBBI, SB);
138         }
139       } else 
140         addBasicBlock(NewBB, Set);
141     }
142     
143   } else {
144     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
145     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
146     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
147     DominanceFrontier::DomSetType NewDFSet;
148     NewDFSet.insert(NewBBSucc);
149     addBasicBlock(NewBB, NewDFSet);
150   }
151   
152   // Now we must loop over all of the dominance frontiers in the function,
153   // replacing occurrences of NewBBSucc with NewBB in some cases.  All
154   // blocks that dominate a block in PredBlocks and contained NewBBSucc in
155   // their dominance frontier must be updated to contain NewBB instead.
156   //
157   for (Function::iterator FI = NewBB->getParent()->begin(),
158          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
159     DominanceFrontier::iterator DFI = find(FI);
160     if (DFI == end()) continue;  // unreachable block.
161     
162     // Only consider nodes that have NewBBSucc in their dominator frontier.
163     if (!DFI->second.count(NewBBSucc)) continue;
164
165     // Verify whether this block dominates a block in predblocks.  If not, do
166     // not update it.
167     bool BlockDominatesAny = false;
168     for (SmallVectorImpl<BasicBlock*>::const_iterator BI = PredBlocks.begin(), 
169            BE = PredBlocks.end(); BI != BE; ++BI) {
170       if (DT.dominates(FI, *BI)) {
171         BlockDominatesAny = true;
172         break;
173       }
174     }
175
176     // If NewBBSucc should not stay in our dominator frontier, remove it.
177     // We remove it unless there is a predecessor of NewBBSucc that we
178     // dominate, but we don't strictly dominate NewBBSucc.
179     bool ShouldRemove = true;
180     if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
181       // Okay, we know that PredDom does not strictly dominate NewBBSucc.
182       // Check to see if it dominates any predecessors of NewBBSucc.
183       for (pred_iterator PI = pred_begin(NewBBSucc),
184            E = pred_end(NewBBSucc); PI != E; ++PI)
185         if (DT.dominates(FI, *PI)) {
186           ShouldRemove = false;
187           break;
188         }
189     }
190     
191     if (ShouldRemove)
192       removeFromFrontier(DFI, NewBBSucc);
193     if (BlockDominatesAny && (&*FI == NewBB || !DT.dominates(FI, NewBB)))
194       addToFrontier(DFI, NewBB);
195   }
196 }
197
198 namespace {
199   class DFCalculateWorkObject {
200   public:
201     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
202                           const DomTreeNode *N,
203                           const DomTreeNode *PN)
204     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
205     BasicBlock *currentBB;
206     BasicBlock *parentBB;
207     const DomTreeNode *Node;
208     const DomTreeNode *parentNode;
209   };
210 }
211
212 const DominanceFrontier::DomSetType &
213 DominanceFrontier::calculate(const DominatorTree &DT,
214                              const DomTreeNode *Node) {
215   BasicBlock *BB = Node->getBlock();
216   DomSetType *Result = NULL;
217
218   std::vector<DFCalculateWorkObject> workList;
219   SmallPtrSet<BasicBlock *, 32> visited;
220
221   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
222   do {
223     DFCalculateWorkObject *currentW = &workList.back();
224     assert (currentW && "Missing work object.");
225
226     BasicBlock *currentBB = currentW->currentBB;
227     BasicBlock *parentBB = currentW->parentBB;
228     const DomTreeNode *currentNode = currentW->Node;
229     const DomTreeNode *parentNode = currentW->parentNode;
230     assert (currentBB && "Invalid work object. Missing current Basic Block");
231     assert (currentNode && "Invalid work object. Missing current Node");
232     DomSetType &S = Frontiers[currentBB];
233
234     // Visit each block only once.
235     if (visited.count(currentBB) == 0) {
236       visited.insert(currentBB);
237
238       // Loop over CFG successors to calculate DFlocal[currentNode]
239       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
240            SI != SE; ++SI) {
241         // Does Node immediately dominate this successor?
242         if (DT[*SI]->getIDom() != currentNode)
243           S.insert(*SI);
244       }
245     }
246
247     // At this point, S is DFlocal.  Now we union in DFup's of our children...
248     // Loop through and visit the nodes that Node immediately dominates (Node's
249     // children in the IDomTree)
250     bool visitChild = false;
251     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
252            NE = currentNode->end(); NI != NE; ++NI) {
253       DomTreeNode *IDominee = *NI;
254       BasicBlock *childBB = IDominee->getBlock();
255       if (visited.count(childBB) == 0) {
256         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
257                                                  IDominee, currentNode));
258         visitChild = true;
259       }
260     }
261
262     // If all children are visited or there is any child then pop this block
263     // from the workList.
264     if (!visitChild) {
265
266       if (!parentBB) {
267         Result = &S;
268         break;
269       }
270
271       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
272       DomSetType &parentSet = Frontiers[parentBB];
273       for (; CDFI != CDFE; ++CDFI) {
274         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
275           parentSet.insert(*CDFI);
276       }
277       workList.pop_back();
278     }
279
280   } while (!workList.empty());
281
282   return *Result;
283 }
284
285 void DominanceFrontierBase::print(raw_ostream &OS, const Module* ) const {
286   for (const_iterator I = begin(), E = end(); I != E; ++I) {
287     OS << "  DomFrontier for BB";
288     if (I->first)
289       WriteAsOperand(OS, I->first, false);
290     else
291       OS << " <<exit node>>";
292     OS << " is:\t";
293     
294     const std::set<BasicBlock*> &BBs = I->second;
295     
296     for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
297          I != E; ++I)
298       if (*I)
299         WriteAsOperand(OS, *I, false);
300       else
301         OS << " <<exit node>>";
302     OS << "\n";
303   }
304 }
305