LLVM API Documentation

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