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/DebugProgramInstruction.h" 20 #include "llvm/IR/Instructions.h" 21 #include "llvm/IR/IntrinsicInst.h" 22 #include "llvm/IR/LLVMContext.h" 23 #include "llvm/IR/Type.h" 24 #include "llvm/Support/CommandLine.h" 25 26 #include "LLVMContextImpl.h" 27 28 using namespace llvm; 29 30 #define DEBUG_TYPE "ir" 31 STATISTIC(NumInstrRenumberings, "Number of renumberings across all blocks"); 32 33 cl::opt<bool> UseNewDbgInfoFormat( 34 "experimental-debuginfo-iterators", 35 cl::desc("Enable communicating debuginfo positions through iterators, " 36 "eliminating intrinsics. Has no effect if " 37 "--preserve-input-debuginfo-format=true."), 38 cl::init(true)); 39 cl::opt<cl::boolOrDefault> PreserveInputDbgFormat( 40 "preserve-input-debuginfo-format", cl::Hidden, 41 cl::desc("When set to true, IR files will be processed and printed in " 42 "their current debug info format, regardless of default behaviour " 43 "or other flags passed. Has no effect if input IR does not " 44 "contain debug records or intrinsics. Ignored in llvm-link, " 45 "llvm-lto, and llvm-lto2.")); 46 47 bool WriteNewDbgInfoFormatToBitcode /*set default value in cl::init() below*/; 48 cl::opt<bool, true> WriteNewDbgInfoFormatToBitcode2( 49 "write-experimental-debuginfo-iterators-to-bitcode", cl::Hidden, 50 cl::location(WriteNewDbgInfoFormatToBitcode), cl::init(true)); 51 52 DbgMarker *BasicBlock::createMarker(Instruction *I) { 53 assert(IsNewDbgInfoFormat && 54 "Tried to create a marker in a non new debug-info block!"); 55 if (I->DebugMarker) 56 return I->DebugMarker; 57 DbgMarker *Marker = new DbgMarker(); 58 Marker->MarkedInstr = I; 59 I->DebugMarker = Marker; 60 return Marker; 61 } 62 63 DbgMarker *BasicBlock::createMarker(InstListType::iterator It) { 64 assert(IsNewDbgInfoFormat && 65 "Tried to create a marker in a non new debug-info block!"); 66 if (It != end()) 67 return createMarker(&*It); 68 DbgMarker *DM = getTrailingDbgRecords(); 69 if (DM) 70 return DM; 71 DM = new DbgMarker(); 72 setTrailingDbgRecords(DM); 73 return DM; 74 } 75 76 void BasicBlock::convertToNewDbgValues() { 77 IsNewDbgInfoFormat = true; 78 79 // Iterate over all instructions in the instruction list, collecting debug 80 // info intrinsics and converting them to DbgRecords. Once we find a "real" 81 // instruction, attach all those DbgRecords to a DbgMarker in that 82 // instruction. 83 SmallVector<DbgRecord *, 4> DbgVarRecs; 84 for (Instruction &I : make_early_inc_range(InstList)) { 85 assert(!I.DebugMarker && "DebugMarker already set on old-format instrs?"); 86 if (DbgVariableIntrinsic *DVI = dyn_cast<DbgVariableIntrinsic>(&I)) { 87 // Convert this dbg.value to a DbgVariableRecord. 88 DbgVariableRecord *Value = new DbgVariableRecord(DVI); 89 DbgVarRecs.push_back(Value); 90 DVI->eraseFromParent(); 91 continue; 92 } 93 94 if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(&I)) { 95 DbgVarRecs.push_back( 96 new DbgLabelRecord(DLI->getLabel(), DLI->getDebugLoc())); 97 DLI->eraseFromParent(); 98 continue; 99 } 100 101 if (DbgVarRecs.empty()) 102 continue; 103 104 // Create a marker to store DbgRecords in. 105 createMarker(&I); 106 DbgMarker *Marker = I.DebugMarker; 107 108 for (DbgRecord *DVR : DbgVarRecs) 109 Marker->insertDbgRecord(DVR, false); 110 111 DbgVarRecs.clear(); 112 } 113 } 114 115 void BasicBlock::convertFromNewDbgValues() { 116 invalidateOrders(); 117 IsNewDbgInfoFormat = false; 118 119 // Iterate over the block, finding instructions annotated with DbgMarkers. 120 // Convert any attached DbgRecords to debug intrinsics and insert ahead of the 121 // instruction. 122 for (auto &Inst : *this) { 123 if (!Inst.DebugMarker) 124 continue; 125 126 DbgMarker &Marker = *Inst.DebugMarker; 127 for (DbgRecord &DR : Marker.getDbgRecordRange()) 128 InstList.insert(Inst.getIterator(), 129 DR.createDebugIntrinsic(getModule(), nullptr)); 130 131 Marker.eraseFromParent(); 132 } 133 134 // Assume no trailing DbgRecords: we could technically create them at the end 135 // of the block, after a terminator, but this would be non-cannonical and 136 // indicates that something else is broken somewhere. 137 assert(!getTrailingDbgRecords()); 138 } 139 140 #ifndef NDEBUG 141 void BasicBlock::dumpDbgValues() const { 142 for (auto &Inst : *this) { 143 if (!Inst.DebugMarker) 144 continue; 145 146 dbgs() << "@ " << Inst.DebugMarker << " "; 147 Inst.DebugMarker->dump(); 148 }; 149 } 150 #endif 151 152 void BasicBlock::setIsNewDbgInfoFormat(bool NewFlag) { 153 if (NewFlag && !IsNewDbgInfoFormat) 154 convertToNewDbgValues(); 155 else if (!NewFlag && IsNewDbgInfoFormat) 156 convertFromNewDbgValues(); 157 } 158 void BasicBlock::setNewDbgInfoFormatFlag(bool NewFlag) { 159 IsNewDbgInfoFormat = NewFlag; 160 } 161 162 ValueSymbolTable *BasicBlock::getValueSymbolTable() { 163 if (Function *F = getParent()) 164 return F->getValueSymbolTable(); 165 return nullptr; 166 } 167 168 LLVMContext &BasicBlock::getContext() const { 169 return getType()->getContext(); 170 } 171 172 template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) { 173 BB->invalidateOrders(); 174 } 175 176 // Explicit instantiation of SymbolTableListTraits since some of the methods 177 // are not in the public header file... 178 template class llvm::SymbolTableListTraits< 179 Instruction, ilist_iterator_bits<true>, ilist_parent<BasicBlock>>; 180 181 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent, 182 BasicBlock *InsertBefore) 183 : Value(Type::getLabelTy(C), Value::BasicBlockVal), 184 IsNewDbgInfoFormat(UseNewDbgInfoFormat), Parent(nullptr) { 185 186 if (NewParent) 187 insertInto(NewParent, InsertBefore); 188 else 189 assert(!InsertBefore && 190 "Cannot insert block before another block with no function!"); 191 192 end().getNodePtr()->setParent(this); 193 setName(Name); 194 if (NewParent) 195 setIsNewDbgInfoFormat(NewParent->IsNewDbgInfoFormat); 196 } 197 198 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) { 199 assert(NewParent && "Expected a parent"); 200 assert(!Parent && "Already has a parent"); 201 202 if (InsertBefore) 203 NewParent->insert(InsertBefore->getIterator(), this); 204 else 205 NewParent->insert(NewParent->end(), this); 206 207 setIsNewDbgInfoFormat(NewParent->IsNewDbgInfoFormat); 208 } 209 210 BasicBlock::~BasicBlock() { 211 validateInstrOrdering(); 212 213 // If the address of the block is taken and it is being deleted (e.g. because 214 // it is dead), this means that there is either a dangling constant expr 215 // hanging off the block, or an undefined use of the block (source code 216 // expecting the address of a label to keep the block alive even though there 217 // is no indirect branch). Handle these cases by zapping the BlockAddress 218 // nodes. There are no other possible uses at this point. 219 if (hasAddressTaken()) { 220 assert(!use_empty() && "There should be at least one blockaddress!"); 221 Constant *Replacement = 222 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1); 223 while (!use_empty()) { 224 BlockAddress *BA = cast<BlockAddress>(user_back()); 225 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement, 226 BA->getType())); 227 BA->destroyConstant(); 228 } 229 } 230 231 assert(getParent() == nullptr && "BasicBlock still linked into the program!"); 232 dropAllReferences(); 233 for (auto &Inst : *this) { 234 if (!Inst.DebugMarker) 235 continue; 236 Inst.DebugMarker->eraseFromParent(); 237 } 238 InstList.clear(); 239 } 240 241 void BasicBlock::setParent(Function *parent) { 242 // Set Parent=parent, updating instruction symtab entries as appropriate. 243 if (Parent != parent) 244 Number = parent ? parent->NextBlockNum++ : -1u; 245 InstList.setSymTabObject(&Parent, parent); 246 } 247 248 iterator_range<filter_iterator<BasicBlock::const_iterator, 249 std::function<bool(const Instruction &)>>> 250 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const { 251 std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) { 252 return !isa<DbgInfoIntrinsic>(I) && 253 !(SkipPseudoOp && isa<PseudoProbeInst>(I)); 254 }; 255 return make_filter_range(*this, Fn); 256 } 257 258 iterator_range< 259 filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>> 260 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) { 261 std::function<bool(Instruction &)> Fn = [=](Instruction &I) { 262 return !isa<DbgInfoIntrinsic>(I) && 263 !(SkipPseudoOp && isa<PseudoProbeInst>(I)); 264 }; 265 return make_filter_range(*this, Fn); 266 } 267 268 filter_iterator<BasicBlock::const_iterator, 269 std::function<bool(const Instruction &)>>::difference_type 270 BasicBlock::sizeWithoutDebug() const { 271 return std::distance(instructionsWithoutDebug().begin(), 272 instructionsWithoutDebug().end()); 273 } 274 275 void BasicBlock::removeFromParent() { 276 getParent()->getBasicBlockList().remove(getIterator()); 277 } 278 279 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() { 280 return getParent()->getBasicBlockList().erase(getIterator()); 281 } 282 283 void BasicBlock::moveBefore(SymbolTableList<BasicBlock>::iterator MovePos) { 284 getParent()->splice(MovePos, getParent(), getIterator()); 285 } 286 287 void BasicBlock::moveAfter(BasicBlock *MovePos) { 288 MovePos->getParent()->splice(++MovePos->getIterator(), getParent(), 289 getIterator()); 290 } 291 292 const Module *BasicBlock::getModule() const { 293 return getParent()->getParent(); 294 } 295 296 const DataLayout &BasicBlock::getDataLayout() const { 297 return getModule()->getDataLayout(); 298 } 299 300 const CallInst *BasicBlock::getTerminatingMustTailCall() const { 301 if (InstList.empty()) 302 return nullptr; 303 const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back()); 304 if (!RI || RI == &InstList.front()) 305 return nullptr; 306 307 const Instruction *Prev = RI->getPrevNode(); 308 if (!Prev) 309 return nullptr; 310 311 if (Value *RV = RI->getReturnValue()) { 312 if (RV != Prev) 313 return nullptr; 314 315 // Look through the optional bitcast. 316 if (auto *BI = dyn_cast<BitCastInst>(Prev)) { 317 RV = BI->getOperand(0); 318 Prev = BI->getPrevNode(); 319 if (!Prev || RV != Prev) 320 return nullptr; 321 } 322 } 323 324 if (auto *CI = dyn_cast<CallInst>(Prev)) { 325 if (CI->isMustTailCall()) 326 return CI; 327 } 328 return nullptr; 329 } 330 331 const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const { 332 if (InstList.empty()) 333 return nullptr; 334 auto *RI = dyn_cast<ReturnInst>(&InstList.back()); 335 if (!RI || RI == &InstList.front()) 336 return nullptr; 337 338 if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode())) 339 if (Function *F = CI->getCalledFunction()) 340 if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) 341 return CI; 342 343 return nullptr; 344 } 345 346 const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const { 347 const BasicBlock* BB = this; 348 SmallPtrSet<const BasicBlock *, 8> Visited; 349 Visited.insert(BB); 350 while (auto *Succ = BB->getUniqueSuccessor()) { 351 if (!Visited.insert(Succ).second) 352 return nullptr; 353 BB = Succ; 354 } 355 return BB->getTerminatingDeoptimizeCall(); 356 } 357 358 const Instruction *BasicBlock::getFirstMayFaultInst() const { 359 if (InstList.empty()) 360 return nullptr; 361 for (const Instruction &I : *this) 362 if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallBase>(I)) 363 return &I; 364 return nullptr; 365 } 366 367 const Instruction* BasicBlock::getFirstNonPHI() const { 368 for (const Instruction &I : *this) 369 if (!isa<PHINode>(I)) 370 return &I; 371 return nullptr; 372 } 373 374 BasicBlock::const_iterator BasicBlock::getFirstNonPHIIt() const { 375 for (const Instruction &I : *this) { 376 if (isa<PHINode>(I)) 377 continue; 378 379 BasicBlock::const_iterator It = I.getIterator(); 380 // Set the head-inclusive bit to indicate that this iterator includes 381 // any debug-info at the start of the block. This is a no-op unless the 382 // appropriate CMake flag is set. 383 It.setHeadBit(true); 384 return It; 385 } 386 387 return end(); 388 } 389 390 BasicBlock::const_iterator 391 BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const { 392 for (const Instruction &I : *this) { 393 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I)) 394 continue; 395 396 if (SkipPseudoOp && isa<PseudoProbeInst>(I)) 397 continue; 398 399 BasicBlock::const_iterator It = I.getIterator(); 400 // This position comes after any debug records, the head bit should remain 401 // unset. 402 assert(!It.getHeadBit()); 403 return It; 404 } 405 return end(); 406 } 407 408 BasicBlock::const_iterator 409 BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const { 410 for (const Instruction &I : *this) { 411 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I)) 412 continue; 413 414 if (I.isLifetimeStartOrEnd()) 415 continue; 416 417 if (SkipPseudoOp && isa<PseudoProbeInst>(I)) 418 continue; 419 420 BasicBlock::const_iterator It = I.getIterator(); 421 // This position comes after any debug records, the head bit should remain 422 // unset. 423 assert(!It.getHeadBit()); 424 425 return It; 426 } 427 return end(); 428 } 429 430 BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const { 431 const_iterator InsertPt = getFirstNonPHIIt(); 432 if (InsertPt == end()) 433 return end(); 434 435 if (InsertPt->isEHPad()) ++InsertPt; 436 // Set the head-inclusive bit to indicate that this iterator includes 437 // any debug-info at the start of the block. This is a no-op unless the 438 // appropriate CMake flag is set. 439 InsertPt.setHeadBit(true); 440 return InsertPt; 441 } 442 443 BasicBlock::const_iterator BasicBlock::getFirstNonPHIOrDbgOrAlloca() const { 444 const_iterator InsertPt = getFirstNonPHIIt(); 445 if (InsertPt == end()) 446 return end(); 447 448 if (InsertPt->isEHPad()) 449 ++InsertPt; 450 451 if (isEntryBlock()) { 452 const_iterator End = end(); 453 while (InsertPt != End && 454 (isa<AllocaInst>(*InsertPt) || isa<DbgInfoIntrinsic>(*InsertPt) || 455 isa<PseudoProbeInst>(*InsertPt))) { 456 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&*InsertPt)) { 457 if (!AI->isStaticAlloca()) 458 break; 459 } 460 ++InsertPt; 461 } 462 } 463 464 // Signal that this comes after any debug records. 465 InsertPt.setHeadBit(false); 466 return InsertPt; 467 } 468 469 void BasicBlock::dropAllReferences() { 470 for (Instruction &I : *this) 471 I.dropAllReferences(); 472 } 473 474 const BasicBlock *BasicBlock::getSinglePredecessor() const { 475 const_pred_iterator PI = pred_begin(this), E = pred_end(this); 476 if (PI == E) return nullptr; // No preds. 477 const BasicBlock *ThePred = *PI; 478 ++PI; 479 return (PI == E) ? ThePred : nullptr /*multiple preds*/; 480 } 481 482 const BasicBlock *BasicBlock::getUniquePredecessor() const { 483 const_pred_iterator PI = pred_begin(this), E = pred_end(this); 484 if (PI == E) return nullptr; // No preds. 485 const BasicBlock *PredBB = *PI; 486 ++PI; 487 for (;PI != E; ++PI) { 488 if (*PI != PredBB) 489 return nullptr; 490 // The same predecessor appears multiple times in the predecessor list. 491 // This is OK. 492 } 493 return PredBB; 494 } 495 496 bool BasicBlock::hasNPredecessors(unsigned N) const { 497 return hasNItems(pred_begin(this), pred_end(this), N); 498 } 499 500 bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const { 501 return hasNItemsOrMore(pred_begin(this), pred_end(this), N); 502 } 503 504 const BasicBlock *BasicBlock::getSingleSuccessor() const { 505 const_succ_iterator SI = succ_begin(this), E = succ_end(this); 506 if (SI == E) return nullptr; // no successors 507 const BasicBlock *TheSucc = *SI; 508 ++SI; 509 return (SI == E) ? TheSucc : nullptr /* multiple successors */; 510 } 511 512 const BasicBlock *BasicBlock::getUniqueSuccessor() const { 513 const_succ_iterator SI = succ_begin(this), E = succ_end(this); 514 if (SI == E) return nullptr; // No successors 515 const BasicBlock *SuccBB = *SI; 516 ++SI; 517 for (;SI != E; ++SI) { 518 if (*SI != SuccBB) 519 return nullptr; 520 // The same successor appears multiple times in the successor list. 521 // This is OK. 522 } 523 return SuccBB; 524 } 525 526 iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() { 527 PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin()); 528 return make_range<phi_iterator>(P, nullptr); 529 } 530 531 void BasicBlock::removePredecessor(BasicBlock *Pred, 532 bool KeepOneInputPHIs) { 533 // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs. 534 assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) && 535 "Pred is not a predecessor!"); 536 537 // Return early if there are no PHI nodes to update. 538 if (empty() || !isa<PHINode>(begin())) 539 return; 540 541 unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues(); 542 for (PHINode &Phi : make_early_inc_range(phis())) { 543 Phi.removeIncomingValue(Pred, !KeepOneInputPHIs); 544 if (KeepOneInputPHIs) 545 continue; 546 547 // If we have a single predecessor, removeIncomingValue may have erased the 548 // PHI node itself. 549 if (NumPreds == 1) 550 continue; 551 552 // Try to replace the PHI node with a constant value. 553 if (Value *PhiConstant = Phi.hasConstantValue()) { 554 Phi.replaceAllUsesWith(PhiConstant); 555 Phi.eraseFromParent(); 556 } 557 } 558 } 559 560 bool BasicBlock::canSplitPredecessors() const { 561 const_iterator FirstNonPHI = getFirstNonPHIIt(); 562 if (isa<LandingPadInst>(FirstNonPHI)) 563 return true; 564 // This is perhaps a little conservative because constructs like 565 // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors 566 // cannot handle such things just yet. 567 if (FirstNonPHI->isEHPad()) 568 return false; 569 return true; 570 } 571 572 bool BasicBlock::isLegalToHoistInto() const { 573 auto *Term = getTerminator(); 574 // No terminator means the block is under construction. 575 if (!Term) 576 return true; 577 578 // If the block has no successors, there can be no instructions to hoist. 579 assert(Term->getNumSuccessors() > 0); 580 581 // Instructions should not be hoisted across special terminators, which may 582 // have side effects or return values. 583 return !Term->isSpecialTerminator(); 584 } 585 586 bool BasicBlock::isEntryBlock() const { 587 const Function *F = getParent(); 588 assert(F && "Block must have a parent function to use this API"); 589 return this == &F->getEntryBlock(); 590 } 591 592 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName, 593 bool Before) { 594 if (Before) 595 return splitBasicBlockBefore(I, BBName); 596 597 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!"); 598 assert(I != InstList.end() && 599 "Trying to get me to create degenerate basic block!"); 600 601 BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), 602 this->getNextNode()); 603 604 // Save DebugLoc of split point before invalidating iterator. 605 DebugLoc Loc = I->getStableDebugLoc(); 606 // Move all of the specified instructions from the original basic block into 607 // the new basic block. 608 New->splice(New->end(), this, I, end()); 609 610 // Add a branch instruction to the newly formed basic block. 611 BranchInst *BI = BranchInst::Create(New, this); 612 BI->setDebugLoc(Loc); 613 614 // Now we must loop through all of the successors of the New block (which 615 // _were_ the successors of the 'this' block), and update any PHI nodes in 616 // successors. If there were PHI nodes in the successors, then they need to 617 // know that incoming branches will be from New, not from Old (this). 618 // 619 New->replaceSuccessorsPhiUsesWith(this, New); 620 return New; 621 } 622 623 BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) { 624 assert(getTerminator() && 625 "Can't use splitBasicBlockBefore on degenerate BB!"); 626 assert(I != InstList.end() && 627 "Trying to get me to create degenerate basic block!"); 628 629 assert((!isa<PHINode>(*I) || getSinglePredecessor()) && 630 "cannot split on multi incoming phis"); 631 632 BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this); 633 // Save DebugLoc of split point before invalidating iterator. 634 DebugLoc Loc = I->getDebugLoc(); 635 // Move all of the specified instructions from the original basic block into 636 // the new basic block. 637 New->splice(New->end(), this, begin(), I); 638 639 // Loop through all of the predecessors of the 'this' block (which will be the 640 // predecessors of the New block), replace the specified successor 'this' 641 // block to point at the New block and update any PHI nodes in 'this' block. 642 // If there were PHI nodes in 'this' block, the PHI nodes are updated 643 // to reflect that the incoming branches will be from the New block and not 644 // from predecessors of the 'this' block. 645 // Save predecessors to separate vector before modifying them. 646 SmallVector<BasicBlock *, 4> Predecessors(predecessors(this)); 647 for (BasicBlock *Pred : Predecessors) { 648 Instruction *TI = Pred->getTerminator(); 649 TI->replaceSuccessorWith(this, New); 650 this->replacePhiUsesWith(Pred, New); 651 } 652 // Add a branch instruction from "New" to "this" Block. 653 BranchInst *BI = BranchInst::Create(this, New); 654 BI->setDebugLoc(Loc); 655 656 return New; 657 } 658 659 BasicBlock::iterator BasicBlock::erase(BasicBlock::iterator FromIt, 660 BasicBlock::iterator ToIt) { 661 for (Instruction &I : make_early_inc_range(make_range(FromIt, ToIt))) 662 I.eraseFromParent(); 663 return ToIt; 664 } 665 666 void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) { 667 // N.B. This might not be a complete BasicBlock, so don't assume 668 // that it ends with a non-phi instruction. 669 for (Instruction &I : *this) { 670 PHINode *PN = dyn_cast<PHINode>(&I); 671 if (!PN) 672 break; 673 PN->replaceIncomingBlockWith(Old, New); 674 } 675 } 676 677 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old, 678 BasicBlock *New) { 679 Instruction *TI = getTerminator(); 680 if (!TI) 681 // Cope with being called on a BasicBlock that doesn't have a terminator 682 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this. 683 return; 684 for (BasicBlock *Succ : successors(TI)) 685 Succ->replacePhiUsesWith(Old, New); 686 } 687 688 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) { 689 this->replaceSuccessorsPhiUsesWith(this, New); 690 } 691 692 bool BasicBlock::isLandingPad() const { 693 return isa<LandingPadInst>(getFirstNonPHIIt()); 694 } 695 696 const LandingPadInst *BasicBlock::getLandingPadInst() const { 697 return dyn_cast<LandingPadInst>(getFirstNonPHIIt()); 698 } 699 700 std::optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const { 701 const Instruction *TI = getTerminator(); 702 if (MDNode *MDIrrLoopHeader = 703 TI->getMetadata(LLVMContext::MD_irr_loop)) { 704 MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0)); 705 if (MDName->getString() == "loop_header_weight") { 706 auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1)); 707 return std::optional<uint64_t>(CI->getValue().getZExtValue()); 708 } 709 } 710 return std::nullopt; 711 } 712 713 BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) { 714 while (isa<DbgInfoIntrinsic>(It)) 715 ++It; 716 return It; 717 } 718 719 void BasicBlock::renumberInstructions() { 720 unsigned Order = 0; 721 for (Instruction &I : *this) 722 I.Order = Order++; 723 724 // Set the bit to indicate that the instruction order valid and cached. 725 BasicBlockBits Bits = getBasicBlockBits(); 726 Bits.InstrOrderValid = true; 727 setBasicBlockBits(Bits); 728 729 NumInstrRenumberings++; 730 } 731 732 void BasicBlock::flushTerminatorDbgRecords() { 733 // If we erase the terminator in a block, any DbgRecords will sink and "fall 734 // off the end", existing after any terminator that gets inserted. With 735 // dbg.value intrinsics we would just insert the terminator at end() and 736 // the dbg.values would come before the terminator. With DbgRecords, we must 737 // do this manually. 738 // To get out of this unfortunate form, whenever we insert a terminator, 739 // check whether there's anything trailing at the end and move those 740 // DbgRecords in front of the terminator. 741 742 // Do nothing if we're not in new debug-info format. 743 if (!IsNewDbgInfoFormat) 744 return; 745 746 // If there's no terminator, there's nothing to do. 747 Instruction *Term = getTerminator(); 748 if (!Term) 749 return; 750 751 // Are there any dangling DbgRecords? 752 DbgMarker *TrailingDbgRecords = getTrailingDbgRecords(); 753 if (!TrailingDbgRecords) 754 return; 755 756 // Transfer DbgRecords from the trailing position onto the terminator. 757 createMarker(Term); 758 Term->DebugMarker->absorbDebugValues(*TrailingDbgRecords, false); 759 TrailingDbgRecords->eraseFromParent(); 760 deleteTrailingDbgRecords(); 761 } 762 763 void BasicBlock::spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest, 764 BasicBlock *Src, 765 BasicBlock::iterator First, 766 BasicBlock::iterator Last) { 767 // Imagine the folowing: 768 // 769 // bb1: 770 // dbg.value(... 771 // ret i32 0 772 // 773 // If an optimisation pass attempts to splice the contents of the block from 774 // BB1->begin() to BB1->getTerminator(), then the dbg.value will be 775 // transferred to the destination. 776 // However, in the "new" DbgRecord format for debug-info, that range is empty: 777 // begin() returns an iterator to the terminator, as there will only be a 778 // single instruction in the block. We must piece together from the bits set 779 // in the iterators whether there was the intention to transfer any debug 780 // info. 781 782 // If we're not in "new" debug-info format, do nothing. 783 if (!IsNewDbgInfoFormat) 784 return; 785 786 assert(First == Last); 787 bool InsertAtHead = Dest.getHeadBit(); 788 bool ReadFromHead = First.getHeadBit(); 789 790 // If the source block is completely empty, including no terminator, then 791 // transfer any trailing DbgRecords that are still hanging around. This can 792 // occur when a block is optimised away and the terminator has been moved 793 // somewhere else. 794 if (Src->empty()) { 795 DbgMarker *SrcTrailingDbgRecords = Src->getTrailingDbgRecords(); 796 if (!SrcTrailingDbgRecords) 797 return; 798 799 Dest->adoptDbgRecords(Src, Src->end(), InsertAtHead); 800 // adoptDbgRecords should have released the trailing DbgRecords. 801 assert(!Src->getTrailingDbgRecords()); 802 return; 803 } 804 805 // There are instructions in this block; if the First iterator was 806 // with begin() / getFirstInsertionPt() then the caller intended debug-info 807 // at the start of the block to be transferred. Return otherwise. 808 if (Src->empty() || First != Src->begin() || !ReadFromHead) 809 return; 810 811 // Is there actually anything to transfer? 812 if (!First->hasDbgRecords()) 813 return; 814 815 createMarker(Dest)->absorbDebugValues(*First->DebugMarker, InsertAtHead); 816 } 817 818 void BasicBlock::spliceDebugInfo(BasicBlock::iterator Dest, BasicBlock *Src, 819 BasicBlock::iterator First, 820 BasicBlock::iterator Last) { 821 /* Do a quick normalisation before calling the real splice implementation. We 822 might be operating on a degenerate basic block that has no instructions 823 in it, a legitimate transient state. In that case, Dest will be end() and 824 any DbgRecords temporarily stored in the TrailingDbgRecords map in 825 LLVMContext. We might illustrate it thus: 826 827 Dest 828 | 829 this-block: ~~~~~~~~ 830 Src-block: ++++B---B---B---B:::C 831 | | 832 First Last 833 834 However: does the caller expect the "~" DbgRecords to end up before or 835 after the spliced segment? This is communciated in the "Head" bit of Dest, 836 which signals whether the caller called begin() or end() on this block. 837 838 If the head bit is set, then all is well, we leave DbgRecords trailing just 839 like how dbg.value instructions would trail after instructions spliced to 840 the beginning of this block. 841 842 If the head bit isn't set, then try to jam the "~" DbgRecords onto the 843 front of the First instruction, then splice like normal, which joins the 844 "~" DbgRecords with the "+" DbgRecords. However if the "+" DbgRecords are 845 supposed to be left behind in Src, then: 846 * detach the "+" DbgRecords, 847 * move the "~" DbgRecords onto First, 848 * splice like normal, 849 * replace the "+" DbgRecords onto the Last position. 850 Complicated, but gets the job done. */ 851 852 // If we're inserting at end(), and not in front of dangling DbgRecords, then 853 // move the DbgRecords onto "First". They'll then be moved naturally in the 854 // splice process. 855 DbgMarker *MoreDanglingDbgRecords = nullptr; 856 DbgMarker *OurTrailingDbgRecords = getTrailingDbgRecords(); 857 if (Dest == end() && !Dest.getHeadBit() && OurTrailingDbgRecords) { 858 // Are the "+" DbgRecords not supposed to move? If so, detach them 859 // temporarily. 860 if (!First.getHeadBit() && First->hasDbgRecords()) { 861 MoreDanglingDbgRecords = Src->getMarker(First); 862 MoreDanglingDbgRecords->removeFromParent(); 863 } 864 865 if (First->hasDbgRecords()) { 866 // Place them at the front, it would look like this: 867 // Dest 868 // | 869 // this-block: 870 // Src-block: ~~~~~~~~++++B---B---B---B:::C 871 // | | 872 // First Last 873 First->adoptDbgRecords(this, end(), true); 874 } else { 875 // No current marker, create one and absorb in. (FIXME: we can avoid an 876 // allocation in the future). 877 DbgMarker *CurMarker = Src->createMarker(&*First); 878 CurMarker->absorbDebugValues(*OurTrailingDbgRecords, false); 879 OurTrailingDbgRecords->eraseFromParent(); 880 } 881 deleteTrailingDbgRecords(); 882 First.setHeadBit(true); 883 } 884 885 // Call the main debug-info-splicing implementation. 886 spliceDebugInfoImpl(Dest, Src, First, Last); 887 888 // Do we have some "+" DbgRecords hanging around that weren't supposed to 889 // move, and we detached to make things easier? 890 if (!MoreDanglingDbgRecords) 891 return; 892 893 // FIXME: we could avoid an allocation here sometimes. (adoptDbgRecords 894 // requires an iterator). 895 DbgMarker *LastMarker = Src->createMarker(Last); 896 LastMarker->absorbDebugValues(*MoreDanglingDbgRecords, true); 897 MoreDanglingDbgRecords->eraseFromParent(); 898 } 899 900 void BasicBlock::spliceDebugInfoImpl(BasicBlock::iterator Dest, BasicBlock *Src, 901 BasicBlock::iterator First, 902 BasicBlock::iterator Last) { 903 // Find out where to _place_ these dbg.values; if InsertAtHead is specified, 904 // this will be at the start of Dest's debug value range, otherwise this is 905 // just Dest's marker. 906 bool InsertAtHead = Dest.getHeadBit(); 907 bool ReadFromHead = First.getHeadBit(); 908 // Use this flag to signal the abnormal case, where we don't want to copy the 909 // DbgRecords ahead of the "Last" position. 910 bool ReadFromTail = !Last.getTailBit(); 911 bool LastIsEnd = (Last == Src->end()); 912 913 /* 914 Here's an illustration of what we're about to do. We have two blocks, this 915 and Src, and two segments of list. Each instruction is marked by a capital 916 while potential DbgRecord debug-info is marked out by "-" characters and a 917 few other special characters (+:=) where I want to highlight what's going 918 on. 919 920 Dest 921 | 922 this-block: A----A----A ====A----A----A----A---A---A 923 Src-block ++++B---B---B---B:::C 924 | | 925 First Last 926 927 The splice method is going to take all the instructions from First up to 928 (but not including) Last and insert them in _front_ of Dest, forming one 929 long list. All the DbgRecords attached to instructions _between_ First and 930 Last need no maintenence. However, we have to do special things with the 931 DbgRecords marked with the +:= characters. We only have three positions: 932 should the "+" DbgRecords be transferred, and if so to where? Do we move the 933 ":" DbgRecords? Would they go in front of the "=" DbgRecords, or should the 934 "=" DbgRecords go before "+" DbgRecords? 935 936 We're told which way it should be by the bits carried in the iterators. The 937 "Head" bit indicates whether the specified position is supposed to be at the 938 front of the attached DbgRecords (true) or not (false). The Tail bit is true 939 on the other end of a range: is the range intended to include DbgRecords up 940 to the end (false) or not (true). 941 942 FIXME: the tail bit doesn't need to be distinct from the head bit, we could 943 combine them. 944 945 Here are some examples of different configurations: 946 947 Dest.Head = true, First.Head = true, Last.Tail = false 948 949 this-block: A----A----A++++B---B---B---B:::====A----A----A----A---A---A 950 | | 951 First Dest 952 953 Wheras if we didn't want to read from the Src list, 954 955 Dest.Head = true, First.Head = false, Last.Tail = false 956 957 this-block: A----A----AB---B---B---B:::====A----A----A----A---A---A 958 | | 959 First Dest 960 961 Or if we didn't want to insert at the head of Dest: 962 963 Dest.Head = false, First.Head = false, Last.Tail = false 964 965 this-block: A----A----A====B---B---B---B:::A----A----A----A---A---A 966 | | 967 First Dest 968 969 Tests for these various configurations can be found in the unit test file 970 BasicBlockDbgInfoTest.cpp. 971 972 */ 973 974 // Detach the marker at Dest -- this lets us move the "====" DbgRecords 975 // around. 976 DbgMarker *DestMarker = nullptr; 977 if ((DestMarker = getMarker(Dest))) { 978 if (Dest == end()) { 979 assert(DestMarker == getTrailingDbgRecords()); 980 deleteTrailingDbgRecords(); 981 } else { 982 DestMarker->removeFromParent(); 983 } 984 } 985 986 // If we're moving the tail range of DbgRecords (":::"), absorb them into the 987 // front of the DbgRecords at Dest. 988 if (ReadFromTail && Src->getMarker(Last)) { 989 DbgMarker *FromLast = Src->getMarker(Last); 990 if (LastIsEnd) { 991 if (Dest == end()) { 992 // Abosrb the trailing markers from Src. 993 assert(FromLast == Src->getTrailingDbgRecords()); 994 createMarker(Dest)->absorbDebugValues(*FromLast, true); 995 FromLast->eraseFromParent(); 996 Src->deleteTrailingDbgRecords(); 997 } else { 998 // adoptDbgRecords will release any trailers. 999 Dest->adoptDbgRecords(Src, Last, true); 1000 } 1001 assert(!Src->getTrailingDbgRecords()); 1002 } else { 1003 // FIXME: can we use adoptDbgRecords here to reduce allocations? 1004 DbgMarker *OntoDest = createMarker(Dest); 1005 OntoDest->absorbDebugValues(*FromLast, true); 1006 } 1007 } 1008 1009 // If we're _not_ reading from the head of First, i.e. the "++++" DbgRecords, 1010 // move their markers onto Last. They remain in the Src block. No action 1011 // needed. 1012 if (!ReadFromHead && First->hasDbgRecords()) { 1013 if (Last != Src->end()) { 1014 Last->adoptDbgRecords(Src, First, true); 1015 } else { 1016 DbgMarker *OntoLast = Src->createMarker(Last); 1017 DbgMarker *FromFirst = Src->createMarker(First); 1018 // Always insert at front of Last. 1019 OntoLast->absorbDebugValues(*FromFirst, true); 1020 } 1021 } 1022 1023 // Finally, do something with the "====" DbgRecords we detached. 1024 if (DestMarker) { 1025 if (InsertAtHead) { 1026 // Insert them at the end of the DbgRecords at Dest. The "::::" DbgRecords 1027 // might be in front of them. 1028 DbgMarker *NewDestMarker = createMarker(Dest); 1029 NewDestMarker->absorbDebugValues(*DestMarker, false); 1030 } else { 1031 // Insert them right at the start of the range we moved, ahead of First 1032 // and the "++++" DbgRecords. 1033 // This also covers the rare circumstance where we insert at end(), and we 1034 // did not generate the iterator with begin() / getFirstInsertionPt(), 1035 // meaning any trailing debug-info at the end of the block would 1036 // "normally" have been pushed in front of "First". We move it there now. 1037 DbgMarker *FirstMarker = createMarker(First); 1038 FirstMarker->absorbDebugValues(*DestMarker, true); 1039 } 1040 DestMarker->eraseFromParent(); 1041 } 1042 } 1043 1044 void BasicBlock::splice(iterator Dest, BasicBlock *Src, iterator First, 1045 iterator Last) { 1046 assert(Src->IsNewDbgInfoFormat == IsNewDbgInfoFormat); 1047 1048 #ifdef EXPENSIVE_CHECKS 1049 // Check that First is before Last. 1050 auto FromBBEnd = Src->end(); 1051 for (auto It = First; It != Last; ++It) 1052 assert(It != FromBBEnd && "FromBeginIt not before FromEndIt!"); 1053 #endif // EXPENSIVE_CHECKS 1054 1055 // Lots of horrible special casing for empty transfers: the dbg.values between 1056 // two positions could be spliced in dbg.value mode. 1057 if (First == Last) { 1058 spliceDebugInfoEmptyBlock(Dest, Src, First, Last); 1059 return; 1060 } 1061 1062 // Handle non-instr debug-info specific juggling. 1063 if (IsNewDbgInfoFormat) 1064 spliceDebugInfo(Dest, Src, First, Last); 1065 1066 // And move the instructions. 1067 getInstList().splice(Dest, Src->getInstList(), First, Last); 1068 1069 flushTerminatorDbgRecords(); 1070 } 1071 1072 void BasicBlock::insertDbgRecordAfter(DbgRecord *DR, Instruction *I) { 1073 assert(IsNewDbgInfoFormat); 1074 assert(I->getParent() == this); 1075 1076 iterator NextIt = std::next(I->getIterator()); 1077 DbgMarker *NextMarker = createMarker(NextIt); 1078 NextMarker->insertDbgRecord(DR, true); 1079 } 1080 1081 void BasicBlock::insertDbgRecordBefore(DbgRecord *DR, 1082 InstListType::iterator Where) { 1083 assert(Where == end() || Where->getParent() == this); 1084 bool InsertAtHead = Where.getHeadBit(); 1085 DbgMarker *M = createMarker(Where); 1086 M->insertDbgRecord(DR, InsertAtHead); 1087 } 1088 1089 DbgMarker *BasicBlock::getNextMarker(Instruction *I) { 1090 return getMarker(std::next(I->getIterator())); 1091 } 1092 1093 DbgMarker *BasicBlock::getMarker(InstListType::iterator It) { 1094 if (It == end()) { 1095 DbgMarker *DM = getTrailingDbgRecords(); 1096 return DM; 1097 } 1098 return It->DebugMarker; 1099 } 1100 1101 void BasicBlock::reinsertInstInDbgRecords( 1102 Instruction *I, std::optional<DbgRecord::self_iterator> Pos) { 1103 // "I" was originally removed from a position where it was 1104 // immediately in front of Pos. Any DbgRecords on that position then "fell 1105 // down" onto Pos. "I" has been re-inserted at the front of that wedge of 1106 // DbgRecords, shuffle them around to represent the original positioning. To 1107 // illustrate: 1108 // 1109 // Instructions: I1---I---I0 1110 // DbgRecords: DDD DDD 1111 // 1112 // Instruction "I" removed, 1113 // 1114 // Instructions: I1------I0 1115 // DbgRecords: DDDDDD 1116 // ^Pos 1117 // 1118 // Instruction "I" re-inserted (now): 1119 // 1120 // Instructions: I1---I------I0 1121 // DbgRecords: DDDDDD 1122 // ^Pos 1123 // 1124 // After this method completes: 1125 // 1126 // Instructions: I1---I---I0 1127 // DbgRecords: DDD DDD 1128 1129 // This happens if there were no DbgRecords on I0. Are there now DbgRecords 1130 // there? 1131 if (!Pos) { 1132 DbgMarker *NextMarker = getNextMarker(I); 1133 if (!NextMarker) 1134 return; 1135 if (NextMarker->StoredDbgRecords.empty()) 1136 return; 1137 // There are DbgMarkers there now -- they fell down from "I". 1138 DbgMarker *ThisMarker = createMarker(I); 1139 ThisMarker->absorbDebugValues(*NextMarker, false); 1140 return; 1141 } 1142 1143 // Is there even a range of DbgRecords to move? 1144 DbgMarker *DM = (*Pos)->getMarker(); 1145 auto Range = make_range(DM->StoredDbgRecords.begin(), (*Pos)); 1146 if (Range.begin() == Range.end()) 1147 return; 1148 1149 // Otherwise: splice. 1150 DbgMarker *ThisMarker = createMarker(I); 1151 assert(ThisMarker->StoredDbgRecords.empty()); 1152 ThisMarker->absorbDebugValues(Range, *DM, true); 1153 } 1154 1155 #ifndef NDEBUG 1156 /// In asserts builds, this checks the numbering. In non-asserts builds, it 1157 /// is defined as a no-op inline function in BasicBlock.h. 1158 void BasicBlock::validateInstrOrdering() const { 1159 if (!isInstrOrderValid()) 1160 return; 1161 const Instruction *Prev = nullptr; 1162 for (const Instruction &I : *this) { 1163 assert((!Prev || Prev->comesBefore(&I)) && 1164 "cached instruction ordering is incorrect"); 1165 Prev = &I; 1166 } 1167 } 1168 #endif 1169 1170 void BasicBlock::setTrailingDbgRecords(DbgMarker *foo) { 1171 getContext().pImpl->setTrailingDbgRecords(this, foo); 1172 } 1173 1174 DbgMarker *BasicBlock::getTrailingDbgRecords() { 1175 return getContext().pImpl->getTrailingDbgRecords(this); 1176 } 1177 1178 void BasicBlock::deleteTrailingDbgRecords() { 1179 getContext().pImpl->deleteTrailingDbgRecords(this); 1180 } 1181