MachineInstr.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992
  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/FoldingSet.h"
  15. #include "llvm/ADT/Hashing.h"
  16. #include "llvm/Analysis/AliasAnalysis.h"
  17. #include "llvm/CodeGen/MachineConstantPool.h"
  18. #include "llvm/CodeGen/MachineFunction.h"
  19. #include "llvm/CodeGen/MachineMemOperand.h"
  20. #include "llvm/CodeGen/MachineModuleInfo.h"
  21. #include "llvm/CodeGen/MachineRegisterInfo.h"
  22. #include "llvm/CodeGen/PseudoSourceValue.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DebugInfo.h"
  25. #include "llvm/IR/Function.h"
  26. #include "llvm/IR/InlineAsm.h"
  27. #include "llvm/IR/LLVMContext.h"
  28. #include "llvm/IR/Metadata.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/IR/ModuleSlotTracker.h"
  31. #include "llvm/IR/Type.h"
  32. #include "llvm/IR/Value.h"
  33. #include "llvm/MC/MCInstrDesc.h"
  34. #include "llvm/MC/MCSymbol.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/MathExtras.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include "llvm/Target/TargetInstrInfo.h"
  40. #include "llvm/Target/TargetMachine.h"
  41. #include "llvm/Target/TargetRegisterInfo.h"
  42. #include "llvm/Target/TargetSubtargetInfo.h"
  43. using namespace llvm;
  44. //===----------------------------------------------------------------------===//
  45. // MachineOperand Implementation
  46. //===----------------------------------------------------------------------===//
  47. void MachineOperand::setReg(unsigned Reg) {
  48. if (getReg() == Reg) return; // No change.
  49. // Otherwise, we have to change the register. If this operand is embedded
  50. // into a machine function, we need to update the old and new register's
  51. // use/def lists.
  52. if (MachineInstr *MI = getParent())
  53. if (MachineBasicBlock *MBB = MI->getParent())
  54. if (MachineFunction *MF = MBB->getParent()) {
  55. MachineRegisterInfo &MRI = MF->getRegInfo();
  56. MRI.removeRegOperandFromUseList(this);
  57. SmallContents.RegNo = Reg;
  58. MRI.addRegOperandToUseList(this);
  59. return;
  60. }
  61. // Otherwise, just change the register, no problem. :)
  62. SmallContents.RegNo = Reg;
  63. }
  64. void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
  65. const TargetRegisterInfo &TRI) {
  66. assert(TargetRegisterInfo::isVirtualRegister(Reg));
  67. if (SubIdx && getSubReg())
  68. SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
  69. setReg(Reg);
  70. if (SubIdx)
  71. setSubReg(SubIdx);
  72. }
  73. void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
  74. assert(TargetRegisterInfo::isPhysicalRegister(Reg));
  75. if (getSubReg()) {
  76. Reg = TRI.getSubReg(Reg, getSubReg());
  77. // Note that getSubReg() may return 0 if the sub-register doesn't exist.
  78. // That won't happen in legal code.
  79. setSubReg(0);
  80. }
  81. setReg(Reg);
  82. }
  83. /// Change a def to a use, or a use to a def.
  84. void MachineOperand::setIsDef(bool Val) {
  85. assert(isReg() && "Wrong MachineOperand accessor");
  86. assert((!Val || !isDebug()) && "Marking a debug operation as def");
  87. if (IsDef == Val)
  88. return;
  89. // MRI may keep uses and defs in different list positions.
  90. if (MachineInstr *MI = getParent())
  91. if (MachineBasicBlock *MBB = MI->getParent())
  92. if (MachineFunction *MF = MBB->getParent()) {
  93. MachineRegisterInfo &MRI = MF->getRegInfo();
  94. MRI.removeRegOperandFromUseList(this);
  95. IsDef = Val;
  96. MRI.addRegOperandToUseList(this);
  97. return;
  98. }
  99. IsDef = Val;
  100. }
  101. // If this operand is currently a register operand, and if this is in a
  102. // function, deregister the operand from the register's use/def list.
  103. void MachineOperand::removeRegFromUses() {
  104. if (!isReg() || !isOnRegUseList())
  105. return;
  106. if (MachineInstr *MI = getParent()) {
  107. if (MachineBasicBlock *MBB = MI->getParent()) {
  108. if (MachineFunction *MF = MBB->getParent())
  109. MF->getRegInfo().removeRegOperandFromUseList(this);
  110. }
  111. }
  112. }
  113. /// ChangeToImmediate - Replace this operand with a new immediate operand of
  114. /// the specified value. If an operand is known to be an immediate already,
  115. /// the setImm method should be used.
  116. void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
  117. assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
  118. removeRegFromUses();
  119. OpKind = MO_Immediate;
  120. Contents.ImmVal = ImmVal;
  121. }
  122. void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
  123. assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
  124. removeRegFromUses();
  125. OpKind = MO_FPImmediate;
  126. Contents.CFP = FPImm;
  127. }
  128. void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) {
  129. assert((!isReg() || !isTied()) &&
  130. "Cannot change a tied operand into an external symbol");
  131. removeRegFromUses();
  132. OpKind = MO_ExternalSymbol;
  133. Contents.OffsetedInfo.Val.SymbolName = SymName;
  134. setOffset(0); // Offset is always 0.
  135. setTargetFlags(TargetFlags);
  136. }
  137. void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
  138. assert((!isReg() || !isTied()) &&
  139. "Cannot change a tied operand into an MCSymbol");
  140. removeRegFromUses();
  141. OpKind = MO_MCSymbol;
  142. Contents.Sym = Sym;
  143. }
  144. /// ChangeToRegister - Replace this operand with a new register operand of
  145. /// the specified value. If an operand is known to be an register already,
  146. /// the setReg method should be used.
  147. void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
  148. bool isKill, bool isDead, bool isUndef,
  149. bool isDebug) {
  150. MachineRegisterInfo *RegInfo = nullptr;
  151. if (MachineInstr *MI = getParent())
  152. if (MachineBasicBlock *MBB = MI->getParent())
  153. if (MachineFunction *MF = MBB->getParent())
  154. RegInfo = &MF->getRegInfo();
  155. // If this operand is already a register operand, remove it from the
  156. // register's use/def lists.
  157. bool WasReg = isReg();
  158. if (RegInfo && WasReg)
  159. RegInfo->removeRegOperandFromUseList(this);
  160. // Change this to a register and set the reg#.
  161. OpKind = MO_Register;
  162. SmallContents.RegNo = Reg;
  163. SubReg_TargetFlags = 0;
  164. IsDef = isDef;
  165. IsImp = isImp;
  166. IsKill = isKill;
  167. IsDead = isDead;
  168. IsUndef = isUndef;
  169. IsInternalRead = false;
  170. IsEarlyClobber = false;
  171. IsDebug = isDebug;
  172. // Ensure isOnRegUseList() returns false.
  173. Contents.Reg.Prev = nullptr;
  174. // Preserve the tie when the operand was already a register.
  175. if (!WasReg)
  176. TiedTo = 0;
  177. // If this operand is embedded in a function, add the operand to the
  178. // register's use/def list.
  179. if (RegInfo)
  180. RegInfo->addRegOperandToUseList(this);
  181. }
  182. /// isIdenticalTo - Return true if this operand is identical to the specified
  183. /// operand. Note that this should stay in sync with the hash_value overload
  184. /// below.
  185. bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
  186. if (getType() != Other.getType() ||
  187. getTargetFlags() != Other.getTargetFlags())
  188. return false;
  189. switch (getType()) {
  190. case MachineOperand::MO_Register:
  191. return getReg() == Other.getReg() && isDef() == Other.isDef() &&
  192. getSubReg() == Other.getSubReg();
  193. case MachineOperand::MO_Immediate:
  194. return getImm() == Other.getImm();
  195. case MachineOperand::MO_CImmediate:
  196. return getCImm() == Other.getCImm();
  197. case MachineOperand::MO_FPImmediate:
  198. return getFPImm() == Other.getFPImm();
  199. case MachineOperand::MO_MachineBasicBlock:
  200. return getMBB() == Other.getMBB();
  201. case MachineOperand::MO_FrameIndex:
  202. return getIndex() == Other.getIndex();
  203. case MachineOperand::MO_ConstantPoolIndex:
  204. case MachineOperand::MO_TargetIndex:
  205. return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
  206. case MachineOperand::MO_JumpTableIndex:
  207. return getIndex() == Other.getIndex();
  208. case MachineOperand::MO_GlobalAddress:
  209. return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
  210. case MachineOperand::MO_ExternalSymbol:
  211. return !strcmp(getSymbolName(), Other.getSymbolName()) &&
  212. getOffset() == Other.getOffset();
  213. case MachineOperand::MO_BlockAddress:
  214. return getBlockAddress() == Other.getBlockAddress() &&
  215. getOffset() == Other.getOffset();
  216. case MachineOperand::MO_RegisterMask:
  217. case MachineOperand::MO_RegisterLiveOut:
  218. return getRegMask() == Other.getRegMask();
  219. case MachineOperand::MO_MCSymbol:
  220. return getMCSymbol() == Other.getMCSymbol();
  221. case MachineOperand::MO_CFIIndex:
  222. return getCFIIndex() == Other.getCFIIndex();
  223. case MachineOperand::MO_Metadata:
  224. return getMetadata() == Other.getMetadata();
  225. }
  226. llvm_unreachable("Invalid machine operand type");
  227. }
  228. // Note: this must stay exactly in sync with isIdenticalTo above.
  229. hash_code llvm::hash_value(const MachineOperand &MO) {
  230. switch (MO.getType()) {
  231. case MachineOperand::MO_Register:
  232. // Register operands don't have target flags.
  233. return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
  234. case MachineOperand::MO_Immediate:
  235. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
  236. case MachineOperand::MO_CImmediate:
  237. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
  238. case MachineOperand::MO_FPImmediate:
  239. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
  240. case MachineOperand::MO_MachineBasicBlock:
  241. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
  242. case MachineOperand::MO_FrameIndex:
  243. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
  244. case MachineOperand::MO_ConstantPoolIndex:
  245. case MachineOperand::MO_TargetIndex:
  246. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
  247. MO.getOffset());
  248. case MachineOperand::MO_JumpTableIndex:
  249. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
  250. case MachineOperand::MO_ExternalSymbol:
  251. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
  252. MO.getSymbolName());
  253. case MachineOperand::MO_GlobalAddress:
  254. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
  255. MO.getOffset());
  256. case MachineOperand::MO_BlockAddress:
  257. return hash_combine(MO.getType(), MO.getTargetFlags(),
  258. MO.getBlockAddress(), MO.getOffset());
  259. case MachineOperand::MO_RegisterMask:
  260. case MachineOperand::MO_RegisterLiveOut:
  261. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
  262. case MachineOperand::MO_Metadata:
  263. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
  264. case MachineOperand::MO_MCSymbol:
  265. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
  266. case MachineOperand::MO_CFIIndex:
  267. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
  268. }
  269. llvm_unreachable("Invalid machine operand type");
  270. }
  271. void MachineOperand::print(raw_ostream &OS,
  272. const TargetRegisterInfo *TRI) const {
  273. ModuleSlotTracker DummyMST(nullptr);
  274. print(OS, DummyMST, TRI);
  275. }
  276. void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
  277. const TargetRegisterInfo *TRI) const {
  278. switch (getType()) {
  279. case MachineOperand::MO_Register:
  280. OS << PrintReg(getReg(), TRI, getSubReg());
  281. if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
  282. isInternalRead() || isEarlyClobber() || isTied()) {
  283. OS << '<';
  284. bool NeedComma = false;
  285. if (isDef()) {
  286. if (NeedComma) OS << ',';
  287. if (isEarlyClobber())
  288. OS << "earlyclobber,";
  289. if (isImplicit())
  290. OS << "imp-";
  291. OS << "def";
  292. NeedComma = true;
  293. // <def,read-undef> only makes sense when getSubReg() is set.
  294. // Don't clutter the output otherwise.
  295. if (isUndef() && getSubReg())
  296. OS << ",read-undef";
  297. } else if (isImplicit()) {
  298. OS << "imp-use";
  299. NeedComma = true;
  300. }
  301. if (isKill()) {
  302. if (NeedComma) OS << ',';
  303. OS << "kill";
  304. NeedComma = true;
  305. }
  306. if (isDead()) {
  307. if (NeedComma) OS << ',';
  308. OS << "dead";
  309. NeedComma = true;
  310. }
  311. if (isUndef() && isUse()) {
  312. if (NeedComma) OS << ',';
  313. OS << "undef";
  314. NeedComma = true;
  315. }
  316. if (isInternalRead()) {
  317. if (NeedComma) OS << ',';
  318. OS << "internal";
  319. NeedComma = true;
  320. }
  321. if (isTied()) {
  322. if (NeedComma) OS << ',';
  323. OS << "tied";
  324. if (TiedTo != 15)
  325. OS << unsigned(TiedTo - 1);
  326. }
  327. OS << '>';
  328. }
  329. break;
  330. case MachineOperand::MO_Immediate:
  331. OS << getImm();
  332. break;
  333. case MachineOperand::MO_CImmediate:
  334. getCImm()->getValue().print(OS, false);
  335. break;
  336. case MachineOperand::MO_FPImmediate:
  337. if (getFPImm()->getType()->isFloatTy())
  338. OS << getFPImm()->getValueAPF().convertToFloat();
  339. else
  340. OS << getFPImm()->getValueAPF().convertToDouble();
  341. break;
  342. case MachineOperand::MO_MachineBasicBlock:
  343. OS << "<BB#" << getMBB()->getNumber() << ">";
  344. break;
  345. case MachineOperand::MO_FrameIndex:
  346. OS << "<fi#" << getIndex() << '>';
  347. break;
  348. case MachineOperand::MO_ConstantPoolIndex:
  349. OS << "<cp#" << getIndex();
  350. if (getOffset()) OS << "+" << getOffset();
  351. OS << '>';
  352. break;
  353. case MachineOperand::MO_TargetIndex:
  354. OS << "<ti#" << getIndex();
  355. if (getOffset()) OS << "+" << getOffset();
  356. OS << '>';
  357. break;
  358. case MachineOperand::MO_JumpTableIndex:
  359. OS << "<jt#" << getIndex() << '>';
  360. break;
  361. case MachineOperand::MO_GlobalAddress:
  362. OS << "<ga:";
  363. getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
  364. if (getOffset()) OS << "+" << getOffset();
  365. OS << '>';
  366. break;
  367. case MachineOperand::MO_ExternalSymbol:
  368. OS << "<es:" << getSymbolName();
  369. if (getOffset()) OS << "+" << getOffset();
  370. OS << '>';
  371. break;
  372. case MachineOperand::MO_BlockAddress:
  373. OS << '<';
  374. getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
  375. if (getOffset()) OS << "+" << getOffset();
  376. OS << '>';
  377. break;
  378. case MachineOperand::MO_RegisterMask:
  379. OS << "<regmask>";
  380. break;
  381. case MachineOperand::MO_RegisterLiveOut:
  382. OS << "<regliveout>";
  383. break;
  384. case MachineOperand::MO_Metadata:
  385. OS << '<';
  386. getMetadata()->printAsOperand(OS, MST);
  387. OS << '>';
  388. break;
  389. case MachineOperand::MO_MCSymbol:
  390. OS << "<MCSym=" << *getMCSymbol() << '>';
  391. break;
  392. case MachineOperand::MO_CFIIndex:
  393. OS << "<call frame instruction>";
  394. break;
  395. }
  396. if (unsigned TF = getTargetFlags())
  397. OS << "[TF=" << TF << ']';
  398. }
  399. //===----------------------------------------------------------------------===//
  400. // MachineMemOperand Implementation
  401. //===----------------------------------------------------------------------===//
  402. /// getAddrSpace - Return the LLVM IR address space number that this pointer
  403. /// points into.
  404. unsigned MachinePointerInfo::getAddrSpace() const {
  405. if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
  406. return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
  407. }
  408. /// getConstantPool - Return a MachinePointerInfo record that refers to the
  409. /// constant pool.
  410. MachinePointerInfo MachinePointerInfo::getConstantPool() {
  411. return MachinePointerInfo(PseudoSourceValue::getConstantPool());
  412. }
  413. /// getFixedStack - Return a MachinePointerInfo record that refers to the
  414. /// the specified FrameIndex.
  415. MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
  416. return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
  417. }
  418. MachinePointerInfo MachinePointerInfo::getJumpTable() {
  419. return MachinePointerInfo(PseudoSourceValue::getJumpTable());
  420. }
  421. MachinePointerInfo MachinePointerInfo::getGOT() {
  422. return MachinePointerInfo(PseudoSourceValue::getGOT());
  423. }
  424. MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
  425. return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
  426. }
  427. MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
  428. uint64_t s, unsigned int a,
  429. const AAMDNodes &AAInfo,
  430. const MDNode *Ranges)
  431. : PtrInfo(ptrinfo), Size(s),
  432. Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
  433. AAInfo(AAInfo), Ranges(Ranges) {
  434. assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
  435. isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
  436. "invalid pointer value");
  437. assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
  438. assert((isLoad() || isStore()) && "Not a load/store!");
  439. }
  440. /// Profile - Gather unique data for the object.
  441. ///
  442. void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
  443. ID.AddInteger(getOffset());
  444. ID.AddInteger(Size);
  445. ID.AddPointer(getOpaqueValue());
  446. ID.AddInteger(Flags);
  447. }
  448. void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
  449. // The Value and Offset may differ due to CSE. But the flags and size
  450. // should be the same.
  451. assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
  452. assert(MMO->getSize() == getSize() && "Size mismatch!");
  453. if (MMO->getBaseAlignment() >= getBaseAlignment()) {
  454. // Update the alignment value.
  455. Flags = (Flags & ((1 << MOMaxBits) - 1)) |
  456. ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
  457. // Also update the base and offset, because the new alignment may
  458. // not be applicable with the old ones.
  459. PtrInfo = MMO->PtrInfo;
  460. }
  461. }
  462. /// getAlignment - Return the minimum known alignment in bytes of the
  463. /// actual memory reference.
  464. uint64_t MachineMemOperand::getAlignment() const {
  465. return MinAlign(getBaseAlignment(), getOffset());
  466. }
  467. void MachineMemOperand::print(raw_ostream &OS) const {
  468. ModuleSlotTracker DummyMST(nullptr);
  469. print(OS, DummyMST);
  470. }
  471. void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
  472. assert((isLoad() || isStore()) &&
  473. "SV has to be a load, store or both.");
  474. if (isVolatile())
  475. OS << "Volatile ";
  476. if (isLoad())
  477. OS << "LD";
  478. if (isStore())
  479. OS << "ST";
  480. OS << getSize();
  481. // Print the address information.
  482. OS << "[";
  483. if (const Value *V = getValue())
  484. V->printAsOperand(OS, /*PrintType=*/false, MST);
  485. else if (const PseudoSourceValue *PSV = getPseudoValue())
  486. PSV->printCustom(OS);
  487. else
  488. OS << "<unknown>";
  489. unsigned AS = getAddrSpace();
  490. if (AS != 0)
  491. OS << "(addrspace=" << AS << ')';
  492. // If the alignment of the memory reference itself differs from the alignment
  493. // of the base pointer, print the base alignment explicitly, next to the base
  494. // pointer.
  495. if (getBaseAlignment() != getAlignment())
  496. OS << "(align=" << getBaseAlignment() << ")";
  497. if (getOffset() != 0)
  498. OS << "+" << getOffset();
  499. OS << "]";
  500. // Print the alignment of the reference.
  501. if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
  502. OS << "(align=" << getAlignment() << ")";
  503. // Print TBAA info.
  504. if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
  505. OS << "(tbaa=";
  506. if (TBAAInfo->getNumOperands() > 0)
  507. TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
  508. else
  509. OS << "<unknown>";
  510. OS << ")";
  511. }
  512. // Print AA scope info.
  513. if (const MDNode *ScopeInfo = getAAInfo().Scope) {
  514. OS << "(alias.scope=";
  515. if (ScopeInfo->getNumOperands() > 0)
  516. for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
  517. ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
  518. if (i != ie-1)
  519. OS << ",";
  520. }
  521. else
  522. OS << "<unknown>";
  523. OS << ")";
  524. }
  525. // Print AA noalias scope info.
  526. if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
  527. OS << "(noalias=";
  528. if (NoAliasInfo->getNumOperands() > 0)
  529. for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
  530. NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
  531. if (i != ie-1)
  532. OS << ",";
  533. }
  534. else
  535. OS << "<unknown>";
  536. OS << ")";
  537. }
  538. // Print nontemporal info.
  539. if (isNonTemporal())
  540. OS << "(nontemporal)";
  541. if (isInvariant())
  542. OS << "(invariant)";
  543. }
  544. //===----------------------------------------------------------------------===//
  545. // MachineInstr Implementation
  546. //===----------------------------------------------------------------------===//
  547. void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
  548. if (MCID->ImplicitDefs)
  549. for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
  550. addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
  551. if (MCID->ImplicitUses)
  552. for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
  553. addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
  554. }
  555. /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
  556. /// implicit operands. It reserves space for the number of operands specified by
  557. /// the MCInstrDesc.
  558. MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
  559. DebugLoc dl, bool NoImp)
  560. : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0), Flags(0),
  561. AsmPrinterFlags(0), NumMemRefs(0), MemRefs(nullptr),
  562. debugLoc(std::move(dl)) {
  563. assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
  564. // Reserve space for the expected number of operands.
  565. if (unsigned NumOps = MCID->getNumOperands() +
  566. MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
  567. CapOperands = OperandCapacity::get(NumOps);
  568. Operands = MF.allocateOperandArray(CapOperands);
  569. }
  570. if (!NoImp)
  571. addImplicitDefUseOperands(MF);
  572. }
  573. /// MachineInstr ctor - Copies MachineInstr arg exactly
  574. ///
  575. MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
  576. : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
  577. Flags(0), AsmPrinterFlags(0),
  578. NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
  579. debugLoc(MI.getDebugLoc()) {
  580. assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
  581. CapOperands = OperandCapacity::get(MI.getNumOperands());
  582. Operands = MF.allocateOperandArray(CapOperands);
  583. // Copy operands.
  584. for (const MachineOperand &MO : MI.operands())
  585. addOperand(MF, MO);
  586. // Copy all the sensible flags.
  587. setFlags(MI.Flags);
  588. }
  589. /// getRegInfo - If this instruction is embedded into a MachineFunction,
  590. /// return the MachineRegisterInfo object for the current function, otherwise
  591. /// return null.
  592. MachineRegisterInfo *MachineInstr::getRegInfo() {
  593. if (MachineBasicBlock *MBB = getParent())
  594. return &MBB->getParent()->getRegInfo();
  595. return nullptr;
  596. }
  597. /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
  598. /// this instruction from their respective use lists. This requires that the
  599. /// operands already be on their use lists.
  600. void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
  601. for (MachineOperand &MO : operands())
  602. if (MO.isReg())
  603. MRI.removeRegOperandFromUseList(&MO);
  604. }
  605. /// AddRegOperandsToUseLists - Add all of the register operands in
  606. /// this instruction from their respective use lists. This requires that the
  607. /// operands not be on their use lists yet.
  608. void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
  609. for (MachineOperand &MO : operands())
  610. if (MO.isReg())
  611. MRI.addRegOperandToUseList(&MO);
  612. }
  613. void MachineInstr::addOperand(const MachineOperand &Op) {
  614. MachineBasicBlock *MBB = getParent();
  615. assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
  616. MachineFunction *MF = MBB->getParent();
  617. assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
  618. addOperand(*MF, Op);
  619. }
  620. /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
  621. /// ranges. If MRI is non-null also update use-def chains.
  622. static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
  623. unsigned NumOps, MachineRegisterInfo *MRI) {
  624. if (MRI)
  625. return MRI->moveOperands(Dst, Src, NumOps);
  626. // MachineOperand is a trivially copyable type so we can just use memmove.
  627. std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
  628. }
  629. /// addOperand - Add the specified operand to the instruction. If it is an
  630. /// implicit operand, it is added to the end of the operand list. If it is
  631. /// an explicit operand it is added at the end of the explicit operand list
  632. /// (before the first implicit operand).
  633. void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
  634. assert(MCID && "Cannot add operands before providing an instr descriptor");
  635. // Check if we're adding one of our existing operands.
  636. if (&Op >= Operands && &Op < Operands + NumOperands) {
  637. // This is unusual: MI->addOperand(MI->getOperand(i)).
  638. // If adding Op requires reallocating or moving existing operands around,
  639. // the Op reference could go stale. Support it by copying Op.
  640. MachineOperand CopyOp(Op);
  641. return addOperand(MF, CopyOp);
  642. }
  643. // Find the insert location for the new operand. Implicit registers go at
  644. // the end, everything else goes before the implicit regs.
  645. //
  646. // FIXME: Allow mixed explicit and implicit operands on inline asm.
  647. // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
  648. // implicit-defs, but they must not be moved around. See the FIXME in
  649. // InstrEmitter.cpp.
  650. unsigned OpNo = getNumOperands();
  651. bool isImpReg = Op.isReg() && Op.isImplicit();
  652. if (!isImpReg && !isInlineAsm()) {
  653. while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
  654. --OpNo;
  655. assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
  656. }
  657. }
  658. #ifndef NDEBUG
  659. bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
  660. // OpNo now points as the desired insertion point. Unless this is a variadic
  661. // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
  662. // RegMask operands go between the explicit and implicit operands.
  663. assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
  664. OpNo < MCID->getNumOperands() || isMetaDataOp) &&
  665. "Trying to add an operand to a machine instr that is already done!");
  666. #endif
  667. MachineRegisterInfo *MRI = getRegInfo();
  668. // Determine if the Operands array needs to be reallocated.
  669. // Save the old capacity and operand array.
  670. OperandCapacity OldCap = CapOperands;
  671. MachineOperand *OldOperands = Operands;
  672. if (!OldOperands || OldCap.getSize() == getNumOperands()) {
  673. CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
  674. Operands = MF.allocateOperandArray(CapOperands);
  675. // Move the operands before the insertion point.
  676. if (OpNo)
  677. moveOperands(Operands, OldOperands, OpNo, MRI);
  678. }
  679. // Move the operands following the insertion point.
  680. if (OpNo != NumOperands)
  681. moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
  682. MRI);
  683. ++NumOperands;
  684. // Deallocate the old operand array.
  685. if (OldOperands != Operands && OldOperands)
  686. MF.deallocateOperandArray(OldCap, OldOperands);
  687. // Copy Op into place. It still needs to be inserted into the MRI use lists.
  688. MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
  689. NewMO->ParentMI = this;
  690. // When adding a register operand, tell MRI about it.
  691. if (NewMO->isReg()) {
  692. // Ensure isOnRegUseList() returns false, regardless of Op's status.
  693. NewMO->Contents.Reg.Prev = nullptr;
  694. // Ignore existing ties. This is not a property that can be copied.
  695. NewMO->TiedTo = 0;
  696. // Add the new operand to MRI, but only for instructions in an MBB.
  697. if (MRI)
  698. MRI->addRegOperandToUseList(NewMO);
  699. // The MCID operand information isn't accurate until we start adding
  700. // explicit operands. The implicit operands are added first, then the
  701. // explicits are inserted before them.
  702. if (!isImpReg) {
  703. // Tie uses to defs as indicated in MCInstrDesc.
  704. if (NewMO->isUse()) {
  705. int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
  706. if (DefIdx != -1)
  707. tieOperands(DefIdx, OpNo);
  708. }
  709. // If the register operand is flagged as early, mark the operand as such.
  710. if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
  711. NewMO->setIsEarlyClobber(true);
  712. }
  713. }
  714. }
  715. /// RemoveOperand - Erase an operand from an instruction, leaving it with one
  716. /// fewer operand than it started with.
  717. ///
  718. void MachineInstr::RemoveOperand(unsigned OpNo) {
  719. assert(OpNo < getNumOperands() && "Invalid operand number");
  720. untieRegOperand(OpNo);
  721. #ifndef NDEBUG
  722. // Moving tied operands would break the ties.
  723. for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
  724. if (Operands[i].isReg())
  725. assert(!Operands[i].isTied() && "Cannot move tied operands");
  726. #endif
  727. MachineRegisterInfo *MRI = getRegInfo();
  728. if (MRI && Operands[OpNo].isReg())
  729. MRI->removeRegOperandFromUseList(Operands + OpNo);
  730. // Don't call the MachineOperand destructor. A lot of this code depends on
  731. // MachineOperand having a trivial destructor anyway, and adding a call here
  732. // wouldn't make it 'destructor-correct'.
  733. if (unsigned N = NumOperands - 1 - OpNo)
  734. moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
  735. --NumOperands;
  736. }
  737. /// addMemOperand - Add a MachineMemOperand to the machine instruction.
  738. /// This function should be used only occasionally. The setMemRefs function
  739. /// is the primary method for setting up a MachineInstr's MemRefs list.
  740. void MachineInstr::addMemOperand(MachineFunction &MF,
  741. MachineMemOperand *MO) {
  742. mmo_iterator OldMemRefs = MemRefs;
  743. unsigned OldNumMemRefs = NumMemRefs;
  744. unsigned NewNum = NumMemRefs + 1;
  745. mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
  746. std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
  747. NewMemRefs[NewNum - 1] = MO;
  748. setMemRefs(NewMemRefs, NewMemRefs + NewNum);
  749. }
  750. bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
  751. assert(!isBundledWithPred() && "Must be called on bundle header");
  752. for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
  753. if (MII->getDesc().getFlags() & Mask) {
  754. if (Type == AnyInBundle)
  755. return true;
  756. } else {
  757. if (Type == AllInBundle && !MII->isBundle())
  758. return false;
  759. }
  760. // This was the last instruction in the bundle.
  761. if (!MII->isBundledWithSucc())
  762. return Type == AllInBundle;
  763. }
  764. }
  765. bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
  766. MICheckType Check) const {
  767. // If opcodes or number of operands are not the same then the two
  768. // instructions are obviously not identical.
  769. if (Other->getOpcode() != getOpcode() ||
  770. Other->getNumOperands() != getNumOperands())
  771. return false;
  772. if (isBundle()) {
  773. // Both instructions are bundles, compare MIs inside the bundle.
  774. MachineBasicBlock::const_instr_iterator I1 = *this;
  775. MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
  776. MachineBasicBlock::const_instr_iterator I2 = *Other;
  777. MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
  778. while (++I1 != E1 && I1->isInsideBundle()) {
  779. ++I2;
  780. if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
  781. return false;
  782. }
  783. }
  784. // Check operands to make sure they match.
  785. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  786. const MachineOperand &MO = getOperand(i);
  787. const MachineOperand &OMO = Other->getOperand(i);
  788. if (!MO.isReg()) {
  789. if (!MO.isIdenticalTo(OMO))
  790. return false;
  791. continue;
  792. }
  793. // Clients may or may not want to ignore defs when testing for equality.
  794. // For example, machine CSE pass only cares about finding common
  795. // subexpressions, so it's safe to ignore virtual register defs.
  796. if (MO.isDef()) {
  797. if (Check == IgnoreDefs)
  798. continue;
  799. else if (Check == IgnoreVRegDefs) {
  800. if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
  801. TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
  802. if (MO.getReg() != OMO.getReg())
  803. return false;
  804. } else {
  805. if (!MO.isIdenticalTo(OMO))
  806. return false;
  807. if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
  808. return false;
  809. }
  810. } else {
  811. if (!MO.isIdenticalTo(OMO))
  812. return false;
  813. if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
  814. return false;
  815. }
  816. }
  817. // If DebugLoc does not match then two dbg.values are not identical.
  818. if (isDebugValue())
  819. if (getDebugLoc() && Other->getDebugLoc() &&
  820. getDebugLoc() != Other->getDebugLoc())
  821. return false;
  822. return true;
  823. }
  824. MachineInstr *MachineInstr::removeFromParent() {
  825. assert(getParent() && "Not embedded in a basic block!");
  826. return getParent()->remove(this);
  827. }
  828. MachineInstr *MachineInstr::removeFromBundle() {
  829. assert(getParent() && "Not embedded in a basic block!");
  830. return getParent()->remove_instr(this);
  831. }
  832. void MachineInstr::eraseFromParent() {
  833. assert(getParent() && "Not embedded in a basic block!");
  834. getParent()->erase(this);
  835. }
  836. void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
  837. assert(getParent() && "Not embedded in a basic block!");
  838. MachineBasicBlock *MBB = getParent();
  839. MachineFunction *MF = MBB->getParent();
  840. assert(MF && "Not embedded in a function!");
  841. MachineInstr *MI = (MachineInstr *)this;
  842. MachineRegisterInfo &MRI = MF->getRegInfo();
  843. for (const MachineOperand &MO : MI->operands()) {
  844. if (!MO.isReg() || !MO.isDef())
  845. continue;
  846. unsigned Reg = MO.getReg();
  847. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  848. continue;
  849. MRI.markUsesInDebugValueAsUndef(Reg);
  850. }
  851. MI->eraseFromParent();
  852. }
  853. void MachineInstr::eraseFromBundle() {
  854. assert(getParent() && "Not embedded in a basic block!");
  855. getParent()->erase_instr(this);
  856. }
  857. /// getNumExplicitOperands - Returns the number of non-implicit operands.
  858. ///
  859. unsigned MachineInstr::getNumExplicitOperands() const {
  860. unsigned NumOperands = MCID->getNumOperands();
  861. if (!MCID->isVariadic())
  862. return NumOperands;
  863. for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
  864. const MachineOperand &MO = getOperand(i);
  865. if (!MO.isReg() || !MO.isImplicit())
  866. NumOperands++;
  867. }
  868. return NumOperands;
  869. }
  870. void MachineInstr::bundleWithPred() {
  871. assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
  872. setFlag(BundledPred);
  873. MachineBasicBlock::instr_iterator Pred = this;
  874. --Pred;
  875. assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  876. Pred->setFlag(BundledSucc);
  877. }
  878. void MachineInstr::bundleWithSucc() {
  879. assert(!isBundledWithSucc() && "MI is already bundled with its successor");
  880. setFlag(BundledSucc);
  881. MachineBasicBlock::instr_iterator Succ = this;
  882. ++Succ;
  883. assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
  884. Succ->setFlag(BundledPred);
  885. }
  886. void MachineInstr::unbundleFromPred() {
  887. assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
  888. clearFlag(BundledPred);
  889. MachineBasicBlock::instr_iterator Pred = this;
  890. --Pred;
  891. assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  892. Pred->clearFlag(BundledSucc);
  893. }
  894. void MachineInstr::unbundleFromSucc() {
  895. assert(isBundledWithSucc() && "MI isn't bundled with its successor");
  896. clearFlag(BundledSucc);
  897. MachineBasicBlock::instr_iterator Succ = this;
  898. ++Succ;
  899. assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
  900. Succ->clearFlag(BundledPred);
  901. }
  902. bool MachineInstr::isStackAligningInlineAsm() const {
  903. if (isInlineAsm()) {
  904. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  905. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  906. return true;
  907. }
  908. return false;
  909. }
  910. InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
  911. assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
  912. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  913. return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
  914. }
  915. int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
  916. unsigned *GroupNo) const {
  917. assert(isInlineAsm() && "Expected an inline asm instruction");
  918. assert(OpIdx < getNumOperands() && "OpIdx out of range");
  919. // Ignore queries about the initial operands.
  920. if (OpIdx < InlineAsm::MIOp_FirstOperand)
  921. return -1;
  922. unsigned Group = 0;
  923. unsigned NumOps;
  924. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  925. i += NumOps) {
  926. const MachineOperand &FlagMO = getOperand(i);
  927. // If we reach the implicit register operands, stop looking.
  928. if (!FlagMO.isImm())
  929. return -1;
  930. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  931. if (i + NumOps > OpIdx) {
  932. if (GroupNo)
  933. *GroupNo = Group;
  934. return i;
  935. }
  936. ++Group;
  937. }
  938. return -1;
  939. }
  940. const TargetRegisterClass*
  941. MachineInstr::getRegClassConstraint(unsigned OpIdx,
  942. const TargetInstrInfo *TII,
  943. const TargetRegisterInfo *TRI) const {
  944. assert(getParent() && "Can't have an MBB reference here!");
  945. assert(getParent()->getParent() && "Can't have an MF reference here!");
  946. const MachineFunction &MF = *getParent()->getParent();
  947. // Most opcodes have fixed constraints in their MCInstrDesc.
  948. if (!isInlineAsm())
  949. return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
  950. if (!getOperand(OpIdx).isReg())
  951. return nullptr;
  952. // For tied uses on inline asm, get the constraint from the def.
  953. unsigned DefIdx;
  954. if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
  955. OpIdx = DefIdx;
  956. // Inline asm stores register class constraints in the flag word.
  957. int FlagIdx = findInlineAsmFlagIdx(OpIdx);
  958. if (FlagIdx < 0)
  959. return nullptr;
  960. unsigned Flag = getOperand(FlagIdx).getImm();
  961. unsigned RCID;
  962. if (InlineAsm::hasRegClassConstraint(Flag, RCID))
  963. return TRI->getRegClass(RCID);
  964. // Assume that all registers in a memory operand are pointers.
  965. if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
  966. return TRI->getPointerRegClass(MF);
  967. return nullptr;
  968. }
  969. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
  970. unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
  971. const TargetRegisterInfo *TRI, bool ExploreBundle) const {
  972. // Check every operands inside the bundle if we have
  973. // been asked to.
  974. if (ExploreBundle)
  975. for (ConstMIBundleOperands OpndIt(this); OpndIt.isValid() && CurRC;
  976. ++OpndIt)
  977. CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
  978. OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
  979. else
  980. // Otherwise, just check the current operands.
  981. for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
  982. CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
  983. return CurRC;
  984. }
  985. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
  986. unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
  987. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  988. assert(CurRC && "Invalid initial register class");
  989. // Check if Reg is constrained by some of its use/def from MI.
  990. const MachineOperand &MO = getOperand(OpIdx);
  991. if (!MO.isReg() || MO.getReg() != Reg)
  992. return CurRC;
  993. // If yes, accumulate the constraints through the operand.
  994. return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
  995. }
  996. const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
  997. unsigned OpIdx, const TargetRegisterClass *CurRC,
  998. const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
  999. const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
  1000. const MachineOperand &MO = getOperand(OpIdx);
  1001. assert(MO.isReg() &&
  1002. "Cannot get register constraints for non-register operand");
  1003. assert(CurRC && "Invalid initial register class");
  1004. if (unsigned SubIdx = MO.getSubReg()) {
  1005. if (OpRC)
  1006. CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
  1007. else
  1008. CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
  1009. } else if (OpRC)
  1010. CurRC = TRI->getCommonSubClass(CurRC, OpRC);
  1011. return CurRC;
  1012. }
  1013. /// Return the number of instructions inside the MI bundle, not counting the
  1014. /// header instruction.
  1015. unsigned MachineInstr::getBundleSize() const {
  1016. MachineBasicBlock::const_instr_iterator I = this;
  1017. unsigned Size = 0;
  1018. while (I->isBundledWithSucc())
  1019. ++Size, ++I;
  1020. return Size;
  1021. }
  1022. /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
  1023. /// the specific register or -1 if it is not found. It further tightens
  1024. /// the search criteria to a use that kills the register if isKill is true.
  1025. int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
  1026. const TargetRegisterInfo *TRI) const {
  1027. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1028. const MachineOperand &MO = getOperand(i);
  1029. if (!MO.isReg() || !MO.isUse())
  1030. continue;
  1031. unsigned MOReg = MO.getReg();
  1032. if (!MOReg)
  1033. continue;
  1034. if (MOReg == Reg ||
  1035. (TRI &&
  1036. TargetRegisterInfo::isPhysicalRegister(MOReg) &&
  1037. TargetRegisterInfo::isPhysicalRegister(Reg) &&
  1038. TRI->isSubRegister(MOReg, Reg)))
  1039. if (!isKill || MO.isKill())
  1040. return i;
  1041. }
  1042. return -1;
  1043. }
  1044. /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
  1045. /// indicating if this instruction reads or writes Reg. This also considers
  1046. /// partial defines.
  1047. std::pair<bool,bool>
  1048. MachineInstr::readsWritesVirtualRegister(unsigned Reg,
  1049. SmallVectorImpl<unsigned> *Ops) const {
  1050. bool PartDef = false; // Partial redefine.
  1051. bool FullDef = false; // Full define.
  1052. bool Use = false;
  1053. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1054. const MachineOperand &MO = getOperand(i);
  1055. if (!MO.isReg() || MO.getReg() != Reg)
  1056. continue;
  1057. if (Ops)
  1058. Ops->push_back(i);
  1059. if (MO.isUse())
  1060. Use |= !MO.isUndef();
  1061. else if (MO.getSubReg() && !MO.isUndef())
  1062. // A partial <def,undef> doesn't count as reading the register.
  1063. PartDef = true;
  1064. else
  1065. FullDef = true;
  1066. }
  1067. // A partial redefine uses Reg unless there is also a full define.
  1068. return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
  1069. }
  1070. /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
  1071. /// the specified register or -1 if it is not found. If isDead is true, defs
  1072. /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
  1073. /// also checks if there is a def of a super-register.
  1074. int
  1075. MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
  1076. const TargetRegisterInfo *TRI) const {
  1077. bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
  1078. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1079. const MachineOperand &MO = getOperand(i);
  1080. // Accept regmask operands when Overlap is set.
  1081. // Ignore them when looking for a specific def operand (Overlap == false).
  1082. if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
  1083. return i;
  1084. if (!MO.isReg() || !MO.isDef())
  1085. continue;
  1086. unsigned MOReg = MO.getReg();
  1087. bool Found = (MOReg == Reg);
  1088. if (!Found && TRI && isPhys &&
  1089. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  1090. if (Overlap)
  1091. Found = TRI->regsOverlap(MOReg, Reg);
  1092. else
  1093. Found = TRI->isSubRegister(MOReg, Reg);
  1094. }
  1095. if (Found && (!isDead || MO.isDead()))
  1096. return i;
  1097. }
  1098. return -1;
  1099. }
  1100. /// findFirstPredOperandIdx() - Find the index of the first operand in the
  1101. /// operand list that is used to represent the predicate. It returns -1 if
  1102. /// none is found.
  1103. int MachineInstr::findFirstPredOperandIdx() const {
  1104. // Don't call MCID.findFirstPredOperandIdx() because this variant
  1105. // is sometimes called on an instruction that's not yet complete, and
  1106. // so the number of operands is less than the MCID indicates. In
  1107. // particular, the PTX target does this.
  1108. const MCInstrDesc &MCID = getDesc();
  1109. if (MCID.isPredicable()) {
  1110. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  1111. if (MCID.OpInfo[i].isPredicate())
  1112. return i;
  1113. }
  1114. return -1;
  1115. }
  1116. // MachineOperand::TiedTo is 4 bits wide.
  1117. const unsigned TiedMax = 15;
  1118. /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
  1119. ///
  1120. /// Use and def operands can be tied together, indicated by a non-zero TiedTo
  1121. /// field. TiedTo can have these values:
  1122. ///
  1123. /// 0: Operand is not tied to anything.
  1124. /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
  1125. /// TiedMax: Tied to an operand >= TiedMax-1.
  1126. ///
  1127. /// The tied def must be one of the first TiedMax operands on a normal
  1128. /// instruction. INLINEASM instructions allow more tied defs.
  1129. ///
  1130. void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
  1131. MachineOperand &DefMO = getOperand(DefIdx);
  1132. MachineOperand &UseMO = getOperand(UseIdx);
  1133. assert(DefMO.isDef() && "DefIdx must be a def operand");
  1134. assert(UseMO.isUse() && "UseIdx must be a use operand");
  1135. assert(!DefMO.isTied() && "Def is already tied to another use");
  1136. assert(!UseMO.isTied() && "Use is already tied to another def");
  1137. if (DefIdx < TiedMax)
  1138. UseMO.TiedTo = DefIdx + 1;
  1139. else {
  1140. // Inline asm can use the group descriptors to find tied operands, but on
  1141. // normal instruction, the tied def must be within the first TiedMax
  1142. // operands.
  1143. assert(isInlineAsm() && "DefIdx out of range");
  1144. UseMO.TiedTo = TiedMax;
  1145. }
  1146. // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
  1147. DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
  1148. }
  1149. /// Given the index of a tied register operand, find the operand it is tied to.
  1150. /// Defs are tied to uses and vice versa. Returns the index of the tied operand
  1151. /// which must exist.
  1152. unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
  1153. const MachineOperand &MO = getOperand(OpIdx);
  1154. assert(MO.isTied() && "Operand isn't tied");
  1155. // Normally TiedTo is in range.
  1156. if (MO.TiedTo < TiedMax)
  1157. return MO.TiedTo - 1;
  1158. // Uses on normal instructions can be out of range.
  1159. if (!isInlineAsm()) {
  1160. // Normal tied defs must be in the 0..TiedMax-1 range.
  1161. if (MO.isUse())
  1162. return TiedMax - 1;
  1163. // MO is a def. Search for the tied use.
  1164. for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
  1165. const MachineOperand &UseMO = getOperand(i);
  1166. if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
  1167. return i;
  1168. }
  1169. llvm_unreachable("Can't find tied use");
  1170. }
  1171. // Now deal with inline asm by parsing the operand group descriptor flags.
  1172. // Find the beginning of each operand group.
  1173. SmallVector<unsigned, 8> GroupIdx;
  1174. unsigned OpIdxGroup = ~0u;
  1175. unsigned NumOps;
  1176. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  1177. i += NumOps) {
  1178. const MachineOperand &FlagMO = getOperand(i);
  1179. assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
  1180. unsigned CurGroup = GroupIdx.size();
  1181. GroupIdx.push_back(i);
  1182. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  1183. // OpIdx belongs to this operand group.
  1184. if (OpIdx > i && OpIdx < i + NumOps)
  1185. OpIdxGroup = CurGroup;
  1186. unsigned TiedGroup;
  1187. if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
  1188. continue;
  1189. // Operands in this group are tied to operands in TiedGroup which must be
  1190. // earlier. Find the number of operands between the two groups.
  1191. unsigned Delta = i - GroupIdx[TiedGroup];
  1192. // OpIdx is a use tied to TiedGroup.
  1193. if (OpIdxGroup == CurGroup)
  1194. return OpIdx - Delta;
  1195. // OpIdx is a def tied to this use group.
  1196. if (OpIdxGroup == TiedGroup)
  1197. return OpIdx + Delta;
  1198. }
  1199. llvm_unreachable("Invalid tied operand on inline asm");
  1200. }
  1201. /// clearKillInfo - Clears kill flags on all operands.
  1202. ///
  1203. void MachineInstr::clearKillInfo() {
  1204. for (MachineOperand &MO : operands()) {
  1205. if (MO.isReg() && MO.isUse())
  1206. MO.setIsKill(false);
  1207. }
  1208. }
  1209. void MachineInstr::substituteRegister(unsigned FromReg,
  1210. unsigned ToReg,
  1211. unsigned SubIdx,
  1212. const TargetRegisterInfo &RegInfo) {
  1213. if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
  1214. if (SubIdx)
  1215. ToReg = RegInfo.getSubReg(ToReg, SubIdx);
  1216. for (MachineOperand &MO : operands()) {
  1217. if (!MO.isReg() || MO.getReg() != FromReg)
  1218. continue;
  1219. MO.substPhysReg(ToReg, RegInfo);
  1220. }
  1221. } else {
  1222. for (MachineOperand &MO : operands()) {
  1223. if (!MO.isReg() || MO.getReg() != FromReg)
  1224. continue;
  1225. MO.substVirtReg(ToReg, SubIdx, RegInfo);
  1226. }
  1227. }
  1228. }
  1229. /// isSafeToMove - Return true if it is safe to move this instruction. If
  1230. /// SawStore is set to true, it means that there is a store (or call) between
  1231. /// the instruction's location and its intended destination.
  1232. bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
  1233. // Ignore stuff that we obviously can't move.
  1234. //
  1235. // Treat volatile loads as stores. This is not strictly necessary for
  1236. // volatiles, but it is required for atomic loads. It is not allowed to move
  1237. // a load across an atomic load with Ordering > Monotonic.
  1238. if (mayStore() || isCall() ||
  1239. (mayLoad() && hasOrderedMemoryRef())) {
  1240. SawStore = true;
  1241. return false;
  1242. }
  1243. if (isPosition() || isDebugValue() || isTerminator() ||
  1244. hasUnmodeledSideEffects())
  1245. return false;
  1246. // See if this instruction does a load. If so, we have to guarantee that the
  1247. // loaded value doesn't change between the load and the its intended
  1248. // destination. The check for isInvariantLoad gives the targe the chance to
  1249. // classify the load as always returning a constant, e.g. a constant pool
  1250. // load.
  1251. if (mayLoad() && !isInvariantLoad(AA))
  1252. // Otherwise, this is a real load. If there is a store between the load and
  1253. // end of block, we can't move it.
  1254. return !SawStore;
  1255. return true;
  1256. }
  1257. /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
  1258. /// or volatile memory reference, or if the information describing the memory
  1259. /// reference is not available. Return false if it is known to have no ordered
  1260. /// memory references.
  1261. bool MachineInstr::hasOrderedMemoryRef() const {
  1262. // An instruction known never to access memory won't have a volatile access.
  1263. if (!mayStore() &&
  1264. !mayLoad() &&
  1265. !isCall() &&
  1266. !hasUnmodeledSideEffects())
  1267. return false;
  1268. // Otherwise, if the instruction has no memory reference information,
  1269. // conservatively assume it wasn't preserved.
  1270. if (memoperands_empty())
  1271. return true;
  1272. // Check the memory reference information for ordered references.
  1273. for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
  1274. if (!(*I)->isUnordered())
  1275. return true;
  1276. return false;
  1277. }
  1278. /// isInvariantLoad - Return true if this instruction is loading from a
  1279. /// location whose value is invariant across the function. For example,
  1280. /// loading a value from the constant pool or from the argument area
  1281. /// of a function if it does not change. This should only return true of
  1282. /// *all* loads the instruction does are invariant (if it does multiple loads).
  1283. bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
  1284. // If the instruction doesn't load at all, it isn't an invariant load.
  1285. if (!mayLoad())
  1286. return false;
  1287. // If the instruction has lost its memoperands, conservatively assume that
  1288. // it may not be an invariant load.
  1289. if (memoperands_empty())
  1290. return false;
  1291. const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
  1292. for (mmo_iterator I = memoperands_begin(),
  1293. E = memoperands_end(); I != E; ++I) {
  1294. if ((*I)->isVolatile()) return false;
  1295. if ((*I)->isStore()) return false;
  1296. if ((*I)->isInvariant()) return true;
  1297. // A load from a constant PseudoSourceValue is invariant.
  1298. if (const PseudoSourceValue *PSV = (*I)->getPseudoValue())
  1299. if (PSV->isConstant(MFI))
  1300. continue;
  1301. if (const Value *V = (*I)->getValue()) {
  1302. // If we have an AliasAnalysis, ask it whether the memory is constant.
  1303. if (AA &&
  1304. AA->pointsToConstantMemory(
  1305. MemoryLocation(V, (*I)->getSize(), (*I)->getAAInfo())))
  1306. continue;
  1307. }
  1308. // Otherwise assume conservatively.
  1309. return false;
  1310. }
  1311. // Everything checks out.
  1312. return true;
  1313. }
  1314. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1315. /// merges together the same virtual register, return the register, otherwise
  1316. /// return 0.
  1317. unsigned MachineInstr::isConstantValuePHI() const {
  1318. if (!isPHI())
  1319. return 0;
  1320. assert(getNumOperands() >= 3 &&
  1321. "It's illegal to have a PHI without source operands");
  1322. unsigned Reg = getOperand(1).getReg();
  1323. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1324. if (getOperand(i).getReg() != Reg)
  1325. return 0;
  1326. return Reg;
  1327. }
  1328. bool MachineInstr::hasUnmodeledSideEffects() const {
  1329. if (hasProperty(MCID::UnmodeledSideEffects))
  1330. return true;
  1331. if (isInlineAsm()) {
  1332. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1333. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1334. return true;
  1335. }
  1336. return false;
  1337. }
  1338. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1339. ///
  1340. bool MachineInstr::allDefsAreDead() const {
  1341. for (const MachineOperand &MO : operands()) {
  1342. if (!MO.isReg() || MO.isUse())
  1343. continue;
  1344. if (!MO.isDead())
  1345. return false;
  1346. }
  1347. return true;
  1348. }
  1349. /// copyImplicitOps - Copy implicit register operands from specified
  1350. /// instruction to this instruction.
  1351. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1352. const MachineInstr *MI) {
  1353. for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
  1354. i != e; ++i) {
  1355. const MachineOperand &MO = MI->getOperand(i);
  1356. if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
  1357. addOperand(MF, MO);
  1358. }
  1359. }
  1360. void MachineInstr::dump() const {
  1361. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1362. dbgs() << " " << *this;
  1363. #endif
  1364. }
  1365. void MachineInstr::print(raw_ostream &OS, bool SkipOpers) const {
  1366. const Module *M = nullptr;
  1367. if (const MachineBasicBlock *MBB = getParent())
  1368. if (const MachineFunction *MF = MBB->getParent())
  1369. M = MF->getFunction()->getParent();
  1370. ModuleSlotTracker MST(M);
  1371. print(OS, MST, SkipOpers);
  1372. }
  1373. void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
  1374. bool SkipOpers) const {
  1375. // We can be a bit tidier if we know the MachineFunction.
  1376. const MachineFunction *MF = nullptr;
  1377. const TargetRegisterInfo *TRI = nullptr;
  1378. const MachineRegisterInfo *MRI = nullptr;
  1379. const TargetInstrInfo *TII = nullptr;
  1380. if (const MachineBasicBlock *MBB = getParent()) {
  1381. MF = MBB->getParent();
  1382. if (MF) {
  1383. MRI = &MF->getRegInfo();
  1384. TRI = MF->getSubtarget().getRegisterInfo();
  1385. TII = MF->getSubtarget().getInstrInfo();
  1386. }
  1387. }
  1388. // Save a list of virtual registers.
  1389. SmallVector<unsigned, 8> VirtRegs;
  1390. // Print explicitly defined operands on the left of an assignment syntax.
  1391. unsigned StartOp = 0, e = getNumOperands();
  1392. for (; StartOp < e && getOperand(StartOp).isReg() &&
  1393. getOperand(StartOp).isDef() &&
  1394. !getOperand(StartOp).isImplicit();
  1395. ++StartOp) {
  1396. if (StartOp != 0) OS << ", ";
  1397. getOperand(StartOp).print(OS, MST, TRI);
  1398. unsigned Reg = getOperand(StartOp).getReg();
  1399. if (TargetRegisterInfo::isVirtualRegister(Reg))
  1400. VirtRegs.push_back(Reg);
  1401. }
  1402. if (StartOp != 0)
  1403. OS << " = ";
  1404. // Print the opcode name.
  1405. if (TII)
  1406. OS << TII->getName(getOpcode());
  1407. else
  1408. OS << "UNKNOWN";
  1409. if (SkipOpers)
  1410. return;
  1411. // Print the rest of the operands.
  1412. bool OmittedAnyCallClobbers = false;
  1413. bool FirstOp = true;
  1414. unsigned AsmDescOp = ~0u;
  1415. unsigned AsmOpCount = 0;
  1416. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1417. // Print asm string.
  1418. OS << " ";
  1419. getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
  1420. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1421. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1422. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1423. OS << " [sideeffect]";
  1424. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1425. OS << " [mayload]";
  1426. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1427. OS << " [maystore]";
  1428. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1429. OS << " [alignstack]";
  1430. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1431. OS << " [attdialect]";
  1432. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1433. OS << " [inteldialect]";
  1434. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1435. FirstOp = false;
  1436. }
  1437. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1438. const MachineOperand &MO = getOperand(i);
  1439. if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1440. VirtRegs.push_back(MO.getReg());
  1441. // Omit call-clobbered registers which aren't used anywhere. This makes
  1442. // call instructions much less noisy on targets where calls clobber lots
  1443. // of registers. Don't rely on MO.isDead() because we may be called before
  1444. // LiveVariables is run, or we may be looking at a non-allocatable reg.
  1445. if (MRI && isCall() &&
  1446. MO.isReg() && MO.isImplicit() && MO.isDef()) {
  1447. unsigned Reg = MO.getReg();
  1448. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1449. if (MRI->use_empty(Reg)) {
  1450. bool HasAliasLive = false;
  1451. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
  1452. unsigned AliasReg = *AI;
  1453. if (!MRI->use_empty(AliasReg)) {
  1454. HasAliasLive = true;
  1455. break;
  1456. }
  1457. }
  1458. if (!HasAliasLive) {
  1459. OmittedAnyCallClobbers = true;
  1460. continue;
  1461. }
  1462. }
  1463. }
  1464. }
  1465. if (FirstOp) FirstOp = false; else OS << ",";
  1466. OS << " ";
  1467. if (i < getDesc().NumOperands) {
  1468. const MCOperandInfo &MCOI = getDesc().OpInfo[i];
  1469. if (MCOI.isPredicate())
  1470. OS << "pred:";
  1471. if (MCOI.isOptionalDef())
  1472. OS << "opt:";
  1473. }
  1474. if (isDebugValue() && MO.isMetadata()) {
  1475. // Pretty print DBG_VALUE instructions.
  1476. auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
  1477. if (DIV && !DIV->getName().empty())
  1478. OS << "!\"" << DIV->getName() << '\"';
  1479. else
  1480. MO.print(OS, MST, TRI);
  1481. } else if (TRI && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
  1482. OS << TRI->getSubRegIndexName(MO.getImm());
  1483. } else if (i == AsmDescOp && MO.isImm()) {
  1484. // Pretty print the inline asm operand descriptor.
  1485. OS << '$' << AsmOpCount++;
  1486. unsigned Flag = MO.getImm();
  1487. switch (InlineAsm::getKind(Flag)) {
  1488. case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
  1489. case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
  1490. case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
  1491. case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
  1492. case InlineAsm::Kind_Imm: OS << ":[imm"; break;
  1493. case InlineAsm::Kind_Mem: OS << ":[mem"; break;
  1494. default: OS << ":[??" << InlineAsm::getKind(Flag); break;
  1495. }
  1496. unsigned RCID = 0;
  1497. if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1498. if (TRI) {
  1499. OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
  1500. } else
  1501. OS << ":RC" << RCID;
  1502. }
  1503. unsigned TiedTo = 0;
  1504. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1505. OS << " tiedto:$" << TiedTo;
  1506. OS << ']';
  1507. // Compute the index of the next operand descriptor.
  1508. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1509. } else
  1510. MO.print(OS, MST, TRI);
  1511. }
  1512. // Briefly indicate whether any call clobbers were omitted.
  1513. if (OmittedAnyCallClobbers) {
  1514. if (!FirstOp) OS << ",";
  1515. OS << " ...";
  1516. }
  1517. bool HaveSemi = false;
  1518. const unsigned PrintableFlags = FrameSetup;
  1519. if (Flags & PrintableFlags) {
  1520. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1521. OS << " flags: ";
  1522. if (Flags & FrameSetup)
  1523. OS << "FrameSetup";
  1524. }
  1525. if (!memoperands_empty()) {
  1526. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1527. OS << " mem:";
  1528. for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
  1529. i != e; ++i) {
  1530. (*i)->print(OS, MST);
  1531. if (std::next(i) != e)
  1532. OS << " ";
  1533. }
  1534. }
  1535. // Print the regclass of any virtual registers encountered.
  1536. if (MRI && !VirtRegs.empty()) {
  1537. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1538. for (unsigned i = 0; i != VirtRegs.size(); ++i) {
  1539. const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
  1540. OS << " " << TRI->getRegClassName(RC)
  1541. << ':' << PrintReg(VirtRegs[i]);
  1542. for (unsigned j = i+1; j != VirtRegs.size();) {
  1543. if (MRI->getRegClass(VirtRegs[j]) != RC) {
  1544. ++j;
  1545. continue;
  1546. }
  1547. if (VirtRegs[i] != VirtRegs[j])
  1548. OS << "," << PrintReg(VirtRegs[j]);
  1549. VirtRegs.erase(VirtRegs.begin()+j);
  1550. }
  1551. }
  1552. }
  1553. // Print debug location information.
  1554. if (isDebugValue() && getOperand(e - 2).isMetadata()) {
  1555. if (!HaveSemi) OS << ";";
  1556. auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
  1557. OS << " line no:" << DV->getLine();
  1558. if (auto *InlinedAt = debugLoc->getInlinedAt()) {
  1559. DebugLoc InlinedAtDL(InlinedAt);
  1560. if (InlinedAtDL && MF) {
  1561. OS << " inlined @[ ";
  1562. InlinedAtDL.print(OS);
  1563. OS << " ]";
  1564. }
  1565. }
  1566. if (isIndirectDebugValue())
  1567. OS << " indirect";
  1568. } else if (debugLoc && MF) {
  1569. if (!HaveSemi) OS << ";";
  1570. OS << " dbg:";
  1571. debugLoc.print(OS);
  1572. }
  1573. OS << '\n';
  1574. }
  1575. bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
  1576. const TargetRegisterInfo *RegInfo,
  1577. bool AddIfNotFound) {
  1578. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
  1579. bool hasAliases = isPhysReg &&
  1580. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1581. bool Found = false;
  1582. SmallVector<unsigned,4> DeadOps;
  1583. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1584. MachineOperand &MO = getOperand(i);
  1585. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1586. continue;
  1587. unsigned Reg = MO.getReg();
  1588. if (!Reg)
  1589. continue;
  1590. if (Reg == IncomingReg) {
  1591. if (!Found) {
  1592. if (MO.isKill())
  1593. // The register is already marked kill.
  1594. return true;
  1595. if (isPhysReg && isRegTiedToDefOperand(i))
  1596. // Two-address uses of physregs must not be marked kill.
  1597. return true;
  1598. MO.setIsKill();
  1599. Found = true;
  1600. }
  1601. } else if (hasAliases && MO.isKill() &&
  1602. TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1603. // A super-register kill already exists.
  1604. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1605. return true;
  1606. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1607. DeadOps.push_back(i);
  1608. }
  1609. }
  1610. // Trim unneeded kill operands.
  1611. while (!DeadOps.empty()) {
  1612. unsigned OpIdx = DeadOps.back();
  1613. if (getOperand(OpIdx).isImplicit())
  1614. RemoveOperand(OpIdx);
  1615. else
  1616. getOperand(OpIdx).setIsKill(false);
  1617. DeadOps.pop_back();
  1618. }
  1619. // If not found, this means an alias of one of the operands is killed. Add a
  1620. // new implicit operand if required.
  1621. if (!Found && AddIfNotFound) {
  1622. addOperand(MachineOperand::CreateReg(IncomingReg,
  1623. false /*IsDef*/,
  1624. true /*IsImp*/,
  1625. true /*IsKill*/));
  1626. return true;
  1627. }
  1628. return Found;
  1629. }
  1630. void MachineInstr::clearRegisterKills(unsigned Reg,
  1631. const TargetRegisterInfo *RegInfo) {
  1632. if (!TargetRegisterInfo::isPhysicalRegister(Reg))
  1633. RegInfo = nullptr;
  1634. for (MachineOperand &MO : operands()) {
  1635. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1636. continue;
  1637. unsigned OpReg = MO.getReg();
  1638. if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
  1639. MO.setIsKill(false);
  1640. }
  1641. }
  1642. bool MachineInstr::addRegisterDead(unsigned Reg,
  1643. const TargetRegisterInfo *RegInfo,
  1644. bool AddIfNotFound) {
  1645. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
  1646. bool hasAliases = isPhysReg &&
  1647. MCRegAliasIterator(Reg, RegInfo, false).isValid();
  1648. bool Found = false;
  1649. SmallVector<unsigned,4> DeadOps;
  1650. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1651. MachineOperand &MO = getOperand(i);
  1652. if (!MO.isReg() || !MO.isDef())
  1653. continue;
  1654. unsigned MOReg = MO.getReg();
  1655. if (!MOReg)
  1656. continue;
  1657. if (MOReg == Reg) {
  1658. MO.setIsDead();
  1659. Found = true;
  1660. } else if (hasAliases && MO.isDead() &&
  1661. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  1662. // There exists a super-register that's marked dead.
  1663. if (RegInfo->isSuperRegister(Reg, MOReg))
  1664. return true;
  1665. if (RegInfo->isSubRegister(Reg, MOReg))
  1666. DeadOps.push_back(i);
  1667. }
  1668. }
  1669. // Trim unneeded dead operands.
  1670. while (!DeadOps.empty()) {
  1671. unsigned OpIdx = DeadOps.back();
  1672. if (getOperand(OpIdx).isImplicit())
  1673. RemoveOperand(OpIdx);
  1674. else
  1675. getOperand(OpIdx).setIsDead(false);
  1676. DeadOps.pop_back();
  1677. }
  1678. // If not found, this means an alias of one of the operands is dead. Add a
  1679. // new implicit operand if required.
  1680. if (Found || !AddIfNotFound)
  1681. return Found;
  1682. addOperand(MachineOperand::CreateReg(Reg,
  1683. true /*IsDef*/,
  1684. true /*IsImp*/,
  1685. false /*IsKill*/,
  1686. true /*IsDead*/));
  1687. return true;
  1688. }
  1689. void MachineInstr::clearRegisterDeads(unsigned Reg) {
  1690. for (MachineOperand &MO : operands()) {
  1691. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
  1692. continue;
  1693. MO.setIsDead(false);
  1694. }
  1695. }
  1696. void MachineInstr::addRegisterDefReadUndef(unsigned Reg) {
  1697. for (MachineOperand &MO : operands()) {
  1698. if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
  1699. continue;
  1700. MO.setIsUndef();
  1701. }
  1702. }
  1703. void MachineInstr::addRegisterDefined(unsigned Reg,
  1704. const TargetRegisterInfo *RegInfo) {
  1705. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1706. MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
  1707. if (MO)
  1708. return;
  1709. } else {
  1710. for (const MachineOperand &MO : operands()) {
  1711. if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
  1712. MO.getSubReg() == 0)
  1713. return;
  1714. }
  1715. }
  1716. addOperand(MachineOperand::CreateReg(Reg,
  1717. true /*IsDef*/,
  1718. true /*IsImp*/));
  1719. }
  1720. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
  1721. const TargetRegisterInfo &TRI) {
  1722. bool HasRegMask = false;
  1723. for (MachineOperand &MO : operands()) {
  1724. if (MO.isRegMask()) {
  1725. HasRegMask = true;
  1726. continue;
  1727. }
  1728. if (!MO.isReg() || !MO.isDef()) continue;
  1729. unsigned Reg = MO.getReg();
  1730. if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  1731. // If there are no uses, including partial uses, the def is dead.
  1732. if (std::none_of(UsedRegs.begin(), UsedRegs.end(),
  1733. [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
  1734. MO.setIsDead();
  1735. }
  1736. // This is a call with a register mask operand.
  1737. // Mask clobbers are always dead, so add defs for the non-dead defines.
  1738. if (HasRegMask)
  1739. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1740. I != E; ++I)
  1741. addRegisterDefined(*I, &TRI);
  1742. }
  1743. unsigned
  1744. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  1745. // Build up a buffer of hash code components.
  1746. SmallVector<size_t, 8> HashComponents;
  1747. HashComponents.reserve(MI->getNumOperands() + 1);
  1748. HashComponents.push_back(MI->getOpcode());
  1749. for (const MachineOperand &MO : MI->operands()) {
  1750. if (MO.isReg() && MO.isDef() &&
  1751. TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1752. continue; // Skip virtual register defs.
  1753. HashComponents.push_back(hash_value(MO));
  1754. }
  1755. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  1756. }
  1757. void MachineInstr::emitError(StringRef Msg) const {
  1758. // Find the source location cookie.
  1759. unsigned LocCookie = 0;
  1760. const MDNode *LocMD = nullptr;
  1761. for (unsigned i = getNumOperands(); i != 0; --i) {
  1762. if (getOperand(i-1).isMetadata() &&
  1763. (LocMD = getOperand(i-1).getMetadata()) &&
  1764. LocMD->getNumOperands() != 0) {
  1765. if (const ConstantInt *CI =
  1766. mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
  1767. LocCookie = CI->getZExtValue();
  1768. break;
  1769. }
  1770. }
  1771. }
  1772. if (const MachineBasicBlock *MBB = getParent())
  1773. if (const MachineFunction *MF = MBB->getParent())
  1774. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  1775. report_fatal_error(Msg);
  1776. }