MachineFunction.h 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/MachineFunction.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 native machine code for a function. This class contains a list of
  15. // MachineBasicBlock instances that make up the current compiled function.
  16. //
  17. // This class also contains pointers to various classes which hold
  18. // target-specific information about the generated code.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #ifndef LLVM_CODEGEN_MACHINEFUNCTION_H
  22. #define LLVM_CODEGEN_MACHINEFUNCTION_H
  23. #include "llvm/ADT/ArrayRef.h"
  24. #include "llvm/ADT/BitVector.h"
  25. #include "llvm/ADT/DenseMap.h"
  26. #include "llvm/ADT/GraphTraits.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/ilist.h"
  29. #include "llvm/ADT/iterator.h"
  30. #include "llvm/Analysis/EHPersonalities.h"
  31. #include "llvm/CodeGen/MachineBasicBlock.h"
  32. #include "llvm/CodeGen/MachineInstr.h"
  33. #include "llvm/CodeGen/MachineMemOperand.h"
  34. #include "llvm/Support/Allocator.h"
  35. #include "llvm/Support/ArrayRecycler.h"
  36. #include "llvm/Support/AtomicOrdering.h"
  37. #include "llvm/Support/Compiler.h"
  38. #include "llvm/Support/Recycler.h"
  39. #include "llvm/Target/TargetOptions.h"
  40. #include <cassert>
  41. #include <cstdint>
  42. #include <memory>
  43. #include <utility>
  44. #include <vector>
  45. namespace llvm {
  46. class BasicBlock;
  47. class BlockAddress;
  48. class DataLayout;
  49. class DebugLoc;
  50. struct DenormalMode;
  51. class DIExpression;
  52. class DILocalVariable;
  53. class DILocation;
  54. class Function;
  55. class GISelChangeObserver;
  56. class GlobalValue;
  57. class LLVMTargetMachine;
  58. class MachineConstantPool;
  59. class MachineFrameInfo;
  60. class MachineFunction;
  61. class MachineJumpTableInfo;
  62. class MachineModuleInfo;
  63. class MachineRegisterInfo;
  64. class MCContext;
  65. class MCInstrDesc;
  66. class MCSymbol;
  67. class MCSection;
  68. class Pass;
  69. class PseudoSourceValueManager;
  70. class raw_ostream;
  71. class SlotIndexes;
  72. class StringRef;
  73. class TargetRegisterClass;
  74. class TargetSubtargetInfo;
  75. struct WasmEHFuncInfo;
  76. struct WinEHFuncInfo;
  77. template <> struct ilist_alloc_traits<MachineBasicBlock> {
  78. void deleteNode(MachineBasicBlock *MBB);
  79. };
  80. template <> struct ilist_callback_traits<MachineBasicBlock> {
  81. void addNodeToList(MachineBasicBlock* N);
  82. void removeNodeFromList(MachineBasicBlock* N);
  83. template <class Iterator>
  84. void transferNodesFromList(ilist_callback_traits &OldList, Iterator, Iterator) {
  85. assert(this == &OldList && "never transfer MBBs between functions");
  86. }
  87. };
  88. /// MachineFunctionInfo - This class can be derived from and used by targets to
  89. /// hold private target-specific information for each MachineFunction. Objects
  90. /// of type are accessed/created with MF::getInfo and destroyed when the
  91. /// MachineFunction is destroyed.
  92. struct MachineFunctionInfo {
  93. virtual ~MachineFunctionInfo();
  94. /// Factory function: default behavior is to call new using the
  95. /// supplied allocator.
  96. ///
  97. /// This function can be overridden in a derive class.
  98. template<typename Ty>
  99. static Ty *create(BumpPtrAllocator &Allocator, MachineFunction &MF) {
  100. return new (Allocator.Allocate<Ty>()) Ty(MF);
  101. }
  102. };
  103. /// Properties which a MachineFunction may have at a given point in time.
  104. /// Each of these has checking code in the MachineVerifier, and passes can
  105. /// require that a property be set.
  106. class MachineFunctionProperties {
  107. // Possible TODO: Allow targets to extend this (perhaps by allowing the
  108. // constructor to specify the size of the bit vector)
  109. // Possible TODO: Allow requiring the negative (e.g. VRegsAllocated could be
  110. // stated as the negative of "has vregs"
  111. public:
  112. // The properties are stated in "positive" form; i.e. a pass could require
  113. // that the property hold, but not that it does not hold.
  114. // Property descriptions:
  115. // IsSSA: True when the machine function is in SSA form and virtual registers
  116. // have a single def.
  117. // NoPHIs: The machine function does not contain any PHI instruction.
  118. // TracksLiveness: True when tracking register liveness accurately.
  119. // While this property is set, register liveness information in basic block
  120. // live-in lists and machine instruction operands (e.g. implicit defs) is
  121. // accurate, kill flags are conservatively accurate (kill flag correctly
  122. // indicates the last use of a register, an operand without kill flag may or
  123. // may not be the last use of a register). This means it can be used to
  124. // change the code in ways that affect the values in registers, for example
  125. // by the register scavenger.
  126. // When this property is cleared at a very late time, liveness is no longer
  127. // reliable.
  128. // NoVRegs: The machine function does not use any virtual registers.
  129. // Legalized: In GlobalISel: the MachineLegalizer ran and all pre-isel generic
  130. // instructions have been legalized; i.e., all instructions are now one of:
  131. // - generic and always legal (e.g., COPY)
  132. // - target-specific
  133. // - legal pre-isel generic instructions.
  134. // RegBankSelected: In GlobalISel: the RegBankSelect pass ran and all generic
  135. // virtual registers have been assigned to a register bank.
  136. // Selected: In GlobalISel: the InstructionSelect pass ran and all pre-isel
  137. // generic instructions have been eliminated; i.e., all instructions are now
  138. // target-specific or non-pre-isel generic instructions (e.g., COPY).
  139. // Since only pre-isel generic instructions can have generic virtual register
  140. // operands, this also means that all generic virtual registers have been
  141. // constrained to virtual registers (assigned to register classes) and that
  142. // all sizes attached to them have been eliminated.
  143. // TiedOpsRewritten: The twoaddressinstruction pass will set this flag, it
  144. // means that tied-def have been rewritten to meet the RegConstraint.
  145. // FailsVerification: Means that the function is not expected to pass machine
  146. // verification. This can be set by passes that introduce known problems that
  147. // have not been fixed yet.
  148. // TracksDebugUserValues: Without this property enabled, debug instructions
  149. // such as DBG_VALUE are allowed to reference virtual registers even if those
  150. // registers do not have a definition. With the property enabled virtual
  151. // registers must only be used if they have a definition. This property
  152. // allows earlier passes in the pipeline to skip updates of `DBG_VALUE`
  153. // instructions to save compile time.
  154. enum class Property : unsigned {
  155. IsSSA,
  156. NoPHIs,
  157. TracksLiveness,
  158. NoVRegs,
  159. FailedISel,
  160. Legalized,
  161. RegBankSelected,
  162. Selected,
  163. TiedOpsRewritten,
  164. FailsVerification,
  165. TracksDebugUserValues,
  166. LastProperty = TracksDebugUserValues,
  167. };
  168. bool hasProperty(Property P) const {
  169. return Properties[static_cast<unsigned>(P)];
  170. }
  171. MachineFunctionProperties &set(Property P) {
  172. Properties.set(static_cast<unsigned>(P));
  173. return *this;
  174. }
  175. MachineFunctionProperties &reset(Property P) {
  176. Properties.reset(static_cast<unsigned>(P));
  177. return *this;
  178. }
  179. /// Reset all the properties.
  180. MachineFunctionProperties &reset() {
  181. Properties.reset();
  182. return *this;
  183. }
  184. MachineFunctionProperties &set(const MachineFunctionProperties &MFP) {
  185. Properties |= MFP.Properties;
  186. return *this;
  187. }
  188. MachineFunctionProperties &reset(const MachineFunctionProperties &MFP) {
  189. Properties.reset(MFP.Properties);
  190. return *this;
  191. }
  192. // Returns true if all properties set in V (i.e. required by a pass) are set
  193. // in this.
  194. bool verifyRequiredProperties(const MachineFunctionProperties &V) const {
  195. return !V.Properties.test(Properties);
  196. }
  197. /// Print the MachineFunctionProperties in human-readable form.
  198. void print(raw_ostream &OS) const;
  199. private:
  200. BitVector Properties =
  201. BitVector(static_cast<unsigned>(Property::LastProperty)+1);
  202. };
  203. struct SEHHandler {
  204. /// Filter or finally function. Null indicates a catch-all.
  205. const Function *FilterOrFinally;
  206. /// Address of block to recover at. Null for a finally handler.
  207. const BlockAddress *RecoverBA;
  208. };
  209. /// This structure is used to retain landing pad info for the current function.
  210. struct LandingPadInfo {
  211. MachineBasicBlock *LandingPadBlock; // Landing pad block.
  212. SmallVector<MCSymbol *, 1> BeginLabels; // Labels prior to invoke.
  213. SmallVector<MCSymbol *, 1> EndLabels; // Labels after invoke.
  214. SmallVector<SEHHandler, 1> SEHHandlers; // SEH handlers active at this lpad.
  215. MCSymbol *LandingPadLabel = nullptr; // Label at beginning of landing pad.
  216. std::vector<int> TypeIds; // List of type ids (filters negative).
  217. explicit LandingPadInfo(MachineBasicBlock *MBB)
  218. : LandingPadBlock(MBB) {}
  219. };
  220. class LLVM_EXTERNAL_VISIBILITY MachineFunction {
  221. Function &F;
  222. const LLVMTargetMachine &Target;
  223. const TargetSubtargetInfo *STI;
  224. MCContext &Ctx;
  225. MachineModuleInfo &MMI;
  226. // RegInfo - Information about each register in use in the function.
  227. MachineRegisterInfo *RegInfo;
  228. // Used to keep track of target-specific per-machine function information for
  229. // the target implementation.
  230. MachineFunctionInfo *MFInfo;
  231. // Keep track of objects allocated on the stack.
  232. MachineFrameInfo *FrameInfo;
  233. // Keep track of constants which are spilled to memory
  234. MachineConstantPool *ConstantPool;
  235. // Keep track of jump tables for switch instructions
  236. MachineJumpTableInfo *JumpTableInfo;
  237. // Keep track of the function section.
  238. MCSection *Section = nullptr;
  239. // Keeps track of Wasm exception handling related data. This will be null for
  240. // functions that aren't using a wasm EH personality.
  241. WasmEHFuncInfo *WasmEHInfo = nullptr;
  242. // Keeps track of Windows exception handling related data. This will be null
  243. // for functions that aren't using a funclet-based EH personality.
  244. WinEHFuncInfo *WinEHInfo = nullptr;
  245. // Function-level unique numbering for MachineBasicBlocks. When a
  246. // MachineBasicBlock is inserted into a MachineFunction is it automatically
  247. // numbered and this vector keeps track of the mapping from ID's to MBB's.
  248. std::vector<MachineBasicBlock*> MBBNumbering;
  249. // Unary encoding of basic block symbols is used to reduce size of ".strtab".
  250. // Basic block number 'i' gets a prefix of length 'i'. The ith character also
  251. // denotes the type of basic block number 'i'. Return blocks are marked with
  252. // 'r', landing pads with 'l' and regular blocks with 'a'.
  253. std::vector<char> BBSectionsSymbolPrefix;
  254. // Pool-allocate MachineFunction-lifetime and IR objects.
  255. BumpPtrAllocator Allocator;
  256. // Allocation management for instructions in function.
  257. Recycler<MachineInstr> InstructionRecycler;
  258. // Allocation management for operand arrays on instructions.
  259. ArrayRecycler<MachineOperand> OperandRecycler;
  260. // Allocation management for basic blocks in function.
  261. Recycler<MachineBasicBlock> BasicBlockRecycler;
  262. // List of machine basic blocks in function
  263. using BasicBlockListType = ilist<MachineBasicBlock>;
  264. BasicBlockListType BasicBlocks;
  265. /// FunctionNumber - This provides a unique ID for each function emitted in
  266. /// this translation unit.
  267. ///
  268. unsigned FunctionNumber;
  269. /// Alignment - The alignment of the function.
  270. Align Alignment;
  271. /// ExposesReturnsTwice - True if the function calls setjmp or related
  272. /// functions with attribute "returns twice", but doesn't have
  273. /// the attribute itself.
  274. /// This is used to limit optimizations which cannot reason
  275. /// about the control flow of such functions.
  276. bool ExposesReturnsTwice = false;
  277. /// True if the function includes any inline assembly.
  278. bool HasInlineAsm = false;
  279. /// True if any WinCFI instruction have been emitted in this function.
  280. bool HasWinCFI = false;
  281. /// Current high-level properties of the IR of the function (e.g. is in SSA
  282. /// form or whether registers have been allocated)
  283. MachineFunctionProperties Properties;
  284. // Allocation management for pseudo source values.
  285. std::unique_ptr<PseudoSourceValueManager> PSVManager;
  286. /// List of moves done by a function's prolog. Used to construct frame maps
  287. /// by debug and exception handling consumers.
  288. std::vector<MCCFIInstruction> FrameInstructions;
  289. /// List of basic blocks immediately following calls to _setjmp. Used to
  290. /// construct a table of valid longjmp targets for Windows Control Flow Guard.
  291. std::vector<MCSymbol *> LongjmpTargets;
  292. /// List of basic blocks that are the target of catchrets. Used to construct
  293. /// a table of valid targets for Windows EHCont Guard.
  294. std::vector<MCSymbol *> CatchretTargets;
  295. /// \name Exception Handling
  296. /// \{
  297. /// List of LandingPadInfo describing the landing pad information.
  298. std::vector<LandingPadInfo> LandingPads;
  299. /// Map a landing pad's EH symbol to the call site indexes.
  300. DenseMap<MCSymbol*, SmallVector<unsigned, 4>> LPadToCallSiteMap;
  301. /// Map a landing pad to its index.
  302. DenseMap<const MachineBasicBlock *, unsigned> WasmLPadToIndexMap;
  303. /// Map of invoke call site index values to associated begin EH_LABEL.
  304. DenseMap<MCSymbol*, unsigned> CallSiteMap;
  305. /// CodeView label annotations.
  306. std::vector<std::pair<MCSymbol *, MDNode *>> CodeViewAnnotations;
  307. bool CallsEHReturn = false;
  308. bool CallsUnwindInit = false;
  309. bool HasEHCatchret = false;
  310. bool HasEHScopes = false;
  311. bool HasEHFunclets = false;
  312. /// Section Type for basic blocks, only relevant with basic block sections.
  313. BasicBlockSection BBSectionsType = BasicBlockSection::None;
  314. /// List of C++ TypeInfo used.
  315. std::vector<const GlobalValue *> TypeInfos;
  316. /// List of typeids encoding filters used.
  317. std::vector<unsigned> FilterIds;
  318. /// List of the indices in FilterIds corresponding to filter terminators.
  319. std::vector<unsigned> FilterEnds;
  320. EHPersonality PersonalityTypeCache = EHPersonality::Unknown;
  321. /// \}
  322. /// Clear all the members of this MachineFunction, but the ones used
  323. /// to initialize again the MachineFunction.
  324. /// More specifically, this deallocates all the dynamically allocated
  325. /// objects and get rid of all the XXXInfo data structure, but keep
  326. /// unchanged the references to Fn, Target, MMI, and FunctionNumber.
  327. void clear();
  328. /// Allocate and initialize the different members.
  329. /// In particular, the XXXInfo data structure.
  330. /// \pre Fn, Target, MMI, and FunctionNumber are properly set.
  331. void init();
  332. public:
  333. struct VariableDbgInfo {
  334. const DILocalVariable *Var;
  335. const DIExpression *Expr;
  336. // The Slot can be negative for fixed stack objects.
  337. int Slot;
  338. const DILocation *Loc;
  339. VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
  340. int Slot, const DILocation *Loc)
  341. : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {}
  342. };
  343. class Delegate {
  344. virtual void anchor();
  345. public:
  346. virtual ~Delegate() = default;
  347. /// Callback after an insertion. This should not modify the MI directly.
  348. virtual void MF_HandleInsertion(MachineInstr &MI) = 0;
  349. /// Callback before a removal. This should not modify the MI directly.
  350. virtual void MF_HandleRemoval(MachineInstr &MI) = 0;
  351. };
  352. /// Structure used to represent pair of argument number after call lowering
  353. /// and register used to transfer that argument.
  354. /// For now we support only cases when argument is transferred through one
  355. /// register.
  356. struct ArgRegPair {
  357. Register Reg;
  358. uint16_t ArgNo;
  359. ArgRegPair(Register R, unsigned Arg) : Reg(R), ArgNo(Arg) {
  360. assert(Arg < (1 << 16) && "Arg out of range");
  361. }
  362. };
  363. /// Vector of call argument and its forwarding register.
  364. using CallSiteInfo = SmallVector<ArgRegPair, 1>;
  365. using CallSiteInfoImpl = SmallVectorImpl<ArgRegPair>;
  366. private:
  367. Delegate *TheDelegate = nullptr;
  368. GISelChangeObserver *Observer = nullptr;
  369. using CallSiteInfoMap = DenseMap<const MachineInstr *, CallSiteInfo>;
  370. /// Map a call instruction to call site arguments forwarding info.
  371. CallSiteInfoMap CallSitesInfo;
  372. /// A helper function that returns call site info for a give call
  373. /// instruction if debug entry value support is enabled.
  374. CallSiteInfoMap::iterator getCallSiteInfo(const MachineInstr *MI);
  375. // Callbacks for insertion and removal.
  376. void handleInsertion(MachineInstr &MI);
  377. void handleRemoval(MachineInstr &MI);
  378. friend struct ilist_traits<MachineInstr>;
  379. public:
  380. using VariableDbgInfoMapTy = SmallVector<VariableDbgInfo, 4>;
  381. VariableDbgInfoMapTy VariableDbgInfos;
  382. /// A count of how many instructions in the function have had numbers
  383. /// assigned to them. Used for debug value tracking, to determine the
  384. /// next instruction number.
  385. unsigned DebugInstrNumberingCount = 0;
  386. /// Set value of DebugInstrNumberingCount field. Avoid using this unless
  387. /// you're deserializing this data.
  388. void setDebugInstrNumberingCount(unsigned Num);
  389. /// Pair of instruction number and operand number.
  390. using DebugInstrOperandPair = std::pair<unsigned, unsigned>;
  391. /// Replacement definition for a debug instruction reference. Made up of a
  392. /// source instruction / operand pair, destination pair, and a qualifying
  393. /// subregister indicating what bits in the operand make up the substitution.
  394. // For example, a debug user
  395. /// of %1:
  396. /// %0:gr32 = someinst, debug-instr-number 1
  397. /// %1:gr16 = %0.some_16_bit_subreg, debug-instr-number 2
  398. /// Would receive the substitution {{2, 0}, {1, 0}, $subreg}, where $subreg is
  399. /// the subregister number for some_16_bit_subreg.
  400. class DebugSubstitution {
  401. public:
  402. DebugInstrOperandPair Src; ///< Source instruction / operand pair.
  403. DebugInstrOperandPair Dest; ///< Replacement instruction / operand pair.
  404. unsigned Subreg; ///< Qualifier for which part of Dest is read.
  405. DebugSubstitution(const DebugInstrOperandPair &Src,
  406. const DebugInstrOperandPair &Dest, unsigned Subreg)
  407. : Src(Src), Dest(Dest), Subreg(Subreg) {}
  408. /// Order only by source instruction / operand pair: there should never
  409. /// be duplicate entries for the same source in any collection.
  410. bool operator<(const DebugSubstitution &Other) const {
  411. return Src < Other.Src;
  412. }
  413. };
  414. /// Debug value substitutions: a collection of DebugSubstitution objects,
  415. /// recording changes in where a value is defined. For example, when one
  416. /// instruction is substituted for another. Keeping a record allows recovery
  417. /// of variable locations after compilation finishes.
  418. SmallVector<DebugSubstitution, 8> DebugValueSubstitutions;
  419. /// Location of a PHI instruction that is also a debug-info variable value,
  420. /// for the duration of register allocation. Loaded by the PHI-elimination
  421. /// pass, and emitted as DBG_PHI instructions during VirtRegRewriter, with
  422. /// maintenance applied by intermediate passes that edit registers (such as
  423. /// coalescing and the allocator passes).
  424. class DebugPHIRegallocPos {
  425. public:
  426. MachineBasicBlock *MBB; ///< Block where this PHI was originally located.
  427. Register Reg; ///< VReg where the control-flow-merge happens.
  428. unsigned SubReg; ///< Optional subreg qualifier within Reg.
  429. DebugPHIRegallocPos(MachineBasicBlock *MBB, Register Reg, unsigned SubReg)
  430. : MBB(MBB), Reg(Reg), SubReg(SubReg) {}
  431. };
  432. /// Map of debug instruction numbers to the position of their PHI instructions
  433. /// during register allocation. See DebugPHIRegallocPos.
  434. DenseMap<unsigned, DebugPHIRegallocPos> DebugPHIPositions;
  435. /// Create a substitution between one <instr,operand> value to a different,
  436. /// new value.
  437. void makeDebugValueSubstitution(DebugInstrOperandPair, DebugInstrOperandPair,
  438. unsigned SubReg = 0);
  439. /// Create substitutions for any tracked values in \p Old, to point at
  440. /// \p New. Needed when we re-create an instruction during optimization,
  441. /// which has the same signature (i.e., def operands in the same place) but
  442. /// a modified instruction type, flags, or otherwise. An example: X86 moves
  443. /// are sometimes transformed into equivalent LEAs.
  444. /// If the two instructions are not the same opcode, limit which operands to
  445. /// examine for substitutions to the first N operands by setting
  446. /// \p MaxOperand.
  447. void substituteDebugValuesForInst(const MachineInstr &Old, MachineInstr &New,
  448. unsigned MaxOperand = UINT_MAX);
  449. /// Find the underlying defining instruction / operand for a COPY instruction
  450. /// while in SSA form. Copies do not actually define values -- they move them
  451. /// between registers. Labelling a COPY-like instruction with an instruction
  452. /// number is to be avoided as it makes value numbers non-unique later in
  453. /// compilation. This method follows the definition chain for any sequence of
  454. /// COPY-like instructions to find whatever non-COPY-like instruction defines
  455. /// the copied value; or for parameters, creates a DBG_PHI on entry.
  456. /// May insert instructions into the entry block!
  457. /// \p MI The copy-like instruction to salvage.
  458. /// \returns An instruction/operand pair identifying the defining value.
  459. DebugInstrOperandPair salvageCopySSA(MachineInstr &MI);
  460. /// Finalise any partially emitted debug instructions. These are DBG_INSTR_REF
  461. /// instructions where we only knew the vreg of the value they use, not the
  462. /// instruction that defines that vreg. Once isel finishes, we should have
  463. /// enough information for every DBG_INSTR_REF to point at an instruction
  464. /// (or DBG_PHI).
  465. void finalizeDebugInstrRefs();
  466. /// Returns true if the function's variable locations should be tracked with
  467. /// instruction referencing.
  468. bool useDebugInstrRef() const;
  469. /// A reserved operand number representing the instructions memory operand,
  470. /// for instructions that have a stack spill fused into them.
  471. const static unsigned int DebugOperandMemNumber;
  472. MachineFunction(Function &F, const LLVMTargetMachine &Target,
  473. const TargetSubtargetInfo &STI, unsigned FunctionNum,
  474. MachineModuleInfo &MMI);
  475. MachineFunction(const MachineFunction &) = delete;
  476. MachineFunction &operator=(const MachineFunction &) = delete;
  477. ~MachineFunction();
  478. /// Reset the instance as if it was just created.
  479. void reset() {
  480. clear();
  481. init();
  482. }
  483. /// Reset the currently registered delegate - otherwise assert.
  484. void resetDelegate(Delegate *delegate) {
  485. assert(TheDelegate == delegate &&
  486. "Only the current delegate can perform reset!");
  487. TheDelegate = nullptr;
  488. }
  489. /// Set the delegate. resetDelegate must be called before attempting
  490. /// to set.
  491. void setDelegate(Delegate *delegate) {
  492. assert(delegate && !TheDelegate &&
  493. "Attempted to set delegate to null, or to change it without "
  494. "first resetting it!");
  495. TheDelegate = delegate;
  496. }
  497. void setObserver(GISelChangeObserver *O) { Observer = O; }
  498. GISelChangeObserver *getObserver() const { return Observer; }
  499. MachineModuleInfo &getMMI() const { return MMI; }
  500. MCContext &getContext() const { return Ctx; }
  501. /// Returns the Section this function belongs to.
  502. MCSection *getSection() const { return Section; }
  503. /// Indicates the Section this function belongs to.
  504. void setSection(MCSection *S) { Section = S; }
  505. PseudoSourceValueManager &getPSVManager() const { return *PSVManager; }
  506. /// Return the DataLayout attached to the Module associated to this MF.
  507. const DataLayout &getDataLayout() const;
  508. /// Return the LLVM function that this machine code represents
  509. Function &getFunction() { return F; }
  510. /// Return the LLVM function that this machine code represents
  511. const Function &getFunction() const { return F; }
  512. /// getName - Return the name of the corresponding LLVM function.
  513. StringRef getName() const;
  514. /// getFunctionNumber - Return a unique ID for the current function.
  515. unsigned getFunctionNumber() const { return FunctionNumber; }
  516. /// Returns true if this function has basic block sections enabled.
  517. bool hasBBSections() const {
  518. return (BBSectionsType == BasicBlockSection::All ||
  519. BBSectionsType == BasicBlockSection::List ||
  520. BBSectionsType == BasicBlockSection::Preset);
  521. }
  522. /// Returns true if basic block labels are to be generated for this function.
  523. bool hasBBLabels() const {
  524. return BBSectionsType == BasicBlockSection::Labels;
  525. }
  526. void setBBSectionsType(BasicBlockSection V) { BBSectionsType = V; }
  527. /// Assign IsBeginSection IsEndSection fields for basic blocks in this
  528. /// function.
  529. void assignBeginEndSections();
  530. /// getTarget - Return the target machine this machine code is compiled with
  531. const LLVMTargetMachine &getTarget() const { return Target; }
  532. /// getSubtarget - Return the subtarget for which this machine code is being
  533. /// compiled.
  534. const TargetSubtargetInfo &getSubtarget() const { return *STI; }
  535. /// getSubtarget - This method returns a pointer to the specified type of
  536. /// TargetSubtargetInfo. In debug builds, it verifies that the object being
  537. /// returned is of the correct type.
  538. template<typename STC> const STC &getSubtarget() const {
  539. return *static_cast<const STC *>(STI);
  540. }
  541. /// getRegInfo - Return information about the registers currently in use.
  542. MachineRegisterInfo &getRegInfo() { return *RegInfo; }
  543. const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
  544. /// getFrameInfo - Return the frame info object for the current function.
  545. /// This object contains information about objects allocated on the stack
  546. /// frame of the current function in an abstract way.
  547. MachineFrameInfo &getFrameInfo() { return *FrameInfo; }
  548. const MachineFrameInfo &getFrameInfo() const { return *FrameInfo; }
  549. /// getJumpTableInfo - Return the jump table info object for the current
  550. /// function. This object contains information about jump tables in the
  551. /// current function. If the current function has no jump tables, this will
  552. /// return null.
  553. const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
  554. MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
  555. /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
  556. /// does already exist, allocate one.
  557. MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
  558. /// getConstantPool - Return the constant pool object for the current
  559. /// function.
  560. MachineConstantPool *getConstantPool() { return ConstantPool; }
  561. const MachineConstantPool *getConstantPool() const { return ConstantPool; }
  562. /// getWasmEHFuncInfo - Return information about how the current function uses
  563. /// Wasm exception handling. Returns null for functions that don't use wasm
  564. /// exception handling.
  565. const WasmEHFuncInfo *getWasmEHFuncInfo() const { return WasmEHInfo; }
  566. WasmEHFuncInfo *getWasmEHFuncInfo() { return WasmEHInfo; }
  567. /// getWinEHFuncInfo - Return information about how the current function uses
  568. /// Windows exception handling. Returns null for functions that don't use
  569. /// funclets for exception handling.
  570. const WinEHFuncInfo *getWinEHFuncInfo() const { return WinEHInfo; }
  571. WinEHFuncInfo *getWinEHFuncInfo() { return WinEHInfo; }
  572. /// getAlignment - Return the alignment of the function.
  573. Align getAlignment() const { return Alignment; }
  574. /// setAlignment - Set the alignment of the function.
  575. void setAlignment(Align A) { Alignment = A; }
  576. /// ensureAlignment - Make sure the function is at least A bytes aligned.
  577. void ensureAlignment(Align A) {
  578. if (Alignment < A)
  579. Alignment = A;
  580. }
  581. /// exposesReturnsTwice - Returns true if the function calls setjmp or
  582. /// any other similar functions with attribute "returns twice" without
  583. /// having the attribute itself.
  584. bool exposesReturnsTwice() const {
  585. return ExposesReturnsTwice;
  586. }
  587. /// setCallsSetJmp - Set a flag that indicates if there's a call to
  588. /// a "returns twice" function.
  589. void setExposesReturnsTwice(bool B) {
  590. ExposesReturnsTwice = B;
  591. }
  592. /// Returns true if the function contains any inline assembly.
  593. bool hasInlineAsm() const {
  594. return HasInlineAsm;
  595. }
  596. /// Set a flag that indicates that the function contains inline assembly.
  597. void setHasInlineAsm(bool B) {
  598. HasInlineAsm = B;
  599. }
  600. bool hasWinCFI() const {
  601. return HasWinCFI;
  602. }
  603. void setHasWinCFI(bool v) { HasWinCFI = v; }
  604. /// True if this function needs frame moves for debug or exceptions.
  605. bool needsFrameMoves() const;
  606. /// Get the function properties
  607. const MachineFunctionProperties &getProperties() const { return Properties; }
  608. MachineFunctionProperties &getProperties() { return Properties; }
  609. /// getInfo - Keep track of various per-function pieces of information for
  610. /// backends that would like to do so.
  611. ///
  612. template<typename Ty>
  613. Ty *getInfo() {
  614. if (!MFInfo)
  615. MFInfo = Ty::template create<Ty>(Allocator, *this);
  616. return static_cast<Ty*>(MFInfo);
  617. }
  618. template<typename Ty>
  619. const Ty *getInfo() const {
  620. return const_cast<MachineFunction*>(this)->getInfo<Ty>();
  621. }
  622. /// Returns the denormal handling type for the default rounding mode of the
  623. /// function.
  624. DenormalMode getDenormalMode(const fltSemantics &FPType) const;
  625. /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
  626. /// are inserted into the machine function. The block number for a machine
  627. /// basic block can be found by using the MBB::getNumber method, this method
  628. /// provides the inverse mapping.
  629. MachineBasicBlock *getBlockNumbered(unsigned N) const {
  630. assert(N < MBBNumbering.size() && "Illegal block number");
  631. assert(MBBNumbering[N] && "Block was removed from the machine function!");
  632. return MBBNumbering[N];
  633. }
  634. /// Should we be emitting segmented stack stuff for the function
  635. bool shouldSplitStack() const;
  636. /// getNumBlockIDs - Return the number of MBB ID's allocated.
  637. unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
  638. /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
  639. /// recomputes them. This guarantees that the MBB numbers are sequential,
  640. /// dense, and match the ordering of the blocks within the function. If a
  641. /// specific MachineBasicBlock is specified, only that block and those after
  642. /// it are renumbered.
  643. void RenumberBlocks(MachineBasicBlock *MBBFrom = nullptr);
  644. /// print - Print out the MachineFunction in a format suitable for debugging
  645. /// to the specified stream.
  646. void print(raw_ostream &OS, const SlotIndexes* = nullptr) const;
  647. /// viewCFG - This function is meant for use from the debugger. You can just
  648. /// say 'call F->viewCFG()' and a ghostview window should pop up from the
  649. /// program, displaying the CFG of the current function with the code for each
  650. /// basic block inside. This depends on there being a 'dot' and 'gv' program
  651. /// in your path.
  652. void viewCFG() const;
  653. /// viewCFGOnly - This function is meant for use from the debugger. It works
  654. /// just like viewCFG, but it does not include the contents of basic blocks
  655. /// into the nodes, just the label. If you are only interested in the CFG
  656. /// this can make the graph smaller.
  657. ///
  658. void viewCFGOnly() const;
  659. /// dump - Print the current MachineFunction to cerr, useful for debugger use.
  660. void dump() const;
  661. /// Run the current MachineFunction through the machine code verifier, useful
  662. /// for debugger use.
  663. /// \returns true if no problems were found.
  664. bool verify(Pass *p = nullptr, const char *Banner = nullptr,
  665. bool AbortOnError = true) const;
  666. // Provide accessors for the MachineBasicBlock list...
  667. using iterator = BasicBlockListType::iterator;
  668. using const_iterator = BasicBlockListType::const_iterator;
  669. using const_reverse_iterator = BasicBlockListType::const_reverse_iterator;
  670. using reverse_iterator = BasicBlockListType::reverse_iterator;
  671. /// Support for MachineBasicBlock::getNextNode().
  672. static BasicBlockListType MachineFunction::*
  673. getSublistAccess(MachineBasicBlock *) {
  674. return &MachineFunction::BasicBlocks;
  675. }
  676. /// addLiveIn - Add the specified physical register as a live-in value and
  677. /// create a corresponding virtual register for it.
  678. Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC);
  679. //===--------------------------------------------------------------------===//
  680. // BasicBlock accessor functions.
  681. //
  682. iterator begin() { return BasicBlocks.begin(); }
  683. const_iterator begin() const { return BasicBlocks.begin(); }
  684. iterator end () { return BasicBlocks.end(); }
  685. const_iterator end () const { return BasicBlocks.end(); }
  686. reverse_iterator rbegin() { return BasicBlocks.rbegin(); }
  687. const_reverse_iterator rbegin() const { return BasicBlocks.rbegin(); }
  688. reverse_iterator rend () { return BasicBlocks.rend(); }
  689. const_reverse_iterator rend () const { return BasicBlocks.rend(); }
  690. unsigned size() const { return (unsigned)BasicBlocks.size();}
  691. bool empty() const { return BasicBlocks.empty(); }
  692. const MachineBasicBlock &front() const { return BasicBlocks.front(); }
  693. MachineBasicBlock &front() { return BasicBlocks.front(); }
  694. const MachineBasicBlock & back() const { return BasicBlocks.back(); }
  695. MachineBasicBlock & back() { return BasicBlocks.back(); }
  696. void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
  697. void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
  698. void insert(iterator MBBI, MachineBasicBlock *MBB) {
  699. BasicBlocks.insert(MBBI, MBB);
  700. }
  701. void splice(iterator InsertPt, iterator MBBI) {
  702. BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
  703. }
  704. void splice(iterator InsertPt, MachineBasicBlock *MBB) {
  705. BasicBlocks.splice(InsertPt, BasicBlocks, MBB);
  706. }
  707. void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
  708. BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
  709. }
  710. void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
  711. void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
  712. void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
  713. void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
  714. template <typename Comp>
  715. void sort(Comp comp) {
  716. BasicBlocks.sort(comp);
  717. }
  718. /// Return the number of \p MachineInstrs in this \p MachineFunction.
  719. unsigned getInstructionCount() const {
  720. unsigned InstrCount = 0;
  721. for (const MachineBasicBlock &MBB : BasicBlocks)
  722. InstrCount += MBB.size();
  723. return InstrCount;
  724. }
  725. //===--------------------------------------------------------------------===//
  726. // Internal functions used to automatically number MachineBasicBlocks
  727. /// Adds the MBB to the internal numbering. Returns the unique number
  728. /// assigned to the MBB.
  729. unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
  730. MBBNumbering.push_back(MBB);
  731. return (unsigned)MBBNumbering.size()-1;
  732. }
  733. /// removeFromMBBNumbering - Remove the specific machine basic block from our
  734. /// tracker, this is only really to be used by the MachineBasicBlock
  735. /// implementation.
  736. void removeFromMBBNumbering(unsigned N) {
  737. assert(N < MBBNumbering.size() && "Illegal basic block #");
  738. MBBNumbering[N] = nullptr;
  739. }
  740. /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
  741. /// of `new MachineInstr'.
  742. MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID, DebugLoc DL,
  743. bool NoImplicit = false);
  744. /// Create a new MachineInstr which is a copy of \p Orig, identical in all
  745. /// ways except the instruction has no parent, prev, or next. Bundling flags
  746. /// are reset.
  747. ///
  748. /// Note: Clones a single instruction, not whole instruction bundles.
  749. /// Does not perform target specific adjustments; consider using
  750. /// TargetInstrInfo::duplicate() instead.
  751. MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
  752. /// Clones instruction or the whole instruction bundle \p Orig and insert
  753. /// into \p MBB before \p InsertBefore.
  754. ///
  755. /// Note: Does not perform target specific adjustments; consider using
  756. /// TargetInstrInfo::duplicate() intead.
  757. MachineInstr &
  758. cloneMachineInstrBundle(MachineBasicBlock &MBB,
  759. MachineBasicBlock::iterator InsertBefore,
  760. const MachineInstr &Orig);
  761. /// DeleteMachineInstr - Delete the given MachineInstr.
  762. void deleteMachineInstr(MachineInstr *MI);
  763. /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
  764. /// instead of `new MachineBasicBlock'.
  765. MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = nullptr);
  766. /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
  767. void deleteMachineBasicBlock(MachineBasicBlock *MBB);
  768. /// getMachineMemOperand - Allocate a new MachineMemOperand.
  769. /// MachineMemOperands are owned by the MachineFunction and need not be
  770. /// explicitly deallocated.
  771. MachineMemOperand *getMachineMemOperand(
  772. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
  773. Align base_alignment, const AAMDNodes &AAInfo = AAMDNodes(),
  774. const MDNode *Ranges = nullptr, SyncScope::ID SSID = SyncScope::System,
  775. AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
  776. AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic);
  777. MachineMemOperand *getMachineMemOperand(
  778. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
  779. Align base_alignment, const AAMDNodes &AAInfo = AAMDNodes(),
  780. const MDNode *Ranges = nullptr, SyncScope::ID SSID = SyncScope::System,
  781. AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
  782. AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic);
  783. /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
  784. /// an existing one, adjusting by an offset and using the given size.
  785. /// MachineMemOperands are owned by the MachineFunction and need not be
  786. /// explicitly deallocated.
  787. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  788. int64_t Offset, LLT Ty);
  789. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  790. int64_t Offset, uint64_t Size) {
  791. return getMachineMemOperand(
  792. MMO, Offset, Size == ~UINT64_C(0) ? LLT() : LLT::scalar(8 * Size));
  793. }
  794. /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
  795. /// an existing one, replacing only the MachinePointerInfo and size.
  796. /// MachineMemOperands are owned by the MachineFunction and need not be
  797. /// explicitly deallocated.
  798. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  799. const MachinePointerInfo &PtrInfo,
  800. uint64_t Size);
  801. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  802. const MachinePointerInfo &PtrInfo,
  803. LLT Ty);
  804. /// Allocate a new MachineMemOperand by copying an existing one,
  805. /// replacing only AliasAnalysis information. MachineMemOperands are owned
  806. /// by the MachineFunction and need not be explicitly deallocated.
  807. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  808. const AAMDNodes &AAInfo);
  809. /// Allocate a new MachineMemOperand by copying an existing one,
  810. /// replacing the flags. MachineMemOperands are owned
  811. /// by the MachineFunction and need not be explicitly deallocated.
  812. MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
  813. MachineMemOperand::Flags Flags);
  814. using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
  815. /// Allocate an array of MachineOperands. This is only intended for use by
  816. /// internal MachineInstr functions.
  817. MachineOperand *allocateOperandArray(OperandCapacity Cap) {
  818. return OperandRecycler.allocate(Cap, Allocator);
  819. }
  820. /// Dellocate an array of MachineOperands and recycle the memory. This is
  821. /// only intended for use by internal MachineInstr functions.
  822. /// Cap must be the same capacity that was used to allocate the array.
  823. void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array) {
  824. OperandRecycler.deallocate(Cap, Array);
  825. }
  826. /// Allocate and initialize a register mask with @p NumRegister bits.
  827. uint32_t *allocateRegMask();
  828. ArrayRef<int> allocateShuffleMask(ArrayRef<int> Mask);
  829. /// Allocate and construct an extra info structure for a `MachineInstr`.
  830. ///
  831. /// This is allocated on the function's allocator and so lives the life of
  832. /// the function.
  833. MachineInstr::ExtraInfo *createMIExtraInfo(
  834. ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol = nullptr,
  835. MCSymbol *PostInstrSymbol = nullptr, MDNode *HeapAllocMarker = nullptr);
  836. /// Allocate a string and populate it with the given external symbol name.
  837. const char *createExternalSymbolName(StringRef Name);
  838. //===--------------------------------------------------------------------===//
  839. // Label Manipulation.
  840. /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
  841. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  842. /// normal 'L' label is returned.
  843. MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
  844. bool isLinkerPrivate = false) const;
  845. /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
  846. /// base.
  847. MCSymbol *getPICBaseSymbol() const;
  848. /// Returns a reference to a list of cfi instructions in the function's
  849. /// prologue. Used to construct frame maps for debug and exception handling
  850. /// comsumers.
  851. const std::vector<MCCFIInstruction> &getFrameInstructions() const {
  852. return FrameInstructions;
  853. }
  854. LLVM_NODISCARD unsigned addFrameInst(const MCCFIInstruction &Inst);
  855. /// Returns a reference to a list of symbols immediately following calls to
  856. /// _setjmp in the function. Used to construct the longjmp target table used
  857. /// by Windows Control Flow Guard.
  858. const std::vector<MCSymbol *> &getLongjmpTargets() const {
  859. return LongjmpTargets;
  860. }
  861. /// Add the specified symbol to the list of valid longjmp targets for Windows
  862. /// Control Flow Guard.
  863. void addLongjmpTarget(MCSymbol *Target) { LongjmpTargets.push_back(Target); }
  864. /// Returns a reference to a list of symbols that we have catchrets.
  865. /// Used to construct the catchret target table used by Windows EHCont Guard.
  866. const std::vector<MCSymbol *> &getCatchretTargets() const {
  867. return CatchretTargets;
  868. }
  869. /// Add the specified symbol to the list of valid catchret targets for Windows
  870. /// EHCont Guard.
  871. void addCatchretTarget(MCSymbol *Target) {
  872. CatchretTargets.push_back(Target);
  873. }
  874. /// \name Exception Handling
  875. /// \{
  876. bool callsEHReturn() const { return CallsEHReturn; }
  877. void setCallsEHReturn(bool b) { CallsEHReturn = b; }
  878. bool callsUnwindInit() const { return CallsUnwindInit; }
  879. void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
  880. bool hasEHCatchret() const { return HasEHCatchret; }
  881. void setHasEHCatchret(bool V) { HasEHCatchret = V; }
  882. bool hasEHScopes() const { return HasEHScopes; }
  883. void setHasEHScopes(bool V) { HasEHScopes = V; }
  884. bool hasEHFunclets() const { return HasEHFunclets; }
  885. void setHasEHFunclets(bool V) { HasEHFunclets = V; }
  886. /// Find or create an LandingPadInfo for the specified MachineBasicBlock.
  887. LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
  888. /// Remap landing pad labels and remove any deleted landing pads.
  889. void tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap = nullptr,
  890. bool TidyIfNoBeginLabels = true);
  891. /// Return a reference to the landing pad info for the current function.
  892. const std::vector<LandingPadInfo> &getLandingPads() const {
  893. return LandingPads;
  894. }
  895. /// Provide the begin and end labels of an invoke style call and associate it
  896. /// with a try landing pad block.
  897. void addInvoke(MachineBasicBlock *LandingPad,
  898. MCSymbol *BeginLabel, MCSymbol *EndLabel);
  899. /// Add a new panding pad, and extract the exception handling information from
  900. /// the landingpad instruction. Returns the label ID for the landing pad
  901. /// entry.
  902. MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
  903. /// Provide the catch typeinfo for a landing pad.
  904. void addCatchTypeInfo(MachineBasicBlock *LandingPad,
  905. ArrayRef<const GlobalValue *> TyInfo);
  906. /// Provide the filter typeinfo for a landing pad.
  907. void addFilterTypeInfo(MachineBasicBlock *LandingPad,
  908. ArrayRef<const GlobalValue *> TyInfo);
  909. /// Add a cleanup action for a landing pad.
  910. void addCleanup(MachineBasicBlock *LandingPad);
  911. void addSEHCatchHandler(MachineBasicBlock *LandingPad, const Function *Filter,
  912. const BlockAddress *RecoverBA);
  913. void addSEHCleanupHandler(MachineBasicBlock *LandingPad,
  914. const Function *Cleanup);
  915. /// Return the type id for the specified typeinfo. This is function wide.
  916. unsigned getTypeIDFor(const GlobalValue *TI);
  917. /// Return the id of the filter encoded by TyIds. This is function wide.
  918. int getFilterIDFor(std::vector<unsigned> &TyIds);
  919. /// Map the landing pad's EH symbol to the call site indexes.
  920. void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
  921. /// Map the landing pad to its index. Used for Wasm exception handling.
  922. void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index) {
  923. WasmLPadToIndexMap[LPad] = Index;
  924. }
  925. /// Returns true if the landing pad has an associate index in wasm EH.
  926. bool hasWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
  927. return WasmLPadToIndexMap.count(LPad);
  928. }
  929. /// Get the index in wasm EH for a given landing pad.
  930. unsigned getWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
  931. assert(hasWasmLandingPadIndex(LPad));
  932. return WasmLPadToIndexMap.lookup(LPad);
  933. }
  934. /// Get the call site indexes for a landing pad EH symbol.
  935. SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
  936. assert(hasCallSiteLandingPad(Sym) &&
  937. "missing call site number for landing pad!");
  938. return LPadToCallSiteMap[Sym];
  939. }
  940. /// Return true if the landing pad Eh symbol has an associated call site.
  941. bool hasCallSiteLandingPad(MCSymbol *Sym) {
  942. return !LPadToCallSiteMap[Sym].empty();
  943. }
  944. /// Map the begin label for a call site.
  945. void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
  946. CallSiteMap[BeginLabel] = Site;
  947. }
  948. /// Get the call site number for a begin label.
  949. unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) const {
  950. assert(hasCallSiteBeginLabel(BeginLabel) &&
  951. "Missing call site number for EH_LABEL!");
  952. return CallSiteMap.lookup(BeginLabel);
  953. }
  954. /// Return true if the begin label has a call site number associated with it.
  955. bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) const {
  956. return CallSiteMap.count(BeginLabel);
  957. }
  958. /// Record annotations associated with a particular label.
  959. void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD) {
  960. CodeViewAnnotations.push_back({Label, MD});
  961. }
  962. ArrayRef<std::pair<MCSymbol *, MDNode *>> getCodeViewAnnotations() const {
  963. return CodeViewAnnotations;
  964. }
  965. /// Return a reference to the C++ typeinfo for the current function.
  966. const std::vector<const GlobalValue *> &getTypeInfos() const {
  967. return TypeInfos;
  968. }
  969. /// Return a reference to the typeids encoding filters used in the current
  970. /// function.
  971. const std::vector<unsigned> &getFilterIds() const {
  972. return FilterIds;
  973. }
  974. /// \}
  975. /// Collect information used to emit debugging information of a variable.
  976. void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
  977. int Slot, const DILocation *Loc) {
  978. VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
  979. }
  980. VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
  981. const VariableDbgInfoMapTy &getVariableDbgInfo() const {
  982. return VariableDbgInfos;
  983. }
  984. /// Start tracking the arguments passed to the call \p CallI.
  985. void addCallArgsForwardingRegs(const MachineInstr *CallI,
  986. CallSiteInfoImpl &&CallInfo) {
  987. assert(CallI->isCandidateForCallSiteEntry());
  988. bool Inserted =
  989. CallSitesInfo.try_emplace(CallI, std::move(CallInfo)).second;
  990. (void)Inserted;
  991. assert(Inserted && "Call site info not unique");
  992. }
  993. const CallSiteInfoMap &getCallSitesInfo() const {
  994. return CallSitesInfo;
  995. }
  996. /// Following functions update call site info. They should be called before
  997. /// removing, replacing or copying call instruction.
  998. /// Erase the call site info for \p MI. It is used to remove a call
  999. /// instruction from the instruction stream.
  1000. void eraseCallSiteInfo(const MachineInstr *MI);
  1001. /// Copy the call site info from \p Old to \ New. Its usage is when we are
  1002. /// making a copy of the instruction that will be inserted at different point
  1003. /// of the instruction stream.
  1004. void copyCallSiteInfo(const MachineInstr *Old,
  1005. const MachineInstr *New);
  1006. const std::vector<char> &getBBSectionsSymbolPrefix() const {
  1007. return BBSectionsSymbolPrefix;
  1008. }
  1009. /// Move the call site info from \p Old to \New call site info. This function
  1010. /// is used when we are replacing one call instruction with another one to
  1011. /// the same callee.
  1012. void moveCallSiteInfo(const MachineInstr *Old,
  1013. const MachineInstr *New);
  1014. unsigned getNewDebugInstrNum() {
  1015. return ++DebugInstrNumberingCount;
  1016. }
  1017. };
  1018. //===--------------------------------------------------------------------===//
  1019. // GraphTraits specializations for function basic block graphs (CFGs)
  1020. //===--------------------------------------------------------------------===//
  1021. // Provide specializations of GraphTraits to be able to treat a
  1022. // machine function as a graph of machine basic blocks... these are
  1023. // the same as the machine basic block iterators, except that the root
  1024. // node is implicitly the first node of the function.
  1025. //
  1026. template <> struct GraphTraits<MachineFunction*> :
  1027. public GraphTraits<MachineBasicBlock*> {
  1028. static NodeRef getEntryNode(MachineFunction *F) { return &F->front(); }
  1029. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  1030. using nodes_iterator = pointer_iterator<MachineFunction::iterator>;
  1031. static nodes_iterator nodes_begin(MachineFunction *F) {
  1032. return nodes_iterator(F->begin());
  1033. }
  1034. static nodes_iterator nodes_end(MachineFunction *F) {
  1035. return nodes_iterator(F->end());
  1036. }
  1037. static unsigned size (MachineFunction *F) { return F->size(); }
  1038. };
  1039. template <> struct GraphTraits<const MachineFunction*> :
  1040. public GraphTraits<const MachineBasicBlock*> {
  1041. static NodeRef getEntryNode(const MachineFunction *F) { return &F->front(); }
  1042. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  1043. using nodes_iterator = pointer_iterator<MachineFunction::const_iterator>;
  1044. static nodes_iterator nodes_begin(const MachineFunction *F) {
  1045. return nodes_iterator(F->begin());
  1046. }
  1047. static nodes_iterator nodes_end (const MachineFunction *F) {
  1048. return nodes_iterator(F->end());
  1049. }
  1050. static unsigned size (const MachineFunction *F) {
  1051. return F->size();
  1052. }
  1053. };
  1054. // Provide specializations of GraphTraits to be able to treat a function as a
  1055. // graph of basic blocks... and to walk it in inverse order. Inverse order for
  1056. // a function is considered to be when traversing the predecessor edges of a BB
  1057. // instead of the successor edges.
  1058. //
  1059. template <> struct GraphTraits<Inverse<MachineFunction*>> :
  1060. public GraphTraits<Inverse<MachineBasicBlock*>> {
  1061. static NodeRef getEntryNode(Inverse<MachineFunction *> G) {
  1062. return &G.Graph->front();
  1063. }
  1064. };
  1065. template <> struct GraphTraits<Inverse<const MachineFunction*>> :
  1066. public GraphTraits<Inverse<const MachineBasicBlock*>> {
  1067. static NodeRef getEntryNode(Inverse<const MachineFunction *> G) {
  1068. return &G.Graph->front();
  1069. }
  1070. };
  1071. class MachineFunctionAnalysisManager;
  1072. void verifyMachineFunction(MachineFunctionAnalysisManager *,
  1073. const std::string &Banner,
  1074. const MachineFunction &MF);
  1075. } // end namespace llvm
  1076. #endif // LLVM_CODEGEN_MACHINEFUNCTION_H
  1077. #ifdef __GNUC__
  1078. #pragma GCC diagnostic pop
  1079. #endif