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 || (MI->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 (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
    355     MI->addOperand(MachineOperand::CreateRegMask(RM->getRegMask()));
    356   } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
    357     MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(), TGA->getOffset(),
    358                                             TGA->getTargetFlags()));
    359   } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
    360     MI->addOperand(MachineOperand::CreateMBB(BBNode->getBasicBlock()));
    361   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
    362     MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
    363   } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
    364     MI->addOperand(MachineOperand::CreateJTI(JT->getIndex(),
    365                                              JT->getTargetFlags()));
    366   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
    367     int Offset = CP->getOffset();
    368     unsigned Align = CP->getAlignment();
    369     Type *Type = CP->getType();
    370     // MachineConstantPool wants an explicit alignment.
    371     if (Align == 0) {
    372       Align = TM->getTargetData()->getPrefTypeAlignment(Type);
    373       if (Align == 0) {
    374         // Alignment of vector types.  FIXME!
    375         Align = TM->getTargetData()->getTypeAllocSize(Type);
    376       }
    377     }
    378 
    379     unsigned Idx;
    380     MachineConstantPool *MCP = MF->getConstantPool();
    381     if (CP->isMachineConstantPoolEntry())
    382       Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
    383     else
    384       Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
    385     MI->addOperand(MachineOperand::CreateCPI(Idx, Offset,
    386                                              CP->getTargetFlags()));
    387   } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
    388     MI->addOperand(MachineOperand::CreateES(ES->getSymbol(),
    389                                             ES->getTargetFlags()));
    390   } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
    391     MI->addOperand(MachineOperand::CreateBA(BA->getBlockAddress(),
    392                                             BA->getTargetFlags()));
    393   } else {
    394     assert(Op.getValueType() != MVT::Other &&
    395            Op.getValueType() != MVT::Glue &&
    396            "Chain and glue operands should occur at end of operand list!");
    397     AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap,
    398                        IsDebug, IsClone, IsCloned);
    399   }
    400 }
    401 
    402 unsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
    403                                           EVT VT, DebugLoc DL) {
    404   const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
    405   const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
    406 
    407   // RC is a sub-class of VRC that supports SubIdx.  Try to constrain VReg
    408   // within reason.
    409   if (RC && RC != VRC)
    410     RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
    411 
    412   // VReg has been adjusted.  It can be used with SubIdx operands now.
    413   if (RC)
    414     return VReg;
    415 
    416   // VReg couldn't be reasonably constrained.  Emit a COPY to a new virtual
    417   // register instead.
    418   RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
    419   assert(RC && "No legal register class for VT supports that SubIdx");
    420   unsigned NewReg = MRI->createVirtualRegister(RC);
    421   BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
    422     .addReg(VReg);
    423   return NewReg;
    424 }
    425 
    426 /// EmitSubregNode - Generate machine code for subreg nodes.
    427 ///
    428 void InstrEmitter::EmitSubregNode(SDNode *Node,
    429                                   DenseMap<SDValue, unsigned> &VRBaseMap,
    430                                   bool IsClone, bool IsCloned) {
    431   unsigned VRBase = 0;
    432   unsigned Opc = Node->getMachineOpcode();
    433 
    434   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
    435   // the CopyToReg'd destination register instead of creating a new vreg.
    436   for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
    437        UI != E; ++UI) {
    438     SDNode *User = *UI;
    439     if (User->getOpcode() == ISD::CopyToReg &&
    440         User->getOperand(2).getNode() == Node) {
    441       unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
    442       if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
    443         VRBase = DestReg;
    444         break;
    445       }
    446     }
    447   }
    448 
    449   if (Opc == TargetOpcode::EXTRACT_SUBREG) {
    450     // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub.  There are no
    451     // constraints on the %dst register, COPY can target all legal register
    452     // classes.
    453     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
    454     const TargetRegisterClass *TRC = TLI->getRegClassFor(Node->getValueType(0));
    455 
    456     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
    457     MachineInstr *DefMI = MRI->getVRegDef(VReg);
    458     unsigned SrcReg, DstReg, DefSubIdx;
    459     if (DefMI &&
    460         TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
    461         SubIdx == DefSubIdx) {
    462       // Optimize these:
    463       // r1025 = s/zext r1024, 4
    464       // r1026 = extract_subreg r1025, 4
    465       // to a copy
    466       // r1026 = copy r1024
    467       VRBase = MRI->createVirtualRegister(TRC);
    468       BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
    469               TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
    470     } else {
    471       // VReg may not support a SubIdx sub-register, and we may need to
    472       // constrain its register class or issue a COPY to a compatible register
    473       // class.
    474       VReg = ConstrainForSubReg(VReg, SubIdx,
    475                                 Node->getOperand(0).getValueType(),
    476                                 Node->getDebugLoc());
    477 
    478       // Create the destreg if it is missing.
    479       if (VRBase == 0)
    480         VRBase = MRI->createVirtualRegister(TRC);
    481 
    482       // Create the extract_subreg machine instruction.
    483       BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
    484               TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
    485     }
    486   } else if (Opc == TargetOpcode::INSERT_SUBREG ||
    487              Opc == TargetOpcode::SUBREG_TO_REG) {
    488     SDValue N0 = Node->getOperand(0);
    489     SDValue N1 = Node->getOperand(1);
    490     SDValue N2 = Node->getOperand(2);
    491     unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
    492 
    493     // Figure out the register class to create for the destreg.  It should be
    494     // the largest legal register class supporting SubIdx sub-registers.
    495     // RegisterCoalescer will constrain it further if it decides to eliminate
    496     // the INSERT_SUBREG instruction.
    497     //
    498     //   %dst = INSERT_SUBREG %src, %sub, SubIdx
    499     //
    500     // is lowered by TwoAddressInstructionPass to:
    501     //
    502     //   %dst = COPY %src
    503     //   %dst:SubIdx = COPY %sub
    504     //
    505     // There is no constraint on the %src register class.
    506     //
    507     const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getValueType(0));
    508     SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
    509     assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
    510 
    511     if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
    512       VRBase = MRI->createVirtualRegister(SRC);
    513 
    514     // Create the insert_subreg or subreg_to_reg machine instruction.
    515     MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc));
    516     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
    517 
    518     // If creating a subreg_to_reg, then the first input operand
    519     // is an implicit value immediate, otherwise it's a register
    520     if (Opc == TargetOpcode::SUBREG_TO_REG) {
    521       const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
    522       MI->addOperand(MachineOperand::CreateImm(SD->getZExtValue()));
    523     } else
    524       AddOperand(MI, N0, 0, 0, VRBaseMap, /*IsDebug=*/false,
    525                  IsClone, IsCloned);
    526     // Add the subregster being inserted
    527     AddOperand(MI, N1, 0, 0, VRBaseMap, /*IsDebug=*/false,
    528                IsClone, IsCloned);
    529     MI->addOperand(MachineOperand::CreateImm(SubIdx));
    530     MBB->insert(InsertPos, MI);
    531   } else
    532     llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
    533 
    534   SDValue Op(Node, 0);
    535   bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
    536   (void)isNew; // Silence compiler warning.
    537   assert(isNew && "Node emitted out of order - early");
    538 }
    539 
    540 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
    541 /// COPY_TO_REGCLASS is just a normal copy, except that the destination
    542 /// register is constrained to be in a particular register class.
    543 ///
    544 void
    545 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
    546                                      DenseMap<SDValue, unsigned> &VRBaseMap) {
    547   unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
    548 
    549   // Create the new VReg in the destination class and emit a copy.
    550   unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
    551   const TargetRegisterClass *DstRC = TRI->getRegClass(DstRCIdx);
    552   unsigned NewVReg = MRI->createVirtualRegister(DstRC);
    553   BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
    554     NewVReg).addReg(VReg);
    555 
    556   SDValue Op(Node, 0);
    557   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
    558   (void)isNew; // Silence compiler warning.
    559   assert(isNew && "Node emitted out of order - early");
    560 }
    561 
    562 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
    563 ///
    564 void InstrEmitter::EmitRegSequence(SDNode *Node,
    565                                   DenseMap<SDValue, unsigned> &VRBaseMap,
    566                                   bool IsClone, bool IsCloned) {
    567   unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
    568   const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
    569   unsigned NewVReg = MRI->createVirtualRegister(RC);
    570   MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
    571                              TII->get(TargetOpcode::REG_SEQUENCE), NewVReg);
    572   unsigned NumOps = Node->getNumOperands();
    573   assert((NumOps & 1) == 1 &&
    574          "REG_SEQUENCE must have an odd number of operands!");
    575   const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
    576   for (unsigned i = 1; i != NumOps; ++i) {
    577     SDValue Op = Node->getOperand(i);
    578     if ((i & 1) == 0) {
    579       RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
    580       // Skip physical registers as they don't have a vreg to get and we'll
    581       // insert copies for them in TwoAddressInstructionPass anyway.
    582       if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
    583         unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
    584         unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
    585         const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
    586         const TargetRegisterClass *SRC =
    587         TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
    588         if (SRC && SRC != RC) {
    589           MRI->setRegClass(NewVReg, SRC);
    590           RC = SRC;
    591         }
    592       }
    593     }
    594     AddOperand(MI, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
    595                IsClone, IsCloned);
    596   }
    597 
    598   MBB->insert(InsertPos, MI);
    599   SDValue Op(Node, 0);
    600   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
    601   (void)isNew; // Silence compiler warning.
    602   assert(isNew && "Node emitted out of order - early");
    603 }
    604 
    605 /// EmitDbgValue - Generate machine instruction for a dbg_value node.
    606 ///
    607 MachineInstr *
    608 InstrEmitter::EmitDbgValue(SDDbgValue *SD,
    609                            DenseMap<SDValue, unsigned> &VRBaseMap) {
    610   uint64_t Offset = SD->getOffset();
    611   MDNode* MDPtr = SD->getMDPtr();
    612   DebugLoc DL = SD->getDebugLoc();
    613 
    614   if (SD->getKind() == SDDbgValue::FRAMEIX) {
    615     // Stack address; this needs to be lowered in target-dependent fashion.
    616     // EmitTargetCodeForFrameDebugValue is responsible for allocation.
    617     unsigned FrameIx = SD->getFrameIx();
    618     return TII->emitFrameIndexDebugValue(*MF, FrameIx, Offset, MDPtr, DL);
    619   }
    620   // Otherwise, we're going to create an instruction here.
    621   const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
    622   MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
    623   if (SD->getKind() == SDDbgValue::SDNODE) {
    624     SDNode *Node = SD->getSDNode();
    625     SDValue Op = SDValue(Node, SD->getResNo());
    626     // It's possible we replaced this SDNode with other(s) and therefore
    627     // didn't generate code for it.  It's better to catch these cases where
    628     // they happen and transfer the debug info, but trying to guarantee that
    629     // in all cases would be very fragile; this is a safeguard for any
    630     // that were missed.
    631     DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
    632     if (I==VRBaseMap.end())
    633       MIB.addReg(0U);       // undef
    634     else
    635       AddOperand(&*MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
    636                  /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
    637   } else if (SD->getKind() == SDDbgValue::CONST) {
    638     const Value *V = SD->getConst();
    639     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    640       if (CI->getBitWidth() > 64)
    641         MIB.addCImm(CI);
    642       else
    643         MIB.addImm(CI->getSExtValue());
    644     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
    645       MIB.addFPImm(CF);
    646     } else {
    647       // Could be an Undef.  In any case insert an Undef so we can see what we
    648       // dropped.
    649       MIB.addReg(0U);
    650     }
    651   } else {
    652     // Insert an Undef so we can see what we dropped.
    653     MIB.addReg(0U);
    654   }
    655 
    656   MIB.addImm(Offset).addMetadata(MDPtr);
    657   return &*MIB;
    658 }
    659 
    660 /// EmitMachineNode - Generate machine code for a target-specific node and
    661 /// needed dependencies.
    662 ///
    663 void InstrEmitter::
    664 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
    665                 DenseMap<SDValue, unsigned> &VRBaseMap) {
    666   unsigned Opc = Node->getMachineOpcode();
    667 
    668   // Handle subreg insert/extract specially
    669   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
    670       Opc == TargetOpcode::INSERT_SUBREG ||
    671       Opc == TargetOpcode::SUBREG_TO_REG) {
    672     EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
    673     return;
    674   }
    675 
    676   // Handle COPY_TO_REGCLASS specially.
    677   if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
    678     EmitCopyToRegClassNode(Node, VRBaseMap);
    679     return;
    680   }
    681 
    682   // Handle REG_SEQUENCE specially.
    683   if (Opc == TargetOpcode::REG_SEQUENCE) {
    684     EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
    685     return;
    686   }
    687 
    688   if (Opc == TargetOpcode::IMPLICIT_DEF)
    689     // We want a unique VR for each IMPLICIT_DEF use.
    690     return;
    691 
    692   const MCInstrDesc &II = TII->get(Opc);
    693   unsigned NumResults = CountResults(Node);
    694   unsigned NodeOperands = CountOperands(Node);
    695   bool HasPhysRegOuts = NumResults > II.getNumDefs() && II.getImplicitDefs()!=0;
    696 #ifndef NDEBUG
    697   unsigned NumMIOperands = NodeOperands + NumResults;
    698   if (II.isVariadic())
    699     assert(NumMIOperands >= II.getNumOperands() &&
    700            "Too few operands for a variadic node!");
    701   else
    702     assert(NumMIOperands >= II.getNumOperands() &&
    703            NumMIOperands <= II.getNumOperands()+II.getNumImplicitDefs() &&
    704            "#operands for dag node doesn't match .td file!");
    705 #endif
    706 
    707   // Create the new machine instruction.
    708   MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), II);
    709 
    710   // Add result register values for things that are defined by this
    711   // instruction.
    712   if (NumResults)
    713     CreateVirtualRegisters(Node, MI, II, IsClone, IsCloned, VRBaseMap);
    714 
    715   // Emit all of the actual operands of this instruction, adding them to the
    716   // instruction as appropriate.
    717   bool HasOptPRefs = II.getNumDefs() > NumResults;
    718   assert((!HasOptPRefs || !HasPhysRegOuts) &&
    719          "Unable to cope with optional defs and phys regs defs!");
    720   unsigned NumSkip = HasOptPRefs ? II.getNumDefs() - NumResults : 0;
    721   for (unsigned i = NumSkip; i != NodeOperands; ++i)
    722     AddOperand(MI, Node->getOperand(i), i-NumSkip+II.getNumDefs(), &II,
    723                VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
    724 
    725   // Transfer all of the memory reference descriptions of this instruction.
    726   MI->setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
    727                  cast<MachineSDNode>(Node)->memoperands_end());
    728 
    729   // Insert the instruction into position in the block. This needs to
    730   // happen before any custom inserter hook is called so that the
    731   // hook knows where in the block to insert the replacement code.
    732   MBB->insert(InsertPos, MI);
    733 
    734   // The MachineInstr may also define physregs instead of virtregs.  These
    735   // physreg values can reach other instructions in different ways:
    736   //
    737   // 1. When there is a use of a Node value beyond the explicitly defined
    738   //    virtual registers, we emit a CopyFromReg for one of the implicitly
    739   //    defined physregs.  This only happens when HasPhysRegOuts is true.
    740   //
    741   // 2. A CopyFromReg reading a physreg may be glued to this instruction.
    742   //
    743   // 3. A glued instruction may implicitly use a physreg.
    744   //
    745   // 4. A glued instruction may use a RegisterSDNode operand.
    746   //
    747   // Collect all the used physreg defs, and make sure that any unused physreg
    748   // defs are marked as dead.
    749   SmallVector<unsigned, 8> UsedRegs;
    750 
    751   // Additional results must be physical register defs.
    752   if (HasPhysRegOuts) {
    753     for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
    754       unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
    755       if (!Node->hasAnyUseOfValue(i))
    756         continue;
    757       // This implicitly defined physreg has a use.
    758       UsedRegs.push_back(Reg);
    759       EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
    760     }
    761   }
    762 
    763   // Scan the glue chain for any used physregs.
    764   if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
    765     for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
    766       if (F->getOpcode() == ISD::CopyFromReg) {
    767         UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
    768         continue;
    769       } else if (F->getOpcode() == ISD::CopyToReg) {
    770         // Skip CopyToReg nodes that are internal to the glue chain.
    771         continue;
    772       }
    773       // Collect declared implicit uses.
    774       const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
    775       UsedRegs.append(MCID.getImplicitUses(),
    776                       MCID.getImplicitUses() + MCID.getNumImplicitUses());
    777       // In addition to declared implicit uses, we must also check for
    778       // direct RegisterSDNode operands.
    779       for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
    780         if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
    781           unsigned Reg = R->getReg();
    782           if (TargetRegisterInfo::isPhysicalRegister(Reg))
    783             UsedRegs.push_back(Reg);
    784         }
    785     }
    786   }
    787 
    788   // Finally mark unused registers as dead.
    789   if (!UsedRegs.empty() || II.getImplicitDefs())
    790     MI->setPhysRegsDeadExcept(UsedRegs, *TRI);
    791 
    792   // Run post-isel target hook to adjust this instruction if needed.
    793 #ifdef NDEBUG
    794   if (II.hasPostISelHook())
    795 #endif
    796     TLI->AdjustInstrPostInstrSelection(MI, Node);
    797 }
    798 
    799 /// EmitSpecialNode - Generate machine code for a target-independent node and
    800 /// needed dependencies.
    801 void InstrEmitter::
    802 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
    803                 DenseMap<SDValue, unsigned> &VRBaseMap) {
    804   switch (Node->getOpcode()) {
    805   default:
    806 #ifndef NDEBUG
    807     Node->dump();
    808 #endif
    809     llvm_unreachable("This target-independent node should have been selected!");
    810   case ISD::EntryToken:
    811     llvm_unreachable("EntryToken should have been excluded from the schedule!");
    812   case ISD::MERGE_VALUES:
    813   case ISD::TokenFactor: // fall thru
    814     break;
    815   case ISD::CopyToReg: {
    816     unsigned SrcReg;
    817     SDValue SrcVal = Node->getOperand(2);
    818     if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
    819       SrcReg = R->getReg();
    820     else
    821       SrcReg = getVR(SrcVal, VRBaseMap);
    822 
    823     unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
    824     if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
    825       break;
    826 
    827     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
    828             DestReg).addReg(SrcReg);
    829     break;
    830   }
    831   case ISD::CopyFromReg: {
    832     unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
    833     EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
    834     break;
    835   }
    836   case ISD::EH_LABEL: {
    837     MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
    838     BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
    839             TII->get(TargetOpcode::EH_LABEL)).addSym(S);
    840     break;
    841   }
    842 
    843   case ISD::INLINEASM: {
    844     unsigned NumOps = Node->getNumOperands();
    845     if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
    846       --NumOps;  // Ignore the glue operand.
    847 
    848     // Create the inline asm machine instruction.
    849     MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
    850                                TII->get(TargetOpcode::INLINEASM));
    851 
    852     // Add the asm string as an external symbol operand.
    853     SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
    854     const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
    855     MI->addOperand(MachineOperand::CreateES(AsmStr));
    856 
    857     // Add the HasSideEffect and isAlignStack bits.
    858     int64_t ExtraInfo =
    859       cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
    860                           getZExtValue();
    861     MI->addOperand(MachineOperand::CreateImm(ExtraInfo));
    862 
    863     // Add all of the operand registers to the instruction.
    864     for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
    865       unsigned Flags =
    866         cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
    867       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
    868 
    869       MI->addOperand(MachineOperand::CreateImm(Flags));
    870       ++i;  // Skip the ID value.
    871 
    872       switch (InlineAsm::getKind(Flags)) {
    873       default: llvm_unreachable("Bad flags!");
    874         case InlineAsm::Kind_RegDef:
    875         for (; NumVals; --NumVals, ++i) {
    876           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
    877           // FIXME: Add dead flags for physical and virtual registers defined.
    878           // For now, mark physical register defs as implicit to help fast
    879           // regalloc. This makes inline asm look a lot like calls.
    880           MI->addOperand(MachineOperand::CreateReg(Reg, true,
    881                        /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg)));
    882         }
    883         break;
    884       case InlineAsm::Kind_RegDefEarlyClobber:
    885       case InlineAsm::Kind_Clobber:
    886         for (; NumVals; --NumVals, ++i) {
    887           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
    888           MI->addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/ true,
    889                          /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg),
    890                                                    /*isKill=*/ false,
    891                                                    /*isDead=*/ false,
    892                                                    /*isUndef=*/false,
    893                                                    /*isEarlyClobber=*/ true));
    894         }
    895         break;
    896       case InlineAsm::Kind_RegUse:  // Use of register.
    897       case InlineAsm::Kind_Imm:  // Immediate.
    898       case InlineAsm::Kind_Mem:  // Addressing mode.
    899         // The addressing mode has been selected, just add all of the
    900         // operands to the machine instruction.
    901         for (; NumVals; --NumVals, ++i)
    902           AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap,
    903                      /*IsDebug=*/false, IsClone, IsCloned);
    904         break;
    905       }
    906     }
    907 
    908     // Get the mdnode from the asm if it exists and add it to the instruction.
    909     SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
    910     const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
    911     if (MD)
    912       MI->addOperand(MachineOperand::CreateMetadata(MD));
    913 
    914     MBB->insert(InsertPos, MI);
    915     break;
    916   }
    917   }
    918 }
    919 
    920 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
    921 /// at the given position in the given block.
    922 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
    923                            MachineBasicBlock::iterator insertpos)
    924   : MF(mbb->getParent()),
    925     MRI(&MF->getRegInfo()),
    926     TM(&MF->getTarget()),
    927     TII(TM->getInstrInfo()),
    928     TRI(TM->getRegisterInfo()),
    929     TLI(TM->getTargetLowering()),
    930     MBB(mbb), InsertPos(insertpos) {
    931 }
    932