Path: blob/main/contrib/llvm-project/llvm/lib/IR/BasicBlock.cpp
35232 views
//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the BasicBlock class for the IR library.9//10//===----------------------------------------------------------------------===//1112#include "llvm/IR/BasicBlock.h"13#include "SymbolTableListTraitsImpl.h"14#include "llvm/ADT/STLExtras.h"15#include "llvm/ADT/Statistic.h"16#include "llvm/IR/CFG.h"17#include "llvm/IR/Constants.h"18#include "llvm/IR/DebugProgramInstruction.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#include "llvm/Support/CommandLine.h"2425#include "LLVMContextImpl.h"2627using namespace llvm;2829#define DEBUG_TYPE "ir"30STATISTIC(NumInstrRenumberings, "Number of renumberings across all blocks");3132cl::opt<bool> UseNewDbgInfoFormat(33"experimental-debuginfo-iterators",34cl::desc("Enable communicating debuginfo positions through iterators, "35"eliminating intrinsics. Has no effect if "36"--preserve-input-debuginfo-format=true."),37cl::init(true));38cl::opt<cl::boolOrDefault> PreserveInputDbgFormat(39"preserve-input-debuginfo-format", cl::Hidden,40cl::desc("When set to true, IR files will be processed and printed in "41"their current debug info format, regardless of default behaviour "42"or other flags passed. Has no effect if input IR does not "43"contain debug records or intrinsics. Ignored in llvm-link, "44"llvm-lto, and llvm-lto2."));4546bool WriteNewDbgInfoFormatToBitcode /*set default value in cl::init() below*/;47cl::opt<bool, true> WriteNewDbgInfoFormatToBitcode2(48"write-experimental-debuginfo-iterators-to-bitcode", cl::Hidden,49cl::location(WriteNewDbgInfoFormatToBitcode), cl::init(true));5051DbgMarker *BasicBlock::createMarker(Instruction *I) {52assert(IsNewDbgInfoFormat &&53"Tried to create a marker in a non new debug-info block!");54if (I->DebugMarker)55return I->DebugMarker;56DbgMarker *Marker = new DbgMarker();57Marker->MarkedInstr = I;58I->DebugMarker = Marker;59return Marker;60}6162DbgMarker *BasicBlock::createMarker(InstListType::iterator It) {63assert(IsNewDbgInfoFormat &&64"Tried to create a marker in a non new debug-info block!");65if (It != end())66return createMarker(&*It);67DbgMarker *DM = getTrailingDbgRecords();68if (DM)69return DM;70DM = new DbgMarker();71setTrailingDbgRecords(DM);72return DM;73}7475void BasicBlock::convertToNewDbgValues() {76IsNewDbgInfoFormat = true;7778// Iterate over all instructions in the instruction list, collecting debug79// info intrinsics and converting them to DbgRecords. Once we find a "real"80// instruction, attach all those DbgRecords to a DbgMarker in that81// instruction.82SmallVector<DbgRecord *, 4> DbgVarRecs;83for (Instruction &I : make_early_inc_range(InstList)) {84assert(!I.DebugMarker && "DebugMarker already set on old-format instrs?");85if (DbgVariableIntrinsic *DVI = dyn_cast<DbgVariableIntrinsic>(&I)) {86// Convert this dbg.value to a DbgVariableRecord.87DbgVariableRecord *Value = new DbgVariableRecord(DVI);88DbgVarRecs.push_back(Value);89DVI->eraseFromParent();90continue;91}9293if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(&I)) {94DbgVarRecs.push_back(95new DbgLabelRecord(DLI->getLabel(), DLI->getDebugLoc()));96DLI->eraseFromParent();97continue;98}99100if (DbgVarRecs.empty())101continue;102103// Create a marker to store DbgRecords in.104createMarker(&I);105DbgMarker *Marker = I.DebugMarker;106107for (DbgRecord *DVR : DbgVarRecs)108Marker->insertDbgRecord(DVR, false);109110DbgVarRecs.clear();111}112}113114void BasicBlock::convertFromNewDbgValues() {115invalidateOrders();116IsNewDbgInfoFormat = false;117118// Iterate over the block, finding instructions annotated with DbgMarkers.119// Convert any attached DbgRecords to debug intrinsics and insert ahead of the120// instruction.121for (auto &Inst : *this) {122if (!Inst.DebugMarker)123continue;124125DbgMarker &Marker = *Inst.DebugMarker;126for (DbgRecord &DR : Marker.getDbgRecordRange())127InstList.insert(Inst.getIterator(),128DR.createDebugIntrinsic(getModule(), nullptr));129130Marker.eraseFromParent();131}132133// Assume no trailing DbgRecords: we could technically create them at the end134// of the block, after a terminator, but this would be non-cannonical and135// indicates that something else is broken somewhere.136assert(!getTrailingDbgRecords());137}138139#ifndef NDEBUG140void BasicBlock::dumpDbgValues() const {141for (auto &Inst : *this) {142if (!Inst.DebugMarker)143continue;144145dbgs() << "@ " << Inst.DebugMarker << " ";146Inst.DebugMarker->dump();147};148}149#endif150151void BasicBlock::setIsNewDbgInfoFormat(bool NewFlag) {152if (NewFlag && !IsNewDbgInfoFormat)153convertToNewDbgValues();154else if (!NewFlag && IsNewDbgInfoFormat)155convertFromNewDbgValues();156}157void BasicBlock::setNewDbgInfoFormatFlag(bool NewFlag) {158IsNewDbgInfoFormat = NewFlag;159}160161ValueSymbolTable *BasicBlock::getValueSymbolTable() {162if (Function *F = getParent())163return F->getValueSymbolTable();164return nullptr;165}166167LLVMContext &BasicBlock::getContext() const {168return getType()->getContext();169}170171template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) {172BB->invalidateOrders();173}174175// Explicit instantiation of SymbolTableListTraits since some of the methods176// are not in the public header file...177template class llvm::SymbolTableListTraits<178Instruction, ilist_iterator_bits<true>, ilist_parent<BasicBlock>>;179180BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,181BasicBlock *InsertBefore)182: Value(Type::getLabelTy(C), Value::BasicBlockVal),183IsNewDbgInfoFormat(UseNewDbgInfoFormat), Parent(nullptr) {184185if (NewParent)186insertInto(NewParent, InsertBefore);187else188assert(!InsertBefore &&189"Cannot insert block before another block with no function!");190191end().getNodePtr()->setParent(this);192setName(Name);193if (NewParent)194setIsNewDbgInfoFormat(NewParent->IsNewDbgInfoFormat);195}196197void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {198assert(NewParent && "Expected a parent");199assert(!Parent && "Already has a parent");200201if (InsertBefore)202NewParent->insert(InsertBefore->getIterator(), this);203else204NewParent->insert(NewParent->end(), this);205206setIsNewDbgInfoFormat(NewParent->IsNewDbgInfoFormat);207}208209BasicBlock::~BasicBlock() {210validateInstrOrdering();211212// If the address of the block is taken and it is being deleted (e.g. because213// it is dead), this means that there is either a dangling constant expr214// hanging off the block, or an undefined use of the block (source code215// expecting the address of a label to keep the block alive even though there216// is no indirect branch). Handle these cases by zapping the BlockAddress217// nodes. There are no other possible uses at this point.218if (hasAddressTaken()) {219assert(!use_empty() && "There should be at least one blockaddress!");220Constant *Replacement =221ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);222while (!use_empty()) {223BlockAddress *BA = cast<BlockAddress>(user_back());224BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,225BA->getType()));226BA->destroyConstant();227}228}229230assert(getParent() == nullptr && "BasicBlock still linked into the program!");231dropAllReferences();232for (auto &Inst : *this) {233if (!Inst.DebugMarker)234continue;235Inst.DebugMarker->eraseFromParent();236}237InstList.clear();238}239240void BasicBlock::setParent(Function *parent) {241// Set Parent=parent, updating instruction symtab entries as appropriate.242InstList.setSymTabObject(&Parent, parent);243}244245iterator_range<filter_iterator<BasicBlock::const_iterator,246std::function<bool(const Instruction &)>>>247BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const {248std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) {249return !isa<DbgInfoIntrinsic>(I) &&250!(SkipPseudoOp && isa<PseudoProbeInst>(I));251};252return make_filter_range(*this, Fn);253}254255iterator_range<256filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>257BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) {258std::function<bool(Instruction &)> Fn = [=](Instruction &I) {259return !isa<DbgInfoIntrinsic>(I) &&260!(SkipPseudoOp && isa<PseudoProbeInst>(I));261};262return make_filter_range(*this, Fn);263}264265filter_iterator<BasicBlock::const_iterator,266std::function<bool(const Instruction &)>>::difference_type267BasicBlock::sizeWithoutDebug() const {268return std::distance(instructionsWithoutDebug().begin(),269instructionsWithoutDebug().end());270}271272void BasicBlock::removeFromParent() {273getParent()->getBasicBlockList().remove(getIterator());274}275276iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {277return getParent()->getBasicBlockList().erase(getIterator());278}279280void BasicBlock::moveBefore(SymbolTableList<BasicBlock>::iterator MovePos) {281getParent()->splice(MovePos, getParent(), getIterator());282}283284void BasicBlock::moveAfter(BasicBlock *MovePos) {285MovePos->getParent()->splice(++MovePos->getIterator(), getParent(),286getIterator());287}288289const Module *BasicBlock::getModule() const {290return getParent()->getParent();291}292293const DataLayout &BasicBlock::getDataLayout() const {294return getModule()->getDataLayout();295}296297const CallInst *BasicBlock::getTerminatingMustTailCall() const {298if (InstList.empty())299return nullptr;300const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());301if (!RI || RI == &InstList.front())302return nullptr;303304const Instruction *Prev = RI->getPrevNode();305if (!Prev)306return nullptr;307308if (Value *RV = RI->getReturnValue()) {309if (RV != Prev)310return nullptr;311312// Look through the optional bitcast.313if (auto *BI = dyn_cast<BitCastInst>(Prev)) {314RV = BI->getOperand(0);315Prev = BI->getPrevNode();316if (!Prev || RV != Prev)317return nullptr;318}319}320321if (auto *CI = dyn_cast<CallInst>(Prev)) {322if (CI->isMustTailCall())323return CI;324}325return nullptr;326}327328const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {329if (InstList.empty())330return nullptr;331auto *RI = dyn_cast<ReturnInst>(&InstList.back());332if (!RI || RI == &InstList.front())333return nullptr;334335if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))336if (Function *F = CI->getCalledFunction())337if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)338return CI;339340return nullptr;341}342343const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {344const BasicBlock* BB = this;345SmallPtrSet<const BasicBlock *, 8> Visited;346Visited.insert(BB);347while (auto *Succ = BB->getUniqueSuccessor()) {348if (!Visited.insert(Succ).second)349return nullptr;350BB = Succ;351}352return BB->getTerminatingDeoptimizeCall();353}354355const Instruction *BasicBlock::getFirstMayFaultInst() const {356if (InstList.empty())357return nullptr;358for (const Instruction &I : *this)359if (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallBase>(I))360return &I;361return nullptr;362}363364const Instruction* BasicBlock::getFirstNonPHI() const {365for (const Instruction &I : *this)366if (!isa<PHINode>(I))367return &I;368return nullptr;369}370371BasicBlock::const_iterator BasicBlock::getFirstNonPHIIt() const {372const Instruction *I = getFirstNonPHI();373if (!I)374return end();375BasicBlock::const_iterator It = I->getIterator();376// Set the head-inclusive bit to indicate that this iterator includes377// any debug-info at the start of the block. This is a no-op unless the378// appropriate CMake flag is set.379It.setHeadBit(true);380return It;381}382383const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const {384for (const Instruction &I : *this) {385if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))386continue;387388if (SkipPseudoOp && isa<PseudoProbeInst>(I))389continue;390391return &I;392}393return nullptr;394}395396const Instruction *397BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const {398for (const Instruction &I : *this) {399if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))400continue;401402if (I.isLifetimeStartOrEnd())403continue;404405if (SkipPseudoOp && isa<PseudoProbeInst>(I))406continue;407408return &I;409}410return nullptr;411}412413BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {414const Instruction *FirstNonPHI = getFirstNonPHI();415if (!FirstNonPHI)416return end();417418const_iterator InsertPt = FirstNonPHI->getIterator();419if (InsertPt->isEHPad()) ++InsertPt;420// Set the head-inclusive bit to indicate that this iterator includes421// any debug-info at the start of the block. This is a no-op unless the422// appropriate CMake flag is set.423InsertPt.setHeadBit(true);424return InsertPt;425}426427BasicBlock::const_iterator BasicBlock::getFirstNonPHIOrDbgOrAlloca() const {428const Instruction *FirstNonPHI = getFirstNonPHI();429if (!FirstNonPHI)430return end();431432const_iterator InsertPt = FirstNonPHI->getIterator();433if (InsertPt->isEHPad())434++InsertPt;435436if (isEntryBlock()) {437const_iterator End = end();438while (InsertPt != End &&439(isa<AllocaInst>(*InsertPt) || isa<DbgInfoIntrinsic>(*InsertPt) ||440isa<PseudoProbeInst>(*InsertPt))) {441if (const AllocaInst *AI = dyn_cast<AllocaInst>(&*InsertPt)) {442if (!AI->isStaticAlloca())443break;444}445++InsertPt;446}447}448return InsertPt;449}450451void BasicBlock::dropAllReferences() {452for (Instruction &I : *this)453I.dropAllReferences();454}455456const BasicBlock *BasicBlock::getSinglePredecessor() const {457const_pred_iterator PI = pred_begin(this), E = pred_end(this);458if (PI == E) return nullptr; // No preds.459const BasicBlock *ThePred = *PI;460++PI;461return (PI == E) ? ThePred : nullptr /*multiple preds*/;462}463464const BasicBlock *BasicBlock::getUniquePredecessor() const {465const_pred_iterator PI = pred_begin(this), E = pred_end(this);466if (PI == E) return nullptr; // No preds.467const BasicBlock *PredBB = *PI;468++PI;469for (;PI != E; ++PI) {470if (*PI != PredBB)471return nullptr;472// The same predecessor appears multiple times in the predecessor list.473// This is OK.474}475return PredBB;476}477478bool BasicBlock::hasNPredecessors(unsigned N) const {479return hasNItems(pred_begin(this), pred_end(this), N);480}481482bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {483return hasNItemsOrMore(pred_begin(this), pred_end(this), N);484}485486const BasicBlock *BasicBlock::getSingleSuccessor() const {487const_succ_iterator SI = succ_begin(this), E = succ_end(this);488if (SI == E) return nullptr; // no successors489const BasicBlock *TheSucc = *SI;490++SI;491return (SI == E) ? TheSucc : nullptr /* multiple successors */;492}493494const BasicBlock *BasicBlock::getUniqueSuccessor() const {495const_succ_iterator SI = succ_begin(this), E = succ_end(this);496if (SI == E) return nullptr; // No successors497const BasicBlock *SuccBB = *SI;498++SI;499for (;SI != E; ++SI) {500if (*SI != SuccBB)501return nullptr;502// The same successor appears multiple times in the successor list.503// This is OK.504}505return SuccBB;506}507508iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {509PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());510return make_range<phi_iterator>(P, nullptr);511}512513void BasicBlock::removePredecessor(BasicBlock *Pred,514bool KeepOneInputPHIs) {515// Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.516assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&517"Pred is not a predecessor!");518519// Return early if there are no PHI nodes to update.520if (empty() || !isa<PHINode>(begin()))521return;522523unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();524for (PHINode &Phi : make_early_inc_range(phis())) {525Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);526if (KeepOneInputPHIs)527continue;528529// If we have a single predecessor, removeIncomingValue may have erased the530// PHI node itself.531if (NumPreds == 1)532continue;533534// Try to replace the PHI node with a constant value.535if (Value *PhiConstant = Phi.hasConstantValue()) {536Phi.replaceAllUsesWith(PhiConstant);537Phi.eraseFromParent();538}539}540}541542bool BasicBlock::canSplitPredecessors() const {543const Instruction *FirstNonPHI = getFirstNonPHI();544if (isa<LandingPadInst>(FirstNonPHI))545return true;546// This is perhaps a little conservative because constructs like547// CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors548// cannot handle such things just yet.549if (FirstNonPHI->isEHPad())550return false;551return true;552}553554bool BasicBlock::isLegalToHoistInto() const {555auto *Term = getTerminator();556// No terminator means the block is under construction.557if (!Term)558return true;559560// If the block has no successors, there can be no instructions to hoist.561assert(Term->getNumSuccessors() > 0);562563// Instructions should not be hoisted across special terminators, which may564// have side effects or return values.565return !Term->isSpecialTerminator();566}567568bool BasicBlock::isEntryBlock() const {569const Function *F = getParent();570assert(F && "Block must have a parent function to use this API");571return this == &F->getEntryBlock();572}573574BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName,575bool Before) {576if (Before)577return splitBasicBlockBefore(I, BBName);578579assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");580assert(I != InstList.end() &&581"Trying to get me to create degenerate basic block!");582583BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),584this->getNextNode());585586// Save DebugLoc of split point before invalidating iterator.587DebugLoc Loc = I->getStableDebugLoc();588// Move all of the specified instructions from the original basic block into589// the new basic block.590New->splice(New->end(), this, I, end());591592// Add a branch instruction to the newly formed basic block.593BranchInst *BI = BranchInst::Create(New, this);594BI->setDebugLoc(Loc);595596// Now we must loop through all of the successors of the New block (which597// _were_ the successors of the 'this' block), and update any PHI nodes in598// successors. If there were PHI nodes in the successors, then they need to599// know that incoming branches will be from New, not from Old (this).600//601New->replaceSuccessorsPhiUsesWith(this, New);602return New;603}604605BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {606assert(getTerminator() &&607"Can't use splitBasicBlockBefore on degenerate BB!");608assert(I != InstList.end() &&609"Trying to get me to create degenerate basic block!");610611assert((!isa<PHINode>(*I) || getSinglePredecessor()) &&612"cannot split on multi incoming phis");613614BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this);615// Save DebugLoc of split point before invalidating iterator.616DebugLoc Loc = I->getDebugLoc();617// Move all of the specified instructions from the original basic block into618// the new basic block.619New->splice(New->end(), this, begin(), I);620621// Loop through all of the predecessors of the 'this' block (which will be the622// predecessors of the New block), replace the specified successor 'this'623// block to point at the New block and update any PHI nodes in 'this' block.624// If there were PHI nodes in 'this' block, the PHI nodes are updated625// to reflect that the incoming branches will be from the New block and not626// from predecessors of the 'this' block.627// Save predecessors to separate vector before modifying them.628SmallVector<BasicBlock *, 4> Predecessors;629for (BasicBlock *Pred : predecessors(this))630Predecessors.push_back(Pred);631for (BasicBlock *Pred : Predecessors) {632Instruction *TI = Pred->getTerminator();633TI->replaceSuccessorWith(this, New);634this->replacePhiUsesWith(Pred, New);635}636// Add a branch instruction from "New" to "this" Block.637BranchInst *BI = BranchInst::Create(this, New);638BI->setDebugLoc(Loc);639640return New;641}642643BasicBlock::iterator BasicBlock::erase(BasicBlock::iterator FromIt,644BasicBlock::iterator ToIt) {645for (Instruction &I : make_early_inc_range(make_range(FromIt, ToIt)))646I.eraseFromParent();647return ToIt;648}649650void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {651// N.B. This might not be a complete BasicBlock, so don't assume652// that it ends with a non-phi instruction.653for (Instruction &I : *this) {654PHINode *PN = dyn_cast<PHINode>(&I);655if (!PN)656break;657PN->replaceIncomingBlockWith(Old, New);658}659}660661void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,662BasicBlock *New) {663Instruction *TI = getTerminator();664if (!TI)665// Cope with being called on a BasicBlock that doesn't have a terminator666// yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.667return;668for (BasicBlock *Succ : successors(TI))669Succ->replacePhiUsesWith(Old, New);670}671672void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {673this->replaceSuccessorsPhiUsesWith(this, New);674}675676bool BasicBlock::isLandingPad() const {677return isa<LandingPadInst>(getFirstNonPHI());678}679680const LandingPadInst *BasicBlock::getLandingPadInst() const {681return dyn_cast<LandingPadInst>(getFirstNonPHI());682}683684std::optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {685const Instruction *TI = getTerminator();686if (MDNode *MDIrrLoopHeader =687TI->getMetadata(LLVMContext::MD_irr_loop)) {688MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));689if (MDName->getString() == "loop_header_weight") {690auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));691return std::optional<uint64_t>(CI->getValue().getZExtValue());692}693}694return std::nullopt;695}696697BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {698while (isa<DbgInfoIntrinsic>(It))699++It;700return It;701}702703void BasicBlock::renumberInstructions() {704unsigned Order = 0;705for (Instruction &I : *this)706I.Order = Order++;707708// Set the bit to indicate that the instruction order valid and cached.709BasicBlockBits Bits = getBasicBlockBits();710Bits.InstrOrderValid = true;711setBasicBlockBits(Bits);712713NumInstrRenumberings++;714}715716void BasicBlock::flushTerminatorDbgRecords() {717// If we erase the terminator in a block, any DbgRecords will sink and "fall718// off the end", existing after any terminator that gets inserted. With719// dbg.value intrinsics we would just insert the terminator at end() and720// the dbg.values would come before the terminator. With DbgRecords, we must721// do this manually.722// To get out of this unfortunate form, whenever we insert a terminator,723// check whether there's anything trailing at the end and move those724// DbgRecords in front of the terminator.725726// Do nothing if we're not in new debug-info format.727if (!IsNewDbgInfoFormat)728return;729730// If there's no terminator, there's nothing to do.731Instruction *Term = getTerminator();732if (!Term)733return;734735// Are there any dangling DbgRecords?736DbgMarker *TrailingDbgRecords = getTrailingDbgRecords();737if (!TrailingDbgRecords)738return;739740// Transfer DbgRecords from the trailing position onto the terminator.741createMarker(Term);742Term->DebugMarker->absorbDebugValues(*TrailingDbgRecords, false);743TrailingDbgRecords->eraseFromParent();744deleteTrailingDbgRecords();745}746747void BasicBlock::spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest,748BasicBlock *Src,749BasicBlock::iterator First,750BasicBlock::iterator Last) {751// Imagine the folowing:752//753// bb1:754// dbg.value(...755// ret i32 0756//757// If an optimisation pass attempts to splice the contents of the block from758// BB1->begin() to BB1->getTerminator(), then the dbg.value will be759// transferred to the destination.760// However, in the "new" DbgRecord format for debug-info, that range is empty:761// begin() returns an iterator to the terminator, as there will only be a762// single instruction in the block. We must piece together from the bits set763// in the iterators whether there was the intention to transfer any debug764// info.765766// If we're not in "new" debug-info format, do nothing.767if (!IsNewDbgInfoFormat)768return;769770assert(First == Last);771bool InsertAtHead = Dest.getHeadBit();772bool ReadFromHead = First.getHeadBit();773774// If the source block is completely empty, including no terminator, then775// transfer any trailing DbgRecords that are still hanging around. This can776// occur when a block is optimised away and the terminator has been moved777// somewhere else.778if (Src->empty()) {779DbgMarker *SrcTrailingDbgRecords = Src->getTrailingDbgRecords();780if (!SrcTrailingDbgRecords)781return;782783Dest->adoptDbgRecords(Src, Src->end(), InsertAtHead);784// adoptDbgRecords should have released the trailing DbgRecords.785assert(!Src->getTrailingDbgRecords());786return;787}788789// There are instructions in this block; if the First iterator was790// with begin() / getFirstInsertionPt() then the caller intended debug-info791// at the start of the block to be transferred. Return otherwise.792if (Src->empty() || First != Src->begin() || !ReadFromHead)793return;794795// Is there actually anything to transfer?796if (!First->hasDbgRecords())797return;798799createMarker(Dest)->absorbDebugValues(*First->DebugMarker, InsertAtHead);800801return;802}803804void BasicBlock::spliceDebugInfo(BasicBlock::iterator Dest, BasicBlock *Src,805BasicBlock::iterator First,806BasicBlock::iterator Last) {807/* Do a quick normalisation before calling the real splice implementation. We808might be operating on a degenerate basic block that has no instructions809in it, a legitimate transient state. In that case, Dest will be end() and810any DbgRecords temporarily stored in the TrailingDbgRecords map in811LLVMContext. We might illustrate it thus:812813Dest814|815this-block: ~~~~~~~~816Src-block: ++++B---B---B---B:::C817| |818First Last819820However: does the caller expect the "~" DbgRecords to end up before or821after the spliced segment? This is communciated in the "Head" bit of Dest,822which signals whether the caller called begin() or end() on this block.823824If the head bit is set, then all is well, we leave DbgRecords trailing just825like how dbg.value instructions would trail after instructions spliced to826the beginning of this block.827828If the head bit isn't set, then try to jam the "~" DbgRecords onto the829front of the First instruction, then splice like normal, which joins the830"~" DbgRecords with the "+" DbgRecords. However if the "+" DbgRecords are831supposed to be left behind in Src, then:832* detach the "+" DbgRecords,833* move the "~" DbgRecords onto First,834* splice like normal,835* replace the "+" DbgRecords onto the Last position.836Complicated, but gets the job done. */837838// If we're inserting at end(), and not in front of dangling DbgRecords, then839// move the DbgRecords onto "First". They'll then be moved naturally in the840// splice process.841DbgMarker *MoreDanglingDbgRecords = nullptr;842DbgMarker *OurTrailingDbgRecords = getTrailingDbgRecords();843if (Dest == end() && !Dest.getHeadBit() && OurTrailingDbgRecords) {844// Are the "+" DbgRecords not supposed to move? If so, detach them845// temporarily.846if (!First.getHeadBit() && First->hasDbgRecords()) {847MoreDanglingDbgRecords = Src->getMarker(First);848MoreDanglingDbgRecords->removeFromParent();849}850851if (First->hasDbgRecords()) {852// Place them at the front, it would look like this:853// Dest854// |855// this-block:856// Src-block: ~~~~~~~~++++B---B---B---B:::C857// | |858// First Last859First->adoptDbgRecords(this, end(), true);860} else {861// No current marker, create one and absorb in. (FIXME: we can avoid an862// allocation in the future).863DbgMarker *CurMarker = Src->createMarker(&*First);864CurMarker->absorbDebugValues(*OurTrailingDbgRecords, false);865OurTrailingDbgRecords->eraseFromParent();866}867deleteTrailingDbgRecords();868First.setHeadBit(true);869}870871// Call the main debug-info-splicing implementation.872spliceDebugInfoImpl(Dest, Src, First, Last);873874// Do we have some "+" DbgRecords hanging around that weren't supposed to875// move, and we detached to make things easier?876if (!MoreDanglingDbgRecords)877return;878879// FIXME: we could avoid an allocation here sometimes. (adoptDbgRecords880// requires an iterator).881DbgMarker *LastMarker = Src->createMarker(Last);882LastMarker->absorbDebugValues(*MoreDanglingDbgRecords, true);883MoreDanglingDbgRecords->eraseFromParent();884}885886void BasicBlock::spliceDebugInfoImpl(BasicBlock::iterator Dest, BasicBlock *Src,887BasicBlock::iterator First,888BasicBlock::iterator Last) {889// Find out where to _place_ these dbg.values; if InsertAtHead is specified,890// this will be at the start of Dest's debug value range, otherwise this is891// just Dest's marker.892bool InsertAtHead = Dest.getHeadBit();893bool ReadFromHead = First.getHeadBit();894// Use this flag to signal the abnormal case, where we don't want to copy the895// DbgRecords ahead of the "Last" position.896bool ReadFromTail = !Last.getTailBit();897bool LastIsEnd = (Last == Src->end());898899/*900Here's an illustration of what we're about to do. We have two blocks, this901and Src, and two segments of list. Each instruction is marked by a capital902while potential DbgRecord debug-info is marked out by "-" characters and a903few other special characters (+:=) where I want to highlight what's going904on.905906Dest907|908this-block: A----A----A ====A----A----A----A---A---A909Src-block ++++B---B---B---B:::C910| |911First Last912913The splice method is going to take all the instructions from First up to914(but not including) Last and insert them in _front_ of Dest, forming one915long list. All the DbgRecords attached to instructions _between_ First and916Last need no maintenence. However, we have to do special things with the917DbgRecords marked with the +:= characters. We only have three positions:918should the "+" DbgRecords be transferred, and if so to where? Do we move the919":" DbgRecords? Would they go in front of the "=" DbgRecords, or should the920"=" DbgRecords go before "+" DbgRecords?921922We're told which way it should be by the bits carried in the iterators. The923"Head" bit indicates whether the specified position is supposed to be at the924front of the attached DbgRecords (true) or not (false). The Tail bit is true925on the other end of a range: is the range intended to include DbgRecords up926to the end (false) or not (true).927928FIXME: the tail bit doesn't need to be distinct from the head bit, we could929combine them.930931Here are some examples of different configurations:932933Dest.Head = true, First.Head = true, Last.Tail = false934935this-block: A----A----A++++B---B---B---B:::====A----A----A----A---A---A936| |937First Dest938939Wheras if we didn't want to read from the Src list,940941Dest.Head = true, First.Head = false, Last.Tail = false942943this-block: A----A----AB---B---B---B:::====A----A----A----A---A---A944| |945First Dest946947Or if we didn't want to insert at the head of Dest:948949Dest.Head = false, First.Head = false, Last.Tail = false950951this-block: A----A----A====B---B---B---B:::A----A----A----A---A---A952| |953First Dest954955Tests for these various configurations can be found in the unit test file956BasicBlockDbgInfoTest.cpp.957958*/959960// Detach the marker at Dest -- this lets us move the "====" DbgRecords961// around.962DbgMarker *DestMarker = nullptr;963if ((DestMarker = getMarker(Dest))) {964if (Dest == end()) {965assert(DestMarker == getTrailingDbgRecords());966deleteTrailingDbgRecords();967} else {968DestMarker->removeFromParent();969}970}971972// If we're moving the tail range of DbgRecords (":::"), absorb them into the973// front of the DbgRecords at Dest.974if (ReadFromTail && Src->getMarker(Last)) {975DbgMarker *FromLast = Src->getMarker(Last);976if (LastIsEnd) {977if (Dest == end()) {978// Abosrb the trailing markers from Src.979assert(FromLast == Src->getTrailingDbgRecords());980createMarker(Dest)->absorbDebugValues(*FromLast, true);981FromLast->eraseFromParent();982Src->deleteTrailingDbgRecords();983} else {984// adoptDbgRecords will release any trailers.985Dest->adoptDbgRecords(Src, Last, true);986}987assert(!Src->getTrailingDbgRecords());988} else {989// FIXME: can we use adoptDbgRecords here to reduce allocations?990DbgMarker *OntoDest = createMarker(Dest);991OntoDest->absorbDebugValues(*FromLast, true);992}993}994995// If we're _not_ reading from the head of First, i.e. the "++++" DbgRecords,996// move their markers onto Last. They remain in the Src block. No action997// needed.998if (!ReadFromHead && First->hasDbgRecords()) {999if (Last != Src->end()) {1000Last->adoptDbgRecords(Src, First, true);1001} else {1002DbgMarker *OntoLast = Src->createMarker(Last);1003DbgMarker *FromFirst = Src->createMarker(First);1004// Always insert at front of Last.1005OntoLast->absorbDebugValues(*FromFirst, true);1006}1007}10081009// Finally, do something with the "====" DbgRecords we detached.1010if (DestMarker) {1011if (InsertAtHead) {1012// Insert them at the end of the DbgRecords at Dest. The "::::" DbgRecords1013// might be in front of them.1014DbgMarker *NewDestMarker = createMarker(Dest);1015NewDestMarker->absorbDebugValues(*DestMarker, false);1016} else {1017// Insert them right at the start of the range we moved, ahead of First1018// and the "++++" DbgRecords.1019// This also covers the rare circumstance where we insert at end(), and we1020// did not generate the iterator with begin() / getFirstInsertionPt(),1021// meaning any trailing debug-info at the end of the block would1022// "normally" have been pushed in front of "First". We move it there now.1023DbgMarker *FirstMarker = createMarker(First);1024FirstMarker->absorbDebugValues(*DestMarker, true);1025}1026DestMarker->eraseFromParent();1027}1028}10291030void BasicBlock::splice(iterator Dest, BasicBlock *Src, iterator First,1031iterator Last) {1032assert(Src->IsNewDbgInfoFormat == IsNewDbgInfoFormat);10331034#ifdef EXPENSIVE_CHECKS1035// Check that First is before Last.1036auto FromBBEnd = Src->end();1037for (auto It = First; It != Last; ++It)1038assert(It != FromBBEnd && "FromBeginIt not before FromEndIt!");1039#endif // EXPENSIVE_CHECKS10401041// Lots of horrible special casing for empty transfers: the dbg.values between1042// two positions could be spliced in dbg.value mode.1043if (First == Last) {1044spliceDebugInfoEmptyBlock(Dest, Src, First, Last);1045return;1046}10471048// Handle non-instr debug-info specific juggling.1049if (IsNewDbgInfoFormat)1050spliceDebugInfo(Dest, Src, First, Last);10511052// And move the instructions.1053getInstList().splice(Dest, Src->getInstList(), First, Last);10541055flushTerminatorDbgRecords();1056}10571058void BasicBlock::insertDbgRecordAfter(DbgRecord *DR, Instruction *I) {1059assert(IsNewDbgInfoFormat);1060assert(I->getParent() == this);10611062iterator NextIt = std::next(I->getIterator());1063DbgMarker *NextMarker = createMarker(NextIt);1064NextMarker->insertDbgRecord(DR, true);1065}10661067void BasicBlock::insertDbgRecordBefore(DbgRecord *DR,1068InstListType::iterator Where) {1069assert(Where == end() || Where->getParent() == this);1070bool InsertAtHead = Where.getHeadBit();1071DbgMarker *M = createMarker(Where);1072M->insertDbgRecord(DR, InsertAtHead);1073}10741075DbgMarker *BasicBlock::getNextMarker(Instruction *I) {1076return getMarker(std::next(I->getIterator()));1077}10781079DbgMarker *BasicBlock::getMarker(InstListType::iterator It) {1080if (It == end()) {1081DbgMarker *DM = getTrailingDbgRecords();1082return DM;1083}1084return It->DebugMarker;1085}10861087void BasicBlock::reinsertInstInDbgRecords(1088Instruction *I, std::optional<DbgRecord::self_iterator> Pos) {1089// "I" was originally removed from a position where it was1090// immediately in front of Pos. Any DbgRecords on that position then "fell1091// down" onto Pos. "I" has been re-inserted at the front of that wedge of1092// DbgRecords, shuffle them around to represent the original positioning. To1093// illustrate:1094//1095// Instructions: I1---I---I01096// DbgRecords: DDD DDD1097//1098// Instruction "I" removed,1099//1100// Instructions: I1------I01101// DbgRecords: DDDDDD1102// ^Pos1103//1104// Instruction "I" re-inserted (now):1105//1106// Instructions: I1---I------I01107// DbgRecords: DDDDDD1108// ^Pos1109//1110// After this method completes:1111//1112// Instructions: I1---I---I01113// DbgRecords: DDD DDD11141115// This happens if there were no DbgRecords on I0. Are there now DbgRecords1116// there?1117if (!Pos) {1118DbgMarker *NextMarker = getNextMarker(I);1119if (!NextMarker)1120return;1121if (NextMarker->StoredDbgRecords.empty())1122return;1123// There are DbgMarkers there now -- they fell down from "I".1124DbgMarker *ThisMarker = createMarker(I);1125ThisMarker->absorbDebugValues(*NextMarker, false);1126return;1127}11281129// Is there even a range of DbgRecords to move?1130DbgMarker *DM = (*Pos)->getMarker();1131auto Range = make_range(DM->StoredDbgRecords.begin(), (*Pos));1132if (Range.begin() == Range.end())1133return;11341135// Otherwise: splice.1136DbgMarker *ThisMarker = createMarker(I);1137assert(ThisMarker->StoredDbgRecords.empty());1138ThisMarker->absorbDebugValues(Range, *DM, true);1139}11401141#ifndef NDEBUG1142/// In asserts builds, this checks the numbering. In non-asserts builds, it1143/// is defined as a no-op inline function in BasicBlock.h.1144void BasicBlock::validateInstrOrdering() const {1145if (!isInstrOrderValid())1146return;1147const Instruction *Prev = nullptr;1148for (const Instruction &I : *this) {1149assert((!Prev || Prev->comesBefore(&I)) &&1150"cached instruction ordering is incorrect");1151Prev = &I;1152}1153}1154#endif11551156void BasicBlock::setTrailingDbgRecords(DbgMarker *foo) {1157getContext().pImpl->setTrailingDbgRecords(this, foo);1158}11591160DbgMarker *BasicBlock::getTrailingDbgRecords() {1161return getContext().pImpl->getTrailingDbgRecords(this);1162}11631164void BasicBlock::deleteTrailingDbgRecords() {1165getContext().pImpl->deleteTrailingDbgRecords(this);1166}116711681169