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