MachineInstr.h 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file contains the declaration of the MachineInstr class, which is the
  15. // basic representation for all target dependent machine instructions used by
  16. // the back end.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_CODEGEN_MACHINEINSTR_H
  20. #define LLVM_CODEGEN_MACHINEINSTR_H
  21. #include "llvm/ADT/DenseMapInfo.h"
  22. #include "llvm/ADT/PointerSumType.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/ADT/ilist.h"
  25. #include "llvm/ADT/ilist_node.h"
  26. #include "llvm/ADT/iterator_range.h"
  27. #include "llvm/CodeGen/MachineMemOperand.h"
  28. #include "llvm/CodeGen/MachineOperand.h"
  29. #include "llvm/CodeGen/TargetOpcodes.h"
  30. #include "llvm/IR/DebugLoc.h"
  31. #include "llvm/IR/InlineAsm.h"
  32. #include "llvm/IR/PseudoProbe.h"
  33. #include "llvm/MC/MCInstrDesc.h"
  34. #include "llvm/MC/MCSymbol.h"
  35. #include "llvm/Support/ArrayRecycler.h"
  36. #include "llvm/Support/TrailingObjects.h"
  37. #include <algorithm>
  38. #include <cassert>
  39. #include <cstdint>
  40. #include <utility>
  41. namespace llvm {
  42. class AAResults;
  43. template <typename T> class ArrayRef;
  44. class DIExpression;
  45. class DILocalVariable;
  46. class MachineBasicBlock;
  47. class MachineFunction;
  48. class MachineRegisterInfo;
  49. class ModuleSlotTracker;
  50. class raw_ostream;
  51. template <typename T> class SmallVectorImpl;
  52. class SmallBitVector;
  53. class StringRef;
  54. class TargetInstrInfo;
  55. class TargetRegisterClass;
  56. class TargetRegisterInfo;
  57. //===----------------------------------------------------------------------===//
  58. /// Representation of each machine instruction.
  59. ///
  60. /// This class isn't a POD type, but it must have a trivial destructor. When a
  61. /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
  62. /// without having their destructor called.
  63. ///
  64. class MachineInstr
  65. : public ilist_node_with_parent<MachineInstr, MachineBasicBlock,
  66. ilist_sentinel_tracking<true>> {
  67. public:
  68. using mmo_iterator = ArrayRef<MachineMemOperand *>::iterator;
  69. /// Flags to specify different kinds of comments to output in
  70. /// assembly code. These flags carry semantic information not
  71. /// otherwise easily derivable from the IR text.
  72. ///
  73. enum CommentFlag {
  74. ReloadReuse = 0x1, // higher bits are reserved for target dep comments.
  75. NoSchedComment = 0x2,
  76. TAsmComments = 0x4 // Target Asm comments should start from this value.
  77. };
  78. enum MIFlag {
  79. NoFlags = 0,
  80. FrameSetup = 1 << 0, // Instruction is used as a part of
  81. // function frame setup code.
  82. FrameDestroy = 1 << 1, // Instruction is used as a part of
  83. // function frame destruction code.
  84. BundledPred = 1 << 2, // Instruction has bundled predecessors.
  85. BundledSucc = 1 << 3, // Instruction has bundled successors.
  86. FmNoNans = 1 << 4, // Instruction does not support Fast
  87. // math nan values.
  88. FmNoInfs = 1 << 5, // Instruction does not support Fast
  89. // math infinity values.
  90. FmNsz = 1 << 6, // Instruction is not required to retain
  91. // signed zero values.
  92. FmArcp = 1 << 7, // Instruction supports Fast math
  93. // reciprocal approximations.
  94. FmContract = 1 << 8, // Instruction supports Fast math
  95. // contraction operations like fma.
  96. FmAfn = 1 << 9, // Instruction may map to Fast math
  97. // instrinsic approximation.
  98. FmReassoc = 1 << 10, // Instruction supports Fast math
  99. // reassociation of operand order.
  100. NoUWrap = 1 << 11, // Instruction supports binary operator
  101. // no unsigned wrap.
  102. NoSWrap = 1 << 12, // Instruction supports binary operator
  103. // no signed wrap.
  104. IsExact = 1 << 13, // Instruction supports division is
  105. // known to be exact.
  106. NoFPExcept = 1 << 14, // Instruction does not raise
  107. // floatint-point exceptions.
  108. NoMerge = 1 << 15, // Passes that drop source location info
  109. // (e.g. branch folding) should skip
  110. // this instruction.
  111. };
  112. private:
  113. const MCInstrDesc *MCID; // Instruction descriptor.
  114. MachineBasicBlock *Parent = nullptr; // Pointer to the owning basic block.
  115. // Operands are allocated by an ArrayRecycler.
  116. MachineOperand *Operands = nullptr; // Pointer to the first operand.
  117. unsigned NumOperands = 0; // Number of operands on instruction.
  118. uint16_t Flags = 0; // Various bits of additional
  119. // information about machine
  120. // instruction.
  121. uint8_t AsmPrinterFlags = 0; // Various bits of information used by
  122. // the AsmPrinter to emit helpful
  123. // comments. This is *not* semantic
  124. // information. Do not use this for
  125. // anything other than to convey comment
  126. // information to AsmPrinter.
  127. // OperandCapacity has uint8_t size, so it should be next to AsmPrinterFlags
  128. // to properly pack.
  129. using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
  130. OperandCapacity CapOperands; // Capacity of the Operands array.
  131. /// Internal implementation detail class that provides out-of-line storage for
  132. /// extra info used by the machine instruction when this info cannot be stored
  133. /// in-line within the instruction itself.
  134. ///
  135. /// This has to be defined eagerly due to the implementation constraints of
  136. /// `PointerSumType` where it is used.
  137. class ExtraInfo final
  138. : TrailingObjects<ExtraInfo, MachineMemOperand *, MCSymbol *, MDNode *> {
  139. public:
  140. static ExtraInfo *create(BumpPtrAllocator &Allocator,
  141. ArrayRef<MachineMemOperand *> MMOs,
  142. MCSymbol *PreInstrSymbol = nullptr,
  143. MCSymbol *PostInstrSymbol = nullptr,
  144. MDNode *HeapAllocMarker = nullptr) {
  145. bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
  146. bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
  147. bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
  148. auto *Result = new (Allocator.Allocate(
  149. totalSizeToAlloc<MachineMemOperand *, MCSymbol *, MDNode *>(
  150. MMOs.size(), HasPreInstrSymbol + HasPostInstrSymbol,
  151. HasHeapAllocMarker),
  152. alignof(ExtraInfo)))
  153. ExtraInfo(MMOs.size(), HasPreInstrSymbol, HasPostInstrSymbol,
  154. HasHeapAllocMarker);
  155. // Copy the actual data into the trailing objects.
  156. std::copy(MMOs.begin(), MMOs.end(),
  157. Result->getTrailingObjects<MachineMemOperand *>());
  158. if (HasPreInstrSymbol)
  159. Result->getTrailingObjects<MCSymbol *>()[0] = PreInstrSymbol;
  160. if (HasPostInstrSymbol)
  161. Result->getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] =
  162. PostInstrSymbol;
  163. if (HasHeapAllocMarker)
  164. Result->getTrailingObjects<MDNode *>()[0] = HeapAllocMarker;
  165. return Result;
  166. }
  167. ArrayRef<MachineMemOperand *> getMMOs() const {
  168. return makeArrayRef(getTrailingObjects<MachineMemOperand *>(), NumMMOs);
  169. }
  170. MCSymbol *getPreInstrSymbol() const {
  171. return HasPreInstrSymbol ? getTrailingObjects<MCSymbol *>()[0] : nullptr;
  172. }
  173. MCSymbol *getPostInstrSymbol() const {
  174. return HasPostInstrSymbol
  175. ? getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol]
  176. : nullptr;
  177. }
  178. MDNode *getHeapAllocMarker() const {
  179. return HasHeapAllocMarker ? getTrailingObjects<MDNode *>()[0] : nullptr;
  180. }
  181. private:
  182. friend TrailingObjects;
  183. // Description of the extra info, used to interpret the actual optional
  184. // data appended.
  185. //
  186. // Note that this is not terribly space optimized. This leaves a great deal
  187. // of flexibility to fit more in here later.
  188. const int NumMMOs;
  189. const bool HasPreInstrSymbol;
  190. const bool HasPostInstrSymbol;
  191. const bool HasHeapAllocMarker;
  192. // Implement the `TrailingObjects` internal API.
  193. size_t numTrailingObjects(OverloadToken<MachineMemOperand *>) const {
  194. return NumMMOs;
  195. }
  196. size_t numTrailingObjects(OverloadToken<MCSymbol *>) const {
  197. return HasPreInstrSymbol + HasPostInstrSymbol;
  198. }
  199. size_t numTrailingObjects(OverloadToken<MDNode *>) const {
  200. return HasHeapAllocMarker;
  201. }
  202. // Just a boring constructor to allow us to initialize the sizes. Always use
  203. // the `create` routine above.
  204. ExtraInfo(int NumMMOs, bool HasPreInstrSymbol, bool HasPostInstrSymbol,
  205. bool HasHeapAllocMarker)
  206. : NumMMOs(NumMMOs), HasPreInstrSymbol(HasPreInstrSymbol),
  207. HasPostInstrSymbol(HasPostInstrSymbol),
  208. HasHeapAllocMarker(HasHeapAllocMarker) {}
  209. };
  210. /// Enumeration of the kinds of inline extra info available. It is important
  211. /// that the `MachineMemOperand` inline kind has a tag value of zero to make
  212. /// it accessible as an `ArrayRef`.
  213. enum ExtraInfoInlineKinds {
  214. EIIK_MMO = 0,
  215. EIIK_PreInstrSymbol,
  216. EIIK_PostInstrSymbol,
  217. EIIK_OutOfLine
  218. };
  219. // We store extra information about the instruction here. The common case is
  220. // expected to be nothing or a single pointer (typically a MMO or a symbol).
  221. // We work to optimize this common case by storing it inline here rather than
  222. // requiring a separate allocation, but we fall back to an allocation when
  223. // multiple pointers are needed.
  224. PointerSumType<ExtraInfoInlineKinds,
  225. PointerSumTypeMember<EIIK_MMO, MachineMemOperand *>,
  226. PointerSumTypeMember<EIIK_PreInstrSymbol, MCSymbol *>,
  227. PointerSumTypeMember<EIIK_PostInstrSymbol, MCSymbol *>,
  228. PointerSumTypeMember<EIIK_OutOfLine, ExtraInfo *>>
  229. Info;
  230. DebugLoc DbgLoc; // Source line information.
  231. /// Unique instruction number. Used by DBG_INSTR_REFs to refer to the values
  232. /// defined by this instruction.
  233. unsigned DebugInstrNum;
  234. // Intrusive list support
  235. friend struct ilist_traits<MachineInstr>;
  236. friend struct ilist_callback_traits<MachineBasicBlock>;
  237. void setParent(MachineBasicBlock *P) { Parent = P; }
  238. /// This constructor creates a copy of the given
  239. /// MachineInstr in the given MachineFunction.
  240. MachineInstr(MachineFunction &, const MachineInstr &);
  241. /// This constructor create a MachineInstr and add the implicit operands.
  242. /// It reserves space for number of operands specified by
  243. /// MCInstrDesc. An explicit DebugLoc is supplied.
  244. MachineInstr(MachineFunction &, const MCInstrDesc &TID, DebugLoc DL,
  245. bool NoImp = false);
  246. // MachineInstrs are pool-allocated and owned by MachineFunction.
  247. friend class MachineFunction;
  248. void
  249. dumprImpl(const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth,
  250. SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const;
  251. public:
  252. MachineInstr(const MachineInstr &) = delete;
  253. MachineInstr &operator=(const MachineInstr &) = delete;
  254. // Use MachineFunction::DeleteMachineInstr() instead.
  255. ~MachineInstr() = delete;
  256. const MachineBasicBlock* getParent() const { return Parent; }
  257. MachineBasicBlock* getParent() { return Parent; }
  258. /// Move the instruction before \p MovePos.
  259. void moveBefore(MachineInstr *MovePos);
  260. /// Return the function that contains the basic block that this instruction
  261. /// belongs to.
  262. ///
  263. /// Note: this is undefined behaviour if the instruction does not have a
  264. /// parent.
  265. const MachineFunction *getMF() const;
  266. MachineFunction *getMF() {
  267. return const_cast<MachineFunction *>(
  268. static_cast<const MachineInstr *>(this)->getMF());
  269. }
  270. /// Return the asm printer flags bitvector.
  271. uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
  272. /// Clear the AsmPrinter bitvector.
  273. void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
  274. /// Return whether an AsmPrinter flag is set.
  275. bool getAsmPrinterFlag(CommentFlag Flag) const {
  276. return AsmPrinterFlags & Flag;
  277. }
  278. /// Set a flag for the AsmPrinter.
  279. void setAsmPrinterFlag(uint8_t Flag) {
  280. AsmPrinterFlags |= Flag;
  281. }
  282. /// Clear specific AsmPrinter flags.
  283. void clearAsmPrinterFlag(CommentFlag Flag) {
  284. AsmPrinterFlags &= ~Flag;
  285. }
  286. /// Return the MI flags bitvector.
  287. uint16_t getFlags() const {
  288. return Flags;
  289. }
  290. /// Return whether an MI flag is set.
  291. bool getFlag(MIFlag Flag) const {
  292. return Flags & Flag;
  293. }
  294. /// Set a MI flag.
  295. void setFlag(MIFlag Flag) {
  296. Flags |= (uint16_t)Flag;
  297. }
  298. void setFlags(unsigned flags) {
  299. // Filter out the automatically maintained flags.
  300. unsigned Mask = BundledPred | BundledSucc;
  301. Flags = (Flags & Mask) | (flags & ~Mask);
  302. }
  303. /// clearFlag - Clear a MI flag.
  304. void clearFlag(MIFlag Flag) {
  305. Flags &= ~((uint16_t)Flag);
  306. }
  307. /// Return true if MI is in a bundle (but not the first MI in a bundle).
  308. ///
  309. /// A bundle looks like this before it's finalized:
  310. /// ----------------
  311. /// | MI |
  312. /// ----------------
  313. /// |
  314. /// ----------------
  315. /// | MI * |
  316. /// ----------------
  317. /// |
  318. /// ----------------
  319. /// | MI * |
  320. /// ----------------
  321. /// In this case, the first MI starts a bundle but is not inside a bundle, the
  322. /// next 2 MIs are considered "inside" the bundle.
  323. ///
  324. /// After a bundle is finalized, it looks like this:
  325. /// ----------------
  326. /// | Bundle |
  327. /// ----------------
  328. /// |
  329. /// ----------------
  330. /// | MI * |
  331. /// ----------------
  332. /// |
  333. /// ----------------
  334. /// | MI * |
  335. /// ----------------
  336. /// |
  337. /// ----------------
  338. /// | MI * |
  339. /// ----------------
  340. /// The first instruction has the special opcode "BUNDLE". It's not "inside"
  341. /// a bundle, but the next three MIs are.
  342. bool isInsideBundle() const {
  343. return getFlag(BundledPred);
  344. }
  345. /// Return true if this instruction part of a bundle. This is true
  346. /// if either itself or its following instruction is marked "InsideBundle".
  347. bool isBundled() const {
  348. return isBundledWithPred() || isBundledWithSucc();
  349. }
  350. /// Return true if this instruction is part of a bundle, and it is not the
  351. /// first instruction in the bundle.
  352. bool isBundledWithPred() const { return getFlag(BundledPred); }
  353. /// Return true if this instruction is part of a bundle, and it is not the
  354. /// last instruction in the bundle.
  355. bool isBundledWithSucc() const { return getFlag(BundledSucc); }
  356. /// Bundle this instruction with its predecessor. This can be an unbundled
  357. /// instruction, or it can be the first instruction in a bundle.
  358. void bundleWithPred();
  359. /// Bundle this instruction with its successor. This can be an unbundled
  360. /// instruction, or it can be the last instruction in a bundle.
  361. void bundleWithSucc();
  362. /// Break bundle above this instruction.
  363. void unbundleFromPred();
  364. /// Break bundle below this instruction.
  365. void unbundleFromSucc();
  366. /// Returns the debug location id of this MachineInstr.
  367. const DebugLoc &getDebugLoc() const { return DbgLoc; }
  368. /// Return the operand containing the offset to be used if this DBG_VALUE
  369. /// instruction is indirect; will be an invalid register if this value is
  370. /// not indirect, and an immediate with value 0 otherwise.
  371. const MachineOperand &getDebugOffset() const {
  372. assert(isNonListDebugValue() && "not a DBG_VALUE");
  373. return getOperand(1);
  374. }
  375. MachineOperand &getDebugOffset() {
  376. assert(isNonListDebugValue() && "not a DBG_VALUE");
  377. return getOperand(1);
  378. }
  379. /// Return the operand for the debug variable referenced by
  380. /// this DBG_VALUE instruction.
  381. const MachineOperand &getDebugVariableOp() const;
  382. MachineOperand &getDebugVariableOp();
  383. /// Return the debug variable referenced by
  384. /// this DBG_VALUE instruction.
  385. const DILocalVariable *getDebugVariable() const;
  386. /// Return the operand for the complex address expression referenced by
  387. /// this DBG_VALUE instruction.
  388. const MachineOperand &getDebugExpressionOp() const;
  389. MachineOperand &getDebugExpressionOp();
  390. /// Return the complex address expression referenced by
  391. /// this DBG_VALUE instruction.
  392. const DIExpression *getDebugExpression() const;
  393. /// Return the debug label referenced by
  394. /// this DBG_LABEL instruction.
  395. const DILabel *getDebugLabel() const;
  396. /// Fetch the instruction number of this MachineInstr. If it does not have
  397. /// one already, a new and unique number will be assigned.
  398. unsigned getDebugInstrNum();
  399. /// Fetch instruction number of this MachineInstr -- but before it's inserted
  400. /// into \p MF. Needed for transformations that create an instruction but
  401. /// don't immediately insert them.
  402. unsigned getDebugInstrNum(MachineFunction &MF);
  403. /// Examine the instruction number of this MachineInstr. May be zero if
  404. /// it hasn't been assigned a number yet.
  405. unsigned peekDebugInstrNum() const { return DebugInstrNum; }
  406. /// Set instruction number of this MachineInstr. Avoid using unless you're
  407. /// deserializing this information.
  408. void setDebugInstrNum(unsigned Num) { DebugInstrNum = Num; }
  409. /// Drop any variable location debugging information associated with this
  410. /// instruction. Use when an instruction is modified in such a way that it no
  411. /// longer defines the value it used to. Variable locations using that value
  412. /// will be dropped.
  413. void dropDebugNumber() { DebugInstrNum = 0; }
  414. /// Emit an error referring to the source location of this instruction.
  415. /// This should only be used for inline assembly that is somehow
  416. /// impossible to compile. Other errors should have been handled much
  417. /// earlier.
  418. ///
  419. /// If this method returns, the caller should try to recover from the error.
  420. void emitError(StringRef Msg) const;
  421. /// Returns the target instruction descriptor of this MachineInstr.
  422. const MCInstrDesc &getDesc() const { return *MCID; }
  423. /// Returns the opcode of this MachineInstr.
  424. unsigned getOpcode() const { return MCID->Opcode; }
  425. /// Retuns the total number of operands.
  426. unsigned getNumOperands() const { return NumOperands; }
  427. /// Returns the total number of operands which are debug locations.
  428. unsigned getNumDebugOperands() const {
  429. return std::distance(debug_operands().begin(), debug_operands().end());
  430. }
  431. const MachineOperand& getOperand(unsigned i) const {
  432. assert(i < getNumOperands() && "getOperand() out of range!");
  433. return Operands[i];
  434. }
  435. MachineOperand& getOperand(unsigned i) {
  436. assert(i < getNumOperands() && "getOperand() out of range!");
  437. return Operands[i];
  438. }
  439. MachineOperand &getDebugOperand(unsigned Index) {
  440. assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!");
  441. return *(debug_operands().begin() + Index);
  442. }
  443. const MachineOperand &getDebugOperand(unsigned Index) const {
  444. assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!");
  445. return *(debug_operands().begin() + Index);
  446. }
  447. SmallSet<Register, 4> getUsedDebugRegs() const {
  448. assert(isDebugValue() && "not a DBG_VALUE*");
  449. SmallSet<Register, 4> UsedRegs;
  450. for (const auto &MO : debug_operands())
  451. if (MO.isReg() && MO.getReg())
  452. UsedRegs.insert(MO.getReg());
  453. return UsedRegs;
  454. }
  455. /// Returns whether this debug value has at least one debug operand with the
  456. /// register \p Reg.
  457. bool hasDebugOperandForReg(Register Reg) const {
  458. return any_of(debug_operands(), [Reg](const MachineOperand &Op) {
  459. return Op.isReg() && Op.getReg() == Reg;
  460. });
  461. }
  462. /// Returns a range of all of the operands that correspond to a debug use of
  463. /// \p Reg.
  464. template <typename Operand, typename Instruction>
  465. static iterator_range<
  466. filter_iterator<Operand *, std::function<bool(Operand &Op)>>>
  467. getDebugOperandsForReg(Instruction *MI, Register Reg) {
  468. std::function<bool(Operand & Op)> OpUsesReg(
  469. [Reg](Operand &Op) { return Op.isReg() && Op.getReg() == Reg; });
  470. return make_filter_range(MI->debug_operands(), OpUsesReg);
  471. }
  472. iterator_range<filter_iterator<const MachineOperand *,
  473. std::function<bool(const MachineOperand &Op)>>>
  474. getDebugOperandsForReg(Register Reg) const {
  475. return MachineInstr::getDebugOperandsForReg<const MachineOperand,
  476. const MachineInstr>(this, Reg);
  477. }
  478. iterator_range<filter_iterator<MachineOperand *,
  479. std::function<bool(MachineOperand &Op)>>>
  480. getDebugOperandsForReg(Register Reg) {
  481. return MachineInstr::getDebugOperandsForReg<MachineOperand, MachineInstr>(
  482. this, Reg);
  483. }
  484. bool isDebugOperand(const MachineOperand *Op) const {
  485. return Op >= adl_begin(debug_operands()) && Op <= adl_end(debug_operands());
  486. }
  487. unsigned getDebugOperandIndex(const MachineOperand *Op) const {
  488. assert(isDebugOperand(Op) && "Expected a debug operand.");
  489. return std::distance(adl_begin(debug_operands()), Op);
  490. }
  491. /// Returns the total number of definitions.
  492. unsigned getNumDefs() const {
  493. return getNumExplicitDefs() + MCID->getNumImplicitDefs();
  494. }
  495. /// Returns true if the instruction has implicit definition.
  496. bool hasImplicitDef() const {
  497. for (unsigned I = getNumExplicitOperands(), E = getNumOperands();
  498. I != E; ++I) {
  499. const MachineOperand &MO = getOperand(I);
  500. if (MO.isDef() && MO.isImplicit())
  501. return true;
  502. }
  503. return false;
  504. }
  505. /// Returns the implicit operands number.
  506. unsigned getNumImplicitOperands() const {
  507. return getNumOperands() - getNumExplicitOperands();
  508. }
  509. /// Return true if operand \p OpIdx is a subregister index.
  510. bool isOperandSubregIdx(unsigned OpIdx) const {
  511. assert(getOperand(OpIdx).getType() == MachineOperand::MO_Immediate &&
  512. "Expected MO_Immediate operand type.");
  513. if (isExtractSubreg() && OpIdx == 2)
  514. return true;
  515. if (isInsertSubreg() && OpIdx == 3)
  516. return true;
  517. if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
  518. return true;
  519. if (isSubregToReg() && OpIdx == 3)
  520. return true;
  521. return false;
  522. }
  523. /// Returns the number of non-implicit operands.
  524. unsigned getNumExplicitOperands() const;
  525. /// Returns the number of non-implicit definitions.
  526. unsigned getNumExplicitDefs() const;
  527. /// iterator/begin/end - Iterate over all operands of a machine instruction.
  528. using mop_iterator = MachineOperand *;
  529. using const_mop_iterator = const MachineOperand *;
  530. mop_iterator operands_begin() { return Operands; }
  531. mop_iterator operands_end() { return Operands + NumOperands; }
  532. const_mop_iterator operands_begin() const { return Operands; }
  533. const_mop_iterator operands_end() const { return Operands + NumOperands; }
  534. iterator_range<mop_iterator> operands() {
  535. return make_range(operands_begin(), operands_end());
  536. }
  537. iterator_range<const_mop_iterator> operands() const {
  538. return make_range(operands_begin(), operands_end());
  539. }
  540. iterator_range<mop_iterator> explicit_operands() {
  541. return make_range(operands_begin(),
  542. operands_begin() + getNumExplicitOperands());
  543. }
  544. iterator_range<const_mop_iterator> explicit_operands() const {
  545. return make_range(operands_begin(),
  546. operands_begin() + getNumExplicitOperands());
  547. }
  548. iterator_range<mop_iterator> implicit_operands() {
  549. return make_range(explicit_operands().end(), operands_end());
  550. }
  551. iterator_range<const_mop_iterator> implicit_operands() const {
  552. return make_range(explicit_operands().end(), operands_end());
  553. }
  554. /// Returns a range over all operands that are used to determine the variable
  555. /// location for this DBG_VALUE instruction.
  556. iterator_range<mop_iterator> debug_operands() {
  557. assert(isDebugValue() && "Must be a debug value instruction.");
  558. return isDebugValueList()
  559. ? make_range(operands_begin() + 2, operands_end())
  560. : make_range(operands_begin(), operands_begin() + 1);
  561. }
  562. /// \copydoc debug_operands()
  563. iterator_range<const_mop_iterator> debug_operands() const {
  564. assert(isDebugValue() && "Must be a debug value instruction.");
  565. return isDebugValueList()
  566. ? make_range(operands_begin() + 2, operands_end())
  567. : make_range(operands_begin(), operands_begin() + 1);
  568. }
  569. /// Returns a range over all explicit operands that are register definitions.
  570. /// Implicit definition are not included!
  571. iterator_range<mop_iterator> defs() {
  572. return make_range(operands_begin(),
  573. operands_begin() + getNumExplicitDefs());
  574. }
  575. /// \copydoc defs()
  576. iterator_range<const_mop_iterator> defs() const {
  577. return make_range(operands_begin(),
  578. operands_begin() + getNumExplicitDefs());
  579. }
  580. /// Returns a range that includes all operands that are register uses.
  581. /// This may include unrelated operands which are not register uses.
  582. iterator_range<mop_iterator> uses() {
  583. return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
  584. }
  585. /// \copydoc uses()
  586. iterator_range<const_mop_iterator> uses() const {
  587. return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
  588. }
  589. iterator_range<mop_iterator> explicit_uses() {
  590. return make_range(operands_begin() + getNumExplicitDefs(),
  591. operands_begin() + getNumExplicitOperands());
  592. }
  593. iterator_range<const_mop_iterator> explicit_uses() const {
  594. return make_range(operands_begin() + getNumExplicitDefs(),
  595. operands_begin() + getNumExplicitOperands());
  596. }
  597. /// Returns the number of the operand iterator \p I points to.
  598. unsigned getOperandNo(const_mop_iterator I) const {
  599. return I - operands_begin();
  600. }
  601. /// Access to memory operands of the instruction. If there are none, that does
  602. /// not imply anything about whether the function accesses memory. Instead,
  603. /// the caller must behave conservatively.
  604. ArrayRef<MachineMemOperand *> memoperands() const {
  605. if (!Info)
  606. return {};
  607. if (Info.is<EIIK_MMO>())
  608. return makeArrayRef(Info.getAddrOfZeroTagPointer(), 1);
  609. if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
  610. return EI->getMMOs();
  611. return {};
  612. }
  613. /// Access to memory operands of the instruction.
  614. ///
  615. /// If `memoperands_begin() == memoperands_end()`, that does not imply
  616. /// anything about whether the function accesses memory. Instead, the caller
  617. /// must behave conservatively.
  618. mmo_iterator memoperands_begin() const { return memoperands().begin(); }
  619. /// Access to memory operands of the instruction.
  620. ///
  621. /// If `memoperands_begin() == memoperands_end()`, that does not imply
  622. /// anything about whether the function accesses memory. Instead, the caller
  623. /// must behave conservatively.
  624. mmo_iterator memoperands_end() const { return memoperands().end(); }
  625. /// Return true if we don't have any memory operands which described the
  626. /// memory access done by this instruction. If this is true, calling code
  627. /// must be conservative.
  628. bool memoperands_empty() const { return memoperands().empty(); }
  629. /// Return true if this instruction has exactly one MachineMemOperand.
  630. bool hasOneMemOperand() const { return memoperands().size() == 1; }
  631. /// Return the number of memory operands.
  632. unsigned getNumMemOperands() const { return memoperands().size(); }
  633. /// Helper to extract a pre-instruction symbol if one has been added.
  634. MCSymbol *getPreInstrSymbol() const {
  635. if (!Info)
  636. return nullptr;
  637. if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>())
  638. return S;
  639. if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
  640. return EI->getPreInstrSymbol();
  641. return nullptr;
  642. }
  643. /// Helper to extract a post-instruction symbol if one has been added.
  644. MCSymbol *getPostInstrSymbol() const {
  645. if (!Info)
  646. return nullptr;
  647. if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>())
  648. return S;
  649. if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
  650. return EI->getPostInstrSymbol();
  651. return nullptr;
  652. }
  653. /// Helper to extract a heap alloc marker if one has been added.
  654. MDNode *getHeapAllocMarker() const {
  655. if (!Info)
  656. return nullptr;
  657. if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
  658. return EI->getHeapAllocMarker();
  659. return nullptr;
  660. }
  661. /// API for querying MachineInstr properties. They are the same as MCInstrDesc
  662. /// queries but they are bundle aware.
  663. enum QueryType {
  664. IgnoreBundle, // Ignore bundles
  665. AnyInBundle, // Return true if any instruction in bundle has property
  666. AllInBundle // Return true if all instructions in bundle have property
  667. };
  668. /// Return true if the instruction (or in the case of a bundle,
  669. /// the instructions inside the bundle) has the specified property.
  670. /// The first argument is the property being queried.
  671. /// The second argument indicates whether the query should look inside
  672. /// instruction bundles.
  673. bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
  674. assert(MCFlag < 64 &&
  675. "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.");
  676. // Inline the fast path for unbundled or bundle-internal instructions.
  677. if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
  678. return getDesc().getFlags() & (1ULL << MCFlag);
  679. // If this is the first instruction in a bundle, take the slow path.
  680. return hasPropertyInBundle(1ULL << MCFlag, Type);
  681. }
  682. /// Return true if this is an instruction that should go through the usual
  683. /// legalization steps.
  684. bool isPreISelOpcode(QueryType Type = IgnoreBundle) const {
  685. return hasProperty(MCID::PreISelOpcode, Type);
  686. }
  687. /// Return true if this instruction can have a variable number of operands.
  688. /// In this case, the variable operands will be after the normal
  689. /// operands but before the implicit definitions and uses (if any are
  690. /// present).
  691. bool isVariadic(QueryType Type = IgnoreBundle) const {
  692. return hasProperty(MCID::Variadic, Type);
  693. }
  694. /// Set if this instruction has an optional definition, e.g.
  695. /// ARM instructions which can set condition code if 's' bit is set.
  696. bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
  697. return hasProperty(MCID::HasOptionalDef, Type);
  698. }
  699. /// Return true if this is a pseudo instruction that doesn't
  700. /// correspond to a real machine instruction.
  701. bool isPseudo(QueryType Type = IgnoreBundle) const {
  702. return hasProperty(MCID::Pseudo, Type);
  703. }
  704. bool isReturn(QueryType Type = AnyInBundle) const {
  705. return hasProperty(MCID::Return, Type);
  706. }
  707. /// Return true if this is an instruction that marks the end of an EH scope,
  708. /// i.e., a catchpad or a cleanuppad instruction.
  709. bool isEHScopeReturn(QueryType Type = AnyInBundle) const {
  710. return hasProperty(MCID::EHScopeReturn, Type);
  711. }
  712. bool isCall(QueryType Type = AnyInBundle) const {
  713. return hasProperty(MCID::Call, Type);
  714. }
  715. /// Return true if this is a call instruction that may have an associated
  716. /// call site entry in the debug info.
  717. bool isCandidateForCallSiteEntry(QueryType Type = IgnoreBundle) const;
  718. /// Return true if copying, moving, or erasing this instruction requires
  719. /// updating Call Site Info (see \ref copyCallSiteInfo, \ref moveCallSiteInfo,
  720. /// \ref eraseCallSiteInfo).
  721. bool shouldUpdateCallSiteInfo() const;
  722. /// Returns true if the specified instruction stops control flow
  723. /// from executing the instruction immediately following it. Examples include
  724. /// unconditional branches and return instructions.
  725. bool isBarrier(QueryType Type = AnyInBundle) const {
  726. return hasProperty(MCID::Barrier, Type);
  727. }
  728. /// Returns true if this instruction part of the terminator for a basic block.
  729. /// Typically this is things like return and branch instructions.
  730. ///
  731. /// Various passes use this to insert code into the bottom of a basic block,
  732. /// but before control flow occurs.
  733. bool isTerminator(QueryType Type = AnyInBundle) const {
  734. return hasProperty(MCID::Terminator, Type);
  735. }
  736. /// Returns true if this is a conditional, unconditional, or indirect branch.
  737. /// Predicates below can be used to discriminate between
  738. /// these cases, and the TargetInstrInfo::analyzeBranch method can be used to
  739. /// get more information.
  740. bool isBranch(QueryType Type = AnyInBundle) const {
  741. return hasProperty(MCID::Branch, Type);
  742. }
  743. /// Return true if this is an indirect branch, such as a
  744. /// branch through a register.
  745. bool isIndirectBranch(QueryType Type = AnyInBundle) const {
  746. return hasProperty(MCID::IndirectBranch, Type);
  747. }
  748. /// Return true if this is a branch which may fall
  749. /// through to the next instruction or may transfer control flow to some other
  750. /// block. The TargetInstrInfo::analyzeBranch method can be used to get more
  751. /// information about this branch.
  752. bool isConditionalBranch(QueryType Type = AnyInBundle) const {
  753. return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type);
  754. }
  755. /// Return true if this is a branch which always
  756. /// transfers control flow to some other block. The
  757. /// TargetInstrInfo::analyzeBranch method can be used to get more information
  758. /// about this branch.
  759. bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
  760. return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type);
  761. }
  762. /// Return true if this instruction has a predicate operand that
  763. /// controls execution. It may be set to 'always', or may be set to other
  764. /// values. There are various methods in TargetInstrInfo that can be used to
  765. /// control and modify the predicate in this instruction.
  766. bool isPredicable(QueryType Type = AllInBundle) const {
  767. // If it's a bundle than all bundled instructions must be predicable for this
  768. // to return true.
  769. return hasProperty(MCID::Predicable, Type);
  770. }
  771. /// Return true if this instruction is a comparison.
  772. bool isCompare(QueryType Type = IgnoreBundle) const {
  773. return hasProperty(MCID::Compare, Type);
  774. }
  775. /// Return true if this instruction is a move immediate
  776. /// (including conditional moves) instruction.
  777. bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
  778. return hasProperty(MCID::MoveImm, Type);
  779. }
  780. /// Return true if this instruction is a register move.
  781. /// (including moving values from subreg to reg)
  782. bool isMoveReg(QueryType Type = IgnoreBundle) const {
  783. return hasProperty(MCID::MoveReg, Type);
  784. }
  785. /// Return true if this instruction is a bitcast instruction.
  786. bool isBitcast(QueryType Type = IgnoreBundle) const {
  787. return hasProperty(MCID::Bitcast, Type);
  788. }
  789. /// Return true if this instruction is a select instruction.
  790. bool isSelect(QueryType Type = IgnoreBundle) const {
  791. return hasProperty(MCID::Select, Type);
  792. }
  793. /// Return true if this instruction cannot be safely duplicated.
  794. /// For example, if the instruction has a unique labels attached
  795. /// to it, duplicating it would cause multiple definition errors.
  796. bool isNotDuplicable(QueryType Type = AnyInBundle) const {
  797. return hasProperty(MCID::NotDuplicable, Type);
  798. }
  799. /// Return true if this instruction is convergent.
  800. /// Convergent instructions can not be made control-dependent on any
  801. /// additional values.
  802. bool isConvergent(QueryType Type = AnyInBundle) const {
  803. if (isInlineAsm()) {
  804. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  805. if (ExtraInfo & InlineAsm::Extra_IsConvergent)
  806. return true;
  807. }
  808. return hasProperty(MCID::Convergent, Type);
  809. }
  810. /// Returns true if the specified instruction has a delay slot
  811. /// which must be filled by the code generator.
  812. bool hasDelaySlot(QueryType Type = AnyInBundle) const {
  813. return hasProperty(MCID::DelaySlot, Type);
  814. }
  815. /// Return true for instructions that can be folded as
  816. /// memory operands in other instructions. The most common use for this
  817. /// is instructions that are simple loads from memory that don't modify
  818. /// the loaded value in any way, but it can also be used for instructions
  819. /// that can be expressed as constant-pool loads, such as V_SETALLONES
  820. /// on x86, to allow them to be folded when it is beneficial.
  821. /// This should only be set on instructions that return a value in their
  822. /// only virtual register definition.
  823. bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
  824. return hasProperty(MCID::FoldableAsLoad, Type);
  825. }
  826. /// Return true if this instruction behaves
  827. /// the same way as the generic REG_SEQUENCE instructions.
  828. /// E.g., on ARM,
  829. /// dX VMOVDRR rY, rZ
  830. /// is equivalent to
  831. /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
  832. ///
  833. /// Note that for the optimizers to be able to take advantage of
  834. /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
  835. /// override accordingly.
  836. bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
  837. return hasProperty(MCID::RegSequence, Type);
  838. }
  839. /// Return true if this instruction behaves
  840. /// the same way as the generic EXTRACT_SUBREG instructions.
  841. /// E.g., on ARM,
  842. /// rX, rY VMOVRRD dZ
  843. /// is equivalent to two EXTRACT_SUBREG:
  844. /// rX = EXTRACT_SUBREG dZ, ssub_0
  845. /// rY = EXTRACT_SUBREG dZ, ssub_1
  846. ///
  847. /// Note that for the optimizers to be able to take advantage of
  848. /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
  849. /// override accordingly.
  850. bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
  851. return hasProperty(MCID::ExtractSubreg, Type);
  852. }
  853. /// Return true if this instruction behaves
  854. /// the same way as the generic INSERT_SUBREG instructions.
  855. /// E.g., on ARM,
  856. /// dX = VSETLNi32 dY, rZ, Imm
  857. /// is equivalent to a INSERT_SUBREG:
  858. /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
  859. ///
  860. /// Note that for the optimizers to be able to take advantage of
  861. /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
  862. /// override accordingly.
  863. bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
  864. return hasProperty(MCID::InsertSubreg, Type);
  865. }
  866. //===--------------------------------------------------------------------===//
  867. // Side Effect Analysis
  868. //===--------------------------------------------------------------------===//
  869. /// Return true if this instruction could possibly read memory.
  870. /// Instructions with this flag set are not necessarily simple load
  871. /// instructions, they may load a value and modify it, for example.
  872. bool mayLoad(QueryType Type = AnyInBundle) const {
  873. if (isInlineAsm()) {
  874. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  875. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  876. return true;
  877. }
  878. return hasProperty(MCID::MayLoad, Type);
  879. }
  880. /// Return true if this instruction could possibly modify memory.
  881. /// Instructions with this flag set are not necessarily simple store
  882. /// instructions, they may store a modified value based on their operands, or
  883. /// may not actually modify anything, for example.
  884. bool mayStore(QueryType Type = AnyInBundle) const {
  885. if (isInlineAsm()) {
  886. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  887. if (ExtraInfo & InlineAsm::Extra_MayStore)
  888. return true;
  889. }
  890. return hasProperty(MCID::MayStore, Type);
  891. }
  892. /// Return true if this instruction could possibly read or modify memory.
  893. bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
  894. return mayLoad(Type) || mayStore(Type);
  895. }
  896. /// Return true if this instruction could possibly raise a floating-point
  897. /// exception. This is the case if the instruction is a floating-point
  898. /// instruction that can in principle raise an exception, as indicated
  899. /// by the MCID::MayRaiseFPException property, *and* at the same time,
  900. /// the instruction is used in a context where we expect floating-point
  901. /// exceptions are not disabled, as indicated by the NoFPExcept MI flag.
  902. bool mayRaiseFPException() const {
  903. return hasProperty(MCID::MayRaiseFPException) &&
  904. !getFlag(MachineInstr::MIFlag::NoFPExcept);
  905. }
  906. //===--------------------------------------------------------------------===//
  907. // Flags that indicate whether an instruction can be modified by a method.
  908. //===--------------------------------------------------------------------===//
  909. /// Return true if this may be a 2- or 3-address
  910. /// instruction (of the form "X = op Y, Z, ..."), which produces the same
  911. /// result if Y and Z are exchanged. If this flag is set, then the
  912. /// TargetInstrInfo::commuteInstruction method may be used to hack on the
  913. /// instruction.
  914. ///
  915. /// Note that this flag may be set on instructions that are only commutable
  916. /// sometimes. In these cases, the call to commuteInstruction will fail.
  917. /// Also note that some instructions require non-trivial modification to
  918. /// commute them.
  919. bool isCommutable(QueryType Type = IgnoreBundle) const {
  920. return hasProperty(MCID::Commutable, Type);
  921. }
  922. /// Return true if this is a 2-address instruction
  923. /// which can be changed into a 3-address instruction if needed. Doing this
  924. /// transformation can be profitable in the register allocator, because it
  925. /// means that the instruction can use a 2-address form if possible, but
  926. /// degrade into a less efficient form if the source and dest register cannot
  927. /// be assigned to the same register. For example, this allows the x86
  928. /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
  929. /// is the same speed as the shift but has bigger code size.
  930. ///
  931. /// If this returns true, then the target must implement the
  932. /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
  933. /// is allowed to fail if the transformation isn't valid for this specific
  934. /// instruction (e.g. shl reg, 4 on x86).
  935. ///
  936. bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
  937. return hasProperty(MCID::ConvertibleTo3Addr, Type);
  938. }
  939. /// Return true if this instruction requires
  940. /// custom insertion support when the DAG scheduler is inserting it into a
  941. /// machine basic block. If this is true for the instruction, it basically
  942. /// means that it is a pseudo instruction used at SelectionDAG time that is
  943. /// expanded out into magic code by the target when MachineInstrs are formed.
  944. ///
  945. /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
  946. /// is used to insert this into the MachineBasicBlock.
  947. bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
  948. return hasProperty(MCID::UsesCustomInserter, Type);
  949. }
  950. /// Return true if this instruction requires *adjustment*
  951. /// after instruction selection by calling a target hook. For example, this
  952. /// can be used to fill in ARM 's' optional operand depending on whether
  953. /// the conditional flag register is used.
  954. bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
  955. return hasProperty(MCID::HasPostISelHook, Type);
  956. }
  957. /// Returns true if this instruction is a candidate for remat.
  958. /// This flag is deprecated, please don't use it anymore. If this
  959. /// flag is set, the isReallyTriviallyReMaterializable() method is called to
  960. /// verify the instruction is really rematable.
  961. bool isRematerializable(QueryType Type = AllInBundle) const {
  962. // It's only possible to re-mat a bundle if all bundled instructions are
  963. // re-materializable.
  964. return hasProperty(MCID::Rematerializable, Type);
  965. }
  966. /// Returns true if this instruction has the same cost (or less) than a move
  967. /// instruction. This is useful during certain types of optimizations
  968. /// (e.g., remat during two-address conversion or machine licm)
  969. /// where we would like to remat or hoist the instruction, but not if it costs
  970. /// more than moving the instruction into the appropriate register. Note, we
  971. /// are not marking copies from and to the same register class with this flag.
  972. bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
  973. // Only returns true for a bundle if all bundled instructions are cheap.
  974. return hasProperty(MCID::CheapAsAMove, Type);
  975. }
  976. /// Returns true if this instruction source operands
  977. /// have special register allocation requirements that are not captured by the
  978. /// operand register classes. e.g. ARM::STRD's two source registers must be an
  979. /// even / odd pair, ARM::STM registers have to be in ascending order.
  980. /// Post-register allocation passes should not attempt to change allocations
  981. /// for sources of instructions with this flag.
  982. bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
  983. return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
  984. }
  985. /// Returns true if this instruction def operands
  986. /// have special register allocation requirements that are not captured by the
  987. /// operand register classes. e.g. ARM::LDRD's two def registers must be an
  988. /// even / odd pair, ARM::LDM registers have to be in ascending order.
  989. /// Post-register allocation passes should not attempt to change allocations
  990. /// for definitions of instructions with this flag.
  991. bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
  992. return hasProperty(MCID::ExtraDefRegAllocReq, Type);
  993. }
  994. enum MICheckType {
  995. CheckDefs, // Check all operands for equality
  996. CheckKillDead, // Check all operands including kill / dead markers
  997. IgnoreDefs, // Ignore all definitions
  998. IgnoreVRegDefs // Ignore virtual register definitions
  999. };
  1000. /// Return true if this instruction is identical to \p Other.
  1001. /// Two instructions are identical if they have the same opcode and all their
  1002. /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
  1003. /// Note that this means liveness related flags (dead, undef, kill) do not
  1004. /// affect the notion of identical.
  1005. bool isIdenticalTo(const MachineInstr &Other,
  1006. MICheckType Check = CheckDefs) const;
  1007. /// Unlink 'this' from the containing basic block, and return it without
  1008. /// deleting it.
  1009. ///
  1010. /// This function can not be used on bundled instructions, use
  1011. /// removeFromBundle() to remove individual instructions from a bundle.
  1012. MachineInstr *removeFromParent();
  1013. /// Unlink this instruction from its basic block and return it without
  1014. /// deleting it.
  1015. ///
  1016. /// If the instruction is part of a bundle, the other instructions in the
  1017. /// bundle remain bundled.
  1018. MachineInstr *removeFromBundle();
  1019. /// Unlink 'this' from the containing basic block and delete it.
  1020. ///
  1021. /// If this instruction is the header of a bundle, the whole bundle is erased.
  1022. /// This function can not be used for instructions inside a bundle, use
  1023. /// eraseFromBundle() to erase individual bundled instructions.
  1024. void eraseFromParent();
  1025. /// Unlink 'this' form its basic block and delete it.
  1026. ///
  1027. /// If the instruction is part of a bundle, the other instructions in the
  1028. /// bundle remain bundled.
  1029. void eraseFromBundle();
  1030. bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
  1031. bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
  1032. bool isAnnotationLabel() const {
  1033. return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
  1034. }
  1035. /// Returns true if the MachineInstr represents a label.
  1036. bool isLabel() const {
  1037. return isEHLabel() || isGCLabel() || isAnnotationLabel();
  1038. }
  1039. bool isCFIInstruction() const {
  1040. return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
  1041. }
  1042. bool isPseudoProbe() const {
  1043. return getOpcode() == TargetOpcode::PSEUDO_PROBE;
  1044. }
  1045. // True if the instruction represents a position in the function.
  1046. bool isPosition() const { return isLabel() || isCFIInstruction(); }
  1047. bool isNonListDebugValue() const {
  1048. return getOpcode() == TargetOpcode::DBG_VALUE;
  1049. }
  1050. bool isDebugValueList() const {
  1051. return getOpcode() == TargetOpcode::DBG_VALUE_LIST;
  1052. }
  1053. bool isDebugValue() const {
  1054. return isNonListDebugValue() || isDebugValueList();
  1055. }
  1056. bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
  1057. bool isDebugRef() const { return getOpcode() == TargetOpcode::DBG_INSTR_REF; }
  1058. bool isDebugPHI() const { return getOpcode() == TargetOpcode::DBG_PHI; }
  1059. bool isDebugInstr() const {
  1060. return isDebugValue() || isDebugLabel() || isDebugRef() || isDebugPHI();
  1061. }
  1062. bool isDebugOrPseudoInstr() const {
  1063. return isDebugInstr() || isPseudoProbe();
  1064. }
  1065. bool isDebugOffsetImm() const {
  1066. return isNonListDebugValue() && getDebugOffset().isImm();
  1067. }
  1068. /// A DBG_VALUE is indirect iff the location operand is a register and
  1069. /// the offset operand is an immediate.
  1070. bool isIndirectDebugValue() const {
  1071. return isDebugOffsetImm() && getDebugOperand(0).isReg();
  1072. }
  1073. /// A DBG_VALUE is an entry value iff its debug expression contains the
  1074. /// DW_OP_LLVM_entry_value operation.
  1075. bool isDebugEntryValue() const;
  1076. /// Return true if the instruction is a debug value which describes a part of
  1077. /// a variable as unavailable.
  1078. bool isUndefDebugValue() const {
  1079. if (!isDebugValue())
  1080. return false;
  1081. // If any $noreg locations are given, this DV is undef.
  1082. for (const MachineOperand &Op : debug_operands())
  1083. if (Op.isReg() && !Op.getReg().isValid())
  1084. return true;
  1085. return false;
  1086. }
  1087. bool isPHI() const {
  1088. return getOpcode() == TargetOpcode::PHI ||
  1089. getOpcode() == TargetOpcode::G_PHI;
  1090. }
  1091. bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
  1092. bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
  1093. bool isInlineAsm() const {
  1094. return getOpcode() == TargetOpcode::INLINEASM ||
  1095. getOpcode() == TargetOpcode::INLINEASM_BR;
  1096. }
  1097. /// FIXME: Seems like a layering violation that the AsmDialect, which is X86
  1098. /// specific, be attached to a generic MachineInstr.
  1099. bool isMSInlineAsm() const {
  1100. return isInlineAsm() && getInlineAsmDialect() == InlineAsm::AD_Intel;
  1101. }
  1102. bool isStackAligningInlineAsm() const;
  1103. InlineAsm::AsmDialect getInlineAsmDialect() const;
  1104. bool isInsertSubreg() const {
  1105. return getOpcode() == TargetOpcode::INSERT_SUBREG;
  1106. }
  1107. bool isSubregToReg() const {
  1108. return getOpcode() == TargetOpcode::SUBREG_TO_REG;
  1109. }
  1110. bool isRegSequence() const {
  1111. return getOpcode() == TargetOpcode::REG_SEQUENCE;
  1112. }
  1113. bool isBundle() const {
  1114. return getOpcode() == TargetOpcode::BUNDLE;
  1115. }
  1116. bool isCopy() const {
  1117. return getOpcode() == TargetOpcode::COPY;
  1118. }
  1119. bool isFullCopy() const {
  1120. return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
  1121. }
  1122. bool isExtractSubreg() const {
  1123. return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
  1124. }
  1125. /// Return true if the instruction behaves like a copy.
  1126. /// This does not include native copy instructions.
  1127. bool isCopyLike() const {
  1128. return isCopy() || isSubregToReg();
  1129. }
  1130. /// Return true is the instruction is an identity copy.
  1131. bool isIdentityCopy() const {
  1132. return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
  1133. getOperand(0).getSubReg() == getOperand(1).getSubReg();
  1134. }
  1135. /// Return true if this instruction doesn't produce any output in the form of
  1136. /// executable instructions.
  1137. bool isMetaInstruction() const {
  1138. switch (getOpcode()) {
  1139. default:
  1140. return false;
  1141. case TargetOpcode::IMPLICIT_DEF:
  1142. case TargetOpcode::KILL:
  1143. case TargetOpcode::CFI_INSTRUCTION:
  1144. case TargetOpcode::EH_LABEL:
  1145. case TargetOpcode::GC_LABEL:
  1146. case TargetOpcode::DBG_VALUE:
  1147. case TargetOpcode::DBG_VALUE_LIST:
  1148. case TargetOpcode::DBG_INSTR_REF:
  1149. case TargetOpcode::DBG_PHI:
  1150. case TargetOpcode::DBG_LABEL:
  1151. case TargetOpcode::LIFETIME_START:
  1152. case TargetOpcode::LIFETIME_END:
  1153. case TargetOpcode::PSEUDO_PROBE:
  1154. case TargetOpcode::ARITH_FENCE:
  1155. return true;
  1156. }
  1157. }
  1158. /// Return true if this is a transient instruction that is either very likely
  1159. /// to be eliminated during register allocation (such as copy-like
  1160. /// instructions), or if this instruction doesn't have an execution-time cost.
  1161. bool isTransient() const {
  1162. switch (getOpcode()) {
  1163. default:
  1164. return isMetaInstruction();
  1165. // Copy-like instructions are usually eliminated during register allocation.
  1166. case TargetOpcode::PHI:
  1167. case TargetOpcode::G_PHI:
  1168. case TargetOpcode::COPY:
  1169. case TargetOpcode::INSERT_SUBREG:
  1170. case TargetOpcode::SUBREG_TO_REG:
  1171. case TargetOpcode::REG_SEQUENCE:
  1172. return true;
  1173. }
  1174. }
  1175. /// Return the number of instructions inside the MI bundle, excluding the
  1176. /// bundle header.
  1177. ///
  1178. /// This is the number of instructions that MachineBasicBlock::iterator
  1179. /// skips, 0 for unbundled instructions.
  1180. unsigned getBundleSize() const;
  1181. /// Return true if the MachineInstr reads the specified register.
  1182. /// If TargetRegisterInfo is passed, then it also checks if there
  1183. /// is a read of a super-register.
  1184. /// This does not count partial redefines of virtual registers as reads:
  1185. /// %reg1024:6 = OP.
  1186. bool readsRegister(Register Reg,
  1187. const TargetRegisterInfo *TRI = nullptr) const {
  1188. return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
  1189. }
  1190. /// Return true if the MachineInstr reads the specified virtual register.
  1191. /// Take into account that a partial define is a
  1192. /// read-modify-write operation.
  1193. bool readsVirtualRegister(Register Reg) const {
  1194. return readsWritesVirtualRegister(Reg).first;
  1195. }
  1196. /// Return a pair of bools (reads, writes) indicating if this instruction
  1197. /// reads or writes Reg. This also considers partial defines.
  1198. /// If Ops is not null, all operand indices for Reg are added.
  1199. std::pair<bool,bool> readsWritesVirtualRegister(Register Reg,
  1200. SmallVectorImpl<unsigned> *Ops = nullptr) const;
  1201. /// Return true if the MachineInstr kills the specified register.
  1202. /// If TargetRegisterInfo is passed, then it also checks if there is
  1203. /// a kill of a super-register.
  1204. bool killsRegister(Register Reg,
  1205. const TargetRegisterInfo *TRI = nullptr) const {
  1206. return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
  1207. }
  1208. /// Return true if the MachineInstr fully defines the specified register.
  1209. /// If TargetRegisterInfo is passed, then it also checks
  1210. /// if there is a def of a super-register.
  1211. /// NOTE: It's ignoring subreg indices on virtual registers.
  1212. bool definesRegister(Register Reg,
  1213. const TargetRegisterInfo *TRI = nullptr) const {
  1214. return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
  1215. }
  1216. /// Return true if the MachineInstr modifies (fully define or partially
  1217. /// define) the specified register.
  1218. /// NOTE: It's ignoring subreg indices on virtual registers.
  1219. bool modifiesRegister(Register Reg,
  1220. const TargetRegisterInfo *TRI = nullptr) const {
  1221. return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
  1222. }
  1223. /// Returns true if the register is dead in this machine instruction.
  1224. /// If TargetRegisterInfo is passed, then it also checks
  1225. /// if there is a dead def of a super-register.
  1226. bool registerDefIsDead(Register Reg,
  1227. const TargetRegisterInfo *TRI = nullptr) const {
  1228. return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
  1229. }
  1230. /// Returns true if the MachineInstr has an implicit-use operand of exactly
  1231. /// the given register (not considering sub/super-registers).
  1232. bool hasRegisterImplicitUseOperand(Register Reg) const;
  1233. /// Returns the operand index that is a use of the specific register or -1
  1234. /// if it is not found. It further tightens the search criteria to a use
  1235. /// that kills the register if isKill is true.
  1236. int findRegisterUseOperandIdx(Register Reg, bool isKill = false,
  1237. const TargetRegisterInfo *TRI = nullptr) const;
  1238. /// Wrapper for findRegisterUseOperandIdx, it returns
  1239. /// a pointer to the MachineOperand rather than an index.
  1240. MachineOperand *findRegisterUseOperand(Register Reg, bool isKill = false,
  1241. const TargetRegisterInfo *TRI = nullptr) {
  1242. int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
  1243. return (Idx == -1) ? nullptr : &getOperand(Idx);
  1244. }
  1245. const MachineOperand *findRegisterUseOperand(
  1246. Register Reg, bool isKill = false,
  1247. const TargetRegisterInfo *TRI = nullptr) const {
  1248. return const_cast<MachineInstr *>(this)->
  1249. findRegisterUseOperand(Reg, isKill, TRI);
  1250. }
  1251. /// Returns the operand index that is a def of the specified register or
  1252. /// -1 if it is not found. If isDead is true, defs that are not dead are
  1253. /// skipped. If Overlap is true, then it also looks for defs that merely
  1254. /// overlap the specified register. If TargetRegisterInfo is non-null,
  1255. /// then it also checks if there is a def of a super-register.
  1256. /// This may also return a register mask operand when Overlap is true.
  1257. int findRegisterDefOperandIdx(Register Reg,
  1258. bool isDead = false, bool Overlap = false,
  1259. const TargetRegisterInfo *TRI = nullptr) const;
  1260. /// Wrapper for findRegisterDefOperandIdx, it returns
  1261. /// a pointer to the MachineOperand rather than an index.
  1262. MachineOperand *
  1263. findRegisterDefOperand(Register Reg, bool isDead = false,
  1264. bool Overlap = false,
  1265. const TargetRegisterInfo *TRI = nullptr) {
  1266. int Idx = findRegisterDefOperandIdx(Reg, isDead, Overlap, TRI);
  1267. return (Idx == -1) ? nullptr : &getOperand(Idx);
  1268. }
  1269. const MachineOperand *
  1270. findRegisterDefOperand(Register Reg, bool isDead = false,
  1271. bool Overlap = false,
  1272. const TargetRegisterInfo *TRI = nullptr) const {
  1273. return const_cast<MachineInstr *>(this)->findRegisterDefOperand(
  1274. Reg, isDead, Overlap, TRI);
  1275. }
  1276. /// Find the index of the first operand in the
  1277. /// operand list that is used to represent the predicate. It returns -1 if
  1278. /// none is found.
  1279. int findFirstPredOperandIdx() const;
  1280. /// Find the index of the flag word operand that
  1281. /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if
  1282. /// getOperand(OpIdx) does not belong to an inline asm operand group.
  1283. ///
  1284. /// If GroupNo is not NULL, it will receive the number of the operand group
  1285. /// containing OpIdx.
  1286. int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
  1287. /// Compute the static register class constraint for operand OpIdx.
  1288. /// For normal instructions, this is derived from the MCInstrDesc.
  1289. /// For inline assembly it is derived from the flag words.
  1290. ///
  1291. /// Returns NULL if the static register class constraint cannot be
  1292. /// determined.
  1293. const TargetRegisterClass*
  1294. getRegClassConstraint(unsigned OpIdx,
  1295. const TargetInstrInfo *TII,
  1296. const TargetRegisterInfo *TRI) const;
  1297. /// Applies the constraints (def/use) implied by this MI on \p Reg to
  1298. /// the given \p CurRC.
  1299. /// If \p ExploreBundle is set and MI is part of a bundle, all the
  1300. /// instructions inside the bundle will be taken into account. In other words,
  1301. /// this method accumulates all the constraints of the operand of this MI and
  1302. /// the related bundle if MI is a bundle or inside a bundle.
  1303. ///
  1304. /// Returns the register class that satisfies both \p CurRC and the
  1305. /// constraints set by MI. Returns NULL if such a register class does not
  1306. /// exist.
  1307. ///
  1308. /// \pre CurRC must not be NULL.
  1309. const TargetRegisterClass *getRegClassConstraintEffectForVReg(
  1310. Register Reg, const TargetRegisterClass *CurRC,
  1311. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
  1312. bool ExploreBundle = false) const;
  1313. /// Applies the constraints (def/use) implied by the \p OpIdx operand
  1314. /// to the given \p CurRC.
  1315. ///
  1316. /// Returns the register class that satisfies both \p CurRC and the
  1317. /// constraints set by \p OpIdx MI. Returns NULL if such a register class
  1318. /// does not exist.
  1319. ///
  1320. /// \pre CurRC must not be NULL.
  1321. /// \pre The operand at \p OpIdx must be a register.
  1322. const TargetRegisterClass *
  1323. getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
  1324. const TargetInstrInfo *TII,
  1325. const TargetRegisterInfo *TRI) const;
  1326. /// Add a tie between the register operands at DefIdx and UseIdx.
  1327. /// The tie will cause the register allocator to ensure that the two
  1328. /// operands are assigned the same physical register.
  1329. ///
  1330. /// Tied operands are managed automatically for explicit operands in the
  1331. /// MCInstrDesc. This method is for exceptional cases like inline asm.
  1332. void tieOperands(unsigned DefIdx, unsigned UseIdx);
  1333. /// Given the index of a tied register operand, find the
  1334. /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
  1335. /// index of the tied operand which must exist.
  1336. unsigned findTiedOperandIdx(unsigned OpIdx) const;
  1337. /// Given the index of a register def operand,
  1338. /// check if the register def is tied to a source operand, due to either
  1339. /// two-address elimination or inline assembly constraints. Returns the
  1340. /// first tied use operand index by reference if UseOpIdx is not null.
  1341. bool isRegTiedToUseOperand(unsigned DefOpIdx,
  1342. unsigned *UseOpIdx = nullptr) const {
  1343. const MachineOperand &MO = getOperand(DefOpIdx);
  1344. if (!MO.isReg() || !MO.isDef() || !MO.isTied())
  1345. return false;
  1346. if (UseOpIdx)
  1347. *UseOpIdx = findTiedOperandIdx(DefOpIdx);
  1348. return true;
  1349. }
  1350. /// Return true if the use operand of the specified index is tied to a def
  1351. /// operand. It also returns the def operand index by reference if DefOpIdx
  1352. /// is not null.
  1353. bool isRegTiedToDefOperand(unsigned UseOpIdx,
  1354. unsigned *DefOpIdx = nullptr) const {
  1355. const MachineOperand &MO = getOperand(UseOpIdx);
  1356. if (!MO.isReg() || !MO.isUse() || !MO.isTied())
  1357. return false;
  1358. if (DefOpIdx)
  1359. *DefOpIdx = findTiedOperandIdx(UseOpIdx);
  1360. return true;
  1361. }
  1362. /// Clears kill flags on all operands.
  1363. void clearKillInfo();
  1364. /// Replace all occurrences of FromReg with ToReg:SubIdx,
  1365. /// properly composing subreg indices where necessary.
  1366. void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx,
  1367. const TargetRegisterInfo &RegInfo);
  1368. /// We have determined MI kills a register. Look for the
  1369. /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
  1370. /// add a implicit operand if it's not found. Returns true if the operand
  1371. /// exists / is added.
  1372. bool addRegisterKilled(Register IncomingReg,
  1373. const TargetRegisterInfo *RegInfo,
  1374. bool AddIfNotFound = false);
  1375. /// Clear all kill flags affecting Reg. If RegInfo is provided, this includes
  1376. /// all aliasing registers.
  1377. void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo);
  1378. /// We have determined MI defined a register without a use.
  1379. /// Look for the operand that defines it and mark it as IsDead. If
  1380. /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
  1381. /// true if the operand exists / is added.
  1382. bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo,
  1383. bool AddIfNotFound = false);
  1384. /// Clear all dead flags on operands defining register @p Reg.
  1385. void clearRegisterDeads(Register Reg);
  1386. /// Mark all subregister defs of register @p Reg with the undef flag.
  1387. /// This function is used when we determined to have a subregister def in an
  1388. /// otherwise undefined super register.
  1389. void setRegisterDefReadUndef(Register Reg, bool IsUndef = true);
  1390. /// We have determined MI defines a register. Make sure there is an operand
  1391. /// defining Reg.
  1392. void addRegisterDefined(Register Reg,
  1393. const TargetRegisterInfo *RegInfo = nullptr);
  1394. /// Mark every physreg used by this instruction as
  1395. /// dead except those in the UsedRegs list.
  1396. ///
  1397. /// On instructions with register mask operands, also add implicit-def
  1398. /// operands for all registers in UsedRegs.
  1399. void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs,
  1400. const TargetRegisterInfo &TRI);
  1401. /// Return true if it is safe to move this instruction. If
  1402. /// SawStore is set to true, it means that there is a store (or call) between
  1403. /// the instruction's location and its intended destination.
  1404. bool isSafeToMove(AAResults *AA, bool &SawStore) const;
  1405. /// Returns true if this instruction's memory access aliases the memory
  1406. /// access of Other.
  1407. //
  1408. /// Assumes any physical registers used to compute addresses
  1409. /// have the same value for both instructions. Returns false if neither
  1410. /// instruction writes to memory.
  1411. ///
  1412. /// @param AA Optional alias analysis, used to compare memory operands.
  1413. /// @param Other MachineInstr to check aliasing against.
  1414. /// @param UseTBAA Whether to pass TBAA information to alias analysis.
  1415. bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const;
  1416. /// Return true if this instruction may have an ordered
  1417. /// or volatile memory reference, or if the information describing the memory
  1418. /// reference is not available. Return false if it is known to have no
  1419. /// ordered or volatile memory references.
  1420. bool hasOrderedMemoryRef() const;
  1421. /// Return true if this load instruction never traps and points to a memory
  1422. /// location whose value doesn't change during the execution of this function.
  1423. ///
  1424. /// Examples include loading a value from the constant pool or from the
  1425. /// argument area of a function (if it does not change). If the instruction
  1426. /// does multiple loads, this returns true only if all of the loads are
  1427. /// dereferenceable and invariant.
  1428. bool isDereferenceableInvariantLoad(AAResults *AA) const;
  1429. /// If the specified instruction is a PHI that always merges together the
  1430. /// same virtual register, return the register, otherwise return 0.
  1431. unsigned isConstantValuePHI() const;
  1432. /// Return true if this instruction has side effects that are not modeled
  1433. /// by mayLoad / mayStore, etc.
  1434. /// For all instructions, the property is encoded in MCInstrDesc::Flags
  1435. /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
  1436. /// INLINEASM instruction, in which case the side effect property is encoded
  1437. /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
  1438. ///
  1439. bool hasUnmodeledSideEffects() const;
  1440. /// Returns true if it is illegal to fold a load across this instruction.
  1441. bool isLoadFoldBarrier() const;
  1442. /// Return true if all the defs of this instruction are dead.
  1443. bool allDefsAreDead() const;
  1444. /// Return a valid size if the instruction is a spill instruction.
  1445. Optional<unsigned> getSpillSize(const TargetInstrInfo *TII) const;
  1446. /// Return a valid size if the instruction is a folded spill instruction.
  1447. Optional<unsigned> getFoldedSpillSize(const TargetInstrInfo *TII) const;
  1448. /// Return a valid size if the instruction is a restore instruction.
  1449. Optional<unsigned> getRestoreSize(const TargetInstrInfo *TII) const;
  1450. /// Return a valid size if the instruction is a folded restore instruction.
  1451. Optional<unsigned>
  1452. getFoldedRestoreSize(const TargetInstrInfo *TII) const;
  1453. /// Copy implicit register operands from specified
  1454. /// instruction to this instruction.
  1455. void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
  1456. /// Debugging support
  1457. /// @{
  1458. /// Determine the generic type to be printed (if needed) on uses and defs.
  1459. LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
  1460. const MachineRegisterInfo &MRI) const;
  1461. /// Return true when an instruction has tied register that can't be determined
  1462. /// by the instruction's descriptor. This is useful for MIR printing, to
  1463. /// determine whether we need to print the ties or not.
  1464. bool hasComplexRegisterTies() const;
  1465. /// Print this MI to \p OS.
  1466. /// Don't print information that can be inferred from other instructions if
  1467. /// \p IsStandalone is false. It is usually true when only a fragment of the
  1468. /// function is printed.
  1469. /// Only print the defs and the opcode if \p SkipOpers is true.
  1470. /// Otherwise, also print operands if \p SkipDebugLoc is true.
  1471. /// Otherwise, also print the debug loc, with a terminating newline.
  1472. /// \p TII is used to print the opcode name. If it's not present, but the
  1473. /// MI is in a function, the opcode will be printed using the function's TII.
  1474. void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
  1475. bool SkipDebugLoc = false, bool AddNewLine = true,
  1476. const TargetInstrInfo *TII = nullptr) const;
  1477. void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
  1478. bool SkipOpers = false, bool SkipDebugLoc = false,
  1479. bool AddNewLine = true,
  1480. const TargetInstrInfo *TII = nullptr) const;
  1481. void dump() const;
  1482. /// Print on dbgs() the current instruction and the instructions defining its
  1483. /// operands and so on until we reach \p MaxDepth.
  1484. void dumpr(const MachineRegisterInfo &MRI,
  1485. unsigned MaxDepth = UINT_MAX) const;
  1486. /// @}
  1487. //===--------------------------------------------------------------------===//
  1488. // Accessors used to build up machine instructions.
  1489. /// Add the specified operand to the instruction. If it is an implicit
  1490. /// operand, it is added to the end of the operand list. If it is an
  1491. /// explicit operand it is added at the end of the explicit operand list
  1492. /// (before the first implicit operand).
  1493. ///
  1494. /// MF must be the machine function that was used to allocate this
  1495. /// instruction.
  1496. ///
  1497. /// MachineInstrBuilder provides a more convenient interface for creating
  1498. /// instructions and adding operands.
  1499. void addOperand(MachineFunction &MF, const MachineOperand &Op);
  1500. /// Add an operand without providing an MF reference. This only works for
  1501. /// instructions that are inserted in a basic block.
  1502. ///
  1503. /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
  1504. /// preferred.
  1505. void addOperand(const MachineOperand &Op);
  1506. /// Replace the instruction descriptor (thus opcode) of
  1507. /// the current instruction with a new one.
  1508. void setDesc(const MCInstrDesc &TID) { MCID = &TID; }
  1509. /// Replace current source information with new such.
  1510. /// Avoid using this, the constructor argument is preferable.
  1511. void setDebugLoc(DebugLoc DL) {
  1512. DbgLoc = std::move(DL);
  1513. assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor");
  1514. }
  1515. /// Erase an operand from an instruction, leaving it with one
  1516. /// fewer operand than it started with.
  1517. void RemoveOperand(unsigned OpNo);
  1518. /// Clear this MachineInstr's memory reference descriptor list. This resets
  1519. /// the memrefs to their most conservative state. This should be used only
  1520. /// as a last resort since it greatly pessimizes our knowledge of the memory
  1521. /// access performed by the instruction.
  1522. void dropMemRefs(MachineFunction &MF);
  1523. /// Assign this MachineInstr's memory reference descriptor list.
  1524. ///
  1525. /// Unlike other methods, this *will* allocate them into a new array
  1526. /// associated with the provided `MachineFunction`.
  1527. void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs);
  1528. /// Add a MachineMemOperand to the machine instruction.
  1529. /// This function should be used only occasionally. The setMemRefs function
  1530. /// is the primary method for setting up a MachineInstr's MemRefs list.
  1531. void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
  1532. /// Clone another MachineInstr's memory reference descriptor list and replace
  1533. /// ours with it.
  1534. ///
  1535. /// Note that `*this` may be the incoming MI!
  1536. ///
  1537. /// Prefer this API whenever possible as it can avoid allocations in common
  1538. /// cases.
  1539. void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI);
  1540. /// Clone the merge of multiple MachineInstrs' memory reference descriptors
  1541. /// list and replace ours with it.
  1542. ///
  1543. /// Note that `*this` may be one of the incoming MIs!
  1544. ///
  1545. /// Prefer this API whenever possible as it can avoid allocations in common
  1546. /// cases.
  1547. void cloneMergedMemRefs(MachineFunction &MF,
  1548. ArrayRef<const MachineInstr *> MIs);
  1549. /// Set a symbol that will be emitted just prior to the instruction itself.
  1550. ///
  1551. /// Setting this to a null pointer will remove any such symbol.
  1552. ///
  1553. /// FIXME: This is not fully implemented yet.
  1554. void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
  1555. /// Set a symbol that will be emitted just after the instruction itself.
  1556. ///
  1557. /// Setting this to a null pointer will remove any such symbol.
  1558. ///
  1559. /// FIXME: This is not fully implemented yet.
  1560. void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
  1561. /// Clone another MachineInstr's pre- and post- instruction symbols and
  1562. /// replace ours with it.
  1563. void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI);
  1564. /// Set a marker on instructions that denotes where we should create and emit
  1565. /// heap alloc site labels. This waits until after instruction selection and
  1566. /// optimizations to create the label, so it should still work if the
  1567. /// instruction is removed or duplicated.
  1568. void setHeapAllocMarker(MachineFunction &MF, MDNode *MD);
  1569. /// Return the MIFlags which represent both MachineInstrs. This
  1570. /// should be used when merging two MachineInstrs into one. This routine does
  1571. /// not modify the MIFlags of this MachineInstr.
  1572. uint16_t mergeFlagsWith(const MachineInstr& Other) const;
  1573. static uint16_t copyFlagsFromInstruction(const Instruction &I);
  1574. /// Copy all flags to MachineInst MIFlags
  1575. void copyIRFlags(const Instruction &I);
  1576. /// Break any tie involving OpIdx.
  1577. void untieRegOperand(unsigned OpIdx) {
  1578. MachineOperand &MO = getOperand(OpIdx);
  1579. if (MO.isReg() && MO.isTied()) {
  1580. getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
  1581. MO.TiedTo = 0;
  1582. }
  1583. }
  1584. /// Add all implicit def and use operands to this instruction.
  1585. void addImplicitDefUseOperands(MachineFunction &MF);
  1586. /// Scan instructions immediately following MI and collect any matching
  1587. /// DBG_VALUEs.
  1588. void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues);
  1589. /// Find all DBG_VALUEs that point to the register def in this instruction
  1590. /// and point them to \p Reg instead.
  1591. void changeDebugValuesDefReg(Register Reg);
  1592. /// Returns the Intrinsic::ID for this instruction.
  1593. /// \pre Must have an intrinsic ID operand.
  1594. unsigned getIntrinsicID() const {
  1595. return getOperand(getNumExplicitDefs()).getIntrinsicID();
  1596. }
  1597. /// Sets all register debug operands in this debug value instruction to be
  1598. /// undef.
  1599. void setDebugValueUndef() {
  1600. assert(isDebugValue() && "Must be a debug value instruction.");
  1601. for (MachineOperand &MO : debug_operands()) {
  1602. if (MO.isReg()) {
  1603. MO.setReg(0);
  1604. MO.setSubReg(0);
  1605. }
  1606. }
  1607. }
  1608. private:
  1609. /// If this instruction is embedded into a MachineFunction, return the
  1610. /// MachineRegisterInfo object for the current function, otherwise
  1611. /// return null.
  1612. MachineRegisterInfo *getRegInfo();
  1613. /// Unlink all of the register operands in this instruction from their
  1614. /// respective use lists. This requires that the operands already be on their
  1615. /// use lists.
  1616. void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
  1617. /// Add all of the register operands in this instruction from their
  1618. /// respective use lists. This requires that the operands not be on their
  1619. /// use lists yet.
  1620. void AddRegOperandsToUseLists(MachineRegisterInfo&);
  1621. /// Slow path for hasProperty when we're dealing with a bundle.
  1622. bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const;
  1623. /// Implements the logic of getRegClassConstraintEffectForVReg for the
  1624. /// this MI and the given operand index \p OpIdx.
  1625. /// If the related operand does not constrained Reg, this returns CurRC.
  1626. const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
  1627. unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC,
  1628. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
  1629. /// Stores extra instruction information inline or allocates as ExtraInfo
  1630. /// based on the number of pointers.
  1631. void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs,
  1632. MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol,
  1633. MDNode *HeapAllocMarker);
  1634. };
  1635. /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
  1636. /// instruction rather than by pointer value.
  1637. /// The hashing and equality testing functions ignore definitions so this is
  1638. /// useful for CSE, etc.
  1639. struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
  1640. static inline MachineInstr *getEmptyKey() {
  1641. return nullptr;
  1642. }
  1643. static inline MachineInstr *getTombstoneKey() {
  1644. return reinterpret_cast<MachineInstr*>(-1);
  1645. }
  1646. static unsigned getHashValue(const MachineInstr* const &MI);
  1647. static bool isEqual(const MachineInstr* const &LHS,
  1648. const MachineInstr* const &RHS) {
  1649. if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
  1650. LHS == getEmptyKey() || LHS == getTombstoneKey())
  1651. return LHS == RHS;
  1652. return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
  1653. }
  1654. };
  1655. //===----------------------------------------------------------------------===//
  1656. // Debugging Support
  1657. inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
  1658. MI.print(OS);
  1659. return OS;
  1660. }
  1661. } // end namespace llvm
  1662. #endif // LLVM_CODEGEN_MACHINEINSTR_H
  1663. #ifdef __GNUC__
  1664. #pragma GCC diagnostic pop
  1665. #endif