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/IR/Dominators.h" 18 #include "llvm/ADT/DepthFirstIterator.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/IR/CFG.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/Instructions.h" 23 #include "llvm/IR/PassManager.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/GenericDomTreeConstruction.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include <algorithm> 29 using namespace llvm; 30 31 // Always verify dominfo if expensive checking is enabled. 32 #ifdef EXPENSIVE_CHECKS 33 bool llvm::VerifyDomInfo = true; 34 #else 35 bool llvm::VerifyDomInfo = false; 36 #endif 37 static cl::opt<bool, true> 38 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo), cl::Hidden, 39 cl::desc("Verify dominator info (time consuming)")); 40 41 bool BasicBlockEdge::isSingleEdge() const { 42 const TerminatorInst *TI = Start->getTerminator(); 43 unsigned NumEdgesToEnd = 0; 44 for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) { 45 if (TI->getSuccessor(i) == End) 46 ++NumEdgesToEnd; 47 if (NumEdgesToEnd >= 2) 48 return false; 49 } 50 assert(NumEdgesToEnd == 1); 51 return true; 52 } 53 54 //===----------------------------------------------------------------------===// 55 // DominatorTree Implementation 56 //===----------------------------------------------------------------------===// 57 // 58 // Provide public access to DominatorTree information. Implementation details 59 // can be found in Dominators.h, GenericDomTree.h, and 60 // GenericDomTreeConstruction.h. 61 // 62 //===----------------------------------------------------------------------===// 63 64 template class llvm::DomTreeNodeBase<BasicBlock>; 65 template class llvm::DominatorTreeBase<BasicBlock, false>; // DomTreeBase 66 template class llvm::DominatorTreeBase<BasicBlock, true>; // PostDomTreeBase 67 68 template struct llvm::DomTreeBuilder::Update<BasicBlock *>; 69 70 template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBDomTree>( 71 DomTreeBuilder::BBDomTree &DT); 72 template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBPostDomTree>( 73 DomTreeBuilder::BBPostDomTree &DT); 74 75 template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBDomTree>( 76 DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To); 77 template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBPostDomTree>( 78 DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To); 79 80 template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBDomTree>( 81 DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To); 82 template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBPostDomTree>( 83 DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To); 84 85 template void llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBDomTree>( 86 DomTreeBuilder::BBDomTree &DT, DomTreeBuilder::BBUpdates); 87 template void llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBPostDomTree>( 88 DomTreeBuilder::BBPostDomTree &DT, DomTreeBuilder::BBUpdates); 89 90 template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBDomTree>( 91 const DomTreeBuilder::BBDomTree &DT); 92 template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBPostDomTree>( 93 const DomTreeBuilder::BBPostDomTree &DT); 94 95 bool DominatorTree::invalidate(Function &F, const PreservedAnalyses &PA, 96 FunctionAnalysisManager::Invalidator &) { 97 // Check whether the analysis, all analyses on functions, or the function's 98 // CFG have been preserved. 99 auto PAC = PA.getChecker<DominatorTreeAnalysis>(); 100 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() || 101 PAC.preservedSet<CFGAnalyses>()); 102 } 103 104 // dominates - Return true if Def dominates a use in User. This performs 105 // the special checks necessary if Def and User are in the same basic block. 106 // Note that Def doesn't dominate a use in Def itself! 107 bool DominatorTree::dominates(const Instruction *Def, 108 const Instruction *User) const { 109 const BasicBlock *UseBB = User->getParent(); 110 const BasicBlock *DefBB = Def->getParent(); 111 112 // Any unreachable use is dominated, even if Def == User. 113 if (!isReachableFromEntry(UseBB)) 114 return true; 115 116 // Unreachable definitions don't dominate anything. 117 if (!isReachableFromEntry(DefBB)) 118 return false; 119 120 // An instruction doesn't dominate a use in itself. 121 if (Def == User) 122 return false; 123 124 // The value defined by an invoke dominates an instruction only if it 125 // dominates every instruction in UseBB. 126 // A PHI is dominated only if the instruction dominates every possible use in 127 // the UseBB. 128 if (isa<InvokeInst>(Def) || isa<PHINode>(User)) 129 return dominates(Def, UseBB); 130 131 if (DefBB != UseBB) 132 return dominates(DefBB, UseBB); 133 134 // Loop through the basic block until we find Def or User. 135 BasicBlock::const_iterator I = DefBB->begin(); 136 for (; &*I != Def && &*I != User; ++I) 137 /*empty*/; 138 139 return &*I == Def; 140 } 141 142 // true if Def would dominate a use in any instruction in UseBB. 143 // note that dominates(Def, Def->getParent()) is false. 144 bool DominatorTree::dominates(const Instruction *Def, 145 const BasicBlock *UseBB) const { 146 const BasicBlock *DefBB = Def->getParent(); 147 148 // Any unreachable use is dominated, even if DefBB == UseBB. 149 if (!isReachableFromEntry(UseBB)) 150 return true; 151 152 // Unreachable definitions don't dominate anything. 153 if (!isReachableFromEntry(DefBB)) 154 return false; 155 156 if (DefBB == UseBB) 157 return false; 158 159 // Invoke results are only usable in the normal destination, not in the 160 // exceptional destination. 161 if (const auto *II = dyn_cast<InvokeInst>(Def)) { 162 BasicBlock *NormalDest = II->getNormalDest(); 163 BasicBlockEdge E(DefBB, NormalDest); 164 return dominates(E, UseBB); 165 } 166 167 return dominates(DefBB, UseBB); 168 } 169 170 bool DominatorTree::dominates(const BasicBlockEdge &BBE, 171 const BasicBlock *UseBB) const { 172 // If the BB the edge ends in doesn't dominate the use BB, then the 173 // edge also doesn't. 174 const BasicBlock *Start = BBE.getStart(); 175 const BasicBlock *End = BBE.getEnd(); 176 if (!dominates(End, UseBB)) 177 return false; 178 179 // Simple case: if the end BB has a single predecessor, the fact that it 180 // dominates the use block implies that the edge also does. 181 if (End->getSinglePredecessor()) 182 return true; 183 184 // The normal edge from the invoke is critical. Conceptually, what we would 185 // like to do is split it and check if the new block dominates the use. 186 // With X being the new block, the graph would look like: 187 // 188 // DefBB 189 // /\ . . 190 // / \ . . 191 // / \ . . 192 // / \ | | 193 // A X B C 194 // | \ | / 195 // . \|/ 196 // . NormalDest 197 // . 198 // 199 // Given the definition of dominance, NormalDest is dominated by X iff X 200 // dominates all of NormalDest's predecessors (X, B, C in the example). X 201 // trivially dominates itself, so we only have to find if it dominates the 202 // other predecessors. Since the only way out of X is via NormalDest, X can 203 // only properly dominate a node if NormalDest dominates that node too. 204 int IsDuplicateEdge = 0; 205 for (const_pred_iterator PI = pred_begin(End), E = pred_end(End); 206 PI != E; ++PI) { 207 const BasicBlock *BB = *PI; 208 if (BB == Start) { 209 // If there are multiple edges between Start and End, by definition they 210 // can't dominate anything. 211 if (IsDuplicateEdge++) 212 return false; 213 continue; 214 } 215 216 if (!dominates(End, BB)) 217 return false; 218 } 219 return true; 220 } 221 222 bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const { 223 Instruction *UserInst = cast<Instruction>(U.getUser()); 224 // A PHI in the end of the edge is dominated by it. 225 PHINode *PN = dyn_cast<PHINode>(UserInst); 226 if (PN && PN->getParent() == BBE.getEnd() && 227 PN->getIncomingBlock(U) == BBE.getStart()) 228 return true; 229 230 // Otherwise use the edge-dominates-block query, which 231 // handles the crazy critical edge cases properly. 232 const BasicBlock *UseBB; 233 if (PN) 234 UseBB = PN->getIncomingBlock(U); 235 else 236 UseBB = UserInst->getParent(); 237 return dominates(BBE, UseBB); 238 } 239 240 bool DominatorTree::dominates(const Instruction *Def, const Use &U) const { 241 Instruction *UserInst = cast<Instruction>(U.getUser()); 242 const BasicBlock *DefBB = Def->getParent(); 243 244 // Determine the block in which the use happens. PHI nodes use 245 // their operands on edges; simulate this by thinking of the use 246 // happening at the end of the predecessor block. 247 const BasicBlock *UseBB; 248 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 249 UseBB = PN->getIncomingBlock(U); 250 else 251 UseBB = UserInst->getParent(); 252 253 // Any unreachable use is dominated, even if Def == User. 254 if (!isReachableFromEntry(UseBB)) 255 return true; 256 257 // Unreachable definitions don't dominate anything. 258 if (!isReachableFromEntry(DefBB)) 259 return false; 260 261 // Invoke instructions define their return values on the edges to their normal 262 // successors, so we have to handle them specially. 263 // Among other things, this means they don't dominate anything in 264 // their own block, except possibly a phi, so we don't need to 265 // walk the block in any case. 266 if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) { 267 BasicBlock *NormalDest = II->getNormalDest(); 268 BasicBlockEdge E(DefBB, NormalDest); 269 return dominates(E, U); 270 } 271 272 // If the def and use are in different blocks, do a simple CFG dominator 273 // tree query. 274 if (DefBB != UseBB) 275 return dominates(DefBB, UseBB); 276 277 // Ok, def and use are in the same block. If the def is an invoke, it 278 // doesn't dominate anything in the block. If it's a PHI, it dominates 279 // everything in the block. 280 if (isa<PHINode>(UserInst)) 281 return true; 282 283 // Otherwise, just loop through the basic block until we find Def or User. 284 BasicBlock::const_iterator I = DefBB->begin(); 285 for (; &*I != Def && &*I != UserInst; ++I) 286 /*empty*/; 287 288 return &*I != UserInst; 289 } 290 291 bool DominatorTree::isReachableFromEntry(const Use &U) const { 292 Instruction *I = dyn_cast<Instruction>(U.getUser()); 293 294 // ConstantExprs aren't really reachable from the entry block, but they 295 // don't need to be treated like unreachable code either. 296 if (!I) return true; 297 298 // PHI nodes use their operands on their incoming edges. 299 if (PHINode *PN = dyn_cast<PHINode>(I)) 300 return isReachableFromEntry(PN->getIncomingBlock(U)); 301 302 // Everything else uses their operands in their own block. 303 return isReachableFromEntry(I->getParent()); 304 } 305 306 void DominatorTree::verifyDomTree() const { 307 // Perform the expensive checks only when VerifyDomInfo is set. 308 if (VerifyDomInfo && !verify()) { 309 errs() << "\n~~~~~~~~~~~\n\t\tDomTree verification failed!\n~~~~~~~~~~~\n"; 310 print(errs()); 311 abort(); 312 } 313 314 Function &F = *getRoot()->getParent(); 315 316 DominatorTree OtherDT; 317 OtherDT.recalculate(F); 318 if (compare(OtherDT)) { 319 errs() << "DominatorTree for function " << F.getName() 320 << " is not up to date!\nComputed:\n"; 321 print(errs()); 322 errs() << "\nActual:\n"; 323 OtherDT.print(errs()); 324 errs() << "\nCFG:\n"; 325 F.print(errs()); 326 errs().flush(); 327 abort(); 328 } 329 } 330 331 //===----------------------------------------------------------------------===// 332 // DominatorTreeAnalysis and related pass implementations 333 //===----------------------------------------------------------------------===// 334 // 335 // This implements the DominatorTreeAnalysis which is used with the new pass 336 // manager. It also implements some methods from utility passes. 337 // 338 //===----------------------------------------------------------------------===// 339 340 DominatorTree DominatorTreeAnalysis::run(Function &F, 341 FunctionAnalysisManager &) { 342 DominatorTree DT; 343 DT.recalculate(F); 344 return DT; 345 } 346 347 AnalysisKey DominatorTreeAnalysis::Key; 348 349 DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {} 350 351 PreservedAnalyses DominatorTreePrinterPass::run(Function &F, 352 FunctionAnalysisManager &AM) { 353 OS << "DominatorTree for function: " << F.getName() << "\n"; 354 AM.getResult<DominatorTreeAnalysis>(F).print(OS); 355 356 return PreservedAnalyses::all(); 357 } 358 359 PreservedAnalyses DominatorTreeVerifierPass::run(Function &F, 360 FunctionAnalysisManager &AM) { 361 AM.getResult<DominatorTreeAnalysis>(F).verifyDomTree(); 362 363 return PreservedAnalyses::all(); 364 } 365 366 //===----------------------------------------------------------------------===// 367 // DominatorTreeWrapperPass Implementation 368 //===----------------------------------------------------------------------===// 369 // 370 // The implementation details of the wrapper pass that holds a DominatorTree 371 // suitable for use with the legacy pass manager. 372 // 373 //===----------------------------------------------------------------------===// 374 375 char DominatorTreeWrapperPass::ID = 0; 376 INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree", 377 "Dominator Tree Construction", true, true) 378 379 bool DominatorTreeWrapperPass::runOnFunction(Function &F) { 380 DT.recalculate(F); 381 return false; 382 } 383 384 void DominatorTreeWrapperPass::verifyAnalysis() const { 385 if (VerifyDomInfo) 386 DT.verifyDomTree(); 387 } 388 389 void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const { 390 DT.print(OS); 391 } 392 393 //===----------------------------------------------------------------------===// 394 // DeferredDominance Implementation 395 //===----------------------------------------------------------------------===// 396 // 397 // The implementation details of the DeferredDominance class which allows 398 // one to queue updates to a DominatorTree. 399 // 400 //===----------------------------------------------------------------------===// 401 402 /// \brief Queues multiple updates and discards duplicates. 403 void DeferredDominance::applyUpdates( 404 ArrayRef<DominatorTree::UpdateType> Updates) { 405 SmallVector<DominatorTree::UpdateType, 8> Seen; 406 for (auto U : Updates) 407 // Avoid duplicates to applyUpdate() to save on analysis. 408 if (std::none_of(Seen.begin(), Seen.end(), 409 [U](DominatorTree::UpdateType S) { return S == U; })) { 410 Seen.push_back(U); 411 applyUpdate(U.getKind(), U.getFrom(), U.getTo()); 412 } 413 } 414 415 /// \brief Helper method for a single edge insertion. It's almost always better 416 /// to batch updates and call applyUpdates to quickly remove duplicate edges. 417 /// This is best used when there is only a single insertion needed to update 418 /// Dominators. 419 void DeferredDominance::insertEdge(BasicBlock *From, BasicBlock *To) { 420 applyUpdate(DominatorTree::Insert, From, To); 421 } 422 423 /// \brief Helper method for a single edge deletion. It's almost always better 424 /// to batch updates and call applyUpdates to quickly remove duplicate edges. 425 /// This is best used when there is only a single deletion needed to update 426 /// Dominators. 427 void DeferredDominance::deleteEdge(BasicBlock *From, BasicBlock *To) { 428 applyUpdate(DominatorTree::Delete, From, To); 429 } 430 431 /// \brief Delays the deletion of a basic block until a flush() event. 432 void DeferredDominance::deleteBB(BasicBlock *DelBB) { 433 assert(DelBB && "Invalid push_back of nullptr DelBB."); 434 assert(pred_empty(DelBB) && "DelBB has one or more predecessors."); 435 // DelBB is unreachable and all its instructions are dead. 436 while (!DelBB->empty()) { 437 Instruction &I = DelBB->back(); 438 // Replace used instructions with an arbitrary value (undef). 439 if (!I.use_empty()) 440 I.replaceAllUsesWith(llvm::UndefValue::get(I.getType())); 441 DelBB->getInstList().pop_back(); 442 } 443 // Make sure DelBB has a valid terminator instruction. As long as DelBB is a 444 // Child of Function F it must contain valid IR. 445 new UnreachableInst(DelBB->getContext(), DelBB); 446 DeletedBBs.insert(DelBB); 447 } 448 449 /// \brief Returns true if DelBB is awaiting deletion at a flush() event. 450 bool DeferredDominance::pendingDeletedBB(BasicBlock *DelBB) { 451 if (DeletedBBs.empty()) 452 return false; 453 return DeletedBBs.count(DelBB) != 0; 454 } 455 456 /// \brief Flushes all pending updates and block deletions. Returns a 457 /// correct DominatorTree reference to be used by the caller for analysis. 458 DominatorTree &DeferredDominance::flush() { 459 // Updates to DT must happen before blocks are deleted below. Otherwise the 460 // DT traversal will encounter badref blocks and assert. 461 if (!PendUpdates.empty()) { 462 DT.applyUpdates(PendUpdates); 463 PendUpdates.clear(); 464 } 465 flushDelBB(); 466 return DT; 467 } 468 469 /// \brief Drops all internal state and forces a (slow) recalculation of the 470 /// DominatorTree based on the current state of the LLVM IR in F. This should 471 /// only be used in corner cases such as the Entry block of F being deleted. 472 void DeferredDominance::recalculate(Function &F) { 473 // flushDelBB must be flushed before the recalculation. The state of the IR 474 // must be consistent before the DT traversal algorithm determines the 475 // actual DT. 476 if (flushDelBB() || !PendUpdates.empty()) { 477 DT.recalculate(F); 478 PendUpdates.clear(); 479 } 480 } 481 482 /// \brief Debug method to help view the state of pending updates. 483 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 484 LLVM_DUMP_METHOD void DeferredDominance::dump() const { 485 raw_ostream &OS = llvm::dbgs(); 486 OS << "PendUpdates:\n"; 487 int I = 0; 488 for (auto U : PendUpdates) { 489 OS << " " << I << " : "; 490 ++I; 491 if (U.getKind() == DominatorTree::Insert) 492 OS << "Insert, "; 493 else 494 OS << "Delete, "; 495 BasicBlock *From = U.getFrom(); 496 if (From) { 497 auto S = From->getName(); 498 if (!From->hasName()) 499 S = "(no name)"; 500 OS << S << "(" << From << "), "; 501 } else { 502 OS << "(badref), "; 503 } 504 BasicBlock *To = U.getTo(); 505 if (To) { 506 auto S = To->getName(); 507 if (!To->hasName()) 508 S = "(no_name)"; 509 OS << S << "(" << To << ")\n"; 510 } else { 511 OS << "(badref)\n"; 512 } 513 } 514 OS << "DeletedBBs:\n"; 515 I = 0; 516 for (auto BB : DeletedBBs) { 517 OS << " " << I << " : "; 518 ++I; 519 if (BB->hasName()) 520 OS << BB->getName() << "("; 521 else 522 OS << "(no_name)("; 523 OS << BB << ")\n"; 524 } 525 } 526 #endif 527 528 /// Apply an update (Kind, From, To) to the internal queued updates. The 529 /// update is only added when determined to be necessary. Checks for 530 /// self-domination, unnecessary updates, duplicate requests, and balanced 531 /// pairs of requests are all performed. Returns true if the update is 532 /// queued and false if it is discarded. 533 bool DeferredDominance::applyUpdate(DominatorTree::UpdateKind Kind, 534 BasicBlock *From, BasicBlock *To) { 535 if (From == To) 536 return false; // Cannot dominate self; discard update. 537 538 // Discard updates by inspecting the current state of successors of From. 539 // Since applyUpdate() must be called *after* the Terminator of From is 540 // altered we can determine if the update is unnecessary. 541 bool HasEdge = std::any_of(succ_begin(From), succ_end(From), 542 [To](BasicBlock *B) { return B == To; }); 543 if (Kind == DominatorTree::Insert && !HasEdge) 544 return false; // Unnecessary Insert: edge does not exist in IR. 545 if (Kind == DominatorTree::Delete && HasEdge) 546 return false; // Unnecessary Delete: edge still exists in IR. 547 548 // Analyze pending updates to determine if the update is unnecessary. 549 DominatorTree::UpdateType Update = {Kind, From, To}; 550 DominatorTree::UpdateType Invert = {Kind != DominatorTree::Insert 551 ? DominatorTree::Insert 552 : DominatorTree::Delete, 553 From, To}; 554 for (auto I = PendUpdates.begin(), E = PendUpdates.end(); I != E; ++I) { 555 if (Update == *I) 556 return false; // Discard duplicate updates. 557 if (Invert == *I) { 558 // Update and Invert are both valid (equivalent to a no-op). Remove 559 // Invert from PendUpdates and discard the Update. 560 PendUpdates.erase(I); 561 return false; 562 } 563 } 564 PendUpdates.push_back(Update); // Save the valid update. 565 return true; 566 } 567 568 /// Performs all pending basic block deletions. We have to defer the deletion 569 /// of these blocks until after the DominatorTree updates are applied. The 570 /// internal workings of the DominatorTree code expect every update's From 571 /// and To blocks to exist and to be a member of the same Function. 572 bool DeferredDominance::flushDelBB() { 573 if (DeletedBBs.empty()) 574 return false; 575 for (auto *BB : DeletedBBs) 576 BB->eraseFromParent(); 577 DeletedBBs.clear(); 578 return true; 579 } 580