MachineInstr.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447
  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/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/MachineFunction.h"
  28. #include "llvm/CodeGen/MachineInstrBuilder.h"
  29. #include "llvm/CodeGen/MachineInstrBundle.h"
  30. #include "llvm/CodeGen/MachineMemOperand.h"
  31. #include "llvm/CodeGen/MachineModuleInfo.h"
  32. #include "llvm/CodeGen/MachineOperand.h"
  33. #include "llvm/CodeGen/MachineRegisterInfo.h"
  34. #include "llvm/CodeGen/PseudoSourceValue.h"
  35. #include "llvm/IR/Constants.h"
  36. #include "llvm/IR/DebugInfoMetadata.h"
  37. #include "llvm/IR/DebugLoc.h"
  38. #include "llvm/IR/DerivedTypes.h"
  39. #include "llvm/IR/Function.h"
  40. #include "llvm/IR/InlineAsm.h"
  41. #include "llvm/IR/InstrTypes.h"
  42. #include "llvm/IR/Intrinsics.h"
  43. #include "llvm/IR/LLVMContext.h"
  44. #include "llvm/IR/Metadata.h"
  45. #include "llvm/IR/Module.h"
  46. #include "llvm/IR/ModuleSlotTracker.h"
  47. #include "llvm/IR/Type.h"
  48. #include "llvm/IR/Value.h"
  49. #include "llvm/MC/MCInstrDesc.h"
  50. #include "llvm/MC/MCRegisterInfo.h"
  51. #include "llvm/MC/MCSymbol.h"
  52. #include "llvm/Support/Casting.h"
  53. #include "llvm/Support/CommandLine.h"
  54. #include "llvm/Support/Compiler.h"
  55. #include "llvm/Support/Debug.h"
  56. #include "llvm/Support/ErrorHandling.h"
  57. #include "llvm/Support/LowLevelTypeImpl.h"
  58. #include "llvm/Support/MathExtras.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include "llvm/Target/TargetInstrInfo.h"
  61. #include "llvm/Target/TargetIntrinsicInfo.h"
  62. #include "llvm/Target/TargetMachine.h"
  63. #include "llvm/Target/TargetRegisterInfo.h"
  64. #include "llvm/Target/TargetSubtargetInfo.h"
  65. #include <algorithm>
  66. #include <cassert>
  67. #include <cstddef>
  68. #include <cstdint>
  69. #include <cstring>
  70. #include <iterator>
  71. #include <utility>
  72. using namespace llvm;
  73. static cl::opt<int> PrintRegMaskNumRegs(
  74. "print-regmask-num-regs",
  75. cl::desc("Number of registers to limit to when "
  76. "printing regmask operands in IR dumps. "
  77. "unlimited = -1"),
  78. cl::init(32), cl::Hidden);
  79. //===----------------------------------------------------------------------===//
  80. // MachineOperand Implementation
  81. //===----------------------------------------------------------------------===//
  82. void MachineOperand::setReg(unsigned Reg) {
  83. if (getReg() == Reg) return; // No change.
  84. // Otherwise, we have to change the register. If this operand is embedded
  85. // into a machine function, we need to update the old and new register's
  86. // use/def lists.
  87. if (MachineInstr *MI = getParent())
  88. if (MachineBasicBlock *MBB = MI->getParent())
  89. if (MachineFunction *MF = MBB->getParent()) {
  90. MachineRegisterInfo &MRI = MF->getRegInfo();
  91. MRI.removeRegOperandFromUseList(this);
  92. SmallContents.RegNo = Reg;
  93. MRI.addRegOperandToUseList(this);
  94. return;
  95. }
  96. // Otherwise, just change the register, no problem. :)
  97. SmallContents.RegNo = Reg;
  98. }
  99. void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
  100. const TargetRegisterInfo &TRI) {
  101. assert(TargetRegisterInfo::isVirtualRegister(Reg));
  102. if (SubIdx && getSubReg())
  103. SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
  104. setReg(Reg);
  105. if (SubIdx)
  106. setSubReg(SubIdx);
  107. }
  108. void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
  109. assert(TargetRegisterInfo::isPhysicalRegister(Reg));
  110. if (getSubReg()) {
  111. Reg = TRI.getSubReg(Reg, getSubReg());
  112. // Note that getSubReg() may return 0 if the sub-register doesn't exist.
  113. // That won't happen in legal code.
  114. setSubReg(0);
  115. if (isDef())
  116. setIsUndef(false);
  117. }
  118. setReg(Reg);
  119. }
  120. /// Change a def to a use, or a use to a def.
  121. void MachineOperand::setIsDef(bool Val) {
  122. assert(isReg() && "Wrong MachineOperand accessor");
  123. assert((!Val || !isDebug()) && "Marking a debug operation as def");
  124. if (IsDef == Val)
  125. return;
  126. // MRI may keep uses and defs in different list positions.
  127. if (MachineInstr *MI = getParent())
  128. if (MachineBasicBlock *MBB = MI->getParent())
  129. if (MachineFunction *MF = MBB->getParent()) {
  130. MachineRegisterInfo &MRI = MF->getRegInfo();
  131. MRI.removeRegOperandFromUseList(this);
  132. IsDef = Val;
  133. MRI.addRegOperandToUseList(this);
  134. return;
  135. }
  136. IsDef = Val;
  137. }
  138. // If this operand is currently a register operand, and if this is in a
  139. // function, deregister the operand from the register's use/def list.
  140. void MachineOperand::removeRegFromUses() {
  141. if (!isReg() || !isOnRegUseList())
  142. return;
  143. if (MachineInstr *MI = getParent()) {
  144. if (MachineBasicBlock *MBB = MI->getParent()) {
  145. if (MachineFunction *MF = MBB->getParent())
  146. MF->getRegInfo().removeRegOperandFromUseList(this);
  147. }
  148. }
  149. }
  150. /// ChangeToImmediate - Replace this operand with a new immediate operand of
  151. /// the specified value. If an operand is known to be an immediate already,
  152. /// the setImm method should be used.
  153. void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
  154. assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
  155. removeRegFromUses();
  156. OpKind = MO_Immediate;
  157. Contents.ImmVal = ImmVal;
  158. }
  159. void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
  160. assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
  161. removeRegFromUses();
  162. OpKind = MO_FPImmediate;
  163. Contents.CFP = FPImm;
  164. }
  165. void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) {
  166. assert((!isReg() || !isTied()) &&
  167. "Cannot change a tied operand into an external symbol");
  168. removeRegFromUses();
  169. OpKind = MO_ExternalSymbol;
  170. Contents.OffsetedInfo.Val.SymbolName = SymName;
  171. setOffset(0); // Offset is always 0.
  172. setTargetFlags(TargetFlags);
  173. }
  174. void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
  175. assert((!isReg() || !isTied()) &&
  176. "Cannot change a tied operand into an MCSymbol");
  177. removeRegFromUses();
  178. OpKind = MO_MCSymbol;
  179. Contents.Sym = Sym;
  180. }
  181. void MachineOperand::ChangeToFrameIndex(int Idx) {
  182. assert((!isReg() || !isTied()) &&
  183. "Cannot change a tied operand into a FrameIndex");
  184. removeRegFromUses();
  185. OpKind = MO_FrameIndex;
  186. setIndex(Idx);
  187. }
  188. void MachineOperand::ChangeToTargetIndex(unsigned Idx, int64_t Offset,
  189. unsigned char TargetFlags) {
  190. assert((!isReg() || !isTied()) &&
  191. "Cannot change a tied operand into a FrameIndex");
  192. removeRegFromUses();
  193. OpKind = MO_TargetIndex;
  194. setIndex(Idx);
  195. setOffset(Offset);
  196. setTargetFlags(TargetFlags);
  197. }
  198. /// ChangeToRegister - Replace this operand with a new register operand of
  199. /// the specified value. If an operand is known to be an register already,
  200. /// the setReg method should be used.
  201. void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
  202. bool isKill, bool isDead, bool isUndef,
  203. bool isDebug) {
  204. MachineRegisterInfo *RegInfo = nullptr;
  205. if (MachineInstr *MI = getParent())
  206. if (MachineBasicBlock *MBB = MI->getParent())
  207. if (MachineFunction *MF = MBB->getParent())
  208. RegInfo = &MF->getRegInfo();
  209. // If this operand is already a register operand, remove it from the
  210. // register's use/def lists.
  211. bool WasReg = isReg();
  212. if (RegInfo && WasReg)
  213. RegInfo->removeRegOperandFromUseList(this);
  214. // Change this to a register and set the reg#.
  215. OpKind = MO_Register;
  216. SmallContents.RegNo = Reg;
  217. SubReg_TargetFlags = 0;
  218. IsDef = isDef;
  219. IsImp = isImp;
  220. IsKill = isKill;
  221. IsDead = isDead;
  222. IsUndef = isUndef;
  223. IsInternalRead = false;
  224. IsEarlyClobber = false;
  225. IsDebug = isDebug;
  226. // Ensure isOnRegUseList() returns false.
  227. Contents.Reg.Prev = nullptr;
  228. // Preserve the tie when the operand was already a register.
  229. if (!WasReg)
  230. TiedTo = 0;
  231. // If this operand is embedded in a function, add the operand to the
  232. // register's use/def list.
  233. if (RegInfo)
  234. RegInfo->addRegOperandToUseList(this);
  235. }
  236. /// isIdenticalTo - Return true if this operand is identical to the specified
  237. /// operand. Note that this should stay in sync with the hash_value overload
  238. /// below.
  239. bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
  240. if (getType() != Other.getType() ||
  241. getTargetFlags() != Other.getTargetFlags())
  242. return false;
  243. switch (getType()) {
  244. case MachineOperand::MO_Register:
  245. return getReg() == Other.getReg() && isDef() == Other.isDef() &&
  246. getSubReg() == Other.getSubReg();
  247. case MachineOperand::MO_Immediate:
  248. return getImm() == Other.getImm();
  249. case MachineOperand::MO_CImmediate:
  250. return getCImm() == Other.getCImm();
  251. case MachineOperand::MO_FPImmediate:
  252. return getFPImm() == Other.getFPImm();
  253. case MachineOperand::MO_MachineBasicBlock:
  254. return getMBB() == Other.getMBB();
  255. case MachineOperand::MO_FrameIndex:
  256. return getIndex() == Other.getIndex();
  257. case MachineOperand::MO_ConstantPoolIndex:
  258. case MachineOperand::MO_TargetIndex:
  259. return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
  260. case MachineOperand::MO_JumpTableIndex:
  261. return getIndex() == Other.getIndex();
  262. case MachineOperand::MO_GlobalAddress:
  263. return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
  264. case MachineOperand::MO_ExternalSymbol:
  265. return strcmp(getSymbolName(), Other.getSymbolName()) == 0 &&
  266. getOffset() == Other.getOffset();
  267. case MachineOperand::MO_BlockAddress:
  268. return getBlockAddress() == Other.getBlockAddress() &&
  269. getOffset() == Other.getOffset();
  270. case MachineOperand::MO_RegisterMask:
  271. case MachineOperand::MO_RegisterLiveOut: {
  272. // Shallow compare of the two RegMasks
  273. const uint32_t *RegMask = getRegMask();
  274. const uint32_t *OtherRegMask = Other.getRegMask();
  275. if (RegMask == OtherRegMask)
  276. return true;
  277. // Calculate the size of the RegMask
  278. const MachineFunction *MF = getParent()->getMF();
  279. const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
  280. unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
  281. // Deep compare of the two RegMasks
  282. return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
  283. }
  284. case MachineOperand::MO_MCSymbol:
  285. return getMCSymbol() == Other.getMCSymbol();
  286. case MachineOperand::MO_CFIIndex:
  287. return getCFIIndex() == Other.getCFIIndex();
  288. case MachineOperand::MO_Metadata:
  289. return getMetadata() == Other.getMetadata();
  290. case MachineOperand::MO_IntrinsicID:
  291. return getIntrinsicID() == Other.getIntrinsicID();
  292. case MachineOperand::MO_Predicate:
  293. return getPredicate() == Other.getPredicate();
  294. }
  295. llvm_unreachable("Invalid machine operand type");
  296. }
  297. // Note: this must stay exactly in sync with isIdenticalTo above.
  298. hash_code llvm::hash_value(const MachineOperand &MO) {
  299. switch (MO.getType()) {
  300. case MachineOperand::MO_Register:
  301. // Register operands don't have target flags.
  302. return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
  303. case MachineOperand::MO_Immediate:
  304. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
  305. case MachineOperand::MO_CImmediate:
  306. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
  307. case MachineOperand::MO_FPImmediate:
  308. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
  309. case MachineOperand::MO_MachineBasicBlock:
  310. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
  311. case MachineOperand::MO_FrameIndex:
  312. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
  313. case MachineOperand::MO_ConstantPoolIndex:
  314. case MachineOperand::MO_TargetIndex:
  315. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
  316. MO.getOffset());
  317. case MachineOperand::MO_JumpTableIndex:
  318. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
  319. case MachineOperand::MO_ExternalSymbol:
  320. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
  321. MO.getSymbolName());
  322. case MachineOperand::MO_GlobalAddress:
  323. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
  324. MO.getOffset());
  325. case MachineOperand::MO_BlockAddress:
  326. return hash_combine(MO.getType(), MO.getTargetFlags(),
  327. MO.getBlockAddress(), MO.getOffset());
  328. case MachineOperand::MO_RegisterMask:
  329. case MachineOperand::MO_RegisterLiveOut:
  330. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
  331. case MachineOperand::MO_Metadata:
  332. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
  333. case MachineOperand::MO_MCSymbol:
  334. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
  335. case MachineOperand::MO_CFIIndex:
  336. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
  337. case MachineOperand::MO_IntrinsicID:
  338. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
  339. case MachineOperand::MO_Predicate:
  340. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
  341. }
  342. llvm_unreachable("Invalid machine operand type");
  343. }
  344. void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
  345. const TargetIntrinsicInfo *IntrinsicInfo) const {
  346. ModuleSlotTracker DummyMST(nullptr);
  347. print(OS, DummyMST, TRI, IntrinsicInfo);
  348. }
  349. void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
  350. const TargetRegisterInfo *TRI,
  351. const TargetIntrinsicInfo *IntrinsicInfo) const {
  352. switch (getType()) {
  353. case MachineOperand::MO_Register:
  354. OS << PrintReg(getReg(), TRI, getSubReg());
  355. if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
  356. isInternalRead() || isEarlyClobber() || isTied()) {
  357. OS << '<';
  358. bool NeedComma = false;
  359. if (isDef()) {
  360. if (NeedComma) OS << ',';
  361. if (isEarlyClobber())
  362. OS << "earlyclobber,";
  363. if (isImplicit())
  364. OS << "imp-";
  365. OS << "def";
  366. NeedComma = true;
  367. // <def,read-undef> only makes sense when getSubReg() is set.
  368. // Don't clutter the output otherwise.
  369. if (isUndef() && getSubReg())
  370. OS << ",read-undef";
  371. } else if (isImplicit()) {
  372. OS << "imp-use";
  373. NeedComma = true;
  374. }
  375. if (isKill()) {
  376. if (NeedComma) OS << ',';
  377. OS << "kill";
  378. NeedComma = true;
  379. }
  380. if (isDead()) {
  381. if (NeedComma) OS << ',';
  382. OS << "dead";
  383. NeedComma = true;
  384. }
  385. if (isUndef() && isUse()) {
  386. if (NeedComma) OS << ',';
  387. OS << "undef";
  388. NeedComma = true;
  389. }
  390. if (isInternalRead()) {
  391. if (NeedComma) OS << ',';
  392. OS << "internal";
  393. NeedComma = true;
  394. }
  395. if (isTied()) {
  396. if (NeedComma) OS << ',';
  397. OS << "tied";
  398. if (TiedTo != 15)
  399. OS << unsigned(TiedTo - 1);
  400. }
  401. OS << '>';
  402. }
  403. break;
  404. case MachineOperand::MO_Immediate:
  405. OS << getImm();
  406. break;
  407. case MachineOperand::MO_CImmediate:
  408. getCImm()->getValue().print(OS, false);
  409. break;
  410. case MachineOperand::MO_FPImmediate:
  411. if (getFPImm()->getType()->isFloatTy()) {
  412. OS << getFPImm()->getValueAPF().convertToFloat();
  413. } else if (getFPImm()->getType()->isHalfTy()) {
  414. APFloat APF = getFPImm()->getValueAPF();
  415. bool Unused;
  416. APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &Unused);
  417. OS << "half " << APF.convertToFloat();
  418. } else if (getFPImm()->getType()->isFP128Ty()) {
  419. APFloat APF = getFPImm()->getValueAPF();
  420. SmallString<16> Str;
  421. getFPImm()->getValueAPF().toString(Str);
  422. OS << "quad " << Str;
  423. } else if (getFPImm()->getType()->isX86_FP80Ty()) {
  424. APFloat APF = getFPImm()->getValueAPF();
  425. OS << "x86_fp80 0xK";
  426. APInt API = APF.bitcastToAPInt();
  427. OS << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
  428. /*Upper=*/true);
  429. OS << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
  430. /*Upper=*/true);
  431. } else {
  432. OS << getFPImm()->getValueAPF().convertToDouble();
  433. }
  434. break;
  435. case MachineOperand::MO_MachineBasicBlock:
  436. OS << "<BB#" << getMBB()->getNumber() << ">";
  437. break;
  438. case MachineOperand::MO_FrameIndex:
  439. OS << "<fi#" << getIndex() << '>';
  440. break;
  441. case MachineOperand::MO_ConstantPoolIndex:
  442. OS << "<cp#" << getIndex();
  443. if (getOffset()) OS << "+" << getOffset();
  444. OS << '>';
  445. break;
  446. case MachineOperand::MO_TargetIndex:
  447. OS << "<ti#" << getIndex();
  448. if (getOffset()) OS << "+" << getOffset();
  449. OS << '>';
  450. break;
  451. case MachineOperand::MO_JumpTableIndex:
  452. OS << "<jt#" << getIndex() << '>';
  453. break;
  454. case MachineOperand::MO_GlobalAddress:
  455. OS << "<ga:";
  456. getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
  457. if (getOffset()) OS << "+" << getOffset();
  458. OS << '>';
  459. break;
  460. case MachineOperand::MO_ExternalSymbol:
  461. OS << "<es:" << getSymbolName();
  462. if (getOffset()) OS << "+" << getOffset();
  463. OS << '>';
  464. break;
  465. case MachineOperand::MO_BlockAddress:
  466. OS << '<';
  467. getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
  468. if (getOffset()) OS << "+" << getOffset();
  469. OS << '>';
  470. break;
  471. case MachineOperand::MO_RegisterMask: {
  472. unsigned NumRegsInMask = 0;
  473. unsigned NumRegsEmitted = 0;
  474. OS << "<regmask";
  475. for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
  476. unsigned MaskWord = i / 32;
  477. unsigned MaskBit = i % 32;
  478. if (getRegMask()[MaskWord] & (1 << MaskBit)) {
  479. if (PrintRegMaskNumRegs < 0 ||
  480. NumRegsEmitted <= static_cast<unsigned>(PrintRegMaskNumRegs)) {
  481. OS << " " << PrintReg(i, TRI);
  482. NumRegsEmitted++;
  483. }
  484. NumRegsInMask++;
  485. }
  486. }
  487. if (NumRegsEmitted != NumRegsInMask)
  488. OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
  489. OS << ">";
  490. break;
  491. }
  492. case MachineOperand::MO_RegisterLiveOut:
  493. OS << "<regliveout>";
  494. break;
  495. case MachineOperand::MO_Metadata:
  496. OS << '<';
  497. getMetadata()->printAsOperand(OS, MST);
  498. OS << '>';
  499. break;
  500. case MachineOperand::MO_MCSymbol:
  501. OS << "<MCSym=" << *getMCSymbol() << '>';
  502. break;
  503. case MachineOperand::MO_CFIIndex:
  504. OS << "<call frame instruction>";
  505. break;
  506. case MachineOperand::MO_IntrinsicID: {
  507. Intrinsic::ID ID = getIntrinsicID();
  508. if (ID < Intrinsic::num_intrinsics)
  509. OS << "<intrinsic:@" << Intrinsic::getName(ID, None) << '>';
  510. else if (IntrinsicInfo)
  511. OS << "<intrinsic:@" << IntrinsicInfo->getName(ID) << '>';
  512. else
  513. OS << "<intrinsic:" << ID << '>';
  514. break;
  515. }
  516. case MachineOperand::MO_Predicate: {
  517. auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
  518. OS << '<' << (CmpInst::isIntPredicate(Pred) ? "intpred" : "floatpred")
  519. << CmpInst::getPredicateName(Pred) << '>';
  520. break;
  521. }
  522. }
  523. if (unsigned TF = getTargetFlags())
  524. OS << "[TF=" << TF << ']';
  525. }
  526. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  527. LLVM_DUMP_METHOD void MachineOperand::dump() const {
  528. dbgs() << *this << '\n';
  529. }
  530. #endif
  531. //===----------------------------------------------------------------------===//
  532. // MachineMemOperand Implementation
  533. //===----------------------------------------------------------------------===//
  534. /// getAddrSpace - Return the LLVM IR address space number that this pointer
  535. /// points into.
  536. unsigned MachinePointerInfo::getAddrSpace() const {
  537. if (V.isNull()) return 0;
  538. if (V.is<const PseudoSourceValue*>())
  539. return V.get<const PseudoSourceValue*>()->getAddressSpace();
  540. return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
  541. }
  542. /// isDereferenceable - Return true if V is always dereferenceable for
  543. /// Offset + Size byte.
  544. bool MachinePointerInfo::isDereferenceable(unsigned Size, LLVMContext &C,
  545. const DataLayout &DL) const {
  546. if (!V.is<const Value*>())
  547. return false;
  548. const Value *BasePtr = V.get<const Value*>();
  549. if (BasePtr == nullptr)
  550. return false;
  551. return isDereferenceableAndAlignedPointer(
  552. BasePtr, 1, APInt(DL.getPointerSizeInBits(), Offset + Size), DL);
  553. }
  554. /// getConstantPool - Return a MachinePointerInfo record that refers to the
  555. /// constant pool.
  556. MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
  557. return MachinePointerInfo(MF.getPSVManager().getConstantPool());
  558. }
  559. /// getFixedStack - Return a MachinePointerInfo record that refers to the
  560. /// the specified FrameIndex.
  561. MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
  562. int FI, int64_t Offset) {
  563. return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
  564. }
  565. MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
  566. return MachinePointerInfo(MF.getPSVManager().getJumpTable());
  567. }
  568. MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
  569. return MachinePointerInfo(MF.getPSVManager().getGOT());
  570. }
  571. MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
  572. int64_t Offset,
  573. uint8_t ID) {
  574. return MachinePointerInfo(MF.getPSVManager().getStack(), Offset,ID);
  575. }
  576. MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
  577. uint64_t s, unsigned int a,
  578. const AAMDNodes &AAInfo,
  579. const MDNode *Ranges,
  580. SyncScope::ID SSID,
  581. AtomicOrdering Ordering,
  582. AtomicOrdering FailureOrdering)
  583. : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
  584. AAInfo(AAInfo), Ranges(Ranges) {
  585. assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
  586. isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
  587. "invalid pointer value");
  588. assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
  589. assert((isLoad() || isStore()) && "Not a load/store!");
  590. AtomicInfo.SSID = static_cast<unsigned>(SSID);
  591. assert(getSyncScopeID() == SSID && "Value truncated");
  592. AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
  593. assert(getOrdering() == Ordering && "Value truncated");
  594. AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
  595. assert(getFailureOrdering() == FailureOrdering && "Value truncated");
  596. }
  597. /// Profile - Gather unique data for the object.
  598. ///
  599. void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
  600. ID.AddInteger(getOffset());
  601. ID.AddInteger(Size);
  602. ID.AddPointer(getOpaqueValue());
  603. ID.AddInteger(getFlags());
  604. ID.AddInteger(getBaseAlignment());
  605. }
  606. void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
  607. // The Value and Offset may differ due to CSE. But the flags and size
  608. // should be the same.
  609. assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
  610. assert(MMO->getSize() == getSize() && "Size mismatch!");
  611. if (MMO->getBaseAlignment() >= getBaseAlignment()) {
  612. // Update the alignment value.
  613. BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
  614. // Also update the base and offset, because the new alignment may
  615. // not be applicable with the old ones.
  616. PtrInfo = MMO->PtrInfo;
  617. }
  618. }
  619. /// getAlignment - Return the minimum known alignment in bytes of the
  620. /// actual memory reference.
  621. uint64_t MachineMemOperand::getAlignment() const {
  622. return MinAlign(getBaseAlignment(), getOffset());
  623. }
  624. void MachineMemOperand::print(raw_ostream &OS) const {
  625. ModuleSlotTracker DummyMST(nullptr);
  626. print(OS, DummyMST);
  627. }
  628. void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
  629. assert((isLoad() || isStore()) &&
  630. "SV has to be a load, store or both.");
  631. if (isVolatile())
  632. OS << "Volatile ";
  633. if (isLoad())
  634. OS << "LD";
  635. if (isStore())
  636. OS << "ST";
  637. OS << getSize();
  638. // Print the address information.
  639. OS << "[";
  640. if (const Value *V = getValue())
  641. V->printAsOperand(OS, /*PrintType=*/false, MST);
  642. else if (const PseudoSourceValue *PSV = getPseudoValue())
  643. PSV->printCustom(OS);
  644. else
  645. OS << "<unknown>";
  646. unsigned AS = getAddrSpace();
  647. if (AS != 0)
  648. OS << "(addrspace=" << AS << ')';
  649. // If the alignment of the memory reference itself differs from the alignment
  650. // of the base pointer, print the base alignment explicitly, next to the base
  651. // pointer.
  652. if (getBaseAlignment() != getAlignment())
  653. OS << "(align=" << getBaseAlignment() << ")";
  654. if (getOffset() != 0)
  655. OS << "+" << getOffset();
  656. OS << "]";
  657. // Print the alignment of the reference.
  658. if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
  659. OS << "(align=" << getAlignment() << ")";
  660. // Print TBAA info.
  661. if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
  662. OS << "(tbaa=";
  663. if (TBAAInfo->getNumOperands() > 0)
  664. TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
  665. else
  666. OS << "<unknown>";
  667. OS << ")";
  668. }
  669. // Print AA scope info.
  670. if (const MDNode *ScopeInfo = getAAInfo().Scope) {
  671. OS << "(alias.scope=";
  672. if (ScopeInfo->getNumOperands() > 0)
  673. for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
  674. ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
  675. if (i != ie-1)
  676. OS << ",";
  677. }
  678. else
  679. OS << "<unknown>";
  680. OS << ")";
  681. }
  682. // Print AA noalias scope info.
  683. if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
  684. OS << "(noalias=";
  685. if (NoAliasInfo->getNumOperands() > 0)
  686. for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
  687. NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
  688. if (i != ie-1)
  689. OS << ",";
  690. }
  691. else
  692. OS << "<unknown>";
  693. OS << ")";
  694. }
  695. if (isNonTemporal())
  696. OS << "(nontemporal)";
  697. if (isDereferenceable())
  698. OS << "(dereferenceable)";
  699. if (isInvariant())
  700. OS << "(invariant)";
  701. if (getFlags() & MOTargetFlag1)
  702. OS << "(flag1)";
  703. if (getFlags() & MOTargetFlag2)
  704. OS << "(flag2)";
  705. if (getFlags() & MOTargetFlag3)
  706. OS << "(flag3)";
  707. }
  708. //===----------------------------------------------------------------------===//
  709. // MachineInstr Implementation
  710. //===----------------------------------------------------------------------===//
  711. void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
  712. if (MCID->ImplicitDefs)
  713. for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
  714. ++ImpDefs)
  715. addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
  716. if (MCID->ImplicitUses)
  717. for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
  718. ++ImpUses)
  719. addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
  720. }
  721. /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
  722. /// implicit operands. It reserves space for the number of operands specified by
  723. /// the MCInstrDesc.
  724. MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
  725. DebugLoc dl, bool NoImp)
  726. : MCID(&tid), debugLoc(std::move(dl)) {
  727. assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
  728. // Reserve space for the expected number of operands.
  729. if (unsigned NumOps = MCID->getNumOperands() +
  730. MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
  731. CapOperands = OperandCapacity::get(NumOps);
  732. Operands = MF.allocateOperandArray(CapOperands);
  733. }
  734. if (!NoImp)
  735. addImplicitDefUseOperands(MF);
  736. }
  737. /// MachineInstr ctor - Copies MachineInstr arg exactly
  738. ///
  739. MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
  740. : MCID(&MI.getDesc()), NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
  741. debugLoc(MI.getDebugLoc()) {
  742. assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
  743. CapOperands = OperandCapacity::get(MI.getNumOperands());
  744. Operands = MF.allocateOperandArray(CapOperands);
  745. // Copy operands.
  746. for (const MachineOperand &MO : MI.operands())
  747. addOperand(MF, MO);
  748. // Copy all the sensible flags.
  749. setFlags(MI.Flags);
  750. }
  751. /// getRegInfo - If this instruction is embedded into a MachineFunction,
  752. /// return the MachineRegisterInfo object for the current function, otherwise
  753. /// return null.
  754. MachineRegisterInfo *MachineInstr::getRegInfo() {
  755. if (MachineBasicBlock *MBB = getParent())
  756. return &MBB->getParent()->getRegInfo();
  757. return nullptr;
  758. }
  759. /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
  760. /// this instruction from their respective use lists. This requires that the
  761. /// operands already be on their use lists.
  762. void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
  763. for (MachineOperand &MO : operands())
  764. if (MO.isReg())
  765. MRI.removeRegOperandFromUseList(&MO);
  766. }
  767. /// AddRegOperandsToUseLists - Add all of the register operands in
  768. /// this instruction from their respective use lists. This requires that the
  769. /// operands not be on their use lists yet.
  770. void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
  771. for (MachineOperand &MO : operands())
  772. if (MO.isReg())
  773. MRI.addRegOperandToUseList(&MO);
  774. }
  775. void MachineInstr::addOperand(const MachineOperand &Op) {
  776. MachineBasicBlock *MBB = getParent();
  777. assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
  778. MachineFunction *MF = MBB->getParent();
  779. assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
  780. addOperand(*MF, Op);
  781. }
  782. /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
  783. /// ranges. If MRI is non-null also update use-def chains.
  784. static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
  785. unsigned NumOps, MachineRegisterInfo *MRI) {
  786. if (MRI)
  787. return MRI->moveOperands(Dst, Src, NumOps);
  788. // MachineOperand is a trivially copyable type so we can just use memmove.
  789. std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
  790. }
  791. /// addOperand - Add the specified operand to the instruction. If it is an
  792. /// implicit operand, it is added to the end of the operand list. If it is
  793. /// an explicit operand it is added at the end of the explicit operand list
  794. /// (before the first implicit operand).
  795. void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
  796. assert(MCID && "Cannot add operands before providing an instr descriptor");
  797. // Check if we're adding one of our existing operands.
  798. if (&Op >= Operands && &Op < Operands + NumOperands) {
  799. // This is unusual: MI->addOperand(MI->getOperand(i)).
  800. // If adding Op requires reallocating or moving existing operands around,
  801. // the Op reference could go stale. Support it by copying Op.
  802. MachineOperand CopyOp(Op);
  803. return addOperand(MF, CopyOp);
  804. }
  805. // Find the insert location for the new operand. Implicit registers go at
  806. // the end, everything else goes before the implicit regs.
  807. //
  808. // FIXME: Allow mixed explicit and implicit operands on inline asm.
  809. // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
  810. // implicit-defs, but they must not be moved around. See the FIXME in
  811. // InstrEmitter.cpp.
  812. unsigned OpNo = getNumOperands();
  813. bool isImpReg = Op.isReg() && Op.isImplicit();
  814. if (!isImpReg && !isInlineAsm()) {
  815. while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
  816. --OpNo;
  817. assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
  818. }
  819. }
  820. #ifndef NDEBUG
  821. bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
  822. // OpNo now points as the desired insertion point. Unless this is a variadic
  823. // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
  824. // RegMask operands go between the explicit and implicit operands.
  825. assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
  826. OpNo < MCID->getNumOperands() || isMetaDataOp) &&
  827. "Trying to add an operand to a machine instr that is already done!");
  828. #endif
  829. MachineRegisterInfo *MRI = getRegInfo();
  830. // Determine if the Operands array needs to be reallocated.
  831. // Save the old capacity and operand array.
  832. OperandCapacity OldCap = CapOperands;
  833. MachineOperand *OldOperands = Operands;
  834. if (!OldOperands || OldCap.getSize() == getNumOperands()) {
  835. CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
  836. Operands = MF.allocateOperandArray(CapOperands);
  837. // Move the operands before the insertion point.
  838. if (OpNo)
  839. moveOperands(Operands, OldOperands, OpNo, MRI);
  840. }
  841. // Move the operands following the insertion point.
  842. if (OpNo != NumOperands)
  843. moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
  844. MRI);
  845. ++NumOperands;
  846. // Deallocate the old operand array.
  847. if (OldOperands != Operands && OldOperands)
  848. MF.deallocateOperandArray(OldCap, OldOperands);
  849. // Copy Op into place. It still needs to be inserted into the MRI use lists.
  850. MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
  851. NewMO->ParentMI = this;
  852. // When adding a register operand, tell MRI about it.
  853. if (NewMO->isReg()) {
  854. // Ensure isOnRegUseList() returns false, regardless of Op's status.
  855. NewMO->Contents.Reg.Prev = nullptr;
  856. // Ignore existing ties. This is not a property that can be copied.
  857. NewMO->TiedTo = 0;
  858. // Add the new operand to MRI, but only for instructions in an MBB.
  859. if (MRI)
  860. MRI->addRegOperandToUseList(NewMO);
  861. // The MCID operand information isn't accurate until we start adding
  862. // explicit operands. The implicit operands are added first, then the
  863. // explicits are inserted before them.
  864. if (!isImpReg) {
  865. // Tie uses to defs as indicated in MCInstrDesc.
  866. if (NewMO->isUse()) {
  867. int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
  868. if (DefIdx != -1)
  869. tieOperands(DefIdx, OpNo);
  870. }
  871. // If the register operand is flagged as early, mark the operand as such.
  872. if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
  873. NewMO->setIsEarlyClobber(true);
  874. }
  875. }
  876. }
  877. /// RemoveOperand - Erase an operand from an instruction, leaving it with one
  878. /// fewer operand than it started with.
  879. ///
  880. void MachineInstr::RemoveOperand(unsigned OpNo) {
  881. assert(OpNo < getNumOperands() && "Invalid operand number");
  882. untieRegOperand(OpNo);
  883. #ifndef NDEBUG
  884. // Moving tied operands would break the ties.
  885. for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
  886. if (Operands[i].isReg())
  887. assert(!Operands[i].isTied() && "Cannot move tied operands");
  888. #endif
  889. MachineRegisterInfo *MRI = getRegInfo();
  890. if (MRI && Operands[OpNo].isReg())
  891. MRI->removeRegOperandFromUseList(Operands + OpNo);
  892. // Don't call the MachineOperand destructor. A lot of this code depends on
  893. // MachineOperand having a trivial destructor anyway, and adding a call here
  894. // wouldn't make it 'destructor-correct'.
  895. if (unsigned N = NumOperands - 1 - OpNo)
  896. moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
  897. --NumOperands;
  898. }
  899. /// addMemOperand - Add a MachineMemOperand to the machine instruction.
  900. /// This function should be used only occasionally. The setMemRefs function
  901. /// is the primary method for setting up a MachineInstr's MemRefs list.
  902. void MachineInstr::addMemOperand(MachineFunction &MF,
  903. MachineMemOperand *MO) {
  904. mmo_iterator OldMemRefs = MemRefs;
  905. unsigned OldNumMemRefs = NumMemRefs;
  906. unsigned NewNum = NumMemRefs + 1;
  907. mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
  908. std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
  909. NewMemRefs[NewNum - 1] = MO;
  910. setMemRefs(NewMemRefs, NewMemRefs + NewNum);
  911. }
  912. /// Check to see if the MMOs pointed to by the two MemRefs arrays are
  913. /// identical.
  914. static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
  915. auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
  916. auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
  917. if ((E1 - I1) != (E2 - I2))
  918. return false;
  919. for (; I1 != E1; ++I1, ++I2) {
  920. if (**I1 != **I2)
  921. return false;
  922. }
  923. return true;
  924. }
  925. std::pair<MachineInstr::mmo_iterator, unsigned>
  926. MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
  927. // If either of the incoming memrefs are empty, we must be conservative and
  928. // treat this as if we've exhausted our space for memrefs and dropped them.
  929. if (memoperands_empty() || Other.memoperands_empty())
  930. return std::make_pair(nullptr, 0);
  931. // If both instructions have identical memrefs, we don't need to merge them.
  932. // Since many instructions have a single memref, and we tend to merge things
  933. // like pairs of loads from the same location, this catches a large number of
  934. // cases in practice.
  935. if (hasIdenticalMMOs(*this, Other))
  936. return std::make_pair(MemRefs, NumMemRefs);
  937. // TODO: consider uniquing elements within the operand lists to reduce
  938. // space usage and fall back to conservative information less often.
  939. size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
  940. // If we don't have enough room to store this many memrefs, be conservative
  941. // and drop them. Otherwise, we'd fail asserts when trying to add them to
  942. // the new instruction.
  943. if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
  944. return std::make_pair(nullptr, 0);
  945. MachineFunction *MF = getMF();
  946. mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
  947. mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
  948. MemBegin);
  949. MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
  950. MemEnd);
  951. assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
  952. "missing memrefs");
  953. return std::make_pair(MemBegin, CombinedNumMemRefs);
  954. }
  955. bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
  956. assert(!isBundledWithPred() && "Must be called on bundle header");
  957. for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
  958. if (MII->getDesc().getFlags() & Mask) {
  959. if (Type == AnyInBundle)
  960. return true;
  961. } else {
  962. if (Type == AllInBundle && !MII->isBundle())
  963. return false;
  964. }
  965. // This was the last instruction in the bundle.
  966. if (!MII->isBundledWithSucc())
  967. return Type == AllInBundle;
  968. }
  969. }
  970. bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
  971. MICheckType Check) const {
  972. // If opcodes or number of operands are not the same then the two
  973. // instructions are obviously not identical.
  974. if (Other.getOpcode() != getOpcode() ||
  975. Other.getNumOperands() != getNumOperands())
  976. return false;
  977. if (isBundle()) {
  978. // We have passed the test above that both instructions have the same
  979. // opcode, so we know that both instructions are bundles here. Let's compare
  980. // MIs inside the bundle.
  981. assert(Other.isBundle() && "Expected that both instructions are bundles.");
  982. MachineBasicBlock::const_instr_iterator I1 = getIterator();
  983. MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
  984. // Loop until we analysed the last intruction inside at least one of the
  985. // bundles.
  986. while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
  987. ++I1;
  988. ++I2;
  989. if (!I1->isIdenticalTo(*I2, Check))
  990. return false;
  991. }
  992. // If we've reached the end of just one of the two bundles, but not both,
  993. // the instructions are not identical.
  994. if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
  995. return false;
  996. }
  997. // Check operands to make sure they match.
  998. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  999. const MachineOperand &MO = getOperand(i);
  1000. const MachineOperand &OMO = Other.getOperand(i);
  1001. if (!MO.isReg()) {
  1002. if (!MO.isIdenticalTo(OMO))
  1003. return false;
  1004. continue;
  1005. }
  1006. // Clients may or may not want to ignore defs when testing for equality.
  1007. // For example, machine CSE pass only cares about finding common
  1008. // subexpressions, so it's safe to ignore virtual register defs.
  1009. if (MO.isDef()) {
  1010. if (Check == IgnoreDefs)
  1011. continue;
  1012. else if (Check == IgnoreVRegDefs) {
  1013. if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
  1014. TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
  1015. if (MO.getReg() != OMO.getReg())
  1016. return false;
  1017. } else {
  1018. if (!MO.isIdenticalTo(OMO))
  1019. return false;
  1020. if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
  1021. return false;
  1022. }
  1023. } else {
  1024. if (!MO.isIdenticalTo(OMO))
  1025. return false;
  1026. if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
  1027. return false;
  1028. }
  1029. }
  1030. // If DebugLoc does not match then two dbg.values are not identical.
  1031. if (isDebugValue())
  1032. if (getDebugLoc() && Other.getDebugLoc() &&
  1033. getDebugLoc() != Other.getDebugLoc())
  1034. return false;
  1035. return true;
  1036. }
  1037. const MachineFunction *MachineInstr::getMF() const {
  1038. return getParent()->getParent();
  1039. }
  1040. MachineInstr *MachineInstr::removeFromParent() {
  1041. assert(getParent() && "Not embedded in a basic block!");
  1042. return getParent()->remove(this);
  1043. }
  1044. MachineInstr *MachineInstr::removeFromBundle() {
  1045. assert(getParent() && "Not embedded in a basic block!");
  1046. return getParent()->remove_instr(this);
  1047. }
  1048. void MachineInstr::eraseFromParent() {
  1049. assert(getParent() && "Not embedded in a basic block!");
  1050. getParent()->erase(this);
  1051. }
  1052. void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
  1053. assert(getParent() && "Not embedded in a basic block!");
  1054. MachineBasicBlock *MBB = getParent();
  1055. MachineFunction *MF = MBB->getParent();
  1056. assert(MF && "Not embedded in a function!");
  1057. MachineInstr *MI = (MachineInstr *)this;
  1058. MachineRegisterInfo &MRI = MF->getRegInfo();
  1059. for (const MachineOperand &MO : MI->operands()) {
  1060. if (!MO.isReg() || !MO.isDef())
  1061. continue;
  1062. unsigned Reg = MO.getReg();
  1063. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  1064. continue;
  1065. MRI.markUsesInDebugValueAsUndef(Reg);
  1066. }
  1067. MI->eraseFromParent();
  1068. }
  1069. void MachineInstr::eraseFromBundle() {
  1070. assert(getParent() && "Not embedded in a basic block!");
  1071. getParent()->erase_instr(this);
  1072. }
  1073. /// getNumExplicitOperands - Returns the number of non-implicit operands.
  1074. ///
  1075. unsigned MachineInstr::getNumExplicitOperands() const {
  1076. unsigned NumOperands = MCID->getNumOperands();
  1077. if (!MCID->isVariadic())
  1078. return NumOperands;
  1079. for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
  1080. const MachineOperand &MO = getOperand(i);
  1081. if (!MO.isReg() || !MO.isImplicit())
  1082. NumOperands++;
  1083. }
  1084. return NumOperands;
  1085. }
  1086. void MachineInstr::bundleWithPred() {
  1087. assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
  1088. setFlag(BundledPred);
  1089. MachineBasicBlock::instr_iterator Pred = getIterator();
  1090. --Pred;
  1091. assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  1092. Pred->setFlag(BundledSucc);
  1093. }
  1094. void MachineInstr::bundleWithSucc() {
  1095. assert(!isBundledWithSucc() && "MI is already bundled with its successor");
  1096. setFlag(BundledSucc);
  1097. MachineBasicBlock::instr_iterator Succ = getIterator();
  1098. ++Succ;
  1099. assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
  1100. Succ->setFlag(BundledPred);
  1101. }
  1102. void MachineInstr::unbundleFromPred() {
  1103. assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
  1104. clearFlag(BundledPred);
  1105. MachineBasicBlock::instr_iterator Pred = getIterator();
  1106. --Pred;
  1107. assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  1108. Pred->clearFlag(BundledSucc);
  1109. }
  1110. void MachineInstr::unbundleFromSucc() {
  1111. assert(isBundledWithSucc() && "MI isn't bundled with its successor");
  1112. clearFlag(BundledSucc);
  1113. MachineBasicBlock::instr_iterator Succ = getIterator();
  1114. ++Succ;
  1115. assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
  1116. Succ->clearFlag(BundledPred);
  1117. }
  1118. bool MachineInstr::isStackAligningInlineAsm() const {
  1119. if (isInlineAsm()) {
  1120. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1121. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1122. return true;
  1123. }
  1124. return false;
  1125. }
  1126. InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
  1127. assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
  1128. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1129. return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
  1130. }
  1131. int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
  1132. unsigned *GroupNo) const {
  1133. assert(isInlineAsm() && "Expected an inline asm instruction");
  1134. assert(OpIdx < getNumOperands() && "OpIdx out of range");
  1135. // Ignore queries about the initial operands.
  1136. if (OpIdx < InlineAsm::MIOp_FirstOperand)
  1137. return -1;
  1138. unsigned Group = 0;
  1139. unsigned NumOps;
  1140. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  1141. i += NumOps) {
  1142. const MachineOperand &FlagMO = getOperand(i);
  1143. // If we reach the implicit register operands, stop looking.
  1144. if (!FlagMO.isImm())
  1145. return -1;
  1146. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  1147. if (i + NumOps > OpIdx) {
  1148. if (GroupNo)
  1149. *GroupNo = Group;
  1150. return i;
  1151. }
  1152. ++Group;
  1153. }
  1154. return -1;
  1155. }
  1156. const DILocalVariable *MachineInstr::getDebugVariable() const {
  1157. assert(isDebugValue() && "not a DBG_VALUE");
  1158. return cast<DILocalVariable>(getOperand(2).getMetadata());
  1159. }
  1160. const DIExpression *MachineInstr::getDebugExpression() const {
  1161. assert(isDebugValue() && "not a DBG_VALUE");
  1162. return cast<DIExpression>(getOperand(3).getMetadata());
  1163. }
  1164. const TargetRegisterClass*
  1165. MachineInstr::getRegClassConstraint(unsigned OpIdx,
  1166. const TargetInstrInfo *TII,
  1167. const TargetRegisterInfo *TRI) const {
  1168. assert(getParent() && "Can't have an MBB reference here!");
  1169. assert(getMF() && "Can't have an MF reference here!");
  1170. const MachineFunction &MF = *getMF();
  1171. // Most opcodes have fixed constraints in their MCInstrDesc.
  1172. if (!isInlineAsm())
  1173. return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
  1174. if (!getOperand(OpIdx).isReg())
  1175. return nullptr;
  1176. // For tied uses on inline asm, get the constraint from the def.
  1177. unsigned DefIdx;
  1178. if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
  1179. OpIdx = DefIdx;
  1180. // Inline asm stores register class constraints in the flag word.
  1181. int FlagIdx = findInlineAsmFlagIdx(OpIdx);
  1182. if (FlagIdx < 0)
  1183. return nullptr;
  1184. unsigned Flag = getOperand(FlagIdx).getImm();
  1185. unsigned RCID;
  1186. if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
  1187. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
  1188. InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
  1189. InlineAsm::hasRegClassConstraint(Flag, RCID))
  1190. return TRI->getRegClass(RCID);
  1191. // Assume that all registers in a memory operand are pointers.
  1192. if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
  1193. return TRI->getPointerRegClass(MF);
  1194. return nullptr;
  1195. }
  1196. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
  1197. unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
  1198. const TargetRegisterInfo *TRI, bool ExploreBundle) const {
  1199. // Check every operands inside the bundle if we have
  1200. // been asked to.
  1201. if (ExploreBundle)
  1202. for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
  1203. ++OpndIt)
  1204. CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
  1205. OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
  1206. else
  1207. // Otherwise, just check the current operands.
  1208. for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
  1209. CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
  1210. return CurRC;
  1211. }
  1212. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
  1213. unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
  1214. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  1215. assert(CurRC && "Invalid initial register class");
  1216. // Check if Reg is constrained by some of its use/def from MI.
  1217. const MachineOperand &MO = getOperand(OpIdx);
  1218. if (!MO.isReg() || MO.getReg() != Reg)
  1219. return CurRC;
  1220. // If yes, accumulate the constraints through the operand.
  1221. return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
  1222. }
  1223. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
  1224. unsigned OpIdx, const TargetRegisterClass *CurRC,
  1225. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  1226. const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
  1227. const MachineOperand &MO = getOperand(OpIdx);
  1228. assert(MO.isReg() &&
  1229. "Cannot get register constraints for non-register operand");
  1230. assert(CurRC && "Invalid initial register class");
  1231. if (unsigned SubIdx = MO.getSubReg()) {
  1232. if (OpRC)
  1233. CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
  1234. else
  1235. CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
  1236. } else if (OpRC)
  1237. CurRC = TRI->getCommonSubClass(CurRC, OpRC);
  1238. return CurRC;
  1239. }
  1240. /// Return the number of instructions inside the MI bundle, not counting the
  1241. /// header instruction.
  1242. unsigned MachineInstr::getBundleSize() const {
  1243. MachineBasicBlock::const_instr_iterator I = getIterator();
  1244. unsigned Size = 0;
  1245. while (I->isBundledWithSucc()) {
  1246. ++Size;
  1247. ++I;
  1248. }
  1249. return Size;
  1250. }
  1251. /// Returns true if the MachineInstr has an implicit-use operand of exactly
  1252. /// the given register (not considering sub/super-registers).
  1253. bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
  1254. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1255. const MachineOperand &MO = getOperand(i);
  1256. if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
  1257. return true;
  1258. }
  1259. return false;
  1260. }
  1261. /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
  1262. /// the specific register or -1 if it is not found. It further tightens
  1263. /// the search criteria to a use that kills the register if isKill is true.
  1264. int MachineInstr::findRegisterUseOperandIdx(
  1265. unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
  1266. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1267. const MachineOperand &MO = getOperand(i);
  1268. if (!MO.isReg() || !MO.isUse())
  1269. continue;
  1270. unsigned MOReg = MO.getReg();
  1271. if (!MOReg)
  1272. continue;
  1273. if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
  1274. TargetRegisterInfo::isPhysicalRegister(Reg) &&
  1275. TRI->isSubRegister(MOReg, Reg)))
  1276. if (!isKill || MO.isKill())
  1277. return i;
  1278. }
  1279. return -1;
  1280. }
  1281. /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
  1282. /// indicating if this instruction reads or writes Reg. This also considers
  1283. /// partial defines.
  1284. std::pair<bool,bool>
  1285. MachineInstr::readsWritesVirtualRegister(unsigned Reg,
  1286. SmallVectorImpl<unsigned> *Ops) const {
  1287. bool PartDef = false; // Partial redefine.
  1288. bool FullDef = false; // Full define.
  1289. bool Use = false;
  1290. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1291. const MachineOperand &MO = getOperand(i);
  1292. if (!MO.isReg() || MO.getReg() != Reg)
  1293. continue;
  1294. if (Ops)
  1295. Ops->push_back(i);
  1296. if (MO.isUse())
  1297. Use |= !MO.isUndef();
  1298. else if (MO.getSubReg() && !MO.isUndef())
  1299. // A partial <def,undef> doesn't count as reading the register.
  1300. PartDef = true;
  1301. else
  1302. FullDef = true;
  1303. }
  1304. // A partial redefine uses Reg unless there is also a full define.
  1305. return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
  1306. }
  1307. /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
  1308. /// the specified register or -1 if it is not found. If isDead is true, defs
  1309. /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
  1310. /// also checks if there is a def of a super-register.
  1311. int
  1312. MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
  1313. const TargetRegisterInfo *TRI) const {
  1314. bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
  1315. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1316. const MachineOperand &MO = getOperand(i);
  1317. // Accept regmask operands when Overlap is set.
  1318. // Ignore them when looking for a specific def operand (Overlap == false).
  1319. if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
  1320. return i;
  1321. if (!MO.isReg() || !MO.isDef())
  1322. continue;
  1323. unsigned MOReg = MO.getReg();
  1324. bool Found = (MOReg == Reg);
  1325. if (!Found && TRI && isPhys &&
  1326. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  1327. if (Overlap)
  1328. Found = TRI->regsOverlap(MOReg, Reg);
  1329. else
  1330. Found = TRI->isSubRegister(MOReg, Reg);
  1331. }
  1332. if (Found && (!isDead || MO.isDead()))
  1333. return i;
  1334. }
  1335. return -1;
  1336. }
  1337. /// findFirstPredOperandIdx() - Find the index of the first operand in the
  1338. /// operand list that is used to represent the predicate. It returns -1 if
  1339. /// none is found.
  1340. int MachineInstr::findFirstPredOperandIdx() const {
  1341. // Don't call MCID.findFirstPredOperandIdx() because this variant
  1342. // is sometimes called on an instruction that's not yet complete, and
  1343. // so the number of operands is less than the MCID indicates. In
  1344. // particular, the PTX target does this.
  1345. const MCInstrDesc &MCID = getDesc();
  1346. if (MCID.isPredicable()) {
  1347. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  1348. if (MCID.OpInfo[i].isPredicate())
  1349. return i;
  1350. }
  1351. return -1;
  1352. }
  1353. // MachineOperand::TiedTo is 4 bits wide.
  1354. const unsigned TiedMax = 15;
  1355. /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
  1356. ///
  1357. /// Use and def operands can be tied together, indicated by a non-zero TiedTo
  1358. /// field. TiedTo can have these values:
  1359. ///
  1360. /// 0: Operand is not tied to anything.
  1361. /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
  1362. /// TiedMax: Tied to an operand >= TiedMax-1.
  1363. ///
  1364. /// The tied def must be one of the first TiedMax operands on a normal
  1365. /// instruction. INLINEASM instructions allow more tied defs.
  1366. ///
  1367. void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
  1368. MachineOperand &DefMO = getOperand(DefIdx);
  1369. MachineOperand &UseMO = getOperand(UseIdx);
  1370. assert(DefMO.isDef() && "DefIdx must be a def operand");
  1371. assert(UseMO.isUse() && "UseIdx must be a use operand");
  1372. assert(!DefMO.isTied() && "Def is already tied to another use");
  1373. assert(!UseMO.isTied() && "Use is already tied to another def");
  1374. if (DefIdx < TiedMax)
  1375. UseMO.TiedTo = DefIdx + 1;
  1376. else {
  1377. // Inline asm can use the group descriptors to find tied operands, but on
  1378. // normal instruction, the tied def must be within the first TiedMax
  1379. // operands.
  1380. assert(isInlineAsm() && "DefIdx out of range");
  1381. UseMO.TiedTo = TiedMax;
  1382. }
  1383. // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
  1384. DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
  1385. }
  1386. /// Given the index of a tied register operand, find the operand it is tied to.
  1387. /// Defs are tied to uses and vice versa. Returns the index of the tied operand
  1388. /// which must exist.
  1389. unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
  1390. const MachineOperand &MO = getOperand(OpIdx);
  1391. assert(MO.isTied() && "Operand isn't tied");
  1392. // Normally TiedTo is in range.
  1393. if (MO.TiedTo < TiedMax)
  1394. return MO.TiedTo - 1;
  1395. // Uses on normal instructions can be out of range.
  1396. if (!isInlineAsm()) {
  1397. // Normal tied defs must be in the 0..TiedMax-1 range.
  1398. if (MO.isUse())
  1399. return TiedMax - 1;
  1400. // MO is a def. Search for the tied use.
  1401. for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
  1402. const MachineOperand &UseMO = getOperand(i);
  1403. if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
  1404. return i;
  1405. }
  1406. llvm_unreachable("Can't find tied use");
  1407. }
  1408. // Now deal with inline asm by parsing the operand group descriptor flags.
  1409. // Find the beginning of each operand group.
  1410. SmallVector<unsigned, 8> GroupIdx;
  1411. unsigned OpIdxGroup = ~0u;
  1412. unsigned NumOps;
  1413. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  1414. i += NumOps) {
  1415. const MachineOperand &FlagMO = getOperand(i);
  1416. assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
  1417. unsigned CurGroup = GroupIdx.size();
  1418. GroupIdx.push_back(i);
  1419. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  1420. // OpIdx belongs to this operand group.
  1421. if (OpIdx > i && OpIdx < i + NumOps)
  1422. OpIdxGroup = CurGroup;
  1423. unsigned TiedGroup;
  1424. if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
  1425. continue;
  1426. // Operands in this group are tied to operands in TiedGroup which must be
  1427. // earlier. Find the number of operands between the two groups.
  1428. unsigned Delta = i - GroupIdx[TiedGroup];
  1429. // OpIdx is a use tied to TiedGroup.
  1430. if (OpIdxGroup == CurGroup)
  1431. return OpIdx - Delta;
  1432. // OpIdx is a def tied to this use group.
  1433. if (OpIdxGroup == TiedGroup)
  1434. return OpIdx + Delta;
  1435. }
  1436. llvm_unreachable("Invalid tied operand on inline asm");
  1437. }
  1438. /// clearKillInfo - Clears kill flags on all operands.
  1439. ///
  1440. void MachineInstr::clearKillInfo() {
  1441. for (MachineOperand &MO : operands()) {
  1442. if (MO.isReg() && MO.isUse())
  1443. MO.setIsKill(false);
  1444. }
  1445. }
  1446. void MachineInstr::substituteRegister(unsigned FromReg,
  1447. unsigned ToReg,
  1448. unsigned SubIdx,
  1449. const TargetRegisterInfo &RegInfo) {
  1450. if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
  1451. if (SubIdx)
  1452. ToReg = RegInfo.getSubReg(ToReg, SubIdx);
  1453. for (MachineOperand &MO : operands()) {
  1454. if (!MO.isReg() || MO.getReg() != FromReg)
  1455. continue;
  1456. MO.substPhysReg(ToReg, RegInfo);
  1457. }
  1458. } else {
  1459. for (MachineOperand &MO : operands()) {
  1460. if (!MO.isReg() || MO.getReg() != FromReg)
  1461. continue;
  1462. MO.substVirtReg(ToReg, SubIdx, RegInfo);
  1463. }
  1464. }
  1465. }
  1466. /// isSafeToMove - Return true if it is safe to move this instruction. If
  1467. /// SawStore is set to true, it means that there is a store (or call) between
  1468. /// the instruction's location and its intended destination.
  1469. bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
  1470. // Ignore stuff that we obviously can't move.
  1471. //
  1472. // Treat volatile loads as stores. This is not strictly necessary for
  1473. // volatiles, but it is required for atomic loads. It is not allowed to move
  1474. // a load across an atomic load with Ordering > Monotonic.
  1475. if (mayStore() || isCall() ||
  1476. (mayLoad() && hasOrderedMemoryRef())) {
  1477. SawStore = true;
  1478. return false;
  1479. }
  1480. if (isPosition() || isDebugValue() || isTerminator() ||
  1481. hasUnmodeledSideEffects())
  1482. return false;
  1483. // See if this instruction does a load. If so, we have to guarantee that the
  1484. // loaded value doesn't change between the load and the its intended
  1485. // destination. The check for isInvariantLoad gives the targe the chance to
  1486. // classify the load as always returning a constant, e.g. a constant pool
  1487. // load.
  1488. if (mayLoad() && !isDereferenceableInvariantLoad(AA))
  1489. // Otherwise, this is a real load. If there is a store between the load and
  1490. // end of block, we can't move it.
  1491. return !SawStore;
  1492. return true;
  1493. }
  1494. bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
  1495. bool UseTBAA) {
  1496. const MachineFunction *MF = getMF();
  1497. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1498. const MachineFrameInfo &MFI = MF->getFrameInfo();
  1499. // If neither instruction stores to memory, they can't alias in any
  1500. // meaningful way, even if they read from the same address.
  1501. if (!mayStore() && !Other.mayStore())
  1502. return false;
  1503. // Let the target decide if memory accesses cannot possibly overlap.
  1504. if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
  1505. return false;
  1506. // FIXME: Need to handle multiple memory operands to support all targets.
  1507. if (!hasOneMemOperand() || !Other.hasOneMemOperand())
  1508. return true;
  1509. MachineMemOperand *MMOa = *memoperands_begin();
  1510. MachineMemOperand *MMOb = *Other.memoperands_begin();
  1511. // The following interface to AA is fashioned after DAGCombiner::isAlias
  1512. // and operates with MachineMemOperand offset with some important
  1513. // assumptions:
  1514. // - LLVM fundamentally assumes flat address spaces.
  1515. // - MachineOperand offset can *only* result from legalization and
  1516. // cannot affect queries other than the trivial case of overlap
  1517. // checking.
  1518. // - These offsets never wrap and never step outside
  1519. // of allocated objects.
  1520. // - There should never be any negative offsets here.
  1521. //
  1522. // FIXME: Modify API to hide this math from "user"
  1523. // Even before we go to AA we can reason locally about some
  1524. // memory objects. It can save compile time, and possibly catch some
  1525. // corner cases not currently covered.
  1526. int64_t OffsetA = MMOa->getOffset();
  1527. int64_t OffsetB = MMOb->getOffset();
  1528. int64_t MinOffset = std::min(OffsetA, OffsetB);
  1529. int64_t WidthA = MMOa->getSize();
  1530. int64_t WidthB = MMOb->getSize();
  1531. const Value *ValA = MMOa->getValue();
  1532. const Value *ValB = MMOb->getValue();
  1533. bool SameVal = (ValA && ValB && (ValA == ValB));
  1534. if (!SameVal) {
  1535. const PseudoSourceValue *PSVa = MMOa->getPseudoValue();
  1536. const PseudoSourceValue *PSVb = MMOb->getPseudoValue();
  1537. if (PSVa && ValB && !PSVa->mayAlias(&MFI))
  1538. return false;
  1539. if (PSVb && ValA && !PSVb->mayAlias(&MFI))
  1540. return false;
  1541. if (PSVa && PSVb && (PSVa == PSVb))
  1542. SameVal = true;
  1543. }
  1544. if (SameVal) {
  1545. int64_t MaxOffset = std::max(OffsetA, OffsetB);
  1546. int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB;
  1547. return (MinOffset + LowWidth > MaxOffset);
  1548. }
  1549. if (!AA)
  1550. return true;
  1551. if (!ValA || !ValB)
  1552. return true;
  1553. assert((OffsetA >= 0) && "Negative MachineMemOperand offset");
  1554. assert((OffsetB >= 0) && "Negative MachineMemOperand offset");
  1555. int64_t Overlapa = WidthA + OffsetA - MinOffset;
  1556. int64_t Overlapb = WidthB + OffsetB - MinOffset;
  1557. AliasResult AAResult = AA->alias(
  1558. MemoryLocation(ValA, Overlapa,
  1559. UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
  1560. MemoryLocation(ValB, Overlapb,
  1561. UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
  1562. return (AAResult != NoAlias);
  1563. }
  1564. /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
  1565. /// or volatile memory reference, or if the information describing the memory
  1566. /// reference is not available. Return false if it is known to have no ordered
  1567. /// memory references.
  1568. bool MachineInstr::hasOrderedMemoryRef() const {
  1569. // An instruction known never to access memory won't have a volatile access.
  1570. if (!mayStore() &&
  1571. !mayLoad() &&
  1572. !isCall() &&
  1573. !hasUnmodeledSideEffects())
  1574. return false;
  1575. // Otherwise, if the instruction has no memory reference information,
  1576. // conservatively assume it wasn't preserved.
  1577. if (memoperands_empty())
  1578. return true;
  1579. // Check if any of our memory operands are ordered.
  1580. return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) {
  1581. return !MMO->isUnordered();
  1582. });
  1583. }
  1584. /// isDereferenceableInvariantLoad - Return true if this instruction will never
  1585. /// trap and is loading from a location whose value is invariant across a run of
  1586. /// this function.
  1587. bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
  1588. // If the instruction doesn't load at all, it isn't an invariant load.
  1589. if (!mayLoad())
  1590. return false;
  1591. // If the instruction has lost its memoperands, conservatively assume that
  1592. // it may not be an invariant load.
  1593. if (memoperands_empty())
  1594. return false;
  1595. const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
  1596. for (MachineMemOperand *MMO : memoperands()) {
  1597. if (MMO->isVolatile()) return false;
  1598. if (MMO->isStore()) return false;
  1599. if (MMO->isInvariant() && MMO->isDereferenceable())
  1600. continue;
  1601. // A load from a constant PseudoSourceValue is invariant.
  1602. if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
  1603. if (PSV->isConstant(&MFI))
  1604. continue;
  1605. if (const Value *V = MMO->getValue()) {
  1606. // If we have an AliasAnalysis, ask it whether the memory is constant.
  1607. if (AA &&
  1608. AA->pointsToConstantMemory(
  1609. MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
  1610. continue;
  1611. }
  1612. // Otherwise assume conservatively.
  1613. return false;
  1614. }
  1615. // Everything checks out.
  1616. return true;
  1617. }
  1618. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1619. /// merges together the same virtual register, return the register, otherwise
  1620. /// return 0.
  1621. unsigned MachineInstr::isConstantValuePHI() const {
  1622. if (!isPHI())
  1623. return 0;
  1624. assert(getNumOperands() >= 3 &&
  1625. "It's illegal to have a PHI without source operands");
  1626. unsigned Reg = getOperand(1).getReg();
  1627. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1628. if (getOperand(i).getReg() != Reg)
  1629. return 0;
  1630. return Reg;
  1631. }
  1632. bool MachineInstr::hasUnmodeledSideEffects() const {
  1633. if (hasProperty(MCID::UnmodeledSideEffects))
  1634. return true;
  1635. if (isInlineAsm()) {
  1636. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1637. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1638. return true;
  1639. }
  1640. return false;
  1641. }
  1642. bool MachineInstr::isLoadFoldBarrier() const {
  1643. return mayStore() || isCall() || hasUnmodeledSideEffects();
  1644. }
  1645. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1646. ///
  1647. bool MachineInstr::allDefsAreDead() const {
  1648. for (const MachineOperand &MO : operands()) {
  1649. if (!MO.isReg() || MO.isUse())
  1650. continue;
  1651. if (!MO.isDead())
  1652. return false;
  1653. }
  1654. return true;
  1655. }
  1656. /// copyImplicitOps - Copy implicit register operands from specified
  1657. /// instruction to this instruction.
  1658. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1659. const MachineInstr &MI) {
  1660. for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
  1661. i != e; ++i) {
  1662. const MachineOperand &MO = MI.getOperand(i);
  1663. if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
  1664. addOperand(MF, MO);
  1665. }
  1666. }
  1667. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1668. LLVM_DUMP_METHOD void MachineInstr::dump() const {
  1669. dbgs() << " ";
  1670. print(dbgs());
  1671. }
  1672. #endif
  1673. void MachineInstr::print(raw_ostream &OS, bool SkipOpers, bool SkipDebugLoc,
  1674. const TargetInstrInfo *TII) const {
  1675. const Module *M = nullptr;
  1676. if (const MachineBasicBlock *MBB = getParent())
  1677. if (const MachineFunction *MF = MBB->getParent())
  1678. M = MF->getFunction()->getParent();
  1679. ModuleSlotTracker MST(M);
  1680. print(OS, MST, SkipOpers, SkipDebugLoc, TII);
  1681. }
  1682. void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
  1683. bool SkipOpers, bool SkipDebugLoc,
  1684. const TargetInstrInfo *TII) const {
  1685. // We can be a bit tidier if we know the MachineFunction.
  1686. const MachineFunction *MF = nullptr;
  1687. const TargetRegisterInfo *TRI = nullptr;
  1688. const MachineRegisterInfo *MRI = nullptr;
  1689. const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
  1690. if (const MachineBasicBlock *MBB = getParent()) {
  1691. MF = MBB->getParent();
  1692. if (MF) {
  1693. MRI = &MF->getRegInfo();
  1694. TRI = MF->getSubtarget().getRegisterInfo();
  1695. if (!TII)
  1696. TII = MF->getSubtarget().getInstrInfo();
  1697. IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
  1698. }
  1699. }
  1700. // Save a list of virtual registers.
  1701. SmallVector<unsigned, 8> VirtRegs;
  1702. // Print explicitly defined operands on the left of an assignment syntax.
  1703. unsigned StartOp = 0, e = getNumOperands();
  1704. for (; StartOp < e && getOperand(StartOp).isReg() &&
  1705. getOperand(StartOp).isDef() &&
  1706. !getOperand(StartOp).isImplicit();
  1707. ++StartOp) {
  1708. if (StartOp != 0) OS << ", ";
  1709. getOperand(StartOp).print(OS, MST, TRI, IntrinsicInfo);
  1710. unsigned Reg = getOperand(StartOp).getReg();
  1711. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  1712. VirtRegs.push_back(Reg);
  1713. LLT Ty = MRI ? MRI->getType(Reg) : LLT{};
  1714. if (Ty.isValid())
  1715. OS << '(' << Ty << ')';
  1716. }
  1717. }
  1718. if (StartOp != 0)
  1719. OS << " = ";
  1720. // Print the opcode name.
  1721. if (TII)
  1722. OS << TII->getName(getOpcode());
  1723. else
  1724. OS << "UNKNOWN";
  1725. if (SkipOpers)
  1726. return;
  1727. // Print the rest of the operands.
  1728. bool FirstOp = true;
  1729. unsigned AsmDescOp = ~0u;
  1730. unsigned AsmOpCount = 0;
  1731. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1732. // Print asm string.
  1733. OS << " ";
  1734. getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
  1735. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1736. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1737. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1738. OS << " [sideeffect]";
  1739. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1740. OS << " [mayload]";
  1741. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1742. OS << " [maystore]";
  1743. if (ExtraInfo & InlineAsm::Extra_IsConvergent)
  1744. OS << " [isconvergent]";
  1745. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1746. OS << " [alignstack]";
  1747. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1748. OS << " [attdialect]";
  1749. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1750. OS << " [inteldialect]";
  1751. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1752. FirstOp = false;
  1753. }
  1754. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1755. const MachineOperand &MO = getOperand(i);
  1756. if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1757. VirtRegs.push_back(MO.getReg());
  1758. if (FirstOp) FirstOp = false; else OS << ",";
  1759. OS << " ";
  1760. if (i < getDesc().NumOperands) {
  1761. const MCOperandInfo &MCOI = getDesc().OpInfo[i];
  1762. if (MCOI.isPredicate())
  1763. OS << "pred:";
  1764. if (MCOI.isOptionalDef())
  1765. OS << "opt:";
  1766. }
  1767. if (isDebugValue() && MO.isMetadata()) {
  1768. // Pretty print DBG_VALUE instructions.
  1769. auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
  1770. if (DIV && !DIV->getName().empty())
  1771. OS << "!\"" << DIV->getName() << '\"';
  1772. else
  1773. MO.print(OS, MST, TRI);
  1774. } else if (TRI && (isInsertSubreg() || isRegSequence() ||
  1775. (isSubregToReg() && i == 3)) && MO.isImm()) {
  1776. OS << TRI->getSubRegIndexName(MO.getImm());
  1777. } else if (i == AsmDescOp && MO.isImm()) {
  1778. // Pretty print the inline asm operand descriptor.
  1779. OS << '$' << AsmOpCount++;
  1780. unsigned Flag = MO.getImm();
  1781. switch (InlineAsm::getKind(Flag)) {
  1782. case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
  1783. case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
  1784. case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
  1785. case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
  1786. case InlineAsm::Kind_Imm: OS << ":[imm"; break;
  1787. case InlineAsm::Kind_Mem: OS << ":[mem"; break;
  1788. default: OS << ":[??" << InlineAsm::getKind(Flag); break;
  1789. }
  1790. unsigned RCID = 0;
  1791. if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
  1792. InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1793. if (TRI) {
  1794. OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
  1795. } else
  1796. OS << ":RC" << RCID;
  1797. }
  1798. if (InlineAsm::isMemKind(Flag)) {
  1799. unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
  1800. switch (MCID) {
  1801. case InlineAsm::Constraint_es: OS << ":es"; break;
  1802. case InlineAsm::Constraint_i: OS << ":i"; break;
  1803. case InlineAsm::Constraint_m: OS << ":m"; break;
  1804. case InlineAsm::Constraint_o: OS << ":o"; break;
  1805. case InlineAsm::Constraint_v: OS << ":v"; break;
  1806. case InlineAsm::Constraint_Q: OS << ":Q"; break;
  1807. case InlineAsm::Constraint_R: OS << ":R"; break;
  1808. case InlineAsm::Constraint_S: OS << ":S"; break;
  1809. case InlineAsm::Constraint_T: OS << ":T"; break;
  1810. case InlineAsm::Constraint_Um: OS << ":Um"; break;
  1811. case InlineAsm::Constraint_Un: OS << ":Un"; break;
  1812. case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
  1813. case InlineAsm::Constraint_Us: OS << ":Us"; break;
  1814. case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
  1815. case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
  1816. case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
  1817. case InlineAsm::Constraint_X: OS << ":X"; break;
  1818. case InlineAsm::Constraint_Z: OS << ":Z"; break;
  1819. case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
  1820. case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
  1821. default: OS << ":?"; break;
  1822. }
  1823. }
  1824. unsigned TiedTo = 0;
  1825. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1826. OS << " tiedto:$" << TiedTo;
  1827. OS << ']';
  1828. // Compute the index of the next operand descriptor.
  1829. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1830. } else
  1831. MO.print(OS, MST, TRI);
  1832. }
  1833. bool HaveSemi = false;
  1834. const unsigned PrintableFlags = FrameSetup | FrameDestroy;
  1835. if (Flags & PrintableFlags) {
  1836. if (!HaveSemi) {
  1837. OS << ";";
  1838. HaveSemi = true;
  1839. }
  1840. OS << " flags: ";
  1841. if (Flags & FrameSetup)
  1842. OS << "FrameSetup";
  1843. if (Flags & FrameDestroy)
  1844. OS << "FrameDestroy";
  1845. }
  1846. if (!memoperands_empty()) {
  1847. if (!HaveSemi) {
  1848. OS << ";";
  1849. HaveSemi = true;
  1850. }
  1851. OS << " mem:";
  1852. for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
  1853. i != e; ++i) {
  1854. (*i)->print(OS, MST);
  1855. if (std::next(i) != e)
  1856. OS << " ";
  1857. }
  1858. }
  1859. // Print the regclass of any virtual registers encountered.
  1860. if (MRI && !VirtRegs.empty()) {
  1861. if (!HaveSemi) {
  1862. OS << ";";
  1863. HaveSemi = true;
  1864. }
  1865. for (unsigned i = 0; i != VirtRegs.size(); ++i) {
  1866. const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
  1867. if (!RC)
  1868. continue;
  1869. // Generic virtual registers do not have register classes.
  1870. if (RC.is<const RegisterBank *>())
  1871. OS << " " << RC.get<const RegisterBank *>()->getName();
  1872. else
  1873. OS << " "
  1874. << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
  1875. OS << ':' << PrintReg(VirtRegs[i]);
  1876. for (unsigned j = i+1; j != VirtRegs.size();) {
  1877. if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
  1878. ++j;
  1879. continue;
  1880. }
  1881. if (VirtRegs[i] != VirtRegs[j])
  1882. OS << "," << PrintReg(VirtRegs[j]);
  1883. VirtRegs.erase(VirtRegs.begin()+j);
  1884. }
  1885. }
  1886. }
  1887. // Print debug location information.
  1888. if (isDebugValue() && getOperand(e - 2).isMetadata()) {
  1889. if (!HaveSemi)
  1890. OS << ";";
  1891. auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
  1892. OS << " line no:" << DV->getLine();
  1893. if (auto *InlinedAt = debugLoc->getInlinedAt()) {
  1894. DebugLoc InlinedAtDL(InlinedAt);
  1895. if (InlinedAtDL && MF) {
  1896. OS << " inlined @[ ";
  1897. InlinedAtDL.print(OS);
  1898. OS << " ]";
  1899. }
  1900. }
  1901. if (isIndirectDebugValue())
  1902. OS << " indirect";
  1903. } else if (SkipDebugLoc) {
  1904. return;
  1905. } else if (debugLoc && MF) {
  1906. if (!HaveSemi)
  1907. OS << ";";
  1908. OS << " dbg:";
  1909. debugLoc.print(OS);
  1910. }
  1911. OS << '\n';
  1912. }
  1913. bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
  1914. const TargetRegisterInfo *RegInfo,
  1915. bool AddIfNotFound) {
  1916. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
  1917. bool hasAliases = isPhysReg &&
  1918. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1919. bool Found = false;
  1920. SmallVector<unsigned,4> DeadOps;
  1921. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1922. MachineOperand &MO = getOperand(i);
  1923. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1924. continue;
  1925. // DEBUG_VALUE nodes do not contribute to code generation and should
  1926. // always be ignored. Failure to do so may result in trying to modify
  1927. // KILL flags on DEBUG_VALUE nodes.
  1928. if (MO.isDebug())
  1929. continue;
  1930. unsigned Reg = MO.getReg();
  1931. if (!Reg)
  1932. continue;
  1933. if (Reg == IncomingReg) {
  1934. if (!Found) {
  1935. if (MO.isKill())
  1936. // The register is already marked kill.
  1937. return true;
  1938. if (isPhysReg && isRegTiedToDefOperand(i))
  1939. // Two-address uses of physregs must not be marked kill.
  1940. return true;
  1941. MO.setIsKill();
  1942. Found = true;
  1943. }
  1944. } else if (hasAliases && MO.isKill() &&
  1945. TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1946. // A super-register kill already exists.
  1947. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1948. return true;
  1949. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1950. DeadOps.push_back(i);
  1951. }
  1952. }
  1953. // Trim unneeded kill operands.
  1954. while (!DeadOps.empty()) {
  1955. unsigned OpIdx = DeadOps.back();
  1956. if (getOperand(OpIdx).isImplicit())
  1957. RemoveOperand(OpIdx);
  1958. else
  1959. getOperand(OpIdx).setIsKill(false);
  1960. DeadOps.pop_back();
  1961. }
  1962. // If not found, this means an alias of one of the operands is killed. Add a
  1963. // new implicit operand if required.
  1964. if (!Found && AddIfNotFound) {
  1965. addOperand(MachineOperand::CreateReg(IncomingReg,
  1966. false /*IsDef*/,
  1967. true /*IsImp*/,
  1968. true /*IsKill*/));
  1969. return true;
  1970. }
  1971. return Found;
  1972. }
  1973. void MachineInstr::clearRegisterKills(unsigned Reg,
  1974. const TargetRegisterInfo *RegInfo) {
  1975. if (!TargetRegisterInfo::isPhysicalRegister(Reg))
  1976. RegInfo = nullptr;
  1977. for (MachineOperand &MO : operands()) {
  1978. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1979. continue;
  1980. unsigned OpReg = MO.getReg();
  1981. if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
  1982. MO.setIsKill(false);
  1983. }
  1984. }
  1985. bool MachineInstr::addRegisterDead(unsigned Reg,
  1986. const TargetRegisterInfo *RegInfo,
  1987. bool AddIfNotFound) {
  1988. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
  1989. bool hasAliases = isPhysReg &&
  1990. MCRegAliasIterator(Reg, RegInfo, false).isValid();
  1991. bool Found = false;
  1992. SmallVector<unsigned,4> DeadOps;
  1993. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1994. MachineOperand &MO = getOperand(i);
  1995. if (!MO.isReg() || !MO.isDef())
  1996. continue;
  1997. unsigned MOReg = MO.getReg();
  1998. if (!MOReg)
  1999. continue;
  2000. if (MOReg == Reg) {
  2001. MO.setIsDead();
  2002. Found = true;
  2003. } else if (hasAliases && MO.isDead() &&
  2004. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  2005. // There exists a super-register that's marked dead.
  2006. if (RegInfo->isSuperRegister(Reg, MOReg))
  2007. return true;
  2008. if (RegInfo->isSubRegister(Reg, MOReg))
  2009. DeadOps.push_back(i);
  2010. }
  2011. }
  2012. // Trim unneeded dead operands.
  2013. while (!DeadOps.empty()) {
  2014. unsigned OpIdx = DeadOps.back();
  2015. if (getOperand(OpIdx).isImplicit())
  2016. RemoveOperand(OpIdx);
  2017. else
  2018. getOperand(OpIdx).setIsDead(false);
  2019. DeadOps.pop_back();
  2020. }
  2021. // If not found, this means an alias of one of the operands is dead. Add a
  2022. // new implicit operand if required.
  2023. if (Found || !AddIfNotFound)
  2024. return Found;
  2025. addOperand(MachineOperand::CreateReg(Reg,
  2026. true /*IsDef*/,
  2027. true /*IsImp*/,
  2028. false /*IsKill*/,
  2029. true /*IsDead*/));
  2030. return true;
  2031. }
  2032. void MachineInstr::clearRegisterDeads(unsigned Reg) {
  2033. for (MachineOperand &MO : operands()) {
  2034. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
  2035. continue;
  2036. MO.setIsDead(false);
  2037. }
  2038. }
  2039. void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
  2040. for (MachineOperand &MO : operands()) {
  2041. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
  2042. continue;
  2043. MO.setIsUndef(IsUndef);
  2044. }
  2045. }
  2046. void MachineInstr::addRegisterDefined(unsigned Reg,
  2047. const TargetRegisterInfo *RegInfo) {
  2048. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  2049. MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
  2050. if (MO)
  2051. return;
  2052. } else {
  2053. for (const MachineOperand &MO : operands()) {
  2054. if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
  2055. MO.getSubReg() == 0)
  2056. return;
  2057. }
  2058. }
  2059. addOperand(MachineOperand::CreateReg(Reg,
  2060. true /*IsDef*/,
  2061. true /*IsImp*/));
  2062. }
  2063. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
  2064. const TargetRegisterInfo &TRI) {
  2065. bool HasRegMask = false;
  2066. for (MachineOperand &MO : operands()) {
  2067. if (MO.isRegMask()) {
  2068. HasRegMask = true;
  2069. continue;
  2070. }
  2071. if (!MO.isReg() || !MO.isDef()) continue;
  2072. unsigned Reg = MO.getReg();
  2073. if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  2074. // If there are no uses, including partial uses, the def is dead.
  2075. if (llvm::none_of(UsedRegs,
  2076. [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
  2077. MO.setIsDead();
  2078. }
  2079. // This is a call with a register mask operand.
  2080. // Mask clobbers are always dead, so add defs for the non-dead defines.
  2081. if (HasRegMask)
  2082. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  2083. I != E; ++I)
  2084. addRegisterDefined(*I, &TRI);
  2085. }
  2086. unsigned
  2087. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  2088. // Build up a buffer of hash code components.
  2089. SmallVector<size_t, 8> HashComponents;
  2090. HashComponents.reserve(MI->getNumOperands() + 1);
  2091. HashComponents.push_back(MI->getOpcode());
  2092. for (const MachineOperand &MO : MI->operands()) {
  2093. if (MO.isReg() && MO.isDef() &&
  2094. TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  2095. continue; // Skip virtual register defs.
  2096. HashComponents.push_back(hash_value(MO));
  2097. }
  2098. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  2099. }
  2100. void MachineInstr::emitError(StringRef Msg) const {
  2101. // Find the source location cookie.
  2102. unsigned LocCookie = 0;
  2103. const MDNode *LocMD = nullptr;
  2104. for (unsigned i = getNumOperands(); i != 0; --i) {
  2105. if (getOperand(i-1).isMetadata() &&
  2106. (LocMD = getOperand(i-1).getMetadata()) &&
  2107. LocMD->getNumOperands() != 0) {
  2108. if (const ConstantInt *CI =
  2109. mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
  2110. LocCookie = CI->getZExtValue();
  2111. break;
  2112. }
  2113. }
  2114. }
  2115. if (const MachineBasicBlock *MBB = getParent())
  2116. if (const MachineFunction *MF = MBB->getParent())
  2117. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  2118. report_fatal_error(Msg);
  2119. }
  2120. MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
  2121. const MCInstrDesc &MCID, bool IsIndirect,
  2122. unsigned Reg, const MDNode *Variable,
  2123. const MDNode *Expr) {
  2124. assert(isa<DILocalVariable>(Variable) && "not a variable");
  2125. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  2126. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  2127. "Expected inlined-at fields to agree");
  2128. if (IsIndirect)
  2129. return BuildMI(MF, DL, MCID)
  2130. .addReg(Reg, RegState::Debug)
  2131. .addImm(0U)
  2132. .addMetadata(Variable)
  2133. .addMetadata(Expr);
  2134. else
  2135. return BuildMI(MF, DL, MCID)
  2136. .addReg(Reg, RegState::Debug)
  2137. .addReg(0U, RegState::Debug)
  2138. .addMetadata(Variable)
  2139. .addMetadata(Expr);
  2140. }
  2141. MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
  2142. MachineBasicBlock::iterator I,
  2143. const DebugLoc &DL, const MCInstrDesc &MCID,
  2144. bool IsIndirect, unsigned Reg,
  2145. const MDNode *Variable, const MDNode *Expr) {
  2146. assert(isa<DILocalVariable>(Variable) && "not a variable");
  2147. assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
  2148. MachineFunction &MF = *BB.getParent();
  2149. MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr);
  2150. BB.insert(I, MI);
  2151. return MachineInstrBuilder(MF, MI);
  2152. }
  2153. /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot.
  2154. /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE.
  2155. static const DIExpression *computeExprForSpill(const MachineInstr &MI) {
  2156. assert(MI.getOperand(0).isReg() && "can't spill non-register");
  2157. assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
  2158. "Expected inlined-at fields to agree");
  2159. const DIExpression *Expr = MI.getDebugExpression();
  2160. if (MI.isIndirectDebugValue()) {
  2161. assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
  2162. Expr = DIExpression::prepend(Expr, DIExpression::WithDeref);
  2163. }
  2164. return Expr;
  2165. }
  2166. MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB,
  2167. MachineBasicBlock::iterator I,
  2168. const MachineInstr &Orig,
  2169. int FrameIndex) {
  2170. const DIExpression *Expr = computeExprForSpill(Orig);
  2171. return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc())
  2172. .addFrameIndex(FrameIndex)
  2173. .addImm(0U)
  2174. .addMetadata(Orig.getDebugVariable())
  2175. .addMetadata(Expr);
  2176. }
  2177. void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) {
  2178. const DIExpression *Expr = computeExprForSpill(Orig);
  2179. Orig.getOperand(0).ChangeToFrameIndex(FrameIndex);
  2180. Orig.getOperand(1).ChangeToImmediate(0U);
  2181. Orig.getOperand(3).setMetadata(Expr);
  2182. }