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