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 uint16_t MachineInstr::copyFlagsFromInstruction(const Instruction &I) { 523 uint16_t MIFlags = 0; 524 // Copy the wrapping flags. 525 if (const OverflowingBinaryOperator *OB = 526 dyn_cast<OverflowingBinaryOperator>(&I)) { 527 if (OB->hasNoSignedWrap()) 528 MIFlags |= MachineInstr::MIFlag::NoSWrap; 529 if (OB->hasNoUnsignedWrap()) 530 MIFlags |= MachineInstr::MIFlag::NoUWrap; 531 } 532 533 // Copy the exact flag. 534 if (const PossiblyExactOperator *PE = dyn_cast<PossiblyExactOperator>(&I)) 535 if (PE->isExact()) 536 MIFlags |= MachineInstr::MIFlag::IsExact; 537 538 // Copy the fast-math flags. 539 if (const FPMathOperator *FP = dyn_cast<FPMathOperator>(&I)) { 540 const FastMathFlags Flags = FP->getFastMathFlags(); 541 if (Flags.noNaNs()) 542 MIFlags |= MachineInstr::MIFlag::FmNoNans; 543 if (Flags.noInfs()) 544 MIFlags |= MachineInstr::MIFlag::FmNoInfs; 545 if (Flags.noSignedZeros()) 546 MIFlags |= MachineInstr::MIFlag::FmNsz; 547 if (Flags.allowReciprocal()) 548 MIFlags |= MachineInstr::MIFlag::FmArcp; 549 if (Flags.allowContract()) 550 MIFlags |= MachineInstr::MIFlag::FmContract; 551 if (Flags.approxFunc()) 552 MIFlags |= MachineInstr::MIFlag::FmAfn; 553 if (Flags.allowReassoc()) 554 MIFlags |= MachineInstr::MIFlag::FmReassoc; 555 } 556 557 return MIFlags; 558 } 559 560 void MachineInstr::copyIRFlags(const Instruction &I) { 561 Flags = copyFlagsFromInstruction(I); 562 } 563 564 bool MachineInstr::hasPropertyInBundle(uint64_t Mask, QueryType Type) const { 565 assert(!isBundledWithPred() && "Must be called on bundle header"); 566 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) { 567 if (MII->getDesc().getFlags() & Mask) { 568 if (Type == AnyInBundle) 569 return true; 570 } else { 571 if (Type == AllInBundle && !MII->isBundle()) 572 return false; 573 } 574 // This was the last instruction in the bundle. 575 if (!MII->isBundledWithSucc()) 576 return Type == AllInBundle; 577 } 578 } 579 580 bool MachineInstr::isIdenticalTo(const MachineInstr &Other, 581 MICheckType Check) const { 582 // If opcodes or number of operands are not the same then the two 583 // instructions are obviously not identical. 584 if (Other.getOpcode() != getOpcode() || 585 Other.getNumOperands() != getNumOperands()) 586 return false; 587 588 if (isBundle()) { 589 // We have passed the test above that both instructions have the same 590 // opcode, so we know that both instructions are bundles here. Let's compare 591 // MIs inside the bundle. 592 assert(Other.isBundle() && "Expected that both instructions are bundles."); 593 MachineBasicBlock::const_instr_iterator I1 = getIterator(); 594 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator(); 595 // Loop until we analysed the last intruction inside at least one of the 596 // bundles. 597 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) { 598 ++I1; 599 ++I2; 600 if (!I1->isIdenticalTo(*I2, Check)) 601 return false; 602 } 603 // If we've reached the end of just one of the two bundles, but not both, 604 // the instructions are not identical. 605 if (I1->isBundledWithSucc() || I2->isBundledWithSucc()) 606 return false; 607 } 608 609 // Check operands to make sure they match. 610 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 611 const MachineOperand &MO = getOperand(i); 612 const MachineOperand &OMO = Other.getOperand(i); 613 if (!MO.isReg()) { 614 if (!MO.isIdenticalTo(OMO)) 615 return false; 616 continue; 617 } 618 619 // Clients may or may not want to ignore defs when testing for equality. 620 // For example, machine CSE pass only cares about finding common 621 // subexpressions, so it's safe to ignore virtual register defs. 622 if (MO.isDef()) { 623 if (Check == IgnoreDefs) 624 continue; 625 else if (Check == IgnoreVRegDefs) { 626 if (!TargetRegisterInfo::isVirtualRegister(MO.getReg()) || 627 !TargetRegisterInfo::isVirtualRegister(OMO.getReg())) 628 if (!MO.isIdenticalTo(OMO)) 629 return false; 630 } else { 631 if (!MO.isIdenticalTo(OMO)) 632 return false; 633 if (Check == CheckKillDead && MO.isDead() != OMO.isDead()) 634 return false; 635 } 636 } else { 637 if (!MO.isIdenticalTo(OMO)) 638 return false; 639 if (Check == CheckKillDead && MO.isKill() != OMO.isKill()) 640 return false; 641 } 642 } 643 // If DebugLoc does not match then two debug instructions are not identical. 644 if (isDebugInstr()) 645 if (getDebugLoc() && Other.getDebugLoc() && 646 getDebugLoc() != Other.getDebugLoc()) 647 return false; 648 return true; 649 } 650 651 const MachineFunction *MachineInstr::getMF() const { 652 return getParent()->getParent(); 653 } 654 655 MachineInstr *MachineInstr::removeFromParent() { 656 assert(getParent() && "Not embedded in a basic block!"); 657 return getParent()->remove(this); 658 } 659 660 MachineInstr *MachineInstr::removeFromBundle() { 661 assert(getParent() && "Not embedded in a basic block!"); 662 return getParent()->remove_instr(this); 663 } 664 665 void MachineInstr::eraseFromParent() { 666 assert(getParent() && "Not embedded in a basic block!"); 667 getParent()->erase(this); 668 } 669 670 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() { 671 assert(getParent() && "Not embedded in a basic block!"); 672 MachineBasicBlock *MBB = getParent(); 673 MachineFunction *MF = MBB->getParent(); 674 assert(MF && "Not embedded in a function!"); 675 676 MachineInstr *MI = (MachineInstr *)this; 677 MachineRegisterInfo &MRI = MF->getRegInfo(); 678 679 for (const MachineOperand &MO : MI->operands()) { 680 if (!MO.isReg() || !MO.isDef()) 681 continue; 682 unsigned Reg = MO.getReg(); 683 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 684 continue; 685 MRI.markUsesInDebugValueAsUndef(Reg); 686 } 687 MI->eraseFromParent(); 688 } 689 690 void MachineInstr::eraseFromBundle() { 691 assert(getParent() && "Not embedded in a basic block!"); 692 getParent()->erase_instr(this); 693 } 694 695 unsigned MachineInstr::getNumExplicitOperands() const { 696 unsigned NumOperands = MCID->getNumOperands(); 697 if (!MCID->isVariadic()) 698 return NumOperands; 699 700 for (unsigned I = NumOperands, E = getNumOperands(); I != E; ++I) { 701 const MachineOperand &MO = getOperand(I); 702 // The operands must always be in the following order: 703 // - explicit reg defs, 704 // - other explicit operands (reg uses, immediates, etc.), 705 // - implicit reg defs 706 // - implicit reg uses 707 if (MO.isReg() && MO.isImplicit()) 708 break; 709 ++NumOperands; 710 } 711 return NumOperands; 712 } 713 714 unsigned MachineInstr::getNumExplicitDefs() const { 715 unsigned NumDefs = MCID->getNumDefs(); 716 if (!MCID->isVariadic()) 717 return NumDefs; 718 719 for (unsigned I = NumDefs, E = getNumOperands(); I != E; ++I) { 720 const MachineOperand &MO = getOperand(I); 721 if (!MO.isReg() || !MO.isDef() || MO.isImplicit()) 722 break; 723 ++NumDefs; 724 } 725 return NumDefs; 726 } 727 728 void MachineInstr::bundleWithPred() { 729 assert(!isBundledWithPred() && "MI is already bundled with its predecessor"); 730 setFlag(BundledPred); 731 MachineBasicBlock::instr_iterator Pred = getIterator(); 732 --Pred; 733 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 734 Pred->setFlag(BundledSucc); 735 } 736 737 void MachineInstr::bundleWithSucc() { 738 assert(!isBundledWithSucc() && "MI is already bundled with its successor"); 739 setFlag(BundledSucc); 740 MachineBasicBlock::instr_iterator Succ = getIterator(); 741 ++Succ; 742 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags"); 743 Succ->setFlag(BundledPred); 744 } 745 746 void MachineInstr::unbundleFromPred() { 747 assert(isBundledWithPred() && "MI isn't bundled with its predecessor"); 748 clearFlag(BundledPred); 749 MachineBasicBlock::instr_iterator Pred = getIterator(); 750 --Pred; 751 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags"); 752 Pred->clearFlag(BundledSucc); 753 } 754 755 void MachineInstr::unbundleFromSucc() { 756 assert(isBundledWithSucc() && "MI isn't bundled with its successor"); 757 clearFlag(BundledSucc); 758 MachineBasicBlock::instr_iterator Succ = getIterator(); 759 ++Succ; 760 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags"); 761 Succ->clearFlag(BundledPred); 762 } 763 764 bool MachineInstr::isStackAligningInlineAsm() const { 765 if (isInlineAsm()) { 766 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 767 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 768 return true; 769 } 770 return false; 771 } 772 773 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const { 774 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!"); 775 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 776 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0); 777 } 778 779 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx, 780 unsigned *GroupNo) const { 781 assert(isInlineAsm() && "Expected an inline asm instruction"); 782 assert(OpIdx < getNumOperands() && "OpIdx out of range"); 783 784 // Ignore queries about the initial operands. 785 if (OpIdx < InlineAsm::MIOp_FirstOperand) 786 return -1; 787 788 unsigned Group = 0; 789 unsigned NumOps; 790 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 791 i += NumOps) { 792 const MachineOperand &FlagMO = getOperand(i); 793 // If we reach the implicit register operands, stop looking. 794 if (!FlagMO.isImm()) 795 return -1; 796 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 797 if (i + NumOps > OpIdx) { 798 if (GroupNo) 799 *GroupNo = Group; 800 return i; 801 } 802 ++Group; 803 } 804 return -1; 805 } 806 807 const DILabel *MachineInstr::getDebugLabel() const { 808 assert(isDebugLabel() && "not a DBG_LABEL"); 809 return cast<DILabel>(getOperand(0).getMetadata()); 810 } 811 812 const DILocalVariable *MachineInstr::getDebugVariable() const { 813 assert(isDebugValue() && "not a DBG_VALUE"); 814 return cast<DILocalVariable>(getOperand(2).getMetadata()); 815 } 816 817 const DIExpression *MachineInstr::getDebugExpression() const { 818 assert(isDebugValue() && "not a DBG_VALUE"); 819 return cast<DIExpression>(getOperand(3).getMetadata()); 820 } 821 822 const TargetRegisterClass* 823 MachineInstr::getRegClassConstraint(unsigned OpIdx, 824 const TargetInstrInfo *TII, 825 const TargetRegisterInfo *TRI) const { 826 assert(getParent() && "Can't have an MBB reference here!"); 827 assert(getMF() && "Can't have an MF reference here!"); 828 const MachineFunction &MF = *getMF(); 829 830 // Most opcodes have fixed constraints in their MCInstrDesc. 831 if (!isInlineAsm()) 832 return TII->getRegClass(getDesc(), OpIdx, TRI, MF); 833 834 if (!getOperand(OpIdx).isReg()) 835 return nullptr; 836 837 // For tied uses on inline asm, get the constraint from the def. 838 unsigned DefIdx; 839 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx)) 840 OpIdx = DefIdx; 841 842 // Inline asm stores register class constraints in the flag word. 843 int FlagIdx = findInlineAsmFlagIdx(OpIdx); 844 if (FlagIdx < 0) 845 return nullptr; 846 847 unsigned Flag = getOperand(FlagIdx).getImm(); 848 unsigned RCID; 849 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse || 850 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef || 851 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) && 852 InlineAsm::hasRegClassConstraint(Flag, RCID)) 853 return TRI->getRegClass(RCID); 854 855 // Assume that all registers in a memory operand are pointers. 856 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem) 857 return TRI->getPointerRegClass(MF); 858 859 return nullptr; 860 } 861 862 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg( 863 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII, 864 const TargetRegisterInfo *TRI, bool ExploreBundle) const { 865 // Check every operands inside the bundle if we have 866 // been asked to. 867 if (ExploreBundle) 868 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC; 869 ++OpndIt) 870 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl( 871 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI); 872 else 873 // Otherwise, just check the current operands. 874 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i) 875 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI); 876 return CurRC; 877 } 878 879 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl( 880 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC, 881 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 882 assert(CurRC && "Invalid initial register class"); 883 // Check if Reg is constrained by some of its use/def from MI. 884 const MachineOperand &MO = getOperand(OpIdx); 885 if (!MO.isReg() || MO.getReg() != Reg) 886 return CurRC; 887 // If yes, accumulate the constraints through the operand. 888 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI); 889 } 890 891 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect( 892 unsigned OpIdx, const TargetRegisterClass *CurRC, 893 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const { 894 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI); 895 const MachineOperand &MO = getOperand(OpIdx); 896 assert(MO.isReg() && 897 "Cannot get register constraints for non-register operand"); 898 assert(CurRC && "Invalid initial register class"); 899 if (unsigned SubIdx = MO.getSubReg()) { 900 if (OpRC) 901 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx); 902 else 903 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx); 904 } else if (OpRC) 905 CurRC = TRI->getCommonSubClass(CurRC, OpRC); 906 return CurRC; 907 } 908 909 /// Return the number of instructions inside the MI bundle, not counting the 910 /// header instruction. 911 unsigned MachineInstr::getBundleSize() const { 912 MachineBasicBlock::const_instr_iterator I = getIterator(); 913 unsigned Size = 0; 914 while (I->isBundledWithSucc()) { 915 ++Size; 916 ++I; 917 } 918 return Size; 919 } 920 921 /// Returns true if the MachineInstr has an implicit-use operand of exactly 922 /// the given register (not considering sub/super-registers). 923 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const { 924 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 925 const MachineOperand &MO = getOperand(i); 926 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg) 927 return true; 928 } 929 return false; 930 } 931 932 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of 933 /// the specific register or -1 if it is not found. It further tightens 934 /// the search criteria to a use that kills the register if isKill is true. 935 int MachineInstr::findRegisterUseOperandIdx( 936 unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const { 937 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 938 const MachineOperand &MO = getOperand(i); 939 if (!MO.isReg() || !MO.isUse()) 940 continue; 941 unsigned MOReg = MO.getReg(); 942 if (!MOReg) 943 continue; 944 if (MOReg == Reg || (TRI && Reg && MOReg && TRI->regsOverlap(MOReg, Reg))) 945 if (!isKill || MO.isKill()) 946 return i; 947 } 948 return -1; 949 } 950 951 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes) 952 /// indicating if this instruction reads or writes Reg. This also considers 953 /// partial defines. 954 std::pair<bool,bool> 955 MachineInstr::readsWritesVirtualRegister(unsigned Reg, 956 SmallVectorImpl<unsigned> *Ops) const { 957 bool PartDef = false; // Partial redefine. 958 bool FullDef = false; // Full define. 959 bool Use = false; 960 961 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 962 const MachineOperand &MO = getOperand(i); 963 if (!MO.isReg() || MO.getReg() != Reg) 964 continue; 965 if (Ops) 966 Ops->push_back(i); 967 if (MO.isUse()) 968 Use |= !MO.isUndef(); 969 else if (MO.getSubReg() && !MO.isUndef()) 970 // A partial def undef doesn't count as reading the register. 971 PartDef = true; 972 else 973 FullDef = true; 974 } 975 // A partial redefine uses Reg unless there is also a full define. 976 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef); 977 } 978 979 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of 980 /// the specified register or -1 if it is not found. If isDead is true, defs 981 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it 982 /// also checks if there is a def of a super-register. 983 int 984 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap, 985 const TargetRegisterInfo *TRI) const { 986 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg); 987 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 988 const MachineOperand &MO = getOperand(i); 989 // Accept regmask operands when Overlap is set. 990 // Ignore them when looking for a specific def operand (Overlap == false). 991 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg)) 992 return i; 993 if (!MO.isReg() || !MO.isDef()) 994 continue; 995 unsigned MOReg = MO.getReg(); 996 bool Found = (MOReg == Reg); 997 if (!Found && TRI && isPhys && 998 TargetRegisterInfo::isPhysicalRegister(MOReg)) { 999 if (Overlap) 1000 Found = TRI->regsOverlap(MOReg, Reg); 1001 else 1002 Found = TRI->isSubRegister(MOReg, Reg); 1003 } 1004 if (Found && (!isDead || MO.isDead())) 1005 return i; 1006 } 1007 return -1; 1008 } 1009 1010 /// findFirstPredOperandIdx() - Find the index of the first operand in the 1011 /// operand list that is used to represent the predicate. It returns -1 if 1012 /// none is found. 1013 int MachineInstr::findFirstPredOperandIdx() const { 1014 // Don't call MCID.findFirstPredOperandIdx() because this variant 1015 // is sometimes called on an instruction that's not yet complete, and 1016 // so the number of operands is less than the MCID indicates. In 1017 // particular, the PTX target does this. 1018 const MCInstrDesc &MCID = getDesc(); 1019 if (MCID.isPredicable()) { 1020 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 1021 if (MCID.OpInfo[i].isPredicate()) 1022 return i; 1023 } 1024 1025 return -1; 1026 } 1027 1028 // MachineOperand::TiedTo is 4 bits wide. 1029 const unsigned TiedMax = 15; 1030 1031 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other. 1032 /// 1033 /// Use and def operands can be tied together, indicated by a non-zero TiedTo 1034 /// field. TiedTo can have these values: 1035 /// 1036 /// 0: Operand is not tied to anything. 1037 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1). 1038 /// TiedMax: Tied to an operand >= TiedMax-1. 1039 /// 1040 /// The tied def must be one of the first TiedMax operands on a normal 1041 /// instruction. INLINEASM instructions allow more tied defs. 1042 /// 1043 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) { 1044 MachineOperand &DefMO = getOperand(DefIdx); 1045 MachineOperand &UseMO = getOperand(UseIdx); 1046 assert(DefMO.isDef() && "DefIdx must be a def operand"); 1047 assert(UseMO.isUse() && "UseIdx must be a use operand"); 1048 assert(!DefMO.isTied() && "Def is already tied to another use"); 1049 assert(!UseMO.isTied() && "Use is already tied to another def"); 1050 1051 if (DefIdx < TiedMax) 1052 UseMO.TiedTo = DefIdx + 1; 1053 else { 1054 // Inline asm can use the group descriptors to find tied operands, but on 1055 // normal instruction, the tied def must be within the first TiedMax 1056 // operands. 1057 assert(isInlineAsm() && "DefIdx out of range"); 1058 UseMO.TiedTo = TiedMax; 1059 } 1060 1061 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx(). 1062 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax); 1063 } 1064 1065 /// Given the index of a tied register operand, find the operand it is tied to. 1066 /// Defs are tied to uses and vice versa. Returns the index of the tied operand 1067 /// which must exist. 1068 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const { 1069 const MachineOperand &MO = getOperand(OpIdx); 1070 assert(MO.isTied() && "Operand isn't tied"); 1071 1072 // Normally TiedTo is in range. 1073 if (MO.TiedTo < TiedMax) 1074 return MO.TiedTo - 1; 1075 1076 // Uses on normal instructions can be out of range. 1077 if (!isInlineAsm()) { 1078 // Normal tied defs must be in the 0..TiedMax-1 range. 1079 if (MO.isUse()) 1080 return TiedMax - 1; 1081 // MO is a def. Search for the tied use. 1082 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) { 1083 const MachineOperand &UseMO = getOperand(i); 1084 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1) 1085 return i; 1086 } 1087 llvm_unreachable("Can't find tied use"); 1088 } 1089 1090 // Now deal with inline asm by parsing the operand group descriptor flags. 1091 // Find the beginning of each operand group. 1092 SmallVector<unsigned, 8> GroupIdx; 1093 unsigned OpIdxGroup = ~0u; 1094 unsigned NumOps; 1095 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e; 1096 i += NumOps) { 1097 const MachineOperand &FlagMO = getOperand(i); 1098 assert(FlagMO.isImm() && "Invalid tied operand on inline asm"); 1099 unsigned CurGroup = GroupIdx.size(); 1100 GroupIdx.push_back(i); 1101 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm()); 1102 // OpIdx belongs to this operand group. 1103 if (OpIdx > i && OpIdx < i + NumOps) 1104 OpIdxGroup = CurGroup; 1105 unsigned TiedGroup; 1106 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup)) 1107 continue; 1108 // Operands in this group are tied to operands in TiedGroup which must be 1109 // earlier. Find the number of operands between the two groups. 1110 unsigned Delta = i - GroupIdx[TiedGroup]; 1111 1112 // OpIdx is a use tied to TiedGroup. 1113 if (OpIdxGroup == CurGroup) 1114 return OpIdx - Delta; 1115 1116 // OpIdx is a def tied to this use group. 1117 if (OpIdxGroup == TiedGroup) 1118 return OpIdx + Delta; 1119 } 1120 llvm_unreachable("Invalid tied operand on inline asm"); 1121 } 1122 1123 /// clearKillInfo - Clears kill flags on all operands. 1124 /// 1125 void MachineInstr::clearKillInfo() { 1126 for (MachineOperand &MO : operands()) { 1127 if (MO.isReg() && MO.isUse()) 1128 MO.setIsKill(false); 1129 } 1130 } 1131 1132 void MachineInstr::substituteRegister(unsigned FromReg, unsigned ToReg, 1133 unsigned SubIdx, 1134 const TargetRegisterInfo &RegInfo) { 1135 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) { 1136 if (SubIdx) 1137 ToReg = RegInfo.getSubReg(ToReg, SubIdx); 1138 for (MachineOperand &MO : operands()) { 1139 if (!MO.isReg() || MO.getReg() != FromReg) 1140 continue; 1141 MO.substPhysReg(ToReg, RegInfo); 1142 } 1143 } else { 1144 for (MachineOperand &MO : operands()) { 1145 if (!MO.isReg() || MO.getReg() != FromReg) 1146 continue; 1147 MO.substVirtReg(ToReg, SubIdx, RegInfo); 1148 } 1149 } 1150 } 1151 1152 /// isSafeToMove - Return true if it is safe to move this instruction. If 1153 /// SawStore is set to true, it means that there is a store (or call) between 1154 /// the instruction's location and its intended destination. 1155 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const { 1156 // Ignore stuff that we obviously can't move. 1157 // 1158 // Treat volatile loads as stores. This is not strictly necessary for 1159 // volatiles, but it is required for atomic loads. It is not allowed to move 1160 // a load across an atomic load with Ordering > Monotonic. 1161 if (mayStore() || isCall() || isPHI() || 1162 (mayLoad() && hasOrderedMemoryRef())) { 1163 SawStore = true; 1164 return false; 1165 } 1166 1167 if (isPosition() || isDebugInstr() || isTerminator() || 1168 hasUnmodeledSideEffects()) 1169 return false; 1170 1171 // See if this instruction does a load. If so, we have to guarantee that the 1172 // loaded value doesn't change between the load and the its intended 1173 // destination. The check for isInvariantLoad gives the targe the chance to 1174 // classify the load as always returning a constant, e.g. a constant pool 1175 // load. 1176 if (mayLoad() && !isDereferenceableInvariantLoad(AA)) 1177 // Otherwise, this is a real load. If there is a store between the load and 1178 // end of block, we can't move it. 1179 return !SawStore; 1180 1181 return true; 1182 } 1183 1184 bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other, 1185 bool UseTBAA) { 1186 const MachineFunction *MF = getMF(); 1187 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1188 const MachineFrameInfo &MFI = MF->getFrameInfo(); 1189 1190 // If neither instruction stores to memory, they can't alias in any 1191 // meaningful way, even if they read from the same address. 1192 if (!mayStore() && !Other.mayStore()) 1193 return false; 1194 1195 // Let the target decide if memory accesses cannot possibly overlap. 1196 if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA)) 1197 return false; 1198 1199 // FIXME: Need to handle multiple memory operands to support all targets. 1200 if (!hasOneMemOperand() || !Other.hasOneMemOperand()) 1201 return true; 1202 1203 MachineMemOperand *MMOa = *memoperands_begin(); 1204 MachineMemOperand *MMOb = *Other.memoperands_begin(); 1205 1206 // The following interface to AA is fashioned after DAGCombiner::isAlias 1207 // and operates with MachineMemOperand offset with some important 1208 // assumptions: 1209 // - LLVM fundamentally assumes flat address spaces. 1210 // - MachineOperand offset can *only* result from legalization and 1211 // cannot affect queries other than the trivial case of overlap 1212 // checking. 1213 // - These offsets never wrap and never step outside 1214 // of allocated objects. 1215 // - There should never be any negative offsets here. 1216 // 1217 // FIXME: Modify API to hide this math from "user" 1218 // Even before we go to AA we can reason locally about some 1219 // memory objects. It can save compile time, and possibly catch some 1220 // corner cases not currently covered. 1221 1222 int64_t OffsetA = MMOa->getOffset(); 1223 int64_t OffsetB = MMOb->getOffset(); 1224 int64_t MinOffset = std::min(OffsetA, OffsetB); 1225 1226 uint64_t WidthA = MMOa->getSize(); 1227 uint64_t WidthB = MMOb->getSize(); 1228 bool KnownWidthA = WidthA != MemoryLocation::UnknownSize; 1229 bool KnownWidthB = WidthB != MemoryLocation::UnknownSize; 1230 1231 const Value *ValA = MMOa->getValue(); 1232 const Value *ValB = MMOb->getValue(); 1233 bool SameVal = (ValA && ValB && (ValA == ValB)); 1234 if (!SameVal) { 1235 const PseudoSourceValue *PSVa = MMOa->getPseudoValue(); 1236 const PseudoSourceValue *PSVb = MMOb->getPseudoValue(); 1237 if (PSVa && ValB && !PSVa->mayAlias(&MFI)) 1238 return false; 1239 if (PSVb && ValA && !PSVb->mayAlias(&MFI)) 1240 return false; 1241 if (PSVa && PSVb && (PSVa == PSVb)) 1242 SameVal = true; 1243 } 1244 1245 if (SameVal) { 1246 if (!KnownWidthA || !KnownWidthB) 1247 return true; 1248 int64_t MaxOffset = std::max(OffsetA, OffsetB); 1249 int64_t LowWidth = (MinOffset == OffsetA) ? WidthA : WidthB; 1250 return (MinOffset + LowWidth > MaxOffset); 1251 } 1252 1253 if (!AA) 1254 return true; 1255 1256 if (!ValA || !ValB) 1257 return true; 1258 1259 assert((OffsetA >= 0) && "Negative MachineMemOperand offset"); 1260 assert((OffsetB >= 0) && "Negative MachineMemOperand offset"); 1261 1262 int64_t OverlapA = KnownWidthA ? WidthA + OffsetA - MinOffset 1263 : MemoryLocation::UnknownSize; 1264 int64_t OverlapB = KnownWidthB ? WidthB + OffsetB - MinOffset 1265 : MemoryLocation::UnknownSize; 1266 1267 AliasResult AAResult = AA->alias( 1268 MemoryLocation(ValA, OverlapA, 1269 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()), 1270 MemoryLocation(ValB, OverlapB, 1271 UseTBAA ? MMOb->getAAInfo() : AAMDNodes())); 1272 1273 return (AAResult != NoAlias); 1274 } 1275 1276 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered 1277 /// or volatile memory reference, or if the information describing the memory 1278 /// reference is not available. Return false if it is known to have no ordered 1279 /// memory references. 1280 bool MachineInstr::hasOrderedMemoryRef() const { 1281 // An instruction known never to access memory won't have a volatile access. 1282 if (!mayStore() && 1283 !mayLoad() && 1284 !isCall() && 1285 !hasUnmodeledSideEffects()) 1286 return false; 1287 1288 // Otherwise, if the instruction has no memory reference information, 1289 // conservatively assume it wasn't preserved. 1290 if (memoperands_empty()) 1291 return true; 1292 1293 // Check if any of our memory operands are ordered. 1294 return llvm::any_of(memoperands(), [](const MachineMemOperand *MMO) { 1295 return !MMO->isUnordered(); 1296 }); 1297 } 1298 1299 /// isDereferenceableInvariantLoad - Return true if this instruction will never 1300 /// trap and is loading from a location whose value is invariant across a run of 1301 /// this function. 1302 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const { 1303 // If the instruction doesn't load at all, it isn't an invariant load. 1304 if (!mayLoad()) 1305 return false; 1306 1307 // If the instruction has lost its memoperands, conservatively assume that 1308 // it may not be an invariant load. 1309 if (memoperands_empty()) 1310 return false; 1311 1312 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo(); 1313 1314 for (MachineMemOperand *MMO : memoperands()) { 1315 if (MMO->isVolatile()) return false; 1316 // TODO: Figure out whether isAtomic is really necessary (see D57601). 1317 if (MMO->isAtomic()) return false; 1318 if (MMO->isStore()) return false; 1319 if (MMO->isInvariant() && MMO->isDereferenceable()) 1320 continue; 1321 1322 // A load from a constant PseudoSourceValue is invariant. 1323 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) 1324 if (PSV->isConstant(&MFI)) 1325 continue; 1326 1327 if (const Value *V = MMO->getValue()) { 1328 // If we have an AliasAnalysis, ask it whether the memory is constant. 1329 if (AA && 1330 AA->pointsToConstantMemory( 1331 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo()))) 1332 continue; 1333 } 1334 1335 // Otherwise assume conservatively. 1336 return false; 1337 } 1338 1339 // Everything checks out. 1340 return true; 1341 } 1342 1343 /// isConstantValuePHI - If the specified instruction is a PHI that always 1344 /// merges together the same virtual register, return the register, otherwise 1345 /// return 0. 1346 unsigned MachineInstr::isConstantValuePHI() const { 1347 if (!isPHI()) 1348 return 0; 1349 assert(getNumOperands() >= 3 && 1350 "It's illegal to have a PHI without source operands"); 1351 1352 unsigned Reg = getOperand(1).getReg(); 1353 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2) 1354 if (getOperand(i).getReg() != Reg) 1355 return 0; 1356 return Reg; 1357 } 1358 1359 bool MachineInstr::hasUnmodeledSideEffects() const { 1360 if (hasProperty(MCID::UnmodeledSideEffects)) 1361 return true; 1362 if (isInlineAsm()) { 1363 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1364 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1365 return true; 1366 } 1367 1368 return false; 1369 } 1370 1371 bool MachineInstr::isLoadFoldBarrier() const { 1372 return mayStore() || isCall() || hasUnmodeledSideEffects(); 1373 } 1374 1375 /// allDefsAreDead - Return true if all the defs of this instruction are dead. 1376 /// 1377 bool MachineInstr::allDefsAreDead() const { 1378 for (const MachineOperand &MO : operands()) { 1379 if (!MO.isReg() || MO.isUse()) 1380 continue; 1381 if (!MO.isDead()) 1382 return false; 1383 } 1384 return true; 1385 } 1386 1387 /// copyImplicitOps - Copy implicit register operands from specified 1388 /// instruction to this instruction. 1389 void MachineInstr::copyImplicitOps(MachineFunction &MF, 1390 const MachineInstr &MI) { 1391 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands(); 1392 i != e; ++i) { 1393 const MachineOperand &MO = MI.getOperand(i); 1394 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask()) 1395 addOperand(MF, MO); 1396 } 1397 } 1398 1399 bool MachineInstr::hasComplexRegisterTies() const { 1400 const MCInstrDesc &MCID = getDesc(); 1401 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 1402 const auto &Operand = getOperand(I); 1403 if (!Operand.isReg() || Operand.isDef()) 1404 // Ignore the defined registers as MCID marks only the uses as tied. 1405 continue; 1406 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO); 1407 int TiedIdx = Operand.isTied() ? int(findTiedOperandIdx(I)) : -1; 1408 if (ExpectedTiedIdx != TiedIdx) 1409 return true; 1410 } 1411 return false; 1412 } 1413 1414 LLT MachineInstr::getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes, 1415 const MachineRegisterInfo &MRI) const { 1416 const MachineOperand &Op = getOperand(OpIdx); 1417 if (!Op.isReg()) 1418 return LLT{}; 1419 1420 if (isVariadic() || OpIdx >= getNumExplicitOperands()) 1421 return MRI.getType(Op.getReg()); 1422 1423 auto &OpInfo = getDesc().OpInfo[OpIdx]; 1424 if (!OpInfo.isGenericType()) 1425 return MRI.getType(Op.getReg()); 1426 1427 if (PrintedTypes[OpInfo.getGenericTypeIndex()]) 1428 return LLT{}; 1429 1430 LLT TypeToPrint = MRI.getType(Op.getReg()); 1431 // Don't mark the type index printed if it wasn't actually printed: maybe 1432 // another operand with the same type index has an actual type attached: 1433 if (TypeToPrint.isValid()) 1434 PrintedTypes.set(OpInfo.getGenericTypeIndex()); 1435 return TypeToPrint; 1436 } 1437 1438 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1439 LLVM_DUMP_METHOD void MachineInstr::dump() const { 1440 dbgs() << " "; 1441 print(dbgs()); 1442 } 1443 #endif 1444 1445 void MachineInstr::print(raw_ostream &OS, bool IsStandalone, bool SkipOpers, 1446 bool SkipDebugLoc, bool AddNewLine, 1447 const TargetInstrInfo *TII) const { 1448 const Module *M = nullptr; 1449 const Function *F = nullptr; 1450 if (const MachineFunction *MF = getMFIfAvailable(*this)) { 1451 F = &MF->getFunction(); 1452 M = F->getParent(); 1453 if (!TII) 1454 TII = MF->getSubtarget().getInstrInfo(); 1455 } 1456 1457 ModuleSlotTracker MST(M); 1458 if (F) 1459 MST.incorporateFunction(*F); 1460 print(OS, MST, IsStandalone, SkipOpers, SkipDebugLoc, TII); 1461 } 1462 1463 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST, 1464 bool IsStandalone, bool SkipOpers, bool SkipDebugLoc, 1465 bool AddNewLine, const TargetInstrInfo *TII) const { 1466 // We can be a bit tidier if we know the MachineFunction. 1467 const MachineFunction *MF = nullptr; 1468 const TargetRegisterInfo *TRI = nullptr; 1469 const MachineRegisterInfo *MRI = nullptr; 1470 const TargetIntrinsicInfo *IntrinsicInfo = nullptr; 1471 tryToGetTargetInfo(*this, TRI, MRI, IntrinsicInfo, TII); 1472 1473 if (isCFIInstruction()) 1474 assert(getNumOperands() == 1 && "Expected 1 operand in CFI instruction"); 1475 1476 SmallBitVector PrintedTypes(8); 1477 bool ShouldPrintRegisterTies = IsStandalone || hasComplexRegisterTies(); 1478 auto getTiedOperandIdx = [&](unsigned OpIdx) { 1479 if (!ShouldPrintRegisterTies) 1480 return 0U; 1481 const MachineOperand &MO = getOperand(OpIdx); 1482 if (MO.isReg() && MO.isTied() && !MO.isDef()) 1483 return findTiedOperandIdx(OpIdx); 1484 return 0U; 1485 }; 1486 unsigned StartOp = 0; 1487 unsigned e = getNumOperands(); 1488 1489 // Print explicitly defined operands on the left of an assignment syntax. 1490 while (StartOp < e) { 1491 const MachineOperand &MO = getOperand(StartOp); 1492 if (!MO.isReg() || !MO.isDef() || MO.isImplicit()) 1493 break; 1494 1495 if (StartOp != 0) 1496 OS << ", "; 1497 1498 LLT TypeToPrint = MRI ? getTypeToPrint(StartOp, PrintedTypes, *MRI) : LLT{}; 1499 unsigned TiedOperandIdx = getTiedOperandIdx(StartOp); 1500 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/false, IsStandalone, 1501 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1502 ++StartOp; 1503 } 1504 1505 if (StartOp != 0) 1506 OS << " = "; 1507 1508 if (getFlag(MachineInstr::FrameSetup)) 1509 OS << "frame-setup "; 1510 if (getFlag(MachineInstr::FrameDestroy)) 1511 OS << "frame-destroy "; 1512 if (getFlag(MachineInstr::FmNoNans)) 1513 OS << "nnan "; 1514 if (getFlag(MachineInstr::FmNoInfs)) 1515 OS << "ninf "; 1516 if (getFlag(MachineInstr::FmNsz)) 1517 OS << "nsz "; 1518 if (getFlag(MachineInstr::FmArcp)) 1519 OS << "arcp "; 1520 if (getFlag(MachineInstr::FmContract)) 1521 OS << "contract "; 1522 if (getFlag(MachineInstr::FmAfn)) 1523 OS << "afn "; 1524 if (getFlag(MachineInstr::FmReassoc)) 1525 OS << "reassoc "; 1526 if (getFlag(MachineInstr::NoUWrap)) 1527 OS << "nuw "; 1528 if (getFlag(MachineInstr::NoSWrap)) 1529 OS << "nsw "; 1530 if (getFlag(MachineInstr::IsExact)) 1531 OS << "exact "; 1532 1533 // Print the opcode name. 1534 if (TII) 1535 OS << TII->getName(getOpcode()); 1536 else 1537 OS << "UNKNOWN"; 1538 1539 if (SkipOpers) 1540 return; 1541 1542 // Print the rest of the operands. 1543 bool FirstOp = true; 1544 unsigned AsmDescOp = ~0u; 1545 unsigned AsmOpCount = 0; 1546 1547 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) { 1548 // Print asm string. 1549 OS << " "; 1550 const unsigned OpIdx = InlineAsm::MIOp_AsmString; 1551 LLT TypeToPrint = MRI ? getTypeToPrint(OpIdx, PrintedTypes, *MRI) : LLT{}; 1552 unsigned TiedOperandIdx = getTiedOperandIdx(OpIdx); 1553 getOperand(OpIdx).print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone, 1554 ShouldPrintRegisterTies, TiedOperandIdx, TRI, 1555 IntrinsicInfo); 1556 1557 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack 1558 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1559 if (ExtraInfo & InlineAsm::Extra_HasSideEffects) 1560 OS << " [sideeffect]"; 1561 if (ExtraInfo & InlineAsm::Extra_MayLoad) 1562 OS << " [mayload]"; 1563 if (ExtraInfo & InlineAsm::Extra_MayStore) 1564 OS << " [maystore]"; 1565 if (ExtraInfo & InlineAsm::Extra_IsConvergent) 1566 OS << " [isconvergent]"; 1567 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 1568 OS << " [alignstack]"; 1569 if (getInlineAsmDialect() == InlineAsm::AD_ATT) 1570 OS << " [attdialect]"; 1571 if (getInlineAsmDialect() == InlineAsm::AD_Intel) 1572 OS << " [inteldialect]"; 1573 1574 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand; 1575 FirstOp = false; 1576 } 1577 1578 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) { 1579 const MachineOperand &MO = getOperand(i); 1580 1581 if (FirstOp) FirstOp = false; else OS << ","; 1582 OS << " "; 1583 1584 if (isDebugValue() && MO.isMetadata()) { 1585 // Pretty print DBG_VALUE instructions. 1586 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata()); 1587 if (DIV && !DIV->getName().empty()) 1588 OS << "!\"" << DIV->getName() << '\"'; 1589 else { 1590 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1591 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1592 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone, 1593 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1594 } 1595 } else if (isDebugLabel() && MO.isMetadata()) { 1596 // Pretty print DBG_LABEL instructions. 1597 auto *DIL = dyn_cast<DILabel>(MO.getMetadata()); 1598 if (DIL && !DIL->getName().empty()) 1599 OS << "\"" << DIL->getName() << '\"'; 1600 else { 1601 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1602 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1603 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone, 1604 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1605 } 1606 } else if (i == AsmDescOp && MO.isImm()) { 1607 // Pretty print the inline asm operand descriptor. 1608 OS << '$' << AsmOpCount++; 1609 unsigned Flag = MO.getImm(); 1610 switch (InlineAsm::getKind(Flag)) { 1611 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break; 1612 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break; 1613 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break; 1614 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break; 1615 case InlineAsm::Kind_Imm: OS << ":[imm"; break; 1616 case InlineAsm::Kind_Mem: OS << ":[mem"; break; 1617 default: OS << ":[??" << InlineAsm::getKind(Flag); break; 1618 } 1619 1620 unsigned RCID = 0; 1621 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) && 1622 InlineAsm::hasRegClassConstraint(Flag, RCID)) { 1623 if (TRI) { 1624 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID)); 1625 } else 1626 OS << ":RC" << RCID; 1627 } 1628 1629 if (InlineAsm::isMemKind(Flag)) { 1630 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag); 1631 switch (MCID) { 1632 case InlineAsm::Constraint_es: OS << ":es"; break; 1633 case InlineAsm::Constraint_i: OS << ":i"; break; 1634 case InlineAsm::Constraint_m: OS << ":m"; break; 1635 case InlineAsm::Constraint_o: OS << ":o"; break; 1636 case InlineAsm::Constraint_v: OS << ":v"; break; 1637 case InlineAsm::Constraint_Q: OS << ":Q"; break; 1638 case InlineAsm::Constraint_R: OS << ":R"; break; 1639 case InlineAsm::Constraint_S: OS << ":S"; break; 1640 case InlineAsm::Constraint_T: OS << ":T"; break; 1641 case InlineAsm::Constraint_Um: OS << ":Um"; break; 1642 case InlineAsm::Constraint_Un: OS << ":Un"; break; 1643 case InlineAsm::Constraint_Uq: OS << ":Uq"; break; 1644 case InlineAsm::Constraint_Us: OS << ":Us"; break; 1645 case InlineAsm::Constraint_Ut: OS << ":Ut"; break; 1646 case InlineAsm::Constraint_Uv: OS << ":Uv"; break; 1647 case InlineAsm::Constraint_Uy: OS << ":Uy"; break; 1648 case InlineAsm::Constraint_X: OS << ":X"; break; 1649 case InlineAsm::Constraint_Z: OS << ":Z"; break; 1650 case InlineAsm::Constraint_ZC: OS << ":ZC"; break; 1651 case InlineAsm::Constraint_Zy: OS << ":Zy"; break; 1652 default: OS << ":?"; break; 1653 } 1654 } 1655 1656 unsigned TiedTo = 0; 1657 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo)) 1658 OS << " tiedto:$" << TiedTo; 1659 1660 OS << ']'; 1661 1662 // Compute the index of the next operand descriptor. 1663 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag); 1664 } else { 1665 LLT TypeToPrint = MRI ? getTypeToPrint(i, PrintedTypes, *MRI) : LLT{}; 1666 unsigned TiedOperandIdx = getTiedOperandIdx(i); 1667 if (MO.isImm() && isOperandSubregIdx(i)) 1668 MachineOperand::printSubRegIdx(OS, MO.getImm(), TRI); 1669 else 1670 MO.print(OS, MST, TypeToPrint, /*PrintDef=*/true, IsStandalone, 1671 ShouldPrintRegisterTies, TiedOperandIdx, TRI, IntrinsicInfo); 1672 } 1673 } 1674 1675 // Print any optional symbols attached to this instruction as-if they were 1676 // operands. 1677 if (MCSymbol *PreInstrSymbol = getPreInstrSymbol()) { 1678 if (!FirstOp) { 1679 FirstOp = false; 1680 OS << ','; 1681 } 1682 OS << " pre-instr-symbol "; 1683 MachineOperand::printSymbol(OS, *PreInstrSymbol); 1684 } 1685 if (MCSymbol *PostInstrSymbol = getPostInstrSymbol()) { 1686 if (!FirstOp) { 1687 FirstOp = false; 1688 OS << ','; 1689 } 1690 OS << " post-instr-symbol "; 1691 MachineOperand::printSymbol(OS, *PostInstrSymbol); 1692 } 1693 1694 if (!SkipDebugLoc) { 1695 if (const DebugLoc &DL = getDebugLoc()) { 1696 if (!FirstOp) 1697 OS << ','; 1698 OS << " debug-location "; 1699 DL->printAsOperand(OS, MST); 1700 } 1701 } 1702 1703 if (!memoperands_empty()) { 1704 SmallVector<StringRef, 0> SSNs; 1705 const LLVMContext *Context = nullptr; 1706 std::unique_ptr<LLVMContext> CtxPtr; 1707 const MachineFrameInfo *MFI = nullptr; 1708 if (const MachineFunction *MF = getMFIfAvailable(*this)) { 1709 MFI = &MF->getFrameInfo(); 1710 Context = &MF->getFunction().getContext(); 1711 } else { 1712 CtxPtr = llvm::make_unique<LLVMContext>(); 1713 Context = CtxPtr.get(); 1714 } 1715 1716 OS << " :: "; 1717 bool NeedComma = false; 1718 for (const MachineMemOperand *Op : memoperands()) { 1719 if (NeedComma) 1720 OS << ", "; 1721 Op->print(OS, MST, SSNs, *Context, MFI, TII); 1722 NeedComma = true; 1723 } 1724 } 1725 1726 if (SkipDebugLoc) 1727 return; 1728 1729 bool HaveSemi = false; 1730 1731 // Print debug location information. 1732 if (const DebugLoc &DL = getDebugLoc()) { 1733 if (!HaveSemi) { 1734 OS << ';'; 1735 HaveSemi = true; 1736 } 1737 OS << ' '; 1738 DL.print(OS); 1739 } 1740 1741 // Print extra comments for DEBUG_VALUE. 1742 if (isDebugValue() && getOperand(e - 2).isMetadata()) { 1743 if (!HaveSemi) { 1744 OS << ";"; 1745 HaveSemi = true; 1746 } 1747 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata()); 1748 OS << " line no:" << DV->getLine(); 1749 if (auto *InlinedAt = debugLoc->getInlinedAt()) { 1750 DebugLoc InlinedAtDL(InlinedAt); 1751 if (InlinedAtDL && MF) { 1752 OS << " inlined @[ "; 1753 InlinedAtDL.print(OS); 1754 OS << " ]"; 1755 } 1756 } 1757 if (isIndirectDebugValue()) 1758 OS << " indirect"; 1759 } 1760 // TODO: DBG_LABEL 1761 1762 if (AddNewLine) 1763 OS << '\n'; 1764 } 1765 1766 bool MachineInstr::addRegisterKilled(unsigned IncomingReg, 1767 const TargetRegisterInfo *RegInfo, 1768 bool AddIfNotFound) { 1769 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg); 1770 bool hasAliases = isPhysReg && 1771 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid(); 1772 bool Found = false; 1773 SmallVector<unsigned,4> DeadOps; 1774 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1775 MachineOperand &MO = getOperand(i); 1776 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) 1777 continue; 1778 1779 // DEBUG_VALUE nodes do not contribute to code generation and should 1780 // always be ignored. Failure to do so may result in trying to modify 1781 // KILL flags on DEBUG_VALUE nodes. 1782 if (MO.isDebug()) 1783 continue; 1784 1785 unsigned Reg = MO.getReg(); 1786 if (!Reg) 1787 continue; 1788 1789 if (Reg == IncomingReg) { 1790 if (!Found) { 1791 if (MO.isKill()) 1792 // The register is already marked kill. 1793 return true; 1794 if (isPhysReg && isRegTiedToDefOperand(i)) 1795 // Two-address uses of physregs must not be marked kill. 1796 return true; 1797 MO.setIsKill(); 1798 Found = true; 1799 } 1800 } else if (hasAliases && MO.isKill() && 1801 TargetRegisterInfo::isPhysicalRegister(Reg)) { 1802 // A super-register kill already exists. 1803 if (RegInfo->isSuperRegister(IncomingReg, Reg)) 1804 return true; 1805 if (RegInfo->isSubRegister(IncomingReg, Reg)) 1806 DeadOps.push_back(i); 1807 } 1808 } 1809 1810 // Trim unneeded kill operands. 1811 while (!DeadOps.empty()) { 1812 unsigned OpIdx = DeadOps.back(); 1813 if (getOperand(OpIdx).isImplicit() && 1814 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0)) 1815 RemoveOperand(OpIdx); 1816 else 1817 getOperand(OpIdx).setIsKill(false); 1818 DeadOps.pop_back(); 1819 } 1820 1821 // If not found, this means an alias of one of the operands is killed. Add a 1822 // new implicit operand if required. 1823 if (!Found && AddIfNotFound) { 1824 addOperand(MachineOperand::CreateReg(IncomingReg, 1825 false /*IsDef*/, 1826 true /*IsImp*/, 1827 true /*IsKill*/)); 1828 return true; 1829 } 1830 return Found; 1831 } 1832 1833 void MachineInstr::clearRegisterKills(unsigned Reg, 1834 const TargetRegisterInfo *RegInfo) { 1835 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) 1836 RegInfo = nullptr; 1837 for (MachineOperand &MO : operands()) { 1838 if (!MO.isReg() || !MO.isUse() || !MO.isKill()) 1839 continue; 1840 unsigned OpReg = MO.getReg(); 1841 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg) 1842 MO.setIsKill(false); 1843 } 1844 } 1845 1846 bool MachineInstr::addRegisterDead(unsigned Reg, 1847 const TargetRegisterInfo *RegInfo, 1848 bool AddIfNotFound) { 1849 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg); 1850 bool hasAliases = isPhysReg && 1851 MCRegAliasIterator(Reg, RegInfo, false).isValid(); 1852 bool Found = false; 1853 SmallVector<unsigned,4> DeadOps; 1854 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 1855 MachineOperand &MO = getOperand(i); 1856 if (!MO.isReg() || !MO.isDef()) 1857 continue; 1858 unsigned MOReg = MO.getReg(); 1859 if (!MOReg) 1860 continue; 1861 1862 if (MOReg == Reg) { 1863 MO.setIsDead(); 1864 Found = true; 1865 } else if (hasAliases && MO.isDead() && 1866 TargetRegisterInfo::isPhysicalRegister(MOReg)) { 1867 // There exists a super-register that's marked dead. 1868 if (RegInfo->isSuperRegister(Reg, MOReg)) 1869 return true; 1870 if (RegInfo->isSubRegister(Reg, MOReg)) 1871 DeadOps.push_back(i); 1872 } 1873 } 1874 1875 // Trim unneeded dead operands. 1876 while (!DeadOps.empty()) { 1877 unsigned OpIdx = DeadOps.back(); 1878 if (getOperand(OpIdx).isImplicit() && 1879 (!isInlineAsm() || findInlineAsmFlagIdx(OpIdx) < 0)) 1880 RemoveOperand(OpIdx); 1881 else 1882 getOperand(OpIdx).setIsDead(false); 1883 DeadOps.pop_back(); 1884 } 1885 1886 // If not found, this means an alias of one of the operands is dead. Add a 1887 // new implicit operand if required. 1888 if (Found || !AddIfNotFound) 1889 return Found; 1890 1891 addOperand(MachineOperand::CreateReg(Reg, 1892 true /*IsDef*/, 1893 true /*IsImp*/, 1894 false /*IsKill*/, 1895 true /*IsDead*/)); 1896 return true; 1897 } 1898 1899 void MachineInstr::clearRegisterDeads(unsigned Reg) { 1900 for (MachineOperand &MO : operands()) { 1901 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg) 1902 continue; 1903 MO.setIsDead(false); 1904 } 1905 } 1906 1907 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) { 1908 for (MachineOperand &MO : operands()) { 1909 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0) 1910 continue; 1911 MO.setIsUndef(IsUndef); 1912 } 1913 } 1914 1915 void MachineInstr::addRegisterDefined(unsigned Reg, 1916 const TargetRegisterInfo *RegInfo) { 1917 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 1918 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo); 1919 if (MO) 1920 return; 1921 } else { 1922 for (const MachineOperand &MO : operands()) { 1923 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() && 1924 MO.getSubReg() == 0) 1925 return; 1926 } 1927 } 1928 addOperand(MachineOperand::CreateReg(Reg, 1929 true /*IsDef*/, 1930 true /*IsImp*/)); 1931 } 1932 1933 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs, 1934 const TargetRegisterInfo &TRI) { 1935 bool HasRegMask = false; 1936 for (MachineOperand &MO : operands()) { 1937 if (MO.isRegMask()) { 1938 HasRegMask = true; 1939 continue; 1940 } 1941 if (!MO.isReg() || !MO.isDef()) continue; 1942 unsigned Reg = MO.getReg(); 1943 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue; 1944 // If there are no uses, including partial uses, the def is dead. 1945 if (llvm::none_of(UsedRegs, 1946 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); })) 1947 MO.setIsDead(); 1948 } 1949 1950 // This is a call with a register mask operand. 1951 // Mask clobbers are always dead, so add defs for the non-dead defines. 1952 if (HasRegMask) 1953 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end(); 1954 I != E; ++I) 1955 addRegisterDefined(*I, &TRI); 1956 } 1957 1958 unsigned 1959 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) { 1960 // Build up a buffer of hash code components. 1961 SmallVector<size_t, 8> HashComponents; 1962 HashComponents.reserve(MI->getNumOperands() + 1); 1963 HashComponents.push_back(MI->getOpcode()); 1964 for (const MachineOperand &MO : MI->operands()) { 1965 if (MO.isReg() && MO.isDef() && 1966 TargetRegisterInfo::isVirtualRegister(MO.getReg())) 1967 continue; // Skip virtual register defs. 1968 1969 HashComponents.push_back(hash_value(MO)); 1970 } 1971 return hash_combine_range(HashComponents.begin(), HashComponents.end()); 1972 } 1973 1974 void MachineInstr::emitError(StringRef Msg) const { 1975 // Find the source location cookie. 1976 unsigned LocCookie = 0; 1977 const MDNode *LocMD = nullptr; 1978 for (unsigned i = getNumOperands(); i != 0; --i) { 1979 if (getOperand(i-1).isMetadata() && 1980 (LocMD = getOperand(i-1).getMetadata()) && 1981 LocMD->getNumOperands() != 0) { 1982 if (const ConstantInt *CI = 1983 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) { 1984 LocCookie = CI->getZExtValue(); 1985 break; 1986 } 1987 } 1988 } 1989 1990 if (const MachineBasicBlock *MBB = getParent()) 1991 if (const MachineFunction *MF = MBB->getParent()) 1992 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg); 1993 report_fatal_error(Msg); 1994 } 1995 1996 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL, 1997 const MCInstrDesc &MCID, bool IsIndirect, 1998 unsigned Reg, const MDNode *Variable, 1999 const MDNode *Expr) { 2000 assert(isa<DILocalVariable>(Variable) && "not a variable"); 2001 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 2002 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 2003 "Expected inlined-at fields to agree"); 2004 auto MIB = BuildMI(MF, DL, MCID).addReg(Reg, RegState::Debug); 2005 if (IsIndirect) 2006 MIB.addImm(0U); 2007 else 2008 MIB.addReg(0U, RegState::Debug); 2009 return MIB.addMetadata(Variable).addMetadata(Expr); 2010 } 2011 2012 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL, 2013 const MCInstrDesc &MCID, bool IsIndirect, 2014 MachineOperand &MO, const MDNode *Variable, 2015 const MDNode *Expr) { 2016 assert(isa<DILocalVariable>(Variable) && "not a variable"); 2017 assert(cast<DIExpression>(Expr)->isValid() && "not an expression"); 2018 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 2019 "Expected inlined-at fields to agree"); 2020 if (MO.isReg()) 2021 return BuildMI(MF, DL, MCID, IsIndirect, MO.getReg(), Variable, Expr); 2022 2023 auto MIB = BuildMI(MF, DL, MCID).add(MO); 2024 if (IsIndirect) 2025 MIB.addImm(0U); 2026 else 2027 MIB.addReg(0U, RegState::Debug); 2028 return MIB.addMetadata(Variable).addMetadata(Expr); 2029 } 2030 2031 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB, 2032 MachineBasicBlock::iterator I, 2033 const DebugLoc &DL, const MCInstrDesc &MCID, 2034 bool IsIndirect, unsigned Reg, 2035 const MDNode *Variable, const MDNode *Expr) { 2036 MachineFunction &MF = *BB.getParent(); 2037 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, Reg, Variable, Expr); 2038 BB.insert(I, MI); 2039 return MachineInstrBuilder(MF, MI); 2040 } 2041 2042 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB, 2043 MachineBasicBlock::iterator I, 2044 const DebugLoc &DL, const MCInstrDesc &MCID, 2045 bool IsIndirect, MachineOperand &MO, 2046 const MDNode *Variable, const MDNode *Expr) { 2047 MachineFunction &MF = *BB.getParent(); 2048 MachineInstr *MI = BuildMI(MF, DL, MCID, IsIndirect, MO, Variable, Expr); 2049 BB.insert(I, MI); 2050 return MachineInstrBuilder(MF, *MI); 2051 } 2052 2053 /// Compute the new DIExpression to use with a DBG_VALUE for a spill slot. 2054 /// This prepends DW_OP_deref when spilling an indirect DBG_VALUE. 2055 static const DIExpression *computeExprForSpill(const MachineInstr &MI) { 2056 assert(MI.getOperand(0).isReg() && "can't spill non-register"); 2057 assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) && 2058 "Expected inlined-at fields to agree"); 2059 2060 const DIExpression *Expr = MI.getDebugExpression(); 2061 if (MI.isIndirectDebugValue()) { 2062 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset"); 2063 Expr = DIExpression::prepend(Expr, DIExpression::WithDeref); 2064 } 2065 return Expr; 2066 } 2067 2068 MachineInstr *llvm::buildDbgValueForSpill(MachineBasicBlock &BB, 2069 MachineBasicBlock::iterator I, 2070 const MachineInstr &Orig, 2071 int FrameIndex) { 2072 const DIExpression *Expr = computeExprForSpill(Orig); 2073 return BuildMI(BB, I, Orig.getDebugLoc(), Orig.getDesc()) 2074 .addFrameIndex(FrameIndex) 2075 .addImm(0U) 2076 .addMetadata(Orig.getDebugVariable()) 2077 .addMetadata(Expr); 2078 } 2079 2080 void llvm::updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex) { 2081 const DIExpression *Expr = computeExprForSpill(Orig); 2082 Orig.getOperand(0).ChangeToFrameIndex(FrameIndex); 2083 Orig.getOperand(1).ChangeToImmediate(0U); 2084 Orig.getOperand(3).setMetadata(Expr); 2085 } 2086 2087 void MachineInstr::collectDebugValues( 2088 SmallVectorImpl<MachineInstr *> &DbgValues) { 2089 MachineInstr &MI = *this; 2090 if (!MI.getOperand(0).isReg()) 2091 return; 2092 2093 MachineBasicBlock::iterator DI = MI; ++DI; 2094 for (MachineBasicBlock::iterator DE = MI.getParent()->end(); 2095 DI != DE; ++DI) { 2096 if (!DI->isDebugValue()) 2097 return; 2098 if (DI->getOperand(0).isReg() && 2099 DI->getOperand(0).getReg() == MI.getOperand(0).getReg()) 2100 DbgValues.push_back(&*DI); 2101 } 2102 } 2103 2104 void MachineInstr::changeDebugValuesDefReg(unsigned Reg) { 2105 // Collect matching debug values. 2106 SmallVector<MachineInstr *, 2> DbgValues; 2107 collectDebugValues(DbgValues); 2108 2109 // Propagate Reg to debug value instructions. 2110 for (auto *DBI : DbgValues) 2111 DBI->getOperand(0).setReg(Reg); 2112 } 2113 2114 using MMOList = SmallVector<const MachineMemOperand *, 2>; 2115 2116 static unsigned getSpillSlotSize(MMOList &Accesses, 2117 const MachineFrameInfo &MFI) { 2118 unsigned Size = 0; 2119 for (auto A : Accesses) 2120 if (MFI.isSpillSlotObjectIndex( 2121 cast<FixedStackPseudoSourceValue>(A->getPseudoValue()) 2122 ->getFrameIndex())) 2123 Size += A->getSize(); 2124 return Size; 2125 } 2126 2127 Optional<unsigned> 2128 MachineInstr::getSpillSize(const TargetInstrInfo *TII) const { 2129 int FI; 2130 if (TII->isStoreToStackSlotPostFE(*this, FI)) { 2131 const MachineFrameInfo &MFI = getMF()->getFrameInfo(); 2132 if (MFI.isSpillSlotObjectIndex(FI)) 2133 return (*memoperands_begin())->getSize(); 2134 } 2135 return None; 2136 } 2137 2138 Optional<unsigned> 2139 MachineInstr::getFoldedSpillSize(const TargetInstrInfo *TII) const { 2140 MMOList Accesses; 2141 if (TII->hasStoreToStackSlot(*this, Accesses)) 2142 return getSpillSlotSize(Accesses, getMF()->getFrameInfo()); 2143 return None; 2144 } 2145 2146 Optional<unsigned> 2147 MachineInstr::getRestoreSize(const TargetInstrInfo *TII) const { 2148 int FI; 2149 if (TII->isLoadFromStackSlotPostFE(*this, FI)) { 2150 const MachineFrameInfo &MFI = getMF()->getFrameInfo(); 2151 if (MFI.isSpillSlotObjectIndex(FI)) 2152 return (*memoperands_begin())->getSize(); 2153 } 2154 return None; 2155 } 2156 2157 Optional<unsigned> 2158 MachineInstr::getFoldedRestoreSize(const TargetInstrInfo *TII) const { 2159 MMOList Accesses; 2160 if (TII->hasLoadFromStackSlot(*this, Accesses)) 2161 return getSpillSlotSize(Accesses, getMF()->getFrameInfo()); 2162 return None; 2163 } 2164