1 //===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains the declaration of the MachineInstr class, which is the
10 // basic representation for all target dependent machine instructions used by
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
16 #define LLVM_CODEGEN_MACHINEINSTR_H
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/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineOperand.h"
26 #include "llvm/CodeGen/TargetOpcodes.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DebugLoc.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Support/ArrayRecycler.h"
33 #include "llvm/Support/TrailingObjects.h"
41 template <typename T> class ArrayRef;
43 class DILocalVariable;
44 class MachineBasicBlock;
45 class MachineFunction;
46 class MachineMemOperand;
47 class MachineRegisterInfo;
48 class ModuleSlotTracker;
50 template <typename T> class SmallVectorImpl;
53 class TargetInstrInfo;
54 class TargetRegisterClass;
55 class TargetRegisterInfo;
57 //===----------------------------------------------------------------------===//
58 /// Representation of each machine instruction.
60 /// This class isn't a POD type, but it must have a trivial destructor. When a
61 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
62 /// without having their destructor called.
65 : public ilist_node_with_parent<MachineInstr, MachineBasicBlock,
66 ilist_sentinel_tracking<true>> {
68 using mmo_iterator = ArrayRef<MachineMemOperand *>::iterator;
70 /// Flags to specify different kinds of comments to output in
71 /// assembly code. These flags carry semantic information not
72 /// otherwise easily derivable from the IR text.
75 ReloadReuse = 0x1, // higher bits are reserved for target dep comments.
77 TAsmComments = 0x4 // Target Asm comments should start from this value.
82 FrameSetup = 1 << 0, // Instruction is used as a part of
83 // function frame setup code.
84 FrameDestroy = 1 << 1, // Instruction is used as a part of
85 // function frame destruction code.
86 BundledPred = 1 << 2, // Instruction has bundled predecessors.
87 BundledSucc = 1 << 3, // Instruction has bundled successors.
88 FmNoNans = 1 << 4, // Instruction does not support Fast
90 FmNoInfs = 1 << 5, // Instruction does not support Fast
91 // math infinity values.
92 FmNsz = 1 << 6, // Instruction is not required to retain
93 // signed zero values.
94 FmArcp = 1 << 7, // Instruction supports Fast math
95 // reciprocal approximations.
96 FmContract = 1 << 8, // Instruction supports Fast math
97 // contraction operations like fma.
98 FmAfn = 1 << 9, // Instruction may map to Fast math
99 // instrinsic approximation.
100 FmReassoc = 1 << 10, // Instruction supports Fast math
101 // reassociation of operand order.
102 NoUWrap = 1 << 11, // Instruction supports binary operator
104 NoSWrap = 1 << 12, // Instruction supports binary operator
106 IsExact = 1 << 13, // Instruction supports division is
107 // known to be exact.
108 FPExcept = 1 << 14, // Instruction may raise floating-point
113 const MCInstrDesc *MCID; // Instruction descriptor.
114 MachineBasicBlock *Parent = nullptr; // Pointer to the owning basic block.
116 // Operands are allocated by an ArrayRecycler.
117 MachineOperand *Operands = nullptr; // Pointer to the first operand.
118 unsigned NumOperands = 0; // Number of operands on instruction.
119 using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
120 OperandCapacity CapOperands; // Capacity of the Operands array.
122 uint16_t Flags = 0; // Various bits of additional
123 // information about machine
126 uint8_t AsmPrinterFlags = 0; // Various bits of information used by
127 // the AsmPrinter to emit helpful
128 // comments. This is *not* semantic
129 // information. Do not use this for
130 // anything other than to convey comment
131 // information to AsmPrinter.
133 /// Internal implementation detail class that provides out-of-line storage for
134 /// extra info used by the machine instruction when this info cannot be stored
135 /// in-line within the instruction itself.
137 /// This has to be defined eagerly due to the implementation constraints of
138 /// `PointerSumType` where it is used.
139 class ExtraInfo final
140 : TrailingObjects<ExtraInfo, MachineMemOperand *, MCSymbol *, MDNode *> {
142 static ExtraInfo *create(BumpPtrAllocator &Allocator,
143 ArrayRef<MachineMemOperand *> MMOs,
144 MCSymbol *PreInstrSymbol = nullptr,
145 MCSymbol *PostInstrSymbol = nullptr,
146 MDNode *HeapAllocMarker = nullptr) {
147 bool HasPreInstrSymbol = PreInstrSymbol != nullptr;
148 bool HasPostInstrSymbol = PostInstrSymbol != nullptr;
149 bool HasHeapAllocMarker = HeapAllocMarker != nullptr;
150 auto *Result = new (Allocator.Allocate(
151 totalSizeToAlloc<MachineMemOperand *, MCSymbol *, MDNode *>(
152 MMOs.size(), HasPreInstrSymbol + HasPostInstrSymbol,
155 ExtraInfo(MMOs.size(), HasPreInstrSymbol, HasPostInstrSymbol,
158 // Copy the actual data into the trailing objects.
159 std::copy(MMOs.begin(), MMOs.end(),
160 Result->getTrailingObjects<MachineMemOperand *>());
162 if (HasPreInstrSymbol)
163 Result->getTrailingObjects<MCSymbol *>()[0] = PreInstrSymbol;
164 if (HasPostInstrSymbol)
165 Result->getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol] =
167 if (HasHeapAllocMarker)
168 Result->getTrailingObjects<MDNode *>()[0] = HeapAllocMarker;
173 ArrayRef<MachineMemOperand *> getMMOs() const {
174 return makeArrayRef(getTrailingObjects<MachineMemOperand *>(), NumMMOs);
177 MCSymbol *getPreInstrSymbol() const {
178 return HasPreInstrSymbol ? getTrailingObjects<MCSymbol *>()[0] : nullptr;
181 MCSymbol *getPostInstrSymbol() const {
182 return HasPostInstrSymbol
183 ? getTrailingObjects<MCSymbol *>()[HasPreInstrSymbol]
187 MDNode *getHeapAllocMarker() const {
188 return HasHeapAllocMarker ? getTrailingObjects<MDNode *>()[0] : nullptr;
192 friend TrailingObjects;
194 // Description of the extra info, used to interpret the actual optional
197 // Note that this is not terribly space optimized. This leaves a great deal
198 // of flexibility to fit more in here later.
200 const bool HasPreInstrSymbol;
201 const bool HasPostInstrSymbol;
202 const bool HasHeapAllocMarker;
204 // Implement the `TrailingObjects` internal API.
205 size_t numTrailingObjects(OverloadToken<MachineMemOperand *>) const {
208 size_t numTrailingObjects(OverloadToken<MCSymbol *>) const {
209 return HasPreInstrSymbol + HasPostInstrSymbol;
211 size_t numTrailingObjects(OverloadToken<MDNode *>) const {
212 return HasHeapAllocMarker;
215 // Just a boring constructor to allow us to initialize the sizes. Always use
216 // the `create` routine above.
217 ExtraInfo(int NumMMOs, bool HasPreInstrSymbol, bool HasPostInstrSymbol,
218 bool HasHeapAllocMarker)
219 : NumMMOs(NumMMOs), HasPreInstrSymbol(HasPreInstrSymbol),
220 HasPostInstrSymbol(HasPostInstrSymbol),
221 HasHeapAllocMarker(HasHeapAllocMarker) {}
224 /// Enumeration of the kinds of inline extra info available. It is important
225 /// that the `MachineMemOperand` inline kind has a tag value of zero to make
226 /// it accessible as an `ArrayRef`.
227 enum ExtraInfoInlineKinds {
230 EIIK_PostInstrSymbol,
234 // We store extra information about the instruction here. The common case is
235 // expected to be nothing or a single pointer (typically a MMO or a symbol).
236 // We work to optimize this common case by storing it inline here rather than
237 // requiring a separate allocation, but we fall back to an allocation when
238 // multiple pointers are needed.
239 PointerSumType<ExtraInfoInlineKinds,
240 PointerSumTypeMember<EIIK_MMO, MachineMemOperand *>,
241 PointerSumTypeMember<EIIK_PreInstrSymbol, MCSymbol *>,
242 PointerSumTypeMember<EIIK_PostInstrSymbol, MCSymbol *>,
243 PointerSumTypeMember<EIIK_OutOfLine, ExtraInfo *>>
246 DebugLoc debugLoc; // Source line information.
248 // Intrusive list support
249 friend struct ilist_traits<MachineInstr>;
250 friend struct ilist_callback_traits<MachineBasicBlock>;
251 void setParent(MachineBasicBlock *P) { Parent = P; }
253 /// This constructor creates a copy of the given
254 /// MachineInstr in the given MachineFunction.
255 MachineInstr(MachineFunction &, const MachineInstr &);
257 /// This constructor create a MachineInstr and add the implicit operands.
258 /// It reserves space for number of operands specified by
259 /// MCInstrDesc. An explicit DebugLoc is supplied.
260 MachineInstr(MachineFunction &, const MCInstrDesc &tid, DebugLoc dl,
263 // MachineInstrs are pool-allocated and owned by MachineFunction.
264 friend class MachineFunction;
267 MachineInstr(const MachineInstr &) = delete;
268 MachineInstr &operator=(const MachineInstr &) = delete;
269 // Use MachineFunction::DeleteMachineInstr() instead.
270 ~MachineInstr() = delete;
272 const MachineBasicBlock* getParent() const { return Parent; }
273 MachineBasicBlock* getParent() { return Parent; }
275 /// Return the function that contains the basic block that this instruction
278 /// Note: this is undefined behaviour if the instruction does not have a
280 const MachineFunction *getMF() const;
281 MachineFunction *getMF() {
282 return const_cast<MachineFunction *>(
283 static_cast<const MachineInstr *>(this)->getMF());
286 /// Return the asm printer flags bitvector.
287 uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
289 /// Clear the AsmPrinter bitvector.
290 void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
292 /// Return whether an AsmPrinter flag is set.
293 bool getAsmPrinterFlag(CommentFlag Flag) const {
294 return AsmPrinterFlags & Flag;
297 /// Set a flag for the AsmPrinter.
298 void setAsmPrinterFlag(uint8_t Flag) {
299 AsmPrinterFlags |= Flag;
302 /// Clear specific AsmPrinter flags.
303 void clearAsmPrinterFlag(CommentFlag Flag) {
304 AsmPrinterFlags &= ~Flag;
307 /// Return the MI flags bitvector.
308 uint16_t getFlags() const {
312 /// Return whether an MI flag is set.
313 bool getFlag(MIFlag Flag) const {
318 void setFlag(MIFlag Flag) {
319 Flags |= (uint16_t)Flag;
322 void setFlags(unsigned flags) {
323 // Filter out the automatically maintained flags.
324 unsigned Mask = BundledPred | BundledSucc;
325 Flags = (Flags & Mask) | (flags & ~Mask);
328 /// clearFlag - Clear a MI flag.
329 void clearFlag(MIFlag Flag) {
330 Flags &= ~((uint16_t)Flag);
333 /// Return true if MI is in a bundle (but not the first MI in a bundle).
335 /// A bundle looks like this before it's finalized:
347 /// In this case, the first MI starts a bundle but is not inside a bundle, the
348 /// next 2 MIs are considered "inside" the bundle.
350 /// After a bundle is finalized, it looks like this:
366 /// The first instruction has the special opcode "BUNDLE". It's not "inside"
367 /// a bundle, but the next three MIs are.
368 bool isInsideBundle() const {
369 return getFlag(BundledPred);
372 /// Return true if this instruction part of a bundle. This is true
373 /// if either itself or its following instruction is marked "InsideBundle".
374 bool isBundled() const {
375 return isBundledWithPred() || isBundledWithSucc();
378 /// Return true if this instruction is part of a bundle, and it is not the
379 /// first instruction in the bundle.
380 bool isBundledWithPred() const { return getFlag(BundledPred); }
382 /// Return true if this instruction is part of a bundle, and it is not the
383 /// last instruction in the bundle.
384 bool isBundledWithSucc() const { return getFlag(BundledSucc); }
386 /// Bundle this instruction with its predecessor. This can be an unbundled
387 /// instruction, or it can be the first instruction in a bundle.
388 void bundleWithPred();
390 /// Bundle this instruction with its successor. This can be an unbundled
391 /// instruction, or it can be the last instruction in a bundle.
392 void bundleWithSucc();
394 /// Break bundle above this instruction.
395 void unbundleFromPred();
397 /// Break bundle below this instruction.
398 void unbundleFromSucc();
400 /// Returns the debug location id of this MachineInstr.
401 const DebugLoc &getDebugLoc() const { return debugLoc; }
403 /// Return the debug variable referenced by
404 /// this DBG_VALUE instruction.
405 const DILocalVariable *getDebugVariable() const;
407 /// Return the complex address expression referenced by
408 /// this DBG_VALUE instruction.
409 const DIExpression *getDebugExpression() const;
411 /// Return the debug label referenced by
412 /// this DBG_LABEL instruction.
413 const DILabel *getDebugLabel() const;
415 /// Emit an error referring to the source location of this instruction.
416 /// This should only be used for inline assembly that is somehow
417 /// impossible to compile. Other errors should have been handled much
420 /// If this method returns, the caller should try to recover from the error.
421 void emitError(StringRef Msg) const;
423 /// Returns the target instruction descriptor of this MachineInstr.
424 const MCInstrDesc &getDesc() const { return *MCID; }
426 /// Returns the opcode of this MachineInstr.
427 unsigned getOpcode() const { return MCID->Opcode; }
429 /// Retuns the total number of operands.
430 unsigned getNumOperands() const { return NumOperands; }
432 const MachineOperand& getOperand(unsigned i) const {
433 assert(i < getNumOperands() && "getOperand() out of range!");
436 MachineOperand& getOperand(unsigned i) {
437 assert(i < getNumOperands() && "getOperand() out of range!");
441 /// Returns the total number of definitions.
442 unsigned getNumDefs() const {
443 return getNumExplicitDefs() + MCID->getNumImplicitDefs();
446 /// Return true if operand \p OpIdx is a subregister index.
447 bool isOperandSubregIdx(unsigned OpIdx) const {
448 assert(getOperand(OpIdx).getType() == MachineOperand::MO_Immediate &&
449 "Expected MO_Immediate operand type.");
450 if (isExtractSubreg() && OpIdx == 2)
452 if (isInsertSubreg() && OpIdx == 3)
454 if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
456 if (isSubregToReg() && OpIdx == 3)
461 /// Returns the number of non-implicit operands.
462 unsigned getNumExplicitOperands() const;
464 /// Returns the number of non-implicit definitions.
465 unsigned getNumExplicitDefs() const;
467 /// iterator/begin/end - Iterate over all operands of a machine instruction.
468 using mop_iterator = MachineOperand *;
469 using const_mop_iterator = const MachineOperand *;
471 mop_iterator operands_begin() { return Operands; }
472 mop_iterator operands_end() { return Operands + NumOperands; }
474 const_mop_iterator operands_begin() const { return Operands; }
475 const_mop_iterator operands_end() const { return Operands + NumOperands; }
477 iterator_range<mop_iterator> operands() {
478 return make_range(operands_begin(), operands_end());
480 iterator_range<const_mop_iterator> operands() const {
481 return make_range(operands_begin(), operands_end());
483 iterator_range<mop_iterator> explicit_operands() {
484 return make_range(operands_begin(),
485 operands_begin() + getNumExplicitOperands());
487 iterator_range<const_mop_iterator> explicit_operands() const {
488 return make_range(operands_begin(),
489 operands_begin() + getNumExplicitOperands());
491 iterator_range<mop_iterator> implicit_operands() {
492 return make_range(explicit_operands().end(), operands_end());
494 iterator_range<const_mop_iterator> implicit_operands() const {
495 return make_range(explicit_operands().end(), operands_end());
497 /// Returns a range over all explicit operands that are register definitions.
498 /// Implicit definition are not included!
499 iterator_range<mop_iterator> defs() {
500 return make_range(operands_begin(),
501 operands_begin() + getNumExplicitDefs());
504 iterator_range<const_mop_iterator> defs() const {
505 return make_range(operands_begin(),
506 operands_begin() + getNumExplicitDefs());
508 /// Returns a range that includes all operands that are register uses.
509 /// This may include unrelated operands which are not register uses.
510 iterator_range<mop_iterator> uses() {
511 return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
514 iterator_range<const_mop_iterator> uses() const {
515 return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
517 iterator_range<mop_iterator> explicit_uses() {
518 return make_range(operands_begin() + getNumExplicitDefs(),
519 operands_begin() + getNumExplicitOperands());
521 iterator_range<const_mop_iterator> explicit_uses() const {
522 return make_range(operands_begin() + getNumExplicitDefs(),
523 operands_begin() + getNumExplicitOperands());
526 /// Returns the number of the operand iterator \p I points to.
527 unsigned getOperandNo(const_mop_iterator I) const {
528 return I - operands_begin();
531 /// Access to memory operands of the instruction. If there are none, that does
532 /// not imply anything about whether the function accesses memory. Instead,
533 /// the caller must behave conservatively.
534 ArrayRef<MachineMemOperand *> memoperands() const {
538 if (Info.is<EIIK_MMO>())
539 return makeArrayRef(Info.getAddrOfZeroTagPointer(), 1);
541 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
542 return EI->getMMOs();
547 /// Access to memory operands of the instruction.
549 /// If `memoperands_begin() == memoperands_end()`, that does not imply
550 /// anything about whether the function accesses memory. Instead, the caller
551 /// must behave conservatively.
552 mmo_iterator memoperands_begin() const { return memoperands().begin(); }
554 /// Access to memory operands of the instruction.
556 /// If `memoperands_begin() == memoperands_end()`, that does not imply
557 /// anything about whether the function accesses memory. Instead, the caller
558 /// must behave conservatively.
559 mmo_iterator memoperands_end() const { return memoperands().end(); }
561 /// Return true if we don't have any memory operands which described the
562 /// memory access done by this instruction. If this is true, calling code
563 /// must be conservative.
564 bool memoperands_empty() const { return memoperands().empty(); }
566 /// Return true if this instruction has exactly one MachineMemOperand.
567 bool hasOneMemOperand() const { return memoperands().size() == 1; }
569 /// Return the number of memory operands.
570 unsigned getNumMemOperands() const { return memoperands().size(); }
572 /// Helper to extract a pre-instruction symbol if one has been added.
573 MCSymbol *getPreInstrSymbol() const {
576 if (MCSymbol *S = Info.get<EIIK_PreInstrSymbol>())
578 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
579 return EI->getPreInstrSymbol();
584 /// Helper to extract a post-instruction symbol if one has been added.
585 MCSymbol *getPostInstrSymbol() const {
588 if (MCSymbol *S = Info.get<EIIK_PostInstrSymbol>())
590 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
591 return EI->getPostInstrSymbol();
596 /// Helper to extract a heap alloc marker if one has been added.
597 MDNode *getHeapAllocMarker() const {
600 if (ExtraInfo *EI = Info.get<EIIK_OutOfLine>())
601 return EI->getHeapAllocMarker();
606 /// API for querying MachineInstr properties. They are the same as MCInstrDesc
607 /// queries but they are bundle aware.
610 IgnoreBundle, // Ignore bundles
611 AnyInBundle, // Return true if any instruction in bundle has property
612 AllInBundle // Return true if all instructions in bundle have property
615 /// Return true if the instruction (or in the case of a bundle,
616 /// the instructions inside the bundle) has the specified property.
617 /// The first argument is the property being queried.
618 /// The second argument indicates whether the query should look inside
619 /// instruction bundles.
620 bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
621 assert(MCFlag < 64 &&
622 "MCFlag out of range for bit mask in getFlags/hasPropertyInBundle.");
623 // Inline the fast path for unbundled or bundle-internal instructions.
624 if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
625 return getDesc().getFlags() & (1ULL << MCFlag);
627 // If this is the first instruction in a bundle, take the slow path.
628 return hasPropertyInBundle(1ULL << MCFlag, Type);
631 /// Return true if this instruction can have a variable number of operands.
632 /// In this case, the variable operands will be after the normal
633 /// operands but before the implicit definitions and uses (if any are
635 bool isVariadic(QueryType Type = IgnoreBundle) const {
636 return hasProperty(MCID::Variadic, Type);
639 /// Set if this instruction has an optional definition, e.g.
640 /// ARM instructions which can set condition code if 's' bit is set.
641 bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
642 return hasProperty(MCID::HasOptionalDef, Type);
645 /// Return true if this is a pseudo instruction that doesn't
646 /// correspond to a real machine instruction.
647 bool isPseudo(QueryType Type = IgnoreBundle) const {
648 return hasProperty(MCID::Pseudo, Type);
651 bool isReturn(QueryType Type = AnyInBundle) const {
652 return hasProperty(MCID::Return, Type);
655 /// Return true if this is an instruction that marks the end of an EH scope,
656 /// i.e., a catchpad or a cleanuppad instruction.
657 bool isEHScopeReturn(QueryType Type = AnyInBundle) const {
658 return hasProperty(MCID::EHScopeReturn, Type);
661 bool isCall(QueryType Type = AnyInBundle) const {
662 return hasProperty(MCID::Call, Type);
665 /// Returns true if the specified instruction stops control flow
666 /// from executing the instruction immediately following it. Examples include
667 /// unconditional branches and return instructions.
668 bool isBarrier(QueryType Type = AnyInBundle) const {
669 return hasProperty(MCID::Barrier, Type);
672 /// Returns true if this instruction part of the terminator for a basic block.
673 /// Typically this is things like return and branch instructions.
675 /// Various passes use this to insert code into the bottom of a basic block,
676 /// but before control flow occurs.
677 bool isTerminator(QueryType Type = AnyInBundle) const {
678 return hasProperty(MCID::Terminator, Type);
681 /// Returns true if this is a conditional, unconditional, or indirect branch.
682 /// Predicates below can be used to discriminate between
683 /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
684 /// get more information.
685 bool isBranch(QueryType Type = AnyInBundle) const {
686 return hasProperty(MCID::Branch, Type);
689 /// Return true if this is an indirect branch, such as a
690 /// branch through a register.
691 bool isIndirectBranch(QueryType Type = AnyInBundle) const {
692 return hasProperty(MCID::IndirectBranch, Type);
695 /// Return true if this is a branch which may fall
696 /// through to the next instruction or may transfer control flow to some other
697 /// block. The TargetInstrInfo::AnalyzeBranch method can be used to get more
698 /// information about this branch.
699 bool isConditionalBranch(QueryType Type = AnyInBundle) const {
700 return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
703 /// Return true if this is a branch which always
704 /// transfers control flow to some other block. The
705 /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
706 /// about this branch.
707 bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
708 return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
711 /// Return true if this instruction has a predicate operand that
712 /// controls execution. It may be set to 'always', or may be set to other
713 /// values. There are various methods in TargetInstrInfo that can be used to
714 /// control and modify the predicate in this instruction.
715 bool isPredicable(QueryType Type = AllInBundle) const {
716 // If it's a bundle than all bundled instructions must be predicable for this
718 return hasProperty(MCID::Predicable, Type);
721 /// Return true if this instruction is a comparison.
722 bool isCompare(QueryType Type = IgnoreBundle) const {
723 return hasProperty(MCID::Compare, Type);
726 /// Return true if this instruction is a move immediate
727 /// (including conditional moves) instruction.
728 bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
729 return hasProperty(MCID::MoveImm, Type);
732 /// Return true if this instruction is a register move.
733 /// (including moving values from subreg to reg)
734 bool isMoveReg(QueryType Type = IgnoreBundle) const {
735 return hasProperty(MCID::MoveReg, Type);
738 /// Return true if this instruction is a bitcast instruction.
739 bool isBitcast(QueryType Type = IgnoreBundle) const {
740 return hasProperty(MCID::Bitcast, Type);
743 /// Return true if this instruction is a select instruction.
744 bool isSelect(QueryType Type = IgnoreBundle) const {
745 return hasProperty(MCID::Select, Type);
748 /// Return true if this instruction cannot be safely duplicated.
749 /// For example, if the instruction has a unique labels attached
750 /// to it, duplicating it would cause multiple definition errors.
751 bool isNotDuplicable(QueryType Type = AnyInBundle) const {
752 return hasProperty(MCID::NotDuplicable, Type);
755 /// Return true if this instruction is convergent.
756 /// Convergent instructions can not be made control-dependent on any
757 /// additional values.
758 bool isConvergent(QueryType Type = AnyInBundle) const {
760 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
761 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
764 return hasProperty(MCID::Convergent, Type);
767 /// Returns true if the specified instruction has a delay slot
768 /// which must be filled by the code generator.
769 bool hasDelaySlot(QueryType Type = AnyInBundle) const {
770 return hasProperty(MCID::DelaySlot, Type);
773 /// Return true for instructions that can be folded as
774 /// memory operands in other instructions. The most common use for this
775 /// is instructions that are simple loads from memory that don't modify
776 /// the loaded value in any way, but it can also be used for instructions
777 /// that can be expressed as constant-pool loads, such as V_SETALLONES
778 /// on x86, to allow them to be folded when it is beneficial.
779 /// This should only be set on instructions that return a value in their
780 /// only virtual register definition.
781 bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
782 return hasProperty(MCID::FoldableAsLoad, Type);
785 /// Return true if this instruction behaves
786 /// the same way as the generic REG_SEQUENCE instructions.
788 /// dX VMOVDRR rY, rZ
790 /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
792 /// Note that for the optimizers to be able to take advantage of
793 /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
794 /// override accordingly.
795 bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
796 return hasProperty(MCID::RegSequence, Type);
799 /// Return true if this instruction behaves
800 /// the same way as the generic EXTRACT_SUBREG instructions.
802 /// rX, rY VMOVRRD dZ
803 /// is equivalent to two EXTRACT_SUBREG:
804 /// rX = EXTRACT_SUBREG dZ, ssub_0
805 /// rY = EXTRACT_SUBREG dZ, ssub_1
807 /// Note that for the optimizers to be able to take advantage of
808 /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
809 /// override accordingly.
810 bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
811 return hasProperty(MCID::ExtractSubreg, Type);
814 /// Return true if this instruction behaves
815 /// the same way as the generic INSERT_SUBREG instructions.
817 /// dX = VSETLNi32 dY, rZ, Imm
818 /// is equivalent to a INSERT_SUBREG:
819 /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
821 /// Note that for the optimizers to be able to take advantage of
822 /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
823 /// override accordingly.
824 bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
825 return hasProperty(MCID::InsertSubreg, Type);
828 //===--------------------------------------------------------------------===//
829 // Side Effect Analysis
830 //===--------------------------------------------------------------------===//
832 /// Return true if this instruction could possibly read memory.
833 /// Instructions with this flag set are not necessarily simple load
834 /// instructions, they may load a value and modify it, for example.
835 bool mayLoad(QueryType Type = AnyInBundle) const {
837 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
838 if (ExtraInfo & InlineAsm::Extra_MayLoad)
841 return hasProperty(MCID::MayLoad, Type);
844 /// Return true if this instruction could possibly modify memory.
845 /// Instructions with this flag set are not necessarily simple store
846 /// instructions, they may store a modified value based on their operands, or
847 /// may not actually modify anything, for example.
848 bool mayStore(QueryType Type = AnyInBundle) const {
850 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
851 if (ExtraInfo & InlineAsm::Extra_MayStore)
854 return hasProperty(MCID::MayStore, Type);
857 /// Return true if this instruction could possibly read or modify memory.
858 bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
859 return mayLoad(Type) || mayStore(Type);
862 /// Return true if this instruction could possibly raise a floating-point
863 /// exception. This is the case if the instruction is a floating-point
864 /// instruction that can in principle raise an exception, as indicated
865 /// by the MCID::MayRaiseFPException property, *and* at the same time,
866 /// the instruction is used in a context where we expect floating-point
867 /// exceptions might be enabled, as indicated by the FPExcept MI flag.
868 bool mayRaiseFPException() const {
869 return hasProperty(MCID::MayRaiseFPException) &&
870 getFlag(MachineInstr::MIFlag::FPExcept);
873 //===--------------------------------------------------------------------===//
874 // Flags that indicate whether an instruction can be modified by a method.
875 //===--------------------------------------------------------------------===//
877 /// Return true if this may be a 2- or 3-address
878 /// instruction (of the form "X = op Y, Z, ..."), which produces the same
879 /// result if Y and Z are exchanged. If this flag is set, then the
880 /// TargetInstrInfo::commuteInstruction method may be used to hack on the
883 /// Note that this flag may be set on instructions that are only commutable
884 /// sometimes. In these cases, the call to commuteInstruction will fail.
885 /// Also note that some instructions require non-trivial modification to
887 bool isCommutable(QueryType Type = IgnoreBundle) const {
888 return hasProperty(MCID::Commutable, Type);
891 /// Return true if this is a 2-address instruction
892 /// which can be changed into a 3-address instruction if needed. Doing this
893 /// transformation can be profitable in the register allocator, because it
894 /// means that the instruction can use a 2-address form if possible, but
895 /// degrade into a less efficient form if the source and dest register cannot
896 /// be assigned to the same register. For example, this allows the x86
897 /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
898 /// is the same speed as the shift but has bigger code size.
900 /// If this returns true, then the target must implement the
901 /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
902 /// is allowed to fail if the transformation isn't valid for this specific
903 /// instruction (e.g. shl reg, 4 on x86).
905 bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
906 return hasProperty(MCID::ConvertibleTo3Addr, Type);
909 /// Return true if this instruction requires
910 /// custom insertion support when the DAG scheduler is inserting it into a
911 /// machine basic block. If this is true for the instruction, it basically
912 /// means that it is a pseudo instruction used at SelectionDAG time that is
913 /// expanded out into magic code by the target when MachineInstrs are formed.
915 /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
916 /// is used to insert this into the MachineBasicBlock.
917 bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
918 return hasProperty(MCID::UsesCustomInserter, Type);
921 /// Return true if this instruction requires *adjustment*
922 /// after instruction selection by calling a target hook. For example, this
923 /// can be used to fill in ARM 's' optional operand depending on whether
924 /// the conditional flag register is used.
925 bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
926 return hasProperty(MCID::HasPostISelHook, Type);
929 /// Returns true if this instruction is a candidate for remat.
930 /// This flag is deprecated, please don't use it anymore. If this
931 /// flag is set, the isReallyTriviallyReMaterializable() method is called to
932 /// verify the instruction is really rematable.
933 bool isRematerializable(QueryType Type = AllInBundle) const {
934 // It's only possible to re-mat a bundle if all bundled instructions are
935 // re-materializable.
936 return hasProperty(MCID::Rematerializable, Type);
939 /// Returns true if this instruction has the same cost (or less) than a move
940 /// instruction. This is useful during certain types of optimizations
941 /// (e.g., remat during two-address conversion or machine licm)
942 /// where we would like to remat or hoist the instruction, but not if it costs
943 /// more than moving the instruction into the appropriate register. Note, we
944 /// are not marking copies from and to the same register class with this flag.
945 bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
946 // Only returns true for a bundle if all bundled instructions are cheap.
947 return hasProperty(MCID::CheapAsAMove, Type);
950 /// Returns true if this instruction source operands
951 /// have special register allocation requirements that are not captured by the
952 /// operand register classes. e.g. ARM::STRD's two source registers must be an
953 /// even / odd pair, ARM::STM registers have to be in ascending order.
954 /// Post-register allocation passes should not attempt to change allocations
955 /// for sources of instructions with this flag.
956 bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
957 return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
960 /// Returns true if this instruction def operands
961 /// have special register allocation requirements that are not captured by the
962 /// operand register classes. e.g. ARM::LDRD's two def registers must be an
963 /// even / odd pair, ARM::LDM registers have to be in ascending order.
964 /// Post-register allocation passes should not attempt to change allocations
965 /// for definitions of instructions with this flag.
966 bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
967 return hasProperty(MCID::ExtraDefRegAllocReq, Type);
971 CheckDefs, // Check all operands for equality
972 CheckKillDead, // Check all operands including kill / dead markers
973 IgnoreDefs, // Ignore all definitions
974 IgnoreVRegDefs // Ignore virtual register definitions
977 /// Return true if this instruction is identical to \p Other.
978 /// Two instructions are identical if they have the same opcode and all their
979 /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
980 /// Note that this means liveness related flags (dead, undef, kill) do not
981 /// affect the notion of identical.
982 bool isIdenticalTo(const MachineInstr &Other,
983 MICheckType Check = CheckDefs) const;
985 /// Unlink 'this' from the containing basic block, and return it without
988 /// This function can not be used on bundled instructions, use
989 /// removeFromBundle() to remove individual instructions from a bundle.
990 MachineInstr *removeFromParent();
992 /// Unlink this instruction from its basic block and return it without
995 /// If the instruction is part of a bundle, the other instructions in the
996 /// bundle remain bundled.
997 MachineInstr *removeFromBundle();
999 /// Unlink 'this' from the containing basic block and delete it.
1001 /// If this instruction is the header of a bundle, the whole bundle is erased.
1002 /// This function can not be used for instructions inside a bundle, use
1003 /// eraseFromBundle() to erase individual bundled instructions.
1004 void eraseFromParent();
1006 /// Unlink 'this' from the containing basic block and delete it.
1008 /// For all definitions mark their uses in DBG_VALUE nodes
1009 /// as undefined. Otherwise like eraseFromParent().
1010 void eraseFromParentAndMarkDBGValuesForRemoval();
1012 /// Unlink 'this' form its basic block and delete it.
1014 /// If the instruction is part of a bundle, the other instructions in the
1015 /// bundle remain bundled.
1016 void eraseFromBundle();
1018 bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
1019 bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
1020 bool isAnnotationLabel() const {
1021 return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
1024 /// Returns true if the MachineInstr represents a label.
1025 bool isLabel() const {
1026 return isEHLabel() || isGCLabel() || isAnnotationLabel();
1029 bool isCFIInstruction() const {
1030 return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
1033 // True if the instruction represents a position in the function.
1034 bool isPosition() const { return isLabel() || isCFIInstruction(); }
1036 bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
1037 bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
1038 bool isDebugInstr() const { return isDebugValue() || isDebugLabel(); }
1040 /// A DBG_VALUE is indirect iff the first operand is a register and
1041 /// the second operand is an immediate.
1042 bool isIndirectDebugValue() const {
1043 return isDebugValue()
1044 && getOperand(0).isReg()
1045 && getOperand(1).isImm();
1048 /// A DBG_VALUE is an entry value iff its debug expression contains the
1049 /// DW_OP_entry_value DWARF operation.
1050 bool isDebugEntryValue() const {
1051 return isDebugValue() && getDebugExpression()->isEntryValue();
1054 /// Return true if the instruction is a debug value which describes a part of
1055 /// a variable as unavailable.
1056 bool isUndefDebugValue() const {
1057 return isDebugValue() && getOperand(0).isReg() && !getOperand(0).getReg();
1060 bool isPHI() const {
1061 return getOpcode() == TargetOpcode::PHI ||
1062 getOpcode() == TargetOpcode::G_PHI;
1064 bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
1065 bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
1066 bool isInlineAsm() const {
1067 return getOpcode() == TargetOpcode::INLINEASM ||
1068 getOpcode() == TargetOpcode::INLINEASM_BR;
1071 /// FIXME: Seems like a layering violation that the AsmDialect, which is X86
1072 /// specific, be attached to a generic MachineInstr.
1073 bool isMSInlineAsm() const {
1074 return isInlineAsm() && getInlineAsmDialect() == InlineAsm::AD_Intel;
1077 bool isStackAligningInlineAsm() const;
1078 InlineAsm::AsmDialect getInlineAsmDialect() const;
1080 bool isInsertSubreg() const {
1081 return getOpcode() == TargetOpcode::INSERT_SUBREG;
1084 bool isSubregToReg() const {
1085 return getOpcode() == TargetOpcode::SUBREG_TO_REG;
1088 bool isRegSequence() const {
1089 return getOpcode() == TargetOpcode::REG_SEQUENCE;
1092 bool isBundle() const {
1093 return getOpcode() == TargetOpcode::BUNDLE;
1096 bool isCopy() const {
1097 return getOpcode() == TargetOpcode::COPY;
1100 bool isFullCopy() const {
1101 return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
1104 bool isExtractSubreg() const {
1105 return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
1108 /// Return true if the instruction behaves like a copy.
1109 /// This does not include native copy instructions.
1110 bool isCopyLike() const {
1111 return isCopy() || isSubregToReg();
1114 /// Return true is the instruction is an identity copy.
1115 bool isIdentityCopy() const {
1116 return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
1117 getOperand(0).getSubReg() == getOperand(1).getSubReg();
1120 /// Return true if this instruction doesn't produce any output in the form of
1121 /// executable instructions.
1122 bool isMetaInstruction() const {
1123 switch (getOpcode()) {
1126 case TargetOpcode::IMPLICIT_DEF:
1127 case TargetOpcode::KILL:
1128 case TargetOpcode::CFI_INSTRUCTION:
1129 case TargetOpcode::EH_LABEL:
1130 case TargetOpcode::GC_LABEL:
1131 case TargetOpcode::DBG_VALUE:
1132 case TargetOpcode::DBG_LABEL:
1133 case TargetOpcode::LIFETIME_START:
1134 case TargetOpcode::LIFETIME_END:
1139 /// Return true if this is a transient instruction that is either very likely
1140 /// to be eliminated during register allocation (such as copy-like
1141 /// instructions), or if this instruction doesn't have an execution-time cost.
1142 bool isTransient() const {
1143 switch (getOpcode()) {
1145 return isMetaInstruction();
1146 // Copy-like instructions are usually eliminated during register allocation.
1147 case TargetOpcode::PHI:
1148 case TargetOpcode::G_PHI:
1149 case TargetOpcode::COPY:
1150 case TargetOpcode::INSERT_SUBREG:
1151 case TargetOpcode::SUBREG_TO_REG:
1152 case TargetOpcode::REG_SEQUENCE:
1157 /// Return the number of instructions inside the MI bundle, excluding the
1160 /// This is the number of instructions that MachineBasicBlock::iterator
1161 /// skips, 0 for unbundled instructions.
1162 unsigned getBundleSize() const;
1164 /// Return true if the MachineInstr reads the specified register.
1165 /// If TargetRegisterInfo is passed, then it also checks if there
1166 /// is a read of a super-register.
1167 /// This does not count partial redefines of virtual registers as reads:
1168 /// %reg1024:6 = OP.
1169 bool readsRegister(unsigned Reg,
1170 const TargetRegisterInfo *TRI = nullptr) const {
1171 return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
1174 /// Return true if the MachineInstr reads the specified virtual register.
1175 /// Take into account that a partial define is a
1176 /// read-modify-write operation.
1177 bool readsVirtualRegister(unsigned Reg) const {
1178 return readsWritesVirtualRegister(Reg).first;
1181 /// Return a pair of bools (reads, writes) indicating if this instruction
1182 /// reads or writes Reg. This also considers partial defines.
1183 /// If Ops is not null, all operand indices for Reg are added.
1184 std::pair<bool,bool> readsWritesVirtualRegister(unsigned Reg,
1185 SmallVectorImpl<unsigned> *Ops = nullptr) const;
1187 /// Return true if the MachineInstr kills the specified register.
1188 /// If TargetRegisterInfo is passed, then it also checks if there is
1189 /// a kill of a super-register.
1190 bool killsRegister(unsigned Reg,
1191 const TargetRegisterInfo *TRI = nullptr) const {
1192 return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
1195 /// Return true if the MachineInstr fully defines the specified register.
1196 /// If TargetRegisterInfo is passed, then it also checks
1197 /// if there is a def of a super-register.
1198 /// NOTE: It's ignoring subreg indices on virtual registers.
1199 bool definesRegister(unsigned Reg,
1200 const TargetRegisterInfo *TRI = nullptr) const {
1201 return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
1204 /// Return true if the MachineInstr modifies (fully define or partially
1205 /// define) the specified register.
1206 /// NOTE: It's ignoring subreg indices on virtual registers.
1207 bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const {
1208 return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
1211 /// Returns true if the register is dead in this machine instruction.
1212 /// If TargetRegisterInfo is passed, then it also checks
1213 /// if there is a dead def of a super-register.
1214 bool registerDefIsDead(unsigned Reg,
1215 const TargetRegisterInfo *TRI = nullptr) const {
1216 return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
1219 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1220 /// the given register (not considering sub/super-registers).
1221 bool hasRegisterImplicitUseOperand(unsigned Reg) const;
1223 /// Returns the operand index that is a use of the specific register or -1
1224 /// if it is not found. It further tightens the search criteria to a use
1225 /// that kills the register if isKill is true.
1226 int findRegisterUseOperandIdx(unsigned Reg, bool isKill = false,
1227 const TargetRegisterInfo *TRI = nullptr) const;
1229 /// Wrapper for findRegisterUseOperandIdx, it returns
1230 /// a pointer to the MachineOperand rather than an index.
1231 MachineOperand *findRegisterUseOperand(unsigned Reg, bool isKill = false,
1232 const TargetRegisterInfo *TRI = nullptr) {
1233 int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
1234 return (Idx == -1) ? nullptr : &getOperand(Idx);
1237 const MachineOperand *findRegisterUseOperand(
1238 unsigned Reg, bool isKill = false,
1239 const TargetRegisterInfo *TRI = nullptr) const {
1240 return const_cast<MachineInstr *>(this)->
1241 findRegisterUseOperand(Reg, isKill, TRI);
1244 /// Returns the operand index that is a def of the specified register or
1245 /// -1 if it is not found. If isDead is true, defs that are not dead are
1246 /// skipped. If Overlap is true, then it also looks for defs that merely
1247 /// overlap the specified register. If TargetRegisterInfo is non-null,
1248 /// then it also checks if there is a def of a super-register.
1249 /// This may also return a register mask operand when Overlap is true.
1250 int findRegisterDefOperandIdx(unsigned Reg,
1251 bool isDead = false, bool Overlap = false,
1252 const TargetRegisterInfo *TRI = nullptr) const;
1254 /// Wrapper for findRegisterDefOperandIdx, it returns
1255 /// a pointer to the MachineOperand rather than an index.
1257 findRegisterDefOperand(unsigned Reg, bool isDead = false,
1258 bool Overlap = false,
1259 const TargetRegisterInfo *TRI = nullptr) {
1260 int Idx = findRegisterDefOperandIdx(Reg, isDead, Overlap, TRI);
1261 return (Idx == -1) ? nullptr : &getOperand(Idx);
1264 const MachineOperand *
1265 findRegisterDefOperand(unsigned Reg, bool isDead = false,
1266 bool Overlap = false,
1267 const TargetRegisterInfo *TRI = nullptr) const {
1268 return const_cast<MachineInstr *>(this)->findRegisterDefOperand(
1269 Reg, isDead, Overlap, TRI);
1272 /// Find the index of the first operand in the
1273 /// operand list that is used to represent the predicate. It returns -1 if
1275 int findFirstPredOperandIdx() const;
1277 /// Find the index of the flag word operand that
1278 /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if
1279 /// getOperand(OpIdx) does not belong to an inline asm operand group.
1281 /// If GroupNo is not NULL, it will receive the number of the operand group
1282 /// containing OpIdx.
1284 /// The flag operand is an immediate that can be decoded with methods like
1285 /// InlineAsm::hasRegClassConstraint().
1286 int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
1288 /// Compute the static register class constraint for operand OpIdx.
1289 /// For normal instructions, this is derived from the MCInstrDesc.
1290 /// For inline assembly it is derived from the flag words.
1292 /// Returns NULL if the static register class constraint cannot be
1294 const TargetRegisterClass*
1295 getRegClassConstraint(unsigned OpIdx,
1296 const TargetInstrInfo *TII,
1297 const TargetRegisterInfo *TRI) const;
1299 /// Applies the constraints (def/use) implied by this MI on \p Reg to
1300 /// the given \p CurRC.
1301 /// If \p ExploreBundle is set and MI is part of a bundle, all the
1302 /// instructions inside the bundle will be taken into account. In other words,
1303 /// this method accumulates all the constraints of the operand of this MI and
1304 /// the related bundle if MI is a bundle or inside a bundle.
1306 /// Returns the register class that satisfies both \p CurRC and the
1307 /// constraints set by MI. Returns NULL if such a register class does not
1310 /// \pre CurRC must not be NULL.
1311 const TargetRegisterClass *getRegClassConstraintEffectForVReg(
1312 unsigned Reg, const TargetRegisterClass *CurRC,
1313 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1314 bool ExploreBundle = false) const;
1316 /// Applies the constraints (def/use) implied by the \p OpIdx operand
1317 /// to the given \p CurRC.
1319 /// Returns the register class that satisfies both \p CurRC and the
1320 /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1323 /// \pre CurRC must not be NULL.
1324 /// \pre The operand at \p OpIdx must be a register.
1325 const TargetRegisterClass *
1326 getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1327 const TargetInstrInfo *TII,
1328 const TargetRegisterInfo *TRI) const;
1330 /// Add a tie between the register operands at DefIdx and UseIdx.
1331 /// The tie will cause the register allocator to ensure that the two
1332 /// operands are assigned the same physical register.
1334 /// Tied operands are managed automatically for explicit operands in the
1335 /// MCInstrDesc. This method is for exceptional cases like inline asm.
1336 void tieOperands(unsigned DefIdx, unsigned UseIdx);
1338 /// Given the index of a tied register operand, find the
1339 /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1340 /// index of the tied operand which must exist.
1341 unsigned findTiedOperandIdx(unsigned OpIdx) const;
1343 /// Given the index of a register def operand,
1344 /// check if the register def is tied to a source operand, due to either
1345 /// two-address elimination or inline assembly constraints. Returns the
1346 /// first tied use operand index by reference if UseOpIdx is not null.
1347 bool isRegTiedToUseOperand(unsigned DefOpIdx,
1348 unsigned *UseOpIdx = nullptr) const {
1349 const MachineOperand &MO = getOperand(DefOpIdx);
1350 if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1353 *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1357 /// Return true if the use operand of the specified index is tied to a def
1358 /// operand. It also returns the def operand index by reference if DefOpIdx
1360 bool isRegTiedToDefOperand(unsigned UseOpIdx,
1361 unsigned *DefOpIdx = nullptr) const {
1362 const MachineOperand &MO = getOperand(UseOpIdx);
1363 if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1366 *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1370 /// Clears kill flags on all operands.
1371 void clearKillInfo();
1373 /// Replace all occurrences of FromReg with ToReg:SubIdx,
1374 /// properly composing subreg indices where necessary.
1375 void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx,
1376 const TargetRegisterInfo &RegInfo);
1378 /// We have determined MI kills a register. Look for the
1379 /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1380 /// add a implicit operand if it's not found. Returns true if the operand
1381 /// exists / is added.
1382 bool addRegisterKilled(unsigned IncomingReg,
1383 const TargetRegisterInfo *RegInfo,
1384 bool AddIfNotFound = false);
1386 /// Clear all kill flags affecting Reg. If RegInfo is provided, this includes
1387 /// all aliasing registers.
1388 void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
1390 /// We have determined MI defined a register without a use.
1391 /// Look for the operand that defines it and mark it as IsDead. If
1392 /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1393 /// true if the operand exists / is added.
1394 bool addRegisterDead(unsigned Reg, const TargetRegisterInfo *RegInfo,
1395 bool AddIfNotFound = false);
1397 /// Clear all dead flags on operands defining register @p Reg.
1398 void clearRegisterDeads(unsigned Reg);
1400 /// Mark all subregister defs of register @p Reg with the undef flag.
1401 /// This function is used when we determined to have a subregister def in an
1402 /// otherwise undefined super register.
1403 void setRegisterDefReadUndef(unsigned Reg, bool IsUndef = true);
1405 /// We have determined MI defines a register. Make sure there is an operand
1407 void addRegisterDefined(unsigned Reg,
1408 const TargetRegisterInfo *RegInfo = nullptr);
1410 /// Mark every physreg used by this instruction as
1411 /// dead except those in the UsedRegs list.
1413 /// On instructions with register mask operands, also add implicit-def
1414 /// operands for all registers in UsedRegs.
1415 void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1416 const TargetRegisterInfo &TRI);
1418 /// Return true if it is safe to move this instruction. If
1419 /// SawStore is set to true, it means that there is a store (or call) between
1420 /// the instruction's location and its intended destination.
1421 bool isSafeToMove(AliasAnalysis *AA, bool &SawStore) const;
1423 /// Returns true if this instruction's memory access aliases the memory
1424 /// access of Other.
1426 /// Assumes any physical registers used to compute addresses
1427 /// have the same value for both instructions. Returns false if neither
1428 /// instruction writes to memory.
1430 /// @param AA Optional alias analysis, used to compare memory operands.
1431 /// @param Other MachineInstr to check aliasing against.
1432 /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1433 bool mayAlias(AliasAnalysis *AA, const MachineInstr &Other, bool UseTBAA) const;
1435 /// Return true if this instruction may have an ordered
1436 /// or volatile memory reference, or if the information describing the memory
1437 /// reference is not available. Return false if it is known to have no
1438 /// ordered or volatile memory references.
1439 bool hasOrderedMemoryRef() const;
1441 /// Return true if this load instruction never traps and points to a memory
1442 /// location whose value doesn't change during the execution of this function.
1444 /// Examples include loading a value from the constant pool or from the
1445 /// argument area of a function (if it does not change). If the instruction
1446 /// does multiple loads, this returns true only if all of the loads are
1447 /// dereferenceable and invariant.
1448 bool isDereferenceableInvariantLoad(AliasAnalysis *AA) const;
1450 /// If the specified instruction is a PHI that always merges together the
1451 /// same virtual register, return the register, otherwise return 0.
1452 unsigned isConstantValuePHI() const;
1454 /// Return true if this instruction has side effects that are not modeled
1455 /// by mayLoad / mayStore, etc.
1456 /// For all instructions, the property is encoded in MCInstrDesc::Flags
1457 /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1458 /// INLINEASM instruction, in which case the side effect property is encoded
1459 /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1461 bool hasUnmodeledSideEffects() const;
1463 /// Returns true if it is illegal to fold a load across this instruction.
1464 bool isLoadFoldBarrier() const;
1466 /// Return true if all the defs of this instruction are dead.
1467 bool allDefsAreDead() const;
1469 /// Return a valid size if the instruction is a spill instruction.
1470 Optional<unsigned> getSpillSize(const TargetInstrInfo *TII) const;
1472 /// Return a valid size if the instruction is a folded spill instruction.
1473 Optional<unsigned> getFoldedSpillSize(const TargetInstrInfo *TII) const;
1475 /// Return a valid size if the instruction is a restore instruction.
1476 Optional<unsigned> getRestoreSize(const TargetInstrInfo *TII) const;
1478 /// Return a valid size if the instruction is a folded restore instruction.
1480 getFoldedRestoreSize(const TargetInstrInfo *TII) const;
1482 /// Copy implicit register operands from specified
1483 /// instruction to this instruction.
1484 void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1486 /// Debugging support
1488 /// Determine the generic type to be printed (if needed) on uses and defs.
1489 LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1490 const MachineRegisterInfo &MRI) const;
1492 /// Return true when an instruction has tied register that can't be determined
1493 /// by the instruction's descriptor. This is useful for MIR printing, to
1494 /// determine whether we need to print the ties or not.
1495 bool hasComplexRegisterTies() const;
1497 /// Print this MI to \p OS.
1498 /// Don't print information that can be inferred from other instructions if
1499 /// \p IsStandalone is false. It is usually true when only a fragment of the
1500 /// function is printed.
1501 /// Only print the defs and the opcode if \p SkipOpers is true.
1502 /// Otherwise, also print operands if \p SkipDebugLoc is true.
1503 /// Otherwise, also print the debug loc, with a terminating newline.
1504 /// \p TII is used to print the opcode name. If it's not present, but the
1505 /// MI is in a function, the opcode will be printed using the function's TII.
1506 void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
1507 bool SkipDebugLoc = false, bool AddNewLine = true,
1508 const TargetInstrInfo *TII = nullptr) const;
1509 void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
1510 bool SkipOpers = false, bool SkipDebugLoc = false,
1511 bool AddNewLine = true,
1512 const TargetInstrInfo *TII = nullptr) const;
1516 //===--------------------------------------------------------------------===//
1517 // Accessors used to build up machine instructions.
1519 /// Add the specified operand to the instruction. If it is an implicit
1520 /// operand, it is added to the end of the operand list. If it is an
1521 /// explicit operand it is added at the end of the explicit operand list
1522 /// (before the first implicit operand).
1524 /// MF must be the machine function that was used to allocate this
1527 /// MachineInstrBuilder provides a more convenient interface for creating
1528 /// instructions and adding operands.
1529 void addOperand(MachineFunction &MF, const MachineOperand &Op);
1531 /// Add an operand without providing an MF reference. This only works for
1532 /// instructions that are inserted in a basic block.
1534 /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1536 void addOperand(const MachineOperand &Op);
1538 /// Replace the instruction descriptor (thus opcode) of
1539 /// the current instruction with a new one.
1540 void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1542 /// Replace current source information with new such.
1543 /// Avoid using this, the constructor argument is preferable.
1544 void setDebugLoc(DebugLoc dl) {
1545 debugLoc = std::move(dl);
1546 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1549 /// Erase an operand from an instruction, leaving it with one
1550 /// fewer operand than it started with.
1551 void RemoveOperand(unsigned OpNo);
1553 /// Clear this MachineInstr's memory reference descriptor list. This resets
1554 /// the memrefs to their most conservative state. This should be used only
1555 /// as a last resort since it greatly pessimizes our knowledge of the memory
1556 /// access performed by the instruction.
1557 void dropMemRefs(MachineFunction &MF);
1559 /// Assign this MachineInstr's memory reference descriptor list.
1561 /// Unlike other methods, this *will* allocate them into a new array
1562 /// associated with the provided `MachineFunction`.
1563 void setMemRefs(MachineFunction &MF, ArrayRef<MachineMemOperand *> MemRefs);
1565 /// Add a MachineMemOperand to the machine instruction.
1566 /// This function should be used only occasionally. The setMemRefs function
1567 /// is the primary method for setting up a MachineInstr's MemRefs list.
1568 void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1570 /// Clone another MachineInstr's memory reference descriptor list and replace
1573 /// Note that `*this` may be the incoming MI!
1575 /// Prefer this API whenever possible as it can avoid allocations in common
1577 void cloneMemRefs(MachineFunction &MF, const MachineInstr &MI);
1579 /// Clone the merge of multiple MachineInstrs' memory reference descriptors
1580 /// list and replace ours with it.
1582 /// Note that `*this` may be one of the incoming MIs!
1584 /// Prefer this API whenever possible as it can avoid allocations in common
1586 void cloneMergedMemRefs(MachineFunction &MF,
1587 ArrayRef<const MachineInstr *> MIs);
1589 /// Set a symbol that will be emitted just prior to the instruction itself.
1591 /// Setting this to a null pointer will remove any such symbol.
1593 /// FIXME: This is not fully implemented yet.
1594 void setPreInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1596 /// Set a symbol that will be emitted just after the instruction itself.
1598 /// Setting this to a null pointer will remove any such symbol.
1600 /// FIXME: This is not fully implemented yet.
1601 void setPostInstrSymbol(MachineFunction &MF, MCSymbol *Symbol);
1603 /// Clone another MachineInstr's pre- and post- instruction symbols and
1604 /// replace ours with it.
1605 void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI);
1607 /// Set a marker on instructions that denotes where we should create and emit
1608 /// heap alloc site labels. This waits until after instruction selection and
1609 /// optimizations to create the label, so it should still work if the
1610 /// instruction is removed or duplicated.
1611 void setHeapAllocMarker(MachineFunction &MF, MDNode *MD);
1613 /// Return the MIFlags which represent both MachineInstrs. This
1614 /// should be used when merging two MachineInstrs into one. This routine does
1615 /// not modify the MIFlags of this MachineInstr.
1616 uint16_t mergeFlagsWith(const MachineInstr& Other) const;
1618 static uint16_t copyFlagsFromInstruction(const Instruction &I);
1620 /// Copy all flags to MachineInst MIFlags
1621 void copyIRFlags(const Instruction &I);
1623 /// Break any tie involving OpIdx.
1624 void untieRegOperand(unsigned OpIdx) {
1625 MachineOperand &MO = getOperand(OpIdx);
1626 if (MO.isReg() && MO.isTied()) {
1627 getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1632 /// Add all implicit def and use operands to this instruction.
1633 void addImplicitDefUseOperands(MachineFunction &MF);
1635 /// Scan instructions following MI and collect any matching DBG_VALUEs.
1636 void collectDebugValues(SmallVectorImpl<MachineInstr *> &DbgValues);
1638 /// Find all DBG_VALUEs immediately following this instruction that point
1639 /// to a register def in this instruction and point them to \p Reg instead.
1640 void changeDebugValuesDefReg(unsigned Reg);
1643 /// If this instruction is embedded into a MachineFunction, return the
1644 /// MachineRegisterInfo object for the current function, otherwise
1646 MachineRegisterInfo *getRegInfo();
1648 /// Unlink all of the register operands in this instruction from their
1649 /// respective use lists. This requires that the operands already be on their
1651 void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1653 /// Add all of the register operands in this instruction from their
1654 /// respective use lists. This requires that the operands not be on their
1656 void AddRegOperandsToUseLists(MachineRegisterInfo&);
1658 /// Slow path for hasProperty when we're dealing with a bundle.
1659 bool hasPropertyInBundle(uint64_t Mask, QueryType Type) const;
1661 /// Implements the logic of getRegClassConstraintEffectForVReg for the
1662 /// this MI and the given operand index \p OpIdx.
1663 /// If the related operand does not constrained Reg, this returns CurRC.
1664 const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1665 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1666 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1668 /// Stores extra instruction information inline or allocates as ExtraInfo
1669 /// based on the number of pointers.
1670 void setExtraInfo(MachineFunction &MF, ArrayRef<MachineMemOperand *> MMOs,
1671 MCSymbol *PreInstrSymbol, MCSymbol *PostInstrSymbol,
1672 MDNode *HeapAllocMarker);
1675 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1676 /// instruction rather than by pointer value.
1677 /// The hashing and equality testing functions ignore definitions so this is
1678 /// useful for CSE, etc.
1679 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1680 static inline MachineInstr *getEmptyKey() {
1684 static inline MachineInstr *getTombstoneKey() {
1685 return reinterpret_cast<MachineInstr*>(-1);
1688 static unsigned getHashValue(const MachineInstr* const &MI);
1690 static bool isEqual(const MachineInstr* const &LHS,
1691 const MachineInstr* const &RHS) {
1692 if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1693 LHS == getEmptyKey() || LHS == getTombstoneKey())
1695 return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
1699 //===----------------------------------------------------------------------===//
1700 // Debugging Support
1702 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1707 } // end namespace llvm
1709 #endif // LLVM_CODEGEN_MACHINEINSTR_H