MachineInstr.cpp 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156
  1. //===- lib/CodeGen/MachineInstr.cpp ---------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Methods common to all machine instructions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/MachineInstr.h"
  13. #include "llvm/ADT/APFloat.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/FoldingSet.h"
  16. #include "llvm/ADT/Hashing.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallBitVector.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/Analysis/Loads.h"
  24. #include "llvm/Analysis/MemoryLocation.h"
  25. #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
  26. #include "llvm/CodeGen/MachineBasicBlock.h"
  27. #include "llvm/CodeGen/MachineFrameInfo.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/Operator.h"
  53. #include "llvm/IR/Type.h"
  54. #include "llvm/IR/Value.h"
  55. #include "llvm/MC/MCInstrDesc.h"
  56. #include "llvm/MC/MCRegisterInfo.h"
  57. #include "llvm/MC/MCSymbol.h"
  58. #include "llvm/Support/Casting.h"
  59. #include "llvm/Support/CommandLine.h"
  60. #include "llvm/Support/Compiler.h"
  61. #include "llvm/Support/Debug.h"
  62. #include "llvm/Support/ErrorHandling.h"
  63. #include "llvm/Support/LowLevelTypeImpl.h"
  64. #include "llvm/Support/MathExtras.h"
  65. #include "llvm/Support/raw_ostream.h"
  66. #include "llvm/Target/TargetIntrinsicInfo.h"
  67. #include "llvm/Target/TargetMachine.h"
  68. #include <algorithm>
  69. #include <cassert>
  70. #include <cstddef>
  71. #include <cstdint>
  72. #include <cstring>
  73. #include <iterator>
  74. #include <utility>
  75. using namespace llvm;
  76. static const MachineFunction *getMFIfAvailable(const MachineInstr &MI) {
  77. if (const MachineBasicBlock *MBB = MI.getParent())
  78. if (const MachineFunction *MF = MBB->getParent())
  79. return MF;
  80. return nullptr;
  81. }
  82. // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
  83. // it.
  84. static void tryToGetTargetInfo(const MachineInstr &MI,
  85. const TargetRegisterInfo *&TRI,
  86. const MachineRegisterInfo *&MRI,
  87. const TargetIntrinsicInfo *&IntrinsicInfo,
  88. const TargetInstrInfo *&TII) {
  89. if (const MachineFunction *MF = getMFIfAvailable(MI)) {
  90. TRI = MF->getSubtarget().getRegisterInfo();
  91. MRI = &MF->getRegInfo();
  92. IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
  93. TII = MF->getSubtarget().getInstrInfo();
  94. }
  95. }
  96. void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
  97. if (MCID->ImplicitDefs)
  98. for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
  99. ++ImpDefs)
  100. addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
  101. if (MCID->ImplicitUses)
  102. for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
  103. ++ImpUses)
  104. addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
  105. }
  106. /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
  107. /// implicit operands. It reserves space for the number of operands specified by
  108. /// the MCInstrDesc.
  109. MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
  110. DebugLoc dl, bool NoImp)
  111. : MCID(&tid), debugLoc(std::move(dl)) {
  112. assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
  113. // Reserve space for the expected number of operands.
  114. if (unsigned NumOps = MCID->getNumOperands() +
  115. MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
  116. CapOperands = OperandCapacity::get(NumOps);
  117. Operands = MF.allocateOperandArray(CapOperands);
  118. }
  119. if (!NoImp)
  120. addImplicitDefUseOperands(MF);
  121. }
  122. /// MachineInstr ctor - Copies MachineInstr arg exactly
  123. ///
  124. MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
  125. : MCID(&MI.getDesc()), Info(MI.Info), 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 isDebugOp = Op.getType() == MachineOperand::MO_Metadata ||
  206. Op.getType() == MachineOperand::MO_MCSymbol;
  207. // OpNo now points as the desired insertion point. Unless this is a variadic
  208. // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
  209. // RegMask operands go between the explicit and implicit operands.
  210. assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
  211. OpNo < MCID->getNumOperands() || isDebugOp) &&
  212. "Trying to add an operand to a machine instr that is already done!");
  213. #endif
  214. MachineRegisterInfo *MRI = getRegInfo();
  215. // Determine if the Operands array needs to be reallocated.
  216. // Save the old capacity and operand array.
  217. OperandCapacity OldCap = CapOperands;
  218. MachineOperand *OldOperands = Operands;
  219. if (!OldOperands || OldCap.getSize() == getNumOperands()) {
  220. CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
  221. Operands = MF.allocateOperandArray(CapOperands);
  222. // Move the operands before the insertion point.
  223. if (OpNo)
  224. moveOperands(Operands, OldOperands, OpNo, MRI);
  225. }
  226. // Move the operands following the insertion point.
  227. if (OpNo != NumOperands)
  228. moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
  229. MRI);
  230. ++NumOperands;
  231. // Deallocate the old operand array.
  232. if (OldOperands != Operands && OldOperands)
  233. MF.deallocateOperandArray(OldCap, OldOperands);
  234. // Copy Op into place. It still needs to be inserted into the MRI use lists.
  235. MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
  236. NewMO->ParentMI = this;
  237. // When adding a register operand, tell MRI about it.
  238. if (NewMO->isReg()) {
  239. // Ensure isOnRegUseList() returns false, regardless of Op's status.
  240. NewMO->Contents.Reg.Prev = nullptr;
  241. // Ignore existing ties. This is not a property that can be copied.
  242. NewMO->TiedTo = 0;
  243. // Add the new operand to MRI, but only for instructions in an MBB.
  244. if (MRI)
  245. MRI->addRegOperandToUseList(NewMO);
  246. // The MCID operand information isn't accurate until we start adding
  247. // explicit operands. The implicit operands are added first, then the
  248. // explicits are inserted before them.
  249. if (!isImpReg) {
  250. // Tie uses to defs as indicated in MCInstrDesc.
  251. if (NewMO->isUse()) {
  252. int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
  253. if (DefIdx != -1)
  254. tieOperands(DefIdx, OpNo);
  255. }
  256. // If the register operand is flagged as early, mark the operand as such.
  257. if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
  258. NewMO->setIsEarlyClobber(true);
  259. }
  260. }
  261. }
  262. /// RemoveOperand - Erase an operand from an instruction, leaving it with one
  263. /// fewer operand than it started with.
  264. ///
  265. void MachineInstr::RemoveOperand(unsigned OpNo) {
  266. assert(OpNo < getNumOperands() && "Invalid operand number");
  267. untieRegOperand(OpNo);
  268. #ifndef NDEBUG
  269. // Moving tied operands would break the ties.
  270. for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
  271. if (Operands[i].isReg())
  272. assert(!Operands[i].isTied() && "Cannot move tied operands");
  273. #endif
  274. MachineRegisterInfo *MRI = getRegInfo();
  275. if (MRI && Operands[OpNo].isReg())
  276. MRI->removeRegOperandFromUseList(Operands + OpNo);
  277. // Don't call the MachineOperand destructor. A lot of this code depends on
  278. // MachineOperand having a trivial destructor anyway, and adding a call here
  279. // wouldn't make it 'destructor-correct'.
  280. if (unsigned N = NumOperands - 1 - OpNo)
  281. moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
  282. --NumOperands;
  283. }
  284. void MachineInstr::dropMemRefs(MachineFunction &MF) {
  285. if (memoperands_empty())
  286. return;
  287. // See if we can just drop all of our extra info.
  288. if (!getPreInstrSymbol() && !getPostInstrSymbol()) {
  289. Info.clear();
  290. return;
  291. }
  292. if (!getPostInstrSymbol()) {
  293. Info.set<EIIK_PreInstrSymbol>(getPreInstrSymbol());
  294. return;
  295. }
  296. if (!getPreInstrSymbol()) {
  297. Info.set<EIIK_PostInstrSymbol>(getPostInstrSymbol());
  298. return;
  299. }
  300. // Otherwise allocate a fresh extra info with just these symbols.
  301. Info.set<EIIK_OutOfLine>(
  302. MF.createMIExtraInfo({}, getPreInstrSymbol(), getPostInstrSymbol()));
  303. }
  304. void MachineInstr::setMemRefs(MachineFunction &MF,
  305. ArrayRef<MachineMemOperand *> MMOs) {
  306. if (MMOs.empty()) {
  307. dropMemRefs(MF);
  308. return;
  309. }
  310. // Try to store a single MMO inline.
  311. if (MMOs.size() == 1 && !getPreInstrSymbol() && !getPostInstrSymbol()) {
  312. Info.set<EIIK_MMO>(MMOs[0]);
  313. return;
  314. }
  315. // Otherwise create an extra info struct with all of our info.
  316. Info.set<EIIK_OutOfLine>(
  317. MF.createMIExtraInfo(MMOs, getPreInstrSymbol(), getPostInstrSymbol()));
  318. }
  319. void MachineInstr::addMemOperand(MachineFunction &MF,
  320. MachineMemOperand *MO) {
  321. SmallVector<MachineMemOperand *, 2> MMOs;
  322. MMOs.append(memoperands_begin(), memoperands_end());
  323. MMOs.push_back(MO);
  324. setMemRefs(MF, MMOs);
  325. }
  326. void MachineInstr::cloneMemRefs(MachineFunction &MF, const MachineInstr &MI) {
  327. if (this == &MI)
  328. // Nothing to do for a self-clone!
  329. return;
  330. assert(&MF == MI.getMF() &&
  331. "Invalid machine functions when cloning memory refrences!");
  332. // See if we can just steal the extra info already allocated for the
  333. // instruction. We can do this whenever the pre- and post-instruction symbols
  334. // are the same (including null).
  335. if (getPreInstrSymbol() == MI.getPreInstrSymbol() &&
  336. getPostInstrSymbol() == MI.getPostInstrSymbol()) {
  337. Info = MI.Info;
  338. return;
  339. }
  340. // Otherwise, fall back on a copy-based clone.
  341. setMemRefs(MF, MI.memoperands());
  342. }
  343. /// Check to see if the MMOs pointed to by the two MemRefs arrays are
  344. /// identical.
  345. static bool hasIdenticalMMOs(ArrayRef<MachineMemOperand *> LHS,
  346. ArrayRef<MachineMemOperand *> RHS) {
  347. if (LHS.size() != RHS.size())
  348. return false;
  349. auto LHSPointees = make_pointee_range(LHS);
  350. auto RHSPointees = make_pointee_range(RHS);
  351. return std::equal(LHSPointees.begin(), LHSPointees.end(),
  352. RHSPointees.begin());
  353. }
  354. void MachineInstr::cloneMergedMemRefs(MachineFunction &MF,
  355. ArrayRef<const MachineInstr *> MIs) {
  356. // Try handling easy numbers of MIs with simpler mechanisms.
  357. if (MIs.empty()) {
  358. dropMemRefs(MF);
  359. return;
  360. }
  361. if (MIs.size() == 1) {
  362. cloneMemRefs(MF, *MIs[0]);
  363. return;
  364. }
  365. // Because an empty memoperands list provides *no* information and must be
  366. // handled conservatively (assuming the instruction can do anything), the only
  367. // way to merge with it is to drop all other memoperands.
  368. if (MIs[0]->memoperands_empty()) {
  369. dropMemRefs(MF);
  370. return;
  371. }
  372. // Handle the general case.
  373. SmallVector<MachineMemOperand *, 2> MergedMMOs;
  374. // Start with the first instruction.
  375. assert(&MF == MIs[0]->getMF() &&
  376. "Invalid machine functions when cloning memory references!");
  377. MergedMMOs.append(MIs[0]->memoperands_begin(), MIs[0]->memoperands_end());
  378. // Now walk all the other instructions and accumulate any different MMOs.
  379. for (const MachineInstr &MI : make_pointee_range(MIs.slice(1))) {
  380. assert(&MF == MI.getMF() &&
  381. "Invalid machine functions when cloning memory references!");
  382. // Skip MIs with identical operands to the first. This is a somewhat
  383. // arbitrary hack but will catch common cases without being quadratic.
  384. // TODO: We could fully implement merge semantics here if needed.
  385. if (hasIdenticalMMOs(MIs[0]->memoperands(), MI.memoperands()))
  386. continue;
  387. // Because an empty memoperands list provides *no* information and must be
  388. // handled conservatively (assuming the instruction can do anything), the
  389. // only way to merge with it is to drop all other memoperands.
  390. if (MI.memoperands_empty()) {
  391. dropMemRefs(MF);
  392. return;
  393. }
  394. // Otherwise accumulate these into our temporary buffer of the merged state.
  395. MergedMMOs.append(MI.memoperands_begin(), MI.memoperands_end());
  396. }
  397. setMemRefs(MF, MergedMMOs);
  398. }
  399. void MachineInstr::setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
  400. MCSymbol *OldSymbol = getPreInstrSymbol();
  401. if (OldSymbol == Symbol)
  402. return;
  403. if (OldSymbol && !Symbol) {
  404. // We're removing a symbol rather than adding one. Try to clean up any
  405. // extra info carried around.
  406. if (Info.is<EIIK_PreInstrSymbol>()) {
  407. Info.clear();
  408. return;
  409. }
  410. if (memoperands_empty()) {
  411. assert(getPostInstrSymbol() &&
  412. "Should never have only a single symbol allocated out-of-line!");
  413. Info.set<EIIK_PostInstrSymbol>(getPostInstrSymbol());
  414. return;
  415. }
  416. // Otherwise fallback on the generic update.
  417. } else if (!Info || Info.is<EIIK_PreInstrSymbol>()) {
  418. // If we don't have any other extra info, we can store this inline.
  419. Info.set<EIIK_PreInstrSymbol>(Symbol);
  420. return;
  421. }
  422. // Otherwise, allocate a full new set of extra info.
  423. // FIXME: Maybe we should make the symbols in the extra info mutable?
  424. Info.set<EIIK_OutOfLine>(
  425. MF.createMIExtraInfo(memoperands(), Symbol, getPostInstrSymbol()));
  426. }
  427. void MachineInstr::setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol) {
  428. MCSymbol *OldSymbol = getPostInstrSymbol();
  429. if (OldSymbol == Symbol)
  430. return;
  431. if (OldSymbol && !Symbol) {
  432. // We're removing a symbol rather than adding one. Try to clean up any
  433. // extra info carried around.
  434. if (Info.is<EIIK_PostInstrSymbol>()) {
  435. Info.clear();
  436. return;
  437. }
  438. if (memoperands_empty()) {
  439. assert(getPreInstrSymbol() &&
  440. "Should never have only a single symbol allocated out-of-line!");
  441. Info.set<EIIK_PreInstrSymbol>(getPreInstrSymbol());
  442. return;
  443. }
  444. // Otherwise fallback on the generic update.
  445. } else if (!Info || Info.is<EIIK_PostInstrSymbol>()) {
  446. // If we don't have any other extra info, we can store this inline.
  447. Info.set<EIIK_PostInstrSymbol>(Symbol);
  448. return;
  449. }
  450. // Otherwise, allocate a full new set of extra info.
  451. // FIXME: Maybe we should make the symbols in the extra info mutable?
  452. Info.set<EIIK_OutOfLine>(
  453. MF.createMIExtraInfo(memoperands(), getPreInstrSymbol(), Symbol));
  454. }
  455. uint16_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
  456. // For now, the just return the union of the flags. If the flags get more
  457. // complicated over time, we might need more logic here.
  458. return getFlags() | Other.getFlags();
  459. }
  460. void MachineInstr::copyIRFlags(const Instruction &I) {
  461. // Copy the wrapping flags.
  462. if (const OverflowingBinaryOperator *OB =
  463. dyn_cast<OverflowingBinaryOperator>(&I)) {
  464. if (OB->hasNoSignedWrap())
  465. setFlag(MachineInstr::MIFlag::NoSWrap);
  466. if (OB->hasNoUnsignedWrap())
  467. setFlag(MachineInstr::MIFlag::NoUWrap);
  468. }
  469. // Copy the exact flag.
  470. if (const PossiblyExactOperator *PE = dyn_cast<PossiblyExactOperator>(&I))
  471. if (PE->isExact())
  472. setFlag(MachineInstr::MIFlag::IsExact);
  473. // Copy the fast-math flags.
  474. if (const FPMathOperator *FP = dyn_cast<FPMathOperator>(&I)) {
  475. const FastMathFlags Flags = FP->getFastMathFlags();
  476. if (Flags.noNaNs())
  477. setFlag(MachineInstr::MIFlag::FmNoNans);
  478. if (Flags.noInfs())
  479. setFlag(MachineInstr::MIFlag::FmNoInfs);
  480. if (Flags.noSignedZeros())
  481. setFlag(MachineInstr::MIFlag::FmNsz);
  482. if (Flags.allowReciprocal())
  483. setFlag(MachineInstr::MIFlag::FmArcp);
  484. if (Flags.allowContract())
  485. setFlag(MachineInstr::MIFlag::FmContract);
  486. if (Flags.approxFunc())
  487. setFlag(MachineInstr::MIFlag::FmAfn);
  488. if (Flags.allowReassoc())
  489. setFlag(MachineInstr::MIFlag::FmReassoc);
  490. }
  491. }
  492. bool MachineInstr::hasPropertyInBundle(uint64_t Mask, QueryType Type) const {
  493. assert(!isBundledWithPred() && "Must be called on bundle header");
  494. for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
  495. if (MII->getDesc().getFlags() & Mask) {
  496. if (Type == AnyInBundle)
  497. return true;
  498. } else {
  499. if (Type == AllInBundle && !MII->isBundle())
  500. return false;
  501. }
  502. // This was the last instruction in the bundle.
  503. if (!MII->isBundledWithSucc())
  504. return Type == AllInBundle;
  505. }
  506. }
  507. bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
  508. MICheckType Check) const {
  509. // If opcodes or number of operands are not the same then the two
  510. // instructions are obviously not identical.
  511. if (Other.getOpcode() != getOpcode() ||
  512. Other.getNumOperands() != getNumOperands())
  513. return false;
  514. if (isBundle()) {
  515. // We have passed the test above that both instructions have the same
  516. // opcode, so we know that both instructions are bundles here. Let's compare
  517. // MIs inside the bundle.
  518. assert(Other.isBundle() && "Expected that both instructions are bundles.");
  519. MachineBasicBlock::const_instr_iterator I1 = getIterator();
  520. MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
  521. // Loop until we analysed the last intruction inside at least one of the
  522. // bundles.
  523. while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
  524. ++I1;
  525. ++I2;
  526. if (!I1->isIdenticalTo(*I2, Check))
  527. return false;
  528. }
  529. // If we've reached the end of just one of the two bundles, but not both,
  530. // the instructions are not identical.
  531. if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
  532. return false;
  533. }
  534. // Check operands to make sure they match.
  535. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  536. const MachineOperand &MO = getOperand(i);
  537. const MachineOperand &OMO = Other.getOperand(i);
  538. if (!MO.isReg()) {
  539. if (!MO.isIdenticalTo(OMO))
  540. return false;
  541. continue;
  542. }
  543. // Clients may or may not want to ignore defs when testing for equality.
  544. // For example, machine CSE pass only cares about finding common
  545. // subexpressions, so it's safe to ignore virtual register defs.
  546. if (MO.isDef()) {
  547. if (Check == IgnoreDefs)
  548. continue;
  549. else if (Check == IgnoreVRegDefs) {
  550. if (!TargetRegisterInfo::isVirtualRegister(MO.getReg()) ||
  551. !TargetRegisterInfo::isVirtualRegister(OMO.getReg()))
  552. if (!MO.isIdenticalTo(OMO))
  553. return false;
  554. } else {
  555. if (!MO.isIdenticalTo(OMO))
  556. return false;
  557. if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
  558. return false;
  559. }
  560. } else {
  561. if (!MO.isIdenticalTo(OMO))
  562. return false;
  563. if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
  564. return false;
  565. }
  566. }
  567. // If DebugLoc does not match then two debug instructions are not identical.
  568. if (isDebugInstr())
  569. if (getDebugLoc() && Other.getDebugLoc() &&
  570. getDebugLoc() != Other.getDebugLoc())
  571. return false;
  572. return true;
  573. }
  574. const MachineFunction *MachineInstr::getMF() const {
  575. return getParent()->getParent();
  576. }
  577. MachineInstr *MachineInstr::removeFromParent() {
  578. assert(getParent() && "Not embedded in a basic block!");
  579. return getParent()->remove(this);
  580. }
  581. MachineInstr *MachineInstr::removeFromBundle() {
  582. assert(getParent() && "Not embedded in a basic block!");
  583. return getParent()->remove_instr(this);
  584. }
  585. void MachineInstr::eraseFromParent() {
  586. assert(getParent() && "Not embedded in a basic block!");
  587. getParent()->erase(this);
  588. }
  589. void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
  590. assert(getParent() && "Not embedded in a basic block!");
  591. MachineBasicBlock *MBB = getParent();
  592. MachineFunction *MF = MBB->getParent();
  593. assert(MF && "Not embedded in a function!");
  594. MachineInstr *MI = (MachineInstr *)this;
  595. MachineRegisterInfo &MRI = MF->getRegInfo();
  596. for (const MachineOperand &MO : MI->operands()) {
  597. if (!MO.isReg() || !MO.isDef())
  598. continue;
  599. unsigned Reg = MO.getReg();
  600. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  601. continue;
  602. MRI.markUsesInDebugValueAsUndef(Reg);
  603. }
  604. MI->eraseFromParent();
  605. }
  606. void MachineInstr::eraseFromBundle() {
  607. assert(getParent() && "Not embedded in a basic block!");
  608. getParent()->erase_instr(this);
  609. }
  610. unsigned MachineInstr::getNumExplicitOperands() const {
  611. unsigned NumOperands = MCID->getNumOperands();
  612. if (!MCID->isVariadic())
  613. return NumOperands;
  614. for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) {
  615. const MachineOperand &MO = getOperand(I);
  616. // The operands must always be in the following order:
  617. // - explicit reg defs,
  618. // - other explicit operands (reg uses, immediates, etc.),
  619. // - implicit reg defs
  620. // - implicit reg uses
  621. if (MO.isReg() && MO.isImplicit())
  622. break;
  623. ++NumOperands;
  624. }
  625. return NumOperands;
  626. }
  627. unsigned MachineInstr::getNumExplicitDefs() const {
  628. unsigned NumDefs = MCID->getNumDefs();
  629. if (!MCID->isVariadic())
  630. return NumDefs;
  631. for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) {
  632. const MachineOperand &MO = getOperand(I);
  633. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  634. break;
  635. ++NumDefs;
  636. }
  637. return NumDefs;
  638. }
  639. void MachineInstr::bundleWithPred() {
  640. assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
  641. setFlag(BundledPred);
  642. MachineBasicBlock::instr_iterator Pred = getIterator();
  643. --Pred;
  644. assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  645. Pred->setFlag(BundledSucc);
  646. }
  647. void MachineInstr::bundleWithSucc() {
  648. assert(!isBundledWithSucc() && "MI is already bundled with its successor");
  649. setFlag(BundledSucc);
  650. MachineBasicBlock::instr_iterator Succ = getIterator();
  651. ++Succ;
  652. assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
  653. Succ->setFlag(BundledPred);
  654. }
  655. void MachineInstr::unbundleFromPred() {
  656. assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
  657. clearFlag(BundledPred);
  658. MachineBasicBlock::instr_iterator Pred = getIterator();
  659. --Pred;
  660. assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  661. Pred->clearFlag(BundledSucc);
  662. }
  663. void MachineInstr::unbundleFromSucc() {
  664. assert(isBundledWithSucc() && "MI isn't bundled with its successor");
  665. clearFlag(BundledSucc);
  666. MachineBasicBlock::instr_iterator Succ = getIterator();
  667. ++Succ;
  668. assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
  669. Succ->clearFlag(BundledPred);
  670. }
  671. bool MachineInstr::isStackAligningInlineAsm() const {
  672. if (isInlineAsm()) {
  673. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  674. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  675. return true;
  676. }
  677. return false;
  678. }
  679. InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
  680. assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
  681. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  682. return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
  683. }
  684. int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
  685. unsigned *GroupNo) const {
  686. assert(isInlineAsm() && "Expected an inline asm instruction");
  687. assert(OpIdx < getNumOperands() && "OpIdx out of range");
  688. // Ignore queries about the initial operands.
  689. if (OpIdx < InlineAsm::MIOp_FirstOperand)
  690. return -1;
  691. unsigned Group = 0;
  692. unsigned NumOps;
  693. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  694. i += NumOps) {
  695. const MachineOperand &FlagMO = getOperand(i);
  696. // If we reach the implicit register operands, stop looking.
  697. if (!FlagMO.isImm())
  698. return -1;
  699. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  700. if (i + NumOps > OpIdx) {
  701. if (GroupNo)
  702. *GroupNo = Group;
  703. return i;
  704. }
  705. ++Group;
  706. }
  707. return -1;
  708. }
  709. const DILabel *MachineInstr::getDebugLabel() const {
  710. assert(isDebugLabel() && "not a DBG_LABEL");
  711. return cast<DILabel>(getOperand(0).getMetadata());
  712. }
  713. const DILocalVariable *MachineInstr::getDebugVariable() const {
  714. assert(isDebugValue() && "not a DBG_VALUE");
  715. return cast<DILocalVariable>(getOperand(2).getMetadata());
  716. }
  717. const DIExpression *MachineInstr::getDebugExpression() const {
  718. assert(isDebugValue() && "not a DBG_VALUE");
  719. return cast<DIExpression>(getOperand(3).getMetadata());
  720. }
  721. const TargetRegisterClass*
  722. MachineInstr::getRegClassConstraint(unsigned OpIdx,
  723. const TargetInstrInfo *TII,
  724. const TargetRegisterInfo *TRI) const {
  725. assert(getParent() && "Can't have an MBB reference here!");
  726. assert(getMF() && "Can't have an MF reference here!");
  727. const MachineFunction &MF = *getMF();
  728. // Most opcodes have fixed constraints in their MCInstrDesc.
  729. if (!isInlineAsm())
  730. return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
  731. if (!getOperand(OpIdx).isReg())
  732. return nullptr;
  733. // For tied uses on inline asm, get the constraint from the def.
  734. unsigned DefIdx;
  735. if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
  736. OpIdx = DefIdx;
  737. // Inline asm stores register class constraints in the flag word.
  738. int FlagIdx = findInlineAsmFlagIdx(OpIdx);
  739. if (FlagIdx < 0)
  740. return nullptr;
  741. unsigned Flag = getOperand(FlagIdx).getImm();
  742. unsigned RCID;
  743. if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
  744. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
  745. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
  746. InlineAsm::hasRegClassConstraint(Flag, RCID))
  747. return TRI->getRegClass(RCID);
  748. // Assume that all registers in a memory operand are pointers.
  749. if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
  750. return TRI->getPointerRegClass(MF);
  751. return nullptr;
  752. }
  753. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
  754. unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
  755. const TargetRegisterInfo *TRI, bool ExploreBundle) const {
  756. // Check every operands inside the bundle if we have
  757. // been asked to.
  758. if (ExploreBundle)
  759. for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
  760. ++OpndIt)
  761. CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
  762. OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
  763. else
  764. // Otherwise, just check the current operands.
  765. for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
  766. CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
  767. return CurRC;
  768. }
  769. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
  770. unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
  771. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  772. assert(CurRC && "Invalid initial register class");
  773. // Check if Reg is constrained by some of its use/def from MI.
  774. const MachineOperand &MO = getOperand(OpIdx);
  775. if (!MO.isReg() || MO.getReg() != Reg)
  776. return CurRC;
  777. // If yes, accumulate the constraints through the operand.
  778. return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
  779. }
  780. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
  781. unsigned OpIdx, const TargetRegisterClass *CurRC,
  782. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  783. const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
  784. const MachineOperand &MO = getOperand(OpIdx);
  785. assert(MO.isReg() &&
  786. "Cannot get register constraints for non-register operand");
  787. assert(CurRC && "Invalid initial register class");
  788. if (unsigned SubIdx = MO.getSubReg()) {
  789. if (OpRC)
  790. CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
  791. else
  792. CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
  793. } else if (OpRC)
  794. CurRC = TRI->getCommonSubClass(CurRC, OpRC);
  795. return CurRC;
  796. }
  797. /// Return the number of instructions inside the MI bundle, not counting the
  798. /// header instruction.
  799. unsigned MachineInstr::getBundleSize() const {
  800. MachineBasicBlock::const_instr_iterator I = getIterator();
  801. unsigned Size = 0;
  802. while (I->isBundledWithSucc()) {
  803. ++Size;
  804. ++I;
  805. }
  806. return Size;
  807. }
  808. /// Returns true if the MachineInstr has an implicit-use operand of exactly
  809. /// the given register (not considering sub/super-registers).
  810. bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
  811. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  812. const MachineOperand &MO = getOperand(i);
  813. if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
  814. return true;
  815. }
  816. return false;
  817. }
  818. /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
  819. /// the specific register or -1 if it is not found. It further tightens
  820. /// the search criteria to a use that kills the register if isKill is true.
  821. int MachineInstr::findRegisterUseOperandIdx(
  822. unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
  823. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  824. const MachineOperand &MO = getOperand(i);
  825. if (!MO.isReg() || !MO.isUse())
  826. continue;
  827. unsigned MOReg = MO.getReg();
  828. if (!MOReg)
  829. continue;
  830. if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg)))
  831. if (!isKill || MO.isKill())
  832. return i;
  833. }
  834. return -1;
  835. }
  836. /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
  837. /// indicating if this instruction reads or writes Reg. This also considers
  838. /// partial defines.
  839. std::pair<bool,bool>
  840. MachineInstr::readsWritesVirtualRegister(unsigned Reg,
  841. SmallVectorImpl<unsigned> *Ops) const {
  842. bool PartDef = false; // Partial redefine.
  843. bool FullDef = false; // Full define.
  844. bool Use = false;
  845. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  846. const MachineOperand &MO = getOperand(i);
  847. if (!MO.isReg() || MO.getReg() != Reg)
  848. continue;
  849. if (Ops)
  850. Ops->push_back(i);
  851. if (MO.isUse())
  852. Use |= !MO.isUndef();
  853. else if (MO.getSubReg() && !MO.isUndef())
  854. // A partial def undef doesn't count as reading the register.
  855. PartDef = true;
  856. else
  857. FullDef = true;
  858. }
  859. // A partial redefine uses Reg unless there is also a full define.
  860. return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
  861. }
  862. /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
  863. /// the specified register or -1 if it is not found. If isDead is true, defs
  864. /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
  865. /// also checks if there is a def of a super-register.
  866. int
  867. MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
  868. const TargetRegisterInfo *TRI) const {
  869. bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
  870. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  871. const MachineOperand &MO = getOperand(i);
  872. // Accept regmask operands when Overlap is set.
  873. // Ignore them when looking for a specific def operand (Overlap == false).
  874. if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
  875. return i;
  876. if (!MO.isReg() || !MO.isDef())
  877. continue;
  878. unsigned MOReg = MO.getReg();
  879. bool Found = (MOReg == Reg);
  880. if (!Found && TRI && isPhys &&
  881. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  882. if (Overlap)
  883. Found = TRI->regsOverlap(MOReg, Reg);
  884. else
  885. Found = TRI->isSubRegister(MOReg, Reg);
  886. }
  887. if (Found && (!isDead || MO.isDead()))
  888. return i;
  889. }
  890. return -1;
  891. }
  892. /// findFirstPredOperandIdx() - Find the index of the first operand in the
  893. /// operand list that is used to represent the predicate. It returns -1 if
  894. /// none is found.
  895. int MachineInstr::findFirstPredOperandIdx() const {
  896. // Don't call MCID.findFirstPredOperandIdx() because this variant
  897. // is sometimes called on an instruction that's not yet complete, and
  898. // so the number of operands is less than the MCID indicates. In
  899. // particular, the PTX target does this.
  900. const MCInstrDesc &MCID = getDesc();
  901. if (MCID.isPredicable()) {
  902. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  903. if (MCID.OpInfo[i].isPredicate())
  904. return i;
  905. }
  906. return -1;
  907. }
  908. // MachineOperand::TiedTo is 4 bits wide.
  909. const unsigned TiedMax = 15;
  910. /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
  911. ///
  912. /// Use and def operands can be tied together, indicated by a non-zero TiedTo
  913. /// field. TiedTo can have these values:
  914. ///
  915. /// 0: Operand is not tied to anything.
  916. /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
  917. /// TiedMax: Tied to an operand >= TiedMax-1.
  918. ///
  919. /// The tied def must be one of the first TiedMax operands on a normal
  920. /// instruction. INLINEASM instructions allow more tied defs.
  921. ///
  922. void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
  923. MachineOperand &DefMO = getOperand(DefIdx);
  924. MachineOperand &UseMO = getOperand(UseIdx);
  925. assert(DefMO.isDef() && "DefIdx must be a def operand");
  926. assert(UseMO.isUse() && "UseIdx must be a use operand");
  927. assert(!DefMO.isTied() && "Def is already tied to another use");
  928. assert(!UseMO.isTied() && "Use is already tied to another def");
  929. if (DefIdx < TiedMax)
  930. UseMO.TiedTo = DefIdx + 1;
  931. else {
  932. // Inline asm can use the group descriptors to find tied operands, but on
  933. // normal instruction, the tied def must be within the first TiedMax
  934. // operands.
  935. assert(isInlineAsm() && "DefIdx out of range");
  936. UseMO.TiedTo = TiedMax;
  937. }
  938. // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
  939. DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
  940. }
  941. /// Given the index of a tied register operand, find the operand it is tied to.
  942. /// Defs are tied to uses and vice versa. Returns the index of the tied operand
  943. /// which must exist.
  944. unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
  945. const MachineOperand &MO = getOperand(OpIdx);
  946. assert(MO.isTied() && "Operand isn't tied");
  947. // Normally TiedTo is in range.
  948. if (MO.TiedTo < TiedMax)
  949. return MO.TiedTo - 1;
  950. // Uses on normal instructions can be out of range.
  951. if (!isInlineAsm()) {
  952. // Normal tied defs must be in the 0..TiedMax-1 range.
  953. if (MO.isUse())
  954. return TiedMax - 1;
  955. // MO is a def. Search for the tied use.
  956. for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
  957. const MachineOperand &UseMO = getOperand(i);
  958. if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
  959. return i;
  960. }
  961. llvm_unreachable("Can't find tied use");
  962. }
  963. // Now deal with inline asm by parsing the operand group descriptor flags.
  964. // Find the beginning of each operand group.
  965. SmallVector<unsigned, 8> GroupIdx;
  966. unsigned OpIdxGroup = ~0u;
  967. unsigned NumOps;
  968. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  969. i += NumOps) {
  970. const MachineOperand &FlagMO = getOperand(i);
  971. assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
  972. unsigned CurGroup = GroupIdx.size();
  973. GroupIdx.push_back(i);
  974. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  975. // OpIdx belongs to this operand group.
  976. if (OpIdx > i && OpIdx < i + NumOps)
  977. OpIdxGroup = CurGroup;
  978. unsigned TiedGroup;
  979. if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
  980. continue;
  981. // Operands in this group are tied to operands in TiedGroup which must be
  982. // earlier. Find the number of operands between the two groups.
  983. unsigned Delta = i - GroupIdx[TiedGroup];
  984. // OpIdx is a use tied to TiedGroup.
  985. if (OpIdxGroup == CurGroup)
  986. return OpIdx - Delta;
  987. // OpIdx is a def tied to this use group.
  988. if (OpIdxGroup == TiedGroup)
  989. return OpIdx + Delta;
  990. }
  991. llvm_unreachable("Invalid tied operand on inline asm");
  992. }
  993. /// clearKillInfo - Clears kill flags on all operands.
  994. ///
  995. void MachineInstr::clearKillInfo() {
  996. for (MachineOperand &MO : operands()) {
  997. if (MO.isReg() && MO.isUse())
  998. MO.setIsKill(false);
  999. }
  1000. }
  1001. void MachineInstr::substituteRegister(unsigned FromReg, unsigned ToReg,
  1002. unsigned SubIdx,
  1003. const TargetRegisterInfo &RegInfo) {
  1004. if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
  1005. if (SubIdx)
  1006. ToReg = RegInfo.getSubReg(ToReg, SubIdx);
  1007. for (MachineOperand &MO : operands()) {
  1008. if (!MO.isReg() || MO.getReg() != FromReg)
  1009. continue;
  1010. MO.substPhysReg(ToReg, RegInfo);
  1011. }
  1012. } else {
  1013. for (MachineOperand &MO : operands()) {
  1014. if (!MO.isReg() || MO.getReg() != FromReg)
  1015. continue;
  1016. MO.substVirtReg(ToReg, SubIdx, RegInfo);
  1017. }
  1018. }
  1019. }
  1020. /// isSafeToMove - Return true if it is safe to move this instruction. If
  1021. /// SawStore is set to true, it means that there is a store (or call) between
  1022. /// the instruction's location and its intended destination.
  1023. bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
  1024. // Ignore stuff that we obviously can't move.
  1025. //
  1026. // Treat volatile loads as stores. This is not strictly necessary for
  1027. // volatiles, but it is required for atomic loads. It is not allowed to move
  1028. // a load across an atomic load with Ordering > Monotonic.
  1029. if (mayStore() || isCall() || isPHI() ||
  1030. (mayLoad() && hasOrderedMemoryRef())) {
  1031. SawStore = true;
  1032. return false;
  1033. }
  1034. if (isPosition() || isDebugInstr() || isTerminator() ||
  1035. hasUnmodeledSideEffects())
  1036. return false;
  1037. // See if this instruction does a load. If so, we have to guarantee that the
  1038. // loaded value doesn't change between the load and the its intended
  1039. // destination. The check for isInvariantLoad gives the targe the chance to
  1040. // classify the load as always returning a constant, e.g. a constant pool
  1041. // load.
  1042. if (mayLoad() && !isDereferenceableInvariantLoad(AA))
  1043. // Otherwise, this is a real load. If there is a store between the load and
  1044. // end of block, we can't move it.
  1045. return !SawStore;
  1046. return true;
  1047. }
  1048. bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
  1049. bool UseTBAA) {
  1050. const MachineFunction *MF = getMF();
  1051. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1052. const MachineFrameInfo &MFI = MF->getFrameInfo();
  1053. // If neither instruction stores to memory, they can't alias in any
  1054. // meaningful way, even if they read from the same address.
  1055. if (!mayStore() && !Other.mayStore())
  1056. return false;
  1057. // Let the target decide if memory accesses cannot possibly overlap.
  1058. if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
  1059. return false;
  1060. // FIXME: Need to handle multiple memory operands to support all targets.
  1061. if (!hasOneMemOperand() || !Other.hasOneMemOperand())
  1062. return true;
  1063. MachineMemOperand *MMOa = *memoperands_begin();
  1064. MachineMemOperand *MMOb = *Other.memoperands_begin();
  1065. // The following interface to AA is fashioned after DAGCombiner::isAlias
  1066. // and operates with MachineMemOperand offset with some important
  1067. // assumptions:
  1068. // - LLVM fundamentally assumes flat address spaces.
  1069. // - MachineOperand offset can *only* result from legalization and
  1070. // cannot affect queries other than the trivial case of overlap
  1071. // checking.
  1072. // - These offsets never wrap and never step outside
  1073. // of allocated objects.
  1074. // - There should never be any negative offsets here.
  1075. //
  1076. // FIXME: Modify API to hide this math from "user"
  1077. // Even before we go to AA we can reason locally about some
  1078. // memory objects. It can save compile time, and possibly catch some
  1079. // corner cases not currently covered.
  1080. int64_t OffsetA = MMOa->getOffset();
  1081. int64_t OffsetB = MMOb->getOffset();
  1082. int64_t MinOffset = std::min(OffsetA, OffsetB);
  1083. uint64_t WidthA = MMOa->getSize();
  1084. uint64_t WidthB = MMOb->getSize();
  1085. bool KnownWidthA = WidthA != MemoryLocation::UnknownSize;
  1086. bool KnownWidthB = WidthB != MemoryLocation::UnknownSize;
  1087. const Value *ValA = MMOa->getValue();
  1088. const Value *ValB = MMOb->getValue();
  1089. bool SameVal = (ValA && ValB && (ValA == ValB));
  1090. if (!SameVal) {
  1091. const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
  1092. const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
  1093. if (PSVa && ValB && !PSVa->mayAlias(&MFI))
  1094. return false;
  1095. if (PSVb && ValA && !PSVb->mayAlias(&MFI))
  1096. return false;
  1097. if (PSVa && PSVb && (PSVa == PSVb))
  1098. SameVal = true;
  1099. }
  1100. if (SameVal) {
  1101. if (!KnownWidthA || !KnownWidthB)
  1102. return true;
  1103. int64_t MaxOffset = std::max(OffsetA, OffsetB);
  1104. int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
  1105. return (MinOffset + LowWidth > MaxOffset);
  1106. }
  1107. if (!AA)
  1108. return true;
  1109. if (!ValA || !ValB)
  1110. return true;
  1111. assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
  1112. assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
  1113. int64_t OverlapA = KnownWidthA ? WidthA + OffsetA - MinOffset
  1114. : MemoryLocation::UnknownSize;
  1115. int64_t OverlapB = KnownWidthB ? WidthB + OffsetB - MinOffset
  1116. : MemoryLocation::UnknownSize;
  1117. AliasResult AAResult = AA->alias(
  1118. MemoryLocation(ValA, OverlapA,
  1119. UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
  1120. MemoryLocation(ValB, OverlapB,
  1121. UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
  1122. return (AAResult != NoAlias);
  1123. }
  1124. /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
  1125. /// or volatile memory reference, or if the information describing the memory
  1126. /// reference is not available. Return false if it is known to have no ordered
  1127. /// memory references.
  1128. bool MachineInstr::hasOrderedMemoryRef() const {
  1129. // An instruction known never to access memory won't have a volatile access.
  1130. if (!mayStore() &&
  1131. !mayLoad() &&
  1132. !isCall() &&
  1133. !hasUnmodeledSideEffects())
  1134. return false;
  1135. // Otherwise, if the instruction has no memory reference information,
  1136. // conservatively assume it wasn't preserved.
  1137. if (memoperands_empty())
  1138. return true;
  1139. // Check if any of our memory operands are ordered.
  1140. return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
  1141. return !MMO->isUnordered();
  1142. });
  1143. }
  1144. /// isDereferenceableInvariantLoad - Return true if this instruction will never
  1145. /// trap and is loading from a location whose value is invariant across a run of
  1146. /// this function.
  1147. bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
  1148. // If the instruction doesn't load at all, it isn't an invariant load.
  1149. if (!mayLoad())
  1150. return false;
  1151. // If the instruction has lost its memoperands, conservatively assume that
  1152. // it may not be an invariant load.
  1153. if (memoperands_empty())
  1154. return false;
  1155. const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
  1156. for (MachineMemOperand *MMO : memoperands()) {
  1157. if (MMO->isVolatile()) return false;
  1158. // TODO: Figure out whether isAtomic is really necessary (see D57601).
  1159. if (MMO->isAtomic()) return false;
  1160. if (MMO->isStore()) return false;
  1161. if (MMO->isInvariant() && MMO->isDereferenceable())
  1162. continue;
  1163. // A load from a constant PseudoSourceValue is invariant.
  1164. if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
  1165. if (PSV->isConstant(&MFI))
  1166. continue;
  1167. if (const Value *V = MMO->getValue()) {
  1168. // If we have an AliasAnalysis, ask it whether the memory is constant.
  1169. if (AA &&
  1170. AA->pointsToConstantMemory(
  1171. MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
  1172. continue;
  1173. }
  1174. // Otherwise assume conservatively.
  1175. return false;
  1176. }
  1177. // Everything checks out.
  1178. return true;
  1179. }
  1180. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1181. /// merges together the same virtual register, return the register, otherwise
  1182. /// return 0.
  1183. unsigned MachineInstr::isConstantValuePHI() const {
  1184. if (!isPHI())
  1185. return 0;
  1186. assert(getNumOperands() >= 3 &&
  1187. "It's illegal to have a PHI without source operands");
  1188. unsigned Reg = getOperand(1).getReg();
  1189. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1190. if (getOperand(i).getReg() != Reg)
  1191. return 0;
  1192. return Reg;
  1193. }
  1194. bool MachineInstr::hasUnmodeledSideEffects() const {
  1195. if (hasProperty(MCID::UnmodeledSideEffects))
  1196. return true;
  1197. if (isInlineAsm()) {
  1198. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1199. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1200. return true;
  1201. }
  1202. return false;
  1203. }
  1204. bool MachineInstr::isLoadFoldBarrier() const {
  1205. return mayStore() || isCall() || hasUnmodeledSideEffects();
  1206. }
  1207. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1208. ///
  1209. bool MachineInstr::allDefsAreDead() const {
  1210. for (const MachineOperand &MO : operands()) {
  1211. if (!MO.isReg() || MO.isUse())
  1212. continue;
  1213. if (!MO.isDead())
  1214. return false;
  1215. }
  1216. return true;
  1217. }
  1218. /// copyImplicitOps - Copy implicit register operands from specified
  1219. /// instruction to this instruction.
  1220. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1221. const MachineInstr &MI) {
  1222. for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
  1223. i != e; ++i) {
  1224. const MachineOperand &MO = MI.getOperand(i);
  1225. if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
  1226. addOperand(MF, MO);
  1227. }
  1228. }
  1229. bool MachineInstr::hasComplexRegisterTies() const {
  1230. const MCInstrDesc &MCID = getDesc();
  1231. for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
  1232. const auto &Operand = getOperand(I);
  1233. if (!Operand.isReg() || Operand.isDef())
  1234. // Ignore the defined registers as MCID marks only the uses as tied.
  1235. continue;
  1236. int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
  1237. int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1;
  1238. if (ExpectedTiedIdx != TiedIdx)
  1239. return true;
  1240. }
  1241. return false;
  1242. }
  1243. LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
  1244. const MachineRegisterInfo &MRI) const {
  1245. const MachineOperand &Op = getOperand(OpIdx);
  1246. if (!Op.isReg())
  1247. return LLT{};
  1248. if (isVariadic() || OpIdx >= getNumExplicitOperands())
  1249. return MRI.getType(Op.getReg());
  1250. auto &OpInfo = getDesc().OpInfo[OpIdx];
  1251. if (!OpInfo.isGenericType())
  1252. return MRI.getType(Op.getReg());
  1253. if (PrintedTypes[OpInfo.getGenericTypeIndex()])
  1254. return LLT{};
  1255. LLT TypeToPrint = MRI.getType(Op.getReg());
  1256. // Don't mark the type index printed if it wasn't actually printed: maybe
  1257. // another operand with the same type index has an actual type attached:
  1258. if (TypeToPrint.isValid())
  1259. PrintedTypes.set(OpInfo.getGenericTypeIndex());
  1260. return TypeToPrint;
  1261. }
  1262. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1263. LLVM_DUMP_METHOD void MachineInstr::dump() const {
  1264. dbgs() << " ";
  1265. print(dbgs());
  1266. }
  1267. #endif
  1268. void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers,
  1269. bool SkipDebugLoc, bool AddNewLine,
  1270. const TargetInstrInfo *TII) const {
  1271. const Module *M = nullptr;
  1272. const Function *F = nullptr;
  1273. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1274. F = &MF->getFunction();
  1275. M = F->getParent();
  1276. if (!TII)
  1277. TII = MF->getSubtarget().getInstrInfo();
  1278. }
  1279. ModuleSlotTracker MST(M);
  1280. if (F)
  1281. MST.incorporateFunction(*F);
  1282. print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, TII);
  1283. }
  1284. void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
  1285. bool IsStandalone, bool SkipOpers, bool SkipDebugLoc,
  1286. bool AddNewLine, const TargetInstrInfo *TII) const {
  1287. // We can be a bit tidier if we know the MachineFunction.
  1288. const MachineFunction *MF = nullptr;
  1289. const TargetRegisterInfo *TRI = nullptr;
  1290. const MachineRegisterInfo *MRI = nullptr;
  1291. const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
  1292. tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII);
  1293. if (isCFIInstruction())
  1294. assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
  1295. SmallBitVector PrintedTypes(8);
  1296. bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies();
  1297. auto getTiedOperandIdx = [&](unsigned OpIdx) {
  1298. if (!ShouldPrintRegisterTies)
  1299. return 0U;
  1300. const MachineOperand &MO = getOperand(OpIdx);
  1301. if (MO.isReg() && MO.isTied() && !MO.isDef())
  1302. return findTiedOperandIdx(OpIdx);
  1303. return 0U;
  1304. };
  1305. unsigned StartOp = 0;
  1306. unsigned e = getNumOperands();
  1307. // Print explicitly defined operands on the left of an assignment syntax.
  1308. while (StartOp < e) {
  1309. const MachineOperand &MO = getOperand(StartOp);
  1310. if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
  1311. break;
  1312. if (StartOp != 0)
  1313. OS << ", ";
  1314. LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{};
  1315. unsigned TiedOperandIdx = getTiedOperandIdx(StartOp);
  1316. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/false, IsStandalone,
  1317. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1318. ++StartOp;
  1319. }
  1320. if (StartOp != 0)
  1321. OS << " = ";
  1322. if (getFlag(MachineInstr::FrameSetup))
  1323. OS << "frame-setup ";
  1324. if (getFlag(MachineInstr::FrameDestroy))
  1325. OS << "frame-destroy ";
  1326. if (getFlag(MachineInstr::FmNoNans))
  1327. OS << "nnan ";
  1328. if (getFlag(MachineInstr::FmNoInfs))
  1329. OS << "ninf ";
  1330. if (getFlag(MachineInstr::FmNsz))
  1331. OS << "nsz ";
  1332. if (getFlag(MachineInstr::FmArcp))
  1333. OS << "arcp ";
  1334. if (getFlag(MachineInstr::FmContract))
  1335. OS << "contract ";
  1336. if (getFlag(MachineInstr::FmAfn))
  1337. OS << "afn ";
  1338. if (getFlag(MachineInstr::FmReassoc))
  1339. OS << "reassoc ";
  1340. if (getFlag(MachineInstr::NoUWrap))
  1341. OS << "nuw ";
  1342. if (getFlag(MachineInstr::NoSWrap))
  1343. OS << "nsw ";
  1344. if (getFlag(MachineInstr::IsExact))
  1345. OS << "exact ";
  1346. // Print the opcode name.
  1347. if (TII)
  1348. OS << TII->getName(getOpcode());
  1349. else
  1350. OS << "UNKNOWN";
  1351. if (SkipOpers)
  1352. return;
  1353. // Print the rest of the operands.
  1354. bool FirstOp = true;
  1355. unsigned AsmDescOp = ~0u;
  1356. unsigned AsmOpCount = 0;
  1357. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1358. // Print asm string.
  1359. OS << " ";
  1360. const unsigned OpIdx = InlineAsm::MIOp_AsmString;
  1361. LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{};
  1362. unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx);
  1363. getOperand(OpIdx).print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1364. ShouldPrintRegisterTies, TiedOperandIdx, TRI,
  1365. IntrinsicInfo);
  1366. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1367. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1368. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1369. OS << " [sideeffect]";
  1370. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1371. OS << " [mayload]";
  1372. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1373. OS << " [maystore]";
  1374. if (ExtraInfo & InlineAsm::Extra_IsConvergent)
  1375. OS << " [isconvergent]";
  1376. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1377. OS << " [alignstack]";
  1378. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1379. OS << " [attdialect]";
  1380. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1381. OS << " [inteldialect]";
  1382. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1383. FirstOp = false;
  1384. }
  1385. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1386. const MachineOperand &MO = getOperand(i);
  1387. if (FirstOp) FirstOp = false; else OS << ",";
  1388. OS << " ";
  1389. if (isDebugValue() && MO.isMetadata()) {
  1390. // Pretty print DBG_VALUE instructions.
  1391. auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
  1392. if (DIV && !DIV->getName().empty())
  1393. OS << "!\"" << DIV->getName() << '\"';
  1394. else {
  1395. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1396. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1397. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1398. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1399. }
  1400. } else if (isDebugLabel() && MO.isMetadata()) {
  1401. // Pretty print DBG_LABEL instructions.
  1402. auto *DIL = dyn_cast<DILabel>(MO.getMetadata());
  1403. if (DIL && !DIL->getName().empty())
  1404. OS << "\"" << DIL->getName() << '\"';
  1405. else {
  1406. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1407. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1408. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1409. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1410. }
  1411. } else if (i == AsmDescOp && MO.isImm()) {
  1412. // Pretty print the inline asm operand descriptor.
  1413. OS << '$' << AsmOpCount++;
  1414. unsigned Flag = MO.getImm();
  1415. switch (InlineAsm::getKind(Flag)) {
  1416. case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
  1417. case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
  1418. case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
  1419. case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
  1420. case InlineAsm::Kind_Imm: OS << ":[imm"; break;
  1421. case InlineAsm::Kind_Mem: OS << ":[mem"; break;
  1422. default: OS << ":[??" << InlineAsm::getKind(Flag); break;
  1423. }
  1424. unsigned RCID = 0;
  1425. if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
  1426. InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1427. if (TRI) {
  1428. OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
  1429. } else
  1430. OS << ":RC" << RCID;
  1431. }
  1432. if (InlineAsm::isMemKind(Flag)) {
  1433. unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
  1434. switch (MCID) {
  1435. case InlineAsm::Constraint_es: OS << ":es"; break;
  1436. case InlineAsm::Constraint_i: OS << ":i"; break;
  1437. case InlineAsm::Constraint_m: OS << ":m"; break;
  1438. case InlineAsm::Constraint_o: OS << ":o"; break;
  1439. case InlineAsm::Constraint_v: OS << ":v"; break;
  1440. case InlineAsm::Constraint_Q: OS << ":Q"; break;
  1441. case InlineAsm::Constraint_R: OS << ":R"; break;
  1442. case InlineAsm::Constraint_S: OS << ":S"; break;
  1443. case InlineAsm::Constraint_T: OS << ":T"; break;
  1444. case InlineAsm::Constraint_Um: OS << ":Um"; break;
  1445. case InlineAsm::Constraint_Un: OS << ":Un"; break;
  1446. case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
  1447. case InlineAsm::Constraint_Us: OS << ":Us"; break;
  1448. case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
  1449. case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
  1450. case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
  1451. case InlineAsm::Constraint_X: OS << ":X"; break;
  1452. case InlineAsm::Constraint_Z: OS << ":Z"; break;
  1453. case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
  1454. case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
  1455. default: OS << ":?"; break;
  1456. }
  1457. }
  1458. unsigned TiedTo = 0;
  1459. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1460. OS << " tiedto:$" << TiedTo;
  1461. OS << ']';
  1462. // Compute the index of the next operand descriptor.
  1463. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1464. } else {
  1465. LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{};
  1466. unsigned TiedOperandIdx = getTiedOperandIdx(i);
  1467. if (MO.isImm() && isOperandSubregIdx(i))
  1468. MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI);
  1469. else
  1470. MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone,
  1471. ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo);
  1472. }
  1473. }
  1474. // Print any optional symbols attached to this instruction as-if they were
  1475. // operands.
  1476. if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) {
  1477. if (!FirstOp) {
  1478. FirstOp = false;
  1479. OS << ',';
  1480. }
  1481. OS << " pre-instr-symbol ";
  1482. MachineOperand::printSymbol(OS, *PreInstrSymbol);
  1483. }
  1484. if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) {
  1485. if (!FirstOp) {
  1486. FirstOp = false;
  1487. OS << ',';
  1488. }
  1489. OS << " post-instr-symbol ";
  1490. MachineOperand::printSymbol(OS, *PostInstrSymbol);
  1491. }
  1492. if (!SkipDebugLoc) {
  1493. if (const DebugLoc &DL = getDebugLoc()) {
  1494. if (!FirstOp)
  1495. OS << ',';
  1496. OS << " debug-location ";
  1497. DL->printAsOperand(OS, MST);
  1498. }
  1499. }
  1500. if (!memoperands_empty()) {
  1501. SmallVector<StringRef, 0> SSNs;
  1502. const LLVMContext *Context = nullptr;
  1503. std::unique_ptr<LLVMContext> CtxPtr;
  1504. const MachineFrameInfo *MFI = nullptr;
  1505. if (const MachineFunction *MF = getMFIfAvailable(*this)) {
  1506. MFI = &MF->getFrameInfo();
  1507. Context = &MF->getFunction().getContext();
  1508. } else {
  1509. CtxPtr = llvm::make_unique<LLVMContext>();
  1510. Context = CtxPtr.get();
  1511. }
  1512. OS << " :: ";
  1513. bool NeedComma = false;
  1514. for (const MachineMemOperand *Op : memoperands()) {
  1515. if (NeedComma)
  1516. OS << ", ";
  1517. Op->print(OS, MST, SSNs, *Context, MFI, TII);
  1518. NeedComma = true;
  1519. }
  1520. }
  1521. if (SkipDebugLoc)
  1522. return;
  1523. bool HaveSemi = false;
  1524. // Print debug location information.
  1525. if (const DebugLoc &DL = getDebugLoc()) {
  1526. if (!HaveSemi) {
  1527. OS << ';';
  1528. HaveSemi = true;
  1529. }
  1530. OS << ' ';
  1531. DL.print(OS);
  1532. }
  1533. // Print extra comments for DEBUG_VALUE.
  1534. if (isDebugValue() && getOperand(e - 2).isMetadata()) {
  1535. if (!HaveSemi) {
  1536. OS << ";";
  1537. HaveSemi = true;
  1538. }
  1539. auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
  1540. OS << " line no:" << DV->getLine();
  1541. if (auto *InlinedAt = debugLoc->getInlinedAt()) {
  1542. DebugLoc InlinedAtDL(InlinedAt);
  1543. if (InlinedAtDL && MF) {
  1544. OS << " inlined @[ ";
  1545. InlinedAtDL.print(OS);
  1546. OS << " ]";
  1547. }
  1548. }
  1549. if (isIndirectDebugValue())
  1550. OS << " indirect";
  1551. }
  1552. // TODO: DBG_LABEL
  1553. if (AddNewLine)
  1554. OS << '\n';
  1555. }
  1556. bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
  1557. const TargetRegisterInfo *RegInfo,
  1558. bool AddIfNotFound) {
  1559. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
  1560. bool hasAliases = isPhysReg &&
  1561. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1562. bool Found = false;
  1563. SmallVector<unsigned,4> DeadOps;
  1564. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1565. MachineOperand &MO = getOperand(i);
  1566. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1567. continue;
  1568. // DEBUG_VALUE nodes do not contribute to code generation and should
  1569. // always be ignored. Failure to do so may result in trying to modify
  1570. // KILL flags on DEBUG_VALUE nodes.
  1571. if (MO.isDebug())
  1572. continue;
  1573. unsigned Reg = MO.getReg();
  1574. if (!Reg)
  1575. continue;
  1576. if (Reg == IncomingReg) {
  1577. if (!Found) {
  1578. if (MO.isKill())
  1579. // The register is already marked kill.
  1580. return true;
  1581. if (isPhysReg && isRegTiedToDefOperand(i))
  1582. // Two-address uses of physregs must not be marked kill.
  1583. return true;
  1584. MO.setIsKill();
  1585. Found = true;
  1586. }
  1587. } else if (hasAliases && MO.isKill() &&
  1588. TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1589. // A super-register kill already exists.
  1590. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1591. return true;
  1592. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1593. DeadOps.push_back(i);
  1594. }
  1595. }
  1596. // Trim unneeded kill operands.
  1597. while (!DeadOps.empty()) {
  1598. unsigned OpIdx = DeadOps.back();
  1599. if (getOperand(OpIdx).isImplicit() &&
  1600. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1601. RemoveOperand(OpIdx);
  1602. else
  1603. getOperand(OpIdx).setIsKill(false);
  1604. DeadOps.pop_back();
  1605. }
  1606. // If not found, this means an alias of one of the operands is killed. Add a
  1607. // new implicit operand if required.
  1608. if (!Found && AddIfNotFound) {
  1609. addOperand(MachineOperand::CreateReg(IncomingReg,
  1610. false /*IsDef*/,
  1611. true /*IsImp*/,
  1612. true /*IsKill*/));
  1613. return true;
  1614. }
  1615. return Found;
  1616. }
  1617. void MachineInstr::clearRegisterKills(unsigned Reg,
  1618. const TargetRegisterInfo *RegInfo) {
  1619. if (!TargetRegisterInfo::isPhysicalRegister(Reg))
  1620. RegInfo = nullptr;
  1621. for (MachineOperand &MO : operands()) {
  1622. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1623. continue;
  1624. unsigned OpReg = MO.getReg();
  1625. if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
  1626. MO.setIsKill(false);
  1627. }
  1628. }
  1629. bool MachineInstr::addRegisterDead(unsigned Reg,
  1630. const TargetRegisterInfo *RegInfo,
  1631. bool AddIfNotFound) {
  1632. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
  1633. bool hasAliases = isPhysReg &&
  1634. MCRegAliasIterator(Reg, RegInfo, false).isValid();
  1635. bool Found = false;
  1636. SmallVector<unsigned,4> DeadOps;
  1637. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1638. MachineOperand &MO = getOperand(i);
  1639. if (!MO.isReg() || !MO.isDef())
  1640. continue;
  1641. unsigned MOReg = MO.getReg();
  1642. if (!MOReg)
  1643. continue;
  1644. if (MOReg == Reg) {
  1645. MO.setIsDead();
  1646. Found = true;
  1647. } else if (hasAliases && MO.isDead() &&
  1648. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  1649. // There exists a super-register that's marked dead.
  1650. if (RegInfo->isSuperRegister(Reg, MOReg))
  1651. return true;
  1652. if (RegInfo->isSubRegister(Reg, MOReg))
  1653. DeadOps.push_back(i);
  1654. }
  1655. }
  1656. // Trim unneeded dead operands.
  1657. while (!DeadOps.empty()) {
  1658. unsigned OpIdx = DeadOps.back();
  1659. if (getOperand(OpIdx).isImplicit() &&
  1660. (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0))
  1661. RemoveOperand(OpIdx);
  1662. else
  1663. getOperand(OpIdx).setIsDead(false);
  1664. DeadOps.pop_back();
  1665. }
  1666. // If not found, this means an alias of one of the operands is dead. Add a
  1667. // new implicit operand if required.
  1668. if (Found || !AddIfNotFound)
  1669. return Found;
  1670. addOperand(MachineOperand::CreateReg(Reg,
  1671. true /*IsDef*/,
  1672. true /*IsImp*/,
  1673. false /*IsKill*/,
  1674. true /*IsDead*/));
  1675. return true;
  1676. }
  1677. void MachineInstr::clearRegisterDeads(unsigned Reg) {
  1678. for (MachineOperand &MO : operands()) {
  1679. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
  1680. continue;
  1681. MO.setIsDead(false);
  1682. }
  1683. }
  1684. void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
  1685. for (MachineOperand &MO : operands()) {
  1686. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
  1687. continue;
  1688. MO.setIsUndef(IsUndef);
  1689. }
  1690. }
  1691. void MachineInstr::addRegisterDefined(unsigned Reg,
  1692. const TargetRegisterInfo *RegInfo) {
  1693. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1694. MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
  1695. if (MO)
  1696. return;
  1697. } else {
  1698. for (const MachineOperand &MO : operands()) {
  1699. if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
  1700. MO.getSubReg() == 0)
  1701. return;
  1702. }
  1703. }
  1704. addOperand(MachineOperand::CreateReg(Reg,
  1705. true /*IsDef*/,
  1706. true /*IsImp*/));
  1707. }
  1708. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
  1709. const TargetRegisterInfo &TRI) {
  1710. bool HasRegMask = false;
  1711. for (MachineOperand &MO : operands()) {
  1712. if (MO.isRegMask()) {
  1713. HasRegMask = true;
  1714. continue;
  1715. }
  1716. if (!MO.isReg() || !MO.isDef()) continue;
  1717. unsigned Reg = MO.getReg();
  1718. if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  1719. // If there are no uses, including partial uses, the def is dead.
  1720. if (llvm::none_of(UsedRegs,
  1721. [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
  1722. MO.setIsDead();
  1723. }
  1724. // This is a call with a register mask operand.
  1725. // Mask clobbers are always dead, so add defs for the non-dead defines.
  1726. if (HasRegMask)
  1727. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1728. I != E; ++I)
  1729. addRegisterDefined(*I, &TRI);
  1730. }
  1731. unsigned
  1732. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  1733. // Build up a buffer of hash code components.
  1734. SmallVector<size_t, 8> HashComponents;
  1735. HashComponents.reserve(MI->getNumOperands() + 1);
  1736. HashComponents.push_back(MI->getOpcode());
  1737. for (const MachineOperand &MO : MI->operands()) {
  1738. if (MO.isReg() && MO.isDef() &&
  1739. TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1740. continue; // Skip virtual register defs.
  1741. HashComponents.push_back(hash_value(MO));
  1742. }
  1743. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  1744. }
  1745. void MachineInstr::emitError(StringRef Msg) const {
  1746. // Find the source location cookie.
  1747. unsigned LocCookie = 0;
  1748. const MDNode *LocMD = nullptr;
  1749. for (unsigned i = getNumOperands(); i != 0; --i) {
  1750. if (getOperand(i-1).isMetadata() &&
  1751. (LocMD = getOperand(i-1).getMetadata()) &&
  1752. LocMD->getNumOperands() != 0) {
  1753. if (const ConstantInt *CI =
  1754. mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
  1755. LocCookie = CI->getZExtValue();
  1756. break;
  1757. }
  1758. }
  1759. }
  1760. if (const MachineBasicBlock *MBB = getParent())
  1761. if (const MachineFunction *MF = MBB->getParent())
  1762. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  1763. report_fatal_error(Msg);
  1764. }
  1765. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1766. const MCInstrDesc &MCID, bool IsIndirect,
  1767. unsigned Reg, const MDNode *Variable,
  1768. const MDNode *Expr) {
  1769. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1770. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1771. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1772. "Expected inlined-at fields to agree");
  1773. auto MIB = BuildMI(MF, DL, MCID).addReg(Reg, RegState::Debug);
  1774. if (IsIndirect)
  1775. MIB.addImm(0U);
  1776. else
  1777. MIB.addReg(0U, RegState::Debug);
  1778. return MIB.addMetadata(Variable).addMetadata(Expr);
  1779. }
  1780. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  1781. const MCInstrDesc &MCID, bool IsIndirect,
  1782. MachineOperand &MO, const MDNode *Variable,
  1783. const MDNode *Expr) {
  1784. assert(isa<DILocalVariable>(Variable) && "not a variable");
  1785. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  1786. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  1787. "Expected inlined-at fields to agree");
  1788. if (MO.isReg())
  1789. return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr);
  1790. auto MIB = BuildMI(MF, DL, MCID).add(MO);
  1791. if (IsIndirect)
  1792. MIB.addImm(0U);
  1793. else
  1794. MIB.addReg(0U, RegState::Debug);
  1795. return MIB.addMetadata(Variable).addMetadata(Expr);
  1796. }
  1797. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1798. MachineBasicBlock::iterator I,
  1799. const DebugLoc &DL, const MCInstrDesc &MCID,
  1800. bool IsIndirect, unsigned Reg,
  1801. const MDNode *Variable, const MDNode *Expr) {
  1802. MachineFunction &MF = *BB.getParent();
  1803. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
  1804. BB.insert(I, MI);
  1805. return MachineInstrBuilder(MF, MI);
  1806. }
  1807. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  1808. MachineBasicBlock::iterator I,
  1809. const DebugLoc &DL, const MCInstrDesc &MCID,
  1810. bool IsIndirect, MachineOperand &MO,
  1811. const MDNode *Variable, const MDNode *Expr) {
  1812. MachineFunction &MF = *BB.getParent();
  1813. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr);
  1814. BB.insert(I, MI);
  1815. return MachineInstrBuilder(MF, *MI);
  1816. }
  1817. /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
  1818. /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
  1819. static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
  1820. assert(MI.getOperand(0).isReg() && "can't spill non-register");
  1821. assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
  1822. "Expected inlined-at fields to agree");
  1823. const DIExpression *Expr = MI.getDebugExpression();
  1824. if (MI.isIndirectDebugValue()) {
  1825. assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
  1826. Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
  1827. }
  1828. return Expr;
  1829. }
  1830. MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
  1831. MachineBasicBlock::iterator I,
  1832. const MachineInstr &Orig,
  1833. int FrameIndex) {
  1834. const DIExpression *Expr = computeExprForSpill(Orig);
  1835. return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
  1836. .addFrameIndex(FrameIndex)
  1837. .addImm(0U)
  1838. .addMetadata(Orig.getDebugVariable())
  1839. .addMetadata(Expr);
  1840. }
  1841. void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
  1842. const DIExpression *Expr = computeExprForSpill(Orig);
  1843. Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
  1844. Orig.getOperand(1).ChangeToImmediate(0U);
  1845. Orig.getOperand(3).setMetadata(Expr);
  1846. }
  1847. void MachineInstr::collectDebugValues(
  1848. SmallVectorImpl<MachineInstr *> &DbgValues) {
  1849. MachineInstr &MI = *this;
  1850. if (!MI.getOperand(0).isReg())
  1851. return;
  1852. MachineBasicBlock::iterator DI = MI; ++DI;
  1853. for (MachineBasicBlock::iterator DE = MI.getParent()->end();
  1854. DI != DE; ++DI) {
  1855. if (!DI->isDebugValue())
  1856. return;
  1857. if (DI->getOperand(0).isReg() &&
  1858. DI->getOperand(0).getReg() == MI.getOperand(0).getReg())
  1859. DbgValues.push_back(&*DI);
  1860. }
  1861. }
  1862. void MachineInstr::changeDebugValuesDefReg(unsigned Reg) {
  1863. // Collect matching debug values.
  1864. SmallVector<MachineInstr *, 2> DbgValues;
  1865. collectDebugValues(DbgValues);
  1866. // Propagate Reg to debug value instructions.
  1867. for (auto *DBI : DbgValues)
  1868. DBI->getOperand(0).setReg(Reg);
  1869. }
  1870. using MMOList = SmallVector<const MachineMemOperand *, 2>;
  1871. static unsigned getSpillSlotSize(MMOList &Accesses,
  1872. const MachineFrameInfo &MFI) {
  1873. unsigned Size = 0;
  1874. for (auto A : Accesses)
  1875. if (MFI.isSpillSlotObjectIndex(
  1876. cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
  1877. ->getFrameIndex()))
  1878. Size += A->getSize();
  1879. return Size;
  1880. }
  1881. Optional<unsigned>
  1882. MachineInstr::getSpillSize(const TargetInstrInfo *TII) const {
  1883. int FI;
  1884. if (TII->isStoreToStackSlotPostFE(*this, FI)) {
  1885. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  1886. if (MFI.isSpillSlotObjectIndex(FI))
  1887. return (*memoperands_begin())->getSize();
  1888. }
  1889. return None;
  1890. }
  1891. Optional<unsigned>
  1892. MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const {
  1893. MMOList Accesses;
  1894. if (TII->hasStoreToStackSlot(*this, Accesses))
  1895. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  1896. return None;
  1897. }
  1898. Optional<unsigned>
  1899. MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const {
  1900. int FI;
  1901. if (TII->isLoadFromStackSlotPostFE(*this, FI)) {
  1902. const MachineFrameInfo &MFI = getMF()->getFrameInfo();
  1903. if (MFI.isSpillSlotObjectIndex(FI))
  1904. return (*memoperands_begin())->getSize();
  1905. }
  1906. return None;
  1907. }
  1908. Optional<unsigned>
  1909. MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const {
  1910. MMOList Accesses;
  1911. if (TII->hasLoadFromStackSlot(*this, Accesses))
  1912. return getSpillSlotSize(Accesses, getMF()->getFrameInfo());
  1913. return None;
  1914. }