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