InstrEmitter.cpp revision 263763
1267677Spfg//==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
228019Sjoerg//
328019Sjoerg//                     The LLVM Compiler Infrastructure
4227753Stheraven//
5227753Stheraven// This file is distributed under the University of Illinois Open Source
6227753Stheraven// License. See LICENSE.TXT for details.
7227753Stheraven//
8227753Stheraven//===----------------------------------------------------------------------===//
928021Sjoerg//
1028019Sjoerg// This implements the Emit routines for the SelectionDAG class, which creates
1128019Sjoerg// MachineInstrs based on the decisions of the SelectionDAG instruction
1228019Sjoerg// selection.
1328019Sjoerg//
1428019Sjoerg//===----------------------------------------------------------------------===//
1528019Sjoerg
1628019Sjoerg#define DEBUG_TYPE "instr-emitter"
1728019Sjoerg#include "InstrEmitter.h"
1828019Sjoerg#include "SDNodeDbgValue.h"
1928019Sjoerg#include "llvm/ADT/Statistic.h"
2028019Sjoerg#include "llvm/CodeGen/MachineConstantPool.h"
2128019Sjoerg#include "llvm/CodeGen/MachineFunction.h"
2228019Sjoerg#include "llvm/CodeGen/MachineInstrBuilder.h"
2328019Sjoerg#include "llvm/CodeGen/MachineRegisterInfo.h"
2428019Sjoerg#include "llvm/CodeGen/StackMaps.h"
2528019Sjoerg#include "llvm/IR/DataLayout.h"
2628019Sjoerg#include "llvm/Support/Debug.h"
2728019Sjoerg#include "llvm/Support/ErrorHandling.h"
2828019Sjoerg#include "llvm/Support/MathExtras.h"
2928019Sjoerg#include "llvm/Target/TargetInstrInfo.h"
30267677Spfg#include "llvm/Target/TargetLowering.h"
31267677Spfg#include "llvm/Target/TargetMachine.h"
32267677Spfgusing namespace llvm;
33267677Spfg
3428019Sjoerg/// MinRCSize - Smallest register class we allow when constraining virtual
3528019Sjoerg/// registers.  If satisfying all register class constraints would require
36111010Snectar/// using a smaller register class, emit a COPY to a new virtual register
3728019Sjoerg/// instead.
3828021Sjoergconst unsigned MinRCSize = 4;
39111010Snectar
4028019Sjoerg/// CountResults - The results of target nodes have register or immediate
41111010Snectar/// operands first, then an optional chain, and optional glue operands (which do
4228021Sjoerg/// not go into the resulting MachineInstr).
4328019Sjoergunsigned InstrEmitter::CountResults(SDNode *Node) {
4492986Sobrien  unsigned N = Node->getNumValues();
4528019Sjoerg  while (N && Node->getValueType(N - 1) == MVT::Glue)
4671579Sdeischen    --N;
4728019Sjoerg  if (N && Node->getValueType(N - 1) == MVT::Other)
4828019Sjoerg    --N;    // Skip over chain result.
49122830Snectar  return N;
5079664Sdd}
5128019Sjoerg
5248614Sobrien/// countOperands - The inputs to target nodes have any actual inputs first,
5371579Sdeischen/// followed by an optional chain operand, then an optional glue operand.
5471579Sdeischen/// Compute the number of actual operands that will go into the resulting
5528021Sjoerg/// MachineInstr.
5628019Sjoerg///
57227753Stheraven/// Also count physreg RegisterSDNode and RegisterMaskSDNode operands preceding
5848614Sobrien/// the chain and glue. These operands may be implicit on the machine instr.
5928021Sjoergstatic unsigned countOperands(SDNode *Node, unsigned NumExpUses,
6028019Sjoerg                              unsigned &NumImpUses) {
6148614Sobrien  unsigned N = Node->getNumOperands();
62227753Stheraven  while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
63227753Stheraven    --N;
6428019Sjoerg  if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
6528021Sjoerg    --N; // Ignore chain if it exists.
6628021Sjoerg
6728021Sjoerg  // Count RegisterSDNode and RegisterMaskSDNode operands for NumImpUses.
6828021Sjoerg  NumImpUses = N - NumExpUses;
6953941Sache  for (unsigned I = N; I > NumExpUses; --I) {
70227753Stheraven    if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1)))
7128019Sjoerg      continue;
7228021Sjoerg    if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1)))
7328021Sjoerg      if (TargetRegisterInfo::isPhysicalRegister(RN->getReg()))
7428021Sjoerg        continue;
7528021Sjoerg    NumImpUses = N - I;
7628019Sjoerg    break;
7728021Sjoerg  }
7828019Sjoerg
7928021Sjoerg  return N;
80227753Stheraven}
81227753Stheraven
82227753Stheraven/// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
8328021Sjoerg/// implicit physical register output.
8428021Sjoergvoid InstrEmitter::
8528021SjoergEmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
8628021Sjoerg                unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
8728021Sjoerg  unsigned VRBase = 0;
8828019Sjoerg  if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
8953941Sache    // Just use the input register directly!
9053941Sache    SDValue Op(Node, ResNo);
9153941Sache    if (IsClone)
9228021Sjoerg      VRBaseMap.erase(Op);
9328021Sjoerg    bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
9428021Sjoerg    (void)isNew; // Silence compiler warning.
9528021Sjoerg    assert(isNew && "Node emitted out of order - early");
9628021Sjoerg    return;
9728021Sjoerg  }
9828021Sjoerg
9928019Sjoerg  // If the node is only used by a CopyToReg and the dest reg is a vreg, use
10053941Sache  // the CopyToReg'd destination register instead of creating a new vreg.
101227753Stheraven  bool MatchReg = true;
10228021Sjoerg  const TargetRegisterClass *UseRC = NULL;
10328021Sjoerg  MVT VT = Node->getSimpleValueType(ResNo);
10428021Sjoerg
10528019Sjoerg  // Stick to the preferred register classes for legal types.
10653941Sache  if (TLI->isTypeLegal(VT))
107227753Stheraven    UseRC = TLI->getRegClassFor(VT);
10853941Sache
10953941Sache  if (!IsClone && !IsCloned)
11054316Ssheldonh    for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
11154316Ssheldonh         UI != E; ++UI) {
112227753Stheraven      SDNode *User = *UI;
113227753Stheraven      bool Match = true;
11453941Sache      if (User->getOpcode() == ISD::CopyToReg &&
11553941Sache          User->getOperand(2).getNode() == Node &&
11654316Ssheldonh          User->getOperand(2).getResNo() == ResNo) {
11753941Sache        unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
11853941Sache        if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
11953941Sache          VRBase = DestReg;
12053941Sache          Match = false;
12153941Sache        } else if (DestReg != SrcReg)
12253941Sache          Match = false;
12353941Sache      } else {
12428021Sjoerg        for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
125227753Stheraven          SDValue Op = User->getOperand(i);
12628021Sjoerg          if (Op.getNode() != Node || Op.getResNo() != ResNo)
12728021Sjoerg            continue;
12828021Sjoerg          MVT VT = Node->getSimpleValueType(Op.getResNo());
12928019Sjoerg          if (VT == MVT::Other || VT == MVT::Glue)
13028021Sjoerg            continue;
131227753Stheraven          Match = false;
13228021Sjoerg          if (User->isMachineOpcode()) {
13328021Sjoerg            const MCInstrDesc &II = TII->get(User->getMachineOpcode());
13428021Sjoerg            const TargetRegisterClass *RC = 0;
13528019Sjoerg            if (i+II.getNumDefs() < II.getNumOperands()) {
13653941Sache              RC = TRI->getAllocatableClass(
13753960Sache                TII->getRegClass(II, i+II.getNumDefs(), TRI, *MF));
13853960Sache            }
13953941Sache            if (!UseRC)
14053941Sache              UseRC = RC;
14153941Sache            else if (RC) {
14253941Sache              const TargetRegisterClass *ComRC =
14353960Sache                TRI->getCommonSubClass(UseRC, RC);
14453960Sache              // If multiple uses expect disjoint register classes, we emit
14553941Sache              // copies in AddRegisterOperand.
14653941Sache              if (ComRC)
14753941Sache                UseRC = ComRC;
14853960Sache            }
149227753Stheraven          }
15074412Sache        }
15174412Sache      }
15274412Sache      MatchReg &= Match;
15374412Sache      if (VRBase)
15428021Sjoerg        break;
155227753Stheraven    }
15628021Sjoerg
15728021Sjoerg  const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
15828021Sjoerg  SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
15928019Sjoerg
16028021Sjoerg  // Figure out the register class to create for the destreg.
161227753Stheraven  if (VRBase) {
16228021Sjoerg    DstRC = MRI->getRegClass(VRBase);
16328021Sjoerg  } else if (UseRC) {
16428021Sjoerg    assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
16528019Sjoerg    DstRC = UseRC;
16628021Sjoerg  } else {
167227753Stheraven    DstRC = TLI->getRegClassFor(VT);
16828021Sjoerg  }
16928021Sjoerg
17028021Sjoerg  // If all uses are reading from the src physical register and copying the
17128019Sjoerg  // register is either impossible or very expensive, then don't create a copy.
17228021Sjoerg  if (MatchReg && SrcRC->getCopyCost() < 0) {
173227753Stheraven    VRBase = SrcReg;
17428021Sjoerg  } else {
17528021Sjoerg    // Create the reg, emit the copy.
17628021Sjoerg    VRBase = MRI->createVirtualRegister(DstRC);
17728019Sjoerg    BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
17828021Sjoerg            VRBase).addReg(SrcReg);
179227753Stheraven  }
18028021Sjoerg
18128021Sjoerg  SDValue Op(Node, ResNo);
18228021Sjoerg  if (IsClone)
18328019Sjoerg    VRBaseMap.erase(Op);
18428021Sjoerg  bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
185227753Stheraven  (void)isNew; // Silence compiler warning.
18628021Sjoerg  assert(isNew && "Node emitted out of order - early");
18728019Sjoerg}
18854316Ssheldonh
189227753Stheraven/// getDstOfCopyToRegUse - If the only use of the specified result number of
190227753Stheraven/// node is a CopyToReg, return its destination register. Return 0 otherwise.
19128021Sjoergunsigned InstrEmitter::getDstOfOnlyCopyToRegUse(SDNode *Node,
19228021Sjoerg                                                unsigned ResNo) const {
19354316Ssheldonh  if (!Node->hasOneUse())
19428021Sjoerg    return 0;
19553083Ssheldonh
19628021Sjoerg  SDNode *User = *Node->use_begin();
19728019Sjoerg  if (User->getOpcode() == ISD::CopyToReg &&
19853083Ssheldonh      User->getOperand(2).getNode() == Node &&
19928021Sjoerg      User->getOperand(2).getResNo() == ResNo) {
20028019Sjoerg    unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
20128021Sjoerg    if (TargetRegisterInfo::isVirtualRegister(Reg))
20228021Sjoerg      return Reg;
203227753Stheraven  }
204227753Stheraven  return 0;
20528021Sjoerg}
20628019Sjoerg
207227753Stheravenvoid InstrEmitter::CreateVirtualRegisters(SDNode *Node,
20828021Sjoerg                                       MachineInstrBuilder &MIB,
20928019Sjoerg                                       const MCInstrDesc &II,
21054316Ssheldonh                                       bool IsClone, bool IsCloned,
211227753Stheraven                                       DenseMap<SDValue, unsigned> &VRBaseMap) {
212227753Stheraven  assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
21328021Sjoerg         "IMPLICIT_DEF should have been handled as a special case elsewhere!");
21428021Sjoerg
21554316Ssheldonh  unsigned NumResults = CountResults(Node);
21628021Sjoerg  for (unsigned i = 0; i < II.getNumDefs(); ++i) {
21728019Sjoerg    // If the specific node value is only used by a CopyToReg and the dest reg
21853083Ssheldonh    // is a vreg in the same register class, use the CopyToReg'd destination
21953083Ssheldonh    // register instead of creating a new vreg.
22053083Ssheldonh    unsigned VRBase = 0;
22128021Sjoerg    const TargetRegisterClass *RC =
22253083Ssheldonh      TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF));
22353083Ssheldonh    // Always let the value type influence the used register class. The
22453083Ssheldonh    // constraints on the instruction may be too lax to represent the value
22528021Sjoerg    // type correctly. For example, a 64-bit float (X86::FR64) can't live in
22653083Ssheldonh    // the 32-bit float super-class (X86::FR32).
22728019Sjoerg    if (i < NumResults && TLI->isTypeLegal(Node->getSimpleValueType(i))) {
228227753Stheraven      const TargetRegisterClass *VTRC =
229227753Stheraven        TLI->getRegClassFor(Node->getSimpleValueType(i));
230227753Stheraven      if (RC)
231227753Stheraven        VTRC = TRI->getCommonSubClass(RC, VTRC);
23228021Sjoerg      if (VTRC)
23328021Sjoerg        RC = VTRC;
23428019Sjoerg    }
23528021Sjoerg
23628021Sjoerg    if (II.OpInfo[i].isOptionalDef()) {
23728021Sjoerg      // Optional def must be a physical register.
23828021Sjoerg      unsigned NumResults = CountResults(Node);
23954316Ssheldonh      VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
24054316Ssheldonh      assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
24154316Ssheldonh      MIB.addReg(VRBase, RegState::Define);
24254316Ssheldonh    }
24354316Ssheldonh
24454316Ssheldonh    if (!VRBase && !IsClone && !IsCloned)
24554316Ssheldonh      for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
24654316Ssheldonh           UI != E; ++UI) {
247227753Stheraven        SDNode *User = *UI;
24828021Sjoerg        if (User->getOpcode() == ISD::CopyToReg &&
24928019Sjoerg            User->getOperand(2).getNode() == Node &&
25054316Ssheldonh            User->getOperand(2).getResNo() == i) {
251227753Stheraven          unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
252227753Stheraven          if (TargetRegisterInfo::isVirtualRegister(Reg)) {
25328021Sjoerg            const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
25428021Sjoerg            if (RegRC == RC) {
25554316Ssheldonh              VRBase = Reg;
25628021Sjoerg              MIB.addReg(VRBase, RegState::Define);
25728021Sjoerg              break;
25828021Sjoerg            }
25928021Sjoerg          }
26054301Ssheldonh        }
26128021Sjoerg      }
26228019Sjoerg
26328021Sjoerg    // Create the result registers for this node and add the result regs to
26428019Sjoerg    // the machine instruction.
265227753Stheraven    if (VRBase == 0) {
266227753Stheraven      assert(RC && "Isn't a register operand!");
267227753Stheraven      VRBase = MRI->createVirtualRegister(RC);
268227753Stheraven      MIB.addReg(VRBase, RegState::Define);
26928021Sjoerg    }
27028021Sjoerg
27128019Sjoerg    SDValue Op(Node, i);
27228021Sjoerg    if (IsClone)
27354316Ssheldonh      VRBaseMap.erase(Op);
27454316Ssheldonh    bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
27554316Ssheldonh    (void)isNew; // Silence compiler warning.
27654316Ssheldonh    assert(isNew && "Node emitted out of order - early");
27772168Sphantom  }
278227753Stheraven}
27928021Sjoerg
28028021Sjoerg/// getVR - Return the virtual register corresponding to the specified result
28128021Sjoerg/// of the specified node.
28228021Sjoergunsigned InstrEmitter::getVR(SDValue Op,
28328021Sjoerg                             DenseMap<SDValue, unsigned> &VRBaseMap) {
28428021Sjoerg  if (Op.isMachineOpcode() &&
28528021Sjoerg      Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
28628019Sjoerg    // Add an IMPLICIT_DEF instruction before every use.
28772168Sphantom    unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
288227753Stheraven    // IMPLICIT_DEF can produce any type of result so its MCInstrDesc
28928021Sjoerg    // does not include operand register class info.
29028021Sjoerg    if (!VReg) {
29128021Sjoerg      const TargetRegisterClass *RC =
29228021Sjoerg        TLI->getRegClassFor(Op.getSimpleValueType());
29328021Sjoerg      VReg = MRI->createVirtualRegister(RC);
29428021Sjoerg    }
29528021Sjoerg    BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
29628019Sjoerg            TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
29728021Sjoerg    return VReg;
29828019Sjoerg  }
29928021Sjoerg
30028021Sjoerg  DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
30172168Sphantom  assert(I != VRBaseMap.end() && "Node emitted out of order - late");
30274409Sache  return I->second;
303227753Stheraven}
304227753Stheraven
30574409Sache
30674409Sache/// AddRegisterOperand - Add the specified register as an operand to the
307227753Stheraven/// specified machine instr. Insert register copies if the register is
308227753Stheraven/// not in the required register class.
30974409Sachevoid
31028021SjoergInstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB,
31172168Sphantom                                 SDValue Op,
31228021Sjoerg                                 unsigned IIOpNum,
31328019Sjoerg                                 const MCInstrDesc *II,
31428021Sjoerg                                 DenseMap<SDValue, unsigned> &VRBaseMap,
31528021Sjoerg                                 bool IsDebug, bool IsClone, bool IsCloned) {
31628021Sjoerg  assert(Op.getValueType() != MVT::Other &&
31728019Sjoerg         Op.getValueType() != MVT::Glue &&
31853083Ssheldonh         "Chain and glue operands should occur at end of operand list!");
31953083Ssheldonh  // Get/emit the operand.
32053083Ssheldonh  unsigned VReg = getVR(Op, VRBaseMap);
32153083Ssheldonh  assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
32253083Ssheldonh
32353083Ssheldonh  const MCInstrDesc &MCID = MIB->getDesc();
32453083Ssheldonh  bool isOptDef = IIOpNum < MCID.getNumOperands() &&
32553083Ssheldonh    MCID.OpInfo[IIOpNum].isOptionalDef();
326227753Stheraven
32753083Ssheldonh  // If the instruction requires a register in a different class, create
32853083Ssheldonh  // a new virtual register and copy the value into it, but first attempt to
32954316Ssheldonh  // shrink VReg's register class within reason.  For example, if VReg == GR32
330227753Stheraven  // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
331227753Stheraven  if (II) {
33253083Ssheldonh    const TargetRegisterClass *DstRC = 0;
33353083Ssheldonh    if (IIOpNum < II->getNumOperands())
33454316Ssheldonh      DstRC = TRI->getAllocatableClass(TII->getRegClass(*II,IIOpNum,TRI,*MF));
33553083Ssheldonh    if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
33653083Ssheldonh      unsigned NewVReg = MRI->createVirtualRegister(DstRC);
33753083Ssheldonh      BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
33853083Ssheldonh              TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
339227753Stheraven      VReg = NewVReg;
340227753Stheraven    }
341227753Stheraven  }
342227753Stheraven
34353083Ssheldonh  // If this value has only one use, that use is a kill. This is a
34453083Ssheldonh  // conservative approximation. InstrEmitter does trivial coalescing
34553083Ssheldonh  // with CopyFromReg nodes, so don't emit kill flags for them.
34653083Ssheldonh  // Avoid kill flags on Schedule cloned nodes, since there will be
347227753Stheraven  // multiple uses.
34853083Ssheldonh  // Tied operands are never killed, so we need to check that. And that
34953083Ssheldonh  // means we need to determine the index of the operand.
35054316Ssheldonh  bool isKill = Op.hasOneUse() &&
35153083Ssheldonh                Op.getNode()->getOpcode() != ISD::CopyFromReg &&
35253083Ssheldonh                !IsDebug &&
35353083Ssheldonh                !(IsClone || IsCloned);
35453083Ssheldonh  if (isKill) {
35553083Ssheldonh    unsigned Idx = MIB->getNumOperands();
356227753Stheraven    while (Idx > 0 &&
357227753Stheraven           MIB->getOperand(Idx-1).isReg() &&
358227753Stheraven           MIB->getOperand(Idx-1).isImplicit())
359227753Stheraven      --Idx;
36053083Ssheldonh    bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
36153083Ssheldonh    if (isTied)
36253083Ssheldonh      isKill = false;
36328021Sjoerg  }
36428021Sjoerg
36554316Ssheldonh  MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) |
36654316Ssheldonh             getDebugRegState(IsDebug));
36754316Ssheldonh}
36854316Ssheldonh
36954316Ssheldonh/// AddOperand - Add the specified operand to the specified machine instr.  II
37054316Ssheldonh/// specifies the instruction information for the node, and IIOpNum is the
37154316Ssheldonh/// operand number (in the II) that we are adding.
37254316Ssheldonhvoid InstrEmitter::AddOperand(MachineInstrBuilder &MIB,
373227753Stheraven                              SDValue Op,
37428021Sjoerg                              unsigned IIOpNum,
37528019Sjoerg                              const MCInstrDesc *II,
37654316Ssheldonh                              DenseMap<SDValue, unsigned> &VRBaseMap,
377227753Stheraven                              bool IsDebug, bool IsClone, bool IsCloned) {
378227753Stheraven  if (Op.isMachineOpcode()) {
37928021Sjoerg    AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
38028021Sjoerg                       IsDebug, IsClone, IsCloned);
38154316Ssheldonh  } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
38228021Sjoerg    MIB.addImm(C->getSExtValue());
38328021Sjoerg  } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
38428021Sjoerg    MIB.addFPImm(F->getConstantFPValue());
38528019Sjoerg  } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
38628021Sjoerg    // Turn additional physreg operands into implicit uses on non-variadic
38728019Sjoerg    // instructions. This is used by call and return instructions passing
388227753Stheraven    // arguments in registers.
389227753Stheraven    bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic());
390227753Stheraven    MIB.addReg(R->getReg(), getImplRegState(Imp));
391227753Stheraven  } else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
39228021Sjoerg    MIB.addRegMask(RM->getRegMask());
39328021Sjoerg  } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
39428019Sjoerg    MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(),
39528021Sjoerg                         TGA->getTargetFlags());
39628021Sjoerg  } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
39728021Sjoerg    MIB.addMBB(BBNode->getBasicBlock());
39872168Sphantom  } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
39953941Sache    MIB.addFrameIndex(FI->getIndex());
40053941Sache  } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
40172168Sphantom    MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags());
402227753Stheraven  } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
40372168Sphantom    int Offset = CP->getOffset();
404227753Stheraven    unsigned Align = CP->getAlignment();
40553941Sache    Type *Type = CP->getType();
40653941Sache    // MachineConstantPool wants an explicit alignment.
40753941Sache    if (Align == 0) {
40874409Sache      Align = TM->getDataLayout()->getPrefTypeAlignment(Type);
409227753Stheraven      if (Align == 0) {
410227753Stheraven        // Alignment of vector types.  FIXME!
41174409Sache        Align = TM->getDataLayout()->getTypeAllocSize(Type);
412207830Sedwin      }
413207830Sedwin    }
414207830Sedwin
415207830Sedwin    unsigned Idx;
416207830Sedwin    MachineConstantPool *MCP = MF->getConstantPool();
417207830Sedwin    if (CP->isMachineConstantPoolEntry())
418207830Sedwin      Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
419207830Sedwin    else
42074409Sache      Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
421227753Stheraven    MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags());
422227753Stheraven  } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
42374409Sache    MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags());
42453941Sache  } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
42528021Sjoerg    MIB.addBlockAddress(BA->getBlockAddress(),
42672168Sphantom                        BA->getOffset(),
42728021Sjoerg                        BA->getTargetFlags());
42828019Sjoerg  } else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
42928021Sjoerg    MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags());
43028021Sjoerg  } else {
43128021Sjoerg    assert(Op.getValueType() != MVT::Other &&
43228019Sjoerg           Op.getValueType() != MVT::Glue &&
43328021Sjoerg           "Chain and glue operands should occur at end of operand list!");
434227753Stheraven    AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
43528021Sjoerg                       IsDebug, IsClone, IsCloned);
43628019Sjoerg  }
43754316Ssheldonh}
438227753Stheraven
439227753Stheravenunsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
44028021Sjoerg                                          MVT VT, DebugLoc DL) {
44128021Sjoerg  const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
44254316Ssheldonh  const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
44328021Sjoerg
44428021Sjoerg  // RC is a sub-class of VRC that supports SubIdx.  Try to constrain VReg
44528021Sjoerg  // within reason.
44628019Sjoerg  if (RC && RC != VRC)
44728021Sjoerg    RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
44828019Sjoerg
449227753Stheraven  // VReg has been adjusted.  It can be used with SubIdx operands now.
450227753Stheraven  if (RC)
451227753Stheraven    return VReg;
452227753Stheraven
45328021Sjoerg  // VReg couldn't be reasonably constrained.  Emit a COPY to a new virtual
45428021Sjoerg  // register instead.
45528019Sjoerg  RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
45679664Sdd  assert(RC && "No legal register class for VT supports that SubIdx");
45779664Sdd  unsigned NewReg = MRI->createVirtualRegister(RC);
45879664Sdd  BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
459122830Snectar    .addReg(VReg);
460122830Snectar  return NewReg;
46179664Sdd}
46279664Sdd
463122830Snectar/// EmitSubregNode - Generate machine code for subreg nodes.
464122830Snectar///
465227753Stheravenvoid InstrEmitter::EmitSubregNode(SDNode *Node,
466122830Snectar                                  DenseMap<SDValue, unsigned> &VRBaseMap,
467122830Snectar                                  bool IsClone, bool IsCloned) {
46879664Sdd  unsigned VRBase = 0;
469122830Snectar  unsigned Opc = Node->getMachineOpcode();
470122830Snectar
47179664Sdd  // If the node is only used by a CopyToReg and the dest reg is a vreg, use
47279664Sdd  // the CopyToReg'd destination register instead of creating a new vreg.
473112156Smtm  for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
47479664Sdd       UI != E; ++UI) {
47579664Sdd    SDNode *User = *UI;
47679664Sdd    if (User->getOpcode() == ISD::CopyToReg &&
47728021Sjoerg        User->getOperand(2).getNode() == Node) {
47828021Sjoerg      unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
479227753Stheraven      if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
480227753Stheraven        VRBase = DestReg;
48128021Sjoerg        break;
48228019Sjoerg      }
483227753Stheraven    }
48428021Sjoerg  }
48528019Sjoerg
48654316Ssheldonh  if (Opc == TargetOpcode::EXTRACT_SUBREG) {
487227753Stheraven    // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub.  There are no
488227753Stheraven    // constraints on the %dst register, COPY can target all legal register
48928021Sjoerg    // classes.
49028021Sjoerg    unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
49154316Ssheldonh    const TargetRegisterClass *TRC =
49228021Sjoerg      TLI->getRegClassFor(Node->getSimpleValueType(0));
49328021Sjoerg
49428021Sjoerg    unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
49546051Swes    MachineInstr *DefMI = MRI->getVRegDef(VReg);
49646042Swes    unsigned SrcReg, DstReg, DefSubIdx;
49728021Sjoerg    if (DefMI &&
49828021Sjoerg        TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
49928019Sjoerg        SubIdx == DefSubIdx &&
50028021Sjoerg        TRC == MRI->getRegClass(SrcReg)) {
50128019Sjoerg      // Optimize these:
502227753Stheraven      // r1025 = s/zext r1024, 4
503227753Stheraven      // r1026 = extract_subreg r1025, 4
504227753Stheraven      // to a copy
505227753Stheraven      // r1026 = copy r1024
50628021Sjoerg      VRBase = MRI->createVirtualRegister(TRC);
50728021Sjoerg      BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
50848550Sobrien              TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
50948550Sobrien      MRI->clearKillFlags(SrcReg);
51048550Sobrien    } else {
51148550Sobrien      // VReg may not support a SubIdx sub-register, and we may need to
51248550Sobrien      // constrain its register class or issue a COPY to a compatible register
51348550Sobrien      // class.
514227753Stheraven      VReg = ConstrainForSubReg(VReg, SubIdx,
515227753Stheraven                                Node->getOperand(0).getSimpleValueType(),
516227753Stheraven                                Node->getDebugLoc());
51748550Sobrien
51848550Sobrien      // Create the destreg if it is missing.
51948550Sobrien      if (VRBase == 0)
52048550Sobrien        VRBase = MRI->createVirtualRegister(TRC);
52148550Sobrien
52248550Sobrien      // Create the extract_subreg machine instruction.
523112156Smtm      BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
52448550Sobrien              TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
52548614Sobrien    }
52648550Sobrien  } else if (Opc == TargetOpcode::INSERT_SUBREG ||
52748614Sobrien             Opc == TargetOpcode::SUBREG_TO_REG) {
52848550Sobrien    SDValue N0 = Node->getOperand(0);
52948614Sobrien    SDValue N1 = Node->getOperand(1);
53048550Sobrien    SDValue N2 = Node->getOperand(2);
53148550Sobrien    unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
53248550Sobrien
53348550Sobrien    // Figure out the register class to create for the destreg.  It should be
53448550Sobrien    // the largest legal register class supporting SubIdx sub-registers.
535195015Sdelphij    // RegisterCoalescer will constrain it further if it decides to eliminate
536195015Sdelphij    // the INSERT_SUBREG instruction.
537195015Sdelphij    //
538195015Sdelphij    //   %dst = INSERT_SUBREG %src, %sub, SubIdx
539195015Sdelphij    //
540195015Sdelphij    // is lowered by TwoAddressInstructionPass to:
541195015Sdelphij    //
542195015Sdelphij    //   %dst = COPY %src
543195015Sdelphij    //   %dst:SubIdx = COPY %sub
544195015Sdelphij    //
545195015Sdelphij    // There is no constraint on the %src register class.
546195015Sdelphij    //
547195015Sdelphij    const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getSimpleValueType(0));
548195015Sdelphij    SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
549195015Sdelphij    assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
550227753Stheraven
551195015Sdelphij    if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
552195015Sdelphij      VRBase = MRI->createVirtualRegister(SRC);
553195015Sdelphij
554195015Sdelphij    // Create the insert_subreg or subreg_to_reg machine instruction.
555195015Sdelphij    MachineInstrBuilder MIB =
556195015Sdelphij      BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
557195015Sdelphij
558195015Sdelphij    // If creating a subreg_to_reg, then the first input operand
559195015Sdelphij    // is an implicit value immediate, otherwise it's a register
560195015Sdelphij    if (Opc == TargetOpcode::SUBREG_TO_REG) {
561195015Sdelphij      const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
562195015Sdelphij      MIB.addImm(SD->getZExtValue());
56328021Sjoerg    } else
56428021Sjoerg      AddOperand(MIB, N0, 0, 0, VRBaseMap, /*IsDebug=*/false,
56548614Sobrien                 IsClone, IsCloned);
56648614Sobrien    // Add the subregster being inserted
56728019Sjoerg    AddOperand(MIB, N1, 0, 0, VRBaseMap, /*IsDebug=*/false,
56848614Sobrien               IsClone, IsCloned);
56948614Sobrien    MIB.addImm(SubIdx);
570227753Stheraven    MBB->insert(InsertPos, MIB);
571227753Stheraven  } else
57248614Sobrien    llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
57348614Sobrien
574112156Smtm  SDValue Op(Node, 0);
575227753Stheraven  bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
57648614Sobrien  (void)isNew; // Silence compiler warning.
577112156Smtm  assert(isNew && "Node emitted out of order - early");
578227753Stheraven}
579114285Smtm
580114285Smtm/// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
58171579Sdeischen/// COPY_TO_REGCLASS is just a normal copy, except that the destination
58248550Sobrien/// register is constrained to be in a particular register class.
58348614Sobrien///
584112156Smtmvoid
58528019SjoergInstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
586227753Stheraven                                     DenseMap<SDValue, unsigned> &VRBaseMap) {
587227753Stheraven  unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
588227753Stheraven
589227753Stheraven  // Create the new VReg in the destination class and emit a copy.
590227753Stheraven  unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
591227753Stheraven  const TargetRegisterClass *DstRC =
592    TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx));
593  unsigned NewVReg = MRI->createVirtualRegister(DstRC);
594  BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
595    NewVReg).addReg(VReg);
596
597  SDValue Op(Node, 0);
598  bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
599  (void)isNew; // Silence compiler warning.
600  assert(isNew && "Node emitted out of order - early");
601}
602
603/// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
604///
605void InstrEmitter::EmitRegSequence(SDNode *Node,
606                                  DenseMap<SDValue, unsigned> &VRBaseMap,
607                                  bool IsClone, bool IsCloned) {
608  unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
609  const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
610  unsigned NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC));
611  const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
612  MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg);
613  unsigned NumOps = Node->getNumOperands();
614  assert((NumOps & 1) == 1 &&
615         "REG_SEQUENCE must have an odd number of operands!");
616  for (unsigned i = 1; i != NumOps; ++i) {
617    SDValue Op = Node->getOperand(i);
618    if ((i & 1) == 0) {
619      RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
620      // Skip physical registers as they don't have a vreg to get and we'll
621      // insert copies for them in TwoAddressInstructionPass anyway.
622      if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
623        unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
624        unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
625        const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
626        const TargetRegisterClass *SRC =
627        TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
628        if (SRC && SRC != RC) {
629          MRI->setRegClass(NewVReg, SRC);
630          RC = SRC;
631        }
632      }
633    }
634    AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
635               IsClone, IsCloned);
636  }
637
638  MBB->insert(InsertPos, MIB);
639  SDValue Op(Node, 0);
640  bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
641  (void)isNew; // Silence compiler warning.
642  assert(isNew && "Node emitted out of order - early");
643}
644
645/// EmitDbgValue - Generate machine instruction for a dbg_value node.
646///
647MachineInstr *
648InstrEmitter::EmitDbgValue(SDDbgValue *SD,
649                           DenseMap<SDValue, unsigned> &VRBaseMap) {
650  uint64_t Offset = SD->getOffset();
651  MDNode* MDPtr = SD->getMDPtr();
652  DebugLoc DL = SD->getDebugLoc();
653
654  if (SD->getKind() == SDDbgValue::FRAMEIX) {
655    // Stack address; this needs to be lowered in target-dependent fashion.
656    // EmitTargetCodeForFrameDebugValue is responsible for allocation.
657    return BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE))
658        .addFrameIndex(SD->getFrameIx()).addImm(Offset).addMetadata(MDPtr);
659  }
660  // Otherwise, we're going to create an instruction here.
661  const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
662  MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
663  if (SD->getKind() == SDDbgValue::SDNODE) {
664    SDNode *Node = SD->getSDNode();
665    SDValue Op = SDValue(Node, SD->getResNo());
666    // It's possible we replaced this SDNode with other(s) and therefore
667    // didn't generate code for it.  It's better to catch these cases where
668    // they happen and transfer the debug info, but trying to guarantee that
669    // in all cases would be very fragile; this is a safeguard for any
670    // that were missed.
671    DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
672    if (I==VRBaseMap.end())
673      MIB.addReg(0U);       // undef
674    else
675      AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
676                 /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
677  } else if (SD->getKind() == SDDbgValue::CONST) {
678    const Value *V = SD->getConst();
679    if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
680      if (CI->getBitWidth() > 64)
681        MIB.addCImm(CI);
682      else
683        MIB.addImm(CI->getSExtValue());
684    } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
685      MIB.addFPImm(CF);
686    } else {
687      // Could be an Undef.  In any case insert an Undef so we can see what we
688      // dropped.
689      MIB.addReg(0U);
690    }
691  } else {
692    // Insert an Undef so we can see what we dropped.
693    MIB.addReg(0U);
694  }
695
696  if (Offset != 0) // Indirect addressing.
697    MIB.addImm(Offset);
698  else
699    MIB.addReg(0U, RegState::Debug);
700
701  MIB.addMetadata(MDPtr);
702
703  return &*MIB;
704}
705
706/// EmitMachineNode - Generate machine code for a target-specific node and
707/// needed dependencies.
708///
709void InstrEmitter::
710EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
711                DenseMap<SDValue, unsigned> &VRBaseMap) {
712  unsigned Opc = Node->getMachineOpcode();
713
714  // Handle subreg insert/extract specially
715  if (Opc == TargetOpcode::EXTRACT_SUBREG ||
716      Opc == TargetOpcode::INSERT_SUBREG ||
717      Opc == TargetOpcode::SUBREG_TO_REG) {
718    EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
719    return;
720  }
721
722  // Handle COPY_TO_REGCLASS specially.
723  if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
724    EmitCopyToRegClassNode(Node, VRBaseMap);
725    return;
726  }
727
728  // Handle REG_SEQUENCE specially.
729  if (Opc == TargetOpcode::REG_SEQUENCE) {
730    EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
731    return;
732  }
733
734  if (Opc == TargetOpcode::IMPLICIT_DEF)
735    // We want a unique VR for each IMPLICIT_DEF use.
736    return;
737
738  const MCInstrDesc &II = TII->get(Opc);
739  unsigned NumResults = CountResults(Node);
740  unsigned NumDefs = II.getNumDefs();
741  const uint16_t *ScratchRegs = NULL;
742
743  // Handle PATCHPOINT specially and then use the generic code.
744  if (Opc == TargetOpcode::PATCHPOINT) {
745    unsigned CC = Node->getConstantOperandVal(PatchPointOpers::CCPos);
746    NumDefs = NumResults;
747    ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC);
748  }
749
750  unsigned NumImpUses = 0;
751  unsigned NodeOperands =
752    countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
753  bool HasPhysRegOuts = NumResults > NumDefs && II.getImplicitDefs()!=0;
754#ifndef NDEBUG
755  unsigned NumMIOperands = NodeOperands + NumResults;
756  if (II.isVariadic())
757    assert(NumMIOperands >= II.getNumOperands() &&
758           "Too few operands for a variadic node!");
759  else
760    assert(NumMIOperands >= II.getNumOperands() &&
761           NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
762                            NumImpUses &&
763           "#operands for dag node doesn't match .td file!");
764#endif
765
766  // Create the new machine instruction.
767  MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
768
769  // Add result register values for things that are defined by this
770  // instruction.
771  if (NumResults)
772    CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
773
774  // Emit all of the actual operands of this instruction, adding them to the
775  // instruction as appropriate.
776  bool HasOptPRefs = NumDefs > NumResults;
777  assert((!HasOptPRefs || !HasPhysRegOuts) &&
778         "Unable to cope with optional defs and phys regs defs!");
779  unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0;
780  for (unsigned i = NumSkip; i != NodeOperands; ++i)
781    AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II,
782               VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
783
784  // Add scratch registers as implicit def and early clobber
785  if (ScratchRegs)
786    for (unsigned i = 0; ScratchRegs[i]; ++i)
787      MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine |
788                                 RegState::EarlyClobber);
789
790  // Transfer all of the memory reference descriptions of this instruction.
791  MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
792                 cast<MachineSDNode>(Node)->memoperands_end());
793
794  // Insert the instruction into position in the block. This needs to
795  // happen before any custom inserter hook is called so that the
796  // hook knows where in the block to insert the replacement code.
797  MBB->insert(InsertPos, MIB);
798
799  // The MachineInstr may also define physregs instead of virtregs.  These
800  // physreg values can reach other instructions in different ways:
801  //
802  // 1. When there is a use of a Node value beyond the explicitly defined
803  //    virtual registers, we emit a CopyFromReg for one of the implicitly
804  //    defined physregs.  This only happens when HasPhysRegOuts is true.
805  //
806  // 2. A CopyFromReg reading a physreg may be glued to this instruction.
807  //
808  // 3. A glued instruction may implicitly use a physreg.
809  //
810  // 4. A glued instruction may use a RegisterSDNode operand.
811  //
812  // Collect all the used physreg defs, and make sure that any unused physreg
813  // defs are marked as dead.
814  SmallVector<unsigned, 8> UsedRegs;
815
816  // Additional results must be physical register defs.
817  if (HasPhysRegOuts) {
818    for (unsigned i = NumDefs; i < NumResults; ++i) {
819      unsigned Reg = II.getImplicitDefs()[i - NumDefs];
820      if (!Node->hasAnyUseOfValue(i))
821        continue;
822      // This implicitly defined physreg has a use.
823      UsedRegs.push_back(Reg);
824      EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
825    }
826  }
827
828  // Scan the glue chain for any used physregs.
829  if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
830    for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
831      if (F->getOpcode() == ISD::CopyFromReg) {
832        UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
833        continue;
834      } else if (F->getOpcode() == ISD::CopyToReg) {
835        // Skip CopyToReg nodes that are internal to the glue chain.
836        continue;
837      }
838      // Collect declared implicit uses.
839      const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
840      UsedRegs.append(MCID.getImplicitUses(),
841                      MCID.getImplicitUses() + MCID.getNumImplicitUses());
842      // In addition to declared implicit uses, we must also check for
843      // direct RegisterSDNode operands.
844      for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
845        if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
846          unsigned Reg = R->getReg();
847          if (TargetRegisterInfo::isPhysicalRegister(Reg))
848            UsedRegs.push_back(Reg);
849        }
850    }
851  }
852
853  // Finally mark unused registers as dead.
854  if (!UsedRegs.empty() || II.getImplicitDefs())
855    MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
856
857  // Run post-isel target hook to adjust this instruction if needed.
858#ifdef NDEBUG
859  if (II.hasPostISelHook())
860#endif
861    TLI->AdjustInstrPostInstrSelection(MIB, Node);
862}
863
864/// EmitSpecialNode - Generate machine code for a target-independent node and
865/// needed dependencies.
866void InstrEmitter::
867EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
868                DenseMap<SDValue, unsigned> &VRBaseMap) {
869  switch (Node->getOpcode()) {
870  default:
871#ifndef NDEBUG
872    Node->dump();
873#endif
874    llvm_unreachable("This target-independent node should have been selected!");
875  case ISD::EntryToken:
876    llvm_unreachable("EntryToken should have been excluded from the schedule!");
877  case ISD::MERGE_VALUES:
878  case ISD::TokenFactor: // fall thru
879    break;
880  case ISD::CopyToReg: {
881    unsigned SrcReg;
882    SDValue SrcVal = Node->getOperand(2);
883    if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
884      SrcReg = R->getReg();
885    else
886      SrcReg = getVR(SrcVal, VRBaseMap);
887
888    unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
889    if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
890      break;
891
892    BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
893            DestReg).addReg(SrcReg);
894    break;
895  }
896  case ISD::CopyFromReg: {
897    unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
898    EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
899    break;
900  }
901  case ISD::EH_LABEL: {
902    MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
903    BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
904            TII->get(TargetOpcode::EH_LABEL)).addSym(S);
905    break;
906  }
907
908  case ISD::LIFETIME_START:
909  case ISD::LIFETIME_END: {
910    unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ?
911    TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END;
912
913    FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1));
914    BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
915    .addFrameIndex(FI->getIndex());
916    break;
917  }
918
919  case ISD::INLINEASM: {
920    unsigned NumOps = Node->getNumOperands();
921    if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
922      --NumOps;  // Ignore the glue operand.
923
924    // Create the inline asm machine instruction.
925    MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(),
926                                      TII->get(TargetOpcode::INLINEASM));
927
928    // Add the asm string as an external symbol operand.
929    SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
930    const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
931    MIB.addExternalSymbol(AsmStr);
932
933    // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
934    // bits.
935    int64_t ExtraInfo =
936      cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
937                          getZExtValue();
938    MIB.addImm(ExtraInfo);
939
940    // Remember to operand index of the group flags.
941    SmallVector<unsigned, 8> GroupIdx;
942
943    // Add all of the operand registers to the instruction.
944    for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
945      unsigned Flags =
946        cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
947      const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
948
949      GroupIdx.push_back(MIB->getNumOperands());
950      MIB.addImm(Flags);
951      ++i;  // Skip the ID value.
952
953      switch (InlineAsm::getKind(Flags)) {
954      default: llvm_unreachable("Bad flags!");
955        case InlineAsm::Kind_RegDef:
956        for (unsigned j = 0; j != NumVals; ++j, ++i) {
957          unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
958          // FIXME: Add dead flags for physical and virtual registers defined.
959          // For now, mark physical register defs as implicit to help fast
960          // regalloc. This makes inline asm look a lot like calls.
961          MIB.addReg(Reg, RegState::Define |
962                  getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
963        }
964        break;
965      case InlineAsm::Kind_RegDefEarlyClobber:
966      case InlineAsm::Kind_Clobber:
967        for (unsigned j = 0; j != NumVals; ++j, ++i) {
968          unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
969          MIB.addReg(Reg, RegState::Define | RegState::EarlyClobber |
970                  getImplRegState(TargetRegisterInfo::isPhysicalRegister(Reg)));
971        }
972        break;
973      case InlineAsm::Kind_RegUse:  // Use of register.
974      case InlineAsm::Kind_Imm:  // Immediate.
975      case InlineAsm::Kind_Mem:  // Addressing mode.
976        // The addressing mode has been selected, just add all of the
977        // operands to the machine instruction.
978        for (unsigned j = 0; j != NumVals; ++j, ++i)
979          AddOperand(MIB, Node->getOperand(i), 0, 0, VRBaseMap,
980                     /*IsDebug=*/false, IsClone, IsCloned);
981
982        // Manually set isTied bits.
983        if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
984          unsigned DefGroup = 0;
985          if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
986            unsigned DefIdx = GroupIdx[DefGroup] + 1;
987            unsigned UseIdx = GroupIdx.back() + 1;
988            for (unsigned j = 0; j != NumVals; ++j)
989              MIB->tieOperands(DefIdx + j, UseIdx + j);
990          }
991        }
992        break;
993      }
994    }
995
996    // Get the mdnode from the asm if it exists and add it to the instruction.
997    SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
998    const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
999    if (MD)
1000      MIB.addMetadata(MD);
1001
1002    MBB->insert(InsertPos, MIB);
1003    break;
1004  }
1005  }
1006}
1007
1008/// InstrEmitter - Construct an InstrEmitter and set it to start inserting
1009/// at the given position in the given block.
1010InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
1011                           MachineBasicBlock::iterator insertpos)
1012  : MF(mbb->getParent()),
1013    MRI(&MF->getRegInfo()),
1014    TM(&MF->getTarget()),
1015    TII(TM->getInstrInfo()),
1016    TRI(TM->getRegisterInfo()),
1017    TLI(TM->getTargetLowering()),
1018    MBB(mbb), InsertPos(insertpos) {
1019}
1020