1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the BasicBlock class for the IR library. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/BasicBlock.h" 14 #include "SymbolTableListTraitsImpl.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/IR/CFG.h" 18 #include "llvm/IR/Constants.h" 19 #include "llvm/IR/Instructions.h" 20 #include "llvm/IR/IntrinsicInst.h" 21 #include "llvm/IR/LLVMContext.h" 22 #include "llvm/IR/Type.h" 23 24 using namespace llvm; 25 26 #define DEBUG_TYPE "ir" 27 STATISTIC(NumInstrRenumberings, "Number of renumberings across all blocks"); 28 29 ValueSymbolTable *BasicBlock::getValueSymbolTable() { 30 if (Function *F = getParent()) 31 return F->getValueSymbolTable(); 32 return nullptr; 33 } 34 35 LLVMContext &BasicBlock::getContext() const { 36 return getType()->getContext(); 37 } 38 39 template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) { 40 BB->invalidateOrders(); 41 } 42 43 // Explicit instantiation of SymbolTableListTraits since some of the methods 44 // are not in the public header file... 45 template class llvm::SymbolTableListTraits<Instruction>; 46 47 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent, 48 BasicBlock *InsertBefore) 49 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) { 50 51 if (NewParent) 52 insertInto(NewParent, InsertBefore); 53 else 54 assert(!InsertBefore && 55 "Cannot insert block before another block with no function!"); 56 57 setName(Name); 58 } 59 60 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) { 61 assert(NewParent && "Expected a parent"); 62 assert(!Parent && "Already has a parent"); 63 64 if (InsertBefore) 65 NewParent->insert(InsertBefore->getIterator(), this); 66 else 67 NewParent->insert(NewParent->end(), this); 68 } 69 70 BasicBlock::~BasicBlock() { 71 validateInstrOrdering(); 72 73 // If the address of the block is taken and it is being deleted (e.g. because 74 // it is dead), this means that there is either a dangling constant expr 75 // hanging off the block, or an undefined use of the block (source code 76 // expecting the address of a label to keep the block alive even though there 77 // is no indirect branch). Handle these cases by zapping the BlockAddress 78 // nodes. There are no other possible uses at this point. 79 if (hasAddressTaken()) { 80 assert(!use_empty() && "There should be at least one blockaddress!"); 81 Constant *Replacement = 82 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1); 83 while (!use_empty()) { 84 BlockAddress *BA = cast<BlockAddress>(user_back()); 85 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement, 86 BA->getType())); 87 BA->destroyConstant(); 88 } 89 } 90 91 assert(getParent() == nullptr && "BasicBlock still linked into the program!"); 92 dropAllReferences(); 93 InstList.clear(); 94 } 95 96 void BasicBlock::setParent(Function *parent) { 97 // Set Parent=parent, updating instruction symtab entries as appropriate. 98 InstList.setSymTabObject(&Parent, parent); 99 } 100 101 iterator_range<filter_iterator<BasicBlock::const_iterator, 102 std::function<bool(const Instruction &)>>> 103 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const { 104 std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) { 105 return !isa<DbgInfoIntrinsic>(I) && 106 !(SkipPseudoOp && isa<PseudoProbeInst>(I)); 107 }; 108 return make_filter_range(*this, Fn); 109 } 110 111 iterator_range< 112 filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>> 113 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) { 114 std::function<bool(Instruction &)> Fn = [=](Instruction &I) { 115 return !isa<DbgInfoIntrinsic>(I) && 116 !(SkipPseudoOp && isa<PseudoProbeInst>(I)); 117 }; 118 return make_filter_range(*this, Fn); 119 } 120 121 filter_iterator<BasicBlock::const_iterator, 122 std::function<bool(const Instruction &)>>::difference_type 123 BasicBlock::sizeWithoutDebug() const { 124 return std::distance(instructionsWithoutDebug().begin(), 125 instructionsWithoutDebug().end()); 126 } 127 128 void BasicBlock::removeFromParent() { 129 getParent()->getBasicBlockList().remove(getIterator()); 130 } 131 132 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() { 133 return getParent()->getBasicBlockList().erase(getIterator()); 134 } 135 136 void BasicBlock::moveBefore(SymbolTableList<BasicBlock>::iterator MovePos) { 137 getParent()->splice(MovePos, getParent(), getIterator()); 138 } 139 140 void BasicBlock::moveAfter(BasicBlock *MovePos) { 141 MovePos->getParent()->splice(++MovePos->getIterator(), getParent(), 142 getIterator()); 143 } 144 145 const Module *BasicBlock::getModule() const { 146 return getParent()->getParent(); 147 } 148 149 const CallInst *BasicBlock::getTerminatingMustTailCall() const { 150 if (InstList.empty()) 151 return nullptr; 152 const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back()); 153 if (!RI || RI == &InstList.front()) 154 return nullptr; 155 156 const Instruction *Prev = RI->getPrevNode(); 157 if (!Prev) 158 return nullptr; 159 160 if (Value *RV = RI->getReturnValue()) { 161 if (RV != Prev) 162 return nullptr; 163 164 // Look through the optional bitcast. 165 if (auto *BI = dyn_cast<BitCastInst>(Prev)) { 166 RV = BI->getOperand(0); 167 Prev = BI->getPrevNode(); 168 if (!Prev || RV != Prev) 169 return nullptr; 170 } 171 } 172 173 if (auto *CI = dyn_cast<CallInst>(Prev)) { 174 if (CI->isMustTailCall()) 175 return CI; 176 } 177 return nullptr; 178 } 179 180 const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const { 181 if (InstList.empty()) 182 return nullptr; 183 auto *RI = dyn_cast<ReturnInst>(&InstList.back()); 184 if (!RI || RI == &InstList.front()) 185 return nullptr; 186 187 if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode())) 188 if (Function *F = CI->getCalledFunction()) 189 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) 190 return CI; 191 192 return nullptr; 193 } 194 195 const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const { 196 const BasicBlock* BB = this; 197 SmallPtrSet<const BasicBlock *, 8> Visited; 198 Visited.insert(BB); 199 while (auto *Succ = BB->getUniqueSuccessor()) { 200 if (!Visited.insert(Succ).second) 201 return nullptr; 202 BB = Succ; 203 } 204 return BB->getTerminatingDeoptimizeCall(); 205 } 206 207 const Instruction *BasicBlock::getFirstMayFaultInst() const { 208 if (InstList.empty()) 209 return nullptr; 210 for (const Instruction &I : *this) 211 if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallBase>(I)) 212 return &I; 213 return nullptr; 214 } 215 216 const Instruction* BasicBlock::getFirstNonPHI() const { 217 for (const Instruction &I : *this) 218 if (!isa<PHINode>(I)) 219 return &I; 220 return nullptr; 221 } 222 223 const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const { 224 for (const Instruction &I : *this) { 225 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I)) 226 continue; 227 228 if (SkipPseudoOp && isa<PseudoProbeInst>(I)) 229 continue; 230 231 return &I; 232 } 233 return nullptr; 234 } 235 236 const Instruction * 237 BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const { 238 for (const Instruction &I : *this) { 239 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I)) 240 continue; 241 242 if (I.isLifetimeStartOrEnd()) 243 continue; 244 245 if (SkipPseudoOp && isa<PseudoProbeInst>(I)) 246 continue; 247 248 return &I; 249 } 250 return nullptr; 251 } 252 253 BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const { 254 const Instruction *FirstNonPHI = getFirstNonPHI(); 255 if (!FirstNonPHI) 256 return end(); 257 258 const_iterator InsertPt = FirstNonPHI->getIterator(); 259 if (InsertPt->isEHPad()) ++InsertPt; 260 return InsertPt; 261 } 262 263 BasicBlock::const_iterator BasicBlock::getFirstNonPHIOrDbgOrAlloca() const { 264 const Instruction *FirstNonPHI = getFirstNonPHI(); 265 if (!FirstNonPHI) 266 return end(); 267 268 const_iterator InsertPt = FirstNonPHI->getIterator(); 269 if (InsertPt->isEHPad()) 270 ++InsertPt; 271 272 if (isEntryBlock()) { 273 const_iterator End = end(); 274 while (InsertPt != End && 275 (isa<AllocaInst>(*InsertPt) || isa<DbgInfoIntrinsic>(*InsertPt) || 276 isa<PseudoProbeInst>(*InsertPt))) { 277 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&*InsertPt)) { 278 if (!AI->isStaticAlloca()) 279 break; 280 } 281 ++InsertPt; 282 } 283 } 284 return InsertPt; 285 } 286 287 void BasicBlock::dropAllReferences() { 288 for (Instruction &I : *this) 289 I.dropAllReferences(); 290 } 291 292 const BasicBlock *BasicBlock::getSinglePredecessor() const { 293 const_pred_iterator PI = pred_begin(this), E = pred_end(this); 294 if (PI == E) return nullptr; // No preds. 295 const BasicBlock *ThePred = *PI; 296 ++PI; 297 return (PI == E) ? ThePred : nullptr /*multiple preds*/; 298 } 299 300 const BasicBlock *BasicBlock::getUniquePredecessor() const { 301 const_pred_iterator PI = pred_begin(this), E = pred_end(this); 302 if (PI == E) return nullptr; // No preds. 303 const BasicBlock *PredBB = *PI; 304 ++PI; 305 for (;PI != E; ++PI) { 306 if (*PI != PredBB) 307 return nullptr; 308 // The same predecessor appears multiple times in the predecessor list. 309 // This is OK. 310 } 311 return PredBB; 312 } 313 314 bool BasicBlock::hasNPredecessors(unsigned N) const { 315 return hasNItems(pred_begin(this), pred_end(this), N); 316 } 317 318 bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const { 319 return hasNItemsOrMore(pred_begin(this), pred_end(this), N); 320 } 321 322 const BasicBlock *BasicBlock::getSingleSuccessor() const { 323 const_succ_iterator SI = succ_begin(this), E = succ_end(this); 324 if (SI == E) return nullptr; // no successors 325 const BasicBlock *TheSucc = *SI; 326 ++SI; 327 return (SI == E) ? TheSucc : nullptr /* multiple successors */; 328 } 329 330 const BasicBlock *BasicBlock::getUniqueSuccessor() const { 331 const_succ_iterator SI = succ_begin(this), E = succ_end(this); 332 if (SI == E) return nullptr; // No successors 333 const BasicBlock *SuccBB = *SI; 334 ++SI; 335 for (;SI != E; ++SI) { 336 if (*SI != SuccBB) 337 return nullptr; 338 // The same successor appears multiple times in the successor list. 339 // This is OK. 340 } 341 return SuccBB; 342 } 343 344 iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() { 345 PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin()); 346 return make_range<phi_iterator>(P, nullptr); 347 } 348 349 void BasicBlock::removePredecessor(BasicBlock *Pred, 350 bool KeepOneInputPHIs) { 351 // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs. 352 assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) && 353 "Pred is not a predecessor!"); 354 355 // Return early if there are no PHI nodes to update. 356 if (empty() || !isa<PHINode>(begin())) 357 return; 358 359 unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues(); 360 for (PHINode &Phi : make_early_inc_range(phis())) { 361 Phi.removeIncomingValue(Pred, !KeepOneInputPHIs); 362 if (KeepOneInputPHIs) 363 continue; 364 365 // If we have a single predecessor, removeIncomingValue may have erased the 366 // PHI node itself. 367 if (NumPreds == 1) 368 continue; 369 370 // Try to replace the PHI node with a constant value. 371 if (Value *PhiConstant = Phi.hasConstantValue()) { 372 Phi.replaceAllUsesWith(PhiConstant); 373 Phi.eraseFromParent(); 374 } 375 } 376 } 377 378 bool BasicBlock::canSplitPredecessors() const { 379 const Instruction *FirstNonPHI = getFirstNonPHI(); 380 if (isa<LandingPadInst>(FirstNonPHI)) 381 return true; 382 // This is perhaps a little conservative because constructs like 383 // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors 384 // cannot handle such things just yet. 385 if (FirstNonPHI->isEHPad()) 386 return false; 387 return true; 388 } 389 390 bool BasicBlock::isLegalToHoistInto() const { 391 auto *Term = getTerminator(); 392 // No terminator means the block is under construction. 393 if (!Term) 394 return true; 395 396 // If the block has no successors, there can be no instructions to hoist. 397 assert(Term->getNumSuccessors() > 0); 398 399 // Instructions should not be hoisted across exception handling boundaries. 400 return !Term->isExceptionalTerminator(); 401 } 402 403 bool BasicBlock::isEntryBlock() const { 404 const Function *F = getParent(); 405 assert(F && "Block must have a parent function to use this API"); 406 return this == &F->getEntryBlock(); 407 } 408 409 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName, 410 bool Before) { 411 if (Before) 412 return splitBasicBlockBefore(I, BBName); 413 414 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!"); 415 assert(I != InstList.end() && 416 "Trying to get me to create degenerate basic block!"); 417 418 BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), 419 this->getNextNode()); 420 421 // Save DebugLoc of split point before invalidating iterator. 422 DebugLoc Loc = I->getDebugLoc(); 423 // Move all of the specified instructions from the original basic block into 424 // the new basic block. 425 New->splice(New->end(), this, I, end()); 426 427 // Add a branch instruction to the newly formed basic block. 428 BranchInst *BI = BranchInst::Create(New, this); 429 BI->setDebugLoc(Loc); 430 431 // Now we must loop through all of the successors of the New block (which 432 // _were_ the successors of the 'this' block), and update any PHI nodes in 433 // successors. If there were PHI nodes in the successors, then they need to 434 // know that incoming branches will be from New, not from Old (this). 435 // 436 New->replaceSuccessorsPhiUsesWith(this, New); 437 return New; 438 } 439 440 BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) { 441 assert(getTerminator() && 442 "Can't use splitBasicBlockBefore on degenerate BB!"); 443 assert(I != InstList.end() && 444 "Trying to get me to create degenerate basic block!"); 445 446 assert((!isa<PHINode>(*I) || getSinglePredecessor()) && 447 "cannot split on multi incoming phis"); 448 449 BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this); 450 // Save DebugLoc of split point before invalidating iterator. 451 DebugLoc Loc = I->getDebugLoc(); 452 // Move all of the specified instructions from the original basic block into 453 // the new basic block. 454 New->splice(New->end(), this, begin(), I); 455 456 // Loop through all of the predecessors of the 'this' block (which will be the 457 // predecessors of the New block), replace the specified successor 'this' 458 // block to point at the New block and update any PHI nodes in 'this' block. 459 // If there were PHI nodes in 'this' block, the PHI nodes are updated 460 // to reflect that the incoming branches will be from the New block and not 461 // from predecessors of the 'this' block. 462 // Save predecessors to separate vector before modifying them. 463 SmallVector<BasicBlock *, 4> Predecessors; 464 for (BasicBlock *Pred : predecessors(this)) 465 Predecessors.push_back(Pred); 466 for (BasicBlock *Pred : Predecessors) { 467 Instruction *TI = Pred->getTerminator(); 468 TI->replaceSuccessorWith(this, New); 469 this->replacePhiUsesWith(Pred, New); 470 } 471 // Add a branch instruction from "New" to "this" Block. 472 BranchInst *BI = BranchInst::Create(this, New); 473 BI->setDebugLoc(Loc); 474 475 return New; 476 } 477 478 void BasicBlock::splice(BasicBlock::iterator ToIt, BasicBlock *FromBB, 479 BasicBlock::iterator FromBeginIt, 480 BasicBlock::iterator FromEndIt) { 481 #ifdef EXPENSIVE_CHECKS 482 // Check that FromBeginIt is befor FromEndIt. 483 auto FromBBEnd = FromBB->end(); 484 for (auto It = FromBeginIt; It != FromEndIt; ++It) 485 assert(It != FromBBEnd && "FromBeginIt not before FromEndIt!"); 486 #endif // EXPENSIVE_CHECKS 487 getInstList().splice(ToIt, FromBB->getInstList(), FromBeginIt, FromEndIt); 488 } 489 490 BasicBlock::iterator BasicBlock::erase(BasicBlock::iterator FromIt, 491 BasicBlock::iterator ToIt) { 492 return InstList.erase(FromIt, ToIt); 493 } 494 495 void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) { 496 // N.B. This might not be a complete BasicBlock, so don't assume 497 // that it ends with a non-phi instruction. 498 for (Instruction &I : *this) { 499 PHINode *PN = dyn_cast<PHINode>(&I); 500 if (!PN) 501 break; 502 PN->replaceIncomingBlockWith(Old, New); 503 } 504 } 505 506 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old, 507 BasicBlock *New) { 508 Instruction *TI = getTerminator(); 509 if (!TI) 510 // Cope with being called on a BasicBlock that doesn't have a terminator 511 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this. 512 return; 513 for (BasicBlock *Succ : successors(TI)) 514 Succ->replacePhiUsesWith(Old, New); 515 } 516 517 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) { 518 this->replaceSuccessorsPhiUsesWith(this, New); 519 } 520 521 bool BasicBlock::isLandingPad() const { 522 return isa<LandingPadInst>(getFirstNonPHI()); 523 } 524 525 const LandingPadInst *BasicBlock::getLandingPadInst() const { 526 return dyn_cast<LandingPadInst>(getFirstNonPHI()); 527 } 528 529 std::optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const { 530 const Instruction *TI = getTerminator(); 531 if (MDNode *MDIrrLoopHeader = 532 TI->getMetadata(LLVMContext::MD_irr_loop)) { 533 MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0)); 534 if (MDName->getString().equals("loop_header_weight")) { 535 auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1)); 536 return std::optional<uint64_t>(CI->getValue().getZExtValue()); 537 } 538 } 539 return std::nullopt; 540 } 541 542 BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) { 543 while (isa<DbgInfoIntrinsic>(It)) 544 ++It; 545 return It; 546 } 547 548 void BasicBlock::renumberInstructions() { 549 unsigned Order = 0; 550 for (Instruction &I : *this) 551 I.Order = Order++; 552 553 // Set the bit to indicate that the instruction order valid and cached. 554 BasicBlockBits Bits = getBasicBlockBits(); 555 Bits.InstrOrderValid = true; 556 setBasicBlockBits(Bits); 557 558 NumInstrRenumberings++; 559 } 560 561 #ifndef NDEBUG 562 /// In asserts builds, this checks the numbering. In non-asserts builds, it 563 /// is defined as a no-op inline function in BasicBlock.h. 564 void BasicBlock::validateInstrOrdering() const { 565 if (!isInstrOrderValid()) 566 return; 567 const Instruction *Prev = nullptr; 568 for (const Instruction &I : *this) { 569 assert((!Prev || Prev->comesBefore(&I)) && 570 "cached instruction ordering is incorrect"); 571 Prev = &I; 572 } 573 } 574 #endif 575