MachineInstr.cpp 64 KB

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