1 //===-- llvm/CodeGen/MachineInstr.h - MachineInstr class --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the declaration of the MachineInstr class, which is the
11 // basic representation for all target dependent machine instructions used by
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
17 #define LLVM_CODEGEN_MACHINEINSTR_H
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMapInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/ilist.h"
24 #include "llvm/ADT/ilist_node.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/CodeGen/MachineOperand.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DebugLoc.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/Support/ArrayRecycler.h"
32 #include "llvm/Target/TargetOpcodes.h"
36 template <typename T> class SmallVectorImpl;
38 class TargetInstrInfo;
39 class TargetRegisterClass;
40 class TargetRegisterInfo;
41 class MachineFunction;
42 class MachineMemOperand;
44 //===----------------------------------------------------------------------===//
45 /// Representation of each machine instruction.
47 /// This class isn't a POD type, but it must have a trivial destructor. When a
48 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
49 /// without having their destructor called.
51 class MachineInstr : public ilist_node<MachineInstr> {
53 typedef MachineMemOperand **mmo_iterator;
55 /// Flags to specify different kinds of comments to output in
56 /// assembly code. These flags carry semantic information not
57 /// otherwise easily derivable from the IR text.
65 FrameSetup = 1 << 0, // Instruction is used as a part of
66 // function frame setup code.
67 BundledPred = 1 << 1, // Instruction has bundled predecessors.
68 BundledSucc = 1 << 2 // Instruction has bundled successors.
71 const MCInstrDesc *MCID; // Instruction descriptor.
72 MachineBasicBlock *Parent; // Pointer to the owning basic block.
74 // Operands are allocated by an ArrayRecycler.
75 MachineOperand *Operands; // Pointer to the first operand.
76 unsigned NumOperands; // Number of operands on instruction.
77 typedef ArrayRecycler<MachineOperand>::Capacity OperandCapacity;
78 OperandCapacity CapOperands; // Capacity of the Operands array.
80 uint8_t Flags; // Various bits of additional
81 // information about machine
84 uint8_t AsmPrinterFlags; // Various bits of information used by
85 // the AsmPrinter to emit helpful
86 // comments. This is *not* semantic
87 // information. Do not use this for
88 // anything other than to convey comment
89 // information to AsmPrinter.
91 uint8_t NumMemRefs; // Information on memory references.
94 DebugLoc debugLoc; // Source line information.
96 MachineInstr(const MachineInstr&) = delete;
97 void operator=(const MachineInstr&) = delete;
98 // Use MachineFunction::DeleteMachineInstr() instead.
99 ~MachineInstr() = delete;
101 // Intrusive list support
102 friend struct ilist_traits<MachineInstr>;
103 friend struct ilist_traits<MachineBasicBlock>;
104 void setParent(MachineBasicBlock *P) { Parent = P; }
106 /// This constructor creates a copy of the given
107 /// MachineInstr in the given MachineFunction.
108 MachineInstr(MachineFunction &, const MachineInstr &);
110 /// This constructor create a MachineInstr and add the implicit operands.
111 /// It reserves space for number of operands specified by
112 /// MCInstrDesc. An explicit DebugLoc is supplied.
113 MachineInstr(MachineFunction &, const MCInstrDesc &MCID, DebugLoc dl,
116 // MachineInstrs are pool-allocated and owned by MachineFunction.
117 friend class MachineFunction;
120 const MachineBasicBlock* getParent() const { return Parent; }
121 MachineBasicBlock* getParent() { return Parent; }
123 /// Return the asm printer flags bitvector.
124 uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
126 /// Clear the AsmPrinter bitvector.
127 void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
129 /// Return whether an AsmPrinter flag is set.
130 bool getAsmPrinterFlag(CommentFlag Flag) const {
131 return AsmPrinterFlags & Flag;
134 /// Set a flag for the AsmPrinter.
135 void setAsmPrinterFlag(CommentFlag Flag) {
136 AsmPrinterFlags |= (uint8_t)Flag;
139 /// Clear specific AsmPrinter flags.
140 void clearAsmPrinterFlag(CommentFlag Flag) {
141 AsmPrinterFlags &= ~Flag;
144 /// Return the MI flags bitvector.
145 uint8_t getFlags() const {
149 /// Return whether an MI flag is set.
150 bool getFlag(MIFlag Flag) const {
155 void setFlag(MIFlag Flag) {
156 Flags |= (uint8_t)Flag;
159 void setFlags(unsigned flags) {
160 // Filter out the automatically maintained flags.
161 unsigned Mask = BundledPred | BundledSucc;
162 Flags = (Flags & Mask) | (flags & ~Mask);
165 /// clearFlag - Clear a MI flag.
166 void clearFlag(MIFlag Flag) {
167 Flags &= ~((uint8_t)Flag);
170 /// Return true if MI is in a bundle (but not the first MI in a bundle).
172 /// A bundle looks like this before it's finalized:
184 /// In this case, the first MI starts a bundle but is not inside a bundle, the
185 /// next 2 MIs are considered "inside" the bundle.
187 /// After a bundle is finalized, it looks like this:
203 /// The first instruction has the special opcode "BUNDLE". It's not "inside"
204 /// a bundle, but the next three MIs are.
205 bool isInsideBundle() const {
206 return getFlag(BundledPred);
209 /// Return true if this instruction part of a bundle. This is true
210 /// if either itself or its following instruction is marked "InsideBundle".
211 bool isBundled() const {
212 return isBundledWithPred() || isBundledWithSucc();
215 /// Return true if this instruction is part of a bundle, and it is not the
216 /// first instruction in the bundle.
217 bool isBundledWithPred() const { return getFlag(BundledPred); }
219 /// Return true if this instruction is part of a bundle, and it is not the
220 /// last instruction in the bundle.
221 bool isBundledWithSucc() const { return getFlag(BundledSucc); }
223 /// Bundle this instruction with its predecessor. This can be an unbundled
224 /// instruction, or it can be the first instruction in a bundle.
225 void bundleWithPred();
227 /// Bundle this instruction with its successor. This can be an unbundled
228 /// instruction, or it can be the last instruction in a bundle.
229 void bundleWithSucc();
231 /// Break bundle above this instruction.
232 void unbundleFromPred();
234 /// Break bundle below this instruction.
235 void unbundleFromSucc();
237 /// Returns the debug location id of this MachineInstr.
238 const DebugLoc &getDebugLoc() const { return debugLoc; }
240 /// Return the debug variable referenced by
241 /// this DBG_VALUE instruction.
242 const DILocalVariable *getDebugVariable() const {
243 assert(isDebugValue() && "not a DBG_VALUE");
244 return cast<DILocalVariable>(getOperand(2).getMetadata());
247 /// Return the complex address expression referenced by
248 /// this DBG_VALUE instruction.
249 const DIExpression *getDebugExpression() const {
250 assert(isDebugValue() && "not a DBG_VALUE");
251 return cast<DIExpression>(getOperand(3).getMetadata());
254 /// Emit an error referring to the source location of this instruction.
255 /// This should only be used for inline assembly that is somehow
256 /// impossible to compile. Other errors should have been handled much
259 /// If this method returns, the caller should try to recover from the error.
261 void emitError(StringRef Msg) const;
263 /// Returns the target instruction descriptor of this MachineInstr.
264 const MCInstrDesc &getDesc() const { return *MCID; }
266 /// Returns the opcode of this MachineInstr.
267 unsigned getOpcode() const { return MCID->Opcode; }
269 /// Access to explicit operands of the instruction.
271 unsigned getNumOperands() const { return NumOperands; }
273 const MachineOperand& getOperand(unsigned i) const {
274 assert(i < getNumOperands() && "getOperand() out of range!");
277 MachineOperand& getOperand(unsigned i) {
278 assert(i < getNumOperands() && "getOperand() out of range!");
282 /// Returns the number of non-implicit operands.
283 unsigned getNumExplicitOperands() const;
285 /// iterator/begin/end - Iterate over all operands of a machine instruction.
286 typedef MachineOperand *mop_iterator;
287 typedef const MachineOperand *const_mop_iterator;
289 mop_iterator operands_begin() { return Operands; }
290 mop_iterator operands_end() { return Operands + NumOperands; }
292 const_mop_iterator operands_begin() const { return Operands; }
293 const_mop_iterator operands_end() const { return Operands + NumOperands; }
295 iterator_range<mop_iterator> operands() {
296 return iterator_range<mop_iterator>(operands_begin(), operands_end());
298 iterator_range<const_mop_iterator> operands() const {
299 return iterator_range<const_mop_iterator>(operands_begin(), operands_end());
301 iterator_range<mop_iterator> explicit_operands() {
302 return iterator_range<mop_iterator>(
303 operands_begin(), operands_begin() + getNumExplicitOperands());
305 iterator_range<const_mop_iterator> explicit_operands() const {
306 return iterator_range<const_mop_iterator>(
307 operands_begin(), operands_begin() + getNumExplicitOperands());
309 iterator_range<mop_iterator> implicit_operands() {
310 return iterator_range<mop_iterator>(explicit_operands().end(),
313 iterator_range<const_mop_iterator> implicit_operands() const {
314 return iterator_range<const_mop_iterator>(explicit_operands().end(),
317 iterator_range<mop_iterator> defs() {
318 return iterator_range<mop_iterator>(
319 operands_begin(), operands_begin() + getDesc().getNumDefs());
321 iterator_range<const_mop_iterator> defs() const {
322 return iterator_range<const_mop_iterator>(
323 operands_begin(), operands_begin() + getDesc().getNumDefs());
325 iterator_range<mop_iterator> uses() {
326 return iterator_range<mop_iterator>(
327 operands_begin() + getDesc().getNumDefs(), operands_end());
329 iterator_range<const_mop_iterator> uses() const {
330 return iterator_range<const_mop_iterator>(
331 operands_begin() + getDesc().getNumDefs(), operands_end());
334 /// Access to memory operands of the instruction
335 mmo_iterator memoperands_begin() const { return MemRefs; }
336 mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
337 bool memoperands_empty() const { return NumMemRefs == 0; }
339 iterator_range<mmo_iterator> memoperands() {
340 return iterator_range<mmo_iterator>(memoperands_begin(), memoperands_end());
342 iterator_range<mmo_iterator> memoperands() const {
343 return iterator_range<mmo_iterator>(memoperands_begin(), memoperands_end());
346 /// Return true if this instruction has exactly one MachineMemOperand.
347 bool hasOneMemOperand() const {
348 return NumMemRefs == 1;
351 /// API for querying MachineInstr properties. They are the same as MCInstrDesc
352 /// queries but they are bundle aware.
355 IgnoreBundle, // Ignore bundles
356 AnyInBundle, // Return true if any instruction in bundle has property
357 AllInBundle // Return true if all instructions in bundle have property
360 /// Return true if the instruction (or in the case of a bundle,
361 /// the instructions inside the bundle) has the specified property.
362 /// The first argument is the property being queried.
363 /// The second argument indicates whether the query should look inside
364 /// instruction bundles.
365 bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
366 // Inline the fast path for unbundled or bundle-internal instructions.
367 if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
368 return getDesc().getFlags() & (1 << MCFlag);
370 // If this is the first instruction in a bundle, take the slow path.
371 return hasPropertyInBundle(1 << MCFlag, Type);
374 /// Return true if this instruction can have a variable number of operands.
375 /// In this case, the variable operands will be after the normal
376 /// operands but before the implicit definitions and uses (if any are
378 bool isVariadic(QueryType Type = IgnoreBundle) const {
379 return hasProperty(MCID::Variadic, Type);
382 /// Set if this instruction has an optional definition, e.g.
383 /// ARM instructions which can set condition code if 's' bit is set.
384 bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
385 return hasProperty(MCID::HasOptionalDef, Type);
388 /// Return true if this is a pseudo instruction that doesn't
389 /// correspond to a real machine instruction.
390 bool isPseudo(QueryType Type = IgnoreBundle) const {
391 return hasProperty(MCID::Pseudo, Type);
394 bool isReturn(QueryType Type = AnyInBundle) const {
395 return hasProperty(MCID::Return, Type);
398 bool isCall(QueryType Type = AnyInBundle) const {
399 return hasProperty(MCID::Call, Type);
402 /// Returns true if the specified instruction stops control flow
403 /// from executing the instruction immediately following it. Examples include
404 /// unconditional branches and return instructions.
405 bool isBarrier(QueryType Type = AnyInBundle) const {
406 return hasProperty(MCID::Barrier, Type);
409 /// Returns true if this instruction part of the terminator for a basic block.
410 /// Typically this is things like return and branch instructions.
412 /// Various passes use this to insert code into the bottom of a basic block,
413 /// but before control flow occurs.
414 bool isTerminator(QueryType Type = AnyInBundle) const {
415 return hasProperty(MCID::Terminator, Type);
418 /// Returns true if this is a conditional, unconditional, or indirect branch.
419 /// Predicates below can be used to discriminate between
420 /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
421 /// get more information.
422 bool isBranch(QueryType Type = AnyInBundle) const {
423 return hasProperty(MCID::Branch, Type);
426 /// Return true if this is an indirect branch, such as a
427 /// branch through a register.
428 bool isIndirectBranch(QueryType Type = AnyInBundle) const {
429 return hasProperty(MCID::IndirectBranch, Type);
432 /// Return true if this is a branch which may fall
433 /// through to the next instruction or may transfer control flow to some other
434 /// block. The TargetInstrInfo::AnalyzeBranch method can be used to get more
435 /// information about this branch.
436 bool isConditionalBranch(QueryType Type = AnyInBundle) const {
437 return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
440 /// Return true if this is a branch which always
441 /// transfers control flow to some other block. The
442 /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
443 /// about this branch.
444 bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
445 return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
448 /// Return true if this instruction has a predicate operand that
449 /// controls execution. It may be set to 'always', or may be set to other
450 /// values. There are various methods in TargetInstrInfo that can be used to
451 /// control and modify the predicate in this instruction.
452 bool isPredicable(QueryType Type = AllInBundle) const {
453 // If it's a bundle than all bundled instructions must be predicable for this
455 return hasProperty(MCID::Predicable, Type);
458 /// Return true if this instruction is a comparison.
459 bool isCompare(QueryType Type = IgnoreBundle) const {
460 return hasProperty(MCID::Compare, Type);
463 /// Return true if this instruction is a move immediate
464 /// (including conditional moves) instruction.
465 bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
466 return hasProperty(MCID::MoveImm, Type);
469 /// Return true if this instruction is a bitcast instruction.
470 bool isBitcast(QueryType Type = IgnoreBundle) const {
471 return hasProperty(MCID::Bitcast, Type);
474 /// Return true if this instruction is a select instruction.
475 bool isSelect(QueryType Type = IgnoreBundle) const {
476 return hasProperty(MCID::Select, Type);
479 /// Return true if this instruction cannot be safely duplicated.
480 /// For example, if the instruction has a unique labels attached
481 /// to it, duplicating it would cause multiple definition errors.
482 bool isNotDuplicable(QueryType Type = AnyInBundle) const {
483 return hasProperty(MCID::NotDuplicable, Type);
486 /// Return true if this instruction is convergent.
487 /// Convergent instructions can only be moved to locations that are
488 /// control-equivalent to their initial position.
489 bool isConvergent(QueryType Type = AnyInBundle) const {
490 return hasProperty(MCID::Convergent, Type);
493 /// Returns true if the specified instruction has a delay slot
494 /// which must be filled by the code generator.
495 bool hasDelaySlot(QueryType Type = AnyInBundle) const {
496 return hasProperty(MCID::DelaySlot, Type);
499 /// Return true for instructions that can be folded as
500 /// memory operands in other instructions. The most common use for this
501 /// is instructions that are simple loads from memory that don't modify
502 /// the loaded value in any way, but it can also be used for instructions
503 /// that can be expressed as constant-pool loads, such as V_SETALLONES
504 /// on x86, to allow them to be folded when it is beneficial.
505 /// This should only be set on instructions that return a value in their
506 /// only virtual register definition.
507 bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
508 return hasProperty(MCID::FoldableAsLoad, Type);
511 /// \brief Return true if this instruction behaves
512 /// the same way as the generic REG_SEQUENCE instructions.
514 /// dX VMOVDRR rY, rZ
516 /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
518 /// Note that for the optimizers to be able to take advantage of
519 /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
520 /// override accordingly.
521 bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
522 return hasProperty(MCID::RegSequence, Type);
525 /// \brief Return true if this instruction behaves
526 /// the same way as the generic EXTRACT_SUBREG instructions.
528 /// rX, rY VMOVRRD dZ
529 /// is equivalent to two EXTRACT_SUBREG:
530 /// rX = EXTRACT_SUBREG dZ, ssub_0
531 /// rY = EXTRACT_SUBREG dZ, ssub_1
533 /// Note that for the optimizers to be able to take advantage of
534 /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
535 /// override accordingly.
536 bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
537 return hasProperty(MCID::ExtractSubreg, Type);
540 /// \brief Return true if this instruction behaves
541 /// the same way as the generic INSERT_SUBREG instructions.
543 /// dX = VSETLNi32 dY, rZ, Imm
544 /// is equivalent to a INSERT_SUBREG:
545 /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
547 /// Note that for the optimizers to be able to take advantage of
548 /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
549 /// override accordingly.
550 bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
551 return hasProperty(MCID::InsertSubreg, Type);
554 //===--------------------------------------------------------------------===//
555 // Side Effect Analysis
556 //===--------------------------------------------------------------------===//
558 /// Return true if this instruction could possibly read memory.
559 /// Instructions with this flag set are not necessarily simple load
560 /// instructions, they may load a value and modify it, for example.
561 bool mayLoad(QueryType Type = AnyInBundle) const {
563 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
564 if (ExtraInfo & InlineAsm::Extra_MayLoad)
567 return hasProperty(MCID::MayLoad, Type);
570 /// Return true if this instruction could possibly modify memory.
571 /// Instructions with this flag set are not necessarily simple store
572 /// instructions, they may store a modified value based on their operands, or
573 /// may not actually modify anything, for example.
574 bool mayStore(QueryType Type = AnyInBundle) const {
576 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
577 if (ExtraInfo & InlineAsm::Extra_MayStore)
580 return hasProperty(MCID::MayStore, Type);
583 /// Return true if this instruction could possibly read or modify memory.
584 bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
585 return mayLoad(Type) || mayStore(Type);
588 //===--------------------------------------------------------------------===//
589 // Flags that indicate whether an instruction can be modified by a method.
590 //===--------------------------------------------------------------------===//
592 /// Return true if this may be a 2- or 3-address
593 /// instruction (of the form "X = op Y, Z, ..."), which produces the same
594 /// result if Y and Z are exchanged. If this flag is set, then the
595 /// TargetInstrInfo::commuteInstruction method may be used to hack on the
598 /// Note that this flag may be set on instructions that are only commutable
599 /// sometimes. In these cases, the call to commuteInstruction will fail.
600 /// Also note that some instructions require non-trivial modification to
602 bool isCommutable(QueryType Type = IgnoreBundle) const {
603 return hasProperty(MCID::Commutable, Type);
606 /// Return true if this is a 2-address instruction
607 /// which can be changed into a 3-address instruction if needed. Doing this
608 /// transformation can be profitable in the register allocator, because it
609 /// means that the instruction can use a 2-address form if possible, but
610 /// degrade into a less efficient form if the source and dest register cannot
611 /// be assigned to the same register. For example, this allows the x86
612 /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
613 /// is the same speed as the shift but has bigger code size.
615 /// If this returns true, then the target must implement the
616 /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
617 /// is allowed to fail if the transformation isn't valid for this specific
618 /// instruction (e.g. shl reg, 4 on x86).
620 bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
621 return hasProperty(MCID::ConvertibleTo3Addr, Type);
624 /// Return true if this instruction requires
625 /// custom insertion support when the DAG scheduler is inserting it into a
626 /// machine basic block. If this is true for the instruction, it basically
627 /// means that it is a pseudo instruction used at SelectionDAG time that is
628 /// expanded out into magic code by the target when MachineInstrs are formed.
630 /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
631 /// is used to insert this into the MachineBasicBlock.
632 bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
633 return hasProperty(MCID::UsesCustomInserter, Type);
636 /// Return true if this instruction requires *adjustment*
637 /// after instruction selection by calling a target hook. For example, this
638 /// can be used to fill in ARM 's' optional operand depending on whether
639 /// the conditional flag register is used.
640 bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
641 return hasProperty(MCID::HasPostISelHook, Type);
644 /// Returns true if this instruction is a candidate for remat.
645 /// This flag is deprecated, please don't use it anymore. If this
646 /// flag is set, the isReallyTriviallyReMaterializable() method is called to
647 /// verify the instruction is really rematable.
648 bool isRematerializable(QueryType Type = AllInBundle) const {
649 // It's only possible to re-mat a bundle if all bundled instructions are
650 // re-materializable.
651 return hasProperty(MCID::Rematerializable, Type);
654 /// Returns true if this instruction has the same cost (or less) than a move
655 /// instruction. This is useful during certain types of optimizations
656 /// (e.g., remat during two-address conversion or machine licm)
657 /// where we would like to remat or hoist the instruction, but not if it costs
658 /// more than moving the instruction into the appropriate register. Note, we
659 /// are not marking copies from and to the same register class with this flag.
660 bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
661 // Only returns true for a bundle if all bundled instructions are cheap.
662 return hasProperty(MCID::CheapAsAMove, Type);
665 /// Returns true if this instruction source operands
666 /// have special register allocation requirements that are not captured by the
667 /// operand register classes. e.g. ARM::STRD's two source registers must be an
668 /// even / odd pair, ARM::STM registers have to be in ascending order.
669 /// Post-register allocation passes should not attempt to change allocations
670 /// for sources of instructions with this flag.
671 bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
672 return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
675 /// Returns true if this instruction def operands
676 /// have special register allocation requirements that are not captured by the
677 /// operand register classes. e.g. ARM::LDRD's two def registers must be an
678 /// even / odd pair, ARM::LDM registers have to be in ascending order.
679 /// Post-register allocation passes should not attempt to change allocations
680 /// for definitions of instructions with this flag.
681 bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
682 return hasProperty(MCID::ExtraDefRegAllocReq, Type);
687 CheckDefs, // Check all operands for equality
688 CheckKillDead, // Check all operands including kill / dead markers
689 IgnoreDefs, // Ignore all definitions
690 IgnoreVRegDefs // Ignore virtual register definitions
693 /// Return true if this instruction is identical to (same
694 /// opcode and same operands as) the specified instruction.
695 bool isIdenticalTo(const MachineInstr *Other,
696 MICheckType Check = CheckDefs) const;
698 /// Unlink 'this' from the containing basic block, and return it without
701 /// This function can not be used on bundled instructions, use
702 /// removeFromBundle() to remove individual instructions from a bundle.
703 MachineInstr *removeFromParent();
705 /// Unlink this instruction from its basic block and return it without
708 /// If the instruction is part of a bundle, the other instructions in the
709 /// bundle remain bundled.
710 MachineInstr *removeFromBundle();
712 /// Unlink 'this' from the containing basic block and delete it.
714 /// If this instruction is the header of a bundle, the whole bundle is erased.
715 /// This function can not be used for instructions inside a bundle, use
716 /// eraseFromBundle() to erase individual bundled instructions.
717 void eraseFromParent();
719 /// Unlink 'this' from the containing basic block and delete it.
721 /// For all definitions mark their uses in DBG_VALUE nodes
722 /// as undefined. Otherwise like eraseFromParent().
723 void eraseFromParentAndMarkDBGValuesForRemoval();
725 /// Unlink 'this' form its basic block and delete it.
727 /// If the instruction is part of a bundle, the other instructions in the
728 /// bundle remain bundled.
729 void eraseFromBundle();
731 bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
732 bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
734 /// Returns true if the MachineInstr represents a label.
735 bool isLabel() const { return isEHLabel() || isGCLabel(); }
736 bool isCFIInstruction() const {
737 return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
740 // True if the instruction represents a position in the function.
741 bool isPosition() const { return isLabel() || isCFIInstruction(); }
743 bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
744 /// A DBG_VALUE is indirect iff the first operand is a register and
745 /// the second operand is an immediate.
746 bool isIndirectDebugValue() const {
747 return isDebugValue()
748 && getOperand(0).isReg()
749 && getOperand(1).isImm();
752 bool isPHI() const { return getOpcode() == TargetOpcode::PHI; }
753 bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
754 bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
755 bool isInlineAsm() const { return getOpcode() == TargetOpcode::INLINEASM; }
756 bool isMSInlineAsm() const {
757 return getOpcode() == TargetOpcode::INLINEASM && getInlineAsmDialect();
759 bool isStackAligningInlineAsm() const;
760 InlineAsm::AsmDialect getInlineAsmDialect() const;
761 bool isInsertSubreg() const {
762 return getOpcode() == TargetOpcode::INSERT_SUBREG;
764 bool isSubregToReg() const {
765 return getOpcode() == TargetOpcode::SUBREG_TO_REG;
767 bool isRegSequence() const {
768 return getOpcode() == TargetOpcode::REG_SEQUENCE;
770 bool isBundle() const {
771 return getOpcode() == TargetOpcode::BUNDLE;
773 bool isCopy() const {
774 return getOpcode() == TargetOpcode::COPY;
776 bool isFullCopy() const {
777 return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
779 bool isExtractSubreg() const {
780 return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
783 /// Return true if the instruction behaves like a copy.
784 /// This does not include native copy instructions.
785 bool isCopyLike() const {
786 return isCopy() || isSubregToReg();
789 /// Return true is the instruction is an identity copy.
790 bool isIdentityCopy() const {
791 return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
792 getOperand(0).getSubReg() == getOperand(1).getSubReg();
795 /// Return true if this is a transient instruction that is
796 /// either very likely to be eliminated during register allocation (such as
797 /// copy-like instructions), or if this instruction doesn't have an
798 /// execution-time cost.
799 bool isTransient() const {
800 switch(getOpcode()) {
801 default: return false;
802 // Copy-like instructions are usually eliminated during register allocation.
803 case TargetOpcode::PHI:
804 case TargetOpcode::COPY:
805 case TargetOpcode::INSERT_SUBREG:
806 case TargetOpcode::SUBREG_TO_REG:
807 case TargetOpcode::REG_SEQUENCE:
808 // Pseudo-instructions that don't produce any real output.
809 case TargetOpcode::IMPLICIT_DEF:
810 case TargetOpcode::KILL:
811 case TargetOpcode::CFI_INSTRUCTION:
812 case TargetOpcode::EH_LABEL:
813 case TargetOpcode::GC_LABEL:
814 case TargetOpcode::DBG_VALUE:
819 /// Return the number of instructions inside the MI bundle, excluding the
822 /// This is the number of instructions that MachineBasicBlock::iterator
823 /// skips, 0 for unbundled instructions.
824 unsigned getBundleSize() const;
826 /// Return true if the MachineInstr reads the specified register.
827 /// If TargetRegisterInfo is passed, then it also checks if there
828 /// is a read of a super-register.
829 /// This does not count partial redefines of virtual registers as reads:
831 bool readsRegister(unsigned Reg,
832 const TargetRegisterInfo *TRI = nullptr) const {
833 return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
836 /// Return true if the MachineInstr reads the specified virtual register.
837 /// Take into account that a partial define is a
838 /// read-modify-write operation.
839 bool readsVirtualRegister(unsigned Reg) const {
840 return readsWritesVirtualRegister(Reg).first;
843 /// Return a pair of bools (reads, writes) indicating if this instruction
844 /// reads or writes Reg. This also considers partial defines.
845 /// If Ops is not null, all operand indices for Reg are added.
846 std::pair<bool,bool> readsWritesVirtualRegister(unsigned Reg,
847 SmallVectorImpl<unsigned> *Ops = nullptr) const;
849 /// Return true if the MachineInstr kills the specified register.
850 /// If TargetRegisterInfo is passed, then it also checks if there is
851 /// a kill of a super-register.
852 bool killsRegister(unsigned Reg,
853 const TargetRegisterInfo *TRI = nullptr) const {
854 return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
857 /// Return true if the MachineInstr fully defines the specified register.
858 /// If TargetRegisterInfo is passed, then it also checks
859 /// if there is a def of a super-register.
860 /// NOTE: It's ignoring subreg indices on virtual registers.
861 bool definesRegister(unsigned Reg,
862 const TargetRegisterInfo *TRI = nullptr) const {
863 return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
866 /// Return true if the MachineInstr modifies (fully define or partially
867 /// define) the specified register.
868 /// NOTE: It's ignoring subreg indices on virtual registers.
869 bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const {
870 return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
873 /// Returns true if the register is dead in this machine instruction.
874 /// If TargetRegisterInfo is passed, then it also checks
875 /// if there is a dead def of a super-register.
876 bool registerDefIsDead(unsigned Reg,
877 const TargetRegisterInfo *TRI = nullptr) const {
878 return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
881 /// Returns the operand index that is a use of the specific register or -1
882 /// if it is not found. It further tightens the search criteria to a use
883 /// that kills the register if isKill is true.
884 int findRegisterUseOperandIdx(unsigned Reg, bool isKill = false,
885 const TargetRegisterInfo *TRI = nullptr) const;
887 /// Wrapper for findRegisterUseOperandIdx, it returns
888 /// a pointer to the MachineOperand rather than an index.
889 MachineOperand *findRegisterUseOperand(unsigned Reg, bool isKill = false,
890 const TargetRegisterInfo *TRI = nullptr) {
891 int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
892 return (Idx == -1) ? nullptr : &getOperand(Idx);
895 /// Returns the operand index that is a def of the specified register or
896 /// -1 if it is not found. If isDead is true, defs that are not dead are
897 /// skipped. If Overlap is true, then it also looks for defs that merely
898 /// overlap the specified register. If TargetRegisterInfo is non-null,
899 /// then it also checks if there is a def of a super-register.
900 /// This may also return a register mask operand when Overlap is true.
901 int findRegisterDefOperandIdx(unsigned Reg,
902 bool isDead = false, bool Overlap = false,
903 const TargetRegisterInfo *TRI = nullptr) const;
905 /// Wrapper for findRegisterDefOperandIdx, it returns
906 /// a pointer to the MachineOperand rather than an index.
907 MachineOperand *findRegisterDefOperand(unsigned Reg, bool isDead = false,
908 const TargetRegisterInfo *TRI = nullptr) {
909 int Idx = findRegisterDefOperandIdx(Reg, isDead, false, TRI);
910 return (Idx == -1) ? nullptr : &getOperand(Idx);
913 /// Find the index of the first operand in the
914 /// operand list that is used to represent the predicate. It returns -1 if
916 int findFirstPredOperandIdx() const;
918 /// Find the index of the flag word operand that
919 /// corresponds to operand OpIdx on an inline asm instruction. Returns -1 if
920 /// getOperand(OpIdx) does not belong to an inline asm operand group.
922 /// If GroupNo is not NULL, it will receive the number of the operand group
923 /// containing OpIdx.
925 /// The flag operand is an immediate that can be decoded with methods like
926 /// InlineAsm::hasRegClassConstraint().
928 int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
930 /// Compute the static register class constraint for operand OpIdx.
931 /// For normal instructions, this is derived from the MCInstrDesc.
932 /// For inline assembly it is derived from the flag words.
934 /// Returns NULL if the static register classs constraint cannot be
937 const TargetRegisterClass*
938 getRegClassConstraint(unsigned OpIdx,
939 const TargetInstrInfo *TII,
940 const TargetRegisterInfo *TRI) const;
942 /// \brief Applies the constraints (def/use) implied by this MI on \p Reg to
943 /// the given \p CurRC.
944 /// If \p ExploreBundle is set and MI is part of a bundle, all the
945 /// instructions inside the bundle will be taken into account. In other words,
946 /// this method accumulates all the constrains of the operand of this MI and
947 /// the related bundle if MI is a bundle or inside a bundle.
949 /// Returns the register class that statisfies both \p CurRC and the
950 /// constraints set by MI. Returns NULL if such a register class does not
953 /// \pre CurRC must not be NULL.
954 const TargetRegisterClass *getRegClassConstraintEffectForVReg(
955 unsigned Reg, const TargetRegisterClass *CurRC,
956 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
957 bool ExploreBundle = false) const;
959 /// \brief Applies the constraints (def/use) implied by the \p OpIdx operand
960 /// to the given \p CurRC.
962 /// Returns the register class that statisfies both \p CurRC and the
963 /// constraints set by \p OpIdx MI. Returns NULL if such a register class
966 /// \pre CurRC must not be NULL.
967 /// \pre The operand at \p OpIdx must be a register.
968 const TargetRegisterClass *
969 getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
970 const TargetInstrInfo *TII,
971 const TargetRegisterInfo *TRI) const;
973 /// Add a tie between the register operands at DefIdx and UseIdx.
974 /// The tie will cause the register allocator to ensure that the two
975 /// operands are assigned the same physical register.
977 /// Tied operands are managed automatically for explicit operands in the
978 /// MCInstrDesc. This method is for exceptional cases like inline asm.
979 void tieOperands(unsigned DefIdx, unsigned UseIdx);
981 /// Given the index of a tied register operand, find the
982 /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
983 /// index of the tied operand which must exist.
984 unsigned findTiedOperandIdx(unsigned OpIdx) const;
986 /// Given the index of a register def operand,
987 /// check if the register def is tied to a source operand, due to either
988 /// two-address elimination or inline assembly constraints. Returns the
989 /// first tied use operand index by reference if UseOpIdx is not null.
990 bool isRegTiedToUseOperand(unsigned DefOpIdx,
991 unsigned *UseOpIdx = nullptr) const {
992 const MachineOperand &MO = getOperand(DefOpIdx);
993 if (!MO.isReg() || !MO.isDef() || !MO.isTied())
996 *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1000 /// Return true if the use operand of the specified index is tied to a def
1001 /// operand. It also returns the def operand index by reference if DefOpIdx
1003 bool isRegTiedToDefOperand(unsigned UseOpIdx,
1004 unsigned *DefOpIdx = nullptr) const {
1005 const MachineOperand &MO = getOperand(UseOpIdx);
1006 if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1009 *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1013 /// Clears kill flags on all operands.
1014 void clearKillInfo();
1016 /// Replace all occurrences of FromReg with ToReg:SubIdx,
1017 /// properly composing subreg indices where necessary.
1018 void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx,
1019 const TargetRegisterInfo &RegInfo);
1021 /// We have determined MI kills a register. Look for the
1022 /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1023 /// add a implicit operand if it's not found. Returns true if the operand
1024 /// exists / is added.
1025 bool addRegisterKilled(unsigned IncomingReg,
1026 const TargetRegisterInfo *RegInfo,
1027 bool AddIfNotFound = false);
1029 /// Clear all kill flags affecting Reg. If RegInfo is
1030 /// provided, this includes super-register kills.
1031 void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
1033 /// We have determined MI defined a register without a use.
1034 /// Look for the operand that defines it and mark it as IsDead. If
1035 /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1036 /// true if the operand exists / is added.
1037 bool addRegisterDead(unsigned Reg, const TargetRegisterInfo *RegInfo,
1038 bool AddIfNotFound = false);
1040 /// Clear all dead flags on operands defining register @p Reg.
1041 void clearRegisterDeads(unsigned Reg);
1043 /// Mark all subregister defs of register @p Reg with the undef flag.
1044 /// This function is used when we determined to have a subregister def in an
1045 /// otherwise undefined super register.
1046 void addRegisterDefReadUndef(unsigned Reg);
1048 /// We have determined MI defines a register. Make sure there is an operand
1050 void addRegisterDefined(unsigned Reg,
1051 const TargetRegisterInfo *RegInfo = nullptr);
1053 /// Mark every physreg used by this instruction as
1054 /// dead except those in the UsedRegs list.
1056 /// On instructions with register mask operands, also add implicit-def
1057 /// operands for all registers in UsedRegs.
1058 void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1059 const TargetRegisterInfo &TRI);
1061 /// Return true if it is safe to move this instruction. If
1062 /// SawStore is set to true, it means that there is a store (or call) between
1063 /// the instruction's location and its intended destination.
1064 bool isSafeToMove(AliasAnalysis *AA, bool &SawStore) const;
1066 /// Return true if this instruction may have an ordered
1067 /// or volatile memory reference, or if the information describing the memory
1068 /// reference is not available. Return false if it is known to have no
1069 /// ordered or volatile memory references.
1070 bool hasOrderedMemoryRef() const;
1072 /// Return true if this instruction is loading from a
1073 /// location whose value is invariant across the function. For example,
1074 /// loading a value from the constant pool or from the argument area of
1075 /// a function if it does not change. This should only return true of *all*
1076 /// loads the instruction does are invariant (if it does multiple loads).
1077 bool isInvariantLoad(AliasAnalysis *AA) const;
1079 /// If the specified instruction is a PHI that always merges together the
1080 /// same virtual register, return the register, otherwise return 0.
1081 unsigned isConstantValuePHI() const;
1083 /// Return true if this instruction has side effects that are not modeled
1084 /// by mayLoad / mayStore, etc.
1085 /// For all instructions, the property is encoded in MCInstrDesc::Flags
1086 /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1087 /// INLINEASM instruction, in which case the side effect property is encoded
1088 /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1090 bool hasUnmodeledSideEffects() const;
1092 /// Return true if all the defs of this instruction are dead.
1093 bool allDefsAreDead() const;
1095 /// Copy implicit register operands from specified
1096 /// instruction to this instruction.
1097 void copyImplicitOps(MachineFunction &MF, const MachineInstr *MI);
1100 // Debugging support
1102 void print(raw_ostream &OS, bool SkipOpers = false) const;
1105 //===--------------------------------------------------------------------===//
1106 // Accessors used to build up machine instructions.
1108 /// Add the specified operand to the instruction. If it is an implicit
1109 /// operand, it is added to the end of the operand list. If it is an
1110 /// explicit operand it is added at the end of the explicit operand list
1111 /// (before the first implicit operand).
1113 /// MF must be the machine function that was used to allocate this
1116 /// MachineInstrBuilder provides a more convenient interface for creating
1117 /// instructions and adding operands.
1118 void addOperand(MachineFunction &MF, const MachineOperand &Op);
1120 /// Add an operand without providing an MF reference. This only works for
1121 /// instructions that are inserted in a basic block.
1123 /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1125 void addOperand(const MachineOperand &Op);
1127 /// Replace the instruction descriptor (thus opcode) of
1128 /// the current instruction with a new one.
1129 void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1131 /// Replace current source information with new such.
1132 /// Avoid using this, the constructor argument is preferable.
1133 void setDebugLoc(DebugLoc dl) {
1134 debugLoc = std::move(dl);
1135 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1138 /// Erase an operand from an instruction, leaving it with one
1139 /// fewer operand than it started with.
1140 void RemoveOperand(unsigned i);
1142 /// Add a MachineMemOperand to the machine instruction.
1143 /// This function should be used only occasionally. The setMemRefs function
1144 /// is the primary method for setting up a MachineInstr's MemRefs list.
1145 void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1147 /// Assign this MachineInstr's memory reference descriptor list.
1148 /// This does not transfer ownership.
1149 void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
1150 MemRefs = NewMemRefs;
1151 NumMemRefs = uint8_t(NewMemRefsEnd - NewMemRefs);
1152 assert(NumMemRefs == NewMemRefsEnd - NewMemRefs && "Too many memrefs");
1155 /// Clear this MachineInstr's memory reference descriptor list.
1156 void clearMemRefs() {
1161 /// Break any tie involving OpIdx.
1162 void untieRegOperand(unsigned OpIdx) {
1163 MachineOperand &MO = getOperand(OpIdx);
1164 if (MO.isReg() && MO.isTied()) {
1165 getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1172 /// If this instruction is embedded into a MachineFunction, return the
1173 /// MachineRegisterInfo object for the current function, otherwise
1175 MachineRegisterInfo *getRegInfo();
1177 /// Add all implicit def and use operands to this instruction.
1178 void addImplicitDefUseOperands(MachineFunction &MF);
1180 /// Unlink all of the register operands in this instruction from their
1181 /// respective use lists. This requires that the operands already be on their
1183 void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1185 /// Add all of the register operands in this instruction from their
1186 /// respective use lists. This requires that the operands not be on their
1188 void AddRegOperandsToUseLists(MachineRegisterInfo&);
1190 /// Slow path for hasProperty when we're dealing with a bundle.
1191 bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
1193 /// \brief Implements the logic of getRegClassConstraintEffectForVReg for the
1194 /// this MI and the given operand index \p OpIdx.
1195 /// If the related operand does not constrained Reg, this returns CurRC.
1196 const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1197 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1198 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1201 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1202 /// instruction rather than by pointer value.
1203 /// The hashing and equality testing functions ignore definitions so this is
1204 /// useful for CSE, etc.
1205 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1206 static inline MachineInstr *getEmptyKey() {
1210 static inline MachineInstr *getTombstoneKey() {
1211 return reinterpret_cast<MachineInstr*>(-1);
1214 static unsigned getHashValue(const MachineInstr* const &MI);
1216 static bool isEqual(const MachineInstr* const &LHS,
1217 const MachineInstr* const &RHS) {
1218 if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1219 LHS == getEmptyKey() || LHS == getTombstoneKey())
1221 return LHS->isIdenticalTo(RHS, MachineInstr::IgnoreVRegDefs);
1225 //===----------------------------------------------------------------------===//
1226 // Debugging Support
1228 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1233 } // End llvm namespace