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