LLVM  mainline
InstrEmitter.cpp
Go to the documentation of this file.
00001 //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements the Emit routines for the SelectionDAG class, which creates
00011 // MachineInstrs based on the decisions of the SelectionDAG instruction
00012 // selection.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "InstrEmitter.h"
00017 #include "SDNodeDbgValue.h"
00018 #include "llvm/ADT/Statistic.h"
00019 #include "llvm/CodeGen/MachineConstantPool.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/CodeGen/MachineInstrBuilder.h"
00022 #include "llvm/CodeGen/MachineRegisterInfo.h"
00023 #include "llvm/CodeGen/StackMaps.h"
00024 #include "llvm/IR/DataLayout.h"
00025 #include "llvm/Support/Debug.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Support/MathExtras.h"
00028 #include "llvm/Target/TargetInstrInfo.h"
00029 #include "llvm/Target/TargetLowering.h"
00030 #include "llvm/Target/TargetSubtargetInfo.h"
00031 using namespace llvm;
00032 
00033 #define DEBUG_TYPE "instr-emitter"
00034 
00035 /// MinRCSize - Smallest register class we allow when constraining virtual
00036 /// registers.  If satisfying all register class constraints would require
00037 /// using a smaller register class, emit a COPY to a new virtual register
00038 /// instead.
00039 const unsigned MinRCSize = 4;
00040 
00041 /// CountResults - The results of target nodes have register or immediate
00042 /// operands first, then an optional chain, and optional glue operands (which do
00043 /// not go into the resulting MachineInstr).
00044 unsigned InstrEmitter::CountResults(SDNode *Node) {
00045   unsigned N = Node->getNumValues();
00046   while (N && Node->getValueType(N - 1) == MVT::Glue)
00047     --N;
00048   if (N && Node->getValueType(N - 1) == MVT::Other)
00049     --N;    // Skip over chain result.
00050   return N;
00051 }
00052 
00053 /// countOperands - The inputs to target nodes have any actual inputs first,
00054 /// followed by an optional chain operand, then an optional glue operand.
00055 /// Compute the number of actual operands that will go into the resulting
00056 /// MachineInstr.
00057 ///
00058 /// Also count physreg RegisterSDNode and RegisterMaskSDNode operands preceding
00059 /// the chain and glue. These operands may be implicit on the machine instr.
00060 static unsigned countOperands(SDNode *Node, unsigned NumExpUses,
00061                               unsigned &NumImpUses) {
00062   unsigned N = Node->getNumOperands();
00063   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
00064     --N;
00065   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
00066     --N; // Ignore chain if it exists.
00067 
00068   // Count RegisterSDNode and RegisterMaskSDNode operands for NumImpUses.
00069   NumImpUses = N - NumExpUses;
00070   for (unsigned I = N; I > NumExpUses; --I) {
00071     if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1)))
00072       continue;
00073     if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1)))
00074       if (TargetRegisterInfo::isPhysicalRegister(RN->getReg()))
00075         continue;
00076     NumImpUses = N - I;
00077     break;
00078   }
00079 
00080   return N;
00081 }
00082 
00083 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
00084 /// implicit physical register output.
00085 void InstrEmitter::
00086 EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
00087                 unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
00088   unsigned VRBase = 0;
00089   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
00090     // Just use the input register directly!
00091     SDValue Op(Node, ResNo);
00092     if (IsClone)
00093       VRBaseMap.erase(Op);
00094     bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
00095     (void)isNew; // Silence compiler warning.
00096     assert(isNew && "Node emitted out of order - early");
00097     return;
00098   }
00099 
00100   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
00101   // the CopyToReg'd destination register instead of creating a new vreg.
00102   bool MatchReg = true;
00103   const TargetRegisterClass *UseRC = nullptr;
00104   MVT VT = Node->getSimpleValueType(ResNo);
00105 
00106   // Stick to the preferred register classes for legal types.
00107   if (TLI->isTypeLegal(VT))
00108     UseRC = TLI->getRegClassFor(VT);
00109 
00110   if (!IsClone && !IsCloned)
00111     for (SDNode *User : Node->uses()) {
00112       bool Match = true;
00113       if (User->getOpcode() == ISD::CopyToReg &&
00114           User->getOperand(2).getNode() == Node &&
00115           User->getOperand(2).getResNo() == ResNo) {
00116         unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
00117         if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
00118           VRBase = DestReg;
00119           Match = false;
00120         } else if (DestReg != SrcReg)
00121           Match = false;
00122       } else {
00123         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
00124           SDValue Op = User->getOperand(i);
00125           if (Op.getNode() != Node || Op.getResNo() != ResNo)
00126             continue;
00127           MVT VT = Node->getSimpleValueType(Op.getResNo());
00128           if (VT == MVT::Other || VT == MVT::Glue)
00129             continue;
00130           Match = false;
00131           if (User->isMachineOpcode()) {
00132             const MCInstrDesc &II = TII->get(User->getMachineOpcode());
00133             const TargetRegisterClass *RC = nullptr;
00134             if (i+II.getNumDefs() < II.getNumOperands()) {
00135               RC = TRI->getAllocatableClass(
00136                 TII->getRegClass(II, i+II.getNumDefs(), TRI, *MF));
00137             }
00138             if (!UseRC)
00139               UseRC = RC;
00140             else if (RC) {
00141               const TargetRegisterClass *ComRC =
00142                 TRI->getCommonSubClass(UseRC, RC);
00143               // If multiple uses expect disjoint register classes, we emit
00144               // copies in AddRegisterOperand.
00145               if (ComRC)
00146                 UseRC = ComRC;
00147             }
00148           }
00149         }
00150       }
00151       MatchReg &= Match;
00152       if (VRBase)
00153         break;
00154     }
00155 
00156   const TargetRegisterClass *SrcRC = nullptr, *DstRC = nullptr;
00157   SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
00158 
00159   // Figure out the register class to create for the destreg.
00160   if (VRBase) {
00161     DstRC = MRI->getRegClass(VRBase);
00162   } else if (UseRC) {
00163     assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
00164     DstRC = UseRC;
00165   } else {
00166     DstRC = TLI->getRegClassFor(VT);
00167   }
00168 
00169   // If all uses are reading from the src physical register and copying the
00170   // register is either impossible or very expensive, then don't create a copy.
00171   if (MatchReg && SrcRC->getCopyCost() < 0) {
00172     VRBase = SrcReg;
00173   } else {
00174     // Create the reg, emit the copy.
00175     VRBase = MRI->createVirtualRegister(DstRC);
00176     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
00177             VRBase).addReg(SrcReg);
00178   }
00179 
00180   SDValue Op(Node, ResNo);
00181   if (IsClone)
00182     VRBaseMap.erase(Op);
00183   bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
00184   (void)isNew; // Silence compiler warning.
00185   assert(isNew && "Node emitted out of order - early");
00186 }
00187 
00188 /// getDstOfCopyToRegUse - If the only use of the specified result number of
00189 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
00190 unsigned InstrEmitter::getDstOfOnlyCopyToRegUse(SDNode *Node,
00191                                                 unsigned ResNo) const {
00192   if (!Node->hasOneUse())
00193     return 0;
00194 
00195   SDNode *User = *Node->use_begin();
00196   if (User->getOpcode() == ISD::CopyToReg &&
00197       User->getOperand(2).getNode() == Node &&
00198       User->getOperand(2).getResNo() == ResNo) {
00199     unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
00200     if (TargetRegisterInfo::isVirtualRegister(Reg))
00201       return Reg;
00202   }
00203   return 0;
00204 }
00205 
00206 void InstrEmitter::CreateVirtualRegisters(SDNode *Node,
00207                                        MachineInstrBuilder &MIB,
00208                                        const MCInstrDesc &II,
00209                                        bool IsClone, bool IsCloned,
00210                                        DenseMap<SDValue, unsigned> &VRBaseMap) {
00211   assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
00212          "IMPLICIT_DEF should have been handled as a special case elsewhere!");
00213 
00214   unsigned NumResults = CountResults(Node);
00215   for (unsigned i = 0; i < II.getNumDefs(); ++i) {
00216     // If the specific node value is only used by a CopyToReg and the dest reg
00217     // is a vreg in the same register class, use the CopyToReg'd destination
00218     // register instead of creating a new vreg.
00219     unsigned VRBase = 0;
00220     const TargetRegisterClass *RC =
00221       TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF));
00222     // Always let the value type influence the used register class. The
00223     // constraints on the instruction may be too lax to represent the value
00224     // type correctly. For example, a 64-bit float (X86::FR64) can't live in
00225     // the 32-bit float super-class (X86::FR32).
00226     if (i < NumResults && TLI->isTypeLegal(Node->getSimpleValueType(i))) {
00227       const TargetRegisterClass *VTRC =
00228         TLI->getRegClassFor(Node->getSimpleValueType(i));
00229       if (RC)
00230         VTRC = TRI->getCommonSubClass(RC, VTRC);
00231       if (VTRC)
00232         RC = VTRC;
00233     }
00234 
00235     if (II.OpInfo[i].isOptionalDef()) {
00236       // Optional def must be a physical register.
00237       unsigned NumResults = CountResults(Node);
00238       VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
00239       assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
00240       MIB.addReg(VRBase, RegState::Define);
00241     }
00242 
00243     if (!VRBase && !IsClone && !IsCloned)
00244       for (SDNode *User : Node->uses()) {
00245         if (User->getOpcode() == ISD::CopyToReg &&
00246             User->getOperand(2).getNode() == Node &&
00247             User->getOperand(2).getResNo() == i) {
00248           unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
00249           if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00250             const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
00251             if (RegRC == RC) {
00252               VRBase = Reg;
00253               MIB.addReg(VRBase, RegState::Define);
00254               break;
00255             }
00256           }
00257         }
00258       }
00259 
00260     // Create the result registers for this node and add the result regs to
00261     // the machine instruction.
00262     if (VRBase == 0) {
00263       assert(RC && "Isn't a register operand!");
00264       VRBase = MRI->createVirtualRegister(RC);
00265       MIB.addReg(VRBase, RegState::Define);
00266     }
00267 
00268     // If this def corresponds to a result of the SDNode insert the VRBase into
00269     // the lookup map.
00270     if (i < NumResults) {
00271       SDValue Op(Node, i);
00272       if (IsClone)
00273         VRBaseMap.erase(Op);
00274       bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
00275       (void)isNew; // Silence compiler warning.
00276       assert(isNew && "Node emitted out of order - early");
00277     }
00278   }
00279 }
00280 
00281 /// getVR - Return the virtual register corresponding to the specified result
00282 /// of the specified node.
00283 unsigned InstrEmitter::getVR(SDValue Op,
00284                              DenseMap<SDValue, unsigned> &VRBaseMap) {
00285   if (Op.isMachineOpcode() &&
00286       Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
00287     // Add an IMPLICIT_DEF instruction before every use.
00288     unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
00289     // IMPLICIT_DEF can produce any type of result so its MCInstrDesc
00290     // does not include operand register class info.
00291     if (!VReg) {
00292       const TargetRegisterClass *RC =
00293         TLI->getRegClassFor(Op.getSimpleValueType());
00294       VReg = MRI->createVirtualRegister(RC);
00295     }
00296     BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
00297             TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
00298     return VReg;
00299   }
00300 
00301   DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
00302   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
00303   return I->second;
00304 }
00305 
00306 
00307 /// AddRegisterOperand - Add the specified register as an operand to the
00308 /// specified machine instr. Insert register copies if the register is
00309 /// not in the required register class.
00310 void
00311 InstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB,
00312                                  SDValue Op,
00313                                  unsigned IIOpNum,
00314                                  const MCInstrDesc *II,
00315                                  DenseMap<SDValue, unsigned> &VRBaseMap,
00316                                  bool IsDebug, bool IsClone, bool IsCloned) {
00317   assert(Op.getValueType() != MVT::Other &&
00318          Op.getValueType() != MVT::Glue &&
00319          "Chain and glue operands should occur at end of operand list!");
00320   // Get/emit the operand.
00321   unsigned VReg = getVR(Op, VRBaseMap);
00322   assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
00323 
00324   const MCInstrDesc &MCID = MIB->getDesc();
00325   bool isOptDef = IIOpNum < MCID.getNumOperands() &&
00326     MCID.OpInfo[IIOpNum].isOptionalDef();
00327 
00328   // If the instruction requires a register in a different class, create
00329   // a new virtual register and copy the value into it, but first attempt to
00330   // shrink VReg's register class within reason.  For example, if VReg == GR32
00331   // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
00332   if (II) {
00333     const TargetRegisterClass *DstRC = nullptr;
00334     if (IIOpNum < II->getNumOperands())
00335       DstRC = TRI->getAllocatableClass(TII->getRegClass(*II,IIOpNum,TRI,*MF));
00336     if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
00337       unsigned NewVReg = MRI->createVirtualRegister(DstRC);
00338       BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
00339               TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
00340       VReg = NewVReg;
00341     }
00342   }
00343 
00344   // If this value has only one use, that use is a kill. This is a
00345   // conservative approximation. InstrEmitter does trivial coalescing
00346   // with CopyFromReg nodes, so don't emit kill flags for them.
00347   // Avoid kill flags on Schedule cloned nodes, since there will be
00348   // multiple uses.
00349   // Tied operands are never killed, so we need to check that. And that
00350   // means we need to determine the index of the operand.
00351   bool isKill = Op.hasOneUse() &&
00352                 Op.getNode()->getOpcode() != ISD::CopyFromReg &&
00353                 !IsDebug &&
00354                 !(IsClone || IsCloned);
00355   if (isKill) {
00356     unsigned Idx = MIB->getNumOperands();
00357     while (Idx > 0 &&
00358            MIB->getOperand(Idx-1).isReg() &&
00359            MIB->getOperand(Idx-1).isImplicit())
00360       --Idx;
00361     bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
00362     if (isTied)
00363       isKill = false;
00364   }
00365 
00366   MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) |
00367              getDebugRegState(IsDebug));
00368 }
00369 
00370 /// AddOperand - Add the specified operand to the specified machine instr.  II
00371 /// specifies the instruction information for the node, and IIOpNum is the
00372 /// operand number (in the II) that we are adding.
00373 void InstrEmitter::AddOperand(MachineInstrBuilder &MIB,
00374                               SDValue Op,
00375                               unsigned IIOpNum,
00376                               const MCInstrDesc *II,
00377                               DenseMap<SDValue, unsigned> &VRBaseMap,
00378                               bool IsDebug, bool IsClone, bool IsCloned) {
00379   if (Op.isMachineOpcode()) {
00380     AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
00381                        IsDebug, IsClone, IsCloned);
00382   } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
00383     MIB.addImm(C->getSExtValue());
00384   } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
00385     MIB.addFPImm(F->getConstantFPValue());
00386   } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
00387     // Turn additional physreg operands into implicit uses on non-variadic
00388     // instructions. This is used by call and return instructions passing
00389     // arguments in registers.
00390     bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic());
00391     MIB.addReg(R->getReg(), getImplRegState(Imp));
00392   } else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
00393     MIB.addRegMask(RM->getRegMask());
00394   } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
00395     MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(),
00396                          TGA->getTargetFlags());
00397   } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
00398     MIB.addMBB(BBNode->getBasicBlock());
00399   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
00400     MIB.addFrameIndex(FI->getIndex());
00401   } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
00402     MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags());
00403   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
00404     int Offset = CP->getOffset();
00405     unsigned Align = CP->getAlignment();
00406     Type *Type = CP->getType();
00407     // MachineConstantPool wants an explicit alignment.
00408     if (Align == 0) {
00409       Align = MF->getTarget().getDataLayout()->getPrefTypeAlignment(Type);
00410       if (Align == 0) {
00411         // Alignment of vector types.  FIXME!
00412         Align = MF->getTarget().getDataLayout()->getTypeAllocSize(Type);
00413       }
00414     }
00415 
00416     unsigned Idx;
00417     MachineConstantPool *MCP = MF->getConstantPool();
00418     if (CP->isMachineConstantPoolEntry())
00419       Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
00420     else
00421       Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
00422     MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags());
00423   } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
00424     MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags());
00425   } else if (auto *SymNode = dyn_cast<MCSymbolSDNode>(Op)) {
00426     MIB.addSym(SymNode->getMCSymbol());
00427   } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
00428     MIB.addBlockAddress(BA->getBlockAddress(),
00429                         BA->getOffset(),
00430                         BA->getTargetFlags());
00431   } else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
00432     MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags());
00433   } else {
00434     assert(Op.getValueType() != MVT::Other &&
00435            Op.getValueType() != MVT::Glue &&
00436            "Chain and glue operands should occur at end of operand list!");
00437     AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
00438                        IsDebug, IsClone, IsCloned);
00439   }
00440 }
00441 
00442 unsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
00443                                           MVT VT, DebugLoc DL) {
00444   const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
00445   const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
00446 
00447   // RC is a sub-class of VRC that supports SubIdx.  Try to constrain VReg
00448   // within reason.
00449   if (RC && RC != VRC)
00450     RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
00451 
00452   // VReg has been adjusted.  It can be used with SubIdx operands now.
00453   if (RC)
00454     return VReg;
00455 
00456   // VReg couldn't be reasonably constrained.  Emit a COPY to a new virtual
00457   // register instead.
00458   RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
00459   assert(RC && "No legal register class for VT supports that SubIdx");
00460   unsigned NewReg = MRI->createVirtualRegister(RC);
00461   BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
00462     .addReg(VReg);
00463   return NewReg;
00464 }
00465 
00466 /// EmitSubregNode - Generate machine code for subreg nodes.
00467 ///
00468 void InstrEmitter::EmitSubregNode(SDNode *Node,
00469                                   DenseMap<SDValue, unsigned> &VRBaseMap,
00470                                   bool IsClone, bool IsCloned) {
00471   unsigned VRBase = 0;
00472   unsigned Opc = Node->getMachineOpcode();
00473 
00474   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
00475   // the CopyToReg'd destination register instead of creating a new vreg.
00476   for (SDNode *User : Node->uses()) {
00477     if (User->getOpcode() == ISD::CopyToReg &&
00478         User->getOperand(2).getNode() == Node) {
00479       unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
00480       if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
00481         VRBase = DestReg;
00482         break;
00483       }
00484     }
00485   }
00486 
00487   if (Opc == TargetOpcode::EXTRACT_SUBREG) {
00488     // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub.  There are no
00489     // constraints on the %dst register, COPY can target all legal register
00490     // classes.
00491     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
00492     const TargetRegisterClass *TRC =
00493       TLI->getRegClassFor(Node->getSimpleValueType(0));
00494 
00495     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
00496     MachineInstr *DefMI = MRI->getVRegDef(VReg);
00497     unsigned SrcReg, DstReg, DefSubIdx;
00498     if (DefMI &&
00499         TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
00500         SubIdx == DefSubIdx &&
00501         TRC == MRI->getRegClass(SrcReg)) {
00502       // Optimize these:
00503       // r1025 = s/zext r1024, 4
00504       // r1026 = extract_subreg r1025, 4
00505       // to a copy
00506       // r1026 = copy r1024
00507       VRBase = MRI->createVirtualRegister(TRC);
00508       BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
00509               TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
00510       MRI->clearKillFlags(SrcReg);
00511     } else {
00512       // VReg may not support a SubIdx sub-register, and we may need to
00513       // constrain its register class or issue a COPY to a compatible register
00514       // class.
00515       VReg = ConstrainForSubReg(VReg, SubIdx,
00516                                 Node->getOperand(0).getSimpleValueType(),
00517                                 Node->getDebugLoc());
00518 
00519       // Create the destreg if it is missing.
00520       if (VRBase == 0)
00521         VRBase = MRI->createVirtualRegister(TRC);
00522 
00523       // Create the extract_subreg machine instruction.
00524       BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
00525               TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
00526     }
00527   } else if (Opc == TargetOpcode::INSERT_SUBREG ||
00528              Opc == TargetOpcode::SUBREG_TO_REG) {
00529     SDValue N0 = Node->getOperand(0);
00530     SDValue N1 = Node->getOperand(1);
00531     SDValue N2 = Node->getOperand(2);
00532     unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
00533 
00534     // Figure out the register class to create for the destreg.  It should be
00535     // the largest legal register class supporting SubIdx sub-registers.
00536     // RegisterCoalescer will constrain it further if it decides to eliminate
00537     // the INSERT_SUBREG instruction.
00538     //
00539     //   %dst = INSERT_SUBREG %src, %sub, SubIdx
00540     //
00541     // is lowered by TwoAddressInstructionPass to:
00542     //
00543     //   %dst = COPY %src
00544     //   %dst:SubIdx = COPY %sub
00545     //
00546     // There is no constraint on the %src register class.
00547     //
00548     const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getSimpleValueType(0));
00549     SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
00550     assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
00551 
00552     if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
00553       VRBase = MRI->createVirtualRegister(SRC);
00554 
00555     // Create the insert_subreg or subreg_to_reg machine instruction.
00556     MachineInstrBuilder MIB =
00557       BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
00558 
00559     // If creating a subreg_to_reg, then the first input operand
00560     // is an implicit value immediate, otherwise it's a register
00561     if (Opc == TargetOpcode::SUBREG_TO_REG) {
00562       const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
00563       MIB.addImm(SD->getZExtValue());
00564     } else
00565       AddOperand(MIB, N0, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
00566                  IsClone, IsCloned);
00567     // Add the subregster being inserted
00568     AddOperand(MIB, N1, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
00569                IsClone, IsCloned);
00570     MIB.addImm(SubIdx);
00571     MBB->insert(InsertPos, MIB);
00572   } else
00573     llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
00574 
00575   SDValue Op(Node, 0);
00576   bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
00577   (void)isNew; // Silence compiler warning.
00578   assert(isNew && "Node emitted out of order - early");
00579 }
00580 
00581 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
00582 /// COPY_TO_REGCLASS is just a normal copy, except that the destination
00583 /// register is constrained to be in a particular register class.
00584 ///
00585 void
00586 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
00587                                      DenseMap<SDValue, unsigned> &VRBaseMap) {
00588   unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
00589 
00590   // Create the new VReg in the destination class and emit a copy.
00591   unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
00592   const TargetRegisterClass *DstRC =
00593     TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx));
00594   unsigned NewVReg = MRI->createVirtualRegister(DstRC);
00595   BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
00596     NewVReg).addReg(VReg);
00597 
00598   SDValue Op(Node, 0);
00599   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
00600   (void)isNew; // Silence compiler warning.
00601   assert(isNew && "Node emitted out of order - early");
00602 }
00603 
00604 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
00605 ///
00606 void InstrEmitter::EmitRegSequence(SDNode *Node,
00607                                   DenseMap<SDValue, unsigned> &VRBaseMap,
00608                                   bool IsClone, bool IsCloned) {
00609   unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
00610   const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
00611   unsigned NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC));
00612   const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
00613   MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg);
00614   unsigned NumOps = Node->getNumOperands();
00615   assert((NumOps & 1) == 1 &&
00616          "REG_SEQUENCE must have an odd number of operands!");
00617   for (unsigned i = 1; i != NumOps; ++i) {
00618     SDValue Op = Node->getOperand(i);
00619     if ((i & 1) == 0) {
00620       RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
00621       // Skip physical registers as they don't have a vreg to get and we'll
00622       // insert copies for them in TwoAddressInstructionPass anyway.
00623       if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
00624         unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
00625         unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
00626         const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
00627         const TargetRegisterClass *SRC =
00628         TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
00629         if (SRC && SRC != RC) {
00630           MRI->setRegClass(NewVReg, SRC);
00631           RC = SRC;
00632         }
00633       }
00634     }
00635     AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
00636                IsClone, IsCloned);
00637   }
00638 
00639   MBB->insert(InsertPos, MIB);
00640   SDValue Op(Node, 0);
00641   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
00642   (void)isNew; // Silence compiler warning.
00643   assert(isNew && "Node emitted out of order - early");
00644 }
00645 
00646 /// EmitDbgValue - Generate machine instruction for a dbg_value node.
00647 ///
00648 MachineInstr *
00649 InstrEmitter::EmitDbgValue(SDDbgValue *SD,
00650                            DenseMap<SDValue, unsigned> &VRBaseMap) {
00651   uint64_t Offset = SD->getOffset();
00652   MDNode *Var = SD->getVariable();
00653   MDNode *Expr = SD->getExpression();
00654   DebugLoc DL = SD->getDebugLoc();
00655   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
00656          "Expected inlined-at fields to agree");
00657 
00658   if (SD->getKind() == SDDbgValue::FRAMEIX) {
00659     // Stack address; this needs to be lowered in target-dependent fashion.
00660     // EmitTargetCodeForFrameDebugValue is responsible for allocation.
00661     return BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE))
00662         .addFrameIndex(SD->getFrameIx())
00663         .addImm(Offset)
00664         .addMetadata(Var)
00665         .addMetadata(Expr);
00666   }
00667   // Otherwise, we're going to create an instruction here.
00668   const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
00669   MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
00670   if (SD->getKind() == SDDbgValue::SDNODE) {
00671     SDNode *Node = SD->getSDNode();
00672     SDValue Op = SDValue(Node, SD->getResNo());
00673     // It's possible we replaced this SDNode with other(s) and therefore
00674     // didn't generate code for it.  It's better to catch these cases where
00675     // they happen and transfer the debug info, but trying to guarantee that
00676     // in all cases would be very fragile; this is a safeguard for any
00677     // that were missed.
00678     DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
00679     if (I==VRBaseMap.end())
00680       MIB.addReg(0U);       // undef
00681     else
00682       AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
00683                  /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
00684   } else if (SD->getKind() == SDDbgValue::CONST) {
00685     const Value *V = SD->getConst();
00686     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00687       if (CI->getBitWidth() > 64)
00688         MIB.addCImm(CI);
00689       else
00690         MIB.addImm(CI->getSExtValue());
00691     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
00692       MIB.addFPImm(CF);
00693     } else {
00694       // Could be an Undef.  In any case insert an Undef so we can see what we
00695       // dropped.
00696       MIB.addReg(0U);
00697     }
00698   } else {
00699     // Insert an Undef so we can see what we dropped.
00700     MIB.addReg(0U);
00701   }
00702 
00703   // Indirect addressing is indicated by an Imm as the second parameter.
00704   if (SD->isIndirect())
00705     MIB.addImm(Offset);
00706   else {
00707     assert(Offset == 0 && "direct value cannot have an offset");
00708     MIB.addReg(0U, RegState::Debug);
00709   }
00710 
00711   MIB.addMetadata(Var);
00712   MIB.addMetadata(Expr);
00713 
00714   return &*MIB;
00715 }
00716 
00717 /// EmitMachineNode - Generate machine code for a target-specific node and
00718 /// needed dependencies.
00719 ///
00720 void InstrEmitter::
00721 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
00722                 DenseMap<SDValue, unsigned> &VRBaseMap) {
00723   unsigned Opc = Node->getMachineOpcode();
00724 
00725   // Handle subreg insert/extract specially
00726   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
00727       Opc == TargetOpcode::INSERT_SUBREG ||
00728       Opc == TargetOpcode::SUBREG_TO_REG) {
00729     EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
00730     return;
00731   }
00732 
00733   // Handle COPY_TO_REGCLASS specially.
00734   if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
00735     EmitCopyToRegClassNode(Node, VRBaseMap);
00736     return;
00737   }
00738 
00739   // Handle REG_SEQUENCE specially.
00740   if (Opc == TargetOpcode::REG_SEQUENCE) {
00741     EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
00742     return;
00743   }
00744 
00745   if (Opc == TargetOpcode::IMPLICIT_DEF)
00746     // We want a unique VR for each IMPLICIT_DEF use.
00747     return;
00748 
00749   const MCInstrDesc &II = TII->get(Opc);
00750   unsigned NumResults = CountResults(Node);
00751   unsigned NumDefs = II.getNumDefs();
00752   const MCPhysReg *ScratchRegs = nullptr;
00753 
00754   // Handle STACKMAP and PATCHPOINT specially and then use the generic code.
00755   if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) {
00756     // Stackmaps do not have arguments and do not preserve their calling
00757     // convention. However, to simplify runtime support, they clobber the same
00758     // scratch registers as AnyRegCC.
00759     unsigned CC = CallingConv::AnyReg;
00760     if (Opc == TargetOpcode::PATCHPOINT) {
00761       CC = Node->getConstantOperandVal(PatchPointOpers::CCPos);
00762       NumDefs = NumResults;
00763     }
00764     ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC);
00765   }
00766 
00767   unsigned NumImpUses = 0;
00768   unsigned NodeOperands =
00769     countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
00770   bool HasPhysRegOuts = NumResults > NumDefs && II.getImplicitDefs()!=nullptr;
00771 #ifndef NDEBUG
00772   unsigned NumMIOperands = NodeOperands + NumResults;
00773   if (II.isVariadic())
00774     assert(NumMIOperands >= II.getNumOperands() &&
00775            "Too few operands for a variadic node!");
00776   else
00777     assert(NumMIOperands >= II.getNumOperands() &&
00778            NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
00779                             NumImpUses &&
00780            "#operands for dag node doesn't match .td file!");
00781 #endif
00782 
00783   // Create the new machine instruction.
00784   MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
00785 
00786   // Add result register values for things that are defined by this
00787   // instruction.
00788   if (NumResults)
00789     CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
00790 
00791   // Emit all of the actual operands of this instruction, adding them to the
00792   // instruction as appropriate.
00793   bool HasOptPRefs = NumDefs > NumResults;
00794   assert((!HasOptPRefs || !HasPhysRegOuts) &&
00795          "Unable to cope with optional defs and phys regs defs!");
00796   unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0;
00797   for (unsigned i = NumSkip; i != NodeOperands; ++i)
00798     AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II,
00799                VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
00800 
00801   // Add scratch registers as implicit def and early clobber
00802   if (ScratchRegs)
00803     for (unsigned i = 0; ScratchRegs[i]; ++i)
00804       MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine |
00805                                  RegState::EarlyClobber);
00806 
00807   // Transfer all of the memory reference descriptions of this instruction.
00808   MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
00809                  cast<MachineSDNode>(Node)->memoperands_end());
00810 
00811   // Insert the instruction into position in the block. This needs to
00812   // happen before any custom inserter hook is called so that the
00813   // hook knows where in the block to insert the replacement code.
00814   MBB->insert(InsertPos, MIB);
00815 
00816   // The MachineInstr may also define physregs instead of virtregs.  These
00817   // physreg values can reach other instructions in different ways:
00818   //
00819   // 1. When there is a use of a Node value beyond the explicitly defined
00820   //    virtual registers, we emit a CopyFromReg for one of the implicitly
00821   //    defined physregs.  This only happens when HasPhysRegOuts is true.
00822   //
00823   // 2. A CopyFromReg reading a physreg may be glued to this instruction.
00824   //
00825   // 3. A glued instruction may implicitly use a physreg.
00826   //
00827   // 4. A glued instruction may use a RegisterSDNode operand.
00828   //
00829   // Collect all the used physreg defs, and make sure that any unused physreg
00830   // defs are marked as dead.
00831   SmallVector<unsigned, 8> UsedRegs;
00832 
00833   // Additional results must be physical register defs.
00834   if (HasPhysRegOuts) {
00835     for (unsigned i = NumDefs; i < NumResults; ++i) {
00836       unsigned Reg = II.getImplicitDefs()[i - NumDefs];
00837       if (!Node->hasAnyUseOfValue(i))
00838         continue;
00839       // This implicitly defined physreg has a use.
00840       UsedRegs.push_back(Reg);
00841       EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
00842     }
00843   }
00844 
00845   // Scan the glue chain for any used physregs.
00846   if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
00847     for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
00848       if (F->getOpcode() == ISD::CopyFromReg) {
00849         UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
00850         continue;
00851       } else if (F->getOpcode() == ISD::CopyToReg) {
00852         // Skip CopyToReg nodes that are internal to the glue chain.
00853         continue;
00854       }
00855       // Collect declared implicit uses.
00856       const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
00857       UsedRegs.append(MCID.getImplicitUses(),
00858                       MCID.getImplicitUses() + MCID.getNumImplicitUses());
00859       // In addition to declared implicit uses, we must also check for
00860       // direct RegisterSDNode operands.
00861       for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
00862         if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
00863           unsigned Reg = R->getReg();
00864           if (TargetRegisterInfo::isPhysicalRegister(Reg))
00865             UsedRegs.push_back(Reg);
00866         }
00867     }
00868   }
00869 
00870   // Finally mark unused registers as dead.
00871   if (!UsedRegs.empty() || II.getImplicitDefs())
00872     MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
00873 
00874   // Run post-isel target hook to adjust this instruction if needed.
00875   if (II.hasPostISelHook())
00876     TLI->AdjustInstrPostInstrSelection(MIB, Node);
00877 }
00878 
00879 /// EmitSpecialNode - Generate machine code for a target-independent node and
00880 /// needed dependencies.
00881 void InstrEmitter::
00882 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
00883                 DenseMap<SDValue, unsigned> &VRBaseMap) {
00884   switch (Node->getOpcode()) {
00885   default:
00886 #ifndef NDEBUG
00887     Node->dump();
00888 #endif
00889     llvm_unreachable("This target-independent node should have been selected!");
00890   case ISD::EntryToken:
00891     llvm_unreachable("EntryToken should have been excluded from the schedule!");
00892   case ISD::MERGE_VALUES:
00893   case ISD::TokenFactor: // fall thru
00894     break;
00895   case ISD::CopyToReg: {
00896     unsigned SrcReg;
00897     SDValue SrcVal = Node->getOperand(2);
00898     if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
00899       SrcReg = R->getReg();
00900     else
00901       SrcReg = getVR(SrcVal, VRBaseMap);
00902 
00903     unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
00904     if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
00905       break;
00906 
00907     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
00908             DestReg).addReg(SrcReg);
00909     break;
00910   }
00911   case ISD::CopyFromReg: {
00912     unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
00913     EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
00914     break;
00915   }
00916   case ISD::EH_LABEL: {
00917     MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
00918     BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
00919             TII->get(TargetOpcode::EH_LABEL)).addSym(S);
00920     break;
00921   }
00922 
00923   case ISD::LIFETIME_START:
00924   case ISD::LIFETIME_END: {
00925     unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ?
00926     TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END;
00927 
00928     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1));
00929     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
00930     .addFrameIndex(FI->getIndex());
00931     break;
00932   }
00933 
00934   case ISD::INLINEASM: {
00935     unsigned NumOps = Node->getNumOperands();
00936     if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
00937       --NumOps;  // Ignore the glue operand.
00938 
00939     // Create the inline asm machine instruction.
00940     MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(),
00941                                       TII->get(TargetOpcode::INLINEASM));
00942 
00943     // Add the asm string as an external symbol operand.
00944     SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
00945     const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
00946     MIB.addExternalSymbol(AsmStr);
00947 
00948     // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
00949     // bits.
00950     int64_t ExtraInfo =
00951       cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
00952                           getZExtValue();
00953     MIB.addImm(ExtraInfo);
00954 
00955     // Remember to operand index of the group flags.
00956     SmallVector<unsigned, 8> GroupIdx;
00957 
00958     // Remember registers that are part of early-clobber defs.
00959     SmallVector<unsigned, 8> ECRegs;
00960 
00961     // Add all of the operand registers to the instruction.
00962     for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
00963       unsigned Flags =
00964         cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
00965       const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
00966 
00967       GroupIdx.push_back(MIB->getNumOperands());
00968       MIB.addImm(Flags);
00969       ++i;  // Skip the ID value.
00970 
00971       switch (InlineAsm::getKind(Flags)) {
00972       default: llvm_unreachable("Bad flags!");
00973         case InlineAsm::Kind_RegDef:
00974         for (unsigned j = 0; j != NumVals; ++j, ++i) {
00975           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
00976           // FIXME: Add dead flags for physical and virtual registers defined.
00977           // For now, mark physical register defs as implicit to help fast
00978           // regalloc. This makes inline asm look a lot like calls.
00979           MIB.addReg(Reg, RegState::Define |
00980                   getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
00981         }
00982         break;
00983       case InlineAsm::Kind_RegDefEarlyClobber:
00984       case InlineAsm::Kind_Clobber:
00985         for (unsigned j = 0; j != NumVals; ++j, ++i) {
00986           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
00987           MIB.addReg(Reg, RegState::Define | RegState::EarlyClobber |
00988                   getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
00989           ECRegs.push_back(Reg);
00990         }
00991         break;
00992       case InlineAsm::Kind_RegUse:  // Use of register.
00993       case InlineAsm::Kind_Imm:  // Immediate.
00994       case InlineAsm::Kind_Mem:  // Addressing mode.
00995         // The addressing mode has been selected, just add all of the
00996         // operands to the machine instruction.
00997         for (unsigned j = 0; j != NumVals; ++j, ++i)
00998           AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap,
00999                      /*IsDebug=*/false, IsClone, IsCloned);
01000 
01001         // Manually set isTied bits.
01002         if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
01003           unsigned DefGroup = 0;
01004           if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
01005             unsigned DefIdx = GroupIdx[DefGroup] + 1;
01006             unsigned UseIdx = GroupIdx.back() + 1;
01007             for (unsigned j = 0; j != NumVals; ++j)
01008               MIB->tieOperands(DefIdx + j, UseIdx + j);
01009           }
01010         }
01011         break;
01012       }
01013     }
01014 
01015     // GCC inline assembly allows input operands to also be early-clobber
01016     // output operands (so long as the operand is written only after it's
01017     // used), but this does not match the semantics of our early-clobber flag.
01018     // If an early-clobber operand register is also an input operand register,
01019     // then remove the early-clobber flag.
01020     for (unsigned Reg : ECRegs) {
01021       if (MIB->readsRegister(Reg, TRI)) {
01022         MachineOperand *MO = MIB->findRegisterDefOperand(Reg, false, TRI);
01023         assert(MO && "No def operand for clobbered register?");
01024         MO->setIsEarlyClobber(false);
01025       }
01026     }
01027 
01028     // Get the mdnode from the asm if it exists and add it to the instruction.
01029     SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
01030     const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
01031     if (MD)
01032       MIB.addMetadata(MD);
01033 
01034     MBB->insert(InsertPos, MIB);
01035     break;
01036   }
01037   }
01038 }
01039 
01040 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
01041 /// at the given position in the given block.
01042 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
01043                            MachineBasicBlock::iterator insertpos)
01044     : MF(mbb->getParent()), MRI(&MF->getRegInfo()),
01045       TII(MF->getSubtarget().getInstrInfo()),
01046       TRI(MF->getSubtarget().getRegisterInfo()),
01047       TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb),
01048       InsertPos(insertpos) {}