1 //===-- llvm/BasicBlock.h - Represent a basic block in the VM ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the declaration of the BasicBlock class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_IR_BASICBLOCK_H
15 #define LLVM_IR_BASICBLOCK_H
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"
31 template<> struct ilist_traits<Instruction>
32 : public SymbolTableListTraits<Instruction, BasicBlock> {
34 /// \brief Return a node that marks the end of a list.
36 /// The sentinel is relative to this instance, so we use a non-static
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);
48 static void destroySentinel(Instruction*) {}
50 Instruction *provideInitialHead() const { return createSentinel(); }
51 Instruction *ensureHead(Instruction*) const { return createSentinel(); }
52 static void noteHead(Instruction*, Instruction*) {}
54 mutable ilist_half_node<Instruction> Sentinel;
57 /// \brief LLVM Basic Block Representation
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.
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;
76 typedef iplist<Instruction> InstListType;
78 InstListType InstList;
81 void setParent(Function *parent);
82 friend class SymbolTableListTraits<BasicBlock, Function>;
84 BasicBlock(const BasicBlock &) LLVM_DELETED_FUNCTION;
85 void operator=(const BasicBlock &) LLVM_DELETED_FUNCTION;
87 /// \brief Constructor.
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 = nullptr,
94 BasicBlock *InsertBefore = nullptr);
96 /// \brief Get the context in which this basic block lives.
97 LLVMContext &getContext() const;
99 /// Instruction iterators...
100 typedef InstListType::iterator iterator;
101 typedef InstListType::const_iterator const_iterator;
102 typedef InstListType::reverse_iterator reverse_iterator;
103 typedef InstListType::const_reverse_iterator const_reverse_iterator;
105 /// \brief Creates a new BasicBlock.
107 /// If the Parent parameter is specified, the basic block is automatically
108 /// inserted at either the end of the function (if InsertBefore is 0), or
109 /// before the specified basic block.
110 static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
111 Function *Parent = nullptr,
112 BasicBlock *InsertBefore = nullptr) {
113 return new BasicBlock(Context, Name, Parent, InsertBefore);
117 /// \brief Return the enclosing method, or null if none.
118 const Function *getParent() const { return Parent; }
119 Function *getParent() { return Parent; }
121 const DataLayout *getDataLayout() const;
123 /// \brief Returns the terminator instruction if the block is well formed or
124 /// null if the block is not well formed.
125 TerminatorInst *getTerminator();
126 const TerminatorInst *getTerminator() const;
128 /// \brief Returns a pointer to the first instruction in this block that is
129 /// not a PHINode instruction.
131 /// When adding instructions to the beginning of the basic block, they should
132 /// be added before the returned value, not before the first instruction,
133 /// which might be PHI. Returns 0 is there's no non-PHI instruction.
134 Instruction* getFirstNonPHI();
135 const Instruction* getFirstNonPHI() const {
136 return const_cast<BasicBlock*>(this)->getFirstNonPHI();
139 /// \brief Returns a pointer to the first instruction in this block that is not
140 /// a PHINode or a debug intrinsic.
141 Instruction* getFirstNonPHIOrDbg();
142 const Instruction* getFirstNonPHIOrDbg() const {
143 return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbg();
146 /// \brief Returns a pointer to the first instruction in this block that is not
147 /// a PHINode, a debug intrinsic, or a lifetime intrinsic.
148 Instruction* getFirstNonPHIOrDbgOrLifetime();
149 const Instruction* getFirstNonPHIOrDbgOrLifetime() const {
150 return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbgOrLifetime();
153 /// \brief Returns an iterator to the first instruction in this block that is
154 /// suitable for inserting a non-PHI instruction.
156 /// In particular, it skips all PHIs and LandingPad instructions.
157 iterator getFirstInsertionPt();
158 const_iterator getFirstInsertionPt() const {
159 return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
162 /// \brief Unlink 'this' from the containing function, but do not delete it.
163 void removeFromParent();
165 /// \brief Unlink 'this' from the containing function and delete it.
166 void eraseFromParent();
168 /// \brief Unlink this basic block from its current function and insert it
169 /// into the function that \p MovePos lives in, right before \p MovePos.
170 void moveBefore(BasicBlock *MovePos);
172 /// \brief Unlink this basic block from its current function and insert it
173 /// right after \p MovePos in the function \p MovePos lives in.
174 void moveAfter(BasicBlock *MovePos);
176 /// \brief Insert unlinked basic block into a function.
178 /// Inserts an unlinked basic block into \c Parent. If \c InsertBefore is
179 /// provided, inserts before that basic block, otherwise inserts at the end.
181 /// \pre \a getParent() is \c nullptr.
182 void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
184 /// \brief Return the predecessor of this block if it has a single predecessor
185 /// block. Otherwise return a null pointer.
186 BasicBlock *getSinglePredecessor();
187 const BasicBlock *getSinglePredecessor() const {
188 return const_cast<BasicBlock*>(this)->getSinglePredecessor();
191 /// \brief Return the predecessor of this block if it has a unique predecessor
192 /// block. Otherwise return a null pointer.
194 /// Note that unique predecessor doesn't mean single edge, there can be
195 /// multiple edges from the unique predecessor to this block (for example a
196 /// switch statement with multiple cases having the same destination).
197 BasicBlock *getUniquePredecessor();
198 const BasicBlock *getUniquePredecessor() const {
199 return const_cast<BasicBlock*>(this)->getUniquePredecessor();
202 //===--------------------------------------------------------------------===//
203 /// Instruction iterator methods
205 inline iterator begin() { return InstList.begin(); }
206 inline const_iterator begin() const { return InstList.begin(); }
207 inline iterator end () { return InstList.end(); }
208 inline const_iterator end () const { return InstList.end(); }
210 inline reverse_iterator rbegin() { return InstList.rbegin(); }
211 inline const_reverse_iterator rbegin() const { return InstList.rbegin(); }
212 inline reverse_iterator rend () { return InstList.rend(); }
213 inline const_reverse_iterator rend () const { return InstList.rend(); }
215 inline size_t size() const { return InstList.size(); }
216 inline bool empty() const { return InstList.empty(); }
217 inline const Instruction &front() const { return InstList.front(); }
218 inline Instruction &front() { return InstList.front(); }
219 inline const Instruction &back() const { return InstList.back(); }
220 inline Instruction &back() { return InstList.back(); }
222 /// \brief Return the underlying instruction list container.
224 /// Currently you need to access the underlying instruction list container
225 /// directly if you want to modify it.
226 const InstListType &getInstList() const { return InstList; }
227 InstListType &getInstList() { return InstList; }
229 /// \brief Returns a pointer to a member of the instruction list.
230 static iplist<Instruction> BasicBlock::*getSublistAccess(Instruction*) {
231 return &BasicBlock::InstList;
234 /// \brief Returns a pointer to the symbol table if one exists.
235 ValueSymbolTable *getValueSymbolTable();
237 /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
238 static inline bool classof(const Value *V) {
239 return V->getValueID() == Value::BasicBlockVal;
242 /// \brief Cause all subinstructions to "let go" of all the references that
243 /// said subinstructions are maintaining.
245 /// This allows one to 'delete' a whole class at a time, even though there may
246 /// be circular references... first all references are dropped, and all use
247 /// counts go to zero. Then everything is delete'd for real. Note that no
248 /// operations are valid on an object that has "dropped all references",
249 /// except operator delete.
250 void dropAllReferences();
252 /// \brief Notify the BasicBlock that the predecessor \p Pred is no longer
253 /// able to reach it.
255 /// This is actually not used to update the Predecessor list, but is actually
256 /// used to update the PHI nodes that reside in the block. Note that this
257 /// should be called while the predecessor still refers to this block.
258 void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
260 /// \brief Split the basic block into two basic blocks at the specified
263 /// Note that all instructions BEFORE the specified iterator stay as part of
264 /// the original basic block, an unconditional branch is added to the original
265 /// BB, and the rest of the instructions in the BB are moved to the new BB,
266 /// including the old terminator. The newly formed BasicBlock is returned.
267 /// This function invalidates the specified iterator.
269 /// Note that this only works on well formed basic blocks (must have a
270 /// terminator), and 'I' must not be the end of instruction list (which would
271 /// cause a degenerate basic block to be formed, having a terminator inside of
272 /// the basic block).
274 /// Also note that this doesn't preserve any passes. To split blocks while
275 /// keeping loop information consistent, use the SplitBlock utility function.
276 BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
278 /// \brief Returns true if there are any uses of this basic block other than
279 /// direct branches, switches, etc. to it.
280 bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
282 /// \brief Update all phi nodes in this basic block's successors to refer to
283 /// basic block \p New instead of to it.
284 void replaceSuccessorsPhiUsesWith(BasicBlock *New);
286 /// \brief Return true if this basic block is a landing pad.
288 /// Being a ``landing pad'' means that the basic block is the destination of
289 /// the 'unwind' edge of an invoke instruction.
290 bool isLandingPad() const;
292 /// \brief Return the landingpad instruction associated with the landing pad.
293 LandingPadInst *getLandingPadInst();
294 const LandingPadInst *getLandingPadInst() const;
297 /// \brief Increment the internal refcount of the number of BlockAddresses
298 /// referencing this BasicBlock by \p Amt.
300 /// This is almost always 0, sometimes one possibly, but almost never 2, and
301 /// inconceivably 3 or more.
302 void AdjustBlockAddressRefCount(int Amt) {
303 setValueSubclassData(getSubclassDataFromValue()+Amt);
304 assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
305 "Refcount wrap-around");
307 /// \brief Shadow Value::setValueSubclassData with a private forwarding method
308 /// so that any future subclasses cannot accidentally use it.
309 void setValueSubclassData(unsigned short D) {
310 Value::setValueSubclassData(D);
314 // Create wrappers for C Binding types (see CBindingWrapping.h).
315 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
317 } // End llvm namespace