MachineInstr.cpp 83 KB

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