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