Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:57

0001 //===- llvm/BasicBlock.h - Represent a basic block in the VM ----*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file contains the declaration of the BasicBlock class.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_IR_BASICBLOCK_H
0014 #define LLVM_IR_BASICBLOCK_H
0015 
0016 #include "llvm-c/Types.h"
0017 #include "llvm/ADT/DenseMap.h"
0018 #include "llvm/ADT/Twine.h"
0019 #include "llvm/ADT/ilist.h"
0020 #include "llvm/ADT/ilist_node.h"
0021 #include "llvm/ADT/iterator.h"
0022 #include "llvm/ADT/iterator_range.h"
0023 #include "llvm/IR/DebugProgramInstruction.h"
0024 #include "llvm/IR/Instruction.h"
0025 #include "llvm/IR/SymbolTableListTraits.h"
0026 #include "llvm/IR/Value.h"
0027 #include <cassert>
0028 #include <cstddef>
0029 #include <iterator>
0030 
0031 namespace llvm {
0032 
0033 class AssemblyAnnotationWriter;
0034 class CallInst;
0035 class DataLayout;
0036 class Function;
0037 class LandingPadInst;
0038 class LLVMContext;
0039 class Module;
0040 class PHINode;
0041 class ValueSymbolTable;
0042 class DbgVariableRecord;
0043 class DbgMarker;
0044 
0045 /// LLVM Basic Block Representation
0046 ///
0047 /// This represents a single basic block in LLVM. A basic block is simply a
0048 /// container of instructions that execute sequentially. Basic blocks are Values
0049 /// because they are referenced by instructions such as branches and switch
0050 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
0051 /// represents a label to which a branch can jump.
0052 ///
0053 /// A well formed basic block is formed of a list of non-terminating
0054 /// instructions followed by a single terminator instruction. Terminator
0055 /// instructions may not occur in the middle of basic blocks, and must terminate
0056 /// the blocks. The BasicBlock class allows malformed basic blocks to occur
0057 /// because it may be useful in the intermediate stage of constructing or
0058 /// modifying a program. However, the verifier will ensure that basic blocks are
0059 /// "well formed".
0060 class BasicBlock final : public Value, // Basic blocks are data objects also
0061                          public ilist_node_with_parent<BasicBlock, Function> {
0062 public:
0063   using InstListType = SymbolTableList<Instruction, ilist_iterator_bits<true>,
0064                                        ilist_parent<BasicBlock>>;
0065   /// Flag recording whether or not this block stores debug-info in the form
0066   /// of intrinsic instructions (false) or non-instruction records (true).
0067   bool IsNewDbgInfoFormat;
0068 
0069 private:
0070   // Allow Function to renumber blocks.
0071   friend class Function;
0072   /// Per-function unique number.
0073   unsigned Number = -1u;
0074 
0075   friend class BlockAddress;
0076   friend class SymbolTableListTraits<BasicBlock>;
0077 
0078   InstListType InstList;
0079   Function *Parent;
0080 
0081 public:
0082   /// Attach a DbgMarker to the given instruction. Enables the storage of any
0083   /// debug-info at this position in the program.
0084   DbgMarker *createMarker(Instruction *I);
0085   DbgMarker *createMarker(InstListType::iterator It);
0086 
0087   /// Convert variable location debugging information stored in dbg.value
0088   /// intrinsics into DbgMarkers / DbgRecords. Deletes all dbg.values in
0089   /// the process and sets IsNewDbgInfoFormat = true. Only takes effect if
0090   /// the UseNewDbgInfoFormat LLVM command line option is given.
0091   void convertToNewDbgValues();
0092 
0093   /// Convert variable location debugging information stored in DbgMarkers and
0094   /// DbgRecords into the dbg.value intrinsic representation. Sets
0095   /// IsNewDbgInfoFormat = false.
0096   void convertFromNewDbgValues();
0097 
0098   /// Ensure the block is in "old" dbg.value format (\p NewFlag == false) or
0099   /// in the new format (\p NewFlag == true), converting to the desired format
0100   /// if necessary.
0101   void setIsNewDbgInfoFormat(bool NewFlag);
0102   void setNewDbgInfoFormatFlag(bool NewFlag);
0103 
0104   unsigned getNumber() const {
0105     assert(getParent() && "only basic blocks in functions have valid numbers");
0106     return Number;
0107   }
0108 
0109   /// Record that the collection of DbgRecords in \p M "trails" after the last
0110   /// instruction of this block. These are equivalent to dbg.value intrinsics
0111   /// that exist at the end of a basic block with no terminator (a transient
0112   /// state that occurs regularly).
0113   void setTrailingDbgRecords(DbgMarker *M);
0114 
0115   /// Fetch the collection of DbgRecords that "trail" after the last instruction
0116   /// of this block, see \ref setTrailingDbgRecords. If there are none, returns
0117   /// nullptr.
0118   DbgMarker *getTrailingDbgRecords();
0119 
0120   /// Delete any trailing DbgRecords at the end of this block, see
0121   /// \ref setTrailingDbgRecords.
0122   void deleteTrailingDbgRecords();
0123 
0124   void dumpDbgValues() const;
0125 
0126   /// Return the DbgMarker for the position given by \p It, so that DbgRecords
0127   /// can be inserted there. This will either be nullptr if not present, a
0128   /// DbgMarker, or TrailingDbgRecords if It is end().
0129   DbgMarker *getMarker(InstListType::iterator It);
0130 
0131   /// Return the DbgMarker for the position that comes after \p I. \see
0132   /// BasicBlock::getMarker, this can be nullptr, a DbgMarker, or
0133   /// TrailingDbgRecords if there is no next instruction.
0134   DbgMarker *getNextMarker(Instruction *I);
0135 
0136   /// Insert a DbgRecord into a block at the position given by \p I.
0137   void insertDbgRecordAfter(DbgRecord *DR, Instruction *I);
0138 
0139   /// Insert a DbgRecord into a block at the position given by \p Here.
0140   void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here);
0141 
0142   /// Eject any debug-info trailing at the end of a block. DbgRecords can
0143   /// transiently be located "off the end" of a block if the blocks terminator
0144   /// is temporarily removed. Once a terminator is re-inserted this method will
0145   /// move such DbgRecords back to the right place (ahead of the terminator).
0146   void flushTerminatorDbgRecords();
0147 
0148   /// In rare circumstances instructions can be speculatively removed from
0149   /// blocks, and then be re-inserted back into that position later. When this
0150   /// happens in RemoveDIs debug-info mode, some special patching-up needs to
0151   /// occur: inserting into the middle of a sequence of dbg.value intrinsics
0152   /// does not have an equivalent with DbgRecords.
0153   void reinsertInstInDbgRecords(Instruction *I,
0154                                 std::optional<DbgRecord::self_iterator> Pos);
0155 
0156 private:
0157   void setParent(Function *parent);
0158 
0159   /// Constructor.
0160   ///
0161   /// If the function parameter is specified, the basic block is automatically
0162   /// inserted at either the end of the function (if InsertBefore is null), or
0163   /// before the specified basic block.
0164   explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
0165                       Function *Parent = nullptr,
0166                       BasicBlock *InsertBefore = nullptr);
0167 
0168 public:
0169   BasicBlock(const BasicBlock &) = delete;
0170   BasicBlock &operator=(const BasicBlock &) = delete;
0171   ~BasicBlock();
0172 
0173   /// Get the context in which this basic block lives.
0174   LLVMContext &getContext() const;
0175 
0176   /// Instruction iterators...
0177   using iterator = InstListType::iterator;
0178   using const_iterator = InstListType::const_iterator;
0179   using reverse_iterator = InstListType::reverse_iterator;
0180   using const_reverse_iterator = InstListType::const_reverse_iterator;
0181 
0182   // These functions and classes need access to the instruction list.
0183   friend void Instruction::removeFromParent();
0184   friend BasicBlock::iterator Instruction::eraseFromParent();
0185   friend BasicBlock::iterator Instruction::insertInto(BasicBlock *BB,
0186                                                       BasicBlock::iterator It);
0187   friend class llvm::SymbolTableListTraits<
0188       llvm::Instruction, ilist_iterator_bits<true>, ilist_parent<BasicBlock>>;
0189   friend class llvm::ilist_node_with_parent<llvm::Instruction, llvm::BasicBlock,
0190                                             ilist_iterator_bits<true>,
0191                                             ilist_parent<BasicBlock>>;
0192 
0193   // Friendly methods that need to access us for the maintenence of
0194   // debug-info attachments.
0195   friend void Instruction::insertBefore(BasicBlock::iterator InsertPos);
0196   friend void Instruction::insertAfter(Instruction *InsertPos);
0197   friend void Instruction::insertAfter(BasicBlock::iterator InsertPos);
0198   friend void Instruction::insertBefore(BasicBlock &BB,
0199                                         InstListType::iterator InsertPos);
0200   friend void Instruction::moveBeforeImpl(BasicBlock &BB,
0201                                           InstListType::iterator I,
0202                                           bool Preserve);
0203   friend iterator_range<DbgRecord::self_iterator>
0204   Instruction::cloneDebugInfoFrom(
0205       const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
0206       bool InsertAtHead);
0207 
0208   /// Creates a new BasicBlock.
0209   ///
0210   /// If the Parent parameter is specified, the basic block is automatically
0211   /// inserted at either the end of the function (if InsertBefore is 0), or
0212   /// before the specified basic block.
0213   static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
0214                             Function *Parent = nullptr,
0215                             BasicBlock *InsertBefore = nullptr) {
0216     return new BasicBlock(Context, Name, Parent, InsertBefore);
0217   }
0218 
0219   /// Return the enclosing method, or null if none.
0220   const Function *getParent() const { return Parent; }
0221         Function *getParent()       { return Parent; }
0222 
0223   /// Return the module owning the function this basic block belongs to, or
0224   /// nullptr if the function does not have a module.
0225   ///
0226   /// Note: this is undefined behavior if the block does not have a parent.
0227   const Module *getModule() const;
0228   Module *getModule() {
0229     return const_cast<Module *>(
0230                             static_cast<const BasicBlock *>(this)->getModule());
0231   }
0232 
0233   /// Get the data layout of the module this basic block belongs to.
0234   ///
0235   /// Requires the basic block to have a parent module.
0236   const DataLayout &getDataLayout() const;
0237 
0238   /// Returns the terminator instruction if the block is well formed or null
0239   /// if the block is not well formed.
0240   const Instruction *getTerminator() const LLVM_READONLY {
0241     if (InstList.empty() || !InstList.back().isTerminator())
0242       return nullptr;
0243     return &InstList.back();
0244   }
0245   Instruction *getTerminator() {
0246     return const_cast<Instruction *>(
0247         static_cast<const BasicBlock *>(this)->getTerminator());
0248   }
0249 
0250   /// Returns the call instruction calling \@llvm.experimental.deoptimize
0251   /// prior to the terminating return instruction of this basic block, if such
0252   /// a call is present.  Otherwise, returns null.
0253   const CallInst *getTerminatingDeoptimizeCall() const;
0254   CallInst *getTerminatingDeoptimizeCall() {
0255     return const_cast<CallInst *>(
0256          static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
0257   }
0258 
0259   /// Returns the call instruction calling \@llvm.experimental.deoptimize
0260   /// that is present either in current basic block or in block that is a unique
0261   /// successor to current block, if such call is present. Otherwise, returns null.
0262   const CallInst *getPostdominatingDeoptimizeCall() const;
0263   CallInst *getPostdominatingDeoptimizeCall() {
0264     return const_cast<CallInst *>(
0265          static_cast<const BasicBlock *>(this)->getPostdominatingDeoptimizeCall());
0266   }
0267 
0268   /// Returns the call instruction marked 'musttail' prior to the terminating
0269   /// return instruction of this basic block, if such a call is present.
0270   /// Otherwise, returns null.
0271   const CallInst *getTerminatingMustTailCall() const;
0272   CallInst *getTerminatingMustTailCall() {
0273     return const_cast<CallInst *>(
0274            static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
0275   }
0276 
0277   /// Returns a pointer to the first instruction in this block that is not a
0278   /// PHINode instruction.
0279   ///
0280   /// When adding instructions to the beginning of the basic block, they should
0281   /// be added before the returned value, not before the first instruction,
0282   /// which might be PHI. Returns 0 is there's no non-PHI instruction.
0283   ///
0284   /// Deprecated in favour of getFirstNonPHIIt, which returns an iterator that
0285   /// preserves some debugging information.
0286   LLVM_DEPRECATED("Use iterators as instruction positions", "getFirstNonPHIIt")
0287   const Instruction *getFirstNonPHI() const;
0288   LLVM_DEPRECATED("Use iterators as instruction positions instead",
0289                   "getFirstNonPHIIt")
0290   Instruction *getFirstNonPHI();
0291 
0292   /// Returns an iterator to the first instruction in this block that is not a
0293   /// PHINode instruction.
0294   ///
0295   /// When adding instructions to the beginning of the basic block, they should
0296   /// be added before the returned value, not before the first instruction,
0297   /// which might be PHI. Returns end() if there's no non-PHI instruction.
0298   ///
0299   /// Avoid unwrapping the iterator to an Instruction* before inserting here,
0300   /// as important debug-info is preserved in the iterator.
0301   InstListType::const_iterator getFirstNonPHIIt() const;
0302   InstListType::iterator getFirstNonPHIIt() {
0303     BasicBlock::iterator It =
0304         static_cast<const BasicBlock *>(this)->getFirstNonPHIIt().getNonConst();
0305     It.setHeadBit(true);
0306     return It;
0307   }
0308 
0309   /// Returns a pointer to the first instruction in this block that is not a
0310   /// PHINode or a debug intrinsic, or any pseudo operation if \c SkipPseudoOp
0311   /// is true.
0312   InstListType::const_iterator
0313   getFirstNonPHIOrDbg(bool SkipPseudoOp = true) const;
0314   InstListType::iterator getFirstNonPHIOrDbg(bool SkipPseudoOp = true) {
0315     return static_cast<const BasicBlock *>(this)
0316         ->getFirstNonPHIOrDbg(SkipPseudoOp)
0317         .getNonConst();
0318   }
0319 
0320   /// Returns a pointer to the first instruction in this block that is not a
0321   /// PHINode, a debug intrinsic, or a lifetime intrinsic, or any pseudo
0322   /// operation if \c SkipPseudoOp is true.
0323   InstListType::const_iterator
0324   getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = true) const;
0325   InstListType::iterator
0326   getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = true) {
0327     return static_cast<const BasicBlock *>(this)
0328         ->getFirstNonPHIOrDbgOrLifetime(SkipPseudoOp)
0329         .getNonConst();
0330   }
0331 
0332   /// Returns an iterator to the first instruction in this block that is
0333   /// suitable for inserting a non-PHI instruction.
0334   ///
0335   /// In particular, it skips all PHIs and LandingPad instructions.
0336   const_iterator getFirstInsertionPt() const;
0337   iterator getFirstInsertionPt() {
0338     return static_cast<const BasicBlock *>(this)
0339                                           ->getFirstInsertionPt().getNonConst();
0340   }
0341 
0342   /// Returns an iterator to the first instruction in this block that is
0343   /// not a PHINode, a debug intrinsic, a static alloca or any pseudo operation.
0344   const_iterator getFirstNonPHIOrDbgOrAlloca() const;
0345   iterator getFirstNonPHIOrDbgOrAlloca() {
0346     return static_cast<const BasicBlock *>(this)
0347         ->getFirstNonPHIOrDbgOrAlloca()
0348         .getNonConst();
0349   }
0350 
0351   /// Returns the first potential AsynchEH faulty instruction
0352   /// currently it checks for loads/stores (which may dereference a null
0353   /// pointer) and calls/invokes (which may propagate exceptions)
0354   const Instruction* getFirstMayFaultInst() const;
0355   Instruction* getFirstMayFaultInst() {
0356       return const_cast<Instruction*>(
0357           static_cast<const BasicBlock*>(this)->getFirstMayFaultInst());
0358   }
0359 
0360   /// Return a const iterator range over the instructions in the block, skipping
0361   /// any debug instructions. Skip any pseudo operations as well if \c
0362   /// SkipPseudoOp is true.
0363   iterator_range<filter_iterator<BasicBlock::const_iterator,
0364                                  std::function<bool(const Instruction &)>>>
0365   instructionsWithoutDebug(bool SkipPseudoOp = true) const;
0366 
0367   /// Return an iterator range over the instructions in the block, skipping any
0368   /// debug instructions. Skip and any pseudo operations as well if \c
0369   /// SkipPseudoOp is true.
0370   iterator_range<
0371       filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
0372   instructionsWithoutDebug(bool SkipPseudoOp = true);
0373 
0374   /// Return the size of the basic block ignoring debug instructions
0375   filter_iterator<BasicBlock::const_iterator,
0376                   std::function<bool(const Instruction &)>>::difference_type
0377   sizeWithoutDebug() const;
0378 
0379   /// Unlink 'this' from the containing function, but do not delete it.
0380   void removeFromParent();
0381 
0382   /// Unlink 'this' from the containing function and delete it.
0383   ///
0384   // \returns an iterator pointing to the element after the erased one.
0385   SymbolTableList<BasicBlock>::iterator eraseFromParent();
0386 
0387   /// Unlink this basic block from its current function and insert it into
0388   /// the function that \p MovePos lives in, right before \p MovePos.
0389   inline void moveBefore(BasicBlock *MovePos) {
0390     moveBefore(MovePos->getIterator());
0391   }
0392   void moveBefore(SymbolTableList<BasicBlock>::iterator MovePos);
0393 
0394   /// Unlink this basic block from its current function and insert it
0395   /// right after \p MovePos in the function \p MovePos lives in.
0396   void moveAfter(BasicBlock *MovePos);
0397 
0398   /// Insert unlinked basic block into a function.
0399   ///
0400   /// Inserts an unlinked basic block into \c Parent.  If \c InsertBefore is
0401   /// provided, inserts before that basic block, otherwise inserts at the end.
0402   ///
0403   /// \pre \a getParent() is \c nullptr.
0404   void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
0405 
0406   /// Return the predecessor of this block if it has a single predecessor
0407   /// block. Otherwise return a null pointer.
0408   const BasicBlock *getSinglePredecessor() const;
0409   BasicBlock *getSinglePredecessor() {
0410     return const_cast<BasicBlock *>(
0411                  static_cast<const BasicBlock *>(this)->getSinglePredecessor());
0412   }
0413 
0414   /// Return the predecessor of this block if it has a unique predecessor
0415   /// block. Otherwise return a null pointer.
0416   ///
0417   /// Note that unique predecessor doesn't mean single edge, there can be
0418   /// multiple edges from the unique predecessor to this block (for example a
0419   /// switch statement with multiple cases having the same destination).
0420   const BasicBlock *getUniquePredecessor() const;
0421   BasicBlock *getUniquePredecessor() {
0422     return const_cast<BasicBlock *>(
0423                  static_cast<const BasicBlock *>(this)->getUniquePredecessor());
0424   }
0425 
0426   /// Return true if this block has exactly N predecessors.
0427   bool hasNPredecessors(unsigned N) const;
0428 
0429   /// Return true if this block has N predecessors or more.
0430   bool hasNPredecessorsOrMore(unsigned N) const;
0431 
0432   /// Return the successor of this block if it has a single successor.
0433   /// Otherwise return a null pointer.
0434   ///
0435   /// This method is analogous to getSinglePredecessor above.
0436   const BasicBlock *getSingleSuccessor() const;
0437   BasicBlock *getSingleSuccessor() {
0438     return const_cast<BasicBlock *>(
0439                    static_cast<const BasicBlock *>(this)->getSingleSuccessor());
0440   }
0441 
0442   /// Return the successor of this block if it has a unique successor.
0443   /// Otherwise return a null pointer.
0444   ///
0445   /// This method is analogous to getUniquePredecessor above.
0446   const BasicBlock *getUniqueSuccessor() const;
0447   BasicBlock *getUniqueSuccessor() {
0448     return const_cast<BasicBlock *>(
0449                    static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
0450   }
0451 
0452   /// Print the basic block to an output stream with an optional
0453   /// AssemblyAnnotationWriter.
0454   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
0455              bool ShouldPreserveUseListOrder = false,
0456              bool IsForDebug = false) const;
0457 
0458   //===--------------------------------------------------------------------===//
0459   /// Instruction iterator methods
0460   ///
0461   inline iterator begin() {
0462     iterator It = InstList.begin();
0463     // Set the head-inclusive bit to indicate that this iterator includes
0464     // any debug-info at the start of the block. This is a no-op unless the
0465     // appropriate CMake flag is set.
0466     It.setHeadBit(true);
0467     return It;
0468   }
0469   inline const_iterator begin() const {
0470     const_iterator It = InstList.begin();
0471     It.setHeadBit(true);
0472     return It;
0473   }
0474   inline iterator                end  ()       { return InstList.end();   }
0475   inline const_iterator          end  () const { return InstList.end();   }
0476 
0477   inline reverse_iterator        rbegin()       { return InstList.rbegin(); }
0478   inline const_reverse_iterator  rbegin() const { return InstList.rbegin(); }
0479   inline reverse_iterator        rend  ()       { return InstList.rend();   }
0480   inline const_reverse_iterator  rend  () const { return InstList.rend();   }
0481 
0482   inline size_t                   size() const { return InstList.size();  }
0483   inline bool                    empty() const { return InstList.empty(); }
0484   inline const Instruction      &front() const { return InstList.front(); }
0485   inline       Instruction      &front()       { return InstList.front(); }
0486   inline const Instruction       &back() const { return InstList.back();  }
0487   inline       Instruction       &back()       { return InstList.back();  }
0488 
0489   /// Iterator to walk just the phi nodes in the basic block.
0490   template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
0491   class phi_iterator_impl
0492       : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
0493                                     std::forward_iterator_tag, PHINodeT> {
0494     friend BasicBlock;
0495 
0496     PHINodeT *PN;
0497 
0498     phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
0499 
0500   public:
0501     // Allow default construction to build variables, but this doesn't build
0502     // a useful iterator.
0503     phi_iterator_impl() = default;
0504 
0505     // Allow conversion between instantiations where valid.
0506     template <typename PHINodeU, typename BBIteratorU,
0507               typename = std::enable_if_t<
0508                   std::is_convertible<PHINodeU *, PHINodeT *>::value>>
0509     phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
0510         : PN(Arg.PN) {}
0511 
0512     bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
0513 
0514     PHINodeT &operator*() const { return *PN; }
0515 
0516     using phi_iterator_impl::iterator_facade_base::operator++;
0517     phi_iterator_impl &operator++() {
0518       assert(PN && "Cannot increment the end iterator!");
0519       PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
0520       return *this;
0521     }
0522   };
0523   using phi_iterator = phi_iterator_impl<>;
0524   using const_phi_iterator =
0525       phi_iterator_impl<const PHINode, BasicBlock::const_iterator>;
0526 
0527   /// Returns a range that iterates over the phis in the basic block.
0528   ///
0529   /// Note that this cannot be used with basic blocks that have no terminator.
0530   iterator_range<const_phi_iterator> phis() const {
0531     return const_cast<BasicBlock *>(this)->phis();
0532   }
0533   iterator_range<phi_iterator> phis();
0534 
0535 private:
0536   /// Return the underlying instruction list container.
0537   /// This is deliberately private because we have implemented an adequate set
0538   /// of functions to modify the list, including BasicBlock::splice(),
0539   /// BasicBlock::erase(), Instruction::insertInto() etc.
0540   const InstListType &getInstList() const { return InstList; }
0541   InstListType &getInstList() { return InstList; }
0542 
0543   /// Returns a pointer to a member of the instruction list.
0544   /// This is private on purpose, just like `getInstList()`.
0545   static InstListType BasicBlock::*getSublistAccess(Instruction *) {
0546     return &BasicBlock::InstList;
0547   }
0548 
0549   /// Dedicated function for splicing debug-info: when we have an empty
0550   /// splice (i.e. zero instructions), the caller may still intend any
0551   /// debug-info in between the two "positions" to be spliced.
0552   void spliceDebugInfoEmptyBlock(BasicBlock::iterator ToIt, BasicBlock *FromBB,
0553                                  BasicBlock::iterator FromBeginIt,
0554                                  BasicBlock::iterator FromEndIt);
0555 
0556   /// Perform any debug-info specific maintenence for the given splice
0557   /// activity. In the DbgRecord debug-info representation, debug-info is not
0558   /// in instructions, and so it does not automatically move from one block
0559   /// to another.
0560   void spliceDebugInfo(BasicBlock::iterator ToIt, BasicBlock *FromBB,
0561                        BasicBlock::iterator FromBeginIt,
0562                        BasicBlock::iterator FromEndIt);
0563   void spliceDebugInfoImpl(BasicBlock::iterator ToIt, BasicBlock *FromBB,
0564                            BasicBlock::iterator FromBeginIt,
0565                            BasicBlock::iterator FromEndIt);
0566 
0567 public:
0568   /// Returns a pointer to the symbol table if one exists.
0569   ValueSymbolTable *getValueSymbolTable();
0570 
0571   /// Methods for support type inquiry through isa, cast, and dyn_cast.
0572   static bool classof(const Value *V) {
0573     return V->getValueID() == Value::BasicBlockVal;
0574   }
0575 
0576   /// Cause all subinstructions to "let go" of all the references that said
0577   /// subinstructions are maintaining.
0578   ///
0579   /// This allows one to 'delete' a whole class at a time, even though there may
0580   /// be circular references... first all references are dropped, and all use
0581   /// counts go to zero.  Then everything is delete'd for real.  Note that no
0582   /// operations are valid on an object that has "dropped all references",
0583   /// except operator delete.
0584   void dropAllReferences();
0585 
0586   /// Update PHI nodes in this BasicBlock before removal of predecessor \p Pred.
0587   /// Note that this function does not actually remove the predecessor.
0588   ///
0589   /// If \p KeepOneInputPHIs is true then don't remove PHIs that are left with
0590   /// zero or one incoming values, and don't simplify PHIs with all incoming
0591   /// values the same.
0592   void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs = false);
0593 
0594   bool canSplitPredecessors() const;
0595 
0596   /// Split the basic block into two basic blocks at the specified instruction.
0597   ///
0598   /// If \p Before is true, splitBasicBlockBefore handles the
0599   /// block splitting. Otherwise, execution proceeds as described below.
0600   ///
0601   /// Note that all instructions BEFORE the specified iterator
0602   /// stay as part of the original basic block, an unconditional branch is added
0603   /// to the original BB, and the rest of the instructions in the BB are moved
0604   /// to the new BB, including the old terminator.  The newly formed basic block
0605   /// is returned. This function invalidates the specified iterator.
0606   ///
0607   /// Note that this only works on well formed basic blocks (must have a
0608   /// terminator), and \p 'I' must not be the end of instruction list (which
0609   /// would cause a degenerate basic block to be formed, having a terminator
0610   /// inside of the basic block).
0611   ///
0612   /// Also note that this doesn't preserve any passes. To split blocks while
0613   /// keeping loop information consistent, use the SplitBlock utility function.
0614   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "",
0615                               bool Before = false);
0616   BasicBlock *splitBasicBlock(Instruction *I, const Twine &BBName = "",
0617                               bool Before = false) {
0618     return splitBasicBlock(I->getIterator(), BBName, Before);
0619   }
0620 
0621   /// Split the basic block into two basic blocks at the specified instruction
0622   /// and insert the new basic blocks as the predecessor of the current block.
0623   ///
0624   /// This function ensures all instructions AFTER and including the specified
0625   /// iterator \p I are part of the original basic block. All Instructions
0626   /// BEFORE the iterator \p I are moved to the new BB and an unconditional
0627   /// branch is added to the new BB. The new basic block is returned.
0628   ///
0629   /// Note that this only works on well formed basic blocks (must have a
0630   /// terminator), and \p 'I' must not be the end of instruction list (which
0631   /// would cause a degenerate basic block to be formed, having a terminator
0632   /// inside of the basic block).  \p 'I' cannot be a iterator for a PHINode
0633   /// with multiple incoming blocks.
0634   ///
0635   /// Also note that this doesn't preserve any passes. To split blocks while
0636   /// keeping loop information consistent, use the SplitBlockBefore utility
0637   /// function.
0638   BasicBlock *splitBasicBlockBefore(iterator I, const Twine &BBName = "");
0639   BasicBlock *splitBasicBlockBefore(Instruction *I, const Twine &BBName = "") {
0640     return splitBasicBlockBefore(I->getIterator(), BBName);
0641   }
0642 
0643   /// Transfer all instructions from \p FromBB to this basic block at \p ToIt.
0644   void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB) {
0645     splice(ToIt, FromBB, FromBB->begin(), FromBB->end());
0646   }
0647 
0648   /// Transfer one instruction from \p FromBB at \p FromIt to this basic block
0649   /// at \p ToIt.
0650   void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB,
0651               BasicBlock::iterator FromIt) {
0652     auto FromItNext = std::next(FromIt);
0653     // Single-element splice is a noop if destination == source.
0654     if (ToIt == FromIt || ToIt == FromItNext)
0655       return;
0656     splice(ToIt, FromBB, FromIt, FromItNext);
0657   }
0658 
0659   /// Transfer a range of instructions that belong to \p FromBB from \p
0660   /// FromBeginIt to \p FromEndIt, to this basic block at \p ToIt.
0661   void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB,
0662               BasicBlock::iterator FromBeginIt,
0663               BasicBlock::iterator FromEndIt);
0664 
0665   /// Erases a range of instructions from \p FromIt to (not including) \p ToIt.
0666   /// \Returns \p ToIt.
0667   BasicBlock::iterator erase(BasicBlock::iterator FromIt, BasicBlock::iterator ToIt);
0668 
0669   /// Returns true if there are any uses of this basic block other than
0670   /// direct branches, switches, etc. to it.
0671   bool hasAddressTaken() const {
0672     return getBasicBlockBits().BlockAddressRefCount != 0;
0673   }
0674 
0675   /// Update all phi nodes in this basic block to refer to basic block \p New
0676   /// instead of basic block \p Old.
0677   void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New);
0678 
0679   /// Update all phi nodes in this basic block's successors to refer to basic
0680   /// block \p New instead of basic block \p Old.
0681   void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New);
0682 
0683   /// Update all phi nodes in this basic block's successors to refer to basic
0684   /// block \p New instead of to it.
0685   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
0686 
0687   /// Return true if this basic block is an exception handling block.
0688   bool isEHPad() const { return getFirstNonPHIIt()->isEHPad(); }
0689 
0690   /// Return true if this basic block is a landing pad.
0691   ///
0692   /// Being a ``landing pad'' means that the basic block is the destination of
0693   /// the 'unwind' edge of an invoke instruction.
0694   bool isLandingPad() const;
0695 
0696   /// Return the landingpad instruction associated with the landing pad.
0697   const LandingPadInst *getLandingPadInst() const;
0698   LandingPadInst *getLandingPadInst() {
0699     return const_cast<LandingPadInst *>(
0700                     static_cast<const BasicBlock *>(this)->getLandingPadInst());
0701   }
0702 
0703   /// Return true if it is legal to hoist instructions into this block.
0704   bool isLegalToHoistInto() const;
0705 
0706   /// Return true if this is the entry block of the containing function.
0707   /// This method can only be used on blocks that have a parent function.
0708   bool isEntryBlock() const;
0709 
0710   std::optional<uint64_t> getIrrLoopHeaderWeight() const;
0711 
0712   /// Returns true if the Order field of child Instructions is valid.
0713   bool isInstrOrderValid() const {
0714     return getBasicBlockBits().InstrOrderValid;
0715   }
0716 
0717   /// Mark instruction ordering invalid. Done on every instruction insert.
0718   void invalidateOrders() {
0719     validateInstrOrdering();
0720     BasicBlockBits Bits = getBasicBlockBits();
0721     Bits.InstrOrderValid = false;
0722     setBasicBlockBits(Bits);
0723   }
0724 
0725   /// Renumber instructions and mark the ordering as valid.
0726   void renumberInstructions();
0727 
0728   /// Asserts that instruction order numbers are marked invalid, or that they
0729   /// are in ascending order. This is constant time if the ordering is invalid,
0730   /// and linear in the number of instructions if the ordering is valid. Callers
0731   /// should be careful not to call this in ways that make common operations
0732   /// O(n^2). For example, it takes O(n) time to assign order numbers to
0733   /// instructions, so the order should be validated no more than once after
0734   /// each ordering to ensure that transforms have the same algorithmic
0735   /// complexity when asserts are enabled as when they are disabled.
0736   void validateInstrOrdering() const;
0737 
0738 private:
0739 #if defined(_AIX) && (!defined(__GNUC__) || defined(__clang__))
0740 // Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
0741 // and give the `pack` pragma push semantics.
0742 #define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")
0743 #define END_TWO_BYTE_PACK() _Pragma("pack(pop)")
0744 #else
0745 #define BEGIN_TWO_BYTE_PACK()
0746 #define END_TWO_BYTE_PACK()
0747 #endif
0748 
0749   BEGIN_TWO_BYTE_PACK()
0750   /// Bitfield to help interpret the bits in Value::SubclassData.
0751   struct BasicBlockBits {
0752     unsigned short BlockAddressRefCount : 15;
0753     unsigned short InstrOrderValid : 1;
0754   };
0755   END_TWO_BYTE_PACK()
0756 
0757 #undef BEGIN_TWO_BYTE_PACK
0758 #undef END_TWO_BYTE_PACK
0759 
0760   /// Safely reinterpret the subclass data bits to a more useful form.
0761   BasicBlockBits getBasicBlockBits() const {
0762     static_assert(sizeof(BasicBlockBits) == sizeof(unsigned short),
0763                   "too many bits for Value::SubclassData");
0764     unsigned short ValueData = getSubclassDataFromValue();
0765     BasicBlockBits AsBits;
0766     memcpy(&AsBits, &ValueData, sizeof(AsBits));
0767     return AsBits;
0768   }
0769 
0770   /// Reinterpret our subclass bits and store them back into Value.
0771   void setBasicBlockBits(BasicBlockBits AsBits) {
0772     unsigned short D;
0773     memcpy(&D, &AsBits, sizeof(D));
0774     Value::setValueSubclassData(D);
0775   }
0776 
0777   /// Increment the internal refcount of the number of BlockAddresses
0778   /// referencing this BasicBlock by \p Amt.
0779   ///
0780   /// This is almost always 0, sometimes one possibly, but almost never 2, and
0781   /// inconceivably 3 or more.
0782   void AdjustBlockAddressRefCount(int Amt) {
0783     BasicBlockBits Bits = getBasicBlockBits();
0784     Bits.BlockAddressRefCount += Amt;
0785     setBasicBlockBits(Bits);
0786     assert(Bits.BlockAddressRefCount < 255 && "Refcount wrap-around");
0787   }
0788 
0789   /// Shadow Value::setValueSubclassData with a private forwarding method so
0790   /// that any future subclasses cannot accidentally use it.
0791   void setValueSubclassData(unsigned short D) {
0792     Value::setValueSubclassData(D);
0793   }
0794 };
0795 
0796 // Create wrappers for C Binding types (see CBindingWrapping.h).
0797 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
0798 
0799 /// Advance \p It while it points to a debug instruction and return the result.
0800 /// This assumes that \p It is not at the end of a block.
0801 BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It);
0802 
0803 #ifdef NDEBUG
0804 /// In release builds, this is a no-op. For !NDEBUG builds, the checks are
0805 /// implemented in the .cpp file to avoid circular header deps.
0806 inline void BasicBlock::validateInstrOrdering() const {}
0807 #endif
0808 
0809 // Specialize DenseMapInfo for iterators, so that ththey can be installed into
0810 // maps and sets. The iterator is made up of its node pointer, and the
0811 // debug-info "head" bit.
0812 template <> struct DenseMapInfo<BasicBlock::iterator> {
0813   static inline BasicBlock::iterator getEmptyKey() {
0814     return BasicBlock::iterator(nullptr);
0815   }
0816 
0817   static inline BasicBlock::iterator getTombstoneKey() {
0818     BasicBlock::iterator It(nullptr);
0819     It.setHeadBit(true);
0820     return It;
0821   }
0822 
0823   static unsigned getHashValue(const BasicBlock::iterator &It) {
0824     return DenseMapInfo<void *>::getHashValue(
0825                reinterpret_cast<void *>(It.getNodePtr())) ^
0826            (unsigned)It.getHeadBit();
0827   }
0828 
0829   static bool isEqual(const BasicBlock::iterator &LHS,
0830                       const BasicBlock::iterator &RHS) {
0831     return LHS == RHS && LHS.getHeadBit() == RHS.getHeadBit();
0832   }
0833 };
0834 
0835 } // end namespace llvm
0836 
0837 #endif // LLVM_IR_BASICBLOCK_H