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