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