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