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 const Instruction *I = getFirstNonPHI(); 376 if (!I) 377 return end(); 378 BasicBlock::const_iterator It = I->getIterator(); 379 // Set the head-inclusive bit to indicate that this iterator includes 380 // any debug-info at the start of the block. This is a no-op unless the 381 // appropriate CMake flag is set. 382 It.setHeadBit(true); 383 return It; 384 } 385 386 BasicBlock::const_iterator 387 BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const { 388 for (const Instruction &I : *this) { 389 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I)) 390 continue; 391 392 if (SkipPseudoOp && isa<PseudoProbeInst>(I)) 393 continue; 394 395 BasicBlock::const_iterator It = I.getIterator(); 396 // This position comes after any debug records, the head bit should remain 397 // unset. 398 assert(!It.getHeadBit()); 399 return It; 400 } 401 return end(); 402 } 403 404 BasicBlock::const_iterator 405 BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const { 406 for (const Instruction &I : *this) { 407 if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I)) 408 continue; 409 410 if (I.isLifetimeStartOrEnd()) 411 continue; 412 413 if (SkipPseudoOp && isa<PseudoProbeInst>(I)) 414 continue; 415 416 BasicBlock::const_iterator It = I.getIterator(); 417 // This position comes after any debug records, the head bit should remain 418 // unset. 419 assert(!It.getHeadBit()); 420 421 return It; 422 } 423 return end(); 424 } 425 426 BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const { 427 const Instruction *FirstNonPHI = getFirstNonPHI(); 428 if (!FirstNonPHI) 429 return end(); 430 431 const_iterator InsertPt = FirstNonPHI->getIterator(); 432 if (InsertPt->isEHPad()) ++InsertPt; 433 // Set the head-inclusive bit to indicate that this iterator includes 434 // any debug-info at the start of the block. This is a no-op unless the 435 // appropriate CMake flag is set. 436 InsertPt.setHeadBit(true); 437 return InsertPt; 438 } 439 440 BasicBlock::const_iterator BasicBlock::getFirstNonPHIOrDbgOrAlloca() const { 441 const_iterator InsertPt = getFirstNonPHIIt(); 442 if (InsertPt == end()) 443 return end(); 444 445 if (InsertPt->isEHPad()) 446 ++InsertPt; 447 448 if (isEntryBlock()) { 449 const_iterator End = end(); 450 while (InsertPt != End && 451 (isa<AllocaInst>(*InsertPt) || isa<DbgInfoIntrinsic>(*InsertPt) || 452 isa<PseudoProbeInst>(*InsertPt))) { 453 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&*InsertPt)) { 454 if (!AI->isStaticAlloca()) 455 break; 456 } 457 ++InsertPt; 458 } 459 } 460 461 // Signal that this comes after any debug records. 462 InsertPt.setHeadBit(false); 463 return InsertPt; 464 } 465 466 void BasicBlock::dropAllReferences() { 467 for (Instruction &I : *this) 468 I.dropAllReferences(); 469 } 470 471 const BasicBlock *BasicBlock::getSinglePredecessor() const { 472 const_pred_iterator PI = pred_begin(this), E = pred_end(this); 473 if (PI == E) return nullptr; // No preds. 474 const BasicBlock *ThePred = *PI; 475 ++PI; 476 return (PI == E) ? ThePred : nullptr /*multiple preds*/; 477 } 478 479 const BasicBlock *BasicBlock::getUniquePredecessor() const { 480 const_pred_iterator PI = pred_begin(this), E = pred_end(this); 481 if (PI == E) return nullptr; // No preds. 482 const BasicBlock *PredBB = *PI; 483 ++PI; 484 for (;PI != E; ++PI) { 485 if (*PI != PredBB) 486 return nullptr; 487 // The same predecessor appears multiple times in the predecessor list. 488 // This is OK. 489 } 490 return PredBB; 491 } 492 493 bool BasicBlock::hasNPredecessors(unsigned N) const { 494 return hasNItems(pred_begin(this), pred_end(this), N); 495 } 496 497 bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const { 498 return hasNItemsOrMore(pred_begin(this), pred_end(this), N); 499 } 500 501 const BasicBlock *BasicBlock::getSingleSuccessor() const { 502 const_succ_iterator SI = succ_begin(this), E = succ_end(this); 503 if (SI == E) return nullptr; // no successors 504 const BasicBlock *TheSucc = *SI; 505 ++SI; 506 return (SI == E) ? TheSucc : nullptr /* multiple successors */; 507 } 508 509 const BasicBlock *BasicBlock::getUniqueSuccessor() const { 510 const_succ_iterator SI = succ_begin(this), E = succ_end(this); 511 if (SI == E) return nullptr; // No successors 512 const BasicBlock *SuccBB = *SI; 513 ++SI; 514 for (;SI != E; ++SI) { 515 if (*SI != SuccBB) 516 return nullptr; 517 // The same successor appears multiple times in the successor list. 518 // This is OK. 519 } 520 return SuccBB; 521 } 522 523 iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() { 524 PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin()); 525 return make_range<phi_iterator>(P, nullptr); 526 } 527 528 void BasicBlock::removePredecessor(BasicBlock *Pred, 529 bool KeepOneInputPHIs) { 530 // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs. 531 assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) && 532 "Pred is not a predecessor!"); 533 534 // Return early if there are no PHI nodes to update. 535 if (empty() || !isa<PHINode>(begin())) 536 return; 537 538 unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues(); 539 for (PHINode &Phi : make_early_inc_range(phis())) { 540 Phi.removeIncomingValue(Pred, !KeepOneInputPHIs); 541 if (KeepOneInputPHIs) 542 continue; 543 544 // If we have a single predecessor, removeIncomingValue may have erased the 545 // PHI node itself. 546 if (NumPreds == 1) 547 continue; 548 549 // Try to replace the PHI node with a constant value. 550 if (Value *PhiConstant = Phi.hasConstantValue()) { 551 Phi.replaceAllUsesWith(PhiConstant); 552 Phi.eraseFromParent(); 553 } 554 } 555 } 556 557 bool BasicBlock::canSplitPredecessors() const { 558 const_iterator FirstNonPHI = getFirstNonPHIIt(); 559 if (isa<LandingPadInst>(FirstNonPHI)) 560 return true; 561 // This is perhaps a little conservative because constructs like 562 // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors 563 // cannot handle such things just yet. 564 if (FirstNonPHI->isEHPad()) 565 return false; 566 return true; 567 } 568 569 bool BasicBlock::isLegalToHoistInto() const { 570 auto *Term = getTerminator(); 571 // No terminator means the block is under construction. 572 if (!Term) 573 return true; 574 575 // If the block has no successors, there can be no instructions to hoist. 576 assert(Term->getNumSuccessors() > 0); 577 578 // Instructions should not be hoisted across special terminators, which may 579 // have side effects or return values. 580 return !Term->isSpecialTerminator(); 581 } 582 583 bool BasicBlock::isEntryBlock() const { 584 const Function *F = getParent(); 585 assert(F && "Block must have a parent function to use this API"); 586 return this == &F->getEntryBlock(); 587 } 588 589 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName, 590 bool Before) { 591 if (Before) 592 return splitBasicBlockBefore(I, BBName); 593 594 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!"); 595 assert(I != InstList.end() && 596 "Trying to get me to create degenerate basic block!"); 597 598 BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), 599 this->getNextNode()); 600 601 // Save DebugLoc of split point before invalidating iterator. 602 DebugLoc Loc = I->getStableDebugLoc(); 603 // Move all of the specified instructions from the original basic block into 604 // the new basic block. 605 New->splice(New->end(), this, I, end()); 606 607 // Add a branch instruction to the newly formed basic block. 608 BranchInst *BI = BranchInst::Create(New, this); 609 BI->setDebugLoc(Loc); 610 611 // Now we must loop through all of the successors of the New block (which 612 // _were_ the successors of the 'this' block), and update any PHI nodes in 613 // successors. If there were PHI nodes in the successors, then they need to 614 // know that incoming branches will be from New, not from Old (this). 615 // 616 New->replaceSuccessorsPhiUsesWith(this, New); 617 return New; 618 } 619 620 BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) { 621 assert(getTerminator() && 622 "Can't use splitBasicBlockBefore on degenerate BB!"); 623 assert(I != InstList.end() && 624 "Trying to get me to create degenerate basic block!"); 625 626 assert((!isa<PHINode>(*I) || getSinglePredecessor()) && 627 "cannot split on multi incoming phis"); 628 629 BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this); 630 // Save DebugLoc of split point before invalidating iterator. 631 DebugLoc Loc = I->getDebugLoc(); 632 // Move all of the specified instructions from the original basic block into 633 // the new basic block. 634 New->splice(New->end(), this, begin(), I); 635 636 // Loop through all of the predecessors of the 'this' block (which will be the 637 // predecessors of the New block), replace the specified successor 'this' 638 // block to point at the New block and update any PHI nodes in 'this' block. 639 // If there were PHI nodes in 'this' block, the PHI nodes are updated 640 // to reflect that the incoming branches will be from the New block and not 641 // from predecessors of the 'this' block. 642 // Save predecessors to separate vector before modifying them. 643 SmallVector<BasicBlock *, 4> Predecessors(predecessors(this)); 644 for (BasicBlock *Pred : Predecessors) { 645 Instruction *TI = Pred->getTerminator(); 646 TI->replaceSuccessorWith(this, New); 647 this->replacePhiUsesWith(Pred, New); 648 } 649 // Add a branch instruction from "New" to "this" Block. 650 BranchInst *BI = BranchInst::Create(this, New); 651 BI->setDebugLoc(Loc); 652 653 return New; 654 } 655 656 BasicBlock::iterator BasicBlock::erase(BasicBlock::iterator FromIt, 657 BasicBlock::iterator ToIt) { 658 for (Instruction &I : make_early_inc_range(make_range(FromIt, ToIt))) 659 I.eraseFromParent(); 660 return ToIt; 661 } 662 663 void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) { 664 // N.B. This might not be a complete BasicBlock, so don't assume 665 // that it ends with a non-phi instruction. 666 for (Instruction &I : *this) { 667 PHINode *PN = dyn_cast<PHINode>(&I); 668 if (!PN) 669 break; 670 PN->replaceIncomingBlockWith(Old, New); 671 } 672 } 673 674 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old, 675 BasicBlock *New) { 676 Instruction *TI = getTerminator(); 677 if (!TI) 678 // Cope with being called on a BasicBlock that doesn't have a terminator 679 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this. 680 return; 681 for (BasicBlock *Succ : successors(TI)) 682 Succ->replacePhiUsesWith(Old, New); 683 } 684 685 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) { 686 this->replaceSuccessorsPhiUsesWith(this, New); 687 } 688 689 bool BasicBlock::isLandingPad() const { 690 return isa<LandingPadInst>(getFirstNonPHIIt()); 691 } 692 693 const LandingPadInst *BasicBlock::getLandingPadInst() const { 694 return dyn_cast<LandingPadInst>(getFirstNonPHIIt()); 695 } 696 697 std::optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const { 698 const Instruction *TI = getTerminator(); 699 if (MDNode *MDIrrLoopHeader = 700 TI->getMetadata(LLVMContext::MD_irr_loop)) { 701 MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0)); 702 if (MDName->getString() == "loop_header_weight") { 703 auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1)); 704 return std::optional<uint64_t>(CI->getValue().getZExtValue()); 705 } 706 } 707 return std::nullopt; 708 } 709 710 BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) { 711 while (isa<DbgInfoIntrinsic>(It)) 712 ++It; 713 return It; 714 } 715 716 void BasicBlock::renumberInstructions() { 717 unsigned Order = 0; 718 for (Instruction &I : *this) 719 I.Order = Order++; 720 721 // Set the bit to indicate that the instruction order valid and cached. 722 BasicBlockBits Bits = getBasicBlockBits(); 723 Bits.InstrOrderValid = true; 724 setBasicBlockBits(Bits); 725 726 NumInstrRenumberings++; 727 } 728 729 void BasicBlock::flushTerminatorDbgRecords() { 730 // If we erase the terminator in a block, any DbgRecords will sink and "fall 731 // off the end", existing after any terminator that gets inserted. With 732 // dbg.value intrinsics we would just insert the terminator at end() and 733 // the dbg.values would come before the terminator. With DbgRecords, we must 734 // do this manually. 735 // To get out of this unfortunate form, whenever we insert a terminator, 736 // check whether there's anything trailing at the end and move those 737 // DbgRecords in front of the terminator. 738 739 // Do nothing if we're not in new debug-info format. 740 if (!IsNewDbgInfoFormat) 741 return; 742 743 // If there's no terminator, there's nothing to do. 744 Instruction *Term = getTerminator(); 745 if (!Term) 746 return; 747 748 // Are there any dangling DbgRecords? 749 DbgMarker *TrailingDbgRecords = getTrailingDbgRecords(); 750 if (!TrailingDbgRecords) 751 return; 752 753 // Transfer DbgRecords from the trailing position onto the terminator. 754 createMarker(Term); 755 Term->DebugMarker->absorbDebugValues(*TrailingDbgRecords, false); 756 TrailingDbgRecords->eraseFromParent(); 757 deleteTrailingDbgRecords(); 758 } 759 760 void BasicBlock::spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest, 761 BasicBlock *Src, 762 BasicBlock::iterator First, 763 BasicBlock::iterator Last) { 764 // Imagine the folowing: 765 // 766 // bb1: 767 // dbg.value(... 768 // ret i32 0 769 // 770 // If an optimisation pass attempts to splice the contents of the block from 771 // BB1->begin() to BB1->getTerminator(), then the dbg.value will be 772 // transferred to the destination. 773 // However, in the "new" DbgRecord format for debug-info, that range is empty: 774 // begin() returns an iterator to the terminator, as there will only be a 775 // single instruction in the block. We must piece together from the bits set 776 // in the iterators whether there was the intention to transfer any debug 777 // info. 778 779 // If we're not in "new" debug-info format, do nothing. 780 if (!IsNewDbgInfoFormat) 781 return; 782 783 assert(First == Last); 784 bool InsertAtHead = Dest.getHeadBit(); 785 bool ReadFromHead = First.getHeadBit(); 786 787 // If the source block is completely empty, including no terminator, then 788 // transfer any trailing DbgRecords that are still hanging around. This can 789 // occur when a block is optimised away and the terminator has been moved 790 // somewhere else. 791 if (Src->empty()) { 792 DbgMarker *SrcTrailingDbgRecords = Src->getTrailingDbgRecords(); 793 if (!SrcTrailingDbgRecords) 794 return; 795 796 Dest->adoptDbgRecords(Src, Src->end(), InsertAtHead); 797 // adoptDbgRecords should have released the trailing DbgRecords. 798 assert(!Src->getTrailingDbgRecords()); 799 return; 800 } 801 802 // There are instructions in this block; if the First iterator was 803 // with begin() / getFirstInsertionPt() then the caller intended debug-info 804 // at the start of the block to be transferred. Return otherwise. 805 if (Src->empty() || First != Src->begin() || !ReadFromHead) 806 return; 807 808 // Is there actually anything to transfer? 809 if (!First->hasDbgRecords()) 810 return; 811 812 createMarker(Dest)->absorbDebugValues(*First->DebugMarker, InsertAtHead); 813 } 814 815 void BasicBlock::spliceDebugInfo(BasicBlock::iterator Dest, BasicBlock *Src, 816 BasicBlock::iterator First, 817 BasicBlock::iterator Last) { 818 /* Do a quick normalisation before calling the real splice implementation. We 819 might be operating on a degenerate basic block that has no instructions 820 in it, a legitimate transient state. In that case, Dest will be end() and 821 any DbgRecords temporarily stored in the TrailingDbgRecords map in 822 LLVMContext. We might illustrate it thus: 823 824 Dest 825 | 826 this-block: ~~~~~~~~ 827 Src-block: ++++B---B---B---B:::C 828 | | 829 First Last 830 831 However: does the caller expect the "~" DbgRecords to end up before or 832 after the spliced segment? This is communciated in the "Head" bit of Dest, 833 which signals whether the caller called begin() or end() on this block. 834 835 If the head bit is set, then all is well, we leave DbgRecords trailing just 836 like how dbg.value instructions would trail after instructions spliced to 837 the beginning of this block. 838 839 If the head bit isn't set, then try to jam the "~" DbgRecords onto the 840 front of the First instruction, then splice like normal, which joins the 841 "~" DbgRecords with the "+" DbgRecords. However if the "+" DbgRecords are 842 supposed to be left behind in Src, then: 843 * detach the "+" DbgRecords, 844 * move the "~" DbgRecords onto First, 845 * splice like normal, 846 * replace the "+" DbgRecords onto the Last position. 847 Complicated, but gets the job done. */ 848 849 // If we're inserting at end(), and not in front of dangling DbgRecords, then 850 // move the DbgRecords onto "First". They'll then be moved naturally in the 851 // splice process. 852 DbgMarker *MoreDanglingDbgRecords = nullptr; 853 DbgMarker *OurTrailingDbgRecords = getTrailingDbgRecords(); 854 if (Dest == end() && !Dest.getHeadBit() && OurTrailingDbgRecords) { 855 // Are the "+" DbgRecords not supposed to move? If so, detach them 856 // temporarily. 857 if (!First.getHeadBit() && First->hasDbgRecords()) { 858 MoreDanglingDbgRecords = Src->getMarker(First); 859 MoreDanglingDbgRecords->removeFromParent(); 860 } 861 862 if (First->hasDbgRecords()) { 863 // Place them at the front, it would look like this: 864 // Dest 865 // | 866 // this-block: 867 // Src-block: ~~~~~~~~++++B---B---B---B:::C 868 // | | 869 // First Last 870 First->adoptDbgRecords(this, end(), true); 871 } else { 872 // No current marker, create one and absorb in. (FIXME: we can avoid an 873 // allocation in the future). 874 DbgMarker *CurMarker = Src->createMarker(&*First); 875 CurMarker->absorbDebugValues(*OurTrailingDbgRecords, false); 876 OurTrailingDbgRecords->eraseFromParent(); 877 } 878 deleteTrailingDbgRecords(); 879 First.setHeadBit(true); 880 } 881 882 // Call the main debug-info-splicing implementation. 883 spliceDebugInfoImpl(Dest, Src, First, Last); 884 885 // Do we have some "+" DbgRecords hanging around that weren't supposed to 886 // move, and we detached to make things easier? 887 if (!MoreDanglingDbgRecords) 888 return; 889 890 // FIXME: we could avoid an allocation here sometimes. (adoptDbgRecords 891 // requires an iterator). 892 DbgMarker *LastMarker = Src->createMarker(Last); 893 LastMarker->absorbDebugValues(*MoreDanglingDbgRecords, true); 894 MoreDanglingDbgRecords->eraseFromParent(); 895 } 896 897 void BasicBlock::spliceDebugInfoImpl(BasicBlock::iterator Dest, BasicBlock *Src, 898 BasicBlock::iterator First, 899 BasicBlock::iterator Last) { 900 // Find out where to _place_ these dbg.values; if InsertAtHead is specified, 901 // this will be at the start of Dest's debug value range, otherwise this is 902 // just Dest's marker. 903 bool InsertAtHead = Dest.getHeadBit(); 904 bool ReadFromHead = First.getHeadBit(); 905 // Use this flag to signal the abnormal case, where we don't want to copy the 906 // DbgRecords ahead of the "Last" position. 907 bool ReadFromTail = !Last.getTailBit(); 908 bool LastIsEnd = (Last == Src->end()); 909 910 /* 911 Here's an illustration of what we're about to do. We have two blocks, this 912 and Src, and two segments of list. Each instruction is marked by a capital 913 while potential DbgRecord debug-info is marked out by "-" characters and a 914 few other special characters (+:=) where I want to highlight what's going 915 on. 916 917 Dest 918 | 919 this-block: A----A----A ====A----A----A----A---A---A 920 Src-block ++++B---B---B---B:::C 921 | | 922 First Last 923 924 The splice method is going to take all the instructions from First up to 925 (but not including) Last and insert them in _front_ of Dest, forming one 926 long list. All the DbgRecords attached to instructions _between_ First and 927 Last need no maintenence. However, we have to do special things with the 928 DbgRecords marked with the +:= characters. We only have three positions: 929 should the "+" DbgRecords be transferred, and if so to where? Do we move the 930 ":" DbgRecords? Would they go in front of the "=" DbgRecords, or should the 931 "=" DbgRecords go before "+" DbgRecords? 932 933 We're told which way it should be by the bits carried in the iterators. The 934 "Head" bit indicates whether the specified position is supposed to be at the 935 front of the attached DbgRecords (true) or not (false). The Tail bit is true 936 on the other end of a range: is the range intended to include DbgRecords up 937 to the end (false) or not (true). 938 939 FIXME: the tail bit doesn't need to be distinct from the head bit, we could 940 combine them. 941 942 Here are some examples of different configurations: 943 944 Dest.Head = true, First.Head = true, Last.Tail = false 945 946 this-block: A----A----A++++B---B---B---B:::====A----A----A----A---A---A 947 | | 948 First Dest 949 950 Wheras if we didn't want to read from the Src list, 951 952 Dest.Head = true, First.Head = false, Last.Tail = false 953 954 this-block: A----A----AB---B---B---B:::====A----A----A----A---A---A 955 | | 956 First Dest 957 958 Or if we didn't want to insert at the head of Dest: 959 960 Dest.Head = false, First.Head = false, Last.Tail = false 961 962 this-block: A----A----A====B---B---B---B:::A----A----A----A---A---A 963 | | 964 First Dest 965 966 Tests for these various configurations can be found in the unit test file 967 BasicBlockDbgInfoTest.cpp. 968 969 */ 970 971 // Detach the marker at Dest -- this lets us move the "====" DbgRecords 972 // around. 973 DbgMarker *DestMarker = nullptr; 974 if ((DestMarker = getMarker(Dest))) { 975 if (Dest == end()) { 976 assert(DestMarker == getTrailingDbgRecords()); 977 deleteTrailingDbgRecords(); 978 } else { 979 DestMarker->removeFromParent(); 980 } 981 } 982 983 // If we're moving the tail range of DbgRecords (":::"), absorb them into the 984 // front of the DbgRecords at Dest. 985 if (ReadFromTail && Src->getMarker(Last)) { 986 DbgMarker *FromLast = Src->getMarker(Last); 987 if (LastIsEnd) { 988 if (Dest == end()) { 989 // Abosrb the trailing markers from Src. 990 assert(FromLast == Src->getTrailingDbgRecords()); 991 createMarker(Dest)->absorbDebugValues(*FromLast, true); 992 FromLast->eraseFromParent(); 993 Src->deleteTrailingDbgRecords(); 994 } else { 995 // adoptDbgRecords will release any trailers. 996 Dest->adoptDbgRecords(Src, Last, true); 997 } 998 assert(!Src->getTrailingDbgRecords()); 999 } else { 1000 // FIXME: can we use adoptDbgRecords here to reduce allocations? 1001 DbgMarker *OntoDest = createMarker(Dest); 1002 OntoDest->absorbDebugValues(*FromLast, true); 1003 } 1004 } 1005 1006 // If we're _not_ reading from the head of First, i.e. the "++++" DbgRecords, 1007 // move their markers onto Last. They remain in the Src block. No action 1008 // needed. 1009 if (!ReadFromHead && First->hasDbgRecords()) { 1010 if (Last != Src->end()) { 1011 Last->adoptDbgRecords(Src, First, true); 1012 } else { 1013 DbgMarker *OntoLast = Src->createMarker(Last); 1014 DbgMarker *FromFirst = Src->createMarker(First); 1015 // Always insert at front of Last. 1016 OntoLast->absorbDebugValues(*FromFirst, true); 1017 } 1018 } 1019 1020 // Finally, do something with the "====" DbgRecords we detached. 1021 if (DestMarker) { 1022 if (InsertAtHead) { 1023 // Insert them at the end of the DbgRecords at Dest. The "::::" DbgRecords 1024 // might be in front of them. 1025 DbgMarker *NewDestMarker = createMarker(Dest); 1026 NewDestMarker->absorbDebugValues(*DestMarker, false); 1027 } else { 1028 // Insert them right at the start of the range we moved, ahead of First 1029 // and the "++++" DbgRecords. 1030 // This also covers the rare circumstance where we insert at end(), and we 1031 // did not generate the iterator with begin() / getFirstInsertionPt(), 1032 // meaning any trailing debug-info at the end of the block would 1033 // "normally" have been pushed in front of "First". We move it there now. 1034 DbgMarker *FirstMarker = createMarker(First); 1035 FirstMarker->absorbDebugValues(*DestMarker, true); 1036 } 1037 DestMarker->eraseFromParent(); 1038 } 1039 } 1040 1041 void BasicBlock::splice(iterator Dest, BasicBlock *Src, iterator First, 1042 iterator Last) { 1043 assert(Src->IsNewDbgInfoFormat == IsNewDbgInfoFormat); 1044 1045 #ifdef EXPENSIVE_CHECKS 1046 // Check that First is before Last. 1047 auto FromBBEnd = Src->end(); 1048 for (auto It = First; It != Last; ++It) 1049 assert(It != FromBBEnd && "FromBeginIt not before FromEndIt!"); 1050 #endif // EXPENSIVE_CHECKS 1051 1052 // Lots of horrible special casing for empty transfers: the dbg.values between 1053 // two positions could be spliced in dbg.value mode. 1054 if (First == Last) { 1055 spliceDebugInfoEmptyBlock(Dest, Src, First, Last); 1056 return; 1057 } 1058 1059 // Handle non-instr debug-info specific juggling. 1060 if (IsNewDbgInfoFormat) 1061 spliceDebugInfo(Dest, Src, First, Last); 1062 1063 // And move the instructions. 1064 getInstList().splice(Dest, Src->getInstList(), First, Last); 1065 1066 flushTerminatorDbgRecords(); 1067 } 1068 1069 void BasicBlock::insertDbgRecordAfter(DbgRecord *DR, Instruction *I) { 1070 assert(IsNewDbgInfoFormat); 1071 assert(I->getParent() == this); 1072 1073 iterator NextIt = std::next(I->getIterator()); 1074 DbgMarker *NextMarker = createMarker(NextIt); 1075 NextMarker->insertDbgRecord(DR, true); 1076 } 1077 1078 void BasicBlock::insertDbgRecordBefore(DbgRecord *DR, 1079 InstListType::iterator Where) { 1080 assert(Where == end() || Where->getParent() == this); 1081 bool InsertAtHead = Where.getHeadBit(); 1082 DbgMarker *M = createMarker(Where); 1083 M->insertDbgRecord(DR, InsertAtHead); 1084 } 1085 1086 DbgMarker *BasicBlock::getNextMarker(Instruction *I) { 1087 return getMarker(std::next(I->getIterator())); 1088 } 1089 1090 DbgMarker *BasicBlock::getMarker(InstListType::iterator It) { 1091 if (It == end()) { 1092 DbgMarker *DM = getTrailingDbgRecords(); 1093 return DM; 1094 } 1095 return It->DebugMarker; 1096 } 1097 1098 void BasicBlock::reinsertInstInDbgRecords( 1099 Instruction *I, std::optional<DbgRecord::self_iterator> Pos) { 1100 // "I" was originally removed from a position where it was 1101 // immediately in front of Pos. Any DbgRecords on that position then "fell 1102 // down" onto Pos. "I" has been re-inserted at the front of that wedge of 1103 // DbgRecords, shuffle them around to represent the original positioning. To 1104 // illustrate: 1105 // 1106 // Instructions: I1---I---I0 1107 // DbgRecords: DDD DDD 1108 // 1109 // Instruction "I" removed, 1110 // 1111 // Instructions: I1------I0 1112 // DbgRecords: DDDDDD 1113 // ^Pos 1114 // 1115 // Instruction "I" re-inserted (now): 1116 // 1117 // Instructions: I1---I------I0 1118 // DbgRecords: DDDDDD 1119 // ^Pos 1120 // 1121 // After this method completes: 1122 // 1123 // Instructions: I1---I---I0 1124 // DbgRecords: DDD DDD 1125 1126 // This happens if there were no DbgRecords on I0. Are there now DbgRecords 1127 // there? 1128 if (!Pos) { 1129 DbgMarker *NextMarker = getNextMarker(I); 1130 if (!NextMarker) 1131 return; 1132 if (NextMarker->StoredDbgRecords.empty()) 1133 return; 1134 // There are DbgMarkers there now -- they fell down from "I". 1135 DbgMarker *ThisMarker = createMarker(I); 1136 ThisMarker->absorbDebugValues(*NextMarker, false); 1137 return; 1138 } 1139 1140 // Is there even a range of DbgRecords to move? 1141 DbgMarker *DM = (*Pos)->getMarker(); 1142 auto Range = make_range(DM->StoredDbgRecords.begin(), (*Pos)); 1143 if (Range.begin() == Range.end()) 1144 return; 1145 1146 // Otherwise: splice. 1147 DbgMarker *ThisMarker = createMarker(I); 1148 assert(ThisMarker->StoredDbgRecords.empty()); 1149 ThisMarker->absorbDebugValues(Range, *DM, true); 1150 } 1151 1152 #ifndef NDEBUG 1153 /// In asserts builds, this checks the numbering. In non-asserts builds, it 1154 /// is defined as a no-op inline function in BasicBlock.h. 1155 void BasicBlock::validateInstrOrdering() const { 1156 if (!isInstrOrderValid()) 1157 return; 1158 const Instruction *Prev = nullptr; 1159 for (const Instruction &I : *this) { 1160 assert((!Prev || Prev->comesBefore(&I)) && 1161 "cached instruction ordering is incorrect"); 1162 Prev = &I; 1163 } 1164 } 1165 #endif 1166 1167 void BasicBlock::setTrailingDbgRecords(DbgMarker *foo) { 1168 getContext().pImpl->setTrailingDbgRecords(this, foo); 1169 } 1170 1171 DbgMarker *BasicBlock::getTrailingDbgRecords() { 1172 return getContext().pImpl->getTrailingDbgRecords(this); 1173 } 1174 1175 void BasicBlock::deleteTrailingDbgRecords() { 1176 getContext().pImpl->deleteTrailingDbgRecords(this); 1177 } 1178