Home | History | Annotate | Download | only in SelectionDAG
      1 //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This implements the Emit routines for the SelectionDAG class, which creates
     11 // MachineInstrs based on the decisions of the SelectionDAG instruction
     12 // selection.
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #define DEBUG_TYPE "instr-emitter"
     17 #include "InstrEmitter.h"
     18 #include "SDNodeDbgValue.h"
     19 #include "llvm/CodeGen/MachineConstantPool.h"
     20 #include "llvm/CodeGen/MachineFunction.h"
     21 #include "llvm/CodeGen/MachineInstrBuilder.h"
     22 #include "llvm/CodeGen/MachineRegisterInfo.h"
     23 #include "llvm/Target/TargetData.h"
     24 #include "llvm/Target/TargetMachine.h"
     25 #include "llvm/Target/TargetInstrInfo.h"
     26 #include "llvm/Target/TargetLowering.h"
     27 #include "llvm/ADT/Statistic.h"
     28 #include "llvm/Support/Debug.h"
     29 #include "llvm/Support/ErrorHandling.h"
     30 #include "llvm/Support/MathExtras.h"
     31 using namespace llvm;
     32 
     33 /// MinRCSize - Smallest register class we allow when constraining virtual
     34 /// registers.  If satisfying all register class constraints would require
     35 /// using a smaller register class, emit a COPY to a new virtual register
     36 /// instead.
     37 const unsigned MinRCSize = 4;
     38 
     39 /// CountResults - The results of target nodes have register or immediate
     40 /// operands first, then an optional chain, and optional glue operands (which do
     41 /// not go into the resulting MachineInstr).
     42 unsigned InstrEmitter::CountResults(SDNode *Node) {
     43   unsigned N = Node->getNumValues();
     44   while (N && Node->getValueType(N - 1) == MVT::Glue)
     45     --N;
     46   if (N && Node->getValueType(N - 1) == MVT::Other)
     47     --N;    // Skip over chain result.
     48   return N;
     49 }
     50 
     51 /// CountOperands - The inputs to target nodes have any actual inputs first,
     52 /// followed by an optional chain operand, then an optional glue operand.
     53 /// Compute the number of actual operands that will go into the resulting
     54 /// MachineInstr.
     55 unsigned InstrEmitter::CountOperands(SDNode *Node) {
     56   unsigned N = Node->getNumOperands();
     57   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
     58     --N;
     59   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
     60     --N; // Ignore chain if it exists.
     61   return N;
     62 }
     63 
     64 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
     65 /// implicit physical register output.
     66 void InstrEmitter::
     67 EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
     68                 unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
     69   unsigned VRBase = 0;
     70   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
     71     // Just use the input register directly!
     72     SDValue Op(Node, ResNo);
     73     if (IsClone)
     74       VRBaseMap.erase(Op);
     75     bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
     76     (void)isNew; // Silence compiler warning.
     77     assert(isNew && "Node emitted out of order - early");
     78     return;
     79   }
     80 
     81   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
     82   // the CopyToReg'd destination register instead of creating a new vreg.
     83   bool MatchReg = true;
     84   const TargetRegisterClass *UseRC = NULL;
     85   EVT VT = Node->getValueType(ResNo);
     86 
     87   // Stick to the preferred register classes for legal types.
     88   if (TLI->isTypeLegal(VT))
     89     UseRC = TLI->getRegClassFor(VT);
     90 
     91   if (!IsClone && !IsCloned)
     92     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
     93          UI != E; ++UI) {
     94       SDNode *User = *UI;
     95       bool Match = true;
     96       if (User->getOpcode() == ISD::CopyToReg &&
     97           User->getOperand(2).getNode() == Node &&
     98           User->getOperand(2).getResNo() == ResNo) {
     99         unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
    100         if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
    101           VRBase = DestReg;
    102           Match = false;
    103         } else if (DestReg != SrcReg)
    104           Match = false;
    105       } else {
    106         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
    107           SDValue Op = User->getOperand(i);
    108           if (Op.getNode() != Node || Op.getResNo() != ResNo)
    109             continue;
    110           EVT VT = Node->getValueType(Op.getResNo());
    111           if (VT == MVT::Other || VT == MVT::Glue)
    112             continue;
    113           Match = false;
    114           if (User->isMachineOpcode()) {
    115             const MCInstrDesc &II = TII->get(User->getMachineOpcode());
    116             const TargetRegisterClass *RC = 0;
    117             if (i+II.getNumDefs() < II.getNumOperands())
    118               RC = TII->getRegClass(II, i+II.getNumDefs(), TRI);
    119             if (!UseRC)
    120               UseRC = RC;
    121             else if (RC) {
    122               const TargetRegisterClass *ComRC =
    123                 TRI->getCommonSubClass(UseRC, RC);
    124               // If multiple uses expect disjoint register classes, we emit
    125               // copies in AddRegisterOperand.
    126               if (ComRC)
    127                 UseRC = ComRC;
    128             }
    129           }
    130         }
    131       }
    132       MatchReg &= Match;
    133       if (VRBase)
    134         break;
    135     }
    136 
    137   const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
    138   SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
    139 
    140   // Figure out the register class to create for the destreg.
    141   if (VRBase) {
    142     DstRC = MRI->getRegClass(VRBase);
    143   } else if (UseRC) {
    144     assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
    145     DstRC = UseRC;
    146   } else {
    147     DstRC = TLI->getRegClassFor(VT);
    148   }
    149 
    150   // If all uses are reading from the src physical register and copying the
    151   // register is either impossible or very expensive, then don't create a copy.
    152   if (MatchReg && SrcRC->getCopyCost() < 0) {
    153     VRBase = SrcReg;
    154   } else {
    155     // Create the reg, emit the copy.
    156     VRBase = MRI->createVirtualRegister(DstRC);
    157     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
    158             VRBase).addReg(SrcReg);
    159   }
    160 
    161   SDValue Op(Node, ResNo);
    162   if (IsClone)
    163     VRBaseMap.erase(Op);
    164   bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
    165   (void)isNew; // Silence compiler warning.
    166   assert(isNew && "Node emitted out of order - early");
    167 }
    168 
    169 /// getDstOfCopyToRegUse - If the only use of the specified result number of
    170 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
    171 unsigned InstrEmitter::getDstOfOnlyCopyToRegUse(SDNode *Node,
    172                                                 unsigned ResNo) const {
    173   if (!Node->hasOneUse())
    174     return 0;
    175 
    176   SDNode *User = *Node->use_begin();
    177   if (User->getOpcode() == ISD::CopyToReg &&
    178       User->getOperand(2).getNode() == Node &&
    179       User->getOperand(2).getResNo() == ResNo) {
    180     unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
    181     if (TargetRegisterInfo::isVirtualRegister(Reg))
    182       return Reg;
    183   }
    184   return 0;
    185 }
    186 
    187 void InstrEmitter::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
    188                                        const MCInstrDesc &II,
    189                                        bool IsClone, bool IsCloned,
    190                                        DenseMap<SDValue, unsigned> &VRBaseMap) {
    191   assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
    192          "IMPLICIT_DEF should have been handled as a special case elsewhere!");
    193 
    194   for (unsigned i = 0; i < II.getNumDefs(); ++i) {
    195     // If the specific node value is only used by a CopyToReg and the dest reg
    196     // is a vreg in the same register class, use the CopyToReg'd destination
    197     // register instead of creating a new vreg.
    198     unsigned VRBase = 0;
    199     const TargetRegisterClass *RC = TII->getRegClass(II, i, TRI);
    200     if (II.OpInfo[i].isOptionalDef()) {
    201       // Optional def must be a physical register.
    202       unsigned NumResults = CountResults(Node);
    203       VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
    204       assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
    205       MI->addOperand(MachineOperand::CreateReg(VRBase, true));
    206     }
    207 
    208     if (!VRBase && !IsClone && !IsCloned)
    209       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
    210            UI != E; ++UI) {
    211         SDNode *User = *UI;
    212         if (User->getOpcode() == ISD::CopyToReg &&
    213             User->getOperand(2).getNode() == Node &&
    214             User->getOperand(2).getResNo() == i) {
    215           unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
    216           if (TargetRegisterInfo::isVirtualRegister(Reg)) {
    217             const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
    218             if (RegRC == RC) {
    219               VRBase = Reg;
    220               MI->addOperand(MachineOperand::CreateReg(Reg, true));
    221               break;
    222             }
    223           }
    224         }
    225       }
    226 
    227     // Create the result registers for this node and add the result regs to
    228     // the machine instruction.
    229     if (VRBase == 0) {
    230       assert(RC && "Isn't a register operand!");
    231       VRBase = MRI->createVirtualRegister(RC);
    232       MI->addOperand(MachineOperand::CreateReg(VRBase, true));
    233     }
    234 
    235     SDValue Op(Node, i);
    236     if (IsClone)
    237       VRBaseMap.erase(Op);
    238     bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
    239     (void)isNew; // Silence compiler warning.
    240     assert(isNew && "Node emitted out of order - early");
    241   }
    242 }
    243 
    244 /// getVR - Return the virtual register corresponding to the specified result
    245 /// of the specified node.
    246 unsigned InstrEmitter::getVR(SDValue Op,
    247                              DenseMap<SDValue, unsigned> &VRBaseMap) {
    248   if (Op.isMachineOpcode() &&
    249       Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
    250     // Add an IMPLICIT_DEF instruction before every use.
    251     unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
    252     // IMPLICIT_DEF can produce any type of result so its MCInstrDesc
    253     // does not include operand register class info.
    254     if (!VReg) {
    255       const TargetRegisterClass *RC = TLI->getRegClassFor(Op.getValueType());
    256       VReg = MRI->createVirtualRegister(RC);
    257     }
    258     BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
    259             TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
    260     return VReg;
    261   }
    262 
    263   DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
    264   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
    265   return I->second;
    266 }
    267 
    268 
    269 /// AddRegisterOperand - Add the specified register as an operand to the
    270 /// specified machine instr. Insert register copies if the register is
    271 /// not in the required register class.
    272 void
    273 InstrEmitter::AddRegisterOperand(MachineInstr *MI, SDValue Op,
    274                                  unsigned IIOpNum,
    275                                  const MCInstrDesc *II,
    276                                  DenseMap<SDValue, unsigned> &VRBaseMap,
    277                                  bool IsDebug, bool IsClone, bool IsCloned) {
    278   assert(Op.getValueType() != MVT::Other &&
    279          Op.getValueType() != MVT::Glue &&
    280          "Chain and glue operands should occur at end of operand list!");
    281   // Get/emit the operand.
    282   unsigned VReg = getVR(Op, VRBaseMap);
    283   assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
    284 
    285   const MCInstrDesc &MCID = MI->getDesc();
    286   bool isOptDef = IIOpNum < MCID.getNumOperands() &&
    287     MCID.OpInfo[IIOpNum].isOptionalDef();
    288 
    289   // If the instruction requires a register in a different class, create
    290   // a new virtual register and copy the value into it, but first attempt to
    291   // shrink VReg's register class within reason.  For example, if VReg == GR32
    292   // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
    293   if (II) {
    294     const TargetRegisterClass *DstRC = 0;
    295     if (IIOpNum < II->getNumOperands())
    296       DstRC = TII->getRegClass(*II, IIOpNum, TRI);
    297     assert((DstRC || (MCID.isVariadic() && IIOpNum >= MCID.getNumOperands())) &&
    298            "Don't have operand info for this instruction!");
    299     if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
    300       unsigned NewVReg = MRI->createVirtualRegister(DstRC);
    301       BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
    302               TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
    303       VReg = NewVReg;
    304     }
    305   }
    306 
    307   // If this value has only one use, that use is a kill. This is a
    308   // conservative approximation. InstrEmitter does trivial coalescing
    309   // with CopyFromReg nodes, so don't emit kill flags for them.
    310   // Avoid kill flags on Schedule cloned nodes, since there will be
    311   // multiple uses.
    312   // Tied operands are never killed, so we need to check that. And that
    313   // means we need to determine the index of the operand.
    314   bool isKill = Op.hasOneUse() &&
    315                 Op.getNode()->getOpcode() != ISD::CopyFromReg &&
    316                 !IsDebug &&
    317                 !(IsClone || IsCloned);
    318   if (isKill) {
    319     unsigned Idx = MI->getNumOperands();
    320     while (Idx > 0 &&
    321            MI->getOperand(Idx-1).isReg() && MI->getOperand(Idx-1).isImplicit())
    322       --Idx;
    323     bool isTied = MI->getDesc().getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
    324     if (isTied)
    325       isKill = false;
    326   }
    327 
    328   MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef,
    329                                            false/*isImp*/, isKill,
    330                                            false/*isDead*/, false/*isUndef*/,
    331                                            false/*isEarlyClobber*/,
    332                                            0/*SubReg*/, IsDebug));
    333 }
    334 
    335 /// AddOperand - Add the specified operand to the specified machine instr.  II
    336 /// specifies the instruction information for the node, and IIOpNum is the
    337 /// operand number (in the II) that we are adding. IIOpNum and II are used for
    338 /// assertions only.
    339 void InstrEmitter::AddOperand(MachineInstr *MI, SDValue Op,
    340                               unsigned IIOpNum,
    341                               const MCInstrDesc *II,
    342                               DenseMap<SDValue, unsigned> &VRBaseMap,
    343                               bool IsDebug, bool IsClone, bool IsCloned) {
    344   if (Op.isMachineOpcode()) {
    345     AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap,
    346                        IsDebug, IsClone, IsCloned);
    347   } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
    348     MI->addOperand(MachineOperand::CreateImm(C->getSExtValue()));
    349   } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
    350     const ConstantFP *CFP = F->getConstantFPValue();
    351     MI->addOperand(MachineOperand::CreateFPImm(CFP));
    352   } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
    353     MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
    354   } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
    355     MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(), TGA->getOffset(),
    356                                             TGA->getTargetFlags()));
    357   } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
    358     MI->addOperand(MachineOperand::CreateMBB(BBNode->getBasicBlock()));
    359   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
    360     MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
    361   } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
    362     MI->addOperand(MachineOperand::CreateJTI(JT->getIndex(),
    363                                              JT->getTargetFlags()));
    364   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
    365     int Offset = CP->getOffset();
    366     unsigned Align = CP->getAlignment();
    367     Type *Type = CP->getType();
    368     // MachineConstantPool wants an explicit alignment.
    369     if (Align == 0) {
    370       Align = TM->getTargetData()->getPrefTypeAlignment(Type);
    371       if (Align == 0) {
    372         // Alignment of vector types.  FIXME!
    373         Align = TM->getTargetData()->getTypeAllocSize(Type);
    374       }
    375     }
    376 
    377     unsigned Idx;
    378     MachineConstantPool *MCP = MF->getConstantPool();
    379     if (CP->isMachineConstantPoolEntry())
    380       Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
    381     else
    382       Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
    383     MI->addOperand(MachineOperand::CreateCPI(Idx, Offset,
    384                                              CP->getTargetFlags()));
    385   } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
    386     MI->addOperand(MachineOperand::CreateES(ES->getSymbol(),
    387                                             ES->getTargetFlags()));
    388   } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
    389     MI->addOperand(MachineOperand::CreateBA(BA->getBlockAddress(),
    390                                             BA->getTargetFlags()));
    391   } else {
    392     assert(Op.getValueType() != MVT::Other &&
    393            Op.getValueType() != MVT::Glue &&
    394            "Chain and glue operands should occur at end of operand list!");
    395     AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap,
    396                        IsDebug, IsClone, IsCloned);
    397   }
    398 }
    399 
    400 unsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
    401                                           EVT VT, DebugLoc DL) {
    402   const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
    403   const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
    404 
    405   // RC is a sub-class of VRC that supports SubIdx.  Try to constrain VReg
    406   // within reason.
    407   if (RC && RC != VRC)
    408     RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
    409 
    410   // VReg has been adjusted.  It can be used with SubIdx operands now.
    411   if (RC)
    412     return VReg;
    413 
    414   // VReg couldn't be reasonably constrained.  Emit a COPY to a new virtual
    415   // register instead.
    416   RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
    417   assert(RC && "No legal register class for VT supports that SubIdx");
    418   unsigned NewReg = MRI->createVirtualRegister(RC);
    419   BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
    420     .addReg(VReg);
    421   return NewReg;
    422 }
    423 
    424 /// EmitSubregNode - Generate machine code for subreg nodes.
    425 ///
    426 void InstrEmitter::EmitSubregNode(SDNode *Node,
    427                                   DenseMap<SDValue, unsigned> &VRBaseMap,
    428                                   bool IsClone, bool IsCloned) {
    429   unsigned VRBase = 0;
    430   unsigned Opc = Node->getMachineOpcode();
    431 
    432   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
    433   // the CopyToReg'd destination register instead of creating a new vreg.
    434   for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
    435        UI != E; ++UI) {
    436     SDNode *User = *UI;
    437     if (User->getOpcode() == ISD::CopyToReg &&
    438         User->getOperand(2).getNode() == Node) {
    439       unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
    440       if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
    441         VRBase = DestReg;
    442         break;
    443       }
    444     }
    445   }
    446 
    447   if (Opc == TargetOpcode::EXTRACT_SUBREG) {
    448     // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub.  There are no
    449     // constraints on the %dst register, COPY can target all legal register
    450     // classes.
    451     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
    452     const TargetRegisterClass *TRC = TLI->getRegClassFor(Node->getValueType(0));
    453 
    454     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
    455     MachineInstr *DefMI = MRI->getVRegDef(VReg);
    456     unsigned SrcReg, DstReg, DefSubIdx;
    457     if (DefMI &&
    458         TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
    459         SubIdx == DefSubIdx) {
    460       // Optimize these:
    461       // r1025 = s/zext r1024, 4
    462       // r1026 = extract_subreg r1025, 4
    463       // to a copy
    464       // r1026 = copy r1024
    465       VRBase = MRI->createVirtualRegister(TRC);
    466       BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
    467               TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
    468     } else {
    469       // VReg may not support a SubIdx sub-register, and we may need to
    470       // constrain its register class or issue a COPY to a compatible register
    471       // class.
    472       VReg = ConstrainForSubReg(VReg, SubIdx,
    473                                 Node->getOperand(0).getValueType(),
    474                                 Node->getDebugLoc());
    475 
    476       // Create the destreg if it is missing.
    477       if (VRBase == 0)
    478         VRBase = MRI->createVirtualRegister(TRC);
    479 
    480       // Create the extract_subreg machine instruction.
    481       BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
    482               TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
    483     }
    484   } else if (Opc == TargetOpcode::INSERT_SUBREG ||
    485              Opc == TargetOpcode::SUBREG_TO_REG) {
    486     SDValue N0 = Node->getOperand(0);
    487     SDValue N1 = Node->getOperand(1);
    488     SDValue N2 = Node->getOperand(2);
    489     unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
    490 
    491     // Figure out the register class to create for the destreg.  It should be
    492     // the largest legal register class supporting SubIdx sub-registers.
    493     // RegisterCoalescer will constrain it further if it decides to eliminate
    494     // the INSERT_SUBREG instruction.
    495     //
    496     //   %dst = INSERT_SUBREG %src, %sub, SubIdx
    497     //
    498     // is lowered by TwoAddressInstructionPass to:
    499     //
    500     //   %dst = COPY %src
    501     //   %dst:SubIdx = COPY %sub
    502     //
    503     // There is no constraint on the %src register class.
    504     //
    505     const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getValueType(0));
    506     SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
    507     assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
    508 
    509     if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
    510       VRBase = MRI->createVirtualRegister(SRC);
    511 
    512     // Create the insert_subreg or subreg_to_reg machine instruction.
    513     MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc));
    514     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
    515 
    516     // If creating a subreg_to_reg, then the first input operand
    517     // is an implicit value immediate, otherwise it's a register
    518     if (Opc == TargetOpcode::SUBREG_TO_REG) {
    519       const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
    520       MI->addOperand(MachineOperand::CreateImm(SD->getZExtValue()));
    521     } else
    522       AddOperand(MI, N0, 0, 0, VRBaseMap, /*IsDebug=*/false,
    523                  IsClone, IsCloned);
    524     // Add the subregster being inserted
    525     AddOperand(MI, N1, 0, 0, VRBaseMap, /*IsDebug=*/false,
    526                IsClone, IsCloned);
    527     MI->addOperand(MachineOperand::CreateImm(SubIdx));
    528     MBB->insert(InsertPos, MI);
    529   } else
    530     llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
    531 
    532   SDValue Op(Node, 0);
    533   bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
    534   (void)isNew; // Silence compiler warning.
    535   assert(isNew && "Node emitted out of order - early");
    536 }
    537 
    538 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
    539 /// COPY_TO_REGCLASS is just a normal copy, except that the destination
    540 /// register is constrained to be in a particular register class.
    541 ///
    542 void
    543 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
    544                                      DenseMap<SDValue, unsigned> &VRBaseMap) {
    545   unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
    546 
    547   // Create the new VReg in the destination class and emit a copy.
    548   unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
    549   const TargetRegisterClass *DstRC = TRI->getRegClass(DstRCIdx);
    550   unsigned NewVReg = MRI->createVirtualRegister(DstRC);
    551   BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
    552     NewVReg).addReg(VReg);
    553 
    554   SDValue Op(Node, 0);
    555   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
    556   (void)isNew; // Silence compiler warning.
    557   assert(isNew && "Node emitted out of order - early");
    558 }
    559 
    560 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
    561 ///
    562 void InstrEmitter::EmitRegSequence(SDNode *Node,
    563                                   DenseMap<SDValue, unsigned> &VRBaseMap,
    564                                   bool IsClone, bool IsCloned) {
    565   unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
    566   const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
    567   unsigned NewVReg = MRI->createVirtualRegister(RC);
    568   MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
    569                              TII->get(TargetOpcode::REG_SEQUENCE), NewVReg);
    570   unsigned NumOps = Node->getNumOperands();
    571   assert((NumOps & 1) == 1 &&
    572          "REG_SEQUENCE must have an odd number of operands!");
    573   const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
    574   for (unsigned i = 1; i != NumOps; ++i) {
    575     SDValue Op = Node->getOperand(i);
    576     if ((i & 1) == 0) {
    577       unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
    578       unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
    579       const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
    580       const TargetRegisterClass *SRC =
    581         TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
    582       if (SRC && SRC != RC) {
    583         MRI->setRegClass(NewVReg, SRC);
    584         RC = SRC;
    585       }
    586     }
    587     AddOperand(MI, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
    588                IsClone, IsCloned);
    589   }
    590 
    591   MBB->insert(InsertPos, MI);
    592   SDValue Op(Node, 0);
    593   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
    594   (void)isNew; // Silence compiler warning.
    595   assert(isNew && "Node emitted out of order - early");
    596 }
    597 
    598 /// EmitDbgValue - Generate machine instruction for a dbg_value node.
    599 ///
    600 MachineInstr *
    601 InstrEmitter::EmitDbgValue(SDDbgValue *SD,
    602                            DenseMap<SDValue, unsigned> &VRBaseMap) {
    603   uint64_t Offset = SD->getOffset();
    604   MDNode* MDPtr = SD->getMDPtr();
    605   DebugLoc DL = SD->getDebugLoc();
    606 
    607   if (SD->getKind() == SDDbgValue::FRAMEIX) {
    608     // Stack address; this needs to be lowered in target-dependent fashion.
    609     // EmitTargetCodeForFrameDebugValue is responsible for allocation.
    610     unsigned FrameIx = SD->getFrameIx();
    611     return TII->emitFrameIndexDebugValue(*MF, FrameIx, Offset, MDPtr, DL);
    612   }
    613   // Otherwise, we're going to create an instruction here.
    614   const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
    615   MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
    616   if (SD->getKind() == SDDbgValue::SDNODE) {
    617     SDNode *Node = SD->getSDNode();
    618     SDValue Op = SDValue(Node, SD->getResNo());
    619     // It's possible we replaced this SDNode with other(s) and therefore
    620     // didn't generate code for it.  It's better to catch these cases where
    621     // they happen and transfer the debug info, but trying to guarantee that
    622     // in all cases would be very fragile; this is a safeguard for any
    623     // that were missed.
    624     DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
    625     if (I==VRBaseMap.end())
    626       MIB.addReg(0U);       // undef
    627     else
    628       AddOperand(&*MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
    629                  /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
    630   } else if (SD->getKind() == SDDbgValue::CONST) {
    631     const Value *V = SD->getConst();
    632     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    633       if (CI->getBitWidth() > 64)
    634         MIB.addCImm(CI);
    635       else
    636         MIB.addImm(CI->getSExtValue());
    637     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
    638       MIB.addFPImm(CF);
    639     } else {
    640       // Could be an Undef.  In any case insert an Undef so we can see what we
    641       // dropped.
    642       MIB.addReg(0U);
    643     }
    644   } else {
    645     // Insert an Undef so we can see what we dropped.
    646     MIB.addReg(0U);
    647   }
    648 
    649   MIB.addImm(Offset).addMetadata(MDPtr);
    650   return &*MIB;
    651 }
    652 
    653 /// EmitMachineNode - Generate machine code for a target-specific node and
    654 /// needed dependencies.
    655 ///
    656 void InstrEmitter::
    657 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
    658                 DenseMap<SDValue, unsigned> &VRBaseMap) {
    659   unsigned Opc = Node->getMachineOpcode();
    660 
    661   // Handle subreg insert/extract specially
    662   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
    663       Opc == TargetOpcode::INSERT_SUBREG ||
    664       Opc == TargetOpcode::SUBREG_TO_REG) {
    665     EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
    666     return;
    667   }
    668 
    669   // Handle COPY_TO_REGCLASS specially.
    670   if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
    671     EmitCopyToRegClassNode(Node, VRBaseMap);
    672     return;
    673   }
    674 
    675   // Handle REG_SEQUENCE specially.
    676   if (Opc == TargetOpcode::REG_SEQUENCE) {
    677     EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
    678     return;
    679   }
    680 
    681   if (Opc == TargetOpcode::IMPLICIT_DEF)
    682     // We want a unique VR for each IMPLICIT_DEF use.
    683     return;
    684 
    685   const MCInstrDesc &II = TII->get(Opc);
    686   unsigned NumResults = CountResults(Node);
    687   unsigned NodeOperands = CountOperands(Node);
    688   bool HasPhysRegOuts = NumResults > II.getNumDefs() && II.getImplicitDefs()!=0;
    689 #ifndef NDEBUG
    690   unsigned NumMIOperands = NodeOperands + NumResults;
    691   if (II.isVariadic())
    692     assert(NumMIOperands >= II.getNumOperands() &&
    693            "Too few operands for a variadic node!");
    694   else
    695     assert(NumMIOperands >= II.getNumOperands() &&
    696            NumMIOperands <= II.getNumOperands()+II.getNumImplicitDefs() &&
    697            "#operands for dag node doesn't match .td file!");
    698 #endif
    699 
    700   // Create the new machine instruction.
    701   MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), II);
    702 
    703   // The MachineInstr constructor adds implicit-def operands. Scan through
    704   // these to determine which are dead.
    705   if (MI->getNumOperands() != 0 &&
    706       Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
    707     // First, collect all used registers.
    708     SmallVector<unsigned, 8> UsedRegs;
    709     for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser())
    710       if (F->getOpcode() == ISD::CopyFromReg)
    711         UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
    712       else {
    713         // Collect declared implicit uses.
    714         const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
    715         UsedRegs.append(MCID.getImplicitUses(),
    716                         MCID.getImplicitUses() + MCID.getNumImplicitUses());
    717         // In addition to declared implicit uses, we must also check for
    718         // direct RegisterSDNode operands.
    719         for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
    720           if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
    721             unsigned Reg = R->getReg();
    722             if (TargetRegisterInfo::isPhysicalRegister(Reg))
    723               UsedRegs.push_back(Reg);
    724           }
    725       }
    726     // Then mark unused registers as dead.
    727     MI->setPhysRegsDeadExcept(UsedRegs, *TRI);
    728   }
    729 
    730   // Add result register values for things that are defined by this
    731   // instruction.
    732   if (NumResults)
    733     CreateVirtualRegisters(Node, MI, II, IsClone, IsCloned, VRBaseMap);
    734 
    735   // Emit all of the actual operands of this instruction, adding them to the
    736   // instruction as appropriate.
    737   bool HasOptPRefs = II.getNumDefs() > NumResults;
    738   assert((!HasOptPRefs || !HasPhysRegOuts) &&
    739          "Unable to cope with optional defs and phys regs defs!");
    740   unsigned NumSkip = HasOptPRefs ? II.getNumDefs() - NumResults : 0;
    741   for (unsigned i = NumSkip; i != NodeOperands; ++i)
    742     AddOperand(MI, Node->getOperand(i), i-NumSkip+II.getNumDefs(), &II,
    743                VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
    744 
    745   // Transfer all of the memory reference descriptions of this instruction.
    746   MI->setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
    747                  cast<MachineSDNode>(Node)->memoperands_end());
    748 
    749   // Insert the instruction into position in the block. This needs to
    750   // happen before any custom inserter hook is called so that the
    751   // hook knows where in the block to insert the replacement code.
    752   MBB->insert(InsertPos, MI);
    753 
    754   // Additional results must be physical register defs.
    755   if (HasPhysRegOuts) {
    756     for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
    757       unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
    758       if (Node->hasAnyUseOfValue(i))
    759         EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
    760       // If there are no uses, mark the register as dead now, so that
    761       // MachineLICM/Sink can see that it's dead. Don't do this if the
    762       // node has a Glue value, for the benefit of targets still using
    763       // Glue for values in physregs.
    764       else if (Node->getValueType(Node->getNumValues()-1) != MVT::Glue)
    765         MI->addRegisterDead(Reg, TRI);
    766     }
    767   }
    768 
    769   // If the instruction has implicit defs and the node doesn't, mark the
    770   // implicit def as dead.  If the node has any glue outputs, we don't do this
    771   // because we don't know what implicit defs are being used by glued nodes.
    772   if (Node->getValueType(Node->getNumValues()-1) != MVT::Glue)
    773     if (const unsigned *IDList = II.getImplicitDefs()) {
    774       for (unsigned i = NumResults, e = II.getNumDefs()+II.getNumImplicitDefs();
    775            i != e; ++i)
    776         MI->addRegisterDead(IDList[i-II.getNumDefs()], TRI);
    777     }
    778 
    779   // Run post-isel target hook to adjust this instruction if needed.
    780 #ifdef NDEBUG
    781   if (II.hasPostISelHook())
    782 #endif
    783     TLI->AdjustInstrPostInstrSelection(MI, Node);
    784 }
    785 
    786 /// EmitSpecialNode - Generate machine code for a target-independent node and
    787 /// needed dependencies.
    788 void InstrEmitter::
    789 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
    790                 DenseMap<SDValue, unsigned> &VRBaseMap) {
    791   switch (Node->getOpcode()) {
    792   default:
    793 #ifndef NDEBUG
    794     Node->dump();
    795 #endif
    796     llvm_unreachable("This target-independent node should have been selected!");
    797     break;
    798   case ISD::EntryToken:
    799     llvm_unreachable("EntryToken should have been excluded from the schedule!");
    800     break;
    801   case ISD::MERGE_VALUES:
    802   case ISD::TokenFactor: // fall thru
    803     break;
    804   case ISD::CopyToReg: {
    805     unsigned SrcReg;
    806     SDValue SrcVal = Node->getOperand(2);
    807     if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
    808       SrcReg = R->getReg();
    809     else
    810       SrcReg = getVR(SrcVal, VRBaseMap);
    811 
    812     unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
    813     if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
    814       break;
    815 
    816     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
    817             DestReg).addReg(SrcReg);
    818     break;
    819   }
    820   case ISD::CopyFromReg: {
    821     unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
    822     EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
    823     break;
    824   }
    825   case ISD::EH_LABEL: {
    826     MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
    827     BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
    828             TII->get(TargetOpcode::EH_LABEL)).addSym(S);
    829     break;
    830   }
    831 
    832   case ISD::INLINEASM: {
    833     unsigned NumOps = Node->getNumOperands();
    834     if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
    835       --NumOps;  // Ignore the glue operand.
    836 
    837     // Create the inline asm machine instruction.
    838     MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
    839                                TII->get(TargetOpcode::INLINEASM));
    840 
    841     // Add the asm string as an external symbol operand.
    842     SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
    843     const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
    844     MI->addOperand(MachineOperand::CreateES(AsmStr));
    845 
    846     // Add the HasSideEffect and isAlignStack bits.
    847     int64_t ExtraInfo =
    848       cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
    849                           getZExtValue();
    850     MI->addOperand(MachineOperand::CreateImm(ExtraInfo));
    851 
    852     // Add all of the operand registers to the instruction.
    853     for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
    854       unsigned Flags =
    855         cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
    856       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
    857 
    858       MI->addOperand(MachineOperand::CreateImm(Flags));
    859       ++i;  // Skip the ID value.
    860 
    861       switch (InlineAsm::getKind(Flags)) {
    862       default: llvm_unreachable("Bad flags!");
    863         case InlineAsm::Kind_RegDef:
    864         for (; NumVals; --NumVals, ++i) {
    865           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
    866           // FIXME: Add dead flags for physical and virtual registers defined.
    867           // For now, mark physical register defs as implicit to help fast
    868           // regalloc. This makes inline asm look a lot like calls.
    869           MI->addOperand(MachineOperand::CreateReg(Reg, true,
    870                        /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg)));
    871         }
    872         break;
    873       case InlineAsm::Kind_RegDefEarlyClobber:
    874       case InlineAsm::Kind_Clobber:
    875         for (; NumVals; --NumVals, ++i) {
    876           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
    877           MI->addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/ true,
    878                          /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg),
    879                                                    /*isKill=*/ false,
    880                                                    /*isDead=*/ false,
    881                                                    /*isUndef=*/false,
    882                                                    /*isEarlyClobber=*/ true));
    883         }
    884         break;
    885       case InlineAsm::Kind_RegUse:  // Use of register.
    886       case InlineAsm::Kind_Imm:  // Immediate.
    887       case InlineAsm::Kind_Mem:  // Addressing mode.
    888         // The addressing mode has been selected, just add all of the
    889         // operands to the machine instruction.
    890         for (; NumVals; --NumVals, ++i)
    891           AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap,
    892                      /*IsDebug=*/false, IsClone, IsCloned);
    893         break;
    894       }
    895     }
    896 
    897     // Get the mdnode from the asm if it exists and add it to the instruction.
    898     SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
    899     const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
    900     if (MD)
    901       MI->addOperand(MachineOperand::CreateMetadata(MD));
    902 
    903     MBB->insert(InsertPos, MI);
    904     break;
    905   }
    906   }
    907 }
    908 
    909 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
    910 /// at the given position in the given block.
    911 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
    912                            MachineBasicBlock::iterator insertpos)
    913   : MF(mbb->getParent()),
    914     MRI(&MF->getRegInfo()),
    915     TM(&MF->getTarget()),
    916     TII(TM->getInstrInfo()),
    917     TRI(TM->getRegisterInfo()),
    918     TLI(TM->getTargetLowering()),
    919     MBB(mbb), InsertPos(insertpos) {
    920 }
    921