MachineInstr.cpp 87 KB

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