LLVM  mainline
BasicBlock.h
Go to the documentation of this file.
00001 //===-- llvm/BasicBlock.h - Represent a basic block in the VM ---*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the declaration of the BasicBlock class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_IR_BASICBLOCK_H
00015 #define LLVM_IR_BASICBLOCK_H
00016 
00017 #include "llvm/ADT/Twine.h"
00018 #include "llvm/ADT/ilist.h"
00019 #include "llvm/IR/Instruction.h"
00020 #include "llvm/IR/SymbolTableListTraits.h"
00021 #include "llvm/Support/CBindingWrapping.h"
00022 #include "llvm/Support/DataTypes.h"
00023 
00024 namespace llvm {
00025 
00026 class CallInst;
00027 class LandingPadInst;
00028 class TerminatorInst;
00029 class LLVMContext;
00030 class BlockAddress;
00031 class Function;
00032 
00033 template <>
00034 struct SymbolTableListSentinelTraits<BasicBlock>
00035     : public ilist_half_embedded_sentinel_traits<BasicBlock> {};
00036 
00037 /// \brief LLVM Basic Block Representation
00038 ///
00039 /// This represents a single basic block in LLVM. A basic block is simply a
00040 /// container of instructions that execute sequentially. Basic blocks are Values
00041 /// because they are referenced by instructions such as branches and switch
00042 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
00043 /// represents a label to which a branch can jump.
00044 ///
00045 /// A well formed basic block is formed of a list of non-terminating
00046 /// instructions followed by a single TerminatorInst instruction.
00047 /// TerminatorInst's may not occur in the middle of basic blocks, and must
00048 /// terminate the blocks. The BasicBlock class allows malformed basic blocks to
00049 /// occur because it may be useful in the intermediate stage of constructing or
00050 /// modifying a program. However, the verifier will ensure that basic blocks
00051 /// are "well formed".
00052 class BasicBlock : public Value, // Basic blocks are data objects also
00053                    public ilist_node_with_parent<BasicBlock, Function> {
00054   friend class BlockAddress;
00055 public:
00056   typedef SymbolTableList<Instruction> InstListType;
00057 
00058 private:
00059   InstListType InstList;
00060   Function *Parent;
00061 
00062   void setParent(Function *parent);
00063   friend class SymbolTableListTraits<BasicBlock>;
00064 
00065   BasicBlock(const BasicBlock &) = delete;
00066   void operator=(const BasicBlock &) = delete;
00067 
00068   /// \brief Constructor.
00069   ///
00070   /// If the function parameter is specified, the basic block is automatically
00071   /// inserted at either the end of the function (if InsertBefore is null), or
00072   /// before the specified basic block.
00073   explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
00074                       Function *Parent = nullptr,
00075                       BasicBlock *InsertBefore = nullptr);
00076 public:
00077   /// \brief Get the context in which this basic block lives.
00078   LLVMContext &getContext() const;
00079 
00080   /// Instruction iterators...
00081   typedef InstListType::iterator iterator;
00082   typedef InstListType::const_iterator const_iterator;
00083   typedef InstListType::reverse_iterator reverse_iterator;
00084   typedef InstListType::const_reverse_iterator const_reverse_iterator;
00085 
00086   /// \brief Creates a new BasicBlock.
00087   ///
00088   /// If the Parent parameter is specified, the basic block is automatically
00089   /// inserted at either the end of the function (if InsertBefore is 0), or
00090   /// before the specified basic block.
00091   static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
00092                             Function *Parent = nullptr,
00093                             BasicBlock *InsertBefore = nullptr) {
00094     return new BasicBlock(Context, Name, Parent, InsertBefore);
00095   }
00096   ~BasicBlock() override;
00097 
00098   /// \brief Return the enclosing method, or null if none.
00099   const Function *getParent() const { return Parent; }
00100         Function *getParent()       { return Parent; }
00101 
00102   /// \brief Return the module owning the function this basic block belongs to,
00103   /// or nullptr it the function does not have a module.
00104   ///
00105   /// Note: this is undefined behavior if the block does not have a parent.
00106   const Module *getModule() const;
00107   Module *getModule();
00108 
00109   /// \brief Returns the terminator instruction if the block is well formed or
00110   /// null if the block is not well formed.
00111   TerminatorInst *getTerminator();
00112   const TerminatorInst *getTerminator() const;
00113 
00114   /// \brief Returns the call instruction marked 'musttail' prior to the
00115   /// terminating return instruction of this basic block, if such a call is
00116   /// present.  Otherwise, returns null.
00117   CallInst *getTerminatingMustTailCall();
00118   const CallInst *getTerminatingMustTailCall() const {
00119     return const_cast<BasicBlock *>(this)->getTerminatingMustTailCall();
00120   }
00121 
00122   /// \brief Returns a pointer to the first instruction in this block that is
00123   /// not a PHINode instruction.
00124   ///
00125   /// When adding instructions to the beginning of the basic block, they should
00126   /// be added before the returned value, not before the first instruction,
00127   /// which might be PHI. Returns 0 is there's no non-PHI instruction.
00128   Instruction* getFirstNonPHI();
00129   const Instruction* getFirstNonPHI() const {
00130     return const_cast<BasicBlock*>(this)->getFirstNonPHI();
00131   }
00132 
00133   /// \brief Returns a pointer to the first instruction in this block that is not
00134   /// a PHINode or a debug intrinsic.
00135   Instruction* getFirstNonPHIOrDbg();
00136   const Instruction* getFirstNonPHIOrDbg() const {
00137     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbg();
00138   }
00139 
00140   /// \brief Returns a pointer to the first instruction in this block that is not
00141   /// a PHINode, a debug intrinsic, or a lifetime intrinsic.
00142   Instruction* getFirstNonPHIOrDbgOrLifetime();
00143   const Instruction* getFirstNonPHIOrDbgOrLifetime() const {
00144     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbgOrLifetime();
00145   }
00146 
00147   /// \brief Returns an iterator to the first instruction in this block that is
00148   /// suitable for inserting a non-PHI instruction.
00149   ///
00150   /// In particular, it skips all PHIs and LandingPad instructions.
00151   iterator getFirstInsertionPt();
00152   const_iterator getFirstInsertionPt() const {
00153     return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
00154   }
00155 
00156   /// \brief Unlink 'this' from the containing function, but do not delete it.
00157   void removeFromParent();
00158 
00159   /// \brief Unlink 'this' from the containing function and delete it.
00160   ///
00161   // \returns an iterator pointing to the element after the erased one.
00162   SymbolTableList<BasicBlock>::iterator eraseFromParent();
00163 
00164   /// \brief Unlink this basic block from its current function and insert it
00165   /// into the function that \p MovePos lives in, right before \p MovePos.
00166   void moveBefore(BasicBlock *MovePos);
00167 
00168   /// \brief Unlink this basic block from its current function and insert it
00169   /// right after \p MovePos in the function \p MovePos lives in.
00170   void moveAfter(BasicBlock *MovePos);
00171 
00172   /// \brief Insert unlinked basic block into a function.
00173   ///
00174   /// Inserts an unlinked basic block into \c Parent.  If \c InsertBefore is
00175   /// provided, inserts before that basic block, otherwise inserts at the end.
00176   ///
00177   /// \pre \a getParent() is \c nullptr.
00178   void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
00179 
00180   /// \brief Return the predecessor of this block if it has a single predecessor
00181   /// block. Otherwise return a null pointer.
00182   BasicBlock *getSinglePredecessor();
00183   const BasicBlock *getSinglePredecessor() const {
00184     return const_cast<BasicBlock*>(this)->getSinglePredecessor();
00185   }
00186 
00187   /// \brief Return the predecessor of this block if it has a unique predecessor
00188   /// block. Otherwise return a null pointer.
00189   ///
00190   /// Note that unique predecessor doesn't mean single edge, there can be
00191   /// multiple edges from the unique predecessor to this block (for example a
00192   /// switch statement with multiple cases having the same destination).
00193   BasicBlock *getUniquePredecessor();
00194   const BasicBlock *getUniquePredecessor() const {
00195     return const_cast<BasicBlock*>(this)->getUniquePredecessor();
00196   }
00197 
00198   /// \brief Return the successor of this block if it has a single successor.
00199   /// Otherwise return a null pointer.
00200   ///
00201   /// This method is analogous to getSinglePredecessor above.
00202   BasicBlock *getSingleSuccessor();
00203   const BasicBlock *getSingleSuccessor() const {
00204     return const_cast<BasicBlock*>(this)->getSingleSuccessor();
00205   }
00206 
00207   /// \brief Return the successor of this block if it has a unique successor.
00208   /// Otherwise return a null pointer.
00209   ///
00210   /// This method is analogous to getUniquePredecessor above.
00211   BasicBlock *getUniqueSuccessor();
00212   const BasicBlock *getUniqueSuccessor() const {
00213     return const_cast<BasicBlock*>(this)->getUniqueSuccessor();
00214   }
00215 
00216   //===--------------------------------------------------------------------===//
00217   /// Instruction iterator methods
00218   ///
00219   inline iterator                begin()       { return InstList.begin(); }
00220   inline const_iterator          begin() const { return InstList.begin(); }
00221   inline iterator                end  ()       { return InstList.end();   }
00222   inline const_iterator          end  () const { return InstList.end();   }
00223 
00224   inline reverse_iterator        rbegin()       { return InstList.rbegin(); }
00225   inline const_reverse_iterator  rbegin() const { return InstList.rbegin(); }
00226   inline reverse_iterator        rend  ()       { return InstList.rend();   }
00227   inline const_reverse_iterator  rend  () const { return InstList.rend();   }
00228 
00229   inline size_t                   size() const { return InstList.size();  }
00230   inline bool                    empty() const { return InstList.empty(); }
00231   inline const Instruction      &front() const { return InstList.front(); }
00232   inline       Instruction      &front()       { return InstList.front(); }
00233   inline const Instruction       &back() const { return InstList.back();  }
00234   inline       Instruction       &back()       { return InstList.back();  }
00235 
00236   /// \brief Return the underlying instruction list container.
00237   ///
00238   /// Currently you need to access the underlying instruction list container
00239   /// directly if you want to modify it.
00240   const InstListType &getInstList() const { return InstList; }
00241         InstListType &getInstList()       { return InstList; }
00242 
00243   /// \brief Returns a pointer to a member of the instruction list.
00244   static InstListType BasicBlock::*getSublistAccess(Instruction*) {
00245     return &BasicBlock::InstList;
00246   }
00247 
00248   /// \brief Returns a pointer to the symbol table if one exists.
00249   ValueSymbolTable *getValueSymbolTable();
00250 
00251   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
00252   static inline bool classof(const Value *V) {
00253     return V->getValueID() == Value::BasicBlockVal;
00254   }
00255 
00256   /// \brief Cause all subinstructions to "let go" of all the references that
00257   /// said subinstructions are maintaining.
00258   ///
00259   /// This allows one to 'delete' a whole class at a time, even though there may
00260   /// be circular references... first all references are dropped, and all use
00261   /// counts go to zero.  Then everything is delete'd for real.  Note that no
00262   /// operations are valid on an object that has "dropped all references",
00263   /// except operator delete.
00264   void dropAllReferences();
00265 
00266   /// \brief Notify the BasicBlock that the predecessor \p Pred is no longer
00267   /// able to reach it.
00268   ///
00269   /// This is actually not used to update the Predecessor list, but is actually
00270   /// used to update the PHI nodes that reside in the block.  Note that this
00271   /// should be called while the predecessor still refers to this block.
00272   void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
00273 
00274   bool canSplitPredecessors() const;
00275 
00276   /// \brief Split the basic block into two basic blocks at the specified
00277   /// instruction.
00278   ///
00279   /// Note that all instructions BEFORE the specified iterator stay as part of
00280   /// the original basic block, an unconditional branch is added to the original
00281   /// BB, and the rest of the instructions in the BB are moved to the new BB,
00282   /// including the old terminator.  The newly formed BasicBlock is returned.
00283   /// This function invalidates the specified iterator.
00284   ///
00285   /// Note that this only works on well formed basic blocks (must have a
00286   /// terminator), and 'I' must not be the end of instruction list (which would
00287   /// cause a degenerate basic block to be formed, having a terminator inside of
00288   /// the basic block).
00289   ///
00290   /// Also note that this doesn't preserve any passes. To split blocks while
00291   /// keeping loop information consistent, use the SplitBlock utility function.
00292   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
00293   BasicBlock *splitBasicBlock(Instruction *I, const Twine &BBName = "") {
00294     return splitBasicBlock(I->getIterator(), BBName);
00295   }
00296 
00297   /// \brief Returns true if there are any uses of this basic block other than
00298   /// direct branches, switches, etc. to it.
00299   bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
00300 
00301   /// \brief Update all phi nodes in this basic block's successors to refer to
00302   /// basic block \p New instead of to it.
00303   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
00304 
00305   /// \brief Return true if this basic block is an exception handling block.
00306   bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
00307 
00308   /// \brief Return true if this basic block is a landing pad.
00309   ///
00310   /// Being a ``landing pad'' means that the basic block is the destination of
00311   /// the 'unwind' edge of an invoke instruction.
00312   bool isLandingPad() const;
00313 
00314   /// \brief Return the landingpad instruction associated with the landing pad.
00315   LandingPadInst *getLandingPadInst();
00316   const LandingPadInst *getLandingPadInst() const;
00317 
00318 private:
00319   /// \brief Increment the internal refcount of the number of BlockAddresses
00320   /// referencing this BasicBlock by \p Amt.
00321   ///
00322   /// This is almost always 0, sometimes one possibly, but almost never 2, and
00323   /// inconceivably 3 or more.
00324   void AdjustBlockAddressRefCount(int Amt) {
00325     setValueSubclassData(getSubclassDataFromValue()+Amt);
00326     assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
00327            "Refcount wrap-around");
00328   }
00329   /// \brief Shadow Value::setValueSubclassData with a private forwarding method
00330   /// so that any future subclasses cannot accidentally use it.
00331   void setValueSubclassData(unsigned short D) {
00332     Value::setValueSubclassData(D);
00333   }
00334 };
00335 
00336 // Create wrappers for C Binding types (see CBindingWrapping.h).
00337 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
00338 
00339 } // End llvm namespace
00340 
00341 #endif