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