1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===// 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 // Methods common to all machine instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/MachineInstr.h" 15 #include "llvm/ADT/FoldingSet.h" 16 #include "llvm/ADT/Hashing.h" 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/CodeGen/MachineConstantPool.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineInstrBuilder.h" 21 #include "llvm/CodeGen/MachineMemOperand.h" 22 #include "llvm/CodeGen/MachineModuleInfo.h" 23 #include "llvm/CodeGen/MachineRegisterInfo.h" 24 #include "llvm/CodeGen/PseudoSourceValue.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DebugInfo.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/InlineAsm.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/Metadata.h" 31 #include "llvm/IR/Module.h" 32 #include "llvm/IR/ModuleSlotTracker.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/IR/Value.h" 35 #include "llvm/MC/MCInstrDesc.h" 36 #include "llvm/MC/MCSymbol.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/MathExtras.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/Target/TargetInstrInfo.h" 43 #include "llvm/Target/TargetMachine.h" 44 #include "llvm/Target/TargetRegisterInfo.h" 45 #include "llvm/Target/TargetSubtargetInfo.h" 46 using namespace llvm; 47 48 static cl::opt<bool> PrintWholeRegMask( 49 "print-whole-regmask", 50 cl::desc("Print the full contents of regmask operands in IR dumps"), 51 cl::init(true), cl::Hidden); 52 53 //===----------------------------------------------------------------------===// 54 // MachineOperand Implementation 55 //===----------------------------------------------------------------------===// 56 57 void MachineOperand::setReg(unsigned Reg) { 58 if (getReg() == Reg) return; // No change. 59 60 // Otherwise, we have to change the register. If this operand is embedded 61 // into a machine function, we need to update the old and new register's 62 // use/def lists. 63 if (MachineInstr *MI = getParent()) 64 if (MachineBasicBlock *MBB = MI->getParent()) 65 if (MachineFunction *MF = MBB->getParent()) { 66 MachineRegisterInfo &MRI = MF->getRegInfo(); 67 MRI.removeRegOperandFromUseList(this); 68 SmallContents.RegNo = Reg; 69 MRI.addRegOperandToUseList(this); 70 return; 71 } 72 73 // Otherwise, just change the register, no problem. :) 74 SmallContents.RegNo = Reg; 75 } 76 77 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx, 78 const TargetRegisterInfo &TRI) { 79 assert(TargetRegisterInfo::isVirtualRegister(Reg)); 80 if (SubIdx && getSubReg()) 81 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg()); 82 setReg(Reg); 83 if (SubIdx) 84 setSubReg(SubIdx); 85 } 86 87 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) { 88 assert(TargetRegisterInfo::isPhysicalRegister(Reg)); 89 if (getSubReg()) { 90 Reg = TRI.getSubReg(Reg, getSubReg()); 91 // Note that getSubReg() may return 0 if the sub-register doesn't exist. 92 // That won't happen in legal code. 93 setSubReg(0); 94 } 95 setReg(Reg); 96 } 97 98 /// Change a def to a use, or a use to a def. 99 void MachineOperand::setIsDef(bool Val) { 100 assert(isReg() && "Wrong MachineOperand accessor"); 101 assert((!Val || !isDebug()) && "Marking a debug operation as def"); 102 if (IsDef == Val) 103 return; 104 // MRI may keep uses and defs in different list positions. 105 if (MachineInstr *MI = getParent()) 106 if (MachineBasicBlock *MBB = MI->getParent()) 107 if (MachineFunction *MF = MBB->getParent()) { 108 MachineRegisterInfo &MRI = MF->getRegInfo(); 109 MRI.removeRegOperandFromUseList(this); 110 IsDef = Val; 111 MRI.addRegOperandToUseList(this); 112 return; 113 } 114 IsDef = Val; 115 } 116 117 // If this operand is currently a register operand, and if this is in a 118 // function, deregister the operand from the register's use/def list. 119 void MachineOperand::removeRegFromUses() { 120 if (!isReg() || !isOnRegUseList()) 121 return; 122 123 if (MachineInstr *MI = getParent()) { 124 if (MachineBasicBlock *MBB = MI->getParent()) { 125 if (MachineFunction *MF = MBB->getParent()) 126 MF->getRegInfo().removeRegOperandFromUseList(this); 127 } 128 } 129 } 130 131 /// ChangeToImmediate - Replace this operand with a new immediate operand of 132 /// the specified value. If an operand is known to be an immediate already, 133 /// the setImm method should be used. 134 void MachineOperand::ChangeToImmediate(int64_t ImmVal) { 135 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm"); 136 137 removeRegFromUses(); 138 139 OpKind = MO_Immediate; 140 Contents.ImmVal = ImmVal; 141 } 142 143 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) { 144 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm"); 145 146 removeRegFromUses(); 147 148 OpKind = MO_FPImmediate; 149 Contents.CFP = FPImm; 150 } 151 152 void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) { 153 assert((!isReg() || !isTied()) && 154 "Cannot change a tied operand into an external symbol"); 155 156 removeRegFromUses(); 157 158 OpKind = MO_ExternalSymbol; 159 Contents.OffsetedInfo.Val.SymbolName = SymName; 160 setOffset(0); // Offset is always 0. 161 setTargetFlags(TargetFlags); 162 } 163 164 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) { 165 assert((!isReg() || !isTied()) && 166 "Cannot change a tied operand into an MCSymbol"); 167 168 removeRegFromUses(); 169 170 OpKind = MO_MCSymbol; 171 Contents.Sym = Sym; 172 } 173 174 /// ChangeToRegister - Replace this operand with a new register operand of 175 /// the specified value. If an operand is known to be an register already, 176 /// the setReg method should be used. 177 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp, 178 bool isKill, bool isDead, bool isUndef, 179 bool isDebug) { 180 MachineRegisterInfo *RegInfo = nullptr; 181 if (MachineInstr *MI = getParent()) 182 if (MachineBasicBlock *MBB = MI->getParent()) 183 if (MachineFunction *MF = MBB->getParent()) 184 RegInfo = &MF->getRegInfo(); 185 // If this operand is already a register operand, remove it from the 186 // register's use/def lists. 187 bool WasReg = isReg(); 188 if (RegInfo && WasReg) 189 RegInfo->removeRegOperandFromUseList(this); 190 191 // Change this to a register and set the reg#. 192 OpKind = MO_Register; 193 SmallContents.RegNo = Reg; 194 SubReg_TargetFlags = 0; 195 IsDef = isDef; 196 IsImp = isImp; 197 IsKill = isKill; 198 IsDead = isDead; 199 IsUndef = isUndef; 200 IsInternalRead = false; 201 IsEarlyClobber = false; 202 IsDebug = isDebug; 203 // Ensure isOnRegUseList() returns false. 204 Contents.Reg.Prev = nullptr; 205 // Preserve the tie when the operand was already a register. 206 if (!WasReg) 207 TiedTo = 0; 208 209 // If this operand is embedded in a function, add the operand to the 210 // register's use/def list. 211 if (RegInfo) 212 RegInfo->addRegOperandToUseList(this); 213 } 214 215 /// isIdenticalTo - Return true if this operand is identical to the specified 216 /// operand. Note that this should stay in sync with the hash_value overload 217 /// below. 218 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const { 219 if (getType() != Other.getType() || 220 getTargetFlags() != Other.getTargetFlags()) 221 return false; 222 223 switch (getType()) { 224 case MachineOperand::MO_Register: 225 return getReg() == Other.getReg() && isDef() == Other.isDef() && 226 getSubReg() == Other.getSubReg(); 227 case MachineOperand::MO_Immediate: 228 return getImm() == Other.getImm(); 229 case MachineOperand::MO_CImmediate: 230 return getCImm() == Other.getCImm(); 231 case MachineOperand::MO_FPImmediate: 232 return getFPImm() == Other.getFPImm(); 233 case MachineOperand::MO_MachineBasicBlock: 234 return getMBB() == Other.getMBB(); 235 case MachineOperand::MO_FrameIndex: 236 return getIndex() == Other.getIndex(); 237 case MachineOperand::MO_ConstantPoolIndex: 238 case MachineOperand::MO_TargetIndex: 239 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset(); 240 case MachineOperand::MO_JumpTableIndex: 241 return getIndex() == Other.getIndex(); 242 case MachineOperand::MO_GlobalAddress: 243 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset(); 244 case MachineOperand::MO_ExternalSymbol: 245 return !strcmp(getSymbolName(), Other.getSymbolName()) && 246 getOffset() == Other.getOffset(); 247 case MachineOperand::MO_BlockAddress: 248 return getBlockAddress() == Other.getBlockAddress() && 249 getOffset() == Other.getOffset(); 250 case MachineOperand::MO_RegisterMask: 251 case MachineOperand::MO_RegisterLiveOut: 252 return getRegMask() == Other.getRegMask(); 253 case MachineOperand::MO_MCSymbol: 254 return getMCSymbol() == Other.getMCSymbol(); 255 case MachineOperand::MO_CFIIndex: 256 return getCFIIndex() == Other.getCFIIndex(); 257 case MachineOperand::MO_Metadata: 258 return getMetadata() == Other.getMetadata(); 259 } 260 llvm_unreachable("Invalid machine operand type"); 261 } 262 263 // Note: this must stay exactly in sync with isIdenticalTo above. 264 hash_code llvm::hash_value(const MachineOperand &MO) { 265 switch (MO.getType()) { 266 case MachineOperand::MO_Register: 267 // Register operands don't have target flags. 268 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef()); 269 case MachineOperand::MO_Immediate: 270 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm()); 271 case MachineOperand::MO_CImmediate: 272 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm()); 273 case MachineOperand::MO_FPImmediate: 274 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm()); 275 case MachineOperand::MO_MachineBasicBlock: 276 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB()); 277 case MachineOperand::MO_FrameIndex: 278 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex()); 279 case MachineOperand::MO_ConstantPoolIndex: 280 case MachineOperand::MO_TargetIndex: 281 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(), 282 MO.getOffset()); 283 case MachineOperand::MO_JumpTableIndex: 284 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex()); 285 case MachineOperand::MO_ExternalSymbol: 286 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(), 287 MO.getSymbolName()); 288 case MachineOperand::MO_GlobalAddress: 289 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(), 290 MO.getOffset()); 291 case MachineOperand::MO_BlockAddress: 292 return hash_combine(MO.getType(), MO.getTargetFlags(), 293 MO.getBlockAddress(), MO.getOffset()); 294 case MachineOperand::MO_RegisterMask: 295 case MachineOperand::MO_RegisterLiveOut: 296 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask()); 297 case MachineOperand::MO_Metadata: 298 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata()); 299 case MachineOperand::MO_MCSymbol: 300 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol()); 301 case MachineOperand::MO_CFIIndex: 302 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex()); 303 } 304 llvm_unreachable("Invalid machine operand type"); 305 } 306 307 void MachineOperand::print(raw_ostream &OS, 308 const TargetRegisterInfo *TRI) const { 309 ModuleSlotTracker DummyMST(nullptr); 310 print(OS, DummyMST, TRI); 311 } 312 313 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST, 314 const TargetRegisterInfo *TRI) const { 315 switch (getType()) { 316 case MachineOperand::MO_Register: 317 OS << PrintReg(getReg(), TRI, getSubReg()); 318 319 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() || 320 isInternalRead() || isEarlyClobber() || isTied()) { 321 OS << '<'; 322 bool NeedComma = false; 323 if (isDef()) { 324 if (NeedComma) OS << ','; 325 if (isEarlyClobber()) 326 OS << "earlyclobber,"; 327 if (isImplicit()) 328 OS << "imp-"; 329 OS << "def"; 330 NeedComma = true; 331 // <def,read-undef> only makes sense when getSubReg() is set. 332 // Don't clutter the output otherwise. 333 if (isUndef() && getSubReg()) 334 OS << ",read-undef"; 335 } else if (isImplicit()) { 336 OS << "imp-use"; 337 NeedComma = true; 338 } 339 340 if (isKill()) { 341 if (NeedComma) OS << ','; 342 OS << "kill"; 343 NeedComma = true; 344 } 345 if (isDead()) { 346 if (NeedComma) OS << ','; 347 OS << "dead"; 348 NeedComma = true; 349 } 350 if (isUndef() && isUse()) { 351 if (NeedComma) OS << ','; 352 OS << "undef"; 353 NeedComma = true; 354 } 355 if (isInternalRead()) { 356 if (NeedComma) OS << ','; 357 OS << "internal"; 358 NeedComma = true; 359 } 360 if (isTied()) { 361 if (NeedComma) OS << ','; 362 OS << "tied"; 363 if (TiedTo != 15) 364 OS << unsigned(TiedTo - 1); 365 } 366 OS << '>'; 367 } 368 break; 369 case MachineOperand::MO_Immediate: 370 OS << getImm(); 371 break; 372 case MachineOperand::MO_CImmediate: 373 getCImm()->getValue().print(OS, false); 374 break; 375 case MachineOperand::MO_FPImmediate: 376 if (getFPImm()->getType()->isFloatTy()) { 377 OS << getFPImm()->getValueAPF().convertToFloat(); 378 } else if (getFPImm()->getType()->isHalfTy()) { 379 APFloat APF = getFPImm()->getValueAPF(); 380 bool Unused; 381 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &Unused); 382 OS << "half " << APF.convertToFloat(); 383 } else { 384 OS << getFPImm()->getValueAPF().convertToDouble(); 385 } 386 break; 387 case MachineOperand::MO_MachineBasicBlock: 388 OS << "<BB#" << getMBB()->getNumber() << ">"; 389 break; 390 case MachineOperand::MO_FrameIndex: 391 OS << "<fi#" << getIndex() << '>'; 392 break; 393 case MachineOperand::MO_ConstantPoolIndex: 394 OS << "<cp#" << getIndex(); 395 if (getOffset()) OS << "+" << getOffset(); 396 OS << '>'; 397 break; 398 case MachineOperand::MO_TargetIndex: 399 OS << "<ti#" << getIndex(); 400 if (getOffset()) OS << "+" << getOffset(); 401 OS << '>'; 402 break; 403 case MachineOperand::MO_JumpTableIndex: 404 OS << "<jt#" << getIndex() << '>'; 405 break; 406 case MachineOperand::MO_GlobalAddress: 407 OS << "<ga:"; 408 getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST); 409 if (getOffset()) OS << "+" << getOffset(); 410 OS << '>'; 411 break; 412 case MachineOperand::MO_ExternalSymbol: 413 OS << "<es:" << getSymbolName(); 414 if (getOffset()) OS << "+" << getOffset(); 415 OS << '>'; 416 break; 417 case MachineOperand::MO_BlockAddress: 418 OS << '<'; 419 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST); 420 if (getOffset()) OS << "+" << getOffset(); 421 OS << '>'; 422 break; 423 case MachineOperand::MO_RegisterMask: { 424 unsigned NumRegsInMask = 0; 425 unsigned NumRegsEmitted = 0; 426 OS << "<regmask"; 427 for (unsigned i = 0; i < TRI->getNumRegs(); ++i) { 428 unsigned MaskWord = i / 32; 429 unsigned MaskBit = i % 32; 430 if (getRegMask()[MaskWord] & (1 << MaskBit)) { 431 if (PrintWholeRegMask || NumRegsEmitted <= 10) { 432 OS << " " << PrintReg(i, TRI); 433 NumRegsEmitted++; 434 } 435 NumRegsInMask++; 436 } 437 } 438 if (NumRegsEmitted != NumRegsInMask) 439 OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more..."; 440 OS << ">"; 441 break; 442 } 443 case MachineOperand::MO_RegisterLiveOut: 444 OS << "<regliveout>"; 445 break; 446 case MachineOperand::MO_Metadata: 447 OS << '<'; 448 getMetadata()->printAsOperand(OS, MST); 449 OS << '>'; 450 break; 451 case MachineOperand::MO_MCSymbol: 452 OS << "<MCSym=" << *getMCSymbol() << '>'; 453 break; 454 case MachineOperand::MO_CFIIndex: 455 OS << "<call frame instruction>"; 456 break; 457 } 458 459 if (unsigned TF = getTargetFlags()) 460 OS << "[TF=" << TF << ']'; 461 } 462 463 //===----------------------------------------------------------------------===// 464 // MachineMemOperand Implementation 465 //===----------------------------------------------------------------------===// 466 467 /// getAddrSpace - Return the LLVM IR address space number that this pointer 468 /// points into. 469 unsigned MachinePointerInfo::getAddrSpace() const { 470 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0; 471 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace(); 472 } 473 474 /// getConstantPool - Return a MachinePointerInfo record that refers to the 475 /// constant pool. 476 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) { 477 return MachinePointerInfo(MF.getPSVManager().getConstantPool()); 478 } 479 480 /// getFixedStack - Return a MachinePointerInfo record that refers to the 481 /// the specified FrameIndex. 482 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF, 483 int FI, int64_t Offset) { 484 return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset); 485 } 486 487 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) { 488 return MachinePointerInfo(MF.getPSVManager().getJumpTable()); 489 } 490 491 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) { 492 return MachinePointerInfo(MF.getPSVManager().getGOT()); 493 } 494 495 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF, 496 int64_t Offset) { 497 return MachinePointerInfo(MF.getPSVManager().getStack(), Offset); 498 } 499 500 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f, 501 uint64_t s, unsigned int a, 502 const AAMDNodes &AAInfo, 503 const MDNode *Ranges) 504 : PtrInfo(ptrinfo), Size(s), 505 Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)), 506 AAInfo(AAInfo), Ranges(Ranges) { 507 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() || 508 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) && 509 "invalid pointer value"); 510 assert(getBaseAlignment() == a && "Alignment is not a power of 2!"); 511 assert((isLoad() || isStore()) && "Not a load/store!"); 512 } 513 514 /// Profile - Gather unique data for the object. 515 /// 516 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const { 517 ID.AddInteger(getOffset()); 518 ID.AddInteger(Size); 519 ID.AddPointer(getOpaqueValue()); 520 ID.AddInteger(Flags); 521 } 522 523 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) { 524 // The Value and Offset may differ due to CSE. But the flags and size 525 // should be the same. 526 assert(MMO->getFlags() == getFlags() && "Flags mismatch!"); 527 assert(MMO->getSize() == getSize() && "Size mismatch!"); 528 529 if (MMO->getBaseAlignment() >= getBaseAlignment()) { 530 // Update the alignment value. 531 Flags = (Flags & ((1 << MOMaxBits) - 1)) | 532 ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits); 533 // Also update the base and offset, because the new alignment may 534 // not be applicable with the old ones. 535 PtrInfo = MMO->PtrInfo; 536 } 537 } 538 539 /// getAlignment - Return the minimum known alignment in bytes of the 540 /// actual memory reference. 541 uint64_t MachineMemOperand::getAlignment() const { 542 return MinAlign(getBaseAlignment(), getOffset()); 543 } 544 545 void MachineMemOperand::print(raw_ostream &OS) const { 546 ModuleSlotTracker DummyMST(nullptr); 547 print(OS, DummyMST); 548 } 549 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const { 550 assert((isLoad() || isStore()) && 551 "SV has to be a load, store or both."); 552 553 if (isVolatile()) 554 OS << "Volatile "; 555 556 if (isLoad()) 557 OS << "LD"; 558 if (isStore()) 559 OS << "ST"; 560 OS << getSize(); 561 562 // Print the address information. 563 OS << "["; 564 if (const Value *V = getValue()) 565 V->printAsOperand(OS, /*PrintType=*/false, MST); 566 else if (const PseudoSourceValue *PSV = getPseudoValue()) 567 PSV->printCustom(OS); 568 else 569 OS << "<unknown>"; 570 571 unsigned AS = getAddrSpace(); 572 if (AS != 0) 573 OS << "(addrspace=" << AS << ')'; 574 575 // If the alignment of the memory reference itself differs from the alignment 576 // of the base pointer, print the base alignment explicitly, next to the base 577 // pointer. 578 if (getBaseAlignment() != getAlignment()) 579 OS << "(align=" << getBaseAlignment() << ")"; 580 581 if (getOffset() != 0) 582 OS << "+" << getOffset(); 583 OS << "]"; 584 585 // Print the alignment of the reference. 586 if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize()) 587 OS << "(align=" << getAlignment() << ")"; 588 589 // Print TBAA info. 590 if (const MDNode *TBAAInfo = getAAInfo().TBAA) { 591 OS << "(tbaa="; 592 if (TBAAInfo->getNumOperands() > 0) 593 TBAAInfo->getOperand(0)->printAsOperand(OS, MST); 594 else 595 OS << "<unknown>"; 596 OS << ")"; 597 } 598 599 // Print AA scope info. 600 if (const MDNode *ScopeInfo = getAAInfo().Scope) { 601 OS << "(alias.scope="; 602 if (ScopeInfo->getNumOperands() > 0) 603 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) { 604 ScopeInfo->getOperand(i)->printAsOperand(OS, MST); 605 if (i != ie-1) 606 OS << ","; 607 } 608 else 609 OS << "<unknown>"; 610 OS << ")"; 611 } 612 613 // Print AA noalias scope info. 614 if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) { 615 OS << "(noalias="; 616 if (NoAliasInfo->getNumOperands() > 0) 617 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) { 618 NoAliasInfo->getOperand(i)->printAsOperand(OS, MST); 619 if (i != ie-1) 620 OS << ","; 621 } 622 else 623 OS << "<unknown>"; 624 OS << ")"; 625 } 626 627 // Print nontemporal info. 628 if (isNonTemporal()) 629 OS << "(nontemporal)"; 630 631 if (isInvariant()) 632 OS << "(invariant)"; 633 } 634 635 //===----------------------------------------------------------------------===// 636 // MachineInstr Implementation 637 //===----------------------------------------------------------------------===// 638 639 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) { 640 if (MCID->ImplicitDefs) 641 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; 642 ++ImpDefs) 643 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true)); 644 if (MCID->ImplicitUses) 645 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses; 646 ++ImpUses) 647 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true)); 648 } 649 650 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the 651 /// implicit operands. It reserves space for the number of operands specified by 652 /// the MCInstrDesc. 653 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid, 654 DebugLoc dl, bool NoImp) 655 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0), Flags(0), 656 AsmPrinterFlags(0), NumMemRefs(0), MemRefs(nullptr), 657 debugLoc(std::move(dl)) 658 #ifdef LLVM_BUILD_GLOBAL_ISEL 659 , 660 Ty(nullptr) 661 #endif 662 { 663 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor"); 664 665 // Reserve space for the expected number of operands. 666 if (unsigned NumOps = MCID->getNumOperands() + 667 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) { 668 CapOperands = OperandCapacity::get(NumOps); 669 Operands = MF.allocateOperandArray(CapOperands); 670 } 671 672 if (!NoImp) 673 addImplicitDefUseOperands(MF); 674 } 675 676 /// MachineInstr ctor - Copies MachineInstr arg exactly 677 /// 678 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI) 679 : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0), 680 Flags(0), AsmPrinterFlags(0), NumMemRefs(MI.NumMemRefs), 681 MemRefs(MI.MemRefs), debugLoc(MI.getDebugLoc()) 682 #ifdef LLVM_BUILD_GLOBAL_ISEL 683 , 684 Ty(nullptr) 685 #endif 686 { 687 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor"); 688 689 CapOperands = OperandCapacity::get(MI.getNumOperands()); 690 Operands = MF.allocateOperandArray(CapOperands); 691 692 // Copy operands. 693 for (const MachineOperand &MO : MI.operands()) 694 addOperand(MF, MO); 695 696 // Copy all the sensible flags. 697 setFlags(MI.Flags); 698 } 699 700 /// getRegInfo - If this instruction is embedded into a MachineFunction, 701 /// return the MachineRegisterInfo object for the current function, otherwise 702 /// return null. 703 MachineRegisterInfo *MachineInstr::getRegInfo() { 704 if (MachineBasicBlock *MBB = getParent()) 705 return &MBB->getParent()->getRegInfo(); 706 return nullptr; 707 } 708 709 // Implement dummy setter and getter for type when 710 // global-isel is not built. 711 // The proper implementation is WIP and is tracked here: 712 // PR26576. 713 #ifndef LLVM_BUILD_GLOBAL_ISEL 714 void MachineInstr::setType(Type *Ty) {} 715 716 Type *MachineInstr::getType() const { return nullptr; } 717 718 #else 719 void MachineInstr::setType(Type *Ty) { 720 assert((!Ty || isPreISelGenericOpcode(getOpcode())) && 721 "Non generic instructions are not supposed to be typed"); 722 this->Ty = Ty; 723 } 724 725 Type *MachineInstr::getType() const { return Ty; } 726 #endif // LLVM_BUILD_GLOBAL_ISEL 727 728 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in 729 /// this instruction from their respective use lists. This requires that the 730 /// operands already be on their use lists. 731 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) { 732 for (MachineOperand &MO : operands()) 733 if (MO.isReg()) 734 MRI.removeRegOperandFromUseList(&MO); 735 } 736 737 /// AddRegOperandsToUseLists - Add all of the register operands in 738 /// this instruction from their respective use lists. This requires that the 739 /// operands not be on their use lists yet. 740 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) { 741 for (MachineOperand &MO : operands()) 742 if (MO.isReg()) 743 MRI.addRegOperandToUseList(&MO); 744 } 745 746 void MachineInstr::addOperand(const MachineOperand &Op) { 747 MachineBasicBlock *MBB = getParent(); 748 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs"); 749 MachineFunction *MF = MBB->getParent(); 750 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs"); 751 addOperand(*MF, Op); 752 } 753 754 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping 755 /// ranges. If MRI is non-null also update use-def chains. 756 static void moveOperands(MachineOperand *Dst, MachineOperand *Src, 757 unsigned NumOps, MachineRegisterInfo *MRI) { 758 if (MRI) 759 return MRI->moveOperands(Dst, Src, NumOps); 760 761 // MachineOperand is a trivially copyable type so we can just use memmove. 762 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand)); 763 } 764 765 /// addOperand - Add the specified operand to the instruction. If it is an 766 /// implicit operand, it is added to the end of the operand list. If it is 767 /// an explicit operand it is added at the end of the explicit operand list 768 /// (before the first implicit operand). 769 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) { 770 assert(MCID && "Cannot add operands before providing an instr descriptor"); 771 772 // Check if we're adding one of our existing operands. 773 if (&Op >= Operands && &Op < Operands + NumOperands) { 774 // This is unusual: MI->addOperand(MI->getOperand(i)). 775 // If adding Op requires reallocating or moving existing operands around, 776 // the Op reference could go stale. Support it by copying Op. 777 MachineOperand CopyOp(Op); 778 return addOperand(MF, CopyOp); 779 } 780 781 // Find the insert location for the new operand. Implicit registers go at 782 // the end, everything else goes before the implicit regs. 783 // 784 // FIXME: Allow mixed explicit and implicit operands on inline asm. 785 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as 786 // implicit-defs, but they must not be moved around. See the FIXME in 787 // InstrEmitter.cpp. 788 unsigned OpNo = getNumOperands(); 789 bool isImpReg = Op.isReg() && Op.isImplicit(); 790 if (!isImpReg && !isInlineAsm()) { 791 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) { 792 --OpNo; 793 assert(!Operands[OpNo].isTied() && "Cannot move tied operands"); 794 } 795 } 796 797 #ifndef NDEBUG 798 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata; 799 // OpNo now points as the desired insertion point. Unless this is a variadic 800 // instruction, only implicit regs are allowed beyond MCID->getNumOperands(). 801 // RegMask operands go between the explicit and implicit operands. 802 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() || 803 OpNo < MCID->getNumOperands() || isMetaDataOp) && 804 "Trying to add an operand to a machine instr that is already done!"); 805 #endif 806 807 MachineRegisterInfo *MRI = getRegInfo(); 808 809 // Determine if the Operands array needs to be reallocated. 810 // Save the old capacity and operand array. 811 OperandCapacity OldCap = CapOperands; 812 MachineOperand *OldOperands = Operands; 813 if (!OldOperands || OldCap.getSize() == getNumOperands()) { 814 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1); 815 Operands = MF.allocateOperandArray(CapOperands); 816 // Move the operands before the insertion point. 817 if (OpNo) 818 moveOperands(Operands, OldOperands, OpNo, MRI); 819 } 820 821 // Move the operands following the insertion point. 822 if (OpNo != NumOperands) 823 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo, 824 MRI); 825 ++NumOperands; 826 827 // Deallocate the old operand array. 828 if (OldOperands != Operands && OldOperands) 829 MF.deallocateOperandArray(OldCap, OldOperands); 830 831 // Copy Op into place. It still needs to be inserted into the MRI use lists. 832 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op); 833 NewMO->ParentMI = this; 834 835 // When adding a register operand, tell MRI about it. 836 if (NewMO->isReg()) { 837 // Ensure isOnRegUseList() returns false, regardless of Op's status. 838 NewMO->Contents.Reg.Prev = nullptr; 839 // Ignore existing ties. This is not a property that can be copied. 840 NewMO->TiedTo = 0; 841 // Add the new operand to MRI, but only for instructions in an MBB. 842 if (MRI) 843 MRI->addRegOperandToUseList(NewMO); 844 // The MCID operand information isn't accurate until we start adding 845 // explicit operands. The implicit operands are added first, then the 846 // explicits are inserted before them. 847 if (!isImpReg) { 848 // Tie uses to defs as indicated in MCInstrDesc. 849 if (NewMO->isUse()) { 850 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO); 851 if (DefIdx != -1) 852 tieOperands(DefIdx, OpNo); 853 } 854 // If the register operand is flagged as early, mark the operand as such. 855 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1) 856 NewMO->setIsEarlyClobber(true); 857 } 858 } 859 } 860 861 /// RemoveOperand - Erase an operand from an instruction, leaving it with one 862 /// fewer operand than it started with. 863 /// 864 void MachineInstr::RemoveOperand(unsigned OpNo) { 865 assert(OpNo < getNumOperands() && "Invalid operand number"); 866 untieRegOperand(OpNo); 867 868 #ifndef NDEBUG 869 // Moving tied operands would break the ties. 870 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i) 871 if (Operands[i].isReg()) 872 assert(!Operands[i].isTied() && "Cannot move tied operands"); 873 #endif 874 875 MachineRegisterInfo *MRI = getRegInfo(); 876 if (MRI && Operands[OpNo].isReg()) 877 MRI->removeRegOperandFromUseList(Operands + OpNo); 878 879 // Don't call the MachineOperand destructor. A lot of this code depends on 880 // MachineOperand having a trivial destructor anyway, and adding a call here 881 // wouldn't make it 'destructor-correct'. 882 883 if (unsigned N = NumOperands - 1 - OpNo) 884 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI); 885 --NumOperands; 886 } 887 888 /// addMemOperand - Add a MachineMemOperand to the machine instruction. 889 /// This function should be used only occasionally. The setMemRefs function 890 /// is the primary method for setting up a MachineInstr's MemRefs list. 891 void MachineInstr::addMemOperand(MachineFunction &MF, 892 MachineMemOperand *MO) { 893 mmo_iterator OldMemRefs = MemRefs; 894 unsigned OldNumMemRefs = NumMemRefs; 895 896 unsigned NewNum = NumMemRefs + 1; 897 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum); 898 899 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs); 900 NewMemRefs[NewNum - 1] = MO; 901 setMemRefs(NewMemRefs, NewMemRefs + NewNum); 902 } 903 904 /// Check to see if the MMOs pointed to by the two MemRefs arrays are 905 /// identical. 906 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) { 907 auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end(); 908 auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end(); 909 if ((E1 - I1) != (E2 - I2)) 910 return false; 911 for (; I1 != E1; ++I1, ++I2) { 912 if (**I1 != **I2) 913 return false; 914 } 915 return true; 916 } 917 918 std::pair<MachineInstr::mmo_iterator, unsigned> 919 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) { 920 921 // If either of the incoming memrefs are empty, we must be conservative and 922 // treat this as if we've exhausted our space for memrefs and dropped them. 923 if (memoperands_empty() || Other.memoperands_empty()) 924 return std::make_pair(nullptr, 0); 925 926 // If both instructions have identical memrefs, we don't need to merge them. 927 // Since many instructions have a single memref, and we tend to merge things 928 // like pairs of loads from the same location, this catches a large number of 929 // cases in practice. 930 if (hasIdenticalMMOs(*this, Other)) 931 return std::make_pair(MemRefs, NumMemRefs); 932 933 // TODO: consider uniquing elements within the operand lists to reduce 934 // space usage and fall back to conservative information less often. 935 size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs; 936 937 // If we don't have enough room to store this many memrefs, be conservative 938 // and drop them. Otherwise, we'd fail asserts when trying to add them to 939 // the new instruction. 940 if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs)) 941 return std::make_pair(nullptr, 0); 942 943 MachineFunction *MF = getParent()->getParent(); 944 mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs); 945 mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(), 946 MemBegin); 947 MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(), 948 MemEnd); 949 assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs && 950 "missing memrefs"); 951 952 return std::make_pair(MemBegin, CombinedNumMemRefs); 953 } 954 955 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const { 956 assert(!isBundledWithPred() && "Must be called on bundle header"); 957 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) { 958 if (MII->getDesc().getFlags() & Mask) { 959 if (Type == AnyInBundle) 960 return true; 961 } else { 962 if (Type == AllInBundle && !MII->isBundle()) 963 return false; 964 } 965 // This was the last instruction in the bundle. 966 if (!MII->isBundledWithSucc()) 967 return Type == AllInBundle; 968 } 969 } 970 971 bool MachineInstr::isIdenticalTo(const MachineInstr &Other, 972 MICheckType Check) const { 973 // If opcodes or number of operands are not the same then the two 974 // instructions are obviously not identical. 975 if (Other.getOpcode() != getOpcode() || 976 Other.getNumOperands() != getNumOperands()) 977 return false; 978 979 if (isBundle()) { 980 // Both instructions are bundles, compare MIs inside the bundle. 981 MachineBasicBlock::const_instr_iterator I1 = getIterator(); 982 MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end(); 983 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator(); 984 MachineBasicBlock::const_instr_iterator E2 = Other.getParent()->instr_end(); 985 while (++I1 != E1 && I1->isInsideBundle()) { 986 ++I2; 987 if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(*I2, Check)) 988 return false; 989 } 990 } 991 992 // Check operands to make sure they match. 993 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 994 const MachineOperand &MO = getOperand(i); 995 const MachineOperand &OMO = Other.getOperand(i); 996 if (!MO.isReg()) { 997 if (!MO.isIdenticalTo(OMO)) 998 return false; 999 continue; 1000 } 1001 1002 // Clients may or may not want to ignore defs when testing for equality. 1003 // For example, machine CSE pass only cares about finding common 1004 // subexpressions, so it's safe to ignore virtual register defs. 1005 if (MO.isDef()) { 1006 if (Check == IgnoreDefs) 1007 continue; 1008 else if (Check == IgnoreVRegDefs) { 1009 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) || 1010 TargetRegisterInfo::isPhysicalRegister(OMO.getReg())) 1011 if (MO.getReg() != OMO.getReg()) 1012 return false; 1013 } else { 1014 if (!MO.isIdenticalTo(OMO)) 1015 return false; 1016 if (Check == CheckKillDead && MO.isDead() != OMO.isDead()) 1017 return false; 1018 } 1019 } else { 1020 if (!MO.isIdenticalTo(OMO)) 1021 return false; 1022 if (Check == CheckKillDead && MO.isKill() != OMO.isKill()) 1023 return false; 1024 } 1025 } 1026 // If DebugLoc does not match then two dbg.values are not identical. 1027 if (isDebugValue()) 1028 if (getDebugLoc() && Other.getDebugLoc() && 1029 getDebugLoc() != Other.getDebugLoc()) 1030 return false; 1031 return true; 1032 } 1033 1034 MachineInstr *MachineInstr::removeFromParent() { 1035 assert(getParent() && "Not embedded in a basic block!"); 1036 return getParent()->remove(this); 1037 } 1038 1039 MachineInstr *MachineInstr::removeFromBundle() { 1040 assert(getParent() && "Not embedded in a basic block!"); 1041 return getParent()->remove_instr(this); 1042 } 1043 1044 void MachineInstr::eraseFromParent() { 1045 assert(getParent() && "Not embedded in a basic block!"); 1046 getParent()->erase(this); 1047 } 1048 1049 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() { 1050 assert(getParent() && "Not embedded in a basic block!"); 1051 MachineBasicBlock *MBB = getParent(); 1052 MachineFunction *MF = MBB->getParent(); 1053 assert(MF && "Not embedded in a function!"); 1054 1055 MachineInstr *MI = (MachineInstr *)this; 1056 MachineRegisterInfo &MRI = MF->getRegInfo(); 1057 1058 for (const MachineOperand &MO : MI->operands()) { 1059 if (!MO.isReg() || !MO.isDef()) 1060 continue; 1061 unsigned Reg = MO.getReg(); 1062 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 1063 continue; 1064 MRI.markUsesInDebugValueAsUndef(Reg); 1065 } 1066 MI->eraseFromParent(); 1067 } 1068 1069 void MachineInstr::eraseFromBundle() { 1070 assert(getParent() && "Not embedded in a basic block!"); 1071 getParent()->erase_instr(this); 1072 } 1073 1074 /// getNumExplicitOperands - Returns the number of non-implicit operands. 1075 /// 1076 unsigned MachineInstr::getNumExplicitOperands() const { 1077 unsigned NumOperands = MCID->getNumOperands(); 1078 if (!MCID->isVariadic()) 1079 return NumOperands; 1080 1081 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) { 1082 const MachineOperand &MO = getOperand(i); 1083 if (!MO.isReg() || !MO.isImplicit()) 1084 NumOperands++; 1085 } 1086 return NumOperands; 1087 } 1088 1089 void MachineInstr::bundleWithPred() { 1090 assert(!isBundledWithPred() && "MI is already bundled with its predecessor"); 1091 setFlag(BundledPred); 1092 MachineBasicBlock::instr_iterator Pred = getIterator(); 1093 --Pred; 1094 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 1095 Pred->setFlag(BundledSucc); 1096 } 1097 1098 void MachineInstr::bundleWithSucc() { 1099 assert(!isBundledWithSucc() && "MI is already bundled with its successor"); 1100 setFlag(BundledSucc); 1101 MachineBasicBlock::instr_iterator Succ = getIterator(); 1102 ++Succ; 1103 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags"); 1104 Succ->setFlag(BundledPred); 1105 } 1106 1107 void MachineInstr::unbundleFromPred() { 1108 assert(isBundledWithPred() && "MI isn't bundled with its predecessor"); 1109 clearFlag(BundledPred); 1110 MachineBasicBlock::instr_iterator Pred = getIterator(); 1111 --Pred; 1112 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 1113 Pred->clearFlag(BundledSucc); 1114 } 1115 1116 void MachineInstr::unbundleFromSucc() { 1117 assert(isBundledWithSucc() && "MI isn't bundled with its successor"); 1118 clearFlag(BundledSucc); 1119 MachineBasicBlock::instr_iterator Succ = getIterator(); 1120 ++Succ; 1121 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags"); 1122 Succ->clearFlag(BundledPred); 1123 } 1124 1125 bool MachineInstr::isStackAligningInlineAsm() const { 1126 if (isInlineAsm()) { 1127 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1128 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 1129 return true; 1130 } 1131 return false; 1132 } 1133 1134 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const { 1135 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!"); 1136 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1137 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0); 1138 } 1139 1140 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx, 1141 unsigned *GroupNo) const { 1142 assert(isInlineAsm() && "Expected an inline asm instruction"); 1143 assert(OpIdx < getNumOperands() && "OpIdx out of range"); 1144 1145 // Ignore queries about the initial operands. 1146 if (OpIdx < InlineAsm::MIOp_FirstOperand) 1147 return -1; 1148 1149 unsigned Group = 0; 1150 unsigned NumOps; 1151 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 1152 i += NumOps) { 1153 const MachineOperand &FlagMO = getOperand(i); 1154 // If we reach the implicit register operands, stop looking. 1155 if (!FlagMO.isImm()) 1156 return -1; 1157 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 1158 if (i + NumOps > OpIdx) { 1159 if (GroupNo) 1160 *GroupNo = Group; 1161 return i; 1162 } 1163 ++Group; 1164 } 1165 return -1; 1166 } 1167 1168 const DILocalVariable *MachineInstr::getDebugVariable() const { 1169 assert(isDebugValue() && "not a DBG_VALUE"); 1170 return cast<DILocalVariable>(getOperand(2).getMetadata()); 1171 } 1172 1173 const DIExpression *MachineInstr::getDebugExpression() const { 1174 assert(isDebugValue() && "not a DBG_VALUE"); 1175 return cast<DIExpression>(getOperand(3).getMetadata()); 1176 } 1177 1178 const TargetRegisterClass* 1179 MachineInstr::getRegClassConstraint(unsigned OpIdx, 1180 const TargetInstrInfo *TII, 1181 const TargetRegisterInfo *TRI) const { 1182 assert(getParent() && "Can't have an MBB reference here!"); 1183 assert(getParent()->getParent() && "Can't have an MF reference here!"); 1184 const MachineFunction &MF = *getParent()->getParent(); 1185 1186 // Most opcodes have fixed constraints in their MCInstrDesc. 1187 if (!isInlineAsm()) 1188 return TII->getRegClass(getDesc(), OpIdx, TRI, MF); 1189 1190 if (!getOperand(OpIdx).isReg()) 1191 return nullptr; 1192 1193 // For tied uses on inline asm, get the constraint from the def. 1194 unsigned DefIdx; 1195 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx)) 1196 OpIdx = DefIdx; 1197 1198 // Inline asm stores register class constraints in the flag word. 1199 int FlagIdx = findInlineAsmFlagIdx(OpIdx); 1200 if (FlagIdx < 0) 1201 return nullptr; 1202 1203 unsigned Flag = getOperand(FlagIdx).getImm(); 1204 unsigned RCID; 1205 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) 1206 return TRI->getRegClass(RCID); 1207 1208 // Assume that all registers in a memory operand are pointers. 1209 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem) 1210 return TRI->getPointerRegClass(MF); 1211 1212 return nullptr; 1213 } 1214 1215 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg( 1216 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII, 1217 const TargetRegisterInfo *TRI, bool ExploreBundle) const { 1218 // Check every operands inside the bundle if we have 1219 // been asked to. 1220 if (ExploreBundle) 1221 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC; 1222 ++OpndIt) 1223 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl( 1224 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI); 1225 else 1226 // Otherwise, just check the current operands. 1227 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i) 1228 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI); 1229 return CurRC; 1230 } 1231 1232 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl( 1233 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC, 1234 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 1235 assert(CurRC && "Invalid initial register class"); 1236 // Check if Reg is constrained by some of its use/def from MI. 1237 const MachineOperand &MO = getOperand(OpIdx); 1238 if (!MO.isReg() || MO.getReg() != Reg) 1239 return CurRC; 1240 // If yes, accumulate the constraints through the operand. 1241 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI); 1242 } 1243 1244 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect( 1245 unsigned OpIdx, const TargetRegisterClass *CurRC, 1246 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 1247 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI); 1248 const MachineOperand &MO = getOperand(OpIdx); 1249 assert(MO.isReg() && 1250 "Cannot get register constraints for non-register operand"); 1251 assert(CurRC && "Invalid initial register class"); 1252 if (unsigned SubIdx = MO.getSubReg()) { 1253 if (OpRC) 1254 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx); 1255 else 1256 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx); 1257 } else if (OpRC) 1258 CurRC = TRI->getCommonSubClass(CurRC, OpRC); 1259 return CurRC; 1260 } 1261 1262 /// Return the number of instructions inside the MI bundle, not counting the 1263 /// header instruction. 1264 unsigned MachineInstr::getBundleSize() const { 1265 MachineBasicBlock::const_instr_iterator I = getIterator(); 1266 unsigned Size = 0; 1267 while (I->isBundledWithSucc()) { 1268 ++Size; 1269 ++I; 1270 } 1271 return Size; 1272 } 1273 1274 /// Returns true if the MachineInstr has an implicit-use operand of exactly 1275 /// the given register (not considering sub/super-registers). 1276 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const { 1277 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1278 const MachineOperand &MO = getOperand(i); 1279 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg) 1280 return true; 1281 } 1282 return false; 1283 } 1284 1285 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of 1286 /// the specific register or -1 if it is not found. It further tightens 1287 /// the search criteria to a use that kills the register if isKill is true. 1288 int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill, 1289 const TargetRegisterInfo *TRI) const { 1290 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1291 const MachineOperand &MO = getOperand(i); 1292 if (!MO.isReg() || !MO.isUse()) 1293 continue; 1294 unsigned MOReg = MO.getReg(); 1295 if (!MOReg) 1296 continue; 1297 if (MOReg == Reg || 1298 (TRI && 1299 TargetRegisterInfo::isPhysicalRegister(MOReg) && 1300 TargetRegisterInfo::isPhysicalRegister(Reg) && 1301 TRI->isSubRegister(MOReg, Reg))) 1302 if (!isKill || MO.isKill()) 1303 return i; 1304 } 1305 return -1; 1306 } 1307 1308 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes) 1309 /// indicating if this instruction reads or writes Reg. This also considers 1310 /// partial defines. 1311 std::pair<bool,bool> 1312 MachineInstr::readsWritesVirtualRegister(unsigned Reg, 1313 SmallVectorImpl<unsigned> *Ops) const { 1314 bool PartDef = false; // Partial redefine. 1315 bool FullDef = false; // Full define. 1316 bool Use = false; 1317 1318 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1319 const MachineOperand &MO = getOperand(i); 1320 if (!MO.isReg() || MO.getReg() != Reg) 1321 continue; 1322 if (Ops) 1323 Ops->push_back(i); 1324 if (MO.isUse()) 1325 Use |= !MO.isUndef(); 1326 else if (MO.getSubReg() && !MO.isUndef()) 1327 // A partial <def,undef> doesn't count as reading the register. 1328 PartDef = true; 1329 else 1330 FullDef = true; 1331 } 1332 // A partial redefine uses Reg unless there is also a full define. 1333 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef); 1334 } 1335 1336 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of 1337 /// the specified register or -1 if it is not found. If isDead is true, defs 1338 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it 1339 /// also checks if there is a def of a super-register. 1340 int 1341 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap, 1342 const TargetRegisterInfo *TRI) const { 1343 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg); 1344 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1345 const MachineOperand &MO = getOperand(i); 1346 // Accept regmask operands when Overlap is set. 1347 // Ignore them when looking for a specific def operand (Overlap == false). 1348 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg)) 1349 return i; 1350 if (!MO.isReg() || !MO.isDef()) 1351 continue; 1352 unsigned MOReg = MO.getReg(); 1353 bool Found = (MOReg == Reg); 1354 if (!Found && TRI && isPhys && 1355 TargetRegisterInfo::isPhysicalRegister(MOReg)) { 1356 if (Overlap) 1357 Found = TRI->regsOverlap(MOReg, Reg); 1358 else 1359 Found = TRI->isSubRegister(MOReg, Reg); 1360 } 1361 if (Found && (!isDead || MO.isDead())) 1362 return i; 1363 } 1364 return -1; 1365 } 1366 1367 /// findFirstPredOperandIdx() - Find the index of the first operand in the 1368 /// operand list that is used to represent the predicate. It returns -1 if 1369 /// none is found. 1370 int MachineInstr::findFirstPredOperandIdx() const { 1371 // Don't call MCID.findFirstPredOperandIdx() because this variant 1372 // is sometimes called on an instruction that's not yet complete, and 1373 // so the number of operands is less than the MCID indicates. In 1374 // particular, the PTX target does this. 1375 const MCInstrDesc &MCID = getDesc(); 1376 if (MCID.isPredicable()) { 1377 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 1378 if (MCID.OpInfo[i].isPredicate()) 1379 return i; 1380 } 1381 1382 return -1; 1383 } 1384 1385 // MachineOperand::TiedTo is 4 bits wide. 1386 const unsigned TiedMax = 15; 1387 1388 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other. 1389 /// 1390 /// Use and def operands can be tied together, indicated by a non-zero TiedTo 1391 /// field. TiedTo can have these values: 1392 /// 1393 /// 0: Operand is not tied to anything. 1394 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1). 1395 /// TiedMax: Tied to an operand >= TiedMax-1. 1396 /// 1397 /// The tied def must be one of the first TiedMax operands on a normal 1398 /// instruction. INLINEASM instructions allow more tied defs. 1399 /// 1400 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) { 1401 MachineOperand &DefMO = getOperand(DefIdx); 1402 MachineOperand &UseMO = getOperand(UseIdx); 1403 assert(DefMO.isDef() && "DefIdx must be a def operand"); 1404 assert(UseMO.isUse() && "UseIdx must be a use operand"); 1405 assert(!DefMO.isTied() && "Def is already tied to another use"); 1406 assert(!UseMO.isTied() && "Use is already tied to another def"); 1407 1408 if (DefIdx < TiedMax) 1409 UseMO.TiedTo = DefIdx + 1; 1410 else { 1411 // Inline asm can use the group descriptors to find tied operands, but on 1412 // normal instruction, the tied def must be within the first TiedMax 1413 // operands. 1414 assert(isInlineAsm() && "DefIdx out of range"); 1415 UseMO.TiedTo = TiedMax; 1416 } 1417 1418 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx(). 1419 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax); 1420 } 1421 1422 /// Given the index of a tied register operand, find the operand it is tied to. 1423 /// Defs are tied to uses and vice versa. Returns the index of the tied operand 1424 /// which must exist. 1425 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const { 1426 const MachineOperand &MO = getOperand(OpIdx); 1427 assert(MO.isTied() && "Operand isn't tied"); 1428 1429 // Normally TiedTo is in range. 1430 if (MO.TiedTo < TiedMax) 1431 return MO.TiedTo - 1; 1432 1433 // Uses on normal instructions can be out of range. 1434 if (!isInlineAsm()) { 1435 // Normal tied defs must be in the 0..TiedMax-1 range. 1436 if (MO.isUse()) 1437 return TiedMax - 1; 1438 // MO is a def. Search for the tied use. 1439 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) { 1440 const MachineOperand &UseMO = getOperand(i); 1441 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1) 1442 return i; 1443 } 1444 llvm_unreachable("Can't find tied use"); 1445 } 1446 1447 // Now deal with inline asm by parsing the operand group descriptor flags. 1448 // Find the beginning of each operand group. 1449 SmallVector<unsigned, 8> GroupIdx; 1450 unsigned OpIdxGroup = ~0u; 1451 unsigned NumOps; 1452 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 1453 i += NumOps) { 1454 const MachineOperand &FlagMO = getOperand(i); 1455 assert(FlagMO.isImm() && "Invalid tied operand on inline asm"); 1456 unsigned CurGroup = GroupIdx.size(); 1457 GroupIdx.push_back(i); 1458 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 1459 // OpIdx belongs to this operand group. 1460 if (OpIdx > i && OpIdx < i + NumOps) 1461 OpIdxGroup = CurGroup; 1462 unsigned TiedGroup; 1463 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup)) 1464 continue; 1465 // Operands in this group are tied to operands in TiedGroup which must be 1466 // earlier. Find the number of operands between the two groups. 1467 unsigned Delta = i - GroupIdx[TiedGroup]; 1468 1469 // OpIdx is a use tied to TiedGroup. 1470 if (OpIdxGroup == CurGroup) 1471 return OpIdx - Delta; 1472 1473 // OpIdx is a def tied to this use group. 1474 if (OpIdxGroup == TiedGroup) 1475 return OpIdx + Delta; 1476 } 1477 llvm_unreachable("Invalid tied operand on inline asm"); 1478 } 1479 1480 /// clearKillInfo - Clears kill flags on all operands. 1481 /// 1482 void MachineInstr::clearKillInfo() { 1483 for (MachineOperand &MO : operands()) { 1484 if (MO.isReg() && MO.isUse()) 1485 MO.setIsKill(false); 1486 } 1487 } 1488 1489 void MachineInstr::substituteRegister(unsigned FromReg, 1490 unsigned ToReg, 1491 unsigned SubIdx, 1492 const TargetRegisterInfo &RegInfo) { 1493 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) { 1494 if (SubIdx) 1495 ToReg = RegInfo.getSubReg(ToReg, SubIdx); 1496 for (MachineOperand &MO : operands()) { 1497 if (!MO.isReg() || MO.getReg() != FromReg) 1498 continue; 1499 MO.substPhysReg(ToReg, RegInfo); 1500 } 1501 } else { 1502 for (MachineOperand &MO : operands()) { 1503 if (!MO.isReg() || MO.getReg() != FromReg) 1504 continue; 1505 MO.substVirtReg(ToReg, SubIdx, RegInfo); 1506 } 1507 } 1508 } 1509 1510 /// isSafeToMove - Return true if it is safe to move this instruction. If 1511 /// SawStore is set to true, it means that there is a store (or call) between 1512 /// the instruction's location and its intended destination. 1513 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const { 1514 // Ignore stuff that we obviously can't move. 1515 // 1516 // Treat volatile loads as stores. This is not strictly necessary for 1517 // volatiles, but it is required for atomic loads. It is not allowed to move 1518 // a load across an atomic load with Ordering > Monotonic. 1519 if (mayStore() || isCall() || 1520 (mayLoad() && hasOrderedMemoryRef())) { 1521 SawStore = true; 1522 return false; 1523 } 1524 1525 if (isPosition() || isDebugValue() || isTerminator() || 1526 hasUnmodeledSideEffects()) 1527 return false; 1528 1529 // See if this instruction does a load. If so, we have to guarantee that the 1530 // loaded value doesn't change between the load and the its intended 1531 // destination. The check for isInvariantLoad gives the targe the chance to 1532 // classify the load as always returning a constant, e.g. a constant pool 1533 // load. 1534 if (mayLoad() && !isInvariantLoad(AA)) 1535 // Otherwise, this is a real load. If there is a store between the load and 1536 // end of block, we can't move it. 1537 return !SawStore; 1538 1539 return true; 1540 } 1541 1542 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered 1543 /// or volatile memory reference, or if the information describing the memory 1544 /// reference is not available. Return false if it is known to have no ordered 1545 /// memory references. 1546 bool MachineInstr::hasOrderedMemoryRef() const { 1547 // An instruction known never to access memory won't have a volatile access. 1548 if (!mayStore() && 1549 !mayLoad() && 1550 !isCall() && 1551 !hasUnmodeledSideEffects()) 1552 return false; 1553 1554 // Otherwise, if the instruction has no memory reference information, 1555 // conservatively assume it wasn't preserved. 1556 if (memoperands_empty()) 1557 return true; 1558 1559 // Check the memory reference information for ordered references. 1560 for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I) 1561 if (!(*I)->isUnordered()) 1562 return true; 1563 1564 return false; 1565 } 1566 1567 /// isInvariantLoad - Return true if this instruction is loading from a 1568 /// location whose value is invariant across the function. For example, 1569 /// loading a value from the constant pool or from the argument area 1570 /// of a function if it does not change. This should only return true of 1571 /// *all* loads the instruction does are invariant (if it does multiple loads). 1572 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const { 1573 // If the instruction doesn't load at all, it isn't an invariant load. 1574 if (!mayLoad()) 1575 return false; 1576 1577 // If the instruction has lost its memoperands, conservatively assume that 1578 // it may not be an invariant load. 1579 if (memoperands_empty()) 1580 return false; 1581 1582 const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo(); 1583 1584 for (mmo_iterator I = memoperands_begin(), 1585 E = memoperands_end(); I != E; ++I) { 1586 if ((*I)->isVolatile()) return false; 1587 if ((*I)->isStore()) return false; 1588 if ((*I)->isInvariant()) return true; 1589 1590 1591 // A load from a constant PseudoSourceValue is invariant. 1592 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) 1593 if (PSV->isConstant(MFI)) 1594 continue; 1595 1596 if (const Value *V = (*I)->getValue()) { 1597 // If we have an AliasAnalysis, ask it whether the memory is constant. 1598 if (AA && 1599 AA->pointsToConstantMemory( 1600 MemoryLocation(V, (*I)->getSize(), (*I)->getAAInfo()))) 1601 continue; 1602 } 1603 1604 // Otherwise assume conservatively. 1605 return false; 1606 } 1607 1608 // Everything checks out. 1609 return true; 1610 } 1611 1612 /// isConstantValuePHI - If the specified instruction is a PHI that always 1613 /// merges together the same virtual register, return the register, otherwise 1614 /// return 0. 1615 unsigned MachineInstr::isConstantValuePHI() const { 1616 if (!isPHI()) 1617 return 0; 1618 assert(getNumOperands() >= 3 && 1619 "It's illegal to have a PHI without source operands"); 1620 1621 unsigned Reg = getOperand(1).getReg(); 1622 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2) 1623 if (getOperand(i).getReg() != Reg) 1624 return 0; 1625 return Reg; 1626 } 1627 1628 bool MachineInstr::hasUnmodeledSideEffects() const { 1629 if (hasProperty(MCID::UnmodeledSideEffects)) 1630 return true; 1631 if (isInlineAsm()) { 1632 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1633 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1634 return true; 1635 } 1636 1637 return false; 1638 } 1639 1640 bool MachineInstr::isLoadFoldBarrier() const { 1641 return mayStore() || isCall() || hasUnmodeledSideEffects(); 1642 } 1643 1644 /// allDefsAreDead - Return true if all the defs of this instruction are dead. 1645 /// 1646 bool MachineInstr::allDefsAreDead() const { 1647 for (const MachineOperand &MO : operands()) { 1648 if (!MO.isReg() || MO.isUse()) 1649 continue; 1650 if (!MO.isDead()) 1651 return false; 1652 } 1653 return true; 1654 } 1655 1656 /// copyImplicitOps - Copy implicit register operands from specified 1657 /// instruction to this instruction. 1658 void MachineInstr::copyImplicitOps(MachineFunction &MF, 1659 const MachineInstr &MI) { 1660 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands(); 1661 i != e; ++i) { 1662 const MachineOperand &MO = MI.getOperand(i); 1663 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask()) 1664 addOperand(MF, MO); 1665 } 1666 } 1667 1668 LLVM_DUMP_METHOD void MachineInstr::dump() const { 1669 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1670 dbgs() << " " << *this; 1671 #endif 1672 } 1673 1674 void MachineInstr::print(raw_ostream &OS, bool SkipOpers) const { 1675 const Module *M = nullptr; 1676 if (const MachineBasicBlock *MBB = getParent()) 1677 if (const MachineFunction *MF = MBB->getParent()) 1678 M = MF->getFunction()->getParent(); 1679 1680 ModuleSlotTracker MST(M); 1681 print(OS, MST, SkipOpers); 1682 } 1683 1684 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST, 1685 bool SkipOpers) const { 1686 // We can be a bit tidier if we know the MachineFunction. 1687 const MachineFunction *MF = nullptr; 1688 const TargetRegisterInfo *TRI = nullptr; 1689 const MachineRegisterInfo *MRI = nullptr; 1690 const TargetInstrInfo *TII = nullptr; 1691 if (const MachineBasicBlock *MBB = getParent()) { 1692 MF = MBB->getParent(); 1693 if (MF) { 1694 MRI = &MF->getRegInfo(); 1695 TRI = MF->getSubtarget().getRegisterInfo(); 1696 TII = MF->getSubtarget().getInstrInfo(); 1697 } 1698 } 1699 1700 // Save a list of virtual registers. 1701 SmallVector<unsigned, 8> VirtRegs; 1702 1703 // Print explicitly defined operands on the left of an assignment syntax. 1704 unsigned StartOp = 0, e = getNumOperands(); 1705 for (; StartOp < e && getOperand(StartOp).isReg() && 1706 getOperand(StartOp).isDef() && 1707 !getOperand(StartOp).isImplicit(); 1708 ++StartOp) { 1709 if (StartOp != 0) OS << ", "; 1710 getOperand(StartOp).print(OS, MST, TRI); 1711 unsigned Reg = getOperand(StartOp).getReg(); 1712 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 1713 VirtRegs.push_back(Reg); 1714 unsigned Size; 1715 if (MRI && (Size = MRI->getSize(Reg))) 1716 OS << '(' << Size << ')'; 1717 } 1718 } 1719 1720 if (StartOp != 0) 1721 OS << " = "; 1722 1723 // Print the opcode name. 1724 if (TII) 1725 OS << TII->getName(getOpcode()); 1726 else 1727 OS << "UNKNOWN"; 1728 1729 if (getType()) { 1730 OS << ' '; 1731 getType()->print(OS, /*IsForDebug*/ false, /*NoDetails*/ true); 1732 OS << ' '; 1733 } 1734 1735 if (SkipOpers) 1736 return; 1737 1738 // Print the rest of the operands. 1739 bool OmittedAnyCallClobbers = false; 1740 bool FirstOp = true; 1741 unsigned AsmDescOp = ~0u; 1742 unsigned AsmOpCount = 0; 1743 1744 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) { 1745 // Print asm string. 1746 OS << " "; 1747 getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI); 1748 1749 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack 1750 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1751 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1752 OS << " [sideeffect]"; 1753 if (ExtraInfo & InlineAsm::Extra_MayLoad) 1754 OS << " [mayload]"; 1755 if (ExtraInfo & InlineAsm::Extra_MayStore) 1756 OS << " [maystore]"; 1757 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 1758 OS << " [alignstack]"; 1759 if (getInlineAsmDialect() == InlineAsm::AD_ATT) 1760 OS << " [attdialect]"; 1761 if (getInlineAsmDialect() == InlineAsm::AD_Intel) 1762 OS << " [inteldialect]"; 1763 1764 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand; 1765 FirstOp = false; 1766 } 1767 1768 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) { 1769 const MachineOperand &MO = getOperand(i); 1770 1771 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())) 1772 VirtRegs.push_back(MO.getReg()); 1773 1774 // Omit call-clobbered registers which aren't used anywhere. This makes 1775 // call instructions much less noisy on targets where calls clobber lots 1776 // of registers. Don't rely on MO.isDead() because we may be called before 1777 // LiveVariables is run, or we may be looking at a non-allocatable reg. 1778 if (MRI && isCall() && 1779 MO.isReg() && MO.isImplicit() && MO.isDef()) { 1780 unsigned Reg = MO.getReg(); 1781 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1782 if (MRI->use_empty(Reg)) { 1783 bool HasAliasLive = false; 1784 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) { 1785 unsigned AliasReg = *AI; 1786 if (!MRI->use_empty(AliasReg)) { 1787 HasAliasLive = true; 1788 break; 1789 } 1790 } 1791 if (!HasAliasLive) { 1792 OmittedAnyCallClobbers = true; 1793 continue; 1794 } 1795 } 1796 } 1797 } 1798 1799 if (FirstOp) FirstOp = false; else OS << ","; 1800 OS << " "; 1801 if (i < getDesc().NumOperands) { 1802 const MCOperandInfo &MCOI = getDesc().OpInfo[i]; 1803 if (MCOI.isPredicate()) 1804 OS << "pred:"; 1805 if (MCOI.isOptionalDef()) 1806 OS << "opt:"; 1807 } 1808 if (isDebugValue() && MO.isMetadata()) { 1809 // Pretty print DBG_VALUE instructions. 1810 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata()); 1811 if (DIV && !DIV->getName().empty()) 1812 OS << "!\"" << DIV->getName() << '\"'; 1813 else 1814 MO.print(OS, MST, TRI); 1815 } else if (TRI && (isInsertSubreg() || isRegSequence()) && MO.isImm()) { 1816 OS << TRI->getSubRegIndexName(MO.getImm()); 1817 } else if (i == AsmDescOp && MO.isImm()) { 1818 // Pretty print the inline asm operand descriptor. 1819 OS << '$' << AsmOpCount++; 1820 unsigned Flag = MO.getImm(); 1821 switch (InlineAsm::getKind(Flag)) { 1822 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break; 1823 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break; 1824 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break; 1825 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break; 1826 case InlineAsm::Kind_Imm: OS << ":[imm"; break; 1827 case InlineAsm::Kind_Mem: OS << ":[mem"; break; 1828 default: OS << ":[??" << InlineAsm::getKind(Flag); break; 1829 } 1830 1831 unsigned RCID = 0; 1832 if (InlineAsm::hasRegClassConstraint(Flag, RCID)) { 1833 if (TRI) { 1834 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID)); 1835 } else 1836 OS << ":RC" << RCID; 1837 } 1838 1839 unsigned TiedTo = 0; 1840 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo)) 1841 OS << " tiedto:$" << TiedTo; 1842 1843 OS << ']'; 1844 1845 // Compute the index of the next operand descriptor. 1846 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag); 1847 } else 1848 MO.print(OS, MST, TRI); 1849 } 1850 1851 // Briefly indicate whether any call clobbers were omitted. 1852 if (OmittedAnyCallClobbers) { 1853 if (!FirstOp) OS << ","; 1854 OS << " ..."; 1855 } 1856 1857 bool HaveSemi = false; 1858 const unsigned PrintableFlags = FrameSetup | FrameDestroy; 1859 if (Flags & PrintableFlags) { 1860 if (!HaveSemi) { 1861 OS << ";"; 1862 HaveSemi = true; 1863 } 1864 OS << " flags: "; 1865 1866 if (Flags & FrameSetup) 1867 OS << "FrameSetup"; 1868 1869 if (Flags & FrameDestroy) 1870 OS << "FrameDestroy"; 1871 } 1872 1873 if (!memoperands_empty()) { 1874 if (!HaveSemi) { 1875 OS << ";"; 1876 HaveSemi = true; 1877 } 1878 1879 OS << " mem:"; 1880 for (mmo_iterator i = memoperands_begin(), e = memoperands_end(); 1881 i != e; ++i) { 1882 (*i)->print(OS, MST); 1883 if (std::next(i) != e) 1884 OS << " "; 1885 } 1886 } 1887 1888 // Print the regclass of any virtual registers encountered. 1889 if (MRI && !VirtRegs.empty()) { 1890 if (!HaveSemi) { 1891 OS << ";"; 1892 HaveSemi = true; 1893 } 1894 for (unsigned i = 0; i != VirtRegs.size(); ++i) { 1895 const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]); 1896 if (!RC) 1897 continue; 1898 // Generic virtual registers do not have register classes. 1899 if (RC.is<const RegisterBank *>()) 1900 OS << " " << RC.get<const RegisterBank *>()->getName(); 1901 else 1902 OS << " " 1903 << TRI->getRegClassName(RC.get<const TargetRegisterClass *>()); 1904 OS << ':' << PrintReg(VirtRegs[i]); 1905 for (unsigned j = i+1; j != VirtRegs.size();) { 1906 if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) { 1907 ++j; 1908 continue; 1909 } 1910 if (VirtRegs[i] != VirtRegs[j]) 1911 OS << "," << PrintReg(VirtRegs[j]); 1912 VirtRegs.erase(VirtRegs.begin()+j); 1913 } 1914 } 1915 } 1916 1917 // Print debug location information. 1918 if (isDebugValue() && getOperand(e - 2).isMetadata()) { 1919 if (!HaveSemi) 1920 OS << ";"; 1921 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata()); 1922 OS << " line no:" << DV->getLine(); 1923 if (auto *InlinedAt = debugLoc->getInlinedAt()) { 1924 DebugLoc InlinedAtDL(InlinedAt); 1925 if (InlinedAtDL && MF) { 1926 OS << " inlined @[ "; 1927 InlinedAtDL.print(OS); 1928 OS << " ]"; 1929 } 1930 } 1931 if (isIndirectDebugValue()) 1932 OS << " indirect"; 1933 } else if (debugLoc && MF) { 1934 if (!HaveSemi) 1935 OS << ";"; 1936 OS << " dbg:"; 1937 debugLoc.print(OS); 1938 } 1939 1940 OS << '\n'; 1941 } 1942 1943 bool MachineInstr::addRegisterKilled(unsigned IncomingReg, 1944 const TargetRegisterInfo *RegInfo, 1945 bool AddIfNotFound) { 1946 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg); 1947 bool hasAliases = isPhysReg && 1948 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid(); 1949 bool Found = false; 1950 SmallVector<unsigned,4> DeadOps; 1951 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1952 MachineOperand &MO = getOperand(i); 1953 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) 1954 continue; 1955 1956 // DEBUG_VALUE nodes do not contribute to code generation and should 1957 // always be ignored. Failure to do so may result in trying to modify 1958 // KILL flags on DEBUG_VALUE nodes. 1959 if (MO.isDebug()) 1960 continue; 1961 1962 unsigned Reg = MO.getReg(); 1963 if (!Reg) 1964 continue; 1965 1966 if (Reg == IncomingReg) { 1967 if (!Found) { 1968 if (MO.isKill()) 1969 // The register is already marked kill. 1970 return true; 1971 if (isPhysReg && isRegTiedToDefOperand(i)) 1972 // Two-address uses of physregs must not be marked kill. 1973 return true; 1974 MO.setIsKill(); 1975 Found = true; 1976 } 1977 } else if (hasAliases && MO.isKill() && 1978 TargetRegisterInfo::isPhysicalRegister(Reg)) { 1979 // A super-register kill already exists. 1980 if (RegInfo->isSuperRegister(IncomingReg, Reg)) 1981 return true; 1982 if (RegInfo->isSubRegister(IncomingReg, Reg)) 1983 DeadOps.push_back(i); 1984 } 1985 } 1986 1987 // Trim unneeded kill operands. 1988 while (!DeadOps.empty()) { 1989 unsigned OpIdx = DeadOps.back(); 1990 if (getOperand(OpIdx).isImplicit()) 1991 RemoveOperand(OpIdx); 1992 else 1993 getOperand(OpIdx).setIsKill(false); 1994 DeadOps.pop_back(); 1995 } 1996 1997 // If not found, this means an alias of one of the operands is killed. Add a 1998 // new implicit operand if required. 1999 if (!Found && AddIfNotFound) { 2000 addOperand(MachineOperand::CreateReg(IncomingReg, 2001 false /*IsDef*/, 2002 true /*IsImp*/, 2003 true /*IsKill*/)); 2004 return true; 2005 } 2006 return Found; 2007 } 2008 2009 void MachineInstr::clearRegisterKills(unsigned Reg, 2010 const TargetRegisterInfo *RegInfo) { 2011 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) 2012 RegInfo = nullptr; 2013 for (MachineOperand &MO : operands()) { 2014 if (!MO.isReg() || !MO.isUse() || !MO.isKill()) 2015 continue; 2016 unsigned OpReg = MO.getReg(); 2017 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg) 2018 MO.setIsKill(false); 2019 } 2020 } 2021 2022 bool MachineInstr::addRegisterDead(unsigned Reg, 2023 const TargetRegisterInfo *RegInfo, 2024 bool AddIfNotFound) { 2025 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg); 2026 bool hasAliases = isPhysReg && 2027 MCRegAliasIterator(Reg, RegInfo, false).isValid(); 2028 bool Found = false; 2029 SmallVector<unsigned,4> DeadOps; 2030 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 2031 MachineOperand &MO = getOperand(i); 2032 if (!MO.isReg() || !MO.isDef()) 2033 continue; 2034 unsigned MOReg = MO.getReg(); 2035 if (!MOReg) 2036 continue; 2037 2038 if (MOReg == Reg) { 2039 MO.setIsDead(); 2040 Found = true; 2041 } else if (hasAliases && MO.isDead() && 2042 TargetRegisterInfo::isPhysicalRegister(MOReg)) { 2043 // There exists a super-register that's marked dead. 2044 if (RegInfo->isSuperRegister(Reg, MOReg)) 2045 return true; 2046 if (RegInfo->isSubRegister(Reg, MOReg)) 2047 DeadOps.push_back(i); 2048 } 2049 } 2050 2051 // Trim unneeded dead operands. 2052 while (!DeadOps.empty()) { 2053 unsigned OpIdx = DeadOps.back(); 2054 if (getOperand(OpIdx).isImplicit()) 2055 RemoveOperand(OpIdx); 2056 else 2057 getOperand(OpIdx).setIsDead(false); 2058 DeadOps.pop_back(); 2059 } 2060 2061 // If not found, this means an alias of one of the operands is dead. Add a 2062 // new implicit operand if required. 2063 if (Found || !AddIfNotFound) 2064 return Found; 2065 2066 addOperand(MachineOperand::CreateReg(Reg, 2067 true /*IsDef*/, 2068 true /*IsImp*/, 2069 false /*IsKill*/, 2070 true /*IsDead*/)); 2071 return true; 2072 } 2073 2074 void MachineInstr::clearRegisterDeads(unsigned Reg) { 2075 for (MachineOperand &MO : operands()) { 2076 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg) 2077 continue; 2078 MO.setIsDead(false); 2079 } 2080 } 2081 2082 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) { 2083 for (MachineOperand &MO : operands()) { 2084 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0) 2085 continue; 2086 MO.setIsUndef(IsUndef); 2087 } 2088 } 2089 2090 void MachineInstr::addRegisterDefined(unsigned Reg, 2091 const TargetRegisterInfo *RegInfo) { 2092 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 2093 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo); 2094 if (MO) 2095 return; 2096 } else { 2097 for (const MachineOperand &MO : operands()) { 2098 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() && 2099 MO.getSubReg() == 0) 2100 return; 2101 } 2102 } 2103 addOperand(MachineOperand::CreateReg(Reg, 2104 true /*IsDef*/, 2105 true /*IsImp*/)); 2106 } 2107 2108 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs, 2109 const TargetRegisterInfo &TRI) { 2110 bool HasRegMask = false; 2111 for (MachineOperand &MO : operands()) { 2112 if (MO.isRegMask()) { 2113 HasRegMask = true; 2114 continue; 2115 } 2116 if (!MO.isReg() || !MO.isDef()) continue; 2117 unsigned Reg = MO.getReg(); 2118 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue; 2119 // If there are no uses, including partial uses, the def is dead. 2120 if (std::none_of(UsedRegs.begin(), UsedRegs.end(), 2121 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); })) 2122 MO.setIsDead(); 2123 } 2124 2125 // This is a call with a register mask operand. 2126 // Mask clobbers are always dead, so add defs for the non-dead defines. 2127 if (HasRegMask) 2128 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end(); 2129 I != E; ++I) 2130 addRegisterDefined(*I, &TRI); 2131 } 2132 2133 unsigned 2134 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) { 2135 // Build up a buffer of hash code components. 2136 SmallVector<size_t, 8> HashComponents; 2137 HashComponents.reserve(MI->getNumOperands() + 1); 2138 HashComponents.push_back(MI->getOpcode()); 2139 for (const MachineOperand &MO : MI->operands()) { 2140 if (MO.isReg() && MO.isDef() && 2141 TargetRegisterInfo::isVirtualRegister(MO.getReg())) 2142 continue; // Skip virtual register defs. 2143 2144 HashComponents.push_back(hash_value(MO)); 2145 } 2146 return hash_combine_range(HashComponents.begin(), HashComponents.end()); 2147 } 2148 2149 void MachineInstr::emitError(StringRef Msg) const { 2150 // Find the source location cookie. 2151 unsigned LocCookie = 0; 2152 const MDNode *LocMD = nullptr; 2153 for (unsigned i = getNumOperands(); i != 0; --i) { 2154 if (getOperand(i-1).isMetadata() && 2155 (LocMD = getOperand(i-1).getMetadata()) && 2156 LocMD->getNumOperands() != 0) { 2157 if (const ConstantInt *CI = 2158 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) { 2159 LocCookie = CI->getZExtValue(); 2160 break; 2161 } 2162 } 2163 } 2164 2165 if (const MachineBasicBlock *MBB = getParent()) 2166 if (const MachineFunction *MF = MBB->getParent()) 2167 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg); 2168 report_fatal_error(Msg); 2169 } 2170 2171 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL, 2172 const MCInstrDesc &MCID, bool IsIndirect, 2173 unsigned Reg, unsigned Offset, 2174 const MDNode *Variable, const MDNode *Expr) { 2175 assert(isa<DILocalVariable>(Variable) && "not a variable"); 2176 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 2177 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 2178 "Expected inlined-at fields to agree"); 2179 if (IsIndirect) 2180 return BuildMI(MF, DL, MCID) 2181 .addReg(Reg, RegState::Debug) 2182 .addImm(Offset) 2183 .addMetadata(Variable) 2184 .addMetadata(Expr); 2185 else { 2186 assert(Offset == 0 && "A direct address cannot have an offset."); 2187 return BuildMI(MF, DL, MCID) 2188 .addReg(Reg, RegState::Debug) 2189 .addReg(0U, RegState::Debug) 2190 .addMetadata(Variable) 2191 .addMetadata(Expr); 2192 } 2193 } 2194 2195 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB, 2196 MachineBasicBlock::iterator I, 2197 const DebugLoc &DL, const MCInstrDesc &MCID, 2198 bool IsIndirect, unsigned Reg, 2199 unsigned Offset, const MDNode *Variable, 2200 const MDNode *Expr) { 2201 assert(isa<DILocalVariable>(Variable) && "not a variable"); 2202 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 2203 MachineFunction &MF = *BB.getParent(); 2204 MachineInstr *MI = 2205 BuildMI(MF, DL, MCID, IsIndirect, Reg, Offset, Variable, Expr); 2206 BB.insert(I, MI); 2207 return MachineInstrBuilder(MF, MI); 2208 } 2209