TargetInstrInfo.h 96 KB

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