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