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