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