MachineBasicBlock.h 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. //===- llvm/CodeGen/MachineBasicBlock.h -------------------------*- 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. // Collect the sequence of machine instructions for a basic block.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
  13. #define LLVM_CODEGEN_MACHINEBASICBLOCK_H
  14. #include "llvm/ADT/GraphTraits.h"
  15. #include "llvm/ADT/ilist.h"
  16. #include "llvm/ADT/ilist_node.h"
  17. #include "llvm/ADT/iterator_range.h"
  18. #include "llvm/ADT/simple_ilist.h"
  19. #include "llvm/CodeGen/MachineInstr.h"
  20. #include "llvm/CodeGen/MachineInstrBundleIterator.h"
  21. #include "llvm/IR/DebugLoc.h"
  22. #include "llvm/MC/LaneBitmask.h"
  23. #include "llvm/MC/MCRegisterInfo.h"
  24. #include "llvm/Support/BranchProbability.h"
  25. #include "llvm/Support/Printable.h"
  26. #include <cassert>
  27. #include <cstdint>
  28. #include <functional>
  29. #include <iterator>
  30. #include <string>
  31. #include <vector>
  32. namespace llvm {
  33. class BasicBlock;
  34. class MachineFunction;
  35. class MCSymbol;
  36. class ModuleSlotTracker;
  37. class Pass;
  38. class SlotIndexes;
  39. class StringRef;
  40. class raw_ostream;
  41. class TargetRegisterClass;
  42. class TargetRegisterInfo;
  43. template <> struct ilist_traits<MachineInstr> {
  44. private:
  45. friend class MachineBasicBlock; // Set by the owning MachineBasicBlock.
  46. MachineBasicBlock *Parent;
  47. using instr_iterator =
  48. simple_ilist<MachineInstr, ilist_sentinel_tracking<true>>::iterator;
  49. public:
  50. void addNodeToList(MachineInstr *N);
  51. void removeNodeFromList(MachineInstr *N);
  52. void transferNodesFromList(ilist_traits &FromList, instr_iterator First,
  53. instr_iterator Last);
  54. void deleteNode(MachineInstr *MI);
  55. };
  56. class MachineBasicBlock
  57. : public ilist_node_with_parent<MachineBasicBlock, MachineFunction> {
  58. public:
  59. /// Pair of physical register and lane mask.
  60. /// This is not simply a std::pair typedef because the members should be named
  61. /// clearly as they both have an integer type.
  62. struct RegisterMaskPair {
  63. public:
  64. MCPhysReg PhysReg;
  65. LaneBitmask LaneMask;
  66. RegisterMaskPair(MCPhysReg PhysReg, LaneBitmask LaneMask)
  67. : PhysReg(PhysReg), LaneMask(LaneMask) {}
  68. };
  69. private:
  70. using Instructions = ilist<MachineInstr, ilist_sentinel_tracking<true>>;
  71. Instructions Insts;
  72. const BasicBlock *BB;
  73. int Number;
  74. MachineFunction *xParent;
  75. /// Keep track of the predecessor / successor basic blocks.
  76. std::vector<MachineBasicBlock *> Predecessors;
  77. std::vector<MachineBasicBlock *> Successors;
  78. /// Keep track of the probabilities to the successors. This vector has the
  79. /// same order as Successors, or it is empty if we don't use it (disable
  80. /// optimization).
  81. std::vector<BranchProbability> Probs;
  82. using probability_iterator = std::vector<BranchProbability>::iterator;
  83. using const_probability_iterator =
  84. std::vector<BranchProbability>::const_iterator;
  85. Optional<uint64_t> IrrLoopHeaderWeight;
  86. /// Keep track of the physical registers that are livein of the basicblock.
  87. using LiveInVector = std::vector<RegisterMaskPair>;
  88. LiveInVector LiveIns;
  89. /// Alignment of the basic block. Zero if the basic block does not need to be
  90. /// aligned. The alignment is specified as log2(bytes).
  91. unsigned Alignment = 0;
  92. /// Indicate that this basic block is entered via an exception handler.
  93. bool IsEHPad = false;
  94. /// Indicate that this basic block is potentially the target of an indirect
  95. /// branch.
  96. bool AddressTaken = false;
  97. /// Indicate that this basic block needs its symbol be emitted regardless of
  98. /// whether the flow just falls-through to it.
  99. bool LabelMustBeEmitted = false;
  100. /// Indicate that this basic block is the entry block of an EH scope, i.e.,
  101. /// the block that used to have a catchpad or cleanuppad instruction in the
  102. /// LLVM IR.
  103. bool IsEHScopeEntry = false;
  104. /// Indicate that this basic block is the entry block of an EH funclet.
  105. bool IsEHFuncletEntry = false;
  106. /// Indicate that this basic block is the entry block of a cleanup funclet.
  107. bool IsCleanupFuncletEntry = false;
  108. /// since getSymbol is a relatively heavy-weight operation, the symbol
  109. /// is only computed once and is cached.
  110. mutable MCSymbol *CachedMCSymbol = nullptr;
  111. // Intrusive list support
  112. MachineBasicBlock() = default;
  113. explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
  114. ~MachineBasicBlock();
  115. // MachineBasicBlocks are allocated and owned by MachineFunction.
  116. friend class MachineFunction;
  117. public:
  118. /// Return the LLVM basic block that this instance corresponded to originally.
  119. /// Note that this may be NULL if this instance does not correspond directly
  120. /// to an LLVM basic block.
  121. const BasicBlock *getBasicBlock() const { return BB; }
  122. /// Return the name of the corresponding LLVM basic block, or an empty string.
  123. StringRef getName() const;
  124. /// Return a formatted string to identify this block and its parent function.
  125. std::string getFullName() const;
  126. /// Test whether this block is potentially the target of an indirect branch.
  127. bool hasAddressTaken() const { return AddressTaken; }
  128. /// Set this block to reflect that it potentially is the target of an indirect
  129. /// branch.
  130. void setHasAddressTaken() { AddressTaken = true; }
  131. /// Test whether this block must have its label emitted.
  132. bool hasLabelMustBeEmitted() const { return LabelMustBeEmitted; }
  133. /// Set this block to reflect that, regardless how we flow to it, we need
  134. /// its label be emitted.
  135. void setLabelMustBeEmitted() { LabelMustBeEmitted = true; }
  136. /// Return the MachineFunction containing this basic block.
  137. const MachineFunction *getParent() const { return xParent; }
  138. MachineFunction *getParent() { return xParent; }
  139. using instr_iterator = Instructions::iterator;
  140. using const_instr_iterator = Instructions::const_iterator;
  141. using reverse_instr_iterator = Instructions::reverse_iterator;
  142. using const_reverse_instr_iterator = Instructions::const_reverse_iterator;
  143. using iterator = MachineInstrBundleIterator<MachineInstr>;
  144. using const_iterator = MachineInstrBundleIterator<const MachineInstr>;
  145. using reverse_iterator = MachineInstrBundleIterator<MachineInstr, true>;
  146. using const_reverse_iterator =
  147. MachineInstrBundleIterator<const MachineInstr, true>;
  148. unsigned size() const { return (unsigned)Insts.size(); }
  149. bool empty() const { return Insts.empty(); }
  150. MachineInstr &instr_front() { return Insts.front(); }
  151. MachineInstr &instr_back() { return Insts.back(); }
  152. const MachineInstr &instr_front() const { return Insts.front(); }
  153. const MachineInstr &instr_back() const { return Insts.back(); }
  154. MachineInstr &front() { return Insts.front(); }
  155. MachineInstr &back() { return *--end(); }
  156. const MachineInstr &front() const { return Insts.front(); }
  157. const MachineInstr &back() const { return *--end(); }
  158. instr_iterator instr_begin() { return Insts.begin(); }
  159. const_instr_iterator instr_begin() const { return Insts.begin(); }
  160. instr_iterator instr_end() { return Insts.end(); }
  161. const_instr_iterator instr_end() const { return Insts.end(); }
  162. reverse_instr_iterator instr_rbegin() { return Insts.rbegin(); }
  163. const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
  164. reverse_instr_iterator instr_rend () { return Insts.rend(); }
  165. const_reverse_instr_iterator instr_rend () const { return Insts.rend(); }
  166. using instr_range = iterator_range<instr_iterator>;
  167. using const_instr_range = iterator_range<const_instr_iterator>;
  168. instr_range instrs() { return instr_range(instr_begin(), instr_end()); }
  169. const_instr_range instrs() const {
  170. return const_instr_range(instr_begin(), instr_end());
  171. }
  172. iterator begin() { return instr_begin(); }
  173. const_iterator begin() const { return instr_begin(); }
  174. iterator end () { return instr_end(); }
  175. const_iterator end () const { return instr_end(); }
  176. reverse_iterator rbegin() {
  177. return reverse_iterator::getAtBundleBegin(instr_rbegin());
  178. }
  179. const_reverse_iterator rbegin() const {
  180. return const_reverse_iterator::getAtBundleBegin(instr_rbegin());
  181. }
  182. reverse_iterator rend() { return reverse_iterator(instr_rend()); }
  183. const_reverse_iterator rend() const {
  184. return const_reverse_iterator(instr_rend());
  185. }
  186. /// Support for MachineInstr::getNextNode().
  187. static Instructions MachineBasicBlock::*getSublistAccess(MachineInstr *) {
  188. return &MachineBasicBlock::Insts;
  189. }
  190. inline iterator_range<iterator> terminators() {
  191. return make_range(getFirstTerminator(), end());
  192. }
  193. inline iterator_range<const_iterator> terminators() const {
  194. return make_range(getFirstTerminator(), end());
  195. }
  196. /// Returns a range that iterates over the phis in the basic block.
  197. inline iterator_range<iterator> phis() {
  198. return make_range(begin(), getFirstNonPHI());
  199. }
  200. inline iterator_range<const_iterator> phis() const {
  201. return const_cast<MachineBasicBlock *>(this)->phis();
  202. }
  203. // Machine-CFG iterators
  204. using pred_iterator = std::vector<MachineBasicBlock *>::iterator;
  205. using const_pred_iterator = std::vector<MachineBasicBlock *>::const_iterator;
  206. using succ_iterator = std::vector<MachineBasicBlock *>::iterator;
  207. using const_succ_iterator = std::vector<MachineBasicBlock *>::const_iterator;
  208. using pred_reverse_iterator =
  209. std::vector<MachineBasicBlock *>::reverse_iterator;
  210. using const_pred_reverse_iterator =
  211. std::vector<MachineBasicBlock *>::const_reverse_iterator;
  212. using succ_reverse_iterator =
  213. std::vector<MachineBasicBlock *>::reverse_iterator;
  214. using const_succ_reverse_iterator =
  215. std::vector<MachineBasicBlock *>::const_reverse_iterator;
  216. pred_iterator pred_begin() { return Predecessors.begin(); }
  217. const_pred_iterator pred_begin() const { return Predecessors.begin(); }
  218. pred_iterator pred_end() { return Predecessors.end(); }
  219. const_pred_iterator pred_end() const { return Predecessors.end(); }
  220. pred_reverse_iterator pred_rbegin()
  221. { return Predecessors.rbegin();}
  222. const_pred_reverse_iterator pred_rbegin() const
  223. { return Predecessors.rbegin();}
  224. pred_reverse_iterator pred_rend()
  225. { return Predecessors.rend(); }
  226. const_pred_reverse_iterator pred_rend() const
  227. { return Predecessors.rend(); }
  228. unsigned pred_size() const {
  229. return (unsigned)Predecessors.size();
  230. }
  231. bool pred_empty() const { return Predecessors.empty(); }
  232. succ_iterator succ_begin() { return Successors.begin(); }
  233. const_succ_iterator succ_begin() const { return Successors.begin(); }
  234. succ_iterator succ_end() { return Successors.end(); }
  235. const_succ_iterator succ_end() const { return Successors.end(); }
  236. succ_reverse_iterator succ_rbegin()
  237. { return Successors.rbegin(); }
  238. const_succ_reverse_iterator succ_rbegin() const
  239. { return Successors.rbegin(); }
  240. succ_reverse_iterator succ_rend()
  241. { return Successors.rend(); }
  242. const_succ_reverse_iterator succ_rend() const
  243. { return Successors.rend(); }
  244. unsigned succ_size() const {
  245. return (unsigned)Successors.size();
  246. }
  247. bool succ_empty() const { return Successors.empty(); }
  248. inline iterator_range<pred_iterator> predecessors() {
  249. return make_range(pred_begin(), pred_end());
  250. }
  251. inline iterator_range<const_pred_iterator> predecessors() const {
  252. return make_range(pred_begin(), pred_end());
  253. }
  254. inline iterator_range<succ_iterator> successors() {
  255. return make_range(succ_begin(), succ_end());
  256. }
  257. inline iterator_range<const_succ_iterator> successors() const {
  258. return make_range(succ_begin(), succ_end());
  259. }
  260. // LiveIn management methods.
  261. /// Adds the specified register as a live in. Note that it is an error to add
  262. /// the same register to the same set more than once unless the intention is
  263. /// to call sortUniqueLiveIns after all registers are added.
  264. void addLiveIn(MCRegister PhysReg,
  265. LaneBitmask LaneMask = LaneBitmask::getAll()) {
  266. LiveIns.push_back(RegisterMaskPair(PhysReg, LaneMask));
  267. }
  268. void addLiveIn(const RegisterMaskPair &RegMaskPair) {
  269. LiveIns.push_back(RegMaskPair);
  270. }
  271. /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
  272. /// this than repeatedly calling isLiveIn before calling addLiveIn for every
  273. /// LiveIn insertion.
  274. void sortUniqueLiveIns();
  275. /// Clear live in list.
  276. void clearLiveIns();
  277. /// Add PhysReg as live in to this block, and ensure that there is a copy of
  278. /// PhysReg to a virtual register of class RC. Return the virtual register
  279. /// that is a copy of the live in PhysReg.
  280. unsigned addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC);
  281. /// Remove the specified register from the live in set.
  282. void removeLiveIn(MCPhysReg Reg,
  283. LaneBitmask LaneMask = LaneBitmask::getAll());
  284. /// Return true if the specified register is in the live in set.
  285. bool isLiveIn(MCPhysReg Reg,
  286. LaneBitmask LaneMask = LaneBitmask::getAll()) const;
  287. // Iteration support for live in sets. These sets are kept in sorted
  288. // order by their register number.
  289. using livein_iterator = LiveInVector::const_iterator;
  290. #ifndef NDEBUG
  291. /// Unlike livein_begin, this method does not check that the liveness
  292. /// information is accurate. Still for debug purposes it may be useful
  293. /// to have iterators that won't assert if the liveness information
  294. /// is not current.
  295. livein_iterator livein_begin_dbg() const { return LiveIns.begin(); }
  296. iterator_range<livein_iterator> liveins_dbg() const {
  297. return make_range(livein_begin_dbg(), livein_end());
  298. }
  299. #endif
  300. livein_iterator livein_begin() const;
  301. livein_iterator livein_end() const { return LiveIns.end(); }
  302. bool livein_empty() const { return LiveIns.empty(); }
  303. iterator_range<livein_iterator> liveins() const {
  304. return make_range(livein_begin(), livein_end());
  305. }
  306. /// Remove entry from the livein set and return iterator to the next.
  307. livein_iterator removeLiveIn(livein_iterator I);
  308. /// Get the clobber mask for the start of this basic block. Funclets use this
  309. /// to prevent register allocation across funclet transitions.
  310. const uint32_t *getBeginClobberMask(const TargetRegisterInfo *TRI) const;
  311. /// Get the clobber mask for the end of the basic block.
  312. /// \see getBeginClobberMask()
  313. const uint32_t *getEndClobberMask(const TargetRegisterInfo *TRI) const;
  314. /// Return alignment of the basic block. The alignment is specified as
  315. /// log2(bytes).
  316. unsigned getAlignment() const { return Alignment; }
  317. /// Set alignment of the basic block. The alignment is specified as
  318. /// log2(bytes).
  319. void setAlignment(unsigned Align) { Alignment = Align; }
  320. /// Returns true if the block is a landing pad. That is this basic block is
  321. /// entered via an exception handler.
  322. bool isEHPad() const { return IsEHPad; }
  323. /// Indicates the block is a landing pad. That is this basic block is entered
  324. /// via an exception handler.
  325. void setIsEHPad(bool V = true) { IsEHPad = V; }
  326. bool hasEHPadSuccessor() const;
  327. /// Returns true if this is the entry block of an EH scope, i.e., the block
  328. /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
  329. bool isEHScopeEntry() const { return IsEHScopeEntry; }
  330. /// Indicates if this is the entry block of an EH scope, i.e., the block that
  331. /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
  332. void setIsEHScopeEntry(bool V = true) { IsEHScopeEntry = V; }
  333. /// Returns true if this is the entry block of an EH funclet.
  334. bool isEHFuncletEntry() const { return IsEHFuncletEntry; }
  335. /// Indicates if this is the entry block of an EH funclet.
  336. void setIsEHFuncletEntry(bool V = true) { IsEHFuncletEntry = V; }
  337. /// Returns true if this is the entry block of a cleanup funclet.
  338. bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry; }
  339. /// Indicates if this is the entry block of a cleanup funclet.
  340. void setIsCleanupFuncletEntry(bool V = true) { IsCleanupFuncletEntry = V; }
  341. /// Returns true if it is legal to hoist instructions into this block.
  342. bool isLegalToHoistInto() const;
  343. // Code Layout methods.
  344. /// Move 'this' block before or after the specified block. This only moves
  345. /// the block, it does not modify the CFG or adjust potential fall-throughs at
  346. /// the end of the block.
  347. void moveBefore(MachineBasicBlock *NewAfter);
  348. void moveAfter(MachineBasicBlock *NewBefore);
  349. /// Update the terminator instructions in block to account for changes to the
  350. /// layout. If the block previously used a fallthrough, it may now need a
  351. /// branch, and if it previously used branching it may now be able to use a
  352. /// fallthrough.
  353. void updateTerminator();
  354. // Machine-CFG mutators
  355. /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
  356. /// of Succ is automatically updated. PROB parameter is stored in
  357. /// Probabilities list. The default probability is set as unknown. Mixing
  358. /// known and unknown probabilities in successor list is not allowed. When all
  359. /// successors have unknown probabilities, 1 / N is returned as the
  360. /// probability for each successor, where N is the number of successors.
  361. ///
  362. /// Note that duplicate Machine CFG edges are not allowed.
  363. void addSuccessor(MachineBasicBlock *Succ,
  364. BranchProbability Prob = BranchProbability::getUnknown());
  365. /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
  366. /// of Succ is automatically updated. The probability is not provided because
  367. /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
  368. /// won't be used. Using this interface can save some space.
  369. void addSuccessorWithoutProb(MachineBasicBlock *Succ);
  370. /// Set successor probability of a given iterator.
  371. void setSuccProbability(succ_iterator I, BranchProbability Prob);
  372. /// Normalize probabilities of all successors so that the sum of them becomes
  373. /// one. This is usually done when the current update on this MBB is done, and
  374. /// the sum of its successors' probabilities is not guaranteed to be one. The
  375. /// user is responsible for the correct use of this function.
  376. /// MBB::removeSuccessor() has an option to do this automatically.
  377. void normalizeSuccProbs() {
  378. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  379. }
  380. /// Validate successors' probabilities and check if the sum of them is
  381. /// approximate one. This only works in DEBUG mode.
  382. void validateSuccProbs() const;
  383. /// Remove successor from the successors list of this MachineBasicBlock. The
  384. /// Predecessors list of Succ is automatically updated.
  385. /// If NormalizeSuccProbs is true, then normalize successors' probabilities
  386. /// after the successor is removed.
  387. void removeSuccessor(MachineBasicBlock *Succ,
  388. bool NormalizeSuccProbs = false);
  389. /// Remove specified successor from the successors list of this
  390. /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
  391. /// If NormalizeSuccProbs is true, then normalize successors' probabilities
  392. /// after the successor is removed.
  393. /// Return the iterator to the element after the one removed.
  394. succ_iterator removeSuccessor(succ_iterator I,
  395. bool NormalizeSuccProbs = false);
  396. /// Replace successor OLD with NEW and update probability info.
  397. void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
  398. /// Copy a successor (and any probability info) from original block to this
  399. /// block's. Uses an iterator into the original blocks successors.
  400. ///
  401. /// This is useful when doing a partial clone of successors. Afterward, the
  402. /// probabilities may need to be normalized.
  403. void copySuccessor(MachineBasicBlock *Orig, succ_iterator I);
  404. /// Split the old successor into old plus new and updates the probability
  405. /// info.
  406. void splitSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New,
  407. bool NormalizeSuccProbs = false);
  408. /// Transfers all the successors from MBB to this machine basic block (i.e.,
  409. /// copies all the successors FromMBB and remove all the successors from
  410. /// FromMBB).
  411. void transferSuccessors(MachineBasicBlock *FromMBB);
  412. /// Transfers all the successors, as in transferSuccessors, and update PHI
  413. /// operands in the successor blocks which refer to FromMBB to refer to this.
  414. void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB);
  415. /// Return true if any of the successors have probabilities attached to them.
  416. bool hasSuccessorProbabilities() const { return !Probs.empty(); }
  417. /// Return true if the specified MBB is a predecessor of this block.
  418. bool isPredecessor(const MachineBasicBlock *MBB) const;
  419. /// Return true if the specified MBB is a successor of this block.
  420. bool isSuccessor(const MachineBasicBlock *MBB) const;
  421. /// Return true if the specified MBB will be emitted immediately after this
  422. /// block, such that if this block exits by falling through, control will
  423. /// transfer to the specified MBB. Note that MBB need not be a successor at
  424. /// all, for example if this block ends with an unconditional branch to some
  425. /// other block.
  426. bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
  427. /// Return the fallthrough block if the block can implicitly
  428. /// transfer control to the block after it by falling off the end of
  429. /// it. This should return null if it can reach the block after
  430. /// it, but it uses an explicit branch to do so (e.g., a table
  431. /// jump). Non-null return is a conservative answer.
  432. MachineBasicBlock *getFallThrough();
  433. /// Return true if the block can implicitly transfer control to the
  434. /// block after it by falling off the end of it. This should return
  435. /// false if it can reach the block after it, but it uses an
  436. /// explicit branch to do so (e.g., a table jump). True is a
  437. /// conservative answer.
  438. bool canFallThrough();
  439. /// Returns a pointer to the first instruction in this block that is not a
  440. /// PHINode instruction. When adding instructions to the beginning of the
  441. /// basic block, they should be added before the returned value, not before
  442. /// the first instruction, which might be PHI.
  443. /// Returns end() is there's no non-PHI instruction.
  444. iterator getFirstNonPHI();
  445. /// Return the first instruction in MBB after I that is not a PHI or a label.
  446. /// This is the correct point to insert lowered copies at the beginning of a
  447. /// basic block that must be before any debugging information.
  448. iterator SkipPHIsAndLabels(iterator I);
  449. /// Return the first instruction in MBB after I that is not a PHI, label or
  450. /// debug. This is the correct point to insert copies at the beginning of a
  451. /// basic block.
  452. iterator SkipPHIsLabelsAndDebug(iterator I);
  453. /// Returns an iterator to the first terminator instruction of this basic
  454. /// block. If a terminator does not exist, it returns end().
  455. iterator getFirstTerminator();
  456. const_iterator getFirstTerminator() const {
  457. return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
  458. }
  459. /// Same getFirstTerminator but it ignores bundles and return an
  460. /// instr_iterator instead.
  461. instr_iterator getFirstInstrTerminator();
  462. /// Returns an iterator to the first non-debug instruction in the basic block,
  463. /// or end().
  464. iterator getFirstNonDebugInstr();
  465. const_iterator getFirstNonDebugInstr() const {
  466. return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr();
  467. }
  468. /// Returns an iterator to the last non-debug instruction in the basic block,
  469. /// or end().
  470. iterator getLastNonDebugInstr();
  471. const_iterator getLastNonDebugInstr() const {
  472. return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr();
  473. }
  474. /// Convenience function that returns true if the block ends in a return
  475. /// instruction.
  476. bool isReturnBlock() const {
  477. return !empty() && back().isReturn();
  478. }
  479. /// Convenience function that returns true if the bock ends in a EH scope
  480. /// return instruction.
  481. bool isEHScopeReturnBlock() const {
  482. return !empty() && back().isEHScopeReturn();
  483. }
  484. /// Split the critical edge from this block to the given successor block, and
  485. /// return the newly created block, or null if splitting is not possible.
  486. ///
  487. /// This function updates LiveVariables, MachineDominatorTree, and
  488. /// MachineLoopInfo, as applicable.
  489. MachineBasicBlock *SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P);
  490. /// Check if the edge between this block and the given successor \p
  491. /// Succ, can be split. If this returns true a subsequent call to
  492. /// SplitCriticalEdge is guaranteed to return a valid basic block if
  493. /// no changes occurred in the meantime.
  494. bool canSplitCriticalEdge(const MachineBasicBlock *Succ) const;
  495. void pop_front() { Insts.pop_front(); }
  496. void pop_back() { Insts.pop_back(); }
  497. void push_back(MachineInstr *MI) { Insts.push_back(MI); }
  498. /// Insert MI into the instruction list before I, possibly inside a bundle.
  499. ///
  500. /// If the insertion point is inside a bundle, MI will be added to the bundle,
  501. /// otherwise MI will not be added to any bundle. That means this function
  502. /// alone can't be used to prepend or append instructions to bundles. See
  503. /// MIBundleBuilder::insert() for a more reliable way of doing that.
  504. instr_iterator insert(instr_iterator I, MachineInstr *M);
  505. /// Insert a range of instructions into the instruction list before I.
  506. template<typename IT>
  507. void insert(iterator I, IT S, IT E) {
  508. assert((I == end() || I->getParent() == this) &&
  509. "iterator points outside of basic block");
  510. Insts.insert(I.getInstrIterator(), S, E);
  511. }
  512. /// Insert MI into the instruction list before I.
  513. iterator insert(iterator I, MachineInstr *MI) {
  514. assert((I == end() || I->getParent() == this) &&
  515. "iterator points outside of basic block");
  516. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  517. "Cannot insert instruction with bundle flags");
  518. return Insts.insert(I.getInstrIterator(), MI);
  519. }
  520. /// Insert MI into the instruction list after I.
  521. iterator insertAfter(iterator I, MachineInstr *MI) {
  522. assert((I == end() || I->getParent() == this) &&
  523. "iterator points outside of basic block");
  524. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  525. "Cannot insert instruction with bundle flags");
  526. return Insts.insertAfter(I.getInstrIterator(), MI);
  527. }
  528. /// If I is bundled then insert MI into the instruction list after the end of
  529. /// the bundle, otherwise insert MI immediately after I.
  530. instr_iterator insertAfterBundle(instr_iterator I, MachineInstr *MI) {
  531. assert((I == instr_end() || I->getParent() == this) &&
  532. "iterator points outside of basic block");
  533. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  534. "Cannot insert instruction with bundle flags");
  535. while (I->isBundledWithSucc())
  536. ++I;
  537. return Insts.insertAfter(I, MI);
  538. }
  539. /// Remove an instruction from the instruction list and delete it.
  540. ///
  541. /// If the instruction is part of a bundle, the other instructions in the
  542. /// bundle will still be bundled after removing the single instruction.
  543. instr_iterator erase(instr_iterator I);
  544. /// Remove an instruction from the instruction list and delete it.
  545. ///
  546. /// If the instruction is part of a bundle, the other instructions in the
  547. /// bundle will still be bundled after removing the single instruction.
  548. instr_iterator erase_instr(MachineInstr *I) {
  549. return erase(instr_iterator(I));
  550. }
  551. /// Remove a range of instructions from the instruction list and delete them.
  552. iterator erase(iterator I, iterator E) {
  553. return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
  554. }
  555. /// Remove an instruction or bundle from the instruction list and delete it.
  556. ///
  557. /// If I points to a bundle of instructions, they are all erased.
  558. iterator erase(iterator I) {
  559. return erase(I, std::next(I));
  560. }
  561. /// Remove an instruction from the instruction list and delete it.
  562. ///
  563. /// If I is the head of a bundle of instructions, the whole bundle will be
  564. /// erased.
  565. iterator erase(MachineInstr *I) {
  566. return erase(iterator(I));
  567. }
  568. /// Remove the unbundled instruction from the instruction list without
  569. /// deleting it.
  570. ///
  571. /// This function can not be used to remove bundled instructions, use
  572. /// remove_instr to remove individual instructions from a bundle.
  573. MachineInstr *remove(MachineInstr *I) {
  574. assert(!I->isBundled() && "Cannot remove bundled instructions");
  575. return Insts.remove(instr_iterator(I));
  576. }
  577. /// Remove the possibly bundled instruction from the instruction list
  578. /// without deleting it.
  579. ///
  580. /// If the instruction is part of a bundle, the other instructions in the
  581. /// bundle will still be bundled after removing the single instruction.
  582. MachineInstr *remove_instr(MachineInstr *I);
  583. void clear() {
  584. Insts.clear();
  585. }
  586. /// Take an instruction from MBB 'Other' at the position From, and insert it
  587. /// into this MBB right before 'Where'.
  588. ///
  589. /// If From points to a bundle of instructions, the whole bundle is moved.
  590. void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
  591. // The range splice() doesn't allow noop moves, but this one does.
  592. if (Where != From)
  593. splice(Where, Other, From, std::next(From));
  594. }
  595. /// Take a block of instructions from MBB 'Other' in the range [From, To),
  596. /// and insert them into this MBB right before 'Where'.
  597. ///
  598. /// The instruction at 'Where' must not be included in the range of
  599. /// instructions to move.
  600. void splice(iterator Where, MachineBasicBlock *Other,
  601. iterator From, iterator To) {
  602. Insts.splice(Where.getInstrIterator(), Other->Insts,
  603. From.getInstrIterator(), To.getInstrIterator());
  604. }
  605. /// This method unlinks 'this' from the containing function, and returns it,
  606. /// but does not delete it.
  607. MachineBasicBlock *removeFromParent();
  608. /// This method unlinks 'this' from the containing function and deletes it.
  609. void eraseFromParent();
  610. /// Given a machine basic block that branched to 'Old', change the code and
  611. /// CFG so that it branches to 'New' instead.
  612. void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
  613. /// Update all phi nodes in this basic block to refer to basic block \p New
  614. /// instead of basic block \p Old.
  615. void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New);
  616. /// Various pieces of code can cause excess edges in the CFG to be inserted.
  617. /// If we have proven that MBB can only branch to DestA and DestB, remove any
  618. /// other MBB successors from the CFG. DestA and DestB can be null. Besides
  619. /// DestA and DestB, retain other edges leading to LandingPads (currently
  620. /// there can be only one; we don't check or require that here). Note it is
  621. /// possible that DestA and/or DestB are LandingPads.
  622. bool CorrectExtraCFGEdges(MachineBasicBlock *DestA,
  623. MachineBasicBlock *DestB,
  624. bool IsCond);
  625. /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
  626. /// and DBG_LABEL instructions. Return UnknownLoc if there is none.
  627. DebugLoc findDebugLoc(instr_iterator MBBI);
  628. DebugLoc findDebugLoc(iterator MBBI) {
  629. return findDebugLoc(MBBI.getInstrIterator());
  630. }
  631. /// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE
  632. /// instructions. Return UnknownLoc if there is none.
  633. DebugLoc findPrevDebugLoc(instr_iterator MBBI);
  634. DebugLoc findPrevDebugLoc(iterator MBBI) {
  635. return findPrevDebugLoc(MBBI.getInstrIterator());
  636. }
  637. /// Find and return the merged DebugLoc of the branch instructions of the
  638. /// block. Return UnknownLoc if there is none.
  639. DebugLoc findBranchDebugLoc();
  640. /// Possible outcome of a register liveness query to computeRegisterLiveness()
  641. enum LivenessQueryResult {
  642. LQR_Live, ///< Register is known to be (at least partially) live.
  643. LQR_Dead, ///< Register is known to be fully dead.
  644. LQR_Unknown ///< Register liveness not decidable from local neighborhood.
  645. };
  646. /// Return whether (physical) register \p Reg has been defined and not
  647. /// killed as of just before \p Before.
  648. ///
  649. /// Search is localised to a neighborhood of \p Neighborhood instructions
  650. /// before (searching for defs or kills) and \p Neighborhood instructions
  651. /// after (searching just for defs) \p Before.
  652. ///
  653. /// \p Reg must be a physical register.
  654. LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
  655. unsigned Reg,
  656. const_iterator Before,
  657. unsigned Neighborhood = 10) const;
  658. // Debugging methods.
  659. void dump() const;
  660. void print(raw_ostream &OS, const SlotIndexes * = nullptr,
  661. bool IsStandalone = true) const;
  662. void print(raw_ostream &OS, ModuleSlotTracker &MST,
  663. const SlotIndexes * = nullptr, bool IsStandalone = true) const;
  664. // Printing method used by LoopInfo.
  665. void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
  666. /// MachineBasicBlocks are uniquely numbered at the function level, unless
  667. /// they're not in a MachineFunction yet, in which case this will return -1.
  668. int getNumber() const { return Number; }
  669. void setNumber(int N) { Number = N; }
  670. /// Return the MCSymbol for this basic block.
  671. MCSymbol *getSymbol() const;
  672. Optional<uint64_t> getIrrLoopHeaderWeight() const {
  673. return IrrLoopHeaderWeight;
  674. }
  675. void setIrrLoopHeaderWeight(uint64_t Weight) {
  676. IrrLoopHeaderWeight = Weight;
  677. }
  678. private:
  679. /// Return probability iterator corresponding to the I successor iterator.
  680. probability_iterator getProbabilityIterator(succ_iterator I);
  681. const_probability_iterator
  682. getProbabilityIterator(const_succ_iterator I) const;
  683. friend class MachineBranchProbabilityInfo;
  684. friend class MIPrinter;
  685. /// Return probability of the edge from this block to MBB. This method should
  686. /// NOT be called directly, but by using getEdgeProbability method from
  687. /// MachineBranchProbabilityInfo class.
  688. BranchProbability getSuccProbability(const_succ_iterator Succ) const;
  689. // Methods used to maintain doubly linked list of blocks...
  690. friend struct ilist_callback_traits<MachineBasicBlock>;
  691. // Machine-CFG mutators
  692. /// Add Pred as a predecessor of this MachineBasicBlock. Don't do this
  693. /// unless you know what you're doing, because it doesn't update Pred's
  694. /// successors list. Use Pred->addSuccessor instead.
  695. void addPredecessor(MachineBasicBlock *Pred);
  696. /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
  697. /// unless you know what you're doing, because it doesn't update Pred's
  698. /// successors list. Use Pred->removeSuccessor instead.
  699. void removePredecessor(MachineBasicBlock *Pred);
  700. };
  701. raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
  702. /// Prints a machine basic block reference.
  703. ///
  704. /// The format is:
  705. /// %bb.5 - a machine basic block with MBB.getNumber() == 5.
  706. ///
  707. /// Usage: OS << printMBBReference(MBB) << '\n';
  708. Printable printMBBReference(const MachineBasicBlock &MBB);
  709. // This is useful when building IndexedMaps keyed on basic block pointers.
  710. struct MBB2NumberFunctor {
  711. using argument_type = const MachineBasicBlock *;
  712. unsigned operator()(const MachineBasicBlock *MBB) const {
  713. return MBB->getNumber();
  714. }
  715. };
  716. //===--------------------------------------------------------------------===//
  717. // GraphTraits specializations for machine basic block graphs (machine-CFGs)
  718. //===--------------------------------------------------------------------===//
  719. // Provide specializations of GraphTraits to be able to treat a
  720. // MachineFunction as a graph of MachineBasicBlocks.
  721. //
  722. template <> struct GraphTraits<MachineBasicBlock *> {
  723. using NodeRef = MachineBasicBlock *;
  724. using ChildIteratorType = MachineBasicBlock::succ_iterator;
  725. static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
  726. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  727. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  728. };
  729. template <> struct GraphTraits<const MachineBasicBlock *> {
  730. using NodeRef = const MachineBasicBlock *;
  731. using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
  732. static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
  733. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  734. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  735. };
  736. // Provide specializations of GraphTraits to be able to treat a
  737. // MachineFunction as a graph of MachineBasicBlocks and to walk it
  738. // in inverse order. Inverse order for a function is considered
  739. // to be when traversing the predecessor edges of a MBB
  740. // instead of the successor edges.
  741. //
  742. template <> struct GraphTraits<Inverse<MachineBasicBlock*>> {
  743. using NodeRef = MachineBasicBlock *;
  744. using ChildIteratorType = MachineBasicBlock::pred_iterator;
  745. static NodeRef getEntryNode(Inverse<MachineBasicBlock *> G) {
  746. return G.Graph;
  747. }
  748. static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
  749. static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
  750. };
  751. template <> struct GraphTraits<Inverse<const MachineBasicBlock*>> {
  752. using NodeRef = const MachineBasicBlock *;
  753. using ChildIteratorType = MachineBasicBlock::const_pred_iterator;
  754. static NodeRef getEntryNode(Inverse<const MachineBasicBlock *> G) {
  755. return G.Graph;
  756. }
  757. static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
  758. static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
  759. };
  760. /// MachineInstrSpan provides an interface to get an iteration range
  761. /// containing the instruction it was initialized with, along with all
  762. /// those instructions inserted prior to or following that instruction
  763. /// at some point after the MachineInstrSpan is constructed.
  764. class MachineInstrSpan {
  765. MachineBasicBlock &MBB;
  766. MachineBasicBlock::iterator I, B, E;
  767. public:
  768. MachineInstrSpan(MachineBasicBlock::iterator I, MachineBasicBlock *BB)
  769. : MBB(*BB), I(I), B(I == MBB.begin() ? MBB.end() : std::prev(I)),
  770. E(std::next(I)) {
  771. assert(I == BB->end() || I->getParent() == BB);
  772. }
  773. MachineBasicBlock::iterator begin() {
  774. return B == MBB.end() ? MBB.begin() : std::next(B);
  775. }
  776. MachineBasicBlock::iterator end() { return E; }
  777. bool empty() { return begin() == end(); }
  778. MachineBasicBlock::iterator getInitial() { return I; }
  779. };
  780. /// Increment \p It until it points to a non-debug instruction or to \p End
  781. /// and return the resulting iterator. This function should only be used
  782. /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
  783. /// const_instr_iterator} and the respective reverse iterators.
  784. template<typename IterT>
  785. inline IterT skipDebugInstructionsForward(IterT It, IterT End) {
  786. while (It != End && It->isDebugInstr())
  787. It++;
  788. return It;
  789. }
  790. /// Decrement \p It until it points to a non-debug instruction or to \p Begin
  791. /// and return the resulting iterator. This function should only be used
  792. /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
  793. /// const_instr_iterator} and the respective reverse iterators.
  794. template<class IterT>
  795. inline IterT skipDebugInstructionsBackward(IterT It, IterT Begin) {
  796. while (It != Begin && It->isDebugInstr())
  797. It--;
  798. return It;
  799. }
  800. } // end namespace llvm
  801. #endif // LLVM_CODEGEN_MACHINEBASICBLOCK_H