InstrEmitter.cpp 52 KB

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