MachineInstr.cpp 65 KB

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