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