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