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