1 //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the Emit routines for the SelectionDAG class, which creates
11 // MachineInstrs based on the decisions of the SelectionDAG instruction
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "instr-emitter"
17 #include "InstrEmitter.h"
18 #include "SDNodeDbgValue.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
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
37 const unsigned MinRCSize = 4;
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)
46 if (N && Node->getValueType(N - 1) == MVT::Other)
47 --N; // Skip over chain result.
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
55 unsigned InstrEmitter::CountOperands(SDNode *Node) {
56 unsigned N = Node->getNumOperands();
57 while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
59 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
60 --N; // Ignore chain if it exists.
64 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
65 /// implicit physical register output.
67 EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
68 unsigned SrcReg, DenseMap<SDValue, unsigned> &VRBaseMap) {
70 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
71 // Just use the input register directly!
72 SDValue Op(Node, ResNo);
75 bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
76 (void)isNew; // Silence compiler warning.
77 assert(isNew && "Node emitted out of order - early");
81 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
82 // the CopyToReg'd destination register instead of creating a new vreg.
84 const TargetRegisterClass *UseRC = NULL;
85 EVT VT = Node->getValueType(ResNo);
87 // Stick to the preferred register classes for legal types.
88 if (TLI->isTypeLegal(VT))
89 UseRC = TLI->getRegClassFor(VT);
91 if (!IsClone && !IsCloned)
92 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
96 if (User->getOpcode() == ISD::CopyToReg &&
97 User->getOperand(2).getNode() == Node &&
98 User->getOperand(2).getResNo() == ResNo) {
99 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
100 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
103 } else if (DestReg != SrcReg)
106 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
107 SDValue Op = User->getOperand(i);
108 if (Op.getNode() != Node || Op.getResNo() != ResNo)
110 EVT VT = Node->getValueType(Op.getResNo());
111 if (VT == MVT::Other || VT == MVT::Glue)
114 if (User->isMachineOpcode()) {
115 const MCInstrDesc &II = TII->get(User->getMachineOpcode());
116 const TargetRegisterClass *RC = 0;
117 if (i+II.getNumDefs() < II.getNumOperands())
118 RC = TII->getRegClass(II, i+II.getNumDefs(), TRI);
122 const TargetRegisterClass *ComRC =
123 TRI->getCommonSubClass(UseRC, RC);
124 // If multiple uses expect disjoint register classes, we emit
125 // copies in AddRegisterOperand.
137 const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
138 SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
140 // Figure out the register class to create for the destreg.
142 DstRC = MRI->getRegClass(VRBase);
144 assert(UseRC->hasType(VT) && "Incompatible phys register def and uses!");
147 DstRC = TLI->getRegClassFor(VT);
150 // If all uses are reading from the src physical register and copying the
151 // register is either impossible or very expensive, then don't create a copy.
152 if (MatchReg && SrcRC->getCopyCost() < 0) {
155 // Create the reg, emit the copy.
156 VRBase = MRI->createVirtualRegister(DstRC);
157 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
158 VRBase).addReg(SrcReg);
161 SDValue Op(Node, ResNo);
164 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
165 (void)isNew; // Silence compiler warning.
166 assert(isNew && "Node emitted out of order - early");
169 /// getDstOfCopyToRegUse - If the only use of the specified result number of
170 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
171 unsigned InstrEmitter::getDstOfOnlyCopyToRegUse(SDNode *Node,
172 unsigned ResNo) const {
173 if (!Node->hasOneUse())
176 SDNode *User = *Node->use_begin();
177 if (User->getOpcode() == ISD::CopyToReg &&
178 User->getOperand(2).getNode() == Node &&
179 User->getOperand(2).getResNo() == ResNo) {
180 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
181 if (TargetRegisterInfo::isVirtualRegister(Reg))
187 void InstrEmitter::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
188 const MCInstrDesc &II,
189 bool IsClone, bool IsCloned,
190 DenseMap<SDValue, unsigned> &VRBaseMap) {
191 assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
192 "IMPLICIT_DEF should have been handled as a special case elsewhere!");
194 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
195 // If the specific node value is only used by a CopyToReg and the dest reg
196 // is a vreg in the same register class, use the CopyToReg'd destination
197 // register instead of creating a new vreg.
199 const TargetRegisterClass *RC = TII->getRegClass(II, i, TRI);
200 if (II.OpInfo[i].isOptionalDef()) {
201 // Optional def must be a physical register.
202 unsigned NumResults = CountResults(Node);
203 VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
204 assert(TargetRegisterInfo::isPhysicalRegister(VRBase));
205 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
208 if (!VRBase && !IsClone && !IsCloned)
209 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
212 if (User->getOpcode() == ISD::CopyToReg &&
213 User->getOperand(2).getNode() == Node &&
214 User->getOperand(2).getResNo() == i) {
215 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
216 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
217 const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
220 MI->addOperand(MachineOperand::CreateReg(Reg, true));
227 // Create the result registers for this node and add the result regs to
228 // the machine instruction.
230 assert(RC && "Isn't a register operand!");
231 VRBase = MRI->createVirtualRegister(RC);
232 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
238 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
239 (void)isNew; // Silence compiler warning.
240 assert(isNew && "Node emitted out of order - early");
244 /// getVR - Return the virtual register corresponding to the specified result
245 /// of the specified node.
246 unsigned InstrEmitter::getVR(SDValue Op,
247 DenseMap<SDValue, unsigned> &VRBaseMap) {
248 if (Op.isMachineOpcode() &&
249 Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
250 // Add an IMPLICIT_DEF instruction before every use.
251 unsigned VReg = getDstOfOnlyCopyToRegUse(Op.getNode(), Op.getResNo());
252 // IMPLICIT_DEF can produce any type of result so its MCInstrDesc
253 // does not include operand register class info.
255 const TargetRegisterClass *RC = TLI->getRegClassFor(Op.getValueType());
256 VReg = MRI->createVirtualRegister(RC);
258 BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
259 TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
263 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
264 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
269 /// AddRegisterOperand - Add the specified register as an operand to the
270 /// specified machine instr. Insert register copies if the register is
271 /// not in the required register class.
273 InstrEmitter::AddRegisterOperand(MachineInstr *MI, SDValue Op,
275 const MCInstrDesc *II,
276 DenseMap<SDValue, unsigned> &VRBaseMap,
277 bool IsDebug, bool IsClone, bool IsCloned) {
278 assert(Op.getValueType() != MVT::Other &&
279 Op.getValueType() != MVT::Glue &&
280 "Chain and glue operands should occur at end of operand list!");
281 // Get/emit the operand.
282 unsigned VReg = getVR(Op, VRBaseMap);
283 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
285 const MCInstrDesc &MCID = MI->getDesc();
286 bool isOptDef = IIOpNum < MCID.getNumOperands() &&
287 MCID.OpInfo[IIOpNum].isOptionalDef();
289 // If the instruction requires a register in a different class, create
290 // a new virtual register and copy the value into it, but first attempt to
291 // shrink VReg's register class within reason. For example, if VReg == GR32
292 // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP.
294 const TargetRegisterClass *DstRC = 0;
295 if (IIOpNum < II->getNumOperands())
296 DstRC = TII->getRegClass(*II, IIOpNum, TRI);
297 assert((DstRC || (MI->isVariadic() && IIOpNum >= MCID.getNumOperands())) &&
298 "Don't have operand info for this instruction!");
299 if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
300 unsigned NewVReg = MRI->createVirtualRegister(DstRC);
301 BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
302 TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
307 // If this value has only one use, that use is a kill. This is a
308 // conservative approximation. InstrEmitter does trivial coalescing
309 // with CopyFromReg nodes, so don't emit kill flags for them.
310 // Avoid kill flags on Schedule cloned nodes, since there will be
312 // Tied operands are never killed, so we need to check that. And that
313 // means we need to determine the index of the operand.
314 bool isKill = Op.hasOneUse() &&
315 Op.getNode()->getOpcode() != ISD::CopyFromReg &&
317 !(IsClone || IsCloned);
319 unsigned Idx = MI->getNumOperands();
321 MI->getOperand(Idx-1).isReg() && MI->getOperand(Idx-1).isImplicit())
323 bool isTied = MI->getDesc().getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
328 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef,
329 false/*isImp*/, isKill,
330 false/*isDead*/, false/*isUndef*/,
331 false/*isEarlyClobber*/,
332 0/*SubReg*/, IsDebug));
335 /// AddOperand - Add the specified operand to the specified machine instr. II
336 /// specifies the instruction information for the node, and IIOpNum is the
337 /// operand number (in the II) that we are adding. IIOpNum and II are used for
339 void InstrEmitter::AddOperand(MachineInstr *MI, SDValue Op,
341 const MCInstrDesc *II,
342 DenseMap<SDValue, unsigned> &VRBaseMap,
343 bool IsDebug, bool IsClone, bool IsCloned) {
344 if (Op.isMachineOpcode()) {
345 AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap,
346 IsDebug, IsClone, IsCloned);
347 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
348 MI->addOperand(MachineOperand::CreateImm(C->getSExtValue()));
349 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
350 const ConstantFP *CFP = F->getConstantFPValue();
351 MI->addOperand(MachineOperand::CreateFPImm(CFP));
352 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
353 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
354 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
355 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(), TGA->getOffset(),
356 TGA->getTargetFlags()));
357 } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
358 MI->addOperand(MachineOperand::CreateMBB(BBNode->getBasicBlock()));
359 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
360 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
361 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
362 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex(),
363 JT->getTargetFlags()));
364 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
365 int Offset = CP->getOffset();
366 unsigned Align = CP->getAlignment();
367 Type *Type = CP->getType();
368 // MachineConstantPool wants an explicit alignment.
370 Align = TM->getTargetData()->getPrefTypeAlignment(Type);
372 // Alignment of vector types. FIXME!
373 Align = TM->getTargetData()->getTypeAllocSize(Type);
378 MachineConstantPool *MCP = MF->getConstantPool();
379 if (CP->isMachineConstantPoolEntry())
380 Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Align);
382 Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Align);
383 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset,
384 CP->getTargetFlags()));
385 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
386 MI->addOperand(MachineOperand::CreateES(ES->getSymbol(),
387 ES->getTargetFlags()));
388 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
389 MI->addOperand(MachineOperand::CreateBA(BA->getBlockAddress(),
390 BA->getTargetFlags()));
392 assert(Op.getValueType() != MVT::Other &&
393 Op.getValueType() != MVT::Glue &&
394 "Chain and glue operands should occur at end of operand list!");
395 AddRegisterOperand(MI, Op, IIOpNum, II, VRBaseMap,
396 IsDebug, IsClone, IsCloned);
400 unsigned InstrEmitter::ConstrainForSubReg(unsigned VReg, unsigned SubIdx,
401 EVT VT, DebugLoc DL) {
402 const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
403 const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
405 // RC is a sub-class of VRC that supports SubIdx. Try to constrain VReg
408 RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
410 // VReg has been adjusted. It can be used with SubIdx operands now.
414 // VReg couldn't be reasonably constrained. Emit a COPY to a new virtual
416 RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT), SubIdx);
417 assert(RC && "No legal register class for VT supports that SubIdx");
418 unsigned NewReg = MRI->createVirtualRegister(RC);
419 BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
424 /// EmitSubregNode - Generate machine code for subreg nodes.
426 void InstrEmitter::EmitSubregNode(SDNode *Node,
427 DenseMap<SDValue, unsigned> &VRBaseMap,
428 bool IsClone, bool IsCloned) {
430 unsigned Opc = Node->getMachineOpcode();
432 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
433 // the CopyToReg'd destination register instead of creating a new vreg.
434 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
437 if (User->getOpcode() == ISD::CopyToReg &&
438 User->getOperand(2).getNode() == Node) {
439 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
440 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
447 if (Opc == TargetOpcode::EXTRACT_SUBREG) {
448 // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub. There are no
449 // constraints on the %dst register, COPY can target all legal register
451 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
452 const TargetRegisterClass *TRC = TLI->getRegClassFor(Node->getValueType(0));
454 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
455 MachineInstr *DefMI = MRI->getVRegDef(VReg);
456 unsigned SrcReg, DstReg, DefSubIdx;
458 TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
459 SubIdx == DefSubIdx) {
461 // r1025 = s/zext r1024, 4
462 // r1026 = extract_subreg r1025, 4
464 // r1026 = copy r1024
465 VRBase = MRI->createVirtualRegister(TRC);
466 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
467 TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
469 // VReg may not support a SubIdx sub-register, and we may need to
470 // constrain its register class or issue a COPY to a compatible register
472 VReg = ConstrainForSubReg(VReg, SubIdx,
473 Node->getOperand(0).getValueType(),
474 Node->getDebugLoc());
476 // Create the destreg if it is missing.
478 VRBase = MRI->createVirtualRegister(TRC);
480 // Create the extract_subreg machine instruction.
481 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
482 TII->get(TargetOpcode::COPY), VRBase).addReg(VReg, 0, SubIdx);
484 } else if (Opc == TargetOpcode::INSERT_SUBREG ||
485 Opc == TargetOpcode::SUBREG_TO_REG) {
486 SDValue N0 = Node->getOperand(0);
487 SDValue N1 = Node->getOperand(1);
488 SDValue N2 = Node->getOperand(2);
489 unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
491 // Figure out the register class to create for the destreg. It should be
492 // the largest legal register class supporting SubIdx sub-registers.
493 // RegisterCoalescer will constrain it further if it decides to eliminate
494 // the INSERT_SUBREG instruction.
496 // %dst = INSERT_SUBREG %src, %sub, SubIdx
498 // is lowered by TwoAddressInstructionPass to:
501 // %dst:SubIdx = COPY %sub
503 // There is no constraint on the %src register class.
505 const TargetRegisterClass *SRC = TLI->getRegClassFor(Node->getValueType(0));
506 SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
507 assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
509 if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
510 VRBase = MRI->createVirtualRegister(SRC);
512 // Create the insert_subreg or subreg_to_reg machine instruction.
513 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc));
514 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
516 // If creating a subreg_to_reg, then the first input operand
517 // is an implicit value immediate, otherwise it's a register
518 if (Opc == TargetOpcode::SUBREG_TO_REG) {
519 const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
520 MI->addOperand(MachineOperand::CreateImm(SD->getZExtValue()));
522 AddOperand(MI, N0, 0, 0, VRBaseMap, /*IsDebug=*/false,
524 // Add the subregster being inserted
525 AddOperand(MI, N1, 0, 0, VRBaseMap, /*IsDebug=*/false,
527 MI->addOperand(MachineOperand::CreateImm(SubIdx));
528 MBB->insert(InsertPos, MI);
530 llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
533 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
534 (void)isNew; // Silence compiler warning.
535 assert(isNew && "Node emitted out of order - early");
538 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
539 /// COPY_TO_REGCLASS is just a normal copy, except that the destination
540 /// register is constrained to be in a particular register class.
543 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
544 DenseMap<SDValue, unsigned> &VRBaseMap) {
545 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
547 // Create the new VReg in the destination class and emit a copy.
548 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
549 const TargetRegisterClass *DstRC = TRI->getRegClass(DstRCIdx);
550 unsigned NewVReg = MRI->createVirtualRegister(DstRC);
551 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
552 NewVReg).addReg(VReg);
555 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
556 (void)isNew; // Silence compiler warning.
557 assert(isNew && "Node emitted out of order - early");
560 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
562 void InstrEmitter::EmitRegSequence(SDNode *Node,
563 DenseMap<SDValue, unsigned> &VRBaseMap,
564 bool IsClone, bool IsCloned) {
565 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
566 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
567 unsigned NewVReg = MRI->createVirtualRegister(RC);
568 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
569 TII->get(TargetOpcode::REG_SEQUENCE), NewVReg);
570 unsigned NumOps = Node->getNumOperands();
571 assert((NumOps & 1) == 1 &&
572 "REG_SEQUENCE must have an odd number of operands!");
573 const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
574 for (unsigned i = 1; i != NumOps; ++i) {
575 SDValue Op = Node->getOperand(i);
577 unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
578 unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
579 const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
580 const TargetRegisterClass *SRC =
581 TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
582 if (SRC && SRC != RC) {
583 MRI->setRegClass(NewVReg, SRC);
587 AddOperand(MI, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
591 MBB->insert(InsertPos, MI);
593 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
594 (void)isNew; // Silence compiler warning.
595 assert(isNew && "Node emitted out of order - early");
598 /// EmitDbgValue - Generate machine instruction for a dbg_value node.
601 InstrEmitter::EmitDbgValue(SDDbgValue *SD,
602 DenseMap<SDValue, unsigned> &VRBaseMap) {
603 uint64_t Offset = SD->getOffset();
604 MDNode* MDPtr = SD->getMDPtr();
605 DebugLoc DL = SD->getDebugLoc();
607 if (SD->getKind() == SDDbgValue::FRAMEIX) {
608 // Stack address; this needs to be lowered in target-dependent fashion.
609 // EmitTargetCodeForFrameDebugValue is responsible for allocation.
610 unsigned FrameIx = SD->getFrameIx();
611 return TII->emitFrameIndexDebugValue(*MF, FrameIx, Offset, MDPtr, DL);
613 // Otherwise, we're going to create an instruction here.
614 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
615 MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
616 if (SD->getKind() == SDDbgValue::SDNODE) {
617 SDNode *Node = SD->getSDNode();
618 SDValue Op = SDValue(Node, SD->getResNo());
619 // It's possible we replaced this SDNode with other(s) and therefore
620 // didn't generate code for it. It's better to catch these cases where
621 // they happen and transfer the debug info, but trying to guarantee that
622 // in all cases would be very fragile; this is a safeguard for any
624 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
625 if (I==VRBaseMap.end())
626 MIB.addReg(0U); // undef
628 AddOperand(&*MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
629 /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
630 } else if (SD->getKind() == SDDbgValue::CONST) {
631 const Value *V = SD->getConst();
632 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
633 if (CI->getBitWidth() > 64)
636 MIB.addImm(CI->getSExtValue());
637 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
640 // Could be an Undef. In any case insert an Undef so we can see what we
645 // Insert an Undef so we can see what we dropped.
649 MIB.addImm(Offset).addMetadata(MDPtr);
653 /// EmitMachineNode - Generate machine code for a target-specific node and
654 /// needed dependencies.
657 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
658 DenseMap<SDValue, unsigned> &VRBaseMap) {
659 unsigned Opc = Node->getMachineOpcode();
661 // Handle subreg insert/extract specially
662 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
663 Opc == TargetOpcode::INSERT_SUBREG ||
664 Opc == TargetOpcode::SUBREG_TO_REG) {
665 EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
669 // Handle COPY_TO_REGCLASS specially.
670 if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
671 EmitCopyToRegClassNode(Node, VRBaseMap);
675 // Handle REG_SEQUENCE specially.
676 if (Opc == TargetOpcode::REG_SEQUENCE) {
677 EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
681 if (Opc == TargetOpcode::IMPLICIT_DEF)
682 // We want a unique VR for each IMPLICIT_DEF use.
685 const MCInstrDesc &II = TII->get(Opc);
686 unsigned NumResults = CountResults(Node);
687 unsigned NodeOperands = CountOperands(Node);
688 bool HasPhysRegOuts = NumResults > II.getNumDefs() && II.getImplicitDefs()!=0;
690 unsigned NumMIOperands = NodeOperands + NumResults;
692 assert(NumMIOperands >= II.getNumOperands() &&
693 "Too few operands for a variadic node!");
695 assert(NumMIOperands >= II.getNumOperands() &&
696 NumMIOperands <= II.getNumOperands()+II.getNumImplicitDefs() &&
697 "#operands for dag node doesn't match .td file!");
700 // Create the new machine instruction.
701 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(), II);
703 // The MachineInstr constructor adds implicit-def operands. Scan through
704 // these to determine which are dead.
705 if (MI->getNumOperands() != 0 &&
706 Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
707 // First, collect all used registers.
708 SmallVector<unsigned, 8> UsedRegs;
709 for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser())
710 if (F->getOpcode() == ISD::CopyFromReg)
711 UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
713 // Collect declared implicit uses.
714 const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
715 UsedRegs.append(MCID.getImplicitUses(),
716 MCID.getImplicitUses() + MCID.getNumImplicitUses());
717 // In addition to declared implicit uses, we must also check for
718 // direct RegisterSDNode operands.
719 for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
720 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
721 unsigned Reg = R->getReg();
722 if (TargetRegisterInfo::isPhysicalRegister(Reg))
723 UsedRegs.push_back(Reg);
726 // Then mark unused registers as dead.
727 MI->setPhysRegsDeadExcept(UsedRegs, *TRI);
730 // Add result register values for things that are defined by this
733 CreateVirtualRegisters(Node, MI, II, IsClone, IsCloned, VRBaseMap);
735 // Emit all of the actual operands of this instruction, adding them to the
736 // instruction as appropriate.
737 bool HasOptPRefs = II.getNumDefs() > NumResults;
738 assert((!HasOptPRefs || !HasPhysRegOuts) &&
739 "Unable to cope with optional defs and phys regs defs!");
740 unsigned NumSkip = HasOptPRefs ? II.getNumDefs() - NumResults : 0;
741 for (unsigned i = NumSkip; i != NodeOperands; ++i)
742 AddOperand(MI, Node->getOperand(i), i-NumSkip+II.getNumDefs(), &II,
743 VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
745 // Transfer all of the memory reference descriptions of this instruction.
746 MI->setMemRefs(cast<MachineSDNode>(Node)->memoperands_begin(),
747 cast<MachineSDNode>(Node)->memoperands_end());
749 // Insert the instruction into position in the block. This needs to
750 // happen before any custom inserter hook is called so that the
751 // hook knows where in the block to insert the replacement code.
752 MBB->insert(InsertPos, MI);
754 // Additional results must be physical register defs.
755 if (HasPhysRegOuts) {
756 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
757 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
758 if (Node->hasAnyUseOfValue(i))
759 EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
760 // If there are no uses, mark the register as dead now, so that
761 // MachineLICM/Sink can see that it's dead. Don't do this if the
762 // node has a Glue value, for the benefit of targets still using
763 // Glue for values in physregs.
764 else if (Node->getValueType(Node->getNumValues()-1) != MVT::Glue)
765 MI->addRegisterDead(Reg, TRI);
769 // If the instruction has implicit defs and the node doesn't, mark the
770 // implicit def as dead. If the node has any glue outputs, we don't do this
771 // because we don't know what implicit defs are being used by glued nodes.
772 if (Node->getValueType(Node->getNumValues()-1) != MVT::Glue)
773 if (const unsigned *IDList = II.getImplicitDefs()) {
774 for (unsigned i = NumResults, e = II.getNumDefs()+II.getNumImplicitDefs();
776 MI->addRegisterDead(IDList[i-II.getNumDefs()], TRI);
779 // Run post-isel target hook to adjust this instruction if needed.
781 if (II.hasPostISelHook())
783 TLI->AdjustInstrPostInstrSelection(MI, Node);
786 /// EmitSpecialNode - Generate machine code for a target-independent node and
787 /// needed dependencies.
789 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
790 DenseMap<SDValue, unsigned> &VRBaseMap) {
791 switch (Node->getOpcode()) {
796 llvm_unreachable("This target-independent node should have been selected!");
798 case ISD::EntryToken:
799 llvm_unreachable("EntryToken should have been excluded from the schedule!");
801 case ISD::MERGE_VALUES:
802 case ISD::TokenFactor: // fall thru
804 case ISD::CopyToReg: {
806 SDValue SrcVal = Node->getOperand(2);
807 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
808 SrcReg = R->getReg();
810 SrcReg = getVR(SrcVal, VRBaseMap);
812 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
813 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
816 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
817 DestReg).addReg(SrcReg);
820 case ISD::CopyFromReg: {
821 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
822 EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
825 case ISD::EH_LABEL: {
826 MCSymbol *S = cast<EHLabelSDNode>(Node)->getLabel();
827 BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
828 TII->get(TargetOpcode::EH_LABEL)).addSym(S);
832 case ISD::INLINEASM: {
833 unsigned NumOps = Node->getNumOperands();
834 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
835 --NumOps; // Ignore the glue operand.
837 // Create the inline asm machine instruction.
838 MachineInstr *MI = BuildMI(*MF, Node->getDebugLoc(),
839 TII->get(TargetOpcode::INLINEASM));
841 // Add the asm string as an external symbol operand.
842 SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
843 const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
844 MI->addOperand(MachineOperand::CreateES(AsmStr));
846 // Add the HasSideEffect and isAlignStack bits.
848 cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
850 MI->addOperand(MachineOperand::CreateImm(ExtraInfo));
852 // Add all of the operand registers to the instruction.
853 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
855 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
856 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
858 MI->addOperand(MachineOperand::CreateImm(Flags));
859 ++i; // Skip the ID value.
861 switch (InlineAsm::getKind(Flags)) {
862 default: llvm_unreachable("Bad flags!");
863 case InlineAsm::Kind_RegDef:
864 for (; NumVals; --NumVals, ++i) {
865 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
866 // FIXME: Add dead flags for physical and virtual registers defined.
867 // For now, mark physical register defs as implicit to help fast
868 // regalloc. This makes inline asm look a lot like calls.
869 MI->addOperand(MachineOperand::CreateReg(Reg, true,
870 /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg)));
873 case InlineAsm::Kind_RegDefEarlyClobber:
874 case InlineAsm::Kind_Clobber:
875 for (; NumVals; --NumVals, ++i) {
876 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
877 MI->addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/ true,
878 /*isImp=*/ TargetRegisterInfo::isPhysicalRegister(Reg),
882 /*isEarlyClobber=*/ true));
885 case InlineAsm::Kind_RegUse: // Use of register.
886 case InlineAsm::Kind_Imm: // Immediate.
887 case InlineAsm::Kind_Mem: // Addressing mode.
888 // The addressing mode has been selected, just add all of the
889 // operands to the machine instruction.
890 for (; NumVals; --NumVals, ++i)
891 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap,
892 /*IsDebug=*/false, IsClone, IsCloned);
897 // Get the mdnode from the asm if it exists and add it to the instruction.
898 SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
899 const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
901 MI->addOperand(MachineOperand::CreateMetadata(MD));
903 MBB->insert(InsertPos, MI);
909 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
910 /// at the given position in the given block.
911 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
912 MachineBasicBlock::iterator insertpos)
913 : MF(mbb->getParent()),
914 MRI(&MF->getRegInfo()),
915 TM(&MF->getTarget()),
916 TII(TM->getInstrInfo()),
917 TRI(TM->getRegisterInfo()),
918 TLI(TM->getTargetLowering()),
919 MBB(mbb), InsertPos(insertpos) {