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