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-c/Types.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/ADT/ilist.h"
20 #include "llvm/ADT/ilist_node.h"
21 #include "llvm/ADT/iterator.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/SymbolTableListTraits.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/CBindingWrapping.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Compiler.h"
42 class ValueSymbolTable;
44 /// LLVM Basic Block Representation
46 /// This represents a single basic block in LLVM. A basic block is simply a
47 /// container of instructions that execute sequentially. Basic blocks are Values
48 /// because they are referenced by instructions such as branches and switch
49 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
50 /// represents a label to which a branch can jump.
52 /// A well formed basic block is formed of a list of non-terminating
53 /// instructions followed by a single TerminatorInst instruction.
54 /// TerminatorInst's may not occur in the middle of basic blocks, and must
55 /// terminate the blocks. The BasicBlock class allows malformed basic blocks to
56 /// occur because it may be useful in the intermediate stage of constructing or
57 /// modifying a program. However, the verifier will ensure that basic blocks
58 /// are "well formed".
59 class BasicBlock final : public Value, // Basic blocks are data objects also
60 public ilist_node_with_parent<BasicBlock, Function> {
62 using InstListType = SymbolTableList<Instruction>;
65 friend class BlockAddress;
66 friend class SymbolTableListTraits<BasicBlock>;
68 InstListType InstList;
71 void setParent(Function *parent);
75 /// If the function parameter is specified, the basic block is automatically
76 /// inserted at either the end of the function (if InsertBefore is null), or
77 /// before the specified basic block.
78 explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
79 Function *Parent = nullptr,
80 BasicBlock *InsertBefore = nullptr);
83 BasicBlock(const BasicBlock &) = delete;
84 BasicBlock &operator=(const BasicBlock &) = delete;
87 /// Get the context in which this basic block lives.
88 LLVMContext &getContext() const;
90 /// Instruction iterators...
91 using iterator = InstListType::iterator;
92 using const_iterator = InstListType::const_iterator;
93 using reverse_iterator = InstListType::reverse_iterator;
94 using const_reverse_iterator = InstListType::const_reverse_iterator;
96 /// Creates a new BasicBlock.
98 /// If the Parent parameter is specified, the basic block is automatically
99 /// inserted at either the end of the function (if InsertBefore is 0), or
100 /// before the specified basic block.
101 static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
102 Function *Parent = nullptr,
103 BasicBlock *InsertBefore = nullptr) {
104 return new BasicBlock(Context, Name, Parent, InsertBefore);
107 /// Return the enclosing method, or null if none.
108 const Function *getParent() const { return Parent; }
109 Function *getParent() { return Parent; }
111 /// Return the module owning the function this basic block belongs to, or
112 /// nullptr if the function does not have a module.
114 /// Note: this is undefined behavior if the block does not have a parent.
115 const Module *getModule() const;
116 Module *getModule() {
117 return const_cast<Module *>(
118 static_cast<const BasicBlock *>(this)->getModule());
121 /// Returns the terminator instruction if the block is well formed or null
122 /// if the block is not well formed.
123 const TerminatorInst *getTerminator() const LLVM_READONLY;
124 TerminatorInst *getTerminator() {
125 return const_cast<TerminatorInst *>(
126 static_cast<const BasicBlock *>(this)->getTerminator());
129 /// Returns the call instruction calling \@llvm.experimental.deoptimize
130 /// prior to the terminating return instruction of this basic block, if such
131 /// a call is present. Otherwise, returns null.
132 const CallInst *getTerminatingDeoptimizeCall() const;
133 CallInst *getTerminatingDeoptimizeCall() {
134 return const_cast<CallInst *>(
135 static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
138 /// Returns the call instruction marked 'musttail' prior to the terminating
139 /// return instruction of this basic block, if such a call is present.
140 /// Otherwise, returns null.
141 const CallInst *getTerminatingMustTailCall() const;
142 CallInst *getTerminatingMustTailCall() {
143 return const_cast<CallInst *>(
144 static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
147 /// Returns a pointer to the first instruction in this block that is not a
148 /// PHINode instruction.
150 /// When adding instructions to the beginning of the basic block, they should
151 /// be added before the returned value, not before the first instruction,
152 /// which might be PHI. Returns 0 is there's no non-PHI instruction.
153 const Instruction* getFirstNonPHI() const;
154 Instruction* getFirstNonPHI() {
155 return const_cast<Instruction *>(
156 static_cast<const BasicBlock *>(this)->getFirstNonPHI());
159 /// Returns a pointer to the first instruction in this block that is not a
160 /// PHINode or a debug intrinsic.
161 const Instruction* getFirstNonPHIOrDbg() const;
162 Instruction* getFirstNonPHIOrDbg() {
163 return const_cast<Instruction *>(
164 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbg());
167 /// Returns a pointer to the first instruction in this block that is not a
168 /// PHINode, a debug intrinsic, or a lifetime intrinsic.
169 const Instruction* getFirstNonPHIOrDbgOrLifetime() const;
170 Instruction* getFirstNonPHIOrDbgOrLifetime() {
171 return const_cast<Instruction *>(
172 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbgOrLifetime());
175 /// Returns an iterator to the first instruction in this block that is
176 /// suitable for inserting a non-PHI instruction.
178 /// In particular, it skips all PHIs and LandingPad instructions.
179 const_iterator getFirstInsertionPt() const;
180 iterator getFirstInsertionPt() {
181 return static_cast<const BasicBlock *>(this)
182 ->getFirstInsertionPt().getNonConst();
185 /// Return a const iterator range over the instructions in the block, skipping
186 /// any debug instructions.
187 iterator_range<filter_iterator<BasicBlock::const_iterator,
188 std::function<bool(const Instruction &)>>>
189 instructionsWithoutDebug() const;
191 /// Return an iterator range over the instructions in the block, skipping any
192 /// debug instructions.
193 iterator_range<filter_iterator<BasicBlock::iterator,
194 std::function<bool(Instruction &)>>>
195 instructionsWithoutDebug();
197 /// Unlink 'this' from the containing function, but do not delete it.
198 void removeFromParent();
200 /// Unlink 'this' from the containing function and delete it.
202 // \returns an iterator pointing to the element after the erased one.
203 SymbolTableList<BasicBlock>::iterator eraseFromParent();
205 /// Unlink this basic block from its current function and insert it into
206 /// the function that \p MovePos lives in, right before \p MovePos.
207 void moveBefore(BasicBlock *MovePos);
209 /// Unlink this basic block from its current function and insert it
210 /// right after \p MovePos in the function \p MovePos lives in.
211 void moveAfter(BasicBlock *MovePos);
213 /// Insert unlinked basic block into a function.
215 /// Inserts an unlinked basic block into \c Parent. If \c InsertBefore is
216 /// provided, inserts before that basic block, otherwise inserts at the end.
218 /// \pre \a getParent() is \c nullptr.
219 void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
221 /// Return the predecessor of this block if it has a single predecessor
222 /// block. Otherwise return a null pointer.
223 const BasicBlock *getSinglePredecessor() const;
224 BasicBlock *getSinglePredecessor() {
225 return const_cast<BasicBlock *>(
226 static_cast<const BasicBlock *>(this)->getSinglePredecessor());
229 /// Return the predecessor of this block if it has a unique predecessor
230 /// block. Otherwise return a null pointer.
232 /// Note that unique predecessor doesn't mean single edge, there can be
233 /// multiple edges from the unique predecessor to this block (for example a
234 /// switch statement with multiple cases having the same destination).
235 const BasicBlock *getUniquePredecessor() const;
236 BasicBlock *getUniquePredecessor() {
237 return const_cast<BasicBlock *>(
238 static_cast<const BasicBlock *>(this)->getUniquePredecessor());
241 /// Return the successor of this block if it has a single successor.
242 /// Otherwise return a null pointer.
244 /// This method is analogous to getSinglePredecessor above.
245 const BasicBlock *getSingleSuccessor() const;
246 BasicBlock *getSingleSuccessor() {
247 return const_cast<BasicBlock *>(
248 static_cast<const BasicBlock *>(this)->getSingleSuccessor());
251 /// Return the successor of this block if it has a unique successor.
252 /// Otherwise return a null pointer.
254 /// This method is analogous to getUniquePredecessor above.
255 const BasicBlock *getUniqueSuccessor() const;
256 BasicBlock *getUniqueSuccessor() {
257 return const_cast<BasicBlock *>(
258 static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
261 //===--------------------------------------------------------------------===//
262 /// Instruction iterator methods
264 inline iterator begin() { return InstList.begin(); }
265 inline const_iterator begin() const { return InstList.begin(); }
266 inline iterator end () { return InstList.end(); }
267 inline const_iterator end () const { return InstList.end(); }
269 inline reverse_iterator rbegin() { return InstList.rbegin(); }
270 inline const_reverse_iterator rbegin() const { return InstList.rbegin(); }
271 inline reverse_iterator rend () { return InstList.rend(); }
272 inline const_reverse_iterator rend () const { return InstList.rend(); }
274 inline size_t size() const { return InstList.size(); }
275 inline bool empty() const { return InstList.empty(); }
276 inline const Instruction &front() const { return InstList.front(); }
277 inline Instruction &front() { return InstList.front(); }
278 inline const Instruction &back() const { return InstList.back(); }
279 inline Instruction &back() { return InstList.back(); }
281 /// Iterator to walk just the phi nodes in the basic block.
282 template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
283 class phi_iterator_impl
284 : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
285 std::forward_iterator_tag, PHINodeT> {
290 phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
293 // Allow default construction to build variables, but this doesn't build
294 // a useful iterator.
295 phi_iterator_impl() = default;
297 // Allow conversion between instantiations where valid.
298 template <typename PHINodeU, typename BBIteratorU>
299 phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
302 bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
304 PHINodeT &operator*() const { return *PN; }
306 using phi_iterator_impl::iterator_facade_base::operator++;
307 phi_iterator_impl &operator++() {
308 assert(PN && "Cannot increment the end iterator!");
309 PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
313 using phi_iterator = phi_iterator_impl<>;
314 using const_phi_iterator =
315 phi_iterator_impl<const PHINode, BasicBlock::const_iterator>;
317 /// Returns a range that iterates over the phis in the basic block.
319 /// Note that this cannot be used with basic blocks that have no terminator.
320 iterator_range<const_phi_iterator> phis() const {
321 return const_cast<BasicBlock *>(this)->phis();
323 iterator_range<phi_iterator> phis();
325 /// Return the underlying instruction list container.
327 /// Currently you need to access the underlying instruction list container
328 /// directly if you want to modify it.
329 const InstListType &getInstList() const { return InstList; }
330 InstListType &getInstList() { return InstList; }
332 /// Returns a pointer to a member of the instruction list.
333 static InstListType BasicBlock::*getSublistAccess(Instruction*) {
334 return &BasicBlock::InstList;
337 /// Returns a pointer to the symbol table if one exists.
338 ValueSymbolTable *getValueSymbolTable();
340 /// Methods for support type inquiry through isa, cast, and dyn_cast.
341 static bool classof(const Value *V) {
342 return V->getValueID() == Value::BasicBlockVal;
345 /// Cause all subinstructions to "let go" of all the references that said
346 /// subinstructions are maintaining.
348 /// This allows one to 'delete' a whole class at a time, even though there may
349 /// be circular references... first all references are dropped, and all use
350 /// counts go to zero. Then everything is delete'd for real. Note that no
351 /// operations are valid on an object that has "dropped all references",
352 /// except operator delete.
353 void dropAllReferences();
355 /// Notify the BasicBlock that the predecessor \p Pred is no longer able to
358 /// This is actually not used to update the Predecessor list, but is actually
359 /// used to update the PHI nodes that reside in the block. Note that this
360 /// should be called while the predecessor still refers to this block.
361 void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
363 bool canSplitPredecessors() const;
365 /// Split the basic block into two basic blocks at the specified instruction.
367 /// Note that all instructions BEFORE the specified iterator stay as part of
368 /// the original basic block, an unconditional branch is added to the original
369 /// BB, and the rest of the instructions in the BB are moved to the new BB,
370 /// including the old terminator. The newly formed BasicBlock is returned.
371 /// This function invalidates the specified iterator.
373 /// Note that this only works on well formed basic blocks (must have a
374 /// terminator), and 'I' must not be the end of instruction list (which would
375 /// cause a degenerate basic block to be formed, having a terminator inside of
376 /// the basic block).
378 /// Also note that this doesn't preserve any passes. To split blocks while
379 /// keeping loop information consistent, use the SplitBlock utility function.
380 BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
381 BasicBlock *splitBasicBlock(Instruction *I, const Twine &BBName = "") {
382 return splitBasicBlock(I->getIterator(), BBName);
385 /// Returns true if there are any uses of this basic block other than
386 /// direct branches, switches, etc. to it.
387 bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
389 /// Update all phi nodes in this basic block's successors to refer to basic
390 /// block \p New instead of to it.
391 void replaceSuccessorsPhiUsesWith(BasicBlock *New);
393 /// Return true if this basic block is an exception handling block.
394 bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
396 /// Return true if this basic block is a landing pad.
398 /// Being a ``landing pad'' means that the basic block is the destination of
399 /// the 'unwind' edge of an invoke instruction.
400 bool isLandingPad() const;
402 /// Return the landingpad instruction associated with the landing pad.
403 const LandingPadInst *getLandingPadInst() const;
404 LandingPadInst *getLandingPadInst() {
405 return const_cast<LandingPadInst *>(
406 static_cast<const BasicBlock *>(this)->getLandingPadInst());
409 /// Return true if it is legal to hoist instructions into this block.
410 bool isLegalToHoistInto() const;
412 Optional<uint64_t> getIrrLoopHeaderWeight() const;
415 /// Increment the internal refcount of the number of BlockAddresses
416 /// referencing this BasicBlock by \p Amt.
418 /// This is almost always 0, sometimes one possibly, but almost never 2, and
419 /// inconceivably 3 or more.
420 void AdjustBlockAddressRefCount(int Amt) {
421 setValueSubclassData(getSubclassDataFromValue()+Amt);
422 assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
423 "Refcount wrap-around");
426 /// Shadow Value::setValueSubclassData with a private forwarding method so
427 /// that any future subclasses cannot accidentally use it.
428 void setValueSubclassData(unsigned short D) {
429 Value::setValueSubclassData(D);
433 // Create wrappers for C Binding types (see CBindingWrapping.h).
434 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
436 /// Advance \p It while it points to a debug instruction and return the result.
437 /// This assumes that \p It is not at the end of a block.
438 BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It);
440 } // end namespace llvm
442 #endif // LLVM_IR_BASICBLOCK_H