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