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