TargetInstrInfo.h 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/TargetInstrInfo.h - Instruction Info --------*- 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 describes the target machine instruction set to the code generator.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CODEGEN_TARGETINSTRINFO_H
  18. #define LLVM_CODEGEN_TARGETINSTRINFO_H
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/DenseMapInfo.h"
  22. #include "llvm/ADT/None.h"
  23. #include "llvm/CodeGen/MIRFormatter.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineCombinerPattern.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineInstr.h"
  28. #include "llvm/CodeGen/MachineInstrBuilder.h"
  29. #include "llvm/CodeGen/MachineOperand.h"
  30. #include "llvm/CodeGen/MachineOutliner.h"
  31. #include "llvm/CodeGen/RegisterClassInfo.h"
  32. #include "llvm/CodeGen/VirtRegMap.h"
  33. #include "llvm/MC/MCInstrInfo.h"
  34. #include "llvm/Support/BranchProbability.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include <cassert>
  37. #include <cstddef>
  38. #include <cstdint>
  39. #include <utility>
  40. #include <vector>
  41. namespace llvm {
  42. class AAResults;
  43. class DFAPacketizer;
  44. class InstrItineraryData;
  45. class LiveIntervals;
  46. class LiveVariables;
  47. class MachineLoop;
  48. class MachineMemOperand;
  49. class MachineRegisterInfo;
  50. class MCAsmInfo;
  51. class MCInst;
  52. struct MCSchedModel;
  53. class Module;
  54. class ScheduleDAG;
  55. class ScheduleDAGMI;
  56. class ScheduleHazardRecognizer;
  57. class SDNode;
  58. class SelectionDAG;
  59. class RegScavenger;
  60. class TargetRegisterClass;
  61. class TargetRegisterInfo;
  62. class TargetSchedModel;
  63. class TargetSubtargetInfo;
  64. template <class T> class SmallVectorImpl;
  65. using ParamLoadedValue = std::pair<MachineOperand, DIExpression*>;
  66. struct DestSourcePair {
  67. const MachineOperand *Destination;
  68. const MachineOperand *Source;
  69. DestSourcePair(const MachineOperand &Dest, const MachineOperand &Src)
  70. : Destination(&Dest), Source(&Src) {}
  71. };
  72. /// Used to describe a register and immediate addition.
  73. struct RegImmPair {
  74. Register Reg;
  75. int64_t Imm;
  76. RegImmPair(Register Reg, int64_t Imm) : Reg(Reg), Imm(Imm) {}
  77. };
  78. /// Used to describe addressing mode similar to ExtAddrMode in CodeGenPrepare.
  79. /// It holds the register values, the scale value and the displacement.
  80. struct ExtAddrMode {
  81. Register BaseReg;
  82. Register ScaledReg;
  83. int64_t Scale;
  84. int64_t Displacement;
  85. };
  86. //---------------------------------------------------------------------------
  87. ///
  88. /// TargetInstrInfo - Interface to description of machine instruction set
  89. ///
  90. class TargetInstrInfo : public MCInstrInfo {
  91. public:
  92. TargetInstrInfo(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u,
  93. unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u)
  94. : CallFrameSetupOpcode(CFSetupOpcode),
  95. CallFrameDestroyOpcode(CFDestroyOpcode), CatchRetOpcode(CatchRetOpcode),
  96. ReturnOpcode(ReturnOpcode) {}
  97. TargetInstrInfo(const TargetInstrInfo &) = delete;
  98. TargetInstrInfo &operator=(const TargetInstrInfo &) = delete;
  99. virtual ~TargetInstrInfo();
  100. static bool isGenericOpcode(unsigned Opc) {
  101. return Opc <= TargetOpcode::GENERIC_OP_END;
  102. }
  103. /// Given a machine instruction descriptor, returns the register
  104. /// class constraint for OpNum, or NULL.
  105. virtual
  106. const TargetRegisterClass *getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
  107. const TargetRegisterInfo *TRI,
  108. const MachineFunction &MF) const;
  109. /// Return true if the instruction is trivially rematerializable, meaning it
  110. /// has no side effects and requires no operands that aren't always available.
  111. /// This means the only allowed uses are constants and unallocatable physical
  112. /// registers so that the instructions result is independent of the place
  113. /// in the function.
  114. bool isTriviallyReMaterializable(const MachineInstr &MI,
  115. AAResults *AA = nullptr) const {
  116. return MI.getOpcode() == TargetOpcode::IMPLICIT_DEF ||
  117. (MI.getDesc().isRematerializable() &&
  118. (isReallyTriviallyReMaterializable(MI, AA) ||
  119. isReallyTriviallyReMaterializableGeneric(MI, AA)));
  120. }
  121. /// Given \p MO is a PhysReg use return if it can be ignored for the purpose
  122. /// of instruction rematerialization or sinking.
  123. virtual bool isIgnorableUse(const MachineOperand &MO) const {
  124. return false;
  125. }
  126. protected:
  127. /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
  128. /// set, this hook lets the target specify whether the instruction is actually
  129. /// trivially rematerializable, taking into consideration its operands. This
  130. /// predicate must return false if the instruction has any side effects other
  131. /// than producing a value, or if it requres any address registers that are
  132. /// not always available.
  133. /// Requirements must be check as stated in isTriviallyReMaterializable() .
  134. virtual bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
  135. AAResults *AA) const {
  136. return false;
  137. }
  138. /// This method commutes the operands of the given machine instruction MI.
  139. /// The operands to be commuted are specified by their indices OpIdx1 and
  140. /// OpIdx2.
  141. ///
  142. /// If a target has any instructions that are commutable but require
  143. /// converting to different instructions or making non-trivial changes
  144. /// to commute them, this method can be overloaded to do that.
  145. /// The default implementation simply swaps the commutable operands.
  146. ///
  147. /// If NewMI is false, MI is modified in place and returned; otherwise, a
  148. /// new machine instruction is created and returned.
  149. ///
  150. /// Do not call this method for a non-commutable instruction.
  151. /// Even though the instruction is commutable, the method may still
  152. /// fail to commute the operands, null pointer is returned in such cases.
  153. virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
  154. unsigned OpIdx1,
  155. unsigned OpIdx2) const;
  156. /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
  157. /// operand indices to (ResultIdx1, ResultIdx2).
  158. /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
  159. /// predefined to some indices or be undefined (designated by the special
  160. /// value 'CommuteAnyOperandIndex').
  161. /// The predefined result indices cannot be re-defined.
  162. /// The function returns true iff after the result pair redefinition
  163. /// the fixed result pair is equal to or equivalent to the source pair of
  164. /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
  165. /// the pairs (x,y) and (y,x) are equivalent.
  166. static bool fixCommutedOpIndices(unsigned &ResultIdx1, unsigned &ResultIdx2,
  167. unsigned CommutableOpIdx1,
  168. unsigned CommutableOpIdx2);
  169. private:
  170. /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
  171. /// set and the target hook isReallyTriviallyReMaterializable returns false,
  172. /// this function does target-independent tests to determine if the
  173. /// instruction is really trivially rematerializable.
  174. bool isReallyTriviallyReMaterializableGeneric(const MachineInstr &MI,
  175. AAResults *AA) const;
  176. public:
  177. /// These methods return the opcode of the frame setup/destroy instructions
  178. /// if they exist (-1 otherwise). Some targets use pseudo instructions in
  179. /// order to abstract away the difference between operating with a frame
  180. /// pointer and operating without, through the use of these two instructions.
  181. ///
  182. unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
  183. unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
  184. /// Returns true if the argument is a frame pseudo instruction.
  185. bool isFrameInstr(const MachineInstr &I) const {
  186. return I.getOpcode() == getCallFrameSetupOpcode() ||
  187. I.getOpcode() == getCallFrameDestroyOpcode();
  188. }
  189. /// Returns true if the argument is a frame setup pseudo instruction.
  190. bool isFrameSetup(const MachineInstr &I) const {
  191. return I.getOpcode() == getCallFrameSetupOpcode();
  192. }
  193. /// Returns size of the frame associated with the given frame instruction.
  194. /// For frame setup instruction this is frame that is set up space set up
  195. /// after the instruction. For frame destroy instruction this is the frame
  196. /// freed by the caller.
  197. /// Note, in some cases a call frame (or a part of it) may be prepared prior
  198. /// to the frame setup instruction. It occurs in the calls that involve
  199. /// inalloca arguments. This function reports only the size of the frame part
  200. /// that is set up between the frame setup and destroy pseudo instructions.
  201. int64_t getFrameSize(const MachineInstr &I) const {
  202. assert(isFrameInstr(I) && "Not a frame instruction");
  203. assert(I.getOperand(0).getImm() >= 0);
  204. return I.getOperand(0).getImm();
  205. }
  206. /// Returns the total frame size, which is made up of the space set up inside
  207. /// the pair of frame start-stop instructions and the space that is set up
  208. /// prior to the pair.
  209. int64_t getFrameTotalSize(const MachineInstr &I) const {
  210. if (isFrameSetup(I)) {
  211. assert(I.getOperand(1).getImm() >= 0 &&
  212. "Frame size must not be negative");
  213. return getFrameSize(I) + I.getOperand(1).getImm();
  214. }
  215. return getFrameSize(I);
  216. }
  217. unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
  218. unsigned getReturnOpcode() const { return ReturnOpcode; }
  219. /// Returns the actual stack pointer adjustment made by an instruction
  220. /// as part of a call sequence. By default, only call frame setup/destroy
  221. /// instructions adjust the stack, but targets may want to override this
  222. /// to enable more fine-grained adjustment, or adjust by a different value.
  223. virtual int getSPAdjust(const MachineInstr &MI) const;
  224. /// Return true if the instruction is a "coalescable" extension instruction.
  225. /// That is, it's like a copy where it's legal for the source to overlap the
  226. /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
  227. /// expected the pre-extension value is available as a subreg of the result
  228. /// register. This also returns the sub-register index in SubIdx.
  229. virtual bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg,
  230. Register &DstReg, unsigned &SubIdx) const {
  231. return false;
  232. }
  233. /// If the specified machine instruction is a direct
  234. /// load from a stack slot, return the virtual or physical register number of
  235. /// the destination along with the FrameIndex of the loaded stack slot. If
  236. /// not, return 0. This predicate must return 0 if the instruction has
  237. /// any side effects other than loading from the stack slot.
  238. virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
  239. int &FrameIndex) const {
  240. return 0;
  241. }
  242. /// Optional extension of isLoadFromStackSlot that returns the number of
  243. /// bytes loaded from the stack. This must be implemented if a backend
  244. /// supports partial stack slot spills/loads to further disambiguate
  245. /// what the load does.
  246. virtual unsigned isLoadFromStackSlot(const MachineInstr &MI,
  247. int &FrameIndex,
  248. unsigned &MemBytes) const {
  249. MemBytes = 0;
  250. return isLoadFromStackSlot(MI, FrameIndex);
  251. }
  252. /// Check for post-frame ptr elimination stack locations as well.
  253. /// This uses a heuristic so it isn't reliable for correctness.
  254. virtual unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
  255. int &FrameIndex) const {
  256. return 0;
  257. }
  258. /// If the specified machine instruction has a load from a stack slot,
  259. /// return true along with the FrameIndices of the loaded stack slot and the
  260. /// machine mem operands containing the reference.
  261. /// If not, return false. Unlike isLoadFromStackSlot, this returns true for
  262. /// any instructions that loads from the stack. This is just a hint, as some
  263. /// cases may be missed.
  264. virtual bool hasLoadFromStackSlot(
  265. const MachineInstr &MI,
  266. SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
  267. /// If the specified machine instruction is a direct
  268. /// store to a stack slot, return the virtual or physical register number of
  269. /// the source reg along with the FrameIndex of the loaded stack slot. If
  270. /// not, return 0. This predicate must return 0 if the instruction has
  271. /// any side effects other than storing to the stack slot.
  272. virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
  273. int &FrameIndex) const {
  274. return 0;
  275. }
  276. /// Optional extension of isStoreToStackSlot that returns the number of
  277. /// bytes stored to the stack. This must be implemented if a backend
  278. /// supports partial stack slot spills/loads to further disambiguate
  279. /// what the store does.
  280. virtual unsigned isStoreToStackSlot(const MachineInstr &MI,
  281. int &FrameIndex,
  282. unsigned &MemBytes) const {
  283. MemBytes = 0;
  284. return isStoreToStackSlot(MI, FrameIndex);
  285. }
  286. /// Check for post-frame ptr elimination stack locations as well.
  287. /// This uses a heuristic, so it isn't reliable for correctness.
  288. virtual unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
  289. int &FrameIndex) const {
  290. return 0;
  291. }
  292. /// If the specified machine instruction has a store to a stack slot,
  293. /// return true along with the FrameIndices of the loaded stack slot and the
  294. /// machine mem operands containing the reference.
  295. /// If not, return false. Unlike isStoreToStackSlot,
  296. /// this returns true for any instructions that stores to the
  297. /// stack. This is just a hint, as some cases may be missed.
  298. virtual bool hasStoreToStackSlot(
  299. const MachineInstr &MI,
  300. SmallVectorImpl<const MachineMemOperand *> &Accesses) const;
  301. /// Return true if the specified machine instruction
  302. /// is a copy of one stack slot to another and has no other effect.
  303. /// Provide the identity of the two frame indices.
  304. virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
  305. int &SrcFrameIndex) const {
  306. return false;
  307. }
  308. /// Compute the size in bytes and offset within a stack slot of a spilled
  309. /// register or subregister.
  310. ///
  311. /// \param [out] Size in bytes of the spilled value.
  312. /// \param [out] Offset in bytes within the stack slot.
  313. /// \returns true if both Size and Offset are successfully computed.
  314. ///
  315. /// Not all subregisters have computable spill slots. For example,
  316. /// subregisters registers may not be byte-sized, and a pair of discontiguous
  317. /// subregisters has no single offset.
  318. ///
  319. /// Targets with nontrivial bigendian implementations may need to override
  320. /// this, particularly to support spilled vector registers.
  321. virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
  322. unsigned &Size, unsigned &Offset,
  323. const MachineFunction &MF) const;
  324. /// Return true if the given instruction is terminator that is unspillable,
  325. /// according to isUnspillableTerminatorImpl.
  326. bool isUnspillableTerminator(const MachineInstr *MI) const {
  327. return MI->isTerminator() && isUnspillableTerminatorImpl(MI);
  328. }
  329. /// Returns the size in bytes of the specified MachineInstr, or ~0U
  330. /// when this function is not implemented by a target.
  331. virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const {
  332. return ~0U;
  333. }
  334. /// Return true if the instruction is as cheap as a move instruction.
  335. ///
  336. /// Targets for different archs need to override this, and different
  337. /// micro-architectures can also be finely tuned inside.
  338. virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
  339. return MI.isAsCheapAsAMove();
  340. }
  341. /// Return true if the instruction should be sunk by MachineSink.
  342. ///
  343. /// MachineSink determines on its own whether the instruction is safe to sink;
  344. /// this gives the target a hook to override the default behavior with regards
  345. /// to which instructions should be sunk.
  346. virtual bool shouldSink(const MachineInstr &MI) const { return true; }
  347. /// Re-issue the specified 'original' instruction at the
  348. /// specific location targeting a new destination register.
  349. /// The register in Orig->getOperand(0).getReg() will be substituted by
  350. /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
  351. /// SubIdx.
  352. virtual void reMaterialize(MachineBasicBlock &MBB,
  353. MachineBasicBlock::iterator MI, Register DestReg,
  354. unsigned SubIdx, const MachineInstr &Orig,
  355. const TargetRegisterInfo &TRI) const;
  356. /// Clones instruction or the whole instruction bundle \p Orig and
  357. /// insert into \p MBB before \p InsertBefore. The target may update operands
  358. /// that are required to be unique.
  359. ///
  360. /// \p Orig must not return true for MachineInstr::isNotDuplicable().
  361. virtual MachineInstr &duplicate(MachineBasicBlock &MBB,
  362. MachineBasicBlock::iterator InsertBefore,
  363. const MachineInstr &Orig) const;
  364. /// This method must be implemented by targets that
  365. /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
  366. /// may be able to convert a two-address instruction into one or more true
  367. /// three-address instructions on demand. This allows the X86 target (for
  368. /// example) to convert ADD and SHL instructions into LEA instructions if they
  369. /// would require register copies due to two-addressness.
  370. ///
  371. /// This method returns a null pointer if the transformation cannot be
  372. /// performed, otherwise it returns the last new instruction.
  373. ///
  374. /// If \p LIS is not nullptr, the LiveIntervals info should be updated for
  375. /// replacing \p MI with new instructions, even though this function does not
  376. /// remove MI.
  377. virtual MachineInstr *convertToThreeAddress(MachineInstr &MI,
  378. LiveVariables *LV,
  379. LiveIntervals *LIS) const {
  380. return nullptr;
  381. }
  382. // This constant can be used as an input value of operand index passed to
  383. // the method findCommutedOpIndices() to tell the method that the
  384. // corresponding operand index is not pre-defined and that the method
  385. // can pick any commutable operand.
  386. static const unsigned CommuteAnyOperandIndex = ~0U;
  387. /// This method commutes the operands of the given machine instruction MI.
  388. ///
  389. /// The operands to be commuted are specified by their indices OpIdx1 and
  390. /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
  391. /// 'CommuteAnyOperandIndex', which means that the method is free to choose
  392. /// any arbitrarily chosen commutable operand. If both arguments are set to
  393. /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
  394. /// operands; then commutes them if such operands could be found.
  395. ///
  396. /// If NewMI is false, MI is modified in place and returned; otherwise, a
  397. /// new machine instruction is created and returned.
  398. ///
  399. /// Do not call this method for a non-commutable instruction or
  400. /// for non-commuable operands.
  401. /// Even though the instruction is commutable, the method may still
  402. /// fail to commute the operands, null pointer is returned in such cases.
  403. MachineInstr *
  404. commuteInstruction(MachineInstr &MI, bool NewMI = false,
  405. unsigned OpIdx1 = CommuteAnyOperandIndex,
  406. unsigned OpIdx2 = CommuteAnyOperandIndex) const;
  407. /// Returns true iff the routine could find two commutable operands in the
  408. /// given machine instruction.
  409. /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
  410. /// If any of the INPUT values is set to the special value
  411. /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
  412. /// operand, then returns its index in the corresponding argument.
  413. /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
  414. /// looks for 2 commutable operands.
  415. /// If INPUT values refer to some operands of MI, then the method simply
  416. /// returns true if the corresponding operands are commutable and returns
  417. /// false otherwise.
  418. ///
  419. /// For example, calling this method this way:
  420. /// unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
  421. /// findCommutedOpIndices(MI, Op1, Op2);
  422. /// can be interpreted as a query asking to find an operand that would be
  423. /// commutable with the operand#1.
  424. virtual bool findCommutedOpIndices(const MachineInstr &MI,
  425. unsigned &SrcOpIdx1,
  426. unsigned &SrcOpIdx2) const;
  427. /// Returns true if the target has a preference on the operands order of
  428. /// the given machine instruction. And specify if \p Commute is required to
  429. /// get the desired operands order.
  430. virtual bool hasCommutePreference(MachineInstr &MI, bool &Commute) const {
  431. return false;
  432. }
  433. /// A pair composed of a register and a sub-register index.
  434. /// Used to give some type checking when modeling Reg:SubReg.
  435. struct RegSubRegPair {
  436. Register Reg;
  437. unsigned SubReg;
  438. RegSubRegPair(Register Reg = Register(), unsigned SubReg = 0)
  439. : Reg(Reg), SubReg(SubReg) {}
  440. bool operator==(const RegSubRegPair& P) const {
  441. return Reg == P.Reg && SubReg == P.SubReg;
  442. }
  443. bool operator!=(const RegSubRegPair& P) const {
  444. return !(*this == P);
  445. }
  446. };
  447. /// A pair composed of a pair of a register and a sub-register index,
  448. /// and another sub-register index.
  449. /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
  450. struct RegSubRegPairAndIdx : RegSubRegPair {
  451. unsigned SubIdx;
  452. RegSubRegPairAndIdx(Register Reg = Register(), unsigned SubReg = 0,
  453. unsigned SubIdx = 0)
  454. : RegSubRegPair(Reg, SubReg), SubIdx(SubIdx) {}
  455. };
  456. /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
  457. /// and \p DefIdx.
  458. /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
  459. /// the list is modeled as <Reg:SubReg, SubIdx>. Operands with the undef
  460. /// flag are not added to this list.
  461. /// E.g., REG_SEQUENCE %1:sub1, sub0, %2, sub1 would produce
  462. /// two elements:
  463. /// - %1:sub1, sub0
  464. /// - %2<:0>, sub1
  465. ///
  466. /// \returns true if it is possible to build such an input sequence
  467. /// with the pair \p MI, \p DefIdx. False otherwise.
  468. ///
  469. /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
  470. ///
  471. /// \note The generic implementation does not provide any support for
  472. /// MI.isRegSequenceLike(). In other words, one has to override
  473. /// getRegSequenceLikeInputs for target specific instructions.
  474. bool
  475. getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
  476. SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
  477. /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
  478. /// and \p DefIdx.
  479. /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
  480. /// E.g., EXTRACT_SUBREG %1:sub1, sub0, sub1 would produce:
  481. /// - %1:sub1, sub0
  482. ///
  483. /// \returns true if it is possible to build such an input sequence
  484. /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
  485. /// False otherwise.
  486. ///
  487. /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
  488. ///
  489. /// \note The generic implementation does not provide any support for
  490. /// MI.isExtractSubregLike(). In other words, one has to override
  491. /// getExtractSubregLikeInputs for target specific instructions.
  492. bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
  493. RegSubRegPairAndIdx &InputReg) const;
  494. /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
  495. /// and \p DefIdx.
  496. /// \p [out] BaseReg and \p [out] InsertedReg contain
  497. /// the equivalent inputs of INSERT_SUBREG.
  498. /// E.g., INSERT_SUBREG %0:sub0, %1:sub1, sub3 would produce:
  499. /// - BaseReg: %0:sub0
  500. /// - InsertedReg: %1:sub1, sub3
  501. ///
  502. /// \returns true if it is possible to build such an input sequence
  503. /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
  504. /// False otherwise.
  505. ///
  506. /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
  507. ///
  508. /// \note The generic implementation does not provide any support for
  509. /// MI.isInsertSubregLike(). In other words, one has to override
  510. /// getInsertSubregLikeInputs for target specific instructions.
  511. bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
  512. RegSubRegPair &BaseReg,
  513. RegSubRegPairAndIdx &InsertedReg) const;
  514. /// Return true if two machine instructions would produce identical values.
  515. /// By default, this is only true when the two instructions
  516. /// are deemed identical except for defs. If this function is called when the
  517. /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
  518. /// aggressive checks.
  519. virtual bool produceSameValue(const MachineInstr &MI0,
  520. const MachineInstr &MI1,
  521. const MachineRegisterInfo *MRI = nullptr) const;
  522. /// \returns true if a branch from an instruction with opcode \p BranchOpc
  523. /// bytes is capable of jumping to a position \p BrOffset bytes away.
  524. virtual bool isBranchOffsetInRange(unsigned BranchOpc,
  525. int64_t BrOffset) const {
  526. llvm_unreachable("target did not implement");
  527. }
  528. /// \returns The block that branch instruction \p MI jumps to.
  529. virtual MachineBasicBlock *getBranchDestBlock(const MachineInstr &MI) const {
  530. llvm_unreachable("target did not implement");
  531. }
  532. /// Insert an unconditional indirect branch at the end of \p MBB to \p
  533. /// NewDestBB. Optionally, insert the clobbered register restoring in \p
  534. /// RestoreBB. \p BrOffset indicates the offset of \p NewDestBB relative to
  535. /// the offset of the position to insert the new branch.
  536. virtual void insertIndirectBranch(MachineBasicBlock &MBB,
  537. MachineBasicBlock &NewDestBB,
  538. MachineBasicBlock &RestoreBB,
  539. const DebugLoc &DL, int64_t BrOffset = 0,
  540. RegScavenger *RS = nullptr) const {
  541. llvm_unreachable("target did not implement");
  542. }
  543. /// Analyze the branching code at the end of MBB, returning
  544. /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
  545. /// implemented for a target). Upon success, this returns false and returns
  546. /// with the following information in various cases:
  547. ///
  548. /// 1. If this block ends with no branches (it just falls through to its succ)
  549. /// just return false, leaving TBB/FBB null.
  550. /// 2. If this block ends with only an unconditional branch, it sets TBB to be
  551. /// the destination block.
  552. /// 3. If this block ends with a conditional branch and it falls through to a
  553. /// successor block, it sets TBB to be the branch destination block and a
  554. /// list of operands that evaluate the condition. These operands can be
  555. /// passed to other TargetInstrInfo methods to create new branches.
  556. /// 4. If this block ends with a conditional branch followed by an
  557. /// unconditional branch, it returns the 'true' destination in TBB, the
  558. /// 'false' destination in FBB, and a list of operands that evaluate the
  559. /// condition. These operands can be passed to other TargetInstrInfo
  560. /// methods to create new branches.
  561. ///
  562. /// Note that removeBranch and insertBranch must be implemented to support
  563. /// cases where this method returns success.
  564. ///
  565. /// If AllowModify is true, then this routine is allowed to modify the basic
  566. /// block (e.g. delete instructions after the unconditional branch).
  567. ///
  568. /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
  569. /// before calling this function.
  570. virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
  571. MachineBasicBlock *&FBB,
  572. SmallVectorImpl<MachineOperand> &Cond,
  573. bool AllowModify = false) const {
  574. return true;
  575. }
  576. /// Represents a predicate at the MachineFunction level. The control flow a
  577. /// MachineBranchPredicate represents is:
  578. ///
  579. /// Reg = LHS `Predicate` RHS == ConditionDef
  580. /// if Reg then goto TrueDest else goto FalseDest
  581. ///
  582. struct MachineBranchPredicate {
  583. enum ComparePredicate {
  584. PRED_EQ, // True if two values are equal
  585. PRED_NE, // True if two values are not equal
  586. PRED_INVALID // Sentinel value
  587. };
  588. ComparePredicate Predicate = PRED_INVALID;
  589. MachineOperand LHS = MachineOperand::CreateImm(0);
  590. MachineOperand RHS = MachineOperand::CreateImm(0);
  591. MachineBasicBlock *TrueDest = nullptr;
  592. MachineBasicBlock *FalseDest = nullptr;
  593. MachineInstr *ConditionDef = nullptr;
  594. /// SingleUseCondition is true if ConditionDef is dead except for the
  595. /// branch(es) at the end of the basic block.
  596. ///
  597. bool SingleUseCondition = false;
  598. explicit MachineBranchPredicate() = default;
  599. };
  600. /// Analyze the branching code at the end of MBB and parse it into the
  601. /// MachineBranchPredicate structure if possible. Returns false on success
  602. /// and true on failure.
  603. ///
  604. /// If AllowModify is true, then this routine is allowed to modify the basic
  605. /// block (e.g. delete instructions after the unconditional branch).
  606. ///
  607. virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB,
  608. MachineBranchPredicate &MBP,
  609. bool AllowModify = false) const {
  610. return true;
  611. }
  612. /// Remove the branching code at the end of the specific MBB.
  613. /// This is only invoked in cases where analyzeBranch returns success. It
  614. /// returns the number of instructions that were removed.
  615. /// If \p BytesRemoved is non-null, report the change in code size from the
  616. /// removed instructions.
  617. virtual unsigned removeBranch(MachineBasicBlock &MBB,
  618. int *BytesRemoved = nullptr) const {
  619. llvm_unreachable("Target didn't implement TargetInstrInfo::removeBranch!");
  620. }
  621. /// Insert branch code into the end of the specified MachineBasicBlock. The
  622. /// operands to this method are the same as those returned by analyzeBranch.
  623. /// This is only invoked in cases where analyzeBranch returns success. It
  624. /// returns the number of instructions inserted. If \p BytesAdded is non-null,
  625. /// report the change in code size from the added instructions.
  626. ///
  627. /// It is also invoked by tail merging to add unconditional branches in
  628. /// cases where analyzeBranch doesn't apply because there was no original
  629. /// branch to analyze. At least this much must be implemented, else tail
  630. /// merging needs to be disabled.
  631. ///
  632. /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
  633. /// before calling this function.
  634. virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
  635. MachineBasicBlock *FBB,
  636. ArrayRef<MachineOperand> Cond,
  637. const DebugLoc &DL,
  638. int *BytesAdded = nullptr) const {
  639. llvm_unreachable("Target didn't implement TargetInstrInfo::insertBranch!");
  640. }
  641. unsigned insertUnconditionalBranch(MachineBasicBlock &MBB,
  642. MachineBasicBlock *DestBB,
  643. const DebugLoc &DL,
  644. int *BytesAdded = nullptr) const {
  645. return insertBranch(MBB, DestBB, nullptr, ArrayRef<MachineOperand>(), DL,
  646. BytesAdded);
  647. }
  648. /// Object returned by analyzeLoopForPipelining. Allows software pipelining
  649. /// implementations to query attributes of the loop being pipelined and to
  650. /// apply target-specific updates to the loop once pipelining is complete.
  651. class PipelinerLoopInfo {
  652. public:
  653. virtual ~PipelinerLoopInfo();
  654. /// Return true if the given instruction should not be pipelined and should
  655. /// be ignored. An example could be a loop comparison, or induction variable
  656. /// update with no users being pipelined.
  657. virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const = 0;
  658. /// Create a condition to determine if the trip count of the loop is greater
  659. /// than TC.
  660. ///
  661. /// If the trip count is statically known to be greater than TC, return
  662. /// true. If the trip count is statically known to be not greater than TC,
  663. /// return false. Otherwise return nullopt and fill out Cond with the test
  664. /// condition.
  665. virtual Optional<bool>
  666. createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB,
  667. SmallVectorImpl<MachineOperand> &Cond) = 0;
  668. /// Modify the loop such that the trip count is
  669. /// OriginalTC + TripCountAdjust.
  670. virtual void adjustTripCount(int TripCountAdjust) = 0;
  671. /// Called when the loop's preheader has been modified to NewPreheader.
  672. virtual void setPreheader(MachineBasicBlock *NewPreheader) = 0;
  673. /// Called when the loop is being removed. Any instructions in the preheader
  674. /// should be removed.
  675. ///
  676. /// Once this function is called, no other functions on this object are
  677. /// valid; the loop has been removed.
  678. virtual void disposed() = 0;
  679. };
  680. /// Analyze loop L, which must be a single-basic-block loop, and if the
  681. /// conditions can be understood enough produce a PipelinerLoopInfo object.
  682. virtual std::unique_ptr<PipelinerLoopInfo>
  683. analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const {
  684. return nullptr;
  685. }
  686. /// Analyze the loop code, return true if it cannot be understood. Upon
  687. /// success, this function returns false and returns information about the
  688. /// induction variable and compare instruction used at the end.
  689. virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
  690. MachineInstr *&CmpInst) const {
  691. return true;
  692. }
  693. /// Generate code to reduce the loop iteration by one and check if the loop
  694. /// is finished. Return the value/register of the new loop count. We need
  695. /// this function when peeling off one or more iterations of a loop. This
  696. /// function assumes the nth iteration is peeled first.
  697. virtual unsigned reduceLoopCount(MachineBasicBlock &MBB,
  698. MachineBasicBlock &PreHeader,
  699. MachineInstr *IndVar, MachineInstr &Cmp,
  700. SmallVectorImpl<MachineOperand> &Cond,
  701. SmallVectorImpl<MachineInstr *> &PrevInsts,
  702. unsigned Iter, unsigned MaxIter) const {
  703. llvm_unreachable("Target didn't implement ReduceLoopCount");
  704. }
  705. /// Delete the instruction OldInst and everything after it, replacing it with
  706. /// an unconditional branch to NewDest. This is used by the tail merging pass.
  707. virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
  708. MachineBasicBlock *NewDest) const;
  709. /// Return true if it's legal to split the given basic
  710. /// block at the specified instruction (i.e. instruction would be the start
  711. /// of a new basic block).
  712. virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB,
  713. MachineBasicBlock::iterator MBBI) const {
  714. return true;
  715. }
  716. /// Return true if it's profitable to predicate
  717. /// instructions with accumulated instruction latency of "NumCycles"
  718. /// of the specified basic block, where the probability of the instructions
  719. /// being executed is given by Probability, and Confidence is a measure
  720. /// of our confidence that it will be properly predicted.
  721. virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
  722. unsigned ExtraPredCycles,
  723. BranchProbability Probability) const {
  724. return false;
  725. }
  726. /// Second variant of isProfitableToIfCvt. This one
  727. /// checks for the case where two basic blocks from true and false path
  728. /// of a if-then-else (diamond) are predicated on mutually exclusive
  729. /// predicates, where the probability of the true path being taken is given
  730. /// by Probability, and Confidence is a measure of our confidence that it
  731. /// will be properly predicted.
  732. virtual bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumTCycles,
  733. unsigned ExtraTCycles,
  734. MachineBasicBlock &FMBB, unsigned NumFCycles,
  735. unsigned ExtraFCycles,
  736. BranchProbability Probability) const {
  737. return false;
  738. }
  739. /// Return true if it's profitable for if-converter to duplicate instructions
  740. /// of specified accumulated instruction latencies in the specified MBB to
  741. /// enable if-conversion.
  742. /// The probability of the instructions being executed is given by
  743. /// Probability, and Confidence is a measure of our confidence that it
  744. /// will be properly predicted.
  745. virtual bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB,
  746. unsigned NumCycles,
  747. BranchProbability Probability) const {
  748. return false;
  749. }
  750. /// Return the increase in code size needed to predicate a contiguous run of
  751. /// NumInsts instructions.
  752. virtual unsigned extraSizeToPredicateInstructions(const MachineFunction &MF,
  753. unsigned NumInsts) const {
  754. return 0;
  755. }
  756. /// Return an estimate for the code size reduction (in bytes) which will be
  757. /// caused by removing the given branch instruction during if-conversion.
  758. virtual unsigned predictBranchSizeForIfCvt(MachineInstr &MI) const {
  759. return getInstSizeInBytes(MI);
  760. }
  761. /// Return true if it's profitable to unpredicate
  762. /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
  763. /// exclusive predicates.
  764. /// e.g.
  765. /// subeq r0, r1, #1
  766. /// addne r0, r1, #1
  767. /// =>
  768. /// sub r0, r1, #1
  769. /// addne r0, r1, #1
  770. ///
  771. /// This may be profitable is conditional instructions are always executed.
  772. virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
  773. MachineBasicBlock &FMBB) const {
  774. return false;
  775. }
  776. /// Return true if it is possible to insert a select
  777. /// instruction that chooses between TrueReg and FalseReg based on the
  778. /// condition code in Cond.
  779. ///
  780. /// When successful, also return the latency in cycles from TrueReg,
  781. /// FalseReg, and Cond to the destination register. In most cases, a select
  782. /// instruction will be 1 cycle, so CondCycles = TrueCycles = FalseCycles = 1
  783. ///
  784. /// Some x86 implementations have 2-cycle cmov instructions.
  785. ///
  786. /// @param MBB Block where select instruction would be inserted.
  787. /// @param Cond Condition returned by analyzeBranch.
  788. /// @param DstReg Virtual dest register that the result should write to.
  789. /// @param TrueReg Virtual register to select when Cond is true.
  790. /// @param FalseReg Virtual register to select when Cond is false.
  791. /// @param CondCycles Latency from Cond+Branch to select output.
  792. /// @param TrueCycles Latency from TrueReg to select output.
  793. /// @param FalseCycles Latency from FalseReg to select output.
  794. virtual bool canInsertSelect(const MachineBasicBlock &MBB,
  795. ArrayRef<MachineOperand> Cond, Register DstReg,
  796. Register TrueReg, Register FalseReg,
  797. int &CondCycles, int &TrueCycles,
  798. int &FalseCycles) const {
  799. return false;
  800. }
  801. /// Insert a select instruction into MBB before I that will copy TrueReg to
  802. /// DstReg when Cond is true, and FalseReg to DstReg when Cond is false.
  803. ///
  804. /// This function can only be called after canInsertSelect() returned true.
  805. /// The condition in Cond comes from analyzeBranch, and it can be assumed
  806. /// that the same flags or registers required by Cond are available at the
  807. /// insertion point.
  808. ///
  809. /// @param MBB Block where select instruction should be inserted.
  810. /// @param I Insertion point.
  811. /// @param DL Source location for debugging.
  812. /// @param DstReg Virtual register to be defined by select instruction.
  813. /// @param Cond Condition as computed by analyzeBranch.
  814. /// @param TrueReg Virtual register to copy when Cond is true.
  815. /// @param FalseReg Virtual register to copy when Cons is false.
  816. virtual void insertSelect(MachineBasicBlock &MBB,
  817. MachineBasicBlock::iterator I, const DebugLoc &DL,
  818. Register DstReg, ArrayRef<MachineOperand> Cond,
  819. Register TrueReg, Register FalseReg) const {
  820. llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!");
  821. }
  822. /// Analyze the given select instruction, returning true if
  823. /// it cannot be understood. It is assumed that MI->isSelect() is true.
  824. ///
  825. /// When successful, return the controlling condition and the operands that
  826. /// determine the true and false result values.
  827. ///
  828. /// Result = SELECT Cond, TrueOp, FalseOp
  829. ///
  830. /// Some targets can optimize select instructions, for example by predicating
  831. /// the instruction defining one of the operands. Such targets should set
  832. /// Optimizable.
  833. ///
  834. /// @param MI Select instruction to analyze.
  835. /// @param Cond Condition controlling the select.
  836. /// @param TrueOp Operand number of the value selected when Cond is true.
  837. /// @param FalseOp Operand number of the value selected when Cond is false.
  838. /// @param Optimizable Returned as true if MI is optimizable.
  839. /// @returns False on success.
  840. virtual bool analyzeSelect(const MachineInstr &MI,
  841. SmallVectorImpl<MachineOperand> &Cond,
  842. unsigned &TrueOp, unsigned &FalseOp,
  843. bool &Optimizable) const {
  844. assert(MI.getDesc().isSelect() && "MI must be a select instruction");
  845. return true;
  846. }
  847. /// Given a select instruction that was understood by
  848. /// analyzeSelect and returned Optimizable = true, attempt to optimize MI by
  849. /// merging it with one of its operands. Returns NULL on failure.
  850. ///
  851. /// When successful, returns the new select instruction. The client is
  852. /// responsible for deleting MI.
  853. ///
  854. /// If both sides of the select can be optimized, PreferFalse is used to pick
  855. /// a side.
  856. ///
  857. /// @param MI Optimizable select instruction.
  858. /// @param NewMIs Set that record all MIs in the basic block up to \p
  859. /// MI. Has to be updated with any newly created MI or deleted ones.
  860. /// @param PreferFalse Try to optimize FalseOp instead of TrueOp.
  861. /// @returns Optimized instruction or NULL.
  862. virtual MachineInstr *optimizeSelect(MachineInstr &MI,
  863. SmallPtrSetImpl<MachineInstr *> &NewMIs,
  864. bool PreferFalse = false) const {
  865. // This function must be implemented if Optimizable is ever set.
  866. llvm_unreachable("Target must implement TargetInstrInfo::optimizeSelect!");
  867. }
  868. /// Emit instructions to copy a pair of physical registers.
  869. ///
  870. /// This function should support copies within any legal register class as
  871. /// well as any cross-class copies created during instruction selection.
  872. ///
  873. /// The source and destination registers may overlap, which may require a
  874. /// careful implementation when multiple copy instructions are required for
  875. /// large registers. See for example the ARM target.
  876. virtual void copyPhysReg(MachineBasicBlock &MBB,
  877. MachineBasicBlock::iterator MI, const DebugLoc &DL,
  878. MCRegister DestReg, MCRegister SrcReg,
  879. bool KillSrc) const {
  880. llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
  881. }
  882. /// Allow targets to tell MachineVerifier whether a specific register
  883. /// MachineOperand can be used as part of PC-relative addressing.
  884. /// PC-relative addressing modes in many CISC architectures contain
  885. /// (non-PC) registers as offsets or scaling values, which inherently
  886. /// tags the corresponding MachineOperand with OPERAND_PCREL.
  887. ///
  888. /// @param MO The MachineOperand in question. MO.isReg() should always
  889. /// be true.
  890. /// @return Whether this operand is allowed to be used PC-relatively.
  891. virtual bool isPCRelRegisterOperandLegal(const MachineOperand &MO) const {
  892. return false;
  893. }
  894. protected:
  895. /// Target-dependent implementation for IsCopyInstr.
  896. /// If the specific machine instruction is a instruction that moves/copies
  897. /// value from one register to another register return destination and source
  898. /// registers as machine operands.
  899. virtual Optional<DestSourcePair>
  900. isCopyInstrImpl(const MachineInstr &MI) const {
  901. return None;
  902. }
  903. /// Return true if the given terminator MI is not expected to spill. This
  904. /// sets the live interval as not spillable and adjusts phi node lowering to
  905. /// not introduce copies after the terminator. Use with care, these are
  906. /// currently used for hardware loop intrinsics in very controlled situations,
  907. /// created prior to registry allocation in loops that only have single phi
  908. /// users for the terminators value. They may run out of registers if not used
  909. /// carefully.
  910. virtual bool isUnspillableTerminatorImpl(const MachineInstr *MI) const {
  911. return false;
  912. }
  913. public:
  914. /// If the specific machine instruction is a instruction that moves/copies
  915. /// value from one register to another register return destination and source
  916. /// registers as machine operands.
  917. /// For COPY-instruction the method naturally returns destination and source
  918. /// registers as machine operands, for all other instructions the method calls
  919. /// target-dependent implementation.
  920. Optional<DestSourcePair> isCopyInstr(const MachineInstr &MI) const {
  921. if (MI.isCopy()) {
  922. return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
  923. }
  924. return isCopyInstrImpl(MI);
  925. }
  926. /// If the specific machine instruction is an instruction that adds an
  927. /// immediate value and a physical register, and stores the result in
  928. /// the given physical register \c Reg, return a pair of the source
  929. /// register and the offset which has been added.
  930. virtual Optional<RegImmPair> isAddImmediate(const MachineInstr &MI,
  931. Register Reg) const {
  932. return None;
  933. }
  934. /// Returns true if MI is an instruction that defines Reg to have a constant
  935. /// value and the value is recorded in ImmVal. The ImmVal is a result that
  936. /// should be interpreted as modulo size of Reg.
  937. virtual bool getConstValDefinedInReg(const MachineInstr &MI,
  938. const Register Reg,
  939. int64_t &ImmVal) const {
  940. return false;
  941. }
  942. /// Store the specified register of the given register class to the specified
  943. /// stack frame index. The store instruction is to be added to the given
  944. /// machine basic block before the specified machine instruction. If isKill
  945. /// is true, the register operand is the last use and must be marked kill.
  946. virtual void storeRegToStackSlot(MachineBasicBlock &MBB,
  947. MachineBasicBlock::iterator MI,
  948. Register SrcReg, bool isKill, int FrameIndex,
  949. const TargetRegisterClass *RC,
  950. const TargetRegisterInfo *TRI) const {
  951. llvm_unreachable("Target didn't implement "
  952. "TargetInstrInfo::storeRegToStackSlot!");
  953. }
  954. /// Load the specified register of the given register class from the specified
  955. /// stack frame index. The load instruction is to be added to the given
  956. /// machine basic block before the specified machine instruction.
  957. virtual void loadRegFromStackSlot(MachineBasicBlock &MBB,
  958. MachineBasicBlock::iterator MI,
  959. Register DestReg, int FrameIndex,
  960. const TargetRegisterClass *RC,
  961. const TargetRegisterInfo *TRI) const {
  962. llvm_unreachable("Target didn't implement "
  963. "TargetInstrInfo::loadRegFromStackSlot!");
  964. }
  965. /// This function is called for all pseudo instructions
  966. /// that remain after register allocation. Many pseudo instructions are
  967. /// created to help register allocation. This is the place to convert them
  968. /// into real instructions. The target can edit MI in place, or it can insert
  969. /// new instructions and erase MI. The function should return true if
  970. /// anything was changed.
  971. virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }
  972. /// Check whether the target can fold a load that feeds a subreg operand
  973. /// (or a subreg operand that feeds a store).
  974. /// For example, X86 may want to return true if it can fold
  975. /// movl (%esp), %eax
  976. /// subb, %al, ...
  977. /// Into:
  978. /// subb (%esp), ...
  979. ///
  980. /// Ideally, we'd like the target implementation of foldMemoryOperand() to
  981. /// reject subregs - but since this behavior used to be enforced in the
  982. /// target-independent code, moving this responsibility to the targets
  983. /// has the potential of causing nasty silent breakage in out-of-tree targets.
  984. virtual bool isSubregFoldable() const { return false; }
  985. /// For a patchpoint, stackmap, or statepoint intrinsic, return the range of
  986. /// operands which can't be folded into stack references. Operands outside
  987. /// of the range are most likely foldable but it is not guaranteed.
  988. /// These instructions are unique in that stack references for some operands
  989. /// have the same execution cost (e.g. none) as the unfolded register forms.
  990. /// The ranged return is guaranteed to include all operands which can't be
  991. /// folded at zero cost.
  992. virtual std::pair<unsigned, unsigned>
  993. getPatchpointUnfoldableRange(const MachineInstr &MI) const;
  994. /// Attempt to fold a load or store of the specified stack
  995. /// slot into the specified machine instruction for the specified operand(s).
  996. /// If this is possible, a new instruction is returned with the specified
  997. /// operand folded, otherwise NULL is returned.
  998. /// The new instruction is inserted before MI, and the client is responsible
  999. /// for removing the old instruction.
  1000. /// If VRM is passed, the assigned physregs can be inspected by target to
  1001. /// decide on using an opcode (note that those assignments can still change).
  1002. MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
  1003. int FI,
  1004. LiveIntervals *LIS = nullptr,
  1005. VirtRegMap *VRM = nullptr) const;
  1006. /// Same as the previous version except it allows folding of any load and
  1007. /// store from / to any address, not just from a specific stack slot.
  1008. MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
  1009. MachineInstr &LoadMI,
  1010. LiveIntervals *LIS = nullptr) const;
  1011. /// Return true when there is potentially a faster code sequence
  1012. /// for an instruction chain ending in \p Root. All potential patterns are
  1013. /// returned in the \p Pattern vector. Pattern should be sorted in priority
  1014. /// order since the pattern evaluator stops checking as soon as it finds a
  1015. /// faster sequence.
  1016. /// \param Root - Instruction that could be combined with one of its operands
  1017. /// \param Patterns - Vector of possible combination patterns
  1018. virtual bool
  1019. getMachineCombinerPatterns(MachineInstr &Root,
  1020. SmallVectorImpl<MachineCombinerPattern> &Patterns,
  1021. bool DoRegPressureReduce) const;
  1022. /// Return true if target supports reassociation of instructions in machine
  1023. /// combiner pass to reduce register pressure for a given BB.
  1024. virtual bool
  1025. shouldReduceRegisterPressure(MachineBasicBlock *MBB,
  1026. RegisterClassInfo *RegClassInfo) const {
  1027. return false;
  1028. }
  1029. /// Fix up the placeholder we may add in genAlternativeCodeSequence().
  1030. virtual void
  1031. finalizeInsInstrs(MachineInstr &Root, MachineCombinerPattern &P,
  1032. SmallVectorImpl<MachineInstr *> &InsInstrs) const {}
  1033. /// Return true when a code sequence can improve throughput. It
  1034. /// should be called only for instructions in loops.
  1035. /// \param Pattern - combiner pattern
  1036. virtual bool isThroughputPattern(MachineCombinerPattern Pattern) const;
  1037. /// Return true if the input \P Inst is part of a chain of dependent ops
  1038. /// that are suitable for reassociation, otherwise return false.
  1039. /// If the instruction's operands must be commuted to have a previous
  1040. /// instruction of the same type define the first source operand, \P Commuted
  1041. /// will be set to true.
  1042. bool isReassociationCandidate(const MachineInstr &Inst, bool &Commuted) const;
  1043. /// Return true when \P Inst is both associative and commutative.
  1044. virtual bool isAssociativeAndCommutative(const MachineInstr &Inst) const {
  1045. return false;
  1046. }
  1047. /// Return true when \P Inst has reassociable operands in the same \P MBB.
  1048. virtual bool hasReassociableOperands(const MachineInstr &Inst,
  1049. const MachineBasicBlock *MBB) const;
  1050. /// Return true when \P Inst has reassociable sibling.
  1051. bool hasReassociableSibling(const MachineInstr &Inst, bool &Commuted) const;
  1052. /// When getMachineCombinerPatterns() finds patterns, this function generates
  1053. /// the instructions that could replace the original code sequence. The client
  1054. /// has to decide whether the actual replacement is beneficial or not.
  1055. /// \param Root - Instruction that could be combined with one of its operands
  1056. /// \param Pattern - Combination pattern for Root
  1057. /// \param InsInstrs - Vector of new instructions that implement P
  1058. /// \param DelInstrs - Old instructions, including Root, that could be
  1059. /// replaced by InsInstr
  1060. /// \param InstIdxForVirtReg - map of virtual register to instruction in
  1061. /// InsInstr that defines it
  1062. virtual void genAlternativeCodeSequence(
  1063. MachineInstr &Root, MachineCombinerPattern Pattern,
  1064. SmallVectorImpl<MachineInstr *> &InsInstrs,
  1065. SmallVectorImpl<MachineInstr *> &DelInstrs,
  1066. DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const;
  1067. /// Attempt to reassociate \P Root and \P Prev according to \P Pattern to
  1068. /// reduce critical path length.
  1069. void reassociateOps(MachineInstr &Root, MachineInstr &Prev,
  1070. MachineCombinerPattern Pattern,
  1071. SmallVectorImpl<MachineInstr *> &InsInstrs,
  1072. SmallVectorImpl<MachineInstr *> &DelInstrs,
  1073. DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const;
  1074. /// The limit on resource length extension we accept in MachineCombiner Pass.
  1075. virtual int getExtendResourceLenLimit() const { return 0; }
  1076. /// This is an architecture-specific helper function of reassociateOps.
  1077. /// Set special operand attributes for new instructions after reassociation.
  1078. virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
  1079. MachineInstr &NewMI1,
  1080. MachineInstr &NewMI2) const {}
  1081. /// Return true when a target supports MachineCombiner.
  1082. virtual bool useMachineCombiner() const { return false; }
  1083. /// Return true if the given SDNode can be copied during scheduling
  1084. /// even if it has glue.
  1085. virtual bool canCopyGluedNodeDuringSchedule(SDNode *N) const { return false; }
  1086. protected:
  1087. /// Target-dependent implementation for foldMemoryOperand.
  1088. /// Target-independent code in foldMemoryOperand will
  1089. /// take care of adding a MachineMemOperand to the newly created instruction.
  1090. /// The instruction and any auxiliary instructions necessary will be inserted
  1091. /// at InsertPt.
  1092. virtual MachineInstr *
  1093. foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
  1094. ArrayRef<unsigned> Ops,
  1095. MachineBasicBlock::iterator InsertPt, int FrameIndex,
  1096. LiveIntervals *LIS = nullptr,
  1097. VirtRegMap *VRM = nullptr) const {
  1098. return nullptr;
  1099. }
  1100. /// Target-dependent implementation for foldMemoryOperand.
  1101. /// Target-independent code in foldMemoryOperand will
  1102. /// take care of adding a MachineMemOperand to the newly created instruction.
  1103. /// The instruction and any auxiliary instructions necessary will be inserted
  1104. /// at InsertPt.
  1105. virtual MachineInstr *foldMemoryOperandImpl(
  1106. MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
  1107. MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
  1108. LiveIntervals *LIS = nullptr) const {
  1109. return nullptr;
  1110. }
  1111. /// Target-dependent implementation of getRegSequenceInputs.
  1112. ///
  1113. /// \returns true if it is possible to build the equivalent
  1114. /// REG_SEQUENCE inputs with the pair \p MI, \p DefIdx. False otherwise.
  1115. ///
  1116. /// \pre MI.isRegSequenceLike().
  1117. ///
  1118. /// \see TargetInstrInfo::getRegSequenceInputs.
  1119. virtual bool getRegSequenceLikeInputs(
  1120. const MachineInstr &MI, unsigned DefIdx,
  1121. SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
  1122. return false;
  1123. }
  1124. /// Target-dependent implementation of getExtractSubregInputs.
  1125. ///
  1126. /// \returns true if it is possible to build the equivalent
  1127. /// EXTRACT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
  1128. ///
  1129. /// \pre MI.isExtractSubregLike().
  1130. ///
  1131. /// \see TargetInstrInfo::getExtractSubregInputs.
  1132. virtual bool getExtractSubregLikeInputs(const MachineInstr &MI,
  1133. unsigned DefIdx,
  1134. RegSubRegPairAndIdx &InputReg) const {
  1135. return false;
  1136. }
  1137. /// Target-dependent implementation of getInsertSubregInputs.
  1138. ///
  1139. /// \returns true if it is possible to build the equivalent
  1140. /// INSERT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
  1141. ///
  1142. /// \pre MI.isInsertSubregLike().
  1143. ///
  1144. /// \see TargetInstrInfo::getInsertSubregInputs.
  1145. virtual bool
  1146. getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx,
  1147. RegSubRegPair &BaseReg,
  1148. RegSubRegPairAndIdx &InsertedReg) const {
  1149. return false;
  1150. }
  1151. public:
  1152. /// getAddressSpaceForPseudoSourceKind - Given the kind of memory
  1153. /// (e.g. stack) the target returns the corresponding address space.
  1154. virtual unsigned
  1155. getAddressSpaceForPseudoSourceKind(unsigned Kind) const {
  1156. return 0;
  1157. }
  1158. /// unfoldMemoryOperand - Separate a single instruction which folded a load or
  1159. /// a store or a load and a store into two or more instruction. If this is
  1160. /// possible, returns true as well as the new instructions by reference.
  1161. virtual bool
  1162. unfoldMemoryOperand(MachineFunction &MF, MachineInstr &MI, unsigned Reg,
  1163. bool UnfoldLoad, bool UnfoldStore,
  1164. SmallVectorImpl<MachineInstr *> &NewMIs) const {
  1165. return false;
  1166. }
  1167. virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
  1168. SmallVectorImpl<SDNode *> &NewNodes) const {
  1169. return false;
  1170. }
  1171. /// Returns the opcode of the would be new
  1172. /// instruction after load / store are unfolded from an instruction of the
  1173. /// specified opcode. It returns zero if the specified unfolding is not
  1174. /// possible. If LoadRegIndex is non-null, it is filled in with the operand
  1175. /// index of the operand which will hold the register holding the loaded
  1176. /// value.
  1177. virtual unsigned
  1178. getOpcodeAfterMemoryUnfold(unsigned Opc, bool UnfoldLoad, bool UnfoldStore,
  1179. unsigned *LoadRegIndex = nullptr) const {
  1180. return 0;
  1181. }
  1182. /// This is used by the pre-regalloc scheduler to determine if two loads are
  1183. /// loading from the same base address. It should only return true if the base
  1184. /// pointers are the same and the only differences between the two addresses
  1185. /// are the offset. It also returns the offsets by reference.
  1186. virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
  1187. int64_t &Offset1,
  1188. int64_t &Offset2) const {
  1189. return false;
  1190. }
  1191. /// This is a used by the pre-regalloc scheduler to determine (in conjunction
  1192. /// with areLoadsFromSameBasePtr) if two loads should be scheduled together.
  1193. /// On some targets if two loads are loading from
  1194. /// addresses in the same cache line, it's better if they are scheduled
  1195. /// together. This function takes two integers that represent the load offsets
  1196. /// from the common base address. It returns true if it decides it's desirable
  1197. /// to schedule the two loads together. "NumLoads" is the number of loads that
  1198. /// have already been scheduled after Load1.
  1199. virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
  1200. int64_t Offset1, int64_t Offset2,
  1201. unsigned NumLoads) const {
  1202. return false;
  1203. }
  1204. /// Get the base operand and byte offset of an instruction that reads/writes
  1205. /// memory. This is a convenience function for callers that are only prepared
  1206. /// to handle a single base operand.
  1207. bool getMemOperandWithOffset(const MachineInstr &MI,
  1208. const MachineOperand *&BaseOp, int64_t &Offset,
  1209. bool &OffsetIsScalable,
  1210. const TargetRegisterInfo *TRI) const;
  1211. /// Get zero or more base operands and the byte offset of an instruction that
  1212. /// reads/writes memory. Note that there may be zero base operands if the
  1213. /// instruction accesses a constant address.
  1214. /// It returns false if MI does not read/write memory.
  1215. /// It returns false if base operands and offset could not be determined.
  1216. /// It is not guaranteed to always recognize base operands and offsets in all
  1217. /// cases.
  1218. virtual bool getMemOperandsWithOffsetWidth(
  1219. const MachineInstr &MI, SmallVectorImpl<const MachineOperand *> &BaseOps,
  1220. int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
  1221. const TargetRegisterInfo *TRI) const {
  1222. return false;
  1223. }
  1224. /// Return true if the instruction contains a base register and offset. If
  1225. /// true, the function also sets the operand position in the instruction
  1226. /// for the base register and offset.
  1227. virtual bool getBaseAndOffsetPosition(const MachineInstr &MI,
  1228. unsigned &BasePos,
  1229. unsigned &OffsetPos) const {
  1230. return false;
  1231. }
  1232. /// Target dependent implementation to get the values constituting the address
  1233. /// MachineInstr that is accessing memory. These values are returned as a
  1234. /// struct ExtAddrMode which contains all relevant information to make up the
  1235. /// address.
  1236. virtual Optional<ExtAddrMode>
  1237. getAddrModeFromMemoryOp(const MachineInstr &MemI,
  1238. const TargetRegisterInfo *TRI) const {
  1239. return None;
  1240. }
  1241. /// Returns true if MI's Def is NullValueReg, and the MI
  1242. /// does not change the Zero value. i.e. cases such as rax = shr rax, X where
  1243. /// NullValueReg = rax. Note that if the NullValueReg is non-zero, this
  1244. /// function can return true even if becomes zero. Specifically cases such as
  1245. /// NullValueReg = shl NullValueReg, 63.
  1246. virtual bool preservesZeroValueInReg(const MachineInstr *MI,
  1247. const Register NullValueReg,
  1248. const TargetRegisterInfo *TRI) const {
  1249. return false;
  1250. }
  1251. /// If the instruction is an increment of a constant value, return the amount.
  1252. virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const {
  1253. return false;
  1254. }
  1255. /// Returns true if the two given memory operations should be scheduled
  1256. /// adjacent. Note that you have to add:
  1257. /// DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
  1258. /// or
  1259. /// DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
  1260. /// to TargetPassConfig::createMachineScheduler() to have an effect.
  1261. ///
  1262. /// \p BaseOps1 and \p BaseOps2 are memory operands of two memory operations.
  1263. /// \p NumLoads is the number of loads that will be in the cluster if this
  1264. /// hook returns true.
  1265. /// \p NumBytes is the number of bytes that will be loaded from all the
  1266. /// clustered loads if this hook returns true.
  1267. virtual bool shouldClusterMemOps(ArrayRef<const MachineOperand *> BaseOps1,
  1268. ArrayRef<const MachineOperand *> BaseOps2,
  1269. unsigned NumLoads, unsigned NumBytes) const {
  1270. llvm_unreachable("target did not implement shouldClusterMemOps()");
  1271. }
  1272. /// Reverses the branch condition of the specified condition list,
  1273. /// returning false on success and true if it cannot be reversed.
  1274. virtual bool
  1275. reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
  1276. return true;
  1277. }
  1278. /// Insert a noop into the instruction stream at the specified point.
  1279. virtual void insertNoop(MachineBasicBlock &MBB,
  1280. MachineBasicBlock::iterator MI) const;
  1281. /// Insert noops into the instruction stream at the specified point.
  1282. virtual void insertNoops(MachineBasicBlock &MBB,
  1283. MachineBasicBlock::iterator MI,
  1284. unsigned Quantity) const;
  1285. /// Return the noop instruction to use for a noop.
  1286. virtual MCInst getNop() const;
  1287. /// Return true for post-incremented instructions.
  1288. virtual bool isPostIncrement(const MachineInstr &MI) const { return false; }
  1289. /// Returns true if the instruction is already predicated.
  1290. virtual bool isPredicated(const MachineInstr &MI) const { return false; }
  1291. // Returns a MIRPrinter comment for this machine operand.
  1292. virtual std::string
  1293. createMIROperandComment(const MachineInstr &MI, const MachineOperand &Op,
  1294. unsigned OpIdx, const TargetRegisterInfo *TRI) const;
  1295. /// Returns true if the instruction is a
  1296. /// terminator instruction that has not been predicated.
  1297. bool isUnpredicatedTerminator(const MachineInstr &MI) const;
  1298. /// Returns true if MI is an unconditional tail call.
  1299. virtual bool isUnconditionalTailCall(const MachineInstr &MI) const {
  1300. return false;
  1301. }
  1302. /// Returns true if the tail call can be made conditional on BranchCond.
  1303. virtual bool canMakeTailCallConditional(SmallVectorImpl<MachineOperand> &Cond,
  1304. const MachineInstr &TailCall) const {
  1305. return false;
  1306. }
  1307. /// Replace the conditional branch in MBB with a conditional tail call.
  1308. virtual void replaceBranchWithTailCall(MachineBasicBlock &MBB,
  1309. SmallVectorImpl<MachineOperand> &Cond,
  1310. const MachineInstr &TailCall) const {
  1311. llvm_unreachable("Target didn't implement replaceBranchWithTailCall!");
  1312. }
  1313. /// Convert the instruction into a predicated instruction.
  1314. /// It returns true if the operation was successful.
  1315. virtual bool PredicateInstruction(MachineInstr &MI,
  1316. ArrayRef<MachineOperand> Pred) const;
  1317. /// Returns true if the first specified predicate
  1318. /// subsumes the second, e.g. GE subsumes GT.
  1319. virtual bool SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
  1320. ArrayRef<MachineOperand> Pred2) const {
  1321. return false;
  1322. }
  1323. /// If the specified instruction defines any predicate
  1324. /// or condition code register(s) used for predication, returns true as well
  1325. /// as the definition predicate(s) by reference.
  1326. /// SkipDead should be set to false at any point that dead
  1327. /// predicate instructions should be considered as being defined.
  1328. /// A dead predicate instruction is one that is guaranteed to be removed
  1329. /// after a call to PredicateInstruction.
  1330. virtual bool ClobbersPredicate(MachineInstr &MI,
  1331. std::vector<MachineOperand> &Pred,
  1332. bool SkipDead) const {
  1333. return false;
  1334. }
  1335. /// Return true if the specified instruction can be predicated.
  1336. /// By default, this returns true for every instruction with a
  1337. /// PredicateOperand.
  1338. virtual bool isPredicable(const MachineInstr &MI) const {
  1339. return MI.getDesc().isPredicable();
  1340. }
  1341. /// Return true if it's safe to move a machine
  1342. /// instruction that defines the specified register class.
  1343. virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
  1344. return true;
  1345. }
  1346. /// Test if the given instruction should be considered a scheduling boundary.
  1347. /// This primarily includes labels and terminators.
  1348. virtual bool isSchedulingBoundary(const MachineInstr &MI,
  1349. const MachineBasicBlock *MBB,
  1350. const MachineFunction &MF) const;
  1351. /// Measure the specified inline asm to determine an approximation of its
  1352. /// length.
  1353. virtual unsigned getInlineAsmLength(
  1354. const char *Str, const MCAsmInfo &MAI,
  1355. const TargetSubtargetInfo *STI = nullptr) const;
  1356. /// Allocate and return a hazard recognizer to use for this target when
  1357. /// scheduling the machine instructions before register allocation.
  1358. virtual ScheduleHazardRecognizer *
  1359. CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
  1360. const ScheduleDAG *DAG) const;
  1361. /// Allocate and return a hazard recognizer to use for this target when
  1362. /// scheduling the machine instructions before register allocation.
  1363. virtual ScheduleHazardRecognizer *
  1364. CreateTargetMIHazardRecognizer(const InstrItineraryData *,
  1365. const ScheduleDAGMI *DAG) const;
  1366. /// Allocate and return a hazard recognizer to use for this target when
  1367. /// scheduling the machine instructions after register allocation.
  1368. virtual ScheduleHazardRecognizer *
  1369. CreateTargetPostRAHazardRecognizer(const InstrItineraryData *,
  1370. const ScheduleDAG *DAG) const;
  1371. /// Allocate and return a hazard recognizer to use for by non-scheduling
  1372. /// passes.
  1373. virtual ScheduleHazardRecognizer *
  1374. CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
  1375. return nullptr;
  1376. }
  1377. /// Provide a global flag for disabling the PreRA hazard recognizer that
  1378. /// targets may choose to honor.
  1379. bool usePreRAHazardRecognizer() const;
  1380. /// For a comparison instruction, return the source registers
  1381. /// in SrcReg and SrcReg2 if having two register operands, and the value it
  1382. /// compares against in CmpValue. Return true if the comparison instruction
  1383. /// can be analyzed.
  1384. virtual bool analyzeCompare(const MachineInstr &MI, Register &SrcReg,
  1385. Register &SrcReg2, int64_t &Mask,
  1386. int64_t &Value) const {
  1387. return false;
  1388. }
  1389. /// See if the comparison instruction can be converted
  1390. /// into something more efficient. E.g., on ARM most instructions can set the
  1391. /// flags register, obviating the need for a separate CMP.
  1392. virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
  1393. Register SrcReg2, int64_t Mask,
  1394. int64_t Value,
  1395. const MachineRegisterInfo *MRI) const {
  1396. return false;
  1397. }
  1398. virtual bool optimizeCondBranch(MachineInstr &MI) const { return false; }
  1399. /// Try to remove the load by folding it to a register operand at the use.
  1400. /// We fold the load instructions if and only if the
  1401. /// def and use are in the same BB. We only look at one load and see
  1402. /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
  1403. /// defined by the load we are trying to fold. DefMI returns the machine
  1404. /// instruction that defines FoldAsLoadDefReg, and the function returns
  1405. /// the machine instruction generated due to folding.
  1406. virtual MachineInstr *optimizeLoadInstr(MachineInstr &MI,
  1407. const MachineRegisterInfo *MRI,
  1408. Register &FoldAsLoadDefReg,
  1409. MachineInstr *&DefMI) const {
  1410. return nullptr;
  1411. }
  1412. /// 'Reg' is known to be defined by a move immediate instruction,
  1413. /// try to fold the immediate into the use instruction.
  1414. /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
  1415. /// then the caller may assume that DefMI has been erased from its parent
  1416. /// block. The caller may assume that it will not be erased by this
  1417. /// function otherwise.
  1418. virtual bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
  1419. Register Reg, MachineRegisterInfo *MRI) const {
  1420. return false;
  1421. }
  1422. /// Return the number of u-operations the given machine
  1423. /// instruction will be decoded to on the target cpu. The itinerary's
  1424. /// IssueWidth is the number of microops that can be dispatched each
  1425. /// cycle. An instruction with zero microops takes no dispatch resources.
  1426. virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
  1427. const MachineInstr &MI) const;
  1428. /// Return true for pseudo instructions that don't consume any
  1429. /// machine resources in their current form. These are common cases that the
  1430. /// scheduler should consider free, rather than conservatively handling them
  1431. /// as instructions with no itinerary.
  1432. bool isZeroCost(unsigned Opcode) const {
  1433. return Opcode <= TargetOpcode::COPY;
  1434. }
  1435. virtual int getOperandLatency(const InstrItineraryData *ItinData,
  1436. SDNode *DefNode, unsigned DefIdx,
  1437. SDNode *UseNode, unsigned UseIdx) const;
  1438. /// Compute and return the use operand latency of a given pair of def and use.
  1439. /// In most cases, the static scheduling itinerary was enough to determine the
  1440. /// operand latency. But it may not be possible for instructions with variable
  1441. /// number of defs / uses.
  1442. ///
  1443. /// This is a raw interface to the itinerary that may be directly overridden
  1444. /// by a target. Use computeOperandLatency to get the best estimate of
  1445. /// latency.
  1446. virtual int getOperandLatency(const InstrItineraryData *ItinData,
  1447. const MachineInstr &DefMI, unsigned DefIdx,
  1448. const MachineInstr &UseMI,
  1449. unsigned UseIdx) const;
  1450. /// Compute the instruction latency of a given instruction.
  1451. /// If the instruction has higher cost when predicated, it's returned via
  1452. /// PredCost.
  1453. virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
  1454. const MachineInstr &MI,
  1455. unsigned *PredCost = nullptr) const;
  1456. virtual unsigned getPredicationCost(const MachineInstr &MI) const;
  1457. virtual int getInstrLatency(const InstrItineraryData *ItinData,
  1458. SDNode *Node) const;
  1459. /// Return the default expected latency for a def based on its opcode.
  1460. unsigned defaultDefLatency(const MCSchedModel &SchedModel,
  1461. const MachineInstr &DefMI) const;
  1462. /// Return true if this opcode has high latency to its result.
  1463. virtual bool isHighLatencyDef(int opc) const { return false; }
  1464. /// Compute operand latency between a def of 'Reg'
  1465. /// and a use in the current loop. Return true if the target considered
  1466. /// it 'high'. This is used by optimization passes such as machine LICM to
  1467. /// determine whether it makes sense to hoist an instruction out even in a
  1468. /// high register pressure situation.
  1469. virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
  1470. const MachineRegisterInfo *MRI,
  1471. const MachineInstr &DefMI, unsigned DefIdx,
  1472. const MachineInstr &UseMI,
  1473. unsigned UseIdx) const {
  1474. return false;
  1475. }
  1476. /// Compute operand latency of a def of 'Reg'. Return true
  1477. /// if the target considered it 'low'.
  1478. virtual bool hasLowDefLatency(const TargetSchedModel &SchedModel,
  1479. const MachineInstr &DefMI,
  1480. unsigned DefIdx) const;
  1481. /// Perform target-specific instruction verification.
  1482. virtual bool verifyInstruction(const MachineInstr &MI,
  1483. StringRef &ErrInfo) const {
  1484. return true;
  1485. }
  1486. /// Return the current execution domain and bit mask of
  1487. /// possible domains for instruction.
  1488. ///
  1489. /// Some micro-architectures have multiple execution domains, and multiple
  1490. /// opcodes that perform the same operation in different domains. For
  1491. /// example, the x86 architecture provides the por, orps, and orpd
  1492. /// instructions that all do the same thing. There is a latency penalty if a
  1493. /// register is written in one domain and read in another.
  1494. ///
  1495. /// This function returns a pair (domain, mask) containing the execution
  1496. /// domain of MI, and a bit mask of possible domains. The setExecutionDomain
  1497. /// function can be used to change the opcode to one of the domains in the
  1498. /// bit mask. Instructions whose execution domain can't be changed should
  1499. /// return a 0 mask.
  1500. ///
  1501. /// The execution domain numbers don't have any special meaning except domain
  1502. /// 0 is used for instructions that are not associated with any interesting
  1503. /// execution domain.
  1504. ///
  1505. virtual std::pair<uint16_t, uint16_t>
  1506. getExecutionDomain(const MachineInstr &MI) const {
  1507. return std::make_pair(0, 0);
  1508. }
  1509. /// Change the opcode of MI to execute in Domain.
  1510. ///
  1511. /// The bit (1 << Domain) must be set in the mask returned from
  1512. /// getExecutionDomain(MI).
  1513. virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const {}
  1514. /// Returns the preferred minimum clearance
  1515. /// before an instruction with an unwanted partial register update.
  1516. ///
  1517. /// Some instructions only write part of a register, and implicitly need to
  1518. /// read the other parts of the register. This may cause unwanted stalls
  1519. /// preventing otherwise unrelated instructions from executing in parallel in
  1520. /// an out-of-order CPU.
  1521. ///
  1522. /// For example, the x86 instruction cvtsi2ss writes its result to bits
  1523. /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
  1524. /// the instruction needs to wait for the old value of the register to become
  1525. /// available:
  1526. ///
  1527. /// addps %xmm1, %xmm0
  1528. /// movaps %xmm0, (%rax)
  1529. /// cvtsi2ss %rbx, %xmm0
  1530. ///
  1531. /// In the code above, the cvtsi2ss instruction needs to wait for the addps
  1532. /// instruction before it can issue, even though the high bits of %xmm0
  1533. /// probably aren't needed.
  1534. ///
  1535. /// This hook returns the preferred clearance before MI, measured in
  1536. /// instructions. Other defs of MI's operand OpNum are avoided in the last N
  1537. /// instructions before MI. It should only return a positive value for
  1538. /// unwanted dependencies. If the old bits of the defined register have
  1539. /// useful values, or if MI is determined to otherwise read the dependency,
  1540. /// the hook should return 0.
  1541. ///
  1542. /// The unwanted dependency may be handled by:
  1543. ///
  1544. /// 1. Allocating the same register for an MI def and use. That makes the
  1545. /// unwanted dependency identical to a required dependency.
  1546. ///
  1547. /// 2. Allocating a register for the def that has no defs in the previous N
  1548. /// instructions.
  1549. ///
  1550. /// 3. Calling breakPartialRegDependency() with the same arguments. This
  1551. /// allows the target to insert a dependency breaking instruction.
  1552. ///
  1553. virtual unsigned
  1554. getPartialRegUpdateClearance(const MachineInstr &MI, unsigned OpNum,
  1555. const TargetRegisterInfo *TRI) const {
  1556. // The default implementation returns 0 for no partial register dependency.
  1557. return 0;
  1558. }
  1559. /// Return the minimum clearance before an instruction that reads an
  1560. /// unused register.
  1561. ///
  1562. /// For example, AVX instructions may copy part of a register operand into
  1563. /// the unused high bits of the destination register.
  1564. ///
  1565. /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
  1566. ///
  1567. /// In the code above, vcvtsi2sdq copies %xmm0[127:64] into %xmm14 creating a
  1568. /// false dependence on any previous write to %xmm0.
  1569. ///
  1570. /// This hook works similarly to getPartialRegUpdateClearance, except that it
  1571. /// does not take an operand index. Instead sets \p OpNum to the index of the
  1572. /// unused register.
  1573. virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned OpNum,
  1574. const TargetRegisterInfo *TRI) const {
  1575. // The default implementation returns 0 for no undef register dependency.
  1576. return 0;
  1577. }
  1578. /// Insert a dependency-breaking instruction
  1579. /// before MI to eliminate an unwanted dependency on OpNum.
  1580. ///
  1581. /// If it wasn't possible to avoid a def in the last N instructions before MI
  1582. /// (see getPartialRegUpdateClearance), this hook will be called to break the
  1583. /// unwanted dependency.
  1584. ///
  1585. /// On x86, an xorps instruction can be used as a dependency breaker:
  1586. ///
  1587. /// addps %xmm1, %xmm0
  1588. /// movaps %xmm0, (%rax)
  1589. /// xorps %xmm0, %xmm0
  1590. /// cvtsi2ss %rbx, %xmm0
  1591. ///
  1592. /// An <imp-kill> operand should be added to MI if an instruction was
  1593. /// inserted. This ties the instructions together in the post-ra scheduler.
  1594. ///
  1595. virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum,
  1596. const TargetRegisterInfo *TRI) const {}
  1597. /// Create machine specific model for scheduling.
  1598. virtual DFAPacketizer *
  1599. CreateTargetScheduleState(const TargetSubtargetInfo &) const {
  1600. return nullptr;
  1601. }
  1602. /// Sometimes, it is possible for the target
  1603. /// to tell, even without aliasing information, that two MIs access different
  1604. /// memory addresses. This function returns true if two MIs access different
  1605. /// memory addresses and false otherwise.
  1606. ///
  1607. /// Assumes any physical registers used to compute addresses have the same
  1608. /// value for both instructions. (This is the most useful assumption for
  1609. /// post-RA scheduling.)
  1610. ///
  1611. /// See also MachineInstr::mayAlias, which is implemented on top of this
  1612. /// function.
  1613. virtual bool
  1614. areMemAccessesTriviallyDisjoint(const MachineInstr &MIa,
  1615. const MachineInstr &MIb) const {
  1616. assert(MIa.mayLoadOrStore() &&
  1617. "MIa must load from or modify a memory location");
  1618. assert(MIb.mayLoadOrStore() &&
  1619. "MIb must load from or modify a memory location");
  1620. return false;
  1621. }
  1622. /// Return the value to use for the MachineCSE's LookAheadLimit,
  1623. /// which is a heuristic used for CSE'ing phys reg defs.
  1624. virtual unsigned getMachineCSELookAheadLimit() const {
  1625. // The default lookahead is small to prevent unprofitable quadratic
  1626. // behavior.
  1627. return 5;
  1628. }
  1629. /// Return the maximal number of alias checks on memory operands. For
  1630. /// instructions with more than one memory operands, the alias check on a
  1631. /// single MachineInstr pair has quadratic overhead and results in
  1632. /// unacceptable performance in the worst case. The limit here is to clamp
  1633. /// that maximal checks performed. Usually, that's the product of memory
  1634. /// operand numbers from that pair of MachineInstr to be checked. For
  1635. /// instance, with two MachineInstrs with 4 and 5 memory operands
  1636. /// correspondingly, a total of 20 checks are required. With this limit set to
  1637. /// 16, their alias check is skipped. We choose to limit the product instead
  1638. /// of the individual instruction as targets may have special MachineInstrs
  1639. /// with a considerably high number of memory operands, such as `ldm` in ARM.
  1640. /// Setting this limit per MachineInstr would result in either too high
  1641. /// overhead or too rigid restriction.
  1642. virtual unsigned getMemOperandAACheckLimit() const { return 16; }
  1643. /// Return an array that contains the ids of the target indices (used for the
  1644. /// TargetIndex machine operand) and their names.
  1645. ///
  1646. /// MIR Serialization is able to serialize only the target indices that are
  1647. /// defined by this method.
  1648. virtual ArrayRef<std::pair<int, const char *>>
  1649. getSerializableTargetIndices() const {
  1650. return None;
  1651. }
  1652. /// Decompose the machine operand's target flags into two values - the direct
  1653. /// target flag value and any of bit flags that are applied.
  1654. virtual std::pair<unsigned, unsigned>
  1655. decomposeMachineOperandsTargetFlags(unsigned /*TF*/) const {
  1656. return std::make_pair(0u, 0u);
  1657. }
  1658. /// Return an array that contains the direct target flag values and their
  1659. /// names.
  1660. ///
  1661. /// MIR Serialization is able to serialize only the target flags that are
  1662. /// defined by this method.
  1663. virtual ArrayRef<std::pair<unsigned, const char *>>
  1664. getSerializableDirectMachineOperandTargetFlags() const {
  1665. return None;
  1666. }
  1667. /// Return an array that contains the bitmask target flag values and their
  1668. /// names.
  1669. ///
  1670. /// MIR Serialization is able to serialize only the target flags that are
  1671. /// defined by this method.
  1672. virtual ArrayRef<std::pair<unsigned, const char *>>
  1673. getSerializableBitmaskMachineOperandTargetFlags() const {
  1674. return None;
  1675. }
  1676. /// Return an array that contains the MMO target flag values and their
  1677. /// names.
  1678. ///
  1679. /// MIR Serialization is able to serialize only the MMO target flags that are
  1680. /// defined by this method.
  1681. virtual ArrayRef<std::pair<MachineMemOperand::Flags, const char *>>
  1682. getSerializableMachineMemOperandTargetFlags() const {
  1683. return None;
  1684. }
  1685. /// Determines whether \p Inst is a tail call instruction. Override this
  1686. /// method on targets that do not properly set MCID::Return and MCID::Call on
  1687. /// tail call instructions."
  1688. virtual bool isTailCall(const MachineInstr &Inst) const {
  1689. return Inst.isReturn() && Inst.isCall();
  1690. }
  1691. /// True if the instruction is bound to the top of its basic block and no
  1692. /// other instructions shall be inserted before it. This can be implemented
  1693. /// to prevent register allocator to insert spills before such instructions.
  1694. virtual bool isBasicBlockPrologue(const MachineInstr &MI) const {
  1695. return false;
  1696. }
  1697. /// During PHI eleimination lets target to make necessary checks and
  1698. /// insert the copy to the PHI destination register in a target specific
  1699. /// manner.
  1700. virtual MachineInstr *createPHIDestinationCopy(
  1701. MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
  1702. const DebugLoc &DL, Register Src, Register Dst) const {
  1703. return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
  1704. .addReg(Src);
  1705. }
  1706. /// During PHI eleimination lets target to make necessary checks and
  1707. /// insert the copy to the PHI destination register in a target specific
  1708. /// manner.
  1709. virtual MachineInstr *createPHISourceCopy(MachineBasicBlock &MBB,
  1710. MachineBasicBlock::iterator InsPt,
  1711. const DebugLoc &DL, Register Src,
  1712. unsigned SrcSubReg,
  1713. Register Dst) const {
  1714. return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
  1715. .addReg(Src, 0, SrcSubReg);
  1716. }
  1717. /// Returns a \p outliner::OutlinedFunction struct containing target-specific
  1718. /// information for a set of outlining candidates.
  1719. virtual outliner::OutlinedFunction getOutliningCandidateInfo(
  1720. std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
  1721. llvm_unreachable(
  1722. "Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!");
  1723. }
  1724. /// Optional target hook to create the LLVM IR attributes for the outlined
  1725. /// function. If overridden, the overriding function must call the default
  1726. /// implementation.
  1727. virtual void mergeOutliningCandidateAttributes(
  1728. Function &F, std::vector<outliner::Candidate> &Candidates) const;
  1729. /// Returns how or if \p MI should be outlined.
  1730. virtual outliner::InstrType
  1731. getOutliningType(MachineBasicBlock::iterator &MIT, unsigned Flags) const {
  1732. llvm_unreachable(
  1733. "Target didn't implement TargetInstrInfo::getOutliningType!");
  1734. }
  1735. /// Optional target hook that returns true if \p MBB is safe to outline from,
  1736. /// and returns any target-specific information in \p Flags.
  1737. virtual bool isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
  1738. unsigned &Flags) const;
  1739. /// Insert a custom frame for outlined functions.
  1740. virtual void buildOutlinedFrame(MachineBasicBlock &MBB, MachineFunction &MF,
  1741. const outliner::OutlinedFunction &OF) const {
  1742. llvm_unreachable(
  1743. "Target didn't implement TargetInstrInfo::buildOutlinedFrame!");
  1744. }
  1745. /// Insert a call to an outlined function into the program.
  1746. /// Returns an iterator to the spot where we inserted the call. This must be
  1747. /// implemented by the target.
  1748. virtual MachineBasicBlock::iterator
  1749. insertOutlinedCall(Module &M, MachineBasicBlock &MBB,
  1750. MachineBasicBlock::iterator &It, MachineFunction &MF,
  1751. const outliner::Candidate &C) const {
  1752. llvm_unreachable(
  1753. "Target didn't implement TargetInstrInfo::insertOutlinedCall!");
  1754. }
  1755. /// Return true if the function can safely be outlined from.
  1756. /// A function \p MF is considered safe for outlining if an outlined function
  1757. /// produced from instructions in F will produce a program which produces the
  1758. /// same output for any set of given inputs.
  1759. virtual bool isFunctionSafeToOutlineFrom(MachineFunction &MF,
  1760. bool OutlineFromLinkOnceODRs) const {
  1761. llvm_unreachable("Target didn't implement "
  1762. "TargetInstrInfo::isFunctionSafeToOutlineFrom!");
  1763. }
  1764. /// Return true if the function should be outlined from by default.
  1765. virtual bool shouldOutlineFromFunctionByDefault(MachineFunction &MF) const {
  1766. return false;
  1767. }
  1768. /// Produce the expression describing the \p MI loading a value into
  1769. /// the physical register \p Reg. This hook should only be used with
  1770. /// \p MIs belonging to VReg-less functions.
  1771. virtual Optional<ParamLoadedValue> describeLoadedValue(const MachineInstr &MI,
  1772. Register Reg) const;
  1773. /// Given the generic extension instruction \p ExtMI, returns true if this
  1774. /// extension is a likely candidate for being folded into an another
  1775. /// instruction.
  1776. virtual bool isExtendLikelyToBeFolded(MachineInstr &ExtMI,
  1777. MachineRegisterInfo &MRI) const {
  1778. return false;
  1779. }
  1780. /// Return MIR formatter to format/parse MIR operands. Target can override
  1781. /// this virtual function and return target specific MIR formatter.
  1782. virtual const MIRFormatter *getMIRFormatter() const {
  1783. if (!Formatter.get())
  1784. Formatter = std::make_unique<MIRFormatter>();
  1785. return Formatter.get();
  1786. }
  1787. /// Returns the target-specific default value for tail duplication.
  1788. /// This value will be used if the tail-dup-placement-threshold argument is
  1789. /// not provided.
  1790. virtual unsigned getTailDuplicateSize(CodeGenOpt::Level OptLevel) const {
  1791. return OptLevel >= CodeGenOpt::Aggressive ? 4 : 2;
  1792. }
  1793. /// Returns the callee operand from the given \p MI.
  1794. virtual const MachineOperand &getCalleeOperand(const MachineInstr &MI) const {
  1795. return MI.getOperand(0);
  1796. }
  1797. private:
  1798. mutable std::unique_ptr<MIRFormatter> Formatter;
  1799. unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
  1800. unsigned CatchRetOpcode;
  1801. unsigned ReturnOpcode;
  1802. };
  1803. /// Provide DenseMapInfo for TargetInstrInfo::RegSubRegPair.
  1804. template <> struct DenseMapInfo<TargetInstrInfo::RegSubRegPair> {
  1805. using RegInfo = DenseMapInfo<unsigned>;
  1806. static inline TargetInstrInfo::RegSubRegPair getEmptyKey() {
  1807. return TargetInstrInfo::RegSubRegPair(RegInfo::getEmptyKey(),
  1808. RegInfo::getEmptyKey());
  1809. }
  1810. static inline TargetInstrInfo::RegSubRegPair getTombstoneKey() {
  1811. return TargetInstrInfo::RegSubRegPair(RegInfo::getTombstoneKey(),
  1812. RegInfo::getTombstoneKey());
  1813. }
  1814. /// Reuse getHashValue implementation from
  1815. /// std::pair<unsigned, unsigned>.
  1816. static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val) {
  1817. std::pair<unsigned, unsigned> PairVal = std::make_pair(Val.Reg, Val.SubReg);
  1818. return DenseMapInfo<std::pair<unsigned, unsigned>>::getHashValue(PairVal);
  1819. }
  1820. static bool isEqual(const TargetInstrInfo::RegSubRegPair &LHS,
  1821. const TargetInstrInfo::RegSubRegPair &RHS) {
  1822. return RegInfo::isEqual(LHS.Reg, RHS.Reg) &&
  1823. RegInfo::isEqual(LHS.SubReg, RHS.SubReg);
  1824. }
  1825. };
  1826. } // end namespace llvm
  1827. #endif // LLVM_CODEGEN_TARGETINSTRINFO_H
  1828. #ifdef __GNUC__
  1829. #pragma GCC diagnostic pop
  1830. #endif