30#define DEBUG_TYPE "ir"
31STATISTIC(NumInstrRenumberings,
"Number of renumberings across all blocks");
35 return I->DebugMarker;
38 I->DebugMarker = Marker;
42DbgMarker *BasicBlock::createMarker(InstListType::iterator It) {
44 return createMarker(&*It);
49 setTrailingDbgRecords(
DM);
53void BasicBlock::convertToNewDbgValues() {
64 DVI->eraseFromParent();
71 DLI->eraseFromParent();
75 if (DbgVarRecs.
empty())
89void BasicBlock::convertFromNewDbgValues() {
95 for (
auto &Inst : *
this) {
96 if (!Inst.DebugMarker)
101 InstList.insert(Inst.getIterator(),
102 DR.createDebugIntrinsic(getModule(),
nullptr));
110 assert(!getTrailingDbgRecords());
114void BasicBlock::dumpDbgValues()
const {
115 for (
auto &Inst : *
this) {
116 if (!Inst.DebugMarker)
119 dbgs() <<
"@ " << Inst.DebugMarker <<
" ";
120 Inst.DebugMarker->dump();
127 return F->getValueSymbolTable();
132 return getType()->getContext();
149 insertInto(NewParent, InsertBefore);
152 "Cannot insert block before another block with no function!");
154 end().getNodePtr()->setParent(
this);
159 assert(NewParent &&
"Expected a parent");
160 assert(!Parent &&
"Already has a parent");
165 NewParent->
insert(NewParent->
end(),
this);
168BasicBlock::~BasicBlock() {
169 validateInstrOrdering();
177 if (hasAddressTaken()) {
178 assert(!use_empty() &&
"There should be at least one blockaddress!");
181 Constant *Replacement = ConstantInt::get(Type::getInt32Ty(getContext()), 1);
183 ConstantExpr::getIntToPtr(Replacement, BA->
getType()));
187 assert(
getParent() ==
nullptr &&
"BasicBlock still linked into the program!");
189 for (
auto &Inst : *
this) {
190 if (!Inst.DebugMarker)
192 Inst.DebugMarker->eraseFromParent();
197void BasicBlock::setParent(
Function *parent) {
199 if (Parent != parent)
200 Number = parent ? parent->NextBlockNum++ : -1u;
201 InstList.setSymTabObject(&Parent, parent);
206BasicBlock::instructionsWithoutDebug(
bool SkipPseudoOp)
const {
208 return !isa<DbgInfoIntrinsic>(
I) &&
209 !(SkipPseudoOp && isa<PseudoProbeInst>(
I));
216BasicBlock::instructionsWithoutDebug(
bool SkipPseudoOp) {
218 return !isa<DbgInfoIntrinsic>(
I) &&
219 !(SkipPseudoOp && isa<PseudoProbeInst>(
I));
226BasicBlock::sizeWithoutDebug()
const {
231void BasicBlock::removeFromParent() {
232 getParent()->getBasicBlockList().remove(getIterator());
236 return getParent()->getBasicBlockList().erase(getIterator());
243void BasicBlock::moveAfter(
BasicBlock *MovePos) {
248const Module *BasicBlock::getModule()
const {
252const DataLayout &BasicBlock::getDataLayout()
const {
253 return getModule()->getDataLayout();
256const CallInst *BasicBlock::getTerminatingMustTailCall()
const {
257 if (InstList.empty())
259 const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
260 if (!RI || RI == &InstList.front())
272 if (
auto *BI = dyn_cast<BitCastInst>(Prev)) {
275 if (!Prev || RV != Prev)
280 if (
auto *CI = dyn_cast<CallInst>(Prev)) {
281 if (CI->isMustTailCall())
287const CallInst *BasicBlock::getTerminatingDeoptimizeCall()
const {
288 if (InstList.empty())
290 auto *RI = dyn_cast<ReturnInst>(&InstList.back());
291 if (!RI || RI == &InstList.front())
294 if (
auto *CI = dyn_cast_or_null<CallInst>(RI->
getPrevNode()))
295 if (
Function *
F = CI->getCalledFunction())
296 if (
F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
302const CallInst *BasicBlock::getPostdominatingDeoptimizeCall()
const {
307 if (!Visited.
insert(Succ).second)
314const Instruction *BasicBlock::getFirstMayFaultInst()
const {
315 if (InstList.empty())
318 if (isa<LoadInst>(
I) || isa<StoreInst>(
I) || isa<CallBase>(
I))
323const Instruction* BasicBlock::getFirstNonPHI()
const {
325 if (!isa<PHINode>(
I))
332 if (!isa<PHINode>(
I))
354BasicBlock::getFirstNonPHIOrDbg(
bool SkipPseudoOp)
const {
356 if (isa<PHINode>(
I) || isa<DbgInfoIntrinsic>(
I))
359 if (SkipPseudoOp && isa<PseudoProbeInst>(
I))
372BasicBlock::getFirstNonPHIOrDbgOrLifetime(
bool SkipPseudoOp)
const {
374 if (isa<PHINode>(
I) || isa<DbgInfoIntrinsic>(
I))
377 if (
I.isLifetimeStartOrEnd())
380 if (SkipPseudoOp && isa<PseudoProbeInst>(
I))
395 if (InsertPt ==
end())
398 if (InsertPt->isEHPad()) ++InsertPt;
402 InsertPt.setHeadBit(
true);
408 if (InsertPt ==
end())
411 if (InsertPt->isEHPad())
414 if (isEntryBlock()) {
416 while (InsertPt !=
End &&
417 (isa<AllocaInst>(*InsertPt) || isa<DbgInfoIntrinsic>(*InsertPt) ||
418 isa<PseudoProbeInst>(*InsertPt))) {
419 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(&*InsertPt)) {
420 if (!AI->isStaticAlloca())
428 InsertPt.setHeadBit(
false);
432void BasicBlock::dropAllReferences() {
434 I.dropAllReferences();
437const BasicBlock *BasicBlock::getSinglePredecessor()
const {
439 if (PI ==
E)
return nullptr;
442 return (PI ==
E) ? ThePred :
nullptr ;
445const BasicBlock *BasicBlock::getUniquePredecessor()
const {
447 if (PI ==
E)
return nullptr;
450 for (;PI !=
E; ++PI) {
459bool BasicBlock::hasNPredecessors(
unsigned N)
const {
463bool BasicBlock::hasNPredecessorsOrMore(
unsigned N)
const {
467const BasicBlock *BasicBlock::getSingleSuccessor()
const {
469 if (
SI ==
E)
return nullptr;
472 return (
SI ==
E) ? TheSucc :
nullptr ;
475const BasicBlock *BasicBlock::getUniqueSuccessor()
const {
477 if (
SI ==
E)
return nullptr;
480 for (;
SI !=
E; ++
SI) {
490 PHINode *
P = empty() ? nullptr : dyn_cast<PHINode>(&*
begin());
491 return make_range<phi_iterator>(
P,
nullptr);
494void BasicBlock::removePredecessor(
BasicBlock *Pred,
495 bool KeepOneInputPHIs) {
498 "Pred is not a predecessor!");
501 if (empty() || !isa<PHINode>(
begin()))
504 unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
506 Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
507 if (KeepOneInputPHIs)
516 if (
Value *PhiConstant =
Phi.hasConstantValue()) {
517 Phi.replaceAllUsesWith(PhiConstant);
518 Phi.eraseFromParent();
523bool BasicBlock::canSplitPredecessors()
const {
525 if (isa<LandingPadInst>(FirstNonPHI))
530 if (FirstNonPHI->isEHPad())
535bool BasicBlock::isLegalToHoistInto()
const {
536 auto *
Term = getTerminator();
546 return !
Term->isSpecialTerminator();
549bool BasicBlock::isEntryBlock()
const {
551 assert(
F &&
"Block must have a parent function to use this API");
552 return this == &
F->getEntryBlock();
558 return splitBasicBlockBefore(
I, BBName);
560 assert(getTerminator() &&
"Can't use splitBasicBlock on degenerate BB!");
562 "Trying to get me to create degenerate basic block!");
577 BranchInst *BI = BranchInst::Create(New,
this);
585 New->replaceSuccessorsPhiUsesWith(
this, New);
589BasicBlock *BasicBlock::splitBasicBlockBefore(iterator
I,
const Twine &BBName) {
591 "Can't use splitBasicBlockBefore on degenerate BB!");
593 "Trying to get me to create degenerate basic block!");
595 assert((!isa<PHINode>(*
I) || getSinglePredecessor()) &&
596 "cannot split on multi incoming phis");
619 this->replacePhiUsesWith(Pred, New);
622 BranchInst *BI = BranchInst::Create(
this, New);
639 PHINode *PN = dyn_cast<PHINode>(&
I);
646void BasicBlock::replaceSuccessorsPhiUsesWith(
BasicBlock *Old,
654 Succ->replacePhiUsesWith(Old, New);
657void BasicBlock::replaceSuccessorsPhiUsesWith(
BasicBlock *New) {
658 this->replaceSuccessorsPhiUsesWith(
this, New);
661bool BasicBlock::isLandingPad()
const {
662 return isa<LandingPadInst>(getFirstNonPHIIt());
666 return dyn_cast<LandingPadInst>(getFirstNonPHIIt());
669std::optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight()
const {
671 if (
MDNode *MDIrrLoopHeader =
673 MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
674 if (MDName->
getString() ==
"loop_header_weight") {
675 auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
676 return std::optional<uint64_t>(CI->getValue().getZExtValue());
683 while (isa<DbgInfoIntrinsic>(It))
688void BasicBlock::renumberInstructions() {
694 SubclassOptionalData |= InstrOrderValid;
696 NumInstrRenumberings++;
699void BasicBlock::flushTerminatorDbgRecords() {
715 DbgMarker *TrailingDbgRecords = getTrailingDbgRecords();
716 if (!TrailingDbgRecords)
721 Term->DebugMarker->absorbDebugValues(*TrailingDbgRecords,
false);
723 deleteTrailingDbgRecords();
746 bool InsertAtHead = Dest.getHeadBit();
747 bool ReadFromHead =
First.getHeadBit();
754 DbgMarker *SrcTrailingDbgRecords = Src->getTrailingDbgRecords();
755 if (!SrcTrailingDbgRecords)
758 Dest->adoptDbgRecords(Src, Src->end(), InsertAtHead);
760 assert(!Src->getTrailingDbgRecords());
767 if (Src->empty() || First != Src->begin() || !ReadFromHead)
771 if (!
First->hasDbgRecords())
774 createMarker(Dest)->absorbDebugValues(*
First->DebugMarker, InsertAtHead);
814 DbgMarker *MoreDanglingDbgRecords =
nullptr;
815 DbgMarker *OurTrailingDbgRecords = getTrailingDbgRecords();
816 if (Dest ==
end() && !Dest.getHeadBit() && OurTrailingDbgRecords) {
819 if (!
First.getHeadBit() &&
First->hasDbgRecords()) {
820 MoreDanglingDbgRecords = Src->getMarker(First);
824 if (
First->hasDbgRecords()) {
832 First->adoptDbgRecords(
this,
end(),
true);
836 DbgMarker *CurMarker = Src->createMarker(&*First);
840 deleteTrailingDbgRecords();
841 First.setHeadBit(
true);
845 spliceDebugInfoImpl(Dest, Src, First, Last);
849 if (!MoreDanglingDbgRecords)
854 DbgMarker *LastMarker = Src->createMarker(Last);
865 bool InsertAtHead = Dest.getHeadBit();
866 bool ReadFromHead =
First.getHeadBit();
869 bool ReadFromTail = !
Last.getTailBit();
870 bool LastIsEnd = (
Last == Src->end());
936 if ((DestMarker = getMarker(Dest))) {
938 assert(DestMarker == getTrailingDbgRecords());
939 deleteTrailingDbgRecords();
947 if (ReadFromTail && Src->getMarker(Last)) {
948 DbgMarker *FromLast = Src->getMarker(Last);
952 assert(FromLast == Src->getTrailingDbgRecords());
953 createMarker(Dest)->absorbDebugValues(*FromLast,
true);
955 Src->deleteTrailingDbgRecords();
958 Dest->adoptDbgRecords(Src, Last,
true);
960 assert(!Src->getTrailingDbgRecords());
963 DbgMarker *OntoDest = createMarker(Dest);
971 if (!ReadFromHead &&
First->hasDbgRecords()) {
972 if (Last != Src->end()) {
973 Last->adoptDbgRecords(Src, First,
true);
975 DbgMarker *OntoLast = Src->createMarker(Last);
976 DbgMarker *FromFirst = Src->createMarker(First);
987 DbgMarker *NewDestMarker = createMarker(Dest);
996 DbgMarker *FirstMarker = createMarker(First);
1003void BasicBlock::splice(iterator Dest,
BasicBlock *Src, iterator First,
1005#ifdef EXPENSIVE_CHECKS
1007 auto FromBBEnd = Src->end();
1008 for (
auto It = First; It !=
Last; ++It)
1009 assert(It != FromBBEnd &&
"FromBeginIt not before FromEndIt!");
1014 if (First == Last) {
1015 spliceDebugInfoEmptyBlock(Dest, Src, First, Last);
1019 spliceDebugInfo(Dest, Src, First, Last);
1022 getInstList().splice(Dest, Src->getInstList(), First, Last);
1024 flushTerminatorDbgRecords();
1028 assert(
I->getParent() ==
this);
1030 iterator NextIt = std::next(
I->getIterator());
1031 DbgMarker *NextMarker = createMarker(NextIt);
1035void BasicBlock::insertDbgRecordBefore(
DbgRecord *DR,
1036 InstListType::iterator Where) {
1037 assert(Where ==
end() || Where->getParent() ==
this);
1038 bool InsertAtHead = Where.getHeadBit();
1040 M->insertDbgRecord(DR, InsertAtHead);
1044 return getMarker(std::next(
I->getIterator()));
1047DbgMarker *BasicBlock::getMarker(InstListType::iterator It) {
1052 return It->DebugMarker;
1055void BasicBlock::reinsertInstInDbgRecords(
1056 Instruction *
I, std::optional<DbgRecord::self_iterator> Pos) {
1112void BasicBlock::validateInstrOrdering()
const {
1113 if (!isInstrOrderValid())
1118 "cached instruction ordering is incorrect");
1124void BasicBlock::setTrailingDbgRecords(
DbgMarker *foo) {
1125 getContext().pImpl->setTrailingDbgRecords(
this, foo);
1128DbgMarker *BasicBlock::getTrailingDbgRecords() {
1129 return getContext().pImpl->getTrailingDbgRecords(
this);
1132void BasicBlock::deleteTrailingDbgRecords() {
1133 getContext().pImpl->deleteTrailingDbgRecords(
this);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
VarLocInsertPt getNextNode(const DbgRecord *DVR)
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
an instruction to allocate memory on the stack
LLVM Basic Block Representation.
void invalidateOrders()
Mark instruction ordering invalid. Done on every instruction insert.
InstListType::const_iterator const_iterator
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
The address of a basic block.
Conditional or Unconditional Branch instruction.
This class represents a function call, abstracting a target machine's calling convention.
This is an important base class in LLVM.
LLVM_ABI void destroyConstant()
Called if some element of this constant is no longer valid.
const DILocation * getWithoutAtom() const
A parsed version of the target data layout string in and methods for querying it.
This represents the llvm.dbg.label instruction.
Records a position in IR for a source label (DILabel).
Per-instruction record of debug-info.
LLVM_ABI void removeFromParent()
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
LLVM_ABI void absorbDebugValues(DbgMarker &Src, bool InsertAtHead)
Transfer any DbgRecords from Src into this DbgMarker.
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange()
Produce a range over all the DbgRecords in this Marker.
simple_ilist< DbgRecord > StoredDbgRecords
List of DbgRecords, the non-instruction equivalent of llvm.dbg.
LLVM_ABI void eraseFromParent()
LLVM_ABI void insertDbgRecord(DbgRecord *New, bool InsertAtHead)
Insert a DbgRecord into this DbgMarker, at the end of the list.
Base class for non-instruction debug metadata records that have positions within IR.
This is the common base class for debug info intrinsics for variables.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Function::iterator insert(Function::iterator Position, BasicBlock *BB)
Insert BB in the basic block list at Position.
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
This is an important class for using LLVM in a threaded context.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
LLVM_ABI StringRef getString() const
A Module instance is used to store all the information related to an LLVM module.
void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New)
Replace every incoming basic block Old to basic block New.
Return a value (possibly void), from a function.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
Value * getOperand(unsigned i) const
This class provides a symbol table of name/value pairs.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Specialization of filter_iterator_base for forward iteration only.
self_iterator getIterator()
base_list_type::iterator iterator
A range adaptor for a pair of iterators.
NodeAddr< PhiNode * > Phi
LLVM_ABI const_iterator begin(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get begin iterator over path.
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
This is an optimization pass for GlobalISel generic memory operations.
auto pred_end(const MachineBasicBlock *BB)
auto successors(const MachineBasicBlock *BB)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
bool hasNItemsOrMore(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has N or more items.
LLVM_ABI BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It)
Advance It while it points to a debug instruction and return the result.
bool hasNItems(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has exactly N items.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
void invalidateParentIListOrdering(ParentClass *Parent)
Notify basic blocks when an instruction is inserted.
auto pred_begin(const MachineBasicBlock *BB)
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Option to add extra bits to the ilist_iterator.
Option to add a pointer to this list's owner in every node.