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