BasicBlock.h 26 KB

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