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