1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the BasicBlock class for the IR library.
11 //===----------------------------------------------------------------------===//
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"
26 #include "LLVMContextImpl.h"
30 #define DEBUG_TYPE "ir"
31 STATISTIC(NumInstrRenumberings
, "Number of renumberings across all blocks");
34 UseNewDbgInfoFormat("experimental-debuginfo-iterators",
35 cl::desc("Enable communicating debuginfo positions "
36 "through iterators, eliminating intrinsics"),
39 DPMarker
*BasicBlock::createMarker(Instruction
*I
) {
40 assert(IsNewDbgInfoFormat
&&
41 "Tried to create a marker in a non new debug-info block!");
44 DPMarker
*Marker
= new DPMarker();
45 Marker
->MarkedInstr
= I
;
46 I
->DbgMarker
= Marker
;
50 DPMarker
*BasicBlock::createMarker(InstListType::iterator It
) {
51 assert(IsNewDbgInfoFormat
&&
52 "Tried to create a marker in a non new debug-info block!");
54 return createMarker(&*It
);
55 DPMarker
*DPM
= getTrailingDPValues();
59 setTrailingDPValues(DPM
);
63 void BasicBlock::convertToNewDbgValues() {
64 // Is the command line option set?
65 if (!UseNewDbgInfoFormat
)
68 IsNewDbgInfoFormat
= true;
70 // Iterate over all instructions in the instruction list, collecting dbg.value
71 // instructions and converting them to DPValues. Once we find a "real"
72 // instruction, attach all those DPValues to a DPMarker in that instruction.
73 SmallVector
<DPValue
*, 4> DPVals
;
74 for (Instruction
&I
: make_early_inc_range(InstList
)) {
75 assert(!I
.DbgMarker
&& "DbgMarker already set on old-format instrs?");
76 if (DbgVariableIntrinsic
*DVI
= dyn_cast
<DbgVariableIntrinsic
>(&I
)) {
77 // Convert this dbg.value to a DPValue.
78 DPValue
*Value
= new DPValue(DVI
);
79 DPVals
.push_back(Value
);
80 DVI
->eraseFromParent();
84 // Create a marker to store DPValues in. Technically we don't need to store
85 // one marker per instruction, but that's a future optimisation.
87 DPMarker
*Marker
= I
.DbgMarker
;
89 for (DPValue
*DPV
: DPVals
)
90 Marker
->insertDPValue(DPV
, false);
96 void BasicBlock::convertFromNewDbgValues() {
98 IsNewDbgInfoFormat
= false;
100 // Iterate over the block, finding instructions annotated with DPMarkers.
101 // Convert any attached DPValues to dbg.values and insert ahead of the
103 for (auto &Inst
: *this) {
107 DPMarker
&Marker
= *Inst
.DbgMarker
;
108 for (DPValue
&DPV
: Marker
.getDbgValueRange())
109 InstList
.insert(Inst
.getIterator(),
110 DPV
.createDebugIntrinsic(getModule(), nullptr));
112 Marker
.eraseFromParent();
115 // Assume no trailing DPValues: we could technically create them at the end
116 // of the block, after a terminator, but this would be non-cannonical and
117 // indicates that something else is broken somewhere.
118 assert(!getTrailingDPValues());
121 bool BasicBlock::validateDbgValues(bool Assert
, bool Msg
, raw_ostream
*OS
) {
126 // Helper lambda for reporting failures: via assertion, printing, and return
128 auto TestFailure
= [Assert
, Msg
, &RetVal
, OS
](bool Val
, const char *Text
) {
129 // Did the test fail?
133 // If we're asserting, then fire off an assertion.
135 llvm_unreachable(Text
);
142 // We should have the same debug-format as the parent function.
143 TestFailure(getParent()->IsNewDbgInfoFormat
== IsNewDbgInfoFormat
,
144 "Parent function doesn't have the same debug-info format");
146 // Only validate if we are using the new format.
147 if (!IsNewDbgInfoFormat
)
150 // Match every DPMarker to every Instruction and vice versa, and
151 // verify that there are no invalid DPValues.
152 for (auto It
= begin(); It
!= end(); ++It
) {
156 // Validate DebugProgramMarkers.
157 DPMarker
*CurrentDebugMarker
= It
->DbgMarker
;
159 // If this is a marker, it should match the instruction and vice versa.
160 TestFailure(CurrentDebugMarker
->MarkedInstr
== &*It
,
161 "Debug Marker points to incorrect instruction?");
163 // Now validate any DPValues in the marker.
164 for (DPValue
&DPV
: CurrentDebugMarker
->getDbgValueRange()) {
165 // Validate DebugProgramValues.
166 TestFailure(DPV
.getMarker() == CurrentDebugMarker
,
167 "Not pointing at correct next marker!");
169 // Verify that no DbgValues appear prior to PHIs.
172 "DebugProgramValues must not appear before PHI nodes in a block!");
176 // Except transiently when removing + re-inserting the block terminator, there
177 // should be no trailing DPValues.
178 TestFailure(!getTrailingDPValues(), "Trailing DPValues in block");
183 void BasicBlock::dumpDbgValues() const {
184 for (auto &Inst
: *this) {
188 dbgs() << "@ " << Inst
.DbgMarker
<< " ";
189 Inst
.DbgMarker
->dump();
194 void BasicBlock::setIsNewDbgInfoFormat(bool NewFlag
) {
195 if (NewFlag
&& !IsNewDbgInfoFormat
)
196 convertToNewDbgValues();
197 else if (!NewFlag
&& IsNewDbgInfoFormat
)
198 convertFromNewDbgValues();
201 ValueSymbolTable
*BasicBlock::getValueSymbolTable() {
202 if (Function
*F
= getParent())
203 return F
->getValueSymbolTable();
207 LLVMContext
&BasicBlock::getContext() const {
208 return getType()->getContext();
211 template <> void llvm::invalidateParentIListOrdering(BasicBlock
*BB
) {
212 BB
->invalidateOrders();
215 // Explicit instantiation of SymbolTableListTraits since some of the methods
216 // are not in the public header file...
217 template class llvm::SymbolTableListTraits
<Instruction
,
218 ilist_iterator_bits
<true>>;
220 BasicBlock::BasicBlock(LLVMContext
&C
, const Twine
&Name
, Function
*NewParent
,
221 BasicBlock
*InsertBefore
)
222 : Value(Type::getLabelTy(C
), Value::BasicBlockVal
),
223 IsNewDbgInfoFormat(false), Parent(nullptr) {
226 insertInto(NewParent
, InsertBefore
);
228 assert(!InsertBefore
&&
229 "Cannot insert block before another block with no function!");
233 setIsNewDbgInfoFormat(NewParent
->IsNewDbgInfoFormat
);
236 void BasicBlock::insertInto(Function
*NewParent
, BasicBlock
*InsertBefore
) {
237 assert(NewParent
&& "Expected a parent");
238 assert(!Parent
&& "Already has a parent");
241 NewParent
->insert(InsertBefore
->getIterator(), this);
243 NewParent
->insert(NewParent
->end(), this);
245 setIsNewDbgInfoFormat(NewParent
->IsNewDbgInfoFormat
);
248 BasicBlock::~BasicBlock() {
249 validateInstrOrdering();
251 // If the address of the block is taken and it is being deleted (e.g. because
252 // it is dead), this means that there is either a dangling constant expr
253 // hanging off the block, or an undefined use of the block (source code
254 // expecting the address of a label to keep the block alive even though there
255 // is no indirect branch). Handle these cases by zapping the BlockAddress
256 // nodes. There are no other possible uses at this point.
257 if (hasAddressTaken()) {
258 assert(!use_empty() && "There should be at least one blockaddress!");
259 Constant
*Replacement
=
260 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
261 while (!use_empty()) {
262 BlockAddress
*BA
= cast
<BlockAddress
>(user_back());
263 BA
->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement
,
265 BA
->destroyConstant();
269 assert(getParent() == nullptr && "BasicBlock still linked into the program!");
271 for (auto &Inst
: *this) {
274 Inst
.DbgMarker
->eraseFromParent();
279 void BasicBlock::setParent(Function
*parent
) {
280 // Set Parent=parent, updating instruction symtab entries as appropriate.
281 InstList
.setSymTabObject(&Parent
, parent
);
284 iterator_range
<filter_iterator
<BasicBlock::const_iterator
,
285 std::function
<bool(const Instruction
&)>>>
286 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp
) const {
287 std::function
<bool(const Instruction
&)> Fn
= [=](const Instruction
&I
) {
288 return !isa
<DbgInfoIntrinsic
>(I
) &&
289 !(SkipPseudoOp
&& isa
<PseudoProbeInst
>(I
));
291 return make_filter_range(*this, Fn
);
295 filter_iterator
<BasicBlock::iterator
, std::function
<bool(Instruction
&)>>>
296 BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp
) {
297 std::function
<bool(Instruction
&)> Fn
= [=](Instruction
&I
) {
298 return !isa
<DbgInfoIntrinsic
>(I
) &&
299 !(SkipPseudoOp
&& isa
<PseudoProbeInst
>(I
));
301 return make_filter_range(*this, Fn
);
304 filter_iterator
<BasicBlock::const_iterator
,
305 std::function
<bool(const Instruction
&)>>::difference_type
306 BasicBlock::sizeWithoutDebug() const {
307 return std::distance(instructionsWithoutDebug().begin(),
308 instructionsWithoutDebug().end());
311 void BasicBlock::removeFromParent() {
312 getParent()->getBasicBlockList().remove(getIterator());
315 iplist
<BasicBlock
>::iterator
BasicBlock::eraseFromParent() {
316 return getParent()->getBasicBlockList().erase(getIterator());
319 void BasicBlock::moveBefore(SymbolTableList
<BasicBlock
>::iterator MovePos
) {
320 getParent()->splice(MovePos
, getParent(), getIterator());
323 void BasicBlock::moveAfter(BasicBlock
*MovePos
) {
324 MovePos
->getParent()->splice(++MovePos
->getIterator(), getParent(),
328 const Module
*BasicBlock::getModule() const {
329 return getParent()->getParent();
332 const CallInst
*BasicBlock::getTerminatingMustTailCall() const {
333 if (InstList
.empty())
335 const ReturnInst
*RI
= dyn_cast
<ReturnInst
>(&InstList
.back());
336 if (!RI
|| RI
== &InstList
.front())
339 const Instruction
*Prev
= RI
->getPrevNode();
343 if (Value
*RV
= RI
->getReturnValue()) {
347 // Look through the optional bitcast.
348 if (auto *BI
= dyn_cast
<BitCastInst
>(Prev
)) {
349 RV
= BI
->getOperand(0);
350 Prev
= BI
->getPrevNode();
351 if (!Prev
|| RV
!= Prev
)
356 if (auto *CI
= dyn_cast
<CallInst
>(Prev
)) {
357 if (CI
->isMustTailCall())
363 const CallInst
*BasicBlock::getTerminatingDeoptimizeCall() const {
364 if (InstList
.empty())
366 auto *RI
= dyn_cast
<ReturnInst
>(&InstList
.back());
367 if (!RI
|| RI
== &InstList
.front())
370 if (auto *CI
= dyn_cast_or_null
<CallInst
>(RI
->getPrevNode()))
371 if (Function
*F
= CI
->getCalledFunction())
372 if (F
->getIntrinsicID() == Intrinsic::experimental_deoptimize
)
378 const CallInst
*BasicBlock::getPostdominatingDeoptimizeCall() const {
379 const BasicBlock
* BB
= this;
380 SmallPtrSet
<const BasicBlock
*, 8> Visited
;
382 while (auto *Succ
= BB
->getUniqueSuccessor()) {
383 if (!Visited
.insert(Succ
).second
)
387 return BB
->getTerminatingDeoptimizeCall();
390 const Instruction
*BasicBlock::getFirstMayFaultInst() const {
391 if (InstList
.empty())
393 for (const Instruction
&I
: *this)
394 if (isa
<LoadInst
>(I
) || isa
<StoreInst
>(I
) || isa
<CallBase
>(I
))
399 const Instruction
* BasicBlock::getFirstNonPHI() const {
400 for (const Instruction
&I
: *this)
401 if (!isa
<PHINode
>(I
))
406 BasicBlock::const_iterator
BasicBlock::getFirstNonPHIIt() const {
407 const Instruction
*I
= getFirstNonPHI();
408 BasicBlock::const_iterator It
= I
->getIterator();
409 // Set the head-inclusive bit to indicate that this iterator includes
410 // any debug-info at the start of the block. This is a no-op unless the
411 // appropriate CMake flag is set.
416 const Instruction
*BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp
) const {
417 for (const Instruction
&I
: *this) {
418 if (isa
<PHINode
>(I
) || isa
<DbgInfoIntrinsic
>(I
))
421 if (SkipPseudoOp
&& isa
<PseudoProbeInst
>(I
))
430 BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp
) const {
431 for (const Instruction
&I
: *this) {
432 if (isa
<PHINode
>(I
) || isa
<DbgInfoIntrinsic
>(I
))
435 if (I
.isLifetimeStartOrEnd())
438 if (SkipPseudoOp
&& isa
<PseudoProbeInst
>(I
))
446 BasicBlock::const_iterator
BasicBlock::getFirstInsertionPt() const {
447 const Instruction
*FirstNonPHI
= getFirstNonPHI();
451 const_iterator InsertPt
= FirstNonPHI
->getIterator();
452 if (InsertPt
->isEHPad()) ++InsertPt
;
453 // Set the head-inclusive bit to indicate that this iterator includes
454 // any debug-info at the start of the block. This is a no-op unless the
455 // appropriate CMake flag is set.
456 InsertPt
.setHeadBit(true);
460 BasicBlock::const_iterator
BasicBlock::getFirstNonPHIOrDbgOrAlloca() const {
461 const Instruction
*FirstNonPHI
= getFirstNonPHI();
465 const_iterator InsertPt
= FirstNonPHI
->getIterator();
466 if (InsertPt
->isEHPad())
469 if (isEntryBlock()) {
470 const_iterator End
= end();
471 while (InsertPt
!= End
&&
472 (isa
<AllocaInst
>(*InsertPt
) || isa
<DbgInfoIntrinsic
>(*InsertPt
) ||
473 isa
<PseudoProbeInst
>(*InsertPt
))) {
474 if (const AllocaInst
*AI
= dyn_cast
<AllocaInst
>(&*InsertPt
)) {
475 if (!AI
->isStaticAlloca())
484 void BasicBlock::dropAllReferences() {
485 for (Instruction
&I
: *this)
486 I
.dropAllReferences();
489 const BasicBlock
*BasicBlock::getSinglePredecessor() const {
490 const_pred_iterator PI
= pred_begin(this), E
= pred_end(this);
491 if (PI
== E
) return nullptr; // No preds.
492 const BasicBlock
*ThePred
= *PI
;
494 return (PI
== E
) ? ThePred
: nullptr /*multiple preds*/;
497 const BasicBlock
*BasicBlock::getUniquePredecessor() const {
498 const_pred_iterator PI
= pred_begin(this), E
= pred_end(this);
499 if (PI
== E
) return nullptr; // No preds.
500 const BasicBlock
*PredBB
= *PI
;
502 for (;PI
!= E
; ++PI
) {
505 // The same predecessor appears multiple times in the predecessor list.
511 bool BasicBlock::hasNPredecessors(unsigned N
) const {
512 return hasNItems(pred_begin(this), pred_end(this), N
);
515 bool BasicBlock::hasNPredecessorsOrMore(unsigned N
) const {
516 return hasNItemsOrMore(pred_begin(this), pred_end(this), N
);
519 const BasicBlock
*BasicBlock::getSingleSuccessor() const {
520 const_succ_iterator SI
= succ_begin(this), E
= succ_end(this);
521 if (SI
== E
) return nullptr; // no successors
522 const BasicBlock
*TheSucc
= *SI
;
524 return (SI
== E
) ? TheSucc
: nullptr /* multiple successors */;
527 const BasicBlock
*BasicBlock::getUniqueSuccessor() const {
528 const_succ_iterator SI
= succ_begin(this), E
= succ_end(this);
529 if (SI
== E
) return nullptr; // No successors
530 const BasicBlock
*SuccBB
= *SI
;
532 for (;SI
!= E
; ++SI
) {
535 // The same successor appears multiple times in the successor list.
541 iterator_range
<BasicBlock::phi_iterator
> BasicBlock::phis() {
542 PHINode
*P
= empty() ? nullptr : dyn_cast
<PHINode
>(&*begin());
543 return make_range
<phi_iterator
>(P
, nullptr);
546 void BasicBlock::removePredecessor(BasicBlock
*Pred
,
547 bool KeepOneInputPHIs
) {
548 // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
549 assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred
)) &&
550 "Pred is not a predecessor!");
552 // Return early if there are no PHI nodes to update.
553 if (empty() || !isa
<PHINode
>(begin()))
556 unsigned NumPreds
= cast
<PHINode
>(front()).getNumIncomingValues();
557 for (PHINode
&Phi
: make_early_inc_range(phis())) {
558 Phi
.removeIncomingValue(Pred
, !KeepOneInputPHIs
);
559 if (KeepOneInputPHIs
)
562 // If we have a single predecessor, removeIncomingValue may have erased the
567 // Try to replace the PHI node with a constant value.
568 if (Value
*PhiConstant
= Phi
.hasConstantValue()) {
569 Phi
.replaceAllUsesWith(PhiConstant
);
570 Phi
.eraseFromParent();
575 bool BasicBlock::canSplitPredecessors() const {
576 const Instruction
*FirstNonPHI
= getFirstNonPHI();
577 if (isa
<LandingPadInst
>(FirstNonPHI
))
579 // This is perhaps a little conservative because constructs like
580 // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors
581 // cannot handle such things just yet.
582 if (FirstNonPHI
->isEHPad())
587 bool BasicBlock::isLegalToHoistInto() const {
588 auto *Term
= getTerminator();
589 // No terminator means the block is under construction.
593 // If the block has no successors, there can be no instructions to hoist.
594 assert(Term
->getNumSuccessors() > 0);
596 // Instructions should not be hoisted across special terminators, which may
597 // have side effects or return values.
598 return !Term
->isSpecialTerminator();
601 bool BasicBlock::isEntryBlock() const {
602 const Function
*F
= getParent();
603 assert(F
&& "Block must have a parent function to use this API");
604 return this == &F
->getEntryBlock();
607 BasicBlock
*BasicBlock::splitBasicBlock(iterator I
, const Twine
&BBName
,
610 return splitBasicBlockBefore(I
, BBName
);
612 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
613 assert(I
!= InstList
.end() &&
614 "Trying to get me to create degenerate basic block!");
616 BasicBlock
*New
= BasicBlock::Create(getContext(), BBName
, getParent(),
617 this->getNextNode());
619 // Save DebugLoc of split point before invalidating iterator.
620 DebugLoc Loc
= I
->getStableDebugLoc();
621 // Move all of the specified instructions from the original basic block into
622 // the new basic block.
623 New
->splice(New
->end(), this, I
, end());
625 // Add a branch instruction to the newly formed basic block.
626 BranchInst
*BI
= BranchInst::Create(New
, this);
627 BI
->setDebugLoc(Loc
);
629 // Now we must loop through all of the successors of the New block (which
630 // _were_ the successors of the 'this' block), and update any PHI nodes in
631 // successors. If there were PHI nodes in the successors, then they need to
632 // know that incoming branches will be from New, not from Old (this).
634 New
->replaceSuccessorsPhiUsesWith(this, New
);
638 BasicBlock
*BasicBlock::splitBasicBlockBefore(iterator I
, const Twine
&BBName
) {
639 assert(getTerminator() &&
640 "Can't use splitBasicBlockBefore on degenerate BB!");
641 assert(I
!= InstList
.end() &&
642 "Trying to get me to create degenerate basic block!");
644 assert((!isa
<PHINode
>(*I
) || getSinglePredecessor()) &&
645 "cannot split on multi incoming phis");
647 BasicBlock
*New
= BasicBlock::Create(getContext(), BBName
, getParent(), this);
648 // Save DebugLoc of split point before invalidating iterator.
649 DebugLoc Loc
= I
->getDebugLoc();
650 // Move all of the specified instructions from the original basic block into
651 // the new basic block.
652 New
->splice(New
->end(), this, begin(), I
);
654 // Loop through all of the predecessors of the 'this' block (which will be the
655 // predecessors of the New block), replace the specified successor 'this'
656 // block to point at the New block and update any PHI nodes in 'this' block.
657 // If there were PHI nodes in 'this' block, the PHI nodes are updated
658 // to reflect that the incoming branches will be from the New block and not
659 // from predecessors of the 'this' block.
660 // Save predecessors to separate vector before modifying them.
661 SmallVector
<BasicBlock
*, 4> Predecessors
;
662 for (BasicBlock
*Pred
: predecessors(this))
663 Predecessors
.push_back(Pred
);
664 for (BasicBlock
*Pred
: Predecessors
) {
665 Instruction
*TI
= Pred
->getTerminator();
666 TI
->replaceSuccessorWith(this, New
);
667 this->replacePhiUsesWith(Pred
, New
);
669 // Add a branch instruction from "New" to "this" Block.
670 BranchInst
*BI
= BranchInst::Create(this, New
);
671 BI
->setDebugLoc(Loc
);
676 BasicBlock::iterator
BasicBlock::erase(BasicBlock::iterator FromIt
,
677 BasicBlock::iterator ToIt
) {
678 return InstList
.erase(FromIt
, ToIt
);
681 void BasicBlock::replacePhiUsesWith(BasicBlock
*Old
, BasicBlock
*New
) {
682 // N.B. This might not be a complete BasicBlock, so don't assume
683 // that it ends with a non-phi instruction.
684 for (Instruction
&I
: *this) {
685 PHINode
*PN
= dyn_cast
<PHINode
>(&I
);
688 PN
->replaceIncomingBlockWith(Old
, New
);
692 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock
*Old
,
694 Instruction
*TI
= getTerminator();
696 // Cope with being called on a BasicBlock that doesn't have a terminator
697 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
699 for (BasicBlock
*Succ
: successors(TI
))
700 Succ
->replacePhiUsesWith(Old
, New
);
703 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock
*New
) {
704 this->replaceSuccessorsPhiUsesWith(this, New
);
707 bool BasicBlock::isLandingPad() const {
708 return isa
<LandingPadInst
>(getFirstNonPHI());
711 const LandingPadInst
*BasicBlock::getLandingPadInst() const {
712 return dyn_cast
<LandingPadInst
>(getFirstNonPHI());
715 std::optional
<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
716 const Instruction
*TI
= getTerminator();
717 if (MDNode
*MDIrrLoopHeader
=
718 TI
->getMetadata(LLVMContext::MD_irr_loop
)) {
719 MDString
*MDName
= cast
<MDString
>(MDIrrLoopHeader
->getOperand(0));
720 if (MDName
->getString().equals("loop_header_weight")) {
721 auto *CI
= mdconst::extract
<ConstantInt
>(MDIrrLoopHeader
->getOperand(1));
722 return std::optional
<uint64_t>(CI
->getValue().getZExtValue());
728 BasicBlock::iterator
llvm::skipDebugIntrinsics(BasicBlock::iterator It
) {
729 while (isa
<DbgInfoIntrinsic
>(It
))
734 void BasicBlock::renumberInstructions() {
736 for (Instruction
&I
: *this)
739 // Set the bit to indicate that the instruction order valid and cached.
740 BasicBlockBits Bits
= getBasicBlockBits();
741 Bits
.InstrOrderValid
= true;
742 setBasicBlockBits(Bits
);
744 NumInstrRenumberings
++;
747 void BasicBlock::flushTerminatorDbgValues() {
748 // If we erase the terminator in a block, any DPValues will sink and "fall
749 // off the end", existing after any terminator that gets inserted. With
750 // dbg.value intrinsics we would just insert the terminator at end() and
751 // the dbg.values would come before the terminator. With DPValues, we must
753 // To get out of this unfortunate form, whenever we insert a terminator,
754 // check whether there's anything trailing at the end and move those DPValues
755 // in front of the terminator.
757 // Do nothing if we're not in new debug-info format.
758 if (!IsNewDbgInfoFormat
)
761 // If there's no terminator, there's nothing to do.
762 Instruction
*Term
= getTerminator();
766 // Are there any dangling DPValues?
767 DPMarker
*TrailingDPValues
= getTrailingDPValues();
768 if (!TrailingDPValues
)
771 // Transfer DPValues from the trailing position onto the terminator.
772 Term
->DbgMarker
->absorbDebugValues(*TrailingDPValues
, false);
773 TrailingDPValues
->eraseFromParent();
774 deleteTrailingDPValues();
777 void BasicBlock::spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest
,
779 BasicBlock::iterator First
,
780 BasicBlock::iterator Last
) {
781 // Imagine the folowing:
787 // If an optimisation pass attempts to splice the contents of the block from
788 // BB1->begin() to BB1->getTerminator(), then the dbg.value will be
789 // transferred to the destination.
790 // However, in the "new" DPValue format for debug-info, that range is empty:
791 // begin() returns an iterator to the terminator, as there will only be a
792 // single instruction in the block. We must piece together from the bits set
793 // in the iterators whether there was the intention to transfer any debug
796 // If we're not in "new" debug-info format, do nothing.
797 if (!IsNewDbgInfoFormat
)
800 assert(First
== Last
);
801 bool InsertAtHead
= Dest
.getHeadBit();
802 bool ReadFromHead
= First
.getHeadBit();
804 // If the source block is completely empty, including no terminator, then
805 // transfer any trailing DPValues that are still hanging around. This can
806 // occur when a block is optimised away and the terminator has been moved
809 assert(Dest
!= end() &&
810 "Transferring trailing DPValues to another trailing position");
811 DPMarker
*SrcTrailingDPValues
= Src
->getTrailingDPValues();
812 if (!SrcTrailingDPValues
)
815 DPMarker
*M
= Dest
->DbgMarker
;
816 M
->absorbDebugValues(*SrcTrailingDPValues
, InsertAtHead
);
817 SrcTrailingDPValues
->eraseFromParent();
818 Src
->deleteTrailingDPValues();
822 // There are instructions in this block; if the First iterator was
823 // with begin() / getFirstInsertionPt() then the caller intended debug-info
824 // at the start of the block to be transferred. Return otherwise.
825 if (Src
->empty() || First
!= Src
->begin() || !ReadFromHead
)
828 // Is there actually anything to transfer?
829 if (!First
->hasDbgValues())
832 createMarker(Dest
)->absorbDebugValues(*First
->DbgMarker
, InsertAtHead
);
837 void BasicBlock::spliceDebugInfo(BasicBlock::iterator Dest
, BasicBlock
*Src
,
838 BasicBlock::iterator First
,
839 BasicBlock::iterator Last
) {
840 /* Do a quick normalisation before calling the real splice implementation. We
841 might be operating on a degenerate basic block that has no instructions
842 in it, a legitimate transient state. In that case, Dest will be end() and
843 any DPValues temporarily stored in the TrailingDPValues map in LLVMContext.
844 We might illustrate it thus:
849 Src-block: ++++B---B---B---B:::C
853 However: does the caller expect the "~" DPValues to end up before or after
854 the spliced segment? This is communciated in the "Head" bit of Dest, which
855 signals whether the caller called begin() or end() on this block.
857 If the head bit is set, then all is well, we leave DPValues trailing just
858 like how dbg.value instructions would trail after instructions spliced to
859 the beginning of this block.
861 If the head bit isn't set, then try to jam the "~" DPValues onto the front
862 of the First instruction, then splice like normal, which joins the "~"
863 DPValues with the "+" DPValues. However if the "+" DPValues are supposed to
864 be left behind in Src, then:
865 * detach the "+" DPValues,
866 * move the "~" DPValues onto First,
867 * splice like normal,
868 * replace the "+" DPValues onto the Last position.
869 Complicated, but gets the job done. */
871 // If we're inserting at end(), and not in front of dangling DPValues, then
872 // move the DPValues onto "First". They'll then be moved naturally in the
874 DPMarker
*MoreDanglingDPValues
= nullptr;
875 DPMarker
*OurTrailingDPValues
= getTrailingDPValues();
876 if (Dest
== end() && !Dest
.getHeadBit() && OurTrailingDPValues
) {
877 // Are the "+" DPValues not supposed to move? If so, detach them
879 if (!First
.getHeadBit() && First
->hasDbgValues()) {
880 MoreDanglingDPValues
= Src
->getMarker(First
);
881 MoreDanglingDPValues
->removeFromParent();
884 if (First
->hasDbgValues()) {
885 DPMarker
*CurMarker
= Src
->getMarker(First
);
886 // Place them at the front, it would look like this:
890 // Src-block: ~~~~~~~~++++B---B---B---B:::C
893 CurMarker
->absorbDebugValues(*OurTrailingDPValues
, true);
894 OurTrailingDPValues
->eraseFromParent();
896 // No current marker, create one and absorb in. (FIXME: we can avoid an
897 // allocation in the future).
898 DPMarker
*CurMarker
= Src
->createMarker(&*First
);
899 CurMarker
->absorbDebugValues(*OurTrailingDPValues
, false);
900 OurTrailingDPValues
->eraseFromParent();
902 deleteTrailingDPValues();
903 First
.setHeadBit(true);
906 // Call the main debug-info-splicing implementation.
907 spliceDebugInfoImpl(Dest
, Src
, First
, Last
);
909 // Do we have some "+" DPValues hanging around that weren't supposed to move,
910 // and we detached to make things easier?
911 if (!MoreDanglingDPValues
)
914 // FIXME: we could avoid an allocation here sometimes.
915 DPMarker
*LastMarker
= Src
->createMarker(Last
);
916 LastMarker
->absorbDebugValues(*MoreDanglingDPValues
, true);
917 MoreDanglingDPValues
->eraseFromParent();
920 void BasicBlock::spliceDebugInfoImpl(BasicBlock::iterator Dest
, BasicBlock
*Src
,
921 BasicBlock::iterator First
,
922 BasicBlock::iterator Last
) {
923 // Find out where to _place_ these dbg.values; if InsertAtHead is specified,
924 // this will be at the start of Dest's debug value range, otherwise this is
925 // just Dest's marker.
926 bool InsertAtHead
= Dest
.getHeadBit();
927 bool ReadFromHead
= First
.getHeadBit();
928 // Use this flag to signal the abnormal case, where we don't want to copy the
929 // DPValues ahead of the "Last" position.
930 bool ReadFromTail
= !Last
.getTailBit();
931 bool LastIsEnd
= (Last
== Src
->end());
934 Here's an illustration of what we're about to do. We have two blocks, this
935 and Src, and two segments of list. Each instruction is marked by a capital
936 while potential DPValue debug-info is marked out by "-" characters and a few
937 other special characters (+:=) where I want to highlight what's going on.
941 this-block: A----A----A ====A----A----A----A---A---A
942 Src-block ++++B---B---B---B:::C
946 The splice method is going to take all the instructions from First up to
947 (but not including) Last and insert them in _front_ of Dest, forming one
948 long list. All the DPValues attached to instructions _between_ First and
949 Last need no maintenence. However, we have to do special things with the
950 DPValues marked with the +:= characters. We only have three positions:
951 should the "+" DPValues be transferred, and if so to where? Do we move the
952 ":" DPValues? Would they go in front of the "=" DPValues, or should the "="
953 DPValues go before "+" DPValues?
955 We're told which way it should be by the bits carried in the iterators. The
956 "Head" bit indicates whether the specified position is supposed to be at the
957 front of the attached DPValues (true) or not (false). The Tail bit is true
958 on the other end of a range: is the range intended to include DPValues up to
959 the end (false) or not (true).
961 FIXME: the tail bit doesn't need to be distinct from the head bit, we could
964 Here are some examples of different configurations:
966 Dest.Head = true, First.Head = true, Last.Tail = false
968 this-block: A----A----A++++B---B---B---B:::====A----A----A----A---A---A
972 Wheras if we didn't want to read from the Src list,
974 Dest.Head = true, First.Head = false, Last.Tail = false
976 this-block: A----A----AB---B---B---B:::====A----A----A----A---A---A
980 Or if we didn't want to insert at the head of Dest:
982 Dest.Head = false, First.Head = false, Last.Tail = false
984 this-block: A----A----A====B---B---B---B:::A----A----A----A---A---A
988 Tests for these various configurations can be found in the unit test file
989 BasicBlockDbgInfoTest.cpp.
993 // Detach the marker at Dest -- this lets us move the "====" DPValues around.
994 DPMarker
*DestMarker
= nullptr;
996 DestMarker
= getMarker(Dest
);
997 DestMarker
->removeFromParent();
998 createMarker(&*Dest
);
1001 // If we're moving the tail range of DPValues (":::"), absorb them into the
1002 // front of the DPValues at Dest.
1003 if (ReadFromTail
&& Src
->getMarker(Last
)) {
1004 DPMarker
*OntoDest
= getMarker(Dest
);
1005 DPMarker
*FromLast
= Src
->getMarker(Last
);
1006 OntoDest
->absorbDebugValues(*FromLast
, true);
1008 FromLast
->eraseFromParent();
1009 Src
->deleteTrailingDPValues();
1013 // If we're _not_ reading from the head of First, i.e. the "++++" DPValues,
1014 // move their markers onto Last. They remain in the Src block. No action
1016 if (!ReadFromHead
&& First
->hasDbgValues()) {
1017 DPMarker
*OntoLast
= Src
->createMarker(Last
);
1018 DPMarker
*FromFirst
= Src
->createMarker(First
);
1019 OntoLast
->absorbDebugValues(*FromFirst
,
1020 true); // Always insert at head of it.
1023 // Finally, do something with the "====" DPValues we detached.
1026 // Insert them at the end of the DPValues at Dest. The "::::" DPValues
1027 // might be in front of them.
1028 DPMarker
*NewDestMarker
= getMarker(Dest
);
1029 NewDestMarker
->absorbDebugValues(*DestMarker
, false);
1031 // Insert them right at the start of the range we moved, ahead of First
1032 // and the "++++" DPValues.
1033 DPMarker
*FirstMarker
= getMarker(First
);
1034 FirstMarker
->absorbDebugValues(*DestMarker
, true);
1036 DestMarker
->eraseFromParent();
1037 } else if (Dest
== end() && !InsertAtHead
) {
1038 // In the rare circumstance where we insert at end(), and we did not
1039 // generate the iterator with begin() / getFirstInsertionPt(), it means
1040 // any trailing debug-info at the end of the block would "normally" have
1041 // been pushed in front of "First". Move it there now.
1042 DPMarker
*FirstMarker
= getMarker(First
);
1043 DPMarker
*TrailingDPValues
= getTrailingDPValues();
1044 if (TrailingDPValues
) {
1045 FirstMarker
->absorbDebugValues(*TrailingDPValues
, true);
1046 TrailingDPValues
->eraseFromParent();
1047 deleteTrailingDPValues();
1052 void BasicBlock::splice(iterator Dest
, BasicBlock
*Src
, iterator First
,
1054 assert(Src
->IsNewDbgInfoFormat
== IsNewDbgInfoFormat
);
1056 #ifdef EXPENSIVE_CHECKS
1057 // Check that First is before Last.
1058 auto FromBBEnd
= Src
->end();
1059 for (auto It
= First
; It
!= Last
; ++It
)
1060 assert(It
!= FromBBEnd
&& "FromBeginIt not before FromEndIt!");
1061 #endif // EXPENSIVE_CHECKS
1063 // Lots of horrible special casing for empty transfers: the dbg.values between
1064 // two positions could be spliced in dbg.value mode.
1065 if (First
== Last
) {
1066 spliceDebugInfoEmptyBlock(Dest
, Src
, First
, Last
);
1070 // Handle non-instr debug-info specific juggling.
1071 if (IsNewDbgInfoFormat
)
1072 spliceDebugInfo(Dest
, Src
, First
, Last
);
1074 // And move the instructions.
1075 getInstList().splice(Dest
, Src
->getInstList(), First
, Last
);
1077 flushTerminatorDbgValues();
1080 void BasicBlock::insertDPValueAfter(DPValue
*DPV
, Instruction
*I
) {
1081 assert(IsNewDbgInfoFormat
);
1082 assert(I
->getParent() == this);
1084 iterator NextIt
= std::next(I
->getIterator());
1085 DPMarker
*NextMarker
= getMarker(NextIt
);
1087 NextMarker
= createMarker(NextIt
);
1088 NextMarker
->insertDPValue(DPV
, true);
1091 void BasicBlock::insertDPValueBefore(DPValue
*DPV
,
1092 InstListType::iterator Where
) {
1093 // We should never directly insert at the end of the block, new DPValues
1094 // shouldn't be generated at times when there's no terminator.
1095 assert(Where
!= end());
1096 assert(Where
->getParent() == this);
1097 if (!Where
->DbgMarker
)
1098 createMarker(Where
);
1099 bool InsertAtHead
= Where
.getHeadBit();
1100 Where
->DbgMarker
->insertDPValue(DPV
, InsertAtHead
);
1103 DPMarker
*BasicBlock::getNextMarker(Instruction
*I
) {
1104 return getMarker(std::next(I
->getIterator()));
1107 DPMarker
*BasicBlock::getMarker(InstListType::iterator It
) {
1109 DPMarker
*DPM
= getTrailingDPValues();
1112 return It
->DbgMarker
;
1115 void BasicBlock::reinsertInstInDPValues(
1116 Instruction
*I
, std::optional
<DPValue::self_iterator
> Pos
) {
1117 // "I" was originally removed from a position where it was
1118 // immediately in front of Pos. Any DPValues on that position then "fell down"
1119 // onto Pos. "I" has been re-inserted at the front of that wedge of DPValues,
1120 // shuffle them around to represent the original positioning. To illustrate:
1122 // Instructions: I1---I---I0
1123 // DPValues: DDD DDD
1125 // Instruction "I" removed,
1127 // Instructions: I1------I0
1131 // Instruction "I" re-inserted (now):
1133 // Instructions: I1---I------I0
1137 // After this method completes:
1139 // Instructions: I1---I---I0
1140 // DPValues: DDD DDD
1142 // This happens if there were no DPValues on I0. Are there now DPValues there?
1144 DPMarker
*NextMarker
= getNextMarker(I
);
1147 if (NextMarker
->StoredDPValues
.empty())
1149 // There are DPMarkers there now -- they fell down from "I".
1150 DPMarker
*ThisMarker
= createMarker(I
);
1151 ThisMarker
->absorbDebugValues(*NextMarker
, false);
1155 // Is there even a range of DPValues to move?
1156 DPMarker
*DPM
= (*Pos
)->getMarker();
1157 auto Range
= make_range(DPM
->StoredDPValues
.begin(), (*Pos
));
1158 if (Range
.begin() == Range
.end())
1161 // Otherwise: splice.
1162 DPMarker
*ThisMarker
= createMarker(I
);
1163 assert(ThisMarker
->StoredDPValues
.empty());
1164 ThisMarker
->absorbDebugValues(Range
, *DPM
, true);
1168 /// In asserts builds, this checks the numbering. In non-asserts builds, it
1169 /// is defined as a no-op inline function in BasicBlock.h.
1170 void BasicBlock::validateInstrOrdering() const {
1171 if (!isInstrOrderValid())
1173 const Instruction
*Prev
= nullptr;
1174 for (const Instruction
&I
: *this) {
1175 assert((!Prev
|| Prev
->comesBefore(&I
)) &&
1176 "cached instruction ordering is incorrect");
1182 void BasicBlock::setTrailingDPValues(DPMarker
*foo
) {
1183 getContext().pImpl
->setTrailingDPValues(this, foo
);
1186 DPMarker
*BasicBlock::getTrailingDPValues() {
1187 return getContext().pImpl
->getTrailingDPValues(this);
1190 void BasicBlock::deleteTrailingDPValues() {
1191 getContext().pImpl
->deleteTrailingDPValues(this);