1 //===- llvm/BasicBlock.h - Represent a basic block in the VM ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the declaration of the BasicBlock class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_IR_BASICBLOCK_H
14 #define LLVM_IR_BASICBLOCK_H
15 
16 #include "llvm-c/Types.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/ADT/iterator.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/IR/Instruction.h"
23 #include "llvm/IR/SymbolTableListTraits.h"
24 #include "llvm/IR/Value.h"
25 #include "llvm/Support/CBindingWrapping.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Compiler.h"
28 #include <cassert>
29 #include <cstddef>
30 #include <iterator>
31 
32 namespace llvm {
33 
34 class CallInst;
35 class Function;
36 class LandingPadInst;
37 class LLVMContext;
38 class Module;
39 class PHINode;
40 class ValueSymbolTable;
41 
42 /// LLVM Basic Block Representation
43 ///
44 /// This represents a single basic block in LLVM. A basic block is simply a
45 /// container of instructions that execute sequentially. Basic blocks are Values
46 /// because they are referenced by instructions such as branches and switch
47 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
48 /// represents a label to which a branch can jump.
49 ///
50 /// A well formed basic block is formed of a list of non-terminating
51 /// instructions followed by a single terminator instruction. Terminator
52 /// instructions may not occur in the middle of basic blocks, and must terminate
53 /// the blocks. The BasicBlock class allows malformed basic blocks to occur
54 /// because it may be useful in the intermediate stage of constructing or
55 /// modifying a program. However, the verifier will ensure that basic blocks are
56 /// "well formed".
57 class BasicBlock final : public Value, // Basic blocks are data objects also
58                          public ilist_node_with_parent<BasicBlock, Function> {
59 public:
60   using InstListType = SymbolTableList<Instruction>;
61 
62 private:
63   friend class BlockAddress;
64   friend class SymbolTableListTraits<BasicBlock>;
65 
66   InstListType InstList;
67   Function *Parent;
68 
69   void setParent(Function *parent);
70 
71   /// Constructor.
72   ///
73   /// If the function parameter is specified, the basic block is automatically
74   /// inserted at either the end of the function (if InsertBefore is null), or
75   /// before the specified basic block.
76   explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
77                       Function *Parent = nullptr,
78                       BasicBlock *InsertBefore = nullptr);
79 
80 public:
81   BasicBlock(const BasicBlock &) = delete;
82   BasicBlock &operator=(const BasicBlock &) = delete;
83   ~BasicBlock();
84 
85   /// Get the context in which this basic block lives.
86   LLVMContext &getContext() const;
87 
88   /// Instruction iterators...
89   using iterator = InstListType::iterator;
90   using const_iterator = InstListType::const_iterator;
91   using reverse_iterator = InstListType::reverse_iterator;
92   using const_reverse_iterator = InstListType::const_reverse_iterator;
93 
94   /// Creates a new BasicBlock.
95   ///
96   /// If the Parent parameter is specified, the basic block is automatically
97   /// inserted at either the end of the function (if InsertBefore is 0), or
98   /// before the specified basic block.
99   static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
100                             Function *Parent = nullptr,
101                             BasicBlock *InsertBefore = nullptr) {
102     return new BasicBlock(Context, Name, Parent, InsertBefore);
103   }
104 
105   /// Return the enclosing method, or null if none.
106   const Function *getParent() const { return Parent; }
107         Function *getParent()       { return Parent; }
108 
109   /// Return the module owning the function this basic block belongs to, or
110   /// nullptr if the function does not have a module.
111   ///
112   /// Note: this is undefined behavior if the block does not have a parent.
113   const Module *getModule() const;
114   Module *getModule() {
115     return const_cast<Module *>(
116                             static_cast<const BasicBlock *>(this)->getModule());
117   }
118 
119   /// Returns the terminator instruction if the block is well formed or null
120   /// if the block is not well formed.
121   const Instruction *getTerminator() const LLVM_READONLY;
122   Instruction *getTerminator() {
123     return const_cast<Instruction *>(
124         static_cast<const BasicBlock *>(this)->getTerminator());
125   }
126 
127   /// Returns the call instruction calling \@llvm.experimental.deoptimize
128   /// prior to the terminating return instruction of this basic block, if such
129   /// a call is present.  Otherwise, returns null.
130   const CallInst *getTerminatingDeoptimizeCall() const;
131   CallInst *getTerminatingDeoptimizeCall() {
132     return const_cast<CallInst *>(
133          static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
134   }
135 
136   /// Returns the call instruction calling \@llvm.experimental.deoptimize
137   /// that is present either in current basic block or in block that is a unique
138   /// successor to current block, if such call is present. Otherwise, returns null.
139   const CallInst *getPostdominatingDeoptimizeCall() const;
140   CallInst *getPostdominatingDeoptimizeCall() {
141     return const_cast<CallInst *>(
142          static_cast<const BasicBlock *>(this)->getPostdominatingDeoptimizeCall());
143   }
144 
145   /// Returns the call instruction marked 'musttail' prior to the terminating
146   /// return instruction of this basic block, if such a call is present.
147   /// Otherwise, returns null.
148   const CallInst *getTerminatingMustTailCall() const;
149   CallInst *getTerminatingMustTailCall() {
150     return const_cast<CallInst *>(
151            static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
152   }
153 
154   /// Returns a pointer to the first instruction in this block that is not a
155   /// PHINode instruction.
156   ///
157   /// When adding instructions to the beginning of the basic block, they should
158   /// be added before the returned value, not before the first instruction,
159   /// which might be PHI. Returns 0 is there's no non-PHI instruction.
160   const Instruction* getFirstNonPHI() const;
161   Instruction* getFirstNonPHI() {
162     return const_cast<Instruction *>(
163                        static_cast<const BasicBlock *>(this)->getFirstNonPHI());
164   }
165 
166   /// Returns a pointer to the first instruction in this block that is not a
167   /// PHINode or a debug intrinsic.
168   const Instruction* getFirstNonPHIOrDbg() const;
169   Instruction* getFirstNonPHIOrDbg() {
170     return const_cast<Instruction *>(
171                   static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbg());
172   }
173 
174   /// Returns a pointer to the first instruction in this block that is not a
175   /// PHINode, a debug intrinsic, or a lifetime intrinsic.
176   const Instruction* getFirstNonPHIOrDbgOrLifetime() const;
177   Instruction* getFirstNonPHIOrDbgOrLifetime() {
178     return const_cast<Instruction *>(
179         static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbgOrLifetime());
180   }
181 
182   /// Returns an iterator to the first instruction in this block that is
183   /// suitable for inserting a non-PHI instruction.
184   ///
185   /// In particular, it skips all PHIs and LandingPad instructions.
186   const_iterator getFirstInsertionPt() const;
187   iterator getFirstInsertionPt() {
188     return static_cast<const BasicBlock *>(this)
189                                           ->getFirstInsertionPt().getNonConst();
190   }
191 
192   /// Return a const iterator range over the instructions in the block, skipping
193   /// any debug instructions.
194   iterator_range<filter_iterator<BasicBlock::const_iterator,
195                                  std::function<bool(const Instruction &)>>>
196   instructionsWithoutDebug() const;
197 
198   /// Return an iterator range over the instructions in the block, skipping any
199   /// debug instructions.
200   iterator_range<filter_iterator<BasicBlock::iterator,
201                                  std::function<bool(Instruction &)>>>
202   instructionsWithoutDebug();
203 
204   /// Return the size of the basic block ignoring debug instructions
205   filter_iterator<BasicBlock::const_iterator,
206                   std::function<bool(const Instruction &)>>::difference_type
207   sizeWithoutDebug() const;
208 
209   /// Unlink 'this' from the containing function, but do not delete it.
210   void removeFromParent();
211 
212   /// Unlink 'this' from the containing function and delete it.
213   ///
214   // \returns an iterator pointing to the element after the erased one.
215   SymbolTableList<BasicBlock>::iterator eraseFromParent();
216 
217   /// Unlink this basic block from its current function and insert it into
218   /// the function that \p MovePos lives in, right before \p MovePos.
219   void moveBefore(BasicBlock *MovePos);
220 
221   /// Unlink this basic block from its current function and insert it
222   /// right after \p MovePos in the function \p MovePos lives in.
223   void moveAfter(BasicBlock *MovePos);
224 
225   /// Insert unlinked basic block into a function.
226   ///
227   /// Inserts an unlinked basic block into \c Parent.  If \c InsertBefore is
228   /// provided, inserts before that basic block, otherwise inserts at the end.
229   ///
230   /// \pre \a getParent() is \c nullptr.
231   void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
232 
233   /// Return the predecessor of this block if it has a single predecessor
234   /// block. Otherwise return a null pointer.
235   const BasicBlock *getSinglePredecessor() const;
236   BasicBlock *getSinglePredecessor() {
237     return const_cast<BasicBlock *>(
238                  static_cast<const BasicBlock *>(this)->getSinglePredecessor());
239   }
240 
241   /// Return the predecessor of this block if it has a unique predecessor
242   /// block. Otherwise return a null pointer.
243   ///
244   /// Note that unique predecessor doesn't mean single edge, there can be
245   /// multiple edges from the unique predecessor to this block (for example a
246   /// switch statement with multiple cases having the same destination).
247   const BasicBlock *getUniquePredecessor() const;
248   BasicBlock *getUniquePredecessor() {
249     return const_cast<BasicBlock *>(
250                  static_cast<const BasicBlock *>(this)->getUniquePredecessor());
251   }
252 
253   /// Return true if this block has exactly N predecessors.
254   bool hasNPredecessors(unsigned N) const;
255 
256   /// Return true if this block has N predecessors or more.
257   bool hasNPredecessorsOrMore(unsigned N) const;
258 
259   /// Return the successor of this block if it has a single successor.
260   /// Otherwise return a null pointer.
261   ///
262   /// This method is analogous to getSinglePredecessor above.
263   const BasicBlock *getSingleSuccessor() const;
264   BasicBlock *getSingleSuccessor() {
265     return const_cast<BasicBlock *>(
266                    static_cast<const BasicBlock *>(this)->getSingleSuccessor());
267   }
268 
269   /// Return the successor of this block if it has a unique successor.
270   /// Otherwise return a null pointer.
271   ///
272   /// This method is analogous to getUniquePredecessor above.
273   const BasicBlock *getUniqueSuccessor() const;
274   BasicBlock *getUniqueSuccessor() {
275     return const_cast<BasicBlock *>(
276                    static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
277   }
278 
279   //===--------------------------------------------------------------------===//
280   /// Instruction iterator methods
281   ///
282   inline iterator                begin()       { return InstList.begin(); }
283   inline const_iterator          begin() const { return InstList.begin(); }
284   inline iterator                end  ()       { return InstList.end();   }
285   inline const_iterator          end  () const { return InstList.end();   }
286 
287   inline reverse_iterator        rbegin()       { return InstList.rbegin(); }
288   inline const_reverse_iterator  rbegin() const { return InstList.rbegin(); }
289   inline reverse_iterator        rend  ()       { return InstList.rend();   }
290   inline const_reverse_iterator  rend  () const { return InstList.rend();   }
291 
292   inline size_t                   size() const { return InstList.size();  }
293   inline bool                    empty() const { return InstList.empty(); }
294   inline const Instruction      &front() const { return InstList.front(); }
295   inline       Instruction      &front()       { return InstList.front(); }
296   inline const Instruction       &back() const { return InstList.back();  }
297   inline       Instruction       &back()       { return InstList.back();  }
298 
299   /// Iterator to walk just the phi nodes in the basic block.
300   template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
301   class phi_iterator_impl
302       : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
303                                     std::forward_iterator_tag, PHINodeT> {
304     friend BasicBlock;
305 
306     PHINodeT *PN;
307 
308     phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
309 
310   public:
311     // Allow default construction to build variables, but this doesn't build
312     // a useful iterator.
313     phi_iterator_impl() = default;
314 
315     // Allow conversion between instantiations where valid.
316     template <typename PHINodeU, typename BBIteratorU>
317     phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
318         : PN(Arg.PN) {}
319 
320     bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
321 
322     PHINodeT &operator*() const { return *PN; }
323 
324     using phi_iterator_impl::iterator_facade_base::operator++;
325     phi_iterator_impl &operator++() {
326       assert(PN && "Cannot increment the end iterator!");
327       PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
328       return *this;
329     }
330   };
331   using phi_iterator = phi_iterator_impl<>;
332   using const_phi_iterator =
333       phi_iterator_impl<const PHINode, BasicBlock::const_iterator>;
334 
335   /// Returns a range that iterates over the phis in the basic block.
336   ///
337   /// Note that this cannot be used with basic blocks that have no terminator.
338   iterator_range<const_phi_iterator> phis() const {
339     return const_cast<BasicBlock *>(this)->phis();
340   }
341   iterator_range<phi_iterator> phis();
342 
343   /// Return the underlying instruction list container.
344   ///
345   /// Currently you need to access the underlying instruction list container
346   /// directly if you want to modify it.
347   const InstListType &getInstList() const { return InstList; }
348         InstListType &getInstList()       { return InstList; }
349 
350   /// Returns a pointer to a member of the instruction list.
351   static InstListType BasicBlock::*getSublistAccess(Instruction*) {
352     return &BasicBlock::InstList;
353   }
354 
355   /// Returns a pointer to the symbol table if one exists.
356   ValueSymbolTable *getValueSymbolTable();
357 
358   /// Methods for support type inquiry through isa, cast, and dyn_cast.
359   static bool classof(const Value *V) {
360     return V->getValueID() == Value::BasicBlockVal;
361   }
362 
363   /// Cause all subinstructions to "let go" of all the references that said
364   /// subinstructions are maintaining.
365   ///
366   /// This allows one to 'delete' a whole class at a time, even though there may
367   /// be circular references... first all references are dropped, and all use
368   /// counts go to zero.  Then everything is delete'd for real.  Note that no
369   /// operations are valid on an object that has "dropped all references",
370   /// except operator delete.
371   void dropAllReferences();
372 
373   /// Notify the BasicBlock that the predecessor \p Pred is no longer able to
374   /// reach it.
375   ///
376   /// This is actually not used to update the Predecessor list, but is actually
377   /// used to update the PHI nodes that reside in the block.  Note that this
378   /// should be called while the predecessor still refers to this block.
379   void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs = false);
380 
381   bool canSplitPredecessors() const;
382 
383   /// Split the basic block into two basic blocks at the specified instruction.
384   ///
385   /// Note that all instructions BEFORE the specified iterator stay as part of
386   /// the original basic block, an unconditional branch is added to the original
387   /// BB, and the rest of the instructions in the BB are moved to the new BB,
388   /// including the old terminator.  The newly formed BasicBlock is returned.
389   /// This function invalidates the specified iterator.
390   ///
391   /// Note that this only works on well formed basic blocks (must have a
392   /// terminator), and 'I' must not be the end of instruction list (which would
393   /// cause a degenerate basic block to be formed, having a terminator inside of
394   /// the basic block).
395   ///
396   /// Also note that this doesn't preserve any passes. To split blocks while
397   /// keeping loop information consistent, use the SplitBlock utility function.
398   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
399   BasicBlock *splitBasicBlock(Instruction *I, const Twine &BBName = "") {
400     return splitBasicBlock(I->getIterator(), BBName);
401   }
402 
403   /// Returns true if there are any uses of this basic block other than
404   /// direct branches, switches, etc. to it.
405   bool hasAddressTaken() const {
406     return getBasicBlockBits().BlockAddressRefCount != 0;
407   }
408 
409   /// Update all phi nodes in this basic block to refer to basic block \p New
410   /// instead of basic block \p Old.
411   void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New);
412 
413   /// Update all phi nodes in this basic block's successors to refer to basic
414   /// block \p New instead of basic block \p Old.
415   void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New);
416 
417   /// Update all phi nodes in this basic block's successors to refer to basic
418   /// block \p New instead of to it.
419   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
420 
421   /// Return true if this basic block is an exception handling block.
422   bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
423 
424   /// Return true if this basic block is a landing pad.
425   ///
426   /// Being a ``landing pad'' means that the basic block is the destination of
427   /// the 'unwind' edge of an invoke instruction.
428   bool isLandingPad() const;
429 
430   /// Return the landingpad instruction associated with the landing pad.
431   const LandingPadInst *getLandingPadInst() const;
432   LandingPadInst *getLandingPadInst() {
433     return const_cast<LandingPadInst *>(
434                     static_cast<const BasicBlock *>(this)->getLandingPadInst());
435   }
436 
437   /// Return true if it is legal to hoist instructions into this block.
438   bool isLegalToHoistInto() const;
439 
440   Optional<uint64_t> getIrrLoopHeaderWeight() const;
441 
442   /// Returns true if the Order field of child Instructions is valid.
443   bool isInstrOrderValid() const {
444     return getBasicBlockBits().InstrOrderValid;
445   }
446 
447   /// Mark instruction ordering invalid. Done on every instruction insert.
448   void invalidateOrders() {
449     validateInstrOrdering();
450     BasicBlockBits Bits = getBasicBlockBits();
451     Bits.InstrOrderValid = false;
452     setBasicBlockBits(Bits);
453   }
454 
455   /// Renumber instructions and mark the ordering as valid.
456   void renumberInstructions();
457 
458   /// Asserts that instruction order numbers are marked invalid, or that they
459   /// are in ascending order. This is constant time if the ordering is invalid,
460   /// and linear in the number of instructions if the ordering is valid. Callers
461   /// should be careful not to call this in ways that make common operations
462   /// O(n^2). For example, it takes O(n) time to assign order numbers to
463   /// instructions, so the order should be validated no more than once after
464   /// each ordering to ensure that transforms have the same algorithmic
465   /// complexity when asserts are enabled as when they are disabled.
466   void validateInstrOrdering() const;
467 
468 private:
469 #if defined(_AIX) && (!defined(__GNUC__) || defined(__ibmxl__))
470 // Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
471 // and give the `pack` pragma push semantics.
472 #define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")
473 #define END_TWO_BYTE_PACK() _Pragma("pack(pop)")
474 #else
475 #define BEGIN_TWO_BYTE_PACK()
476 #define END_TWO_BYTE_PACK()
477 #endif
478 
479   BEGIN_TWO_BYTE_PACK()
480   /// Bitfield to help interpret the bits in Value::SubclassData.
481   struct BasicBlockBits {
482     unsigned short BlockAddressRefCount : 15;
483     unsigned short InstrOrderValid : 1;
484   };
485   END_TWO_BYTE_PACK()
486 
487 #undef BEGIN_TWO_BYTE_PACK
488 #undef END_TWO_BYTE_PACK
489 
490   /// Safely reinterpret the subclass data bits to a more useful form.
491   BasicBlockBits getBasicBlockBits() const {
492     static_assert(sizeof(BasicBlockBits) == sizeof(unsigned short),
493                   "too many bits for Value::SubclassData");
494     unsigned short ValueData = getSubclassDataFromValue();
495     BasicBlockBits AsBits;
496     memcpy(&AsBits, &ValueData, sizeof(AsBits));
497     return AsBits;
498   }
499 
500   /// Reinterpret our subclass bits and store them back into Value.
501   void setBasicBlockBits(BasicBlockBits AsBits) {
502     unsigned short D;
503     memcpy(&D, &AsBits, sizeof(D));
504     Value::setValueSubclassData(D);
505   }
506 
507   /// Increment the internal refcount of the number of BlockAddresses
508   /// referencing this BasicBlock by \p Amt.
509   ///
510   /// This is almost always 0, sometimes one possibly, but almost never 2, and
511   /// inconceivably 3 or more.
512   void AdjustBlockAddressRefCount(int Amt) {
513     BasicBlockBits Bits = getBasicBlockBits();
514     Bits.BlockAddressRefCount += Amt;
515     setBasicBlockBits(Bits);
516     assert(Bits.BlockAddressRefCount < 255 && "Refcount wrap-around");
517   }
518 
519   /// Shadow Value::setValueSubclassData with a private forwarding method so
520   /// that any future subclasses cannot accidentally use it.
521   void setValueSubclassData(unsigned short D) {
522     Value::setValueSubclassData(D);
523   }
524 };
525 
526 // Create wrappers for C Binding types (see CBindingWrapping.h).
527 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
528 
529 /// Advance \p It while it points to a debug instruction and return the result.
530 /// This assumes that \p It is not at the end of a block.
531 BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It);
532 
533 #ifdef NDEBUG
534 /// In release builds, this is a no-op. For !NDEBUG builds, the checks are
535 /// implemented in the .cpp file to avoid circular header deps.
536 inline void BasicBlock::validateInstrOrdering() const {}
537 #endif
538 
539 } // end namespace llvm
540 
541 #endif // LLVM_IR_BASICBLOCK_H
542