InstrEmitter.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements the Emit routines for the SelectionDAG class, which creates
  10. // MachineInstrs based on the decisions of the SelectionDAG instruction
  11. // selection.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "InstrEmitter.h"
  15. #include "SDNodeDbgValue.h"
  16. #include "llvm/BinaryFormat/Dwarf.h"
  17. #include "llvm/CodeGen/MachineConstantPool.h"
  18. #include "llvm/CodeGen/MachineFunction.h"
  19. #include "llvm/CodeGen/MachineInstrBuilder.h"
  20. #include "llvm/CodeGen/MachineRegisterInfo.h"
  21. #include "llvm/CodeGen/StackMaps.h"
  22. #include "llvm/CodeGen/TargetInstrInfo.h"
  23. #include "llvm/CodeGen/TargetLowering.h"
  24. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  25. #include "llvm/IR/DebugInfoMetadata.h"
  26. #include "llvm/IR/PseudoProbe.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Target/TargetMachine.h"
  29. using namespace llvm;
  30. #define DEBUG_TYPE "instr-emitter"
  31. /// MinRCSize - Smallest register class we allow when constraining virtual
  32. /// registers. If satisfying all register class constraints would require
  33. /// using a smaller register class, emit a COPY to a new virtual register
  34. /// instead.
  35. const unsigned MinRCSize = 4;
  36. /// CountResults - The results of target nodes have register or immediate
  37. /// operands first, then an optional chain, and optional glue operands (which do
  38. /// not go into the resulting MachineInstr).
  39. unsigned InstrEmitter::CountResults(SDNode *Node) {
  40. unsigned N = Node->getNumValues();
  41. while (N && Node->getValueType(N - 1) == MVT::Glue)
  42. --N;
  43. if (N && Node->getValueType(N - 1) == MVT::Other)
  44. --N; // Skip over chain result.
  45. return N;
  46. }
  47. /// countOperands - The inputs to target nodes have any actual inputs first,
  48. /// followed by an optional chain operand, then an optional glue operand.
  49. /// Compute the number of actual operands that will go into the resulting
  50. /// MachineInstr.
  51. ///
  52. /// Also count physreg RegisterSDNode and RegisterMaskSDNode operands preceding
  53. /// the chain and glue. These operands may be implicit on the machine instr.
  54. static unsigned countOperands(SDNode *Node, unsigned NumExpUses,
  55. unsigned &NumImpUses) {
  56. unsigned N = Node->getNumOperands();
  57. while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
  58. --N;
  59. if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
  60. --N; // Ignore chain if it exists.
  61. // Count RegisterSDNode and RegisterMaskSDNode operands for NumImpUses.
  62. NumImpUses = N - NumExpUses;
  63. for (unsigned I = N; I > NumExpUses; --I) {
  64. if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1)))
  65. continue;
  66. if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1)))
  67. if (RN->getReg().isPhysical())
  68. continue;
  69. NumImpUses = N - I;
  70. break;
  71. }
  72. return N;
  73. }
  74. /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
  75. /// implicit physical register output.
  76. void InstrEmitter::EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone,
  77. Register SrcReg,
  78. DenseMap<SDValue, Register> &VRBaseMap) {
  79. Register VRBase;
  80. if (SrcReg.isVirtual()) {
  81. // Just use the input register directly!
  82. SDValue Op(Node, ResNo);
  83. if (IsClone)
  84. VRBaseMap.erase(Op);
  85. bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
  86. (void)isNew; // Silence compiler warning.
  87. assert(isNew && "Node emitted out of order - early");
  88. return;
  89. }
  90. // If the node is only used by a CopyToReg and the dest reg is a vreg, use
  91. // the CopyToReg'd destination register instead of creating a new vreg.
  92. bool MatchReg = true;
  93. const TargetRegisterClass *UseRC = nullptr;
  94. MVT VT = Node->getSimpleValueType(ResNo);
  95. // Stick to the preferred register classes for legal types.
  96. if (TLI->isTypeLegal(VT))
  97. UseRC = TLI->getRegClassFor(VT, Node->isDivergent());
  98. for (SDNode *User : Node->uses()) {
  99. bool Match = true;
  100. if (User->getOpcode() == ISD::CopyToReg &&
  101. User->getOperand(2).getNode() == Node &&
  102. User->getOperand(2).getResNo() == ResNo) {
  103. Register DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
  104. if (DestReg.isVirtual()) {
  105. VRBase = DestReg;
  106. Match = false;
  107. } else if (DestReg != SrcReg)
  108. Match = false;
  109. } else {
  110. for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
  111. SDValue Op = User->getOperand(i);
  112. if (Op.getNode() != Node || Op.getResNo() != ResNo)
  113. continue;
  114. MVT VT = Node->getSimpleValueType(Op.getResNo());
  115. if (VT == MVT::Other || VT == MVT::Glue)
  116. continue;
  117. Match = false;
  118. if (User->isMachineOpcode()) {
  119. const MCInstrDesc &II = TII->get(User->getMachineOpcode());
  120. const TargetRegisterClass *RC = nullptr;
  121. if (i + II.getNumDefs() < II.getNumOperands()) {
  122. RC = TRI->getAllocatableClass(
  123. TII->getRegClass(II, i + II.getNumDefs(), TRI, *MF));
  124. }
  125. if (!UseRC)
  126. UseRC = RC;
  127. else if (RC) {
  128. const TargetRegisterClass *ComRC =
  129. TRI->getCommonSubClass(UseRC, RC);
  130. // If multiple uses expect disjoint register classes, we emit
  131. // copies in AddRegisterOperand.
  132. if (ComRC)
  133. UseRC = ComRC;
  134. }
  135. }
  136. }
  137. }
  138. MatchReg &= Match;
  139. if (VRBase)
  140. break;
  141. }
  142. const TargetRegisterClass *SrcRC = nullptr, *DstRC = nullptr;
  143. SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
  144. // Figure out the register class to create for the destreg.
  145. if (VRBase) {
  146. DstRC = MRI->getRegClass(VRBase);
  147. } else if (UseRC) {
  148. assert(TRI->isTypeLegalForClass(*UseRC, VT) &&
  149. "Incompatible phys register def and uses!");
  150. DstRC = UseRC;
  151. } else
  152. DstRC = SrcRC;
  153. // If all uses are reading from the src physical register and copying the
  154. // register is either impossible or very expensive, then don't create a copy.
  155. if (MatchReg && SrcRC->getCopyCost() < 0) {
  156. VRBase = SrcReg;
  157. } else {
  158. // Create the reg, emit the copy.
  159. VRBase = MRI->createVirtualRegister(DstRC);
  160. BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
  161. VRBase).addReg(SrcReg);
  162. }
  163. SDValue Op(Node, ResNo);
  164. if (IsClone)
  165. VRBaseMap.erase(Op);
  166. bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
  167. (void)isNew; // Silence compiler warning.
  168. assert(isNew && "Node emitted out of order - early");
  169. }
  170. void InstrEmitter::CreateVirtualRegisters(SDNode *Node,
  171. MachineInstrBuilder &MIB,
  172. const MCInstrDesc &II,
  173. bool IsClone, bool IsCloned,
  174. DenseMap<SDValue, Register> &VRBaseMap) {
  175. assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
  176. "IMPLICIT_DEF should have been handled as a special case elsewhere!");
  177. unsigned NumResults = CountResults(Node);
  178. bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() &&
  179. II.isVariadic() && II.variadicOpsAreDefs();
  180. unsigned NumVRegs = HasVRegVariadicDefs ? NumResults : II.getNumDefs();
  181. if (Node->getMachineOpcode() == TargetOpcode::STATEPOINT)
  182. NumVRegs = NumResults;
  183. for (unsigned i = 0; i < NumVRegs; ++i) {
  184. // If the specific node value is only used by a CopyToReg and the dest reg
  185. // is a vreg in the same register class, use the CopyToReg'd destination
  186. // register instead of creating a new vreg.
  187. Register VRBase;
  188. const TargetRegisterClass *RC =
  189. TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF));
  190. // Always let the value type influence the used register class. The
  191. // constraints on the instruction may be too lax to represent the value
  192. // type correctly. For example, a 64-bit float (X86::FR64) can't live in
  193. // the 32-bit float super-class (X86::FR32).
  194. if (i < NumResults && TLI->isTypeLegal(Node->getSimpleValueType(i))) {
  195. const TargetRegisterClass *VTRC = TLI->getRegClassFor(
  196. Node->getSimpleValueType(i),
  197. (Node->isDivergent() || (RC && TRI->isDivergentRegClass(RC))));
  198. if (RC)
  199. VTRC = TRI->getCommonSubClass(RC, VTRC);
  200. if (VTRC)
  201. RC = VTRC;
  202. }
  203. if (!II.operands().empty() && II.operands()[i].isOptionalDef()) {
  204. // Optional def must be a physical register.
  205. VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
  206. assert(VRBase.isPhysical());
  207. MIB.addReg(VRBase, RegState::Define);
  208. }
  209. if (!VRBase && !IsClone && !IsCloned)
  210. for (SDNode *User : Node->uses()) {
  211. if (User->getOpcode() == ISD::CopyToReg &&
  212. User->getOperand(2).getNode() == Node &&
  213. User->getOperand(2).getResNo() == i) {
  214. Register Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
  215. if (Reg.isVirtual()) {
  216. const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
  217. if (RegRC == RC) {
  218. VRBase = Reg;
  219. MIB.addReg(VRBase, RegState::Define);
  220. break;
  221. }
  222. }
  223. }
  224. }
  225. // Create the result registers for this node and add the result regs to
  226. // the machine instruction.
  227. if (VRBase == 0) {
  228. assert(RC && "Isn't a register operand!");
  229. VRBase = MRI->createVirtualRegister(RC);
  230. MIB.addReg(VRBase, RegState::Define);
  231. }
  232. // If this def corresponds to a result of the SDNode insert the VRBase into
  233. // the lookup map.
  234. if (i < NumResults) {
  235. SDValue Op(Node, i);
  236. if (IsClone)
  237. VRBaseMap.erase(Op);
  238. bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
  239. (void)isNew; // Silence compiler warning.
  240. assert(isNew && "Node emitted out of order - early");
  241. }
  242. }
  243. }
  244. /// getVR - Return the virtual register corresponding to the specified result
  245. /// of the specified node.
  246. Register InstrEmitter::getVR(SDValue Op,
  247. DenseMap<SDValue, Register> &VRBaseMap) {
  248. if (Op.isMachineOpcode() &&
  249. Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
  250. // Add an IMPLICIT_DEF instruction before every use.
  251. // IMPLICIT_DEF can produce any type of result so its MCInstrDesc
  252. // does not include operand register class info.
  253. const TargetRegisterClass *RC = TLI->getRegClassFor(
  254. Op.getSimpleValueType(), Op.getNode()->isDivergent());
  255. Register VReg = MRI->createVirtualRegister(RC);
  256. BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
  257. TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
  258. return VReg;
  259. }
  260. DenseMap<SDValue, Register>::iterator I = VRBaseMap.find(Op);
  261. assert(I != VRBaseMap.end() && "Node emitted out of order - late");
  262. return I->second;
  263. }
  264. /// AddRegisterOperand - Add the specified register as an operand to the
  265. /// specified machine instr. Insert register copies if the register is
  266. /// not in the required register class.
  267. void
  268. InstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB,
  269. SDValue Op,
  270. unsigned IIOpNum,
  271. const MCInstrDesc *II,
  272. DenseMap<SDValue, Register> &VRBaseMap,
  273. bool IsDebug, bool IsClone, bool IsCloned) {
  274. assert(Op.getValueType() != MVT::Other &&
  275. Op.getValueType() != MVT::Glue &&
  276. "Chain and glue operands should occur at end of operand list!");
  277. // Get/emit the operand.
  278. Register VReg = getVR(Op, VRBaseMap);
  279. const MCInstrDesc &MCID = MIB->getDesc();
  280. bool isOptDef = IIOpNum < MCID.getNumOperands() &&
  281. MCID.operands()[IIOpNum].isOptionalDef();
  282. // If the instruction requires a register in a different class, create
  283. // a new virtual register and copy the value into it, but first attempt to
  284. // shrink VReg's register class within reason. For example, if VReg == GR32
  285. // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
  286. if (II) {
  287. const TargetRegisterClass *OpRC = nullptr;
  288. if (IIOpNum < II->getNumOperands())
  289. OpRC = TII->getRegClass(*II, IIOpNum, TRI, *MF);
  290. if (OpRC) {
  291. unsigned MinNumRegs = MinRCSize;
  292. // Don't apply any RC size limit for IMPLICIT_DEF. Each use has a unique
  293. // virtual register.
  294. if (Op.isMachineOpcode() &&
  295. Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF)
  296. MinNumRegs = 0;
  297. const TargetRegisterClass *ConstrainedRC
  298. = MRI->constrainRegClass(VReg, OpRC, MinNumRegs);
  299. if (!ConstrainedRC) {
  300. OpRC = TRI->getAllocatableClass(OpRC);
  301. assert(OpRC && "Constraints cannot be fulfilled for allocation");
  302. Register NewVReg = MRI->createVirtualRegister(OpRC);
  303. BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
  304. TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
  305. VReg = NewVReg;
  306. } else {
  307. assert(ConstrainedRC->isAllocatable() &&
  308. "Constraining an allocatable VReg produced an unallocatable class?");
  309. }
  310. }
  311. }
  312. // If this value has only one use, that use is a kill. This is a
  313. // conservative approximation. InstrEmitter does trivial coalescing
  314. // with CopyFromReg nodes, so don't emit kill flags for them.
  315. // Avoid kill flags on Schedule cloned nodes, since there will be
  316. // multiple uses.
  317. // Tied operands are never killed, so we need to check that. And that
  318. // means we need to determine the index of the operand.
  319. bool isKill = Op.hasOneUse() &&
  320. Op.getNode()->getOpcode() != ISD::CopyFromReg &&
  321. !IsDebug &&
  322. !(IsClone || IsCloned);
  323. if (isKill) {
  324. unsigned Idx = MIB->getNumOperands();
  325. while (Idx > 0 &&
  326. MIB->getOperand(Idx-1).isReg() &&
  327. MIB->getOperand(Idx-1).isImplicit())
  328. --Idx;
  329. bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
  330. if (isTied)
  331. isKill = false;
  332. }
  333. MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) |
  334. getDebugRegState(IsDebug));
  335. }
  336. /// AddOperand - Add the specified operand to the specified machine instr. II
  337. /// specifies the instruction information for the node, and IIOpNum is the
  338. /// operand number (in the II) that we are adding.
  339. void InstrEmitter::AddOperand(MachineInstrBuilder &MIB,
  340. SDValue Op,
  341. unsigned IIOpNum,
  342. const MCInstrDesc *II,
  343. DenseMap<SDValue, Register> &VRBaseMap,
  344. bool IsDebug, bool IsClone, bool IsCloned) {
  345. if (Op.isMachineOpcode()) {
  346. AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
  347. IsDebug, IsClone, IsCloned);
  348. } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
  349. MIB.addImm(C->getSExtValue());
  350. } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
  351. MIB.addFPImm(F->getConstantFPValue());
  352. } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
  353. Register VReg = R->getReg();
  354. MVT OpVT = Op.getSimpleValueType();
  355. const TargetRegisterClass *IIRC =
  356. II ? TRI->getAllocatableClass(TII->getRegClass(*II, IIOpNum, TRI, *MF))
  357. : nullptr;
  358. const TargetRegisterClass *OpRC =
  359. TLI->isTypeLegal(OpVT)
  360. ? TLI->getRegClassFor(OpVT,
  361. Op.getNode()->isDivergent() ||
  362. (IIRC && TRI->isDivergentRegClass(IIRC)))
  363. : nullptr;
  364. if (OpRC && IIRC && OpRC != IIRC && VReg.isVirtual()) {
  365. Register NewVReg = MRI->createVirtualRegister(IIRC);
  366. BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
  367. TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
  368. VReg = NewVReg;
  369. }
  370. // Turn additional physreg operands into implicit uses on non-variadic
  371. // instructions. This is used by call and return instructions passing
  372. // arguments in registers.
  373. bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic());
  374. MIB.addReg(VReg, getImplRegState(Imp));
  375. } else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
  376. MIB.addRegMask(RM->getRegMask());
  377. } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
  378. MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(),
  379. TGA->getTargetFlags());
  380. } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
  381. MIB.addMBB(BBNode->getBasicBlock());
  382. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
  383. MIB.addFrameIndex(FI->getIndex());
  384. } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
  385. MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags());
  386. } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
  387. int Offset = CP->getOffset();
  388. Align Alignment = CP->getAlign();
  389. unsigned Idx;
  390. MachineConstantPool *MCP = MF->getConstantPool();
  391. if (CP->isMachineConstantPoolEntry())
  392. Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Alignment);
  393. else
  394. Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Alignment);
  395. MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags());
  396. } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
  397. MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags());
  398. } else if (auto *SymNode = dyn_cast<MCSymbolSDNode>(Op)) {
  399. MIB.addSym(SymNode->getMCSymbol());
  400. } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
  401. MIB.addBlockAddress(BA->getBlockAddress(),
  402. BA->getOffset(),
  403. BA->getTargetFlags());
  404. } else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
  405. MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags());
  406. } else {
  407. assert(Op.getValueType() != MVT::Other &&
  408. Op.getValueType() != MVT::Glue &&
  409. "Chain and glue operands should occur at end of operand list!");
  410. AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
  411. IsDebug, IsClone, IsCloned);
  412. }
  413. }
  414. Register InstrEmitter::ConstrainForSubReg(Register VReg, unsigned SubIdx,
  415. MVT VT, bool isDivergent, const DebugLoc &DL) {
  416. const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
  417. const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
  418. // RC is a sub-class of VRC that supports SubIdx. Try to constrain VReg
  419. // within reason.
  420. if (RC && RC != VRC)
  421. RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
  422. // VReg has been adjusted. It can be used with SubIdx operands now.
  423. if (RC)
  424. return VReg;
  425. // VReg couldn't be reasonably constrained. Emit a COPY to a new virtual
  426. // register instead.
  427. RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT, isDivergent), SubIdx);
  428. assert(RC && "No legal register class for VT supports that SubIdx");
  429. Register NewReg = MRI->createVirtualRegister(RC);
  430. BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
  431. .addReg(VReg);
  432. return NewReg;
  433. }
  434. /// EmitSubregNode - Generate machine code for subreg nodes.
  435. ///
  436. void InstrEmitter::EmitSubregNode(SDNode *Node,
  437. DenseMap<SDValue, Register> &VRBaseMap,
  438. bool IsClone, bool IsCloned) {
  439. Register VRBase;
  440. unsigned Opc = Node->getMachineOpcode();
  441. // If the node is only used by a CopyToReg and the dest reg is a vreg, use
  442. // the CopyToReg'd destination register instead of creating a new vreg.
  443. for (SDNode *User : Node->uses()) {
  444. if (User->getOpcode() == ISD::CopyToReg &&
  445. User->getOperand(2).getNode() == Node) {
  446. Register DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
  447. if (DestReg.isVirtual()) {
  448. VRBase = DestReg;
  449. break;
  450. }
  451. }
  452. }
  453. if (Opc == TargetOpcode::EXTRACT_SUBREG) {
  454. // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub. There are no
  455. // constraints on the %dst register, COPY can target all legal register
  456. // classes.
  457. unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
  458. const TargetRegisterClass *TRC =
  459. TLI->getRegClassFor(Node->getSimpleValueType(0), Node->isDivergent());
  460. Register Reg;
  461. MachineInstr *DefMI;
  462. RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(0));
  463. if (R && R->getReg().isPhysical()) {
  464. Reg = R->getReg();
  465. DefMI = nullptr;
  466. } else {
  467. Reg = R ? R->getReg() : getVR(Node->getOperand(0), VRBaseMap);
  468. DefMI = MRI->getVRegDef(Reg);
  469. }
  470. Register SrcReg, DstReg;
  471. unsigned DefSubIdx;
  472. if (DefMI &&
  473. TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
  474. SubIdx == DefSubIdx &&
  475. TRC == MRI->getRegClass(SrcReg)) {
  476. // Optimize these:
  477. // r1025 = s/zext r1024, 4
  478. // r1026 = extract_subreg r1025, 4
  479. // to a copy
  480. // r1026 = copy r1024
  481. VRBase = MRI->createVirtualRegister(TRC);
  482. BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
  483. TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
  484. MRI->clearKillFlags(SrcReg);
  485. } else {
  486. // Reg may not support a SubIdx sub-register, and we may need to
  487. // constrain its register class or issue a COPY to a compatible register
  488. // class.
  489. if (Reg.isVirtual())
  490. Reg = ConstrainForSubReg(Reg, SubIdx,
  491. Node->getOperand(0).getSimpleValueType(),
  492. Node->isDivergent(), Node->getDebugLoc());
  493. // Create the destreg if it is missing.
  494. if (!VRBase)
  495. VRBase = MRI->createVirtualRegister(TRC);
  496. // Create the extract_subreg machine instruction.
  497. MachineInstrBuilder CopyMI =
  498. BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
  499. TII->get(TargetOpcode::COPY), VRBase);
  500. if (Reg.isVirtual())
  501. CopyMI.addReg(Reg, 0, SubIdx);
  502. else
  503. CopyMI.addReg(TRI->getSubReg(Reg, SubIdx));
  504. }
  505. } else if (Opc == TargetOpcode::INSERT_SUBREG ||
  506. Opc == TargetOpcode::SUBREG_TO_REG) {
  507. SDValue N0 = Node->getOperand(0);
  508. SDValue N1 = Node->getOperand(1);
  509. SDValue N2 = Node->getOperand(2);
  510. unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
  511. // Figure out the register class to create for the destreg. It should be
  512. // the largest legal register class supporting SubIdx sub-registers.
  513. // RegisterCoalescer will constrain it further if it decides to eliminate
  514. // the INSERT_SUBREG instruction.
  515. //
  516. // %dst = INSERT_SUBREG %src, %sub, SubIdx
  517. //
  518. // is lowered by TwoAddressInstructionPass to:
  519. //
  520. // %dst = COPY %src
  521. // %dst:SubIdx = COPY %sub
  522. //
  523. // There is no constraint on the %src register class.
  524. //
  525. const TargetRegisterClass *SRC =
  526. TLI->getRegClassFor(Node->getSimpleValueType(0), Node->isDivergent());
  527. SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
  528. assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
  529. if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
  530. VRBase = MRI->createVirtualRegister(SRC);
  531. // Create the insert_subreg or subreg_to_reg machine instruction.
  532. MachineInstrBuilder MIB =
  533. BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
  534. // If creating a subreg_to_reg, then the first input operand
  535. // is an implicit value immediate, otherwise it's a register
  536. if (Opc == TargetOpcode::SUBREG_TO_REG) {
  537. const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
  538. MIB.addImm(SD->getZExtValue());
  539. } else
  540. AddOperand(MIB, N0, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
  541. IsClone, IsCloned);
  542. // Add the subregister being inserted
  543. AddOperand(MIB, N1, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
  544. IsClone, IsCloned);
  545. MIB.addImm(SubIdx);
  546. MBB->insert(InsertPos, MIB);
  547. } else
  548. llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
  549. SDValue Op(Node, 0);
  550. bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
  551. (void)isNew; // Silence compiler warning.
  552. assert(isNew && "Node emitted out of order - early");
  553. }
  554. /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
  555. /// COPY_TO_REGCLASS is just a normal copy, except that the destination
  556. /// register is constrained to be in a particular register class.
  557. ///
  558. void
  559. InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
  560. DenseMap<SDValue, Register> &VRBaseMap) {
  561. unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
  562. // Create the new VReg in the destination class and emit a copy.
  563. unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
  564. const TargetRegisterClass *DstRC =
  565. TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx));
  566. Register NewVReg = MRI->createVirtualRegister(DstRC);
  567. BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
  568. NewVReg).addReg(VReg);
  569. SDValue Op(Node, 0);
  570. bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
  571. (void)isNew; // Silence compiler warning.
  572. assert(isNew && "Node emitted out of order - early");
  573. }
  574. /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
  575. ///
  576. void InstrEmitter::EmitRegSequence(SDNode *Node,
  577. DenseMap<SDValue, Register> &VRBaseMap,
  578. bool IsClone, bool IsCloned) {
  579. unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
  580. const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
  581. Register NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC));
  582. const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
  583. MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg);
  584. unsigned NumOps = Node->getNumOperands();
  585. // If the input pattern has a chain, then the root of the corresponding
  586. // output pattern will get a chain as well. This can happen to be a
  587. // REG_SEQUENCE (which is not "guarded" by countOperands/CountResults).
  588. if (NumOps && Node->getOperand(NumOps-1).getValueType() == MVT::Other)
  589. --NumOps; // Ignore chain if it exists.
  590. assert((NumOps & 1) == 1 &&
  591. "REG_SEQUENCE must have an odd number of operands!");
  592. for (unsigned i = 1; i != NumOps; ++i) {
  593. SDValue Op = Node->getOperand(i);
  594. if ((i & 1) == 0) {
  595. RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
  596. // Skip physical registers as they don't have a vreg to get and we'll
  597. // insert copies for them in TwoAddressInstructionPass anyway.
  598. if (!R || !R->getReg().isPhysical()) {
  599. unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
  600. unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
  601. const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
  602. const TargetRegisterClass *SRC =
  603. TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
  604. if (SRC && SRC != RC) {
  605. MRI->setRegClass(NewVReg, SRC);
  606. RC = SRC;
  607. }
  608. }
  609. }
  610. AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
  611. IsClone, IsCloned);
  612. }
  613. MBB->insert(InsertPos, MIB);
  614. SDValue Op(Node, 0);
  615. bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
  616. (void)isNew; // Silence compiler warning.
  617. assert(isNew && "Node emitted out of order - early");
  618. }
  619. /// EmitDbgValue - Generate machine instruction for a dbg_value node.
  620. ///
  621. MachineInstr *
  622. InstrEmitter::EmitDbgValue(SDDbgValue *SD,
  623. DenseMap<SDValue, Register> &VRBaseMap) {
  624. DebugLoc DL = SD->getDebugLoc();
  625. assert(cast<DILocalVariable>(SD->getVariable())
  626. ->isValidLocationForIntrinsic(DL) &&
  627. "Expected inlined-at fields to agree");
  628. SD->setIsEmitted();
  629. assert(!SD->getLocationOps().empty() &&
  630. "dbg_value with no location operands?");
  631. if (SD->isInvalidated())
  632. return EmitDbgNoLocation(SD);
  633. // Attempt to produce a DBG_INSTR_REF if we've been asked to.
  634. if (EmitDebugInstrRefs)
  635. if (auto *InstrRef = EmitDbgInstrRef(SD, VRBaseMap))
  636. return InstrRef;
  637. // Emit variadic dbg_value nodes as DBG_VALUE_LIST if they have not been
  638. // emitted as instruction references.
  639. if (SD->isVariadic())
  640. return EmitDbgValueList(SD, VRBaseMap);
  641. // Emit single-location dbg_value nodes as DBG_VALUE if they have not been
  642. // emitted as instruction references.
  643. return EmitDbgValueFromSingleOp(SD, VRBaseMap);
  644. }
  645. MachineOperand GetMOForConstDbgOp(const SDDbgOperand &Op) {
  646. const Value *V = Op.getConst();
  647. if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  648. if (CI->getBitWidth() > 64)
  649. return MachineOperand::CreateCImm(CI);
  650. return MachineOperand::CreateImm(CI->getSExtValue());
  651. }
  652. if (const ConstantFP *CF = dyn_cast<ConstantFP>(V))
  653. return MachineOperand::CreateFPImm(CF);
  654. // Note: This assumes that all nullptr constants are zero-valued.
  655. if (isa<ConstantPointerNull>(V))
  656. return MachineOperand::CreateImm(0);
  657. // Undef or unhandled value type, so return an undef operand.
  658. return MachineOperand::CreateReg(
  659. /* Reg */ 0U, /* isDef */ false, /* isImp */ false,
  660. /* isKill */ false, /* isDead */ false,
  661. /* isUndef */ false, /* isEarlyClobber */ false,
  662. /* SubReg */ 0, /* isDebug */ true);
  663. }
  664. void InstrEmitter::AddDbgValueLocationOps(
  665. MachineInstrBuilder &MIB, const MCInstrDesc &DbgValDesc,
  666. ArrayRef<SDDbgOperand> LocationOps,
  667. DenseMap<SDValue, Register> &VRBaseMap) {
  668. for (const SDDbgOperand &Op : LocationOps) {
  669. switch (Op.getKind()) {
  670. case SDDbgOperand::FRAMEIX:
  671. MIB.addFrameIndex(Op.getFrameIx());
  672. break;
  673. case SDDbgOperand::VREG:
  674. MIB.addReg(Op.getVReg());
  675. break;
  676. case SDDbgOperand::SDNODE: {
  677. SDValue V = SDValue(Op.getSDNode(), Op.getResNo());
  678. // It's possible we replaced this SDNode with other(s) and therefore
  679. // didn't generate code for it. It's better to catch these cases where
  680. // they happen and transfer the debug info, but trying to guarantee that
  681. // in all cases would be very fragile; this is a safeguard for any
  682. // that were missed.
  683. if (VRBaseMap.count(V) == 0)
  684. MIB.addReg(0U); // undef
  685. else
  686. AddOperand(MIB, V, (*MIB).getNumOperands(), &DbgValDesc, VRBaseMap,
  687. /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
  688. } break;
  689. case SDDbgOperand::CONST:
  690. MIB.add(GetMOForConstDbgOp(Op));
  691. break;
  692. }
  693. }
  694. }
  695. MachineInstr *
  696. InstrEmitter::EmitDbgInstrRef(SDDbgValue *SD,
  697. DenseMap<SDValue, Register> &VRBaseMap) {
  698. MDNode *Var = SD->getVariable();
  699. const DIExpression *Expr = (DIExpression *)SD->getExpression();
  700. DebugLoc DL = SD->getDebugLoc();
  701. const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_INSTR_REF);
  702. // Returns true if the given operand is not a legal debug operand for a
  703. // DBG_INSTR_REF.
  704. auto IsInvalidOp = [](SDDbgOperand DbgOp) {
  705. return DbgOp.getKind() == SDDbgOperand::FRAMEIX;
  706. };
  707. // Returns true if the given operand is not itself an instruction reference
  708. // but is a legal debug operand for a DBG_INSTR_REF.
  709. auto IsNonInstrRefOp = [](SDDbgOperand DbgOp) {
  710. return DbgOp.getKind() == SDDbgOperand::CONST;
  711. };
  712. // If this variable location does not depend on any instructions or contains
  713. // any stack locations, produce it as a standard debug value instead.
  714. if (any_of(SD->getLocationOps(), IsInvalidOp) ||
  715. all_of(SD->getLocationOps(), IsNonInstrRefOp)) {
  716. if (SD->isVariadic())
  717. return EmitDbgValueList(SD, VRBaseMap);
  718. return EmitDbgValueFromSingleOp(SD, VRBaseMap);
  719. }
  720. // Immediately fold any indirectness from the LLVM-IR intrinsic into the
  721. // expression:
  722. if (SD->isIndirect())
  723. Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
  724. // If this is not already a variadic expression, it must be modified to become
  725. // one.
  726. if (!SD->isVariadic())
  727. Expr = DIExpression::convertToVariadicExpression(Expr);
  728. SmallVector<MachineOperand> MOs;
  729. // It may not be immediately possible to identify the MachineInstr that
  730. // defines a VReg, it can depend for example on the order blocks are
  731. // emitted in. When this happens, or when further analysis is needed later,
  732. // produce an instruction like this:
  733. //
  734. // DBG_INSTR_REF !123, !456, %0:gr64
  735. //
  736. // i.e., point the instruction at the vreg, and patch it up later in
  737. // MachineFunction::finalizeDebugInstrRefs.
  738. auto AddVRegOp = [&](unsigned VReg) {
  739. MOs.push_back(MachineOperand::CreateReg(
  740. /* Reg */ VReg, /* isDef */ false, /* isImp */ false,
  741. /* isKill */ false, /* isDead */ false,
  742. /* isUndef */ false, /* isEarlyClobber */ false,
  743. /* SubReg */ 0, /* isDebug */ true));
  744. };
  745. unsigned OpCount = SD->getLocationOps().size();
  746. for (unsigned OpIdx = 0; OpIdx < OpCount; ++OpIdx) {
  747. SDDbgOperand DbgOperand = SD->getLocationOps()[OpIdx];
  748. // Try to find both the defined register and the instruction defining it.
  749. MachineInstr *DefMI = nullptr;
  750. unsigned VReg;
  751. if (DbgOperand.getKind() == SDDbgOperand::VREG) {
  752. VReg = DbgOperand.getVReg();
  753. // No definition means that block hasn't been emitted yet. Leave a vreg
  754. // reference to be fixed later.
  755. if (!MRI->hasOneDef(VReg)) {
  756. AddVRegOp(VReg);
  757. continue;
  758. }
  759. DefMI = &*MRI->def_instr_begin(VReg);
  760. } else if (DbgOperand.getKind() == SDDbgOperand::SDNODE) {
  761. // Look up the corresponding VReg for the given SDNode, if any.
  762. SDNode *Node = DbgOperand.getSDNode();
  763. SDValue Op = SDValue(Node, DbgOperand.getResNo());
  764. DenseMap<SDValue, Register>::iterator I = VRBaseMap.find(Op);
  765. // No VReg -> produce a DBG_VALUE $noreg instead.
  766. if (I == VRBaseMap.end())
  767. break;
  768. // Try to pick out a defining instruction at this point.
  769. VReg = getVR(Op, VRBaseMap);
  770. // Again, if there's no instruction defining the VReg right now, fix it up
  771. // later.
  772. if (!MRI->hasOneDef(VReg)) {
  773. AddVRegOp(VReg);
  774. continue;
  775. }
  776. DefMI = &*MRI->def_instr_begin(VReg);
  777. } else {
  778. assert(DbgOperand.getKind() == SDDbgOperand::CONST);
  779. MOs.push_back(GetMOForConstDbgOp(DbgOperand));
  780. continue;
  781. }
  782. // Avoid copy like instructions: they don't define values, only move them.
  783. // Leave a virtual-register reference until it can be fixed up later, to
  784. // find the underlying value definition.
  785. if (DefMI->isCopyLike() || TII->isCopyInstr(*DefMI)) {
  786. AddVRegOp(VReg);
  787. continue;
  788. }
  789. // Find the operand number which defines the specified VReg.
  790. unsigned OperandIdx = 0;
  791. for (const auto &MO : DefMI->operands()) {
  792. if (MO.isReg() && MO.isDef() && MO.getReg() == VReg)
  793. break;
  794. ++OperandIdx;
  795. }
  796. assert(OperandIdx < DefMI->getNumOperands());
  797. // Make the DBG_INSTR_REF refer to that instruction, and that operand.
  798. unsigned InstrNum = DefMI->getDebugInstrNum();
  799. MOs.push_back(MachineOperand::CreateDbgInstrRef(InstrNum, OperandIdx));
  800. }
  801. // If we haven't created a valid MachineOperand for every DbgOp, abort and
  802. // produce an undef DBG_VALUE.
  803. if (MOs.size() != OpCount)
  804. return EmitDbgNoLocation(SD);
  805. return BuildMI(*MF, DL, RefII, false, MOs, Var, Expr);
  806. }
  807. MachineInstr *InstrEmitter::EmitDbgNoLocation(SDDbgValue *SD) {
  808. // An invalidated SDNode must generate an undef DBG_VALUE: although the
  809. // original value is no longer computed, earlier DBG_VALUEs live ranges
  810. // must not leak into later code.
  811. DIVariable *Var = SD->getVariable();
  812. const DIExpression *Expr =
  813. DIExpression::convertToUndefExpression(SD->getExpression());
  814. DebugLoc DL = SD->getDebugLoc();
  815. const MCInstrDesc &Desc = TII->get(TargetOpcode::DBG_VALUE);
  816. return BuildMI(*MF, DL, Desc, false, 0U, Var, Expr);
  817. }
  818. MachineInstr *
  819. InstrEmitter::EmitDbgValueList(SDDbgValue *SD,
  820. DenseMap<SDValue, Register> &VRBaseMap) {
  821. MDNode *Var = SD->getVariable();
  822. DIExpression *Expr = SD->getExpression();
  823. DebugLoc DL = SD->getDebugLoc();
  824. // DBG_VALUE_LIST := "DBG_VALUE_LIST" var, expression, loc (, loc)*
  825. const MCInstrDesc &DbgValDesc = TII->get(TargetOpcode::DBG_VALUE_LIST);
  826. // Build the DBG_VALUE_LIST instruction base.
  827. auto MIB = BuildMI(*MF, DL, DbgValDesc);
  828. MIB.addMetadata(Var);
  829. MIB.addMetadata(Expr);
  830. AddDbgValueLocationOps(MIB, DbgValDesc, SD->getLocationOps(), VRBaseMap);
  831. return &*MIB;
  832. }
  833. MachineInstr *
  834. InstrEmitter::EmitDbgValueFromSingleOp(SDDbgValue *SD,
  835. DenseMap<SDValue, Register> &VRBaseMap) {
  836. MDNode *Var = SD->getVariable();
  837. DIExpression *Expr = SD->getExpression();
  838. DebugLoc DL = SD->getDebugLoc();
  839. const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
  840. assert(SD->getLocationOps().size() == 1 &&
  841. "Non variadic dbg_value should have only one location op");
  842. // See about constant-folding the expression.
  843. // Copy the location operand in case we replace it.
  844. SmallVector<SDDbgOperand, 1> LocationOps(1, SD->getLocationOps()[0]);
  845. if (Expr && LocationOps[0].getKind() == SDDbgOperand::CONST) {
  846. const Value *V = LocationOps[0].getConst();
  847. if (auto *C = dyn_cast<ConstantInt>(V)) {
  848. std::tie(Expr, C) = Expr->constantFold(C);
  849. LocationOps[0] = SDDbgOperand::fromConst(C);
  850. }
  851. }
  852. // Emit non-variadic dbg_value nodes as DBG_VALUE.
  853. // DBG_VALUE := "DBG_VALUE" loc, isIndirect, var, expr
  854. auto MIB = BuildMI(*MF, DL, II);
  855. AddDbgValueLocationOps(MIB, II, LocationOps, VRBaseMap);
  856. if (SD->isIndirect())
  857. MIB.addImm(0U);
  858. else
  859. MIB.addReg(0U);
  860. return MIB.addMetadata(Var).addMetadata(Expr);
  861. }
  862. MachineInstr *
  863. InstrEmitter::EmitDbgLabel(SDDbgLabel *SD) {
  864. MDNode *Label = SD->getLabel();
  865. DebugLoc DL = SD->getDebugLoc();
  866. assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
  867. "Expected inlined-at fields to agree");
  868. const MCInstrDesc &II = TII->get(TargetOpcode::DBG_LABEL);
  869. MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
  870. MIB.addMetadata(Label);
  871. return &*MIB;
  872. }
  873. /// EmitMachineNode - Generate machine code for a target-specific node and
  874. /// needed dependencies.
  875. ///
  876. void InstrEmitter::
  877. EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
  878. DenseMap<SDValue, Register> &VRBaseMap) {
  879. unsigned Opc = Node->getMachineOpcode();
  880. // Handle subreg insert/extract specially
  881. if (Opc == TargetOpcode::EXTRACT_SUBREG ||
  882. Opc == TargetOpcode::INSERT_SUBREG ||
  883. Opc == TargetOpcode::SUBREG_TO_REG) {
  884. EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
  885. return;
  886. }
  887. // Handle COPY_TO_REGCLASS specially.
  888. if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
  889. EmitCopyToRegClassNode(Node, VRBaseMap);
  890. return;
  891. }
  892. // Handle REG_SEQUENCE specially.
  893. if (Opc == TargetOpcode::REG_SEQUENCE) {
  894. EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
  895. return;
  896. }
  897. if (Opc == TargetOpcode::IMPLICIT_DEF)
  898. // We want a unique VR for each IMPLICIT_DEF use.
  899. return;
  900. const MCInstrDesc &II = TII->get(Opc);
  901. unsigned NumResults = CountResults(Node);
  902. unsigned NumDefs = II.getNumDefs();
  903. const MCPhysReg *ScratchRegs = nullptr;
  904. // Handle STACKMAP and PATCHPOINT specially and then use the generic code.
  905. if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) {
  906. // Stackmaps do not have arguments and do not preserve their calling
  907. // convention. However, to simplify runtime support, they clobber the same
  908. // scratch registers as AnyRegCC.
  909. unsigned CC = CallingConv::AnyReg;
  910. if (Opc == TargetOpcode::PATCHPOINT) {
  911. CC = Node->getConstantOperandVal(PatchPointOpers::CCPos);
  912. NumDefs = NumResults;
  913. }
  914. ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC);
  915. } else if (Opc == TargetOpcode::STATEPOINT) {
  916. NumDefs = NumResults;
  917. }
  918. unsigned NumImpUses = 0;
  919. unsigned NodeOperands =
  920. countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
  921. bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() &&
  922. II.isVariadic() && II.variadicOpsAreDefs();
  923. bool HasPhysRegOuts = NumResults > NumDefs && !II.implicit_defs().empty() &&
  924. !HasVRegVariadicDefs;
  925. #ifndef NDEBUG
  926. unsigned NumMIOperands = NodeOperands + NumResults;
  927. if (II.isVariadic())
  928. assert(NumMIOperands >= II.getNumOperands() &&
  929. "Too few operands for a variadic node!");
  930. else
  931. assert(NumMIOperands >= II.getNumOperands() &&
  932. NumMIOperands <=
  933. II.getNumOperands() + II.implicit_defs().size() + NumImpUses &&
  934. "#operands for dag node doesn't match .td file!");
  935. #endif
  936. // Create the new machine instruction.
  937. MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
  938. // Add result register values for things that are defined by this
  939. // instruction.
  940. if (NumResults) {
  941. CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
  942. // Transfer any IR flags from the SDNode to the MachineInstr
  943. MachineInstr *MI = MIB.getInstr();
  944. const SDNodeFlags Flags = Node->getFlags();
  945. if (Flags.hasNoSignedZeros())
  946. MI->setFlag(MachineInstr::MIFlag::FmNsz);
  947. if (Flags.hasAllowReciprocal())
  948. MI->setFlag(MachineInstr::MIFlag::FmArcp);
  949. if (Flags.hasNoNaNs())
  950. MI->setFlag(MachineInstr::MIFlag::FmNoNans);
  951. if (Flags.hasNoInfs())
  952. MI->setFlag(MachineInstr::MIFlag::FmNoInfs);
  953. if (Flags.hasAllowContract())
  954. MI->setFlag(MachineInstr::MIFlag::FmContract);
  955. if (Flags.hasApproximateFuncs())
  956. MI->setFlag(MachineInstr::MIFlag::FmAfn);
  957. if (Flags.hasAllowReassociation())
  958. MI->setFlag(MachineInstr::MIFlag::FmReassoc);
  959. if (Flags.hasNoUnsignedWrap())
  960. MI->setFlag(MachineInstr::MIFlag::NoUWrap);
  961. if (Flags.hasNoSignedWrap())
  962. MI->setFlag(MachineInstr::MIFlag::NoSWrap);
  963. if (Flags.hasExact())
  964. MI->setFlag(MachineInstr::MIFlag::IsExact);
  965. if (Flags.hasNoFPExcept())
  966. MI->setFlag(MachineInstr::MIFlag::NoFPExcept);
  967. }
  968. // Emit all of the actual operands of this instruction, adding them to the
  969. // instruction as appropriate.
  970. bool HasOptPRefs = NumDefs > NumResults;
  971. assert((!HasOptPRefs || !HasPhysRegOuts) &&
  972. "Unable to cope with optional defs and phys regs defs!");
  973. unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0;
  974. for (unsigned i = NumSkip; i != NodeOperands; ++i)
  975. AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II,
  976. VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
  977. // Add scratch registers as implicit def and early clobber
  978. if (ScratchRegs)
  979. for (unsigned i = 0; ScratchRegs[i]; ++i)
  980. MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine |
  981. RegState::EarlyClobber);
  982. // Set the memory reference descriptions of this instruction now that it is
  983. // part of the function.
  984. MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands());
  985. // Set the CFI type.
  986. MIB->setCFIType(*MF, Node->getCFIType());
  987. // Insert the instruction into position in the block. This needs to
  988. // happen before any custom inserter hook is called so that the
  989. // hook knows where in the block to insert the replacement code.
  990. MBB->insert(InsertPos, MIB);
  991. // The MachineInstr may also define physregs instead of virtregs. These
  992. // physreg values can reach other instructions in different ways:
  993. //
  994. // 1. When there is a use of a Node value beyond the explicitly defined
  995. // virtual registers, we emit a CopyFromReg for one of the implicitly
  996. // defined physregs. This only happens when HasPhysRegOuts is true.
  997. //
  998. // 2. A CopyFromReg reading a physreg may be glued to this instruction.
  999. //
  1000. // 3. A glued instruction may implicitly use a physreg.
  1001. //
  1002. // 4. A glued instruction may use a RegisterSDNode operand.
  1003. //
  1004. // Collect all the used physreg defs, and make sure that any unused physreg
  1005. // defs are marked as dead.
  1006. SmallVector<Register, 8> UsedRegs;
  1007. // Additional results must be physical register defs.
  1008. if (HasPhysRegOuts) {
  1009. for (unsigned i = NumDefs; i < NumResults; ++i) {
  1010. Register Reg = II.implicit_defs()[i - NumDefs];
  1011. if (!Node->hasAnyUseOfValue(i))
  1012. continue;
  1013. // This implicitly defined physreg has a use.
  1014. UsedRegs.push_back(Reg);
  1015. EmitCopyFromReg(Node, i, IsClone, Reg, VRBaseMap);
  1016. }
  1017. }
  1018. // Scan the glue chain for any used physregs.
  1019. if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
  1020. for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
  1021. if (F->getOpcode() == ISD::CopyFromReg) {
  1022. UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
  1023. continue;
  1024. } else if (F->getOpcode() == ISD::CopyToReg) {
  1025. // Skip CopyToReg nodes that are internal to the glue chain.
  1026. continue;
  1027. }
  1028. // Collect declared implicit uses.
  1029. const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
  1030. append_range(UsedRegs, MCID.implicit_uses());
  1031. // In addition to declared implicit uses, we must also check for
  1032. // direct RegisterSDNode operands.
  1033. for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
  1034. if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
  1035. Register Reg = R->getReg();
  1036. if (Reg.isPhysical())
  1037. UsedRegs.push_back(Reg);
  1038. }
  1039. }
  1040. }
  1041. // Finally mark unused registers as dead.
  1042. if (!UsedRegs.empty() || !II.implicit_defs().empty() || II.hasOptionalDef())
  1043. MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
  1044. // STATEPOINT is too 'dynamic' to have meaningful machine description.
  1045. // We have to manually tie operands.
  1046. if (Opc == TargetOpcode::STATEPOINT && NumDefs > 0) {
  1047. assert(!HasPhysRegOuts && "STATEPOINT mishandled");
  1048. MachineInstr *MI = MIB;
  1049. unsigned Def = 0;
  1050. int First = StatepointOpers(MI).getFirstGCPtrIdx();
  1051. assert(First > 0 && "Statepoint has Defs but no GC ptr list");
  1052. unsigned Use = (unsigned)First;
  1053. while (Def < NumDefs) {
  1054. if (MI->getOperand(Use).isReg())
  1055. MI->tieOperands(Def++, Use);
  1056. Use = StackMaps::getNextMetaArgIdx(MI, Use);
  1057. }
  1058. }
  1059. // Run post-isel target hook to adjust this instruction if needed.
  1060. if (II.hasPostISelHook())
  1061. TLI->AdjustInstrPostInstrSelection(*MIB, Node);
  1062. }
  1063. /// EmitSpecialNode - Generate machine code for a target-independent node and
  1064. /// needed dependencies.
  1065. void InstrEmitter::
  1066. EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
  1067. DenseMap<SDValue, Register> &VRBaseMap) {
  1068. switch (Node->getOpcode()) {
  1069. default:
  1070. #ifndef NDEBUG
  1071. Node->dump();
  1072. #endif
  1073. llvm_unreachable("This target-independent node should have been selected!");
  1074. case ISD::EntryToken:
  1075. case ISD::MERGE_VALUES:
  1076. case ISD::TokenFactor: // fall thru
  1077. break;
  1078. case ISD::CopyToReg: {
  1079. Register DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
  1080. SDValue SrcVal = Node->getOperand(2);
  1081. if (DestReg.isVirtual() && SrcVal.isMachineOpcode() &&
  1082. SrcVal.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
  1083. // Instead building a COPY to that vreg destination, build an
  1084. // IMPLICIT_DEF instruction instead.
  1085. BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
  1086. TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
  1087. break;
  1088. }
  1089. Register SrcReg;
  1090. if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
  1091. SrcReg = R->getReg();
  1092. else
  1093. SrcReg = getVR(SrcVal, VRBaseMap);
  1094. if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
  1095. break;
  1096. BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
  1097. DestReg).addReg(SrcReg);
  1098. break;
  1099. }
  1100. case ISD::CopyFromReg: {
  1101. unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
  1102. EmitCopyFromReg(Node, 0, IsClone, SrcReg, VRBaseMap);
  1103. break;
  1104. }
  1105. case ISD::EH_LABEL:
  1106. case ISD::ANNOTATION_LABEL: {
  1107. unsigned Opc = (Node->getOpcode() == ISD::EH_LABEL)
  1108. ? TargetOpcode::EH_LABEL
  1109. : TargetOpcode::ANNOTATION_LABEL;
  1110. MCSymbol *S = cast<LabelSDNode>(Node)->getLabel();
  1111. BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
  1112. TII->get(Opc)).addSym(S);
  1113. break;
  1114. }
  1115. case ISD::LIFETIME_START:
  1116. case ISD::LIFETIME_END: {
  1117. unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START)
  1118. ? TargetOpcode::LIFETIME_START
  1119. : TargetOpcode::LIFETIME_END;
  1120. auto *FI = cast<FrameIndexSDNode>(Node->getOperand(1));
  1121. BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
  1122. .addFrameIndex(FI->getIndex());
  1123. break;
  1124. }
  1125. case ISD::PSEUDO_PROBE: {
  1126. unsigned TarOp = TargetOpcode::PSEUDO_PROBE;
  1127. auto Guid = cast<PseudoProbeSDNode>(Node)->getGuid();
  1128. auto Index = cast<PseudoProbeSDNode>(Node)->getIndex();
  1129. auto Attr = cast<PseudoProbeSDNode>(Node)->getAttributes();
  1130. BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
  1131. .addImm(Guid)
  1132. .addImm(Index)
  1133. .addImm((uint8_t)PseudoProbeType::Block)
  1134. .addImm(Attr);
  1135. break;
  1136. }
  1137. case ISD::INLINEASM:
  1138. case ISD::INLINEASM_BR: {
  1139. unsigned NumOps = Node->getNumOperands();
  1140. if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
  1141. --NumOps; // Ignore the glue operand.
  1142. // Create the inline asm machine instruction.
  1143. unsigned TgtOpc = Node->getOpcode() == ISD::INLINEASM_BR
  1144. ? TargetOpcode::INLINEASM_BR
  1145. : TargetOpcode::INLINEASM;
  1146. MachineInstrBuilder MIB =
  1147. BuildMI(*MF, Node->getDebugLoc(), TII->get(TgtOpc));
  1148. // Add the asm string as an external symbol operand.
  1149. SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
  1150. const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
  1151. MIB.addExternalSymbol(AsmStr);
  1152. // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
  1153. // bits.
  1154. int64_t ExtraInfo =
  1155. cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
  1156. getZExtValue();
  1157. MIB.addImm(ExtraInfo);
  1158. // Remember to operand index of the group flags.
  1159. SmallVector<unsigned, 8> GroupIdx;
  1160. // Remember registers that are part of early-clobber defs.
  1161. SmallVector<unsigned, 8> ECRegs;
  1162. // Add all of the operand registers to the instruction.
  1163. for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
  1164. unsigned Flags =
  1165. cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
  1166. const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
  1167. GroupIdx.push_back(MIB->getNumOperands());
  1168. MIB.addImm(Flags);
  1169. ++i; // Skip the ID value.
  1170. switch (InlineAsm::getKind(Flags)) {
  1171. default: llvm_unreachable("Bad flags!");
  1172. case InlineAsm::Kind_RegDef:
  1173. for (unsigned j = 0; j != NumVals; ++j, ++i) {
  1174. Register Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
  1175. // FIXME: Add dead flags for physical and virtual registers defined.
  1176. // For now, mark physical register defs as implicit to help fast
  1177. // regalloc. This makes inline asm look a lot like calls.
  1178. MIB.addReg(Reg, RegState::Define | getImplRegState(Reg.isPhysical()));
  1179. }
  1180. break;
  1181. case InlineAsm::Kind_RegDefEarlyClobber:
  1182. case InlineAsm::Kind_Clobber:
  1183. for (unsigned j = 0; j != NumVals; ++j, ++i) {
  1184. Register Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
  1185. MIB.addReg(Reg, RegState::Define | RegState::EarlyClobber |
  1186. getImplRegState(Reg.isPhysical()));
  1187. ECRegs.push_back(Reg);
  1188. }
  1189. break;
  1190. case InlineAsm::Kind_RegUse: // Use of register.
  1191. case InlineAsm::Kind_Imm: // Immediate.
  1192. case InlineAsm::Kind_Mem: // Non-function addressing mode.
  1193. // The addressing mode has been selected, just add all of the
  1194. // operands to the machine instruction.
  1195. for (unsigned j = 0; j != NumVals; ++j, ++i)
  1196. AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap,
  1197. /*IsDebug=*/false, IsClone, IsCloned);
  1198. // Manually set isTied bits.
  1199. if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
  1200. unsigned DefGroup = 0;
  1201. if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
  1202. unsigned DefIdx = GroupIdx[DefGroup] + 1;
  1203. unsigned UseIdx = GroupIdx.back() + 1;
  1204. for (unsigned j = 0; j != NumVals; ++j)
  1205. MIB->tieOperands(DefIdx + j, UseIdx + j);
  1206. }
  1207. }
  1208. break;
  1209. case InlineAsm::Kind_Func: // Function addressing mode.
  1210. for (unsigned j = 0; j != NumVals; ++j, ++i) {
  1211. SDValue Op = Node->getOperand(i);
  1212. AddOperand(MIB, Op, 0, nullptr, VRBaseMap,
  1213. /*IsDebug=*/false, IsClone, IsCloned);
  1214. // Adjust Target Flags for function reference.
  1215. if (auto *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
  1216. unsigned NewFlags =
  1217. MF->getSubtarget().classifyGlobalFunctionReference(
  1218. TGA->getGlobal());
  1219. unsigned LastIdx = MIB.getInstr()->getNumOperands() - 1;
  1220. MIB.getInstr()->getOperand(LastIdx).setTargetFlags(NewFlags);
  1221. }
  1222. }
  1223. }
  1224. }
  1225. // GCC inline assembly allows input operands to also be early-clobber
  1226. // output operands (so long as the operand is written only after it's
  1227. // used), but this does not match the semantics of our early-clobber flag.
  1228. // If an early-clobber operand register is also an input operand register,
  1229. // then remove the early-clobber flag.
  1230. for (unsigned Reg : ECRegs) {
  1231. if (MIB->readsRegister(Reg, TRI)) {
  1232. MachineOperand *MO =
  1233. MIB->findRegisterDefOperand(Reg, false, false, TRI);
  1234. assert(MO && "No def operand for clobbered register?");
  1235. MO->setIsEarlyClobber(false);
  1236. }
  1237. }
  1238. // Get the mdnode from the asm if it exists and add it to the instruction.
  1239. SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
  1240. const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
  1241. if (MD)
  1242. MIB.addMetadata(MD);
  1243. MBB->insert(InsertPos, MIB);
  1244. break;
  1245. }
  1246. }
  1247. }
  1248. /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
  1249. /// at the given position in the given block.
  1250. InstrEmitter::InstrEmitter(const TargetMachine &TM, MachineBasicBlock *mbb,
  1251. MachineBasicBlock::iterator insertpos)
  1252. : MF(mbb->getParent()), MRI(&MF->getRegInfo()),
  1253. TII(MF->getSubtarget().getInstrInfo()),
  1254. TRI(MF->getSubtarget().getRegisterInfo()),
  1255. TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb),
  1256. InsertPos(insertpos) {
  1257. EmitDebugInstrRefs = mbb->getParent()->useDebugInstrRef();
  1258. }