This patch breaks up Wrap.h so that it does not have to include all of
[oota-llvm.git] / include / llvm / IR / BasicBlock.h
1 //===-- llvm/BasicBlock.h - Represent a basic block in the VM ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the declaration of the BasicBlock class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_IR_BASICBLOCK_H
15 #define LLVM_IR_BASICBLOCK_H
16
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/IR/Instruction.h"
20 #include "llvm/IR/SymbolTableListTraits.h"
21 #include "llvm/Support/CBindingWrapping.h"
22 #include "llvm/Support/DataTypes.h"
23
24 namespace llvm {
25
26 class LandingPadInst;
27 class TerminatorInst;
28 class LLVMContext;
29 class BlockAddress;
30
31 template<> struct ilist_traits<Instruction>
32   : public SymbolTableListTraits<Instruction, BasicBlock> {
33
34   /// \brief Return a node that marks the end of a list.
35   ///
36   /// The sentinel is relative to this instance, so we use a non-static
37   /// method.
38   Instruction *createSentinel() const {
39     // Since i(p)lists always publicly derive from their corresponding traits,
40     // placing a data member in this class will augment the i(p)list.  But since
41     // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
42     // there is a legal viable downcast from it to NodeTy. We use this trick to
43     // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
44     // sentinel. Dereferencing the sentinel is forbidden (save the
45     // ilist_node<NodeTy>), so no one will ever notice the superposition.
46     return static_cast<Instruction*>(&Sentinel);
47   }
48   static void destroySentinel(Instruction*) {}
49
50   Instruction *provideInitialHead() const { return createSentinel(); }
51   Instruction *ensureHead(Instruction*) const { return createSentinel(); }
52   static void noteHead(Instruction*, Instruction*) {}
53 private:
54   mutable ilist_half_node<Instruction> Sentinel;
55 };
56
57 /// \brief LLVM Basic Block Representation
58 ///
59 /// This represents a single basic block in LLVM. A basic block is simply a
60 /// container of instructions that execute sequentially. Basic blocks are Values
61 /// because they are referenced by instructions such as branches and switch
62 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
63 /// represents a label to which a branch can jump.
64 ///
65 /// A well formed basic block is formed of a list of non-terminating
66 /// instructions followed by a single TerminatorInst instruction.
67 /// TerminatorInst's may not occur in the middle of basic blocks, and must
68 /// terminate the blocks. The BasicBlock class allows malformed basic blocks to
69 /// occur because it may be useful in the intermediate stage of constructing or
70 /// modifying a program. However, the verifier will ensure that basic blocks
71 /// are "well formed".
72 class BasicBlock : public Value, // Basic blocks are data objects also
73                    public ilist_node<BasicBlock> {
74   friend class BlockAddress;
75 public:
76   typedef iplist<Instruction> InstListType;
77 private:
78   InstListType InstList;
79   Function *Parent;
80
81   void setParent(Function *parent);
82   friend class SymbolTableListTraits<BasicBlock, Function>;
83
84   BasicBlock(const BasicBlock &) LLVM_DELETED_FUNCTION;
85   void operator=(const BasicBlock &) LLVM_DELETED_FUNCTION;
86
87   /// \brief Constructor.
88   ///
89   /// If the function parameter is specified, the basic block is automatically
90   /// inserted at either the end of the function (if InsertBefore is null), or
91   /// before the specified basic block.
92   explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
93                       Function *Parent = 0, BasicBlock *InsertBefore = 0);
94 public:
95   /// \brief Get the context in which this basic block lives.
96   LLVMContext &getContext() const;
97
98   /// Instruction iterators...
99   typedef InstListType::iterator iterator;
100   typedef InstListType::const_iterator const_iterator;
101   typedef InstListType::reverse_iterator reverse_iterator;
102   typedef InstListType::const_reverse_iterator const_reverse_iterator;
103
104   /// \brief Creates a new BasicBlock.
105   ///
106   /// If the Parent parameter is specified, the basic block is automatically
107   /// inserted at either the end of the function (if InsertBefore is 0), or
108   /// before the specified basic block.
109   static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
110                             Function *Parent = 0,BasicBlock *InsertBefore = 0) {
111     return new BasicBlock(Context, Name, Parent, InsertBefore);
112   }
113   ~BasicBlock();
114
115   /// \brief Return the enclosing method, or null if none.
116   const Function *getParent() const { return Parent; }
117         Function *getParent()       { return Parent; }
118
119   /// \brief Returns the terminator instruction if the block is well formed or
120   /// null if the block is not well formed.
121   TerminatorInst *getTerminator();
122   const TerminatorInst *getTerminator() const;
123
124   /// \brief Returns a pointer to the first instruction in this block that is
125   /// not a PHINode instruction.
126   ///
127   /// When adding instructions to the beginning of the basic block, they should
128   /// be added before the returned value, not before the first instruction,
129   /// which might be PHI. Returns 0 is there's no non-PHI instruction.
130   Instruction* getFirstNonPHI();
131   const Instruction* getFirstNonPHI() const {
132     return const_cast<BasicBlock*>(this)->getFirstNonPHI();
133   }
134
135   /// \brief Returns a pointer to the first instruction in this block that is not
136   /// a PHINode or a debug intrinsic.
137   Instruction* getFirstNonPHIOrDbg();
138   const Instruction* getFirstNonPHIOrDbg() const {
139     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbg();
140   }
141
142   /// \brief Returns a pointer to the first instruction in this block that is not
143   /// a PHINode, a debug intrinsic, or a lifetime intrinsic.
144   Instruction* getFirstNonPHIOrDbgOrLifetime();
145   const Instruction* getFirstNonPHIOrDbgOrLifetime() const {
146     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbgOrLifetime();
147   }
148
149   /// \brief Returns an iterator to the first instruction in this block that is
150   /// suitable for inserting a non-PHI instruction.
151   ///
152   /// In particular, it skips all PHIs and LandingPad instructions.
153   iterator getFirstInsertionPt();
154   const_iterator getFirstInsertionPt() const {
155     return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
156   }
157
158   /// \brief Unlink 'this' from the containing function, but do not delete it.
159   void removeFromParent();
160
161   /// \brief Unlink 'this' from the containing function and delete it.
162   void eraseFromParent();
163
164   /// \brief Unlink this basic block from its current function and insert it
165   /// into the function that \p MovePos lives in, right before \p MovePos.
166   void moveBefore(BasicBlock *MovePos);
167
168   /// \brief Unlink this basic block from its current function and insert it
169   /// right after \p MovePos in the function \p MovePos lives in.
170   void moveAfter(BasicBlock *MovePos);
171
172
173   /// \brief Return this block if it has a single predecessor block. Otherwise
174   /// return a null pointer.
175   BasicBlock *getSinglePredecessor();
176   const BasicBlock *getSinglePredecessor() const {
177     return const_cast<BasicBlock*>(this)->getSinglePredecessor();
178   }
179
180   /// \brief Return this block if it has a unique predecessor block. Otherwise return a null pointer.
181   ///
182   /// Note that unique predecessor doesn't mean single edge, there can be
183   /// multiple edges from the unique predecessor to this block (for example a
184   /// switch statement with multiple cases having the same destination).
185   BasicBlock *getUniquePredecessor();
186   const BasicBlock *getUniquePredecessor() const {
187     return const_cast<BasicBlock*>(this)->getUniquePredecessor();
188   }
189
190   //===--------------------------------------------------------------------===//
191   /// Instruction iterator methods
192   ///
193   inline iterator                begin()       { return InstList.begin(); }
194   inline const_iterator          begin() const { return InstList.begin(); }
195   inline iterator                end  ()       { return InstList.end();   }
196   inline const_iterator          end  () const { return InstList.end();   }
197
198   inline reverse_iterator        rbegin()       { return InstList.rbegin(); }
199   inline const_reverse_iterator  rbegin() const { return InstList.rbegin(); }
200   inline reverse_iterator        rend  ()       { return InstList.rend();   }
201   inline const_reverse_iterator  rend  () const { return InstList.rend();   }
202
203   inline size_t                   size() const { return InstList.size();  }
204   inline bool                    empty() const { return InstList.empty(); }
205   inline const Instruction      &front() const { return InstList.front(); }
206   inline       Instruction      &front()       { return InstList.front(); }
207   inline const Instruction       &back() const { return InstList.back();  }
208   inline       Instruction       &back()       { return InstList.back();  }
209
210   /// \brief Return the underlying instruction list container.
211   ///
212   /// Currently you need to access the underlying instruction list container
213   /// directly if you want to modify it.
214   const InstListType &getInstList() const { return InstList; }
215         InstListType &getInstList()       { return InstList; }
216
217   /// \brief Returns a pointer to a member of the instruction list.
218   static iplist<Instruction> BasicBlock::*getSublistAccess(Instruction*) {
219     return &BasicBlock::InstList;
220   }
221
222   /// \brief Returns a pointer to the symbol table if one exists.
223   ValueSymbolTable *getValueSymbolTable();
224
225   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
226   static inline bool classof(const Value *V) {
227     return V->getValueID() == Value::BasicBlockVal;
228   }
229
230   /// \brief Cause all subinstructions to "let go" of all the references that
231   /// said subinstructions are maintaining.
232   ///
233   /// This allows one to 'delete' a whole class at a time, even though there may
234   /// be circular references... first all references are dropped, and all use
235   /// counts go to zero.  Then everything is delete'd for real.  Note that no
236   /// operations are valid on an object that has "dropped all references",
237   /// except operator delete.
238   void dropAllReferences();
239
240   /// \brief Notify the BasicBlock that the predecessor \p Pred is no longer
241   /// able to reach it.
242   ///
243   /// This is actually not used to update the Predecessor list, but is actually
244   /// used to update the PHI nodes that reside in the block.  Note that this
245   /// should be called while the predecessor still refers to this block.
246   void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
247
248   /// \brief Split the basic block into two basic blocks at the specified
249   /// instruction.
250   ///
251   /// Note that all instructions BEFORE the specified iterator stay as part of
252   /// the original basic block, an unconditional branch is added to the original
253   /// BB, and the rest of the instructions in the BB are moved to the new BB,
254   /// including the old terminator.  The newly formed BasicBlock is returned.
255   /// This function invalidates the specified iterator.
256   ///
257   /// Note that this only works on well formed basic blocks (must have a
258   /// terminator), and 'I' must not be the end of instruction list (which would
259   /// cause a degenerate basic block to be formed, having a terminator inside of
260   /// the basic block).
261   ///
262   /// Also note that this doesn't preserve any passes. To split blocks while
263   /// keeping loop information consistent, use the SplitBlock utility function.
264   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
265
266   /// \brief Returns true if there are any uses of this basic block other than
267   /// direct branches, switches, etc. to it.
268   bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
269
270   /// \brief Update all phi nodes in this basic block's successors to refer to
271   /// basic block \p New instead of to it.
272   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
273
274   /// \brief Return true if this basic block is a landing pad.
275   ///
276   /// Being a ``landing pad'' means that the basic block is the destination of
277   /// the 'unwind' edge of an invoke instruction.
278   bool isLandingPad() const;
279
280   /// \brief Return the landingpad instruction associated with the landing pad.
281   LandingPadInst *getLandingPadInst();
282   const LandingPadInst *getLandingPadInst() const;
283
284 private:
285   /// \brief Increment the internal refcount of the number of BlockAddresses
286   /// referencing this BasicBlock by \p Amt.
287   ///
288   /// This is almost always 0, sometimes one possibly, but almost never 2, and
289   /// inconceivably 3 or more.
290   void AdjustBlockAddressRefCount(int Amt) {
291     setValueSubclassData(getSubclassDataFromValue()+Amt);
292     assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
293            "Refcount wrap-around");
294   }
295   /// \brief Shadow Value::setValueSubclassData with a private forwarding method
296   /// so that any future subclasses cannot accidentally use it.
297   void setValueSubclassData(unsigned short D) {
298     Value::setValueSubclassData(D);
299   }
300 };
301
302 // Create wrappers for C Binding types (see CBindingWrapping.h).
303 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
304
305 } // End llvm namespace
306
307 #endif