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