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