1 //===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- C++ -*-===// 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 // This file contains the declaration of the MachineInstr class, which is the 10 // basic representation for all target dependent machine instructions used by 11 // the back end. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CODEGEN_MACHINEINSTR_H 16 #define LLVM_CODEGEN_MACHINEINSTR_H 17 18 #include "llvm/ADT/DenseMapInfo.h" 19 #include "llvm/ADT/PointerSumType.h" 20 #include "llvm/ADT/ilist.h" 21 #include "llvm/ADT/ilist_node.h" 22 #include "llvm/ADT/iterator_range.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineMemOperand.h" 25 #include "llvm/CodeGen/MachineOperand.h" 26 #include "llvm/CodeGen/TargetOpcodes.h" 27 #include "llvm/IR/DebugLoc.h" 28 #include "llvm/IR/InlineAsm.h" 29 #include "llvm/MC/MCInstrDesc.h" 30 #include "llvm/MC/MCSymbol.h" 31 #include "llvm/Support/ArrayRecycler.h" 32 #include "llvm/Support/MathExtras.h" 33 #include "llvm/Support/TrailingObjects.h" 34 #include <algorithm> 35 #include <cassert> 36 #include <cstdint> 37 #include <utility> 38 39 namespace llvm { 40 41 class DILabel; 42 class Instruction; 43 class MDNode; 44 class AAResults; 45 class BatchAAResults; 46 template <typename T> class ArrayRef; 47 class DIExpression; 48 class DILocalVariable; 49 class LiveRegUnits; 50 class MachineBasicBlock; 51 class MachineFunction; 52 class MachineRegisterInfo; 53 class ModuleSlotTracker; 54 class raw_ostream; 55 template <typename T> class SmallVectorImpl; 56 class SmallBitVector; 57 class StringRef; 58 class TargetInstrInfo; 59 class TargetRegisterClass; 60 class TargetRegisterInfo; 61 62 //===----------------------------------------------------------------------===// 63 /// Representation of each machine instruction. 64 /// 65 /// This class isn't a POD type, but it must have a trivial destructor. When a 66 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated 67 /// without having their destructor called. 68 /// 69 class MachineInstr 70 : public ilist_node_with_parent<MachineInstr, MachineBasicBlock, 71 ilist_sentinel_tracking<true>> { 72 public: 73 using mmo_iterator = ArrayRef<MachineMemOperand *>::iterator; 74 75 /// Flags to specify different kinds of comments to output in 76 /// assembly code. These flags carry semantic information not 77 /// otherwise easily derivable from the IR text. 78 /// 79 enum CommentFlag { 80 ReloadReuse = 0x1, // higher bits are reserved for target dep comments. 81 NoSchedComment = 0x2, 82 TAsmComments = 0x4 // Target Asm comments should start from this value. 83 }; 84 85 enum MIFlag { 86 NoFlags = 0, 87 FrameSetup = 1 << 0, // Instruction is used as a part of 88 // function frame setup code. 89 FrameDestroy = 1 << 1, // Instruction is used as a part of 90 // function frame destruction code. 91 BundledPred = 1 << 2, // Instruction has bundled predecessors. 92 BundledSucc = 1 << 3, // Instruction has bundled successors. 93 FmNoNans = 1 << 4, // Instruction does not support Fast 94 // math nan values. 95 FmNoInfs = 1 << 5, // Instruction does not support Fast 96 // math infinity values. 97 FmNsz = 1 << 6, // Instruction is not required to retain 98 // signed zero values. 99 FmArcp = 1 << 7, // Instruction supports Fast math 100 // reciprocal approximations. 101 FmContract = 1 << 8, // Instruction supports Fast math 102 // contraction operations like fma. 103 FmAfn = 1 << 9, // Instruction may map to Fast math 104 // intrinsic approximation. 105 FmReassoc = 1 << 10, // Instruction supports Fast math 106 // reassociation of operand order. 107 NoUWrap = 1 << 11, // Instruction supports binary operator 108 // no unsigned wrap. 109 NoSWrap = 1 << 12, // Instruction supports binary operator 110 // no signed wrap. 111 IsExact = 1 << 13, // Instruction supports division is 112 // known to be exact. 113 NoFPExcept = 1 << 14, // Instruction does not raise 114 // floatint-point exceptions. 115 NoMerge = 1 << 15, // Passes that drop source location info 116 // (e.g. branch folding) should skip 117 // this instruction. 118 Unpredictable = 1 << 16, // Instruction with unpredictable condition. 119 NoConvergent = 1 << 17, // Call does not require convergence guarantees. 120 NonNeg = 1 << 18, // The operand is non-negative. 121 Disjoint = 1 << 19, // Each bit is zero in at least one of the inputs. 122 NoUSWrap = 1 << 20, // Instruction supports geps 123 // no unsigned signed wrap. 124 SameSign = 1 << 21 // Both operands have the same sign. 125 }; 126 127 private: 128 const MCInstrDesc *MCID; // Instruction descriptor. 129 MachineBasicBlock *Parent = nullptr; // Pointer to the owning basic block. 130 131 // Operands are allocated by an ArrayRecycler. 132 MachineOperand *Operands = nullptr; // Pointer to the first operand. 133 134 #define LLVM_MI_NUMOPERANDS_BITS 24 135 #define LLVM_MI_FLAGS_BITS 24 136 #define LLVM_MI_ASMPRINTERFLAGS_BITS 8 137 138 /// Number of operands on instruction. 139 uint32_t NumOperands : LLVM_MI_NUMOPERANDS_BITS; 140 141 // OperandCapacity has uint8_t size, so it should be next to NumOperands 142 // to properly pack. 143 using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity; 144 OperandCapacity CapOperands; // Capacity of the Operands array. 145 146 /// Various bits of additional information about the machine instruction. 147 uint32_t Flags : LLVM_MI_FLAGS_BITS; 148 149 /// Various bits of information used by the AsmPrinter to emit helpful 150 /// comments. This is *not* semantic information. Do not use this for 151 /// anything other than to convey comment information to AsmPrinter. 152 uint8_t AsmPrinterFlags : LLVM_MI_ASMPRINTERFLAGS_BITS; 153 154 /// Internal implementation detail class that provides out-of-line storage for 155 /// extra info used by the machine instruction when this info cannot be stored 156 /// in-line within the instruction itself. 157 /// 158 /// This has to be defined eagerly due to the implementation constraints of 159 /// `PointerSumType` where it is used. 160 class ExtraInfo final : TrailingObjects<ExtraInfo, MachineMemOperand *, 161 MCSymbol *, MDNode *, uint32_t> { 162 public: 163 static ExtraInfo *create(BumpPtrAllocator &Allocator, 164 ArrayRef<MachineMemOperand *> MMOs, 165 MCSymbol *PreInstrSymbol = nullptr, 166 MCSymbol *PostInstrSymbol = nullptr, 167 MDNode *HeapAllocMarker = nullptr, 168 MDNode *PCSections = nullptr, uint32_t CFIType = 0, 169 MDNode *MMRAs = nullptr) { 170 bool HasPreInstrSymbol = PreInstrSymbol != nullptr; 171 bool HasPostInstrSymbol = PostInstrSymbol != nullptr; 172 bool HasHeapAllocMarker = HeapAllocMarker != nullptr; 173 bool HasMMRAs = MMRAs != nullptr; 174 bool HasCFIType = CFIType != 0; 175 bool HasPCSections = PCSections != nullptr; 176 auto *Result = new (Allocator.Allocate( 177 totalSizeToAlloc<MachineMemOperand *, MCSymbol *, MDNode *, uint32_t>( 178 MMOs.size(), HasPreInstrSymbol + HasPostInstrSymbol, 179 HasHeapAllocMarker + HasPCSections + HasMMRAs, HasCFIType), 180 alignof(ExtraInfo))) 181 ExtraInfo(MMOs.size(), HasPreInstrSymbol, HasPostInstrSymbol, 182 HasHeapAllocMarker, HasPCSections, HasCFIType, HasMMRAs); 183 184 // Copy the actual data into the trailing objects. 185 std::copy(MMOs.begin(), MMOs.end(), 186 Result->getTrailingObjects<MachineMemOperand *>()); 187 188 unsigned MDNodeIdx = 0; 189 190 if (HasPreInstrSymbol) 191 Result->getTrailingObjects<MCSymbol *>()[0] = PreInstrSymbol; 192 if (HasPostInstrSymbol) 193 Result->getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] = 194 PostInstrSymbol; 195 if (HasHeapAllocMarker) 196 Result->getTrailingObjects<MDNode *>()[MDNodeIdx++] = HeapAllocMarker; 197 if (HasPCSections) 198 Result->getTrailingObjects<MDNode *>()[MDNodeIdx++] = PCSections; 199 if (HasCFIType) 200 Result->getTrailingObjects<uint32_t>()[0] = CFIType; 201 if (HasMMRAs) 202 Result->getTrailingObjects<MDNode *>()[MDNodeIdx++] = MMRAs; 203 204 return Result; 205 } 206 207 ArrayRef<MachineMemOperand *> getMMOs() const { 208 return ArrayRef(getTrailingObjects<MachineMemOperand *>(), NumMMOs); 209 } 210 211 MCSymbol *getPreInstrSymbol() const { 212 return HasPreInstrSymbol ? getTrailingObjects<MCSymbol *>()[0] : nullptr; 213 } 214 215 MCSymbol *getPostInstrSymbol() const { 216 return HasPostInstrSymbol 217 ? getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] 218 : nullptr; 219 } 220 221 MDNode *getHeapAllocMarker() const { 222 return HasHeapAllocMarker ? getTrailingObjects<MDNode *>()[0] : nullptr; 223 } 224 225 MDNode *getPCSections() const { 226 return HasPCSections 227 ? getTrailingObjects<MDNode *>()[HasHeapAllocMarker] 228 : nullptr; 229 } 230 231 uint32_t getCFIType() const { 232 return HasCFIType ? getTrailingObjects<uint32_t>()[0] : 0; 233 } 234 235 MDNode *getMMRAMetadata() const { 236 return HasMMRAs ? getTrailingObjects<MDNode *>()[HasHeapAllocMarker + 237 HasPCSections] 238 : nullptr; 239 } 240 241 private: 242 friend TrailingObjects; 243 244 // Description of the extra info, used to interpret the actual optional 245 // data appended. 246 // 247 // Note that this is not terribly space optimized. This leaves a great deal 248 // of flexibility to fit more in here later. 249 const int NumMMOs; 250 const bool HasPreInstrSymbol; 251 const bool HasPostInstrSymbol; 252 const bool HasHeapAllocMarker; 253 const bool HasPCSections; 254 const bool HasCFIType; 255 const bool HasMMRAs; 256 257 // Implement the `TrailingObjects` internal API. 258 size_t numTrailingObjects(OverloadToken<MachineMemOperand *>) const { 259 return NumMMOs; 260 } 261 size_t numTrailingObjects(OverloadToken<MCSymbol *>) const { 262 return HasPreInstrSymbol + HasPostInstrSymbol; 263 } 264 size_t numTrailingObjects(OverloadToken<MDNode *>) const { 265 return HasHeapAllocMarker + HasPCSections; 266 } 267 size_t numTrailingObjects(OverloadToken<uint32_t>) const { 268 return HasCFIType; 269 } 270 271 // Just a boring constructor to allow us to initialize the sizes. Always use 272 // the `create` routine above. 273 ExtraInfo(int NumMMOs, bool HasPreInstrSymbol, bool HasPostInstrSymbol, 274 bool HasHeapAllocMarker, bool HasPCSections, bool HasCFIType, 275 bool HasMMRAs) 276 : NumMMOs(NumMMOs), HasPreInstrSymbol(HasPreInstrSymbol), 277 HasPostInstrSymbol(HasPostInstrSymbol), 278 HasHeapAllocMarker(HasHeapAllocMarker), HasPCSections(HasPCSections), 279 HasCFIType(HasCFIType), HasMMRAs(HasMMRAs) {} 280 }; 281 282 /// Enumeration of the kinds of inline extra info available. It is important 283 /// that the `MachineMemOperand` inline kind has a tag value of zero to make 284 /// it accessible as an `ArrayRef`. 285 enum ExtraInfoInlineKinds { 286 EIIK_MMO = 0, 287 EIIK_PreInstrSymbol, 288 EIIK_PostInstrSymbol, 289 EIIK_OutOfLine 290 }; 291 292 // We store extra information about the instruction here. The common case is 293 // expected to be nothing or a single pointer (typically a MMO or a symbol). 294 // We work to optimize this common case by storing it inline here rather than 295 // requiring a separate allocation, but we fall back to an allocation when 296 // multiple pointers are needed. 297 PointerSumType<ExtraInfoInlineKinds, 298 PointerSumTypeMember<EIIK_MMO, MachineMemOperand *>, 299 PointerSumTypeMember<EIIK_PreInstrSymbol, MCSymbol *>, 300 PointerSumTypeMember<EIIK_PostInstrSymbol, MCSymbol *>, 301 PointerSumTypeMember<EIIK_OutOfLine, ExtraInfo *>> 302 Info; 303 304 DebugLoc DbgLoc; // Source line information. 305 306 /// Unique instruction number. Used by DBG_INSTR_REFs to refer to the values 307 /// defined by this instruction. 308 unsigned DebugInstrNum; 309 310 /// Cached opcode from MCID. 311 uint16_t Opcode; 312 313 // Intrusive list support 314 friend struct ilist_traits<MachineInstr>; 315 friend struct ilist_callback_traits<MachineBasicBlock>; 316 void setParent(MachineBasicBlock *P) { Parent = P; } 317 318 /// This constructor creates a copy of the given 319 /// MachineInstr in the given MachineFunction. 320 MachineInstr(MachineFunction &, const MachineInstr &); 321 322 /// This constructor create a MachineInstr and add the implicit operands. 323 /// It reserves space for number of operands specified by 324 /// MCInstrDesc. An explicit DebugLoc is supplied. 325 MachineInstr(MachineFunction &, const MCInstrDesc &TID, DebugLoc DL, 326 bool NoImp = false); 327 328 // MachineInstrs are pool-allocated and owned by MachineFunction. 329 friend class MachineFunction; 330 331 void 332 dumprImpl(const MachineRegisterInfo &MRI, unsigned Depth, unsigned MaxDepth, 333 SmallPtrSetImpl<const MachineInstr *> &AlreadySeenInstrs) const; 334 335 static bool opIsRegDef(const MachineOperand &Op) { 336 return Op.isReg() && Op.isDef(); 337 } 338 339 static bool opIsRegUse(const MachineOperand &Op) { 340 return Op.isReg() && Op.isUse(); 341 } 342 343 public: 344 MachineInstr(const MachineInstr &) = delete; 345 MachineInstr &operator=(const MachineInstr &) = delete; 346 // Use MachineFunction::DeleteMachineInstr() instead. 347 ~MachineInstr() = delete; 348 349 const MachineBasicBlock* getParent() const { return Parent; } 350 MachineBasicBlock* getParent() { return Parent; } 351 352 /// Move the instruction before \p MovePos. 353 void moveBefore(MachineInstr *MovePos); 354 355 /// Return the function that contains the basic block that this instruction 356 /// belongs to. 357 /// 358 /// Note: this is undefined behaviour if the instruction does not have a 359 /// parent. 360 const MachineFunction *getMF() const; 361 MachineFunction *getMF() { 362 return const_cast<MachineFunction *>( 363 static_cast<const MachineInstr *>(this)->getMF()); 364 } 365 366 /// Return the asm printer flags bitvector. 367 uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; } 368 369 /// Clear the AsmPrinter bitvector. 370 void clearAsmPrinterFlags() { AsmPrinterFlags = 0; } 371 372 /// Return whether an AsmPrinter flag is set. 373 bool getAsmPrinterFlag(CommentFlag Flag) const { 374 assert(isUInt<LLVM_MI_ASMPRINTERFLAGS_BITS>(unsigned(Flag)) && 375 "Flag is out of range for the AsmPrinterFlags field"); 376 return AsmPrinterFlags & Flag; 377 } 378 379 /// Set a flag for the AsmPrinter. 380 void setAsmPrinterFlag(uint8_t Flag) { 381 assert(isUInt<LLVM_MI_ASMPRINTERFLAGS_BITS>(unsigned(Flag)) && 382 "Flag is out of range for the AsmPrinterFlags field"); 383 AsmPrinterFlags |= Flag; 384 } 385 386 /// Clear specific AsmPrinter flags. 387 void clearAsmPrinterFlag(CommentFlag Flag) { 388 assert(isUInt<LLVM_MI_ASMPRINTERFLAGS_BITS>(unsigned(Flag)) && 389 "Flag is out of range for the AsmPrinterFlags field"); 390 AsmPrinterFlags &= ~Flag; 391 } 392 393 /// Return the MI flags bitvector. 394 uint32_t getFlags() const { 395 return Flags; 396 } 397 398 /// Return whether an MI flag is set. 399 bool getFlag(MIFlag Flag) const { 400 assert(isUInt<LLVM_MI_FLAGS_BITS>(unsigned(Flag)) && 401 "Flag is out of range for the Flags field"); 402 return Flags & Flag; 403 } 404 405 /// Set a MI flag. 406 void setFlag(MIFlag Flag) { 407 assert(isUInt<LLVM_MI_FLAGS_BITS>(unsigned(Flag)) && 408 "Flag is out of range for the Flags field"); 409 Flags |= (uint32_t)Flag; 410 } 411 412 void setFlags(unsigned flags) { 413 assert(isUInt<LLVM_MI_FLAGS_BITS>(flags) && 414 "flags to be set are out of range for the Flags field"); 415 // Filter out the automatically maintained flags. 416 unsigned Mask = BundledPred | BundledSucc; 417 Flags = (Flags & Mask) | (flags & ~Mask); 418 } 419 420 /// clearFlag - Clear a MI flag. 421 void clearFlag(MIFlag Flag) { 422 assert(isUInt<LLVM_MI_FLAGS_BITS>(unsigned(Flag)) && 423 "Flag to clear is out of range for the Flags field"); 424 Flags &= ~((uint32_t)Flag); 425 } 426 427 void clearFlags(unsigned flags) { 428 assert(isUInt<LLVM_MI_FLAGS_BITS>(flags) && 429 "flags to be cleared are out of range for the Flags field"); 430 Flags &= ~flags; 431 } 432 433 /// Return true if MI is in a bundle (but not the first MI in a bundle). 434 /// 435 /// A bundle looks like this before it's finalized: 436 /// ---------------- 437 /// | MI | 438 /// ---------------- 439 /// | 440 /// ---------------- 441 /// | MI * | 442 /// ---------------- 443 /// | 444 /// ---------------- 445 /// | MI * | 446 /// ---------------- 447 /// In this case, the first MI starts a bundle but is not inside a bundle, the 448 /// next 2 MIs are considered "inside" the bundle. 449 /// 450 /// After a bundle is finalized, it looks like this: 451 /// ---------------- 452 /// | Bundle | 453 /// ---------------- 454 /// | 455 /// ---------------- 456 /// | MI * | 457 /// ---------------- 458 /// | 459 /// ---------------- 460 /// | MI * | 461 /// ---------------- 462 /// | 463 /// ---------------- 464 /// | MI * | 465 /// ---------------- 466 /// The first instruction has the special opcode "BUNDLE". It's not "inside" 467 /// a bundle, but the next three MIs are. 468 bool isInsideBundle() const { 469 return getFlag(BundledPred); 470 } 471 472 /// Return true if this instruction part of a bundle. This is true 473 /// if either itself or its following instruction is marked "InsideBundle". 474 bool isBundled() const { 475 return isBundledWithPred() || isBundledWithSucc(); 476 } 477 478 /// Return true if this instruction is part of a bundle, and it is not the 479 /// first instruction in the bundle. 480 bool isBundledWithPred() const { return getFlag(BundledPred); } 481 482 /// Return true if this instruction is part of a bundle, and it is not the 483 /// last instruction in the bundle. 484 bool isBundledWithSucc() const { return getFlag(BundledSucc); } 485 486 /// Bundle this instruction with its predecessor. This can be an unbundled 487 /// instruction, or it can be the first instruction in a bundle. 488 void bundleWithPred(); 489 490 /// Bundle this instruction with its successor. This can be an unbundled 491 /// instruction, or it can be the last instruction in a bundle. 492 void bundleWithSucc(); 493 494 /// Break bundle above this instruction. 495 void unbundleFromPred(); 496 497 /// Break bundle below this instruction. 498 void unbundleFromSucc(); 499 500 /// Returns the debug location id of this MachineInstr. 501 const DebugLoc &getDebugLoc() const { return DbgLoc; } 502 503 /// Return the operand containing the offset to be used if this DBG_VALUE 504 /// instruction is indirect; will be an invalid register if this value is 505 /// not indirect, and an immediate with value 0 otherwise. 506 const MachineOperand &getDebugOffset() const { 507 assert(isNonListDebugValue() && "not a DBG_VALUE"); 508 return getOperand(1); 509 } 510 MachineOperand &getDebugOffset() { 511 assert(isNonListDebugValue() && "not a DBG_VALUE"); 512 return getOperand(1); 513 } 514 515 /// Return the operand for the debug variable referenced by 516 /// this DBG_VALUE instruction. 517 const MachineOperand &getDebugVariableOp() const; 518 MachineOperand &getDebugVariableOp(); 519 520 /// Return the debug variable referenced by 521 /// this DBG_VALUE instruction. 522 const DILocalVariable *getDebugVariable() const; 523 524 /// Return the operand for the complex address expression referenced by 525 /// this DBG_VALUE instruction. 526 const MachineOperand &getDebugExpressionOp() const; 527 MachineOperand &getDebugExpressionOp(); 528 529 /// Return the complex address expression referenced by 530 /// this DBG_VALUE instruction. 531 const DIExpression *getDebugExpression() const; 532 533 /// Return the debug label referenced by 534 /// this DBG_LABEL instruction. 535 const DILabel *getDebugLabel() const; 536 537 /// Fetch the instruction number of this MachineInstr. If it does not have 538 /// one already, a new and unique number will be assigned. 539 unsigned getDebugInstrNum(); 540 541 /// Fetch instruction number of this MachineInstr -- but before it's inserted 542 /// into \p MF. Needed for transformations that create an instruction but 543 /// don't immediately insert them. 544 unsigned getDebugInstrNum(MachineFunction &MF); 545 546 /// Examine the instruction number of this MachineInstr. May be zero if 547 /// it hasn't been assigned a number yet. 548 unsigned peekDebugInstrNum() const { return DebugInstrNum; } 549 550 /// Set instruction number of this MachineInstr. Avoid using unless you're 551 /// deserializing this information. 552 void setDebugInstrNum(unsigned Num) { DebugInstrNum = Num; } 553 554 /// Drop any variable location debugging information associated with this 555 /// instruction. Use when an instruction is modified in such a way that it no 556 /// longer defines the value it used to. Variable locations using that value 557 /// will be dropped. 558 void dropDebugNumber() { DebugInstrNum = 0; } 559 560 /// For inline asm, get the !srcloc metadata node if we have it, and decode 561 /// the loc cookie from it. 562 const MDNode *getLocCookieMD() const; 563 564 /// Emit an error referring to the source location of this instruction. This 565 /// should only be used for inline assembly that is somehow impossible to 566 /// compile. Other errors should have been handled much earlier. 567 void emitInlineAsmError(const Twine &ErrMsg) const; 568 569 // Emit an error in the LLVMContext referring to the source location of this 570 // instruction, if available. 571 void emitGenericError(const Twine &ErrMsg) const; 572 573 /// Returns the target instruction descriptor of this MachineInstr. 574 const MCInstrDesc &getDesc() const { return *MCID; } 575 576 /// Returns the opcode of this MachineInstr. 577 unsigned getOpcode() const { return Opcode; } 578 579 /// Retuns the total number of operands. 580 unsigned getNumOperands() const { return NumOperands; } 581 582 /// Returns the total number of operands which are debug locations. 583 unsigned getNumDebugOperands() const { 584 return std::distance(debug_operands().begin(), debug_operands().end()); 585 } 586 587 const MachineOperand& getOperand(unsigned i) const { 588 assert(i < getNumOperands() && "getOperand() out of range!"); 589 return Operands[i]; 590 } 591 MachineOperand& getOperand(unsigned i) { 592 assert(i < getNumOperands() && "getOperand() out of range!"); 593 return Operands[i]; 594 } 595 596 MachineOperand &getDebugOperand(unsigned Index) { 597 assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!"); 598 return *(debug_operands().begin() + Index); 599 } 600 const MachineOperand &getDebugOperand(unsigned Index) const { 601 assert(Index < getNumDebugOperands() && "getDebugOperand() out of range!"); 602 return *(debug_operands().begin() + Index); 603 } 604 605 /// Returns whether this debug value has at least one debug operand with the 606 /// register \p Reg. 607 bool hasDebugOperandForReg(Register Reg) const { 608 return any_of(debug_operands(), [Reg](const MachineOperand &Op) { 609 return Op.isReg() && Op.getReg() == Reg; 610 }); 611 } 612 613 /// Returns a range of all of the operands that correspond to a debug use of 614 /// \p Reg. 615 template <typename Operand, typename Instruction> 616 static iterator_range< 617 filter_iterator<Operand *, std::function<bool(Operand &Op)>>> 618 getDebugOperandsForReg(Instruction *MI, Register Reg) { 619 std::function<bool(Operand & Op)> OpUsesReg( 620 [Reg](Operand &Op) { return Op.isReg() && Op.getReg() == Reg; }); 621 return make_filter_range(MI->debug_operands(), OpUsesReg); 622 } 623 iterator_range<filter_iterator<const MachineOperand *, 624 std::function<bool(const MachineOperand &Op)>>> 625 getDebugOperandsForReg(Register Reg) const { 626 return MachineInstr::getDebugOperandsForReg<const MachineOperand, 627 const MachineInstr>(this, Reg); 628 } 629 iterator_range<filter_iterator<MachineOperand *, 630 std::function<bool(MachineOperand &Op)>>> 631 getDebugOperandsForReg(Register Reg) { 632 return MachineInstr::getDebugOperandsForReg<MachineOperand, MachineInstr>( 633 this, Reg); 634 } 635 636 bool isDebugOperand(const MachineOperand *Op) const { 637 return Op >= adl_begin(debug_operands()) && Op <= adl_end(debug_operands()); 638 } 639 640 unsigned getDebugOperandIndex(const MachineOperand *Op) const { 641 assert(isDebugOperand(Op) && "Expected a debug operand."); 642 return std::distance(adl_begin(debug_operands()), Op); 643 } 644 645 /// Returns the total number of definitions. 646 unsigned getNumDefs() const { 647 return getNumExplicitDefs() + MCID->implicit_defs().size(); 648 } 649 650 /// Returns true if the instruction has implicit definition. 651 bool hasImplicitDef() const { 652 for (const MachineOperand &MO : implicit_operands()) 653 if (MO.isDef()) 654 return true; 655 return false; 656 } 657 658 /// Returns the implicit operands number. 659 unsigned getNumImplicitOperands() const { 660 return getNumOperands() - getNumExplicitOperands(); 661 } 662 663 /// Return true if operand \p OpIdx is a subregister index. 664 bool isOperandSubregIdx(unsigned OpIdx) const { 665 assert(getOperand(OpIdx).isImm() && "Expected MO_Immediate operand type."); 666 if (isExtractSubreg() && OpIdx == 2) 667 return true; 668 if (isInsertSubreg() && OpIdx == 3) 669 return true; 670 if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0) 671 return true; 672 if (isSubregToReg() && OpIdx == 3) 673 return true; 674 return false; 675 } 676 677 /// Returns the number of non-implicit operands. 678 unsigned getNumExplicitOperands() const; 679 680 /// Returns the number of non-implicit definitions. 681 unsigned getNumExplicitDefs() const; 682 683 /// iterator/begin/end - Iterate over all operands of a machine instruction. 684 using mop_iterator = MachineOperand *; 685 using const_mop_iterator = const MachineOperand *; 686 687 mop_iterator operands_begin() { return Operands; } 688 mop_iterator operands_end() { return Operands + NumOperands; } 689 690 const_mop_iterator operands_begin() const { return Operands; } 691 const_mop_iterator operands_end() const { return Operands + NumOperands; } 692 693 iterator_range<mop_iterator> operands() { 694 return make_range(operands_begin(), operands_end()); 695 } 696 iterator_range<const_mop_iterator> operands() const { 697 return make_range(operands_begin(), operands_end()); 698 } 699 iterator_range<mop_iterator> explicit_operands() { 700 return make_range(operands_begin(), 701 operands_begin() + getNumExplicitOperands()); 702 } 703 iterator_range<const_mop_iterator> explicit_operands() const { 704 return make_range(operands_begin(), 705 operands_begin() + getNumExplicitOperands()); 706 } 707 iterator_range<mop_iterator> implicit_operands() { 708 return make_range(explicit_operands().end(), operands_end()); 709 } 710 iterator_range<const_mop_iterator> implicit_operands() const { 711 return make_range(explicit_operands().end(), operands_end()); 712 } 713 /// Returns a range over all operands that are used to determine the variable 714 /// location for this DBG_VALUE instruction. 715 iterator_range<mop_iterator> debug_operands() { 716 assert((isDebugValueLike()) && "Must be a debug value instruction."); 717 return isNonListDebugValue() 718 ? make_range(operands_begin(), operands_begin() + 1) 719 : make_range(operands_begin() + 2, operands_end()); 720 } 721 /// \copydoc debug_operands() 722 iterator_range<const_mop_iterator> debug_operands() const { 723 assert((isDebugValueLike()) && "Must be a debug value instruction."); 724 return isNonListDebugValue() 725 ? make_range(operands_begin(), operands_begin() + 1) 726 : make_range(operands_begin() + 2, operands_end()); 727 } 728 /// Returns a range over all explicit operands that are register definitions. 729 /// Implicit definition are not included! 730 iterator_range<mop_iterator> defs() { 731 return make_range(operands_begin(), 732 operands_begin() + getNumExplicitDefs()); 733 } 734 /// \copydoc defs() 735 iterator_range<const_mop_iterator> defs() const { 736 return make_range(operands_begin(), 737 operands_begin() + getNumExplicitDefs()); 738 } 739 /// Returns a range that includes all operands which may be register uses. 740 /// This may include unrelated operands which are not register uses. 741 iterator_range<mop_iterator> uses() { 742 return make_range(operands_begin() + getNumExplicitDefs(), operands_end()); 743 } 744 /// \copydoc uses() 745 iterator_range<const_mop_iterator> uses() const { 746 return make_range(operands_begin() + getNumExplicitDefs(), operands_end()); 747 } 748 iterator_range<mop_iterator> explicit_uses() { 749 return make_range(operands_begin() + getNumExplicitDefs(), 750 operands_begin() + getNumExplicitOperands()); 751 } 752 iterator_range<const_mop_iterator> explicit_uses() const { 753 return make_range(operands_begin() + getNumExplicitDefs(), 754 operands_begin() + getNumExplicitOperands()); 755 } 756 757 using filtered_mop_iterator = 758 filter_iterator<mop_iterator, bool (*)(const MachineOperand &)>; 759 using filtered_const_mop_iterator = 760 filter_iterator<const_mop_iterator, bool (*)(const MachineOperand &)>; 761 762 /// Returns an iterator range over all operands that are (explicit or 763 /// implicit) register defs. 764 iterator_range<filtered_mop_iterator> all_defs() { 765 return make_filter_range(operands(), opIsRegDef); 766 } 767 /// \copydoc all_defs() 768 iterator_range<filtered_const_mop_iterator> all_defs() const { 769 return make_filter_range(operands(), opIsRegDef); 770 } 771 772 /// Returns an iterator range over all operands that are (explicit or 773 /// implicit) register uses. 774 iterator_range<filtered_mop_iterator> all_uses() { 775 return make_filter_range(uses(), opIsRegUse); 776 } 777 /// \copydoc all_uses() 778 iterator_range<filtered_const_mop_iterator> all_uses() const { 779 return make_filter_range(uses(), opIsRegUse); 780 } 781 782 /// Returns the number of the operand iterator \p I points to. 783 unsigned getOperandNo(const_mop_iterator I) const { 784 return I - operands_begin(); 785 } 786 787 /// Access to memory operands of the instruction. If there are none, that does 788 /// not imply anything about whether the function accesses memory. Instead, 789 /// the caller must behave conservatively. 790 ArrayRef<MachineMemOperand *> memoperands() const { 791 if (!Info) 792 return {}; 793 794 if (Info.is<EIIK_MMO>()) 795 return ArrayRef(Info.getAddrOfZeroTagPointer(), 1); 796 797 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 798 return EI->getMMOs(); 799 800 return {}; 801 } 802 803 /// Access to memory operands of the instruction. 804 /// 805 /// If `memoperands_begin() == memoperands_end()`, that does not imply 806 /// anything about whether the function accesses memory. Instead, the caller 807 /// must behave conservatively. 808 mmo_iterator memoperands_begin() const { return memoperands().begin(); } 809 810 /// Access to memory operands of the instruction. 811 /// 812 /// If `memoperands_begin() == memoperands_end()`, that does not imply 813 /// anything about whether the function accesses memory. Instead, the caller 814 /// must behave conservatively. 815 mmo_iterator memoperands_end() const { return memoperands().end(); } 816 817 /// Return true if we don't have any memory operands which described the 818 /// memory access done by this instruction. If this is true, calling code 819 /// must be conservative. 820 bool memoperands_empty() const { return memoperands().empty(); } 821 822 /// Return true if this instruction has exactly one MachineMemOperand. 823 bool hasOneMemOperand() const { return memoperands().size() == 1; } 824 825 /// Return the number of memory operands. 826 unsigned getNumMemOperands() const { return memoperands().size(); } 827 828 /// Helper to extract a pre-instruction symbol if one has been added. 829 MCSymbol *getPreInstrSymbol() const { 830 if (!Info) 831 return nullptr; 832 if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>()) 833 return S; 834 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 835 return EI->getPreInstrSymbol(); 836 837 return nullptr; 838 } 839 840 /// Helper to extract a post-instruction symbol if one has been added. 841 MCSymbol *getPostInstrSymbol() const { 842 if (!Info) 843 return nullptr; 844 if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>()) 845 return S; 846 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 847 return EI->getPostInstrSymbol(); 848 849 return nullptr; 850 } 851 852 /// Helper to extract a heap alloc marker if one has been added. 853 MDNode *getHeapAllocMarker() const { 854 if (!Info) 855 return nullptr; 856 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 857 return EI->getHeapAllocMarker(); 858 859 return nullptr; 860 } 861 862 /// Helper to extract PCSections metadata target sections. 863 MDNode *getPCSections() const { 864 if (!Info) 865 return nullptr; 866 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 867 return EI->getPCSections(); 868 869 return nullptr; 870 } 871 872 /// Helper to extract mmra.op metadata. 873 MDNode *getMMRAMetadata() const { 874 if (!Info) 875 return nullptr; 876 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 877 return EI->getMMRAMetadata(); 878 return nullptr; 879 } 880 881 /// Helper to extract a CFI type hash if one has been added. 882 uint32_t getCFIType() const { 883 if (!Info) 884 return 0; 885 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>()) 886 return EI->getCFIType(); 887 888 return 0; 889 } 890 891 /// API for querying MachineInstr properties. They are the same as MCInstrDesc 892 /// queries but they are bundle aware. 893 894 enum QueryType { 895 IgnoreBundle, // Ignore bundles 896 AnyInBundle, // Return true if any instruction in bundle has property 897 AllInBundle // Return true if all instructions in bundle have property 898 }; 899 900 /// Return true if the instruction (or in the case of a bundle, 901 /// the instructions inside the bundle) has the specified property. 902 /// The first argument is the property being queried. 903 /// The second argument indicates whether the query should look inside 904 /// instruction bundles. 905 bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const { 906 assert(MCFlag < 64 && 907 "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle."); 908 // Inline the fast path for unbundled or bundle-internal instructions. 909 if (Type == IgnoreBundle || !isBundled() || isBundledWithPred()) 910 return getDesc().getFlags() & (1ULL << MCFlag); 911 912 // If this is the first instruction in a bundle, take the slow path. 913 return hasPropertyInBundle(1ULL << MCFlag, Type); 914 } 915 916 /// Return true if this is an instruction that should go through the usual 917 /// legalization steps. 918 bool isPreISelOpcode(QueryType Type = IgnoreBundle) const { 919 return hasProperty(MCID::PreISelOpcode, Type); 920 } 921 922 /// Return true if this instruction can have a variable number of operands. 923 /// In this case, the variable operands will be after the normal 924 /// operands but before the implicit definitions and uses (if any are 925 /// present). 926 bool isVariadic(QueryType Type = IgnoreBundle) const { 927 return hasProperty(MCID::Variadic, Type); 928 } 929 930 /// Set if this instruction has an optional definition, e.g. 931 /// ARM instructions which can set condition code if 's' bit is set. 932 bool hasOptionalDef(QueryType Type = IgnoreBundle) const { 933 return hasProperty(MCID::HasOptionalDef, Type); 934 } 935 936 /// Return true if this is a pseudo instruction that doesn't 937 /// correspond to a real machine instruction. 938 bool isPseudo(QueryType Type = IgnoreBundle) const { 939 return hasProperty(MCID::Pseudo, Type); 940 } 941 942 /// Return true if this instruction doesn't produce any output in the form of 943 /// executable instructions. 944 bool isMetaInstruction(QueryType Type = IgnoreBundle) const { 945 return hasProperty(MCID::Meta, Type); 946 } 947 948 bool isReturn(QueryType Type = AnyInBundle) const { 949 return hasProperty(MCID::Return, Type); 950 } 951 952 /// Return true if this is an instruction that marks the end of an EH scope, 953 /// i.e., a catchpad or a cleanuppad instruction. 954 bool isEHScopeReturn(QueryType Type = AnyInBundle) const { 955 return hasProperty(MCID::EHScopeReturn, Type); 956 } 957 958 bool isCall(QueryType Type = AnyInBundle) const { 959 return hasProperty(MCID::Call, Type); 960 } 961 962 /// Return true if this is a call instruction that may have an additional 963 /// information associated with it. 964 bool isCandidateForAdditionalCallInfo(QueryType Type = IgnoreBundle) const; 965 966 /// Return true if copying, moving, or erasing this instruction requires 967 /// updating additional call info (see \ref copyCallInfo, \ref moveCallInfo, 968 /// \ref eraseCallInfo). 969 bool shouldUpdateAdditionalCallInfo() const; 970 971 /// Returns true if the specified instruction stops control flow 972 /// from executing the instruction immediately following it. Examples include 973 /// unconditional branches and return instructions. 974 bool isBarrier(QueryType Type = AnyInBundle) const { 975 return hasProperty(MCID::Barrier, Type); 976 } 977 978 /// Returns true if this instruction part of the terminator for a basic block. 979 /// Typically this is things like return and branch instructions. 980 /// 981 /// Various passes use this to insert code into the bottom of a basic block, 982 /// but before control flow occurs. 983 bool isTerminator(QueryType Type = AnyInBundle) const { 984 return hasProperty(MCID::Terminator, Type); 985 } 986 987 /// Returns true if this is a conditional, unconditional, or indirect branch. 988 /// Predicates below can be used to discriminate between 989 /// these cases, and the TargetInstrInfo::analyzeBranch method can be used to 990 /// get more information. 991 bool isBranch(QueryType Type = AnyInBundle) const { 992 return hasProperty(MCID::Branch, Type); 993 } 994 995 /// Return true if this is an indirect branch, such as a 996 /// branch through a register. 997 bool isIndirectBranch(QueryType Type = AnyInBundle) const { 998 return hasProperty(MCID::IndirectBranch, Type); 999 } 1000 1001 /// Return true if this is a branch which may fall 1002 /// through to the next instruction or may transfer control flow to some other 1003 /// block. The TargetInstrInfo::analyzeBranch method can be used to get more 1004 /// information about this branch. 1005 bool isConditionalBranch(QueryType Type = AnyInBundle) const { 1006 return isBranch(Type) && !isBarrier(Type) && !isIndirectBranch(Type); 1007 } 1008 1009 /// Return true if this is a branch which always 1010 /// transfers control flow to some other block. The 1011 /// TargetInstrInfo::analyzeBranch method can be used to get more information 1012 /// about this branch. 1013 bool isUnconditionalBranch(QueryType Type = AnyInBundle) const { 1014 return isBranch(Type) && isBarrier(Type) && !isIndirectBranch(Type); 1015 } 1016 1017 /// Return true if this instruction has a predicate operand that 1018 /// controls execution. It may be set to 'always', or may be set to other 1019 /// values. There are various methods in TargetInstrInfo that can be used to 1020 /// control and modify the predicate in this instruction. 1021 bool isPredicable(QueryType Type = AllInBundle) const { 1022 // If it's a bundle than all bundled instructions must be predicable for this 1023 // to return true. 1024 return hasProperty(MCID::Predicable, Type); 1025 } 1026 1027 /// Return true if this instruction is a comparison. 1028 bool isCompare(QueryType Type = IgnoreBundle) const { 1029 return hasProperty(MCID::Compare, Type); 1030 } 1031 1032 /// Return true if this instruction is a move immediate 1033 /// (including conditional moves) instruction. 1034 bool isMoveImmediate(QueryType Type = IgnoreBundle) const { 1035 return hasProperty(MCID::MoveImm, Type); 1036 } 1037 1038 /// Return true if this instruction is a register move. 1039 /// (including moving values from subreg to reg) 1040 bool isMoveReg(QueryType Type = IgnoreBundle) const { 1041 return hasProperty(MCID::MoveReg, Type); 1042 } 1043 1044 /// Return true if this instruction is a bitcast instruction. 1045 bool isBitcast(QueryType Type = IgnoreBundle) const { 1046 return hasProperty(MCID::Bitcast, Type); 1047 } 1048 1049 /// Return true if this instruction is a select instruction. 1050 bool isSelect(QueryType Type = IgnoreBundle) const { 1051 return hasProperty(MCID::Select, Type); 1052 } 1053 1054 /// Return true if this instruction cannot be safely duplicated. 1055 /// For example, if the instruction has a unique labels attached 1056 /// to it, duplicating it would cause multiple definition errors. 1057 bool isNotDuplicable(QueryType Type = AnyInBundle) const { 1058 if (getPreInstrSymbol() || getPostInstrSymbol()) 1059 return true; 1060 return hasProperty(MCID::NotDuplicable, Type); 1061 } 1062 1063 /// Return true if this instruction is convergent. 1064 /// Convergent instructions can not be made control-dependent on any 1065 /// additional values. 1066 bool isConvergent(QueryType Type = AnyInBundle) const { 1067 if (isInlineAsm()) { 1068 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1069 if (ExtraInfo & InlineAsm::Extra_IsConvergent) 1070 return true; 1071 } 1072 if (getFlag(NoConvergent)) 1073 return false; 1074 return hasProperty(MCID::Convergent, Type); 1075 } 1076 1077 /// Returns true if the specified instruction has a delay slot 1078 /// which must be filled by the code generator. 1079 bool hasDelaySlot(QueryType Type = AnyInBundle) const { 1080 return hasProperty(MCID::DelaySlot, Type); 1081 } 1082 1083 /// Return true for instructions that can be folded as 1084 /// memory operands in other instructions. The most common use for this 1085 /// is instructions that are simple loads from memory that don't modify 1086 /// the loaded value in any way, but it can also be used for instructions 1087 /// that can be expressed as constant-pool loads, such as V_SETALLONES 1088 /// on x86, to allow them to be folded when it is beneficial. 1089 /// This should only be set on instructions that return a value in their 1090 /// only virtual register definition. 1091 bool canFoldAsLoad(QueryType Type = IgnoreBundle) const { 1092 return hasProperty(MCID::FoldableAsLoad, Type); 1093 } 1094 1095 /// Return true if this instruction behaves 1096 /// the same way as the generic REG_SEQUENCE instructions. 1097 /// E.g., on ARM, 1098 /// dX VMOVDRR rY, rZ 1099 /// is equivalent to 1100 /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1. 1101 /// 1102 /// Note that for the optimizers to be able to take advantage of 1103 /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be 1104 /// override accordingly. 1105 bool isRegSequenceLike(QueryType Type = IgnoreBundle) const { 1106 return hasProperty(MCID::RegSequence, Type); 1107 } 1108 1109 /// Return true if this instruction behaves 1110 /// the same way as the generic EXTRACT_SUBREG instructions. 1111 /// E.g., on ARM, 1112 /// rX, rY VMOVRRD dZ 1113 /// is equivalent to two EXTRACT_SUBREG: 1114 /// rX = EXTRACT_SUBREG dZ, ssub_0 1115 /// rY = EXTRACT_SUBREG dZ, ssub_1 1116 /// 1117 /// Note that for the optimizers to be able to take advantage of 1118 /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be 1119 /// override accordingly. 1120 bool isExtractSubregLike(QueryType Type = IgnoreBundle) const { 1121 return hasProperty(MCID::ExtractSubreg, Type); 1122 } 1123 1124 /// Return true if this instruction behaves 1125 /// the same way as the generic INSERT_SUBREG instructions. 1126 /// E.g., on ARM, 1127 /// dX = VSETLNi32 dY, rZ, Imm 1128 /// is equivalent to a INSERT_SUBREG: 1129 /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm) 1130 /// 1131 /// Note that for the optimizers to be able to take advantage of 1132 /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be 1133 /// override accordingly. 1134 bool isInsertSubregLike(QueryType Type = IgnoreBundle) const { 1135 return hasProperty(MCID::InsertSubreg, Type); 1136 } 1137 1138 //===--------------------------------------------------------------------===// 1139 // Side Effect Analysis 1140 //===--------------------------------------------------------------------===// 1141 1142 /// Return true if this instruction could possibly read memory. 1143 /// Instructions with this flag set are not necessarily simple load 1144 /// instructions, they may load a value and modify it, for example. 1145 bool mayLoad(QueryType Type = AnyInBundle) const { 1146 if (isInlineAsm()) { 1147 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1148 if (ExtraInfo & InlineAsm::Extra_MayLoad) 1149 return true; 1150 } 1151 return hasProperty(MCID::MayLoad, Type); 1152 } 1153 1154 /// Return true if this instruction could possibly modify memory. 1155 /// Instructions with this flag set are not necessarily simple store 1156 /// instructions, they may store a modified value based on their operands, or 1157 /// may not actually modify anything, for example. 1158 bool mayStore(QueryType Type = AnyInBundle) const { 1159 if (isInlineAsm()) { 1160 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 1161 if (ExtraInfo & InlineAsm::Extra_MayStore) 1162 return true; 1163 } 1164 return hasProperty(MCID::MayStore, Type); 1165 } 1166 1167 /// Return true if this instruction could possibly read or modify memory. 1168 bool mayLoadOrStore(QueryType Type = AnyInBundle) const { 1169 return mayLoad(Type) || mayStore(Type); 1170 } 1171 1172 /// Return true if this instruction could possibly raise a floating-point 1173 /// exception. This is the case if the instruction is a floating-point 1174 /// instruction that can in principle raise an exception, as indicated 1175 /// by the MCID::MayRaiseFPException property, *and* at the same time, 1176 /// the instruction is used in a context where we expect floating-point 1177 /// exceptions are not disabled, as indicated by the NoFPExcept MI flag. 1178 bool mayRaiseFPException() const { 1179 return hasProperty(MCID::MayRaiseFPException) && 1180 !getFlag(MachineInstr::MIFlag::NoFPExcept); 1181 } 1182 1183 //===--------------------------------------------------------------------===// 1184 // Flags that indicate whether an instruction can be modified by a method. 1185 //===--------------------------------------------------------------------===// 1186 1187 /// Return true if this may be a 2- or 3-address 1188 /// instruction (of the form "X = op Y, Z, ..."), which produces the same 1189 /// result if Y and Z are exchanged. If this flag is set, then the 1190 /// TargetInstrInfo::commuteInstruction method may be used to hack on the 1191 /// instruction. 1192 /// 1193 /// Note that this flag may be set on instructions that are only commutable 1194 /// sometimes. In these cases, the call to commuteInstruction will fail. 1195 /// Also note that some instructions require non-trivial modification to 1196 /// commute them. 1197 bool isCommutable(QueryType Type = IgnoreBundle) const { 1198 return hasProperty(MCID::Commutable, Type); 1199 } 1200 1201 /// Return true if this is a 2-address instruction 1202 /// which can be changed into a 3-address instruction if needed. Doing this 1203 /// transformation can be profitable in the register allocator, because it 1204 /// means that the instruction can use a 2-address form if possible, but 1205 /// degrade into a less efficient form if the source and dest register cannot 1206 /// be assigned to the same register. For example, this allows the x86 1207 /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which 1208 /// is the same speed as the shift but has bigger code size. 1209 /// 1210 /// If this returns true, then the target must implement the 1211 /// TargetInstrInfo::convertToThreeAddress method for this instruction, which 1212 /// is allowed to fail if the transformation isn't valid for this specific 1213 /// instruction (e.g. shl reg, 4 on x86). 1214 /// 1215 bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const { 1216 return hasProperty(MCID::ConvertibleTo3Addr, Type); 1217 } 1218 1219 /// Return true if this instruction requires 1220 /// custom insertion support when the DAG scheduler is inserting it into a 1221 /// machine basic block. If this is true for the instruction, it basically 1222 /// means that it is a pseudo instruction used at SelectionDAG time that is 1223 /// expanded out into magic code by the target when MachineInstrs are formed. 1224 /// 1225 /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method 1226 /// is used to insert this into the MachineBasicBlock. 1227 bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const { 1228 return hasProperty(MCID::UsesCustomInserter, Type); 1229 } 1230 1231 /// Return true if this instruction requires *adjustment* 1232 /// after instruction selection by calling a target hook. For example, this 1233 /// can be used to fill in ARM 's' optional operand depending on whether 1234 /// the conditional flag register is used. 1235 bool hasPostISelHook(QueryType Type = IgnoreBundle) const { 1236 return hasProperty(MCID::HasPostISelHook, Type); 1237 } 1238 1239 /// Returns true if this instruction is a candidate for remat. 1240 /// This flag is deprecated, please don't use it anymore. If this 1241 /// flag is set, the isReallyTriviallyReMaterializable() method is called to 1242 /// verify the instruction is really rematerializable. 1243 bool isRematerializable(QueryType Type = AllInBundle) const { 1244 // It's only possible to re-mat a bundle if all bundled instructions are 1245 // re-materializable. 1246 return hasProperty(MCID::Rematerializable, Type); 1247 } 1248 1249 /// Returns true if this instruction has the same cost (or less) than a move 1250 /// instruction. This is useful during certain types of optimizations 1251 /// (e.g., remat during two-address conversion or machine licm) 1252 /// where we would like to remat or hoist the instruction, but not if it costs 1253 /// more than moving the instruction into the appropriate register. Note, we 1254 /// are not marking copies from and to the same register class with this flag. 1255 bool isAsCheapAsAMove(QueryType Type = AllInBundle) const { 1256 // Only returns true for a bundle if all bundled instructions are cheap. 1257 return hasProperty(MCID::CheapAsAMove, Type); 1258 } 1259 1260 /// Returns true if this instruction source operands 1261 /// have special register allocation requirements that are not captured by the 1262 /// operand register classes. e.g. ARM::STRD's two source registers must be an 1263 /// even / odd pair, ARM::STM registers have to be in ascending order. 1264 /// Post-register allocation passes should not attempt to change allocations 1265 /// for sources of instructions with this flag. 1266 bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const { 1267 return hasProperty(MCID::ExtraSrcRegAllocReq, Type); 1268 } 1269 1270 /// Returns true if this instruction def operands 1271 /// have special register allocation requirements that are not captured by the 1272 /// operand register classes. e.g. ARM::LDRD's two def registers must be an 1273 /// even / odd pair, ARM::LDM registers have to be in ascending order. 1274 /// Post-register allocation passes should not attempt to change allocations 1275 /// for definitions of instructions with this flag. 1276 bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const { 1277 return hasProperty(MCID::ExtraDefRegAllocReq, Type); 1278 } 1279 1280 enum MICheckType { 1281 CheckDefs, // Check all operands for equality 1282 CheckKillDead, // Check all operands including kill / dead markers 1283 IgnoreDefs, // Ignore all definitions 1284 IgnoreVRegDefs // Ignore virtual register definitions 1285 }; 1286 1287 /// Return true if this instruction is identical to \p Other. 1288 /// Two instructions are identical if they have the same opcode and all their 1289 /// operands are identical (with respect to MachineOperand::isIdenticalTo()). 1290 /// Note that this means liveness related flags (dead, undef, kill) do not 1291 /// affect the notion of identical. 1292 bool isIdenticalTo(const MachineInstr &Other, 1293 MICheckType Check = CheckDefs) const; 1294 1295 /// Returns true if this instruction is a debug instruction that represents an 1296 /// identical debug value to \p Other. 1297 /// This function considers these debug instructions equivalent if they have 1298 /// identical variables, debug locations, and debug operands, and if the 1299 /// DIExpressions combined with the directness flags are equivalent. 1300 bool isEquivalentDbgInstr(const MachineInstr &Other) const; 1301 1302 /// Unlink 'this' from the containing basic block, and return it without 1303 /// deleting it. 1304 /// 1305 /// This function can not be used on bundled instructions, use 1306 /// removeFromBundle() to remove individual instructions from a bundle. 1307 MachineInstr *removeFromParent(); 1308 1309 /// Unlink this instruction from its basic block and return it without 1310 /// deleting it. 1311 /// 1312 /// If the instruction is part of a bundle, the other instructions in the 1313 /// bundle remain bundled. 1314 MachineInstr *removeFromBundle(); 1315 1316 /// Unlink 'this' from the containing basic block and delete it. 1317 /// 1318 /// If this instruction is the header of a bundle, the whole bundle is erased. 1319 /// This function can not be used for instructions inside a bundle, use 1320 /// eraseFromBundle() to erase individual bundled instructions. 1321 void eraseFromParent(); 1322 1323 /// Unlink 'this' from its basic block and delete it. 1324 /// 1325 /// If the instruction is part of a bundle, the other instructions in the 1326 /// bundle remain bundled. 1327 void eraseFromBundle(); 1328 1329 bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; } 1330 bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; } 1331 bool isAnnotationLabel() const { 1332 return getOpcode() == TargetOpcode::ANNOTATION_LABEL; 1333 } 1334 1335 bool isLifetimeMarker() const { 1336 return getOpcode() == TargetOpcode::LIFETIME_START || 1337 getOpcode() == TargetOpcode::LIFETIME_END; 1338 } 1339 1340 /// Returns true if the MachineInstr represents a label. 1341 bool isLabel() const { 1342 return isEHLabel() || isGCLabel() || isAnnotationLabel(); 1343 } 1344 1345 bool isCFIInstruction() const { 1346 return getOpcode() == TargetOpcode::CFI_INSTRUCTION; 1347 } 1348 1349 bool isPseudoProbe() const { 1350 return getOpcode() == TargetOpcode::PSEUDO_PROBE; 1351 } 1352 1353 // True if the instruction represents a position in the function. 1354 bool isPosition() const { return isLabel() || isCFIInstruction(); } 1355 1356 bool isNonListDebugValue() const { 1357 return getOpcode() == TargetOpcode::DBG_VALUE; 1358 } 1359 bool isDebugValueList() const { 1360 return getOpcode() == TargetOpcode::DBG_VALUE_LIST; 1361 } 1362 bool isDebugValue() const { 1363 return isNonListDebugValue() || isDebugValueList(); 1364 } 1365 bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; } 1366 bool isDebugRef() const { return getOpcode() == TargetOpcode::DBG_INSTR_REF; } 1367 bool isDebugValueLike() const { return isDebugValue() || isDebugRef(); } 1368 bool isDebugPHI() const { return getOpcode() == TargetOpcode::DBG_PHI; } 1369 bool isDebugInstr() const { 1370 return isDebugValue() || isDebugLabel() || isDebugRef() || isDebugPHI(); 1371 } 1372 bool isDebugOrPseudoInstr() const { 1373 return isDebugInstr() || isPseudoProbe(); 1374 } 1375 1376 bool isDebugOffsetImm() const { 1377 return isNonListDebugValue() && getDebugOffset().isImm(); 1378 } 1379 1380 /// A DBG_VALUE is indirect iff the location operand is a register and 1381 /// the offset operand is an immediate. 1382 bool isIndirectDebugValue() const { 1383 return isDebugOffsetImm() && getDebugOperand(0).isReg(); 1384 } 1385 1386 /// A DBG_VALUE is an entry value iff its debug expression contains the 1387 /// DW_OP_LLVM_entry_value operation. 1388 bool isDebugEntryValue() const; 1389 1390 /// Return true if the instruction is a debug value which describes a part of 1391 /// a variable as unavailable. 1392 bool isUndefDebugValue() const { 1393 if (!isDebugValue()) 1394 return false; 1395 // If any $noreg locations are given, this DV is undef. 1396 for (const MachineOperand &Op : debug_operands()) 1397 if (Op.isReg() && !Op.getReg().isValid()) 1398 return true; 1399 return false; 1400 } 1401 1402 bool isJumpTableDebugInfo() const { 1403 return getOpcode() == TargetOpcode::JUMP_TABLE_DEBUG_INFO; 1404 } 1405 1406 bool isPHI() const { 1407 return getOpcode() == TargetOpcode::PHI || 1408 getOpcode() == TargetOpcode::G_PHI; 1409 } 1410 bool isKill() const { return getOpcode() == TargetOpcode::KILL; } 1411 bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; } 1412 bool isInlineAsm() const { 1413 return getOpcode() == TargetOpcode::INLINEASM || 1414 getOpcode() == TargetOpcode::INLINEASM_BR; 1415 } 1416 /// Returns true if the register operand can be folded with a load or store 1417 /// into a frame index. Does so by checking the InlineAsm::Flag immediate 1418 /// operand at OpId - 1. 1419 bool mayFoldInlineAsmRegOp(unsigned OpId) const; 1420 1421 bool isStackAligningInlineAsm() const; 1422 InlineAsm::AsmDialect getInlineAsmDialect() const; 1423 1424 bool isInsertSubreg() const { 1425 return getOpcode() == TargetOpcode::INSERT_SUBREG; 1426 } 1427 1428 bool isSubregToReg() const { 1429 return getOpcode() == TargetOpcode::SUBREG_TO_REG; 1430 } 1431 1432 bool isRegSequence() const { 1433 return getOpcode() == TargetOpcode::REG_SEQUENCE; 1434 } 1435 1436 bool isBundle() const { 1437 return getOpcode() == TargetOpcode::BUNDLE; 1438 } 1439 1440 bool isCopy() const { 1441 return getOpcode() == TargetOpcode::COPY; 1442 } 1443 1444 bool isFullCopy() const { 1445 return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg(); 1446 } 1447 1448 bool isExtractSubreg() const { 1449 return getOpcode() == TargetOpcode::EXTRACT_SUBREG; 1450 } 1451 1452 bool isFakeUse() const { return getOpcode() == TargetOpcode::FAKE_USE; } 1453 1454 /// Return true if the instruction behaves like a copy. 1455 /// This does not include native copy instructions. 1456 bool isCopyLike() const { 1457 return isCopy() || isSubregToReg(); 1458 } 1459 1460 /// Return true is the instruction is an identity copy. 1461 bool isIdentityCopy() const { 1462 return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() && 1463 getOperand(0).getSubReg() == getOperand(1).getSubReg(); 1464 } 1465 1466 /// Return true if this is a transient instruction that is either very likely 1467 /// to be eliminated during register allocation (such as copy-like 1468 /// instructions), or if this instruction doesn't have an execution-time cost. 1469 bool isTransient() const { 1470 switch (getOpcode()) { 1471 default: 1472 return isMetaInstruction(); 1473 // Copy-like instructions are usually eliminated during register allocation. 1474 case TargetOpcode::PHI: 1475 case TargetOpcode::G_PHI: 1476 case TargetOpcode::COPY: 1477 case TargetOpcode::INSERT_SUBREG: 1478 case TargetOpcode::SUBREG_TO_REG: 1479 case TargetOpcode::REG_SEQUENCE: 1480 return true; 1481 } 1482 } 1483 1484 /// Return the number of instructions inside the MI bundle, excluding the 1485 /// bundle header. 1486 /// 1487 /// This is the number of instructions that MachineBasicBlock::iterator 1488 /// skips, 0 for unbundled instructions. 1489 unsigned getBundleSize() const; 1490 1491 /// Return true if the MachineInstr reads the specified register. 1492 /// If TargetRegisterInfo is non-null, then it also checks if there 1493 /// is a read of a super-register. 1494 /// This does not count partial redefines of virtual registers as reads: 1495 /// %reg1024:6 = OP. 1496 bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const { 1497 return findRegisterUseOperandIdx(Reg, TRI, false) != -1; 1498 } 1499 1500 /// Return true if the MachineInstr reads the specified virtual register. 1501 /// Take into account that a partial define is a 1502 /// read-modify-write operation. 1503 bool readsVirtualRegister(Register Reg) const { 1504 return readsWritesVirtualRegister(Reg).first; 1505 } 1506 1507 /// Return a pair of bools (reads, writes) indicating if this instruction 1508 /// reads or writes Reg. This also considers partial defines. 1509 /// If Ops is not null, all operand indices for Reg are added. 1510 std::pair<bool,bool> readsWritesVirtualRegister(Register Reg, 1511 SmallVectorImpl<unsigned> *Ops = nullptr) const; 1512 1513 /// Return true if the MachineInstr kills the specified register. 1514 /// If TargetRegisterInfo is non-null, then it also checks if there is 1515 /// a kill of a super-register. 1516 bool killsRegister(Register Reg, const TargetRegisterInfo *TRI) const { 1517 return findRegisterUseOperandIdx(Reg, TRI, true) != -1; 1518 } 1519 1520 /// Return true if the MachineInstr fully defines the specified register. 1521 /// If TargetRegisterInfo is non-null, then it also checks 1522 /// if there is a def of a super-register. 1523 /// NOTE: It's ignoring subreg indices on virtual registers. 1524 bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const { 1525 return findRegisterDefOperandIdx(Reg, TRI, false, false) != -1; 1526 } 1527 1528 /// Return true if the MachineInstr modifies (fully define or partially 1529 /// define) the specified register. 1530 /// NOTE: It's ignoring subreg indices on virtual registers. 1531 bool modifiesRegister(Register Reg, const TargetRegisterInfo *TRI) const { 1532 return findRegisterDefOperandIdx(Reg, TRI, false, true) != -1; 1533 } 1534 1535 /// Returns true if the register is dead in this machine instruction. 1536 /// If TargetRegisterInfo is non-null, then it also checks 1537 /// if there is a dead def of a super-register. 1538 bool registerDefIsDead(Register Reg, const TargetRegisterInfo *TRI) const { 1539 return findRegisterDefOperandIdx(Reg, TRI, true, false) != -1; 1540 } 1541 1542 /// Returns true if the MachineInstr has an implicit-use operand of exactly 1543 /// the given register (not considering sub/super-registers). 1544 bool hasRegisterImplicitUseOperand(Register Reg) const; 1545 1546 /// Returns the operand index that is a use of the specific register or -1 1547 /// if it is not found. It further tightens the search criteria to a use 1548 /// that kills the register if isKill is true. 1549 int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI, 1550 bool isKill = false) const; 1551 1552 /// Wrapper for findRegisterUseOperandIdx, it returns 1553 /// a pointer to the MachineOperand rather than an index. 1554 MachineOperand *findRegisterUseOperand(Register Reg, 1555 const TargetRegisterInfo *TRI, 1556 bool isKill = false) { 1557 int Idx = findRegisterUseOperandIdx(Reg, TRI, isKill); 1558 return (Idx == -1) ? nullptr : &getOperand(Idx); 1559 } 1560 1561 const MachineOperand *findRegisterUseOperand(Register Reg, 1562 const TargetRegisterInfo *TRI, 1563 bool isKill = false) const { 1564 return const_cast<MachineInstr *>(this)->findRegisterUseOperand(Reg, TRI, 1565 isKill); 1566 } 1567 1568 /// Returns the operand index that is a def of the specified register or 1569 /// -1 if it is not found. If isDead is true, defs that are not dead are 1570 /// skipped. If Overlap is true, then it also looks for defs that merely 1571 /// overlap the specified register. If TargetRegisterInfo is non-null, 1572 /// then it also checks if there is a def of a super-register. 1573 /// This may also return a register mask operand when Overlap is true. 1574 int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, 1575 bool isDead = false, 1576 bool Overlap = false) const; 1577 1578 /// Wrapper for findRegisterDefOperandIdx, it returns 1579 /// a pointer to the MachineOperand rather than an index. 1580 MachineOperand *findRegisterDefOperand(Register Reg, 1581 const TargetRegisterInfo *TRI, 1582 bool isDead = false, 1583 bool Overlap = false) { 1584 int Idx = findRegisterDefOperandIdx(Reg, TRI, isDead, Overlap); 1585 return (Idx == -1) ? nullptr : &getOperand(Idx); 1586 } 1587 1588 const MachineOperand *findRegisterDefOperand(Register Reg, 1589 const TargetRegisterInfo *TRI, 1590 bool isDead = false, 1591 bool Overlap = false) const { 1592 return const_cast<MachineInstr *>(this)->findRegisterDefOperand( 1593 Reg, TRI, isDead, Overlap); 1594 } 1595 1596 /// Find the index of the first operand in the 1597 /// operand list that is used to represent the predicate. It returns -1 if 1598 /// none is found. 1599 int findFirstPredOperandIdx() const; 1600 1601 /// Find the index of the flag word operand that 1602 /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if 1603 /// getOperand(OpIdx) does not belong to an inline asm operand group. 1604 /// 1605 /// If GroupNo is not NULL, it will receive the number of the operand group 1606 /// containing OpIdx. 1607 int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const; 1608 1609 /// Compute the static register class constraint for operand OpIdx. 1610 /// For normal instructions, this is derived from the MCInstrDesc. 1611 /// For inline assembly it is derived from the flag words. 1612 /// 1613 /// Returns NULL if the static register class constraint cannot be 1614 /// determined. 1615 const TargetRegisterClass* 1616 getRegClassConstraint(unsigned OpIdx, 1617 const TargetInstrInfo *TII, 1618 const TargetRegisterInfo *TRI) const; 1619 1620 /// Applies the constraints (def/use) implied by this MI on \p Reg to 1621 /// the given \p CurRC. 1622 /// If \p ExploreBundle is set and MI is part of a bundle, all the 1623 /// instructions inside the bundle will be taken into account. In other words, 1624 /// this method accumulates all the constraints of the operand of this MI and 1625 /// the related bundle if MI is a bundle or inside a bundle. 1626 /// 1627 /// Returns the register class that satisfies both \p CurRC and the 1628 /// constraints set by MI. Returns NULL if such a register class does not 1629 /// exist. 1630 /// 1631 /// \pre CurRC must not be NULL. 1632 const TargetRegisterClass *getRegClassConstraintEffectForVReg( 1633 Register Reg, const TargetRegisterClass *CurRC, 1634 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, 1635 bool ExploreBundle = false) const; 1636 1637 /// Applies the constraints (def/use) implied by the \p OpIdx operand 1638 /// to the given \p CurRC. 1639 /// 1640 /// Returns the register class that satisfies both \p CurRC and the 1641 /// constraints set by \p OpIdx MI. Returns NULL if such a register class 1642 /// does not exist. 1643 /// 1644 /// \pre CurRC must not be NULL. 1645 /// \pre The operand at \p OpIdx must be a register. 1646 const TargetRegisterClass * 1647 getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC, 1648 const TargetInstrInfo *TII, 1649 const TargetRegisterInfo *TRI) const; 1650 1651 /// Add a tie between the register operands at DefIdx and UseIdx. 1652 /// The tie will cause the register allocator to ensure that the two 1653 /// operands are assigned the same physical register. 1654 /// 1655 /// Tied operands are managed automatically for explicit operands in the 1656 /// MCInstrDesc. This method is for exceptional cases like inline asm. 1657 void tieOperands(unsigned DefIdx, unsigned UseIdx); 1658 1659 /// Given the index of a tied register operand, find the 1660 /// operand it is tied to. Defs are tied to uses and vice versa. Returns the 1661 /// index of the tied operand which must exist. 1662 unsigned findTiedOperandIdx(unsigned OpIdx) const; 1663 1664 /// Given the index of a register def operand, 1665 /// check if the register def is tied to a source operand, due to either 1666 /// two-address elimination or inline assembly constraints. Returns the 1667 /// first tied use operand index by reference if UseOpIdx is not null. 1668 bool isRegTiedToUseOperand(unsigned DefOpIdx, 1669 unsigned *UseOpIdx = nullptr) const { 1670 const MachineOperand &MO = getOperand(DefOpIdx); 1671 if (!MO.isReg() || !MO.isDef() || !MO.isTied()) 1672 return false; 1673 if (UseOpIdx) 1674 *UseOpIdx = findTiedOperandIdx(DefOpIdx); 1675 return true; 1676 } 1677 1678 /// Return true if the use operand of the specified index is tied to a def 1679 /// operand. It also returns the def operand index by reference if DefOpIdx 1680 /// is not null. 1681 bool isRegTiedToDefOperand(unsigned UseOpIdx, 1682 unsigned *DefOpIdx = nullptr) const { 1683 const MachineOperand &MO = getOperand(UseOpIdx); 1684 if (!MO.isReg() || !MO.isUse() || !MO.isTied()) 1685 return false; 1686 if (DefOpIdx) 1687 *DefOpIdx = findTiedOperandIdx(UseOpIdx); 1688 return true; 1689 } 1690 1691 /// Clears kill flags on all operands. 1692 void clearKillInfo(); 1693 1694 /// Replace all occurrences of FromReg with ToReg:SubIdx, 1695 /// properly composing subreg indices where necessary. 1696 void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx, 1697 const TargetRegisterInfo &RegInfo); 1698 1699 /// We have determined MI kills a register. Look for the 1700 /// operand that uses it and mark it as IsKill. If AddIfNotFound is true, 1701 /// add a implicit operand if it's not found. Returns true if the operand 1702 /// exists / is added. 1703 bool addRegisterKilled(Register IncomingReg, 1704 const TargetRegisterInfo *RegInfo, 1705 bool AddIfNotFound = false); 1706 1707 /// Clear all kill flags affecting Reg. If RegInfo is provided, this includes 1708 /// all aliasing registers. 1709 void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo); 1710 1711 /// We have determined MI defined a register without a use. 1712 /// Look for the operand that defines it and mark it as IsDead. If 1713 /// AddIfNotFound is true, add a implicit operand if it's not found. Returns 1714 /// true if the operand exists / is added. 1715 bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, 1716 bool AddIfNotFound = false); 1717 1718 /// Clear all dead flags on operands defining register @p Reg. 1719 void clearRegisterDeads(Register Reg); 1720 1721 /// Mark all subregister defs of register @p Reg with the undef flag. 1722 /// This function is used when we determined to have a subregister def in an 1723 /// otherwise undefined super register. 1724 void setRegisterDefReadUndef(Register Reg, bool IsUndef = true); 1725 1726 /// We have determined MI defines a register. Make sure there is an operand 1727 /// defining Reg. 1728 void addRegisterDefined(Register Reg, 1729 const TargetRegisterInfo *RegInfo = nullptr); 1730 1731 /// Mark every physreg used by this instruction as 1732 /// dead except those in the UsedRegs list. 1733 /// 1734 /// On instructions with register mask operands, also add implicit-def 1735 /// operands for all registers in UsedRegs. 1736 void setPhysRegsDeadExcept(ArrayRef<Register> UsedRegs, 1737 const TargetRegisterInfo &TRI); 1738 1739 /// Return true if it is safe to move this instruction. If 1740 /// SawStore is set to true, it means that there is a store (or call) between 1741 /// the instruction's location and its intended destination. 1742 bool isSafeToMove(bool &SawStore) const; 1743 1744 /// Return true if this instruction would be trivially dead if all of its 1745 /// defined registers were dead. 1746 bool wouldBeTriviallyDead() const; 1747 1748 /// Check whether an MI is dead. If \p LivePhysRegs is provided, it is assumed 1749 /// to be at the position of MI and will be used to check the Liveness of 1750 /// physical register defs. If \p LivePhysRegs is not provided, this will 1751 /// pessimistically assume any PhysReg def is live. 1752 /// For trivially dead instructions (i.e. those without hard to model effects 1753 /// / wouldBeTriviallyDead), this checks deadness by analyzing defs of the 1754 /// MachineInstr. If the instruction wouldBeTriviallyDead, and all the defs 1755 /// either have dead flags or have no uses, then the instruction is said to be 1756 /// dead. 1757 bool isDead(const MachineRegisterInfo &MRI, 1758 LiveRegUnits *LivePhysRegs = nullptr) const; 1759 1760 /// Returns true if this instruction's memory access aliases the memory 1761 /// access of Other. 1762 // 1763 /// Assumes any physical registers used to compute addresses 1764 /// have the same value for both instructions. Returns false if neither 1765 /// instruction writes to memory. 1766 /// 1767 /// @param AA Optional alias analysis, used to compare memory operands. 1768 /// @param Other MachineInstr to check aliasing against. 1769 /// @param UseTBAA Whether to pass TBAA information to alias analysis. 1770 bool mayAlias(BatchAAResults *AA, const MachineInstr &Other, 1771 bool UseTBAA) const; 1772 bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const; 1773 1774 /// Return true if this instruction may have an ordered 1775 /// or volatile memory reference, or if the information describing the memory 1776 /// reference is not available. Return false if it is known to have no 1777 /// ordered or volatile memory references. 1778 bool hasOrderedMemoryRef() const; 1779 1780 /// Return true if this load instruction never traps and points to a memory 1781 /// location whose value doesn't change during the execution of this function. 1782 /// 1783 /// Examples include loading a value from the constant pool or from the 1784 /// argument area of a function (if it does not change). If the instruction 1785 /// does multiple loads, this returns true only if all of the loads are 1786 /// dereferenceable and invariant. 1787 bool isDereferenceableInvariantLoad() const; 1788 1789 /// If the specified instruction is a PHI that always merges together the 1790 /// same virtual register, return the register, otherwise return Register(). 1791 Register isConstantValuePHI() const; 1792 1793 /// Return true if this instruction has side effects that are not modeled 1794 /// by mayLoad / mayStore, etc. 1795 /// For all instructions, the property is encoded in MCInstrDesc::Flags 1796 /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is 1797 /// INLINEASM instruction, in which case the side effect property is encoded 1798 /// in one of its operands (see InlineAsm::Extra_HasSideEffect). 1799 /// 1800 bool hasUnmodeledSideEffects() const; 1801 1802 /// Returns true if it is illegal to fold a load across this instruction. 1803 bool isLoadFoldBarrier() const; 1804 1805 /// Return true if all the defs of this instruction are dead. 1806 bool allDefsAreDead() const; 1807 1808 /// Return true if all the implicit defs of this instruction are dead. 1809 bool allImplicitDefsAreDead() const; 1810 1811 /// Return a valid size if the instruction is a spill instruction. 1812 std::optional<LocationSize> getSpillSize(const TargetInstrInfo *TII) const; 1813 1814 /// Return a valid size if the instruction is a folded spill instruction. 1815 std::optional<LocationSize> 1816 getFoldedSpillSize(const TargetInstrInfo *TII) const; 1817 1818 /// Return a valid size if the instruction is a restore instruction. 1819 std::optional<LocationSize> getRestoreSize(const TargetInstrInfo *TII) const; 1820 1821 /// Return a valid size if the instruction is a folded restore instruction. 1822 std::optional<LocationSize> 1823 getFoldedRestoreSize(const TargetInstrInfo *TII) const; 1824 1825 /// Copy implicit register operands from specified 1826 /// instruction to this instruction. 1827 void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI); 1828 1829 /// Debugging support 1830 /// @{ 1831 /// Determine the generic type to be printed (if needed) on uses and defs. 1832 LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes, 1833 const MachineRegisterInfo &MRI) const; 1834 1835 /// Return true when an instruction has tied register that can't be determined 1836 /// by the instruction's descriptor. This is useful for MIR printing, to 1837 /// determine whether we need to print the ties or not. 1838 bool hasComplexRegisterTies() const; 1839 1840 /// Print this MI to \p OS. 1841 /// Don't print information that can be inferred from other instructions if 1842 /// \p IsStandalone is false. It is usually true when only a fragment of the 1843 /// function is printed. 1844 /// Only print the defs and the opcode if \p SkipOpers is true. 1845 /// Otherwise, also print operands if \p SkipDebugLoc is true. 1846 /// Otherwise, also print the debug loc, with a terminating newline. 1847 /// \p TII is used to print the opcode name. If it's not present, but the 1848 /// MI is in a function, the opcode will be printed using the function's TII. 1849 void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false, 1850 bool SkipDebugLoc = false, bool AddNewLine = true, 1851 const TargetInstrInfo *TII = nullptr) const; 1852 void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true, 1853 bool SkipOpers = false, bool SkipDebugLoc = false, 1854 bool AddNewLine = true, 1855 const TargetInstrInfo *TII = nullptr) const; 1856 void dump() const; 1857 /// Print on dbgs() the current instruction and the instructions defining its 1858 /// operands and so on until we reach \p MaxDepth. 1859 void dumpr(const MachineRegisterInfo &MRI, 1860 unsigned MaxDepth = UINT_MAX) const; 1861 /// @} 1862 1863 //===--------------------------------------------------------------------===// 1864 // Accessors used to build up machine instructions. 1865 1866 /// Add the specified operand to the instruction. If it is an implicit 1867 /// operand, it is added to the end of the operand list. If it is an 1868 /// explicit operand it is added at the end of the explicit operand list 1869 /// (before the first implicit operand). 1870 /// 1871 /// MF must be the machine function that was used to allocate this 1872 /// instruction. 1873 /// 1874 /// MachineInstrBuilder provides a more convenient interface for creating 1875 /// instructions and adding operands. 1876 void addOperand(MachineFunction &MF, const MachineOperand &Op); 1877 1878 /// Add an operand without providing an MF reference. This only works for 1879 /// instructions that are inserted in a basic block. 1880 /// 1881 /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be 1882 /// preferred. 1883 void addOperand(const MachineOperand &Op); 1884 1885 /// Inserts Ops BEFORE It. Can untie/retie tied operands. 1886 void insert(mop_iterator InsertBefore, ArrayRef<MachineOperand> Ops); 1887 1888 /// Replace the instruction descriptor (thus opcode) of 1889 /// the current instruction with a new one. 1890 void setDesc(const MCInstrDesc &TID); 1891 1892 /// Replace current source information with new such. 1893 /// Avoid using this, the constructor argument is preferable. 1894 void setDebugLoc(DebugLoc DL) { 1895 DbgLoc = std::move(DL); 1896 assert(DbgLoc.hasTrivialDestructor() && "Expected trivial destructor"); 1897 } 1898 1899 /// Erase an operand from an instruction, leaving it with one 1900 /// fewer operand than it started with. 1901 void removeOperand(unsigned OpNo); 1902 1903 /// Clear this MachineInstr's memory reference descriptor list. This resets 1904 /// the memrefs to their most conservative state. This should be used only 1905 /// as a last resort since it greatly pessimizes our knowledge of the memory 1906 /// access performed by the instruction. 1907 void dropMemRefs(MachineFunction &MF); 1908 1909 /// Assign this MachineInstr's memory reference descriptor list. 1910 /// 1911 /// Unlike other methods, this *will* allocate them into a new array 1912 /// associated with the provided `MachineFunction`. 1913 void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs); 1914 1915 /// Add a MachineMemOperand to the machine instruction. 1916 /// This function should be used only occasionally. The setMemRefs function 1917 /// is the primary method for setting up a MachineInstr's MemRefs list. 1918 void addMemOperand(MachineFunction &MF, MachineMemOperand *MO); 1919 1920 /// Clone another MachineInstr's memory reference descriptor list and replace 1921 /// ours with it. 1922 /// 1923 /// Note that `*this` may be the incoming MI! 1924 /// 1925 /// Prefer this API whenever possible as it can avoid allocations in common 1926 /// cases. 1927 void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI); 1928 1929 /// Clone the merge of multiple MachineInstrs' memory reference descriptors 1930 /// list and replace ours with it. 1931 /// 1932 /// Note that `*this` may be one of the incoming MIs! 1933 /// 1934 /// Prefer this API whenever possible as it can avoid allocations in common 1935 /// cases. 1936 void cloneMergedMemRefs(MachineFunction &MF, 1937 ArrayRef<const MachineInstr *> MIs); 1938 1939 /// Set a symbol that will be emitted just prior to the instruction itself. 1940 /// 1941 /// Setting this to a null pointer will remove any such symbol. 1942 /// 1943 /// FIXME: This is not fully implemented yet. 1944 void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol); 1945 1946 /// Set a symbol that will be emitted just after the instruction itself. 1947 /// 1948 /// Setting this to a null pointer will remove any such symbol. 1949 /// 1950 /// FIXME: This is not fully implemented yet. 1951 void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol); 1952 1953 /// Clone another MachineInstr's pre- and post- instruction symbols and 1954 /// replace ours with it. 1955 void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI); 1956 1957 /// Set a marker on instructions that denotes where we should create and emit 1958 /// heap alloc site labels. This waits until after instruction selection and 1959 /// optimizations to create the label, so it should still work if the 1960 /// instruction is removed or duplicated. 1961 void setHeapAllocMarker(MachineFunction &MF, MDNode *MD); 1962 1963 // Set metadata on instructions that say which sections to emit instruction 1964 // addresses into. 1965 void setPCSections(MachineFunction &MF, MDNode *MD); 1966 1967 void setMMRAMetadata(MachineFunction &MF, MDNode *MMRAs); 1968 1969 /// Set the CFI type for the instruction. 1970 void setCFIType(MachineFunction &MF, uint32_t Type); 1971 1972 /// Return the MIFlags which represent both MachineInstrs. This 1973 /// should be used when merging two MachineInstrs into one. This routine does 1974 /// not modify the MIFlags of this MachineInstr. 1975 uint32_t mergeFlagsWith(const MachineInstr& Other) const; 1976 1977 static uint32_t copyFlagsFromInstruction(const Instruction &I); 1978 1979 /// Copy all flags to MachineInst MIFlags 1980 void copyIRFlags(const Instruction &I); 1981 1982 /// Break any tie involving OpIdx. 1983 void untieRegOperand(unsigned OpIdx) { 1984 MachineOperand &MO = getOperand(OpIdx); 1985 if (MO.isReg() && MO.isTied()) { 1986 getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0; 1987 MO.TiedTo = 0; 1988 } 1989 } 1990 1991 /// Add all implicit def and use operands to this instruction. 1992 void addImplicitDefUseOperands(MachineFunction &MF); 1993 1994 /// Scan instructions immediately following MI and collect any matching 1995 /// DBG_VALUEs. 1996 void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues); 1997 1998 /// Find all DBG_VALUEs that point to the register def in this instruction 1999 /// and point them to \p Reg instead. 2000 void changeDebugValuesDefReg(Register Reg); 2001 2002 /// Sets all register debug operands in this debug value instruction to be 2003 /// undef. 2004 void setDebugValueUndef() { 2005 assert(isDebugValue() && "Must be a debug value instruction."); 2006 for (MachineOperand &MO : debug_operands()) { 2007 if (MO.isReg()) { 2008 MO.setReg(0); 2009 MO.setSubReg(0); 2010 } 2011 } 2012 } 2013 2014 std::tuple<Register, Register> getFirst2Regs() const { 2015 return std::tuple(getOperand(0).getReg(), getOperand(1).getReg()); 2016 } 2017 2018 std::tuple<Register, Register, Register> getFirst3Regs() const { 2019 return std::tuple(getOperand(0).getReg(), getOperand(1).getReg(), 2020 getOperand(2).getReg()); 2021 } 2022 2023 std::tuple<Register, Register, Register, Register> getFirst4Regs() const { 2024 return std::tuple(getOperand(0).getReg(), getOperand(1).getReg(), 2025 getOperand(2).getReg(), getOperand(3).getReg()); 2026 } 2027 2028 std::tuple<Register, Register, Register, Register, Register> 2029 getFirst5Regs() const { 2030 return std::tuple(getOperand(0).getReg(), getOperand(1).getReg(), 2031 getOperand(2).getReg(), getOperand(3).getReg(), 2032 getOperand(4).getReg()); 2033 } 2034 2035 std::tuple<LLT, LLT> getFirst2LLTs() const; 2036 std::tuple<LLT, LLT, LLT> getFirst3LLTs() const; 2037 std::tuple<LLT, LLT, LLT, LLT> getFirst4LLTs() const; 2038 std::tuple<LLT, LLT, LLT, LLT, LLT> getFirst5LLTs() const; 2039 2040 std::tuple<Register, LLT, Register, LLT> getFirst2RegLLTs() const; 2041 std::tuple<Register, LLT, Register, LLT, Register, LLT> 2042 getFirst3RegLLTs() const; 2043 std::tuple<Register, LLT, Register, LLT, Register, LLT, Register, LLT> 2044 getFirst4RegLLTs() const; 2045 std::tuple<Register, LLT, Register, LLT, Register, LLT, Register, LLT, 2046 Register, LLT> 2047 getFirst5RegLLTs() const; 2048 2049 private: 2050 /// If this instruction is embedded into a MachineFunction, return the 2051 /// MachineRegisterInfo object for the current function, otherwise 2052 /// return null. 2053 MachineRegisterInfo *getRegInfo(); 2054 const MachineRegisterInfo *getRegInfo() const; 2055 2056 /// Unlink all of the register operands in this instruction from their 2057 /// respective use lists. This requires that the operands already be on their 2058 /// use lists. 2059 void removeRegOperandsFromUseLists(MachineRegisterInfo&); 2060 2061 /// Add all of the register operands in this instruction from their 2062 /// respective use lists. This requires that the operands not be on their 2063 /// use lists yet. 2064 void addRegOperandsToUseLists(MachineRegisterInfo&); 2065 2066 /// Slow path for hasProperty when we're dealing with a bundle. 2067 bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const; 2068 2069 /// Implements the logic of getRegClassConstraintEffectForVReg for the 2070 /// this MI and the given operand index \p OpIdx. 2071 /// If the related operand does not constrained Reg, this returns CurRC. 2072 const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl( 2073 unsigned OpIdx, Register Reg, const TargetRegisterClass *CurRC, 2074 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const; 2075 2076 /// Stores extra instruction information inline or allocates as ExtraInfo 2077 /// based on the number of pointers. 2078 void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs, 2079 MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol, 2080 MDNode *HeapAllocMarker, MDNode *PCSections, 2081 uint32_t CFIType, MDNode *MMRAs); 2082 }; 2083 2084 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the 2085 /// instruction rather than by pointer value. 2086 /// The hashing and equality testing functions ignore definitions so this is 2087 /// useful for CSE, etc. 2088 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> { 2089 static inline MachineInstr *getEmptyKey() { 2090 return nullptr; 2091 } 2092 2093 static inline MachineInstr *getTombstoneKey() { 2094 return reinterpret_cast<MachineInstr*>(-1); 2095 } 2096 2097 static unsigned getHashValue(const MachineInstr* const &MI); 2098 2099 static bool isEqual(const MachineInstr* const &LHS, 2100 const MachineInstr* const &RHS) { 2101 if (RHS == getEmptyKey() || RHS == getTombstoneKey() || 2102 LHS == getEmptyKey() || LHS == getTombstoneKey()) 2103 return LHS == RHS; 2104 return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs); 2105 } 2106 }; 2107 2108 //===----------------------------------------------------------------------===// 2109 // Debugging Support 2110 2111 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) { 2112 MI.print(OS); 2113 return OS; 2114 } 2115 2116 } // end namespace llvm 2117 2118 #endif // LLVM_CODEGEN_MACHINEINSTR_H 2119