]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/BasicBlock.h
Upgrade our copies of clang, llvm, lld, lldb, compiler-rt and libc++ to
[FreeBSD/FreeBSD.git] / contrib / llvm / 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-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"
29 #include <cassert>
30 #include <cstddef>
31 #include <iterator>
32
33 namespace llvm {
34
35 class CallInst;
36 class Function;
37 class LandingPadInst;
38 class LLVMContext;
39 class Module;
40 class PHINode;
41 class TerminatorInst;
42 class ValueSymbolTable;
43
44 /// LLVM Basic Block Representation
45 ///
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.
51 ///
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> {
61 public:
62   using InstListType = SymbolTableList<Instruction>;
63
64 private:
65   friend class BlockAddress;
66   friend class SymbolTableListTraits<BasicBlock>;
67
68   InstListType InstList;
69   Function *Parent;
70
71   void setParent(Function *parent);
72
73   /// Constructor.
74   ///
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);
81
82 public:
83   BasicBlock(const BasicBlock &) = delete;
84   BasicBlock &operator=(const BasicBlock &) = delete;
85   ~BasicBlock();
86
87   /// Get the context in which this basic block lives.
88   LLVMContext &getContext() const;
89
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;
95
96   /// Creates a new BasicBlock.
97   ///
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);
105   }
106
107   /// Return the enclosing method, or null if none.
108   const Function *getParent() const { return Parent; }
109         Function *getParent()       { return Parent; }
110
111   /// Return the module owning the function this basic block belongs to, or
112   /// nullptr if the function does not have a module.
113   ///
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());
119   }
120
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());
127   }
128
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());
136   }
137
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());
145   }
146
147   /// Returns a pointer to the first instruction in this block that is not a
148   /// PHINode instruction.
149   ///
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());
157   }
158
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());
165   }
166
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());
173   }
174
175   /// Returns an iterator to the first instruction in this block that is
176   /// suitable for inserting a non-PHI instruction.
177   ///
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();
183   }
184
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;
190
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();
196
197   /// Unlink 'this' from the containing function, but do not delete it.
198   void removeFromParent();
199
200   /// Unlink 'this' from the containing function and delete it.
201   ///
202   // \returns an iterator pointing to the element after the erased one.
203   SymbolTableList<BasicBlock>::iterator eraseFromParent();
204
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);
208
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);
212
213   /// Insert unlinked basic block into a function.
214   ///
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.
217   ///
218   /// \pre \a getParent() is \c nullptr.
219   void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
220
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());
227   }
228
229   /// Return the predecessor of this block if it has a unique predecessor
230   /// block. Otherwise return a null pointer.
231   ///
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());
239   }
240
241   /// Return the successor of this block if it has a single successor.
242   /// Otherwise return a null pointer.
243   ///
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());
249   }
250
251   /// Return the successor of this block if it has a unique successor.
252   /// Otherwise return a null pointer.
253   ///
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());
259   }
260
261   //===--------------------------------------------------------------------===//
262   /// Instruction iterator methods
263   ///
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();   }
268
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();   }
273
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();  }
280
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> {
286     friend BasicBlock;
287
288     PHINodeT *PN;
289
290     phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
291
292   public:
293     // Allow default construction to build variables, but this doesn't build
294     // a useful iterator.
295     phi_iterator_impl() = default;
296
297     // Allow conversion between instantiations where valid.
298     template <typename PHINodeU, typename BBIteratorU>
299     phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
300         : PN(Arg.PN) {}
301
302     bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
303
304     PHINodeT &operator*() const { return *PN; }
305
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)));
310       return *this;
311     }
312   };
313   using phi_iterator = phi_iterator_impl<>;
314   using const_phi_iterator =
315       phi_iterator_impl<const PHINode, BasicBlock::const_iterator>;
316
317   /// Returns a range that iterates over the phis in the basic block.
318   ///
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();
322   }
323   iterator_range<phi_iterator> phis();
324
325   /// Return the underlying instruction list container.
326   ///
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; }
331
332   /// Returns a pointer to a member of the instruction list.
333   static InstListType BasicBlock::*getSublistAccess(Instruction*) {
334     return &BasicBlock::InstList;
335   }
336
337   /// Returns a pointer to the symbol table if one exists.
338   ValueSymbolTable *getValueSymbolTable();
339
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;
343   }
344
345   /// Cause all subinstructions to "let go" of all the references that said
346   /// subinstructions are maintaining.
347   ///
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();
354
355   /// Notify the BasicBlock that the predecessor \p Pred is no longer able to
356   /// reach it.
357   ///
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);
362
363   bool canSplitPredecessors() const;
364
365   /// Split the basic block into two basic blocks at the specified instruction.
366   ///
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.
372   ///
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).
377   ///
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);
383   }
384
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; }
388
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);
392
393   /// Return true if this basic block is an exception handling block.
394   bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
395
396   /// Return true if this basic block is a landing pad.
397   ///
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;
401
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());
407   }
408
409   /// Return true if it is legal to hoist instructions into this block.
410   bool isLegalToHoistInto() const;
411
412   Optional<uint64_t> getIrrLoopHeaderWeight() const;
413
414 private:
415   /// Increment the internal refcount of the number of BlockAddresses
416   /// referencing this BasicBlock by \p Amt.
417   ///
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");
424   }
425
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);
430   }
431 };
432
433 // Create wrappers for C Binding types (see CBindingWrapping.h).
434 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
435
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);
439
440 } // end namespace llvm
441
442 #endif // LLVM_IR_BASICBLOCK_H