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