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/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/Streams.h"
31 static std::ostream &operator<<(std::ostream &o,
32 const std::set<BasicBlock*> &BBs) {
33 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
36 WriteAsOperand(o, *I, false);
38 o << " <<exit node>>";
43 //===----------------------------------------------------------------------===//
44 // DominatorTree Implementation
45 //===----------------------------------------------------------------------===//
47 // Provide public access to DominatorTree information. Implementation details
48 // can be found in DominatorCalculation.h.
50 //===----------------------------------------------------------------------===//
52 TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
53 TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
55 char DominatorTree::ID = 0;
56 static RegisterPass<DominatorTree>
57 E("domtree", "Dominator Tree Construction", true);
59 // NewBB is split and now it has one successor. Update dominator tree to
60 // reflect this change.
61 void DominatorTree::splitBlock(BasicBlock *NewBB) {
62 assert(NewBB->getTerminator()->getNumSuccessors() == 1
63 && "NewBB should have a single successor!");
64 BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
66 std::vector<BasicBlock*> PredBlocks;
67 for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
69 PredBlocks.push_back(*PI);
71 assert(!PredBlocks.empty() && "No predblocks??");
73 // The newly inserted basic block will dominate existing basic blocks iff the
74 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
75 // the non-pred blocks, then they all must be the same block!
77 bool NewBBDominatesNewBBSucc = true;
79 BasicBlock *OnePred = PredBlocks[0];
80 unsigned i = 1, e = PredBlocks.size();
81 for (i = 1; !isReachableFromEntry(OnePred); ++i) {
82 assert(i != e && "Didn't find reachable pred?");
83 OnePred = PredBlocks[i];
87 if (PredBlocks[i] != OnePred && isReachableFromEntry(OnePred)) {
88 NewBBDominatesNewBBSucc = false;
92 if (NewBBDominatesNewBBSucc)
93 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
95 if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
96 NewBBDominatesNewBBSucc = false;
101 // The other scenario where the new block can dominate its successors are when
102 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
104 if (!NewBBDominatesNewBBSucc) {
105 NewBBDominatesNewBBSucc = true;
106 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
108 if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
109 NewBBDominatesNewBBSucc = false;
114 // Find NewBB's immediate dominator and create new dominator tree node for
116 BasicBlock *NewBBIDom = 0;
118 for (i = 0; i < PredBlocks.size(); ++i)
119 if (isReachableFromEntry(PredBlocks[i])) {
120 NewBBIDom = PredBlocks[i];
123 assert(i != PredBlocks.size() && "No reachable preds?");
124 for (i = i + 1; i < PredBlocks.size(); ++i) {
125 if (isReachableFromEntry(PredBlocks[i]))
126 NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
128 assert(NewBBIDom && "No immediate dominator found??");
130 // Create the new dominator tree node... and set the idom of NewBB.
131 DomTreeNode *NewBBNode = addNewBlock(NewBB, NewBBIDom);
133 // If NewBB strictly dominates other blocks, then it is now the immediate
134 // dominator of NewBBSucc. Update the dominator tree as appropriate.
135 if (NewBBDominatesNewBBSucc) {
136 DomTreeNode *NewBBSuccNode = getNode(NewBBSucc);
137 changeImmediateDominator(NewBBSuccNode, NewBBNode);
141 bool DominatorTree::runOnFunction(Function &F) {
142 reset(); // Reset from the last time we were run...
145 Roots.push_back(&F.getEntryBlock());
146 IDoms[&F.getEntryBlock()] = 0;
147 DomTreeNodes[&F.getEntryBlock()] = 0;
150 Calculate<BasicBlock*, GraphTraits<BasicBlock*> >(*this, F);
157 //===----------------------------------------------------------------------===//
158 // DominanceFrontier Implementation
159 //===----------------------------------------------------------------------===//
161 char DominanceFrontier::ID = 0;
162 static RegisterPass<DominanceFrontier>
163 G("domfrontier", "Dominance Frontier Construction", true);
165 // NewBB is split and now it has one successor. Update dominace frontier to
166 // reflect this change.
167 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
168 assert(NewBB->getTerminator()->getNumSuccessors() == 1
169 && "NewBB should have a single successor!");
170 BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
172 std::vector<BasicBlock*> PredBlocks;
173 for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
175 PredBlocks.push_back(*PI);
177 if (PredBlocks.empty())
178 // If NewBB does not have any predecessors then it is a entry block.
179 // In this case, NewBB and its successor NewBBSucc dominates all
183 // NewBBSucc inherits original NewBB frontier.
184 DominanceFrontier::iterator NewBBI = find(NewBB);
185 if (NewBBI != end()) {
186 DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
187 DominanceFrontier::DomSetType NewBBSuccSet;
188 NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
189 addBasicBlock(NewBBSucc, NewBBSuccSet);
192 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
193 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
195 DominatorTree &DT = getAnalysis<DominatorTree>();
196 if (DT.dominates(NewBB, NewBBSucc)) {
197 DominanceFrontier::iterator DFI = find(PredBlocks[0]);
199 DominanceFrontier::DomSetType Set = DFI->second;
200 // Filter out stuff in Set that we do not dominate a predecessor of.
201 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
202 E = Set.end(); SetI != E;) {
203 bool DominatesPred = false;
204 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
206 if (DT.dominates(NewBB, *PI))
207 DominatesPred = true;
214 if (NewBBI != end()) {
215 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
216 E = Set.end(); SetI != E; ++SetI) {
217 BasicBlock *SB = *SetI;
218 addToFrontier(NewBBI, SB);
221 addBasicBlock(NewBB, Set);
225 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
226 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
227 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
228 DominanceFrontier::DomSetType NewDFSet;
229 NewDFSet.insert(NewBBSucc);
230 addBasicBlock(NewBB, NewDFSet);
233 // Now we must loop over all of the dominance frontiers in the function,
234 // replacing occurrences of NewBBSucc with NewBB in some cases. All
235 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
236 // their dominance frontier must be updated to contain NewBB instead.
238 for (Function::iterator FI = NewBB->getParent()->begin(),
239 FE = NewBB->getParent()->end(); FI != FE; ++FI) {
240 DominanceFrontier::iterator DFI = find(FI);
241 if (DFI == end()) continue; // unreachable block.
243 // Only consider nodes that have NewBBSucc in their dominator frontier.
244 if (!DFI->second.count(NewBBSucc)) continue;
246 // Verify whether this block dominates a block in predblocks. If not, do
248 bool BlockDominatesAny = false;
249 for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(),
250 BE = PredBlocks.end(); BI != BE; ++BI) {
251 if (DT.dominates(FI, *BI)) {
252 BlockDominatesAny = true;
257 if (!BlockDominatesAny)
260 // If NewBBSucc should not stay in our dominator frontier, remove it.
261 // We remove it unless there is a predecessor of NewBBSucc that we
262 // dominate, but we don't strictly dominate NewBBSucc.
263 bool ShouldRemove = true;
264 if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
265 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
266 // Check to see if it dominates any predecessors of NewBBSucc.
267 for (pred_iterator PI = pred_begin(NewBBSucc),
268 E = pred_end(NewBBSucc); PI != E; ++PI)
269 if (DT.dominates(FI, *PI)) {
270 ShouldRemove = false;
276 removeFromFrontier(DFI, NewBBSucc);
277 addToFrontier(DFI, NewBB);
282 class DFCalculateWorkObject {
284 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
285 const DomTreeNode *N,
286 const DomTreeNode *PN)
287 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
288 BasicBlock *currentBB;
289 BasicBlock *parentBB;
290 const DomTreeNode *Node;
291 const DomTreeNode *parentNode;
295 const DominanceFrontier::DomSetType &
296 DominanceFrontier::calculate(const DominatorTree &DT,
297 const DomTreeNode *Node) {
298 BasicBlock *BB = Node->getBlock();
299 DomSetType *Result = NULL;
301 std::vector<DFCalculateWorkObject> workList;
302 SmallPtrSet<BasicBlock *, 32> visited;
304 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
306 DFCalculateWorkObject *currentW = &workList.back();
307 assert (currentW && "Missing work object.");
309 BasicBlock *currentBB = currentW->currentBB;
310 BasicBlock *parentBB = currentW->parentBB;
311 const DomTreeNode *currentNode = currentW->Node;
312 const DomTreeNode *parentNode = currentW->parentNode;
313 assert (currentBB && "Invalid work object. Missing current Basic Block");
314 assert (currentNode && "Invalid work object. Missing current Node");
315 DomSetType &S = Frontiers[currentBB];
317 // Visit each block only once.
318 if (visited.count(currentBB) == 0) {
319 visited.insert(currentBB);
321 // Loop over CFG successors to calculate DFlocal[currentNode]
322 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
324 // Does Node immediately dominate this successor?
325 if (DT[*SI]->getIDom() != currentNode)
330 // At this point, S is DFlocal. Now we union in DFup's of our children...
331 // Loop through and visit the nodes that Node immediately dominates (Node's
332 // children in the IDomTree)
333 bool visitChild = false;
334 for (DomTreeNode::const_iterator NI = currentNode->begin(),
335 NE = currentNode->end(); NI != NE; ++NI) {
336 DomTreeNode *IDominee = *NI;
337 BasicBlock *childBB = IDominee->getBlock();
338 if (visited.count(childBB) == 0) {
339 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
340 IDominee, currentNode));
345 // If all children are visited or there is any child then pop this block
346 // from the workList.
354 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
355 DomSetType &parentSet = Frontiers[parentBB];
356 for (; CDFI != CDFE; ++CDFI) {
357 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
358 parentSet.insert(*CDFI);
363 } while (!workList.empty());
368 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
369 for (const_iterator I = begin(), E = end(); I != E; ++I) {
370 o << " DomFrontier for BB";
372 WriteAsOperand(o, I->first, false);
374 o << " <<exit node>>";
375 o << " is:\t" << I->second << "\n";
379 void DominanceFrontierBase::dump() {