Use DataLayout from the module when easily available.
[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   const DataLayout *getDataLayout() const;
120
121   /// \brief Returns the terminator instruction if the block is well formed or
122   /// null if the block is not well formed.
123   TerminatorInst *getTerminator();
124   const TerminatorInst *getTerminator() const;
125
126   /// \brief Returns a pointer to the first instruction in this block that is
127   /// not a PHINode instruction.
128   ///
129   /// When adding instructions to the beginning of the basic block, they should
130   /// be added before the returned value, not before the first instruction,
131   /// which might be PHI. Returns 0 is there's no non-PHI instruction.
132   Instruction* getFirstNonPHI();
133   const Instruction* getFirstNonPHI() const {
134     return const_cast<BasicBlock*>(this)->getFirstNonPHI();
135   }
136
137   /// \brief Returns a pointer to the first instruction in this block that is not
138   /// a PHINode or a debug intrinsic.
139   Instruction* getFirstNonPHIOrDbg();
140   const Instruction* getFirstNonPHIOrDbg() const {
141     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbg();
142   }
143
144   /// \brief Returns a pointer to the first instruction in this block that is not
145   /// a PHINode, a debug intrinsic, or a lifetime intrinsic.
146   Instruction* getFirstNonPHIOrDbgOrLifetime();
147   const Instruction* getFirstNonPHIOrDbgOrLifetime() const {
148     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbgOrLifetime();
149   }
150
151   /// \brief Returns an iterator to the first instruction in this block that is
152   /// suitable for inserting a non-PHI instruction.
153   ///
154   /// In particular, it skips all PHIs and LandingPad instructions.
155   iterator getFirstInsertionPt();
156   const_iterator getFirstInsertionPt() const {
157     return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
158   }
159
160   /// \brief Unlink 'this' from the containing function, but do not delete it.
161   void removeFromParent();
162
163   /// \brief Unlink 'this' from the containing function and delete it.
164   void eraseFromParent();
165
166   /// \brief Unlink this basic block from its current function and insert it
167   /// into the function that \p MovePos lives in, right before \p MovePos.
168   void moveBefore(BasicBlock *MovePos);
169
170   /// \brief Unlink this basic block from its current function and insert it
171   /// right after \p MovePos in the function \p MovePos lives in.
172   void moveAfter(BasicBlock *MovePos);
173
174
175   /// \brief Return this block if it has a single predecessor block. Otherwise
176   /// return a null pointer.
177   BasicBlock *getSinglePredecessor();
178   const BasicBlock *getSinglePredecessor() const {
179     return const_cast<BasicBlock*>(this)->getSinglePredecessor();
180   }
181
182   /// \brief Return this block if it has a unique predecessor block. Otherwise return a null pointer.
183   ///
184   /// Note that unique predecessor doesn't mean single edge, there can be
185   /// multiple edges from the unique predecessor to this block (for example a
186   /// switch statement with multiple cases having the same destination).
187   BasicBlock *getUniquePredecessor();
188   const BasicBlock *getUniquePredecessor() const {
189     return const_cast<BasicBlock*>(this)->getUniquePredecessor();
190   }
191
192   //===--------------------------------------------------------------------===//
193   /// Instruction iterator methods
194   ///
195   inline iterator                begin()       { return InstList.begin(); }
196   inline const_iterator          begin() const { return InstList.begin(); }
197   inline iterator                end  ()       { return InstList.end();   }
198   inline const_iterator          end  () const { return InstList.end();   }
199
200   inline reverse_iterator        rbegin()       { return InstList.rbegin(); }
201   inline const_reverse_iterator  rbegin() const { return InstList.rbegin(); }
202   inline reverse_iterator        rend  ()       { return InstList.rend();   }
203   inline const_reverse_iterator  rend  () const { return InstList.rend();   }
204
205   inline size_t                   size() const { return InstList.size();  }
206   inline bool                    empty() const { return InstList.empty(); }
207   inline const Instruction      &front() const { return InstList.front(); }
208   inline       Instruction      &front()       { return InstList.front(); }
209   inline const Instruction       &back() const { return InstList.back();  }
210   inline       Instruction       &back()       { return InstList.back();  }
211
212   /// \brief Return the underlying instruction list container.
213   ///
214   /// Currently you need to access the underlying instruction list container
215   /// directly if you want to modify it.
216   const InstListType &getInstList() const { return InstList; }
217         InstListType &getInstList()       { return InstList; }
218
219   /// \brief Returns a pointer to a member of the instruction list.
220   static iplist<Instruction> BasicBlock::*getSublistAccess(Instruction*) {
221     return &BasicBlock::InstList;
222   }
223
224   /// \brief Returns a pointer to the symbol table if one exists.
225   ValueSymbolTable *getValueSymbolTable();
226
227   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
228   static inline bool classof(const Value *V) {
229     return V->getValueID() == Value::BasicBlockVal;
230   }
231
232   /// \brief Cause all subinstructions to "let go" of all the references that
233   /// said subinstructions are maintaining.
234   ///
235   /// This allows one to 'delete' a whole class at a time, even though there may
236   /// be circular references... first all references are dropped, and all use
237   /// counts go to zero.  Then everything is delete'd for real.  Note that no
238   /// operations are valid on an object that has "dropped all references",
239   /// except operator delete.
240   void dropAllReferences();
241
242   /// \brief Notify the BasicBlock that the predecessor \p Pred is no longer
243   /// able to reach it.
244   ///
245   /// This is actually not used to update the Predecessor list, but is actually
246   /// used to update the PHI nodes that reside in the block.  Note that this
247   /// should be called while the predecessor still refers to this block.
248   void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
249
250   /// \brief Split the basic block into two basic blocks at the specified
251   /// instruction.
252   ///
253   /// Note that all instructions BEFORE the specified iterator stay as part of
254   /// the original basic block, an unconditional branch is added to the original
255   /// BB, and the rest of the instructions in the BB are moved to the new BB,
256   /// including the old terminator.  The newly formed BasicBlock is returned.
257   /// This function invalidates the specified iterator.
258   ///
259   /// Note that this only works on well formed basic blocks (must have a
260   /// terminator), and 'I' must not be the end of instruction list (which would
261   /// cause a degenerate basic block to be formed, having a terminator inside of
262   /// the basic block).
263   ///
264   /// Also note that this doesn't preserve any passes. To split blocks while
265   /// keeping loop information consistent, use the SplitBlock utility function.
266   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
267
268   /// \brief Returns true if there are any uses of this basic block other than
269   /// direct branches, switches, etc. to it.
270   bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
271
272   /// \brief Update all phi nodes in this basic block's successors to refer to
273   /// basic block \p New instead of to it.
274   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
275
276   /// \brief Return true if this basic block is a landing pad.
277   ///
278   /// Being a ``landing pad'' means that the basic block is the destination of
279   /// the 'unwind' edge of an invoke instruction.
280   bool isLandingPad() const;
281
282   /// \brief Return the landingpad instruction associated with the landing pad.
283   LandingPadInst *getLandingPadInst();
284   const LandingPadInst *getLandingPadInst() const;
285
286 private:
287   /// \brief Increment the internal refcount of the number of BlockAddresses
288   /// referencing this BasicBlock by \p Amt.
289   ///
290   /// This is almost always 0, sometimes one possibly, but almost never 2, and
291   /// inconceivably 3 or more.
292   void AdjustBlockAddressRefCount(int Amt) {
293     setValueSubclassData(getSubclassDataFromValue()+Amt);
294     assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
295            "Refcount wrap-around");
296   }
297   /// \brief Shadow Value::setValueSubclassData with a private forwarding method
298   /// so that any future subclasses cannot accidentally use it.
299   void setValueSubclassData(unsigned short D) {
300     Value::setValueSubclassData(D);
301   }
302 };
303
304 // Create wrappers for C Binding types (see CBindingWrapping.h).
305 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
306
307 } // End llvm namespace
308
309 #endif