1 //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the Emit routines for the SelectionDAG class, which creates 10 // MachineInstrs based on the decisions of the SelectionDAG instruction 11 // selection. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "InstrEmitter.h" 16 #include "SDNodeDbgValue.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/CodeGen/MachineConstantPool.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineInstrBuilder.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/SelectionDAG.h" 23 #include "llvm/CodeGen/StackMaps.h" 24 #include "llvm/CodeGen/TargetInstrInfo.h" 25 #include "llvm/CodeGen/TargetLowering.h" 26 #include "llvm/CodeGen/TargetSubtargetInfo.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DebugInfo.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/MathExtras.h" 32 using namespace llvm; 33 34 #define DEBUG_TYPE "instr-emitter" 35 36 /// MinRCSize - Smallest register class we allow when constraining virtual 37 /// registers. If satisfying all register class constraints would require 38 /// using a smaller register class, emit a COPY to a new virtual register 39 /// instead. 40 const unsigned MinRCSize = 4; 41 42 /// CountResults - The results of target nodes have register or immediate 43 /// operands first, then an optional chain, and optional glue operands (which do 44 /// not go into the resulting MachineInstr). 45 unsigned InstrEmitter::CountResults(SDNode *Node) { 46 unsigned N = Node->getNumValues(); 47 while (N && Node->getValueType(N - 1) == MVT::Glue) 48 --N; 49 if (N && Node->getValueType(N - 1) == MVT::Other) 50 --N; // Skip over chain result. 51 return N; 52 } 53 54 /// countOperands - The inputs to target nodes have any actual inputs first, 55 /// followed by an optional chain operand, then an optional glue operand. 56 /// Compute the number of actual operands that will go into the resulting 57 /// MachineInstr. 58 /// 59 /// Also count physreg RegisterSDNode and RegisterMaskSDNode operands preceding 60 /// the chain and glue. These operands may be implicit on the machine instr. 61 static unsigned countOperands(SDNode *Node, unsigned NumExpUses, 62 unsigned &NumImpUses) { 63 unsigned N = Node->getNumOperands(); 64 while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue) 65 --N; 66 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other) 67 --N; // Ignore chain if it exists. 68 69 // Count RegisterSDNode and RegisterMaskSDNode operands for NumImpUses. 70 NumImpUses = N - NumExpUses; 71 for (unsigned I = N; I > NumExpUses; --I) { 72 if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1))) 73 continue; 74 if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1))) 75 if (Register::isPhysicalRegister(RN->getReg())) 76 continue; 77 NumImpUses = N - I; 78 break; 79 } 80 81 return N; 82 } 83 84 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an 85 /// implicit physical register output. 86 void InstrEmitter:: 87 EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned, 88 Register SrcReg, DenseMap<SDValue, Register> &VRBaseMap) { 89 Register VRBase; 90 if (SrcReg.isVirtual()) { 91 // Just use the input register directly! 92 SDValue Op(Node, ResNo); 93 if (IsClone) 94 VRBaseMap.erase(Op); 95 bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second; 96 (void)isNew; // Silence compiler warning. 97 assert(isNew && "Node emitted out of order - early"); 98 return; 99 } 100 101 // If the node is only used by a CopyToReg and the dest reg is a vreg, use 102 // the CopyToReg'd destination register instead of creating a new vreg. 103 bool MatchReg = true; 104 const TargetRegisterClass *UseRC = nullptr; 105 MVT VT = Node->getSimpleValueType(ResNo); 106 107 // Stick to the preferred register classes for legal types. 108 if (TLI->isTypeLegal(VT)) 109 UseRC = TLI->getRegClassFor(VT, Node->isDivergent()); 110 111 if (!IsClone && !IsCloned) 112 for (SDNode *User : Node->uses()) { 113 bool Match = true; 114 if (User->getOpcode() == ISD::CopyToReg && 115 User->getOperand(2).getNode() == Node && 116 User->getOperand(2).getResNo() == ResNo) { 117 Register DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg(); 118 if (DestReg.isVirtual()) { 119 VRBase = DestReg; 120 Match = false; 121 } else if (DestReg != SrcReg) 122 Match = false; 123 } else { 124 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 125 SDValue Op = User->getOperand(i); 126 if (Op.getNode() != Node || Op.getResNo() != ResNo) 127 continue; 128 MVT VT = Node->getSimpleValueType(Op.getResNo()); 129 if (VT == MVT::Other || VT == MVT::Glue) 130 continue; 131 Match = false; 132 if (User->isMachineOpcode()) { 133 const MCInstrDesc &II = TII->get(User->getMachineOpcode()); 134 const TargetRegisterClass *RC = nullptr; 135 if (i+II.getNumDefs() < II.getNumOperands()) { 136 RC = TRI->getAllocatableClass( 137 TII->getRegClass(II, i+II.getNumDefs(), TRI, *MF)); 138 } 139 if (!UseRC) 140 UseRC = RC; 141 else if (RC) { 142 const TargetRegisterClass *ComRC = 143 TRI->getCommonSubClass(UseRC, RC); 144 // If multiple uses expect disjoint register classes, we emit 145 // copies in AddRegisterOperand. 146 if (ComRC) 147 UseRC = ComRC; 148 } 149 } 150 } 151 } 152 MatchReg &= Match; 153 if (VRBase) 154 break; 155 } 156 157 const TargetRegisterClass *SrcRC = nullptr, *DstRC = nullptr; 158 SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT); 159 160 // Figure out the register class to create for the destreg. 161 if (VRBase) { 162 DstRC = MRI->getRegClass(VRBase); 163 } else if (UseRC) { 164 assert(TRI->isTypeLegalForClass(*UseRC, VT) && 165 "Incompatible phys register def and uses!"); 166 DstRC = UseRC; 167 } else { 168 DstRC = TLI->getRegClassFor(VT, Node->isDivergent()); 169 } 170 171 // If all uses are reading from the src physical register and copying the 172 // register is either impossible or very expensive, then don't create a copy. 173 if (MatchReg && SrcRC->getCopyCost() < 0) { 174 VRBase = SrcReg; 175 } else { 176 // Create the reg, emit the copy. 177 VRBase = MRI->createVirtualRegister(DstRC); 178 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY), 179 VRBase).addReg(SrcReg); 180 } 181 182 SDValue Op(Node, ResNo); 183 if (IsClone) 184 VRBaseMap.erase(Op); 185 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second; 186 (void)isNew; // Silence compiler warning. 187 assert(isNew && "Node emitted out of order - early"); 188 } 189 190 void InstrEmitter::CreateVirtualRegisters(SDNode *Node, 191 MachineInstrBuilder &MIB, 192 const MCInstrDesc &II, 193 bool IsClone, bool IsCloned, 194 DenseMap<SDValue, Register> &VRBaseMap) { 195 assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF && 196 "IMPLICIT_DEF should have been handled as a special case elsewhere!"); 197 198 unsigned NumResults = CountResults(Node); 199 bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() && 200 II.isVariadic() && II.variadicOpsAreDefs(); 201 unsigned NumVRegs = HasVRegVariadicDefs ? NumResults : II.getNumDefs(); 202 for (unsigned i = 0; i < NumVRegs; ++i) { 203 // If the specific node value is only used by a CopyToReg and the dest reg 204 // is a vreg in the same register class, use the CopyToReg'd destination 205 // register instead of creating a new vreg. 206 Register VRBase; 207 const TargetRegisterClass *RC = 208 TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF)); 209 // Always let the value type influence the used register class. The 210 // constraints on the instruction may be too lax to represent the value 211 // type correctly. For example, a 64-bit float (X86::FR64) can't live in 212 // the 32-bit float super-class (X86::FR32). 213 if (i < NumResults && TLI->isTypeLegal(Node->getSimpleValueType(i))) { 214 const TargetRegisterClass *VTRC = TLI->getRegClassFor( 215 Node->getSimpleValueType(i), 216 (Node->isDivergent() || (RC && TRI->isDivergentRegClass(RC)))); 217 if (RC) 218 VTRC = TRI->getCommonSubClass(RC, VTRC); 219 if (VTRC) 220 RC = VTRC; 221 } 222 223 if (II.OpInfo != nullptr && II.OpInfo[i].isOptionalDef()) { 224 // Optional def must be a physical register. 225 VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg(); 226 assert(VRBase.isPhysical()); 227 MIB.addReg(VRBase, RegState::Define); 228 } 229 230 if (!VRBase && !IsClone && !IsCloned) 231 for (SDNode *User : Node->uses()) { 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 (Register::isVirtualRegister(Reg)) { 237 const TargetRegisterClass *RegRC = MRI->getRegClass(Reg); 238 if (RegRC == RC) { 239 VRBase = Reg; 240 MIB.addReg(VRBase, RegState::Define); 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 MIB.addReg(VRBase, RegState::Define); 253 } 254 255 // If this def corresponds to a result of the SDNode insert the VRBase into 256 // the lookup map. 257 if (i < NumResults) { 258 SDValue Op(Node, i); 259 if (IsClone) 260 VRBaseMap.erase(Op); 261 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second; 262 (void)isNew; // Silence compiler warning. 263 assert(isNew && "Node emitted out of order - early"); 264 } 265 } 266 } 267 268 /// getVR - Return the virtual register corresponding to the specified result 269 /// of the specified node. 270 Register InstrEmitter::getVR(SDValue Op, 271 DenseMap<SDValue, Register> &VRBaseMap) { 272 if (Op.isMachineOpcode() && 273 Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) { 274 // Add an IMPLICIT_DEF instruction before every use. 275 // IMPLICIT_DEF can produce any type of result so its MCInstrDesc 276 // does not include operand register class info. 277 const TargetRegisterClass *RC = TLI->getRegClassFor( 278 Op.getSimpleValueType(), Op.getNode()->isDivergent()); 279 Register VReg = MRI->createVirtualRegister(RC); 280 BuildMI(*MBB, InsertPos, Op.getDebugLoc(), 281 TII->get(TargetOpcode::IMPLICIT_DEF), VReg); 282 return VReg; 283 } 284 285 DenseMap<SDValue, Register>::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, Register> &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 Register VReg = getVR(Op, VRBaseMap); 306 307 const MCInstrDesc &MCID = MIB->getDesc(); 308 bool isOptDef = IIOpNum < MCID.getNumOperands() && 309 MCID.OpInfo[IIOpNum].isOptionalDef(); 310 311 // If the instruction requires a register in a different class, create 312 // a new virtual register and copy the value into it, but first attempt to 313 // shrink VReg's register class within reason. For example, if VReg == GR32 314 // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP. 315 if (II) { 316 const TargetRegisterClass *OpRC = nullptr; 317 if (IIOpNum < II->getNumOperands()) 318 OpRC = TII->getRegClass(*II, IIOpNum, TRI, *MF); 319 320 if (OpRC) { 321 const TargetRegisterClass *ConstrainedRC 322 = MRI->constrainRegClass(VReg, OpRC, MinRCSize); 323 if (!ConstrainedRC) { 324 OpRC = TRI->getAllocatableClass(OpRC); 325 assert(OpRC && "Constraints cannot be fulfilled for allocation"); 326 Register NewVReg = MRI->createVirtualRegister(OpRC); 327 BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(), 328 TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg); 329 VReg = NewVReg; 330 } else { 331 assert(ConstrainedRC->isAllocatable() && 332 "Constraining an allocatable VReg produced an unallocatable class?"); 333 } 334 } 335 } 336 337 // If this value has only one use, that use is a kill. This is a 338 // conservative approximation. InstrEmitter does trivial coalescing 339 // with CopyFromReg nodes, so don't emit kill flags for them. 340 // Avoid kill flags on Schedule cloned nodes, since there will be 341 // multiple uses. 342 // Tied operands are never killed, so we need to check that. And that 343 // means we need to determine the index of the operand. 344 bool isKill = Op.hasOneUse() && 345 Op.getNode()->getOpcode() != ISD::CopyFromReg && 346 !IsDebug && 347 !(IsClone || IsCloned); 348 if (isKill) { 349 unsigned Idx = MIB->getNumOperands(); 350 while (Idx > 0 && 351 MIB->getOperand(Idx-1).isReg() && 352 MIB->getOperand(Idx-1).isImplicit()) 353 --Idx; 354 bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1; 355 if (isTied) 356 isKill = false; 357 } 358 359 MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) | 360 getDebugRegState(IsDebug)); 361 } 362 363 /// AddOperand - Add the specified operand to the specified machine instr. II 364 /// specifies the instruction information for the node, and IIOpNum is the 365 /// operand number (in the II) that we are adding. 366 void InstrEmitter::AddOperand(MachineInstrBuilder &MIB, 367 SDValue Op, 368 unsigned IIOpNum, 369 const MCInstrDesc *II, 370 DenseMap<SDValue, Register> &VRBaseMap, 371 bool IsDebug, bool IsClone, bool IsCloned) { 372 if (Op.isMachineOpcode()) { 373 AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap, 374 IsDebug, IsClone, IsCloned); 375 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 376 MIB.addImm(C->getSExtValue()); 377 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) { 378 MIB.addFPImm(F->getConstantFPValue()); 379 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) { 380 Register VReg = R->getReg(); 381 MVT OpVT = Op.getSimpleValueType(); 382 const TargetRegisterClass *IIRC = 383 II ? TRI->getAllocatableClass(TII->getRegClass(*II, IIOpNum, TRI, *MF)) 384 : nullptr; 385 const TargetRegisterClass *OpRC = 386 TLI->isTypeLegal(OpVT) 387 ? TLI->getRegClassFor(OpVT, 388 Op.getNode()->isDivergent() || 389 (IIRC && TRI->isDivergentRegClass(IIRC))) 390 : nullptr; 391 392 if (OpRC && IIRC && OpRC != IIRC && Register::isVirtualRegister(VReg)) { 393 Register NewVReg = MRI->createVirtualRegister(IIRC); 394 BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(), 395 TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg); 396 VReg = NewVReg; 397 } 398 // Turn additional physreg operands into implicit uses on non-variadic 399 // instructions. This is used by call and return instructions passing 400 // arguments in registers. 401 bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic()); 402 MIB.addReg(VReg, getImplRegState(Imp)); 403 } else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) { 404 MIB.addRegMask(RM->getRegMask()); 405 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) { 406 MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(), 407 TGA->getTargetFlags()); 408 } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) { 409 MIB.addMBB(BBNode->getBasicBlock()); 410 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 411 MIB.addFrameIndex(FI->getIndex()); 412 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) { 413 MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags()); 414 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) { 415 int Offset = CP->getOffset(); 416 Align Alignment = CP->getAlign(); 417 418 unsigned Idx; 419 MachineConstantPool *MCP = MF->getConstantPool(); 420 if (CP->isMachineConstantPoolEntry()) 421 Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Alignment); 422 else 423 Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Alignment); 424 MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags()); 425 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) { 426 MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags()); 427 } else if (auto *SymNode = dyn_cast<MCSymbolSDNode>(Op)) { 428 MIB.addSym(SymNode->getMCSymbol()); 429 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) { 430 MIB.addBlockAddress(BA->getBlockAddress(), 431 BA->getOffset(), 432 BA->getTargetFlags()); 433 } else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) { 434 MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags()); 435 } else { 436 assert(Op.getValueType() != MVT::Other && 437 Op.getValueType() != MVT::Glue && 438 "Chain and glue operands should occur at end of operand list!"); 439 AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap, 440 IsDebug, IsClone, IsCloned); 441 } 442 } 443 444 Register InstrEmitter::ConstrainForSubReg(Register VReg, unsigned SubIdx, 445 MVT VT, bool isDivergent, const DebugLoc &DL) { 446 const TargetRegisterClass *VRC = MRI->getRegClass(VReg); 447 const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx); 448 449 // RC is a sub-class of VRC that supports SubIdx. Try to constrain VReg 450 // within reason. 451 if (RC && RC != VRC) 452 RC = MRI->constrainRegClass(VReg, RC, MinRCSize); 453 454 // VReg has been adjusted. It can be used with SubIdx operands now. 455 if (RC) 456 return VReg; 457 458 // VReg couldn't be reasonably constrained. Emit a COPY to a new virtual 459 // register instead. 460 RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT, isDivergent), SubIdx); 461 assert(RC && "No legal register class for VT supports that SubIdx"); 462 Register NewReg = MRI->createVirtualRegister(RC); 463 BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg) 464 .addReg(VReg); 465 return NewReg; 466 } 467 468 /// EmitSubregNode - Generate machine code for subreg nodes. 469 /// 470 void InstrEmitter::EmitSubregNode(SDNode *Node, 471 DenseMap<SDValue, Register> &VRBaseMap, 472 bool IsClone, bool IsCloned) { 473 Register VRBase; 474 unsigned Opc = Node->getMachineOpcode(); 475 476 // If the node is only used by a CopyToReg and the dest reg is a vreg, use 477 // the CopyToReg'd destination register instead of creating a new vreg. 478 for (SDNode *User : Node->uses()) { 479 if (User->getOpcode() == ISD::CopyToReg && 480 User->getOperand(2).getNode() == Node) { 481 Register DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg(); 482 if (DestReg.isVirtual()) { 483 VRBase = DestReg; 484 break; 485 } 486 } 487 } 488 489 if (Opc == TargetOpcode::EXTRACT_SUBREG) { 490 // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub. There are no 491 // constraints on the %dst register, COPY can target all legal register 492 // classes. 493 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue(); 494 const TargetRegisterClass *TRC = 495 TLI->getRegClassFor(Node->getSimpleValueType(0), Node->isDivergent()); 496 497 Register Reg; 498 MachineInstr *DefMI; 499 RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(0)); 500 if (R && Register::isPhysicalRegister(R->getReg())) { 501 Reg = R->getReg(); 502 DefMI = nullptr; 503 } else { 504 Reg = R ? R->getReg() : getVR(Node->getOperand(0), VRBaseMap); 505 DefMI = MRI->getVRegDef(Reg); 506 } 507 508 Register SrcReg, DstReg; 509 unsigned DefSubIdx; 510 if (DefMI && 511 TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) && 512 SubIdx == DefSubIdx && 513 TRC == MRI->getRegClass(SrcReg)) { 514 // Optimize these: 515 // r1025 = s/zext r1024, 4 516 // r1026 = extract_subreg r1025, 4 517 // to a copy 518 // r1026 = copy r1024 519 VRBase = MRI->createVirtualRegister(TRC); 520 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 521 TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg); 522 MRI->clearKillFlags(SrcReg); 523 } else { 524 // Reg may not support a SubIdx sub-register, and we may need to 525 // constrain its register class or issue a COPY to a compatible register 526 // class. 527 if (Reg.isVirtual()) 528 Reg = ConstrainForSubReg(Reg, SubIdx, 529 Node->getOperand(0).getSimpleValueType(), 530 Node->isDivergent(), Node->getDebugLoc()); 531 // Create the destreg if it is missing. 532 if (!VRBase) 533 VRBase = MRI->createVirtualRegister(TRC); 534 535 // Create the extract_subreg machine instruction. 536 MachineInstrBuilder CopyMI = 537 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 538 TII->get(TargetOpcode::COPY), VRBase); 539 if (Reg.isVirtual()) 540 CopyMI.addReg(Reg, 0, SubIdx); 541 else 542 CopyMI.addReg(TRI->getSubReg(Reg, SubIdx)); 543 } 544 } else if (Opc == TargetOpcode::INSERT_SUBREG || 545 Opc == TargetOpcode::SUBREG_TO_REG) { 546 SDValue N0 = Node->getOperand(0); 547 SDValue N1 = Node->getOperand(1); 548 SDValue N2 = Node->getOperand(2); 549 unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 550 551 // Figure out the register class to create for the destreg. It should be 552 // the largest legal register class supporting SubIdx sub-registers. 553 // RegisterCoalescer will constrain it further if it decides to eliminate 554 // the INSERT_SUBREG instruction. 555 // 556 // %dst = INSERT_SUBREG %src, %sub, SubIdx 557 // 558 // is lowered by TwoAddressInstructionPass to: 559 // 560 // %dst = COPY %src 561 // %dst:SubIdx = COPY %sub 562 // 563 // There is no constraint on the %src register class. 564 // 565 const TargetRegisterClass *SRC = 566 TLI->getRegClassFor(Node->getSimpleValueType(0), Node->isDivergent()); 567 SRC = TRI->getSubClassWithSubReg(SRC, SubIdx); 568 assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG"); 569 570 if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase))) 571 VRBase = MRI->createVirtualRegister(SRC); 572 573 // Create the insert_subreg or subreg_to_reg machine instruction. 574 MachineInstrBuilder MIB = 575 BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase); 576 577 // If creating a subreg_to_reg, then the first input operand 578 // is an implicit value immediate, otherwise it's a register 579 if (Opc == TargetOpcode::SUBREG_TO_REG) { 580 const ConstantSDNode *SD = cast<ConstantSDNode>(N0); 581 MIB.addImm(SD->getZExtValue()); 582 } else 583 AddOperand(MIB, N0, 0, nullptr, VRBaseMap, /*IsDebug=*/false, 584 IsClone, IsCloned); 585 // Add the subregister being inserted 586 AddOperand(MIB, N1, 0, nullptr, VRBaseMap, /*IsDebug=*/false, 587 IsClone, IsCloned); 588 MIB.addImm(SubIdx); 589 MBB->insert(InsertPos, MIB); 590 } else 591 llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg"); 592 593 SDValue Op(Node, 0); 594 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second; 595 (void)isNew; // Silence compiler warning. 596 assert(isNew && "Node emitted out of order - early"); 597 } 598 599 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes. 600 /// COPY_TO_REGCLASS is just a normal copy, except that the destination 601 /// register is constrained to be in a particular register class. 602 /// 603 void 604 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node, 605 DenseMap<SDValue, Register> &VRBaseMap) { 606 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap); 607 608 // Create the new VReg in the destination class and emit a copy. 609 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue(); 610 const TargetRegisterClass *DstRC = 611 TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx)); 612 Register NewVReg = MRI->createVirtualRegister(DstRC); 613 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY), 614 NewVReg).addReg(VReg); 615 616 SDValue Op(Node, 0); 617 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second; 618 (void)isNew; // Silence compiler warning. 619 assert(isNew && "Node emitted out of order - early"); 620 } 621 622 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes. 623 /// 624 void InstrEmitter::EmitRegSequence(SDNode *Node, 625 DenseMap<SDValue, Register> &VRBaseMap, 626 bool IsClone, bool IsCloned) { 627 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue(); 628 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx); 629 Register NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC)); 630 const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE); 631 MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg); 632 unsigned NumOps = Node->getNumOperands(); 633 // If the input pattern has a chain, then the root of the corresponding 634 // output pattern will get a chain as well. This can happen to be a 635 // REG_SEQUENCE (which is not "guarded" by countOperands/CountResults). 636 if (NumOps && Node->getOperand(NumOps-1).getValueType() == MVT::Other) 637 --NumOps; // Ignore chain if it exists. 638 639 assert((NumOps & 1) == 1 && 640 "REG_SEQUENCE must have an odd number of operands!"); 641 for (unsigned i = 1; i != NumOps; ++i) { 642 SDValue Op = Node->getOperand(i); 643 if ((i & 1) == 0) { 644 RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1)); 645 // Skip physical registers as they don't have a vreg to get and we'll 646 // insert copies for them in TwoAddressInstructionPass anyway. 647 if (!R || !Register::isPhysicalRegister(R->getReg())) { 648 unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue(); 649 unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap); 650 const TargetRegisterClass *TRC = MRI->getRegClass(SubReg); 651 const TargetRegisterClass *SRC = 652 TRI->getMatchingSuperRegClass(RC, TRC, SubIdx); 653 if (SRC && SRC != RC) { 654 MRI->setRegClass(NewVReg, SRC); 655 RC = SRC; 656 } 657 } 658 } 659 AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false, 660 IsClone, IsCloned); 661 } 662 663 MBB->insert(InsertPos, MIB); 664 SDValue Op(Node, 0); 665 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second; 666 (void)isNew; // Silence compiler warning. 667 assert(isNew && "Node emitted out of order - early"); 668 } 669 670 /// EmitDbgValue - Generate machine instruction for a dbg_value node. 671 /// 672 MachineInstr * 673 InstrEmitter::EmitDbgValue(SDDbgValue *SD, 674 DenseMap<SDValue, Register> &VRBaseMap) { 675 MDNode *Var = SD->getVariable(); 676 MDNode *Expr = SD->getExpression(); 677 DebugLoc DL = SD->getDebugLoc(); 678 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 679 "Expected inlined-at fields to agree"); 680 681 SD->setIsEmitted(); 682 683 if (SD->isInvalidated()) { 684 // An invalidated SDNode must generate an undef DBG_VALUE: although the 685 // original value is no longer computed, earlier DBG_VALUEs live ranges 686 // must not leak into later code. 687 auto MIB = BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE)); 688 MIB.addReg(0U); 689 MIB.addReg(0U, RegState::Debug); 690 MIB.addMetadata(Var); 691 MIB.addMetadata(Expr); 692 return &*MIB; 693 } 694 695 if (SD->getKind() == SDDbgValue::FRAMEIX) { 696 // Stack address; this needs to be lowered in target-dependent fashion. 697 // EmitTargetCodeForFrameDebugValue is responsible for allocation. 698 auto FrameMI = BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE)) 699 .addFrameIndex(SD->getFrameIx()); 700 if (SD->isIndirect()) 701 // Push [fi + 0] onto the DIExpression stack. 702 FrameMI.addImm(0); 703 else 704 // Push fi onto the DIExpression stack. 705 FrameMI.addReg(0); 706 return FrameMI.addMetadata(Var).addMetadata(Expr); 707 } 708 // Otherwise, we're going to create an instruction here. 709 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE); 710 MachineInstrBuilder MIB = BuildMI(*MF, DL, II); 711 if (SD->getKind() == SDDbgValue::SDNODE) { 712 SDNode *Node = SD->getSDNode(); 713 SDValue Op = SDValue(Node, SD->getResNo()); 714 // It's possible we replaced this SDNode with other(s) and therefore 715 // didn't generate code for it. It's better to catch these cases where 716 // they happen and transfer the debug info, but trying to guarantee that 717 // in all cases would be very fragile; this is a safeguard for any 718 // that were missed. 719 DenseMap<SDValue, Register>::iterator I = VRBaseMap.find(Op); 720 if (I==VRBaseMap.end()) 721 MIB.addReg(0U); // undef 722 else 723 AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap, 724 /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false); 725 } else if (SD->getKind() == SDDbgValue::VREG) { 726 MIB.addReg(SD->getVReg(), RegState::Debug); 727 } else if (SD->getKind() == SDDbgValue::CONST) { 728 const Value *V = SD->getConst(); 729 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 730 if (CI->getBitWidth() > 64) 731 MIB.addCImm(CI); 732 else 733 MIB.addImm(CI->getSExtValue()); 734 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) { 735 MIB.addFPImm(CF); 736 } else if (isa<ConstantPointerNull>(V)) { 737 // Note: This assumes that all nullptr constants are zero-valued. 738 MIB.addImm(0); 739 } else { 740 // Could be an Undef. In any case insert an Undef so we can see what we 741 // dropped. 742 MIB.addReg(0U); 743 } 744 } else { 745 // Insert an Undef so we can see what we dropped. 746 MIB.addReg(0U); 747 } 748 749 // Indirect addressing is indicated by an Imm as the second parameter. 750 if (SD->isIndirect()) 751 MIB.addImm(0U); 752 else 753 MIB.addReg(0U, RegState::Debug); 754 755 MIB.addMetadata(Var); 756 MIB.addMetadata(Expr); 757 758 return &*MIB; 759 } 760 761 MachineInstr * 762 InstrEmitter::EmitDbgLabel(SDDbgLabel *SD) { 763 MDNode *Label = SD->getLabel(); 764 DebugLoc DL = SD->getDebugLoc(); 765 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 766 "Expected inlined-at fields to agree"); 767 768 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_LABEL); 769 MachineInstrBuilder MIB = BuildMI(*MF, DL, II); 770 MIB.addMetadata(Label); 771 772 return &*MIB; 773 } 774 775 /// EmitMachineNode - Generate machine code for a target-specific node and 776 /// needed dependencies. 777 /// 778 void InstrEmitter:: 779 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned, 780 DenseMap<SDValue, Register> &VRBaseMap) { 781 unsigned Opc = Node->getMachineOpcode(); 782 783 // Handle subreg insert/extract specially 784 if (Opc == TargetOpcode::EXTRACT_SUBREG || 785 Opc == TargetOpcode::INSERT_SUBREG || 786 Opc == TargetOpcode::SUBREG_TO_REG) { 787 EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned); 788 return; 789 } 790 791 // Handle COPY_TO_REGCLASS specially. 792 if (Opc == TargetOpcode::COPY_TO_REGCLASS) { 793 EmitCopyToRegClassNode(Node, VRBaseMap); 794 return; 795 } 796 797 // Handle REG_SEQUENCE specially. 798 if (Opc == TargetOpcode::REG_SEQUENCE) { 799 EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned); 800 return; 801 } 802 803 if (Opc == TargetOpcode::IMPLICIT_DEF) 804 // We want a unique VR for each IMPLICIT_DEF use. 805 return; 806 807 const MCInstrDesc &II = TII->get(Opc); 808 unsigned NumResults = CountResults(Node); 809 unsigned NumDefs = II.getNumDefs(); 810 const MCPhysReg *ScratchRegs = nullptr; 811 812 // Handle STACKMAP and PATCHPOINT specially and then use the generic code. 813 if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) { 814 // Stackmaps do not have arguments and do not preserve their calling 815 // convention. However, to simplify runtime support, they clobber the same 816 // scratch registers as AnyRegCC. 817 unsigned CC = CallingConv::AnyReg; 818 if (Opc == TargetOpcode::PATCHPOINT) { 819 CC = Node->getConstantOperandVal(PatchPointOpers::CCPos); 820 NumDefs = NumResults; 821 } 822 ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC); 823 } 824 825 unsigned NumImpUses = 0; 826 unsigned NodeOperands = 827 countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses); 828 bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() && 829 II.isVariadic() && II.variadicOpsAreDefs(); 830 bool HasPhysRegOuts = NumResults > NumDefs && 831 II.getImplicitDefs() != nullptr && !HasVRegVariadicDefs; 832 #ifndef NDEBUG 833 unsigned NumMIOperands = NodeOperands + NumResults; 834 if (II.isVariadic()) 835 assert(NumMIOperands >= II.getNumOperands() && 836 "Too few operands for a variadic node!"); 837 else 838 assert(NumMIOperands >= II.getNumOperands() && 839 NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() + 840 NumImpUses && 841 "#operands for dag node doesn't match .td file!"); 842 #endif 843 844 // Create the new machine instruction. 845 MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II); 846 847 // Add result register values for things that are defined by this 848 // instruction. 849 if (NumResults) { 850 CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap); 851 852 // Transfer any IR flags from the SDNode to the MachineInstr 853 MachineInstr *MI = MIB.getInstr(); 854 const SDNodeFlags Flags = Node->getFlags(); 855 if (Flags.hasNoSignedZeros()) 856 MI->setFlag(MachineInstr::MIFlag::FmNsz); 857 858 if (Flags.hasAllowReciprocal()) 859 MI->setFlag(MachineInstr::MIFlag::FmArcp); 860 861 if (Flags.hasNoNaNs()) 862 MI->setFlag(MachineInstr::MIFlag::FmNoNans); 863 864 if (Flags.hasNoInfs()) 865 MI->setFlag(MachineInstr::MIFlag::FmNoInfs); 866 867 if (Flags.hasAllowContract()) 868 MI->setFlag(MachineInstr::MIFlag::FmContract); 869 870 if (Flags.hasApproximateFuncs()) 871 MI->setFlag(MachineInstr::MIFlag::FmAfn); 872 873 if (Flags.hasAllowReassociation()) 874 MI->setFlag(MachineInstr::MIFlag::FmReassoc); 875 876 if (Flags.hasNoUnsignedWrap()) 877 MI->setFlag(MachineInstr::MIFlag::NoUWrap); 878 879 if (Flags.hasNoSignedWrap()) 880 MI->setFlag(MachineInstr::MIFlag::NoSWrap); 881 882 if (Flags.hasExact()) 883 MI->setFlag(MachineInstr::MIFlag::IsExact); 884 885 if (Flags.hasNoFPExcept()) 886 MI->setFlag(MachineInstr::MIFlag::NoFPExcept); 887 } 888 889 // Emit all of the actual operands of this instruction, adding them to the 890 // instruction as appropriate. 891 bool HasOptPRefs = NumDefs > NumResults; 892 assert((!HasOptPRefs || !HasPhysRegOuts) && 893 "Unable to cope with optional defs and phys regs defs!"); 894 unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0; 895 for (unsigned i = NumSkip; i != NodeOperands; ++i) 896 AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II, 897 VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned); 898 899 // Add scratch registers as implicit def and early clobber 900 if (ScratchRegs) 901 for (unsigned i = 0; ScratchRegs[i]; ++i) 902 MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine | 903 RegState::EarlyClobber); 904 905 // Set the memory reference descriptions of this instruction now that it is 906 // part of the function. 907 MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands()); 908 909 // Insert the instruction into position in the block. This needs to 910 // happen before any custom inserter hook is called so that the 911 // hook knows where in the block to insert the replacement code. 912 MBB->insert(InsertPos, MIB); 913 914 // The MachineInstr may also define physregs instead of virtregs. These 915 // physreg values can reach other instructions in different ways: 916 // 917 // 1. When there is a use of a Node value beyond the explicitly defined 918 // virtual registers, we emit a CopyFromReg for one of the implicitly 919 // defined physregs. This only happens when HasPhysRegOuts is true. 920 // 921 // 2. A CopyFromReg reading a physreg may be glued to this instruction. 922 // 923 // 3. A glued instruction may implicitly use a physreg. 924 // 925 // 4. A glued instruction may use a RegisterSDNode operand. 926 // 927 // Collect all the used physreg defs, and make sure that any unused physreg 928 // defs are marked as dead. 929 SmallVector<Register, 8> UsedRegs; 930 931 // Additional results must be physical register defs. 932 if (HasPhysRegOuts) { 933 for (unsigned i = NumDefs; i < NumResults; ++i) { 934 Register Reg = II.getImplicitDefs()[i - NumDefs]; 935 if (!Node->hasAnyUseOfValue(i)) 936 continue; 937 // This implicitly defined physreg has a use. 938 UsedRegs.push_back(Reg); 939 EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap); 940 } 941 } 942 943 // Scan the glue chain for any used physregs. 944 if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) { 945 for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) { 946 if (F->getOpcode() == ISD::CopyFromReg) { 947 UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg()); 948 continue; 949 } else if (F->getOpcode() == ISD::CopyToReg) { 950 // Skip CopyToReg nodes that are internal to the glue chain. 951 continue; 952 } 953 // Collect declared implicit uses. 954 const MCInstrDesc &MCID = TII->get(F->getMachineOpcode()); 955 UsedRegs.append(MCID.getImplicitUses(), 956 MCID.getImplicitUses() + MCID.getNumImplicitUses()); 957 // In addition to declared implicit uses, we must also check for 958 // direct RegisterSDNode operands. 959 for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i) 960 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) { 961 Register Reg = R->getReg(); 962 if (Reg.isPhysical()) 963 UsedRegs.push_back(Reg); 964 } 965 } 966 } 967 968 // Finally mark unused registers as dead. 969 if (!UsedRegs.empty() || II.getImplicitDefs() || II.hasOptionalDef()) 970 MIB->setPhysRegsDeadExcept(UsedRegs, *TRI); 971 972 // Run post-isel target hook to adjust this instruction if needed. 973 if (II.hasPostISelHook()) 974 TLI->AdjustInstrPostInstrSelection(*MIB, Node); 975 } 976 977 /// EmitSpecialNode - Generate machine code for a target-independent node and 978 /// needed dependencies. 979 void InstrEmitter:: 980 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned, 981 DenseMap<SDValue, Register> &VRBaseMap) { 982 switch (Node->getOpcode()) { 983 default: 984 #ifndef NDEBUG 985 Node->dump(); 986 #endif 987 llvm_unreachable("This target-independent node should have been selected!"); 988 case ISD::EntryToken: 989 llvm_unreachable("EntryToken should have been excluded from the schedule!"); 990 case ISD::MERGE_VALUES: 991 case ISD::TokenFactor: // fall thru 992 break; 993 case ISD::CopyToReg: { 994 Register DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg(); 995 SDValue SrcVal = Node->getOperand(2); 996 if (Register::isVirtualRegister(DestReg) && SrcVal.isMachineOpcode() && 997 SrcVal.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) { 998 // Instead building a COPY to that vreg destination, build an 999 // IMPLICIT_DEF instruction instead. 1000 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 1001 TII->get(TargetOpcode::IMPLICIT_DEF), DestReg); 1002 break; 1003 } 1004 Register SrcReg; 1005 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal)) 1006 SrcReg = R->getReg(); 1007 else 1008 SrcReg = getVR(SrcVal, VRBaseMap); 1009 1010 if (SrcReg == DestReg) // Coalesced away the copy? Ignore. 1011 break; 1012 1013 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY), 1014 DestReg).addReg(SrcReg); 1015 break; 1016 } 1017 case ISD::CopyFromReg: { 1018 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg(); 1019 EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap); 1020 break; 1021 } 1022 case ISD::EH_LABEL: 1023 case ISD::ANNOTATION_LABEL: { 1024 unsigned Opc = (Node->getOpcode() == ISD::EH_LABEL) 1025 ? TargetOpcode::EH_LABEL 1026 : TargetOpcode::ANNOTATION_LABEL; 1027 MCSymbol *S = cast<LabelSDNode>(Node)->getLabel(); 1028 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 1029 TII->get(Opc)).addSym(S); 1030 break; 1031 } 1032 1033 case ISD::LIFETIME_START: 1034 case ISD::LIFETIME_END: { 1035 unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ? 1036 TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END; 1037 1038 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1)); 1039 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp)) 1040 .addFrameIndex(FI->getIndex()); 1041 break; 1042 } 1043 1044 case ISD::INLINEASM: 1045 case ISD::INLINEASM_BR: { 1046 unsigned NumOps = Node->getNumOperands(); 1047 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue) 1048 --NumOps; // Ignore the glue operand. 1049 1050 // Create the inline asm machine instruction. 1051 unsigned TgtOpc = Node->getOpcode() == ISD::INLINEASM_BR 1052 ? TargetOpcode::INLINEASM_BR 1053 : TargetOpcode::INLINEASM; 1054 MachineInstrBuilder MIB = 1055 BuildMI(*MF, Node->getDebugLoc(), TII->get(TgtOpc)); 1056 1057 // Add the asm string as an external symbol operand. 1058 SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString); 1059 const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol(); 1060 MIB.addExternalSymbol(AsmStr); 1061 1062 // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore 1063 // bits. 1064 int64_t ExtraInfo = 1065 cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))-> 1066 getZExtValue(); 1067 MIB.addImm(ExtraInfo); 1068 1069 // Remember to operand index of the group flags. 1070 SmallVector<unsigned, 8> GroupIdx; 1071 1072 // Remember registers that are part of early-clobber defs. 1073 SmallVector<unsigned, 8> ECRegs; 1074 1075 // Add all of the operand registers to the instruction. 1076 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 1077 unsigned Flags = 1078 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue(); 1079 const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 1080 1081 GroupIdx.push_back(MIB->getNumOperands()); 1082 MIB.addImm(Flags); 1083 ++i; // Skip the ID value. 1084 1085 switch (InlineAsm::getKind(Flags)) { 1086 default: llvm_unreachable("Bad flags!"); 1087 case InlineAsm::Kind_RegDef: 1088 for (unsigned j = 0; j != NumVals; ++j, ++i) { 1089 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg(); 1090 // FIXME: Add dead flags for physical and virtual registers defined. 1091 // For now, mark physical register defs as implicit to help fast 1092 // regalloc. This makes inline asm look a lot like calls. 1093 MIB.addReg(Reg, 1094 RegState::Define | 1095 getImplRegState(Register::isPhysicalRegister(Reg))); 1096 } 1097 break; 1098 case InlineAsm::Kind_RegDefEarlyClobber: 1099 case InlineAsm::Kind_Clobber: 1100 for (unsigned j = 0; j != NumVals; ++j, ++i) { 1101 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg(); 1102 MIB.addReg(Reg, 1103 RegState::Define | RegState::EarlyClobber | 1104 getImplRegState(Register::isPhysicalRegister(Reg))); 1105 ECRegs.push_back(Reg); 1106 } 1107 break; 1108 case InlineAsm::Kind_RegUse: // Use of register. 1109 case InlineAsm::Kind_Imm: // Immediate. 1110 case InlineAsm::Kind_Mem: // Addressing mode. 1111 // The addressing mode has been selected, just add all of the 1112 // operands to the machine instruction. 1113 for (unsigned j = 0; j != NumVals; ++j, ++i) 1114 AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap, 1115 /*IsDebug=*/false, IsClone, IsCloned); 1116 1117 // Manually set isTied bits. 1118 if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) { 1119 unsigned DefGroup = 0; 1120 if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) { 1121 unsigned DefIdx = GroupIdx[DefGroup] + 1; 1122 unsigned UseIdx = GroupIdx.back() + 1; 1123 for (unsigned j = 0; j != NumVals; ++j) 1124 MIB->tieOperands(DefIdx + j, UseIdx + j); 1125 } 1126 } 1127 break; 1128 } 1129 } 1130 1131 // GCC inline assembly allows input operands to also be early-clobber 1132 // output operands (so long as the operand is written only after it's 1133 // used), but this does not match the semantics of our early-clobber flag. 1134 // If an early-clobber operand register is also an input operand register, 1135 // then remove the early-clobber flag. 1136 for (unsigned Reg : ECRegs) { 1137 if (MIB->readsRegister(Reg, TRI)) { 1138 MachineOperand *MO = 1139 MIB->findRegisterDefOperand(Reg, false, false, TRI); 1140 assert(MO && "No def operand for clobbered register?"); 1141 MO->setIsEarlyClobber(false); 1142 } 1143 } 1144 1145 // Get the mdnode from the asm if it exists and add it to the instruction. 1146 SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode); 1147 const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD(); 1148 if (MD) 1149 MIB.addMetadata(MD); 1150 1151 MBB->insert(InsertPos, MIB); 1152 break; 1153 } 1154 } 1155 } 1156 1157 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting 1158 /// at the given position in the given block. 1159 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb, 1160 MachineBasicBlock::iterator insertpos) 1161 : MF(mbb->getParent()), MRI(&MF->getRegInfo()), 1162 TII(MF->getSubtarget().getInstrInfo()), 1163 TRI(MF->getSubtarget().getRegisterInfo()), 1164 TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb), 1165 InsertPos(insertpos) {} 1166