MachineInstr.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  1. //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Methods common to all machine instructions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/MachineInstr.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/FoldingSet.h"
  17. #include "llvm/ADT/Hashing.h"
  18. #include "llvm/ADT/None.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallBitVector.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/Analysis/AliasAnalysis.h"
  24. #include "llvm/Analysis/Loads.h"
  25. #include "llvm/Analysis/MemoryLocation.h"
  26. #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
  27. #include "llvm/CodeGen/MachineBasicBlock.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineInstrBuilder.h"
  30. #include "llvm/CodeGen/MachineInstrBundle.h"
  31. #include "llvm/CodeGen/MachineMemOperand.h"
  32. #include "llvm/CodeGen/MachineModuleInfo.h"
  33. #include "llvm/CodeGen/MachineOperand.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/PseudoSourceValue.h"
  36. #include "llvm/CodeGen/TargetInstrInfo.h"
  37. #include "llvm/CodeGen/TargetRegisterInfo.h"
  38. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  39. #include "llvm/Config/llvm-config.h"
  40. #include "llvm/IR/Constants.h"
  41. #include "llvm/IR/DebugInfoMetadata.h"
  42. #include "llvm/IR/DebugLoc.h"
  43. #include "llvm/IR/DerivedTypes.h"
  44. #include "llvm/IR/Function.h"
  45. #include "llvm/IR/InlineAsm.h"
  46. #include "llvm/IR/InstrTypes.h"
  47. #include "llvm/IR/Intrinsics.h"
  48. #include "llvm/IR/LLVMContext.h"
  49. #include "llvm/IR/Metadata.h"
  50. #include "llvm/IR/Module.h"
  51. #include "llvm/IR/ModuleSlotTracker.h"
  52. #include "llvm/IR/Type.h"
  53. #include "llvm/IR/Value.h"
  54. #include "llvm/MC/MCInstrDesc.h"
  55. #include "llvm/MC/MCRegisterInfo.h"
  56. #include "llvm/MC/MCSymbol.h"
  57. #include "llvm/Support/Casting.h"
  58. #include "llvm/Support/CommandLine.h"
  59. #include "llvm/Support/Compiler.h"
  60. #include "llvm/Support/Debug.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/LowLevelTypeImpl.h"
  63. #include "llvm/Support/MathExtras.h"
  64. #include "llvm/Support/raw_ostream.h"
  65. #include "llvm/Target/TargetIntrinsicInfo.h"
  66. #include "llvm/Target/TargetMachine.h"
  67. #include <algorithm>
  68. #include <cassert>
  69. #include <cstddef>
  70. #include <cstdint>
  71. #include <cstring>
  72. #include <iterator>
  73. #include <utility>
  74. using namespace llvm;
  75. static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) {
  76. if (const MachineBasicBlock *MBB = MI.getParent())
  77. if (const MachineFunction *MF = MBB->getParent())
  78. return MF;
  79. return nullptr;
  80. }
  81. // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
  82. // it.
  83. static void tryToGetTargetInfo(const MachineInstr &MI,
  84. const TargetRegisterInfo *&TRI,
  85. const MachineRegisterInfo *&MRI,
  86. const TargetIntrinsicInfo *&IntrinsicInfo,
  87. const TargetInstrInfo *&TII) {
  88. if (const MachineFunction *MF = getMFIfAvailable(MI)) {
  89. TRI = MF->getSubtarget().getRegisterInfo();
  90. MRI = &MF->getRegInfo();
  91. IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
  92. TII = MF->getSubtarget().getInstrInfo();
  93. }
  94. }
  95. void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
  96. if (MCID->ImplicitDefs)
  97. for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
  98. ++ImpDefs)
  99. addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
  100. if (MCID->ImplicitUses)
  101. for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
  102. ++ImpUses)
  103. addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
  104. }
  105. /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
  106. /// implicit operands. It reserves space for the number of operands specified by
  107. /// the MCInstrDesc.
  108. MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
  109. DebugLoc dl, bool NoImp)
  110. : MCID(&tid), debugLoc(std::move(dl)) {
  111. assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
  112. // Reserve space for the expected number of operands.
  113. if (unsigned NumOps = MCID->getNumOperands() +
  114. MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
  115. CapOperands = OperandCapacity::get(NumOps);
  116. Operands = MF.allocateOperandArray(CapOperands);
  117. }
  118. if (!NoImp)
  119. addImplicitDefUseOperands(MF);
  120. }
  121. /// MachineInstr ctor - Copies MachineInstr arg exactly
  122. ///
  123. MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
  124. : MCID(&MI.getDesc()), NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
  125. debugLoc(MI.getDebugLoc()) {
  126. assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
  127. CapOperands = OperandCapacity::get(MI.getNumOperands());
  128. Operands = MF.allocateOperandArray(CapOperands);
  129. // Copy operands.
  130. for (const MachineOperand &MO : MI.operands())
  131. addOperand(MF, MO);
  132. // Copy all the sensible flags.
  133. setFlags(MI.Flags);
  134. }
  135. /// getRegInfo - If this instruction is embedded into a MachineFunction,
  136. /// return the MachineRegisterInfo object for the current function, otherwise
  137. /// return null.
  138. MachineRegisterInfo *MachineInstr::getRegInfo() {
  139. if (MachineBasicBlock *MBB = getParent())
  140. return &MBB->getParent()->getRegInfo();
  141. return nullptr;
  142. }
  143. /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
  144. /// this instruction from their respective use lists. This requires that the
  145. /// operands already be on their use lists.
  146. void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
  147. for (MachineOperand &MO : operands())
  148. if (MO.isReg())
  149. MRI.removeRegOperandFromUseList(&MO);
  150. }
  151. /// AddRegOperandsToUseLists - Add all of the register operands in
  152. /// this instruction from their respective use lists. This requires that the
  153. /// operands not be on their use lists yet.
  154. void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
  155. for (MachineOperand &MO : operands())
  156. if (MO.isReg())
  157. MRI.addRegOperandToUseList(&MO);
  158. }
  159. void MachineInstr::addOperand(const MachineOperand &Op) {
  160. MachineBasicBlock *MBB = getParent();
  161. assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
  162. MachineFunction *MF = MBB->getParent();
  163. assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
  164. addOperand(*MF, Op);
  165. }
  166. /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
  167. /// ranges. If MRI is non-null also update use-def chains.
  168. static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
  169. unsigned NumOps, MachineRegisterInfo *MRI) {
  170. if (MRI)
  171. return MRI->moveOperands(Dst, Src, NumOps);
  172. // MachineOperand is a trivially copyable type so we can just use memmove.
  173. std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
  174. }
  175. /// addOperand - Add the specified operand to the instruction. If it is an
  176. /// implicit operand, it is added to the end of the operand list. If it is
  177. /// an explicit operand it is added at the end of the explicit operand list
  178. /// (before the first implicit operand).
  179. void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
  180. assert(MCID && "Cannot add operands before providing an instr descriptor");
  181. // Check if we're adding one of our existing operands.
  182. if (&Op >= Operands && &Op < Operands + NumOperands) {
  183. // This is unusual: MI->addOperand(MI->getOperand(i)).
  184. // If adding Op requires reallocating or moving existing operands around,
  185. // the Op reference could go stale. Support it by copying Op.
  186. MachineOperand CopyOp(Op);
  187. return addOperand(MF, CopyOp);
  188. }
  189. // Find the insert location for the new operand. Implicit registers go at
  190. // the end, everything else goes before the implicit regs.
  191. //
  192. // FIXME: Allow mixed explicit and implicit operands on inline asm.
  193. // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
  194. // implicit-defs, but they must not be moved around. See the FIXME in
  195. // InstrEmitter.cpp.
  196. unsigned OpNo = getNumOperands();
  197. bool isImpReg = Op.isReg() && Op.isImplicit();
  198. if (!isImpReg && !isInlineAsm()) {
  199. while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
  200. --OpNo;
  201. assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
  202. }
  203. }
  204. #ifndef NDEBUG
  205. bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
  206. // OpNo now points as the desired insertion point. Unless this is a variadic
  207. // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
  208. // RegMask operands go between the explicit and implicit operands.
  209. assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
  210. OpNo < MCID->getNumOperands() || isMetaDataOp) &&
  211. "Trying to add an operand to a machine instr that is already done!");
  212. #endif
  213. MachineRegisterInfo *MRI = getRegInfo();
  214. // Determine if the Operands array needs to be reallocated.
  215. // Save the old capacity and operand array.
  216. OperandCapacity OldCap = CapOperands;
  217. MachineOperand *OldOperands = Operands;
  218. if (!OldOperands || OldCap.getSize() == getNumOperands()) {
  219. CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
  220. Operands = MF.allocateOperandArray(CapOperands);
  221. // Move the operands before the insertion point.
  222. if (OpNo)
  223. moveOperands(Operands, OldOperands, OpNo, MRI);
  224. }
  225. // Move the operands following the insertion point.
  226. if (OpNo != NumOperands)
  227. moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
  228. MRI);
  229. ++NumOperands;
  230. // Deallocate the old operand array.
  231. if (OldOperands != Operands && OldOperands)
  232. MF.deallocateOperandArray(OldCap, OldOperands);
  233. // Copy Op into place. It still needs to be inserted into the MRI use lists.
  234. MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
  235. NewMO->ParentMI = this;
  236. // When adding a register operand, tell MRI about it.
  237. if (NewMO->isReg()) {
  238. // Ensure isOnRegUseList() returns false, regardless of Op's status.
  239. NewMO->Contents.Reg.Prev = nullptr;
  240. // Ignore existing ties. This is not a property that can be copied.
  241. NewMO->TiedTo = 0;
  242. // Add the new operand to MRI, but only for instructions in an MBB.
  243. if (MRI)
  244. MRI->addRegOperandToUseList(NewMO);
  245. // The MCID operand information isn't accurate until we start adding
  246. // explicit operands. The implicit operands are added first, then the
  247. // explicits are inserted before them.
  248. if (!isImpReg) {
  249. // Tie uses to defs as indicated in MCInstrDesc.
  250. if (NewMO->isUse()) {
  251. int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
  252. if (DefIdx != -1)
  253. tieOperands(DefIdx, OpNo);
  254. }
  255. // If the register operand is flagged as early, mark the operand as such.
  256. if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
  257. NewMO->setIsEarlyClobber(true);
  258. }
  259. }
  260. }
  261. /// RemoveOperand - Erase an operand from an instruction, leaving it with one
  262. /// fewer operand than it started with.
  263. ///
  264. void MachineInstr::RemoveOperand(unsigned OpNo) {
  265. assert(OpNo < getNumOperands() && "Invalid operand number");
  266. untieRegOperand(OpNo);
  267. #ifndef NDEBUG
  268. // Moving tied operands would break the ties.
  269. for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
  270. if (Operands[i].isReg())
  271. assert(!Operands[i].isTied() && "Cannot move tied operands");
  272. #endif
  273. MachineRegisterInfo *MRI = getRegInfo();
  274. if (MRI && Operands[OpNo].isReg())
  275. MRI->removeRegOperandFromUseList(Operands + OpNo);
  276. // Don't call the MachineOperand destructor. A lot of this code depends on
  277. // MachineOperand having a trivial destructor anyway, and adding a call here
  278. // wouldn't make it 'destructor-correct'.
  279. if (unsigned N = NumOperands - 1 - OpNo)
  280. moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
  281. --NumOperands;
  282. }
  283. /// addMemOperand - Add a MachineMemOperand to the machine instruction.
  284. /// This function should be used only occasionally. The setMemRefs function
  285. /// is the primary method for setting up a MachineInstr's MemRefs list.
  286. void MachineInstr::addMemOperand(MachineFunction &MF,
  287. MachineMemOperand *MO) {
  288. mmo_iterator OldMemRefs = MemRefs;
  289. unsigned OldNumMemRefs = NumMemRefs;
  290. unsigned NewNum = NumMemRefs + 1;
  291. mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
  292. std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
  293. NewMemRefs[NewNum - 1] = MO;
  294. setMemRefs(NewMemRefs, NewMemRefs + NewNum);
  295. }
  296. /// Check to see if the MMOs pointed to by the two MemRefs arrays are
  297. /// identical.
  298. static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
  299. auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
  300. auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
  301. if ((E1 - I1) != (E2 - I2))
  302. return false;
  303. for (; I1 != E1; ++I1, ++I2) {
  304. if (**I1 != **I2)
  305. return false;
  306. }
  307. return true;
  308. }
  309. std::pair<MachineInstr::mmo_iterator, unsigned>
  310. MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
  311. // If either of the incoming memrefs are empty, we must be conservative and
  312. // treat this as if we've exhausted our space for memrefs and dropped them.
  313. if (memoperands_empty() || Other.memoperands_empty())
  314. return std::make_pair(nullptr, 0);
  315. // If both instructions have identical memrefs, we don't need to merge them.
  316. // Since many instructions have a single memref, and we tend to merge things
  317. // like pairs of loads from the same location, this catches a large number of
  318. // cases in practice.
  319. if (hasIdenticalMMOs(*this, Other))
  320. return std::make_pair(MemRefs, NumMemRefs);
  321. // TODO: consider uniquing elements within the operand lists to reduce
  322. // space usage and fall back to conservative information less often.
  323. size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
  324. // If we don't have enough room to store this many memrefs, be conservative
  325. // and drop them. Otherwise, we'd fail asserts when trying to add them to
  326. // the new instruction.
  327. if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
  328. return std::make_pair(nullptr, 0);
  329. MachineFunction *MF = getMF();
  330. mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
  331. mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
  332. MemBegin);
  333. MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
  334. MemEnd);
  335. assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
  336. "missing memrefs");
  337. return std::make_pair(MemBegin, CombinedNumMemRefs);
  338. }
  339. uint8_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
  340. // For now, the just return the union of the flags. If the flags get more
  341. // complicated over time, we might need more logic here.
  342. return getFlags() | Other.getFlags();
  343. }
  344. bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
  345. assert(!isBundledWithPred() && "Must be called on bundle header");
  346. for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
  347. if (MII->getDesc().getFlags() & Mask) {
  348. if (Type == AnyInBundle)
  349. return true;
  350. } else {
  351. if (Type == AllInBundle && !MII->isBundle())
  352. return false;
  353. }
  354. // This was the last instruction in the bundle.
  355. if (!MII->isBundledWithSucc())
  356. return Type == AllInBundle;
  357. }
  358. }
  359. bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
  360. MICheckType Check) const {
  361. // If opcodes or number of operands are not the same then the two
  362. // instructions are obviously not identical.
  363. if (Other.getOpcode() != getOpcode() ||
  364. Other.getNumOperands() != getNumOperands())
  365. return false;
  366. if (isBundle()) {
  367. // We have passed the test above that both instructions have the same
  368. // opcode, so we know that both instructions are bundles here. Let's compare
  369. // MIs inside the bundle.
  370. assert(Other.isBundle() && "Expected that both instructions are bundles.");
  371. MachineBasicBlock::const_instr_iterator I1 = getIterator();
  372. MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
  373. // Loop until we analysed the last intruction inside at least one of the
  374. // bundles.
  375. while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
  376. ++I1;
  377. ++I2;
  378. if (!I1->isIdenticalTo(*I2, Check))
  379. return false;
  380. }
  381. // If we've reached the end of just one of the two bundles, but not both,
  382. // the instructions are not identical.
  383. if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
  384. return false;
  385. }
  386. // Check operands to make sure they match.
  387. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  388. const MachineOperand &MO = getOperand(i);
  389. const MachineOperand &OMO = Other.getOperand(i);
  390. if (!MO.isReg()) {
  391. if (!MO.isIdenticalTo(OMO))
  392. return false;
  393. continue;
  394. }
  395. // Clients may or may not want to ignore defs when testing for equality.
  396. // For example, machine CSE pass only cares about finding common
  397. // subexpressions, so it's safe to ignore virtual register defs.
  398. if (MO.isDef()) {
  399. if (Check == IgnoreDefs)
  400. continue;
  401. else if (Check == IgnoreVRegDefs) {
  402. if (!TargetRegisterInfo::isVirtualRegister(MO.getReg()) ||
  403. !TargetRegisterInfo::isVirtualRegister(OMO.getReg()))
  404. if (!MO.isIdenticalTo(OMO))
  405. return false;
  406. } else {
  407. if (!MO.isIdenticalTo(OMO))
  408. return false;
  409. if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
  410. return false;
  411. }
  412. } else {
  413. if (!MO.isIdenticalTo(OMO))
  414. return false;
  415. if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
  416. return false;
  417. }
  418. }
  419. // If DebugLoc does not match then two dbg.values are not identical.
  420. if (isDebugValue())
  421. if (getDebugLoc() && Other.getDebugLoc() &&
  422. getDebugLoc() != Other.getDebugLoc())
  423. return false;
  424. return true;
  425. }
  426. const MachineFunction *MachineInstr::getMF() const {
  427. return getParent()->getParent();
  428. }
  429. MachineInstr *MachineInstr::removeFromParent() {
  430. assert(getParent() && "Not embedded in a basic block!");
  431. return getParent()->remove(this);
  432. }
  433. MachineInstr *MachineInstr::removeFromBundle() {
  434. assert(getParent() && "Not embedded in a basic block!");
  435. return getParent()->remove_instr(this);
  436. }
  437. void MachineInstr::eraseFromParent() {
  438. assert(getParent() && "Not embedded in a basic block!");
  439. getParent()->erase(this);
  440. }
  441. void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
  442. assert(getParent() && "Not embedded in a basic block!");
  443. MachineBasicBlock *MBB = getParent();
  444. MachineFunction *MF = MBB->getParent();
  445. assert(MF && "Not embedded in a function!");
  446. MachineInstr *MI = (MachineInstr *)this;
  447. MachineRegisterInfo &MRI = MF->getRegInfo();
  448. for (const MachineOperand &MO : MI->operands()) {
  449. if (!MO.isReg() || !MO.isDef())
  450. continue;
  451. unsigned Reg = MO.getReg();
  452. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  453. continue;
  454. MRI.markUsesInDebugValueAsUndef(Reg);
  455. }
  456. MI->eraseFromParent();
  457. }
  458. void MachineInstr::eraseFromBundle() {
  459. assert(getParent() && "Not embedded in a basic block!");
  460. getParent()->erase_instr(this);
  461. }
  462. /// getNumExplicitOperands - Returns the number of non-implicit operands.
  463. ///
  464. unsigned MachineInstr::getNumExplicitOperands() const {
  465. unsigned NumOperands = MCID->getNumOperands();
  466. if (!MCID->isVariadic())
  467. return NumOperands;
  468. for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
  469. const MachineOperand &MO = getOperand(i);
  470. if (!MO.isReg() || !MO.isImplicit())
  471. NumOperands++;
  472. }
  473. return NumOperands;
  474. }
  475. void MachineInstr::bundleWithPred() {
  476. assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
  477. setFlag(BundledPred);
  478. MachineBasicBlock::instr_iterator Pred = getIterator();
  479. --Pred;
  480. assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  481. Pred->setFlag(BundledSucc);
  482. }
  483. void MachineInstr::bundleWithSucc() {
  484. assert(!isBundledWithSucc() && "MI is already bundled with its successor");
  485. setFlag(BundledSucc);
  486. MachineBasicBlock::instr_iterator Succ = getIterator();
  487. ++Succ;
  488. assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
  489. Succ->setFlag(BundledPred);
  490. }
  491. void MachineInstr::unbundleFromPred() {
  492. assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
  493. clearFlag(BundledPred);
  494. MachineBasicBlock::instr_iterator Pred = getIterator();
  495. --Pred;
  496. assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  497. Pred->clearFlag(BundledSucc);
  498. }
  499. void MachineInstr::unbundleFromSucc() {
  500. assert(isBundledWithSucc() && "MI isn't bundled with its successor");
  501. clearFlag(BundledSucc);
  502. MachineBasicBlock::instr_iterator Succ = getIterator();
  503. ++Succ;
  504. assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
  505. Succ->clearFlag(BundledPred);
  506. }
  507. bool MachineInstr::isStackAligningInlineAsm() const {
  508. if (isInlineAsm()) {
  509. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  510. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  511. return true;
  512. }
  513. return false;
  514. }
  515. InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
  516. assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
  517. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  518. return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
  519. }
  520. int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
  521. unsigned *GroupNo) const {
  522. assert(isInlineAsm() && "Expected an inline asm instruction");
  523. assert(OpIdx < getNumOperands() && "OpIdx out of range");
  524. // Ignore queries about the initial operands.
  525. if (OpIdx < InlineAsm::MIOp_FirstOperand)
  526. return -1;
  527. unsigned Group = 0;
  528. unsigned NumOps;
  529. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  530. i += NumOps) {
  531. const MachineOperand &FlagMO = getOperand(i);
  532. // If we reach the implicit register operands, stop looking.
  533. if (!FlagMO.isImm())
  534. return -1;
  535. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  536. if (i + NumOps > OpIdx) {
  537. if (GroupNo)
  538. *GroupNo = Group;
  539. return i;
  540. }
  541. ++Group;
  542. }
  543. return -1;
  544. }
  545. const DILocalVariable *MachineInstr::getDebugVariable() const {
  546. assert(isDebugValue() && "not a DBG_VALUE");
  547. return cast<DILocalVariable>(getOperand(2).getMetadata());
  548. }
  549. const DIExpression *MachineInstr::getDebugExpression() const {
  550. assert(isDebugValue() && "not a DBG_VALUE");
  551. return cast<DIExpression>(getOperand(3).getMetadata());
  552. }
  553. const TargetRegisterClass*
  554. MachineInstr::getRegClassConstraint(unsigned OpIdx,
  555. const TargetInstrInfo *TII,
  556. const TargetRegisterInfo *TRI) const {
  557. assert(getParent() && "Can't have an MBB reference here!");
  558. assert(getMF() && "Can't have an MF reference here!");
  559. const MachineFunction &MF = *getMF();
  560. // Most opcodes have fixed constraints in their MCInstrDesc.
  561. if (!isInlineAsm())
  562. return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
  563. if (!getOperand(OpIdx).isReg())
  564. return nullptr;
  565. // For tied uses on inline asm, get the constraint from the def.
  566. unsigned DefIdx;
  567. if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
  568. OpIdx = DefIdx;
  569. // Inline asm stores register class constraints in the flag word.
  570. int FlagIdx = findInlineAsmFlagIdx(OpIdx);
  571. if (FlagIdx < 0)
  572. return nullptr;
  573. unsigned Flag = getOperand(FlagIdx).getImm();
  574. unsigned RCID;
  575. if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
  576. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
  577. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
  578. InlineAsm::hasRegClassConstraint(Flag, RCID))
  579. return TRI->getRegClass(RCID);
  580. // Assume that all registers in a memory operand are pointers.
  581. if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
  582. return TRI->getPointerRegClass(MF);
  583. return nullptr;
  584. }
  585. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
  586. unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
  587. const TargetRegisterInfo *TRI, bool ExploreBundle) const {
  588. // Check every operands inside the bundle if we have
  589. // been asked to.
  590. if (ExploreBundle)
  591. for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
  592. ++OpndIt)
  593. CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
  594. OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
  595. else
  596. // Otherwise, just check the current operands.
  597. for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
  598. CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
  599. return CurRC;
  600. }
  601. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
  602. unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
  603. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  604. assert(CurRC && "Invalid initial register class");
  605. // Check if Reg is constrained by some of its use/def from MI.
  606. const MachineOperand &MO = getOperand(OpIdx);
  607. if (!MO.isReg() || MO.getReg() != Reg)
  608. return CurRC;
  609. // If yes, accumulate the constraints through the operand.
  610. return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
  611. }
  612. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
  613. unsigned OpIdx, const TargetRegisterClass *CurRC,
  614. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  615. const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
  616. const MachineOperand &MO = getOperand(OpIdx);
  617. assert(MO.isReg() &&
  618. "Cannot get register constraints for non-register operand");
  619. assert(CurRC && "Invalid initial register class");
  620. if (unsigned SubIdx = MO.getSubReg()) {
  621. if (OpRC)
  622. CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
  623. else
  624. CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
  625. } else if (OpRC)
  626. CurRC = TRI->getCommonSubClass(CurRC, OpRC);
  627. return CurRC;
  628. }
  629. /// Return the number of instructions inside the MI bundle, not counting the
  630. /// header instruction.
  631. unsigned MachineInstr::getBundleSize() const {
  632. MachineBasicBlock::const_instr_iterator I = getIterator();
  633. unsigned Size = 0;
  634. while (I->isBundledWithSucc()) {
  635. ++Size;
  636. ++I;
  637. }
  638. return Size;
  639. }
  640. /// Returns true if the MachineInstr has an implicit-use operand of exactly
  641. /// the given register (not considering sub/super-registers).
  642. bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
  643. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  644. const MachineOperand &MO = getOperand(i);
  645. if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
  646. return true;
  647. }
  648. return false;
  649. }
  650. /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
  651. /// the specific register or -1 if it is not found. It further tightens
  652. /// the search criteria to a use that kills the register if isKill is true.
  653. int MachineInstr::findRegisterUseOperandIdx(
  654. unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
  655. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  656. const MachineOperand &MO = getOperand(i);
  657. if (!MO.isReg() || !MO.isUse())
  658. continue;
  659. unsigned MOReg = MO.getReg();
  660. if (!MOReg)
  661. continue;
  662. if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
  663. TargetRegisterInfo::isPhysicalRegister(Reg) &&
  664. TRI->isSubRegister(MOReg, Reg)))
  665. if (!isKill || MO.isKill())
  666. return i;
  667. }
  668. return -1;
  669. }
  670. /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
  671. /// indicating if this instruction reads or writes Reg. This also considers
  672. /// partial defines.
  673. std::pair<bool,bool>
  674. MachineInstr::readsWritesVirtualRegister(unsigned Reg,
  675. SmallVectorImpl<unsigned> *Ops) const {
  676. bool PartDef = false; // Partial redefine.
  677. bool FullDef = false; // Full define.
  678. bool Use = false;
  679. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  680. const MachineOperand &MO = getOperand(i);
  681. if (!MO.isReg() || MO.getReg() != Reg)
  682. continue;
  683. if (Ops)
  684. Ops->push_back(i);
  685. if (MO.isUse())
  686. Use |= !MO.isUndef();
  687. else if (MO.getSubReg() && !MO.isUndef())
  688. // A partial def undef doesn't count as reading the register.
  689. PartDef = true;
  690. else
  691. FullDef = true;
  692. }
  693. // A partial redefine uses Reg unless there is also a full define.
  694. return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
  695. }
  696. /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
  697. /// the specified register or -1 if it is not found. If isDead is true, defs
  698. /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
  699. /// also checks if there is a def of a super-register.
  700. int
  701. MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
  702. const TargetRegisterInfo *TRI) const {
  703. bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
  704. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  705. const MachineOperand &MO = getOperand(i);
  706. // Accept regmask operands when Overlap is set.
  707. // Ignore them when looking for a specific def operand (Overlap == false).
  708. if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
  709. return i;
  710. if (!MO.isReg() || !MO.isDef())
  711. continue;
  712. unsigned MOReg = MO.getReg();
  713. bool Found = (MOReg == Reg);
  714. if (!Found && TRI && isPhys &&
  715. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  716. if (Overlap)
  717. Found = TRI->regsOverlap(MOReg, Reg);
  718. else
  719. Found = TRI->isSubRegister(MOReg, Reg);
  720. }
  721. if (Found && (!isDead || MO.isDead()))
  722. return i;
  723. }
  724. return -1;
  725. }
  726. /// findFirstPredOperandIdx() - Find the index of the first operand in the
  727. /// operand list that is used to represent the predicate. It returns -1 if
  728. /// none is found.
  729. int MachineInstr::findFirstPredOperandIdx() const {
  730. // Don't call MCID.findFirstPredOperandIdx() because this variant
  731. // is sometimes called on an instruction that's not yet complete, and
  732. // so the number of operands is less than the MCID indicates. In
  733. // particular, the PTX target does this.
  734. const MCInstrDesc &MCID = getDesc();
  735. if (MCID.isPredicable()) {
  736. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  737. if (MCID.OpInfo[i].isPredicate())
  738. return i;
  739. }
  740. return -1;
  741. }
  742. // MachineOperand::TiedTo is 4 bits wide.
  743. const unsigned TiedMax = 15;
  744. /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
  745. ///
  746. /// Use and def operands can be tied together, indicated by a non-zero TiedTo
  747. /// field. TiedTo can have these values:
  748. ///
  749. /// 0: Operand is not tied to anything.
  750. /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
  751. /// TiedMax: Tied to an operand >= TiedMax-1.
  752. ///
  753. /// The tied def must be one of the first TiedMax operands on a normal
  754. /// instruction. INLINEASM instructions allow more tied defs.
  755. ///
  756. void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
  757. MachineOperand &DefMO = getOperand(DefIdx);
  758. MachineOperand &UseMO = getOperand(UseIdx);
  759. assert(DefMO.isDef() && "DefIdx must be a def operand");
  760. assert(UseMO.isUse() && "UseIdx must be a use operand");
  761. assert(!DefMO.isTied() && "Def is already tied to another use");
  762. assert(!UseMO.isTied() && "Use is already tied to another def");
  763. if (DefIdx < TiedMax)
  764. UseMO.TiedTo = DefIdx + 1;
  765. else {
  766. // Inline asm can use the group descriptors to find tied operands, but on
  767. // normal instruction, the tied def must be within the first TiedMax
  768. // operands.
  769. assert(isInlineAsm() && "DefIdx out of range");
  770. UseMO.TiedTo = TiedMax;
  771. }
  772. // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
  773. DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
  774. }
  775. /// Given the index of a tied register operand, find the operand it is tied to.
  776. /// Defs are tied to uses and vice versa. Returns the index of the tied operand
  777. /// which must exist.
  778. unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
  779. const MachineOperand &MO = getOperand(OpIdx);
  780. assert(MO.isTied() && "Operand isn't tied");
  781. // Normally TiedTo is in range.
  782. if (MO.TiedTo < TiedMax)
  783. return MO.TiedTo - 1;
  784. // Uses on normal instructions can be out of range.
  785. if (!isInlineAsm()) {
  786. // Normal tied defs must be in the 0..TiedMax-1 range.
  787. if (MO.isUse())
  788. return TiedMax - 1;
  789. // MO is a def. Search for the tied use.
  790. for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
  791. const MachineOperand &UseMO = getOperand(i);
  792. if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
  793. return i;
  794. }
  795. llvm_unreachable("Can't find tied use");
  796. }
  797. // Now deal with inline asm by parsing the operand group descriptor flags.
  798. // Find the beginning of each operand group.
  799. SmallVector<unsigned, 8> GroupIdx;
  800. unsigned OpIdxGroup = ~0u;
  801. unsigned NumOps;
  802. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  803. i += NumOps) {
  804. const MachineOperand &FlagMO = getOperand(i);
  805. assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
  806. unsigned CurGroup = GroupIdx.size();
  807. GroupIdx.push_back(i);
  808. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  809. // OpIdx belongs to this operand group.
  810. if (OpIdx > i && OpIdx < i + NumOps)
  811. OpIdxGroup = CurGroup;
  812. unsigned TiedGroup;
  813. if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
  814. continue;
  815. // Operands in this group are tied to operands in TiedGroup which must be
  816. // earlier. Find the number of operands between the two groups.
  817. unsigned Delta = i - GroupIdx[TiedGroup];
  818. // OpIdx is a use tied to TiedGroup.
  819. if (OpIdxGroup == CurGroup)
  820. return OpIdx - Delta;
  821. // OpIdx is a def tied to this use group.
  822. if (OpIdxGroup == TiedGroup)
  823. return OpIdx + Delta;
  824. }
  825. llvm_unreachable("Invalid tied operand on inline asm");
  826. }
  827. /// clearKillInfo - Clears kill flags on all operands.
  828. ///
  829. void MachineInstr::clearKillInfo() {
  830. for (MachineOperand &MO : operands()) {
  831. if (MO.isReg() && MO.isUse())
  832. MO.setIsKill(false);
  833. }
  834. }
  835. void MachineInstr::substituteRegister(unsigned FromReg, unsigned ToReg,
  836. unsigned SubIdx,
  837. const TargetRegisterInfo &RegInfo) {
  838. if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
  839. if (SubIdx)
  840. ToReg = RegInfo.getSubReg(ToReg, SubIdx);
  841. for (MachineOperand &MO : operands()) {
  842. if (!MO.isReg() || MO.getReg() != FromReg)
  843. continue;
  844. MO.substPhysReg(ToReg, RegInfo);
  845. }
  846. } else {
  847. for (MachineOperand &MO : operands()) {
  848. if (!MO.isReg() || MO.getReg() != FromReg)
  849. continue;
  850. MO.substVirtReg(ToReg, SubIdx, RegInfo);
  851. }
  852. }
  853. }
  854. /// isSafeToMove - Return true if it is safe to move this instruction. If
  855. /// SawStore is set to true, it means that there is a store (or call) between
  856. /// the instruction's location and its intended destination.
  857. bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
  858. // Ignore stuff that we obviously can't move.
  859. //
  860. // Treat volatile loads as stores. This is not strictly necessary for
  861. // volatiles, but it is required for atomic loads. It is not allowed to move
  862. // a load across an atomic load with Ordering > Monotonic.
  863. if (mayStore() || isCall() || isPHI() ||
  864. (mayLoad() && hasOrderedMemoryRef())) {
  865. SawStore = true;
  866. return false;
  867. }
  868. if (isPosition() || isDebugValue() || isTerminator() ||
  869. hasUnmodeledSideEffects())
  870. return false;
  871. // See if this instruction does a load. If so, we have to guarantee that the
  872. // loaded value doesn't change between the load and the its intended
  873. // destination. The check for isInvariantLoad gives the targe the chance to
  874. // classify the load as always returning a constant, e.g. a constant pool
  875. // load.
  876. if (mayLoad() && !isDereferenceableInvariantLoad(AA))
  877. // Otherwise, this is a real load. If there is a store between the load and
  878. // end of block, we can't move it.
  879. return !SawStore;
  880. return true;
  881. }
  882. bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
  883. bool UseTBAA) {
  884. const MachineFunction *MF = getMF();
  885. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  886. const MachineFrameInfo &MFI = MF->getFrameInfo();
  887. // If neither instruction stores to memory, they can't alias in any
  888. // meaningful way, even if they read from the same address.
  889. if (!mayStore() && !Other.mayStore())
  890. return false;
  891. // Let the target decide if memory accesses cannot possibly overlap.
  892. if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
  893. return false;
  894. // FIXME: Need to handle multiple memory operands to support all targets.
  895. if (!hasOneMemOperand() || !Other.hasOneMemOperand())
  896. return true;
  897. MachineMemOperand *MMOa = *memoperands_begin();
  898. MachineMemOperand *MMOb = *Other.memoperands_begin();
  899. // The following interface to AA is fashioned after DAGCombiner::isAlias
  900. // and operates with MachineMemOperand offset with some important
  901. // assumptions:
  902. // - LLVM fundamentally assumes flat address spaces.
  903. // - MachineOperand offset can *only* result from legalization and
  904. // cannot affect queries other than the trivial case of overlap
  905. // checking.
  906. // - These offsets never wrap and never step outside
  907. // of allocated objects.
  908. // - There should never be any negative offsets here.
  909. //
  910. // FIXME: Modify API to hide this math from "user"
  911. // Even before we go to AA we can reason locally about some
  912. // memory objects. It can save compile time, and possibly catch some
  913. // corner cases not currently covered.
  914. int64_t OffsetA = MMOa->getOffset();
  915. int64_t OffsetB = MMOb->getOffset();
  916. int64_t MinOffset = std::min(OffsetA, OffsetB);
  917. int64_t WidthA = MMOa->getSize();
  918. int64_t WidthB = MMOb->getSize();
  919. const Value *ValA = MMOa->getValue();
  920. const Value *ValB = MMOb->getValue();
  921. bool SameVal = (ValA && ValB && (ValA == ValB));
  922. if (!SameVal) {
  923. const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
  924. const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
  925. if (PSVa && ValB && !PSVa->mayAlias(&MFI))
  926. return false;
  927. if (PSVb && ValA && !PSVb->mayAlias(&MFI))
  928. return false;
  929. if (PSVa && PSVb && (PSVa == PSVb))
  930. SameVal = true;
  931. }
  932. if (SameVal) {
  933. int64_t MaxOffset = std::max(OffsetA, OffsetB);
  934. int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
  935. return (MinOffset + LowWidth > MaxOffset);
  936. }
  937. if (!AA)
  938. return true;
  939. if (!ValA || !ValB)
  940. return true;
  941. assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
  942. assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
  943. int64_t Overlapa = WidthA + OffsetA - MinOffset;
  944. int64_t Overlapb = WidthB + OffsetB - MinOffset;
  945. AliasResult AAResult = AA->alias(
  946. MemoryLocation(ValA, Overlapa,
  947. UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
  948. MemoryLocation(ValB, Overlapb,
  949. UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
  950. return (AAResult != NoAlias);
  951. }
  952. /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
  953. /// or volatile memory reference, or if the information describing the memory
  954. /// reference is not available. Return false if it is known to have no ordered
  955. /// memory references.
  956. bool MachineInstr::hasOrderedMemoryRef() const {
  957. // An instruction known never to access memory won't have a volatile access.
  958. if (!mayStore() &&
  959. !mayLoad() &&
  960. !isCall() &&
  961. !hasUnmodeledSideEffects())
  962. return false;
  963. // Otherwise, if the instruction has no memory reference information,
  964. // conservatively assume it wasn't preserved.
  965. if (memoperands_empty())
  966. return true;
  967. // Check if any of our memory operands are ordered.
  968. return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
  969. return !MMO->isUnordered();
  970. });
  971. }
  972. /// isDereferenceableInvariantLoad - Return true if this instruction will never
  973. /// trap and is loading from a location whose value is invariant across a run of
  974. /// this function.
  975. bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
  976. // If the instruction doesn't load at all, it isn't an invariant load.
  977. if (!mayLoad())
  978. return false;
  979. // If the instruction has lost its memoperands, conservatively assume that
  980. // it may not be an invariant load.
  981. if (memoperands_empty())
  982. return false;
  983. const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
  984. for (MachineMemOperand *MMO : memoperands()) {
  985. if (MMO->isVolatile()) return false;
  986. if (MMO->isStore()) return false;
  987. if (MMO->isInvariant() && MMO->isDereferenceable())
  988. continue;
  989. // A load from a constant PseudoSourceValue is invariant.
  990. if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
  991. if (PSV->isConstant(&MFI))
  992. continue;
  993. if (const Value *V = MMO->getValue()) {
  994. // If we have an AliasAnalysis, ask it whether the memory is constant.
  995. if (AA &&
  996. AA->pointsToConstantMemory(
  997. MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
  998. continue;
  999. }
  1000. // Otherwise assume conservatively.
  1001. return false;
  1002. }
  1003. // Everything checks out.
  1004. return true;
  1005. }
  1006. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1007. /// merges together the same virtual register, return the register, otherwise
  1008. /// return 0.
  1009. unsigned MachineInstr::isConstantValuePHI() const {
  1010. if (!isPHI())
  1011. return 0;
  1012. assert(getNumOperands() >= 3 &&
  1013. "It's illegal to have a PHI without source operands");
  1014. unsigned Reg = getOperand(1).getReg();
  1015. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1016. if (getOperand(i).getReg() != Reg)
  1017. return 0;
  1018. return Reg;
  1019. }
  1020. bool MachineInstr::hasUnmodeledSideEffects() const {
  1021. if (hasProperty(MCID::UnmodeledSideEffects))
  1022. return true;
  1023. if (isInlineAsm()) {
  1024. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1025. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1026. return true;
  1027. }
  1028. return false;
  1029. }
  1030. bool MachineInstr::isLoadFoldBarrier() const {
  1031. return mayStore() || isCall() || hasUnmodeledSideEffects();
  1032. }
  1033. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1034. ///
  1035. bool MachineInstr::allDefsAreDead() const {
  1036. for (const MachineOperand &MO : operands()) {
  1037. if (!MO.isReg() || MO.isUse())
  1038. continue;
  1039. if (!MO.isDead())
  1040. return false;
  1041. }
  1042. return true;
  1043. }
  1044. /// copyImplicitOps - Copy implicit register operands from specified
  1045. /// instruction to this instruction.
  1046. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1047. const MachineInstr &MI) {
  1048. for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
  1049. i != e; ++i) {
  1050. const MachineOperand &MO = MI.getOperand(i);
  1051. if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
  1052. addOperand(MF, MO);
  1053. }
  1054. }
  1055. bool MachineInstr::hasComplexRegisterTies() const {
  1056. const MCInstrDesc &MCID = getDesc();
  1057. for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
  1058. const auto &Operand = getOperand(I);
  1059. if (!Operand.isReg() || Operand.isDef())
  1060. // Ignore the defined registers as MCID marks only the uses as tied.
  1061. continue;
  1062. int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
  1063. int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
  1064. if (ExpectedTiedIdx != TiedIdx)
  1065. return true;
  1066. }
  1067. return false;
  1068. }
  1069. LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
  1070. const MachineRegisterInfo &MRI) const {
  1071. const MachineOperand &Op = getOperand(OpIdx);
  1072. if (!Op.isReg())
  1073. return LLT{};
  1074. if (isVariadic() || OpIdx >= getNumExplicitOperands())
  1075. return MRI.getType(Op.getReg());
  1076. auto &OpInfo = getDesc().OpInfo[OpIdx];
  1077. if (!OpInfo.isGenericType())
  1078. return MRI.getType(Op.getReg());
  1079. if (PrintedTypes[OpInfo.getGenericTypeIndex()])
  1080. return LLT{};
  1081. PrintedTypes.set(OpInfo.getGenericTypeIndex());
  1082. return MRI.getType(Op.getReg());
  1083. }
  1084. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1085. LLVM_DUMP_METHOD void MachineInstr::dump() const {
  1086. dbgs() << " ";
  1087. print(dbgs());
  1088. }
  1089. #endif
  1090. void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
  1091. bool SkipDebugLoc, bool AddNewLine,
  1092. const TargetInstrInfo *TII) const {
  1093. const Module *M = nullptr;
  1094. const Function *F = nullptr;
  1095. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1096. F = &MF->getFunction();
  1097. M = F->getParent();
  1098. if (!TII)
  1099. TII = MF->getSubtarget().getInstrInfo();
  1100. }
  1101. ModuleSlotTracker MST(M);
  1102. if (F)
  1103. MST.incorporateFunction(*F);
  1104. print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, TII);
  1105. }
  1106. void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
  1107. bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
  1108. bool AddNewLine, const TargetInstrInfo *TII) const {
  1109. // We can be a bit tidier if we know the MachineFunction.
  1110. const MachineFunction *MF = nullptr;
  1111. const TargetRegisterInfo *TRI = nullptr;
  1112. const MachineRegisterInfo *MRI = nullptr;
  1113. const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
  1114. tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
  1115. if (isCFIInstruction())
  1116. assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
  1117. SmallBitVector PrintedTypes(8);
  1118. bool ShouldPrintRegisterTies = hasComplexRegisterTies();
  1119. auto getTiedOperandIdx = [&](unsigned OpIdx) {
  1120. if (!ShouldPrintRegisterTies)
  1121. return 0U;
  1122. const MachineOperand &MO = getOperand(OpIdx);
  1123. if (MO.isReg() && MO.isTied() && !MO.isDef())
  1124. return findTiedOperandIdx(OpIdx);
  1125. return 0U;
  1126. };
  1127. unsigned StartOp = 0;
  1128. unsigned e = getNumOperands();
  1129. // Print explicitly defined operands on the left of an assignment syntax.
  1130. while (StartOp < e) {
  1131. const MachineOperand &MO = getOperand(StartOp);
  1132. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  1133. break;
  1134. if (StartOp != 0)
  1135. OS << ", ";
  1136. LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
  1137. unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
  1138. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/false, IsStandalone,
  1139. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1140. ++StartOp;
  1141. }
  1142. if (StartOp != 0)
  1143. OS << " = ";
  1144. if (getFlag(MachineInstr::FrameSetup))
  1145. OS << "frame-setup ";
  1146. if (getFlag(MachineInstr::FrameDestroy))
  1147. OS << "frame-destroy ";
  1148. // Print the opcode name.
  1149. if (TII)
  1150. OS << TII->getName(getOpcode());
  1151. else
  1152. OS << "UNKNOWN";
  1153. if (SkipOpers)
  1154. return;
  1155. // Print the rest of the operands.
  1156. bool FirstOp = true;
  1157. unsigned AsmDescOp = ~0u;
  1158. unsigned AsmOpCount = 0;
  1159. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1160. // Print asm string.
  1161. OS << " ";
  1162. const unsigned OpIdx = InlineAsm::MIOp_AsmString;
  1163. LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
  1164. unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
  1165. getOperand(OpIdx).print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1166. ShouldPrintRegisterTies, TiedOperandIdx, TRI,
  1167. IntrinsicInfo);
  1168. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1169. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1170. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1171. OS << " [sideeffect]";
  1172. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1173. OS << " [mayload]";
  1174. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1175. OS << " [maystore]";
  1176. if (ExtraInfo & InlineAsm::Extra_IsConvergent)
  1177. OS << " [isconvergent]";
  1178. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1179. OS << " [alignstack]";
  1180. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1181. OS << " [attdialect]";
  1182. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1183. OS << " [inteldialect]";
  1184. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1185. FirstOp = false;
  1186. }
  1187. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1188. const MachineOperand &MO = getOperand(i);
  1189. if (FirstOp) FirstOp = false; else OS << ",";
  1190. OS << " ";
  1191. if (isDebugValue() && MO.isMetadata()) {
  1192. // Pretty print DBG_VALUE instructions.
  1193. auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
  1194. if (DIV && !DIV->getName().empty())
  1195. OS << "!\"" << DIV->getName() << '\"';
  1196. else {
  1197. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1198. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1199. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1200. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1201. }
  1202. } else if (i == AsmDescOp && MO.isImm()) {
  1203. // Pretty print the inline asm operand descriptor.
  1204. OS << '$' << AsmOpCount++;
  1205. unsigned Flag = MO.getImm();
  1206. switch (InlineAsm::getKind(Flag)) {
  1207. case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
  1208. case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
  1209. case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
  1210. case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
  1211. case InlineAsm::Kind_Imm: OS << ":[imm"; break;
  1212. case InlineAsm::Kind_Mem: OS << ":[mem"; break;
  1213. default: OS << ":[??" << InlineAsm::getKind(Flag); break;
  1214. }
  1215. unsigned RCID = 0;
  1216. if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
  1217. InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1218. if (TRI) {
  1219. OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
  1220. } else
  1221. OS << ":RC" << RCID;
  1222. }
  1223. if (InlineAsm::isMemKind(Flag)) {
  1224. unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
  1225. switch (MCID) {
  1226. case InlineAsm::Constraint_es: OS << ":es"; break;
  1227. case InlineAsm::Constraint_i: OS << ":i"; break;
  1228. case InlineAsm::Constraint_m: OS << ":m"; break;
  1229. case InlineAsm::Constraint_o: OS << ":o"; break;
  1230. case InlineAsm::Constraint_v: OS << ":v"; break;
  1231. case InlineAsm::Constraint_Q: OS << ":Q"; break;
  1232. case InlineAsm::Constraint_R: OS << ":R"; break;
  1233. case InlineAsm::Constraint_S: OS << ":S"; break;
  1234. case InlineAsm::Constraint_T: OS << ":T"; break;
  1235. case InlineAsm::Constraint_Um: OS << ":Um"; break;
  1236. case InlineAsm::Constraint_Un: OS << ":Un"; break;
  1237. case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
  1238. case InlineAsm::Constraint_Us: OS << ":Us"; break;
  1239. case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
  1240. case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
  1241. case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
  1242. case InlineAsm::Constraint_X: OS << ":X"; break;
  1243. case InlineAsm::Constraint_Z: OS << ":Z"; break;
  1244. case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
  1245. case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
  1246. default: OS << ":?"; break;
  1247. }
  1248. }
  1249. unsigned TiedTo = 0;
  1250. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1251. OS << " tiedto:$" << TiedTo;
  1252. OS << ']';
  1253. // Compute the index of the next operand descriptor.
  1254. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1255. } else {
  1256. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1257. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1258. if (MO.isImm() && isOperandSubregIdx(i))
  1259. MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
  1260. else
  1261. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1262. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1263. }
  1264. }
  1265. if (!SkipDebugLoc) {
  1266. if (const DebugLoc &DL = getDebugLoc()) {
  1267. if (!FirstOp)
  1268. OS << ',';
  1269. OS << " debug-location ";
  1270. DL->printAsOperand(OS, MST);
  1271. }
  1272. }
  1273. if (!memoperands_empty()) {
  1274. SmallVector<StringRef, 0> SSNs;
  1275. const LLVMContext *Context = nullptr;
  1276. std::unique_ptr<LLVMContext> CtxPtr;
  1277. const MachineFrameInfo *MFI = nullptr;
  1278. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1279. MFI = &MF->getFrameInfo();
  1280. Context = &MF->getFunction().getContext();
  1281. } else {
  1282. CtxPtr = llvm::make_unique<LLVMContext>();
  1283. Context = CtxPtr.get();
  1284. }
  1285. OS << " :: ";
  1286. bool NeedComma = false;
  1287. for (const MachineMemOperand *Op : memoperands()) {
  1288. if (NeedComma)
  1289. OS << ", ";
  1290. Op->print(OS, MST, SSNs, *Context, MFI, TII);
  1291. NeedComma = true;
  1292. }
  1293. }
  1294. if (SkipDebugLoc)
  1295. return;
  1296. bool HaveSemi = false;
  1297. // Print debug location information.
  1298. if (const DebugLoc &DL = getDebugLoc()) {
  1299. if (!HaveSemi) {
  1300. OS << ';';
  1301. HaveSemi = true;
  1302. }
  1303. OS << ' ';
  1304. DL.print(OS);
  1305. }
  1306. // Print extra comments for DEBUG_VALUE.
  1307. if (isDebugValue() && getOperand(e - 2).isMetadata()) {
  1308. if (!HaveSemi) {
  1309. OS << ";";
  1310. HaveSemi = true;
  1311. }
  1312. auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
  1313. OS << " line no:" << DV->getLine();
  1314. if (auto *InlinedAt = debugLoc->getInlinedAt()) {
  1315. DebugLoc InlinedAtDL(InlinedAt);
  1316. if (InlinedAtDL && MF) {
  1317. OS << " inlined @[ ";
  1318. InlinedAtDL.print(OS);
  1319. OS << " ]";
  1320. }
  1321. }
  1322. if (isIndirectDebugValue())
  1323. OS << " indirect";
  1324. }
  1325. if (AddNewLine)
  1326. OS << '\n';
  1327. }
  1328. bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
  1329. const TargetRegisterInfo *RegInfo,
  1330. bool AddIfNotFound) {
  1331. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
  1332. bool hasAliases = isPhysReg &&
  1333. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1334. bool Found = false;
  1335. SmallVector<unsigned,4> DeadOps;
  1336. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1337. MachineOperand &MO = getOperand(i);
  1338. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1339. continue;
  1340. // DEBUG_VALUE nodes do not contribute to code generation and should
  1341. // always be ignored. Failure to do so may result in trying to modify
  1342. // KILL flags on DEBUG_VALUE nodes.
  1343. if (MO.isDebug())
  1344. continue;
  1345. unsigned Reg = MO.getReg();
  1346. if (!Reg)
  1347. continue;
  1348. if (Reg == IncomingReg) {
  1349. if (!Found) {
  1350. if (MO.isKill())
  1351. // The register is already marked kill.
  1352. return true;
  1353. if (isPhysReg && isRegTiedToDefOperand(i))
  1354. // Two-address uses of physregs must not be marked kill.
  1355. return true;
  1356. MO.setIsKill();
  1357. Found = true;
  1358. }
  1359. } else if (hasAliases && MO.isKill() &&
  1360. TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1361. // A super-register kill already exists.
  1362. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1363. return true;
  1364. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1365. DeadOps.push_back(i);
  1366. }
  1367. }
  1368. // Trim unneeded kill operands.
  1369. while (!DeadOps.empty()) {
  1370. unsigned OpIdx = DeadOps.back();
  1371. if (getOperand(OpIdx).isImplicit())
  1372. RemoveOperand(OpIdx);
  1373. else
  1374. getOperand(OpIdx).setIsKill(false);
  1375. DeadOps.pop_back();
  1376. }
  1377. // If not found, this means an alias of one of the operands is killed. Add a
  1378. // new implicit operand if required.
  1379. if (!Found && AddIfNotFound) {
  1380. addOperand(MachineOperand::CreateReg(IncomingReg,
  1381. false /*IsDef*/,
  1382. true /*IsImp*/,
  1383. true /*IsKill*/));
  1384. return true;
  1385. }
  1386. return Found;
  1387. }
  1388. void MachineInstr::clearRegisterKills(unsigned Reg,
  1389. const TargetRegisterInfo *RegInfo) {
  1390. if (!TargetRegisterInfo::isPhysicalRegister(Reg))
  1391. RegInfo = nullptr;
  1392. for (MachineOperand &MO : operands()) {
  1393. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1394. continue;
  1395. unsigned OpReg = MO.getReg();
  1396. if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
  1397. MO.setIsKill(false);
  1398. }
  1399. }
  1400. bool MachineInstr::addRegisterDead(unsigned Reg,
  1401. const TargetRegisterInfo *RegInfo,
  1402. bool AddIfNotFound) {
  1403. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
  1404. bool hasAliases = isPhysReg &&
  1405. MCRegAliasIterator(Reg, RegInfo, false).isValid();
  1406. bool Found = false;
  1407. SmallVector<unsigned,4> DeadOps;
  1408. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1409. MachineOperand &MO = getOperand(i);
  1410. if (!MO.isReg() || !MO.isDef())
  1411. continue;
  1412. unsigned MOReg = MO.getReg();
  1413. if (!MOReg)
  1414. continue;
  1415. if (MOReg == Reg) {
  1416. MO.setIsDead();
  1417. Found = true;
  1418. } else if (hasAliases && MO.isDead() &&
  1419. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  1420. // There exists a super-register that's marked dead.
  1421. if (RegInfo->isSuperRegister(Reg, MOReg))
  1422. return true;
  1423. if (RegInfo->isSubRegister(Reg, MOReg))
  1424. DeadOps.push_back(i);
  1425. }
  1426. }
  1427. // Trim unneeded dead operands.
  1428. while (!DeadOps.empty()) {
  1429. unsigned OpIdx = DeadOps.back();
  1430. if (getOperand(OpIdx).isImplicit())
  1431. RemoveOperand(OpIdx);
  1432. else
  1433. getOperand(OpIdx).setIsDead(false);
  1434. DeadOps.pop_back();
  1435. }
  1436. // If not found, this means an alias of one of the operands is dead. Add a
  1437. // new implicit operand if required.
  1438. if (Found || !AddIfNotFound)
  1439. return Found;
  1440. addOperand(MachineOperand::CreateReg(Reg,
  1441. true /*IsDef*/,
  1442. true /*IsImp*/,
  1443. false /*IsKill*/,
  1444. true /*IsDead*/));
  1445. return true;
  1446. }
  1447. void MachineInstr::clearRegisterDeads(unsigned Reg) {
  1448. for (MachineOperand &MO : operands()) {
  1449. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
  1450. continue;
  1451. MO.setIsDead(false);
  1452. }
  1453. }
  1454. void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
  1455. for (MachineOperand &MO : operands()) {
  1456. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
  1457. continue;
  1458. MO.setIsUndef(IsUndef);
  1459. }
  1460. }
  1461. void MachineInstr::addRegisterDefined(unsigned Reg,
  1462. const TargetRegisterInfo *RegInfo) {
  1463. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1464. MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
  1465. if (MO)
  1466. return;
  1467. } else {
  1468. for (const MachineOperand &MO : operands()) {
  1469. if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
  1470. MO.getSubReg() == 0)
  1471. return;
  1472. }
  1473. }
  1474. addOperand(MachineOperand::CreateReg(Reg,
  1475. true /*IsDef*/,
  1476. true /*IsImp*/));
  1477. }
  1478. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
  1479. const TargetRegisterInfo &TRI) {
  1480. bool HasRegMask = false;
  1481. for (MachineOperand &MO : operands()) {
  1482. if (MO.isRegMask()) {
  1483. HasRegMask = true;
  1484. continue;
  1485. }
  1486. if (!MO.isReg() || !MO.isDef()) continue;
  1487. unsigned Reg = MO.getReg();
  1488. if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  1489. // If there are no uses, including partial uses, the def is dead.
  1490. if (llvm::none_of(UsedRegs,
  1491. [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
  1492. MO.setIsDead();
  1493. }
  1494. // This is a call with a register mask operand.
  1495. // Mask clobbers are always dead, so add defs for the non-dead defines.
  1496. if (HasRegMask)
  1497. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1498. I != E; ++I)
  1499. addRegisterDefined(*I, &TRI);
  1500. }
  1501. unsigned
  1502. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  1503. // Build up a buffer of hash code components.
  1504. SmallVector<size_t, 8> HashComponents;
  1505. HashComponents.reserve(MI->getNumOperands() + 1);
  1506. HashComponents.push_back(MI->getOpcode());
  1507. for (const MachineOperand &MO : MI->operands()) {
  1508. if (MO.isReg() && MO.isDef() &&
  1509. TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1510. continue; // Skip virtual register defs.
  1511. HashComponents.push_back(hash_value(MO));
  1512. }
  1513. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  1514. }
  1515. void MachineInstr::emitError(StringRef Msg) const {
  1516. // Find the source location cookie.
  1517. unsigned LocCookie = 0;
  1518. const MDNode *LocMD = nullptr;
  1519. for (unsigned i = getNumOperands(); i != 0; --i) {
  1520. if (getOperand(i-1).isMetadata() &&
  1521. (LocMD = getOperand(i-1).getMetadata()) &&
  1522. LocMD->getNumOperands() != 0) {
  1523. if (const ConstantInt *CI =
  1524. mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
  1525. LocCookie = CI->getZExtValue();
  1526. break;
  1527. }
  1528. }
  1529. }
  1530. if (const MachineBasicBlock *MBB = getParent())
  1531. if (const MachineFunction *MF = MBB->getParent())
  1532. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  1533. report_fatal_error(Msg);
  1534. }
  1535. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1536. const MCInstrDesc &MCID, bool IsIndirect,
  1537. unsigned Reg, const MDNode *Variable,
  1538. const MDNode *Expr) {
  1539. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1540. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1541. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1542. "Expected inlined-at fields to agree");
  1543. if (IsIndirect)
  1544. return BuildMI(MF, DL, MCID)
  1545. .addReg(Reg, RegState::Debug)
  1546. .addImm(0U)
  1547. .addMetadata(Variable)
  1548. .addMetadata(Expr);
  1549. else
  1550. return BuildMI(MF, DL, MCID)
  1551. .addReg(Reg, RegState::Debug)
  1552. .addReg(0U, RegState::Debug)
  1553. .addMetadata(Variable)
  1554. .addMetadata(Expr);
  1555. }
  1556. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1557. MachineBasicBlock::iterator I,
  1558. const DebugLoc &DL, const MCInstrDesc &MCID,
  1559. bool IsIndirect, unsigned Reg,
  1560. const MDNode *Variable, const MDNode *Expr) {
  1561. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1562. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1563. MachineFunction &MF = *BB.getParent();
  1564. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
  1565. BB.insert(I, MI);
  1566. return MachineInstrBuilder(MF, MI);
  1567. }
  1568. /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
  1569. /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
  1570. static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
  1571. assert(MI.getOperand(0).isReg() && "can't spill non-register");
  1572. assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
  1573. "Expected inlined-at fields to agree");
  1574. const DIExpression *Expr = MI.getDebugExpression();
  1575. if (MI.isIndirectDebugValue()) {
  1576. assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
  1577. Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
  1578. }
  1579. return Expr;
  1580. }
  1581. MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
  1582. MachineBasicBlock::iterator I,
  1583. const MachineInstr &Orig,
  1584. int FrameIndex) {
  1585. const DIExpression *Expr = computeExprForSpill(Orig);
  1586. return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
  1587. .addFrameIndex(FrameIndex)
  1588. .addImm(0U)
  1589. .addMetadata(Orig.getDebugVariable())
  1590. .addMetadata(Expr);
  1591. }
  1592. void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
  1593. const DIExpression *Expr = computeExprForSpill(Orig);
  1594. Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
  1595. Orig.getOperand(1).ChangeToImmediate(0U);
  1596. Orig.getOperand(3).setMetadata(Expr);
  1597. }