MachineInstr.cpp 67 KB

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