]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/CodeGen/MachineInstr.h
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / CodeGen / MachineInstr.h
1 //===- llvm/CodeGen/MachineInstr.h - MachineInstr class ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the declaration of the MachineInstr class, which is the
11 // basic representation for all target dependent machine instructions used by
12 // the back end.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CODEGEN_MACHINEINSTR_H
17 #define LLVM_CODEGEN_MACHINEINSTR_H
18
19 #include "llvm/ADT/DenseMapInfo.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/MachineOperand.h"
25 #include "llvm/CodeGen/TargetOpcodes.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/Support/ArrayRecycler.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cstdint>
33 #include <utility>
34
35 namespace llvm {
36
37 template <typename T> class ArrayRef;
38 class DIExpression;
39 class DILocalVariable;
40 class MachineBasicBlock;
41 class MachineFunction;
42 class MachineMemOperand;
43 class MachineRegisterInfo;
44 class ModuleSlotTracker;
45 class raw_ostream;
46 template <typename T> class SmallVectorImpl;
47 class SmallBitVector;
48 class StringRef;
49 class TargetInstrInfo;
50 class TargetRegisterClass;
51 class TargetRegisterInfo;
52
53 //===----------------------------------------------------------------------===//
54 /// Representation of each machine instruction.
55 ///
56 /// This class isn't a POD type, but it must have a trivial destructor. When a
57 /// MachineFunction is deleted, all the contained MachineInstrs are deallocated
58 /// without having their destructor called.
59 ///
60 class MachineInstr
61     : public ilist_node_with_parent<MachineInstr, MachineBasicBlock,
62                                     ilist_sentinel_tracking<true>> {
63 public:
64   using mmo_iterator = MachineMemOperand **;
65
66   /// Flags to specify different kinds of comments to output in
67   /// assembly code.  These flags carry semantic information not
68   /// otherwise easily derivable from the IR text.
69   ///
70   enum CommentFlag {
71     ReloadReuse = 0x1,    // higher bits are reserved for target dep comments.
72     NoSchedComment = 0x2,
73     TAsmComments = 0x4    // Target Asm comments should start from this value.
74   };
75
76   enum MIFlag {
77     NoFlags      = 0,
78     FrameSetup   = 1 << 0,              // Instruction is used as a part of
79                                         // function frame setup code.
80     FrameDestroy = 1 << 1,              // Instruction is used as a part of
81                                         // function frame destruction code.
82     BundledPred  = 1 << 2,              // Instruction has bundled predecessors.
83     BundledSucc  = 1 << 3,              // Instruction has bundled successors.
84     FmNoNans     = 1 << 4,              // Instruction does not support Fast
85                                         // math nan values.
86     FmNoInfs     = 1 << 5,              // Instruction does not support Fast
87                                         // math infinity values.
88     FmNsz        = 1 << 6,              // Instruction is not required to retain
89                                         // signed zero values.
90     FmArcp       = 1 << 7,              // Instruction supports Fast math
91                                         // reciprocal approximations.
92     FmContract   = 1 << 8,              // Instruction supports Fast math
93                                         // contraction operations like fma.
94     FmAfn        = 1 << 9,              // Instruction may map to Fast math
95                                         // instrinsic approximation.
96     FmReassoc    = 1 << 10              // Instruction supports Fast math
97                                         // reassociation of operand order.
98   };
99
100 private:
101   const MCInstrDesc *MCID;              // Instruction descriptor.
102   MachineBasicBlock *Parent = nullptr;  // Pointer to the owning basic block.
103
104   // Operands are allocated by an ArrayRecycler.
105   MachineOperand *Operands = nullptr;   // Pointer to the first operand.
106   unsigned NumOperands = 0;             // Number of operands on instruction.
107   using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
108   OperandCapacity CapOperands;          // Capacity of the Operands array.
109
110   uint16_t Flags = 0;                   // Various bits of additional
111                                         // information about machine
112                                         // instruction.
113
114   uint8_t AsmPrinterFlags = 0;          // Various bits of information used by
115                                         // the AsmPrinter to emit helpful
116                                         // comments.  This is *not* semantic
117                                         // information.  Do not use this for
118                                         // anything other than to convey comment
119                                         // information to AsmPrinter.
120
121   uint8_t NumMemRefs = 0;               // Information on memory references.
122   // Note that MemRefs == nullptr,  means 'don't know', not 'no memory access'.
123   // Calling code must treat missing information conservatively.  If the number
124   // of memory operands required to be precise exceeds the maximum value of
125   // NumMemRefs - currently 256 - we remove the operands entirely. Note also
126   // that this is a non-owning reference to a shared copy on write buffer owned
127   // by the MachineFunction and created via MF.allocateMemRefsArray.
128   mmo_iterator MemRefs = nullptr;
129
130   DebugLoc debugLoc;                    // Source line information.
131
132   // Intrusive list support
133   friend struct ilist_traits<MachineInstr>;
134   friend struct ilist_callback_traits<MachineBasicBlock>;
135   void setParent(MachineBasicBlock *P) { Parent = P; }
136
137   /// This constructor creates a copy of the given
138   /// MachineInstr in the given MachineFunction.
139   MachineInstr(MachineFunction &, const MachineInstr &);
140
141   /// This constructor create a MachineInstr and add the implicit operands.
142   /// It reserves space for number of operands specified by
143   /// MCInstrDesc.  An explicit DebugLoc is supplied.
144   MachineInstr(MachineFunction &, const MCInstrDesc &tid, DebugLoc dl,
145                bool NoImp = false);
146
147   // MachineInstrs are pool-allocated and owned by MachineFunction.
148   friend class MachineFunction;
149
150 public:
151   MachineInstr(const MachineInstr &) = delete;
152   MachineInstr &operator=(const MachineInstr &) = delete;
153   // Use MachineFunction::DeleteMachineInstr() instead.
154   ~MachineInstr() = delete;
155
156   const MachineBasicBlock* getParent() const { return Parent; }
157   MachineBasicBlock* getParent() { return Parent; }
158
159   /// Return the function that contains the basic block that this instruction
160   /// belongs to.
161   ///
162   /// Note: this is undefined behaviour if the instruction does not have a
163   /// parent.
164   const MachineFunction *getMF() const;
165   MachineFunction *getMF() {
166     return const_cast<MachineFunction *>(
167         static_cast<const MachineInstr *>(this)->getMF());
168   }
169
170   /// Return the asm printer flags bitvector.
171   uint8_t getAsmPrinterFlags() const { return AsmPrinterFlags; }
172
173   /// Clear the AsmPrinter bitvector.
174   void clearAsmPrinterFlags() { AsmPrinterFlags = 0; }
175
176   /// Return whether an AsmPrinter flag is set.
177   bool getAsmPrinterFlag(CommentFlag Flag) const {
178     return AsmPrinterFlags & Flag;
179   }
180
181   /// Set a flag for the AsmPrinter.
182   void setAsmPrinterFlag(uint8_t Flag) {
183     AsmPrinterFlags |= Flag;
184   }
185
186   /// Clear specific AsmPrinter flags.
187   void clearAsmPrinterFlag(CommentFlag Flag) {
188     AsmPrinterFlags &= ~Flag;
189   }
190
191   /// Return the MI flags bitvector.
192   uint16_t getFlags() const {
193     return Flags;
194   }
195
196   /// Return whether an MI flag is set.
197   bool getFlag(MIFlag Flag) const {
198     return Flags & Flag;
199   }
200
201   /// Set a MI flag.
202   void setFlag(MIFlag Flag) {
203     Flags |= (uint16_t)Flag;
204   }
205
206   void setFlags(unsigned flags) {
207     // Filter out the automatically maintained flags.
208     unsigned Mask = BundledPred | BundledSucc;
209     Flags = (Flags & Mask) | (flags & ~Mask);
210   }
211
212   /// clearFlag - Clear a MI flag.
213   void clearFlag(MIFlag Flag) {
214     Flags &= ~((uint16_t)Flag);
215   }
216
217   /// Return true if MI is in a bundle (but not the first MI in a bundle).
218   ///
219   /// A bundle looks like this before it's finalized:
220   ///   ----------------
221   ///   |      MI      |
222   ///   ----------------
223   ///          |
224   ///   ----------------
225   ///   |      MI    * |
226   ///   ----------------
227   ///          |
228   ///   ----------------
229   ///   |      MI    * |
230   ///   ----------------
231   /// In this case, the first MI starts a bundle but is not inside a bundle, the
232   /// next 2 MIs are considered "inside" the bundle.
233   ///
234   /// After a bundle is finalized, it looks like this:
235   ///   ----------------
236   ///   |    Bundle    |
237   ///   ----------------
238   ///          |
239   ///   ----------------
240   ///   |      MI    * |
241   ///   ----------------
242   ///          |
243   ///   ----------------
244   ///   |      MI    * |
245   ///   ----------------
246   ///          |
247   ///   ----------------
248   ///   |      MI    * |
249   ///   ----------------
250   /// The first instruction has the special opcode "BUNDLE". It's not "inside"
251   /// a bundle, but the next three MIs are.
252   bool isInsideBundle() const {
253     return getFlag(BundledPred);
254   }
255
256   /// Return true if this instruction part of a bundle. This is true
257   /// if either itself or its following instruction is marked "InsideBundle".
258   bool isBundled() const {
259     return isBundledWithPred() || isBundledWithSucc();
260   }
261
262   /// Return true if this instruction is part of a bundle, and it is not the
263   /// first instruction in the bundle.
264   bool isBundledWithPred() const { return getFlag(BundledPred); }
265
266   /// Return true if this instruction is part of a bundle, and it is not the
267   /// last instruction in the bundle.
268   bool isBundledWithSucc() const { return getFlag(BundledSucc); }
269
270   /// Bundle this instruction with its predecessor. This can be an unbundled
271   /// instruction, or it can be the first instruction in a bundle.
272   void bundleWithPred();
273
274   /// Bundle this instruction with its successor. This can be an unbundled
275   /// instruction, or it can be the last instruction in a bundle.
276   void bundleWithSucc();
277
278   /// Break bundle above this instruction.
279   void unbundleFromPred();
280
281   /// Break bundle below this instruction.
282   void unbundleFromSucc();
283
284   /// Returns the debug location id of this MachineInstr.
285   const DebugLoc &getDebugLoc() const { return debugLoc; }
286
287   /// Return the debug variable referenced by
288   /// this DBG_VALUE instruction.
289   const DILocalVariable *getDebugVariable() const;
290
291   /// Return the complex address expression referenced by
292   /// this DBG_VALUE instruction.
293   const DIExpression *getDebugExpression() const;
294
295   /// Return the debug label referenced by
296   /// this DBG_LABEL instruction.
297   const DILabel *getDebugLabel() const;
298
299   /// Emit an error referring to the source location of this instruction.
300   /// This should only be used for inline assembly that is somehow
301   /// impossible to compile. Other errors should have been handled much
302   /// earlier.
303   ///
304   /// If this method returns, the caller should try to recover from the error.
305   void emitError(StringRef Msg) const;
306
307   /// Returns the target instruction descriptor of this MachineInstr.
308   const MCInstrDesc &getDesc() const { return *MCID; }
309
310   /// Returns the opcode of this MachineInstr.
311   unsigned getOpcode() const { return MCID->Opcode; }
312
313   /// Access to explicit operands of the instruction.
314   unsigned getNumOperands() const { return NumOperands; }
315
316   const MachineOperand& getOperand(unsigned i) const {
317     assert(i < getNumOperands() && "getOperand() out of range!");
318     return Operands[i];
319   }
320   MachineOperand& getOperand(unsigned i) {
321     assert(i < getNumOperands() && "getOperand() out of range!");
322     return Operands[i];
323   }
324
325   /// Returns the total number of definitions.
326   unsigned getNumDefs() const {
327     return getNumExplicitDefs() + MCID->getNumImplicitDefs();
328   }
329
330   /// Return true if operand \p OpIdx is a subregister index.
331   bool isOperandSubregIdx(unsigned OpIdx) const {
332     assert(getOperand(OpIdx).getType() == MachineOperand::MO_Immediate &&
333            "Expected MO_Immediate operand type.");
334     if (isExtractSubreg() && OpIdx == 2)
335       return true;
336     if (isInsertSubreg() && OpIdx == 3)
337       return true;
338     if (isRegSequence() && OpIdx > 1 && (OpIdx % 2) == 0)
339       return true;
340     if (isSubregToReg() && OpIdx == 3)
341       return true;
342     return false;
343   }
344
345   /// Returns the number of non-implicit operands.
346   unsigned getNumExplicitOperands() const;
347
348   /// Returns the number of non-implicit definitions.
349   unsigned getNumExplicitDefs() const;
350
351   /// iterator/begin/end - Iterate over all operands of a machine instruction.
352   using mop_iterator = MachineOperand *;
353   using const_mop_iterator = const MachineOperand *;
354
355   mop_iterator operands_begin() { return Operands; }
356   mop_iterator operands_end() { return Operands + NumOperands; }
357
358   const_mop_iterator operands_begin() const { return Operands; }
359   const_mop_iterator operands_end() const { return Operands + NumOperands; }
360
361   iterator_range<mop_iterator> operands() {
362     return make_range(operands_begin(), operands_end());
363   }
364   iterator_range<const_mop_iterator> operands() const {
365     return make_range(operands_begin(), operands_end());
366   }
367   iterator_range<mop_iterator> explicit_operands() {
368     return make_range(operands_begin(),
369                       operands_begin() + getNumExplicitOperands());
370   }
371   iterator_range<const_mop_iterator> explicit_operands() const {
372     return make_range(operands_begin(),
373                       operands_begin() + getNumExplicitOperands());
374   }
375   iterator_range<mop_iterator> implicit_operands() {
376     return make_range(explicit_operands().end(), operands_end());
377   }
378   iterator_range<const_mop_iterator> implicit_operands() const {
379     return make_range(explicit_operands().end(), operands_end());
380   }
381   /// Returns a range over all explicit operands that are register definitions.
382   /// Implicit definition are not included!
383   iterator_range<mop_iterator> defs() {
384     return make_range(operands_begin(),
385                       operands_begin() + getNumExplicitDefs());
386   }
387   /// \copydoc defs()
388   iterator_range<const_mop_iterator> defs() const {
389     return make_range(operands_begin(),
390                       operands_begin() + getNumExplicitDefs());
391   }
392   /// Returns a range that includes all operands that are register uses.
393   /// This may include unrelated operands which are not register uses.
394   iterator_range<mop_iterator> uses() {
395     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
396   }
397   /// \copydoc uses()
398   iterator_range<const_mop_iterator> uses() const {
399     return make_range(operands_begin() + getNumExplicitDefs(), operands_end());
400   }
401   iterator_range<mop_iterator> explicit_uses() {
402     return make_range(operands_begin() + getNumExplicitDefs(),
403                       operands_begin() + getNumExplicitOperands());
404   }
405   iterator_range<const_mop_iterator> explicit_uses() const {
406     return make_range(operands_begin() + getNumExplicitDefs(),
407                       operands_begin() + getNumExplicitOperands());
408   }
409
410   /// Returns the number of the operand iterator \p I points to.
411   unsigned getOperandNo(const_mop_iterator I) const {
412     return I - operands_begin();
413   }
414
415   /// Access to memory operands of the instruction
416   mmo_iterator memoperands_begin() const { return MemRefs; }
417   mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
418   /// Return true if we don't have any memory operands which described the
419   /// memory access done by this instruction.  If this is true, calling code
420   /// must be conservative.
421   bool memoperands_empty() const { return NumMemRefs == 0; }
422
423   iterator_range<mmo_iterator>  memoperands() {
424     return make_range(memoperands_begin(), memoperands_end());
425   }
426   iterator_range<mmo_iterator> memoperands() const {
427     return make_range(memoperands_begin(), memoperands_end());
428   }
429
430   /// Return true if this instruction has exactly one MachineMemOperand.
431   bool hasOneMemOperand() const {
432     return NumMemRefs == 1;
433   }
434
435   /// Return the number of memory operands.
436   unsigned getNumMemOperands() const { return NumMemRefs; }
437
438   /// API for querying MachineInstr properties. They are the same as MCInstrDesc
439   /// queries but they are bundle aware.
440
441   enum QueryType {
442     IgnoreBundle,    // Ignore bundles
443     AnyInBundle,     // Return true if any instruction in bundle has property
444     AllInBundle      // Return true if all instructions in bundle have property
445   };
446
447   /// Return true if the instruction (or in the case of a bundle,
448   /// the instructions inside the bundle) has the specified property.
449   /// The first argument is the property being queried.
450   /// The second argument indicates whether the query should look inside
451   /// instruction bundles.
452   bool hasProperty(unsigned MCFlag, QueryType Type = AnyInBundle) const {
453     // Inline the fast path for unbundled or bundle-internal instructions.
454     if (Type == IgnoreBundle || !isBundled() || isBundledWithPred())
455       return getDesc().getFlags() & (1ULL << MCFlag);
456
457     // If this is the first instruction in a bundle, take the slow path.
458     return hasPropertyInBundle(1ULL << MCFlag, Type);
459   }
460
461   /// Return true if this instruction can have a variable number of operands.
462   /// In this case, the variable operands will be after the normal
463   /// operands but before the implicit definitions and uses (if any are
464   /// present).
465   bool isVariadic(QueryType Type = IgnoreBundle) const {
466     return hasProperty(MCID::Variadic, Type);
467   }
468
469   /// Set if this instruction has an optional definition, e.g.
470   /// ARM instructions which can set condition code if 's' bit is set.
471   bool hasOptionalDef(QueryType Type = IgnoreBundle) const {
472     return hasProperty(MCID::HasOptionalDef, Type);
473   }
474
475   /// Return true if this is a pseudo instruction that doesn't
476   /// correspond to a real machine instruction.
477   bool isPseudo(QueryType Type = IgnoreBundle) const {
478     return hasProperty(MCID::Pseudo, Type);
479   }
480
481   bool isReturn(QueryType Type = AnyInBundle) const {
482     return hasProperty(MCID::Return, Type);
483   }
484
485   bool isCall(QueryType Type = AnyInBundle) const {
486     return hasProperty(MCID::Call, Type);
487   }
488
489   /// Returns true if the specified instruction stops control flow
490   /// from executing the instruction immediately following it.  Examples include
491   /// unconditional branches and return instructions.
492   bool isBarrier(QueryType Type = AnyInBundle) const {
493     return hasProperty(MCID::Barrier, Type);
494   }
495
496   /// Returns true if this instruction part of the terminator for a basic block.
497   /// Typically this is things like return and branch instructions.
498   ///
499   /// Various passes use this to insert code into the bottom of a basic block,
500   /// but before control flow occurs.
501   bool isTerminator(QueryType Type = AnyInBundle) const {
502     return hasProperty(MCID::Terminator, Type);
503   }
504
505   /// Returns true if this is a conditional, unconditional, or indirect branch.
506   /// Predicates below can be used to discriminate between
507   /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
508   /// get more information.
509   bool isBranch(QueryType Type = AnyInBundle) const {
510     return hasProperty(MCID::Branch, Type);
511   }
512
513   /// Return true if this is an indirect branch, such as a
514   /// branch through a register.
515   bool isIndirectBranch(QueryType Type = AnyInBundle) const {
516     return hasProperty(MCID::IndirectBranch, Type);
517   }
518
519   /// Return true if this is a branch which may fall
520   /// through to the next instruction or may transfer control flow to some other
521   /// block.  The TargetInstrInfo::AnalyzeBranch method can be used to get more
522   /// information about this branch.
523   bool isConditionalBranch(QueryType Type = AnyInBundle) const {
524     return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
525   }
526
527   /// Return true if this is a branch which always
528   /// transfers control flow to some other block.  The
529   /// TargetInstrInfo::AnalyzeBranch method can be used to get more information
530   /// about this branch.
531   bool isUnconditionalBranch(QueryType Type = AnyInBundle) const {
532     return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
533   }
534
535   /// Return true if this instruction has a predicate operand that
536   /// controls execution.  It may be set to 'always', or may be set to other
537   /// values.   There are various methods in TargetInstrInfo that can be used to
538   /// control and modify the predicate in this instruction.
539   bool isPredicable(QueryType Type = AllInBundle) const {
540     // If it's a bundle than all bundled instructions must be predicable for this
541     // to return true.
542     return hasProperty(MCID::Predicable, Type);
543   }
544
545   /// Return true if this instruction is a comparison.
546   bool isCompare(QueryType Type = IgnoreBundle) const {
547     return hasProperty(MCID::Compare, Type);
548   }
549
550   /// Return true if this instruction is a move immediate
551   /// (including conditional moves) instruction.
552   bool isMoveImmediate(QueryType Type = IgnoreBundle) const {
553     return hasProperty(MCID::MoveImm, Type);
554   }
555
556   /// Return true if this instruction is a register move.
557   /// (including moving values from subreg to reg)
558   bool isMoveReg(QueryType Type = IgnoreBundle) const {
559     return hasProperty(MCID::MoveReg, Type);
560   }
561
562   /// Return true if this instruction is a bitcast instruction.
563   bool isBitcast(QueryType Type = IgnoreBundle) const {
564     return hasProperty(MCID::Bitcast, Type);
565   }
566
567   /// Return true if this instruction is a select instruction.
568   bool isSelect(QueryType Type = IgnoreBundle) const {
569     return hasProperty(MCID::Select, Type);
570   }
571
572   /// Return true if this instruction cannot be safely duplicated.
573   /// For example, if the instruction has a unique labels attached
574   /// to it, duplicating it would cause multiple definition errors.
575   bool isNotDuplicable(QueryType Type = AnyInBundle) const {
576     return hasProperty(MCID::NotDuplicable, Type);
577   }
578
579   /// Return true if this instruction is convergent.
580   /// Convergent instructions can not be made control-dependent on any
581   /// additional values.
582   bool isConvergent(QueryType Type = AnyInBundle) const {
583     if (isInlineAsm()) {
584       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
585       if (ExtraInfo & InlineAsm::Extra_IsConvergent)
586         return true;
587     }
588     return hasProperty(MCID::Convergent, Type);
589   }
590
591   /// Returns true if the specified instruction has a delay slot
592   /// which must be filled by the code generator.
593   bool hasDelaySlot(QueryType Type = AnyInBundle) const {
594     return hasProperty(MCID::DelaySlot, Type);
595   }
596
597   /// Return true for instructions that can be folded as
598   /// memory operands in other instructions. The most common use for this
599   /// is instructions that are simple loads from memory that don't modify
600   /// the loaded value in any way, but it can also be used for instructions
601   /// that can be expressed as constant-pool loads, such as V_SETALLONES
602   /// on x86, to allow them to be folded when it is beneficial.
603   /// This should only be set on instructions that return a value in their
604   /// only virtual register definition.
605   bool canFoldAsLoad(QueryType Type = IgnoreBundle) const {
606     return hasProperty(MCID::FoldableAsLoad, Type);
607   }
608
609   /// Return true if this instruction behaves
610   /// the same way as the generic REG_SEQUENCE instructions.
611   /// E.g., on ARM,
612   /// dX VMOVDRR rY, rZ
613   /// is equivalent to
614   /// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
615   ///
616   /// Note that for the optimizers to be able to take advantage of
617   /// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
618   /// override accordingly.
619   bool isRegSequenceLike(QueryType Type = IgnoreBundle) const {
620     return hasProperty(MCID::RegSequence, Type);
621   }
622
623   /// Return true if this instruction behaves
624   /// the same way as the generic EXTRACT_SUBREG instructions.
625   /// E.g., on ARM,
626   /// rX, rY VMOVRRD dZ
627   /// is equivalent to two EXTRACT_SUBREG:
628   /// rX = EXTRACT_SUBREG dZ, ssub_0
629   /// rY = EXTRACT_SUBREG dZ, ssub_1
630   ///
631   /// Note that for the optimizers to be able to take advantage of
632   /// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
633   /// override accordingly.
634   bool isExtractSubregLike(QueryType Type = IgnoreBundle) const {
635     return hasProperty(MCID::ExtractSubreg, Type);
636   }
637
638   /// Return true if this instruction behaves
639   /// the same way as the generic INSERT_SUBREG instructions.
640   /// E.g., on ARM,
641   /// dX = VSETLNi32 dY, rZ, Imm
642   /// is equivalent to a INSERT_SUBREG:
643   /// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
644   ///
645   /// Note that for the optimizers to be able to take advantage of
646   /// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
647   /// override accordingly.
648   bool isInsertSubregLike(QueryType Type = IgnoreBundle) const {
649     return hasProperty(MCID::InsertSubreg, Type);
650   }
651
652   //===--------------------------------------------------------------------===//
653   // Side Effect Analysis
654   //===--------------------------------------------------------------------===//
655
656   /// Return true if this instruction could possibly read memory.
657   /// Instructions with this flag set are not necessarily simple load
658   /// instructions, they may load a value and modify it, for example.
659   bool mayLoad(QueryType Type = AnyInBundle) const {
660     if (isInlineAsm()) {
661       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
662       if (ExtraInfo & InlineAsm::Extra_MayLoad)
663         return true;
664     }
665     return hasProperty(MCID::MayLoad, Type);
666   }
667
668   /// Return true if this instruction could possibly modify memory.
669   /// Instructions with this flag set are not necessarily simple store
670   /// instructions, they may store a modified value based on their operands, or
671   /// may not actually modify anything, for example.
672   bool mayStore(QueryType Type = AnyInBundle) const {
673     if (isInlineAsm()) {
674       unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
675       if (ExtraInfo & InlineAsm::Extra_MayStore)
676         return true;
677     }
678     return hasProperty(MCID::MayStore, Type);
679   }
680
681   /// Return true if this instruction could possibly read or modify memory.
682   bool mayLoadOrStore(QueryType Type = AnyInBundle) const {
683     return mayLoad(Type) || mayStore(Type);
684   }
685
686   //===--------------------------------------------------------------------===//
687   // Flags that indicate whether an instruction can be modified by a method.
688   //===--------------------------------------------------------------------===//
689
690   /// Return true if this may be a 2- or 3-address
691   /// instruction (of the form "X = op Y, Z, ..."), which produces the same
692   /// result if Y and Z are exchanged.  If this flag is set, then the
693   /// TargetInstrInfo::commuteInstruction method may be used to hack on the
694   /// instruction.
695   ///
696   /// Note that this flag may be set on instructions that are only commutable
697   /// sometimes.  In these cases, the call to commuteInstruction will fail.
698   /// Also note that some instructions require non-trivial modification to
699   /// commute them.
700   bool isCommutable(QueryType Type = IgnoreBundle) const {
701     return hasProperty(MCID::Commutable, Type);
702   }
703
704   /// Return true if this is a 2-address instruction
705   /// which can be changed into a 3-address instruction if needed.  Doing this
706   /// transformation can be profitable in the register allocator, because it
707   /// means that the instruction can use a 2-address form if possible, but
708   /// degrade into a less efficient form if the source and dest register cannot
709   /// be assigned to the same register.  For example, this allows the x86
710   /// backend to turn a "shl reg, 3" instruction into an LEA instruction, which
711   /// is the same speed as the shift but has bigger code size.
712   ///
713   /// If this returns true, then the target must implement the
714   /// TargetInstrInfo::convertToThreeAddress method for this instruction, which
715   /// is allowed to fail if the transformation isn't valid for this specific
716   /// instruction (e.g. shl reg, 4 on x86).
717   ///
718   bool isConvertibleTo3Addr(QueryType Type = IgnoreBundle) const {
719     return hasProperty(MCID::ConvertibleTo3Addr, Type);
720   }
721
722   /// Return true if this instruction requires
723   /// custom insertion support when the DAG scheduler is inserting it into a
724   /// machine basic block.  If this is true for the instruction, it basically
725   /// means that it is a pseudo instruction used at SelectionDAG time that is
726   /// expanded out into magic code by the target when MachineInstrs are formed.
727   ///
728   /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
729   /// is used to insert this into the MachineBasicBlock.
730   bool usesCustomInsertionHook(QueryType Type = IgnoreBundle) const {
731     return hasProperty(MCID::UsesCustomInserter, Type);
732   }
733
734   /// Return true if this instruction requires *adjustment*
735   /// after instruction selection by calling a target hook. For example, this
736   /// can be used to fill in ARM 's' optional operand depending on whether
737   /// the conditional flag register is used.
738   bool hasPostISelHook(QueryType Type = IgnoreBundle) const {
739     return hasProperty(MCID::HasPostISelHook, Type);
740   }
741
742   /// Returns true if this instruction is a candidate for remat.
743   /// This flag is deprecated, please don't use it anymore.  If this
744   /// flag is set, the isReallyTriviallyReMaterializable() method is called to
745   /// verify the instruction is really rematable.
746   bool isRematerializable(QueryType Type = AllInBundle) const {
747     // It's only possible to re-mat a bundle if all bundled instructions are
748     // re-materializable.
749     return hasProperty(MCID::Rematerializable, Type);
750   }
751
752   /// Returns true if this instruction has the same cost (or less) than a move
753   /// instruction. This is useful during certain types of optimizations
754   /// (e.g., remat during two-address conversion or machine licm)
755   /// where we would like to remat or hoist the instruction, but not if it costs
756   /// more than moving the instruction into the appropriate register. Note, we
757   /// are not marking copies from and to the same register class with this flag.
758   bool isAsCheapAsAMove(QueryType Type = AllInBundle) const {
759     // Only returns true for a bundle if all bundled instructions are cheap.
760     return hasProperty(MCID::CheapAsAMove, Type);
761   }
762
763   /// Returns true if this instruction source operands
764   /// have special register allocation requirements that are not captured by the
765   /// operand register classes. e.g. ARM::STRD's two source registers must be an
766   /// even / odd pair, ARM::STM registers have to be in ascending order.
767   /// Post-register allocation passes should not attempt to change allocations
768   /// for sources of instructions with this flag.
769   bool hasExtraSrcRegAllocReq(QueryType Type = AnyInBundle) const {
770     return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
771   }
772
773   /// Returns true if this instruction def operands
774   /// have special register allocation requirements that are not captured by the
775   /// operand register classes. e.g. ARM::LDRD's two def registers must be an
776   /// even / odd pair, ARM::LDM registers have to be in ascending order.
777   /// Post-register allocation passes should not attempt to change allocations
778   /// for definitions of instructions with this flag.
779   bool hasExtraDefRegAllocReq(QueryType Type = AnyInBundle) const {
780     return hasProperty(MCID::ExtraDefRegAllocReq, Type);
781   }
782
783   enum MICheckType {
784     CheckDefs,      // Check all operands for equality
785     CheckKillDead,  // Check all operands including kill / dead markers
786     IgnoreDefs,     // Ignore all definitions
787     IgnoreVRegDefs  // Ignore virtual register definitions
788   };
789
790   /// Return true if this instruction is identical to \p Other.
791   /// Two instructions are identical if they have the same opcode and all their
792   /// operands are identical (with respect to MachineOperand::isIdenticalTo()).
793   /// Note that this means liveness related flags (dead, undef, kill) do not
794   /// affect the notion of identical.
795   bool isIdenticalTo(const MachineInstr &Other,
796                      MICheckType Check = CheckDefs) const;
797
798   /// Unlink 'this' from the containing basic block, and return it without
799   /// deleting it.
800   ///
801   /// This function can not be used on bundled instructions, use
802   /// removeFromBundle() to remove individual instructions from a bundle.
803   MachineInstr *removeFromParent();
804
805   /// Unlink this instruction from its basic block and return it without
806   /// deleting it.
807   ///
808   /// If the instruction is part of a bundle, the other instructions in the
809   /// bundle remain bundled.
810   MachineInstr *removeFromBundle();
811
812   /// Unlink 'this' from the containing basic block and delete it.
813   ///
814   /// If this instruction is the header of a bundle, the whole bundle is erased.
815   /// This function can not be used for instructions inside a bundle, use
816   /// eraseFromBundle() to erase individual bundled instructions.
817   void eraseFromParent();
818
819   /// Unlink 'this' from the containing basic block and delete it.
820   ///
821   /// For all definitions mark their uses in DBG_VALUE nodes
822   /// as undefined. Otherwise like eraseFromParent().
823   void eraseFromParentAndMarkDBGValuesForRemoval();
824
825   /// Unlink 'this' form its basic block and delete it.
826   ///
827   /// If the instruction is part of a bundle, the other instructions in the
828   /// bundle remain bundled.
829   void eraseFromBundle();
830
831   bool isEHLabel() const { return getOpcode() == TargetOpcode::EH_LABEL; }
832   bool isGCLabel() const { return getOpcode() == TargetOpcode::GC_LABEL; }
833   bool isAnnotationLabel() const {
834     return getOpcode() == TargetOpcode::ANNOTATION_LABEL;
835   }
836
837   /// Returns true if the MachineInstr represents a label.
838   bool isLabel() const {
839     return isEHLabel() || isGCLabel() || isAnnotationLabel();
840   }
841
842   bool isCFIInstruction() const {
843     return getOpcode() == TargetOpcode::CFI_INSTRUCTION;
844   }
845
846   // True if the instruction represents a position in the function.
847   bool isPosition() const { return isLabel() || isCFIInstruction(); }
848
849   bool isDebugValue() const { return getOpcode() == TargetOpcode::DBG_VALUE; }
850   bool isDebugLabel() const { return getOpcode() == TargetOpcode::DBG_LABEL; }
851   bool isDebugInstr() const { return isDebugValue() || isDebugLabel(); }
852
853   /// A DBG_VALUE is indirect iff the first operand is a register and
854   /// the second operand is an immediate.
855   bool isIndirectDebugValue() const {
856     return isDebugValue()
857       && getOperand(0).isReg()
858       && getOperand(1).isImm();
859   }
860
861   bool isPHI() const {
862     return getOpcode() == TargetOpcode::PHI ||
863            getOpcode() == TargetOpcode::G_PHI;
864   }
865   bool isKill() const { return getOpcode() == TargetOpcode::KILL; }
866   bool isImplicitDef() const { return getOpcode()==TargetOpcode::IMPLICIT_DEF; }
867   bool isInlineAsm() const { return getOpcode() == TargetOpcode::INLINEASM; }
868
869   bool isMSInlineAsm() const {
870     return getOpcode() == TargetOpcode::INLINEASM && getInlineAsmDialect();
871   }
872
873   bool isStackAligningInlineAsm() const;
874   InlineAsm::AsmDialect getInlineAsmDialect() const;
875
876   bool isInsertSubreg() const {
877     return getOpcode() == TargetOpcode::INSERT_SUBREG;
878   }
879
880   bool isSubregToReg() const {
881     return getOpcode() == TargetOpcode::SUBREG_TO_REG;
882   }
883
884   bool isRegSequence() const {
885     return getOpcode() == TargetOpcode::REG_SEQUENCE;
886   }
887
888   bool isBundle() const {
889     return getOpcode() == TargetOpcode::BUNDLE;
890   }
891
892   bool isCopy() const {
893     return getOpcode() == TargetOpcode::COPY;
894   }
895
896   bool isFullCopy() const {
897     return isCopy() && !getOperand(0).getSubReg() && !getOperand(1).getSubReg();
898   }
899
900   bool isExtractSubreg() const {
901     return getOpcode() == TargetOpcode::EXTRACT_SUBREG;
902   }
903
904   /// Return true if the instruction behaves like a copy.
905   /// This does not include native copy instructions.
906   bool isCopyLike() const {
907     return isCopy() || isSubregToReg();
908   }
909
910   /// Return true is the instruction is an identity copy.
911   bool isIdentityCopy() const {
912     return isCopy() && getOperand(0).getReg() == getOperand(1).getReg() &&
913       getOperand(0).getSubReg() == getOperand(1).getSubReg();
914   }
915
916   /// Return true if this instruction doesn't produce any output in the form of
917   /// executable instructions.
918   bool isMetaInstruction() const {
919     switch (getOpcode()) {
920     default:
921       return false;
922     case TargetOpcode::IMPLICIT_DEF:
923     case TargetOpcode::KILL:
924     case TargetOpcode::CFI_INSTRUCTION:
925     case TargetOpcode::EH_LABEL:
926     case TargetOpcode::GC_LABEL:
927     case TargetOpcode::DBG_VALUE:
928     case TargetOpcode::DBG_LABEL:
929     case TargetOpcode::LIFETIME_START:
930     case TargetOpcode::LIFETIME_END:
931       return true;
932     }
933   }
934
935   /// Return true if this is a transient instruction that is either very likely
936   /// to be eliminated during register allocation (such as copy-like
937   /// instructions), or if this instruction doesn't have an execution-time cost.
938   bool isTransient() const {
939     switch (getOpcode()) {
940     default:
941       return isMetaInstruction();
942     // Copy-like instructions are usually eliminated during register allocation.
943     case TargetOpcode::PHI:
944     case TargetOpcode::G_PHI:
945     case TargetOpcode::COPY:
946     case TargetOpcode::INSERT_SUBREG:
947     case TargetOpcode::SUBREG_TO_REG:
948     case TargetOpcode::REG_SEQUENCE:
949       return true;
950     }
951   }
952
953   /// Return the number of instructions inside the MI bundle, excluding the
954   /// bundle header.
955   ///
956   /// This is the number of instructions that MachineBasicBlock::iterator
957   /// skips, 0 for unbundled instructions.
958   unsigned getBundleSize() const;
959
960   /// Return true if the MachineInstr reads the specified register.
961   /// If TargetRegisterInfo is passed, then it also checks if there
962   /// is a read of a super-register.
963   /// This does not count partial redefines of virtual registers as reads:
964   ///   %reg1024:6 = OP.
965   bool readsRegister(unsigned Reg,
966                      const TargetRegisterInfo *TRI = nullptr) const {
967     return findRegisterUseOperandIdx(Reg, false, TRI) != -1;
968   }
969
970   /// Return true if the MachineInstr reads the specified virtual register.
971   /// Take into account that a partial define is a
972   /// read-modify-write operation.
973   bool readsVirtualRegister(unsigned Reg) const {
974     return readsWritesVirtualRegister(Reg).first;
975   }
976
977   /// Return a pair of bools (reads, writes) indicating if this instruction
978   /// reads or writes Reg. This also considers partial defines.
979   /// If Ops is not null, all operand indices for Reg are added.
980   std::pair<bool,bool> readsWritesVirtualRegister(unsigned Reg,
981                                 SmallVectorImpl<unsigned> *Ops = nullptr) const;
982
983   /// Return true if the MachineInstr kills the specified register.
984   /// If TargetRegisterInfo is passed, then it also checks if there is
985   /// a kill of a super-register.
986   bool killsRegister(unsigned Reg,
987                      const TargetRegisterInfo *TRI = nullptr) const {
988     return findRegisterUseOperandIdx(Reg, true, TRI) != -1;
989   }
990
991   /// Return true if the MachineInstr fully defines the specified register.
992   /// If TargetRegisterInfo is passed, then it also checks
993   /// if there is a def of a super-register.
994   /// NOTE: It's ignoring subreg indices on virtual registers.
995   bool definesRegister(unsigned Reg,
996                        const TargetRegisterInfo *TRI = nullptr) const {
997     return findRegisterDefOperandIdx(Reg, false, false, TRI) != -1;
998   }
999
1000   /// Return true if the MachineInstr modifies (fully define or partially
1001   /// define) the specified register.
1002   /// NOTE: It's ignoring subreg indices on virtual registers.
1003   bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const {
1004     return findRegisterDefOperandIdx(Reg, false, true, TRI) != -1;
1005   }
1006
1007   /// Returns true if the register is dead in this machine instruction.
1008   /// If TargetRegisterInfo is passed, then it also checks
1009   /// if there is a dead def of a super-register.
1010   bool registerDefIsDead(unsigned Reg,
1011                          const TargetRegisterInfo *TRI = nullptr) const {
1012     return findRegisterDefOperandIdx(Reg, true, false, TRI) != -1;
1013   }
1014
1015   /// Returns true if the MachineInstr has an implicit-use operand of exactly
1016   /// the given register (not considering sub/super-registers).
1017   bool hasRegisterImplicitUseOperand(unsigned Reg) const;
1018
1019   /// Returns the operand index that is a use of the specific register or -1
1020   /// if it is not found. It further tightens the search criteria to a use
1021   /// that kills the register if isKill is true.
1022   int findRegisterUseOperandIdx(unsigned Reg, bool isKill = false,
1023                                 const TargetRegisterInfo *TRI = nullptr) const;
1024
1025   /// Wrapper for findRegisterUseOperandIdx, it returns
1026   /// a pointer to the MachineOperand rather than an index.
1027   MachineOperand *findRegisterUseOperand(unsigned Reg, bool isKill = false,
1028                                       const TargetRegisterInfo *TRI = nullptr) {
1029     int Idx = findRegisterUseOperandIdx(Reg, isKill, TRI);
1030     return (Idx == -1) ? nullptr : &getOperand(Idx);
1031   }
1032
1033   const MachineOperand *findRegisterUseOperand(
1034     unsigned Reg, bool isKill = false,
1035     const TargetRegisterInfo *TRI = nullptr) const {
1036     return const_cast<MachineInstr *>(this)->
1037       findRegisterUseOperand(Reg, isKill, TRI);
1038   }
1039
1040   /// Returns the operand index that is a def of the specified register or
1041   /// -1 if it is not found. If isDead is true, defs that are not dead are
1042   /// skipped. If Overlap is true, then it also looks for defs that merely
1043   /// overlap the specified register. If TargetRegisterInfo is non-null,
1044   /// then it also checks if there is a def of a super-register.
1045   /// This may also return a register mask operand when Overlap is true.
1046   int findRegisterDefOperandIdx(unsigned Reg,
1047                                 bool isDead = false, bool Overlap = false,
1048                                 const TargetRegisterInfo *TRI = nullptr) const;
1049
1050   /// Wrapper for findRegisterDefOperandIdx, it returns
1051   /// a pointer to the MachineOperand rather than an index.
1052   MachineOperand *findRegisterDefOperand(unsigned Reg, bool isDead = false,
1053                                       const TargetRegisterInfo *TRI = nullptr) {
1054     int Idx = findRegisterDefOperandIdx(Reg, isDead, false, TRI);
1055     return (Idx == -1) ? nullptr : &getOperand(Idx);
1056   }
1057
1058   /// Find the index of the first operand in the
1059   /// operand list that is used to represent the predicate. It returns -1 if
1060   /// none is found.
1061   int findFirstPredOperandIdx() const;
1062
1063   /// Find the index of the flag word operand that
1064   /// corresponds to operand OpIdx on an inline asm instruction.  Returns -1 if
1065   /// getOperand(OpIdx) does not belong to an inline asm operand group.
1066   ///
1067   /// If GroupNo is not NULL, it will receive the number of the operand group
1068   /// containing OpIdx.
1069   ///
1070   /// The flag operand is an immediate that can be decoded with methods like
1071   /// InlineAsm::hasRegClassConstraint().
1072   int findInlineAsmFlagIdx(unsigned OpIdx, unsigned *GroupNo = nullptr) const;
1073
1074   /// Compute the static register class constraint for operand OpIdx.
1075   /// For normal instructions, this is derived from the MCInstrDesc.
1076   /// For inline assembly it is derived from the flag words.
1077   ///
1078   /// Returns NULL if the static register class constraint cannot be
1079   /// determined.
1080   const TargetRegisterClass*
1081   getRegClassConstraint(unsigned OpIdx,
1082                         const TargetInstrInfo *TII,
1083                         const TargetRegisterInfo *TRI) const;
1084
1085   /// Applies the constraints (def/use) implied by this MI on \p Reg to
1086   /// the given \p CurRC.
1087   /// If \p ExploreBundle is set and MI is part of a bundle, all the
1088   /// instructions inside the bundle will be taken into account. In other words,
1089   /// this method accumulates all the constraints of the operand of this MI and
1090   /// the related bundle if MI is a bundle or inside a bundle.
1091   ///
1092   /// Returns the register class that satisfies both \p CurRC and the
1093   /// constraints set by MI. Returns NULL if such a register class does not
1094   /// exist.
1095   ///
1096   /// \pre CurRC must not be NULL.
1097   const TargetRegisterClass *getRegClassConstraintEffectForVReg(
1098       unsigned Reg, const TargetRegisterClass *CurRC,
1099       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1100       bool ExploreBundle = false) const;
1101
1102   /// Applies the constraints (def/use) implied by the \p OpIdx operand
1103   /// to the given \p CurRC.
1104   ///
1105   /// Returns the register class that satisfies both \p CurRC and the
1106   /// constraints set by \p OpIdx MI. Returns NULL if such a register class
1107   /// does not exist.
1108   ///
1109   /// \pre CurRC must not be NULL.
1110   /// \pre The operand at \p OpIdx must be a register.
1111   const TargetRegisterClass *
1112   getRegClassConstraintEffect(unsigned OpIdx, const TargetRegisterClass *CurRC,
1113                               const TargetInstrInfo *TII,
1114                               const TargetRegisterInfo *TRI) const;
1115
1116   /// Add a tie between the register operands at DefIdx and UseIdx.
1117   /// The tie will cause the register allocator to ensure that the two
1118   /// operands are assigned the same physical register.
1119   ///
1120   /// Tied operands are managed automatically for explicit operands in the
1121   /// MCInstrDesc. This method is for exceptional cases like inline asm.
1122   void tieOperands(unsigned DefIdx, unsigned UseIdx);
1123
1124   /// Given the index of a tied register operand, find the
1125   /// operand it is tied to. Defs are tied to uses and vice versa. Returns the
1126   /// index of the tied operand which must exist.
1127   unsigned findTiedOperandIdx(unsigned OpIdx) const;
1128
1129   /// Given the index of a register def operand,
1130   /// check if the register def is tied to a source operand, due to either
1131   /// two-address elimination or inline assembly constraints. Returns the
1132   /// first tied use operand index by reference if UseOpIdx is not null.
1133   bool isRegTiedToUseOperand(unsigned DefOpIdx,
1134                              unsigned *UseOpIdx = nullptr) const {
1135     const MachineOperand &MO = getOperand(DefOpIdx);
1136     if (!MO.isReg() || !MO.isDef() || !MO.isTied())
1137       return false;
1138     if (UseOpIdx)
1139       *UseOpIdx = findTiedOperandIdx(DefOpIdx);
1140     return true;
1141   }
1142
1143   /// Return true if the use operand of the specified index is tied to a def
1144   /// operand. It also returns the def operand index by reference if DefOpIdx
1145   /// is not null.
1146   bool isRegTiedToDefOperand(unsigned UseOpIdx,
1147                              unsigned *DefOpIdx = nullptr) const {
1148     const MachineOperand &MO = getOperand(UseOpIdx);
1149     if (!MO.isReg() || !MO.isUse() || !MO.isTied())
1150       return false;
1151     if (DefOpIdx)
1152       *DefOpIdx = findTiedOperandIdx(UseOpIdx);
1153     return true;
1154   }
1155
1156   /// Clears kill flags on all operands.
1157   void clearKillInfo();
1158
1159   /// Replace all occurrences of FromReg with ToReg:SubIdx,
1160   /// properly composing subreg indices where necessary.
1161   void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx,
1162                           const TargetRegisterInfo &RegInfo);
1163
1164   /// We have determined MI kills a register. Look for the
1165   /// operand that uses it and mark it as IsKill. If AddIfNotFound is true,
1166   /// add a implicit operand if it's not found. Returns true if the operand
1167   /// exists / is added.
1168   bool addRegisterKilled(unsigned IncomingReg,
1169                          const TargetRegisterInfo *RegInfo,
1170                          bool AddIfNotFound = false);
1171
1172   /// Clear all kill flags affecting Reg.  If RegInfo is provided, this includes
1173   /// all aliasing registers.
1174   void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
1175
1176   /// We have determined MI defined a register without a use.
1177   /// Look for the operand that defines it and mark it as IsDead. If
1178   /// AddIfNotFound is true, add a implicit operand if it's not found. Returns
1179   /// true if the operand exists / is added.
1180   bool addRegisterDead(unsigned Reg, const TargetRegisterInfo *RegInfo,
1181                        bool AddIfNotFound = false);
1182
1183   /// Clear all dead flags on operands defining register @p Reg.
1184   void clearRegisterDeads(unsigned Reg);
1185
1186   /// Mark all subregister defs of register @p Reg with the undef flag.
1187   /// This function is used when we determined to have a subregister def in an
1188   /// otherwise undefined super register.
1189   void setRegisterDefReadUndef(unsigned Reg, bool IsUndef = true);
1190
1191   /// We have determined MI defines a register. Make sure there is an operand
1192   /// defining Reg.
1193   void addRegisterDefined(unsigned Reg,
1194                           const TargetRegisterInfo *RegInfo = nullptr);
1195
1196   /// Mark every physreg used by this instruction as
1197   /// dead except those in the UsedRegs list.
1198   ///
1199   /// On instructions with register mask operands, also add implicit-def
1200   /// operands for all registers in UsedRegs.
1201   void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
1202                              const TargetRegisterInfo &TRI);
1203
1204   /// Return true if it is safe to move this instruction. If
1205   /// SawStore is set to true, it means that there is a store (or call) between
1206   /// the instruction's location and its intended destination.
1207   bool isSafeToMove(AliasAnalysis *AA, bool &SawStore) const;
1208
1209   /// Returns true if this instruction's memory access aliases the memory
1210   /// access of Other.
1211   //
1212   /// Assumes any physical registers used to compute addresses
1213   /// have the same value for both instructions.  Returns false if neither
1214   /// instruction writes to memory.
1215   ///
1216   /// @param AA Optional alias analysis, used to compare memory operands.
1217   /// @param Other MachineInstr to check aliasing against.
1218   /// @param UseTBAA Whether to pass TBAA information to alias analysis.
1219   bool mayAlias(AliasAnalysis *AA, MachineInstr &Other, bool UseTBAA);
1220
1221   /// Return true if this instruction may have an ordered
1222   /// or volatile memory reference, or if the information describing the memory
1223   /// reference is not available. Return false if it is known to have no
1224   /// ordered or volatile memory references.
1225   bool hasOrderedMemoryRef() const;
1226
1227   /// Return true if this load instruction never traps and points to a memory
1228   /// location whose value doesn't change during the execution of this function.
1229   ///
1230   /// Examples include loading a value from the constant pool or from the
1231   /// argument area of a function (if it does not change).  If the instruction
1232   /// does multiple loads, this returns true only if all of the loads are
1233   /// dereferenceable and invariant.
1234   bool isDereferenceableInvariantLoad(AliasAnalysis *AA) const;
1235
1236   /// If the specified instruction is a PHI that always merges together the
1237   /// same virtual register, return the register, otherwise return 0.
1238   unsigned isConstantValuePHI() const;
1239
1240   /// Return true if this instruction has side effects that are not modeled
1241   /// by mayLoad / mayStore, etc.
1242   /// For all instructions, the property is encoded in MCInstrDesc::Flags
1243   /// (see MCInstrDesc::hasUnmodeledSideEffects(). The only exception is
1244   /// INLINEASM instruction, in which case the side effect property is encoded
1245   /// in one of its operands (see InlineAsm::Extra_HasSideEffect).
1246   ///
1247   bool hasUnmodeledSideEffects() const;
1248
1249   /// Returns true if it is illegal to fold a load across this instruction.
1250   bool isLoadFoldBarrier() const;
1251
1252   /// Return true if all the defs of this instruction are dead.
1253   bool allDefsAreDead() const;
1254
1255   /// Copy implicit register operands from specified
1256   /// instruction to this instruction.
1257   void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI);
1258
1259   /// Debugging support
1260   /// @{
1261   /// Determine the generic type to be printed (if needed) on uses and defs.
1262   LLT getTypeToPrint(unsigned OpIdx, SmallBitVector &PrintedTypes,
1263                      const MachineRegisterInfo &MRI) const;
1264
1265   /// Return true when an instruction has tied register that can't be determined
1266   /// by the instruction's descriptor. This is useful for MIR printing, to
1267   /// determine whether we need to print the ties or not.
1268   bool hasComplexRegisterTies() const;
1269
1270   /// Print this MI to \p OS.
1271   /// Don't print information that can be inferred from other instructions if
1272   /// \p IsStandalone is false. It is usually true when only a fragment of the
1273   /// function is printed.
1274   /// Only print the defs and the opcode if \p SkipOpers is true.
1275   /// Otherwise, also print operands if \p SkipDebugLoc is true.
1276   /// Otherwise, also print the debug loc, with a terminating newline.
1277   /// \p TII is used to print the opcode name.  If it's not present, but the
1278   /// MI is in a function, the opcode will be printed using the function's TII.
1279   void print(raw_ostream &OS, bool IsStandalone = true, bool SkipOpers = false,
1280              bool SkipDebugLoc = false, bool AddNewLine = true,
1281              const TargetInstrInfo *TII = nullptr) const;
1282   void print(raw_ostream &OS, ModuleSlotTracker &MST, bool IsStandalone = true,
1283              bool SkipOpers = false, bool SkipDebugLoc = false,
1284              bool AddNewLine = true,
1285              const TargetInstrInfo *TII = nullptr) const;
1286   void dump() const;
1287   /// @}
1288
1289   //===--------------------------------------------------------------------===//
1290   // Accessors used to build up machine instructions.
1291
1292   /// Add the specified operand to the instruction.  If it is an implicit
1293   /// operand, it is added to the end of the operand list.  If it is an
1294   /// explicit operand it is added at the end of the explicit operand list
1295   /// (before the first implicit operand).
1296   ///
1297   /// MF must be the machine function that was used to allocate this
1298   /// instruction.
1299   ///
1300   /// MachineInstrBuilder provides a more convenient interface for creating
1301   /// instructions and adding operands.
1302   void addOperand(MachineFunction &MF, const MachineOperand &Op);
1303
1304   /// Add an operand without providing an MF reference. This only works for
1305   /// instructions that are inserted in a basic block.
1306   ///
1307   /// MachineInstrBuilder and the two-argument addOperand(MF, MO) should be
1308   /// preferred.
1309   void addOperand(const MachineOperand &Op);
1310
1311   /// Replace the instruction descriptor (thus opcode) of
1312   /// the current instruction with a new one.
1313   void setDesc(const MCInstrDesc &tid) { MCID = &tid; }
1314
1315   /// Replace current source information with new such.
1316   /// Avoid using this, the constructor argument is preferable.
1317   void setDebugLoc(DebugLoc dl) {
1318     debugLoc = std::move(dl);
1319     assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
1320   }
1321
1322   /// Erase an operand from an instruction, leaving it with one
1323   /// fewer operand than it started with.
1324   void RemoveOperand(unsigned OpNo);
1325
1326   /// Add a MachineMemOperand to the machine instruction.
1327   /// This function should be used only occasionally. The setMemRefs function
1328   /// is the primary method for setting up a MachineInstr's MemRefs list.
1329   void addMemOperand(MachineFunction &MF, MachineMemOperand *MO);
1330
1331   /// Assign this MachineInstr's memory reference descriptor list.
1332   /// This does not transfer ownership.
1333   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
1334     setMemRefs(std::make_pair(NewMemRefs, NewMemRefsEnd-NewMemRefs));
1335   }
1336
1337   /// Assign this MachineInstr's memory reference descriptor list.  First
1338   /// element in the pair is the begin iterator/pointer to the array; the
1339   /// second is the number of MemoryOperands.  This does not transfer ownership
1340   /// of the underlying memory.
1341   void setMemRefs(std::pair<mmo_iterator, unsigned> NewMemRefs) {
1342     MemRefs = NewMemRefs.first;
1343     NumMemRefs = uint8_t(NewMemRefs.second);
1344     assert(NumMemRefs == NewMemRefs.second &&
1345            "Too many memrefs - must drop memory operands");
1346   }
1347
1348   /// Return a set of memrefs (begin iterator, size) which conservatively
1349   /// describe the memory behavior of both MachineInstrs.  This is appropriate
1350   /// for use when merging two MachineInstrs into one. This routine does not
1351   /// modify the memrefs of the this MachineInstr.
1352   std::pair<mmo_iterator, unsigned> mergeMemRefsWith(const MachineInstr& Other);
1353
1354   /// Return the MIFlags which represent both MachineInstrs. This
1355   /// should be used when merging two MachineInstrs into one. This routine does
1356   /// not modify the MIFlags of this MachineInstr.
1357   uint16_t mergeFlagsWith(const MachineInstr& Other) const;
1358
1359   /// Clear this MachineInstr's memory reference descriptor list.  This resets
1360   /// the memrefs to their most conservative state.  This should be used only
1361   /// as a last resort since it greatly pessimizes our knowledge of the memory
1362   /// access performed by the instruction.
1363   void dropMemRefs() {
1364     MemRefs = nullptr;
1365     NumMemRefs = 0;
1366   }
1367
1368   /// Break any tie involving OpIdx.
1369   void untieRegOperand(unsigned OpIdx) {
1370     MachineOperand &MO = getOperand(OpIdx);
1371     if (MO.isReg() && MO.isTied()) {
1372       getOperand(findTiedOperandIdx(OpIdx)).TiedTo = 0;
1373       MO.TiedTo = 0;
1374     }
1375   }
1376
1377   /// Add all implicit def and use operands to this instruction.
1378   void addImplicitDefUseOperands(MachineFunction &MF);
1379
1380 private:
1381   /// If this instruction is embedded into a MachineFunction, return the
1382   /// MachineRegisterInfo object for the current function, otherwise
1383   /// return null.
1384   MachineRegisterInfo *getRegInfo();
1385
1386   /// Unlink all of the register operands in this instruction from their
1387   /// respective use lists.  This requires that the operands already be on their
1388   /// use lists.
1389   void RemoveRegOperandsFromUseLists(MachineRegisterInfo&);
1390
1391   /// Add all of the register operands in this instruction from their
1392   /// respective use lists.  This requires that the operands not be on their
1393   /// use lists yet.
1394   void AddRegOperandsToUseLists(MachineRegisterInfo&);
1395
1396   /// Slow path for hasProperty when we're dealing with a bundle.
1397   bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
1398
1399   /// Implements the logic of getRegClassConstraintEffectForVReg for the
1400   /// this MI and the given operand index \p OpIdx.
1401   /// If the related operand does not constrained Reg, this returns CurRC.
1402   const TargetRegisterClass *getRegClassConstraintEffectForVRegImpl(
1403       unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1404       const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const;
1405 };
1406
1407 /// Special DenseMapInfo traits to compare MachineInstr* by *value* of the
1408 /// instruction rather than by pointer value.
1409 /// The hashing and equality testing functions ignore definitions so this is
1410 /// useful for CSE, etc.
1411 struct MachineInstrExpressionTrait : DenseMapInfo<MachineInstr*> {
1412   static inline MachineInstr *getEmptyKey() {
1413     return nullptr;
1414   }
1415
1416   static inline MachineInstr *getTombstoneKey() {
1417     return reinterpret_cast<MachineInstr*>(-1);
1418   }
1419
1420   static unsigned getHashValue(const MachineInstr* const &MI);
1421
1422   static bool isEqual(const MachineInstr* const &LHS,
1423                       const MachineInstr* const &RHS) {
1424     if (RHS == getEmptyKey() || RHS == getTombstoneKey() ||
1425         LHS == getEmptyKey() || LHS == getTombstoneKey())
1426       return LHS == RHS;
1427     return LHS->isIdenticalTo(*RHS, MachineInstr::IgnoreVRegDefs);
1428   }
1429 };
1430
1431 //===----------------------------------------------------------------------===//
1432 // Debugging Support
1433
1434 inline raw_ostream& operator<<(raw_ostream &OS, const MachineInstr &MI) {
1435   MI.print(OS);
1436   return OS;
1437 }
1438
1439 } // end namespace llvm
1440
1441 #endif // LLVM_CODEGEN_MACHINEINSTR_H