MachineBasicBlock.h 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/MachineBasicBlock.h -------------------------*- 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. // Collect the sequence of machine instructions for a basic block.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
  18. #define LLVM_CODEGEN_MACHINEBASICBLOCK_H
  19. #include "llvm/ADT/GraphTraits.h"
  20. #include "llvm/ADT/SparseBitVector.h"
  21. #include "llvm/ADT/ilist.h"
  22. #include "llvm/ADT/iterator_range.h"
  23. #include "llvm/CodeGen/MachineInstr.h"
  24. #include "llvm/CodeGen/MachineInstrBundleIterator.h"
  25. #include "llvm/IR/DebugLoc.h"
  26. #include "llvm/MC/LaneBitmask.h"
  27. #include "llvm/Support/BranchProbability.h"
  28. #include <cassert>
  29. #include <cstdint>
  30. #include <iterator>
  31. #include <string>
  32. #include <vector>
  33. namespace llvm {
  34. class BasicBlock;
  35. class MachineFunction;
  36. class MCSymbol;
  37. class ModuleSlotTracker;
  38. class Pass;
  39. class Printable;
  40. class SlotIndexes;
  41. class StringRef;
  42. class raw_ostream;
  43. class LiveIntervals;
  44. class TargetRegisterClass;
  45. class TargetRegisterInfo;
  46. // This structure uniquely identifies a basic block section.
  47. // Possible values are
  48. // {Type: Default, Number: (unsigned)} (These are regular section IDs)
  49. // {Type: Exception, Number: 0} (ExceptionSectionID)
  50. // {Type: Cold, Number: 0} (ColdSectionID)
  51. struct MBBSectionID {
  52. enum SectionType {
  53. Default = 0, // Regular section (these sections are distinguished by the
  54. // Number field).
  55. Exception, // Special section type for exception handling blocks
  56. Cold, // Special section type for cold blocks
  57. } Type;
  58. unsigned Number;
  59. MBBSectionID(unsigned N) : Type(Default), Number(N) {}
  60. // Special unique sections for cold and exception blocks.
  61. const static MBBSectionID ColdSectionID;
  62. const static MBBSectionID ExceptionSectionID;
  63. bool operator==(const MBBSectionID &Other) const {
  64. return Type == Other.Type && Number == Other.Number;
  65. }
  66. bool operator!=(const MBBSectionID &Other) const { return !(*this == Other); }
  67. private:
  68. // This is only used to construct the special cold and exception sections.
  69. MBBSectionID(SectionType T) : Type(T), Number(0) {}
  70. };
  71. template <> struct ilist_traits<MachineInstr> {
  72. private:
  73. friend class MachineBasicBlock; // Set by the owning MachineBasicBlock.
  74. MachineBasicBlock *Parent;
  75. using instr_iterator =
  76. simple_ilist<MachineInstr, ilist_sentinel_tracking<true>>::iterator;
  77. public:
  78. void addNodeToList(MachineInstr *N);
  79. void removeNodeFromList(MachineInstr *N);
  80. void transferNodesFromList(ilist_traits &FromList, instr_iterator First,
  81. instr_iterator Last);
  82. void deleteNode(MachineInstr *MI);
  83. };
  84. class MachineBasicBlock
  85. : public ilist_node_with_parent<MachineBasicBlock, MachineFunction> {
  86. public:
  87. /// Pair of physical register and lane mask.
  88. /// This is not simply a std::pair typedef because the members should be named
  89. /// clearly as they both have an integer type.
  90. struct RegisterMaskPair {
  91. public:
  92. MCPhysReg PhysReg;
  93. LaneBitmask LaneMask;
  94. RegisterMaskPair(MCPhysReg PhysReg, LaneBitmask LaneMask)
  95. : PhysReg(PhysReg), LaneMask(LaneMask) {}
  96. };
  97. private:
  98. using Instructions = ilist<MachineInstr, ilist_sentinel_tracking<true>>;
  99. const BasicBlock *BB;
  100. int Number;
  101. MachineFunction *xParent;
  102. Instructions Insts;
  103. /// Keep track of the predecessor / successor basic blocks.
  104. std::vector<MachineBasicBlock *> Predecessors;
  105. std::vector<MachineBasicBlock *> Successors;
  106. /// Keep track of the probabilities to the successors. This vector has the
  107. /// same order as Successors, or it is empty if we don't use it (disable
  108. /// optimization).
  109. std::vector<BranchProbability> Probs;
  110. using probability_iterator = std::vector<BranchProbability>::iterator;
  111. using const_probability_iterator =
  112. std::vector<BranchProbability>::const_iterator;
  113. std::optional<uint64_t> IrrLoopHeaderWeight;
  114. /// Keep track of the physical registers that are livein of the basicblock.
  115. using LiveInVector = std::vector<RegisterMaskPair>;
  116. LiveInVector LiveIns;
  117. /// Alignment of the basic block. One if the basic block does not need to be
  118. /// aligned.
  119. Align Alignment;
  120. /// Maximum amount of bytes that can be added to align the basic block. If the
  121. /// alignment cannot be reached in this many bytes, no bytes are emitted.
  122. /// Zero to represent no maximum.
  123. unsigned MaxBytesForAlignment = 0;
  124. /// Indicate that this basic block is entered via an exception handler.
  125. bool IsEHPad = false;
  126. /// Indicate that this MachineBasicBlock is referenced somewhere other than
  127. /// as predecessor/successor, a terminator MachineInstr, or a jump table.
  128. bool MachineBlockAddressTaken = false;
  129. /// If this MachineBasicBlock corresponds to an IR-level "blockaddress"
  130. /// constant, this contains a pointer to that block.
  131. BasicBlock *AddressTakenIRBlock = nullptr;
  132. /// Indicate that this basic block needs its symbol be emitted regardless of
  133. /// whether the flow just falls-through to it.
  134. bool LabelMustBeEmitted = false;
  135. /// Indicate that this basic block is the entry block of an EH scope, i.e.,
  136. /// the block that used to have a catchpad or cleanuppad instruction in the
  137. /// LLVM IR.
  138. bool IsEHScopeEntry = false;
  139. /// Indicates if this is a target block of a catchret.
  140. bool IsEHCatchretTarget = false;
  141. /// Indicate that this basic block is the entry block of an EH funclet.
  142. bool IsEHFuncletEntry = false;
  143. /// Indicate that this basic block is the entry block of a cleanup funclet.
  144. bool IsCleanupFuncletEntry = false;
  145. /// Fixed unique ID assigned to this basic block upon creation. Used with
  146. /// basic block sections and basic block labels.
  147. std::optional<unsigned> BBID;
  148. /// With basic block sections, this stores the Section ID of the basic block.
  149. MBBSectionID SectionID{0};
  150. // Indicate that this basic block begins a section.
  151. bool IsBeginSection = false;
  152. // Indicate that this basic block ends a section.
  153. bool IsEndSection = false;
  154. /// Indicate that this basic block is the indirect dest of an INLINEASM_BR.
  155. bool IsInlineAsmBrIndirectTarget = false;
  156. /// since getSymbol is a relatively heavy-weight operation, the symbol
  157. /// is only computed once and is cached.
  158. mutable MCSymbol *CachedMCSymbol = nullptr;
  159. /// Cached MCSymbol for this block (used if IsEHCatchRetTarget).
  160. mutable MCSymbol *CachedEHCatchretMCSymbol = nullptr;
  161. /// Marks the end of the basic block. Used during basic block sections to
  162. /// calculate the size of the basic block, or the BB section ending with it.
  163. mutable MCSymbol *CachedEndMCSymbol = nullptr;
  164. // Intrusive list support
  165. MachineBasicBlock() = default;
  166. explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
  167. ~MachineBasicBlock();
  168. // MachineBasicBlocks are allocated and owned by MachineFunction.
  169. friend class MachineFunction;
  170. public:
  171. /// Return the LLVM basic block that this instance corresponded to originally.
  172. /// Note that this may be NULL if this instance does not correspond directly
  173. /// to an LLVM basic block.
  174. const BasicBlock *getBasicBlock() const { return BB; }
  175. /// Remove the reference to the underlying IR BasicBlock. This is for
  176. /// reduction tools and should generally not be used.
  177. void clearBasicBlock() {
  178. BB = nullptr;
  179. }
  180. /// Return the name of the corresponding LLVM basic block, or an empty string.
  181. StringRef getName() const;
  182. /// Return a formatted string to identify this block and its parent function.
  183. std::string getFullName() const;
  184. /// Test whether this block is used as as something other than the target
  185. /// of a terminator, exception-handling target, or jump table. This is
  186. /// either the result of an IR-level "blockaddress", or some form
  187. /// of target-specific branch lowering.
  188. bool hasAddressTaken() const {
  189. return MachineBlockAddressTaken || AddressTakenIRBlock;
  190. }
  191. /// Test whether this block is used as something other than the target of a
  192. /// terminator, exception-handling target, jump table, or IR blockaddress.
  193. /// For example, its address might be loaded into a register, or
  194. /// stored in some branch table that isn't part of MachineJumpTableInfo.
  195. bool isMachineBlockAddressTaken() const { return MachineBlockAddressTaken; }
  196. /// Test whether this block is the target of an IR BlockAddress. (There can
  197. /// more than one MBB associated with an IR BB where the address is taken.)
  198. bool isIRBlockAddressTaken() const { return AddressTakenIRBlock; }
  199. /// Retrieves the BasicBlock which corresponds to this MachineBasicBlock.
  200. BasicBlock *getAddressTakenIRBlock() const { return AddressTakenIRBlock; }
  201. /// Set this block to indicate that its address is used as something other
  202. /// than the target of a terminator, exception-handling target, jump table,
  203. /// or IR-level "blockaddress".
  204. void setMachineBlockAddressTaken() { MachineBlockAddressTaken = true; }
  205. /// Set this block to reflect that it corresponds to an IR-level basic block
  206. /// with a BlockAddress.
  207. void setAddressTakenIRBlock(BasicBlock *BB) { AddressTakenIRBlock = BB; }
  208. /// Test whether this block must have its label emitted.
  209. bool hasLabelMustBeEmitted() const { return LabelMustBeEmitted; }
  210. /// Set this block to reflect that, regardless how we flow to it, we need
  211. /// its label be emitted.
  212. void setLabelMustBeEmitted() { LabelMustBeEmitted = true; }
  213. /// Return the MachineFunction containing this basic block.
  214. const MachineFunction *getParent() const { return xParent; }
  215. MachineFunction *getParent() { return xParent; }
  216. using instr_iterator = Instructions::iterator;
  217. using const_instr_iterator = Instructions::const_iterator;
  218. using reverse_instr_iterator = Instructions::reverse_iterator;
  219. using const_reverse_instr_iterator = Instructions::const_reverse_iterator;
  220. using iterator = MachineInstrBundleIterator<MachineInstr>;
  221. using const_iterator = MachineInstrBundleIterator<const MachineInstr>;
  222. using reverse_iterator = MachineInstrBundleIterator<MachineInstr, true>;
  223. using const_reverse_iterator =
  224. MachineInstrBundleIterator<const MachineInstr, true>;
  225. unsigned size() const { return (unsigned)Insts.size(); }
  226. bool sizeWithoutDebugLargerThan(unsigned Limit) const;
  227. bool empty() const { return Insts.empty(); }
  228. MachineInstr &instr_front() { return Insts.front(); }
  229. MachineInstr &instr_back() { return Insts.back(); }
  230. const MachineInstr &instr_front() const { return Insts.front(); }
  231. const MachineInstr &instr_back() const { return Insts.back(); }
  232. MachineInstr &front() { return Insts.front(); }
  233. MachineInstr &back() { return *--end(); }
  234. const MachineInstr &front() const { return Insts.front(); }
  235. const MachineInstr &back() const { return *--end(); }
  236. instr_iterator instr_begin() { return Insts.begin(); }
  237. const_instr_iterator instr_begin() const { return Insts.begin(); }
  238. instr_iterator instr_end() { return Insts.end(); }
  239. const_instr_iterator instr_end() const { return Insts.end(); }
  240. reverse_instr_iterator instr_rbegin() { return Insts.rbegin(); }
  241. const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
  242. reverse_instr_iterator instr_rend () { return Insts.rend(); }
  243. const_reverse_instr_iterator instr_rend () const { return Insts.rend(); }
  244. using instr_range = iterator_range<instr_iterator>;
  245. using const_instr_range = iterator_range<const_instr_iterator>;
  246. instr_range instrs() { return instr_range(instr_begin(), instr_end()); }
  247. const_instr_range instrs() const {
  248. return const_instr_range(instr_begin(), instr_end());
  249. }
  250. iterator begin() { return instr_begin(); }
  251. const_iterator begin() const { return instr_begin(); }
  252. iterator end () { return instr_end(); }
  253. const_iterator end () const { return instr_end(); }
  254. reverse_iterator rbegin() {
  255. return reverse_iterator::getAtBundleBegin(instr_rbegin());
  256. }
  257. const_reverse_iterator rbegin() const {
  258. return const_reverse_iterator::getAtBundleBegin(instr_rbegin());
  259. }
  260. reverse_iterator rend() { return reverse_iterator(instr_rend()); }
  261. const_reverse_iterator rend() const {
  262. return const_reverse_iterator(instr_rend());
  263. }
  264. /// Support for MachineInstr::getNextNode().
  265. static Instructions MachineBasicBlock::*getSublistAccess(MachineInstr *) {
  266. return &MachineBasicBlock::Insts;
  267. }
  268. inline iterator_range<iterator> terminators() {
  269. return make_range(getFirstTerminator(), end());
  270. }
  271. inline iterator_range<const_iterator> terminators() const {
  272. return make_range(getFirstTerminator(), end());
  273. }
  274. /// Returns a range that iterates over the phis in the basic block.
  275. inline iterator_range<iterator> phis() {
  276. return make_range(begin(), getFirstNonPHI());
  277. }
  278. inline iterator_range<const_iterator> phis() const {
  279. return const_cast<MachineBasicBlock *>(this)->phis();
  280. }
  281. // Machine-CFG iterators
  282. using pred_iterator = std::vector<MachineBasicBlock *>::iterator;
  283. using const_pred_iterator = std::vector<MachineBasicBlock *>::const_iterator;
  284. using succ_iterator = std::vector<MachineBasicBlock *>::iterator;
  285. using const_succ_iterator = std::vector<MachineBasicBlock *>::const_iterator;
  286. using pred_reverse_iterator =
  287. std::vector<MachineBasicBlock *>::reverse_iterator;
  288. using const_pred_reverse_iterator =
  289. std::vector<MachineBasicBlock *>::const_reverse_iterator;
  290. using succ_reverse_iterator =
  291. std::vector<MachineBasicBlock *>::reverse_iterator;
  292. using const_succ_reverse_iterator =
  293. std::vector<MachineBasicBlock *>::const_reverse_iterator;
  294. pred_iterator pred_begin() { return Predecessors.begin(); }
  295. const_pred_iterator pred_begin() const { return Predecessors.begin(); }
  296. pred_iterator pred_end() { return Predecessors.end(); }
  297. const_pred_iterator pred_end() const { return Predecessors.end(); }
  298. pred_reverse_iterator pred_rbegin()
  299. { return Predecessors.rbegin();}
  300. const_pred_reverse_iterator pred_rbegin() const
  301. { return Predecessors.rbegin();}
  302. pred_reverse_iterator pred_rend()
  303. { return Predecessors.rend(); }
  304. const_pred_reverse_iterator pred_rend() const
  305. { return Predecessors.rend(); }
  306. unsigned pred_size() const {
  307. return (unsigned)Predecessors.size();
  308. }
  309. bool pred_empty() const { return Predecessors.empty(); }
  310. succ_iterator succ_begin() { return Successors.begin(); }
  311. const_succ_iterator succ_begin() const { return Successors.begin(); }
  312. succ_iterator succ_end() { return Successors.end(); }
  313. const_succ_iterator succ_end() const { return Successors.end(); }
  314. succ_reverse_iterator succ_rbegin()
  315. { return Successors.rbegin(); }
  316. const_succ_reverse_iterator succ_rbegin() const
  317. { return Successors.rbegin(); }
  318. succ_reverse_iterator succ_rend()
  319. { return Successors.rend(); }
  320. const_succ_reverse_iterator succ_rend() const
  321. { return Successors.rend(); }
  322. unsigned succ_size() const {
  323. return (unsigned)Successors.size();
  324. }
  325. bool succ_empty() const { return Successors.empty(); }
  326. inline iterator_range<pred_iterator> predecessors() {
  327. return make_range(pred_begin(), pred_end());
  328. }
  329. inline iterator_range<const_pred_iterator> predecessors() const {
  330. return make_range(pred_begin(), pred_end());
  331. }
  332. inline iterator_range<succ_iterator> successors() {
  333. return make_range(succ_begin(), succ_end());
  334. }
  335. inline iterator_range<const_succ_iterator> successors() const {
  336. return make_range(succ_begin(), succ_end());
  337. }
  338. // LiveIn management methods.
  339. /// Adds the specified register as a live in. Note that it is an error to add
  340. /// the same register to the same set more than once unless the intention is
  341. /// to call sortUniqueLiveIns after all registers are added.
  342. void addLiveIn(MCRegister PhysReg,
  343. LaneBitmask LaneMask = LaneBitmask::getAll()) {
  344. LiveIns.push_back(RegisterMaskPair(PhysReg, LaneMask));
  345. }
  346. void addLiveIn(const RegisterMaskPair &RegMaskPair) {
  347. LiveIns.push_back(RegMaskPair);
  348. }
  349. /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
  350. /// this than repeatedly calling isLiveIn before calling addLiveIn for every
  351. /// LiveIn insertion.
  352. void sortUniqueLiveIns();
  353. /// Clear live in list.
  354. void clearLiveIns();
  355. /// Add PhysReg as live in to this block, and ensure that there is a copy of
  356. /// PhysReg to a virtual register of class RC. Return the virtual register
  357. /// that is a copy of the live in PhysReg.
  358. Register addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC);
  359. /// Remove the specified register from the live in set.
  360. void removeLiveIn(MCPhysReg Reg,
  361. LaneBitmask LaneMask = LaneBitmask::getAll());
  362. /// Return true if the specified register is in the live in set.
  363. bool isLiveIn(MCPhysReg Reg,
  364. LaneBitmask LaneMask = LaneBitmask::getAll()) const;
  365. // Iteration support for live in sets. These sets are kept in sorted
  366. // order by their register number.
  367. using livein_iterator = LiveInVector::const_iterator;
  368. /// Unlike livein_begin, this method does not check that the liveness
  369. /// information is accurate. Still for debug purposes it may be useful
  370. /// to have iterators that won't assert if the liveness information
  371. /// is not current.
  372. livein_iterator livein_begin_dbg() const { return LiveIns.begin(); }
  373. iterator_range<livein_iterator> liveins_dbg() const {
  374. return make_range(livein_begin_dbg(), livein_end());
  375. }
  376. livein_iterator livein_begin() const;
  377. livein_iterator livein_end() const { return LiveIns.end(); }
  378. bool livein_empty() const { return LiveIns.empty(); }
  379. iterator_range<livein_iterator> liveins() const {
  380. return make_range(livein_begin(), livein_end());
  381. }
  382. /// Remove entry from the livein set and return iterator to the next.
  383. livein_iterator removeLiveIn(livein_iterator I);
  384. class liveout_iterator {
  385. public:
  386. using iterator_category = std::input_iterator_tag;
  387. using difference_type = std::ptrdiff_t;
  388. using value_type = RegisterMaskPair;
  389. using pointer = const RegisterMaskPair *;
  390. using reference = const RegisterMaskPair &;
  391. liveout_iterator(const MachineBasicBlock &MBB, MCPhysReg ExceptionPointer,
  392. MCPhysReg ExceptionSelector, bool End)
  393. : ExceptionPointer(ExceptionPointer),
  394. ExceptionSelector(ExceptionSelector), BlockI(MBB.succ_begin()),
  395. BlockEnd(MBB.succ_end()) {
  396. if (End)
  397. BlockI = BlockEnd;
  398. else if (BlockI != BlockEnd) {
  399. LiveRegI = (*BlockI)->livein_begin();
  400. if (!advanceToValidPosition())
  401. return;
  402. if (LiveRegI->PhysReg == ExceptionPointer ||
  403. LiveRegI->PhysReg == ExceptionSelector)
  404. ++(*this);
  405. }
  406. }
  407. liveout_iterator &operator++() {
  408. do {
  409. ++LiveRegI;
  410. if (!advanceToValidPosition())
  411. return *this;
  412. } while ((*BlockI)->isEHPad() &&
  413. (LiveRegI->PhysReg == ExceptionPointer ||
  414. LiveRegI->PhysReg == ExceptionSelector));
  415. return *this;
  416. }
  417. liveout_iterator operator++(int) {
  418. liveout_iterator Tmp = *this;
  419. ++(*this);
  420. return Tmp;
  421. }
  422. reference operator*() const {
  423. return *LiveRegI;
  424. }
  425. pointer operator->() const {
  426. return &*LiveRegI;
  427. }
  428. bool operator==(const liveout_iterator &RHS) const {
  429. if (BlockI != BlockEnd)
  430. return BlockI == RHS.BlockI && LiveRegI == RHS.LiveRegI;
  431. return RHS.BlockI == BlockEnd;
  432. }
  433. bool operator!=(const liveout_iterator &RHS) const {
  434. return !(*this == RHS);
  435. }
  436. private:
  437. bool advanceToValidPosition() {
  438. if (LiveRegI != (*BlockI)->livein_end())
  439. return true;
  440. do {
  441. ++BlockI;
  442. } while (BlockI != BlockEnd && (*BlockI)->livein_empty());
  443. if (BlockI == BlockEnd)
  444. return false;
  445. LiveRegI = (*BlockI)->livein_begin();
  446. return true;
  447. }
  448. MCPhysReg ExceptionPointer, ExceptionSelector;
  449. const_succ_iterator BlockI;
  450. const_succ_iterator BlockEnd;
  451. livein_iterator LiveRegI;
  452. };
  453. /// Iterator scanning successor basic blocks' liveins to determine the
  454. /// registers potentially live at the end of this block. There may be
  455. /// duplicates or overlapping registers in the list returned.
  456. liveout_iterator liveout_begin() const;
  457. liveout_iterator liveout_end() const {
  458. return liveout_iterator(*this, 0, 0, true);
  459. }
  460. iterator_range<liveout_iterator> liveouts() const {
  461. return make_range(liveout_begin(), liveout_end());
  462. }
  463. /// Get the clobber mask for the start of this basic block. Funclets use this
  464. /// to prevent register allocation across funclet transitions.
  465. const uint32_t *getBeginClobberMask(const TargetRegisterInfo *TRI) const;
  466. /// Get the clobber mask for the end of the basic block.
  467. /// \see getBeginClobberMask()
  468. const uint32_t *getEndClobberMask(const TargetRegisterInfo *TRI) const;
  469. /// Return alignment of the basic block.
  470. Align getAlignment() const { return Alignment; }
  471. /// Set alignment of the basic block.
  472. void setAlignment(Align A) { Alignment = A; }
  473. void setAlignment(Align A, unsigned MaxBytes) {
  474. setAlignment(A);
  475. setMaxBytesForAlignment(MaxBytes);
  476. }
  477. /// Return the maximum amount of padding allowed for aligning the basic block.
  478. unsigned getMaxBytesForAlignment() const { return MaxBytesForAlignment; }
  479. /// Set the maximum amount of padding allowed for aligning the basic block
  480. void setMaxBytesForAlignment(unsigned MaxBytes) {
  481. MaxBytesForAlignment = MaxBytes;
  482. }
  483. /// Returns true if the block is a landing pad. That is this basic block is
  484. /// entered via an exception handler.
  485. bool isEHPad() const { return IsEHPad; }
  486. /// Indicates the block is a landing pad. That is this basic block is entered
  487. /// via an exception handler.
  488. void setIsEHPad(bool V = true) { IsEHPad = V; }
  489. bool hasEHPadSuccessor() const;
  490. /// Returns true if this is the entry block of the function.
  491. bool isEntryBlock() const;
  492. /// Returns true if this is the entry block of an EH scope, i.e., the block
  493. /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
  494. bool isEHScopeEntry() const { return IsEHScopeEntry; }
  495. /// Indicates if this is the entry block of an EH scope, i.e., the block that
  496. /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
  497. void setIsEHScopeEntry(bool V = true) { IsEHScopeEntry = V; }
  498. /// Returns true if this is a target block of a catchret.
  499. bool isEHCatchretTarget() const { return IsEHCatchretTarget; }
  500. /// Indicates if this is a target block of a catchret.
  501. void setIsEHCatchretTarget(bool V = true) { IsEHCatchretTarget = V; }
  502. /// Returns true if this is the entry block of an EH funclet.
  503. bool isEHFuncletEntry() const { return IsEHFuncletEntry; }
  504. /// Indicates if this is the entry block of an EH funclet.
  505. void setIsEHFuncletEntry(bool V = true) { IsEHFuncletEntry = V; }
  506. /// Returns true if this is the entry block of a cleanup funclet.
  507. bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry; }
  508. /// Indicates if this is the entry block of a cleanup funclet.
  509. void setIsCleanupFuncletEntry(bool V = true) { IsCleanupFuncletEntry = V; }
  510. /// Returns true if this block begins any section.
  511. bool isBeginSection() const { return IsBeginSection; }
  512. /// Returns true if this block ends any section.
  513. bool isEndSection() const { return IsEndSection; }
  514. void setIsBeginSection(bool V = true) { IsBeginSection = V; }
  515. void setIsEndSection(bool V = true) { IsEndSection = V; }
  516. std::optional<unsigned> getBBID() const { return BBID; }
  517. /// Returns the BBID of the block when BBAddrMapVersion >= 2, otherwise
  518. /// returns `MachineBasicBlock::Number`.
  519. /// TODO: Remove this function when version 1 is deprecated and replace its
  520. /// uses with `getBBID()`.
  521. unsigned getBBIDOrNumber() const;
  522. /// Returns the section ID of this basic block.
  523. MBBSectionID getSectionID() const { return SectionID; }
  524. /// Returns the unique section ID number of this basic block.
  525. unsigned getSectionIDNum() const {
  526. return ((unsigned)MBBSectionID::SectionType::Cold) -
  527. ((unsigned)SectionID.Type) + SectionID.Number;
  528. }
  529. /// Sets the fixed BBID of this basic block.
  530. void setBBID(unsigned V) {
  531. assert(!BBID.has_value() && "Cannot change BBID.");
  532. BBID = V;
  533. }
  534. /// Sets the section ID for this basic block.
  535. void setSectionID(MBBSectionID V) { SectionID = V; }
  536. /// Returns the MCSymbol marking the end of this basic block.
  537. MCSymbol *getEndSymbol() const;
  538. /// Returns true if this block may have an INLINEASM_BR (overestimate, by
  539. /// checking if any of the successors are indirect targets of any inlineasm_br
  540. /// in the function).
  541. bool mayHaveInlineAsmBr() const;
  542. /// Returns true if this is the indirect dest of an INLINEASM_BR.
  543. bool isInlineAsmBrIndirectTarget() const {
  544. return IsInlineAsmBrIndirectTarget;
  545. }
  546. /// Indicates if this is the indirect dest of an INLINEASM_BR.
  547. void setIsInlineAsmBrIndirectTarget(bool V = true) {
  548. IsInlineAsmBrIndirectTarget = V;
  549. }
  550. /// Returns true if it is legal to hoist instructions into this block.
  551. bool isLegalToHoistInto() const;
  552. // Code Layout methods.
  553. /// Move 'this' block before or after the specified block. This only moves
  554. /// the block, it does not modify the CFG or adjust potential fall-throughs at
  555. /// the end of the block.
  556. void moveBefore(MachineBasicBlock *NewAfter);
  557. void moveAfter(MachineBasicBlock *NewBefore);
  558. /// Returns true if this and MBB belong to the same section.
  559. bool sameSection(const MachineBasicBlock *MBB) const {
  560. return getSectionID() == MBB->getSectionID();
  561. }
  562. /// Update the terminator instructions in block to account for changes to
  563. /// block layout which may have been made. PreviousLayoutSuccessor should be
  564. /// set to the block which may have been used as fallthrough before the block
  565. /// layout was modified. If the block previously fell through to that block,
  566. /// it may now need a branch. If it previously branched to another block, it
  567. /// may now be able to fallthrough to the current layout successor.
  568. void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor);
  569. // Machine-CFG mutators
  570. /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
  571. /// of Succ is automatically updated. PROB parameter is stored in
  572. /// Probabilities list. The default probability is set as unknown. Mixing
  573. /// known and unknown probabilities in successor list is not allowed. When all
  574. /// successors have unknown probabilities, 1 / N is returned as the
  575. /// probability for each successor, where N is the number of successors.
  576. ///
  577. /// Note that duplicate Machine CFG edges are not allowed.
  578. void addSuccessor(MachineBasicBlock *Succ,
  579. BranchProbability Prob = BranchProbability::getUnknown());
  580. /// Add Succ as a successor of this MachineBasicBlock. The Predecessors list
  581. /// of Succ is automatically updated. The probability is not provided because
  582. /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
  583. /// won't be used. Using this interface can save some space.
  584. void addSuccessorWithoutProb(MachineBasicBlock *Succ);
  585. /// Set successor probability of a given iterator.
  586. void setSuccProbability(succ_iterator I, BranchProbability Prob);
  587. /// Normalize probabilities of all successors so that the sum of them becomes
  588. /// one. This is usually done when the current update on this MBB is done, and
  589. /// the sum of its successors' probabilities is not guaranteed to be one. The
  590. /// user is responsible for the correct use of this function.
  591. /// MBB::removeSuccessor() has an option to do this automatically.
  592. void normalizeSuccProbs() {
  593. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  594. }
  595. /// Validate successors' probabilities and check if the sum of them is
  596. /// approximate one. This only works in DEBUG mode.
  597. void validateSuccProbs() const;
  598. /// Remove successor from the successors list of this MachineBasicBlock. The
  599. /// Predecessors list of Succ is automatically updated.
  600. /// If NormalizeSuccProbs is true, then normalize successors' probabilities
  601. /// after the successor is removed.
  602. void removeSuccessor(MachineBasicBlock *Succ,
  603. bool NormalizeSuccProbs = false);
  604. /// Remove specified successor from the successors list of this
  605. /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
  606. /// If NormalizeSuccProbs is true, then normalize successors' probabilities
  607. /// after the successor is removed.
  608. /// Return the iterator to the element after the one removed.
  609. succ_iterator removeSuccessor(succ_iterator I,
  610. bool NormalizeSuccProbs = false);
  611. /// Replace successor OLD with NEW and update probability info.
  612. void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
  613. /// Copy a successor (and any probability info) from original block to this
  614. /// block's. Uses an iterator into the original blocks successors.
  615. ///
  616. /// This is useful when doing a partial clone of successors. Afterward, the
  617. /// probabilities may need to be normalized.
  618. void copySuccessor(MachineBasicBlock *Orig, succ_iterator I);
  619. /// Split the old successor into old plus new and updates the probability
  620. /// info.
  621. void splitSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New,
  622. bool NormalizeSuccProbs = false);
  623. /// Transfers all the successors from MBB to this machine basic block (i.e.,
  624. /// copies all the successors FromMBB and remove all the successors from
  625. /// FromMBB).
  626. void transferSuccessors(MachineBasicBlock *FromMBB);
  627. /// Transfers all the successors, as in transferSuccessors, and update PHI
  628. /// operands in the successor blocks which refer to FromMBB to refer to this.
  629. void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB);
  630. /// Return true if any of the successors have probabilities attached to them.
  631. bool hasSuccessorProbabilities() const { return !Probs.empty(); }
  632. /// Return true if the specified MBB is a predecessor of this block.
  633. bool isPredecessor(const MachineBasicBlock *MBB) const;
  634. /// Return true if the specified MBB is a successor of this block.
  635. bool isSuccessor(const MachineBasicBlock *MBB) const;
  636. /// Return true if the specified MBB will be emitted immediately after this
  637. /// block, such that if this block exits by falling through, control will
  638. /// transfer to the specified MBB. Note that MBB need not be a successor at
  639. /// all, for example if this block ends with an unconditional branch to some
  640. /// other block.
  641. bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
  642. /// Return the successor of this block if it has a single successor.
  643. /// Otherwise return a null pointer.
  644. ///
  645. const MachineBasicBlock *getSingleSuccessor() const;
  646. MachineBasicBlock *getSingleSuccessor() {
  647. return const_cast<MachineBasicBlock *>(
  648. static_cast<const MachineBasicBlock *>(this)->getSingleSuccessor());
  649. }
  650. /// Return the fallthrough block if the block can implicitly
  651. /// transfer control to the block after it by falling off the end of
  652. /// it. If an explicit branch to the fallthrough block is not allowed,
  653. /// set JumpToFallThrough to be false. Non-null return is a conservative
  654. /// answer.
  655. MachineBasicBlock *getFallThrough(bool JumpToFallThrough = false);
  656. /// Return the fallthrough block if the block can implicitly
  657. /// transfer control to it's successor, whether by a branch or
  658. /// a fallthrough. Non-null return is a conservative answer.
  659. MachineBasicBlock *getLogicalFallThrough() { return getFallThrough(true); }
  660. /// Return true if the block can implicitly transfer control to the
  661. /// block after it by falling off the end of it. This should return
  662. /// false if it can reach the block after it, but it uses an
  663. /// explicit branch to do so (e.g., a table jump). True is a
  664. /// conservative answer.
  665. bool canFallThrough();
  666. /// Returns a pointer to the first instruction in this block that is not a
  667. /// PHINode instruction. When adding instructions to the beginning of the
  668. /// basic block, they should be added before the returned value, not before
  669. /// the first instruction, which might be PHI.
  670. /// Returns end() is there's no non-PHI instruction.
  671. iterator getFirstNonPHI();
  672. /// Return the first instruction in MBB after I that is not a PHI or a label.
  673. /// This is the correct point to insert lowered copies at the beginning of a
  674. /// basic block that must be before any debugging information.
  675. iterator SkipPHIsAndLabels(iterator I);
  676. /// Return the first instruction in MBB after I that is not a PHI, label or
  677. /// debug. This is the correct point to insert copies at the beginning of a
  678. /// basic block.
  679. iterator SkipPHIsLabelsAndDebug(iterator I, bool SkipPseudoOp = true);
  680. /// Returns an iterator to the first terminator instruction of this basic
  681. /// block. If a terminator does not exist, it returns end().
  682. iterator getFirstTerminator();
  683. const_iterator getFirstTerminator() const {
  684. return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
  685. }
  686. /// Same getFirstTerminator but it ignores bundles and return an
  687. /// instr_iterator instead.
  688. instr_iterator getFirstInstrTerminator();
  689. /// Finds the first terminator in a block by scanning forward. This can handle
  690. /// cases in GlobalISel where there may be non-terminator instructions between
  691. /// terminators, for which getFirstTerminator() will not work correctly.
  692. iterator getFirstTerminatorForward();
  693. /// Returns an iterator to the first non-debug instruction in the basic block,
  694. /// or end(). Skip any pseudo probe operation if \c SkipPseudoOp is true.
  695. /// Pseudo probes are like debug instructions which do not turn into real
  696. /// machine code. We try to use the function to skip both debug instructions
  697. /// and pseudo probe operations to avoid API proliferation. This should work
  698. /// most of the time when considering optimizing the rest of code in the
  699. /// block, except for certain cases where pseudo probes are designed to block
  700. /// the optimizations. For example, code merge like optimizations are supposed
  701. /// to be blocked by pseudo probes for better AutoFDO profile quality.
  702. /// Therefore, they should be considered as a valid instruction when this
  703. /// function is called in a context of such optimizations. On the other hand,
  704. /// \c SkipPseudoOp should be true when it's used in optimizations that
  705. /// unlikely hurt profile quality, e.g., without block merging. The default
  706. /// value of \c SkipPseudoOp is set to true to maximize code quality in
  707. /// general, with an explict false value passed in in a few places like branch
  708. /// folding and if-conversion to favor profile quality.
  709. iterator getFirstNonDebugInstr(bool SkipPseudoOp = true);
  710. const_iterator getFirstNonDebugInstr(bool SkipPseudoOp = true) const {
  711. return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr(
  712. SkipPseudoOp);
  713. }
  714. /// Returns an iterator to the last non-debug instruction in the basic block,
  715. /// or end(). Skip any pseudo operation if \c SkipPseudoOp is true.
  716. /// Pseudo probes are like debug instructions which do not turn into real
  717. /// machine code. We try to use the function to skip both debug instructions
  718. /// and pseudo probe operations to avoid API proliferation. This should work
  719. /// most of the time when considering optimizing the rest of code in the
  720. /// block, except for certain cases where pseudo probes are designed to block
  721. /// the optimizations. For example, code merge like optimizations are supposed
  722. /// to be blocked by pseudo probes for better AutoFDO profile quality.
  723. /// Therefore, they should be considered as a valid instruction when this
  724. /// function is called in a context of such optimizations. On the other hand,
  725. /// \c SkipPseudoOp should be true when it's used in optimizations that
  726. /// unlikely hurt profile quality, e.g., without block merging. The default
  727. /// value of \c SkipPseudoOp is set to true to maximize code quality in
  728. /// general, with an explict false value passed in in a few places like branch
  729. /// folding and if-conversion to favor profile quality.
  730. iterator getLastNonDebugInstr(bool SkipPseudoOp = true);
  731. const_iterator getLastNonDebugInstr(bool SkipPseudoOp = true) const {
  732. return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr(
  733. SkipPseudoOp);
  734. }
  735. /// Convenience function that returns true if the block ends in a return
  736. /// instruction.
  737. bool isReturnBlock() const {
  738. return !empty() && back().isReturn();
  739. }
  740. /// Convenience function that returns true if the bock ends in a EH scope
  741. /// return instruction.
  742. bool isEHScopeReturnBlock() const {
  743. return !empty() && back().isEHScopeReturn();
  744. }
  745. /// Split a basic block into 2 pieces at \p SplitPoint. A new block will be
  746. /// inserted after this block, and all instructions after \p SplitInst moved
  747. /// to it (\p SplitInst will be in the original block). If \p LIS is provided,
  748. /// LiveIntervals will be appropriately updated. \return the newly inserted
  749. /// block.
  750. ///
  751. /// If \p UpdateLiveIns is true, this will ensure the live ins list is
  752. /// accurate, including for physreg uses/defs in the original block.
  753. MachineBasicBlock *splitAt(MachineInstr &SplitInst, bool UpdateLiveIns = true,
  754. LiveIntervals *LIS = nullptr);
  755. /// Split the critical edge from this block to the given successor block, and
  756. /// return the newly created block, or null if splitting is not possible.
  757. ///
  758. /// This function updates LiveVariables, MachineDominatorTree, and
  759. /// MachineLoopInfo, as applicable.
  760. MachineBasicBlock *
  761. SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P,
  762. std::vector<SparseBitVector<>> *LiveInSets = nullptr);
  763. /// Check if the edge between this block and the given successor \p
  764. /// Succ, can be split. If this returns true a subsequent call to
  765. /// SplitCriticalEdge is guaranteed to return a valid basic block if
  766. /// no changes occurred in the meantime.
  767. bool canSplitCriticalEdge(const MachineBasicBlock *Succ) const;
  768. void pop_front() { Insts.pop_front(); }
  769. void pop_back() { Insts.pop_back(); }
  770. void push_back(MachineInstr *MI) { Insts.push_back(MI); }
  771. /// Insert MI into the instruction list before I, possibly inside a bundle.
  772. ///
  773. /// If the insertion point is inside a bundle, MI will be added to the bundle,
  774. /// otherwise MI will not be added to any bundle. That means this function
  775. /// alone can't be used to prepend or append instructions to bundles. See
  776. /// MIBundleBuilder::insert() for a more reliable way of doing that.
  777. instr_iterator insert(instr_iterator I, MachineInstr *M);
  778. /// Insert a range of instructions into the instruction list before I.
  779. template<typename IT>
  780. void insert(iterator I, IT S, IT E) {
  781. assert((I == end() || I->getParent() == this) &&
  782. "iterator points outside of basic block");
  783. Insts.insert(I.getInstrIterator(), S, E);
  784. }
  785. /// Insert MI into the instruction list before I.
  786. iterator insert(iterator I, MachineInstr *MI) {
  787. assert((I == end() || I->getParent() == this) &&
  788. "iterator points outside of basic block");
  789. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  790. "Cannot insert instruction with bundle flags");
  791. return Insts.insert(I.getInstrIterator(), MI);
  792. }
  793. /// Insert MI into the instruction list after I.
  794. iterator insertAfter(iterator I, MachineInstr *MI) {
  795. assert((I == end() || I->getParent() == this) &&
  796. "iterator points outside of basic block");
  797. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  798. "Cannot insert instruction with bundle flags");
  799. return Insts.insertAfter(I.getInstrIterator(), MI);
  800. }
  801. /// If I is bundled then insert MI into the instruction list after the end of
  802. /// the bundle, otherwise insert MI immediately after I.
  803. instr_iterator insertAfterBundle(instr_iterator I, MachineInstr *MI) {
  804. assert((I == instr_end() || I->getParent() == this) &&
  805. "iterator points outside of basic block");
  806. assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
  807. "Cannot insert instruction with bundle flags");
  808. while (I->isBundledWithSucc())
  809. ++I;
  810. return Insts.insertAfter(I, MI);
  811. }
  812. /// Remove an instruction from the instruction list and delete it.
  813. ///
  814. /// If the instruction is part of a bundle, the other instructions in the
  815. /// bundle will still be bundled after removing the single instruction.
  816. instr_iterator erase(instr_iterator I);
  817. /// Remove an instruction from the instruction list and delete it.
  818. ///
  819. /// If the instruction is part of a bundle, the other instructions in the
  820. /// bundle will still be bundled after removing the single instruction.
  821. instr_iterator erase_instr(MachineInstr *I) {
  822. return erase(instr_iterator(I));
  823. }
  824. /// Remove a range of instructions from the instruction list and delete them.
  825. iterator erase(iterator I, iterator E) {
  826. return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
  827. }
  828. /// Remove an instruction or bundle from the instruction list and delete it.
  829. ///
  830. /// If I points to a bundle of instructions, they are all erased.
  831. iterator erase(iterator I) {
  832. return erase(I, std::next(I));
  833. }
  834. /// Remove an instruction from the instruction list and delete it.
  835. ///
  836. /// If I is the head of a bundle of instructions, the whole bundle will be
  837. /// erased.
  838. iterator erase(MachineInstr *I) {
  839. return erase(iterator(I));
  840. }
  841. /// Remove the unbundled instruction from the instruction list without
  842. /// deleting it.
  843. ///
  844. /// This function can not be used to remove bundled instructions, use
  845. /// remove_instr to remove individual instructions from a bundle.
  846. MachineInstr *remove(MachineInstr *I) {
  847. assert(!I->isBundled() && "Cannot remove bundled instructions");
  848. return Insts.remove(instr_iterator(I));
  849. }
  850. /// Remove the possibly bundled instruction from the instruction list
  851. /// without deleting it.
  852. ///
  853. /// If the instruction is part of a bundle, the other instructions in the
  854. /// bundle will still be bundled after removing the single instruction.
  855. MachineInstr *remove_instr(MachineInstr *I);
  856. void clear() {
  857. Insts.clear();
  858. }
  859. /// Take an instruction from MBB 'Other' at the position From, and insert it
  860. /// into this MBB right before 'Where'.
  861. ///
  862. /// If From points to a bundle of instructions, the whole bundle is moved.
  863. void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
  864. // The range splice() doesn't allow noop moves, but this one does.
  865. if (Where != From)
  866. splice(Where, Other, From, std::next(From));
  867. }
  868. /// Take a block of instructions from MBB 'Other' in the range [From, To),
  869. /// and insert them into this MBB right before 'Where'.
  870. ///
  871. /// The instruction at 'Where' must not be included in the range of
  872. /// instructions to move.
  873. void splice(iterator Where, MachineBasicBlock *Other,
  874. iterator From, iterator To) {
  875. Insts.splice(Where.getInstrIterator(), Other->Insts,
  876. From.getInstrIterator(), To.getInstrIterator());
  877. }
  878. /// This method unlinks 'this' from the containing function, and returns it,
  879. /// but does not delete it.
  880. MachineBasicBlock *removeFromParent();
  881. /// This method unlinks 'this' from the containing function and deletes it.
  882. void eraseFromParent();
  883. /// Given a machine basic block that branched to 'Old', change the code and
  884. /// CFG so that it branches to 'New' instead.
  885. void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
  886. /// Update all phi nodes in this basic block to refer to basic block \p New
  887. /// instead of basic block \p Old.
  888. void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New);
  889. /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
  890. /// and DBG_LABEL instructions. Return UnknownLoc if there is none.
  891. DebugLoc findDebugLoc(instr_iterator MBBI);
  892. DebugLoc findDebugLoc(iterator MBBI) {
  893. return findDebugLoc(MBBI.getInstrIterator());
  894. }
  895. /// Has exact same behavior as @ref findDebugLoc (it also
  896. /// searches from the first to the last MI of this MBB) except
  897. /// that this takes reverse iterator.
  898. DebugLoc rfindDebugLoc(reverse_instr_iterator MBBI);
  899. DebugLoc rfindDebugLoc(reverse_iterator MBBI) {
  900. return rfindDebugLoc(MBBI.getInstrIterator());
  901. }
  902. /// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE
  903. /// instructions. Return UnknownLoc if there is none.
  904. DebugLoc findPrevDebugLoc(instr_iterator MBBI);
  905. DebugLoc findPrevDebugLoc(iterator MBBI) {
  906. return findPrevDebugLoc(MBBI.getInstrIterator());
  907. }
  908. /// Has exact same behavior as @ref findPrevDebugLoc (it also
  909. /// searches from the last to the first MI of this MBB) except
  910. /// that this takes reverse iterator.
  911. DebugLoc rfindPrevDebugLoc(reverse_instr_iterator MBBI);
  912. DebugLoc rfindPrevDebugLoc(reverse_iterator MBBI) {
  913. return rfindPrevDebugLoc(MBBI.getInstrIterator());
  914. }
  915. /// Find and return the merged DebugLoc of the branch instructions of the
  916. /// block. Return UnknownLoc if there is none.
  917. DebugLoc findBranchDebugLoc();
  918. /// Possible outcome of a register liveness query to computeRegisterLiveness()
  919. enum LivenessQueryResult {
  920. LQR_Live, ///< Register is known to be (at least partially) live.
  921. LQR_Dead, ///< Register is known to be fully dead.
  922. LQR_Unknown ///< Register liveness not decidable from local neighborhood.
  923. };
  924. /// Return whether (physical) register \p Reg has been defined and not
  925. /// killed as of just before \p Before.
  926. ///
  927. /// Search is localised to a neighborhood of \p Neighborhood instructions
  928. /// before (searching for defs or kills) and \p Neighborhood instructions
  929. /// after (searching just for defs) \p Before.
  930. ///
  931. /// \p Reg must be a physical register.
  932. LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
  933. MCRegister Reg,
  934. const_iterator Before,
  935. unsigned Neighborhood = 10) const;
  936. // Debugging methods.
  937. void dump() const;
  938. void print(raw_ostream &OS, const SlotIndexes * = nullptr,
  939. bool IsStandalone = true) const;
  940. void print(raw_ostream &OS, ModuleSlotTracker &MST,
  941. const SlotIndexes * = nullptr, bool IsStandalone = true) const;
  942. enum PrintNameFlag {
  943. PrintNameIr = (1 << 0), ///< Add IR name where available
  944. PrintNameAttributes = (1 << 1), ///< Print attributes
  945. };
  946. void printName(raw_ostream &os, unsigned printNameFlags = PrintNameIr,
  947. ModuleSlotTracker *moduleSlotTracker = nullptr) const;
  948. // Printing method used by LoopInfo.
  949. void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
  950. /// MachineBasicBlocks are uniquely numbered at the function level, unless
  951. /// they're not in a MachineFunction yet, in which case this will return -1.
  952. int getNumber() const { return Number; }
  953. void setNumber(int N) { Number = N; }
  954. /// Return the MCSymbol for this basic block.
  955. MCSymbol *getSymbol() const;
  956. /// Return the EHCatchret Symbol for this basic block.
  957. MCSymbol *getEHCatchretSymbol() const;
  958. std::optional<uint64_t> getIrrLoopHeaderWeight() const {
  959. return IrrLoopHeaderWeight;
  960. }
  961. void setIrrLoopHeaderWeight(uint64_t Weight) {
  962. IrrLoopHeaderWeight = Weight;
  963. }
  964. /// Return probability of the edge from this block to MBB. This method should
  965. /// NOT be called directly, but by using getEdgeProbability method from
  966. /// MachineBranchProbabilityInfo class.
  967. BranchProbability getSuccProbability(const_succ_iterator Succ) const;
  968. private:
  969. /// Return probability iterator corresponding to the I successor iterator.
  970. probability_iterator getProbabilityIterator(succ_iterator I);
  971. const_probability_iterator
  972. getProbabilityIterator(const_succ_iterator I) const;
  973. friend class MachineBranchProbabilityInfo;
  974. friend class MIPrinter;
  975. // Methods used to maintain doubly linked list of blocks...
  976. friend struct ilist_callback_traits<MachineBasicBlock>;
  977. // Machine-CFG mutators
  978. /// Add Pred as a predecessor of this MachineBasicBlock. Don't do this
  979. /// unless you know what you're doing, because it doesn't update Pred's
  980. /// successors list. Use Pred->addSuccessor instead.
  981. void addPredecessor(MachineBasicBlock *Pred);
  982. /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
  983. /// unless you know what you're doing, because it doesn't update Pred's
  984. /// successors list. Use Pred->removeSuccessor instead.
  985. void removePredecessor(MachineBasicBlock *Pred);
  986. };
  987. raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
  988. /// Prints a machine basic block reference.
  989. ///
  990. /// The format is:
  991. /// %bb.5 - a machine basic block with MBB.getNumber() == 5.
  992. ///
  993. /// Usage: OS << printMBBReference(MBB) << '\n';
  994. Printable printMBBReference(const MachineBasicBlock &MBB);
  995. // This is useful when building IndexedMaps keyed on basic block pointers.
  996. struct MBB2NumberFunctor {
  997. using argument_type = const MachineBasicBlock *;
  998. unsigned operator()(const MachineBasicBlock *MBB) const {
  999. return MBB->getNumber();
  1000. }
  1001. };
  1002. //===--------------------------------------------------------------------===//
  1003. // GraphTraits specializations for machine basic block graphs (machine-CFGs)
  1004. //===--------------------------------------------------------------------===//
  1005. // Provide specializations of GraphTraits to be able to treat a
  1006. // MachineFunction as a graph of MachineBasicBlocks.
  1007. //
  1008. template <> struct GraphTraits<MachineBasicBlock *> {
  1009. using NodeRef = MachineBasicBlock *;
  1010. using ChildIteratorType = MachineBasicBlock::succ_iterator;
  1011. static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
  1012. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  1013. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  1014. };
  1015. template <> struct GraphTraits<const MachineBasicBlock *> {
  1016. using NodeRef = const MachineBasicBlock *;
  1017. using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
  1018. static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
  1019. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  1020. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  1021. };
  1022. // Provide specializations of GraphTraits to be able to treat a
  1023. // MachineFunction as a graph of MachineBasicBlocks and to walk it
  1024. // in inverse order. Inverse order for a function is considered
  1025. // to be when traversing the predecessor edges of a MBB
  1026. // instead of the successor edges.
  1027. //
  1028. template <> struct GraphTraits<Inverse<MachineBasicBlock*>> {
  1029. using NodeRef = MachineBasicBlock *;
  1030. using ChildIteratorType = MachineBasicBlock::pred_iterator;
  1031. static NodeRef getEntryNode(Inverse<MachineBasicBlock *> G) {
  1032. return G.Graph;
  1033. }
  1034. static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
  1035. static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
  1036. };
  1037. template <> struct GraphTraits<Inverse<const MachineBasicBlock*>> {
  1038. using NodeRef = const MachineBasicBlock *;
  1039. using ChildIteratorType = MachineBasicBlock::const_pred_iterator;
  1040. static NodeRef getEntryNode(Inverse<const MachineBasicBlock *> G) {
  1041. return G.Graph;
  1042. }
  1043. static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
  1044. static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
  1045. };
  1046. /// MachineInstrSpan provides an interface to get an iteration range
  1047. /// containing the instruction it was initialized with, along with all
  1048. /// those instructions inserted prior to or following that instruction
  1049. /// at some point after the MachineInstrSpan is constructed.
  1050. class MachineInstrSpan {
  1051. MachineBasicBlock &MBB;
  1052. MachineBasicBlock::iterator I, B, E;
  1053. public:
  1054. MachineInstrSpan(MachineBasicBlock::iterator I, MachineBasicBlock *BB)
  1055. : MBB(*BB), I(I), B(I == MBB.begin() ? MBB.end() : std::prev(I)),
  1056. E(std::next(I)) {
  1057. assert(I == BB->end() || I->getParent() == BB);
  1058. }
  1059. MachineBasicBlock::iterator begin() {
  1060. return B == MBB.end() ? MBB.begin() : std::next(B);
  1061. }
  1062. MachineBasicBlock::iterator end() { return E; }
  1063. bool empty() { return begin() == end(); }
  1064. MachineBasicBlock::iterator getInitial() { return I; }
  1065. };
  1066. /// Increment \p It until it points to a non-debug instruction or to \p End
  1067. /// and return the resulting iterator. This function should only be used
  1068. /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
  1069. /// const_instr_iterator} and the respective reverse iterators.
  1070. template <typename IterT>
  1071. inline IterT skipDebugInstructionsForward(IterT It, IterT End,
  1072. bool SkipPseudoOp = true) {
  1073. while (It != End &&
  1074. (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
  1075. ++It;
  1076. return It;
  1077. }
  1078. /// Decrement \p It until it points to a non-debug instruction or to \p Begin
  1079. /// and return the resulting iterator. This function should only be used
  1080. /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
  1081. /// const_instr_iterator} and the respective reverse iterators.
  1082. template <class IterT>
  1083. inline IterT skipDebugInstructionsBackward(IterT It, IterT Begin,
  1084. bool SkipPseudoOp = true) {
  1085. while (It != Begin &&
  1086. (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
  1087. --It;
  1088. return It;
  1089. }
  1090. /// Increment \p It, then continue incrementing it while it points to a debug
  1091. /// instruction. A replacement for std::next.
  1092. template <typename IterT>
  1093. inline IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp = true) {
  1094. return skipDebugInstructionsForward(std::next(It), End, SkipPseudoOp);
  1095. }
  1096. /// Decrement \p It, then continue decrementing it while it points to a debug
  1097. /// instruction. A replacement for std::prev.
  1098. template <typename IterT>
  1099. inline IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp = true) {
  1100. return skipDebugInstructionsBackward(std::prev(It), Begin, SkipPseudoOp);
  1101. }
  1102. /// Construct a range iterator which begins at \p It and moves forwards until
  1103. /// \p End is reached, skipping any debug instructions.
  1104. template <typename IterT>
  1105. inline auto instructionsWithoutDebug(IterT It, IterT End,
  1106. bool SkipPseudoOp = true) {
  1107. return make_filter_range(make_range(It, End), [=](const MachineInstr &MI) {
  1108. return !MI.isDebugInstr() && !(SkipPseudoOp && MI.isPseudoProbe());
  1109. });
  1110. }
  1111. } // end namespace llvm
  1112. #endif // LLVM_CODEGEN_MACHINEBASICBLOCK_H
  1113. #ifdef __GNUC__
  1114. #pragma GCC diagnostic pop
  1115. #endif