1 //===-- llvm/CodeGen/MachineOperand.h - MachineOperand class ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the declaration of the MachineOperand class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CODEGEN_MACHINEOPERAND_H
14 #define LLVM_CODEGEN_MACHINEOPERAND_H
15 
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/CodeGen/Register.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include <cassert>
20 
21 namespace llvm {
22 
23 class LLT;
24 class BlockAddress;
25 class Constant;
26 class ConstantFP;
27 class ConstantInt;
28 class GlobalValue;
29 class MachineBasicBlock;
30 class MachineInstr;
31 class MachineRegisterInfo;
32 class MCCFIInstruction;
33 class MDNode;
34 class ModuleSlotTracker;
35 class TargetIntrinsicInfo;
36 class TargetRegisterInfo;
37 class hash_code;
38 class raw_ostream;
39 class MCSymbol;
40 
41 /// MachineOperand class - Representation of each machine instruction operand.
42 ///
43 /// This class isn't a POD type because it has a private constructor, but its
44 /// destructor must be trivial. Functions like MachineInstr::addOperand(),
45 /// MachineRegisterInfo::moveOperands(), and MF::DeleteMachineInstr() depend on
46 /// not having to call the MachineOperand destructor.
47 ///
48 class MachineOperand {
49 public:
50   enum MachineOperandType : unsigned char {
51     MO_Register,          ///< Register operand.
52     MO_Immediate,         ///< Immediate operand
53     MO_CImmediate,        ///< Immediate >64bit operand
54     MO_FPImmediate,       ///< Floating-point immediate operand
55     MO_MachineBasicBlock, ///< MachineBasicBlock reference
56     MO_FrameIndex,        ///< Abstract Stack Frame Index
57     MO_ConstantPoolIndex, ///< Address of indexed Constant in Constant Pool
58     MO_TargetIndex,       ///< Target-dependent index+offset operand.
59     MO_JumpTableIndex,    ///< Address of indexed Jump Table for switch
60     MO_ExternalSymbol,    ///< Name of external global symbol
61     MO_GlobalAddress,     ///< Address of a global value
62     MO_BlockAddress,      ///< Address of a basic block
63     MO_RegisterMask,      ///< Mask of preserved registers.
64     MO_RegisterLiveOut,   ///< Mask of live-out registers.
65     MO_Metadata,          ///< Metadata reference (for debug info)
66     MO_MCSymbol,          ///< MCSymbol reference (for debug/eh info)
67     MO_CFIIndex,          ///< MCCFIInstruction index.
68     MO_IntrinsicID,       ///< Intrinsic ID for ISel
69     MO_Predicate,         ///< Generic predicate for ISel
70     MO_ShuffleMask,       ///< Other IR Constant for ISel (shuffle masks)
71     MO_DbgInstrRef, ///< Integer indices referring to an instruction+operand
72     MO_Last = MO_DbgInstrRef
73   };
74 
75 private:
76   /// OpKind - Specify what kind of operand this is.  This discriminates the
77   /// union.
78   unsigned OpKind : 8;
79 
80   /// Subregister number for MO_Register.  A value of 0 indicates the
81   /// MO_Register has no subReg.
82   ///
83   /// For all other kinds of operands, this field holds target-specific flags.
84   unsigned SubReg_TargetFlags : 12;
85 
86   /// TiedTo - Non-zero when this register operand is tied to another register
87   /// operand. The encoding of this field is described in the block comment
88   /// before MachineInstr::tieOperands().
89   unsigned TiedTo : 4;
90 
91   /// IsDef - True if this is a def, false if this is a use of the register.
92   /// This is only valid on register operands.
93   ///
94   unsigned IsDef : 1;
95 
96   /// IsImp - True if this is an implicit def or use, false if it is explicit.
97   /// This is only valid on register opderands.
98   ///
99   unsigned IsImp : 1;
100 
101   /// IsDeadOrKill
102   /// For uses: IsKill - Conservatively indicates the last use of a register
103   /// on this path through the function. A register operand with true value of
104   /// this flag must be the last use of the register, a register operand with
105   /// false value may or may not be the last use of the register. After regalloc
106   /// we can use recomputeLivenessFlags to get precise kill flags.
107   /// For defs: IsDead - True if this register is never used by a subsequent
108   /// instruction.
109   /// This is only valid on register operands.
110   unsigned IsDeadOrKill : 1;
111 
112   /// See isRenamable().
113   unsigned IsRenamable : 1;
114 
115   /// IsUndef - True if this register operand reads an "undef" value, i.e. the
116   /// read value doesn't matter.  This flag can be set on both use and def
117   /// operands.  On a sub-register def operand, it refers to the part of the
118   /// register that isn't written.  On a full-register def operand, it is a
119   /// noop.  See readsReg().
120   ///
121   /// This is only valid on registers.
122   ///
123   /// Note that an instruction may have multiple <undef> operands referring to
124   /// the same register.  In that case, the instruction may depend on those
125   /// operands reading the same dont-care value.  For example:
126   ///
127   ///   %1 = XOR undef %2, undef %2
128   ///
129   /// Any register can be used for %2, and its value doesn't matter, but
130   /// the two operands must be the same register.
131   ///
132   unsigned IsUndef : 1;
133 
134   /// IsInternalRead - True if this operand reads a value that was defined
135   /// inside the same instruction or bundle.  This flag can be set on both use
136   /// and def operands.  On a sub-register def operand, it refers to the part
137   /// of the register that isn't written.  On a full-register def operand, it
138   /// is a noop.
139   ///
140   /// When this flag is set, the instruction bundle must contain at least one
141   /// other def of the register.  If multiple instructions in the bundle define
142   /// the register, the meaning is target-defined.
143   unsigned IsInternalRead : 1;
144 
145   /// IsEarlyClobber - True if this MO_Register 'def' operand is written to
146   /// by the MachineInstr before all input registers are read.  This is used to
147   /// model the GCC inline asm '&' constraint modifier.
148   unsigned IsEarlyClobber : 1;
149 
150   /// IsDebug - True if this MO_Register 'use' operand is in a debug pseudo,
151   /// not a real instruction.  Such uses should be ignored during codegen.
152   unsigned IsDebug : 1;
153 
154   /// SmallContents - This really should be part of the Contents union, but
155   /// lives out here so we can get a better packed struct.
156   /// MO_Register: Register number.
157   /// OffsetedInfo: Low bits of offset.
158   union {
159     unsigned RegNo;           // For MO_Register.
160     unsigned OffsetLo;        // Matches Contents.OffsetedInfo.OffsetHi.
161   } SmallContents;
162 
163   /// ParentMI - This is the instruction that this operand is embedded into.
164   /// This is valid for all operand types, when the operand is in an instr.
165   MachineInstr *ParentMI = nullptr;
166 
167   /// Contents union - This contains the payload for the various operand types.
168   union ContentsUnion {
169     ContentsUnion() {}
170     MachineBasicBlock *MBB;  // For MO_MachineBasicBlock.
171     const ConstantFP *CFP;   // For MO_FPImmediate.
172     const ConstantInt *CI;   // For MO_CImmediate. Integers > 64bit.
173     int64_t ImmVal;          // For MO_Immediate.
174     const uint32_t *RegMask; // For MO_RegisterMask and MO_RegisterLiveOut.
175     const MDNode *MD;        // For MO_Metadata.
176     MCSymbol *Sym;           // For MO_MCSymbol.
177     unsigned CFIIndex;       // For MO_CFI.
178     Intrinsic::ID IntrinsicID; // For MO_IntrinsicID.
179     unsigned Pred;           // For MO_Predicate
180     ArrayRef<int> ShuffleMask; // For MO_ShuffleMask
181 
182     struct {                  // For MO_Register.
183       // Register number is in SmallContents.RegNo.
184       MachineOperand *Prev;   // Access list for register. See MRI.
185       MachineOperand *Next;
186     } Reg;
187 
188     struct { // For MO_DbgInstrRef.
189       unsigned InstrIdx;
190       unsigned OpIdx;
191     } InstrRef;
192 
193     /// OffsetedInfo - This struct contains the offset and an object identifier.
194     /// this represent the object as with an optional offset from it.
195     struct {
196       union {
197         int Index;                // For MO_*Index - The index itself.
198         const char *SymbolName;   // For MO_ExternalSymbol.
199         const GlobalValue *GV;    // For MO_GlobalAddress.
200         const BlockAddress *BA;   // For MO_BlockAddress.
201       } Val;
202       // Low bits of offset are in SmallContents.OffsetLo.
203       int OffsetHi;               // An offset from the object, high 32 bits.
204     } OffsetedInfo;
205   } Contents;
206 
207   explicit MachineOperand(MachineOperandType K)
208       : OpKind(K), SubReg_TargetFlags(0) {
209     // Assert that the layout is what we expect. It's easy to grow this object.
210     static_assert(alignof(MachineOperand) <= alignof(int64_t),
211                   "MachineOperand shouldn't be more than 8 byte aligned");
212     static_assert(sizeof(Contents) <= 2 * sizeof(void *),
213                   "Contents should be at most two pointers");
214     static_assert(sizeof(MachineOperand) <=
215                       alignTo<alignof(int64_t)>(2 * sizeof(unsigned) +
216                                                 3 * sizeof(void *)),
217                   "MachineOperand too big. Should be Kind, SmallContents, "
218                   "ParentMI, and Contents");
219   }
220 
221 public:
222   /// getType - Returns the MachineOperandType for this operand.
223   ///
224   MachineOperandType getType() const { return (MachineOperandType)OpKind; }
225 
226   unsigned getTargetFlags() const {
227     return isReg() ? 0 : SubReg_TargetFlags;
228   }
229   void setTargetFlags(unsigned F) {
230     assert(!isReg() && "Register operands can't have target flags");
231     SubReg_TargetFlags = F;
232     assert(SubReg_TargetFlags == F && "Target flags out of range");
233   }
234   void addTargetFlag(unsigned F) {
235     assert(!isReg() && "Register operands can't have target flags");
236     SubReg_TargetFlags |= F;
237     assert((SubReg_TargetFlags & F) && "Target flags out of range");
238   }
239 
240 
241   /// getParent - Return the instruction that this operand belongs to.
242   ///
243   MachineInstr *getParent() { return ParentMI; }
244   const MachineInstr *getParent() const { return ParentMI; }
245 
246   /// clearParent - Reset the parent pointer.
247   ///
248   /// The MachineOperand copy constructor also copies ParentMI, expecting the
249   /// original to be deleted. If a MachineOperand is ever stored outside a
250   /// MachineInstr, the parent pointer must be cleared.
251   ///
252   /// Never call clearParent() on an operand in a MachineInstr.
253   ///
254   void clearParent() { ParentMI = nullptr; }
255 
256   /// Returns the index of this operand in the instruction that it belongs to.
257   unsigned getOperandNo() const;
258 
259   /// Print a subreg index operand.
260   /// MO_Immediate operands can also be subreg idices. If it's the case, the
261   /// subreg index name will be printed. MachineInstr::isOperandSubregIdx can be
262   /// called to check this.
263   static void printSubRegIdx(raw_ostream &OS, uint64_t Index,
264                              const TargetRegisterInfo *TRI);
265 
266   /// Print operand target flags.
267   static void printTargetFlags(raw_ostream& OS, const MachineOperand &Op);
268 
269   /// Print a MCSymbol as an operand.
270   static void printSymbol(raw_ostream &OS, MCSymbol &Sym);
271 
272   /// Print a stack object reference.
273   static void printStackObjectReference(raw_ostream &OS, unsigned FrameIndex,
274                                         bool IsFixed, StringRef Name);
275 
276   /// Print the offset with explicit +/- signs.
277   static void printOperandOffset(raw_ostream &OS, int64_t Offset);
278 
279   /// Print an IRSlotNumber.
280   static void printIRSlotNumber(raw_ostream &OS, int Slot);
281 
282   /// Print the MachineOperand to \p os.
283   /// Providing a valid \p TRI and \p IntrinsicInfo results in a more
284   /// target-specific printing. If \p TRI and \p IntrinsicInfo are null, the
285   /// function will try to pick it up from the parent.
286   void print(raw_ostream &os, const TargetRegisterInfo *TRI = nullptr,
287              const TargetIntrinsicInfo *IntrinsicInfo = nullptr) const;
288 
289   /// More complex way of printing a MachineOperand.
290   /// \param TypeToPrint specifies the generic type to be printed on uses and
291   /// defs. It can be determined using MachineInstr::getTypeToPrint.
292   /// \param OpIdx - specifies the index of the operand in machine instruction.
293   /// This will be used by target dependent MIR formatter. Could be std::nullopt
294   /// if the index is unknown, e.g. called by dump().
295   /// \param PrintDef - whether we want to print `def` on an operand which
296   /// isDef. Sometimes, if the operand is printed before '=', we don't print
297   /// `def`.
298   /// \param IsStandalone - whether we want a verbose output of the MO. This
299   /// prints extra information that can be easily inferred when printing the
300   /// whole function, but not when printing only a fragment of it.
301   /// \param ShouldPrintRegisterTies - whether we want to print register ties.
302   /// Sometimes they are easily determined by the instruction's descriptor
303   /// (MachineInstr::hasComplexRegiterTies can determine if it's needed).
304   /// \param TiedOperandIdx - if we need to print register ties this needs to
305   /// provide the index of the tied register. If not, it will be ignored.
306   /// \param TRI - provide more target-specific information to the printer.
307   /// Unlike the previous function, this one will not try and get the
308   /// information from it's parent.
309   /// \param IntrinsicInfo - same as \p TRI.
310   void print(raw_ostream &os, ModuleSlotTracker &MST, LLT TypeToPrint,
311              std::optional<unsigned> OpIdx, bool PrintDef, bool IsStandalone,
312              bool ShouldPrintRegisterTies, unsigned TiedOperandIdx,
313              const TargetRegisterInfo *TRI,
314              const TargetIntrinsicInfo *IntrinsicInfo) const;
315 
316   /// Same as print(os, TRI, IntrinsicInfo), but allows to specify the low-level
317   /// type to be printed the same way the full version of print(...) does it.
318   void print(raw_ostream &os, LLT TypeToPrint,
319              const TargetRegisterInfo *TRI = nullptr,
320              const TargetIntrinsicInfo *IntrinsicInfo = nullptr) const;
321 
322   void dump() const;
323 
324   //===--------------------------------------------------------------------===//
325   // Accessors that tell you what kind of MachineOperand you're looking at.
326   //===--------------------------------------------------------------------===//
327 
328   /// isReg - Tests if this is a MO_Register operand.
329   bool isReg() const { return OpKind == MO_Register; }
330   /// isImm - Tests if this is a MO_Immediate operand.
331   bool isImm() const { return OpKind == MO_Immediate; }
332   /// isCImm - Test if this is a MO_CImmediate operand.
333   bool isCImm() const { return OpKind == MO_CImmediate; }
334   /// isFPImm - Tests if this is a MO_FPImmediate operand.
335   bool isFPImm() const { return OpKind == MO_FPImmediate; }
336   /// isMBB - Tests if this is a MO_MachineBasicBlock operand.
337   bool isMBB() const { return OpKind == MO_MachineBasicBlock; }
338   /// isFI - Tests if this is a MO_FrameIndex operand.
339   bool isFI() const { return OpKind == MO_FrameIndex; }
340   /// isCPI - Tests if this is a MO_ConstantPoolIndex operand.
341   bool isCPI() const { return OpKind == MO_ConstantPoolIndex; }
342   /// isTargetIndex - Tests if this is a MO_TargetIndex operand.
343   bool isTargetIndex() const { return OpKind == MO_TargetIndex; }
344   /// isJTI - Tests if this is a MO_JumpTableIndex operand.
345   bool isJTI() const { return OpKind == MO_JumpTableIndex; }
346   /// isGlobal - Tests if this is a MO_GlobalAddress operand.
347   bool isGlobal() const { return OpKind == MO_GlobalAddress; }
348   /// isSymbol - Tests if this is a MO_ExternalSymbol operand.
349   bool isSymbol() const { return OpKind == MO_ExternalSymbol; }
350   /// isBlockAddress - Tests if this is a MO_BlockAddress operand.
351   bool isBlockAddress() const { return OpKind == MO_BlockAddress; }
352   /// isRegMask - Tests if this is a MO_RegisterMask operand.
353   bool isRegMask() const { return OpKind == MO_RegisterMask; }
354   /// isRegLiveOut - Tests if this is a MO_RegisterLiveOut operand.
355   bool isRegLiveOut() const { return OpKind == MO_RegisterLiveOut; }
356   /// isMetadata - Tests if this is a MO_Metadata operand.
357   bool isMetadata() const { return OpKind == MO_Metadata; }
358   bool isMCSymbol() const { return OpKind == MO_MCSymbol; }
359   bool isDbgInstrRef() const { return OpKind == MO_DbgInstrRef; }
360   bool isCFIIndex() const { return OpKind == MO_CFIIndex; }
361   bool isIntrinsicID() const { return OpKind == MO_IntrinsicID; }
362   bool isPredicate() const { return OpKind == MO_Predicate; }
363   bool isShuffleMask() const { return OpKind == MO_ShuffleMask; }
364   //===--------------------------------------------------------------------===//
365   // Accessors for Register Operands
366   //===--------------------------------------------------------------------===//
367 
368   /// getReg - Returns the register number.
369   Register getReg() const {
370     assert(isReg() && "This is not a register operand!");
371     return Register(SmallContents.RegNo);
372   }
373 
374   unsigned getSubReg() const {
375     assert(isReg() && "Wrong MachineOperand accessor");
376     return SubReg_TargetFlags;
377   }
378 
379   bool isUse() const {
380     assert(isReg() && "Wrong MachineOperand accessor");
381     return !IsDef;
382   }
383 
384   bool isDef() const {
385     assert(isReg() && "Wrong MachineOperand accessor");
386     return IsDef;
387   }
388 
389   bool isImplicit() const {
390     assert(isReg() && "Wrong MachineOperand accessor");
391     return IsImp;
392   }
393 
394   bool isDead() const {
395     assert(isReg() && "Wrong MachineOperand accessor");
396     return IsDeadOrKill & IsDef;
397   }
398 
399   bool isKill() const {
400     assert(isReg() && "Wrong MachineOperand accessor");
401     return IsDeadOrKill & !IsDef;
402   }
403 
404   bool isUndef() const {
405     assert(isReg() && "Wrong MachineOperand accessor");
406     return IsUndef;
407   }
408 
409   /// isRenamable - Returns true if this register may be renamed, i.e. it does
410   /// not generate a value that is somehow read in a way that is not represented
411   /// by the Machine IR (e.g. to meet an ABI or ISA requirement).  This is only
412   /// valid on physical register operands.  Virtual registers are assumed to
413   /// always be renamable regardless of the value of this field.
414   ///
415   /// Operands that are renamable can freely be changed to any other register
416   /// that is a member of the register class returned by
417   /// MI->getRegClassConstraint().
418   ///
419   /// isRenamable can return false for several different reasons:
420   ///
421   /// - ABI constraints (since liveness is not always precisely modeled).  We
422   ///   conservatively handle these cases by setting all physical register
423   ///   operands that didn’t start out as virtual regs to not be renamable.
424   ///   Also any physical register operands created after register allocation or
425   ///   whose register is changed after register allocation will not be
426   ///   renamable.  This state is tracked in the MachineOperand::IsRenamable
427   ///   bit.
428   ///
429   /// - Opcode/target constraints: for opcodes that have complex register class
430   ///   requirements (e.g. that depend on other operands/instructions), we set
431   ///   hasExtraSrcRegAllocReq/hasExtraDstRegAllocReq in the machine opcode
432   ///   description.  Operands belonging to instructions with opcodes that are
433   ///   marked hasExtraSrcRegAllocReq/hasExtraDstRegAllocReq return false from
434   ///   isRenamable().  Additionally, the AllowRegisterRenaming target property
435   ///   prevents any operands from being marked renamable for targets that don't
436   ///   have detailed opcode hasExtraSrcRegAllocReq/hasExtraDstRegAllocReq
437   ///   values.
438   bool isRenamable() const;
439 
440   bool isInternalRead() const {
441     assert(isReg() && "Wrong MachineOperand accessor");
442     return IsInternalRead;
443   }
444 
445   bool isEarlyClobber() const {
446     assert(isReg() && "Wrong MachineOperand accessor");
447     return IsEarlyClobber;
448   }
449 
450   bool isTied() const {
451     assert(isReg() && "Wrong MachineOperand accessor");
452     return TiedTo;
453   }
454 
455   bool isDebug() const {
456     assert(isReg() && "Wrong MachineOperand accessor");
457     return IsDebug;
458   }
459 
460   /// readsReg - Returns true if this operand reads the previous value of its
461   /// register.  A use operand with the <undef> flag set doesn't read its
462   /// register.  A sub-register def implicitly reads the other parts of the
463   /// register being redefined unless the <undef> flag is set.
464   ///
465   /// This refers to reading the register value from before the current
466   /// instruction or bundle. Internal bundle reads are not included.
467   bool readsReg() const {
468     assert(isReg() && "Wrong MachineOperand accessor");
469     return !isUndef() && !isInternalRead() && (isUse() || getSubReg());
470   }
471 
472   /// Return true if this operand can validly be appended to an arbitrary
473   /// operand list. i.e. this behaves like an implicit operand.
474   bool isValidExcessOperand() const {
475     if ((isReg() && isImplicit()) || isRegMask())
476       return true;
477 
478     // Debug operands
479     return isMetadata() || isMCSymbol();
480   }
481 
482   //===--------------------------------------------------------------------===//
483   // Mutators for Register Operands
484   //===--------------------------------------------------------------------===//
485 
486   /// Change the register this operand corresponds to.
487   ///
488   void setReg(Register Reg);
489 
490   void setSubReg(unsigned subReg) {
491     assert(isReg() && "Wrong MachineOperand mutator");
492     SubReg_TargetFlags = subReg;
493     assert(SubReg_TargetFlags == subReg && "SubReg out of range");
494   }
495 
496   /// substVirtReg - Substitute the current register with the virtual
497   /// subregister Reg:SubReg. Take any existing SubReg index into account,
498   /// using TargetRegisterInfo to compose the subreg indices if necessary.
499   /// Reg must be a virtual register, SubIdx can be 0.
500   ///
501   void substVirtReg(Register Reg, unsigned SubIdx, const TargetRegisterInfo&);
502 
503   /// substPhysReg - Substitute the current register with the physical register
504   /// Reg, taking any existing SubReg into account. For instance,
505   /// substPhysReg(%eax) will change %reg1024:sub_8bit to %al.
506   ///
507   void substPhysReg(MCRegister Reg, const TargetRegisterInfo&);
508 
509   void setIsUse(bool Val = true) { setIsDef(!Val); }
510 
511   /// Change a def to a use, or a use to a def.
512   void setIsDef(bool Val = true);
513 
514   void setImplicit(bool Val = true) {
515     assert(isReg() && "Wrong MachineOperand mutator");
516     IsImp = Val;
517   }
518 
519   void setIsKill(bool Val = true) {
520     assert(isReg() && !IsDef && "Wrong MachineOperand mutator");
521     assert((!Val || !isDebug()) && "Marking a debug operation as kill");
522     IsDeadOrKill = Val;
523   }
524 
525   void setIsDead(bool Val = true) {
526     assert(isReg() && IsDef && "Wrong MachineOperand mutator");
527     IsDeadOrKill = Val;
528   }
529 
530   void setIsUndef(bool Val = true) {
531     assert(isReg() && "Wrong MachineOperand mutator");
532     IsUndef = Val;
533   }
534 
535   void setIsRenamable(bool Val = true);
536 
537   void setIsInternalRead(bool Val = true) {
538     assert(isReg() && "Wrong MachineOperand mutator");
539     IsInternalRead = Val;
540   }
541 
542   void setIsEarlyClobber(bool Val = true) {
543     assert(isReg() && IsDef && "Wrong MachineOperand mutator");
544     IsEarlyClobber = Val;
545   }
546 
547   void setIsDebug(bool Val = true) {
548     assert(isReg() && !IsDef && "Wrong MachineOperand mutator");
549     IsDebug = Val;
550   }
551 
552   //===--------------------------------------------------------------------===//
553   // Accessors for various operand types.
554   //===--------------------------------------------------------------------===//
555 
556   int64_t getImm() const {
557     assert(isImm() && "Wrong MachineOperand accessor");
558     return Contents.ImmVal;
559   }
560 
561   const ConstantInt *getCImm() const {
562     assert(isCImm() && "Wrong MachineOperand accessor");
563     return Contents.CI;
564   }
565 
566   const ConstantFP *getFPImm() const {
567     assert(isFPImm() && "Wrong MachineOperand accessor");
568     return Contents.CFP;
569   }
570 
571   MachineBasicBlock *getMBB() const {
572     assert(isMBB() && "Wrong MachineOperand accessor");
573     return Contents.MBB;
574   }
575 
576   int getIndex() const {
577     assert((isFI() || isCPI() || isTargetIndex() || isJTI()) &&
578            "Wrong MachineOperand accessor");
579     return Contents.OffsetedInfo.Val.Index;
580   }
581 
582   const GlobalValue *getGlobal() const {
583     assert(isGlobal() && "Wrong MachineOperand accessor");
584     return Contents.OffsetedInfo.Val.GV;
585   }
586 
587   const BlockAddress *getBlockAddress() const {
588     assert(isBlockAddress() && "Wrong MachineOperand accessor");
589     return Contents.OffsetedInfo.Val.BA;
590   }
591 
592   MCSymbol *getMCSymbol() const {
593     assert(isMCSymbol() && "Wrong MachineOperand accessor");
594     return Contents.Sym;
595   }
596 
597   unsigned getInstrRefInstrIndex() const {
598     assert(isDbgInstrRef() && "Wrong MachineOperand accessor");
599     return Contents.InstrRef.InstrIdx;
600   }
601 
602   unsigned getInstrRefOpIndex() const {
603     assert(isDbgInstrRef() && "Wrong MachineOperand accessor");
604     return Contents.InstrRef.OpIdx;
605   }
606 
607   unsigned getCFIIndex() const {
608     assert(isCFIIndex() && "Wrong MachineOperand accessor");
609     return Contents.CFIIndex;
610   }
611 
612   Intrinsic::ID getIntrinsicID() const {
613     assert(isIntrinsicID() && "Wrong MachineOperand accessor");
614     return Contents.IntrinsicID;
615   }
616 
617   unsigned getPredicate() const {
618     assert(isPredicate() && "Wrong MachineOperand accessor");
619     return Contents.Pred;
620   }
621 
622   ArrayRef<int> getShuffleMask() const {
623     assert(isShuffleMask() && "Wrong MachineOperand accessor");
624     return Contents.ShuffleMask;
625   }
626 
627   /// Return the offset from the symbol in this operand. This always returns 0
628   /// for ExternalSymbol operands.
629   int64_t getOffset() const {
630     assert((isGlobal() || isSymbol() || isMCSymbol() || isCPI() ||
631             isTargetIndex() || isBlockAddress()) &&
632            "Wrong MachineOperand accessor");
633     return int64_t(uint64_t(Contents.OffsetedInfo.OffsetHi) << 32) |
634            SmallContents.OffsetLo;
635   }
636 
637   const char *getSymbolName() const {
638     assert(isSymbol() && "Wrong MachineOperand accessor");
639     return Contents.OffsetedInfo.Val.SymbolName;
640   }
641 
642   /// clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
643   /// It is sometimes necessary to detach the register mask pointer from its
644   /// machine operand. This static method can be used for such detached bit
645   /// mask pointers.
646   static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg) {
647     // See TargetRegisterInfo.h.
648     assert(PhysReg < (1u << 30) && "Not a physical register");
649     return !(RegMask[PhysReg / 32] & (1u << PhysReg % 32));
650   }
651 
652   /// clobbersPhysReg - Returns true if this RegMask operand clobbers PhysReg.
653   bool clobbersPhysReg(MCRegister PhysReg) const {
654      return clobbersPhysReg(getRegMask(), PhysReg);
655   }
656 
657   /// getRegMask - Returns a bit mask of registers preserved by this RegMask
658   /// operand.
659   const uint32_t *getRegMask() const {
660     assert(isRegMask() && "Wrong MachineOperand accessor");
661     return Contents.RegMask;
662   }
663 
664   /// Returns number of elements needed for a regmask array.
665   static unsigned getRegMaskSize(unsigned NumRegs) {
666     return (NumRegs + 31) / 32;
667   }
668 
669   /// getRegLiveOut - Returns a bit mask of live-out registers.
670   const uint32_t *getRegLiveOut() const {
671     assert(isRegLiveOut() && "Wrong MachineOperand accessor");
672     return Contents.RegMask;
673   }
674 
675   const MDNode *getMetadata() const {
676     assert(isMetadata() && "Wrong MachineOperand accessor");
677     return Contents.MD;
678   }
679 
680   //===--------------------------------------------------------------------===//
681   // Mutators for various operand types.
682   //===--------------------------------------------------------------------===//
683 
684   void setImm(int64_t immVal) {
685     assert(isImm() && "Wrong MachineOperand mutator");
686     Contents.ImmVal = immVal;
687   }
688 
689   void setCImm(const ConstantInt *CI) {
690     assert(isCImm() && "Wrong MachineOperand mutator");
691     Contents.CI = CI;
692   }
693 
694   void setFPImm(const ConstantFP *CFP) {
695     assert(isFPImm() && "Wrong MachineOperand mutator");
696     Contents.CFP = CFP;
697   }
698 
699   void setOffset(int64_t Offset) {
700     assert((isGlobal() || isSymbol() || isMCSymbol() || isCPI() ||
701             isTargetIndex() || isBlockAddress()) &&
702            "Wrong MachineOperand mutator");
703     SmallContents.OffsetLo = unsigned(Offset);
704     Contents.OffsetedInfo.OffsetHi = int(Offset >> 32);
705   }
706 
707   void setIndex(int Idx) {
708     assert((isFI() || isCPI() || isTargetIndex() || isJTI()) &&
709            "Wrong MachineOperand mutator");
710     Contents.OffsetedInfo.Val.Index = Idx;
711   }
712 
713   void setMetadata(const MDNode *MD) {
714     assert(isMetadata() && "Wrong MachineOperand mutator");
715     Contents.MD = MD;
716   }
717 
718   void setInstrRefInstrIndex(unsigned InstrIdx) {
719     assert(isDbgInstrRef() && "Wrong MachineOperand mutator");
720     Contents.InstrRef.InstrIdx = InstrIdx;
721   }
722   void setInstrRefOpIndex(unsigned OpIdx) {
723     assert(isDbgInstrRef() && "Wrong MachineOperand mutator");
724     Contents.InstrRef.OpIdx = OpIdx;
725   }
726 
727   void setMBB(MachineBasicBlock *MBB) {
728     assert(isMBB() && "Wrong MachineOperand mutator");
729     Contents.MBB = MBB;
730   }
731 
732   /// Sets value of register mask operand referencing Mask.  The
733   /// operand does not take ownership of the memory referenced by Mask, it must
734   /// remain valid for the lifetime of the operand. See CreateRegMask().
735   /// Any physreg with a 0 bit in the mask is clobbered by the instruction.
736   void setRegMask(const uint32_t *RegMaskPtr) {
737     assert(isRegMask() && "Wrong MachineOperand mutator");
738     Contents.RegMask = RegMaskPtr;
739   }
740 
741   void setIntrinsicID(Intrinsic::ID IID) {
742     assert(isIntrinsicID() && "Wrong MachineOperand mutator");
743     Contents.IntrinsicID = IID;
744   }
745 
746   void setPredicate(unsigned Predicate) {
747     assert(isPredicate() && "Wrong MachineOperand mutator");
748     Contents.Pred = Predicate;
749   }
750 
751   //===--------------------------------------------------------------------===//
752   // Other methods.
753   //===--------------------------------------------------------------------===//
754 
755   /// Returns true if this operand is identical to the specified operand except
756   /// for liveness related flags (isKill, isUndef and isDead). Note that this
757   /// should stay in sync with the hash_value overload below.
758   bool isIdenticalTo(const MachineOperand &Other) const;
759 
760   /// MachineOperand hash_value overload.
761   ///
762   /// Note that this includes the same information in the hash that
763   /// isIdenticalTo uses for comparison. It is thus suited for use in hash
764   /// tables which use that function for equality comparisons only. This must
765   /// stay exactly in sync with isIdenticalTo above.
766   friend hash_code hash_value(const MachineOperand &MO);
767 
768   /// ChangeToImmediate - Replace this operand with a new immediate operand of
769   /// the specified value.  If an operand is known to be an immediate already,
770   /// the setImm method should be used.
771   void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags = 0);
772 
773   /// ChangeToFPImmediate - Replace this operand with a new FP immediate operand
774   /// of the specified value.  If an operand is known to be an FP immediate
775   /// already, the setFPImm method should be used.
776   void ChangeToFPImmediate(const ConstantFP *FPImm, unsigned TargetFlags = 0);
777 
778   /// ChangeToES - Replace this operand with a new external symbol operand.
779   void ChangeToES(const char *SymName, unsigned TargetFlags = 0);
780 
781   /// ChangeToGA - Replace this operand with a new global address operand.
782   void ChangeToGA(const GlobalValue *GV, int64_t Offset,
783                   unsigned TargetFlags = 0);
784 
785   /// ChangeToMCSymbol - Replace this operand with a new MC symbol operand.
786   void ChangeToMCSymbol(MCSymbol *Sym, unsigned TargetFlags = 0);
787 
788   /// Replace this operand with a frame index.
789   void ChangeToFrameIndex(int Idx, unsigned TargetFlags = 0);
790 
791   /// Replace this operand with a target index.
792   void ChangeToTargetIndex(unsigned Idx, int64_t Offset,
793                            unsigned TargetFlags = 0);
794 
795   /// Replace this operand with an Instruction Reference.
796   void ChangeToDbgInstrRef(unsigned InstrIdx, unsigned OpIdx,
797                            unsigned TargetFlags = 0);
798 
799   /// ChangeToRegister - Replace this operand with a new register operand of
800   /// the specified value.  If an operand is known to be an register already,
801   /// the setReg method should be used.
802   void ChangeToRegister(Register Reg, bool isDef, bool isImp = false,
803                         bool isKill = false, bool isDead = false,
804                         bool isUndef = false, bool isDebug = false);
805 
806   /// getTargetIndexName - If this MachineOperand is a TargetIndex that has a
807   /// name, attempt to get the name. Returns nullptr if the TargetIndex does not
808   /// have a name. Asserts if MO is not a TargetIndex.
809   const char *getTargetIndexName() const;
810 
811   //===--------------------------------------------------------------------===//
812   // Construction methods.
813   //===--------------------------------------------------------------------===//
814 
815   static MachineOperand CreateImm(int64_t Val) {
816     MachineOperand Op(MachineOperand::MO_Immediate);
817     Op.setImm(Val);
818     return Op;
819   }
820 
821   static MachineOperand CreateCImm(const ConstantInt *CI) {
822     MachineOperand Op(MachineOperand::MO_CImmediate);
823     Op.Contents.CI = CI;
824     return Op;
825   }
826 
827   static MachineOperand CreateFPImm(const ConstantFP *CFP) {
828     MachineOperand Op(MachineOperand::MO_FPImmediate);
829     Op.Contents.CFP = CFP;
830     return Op;
831   }
832 
833   static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp = false,
834                                   bool isKill = false, bool isDead = false,
835                                   bool isUndef = false,
836                                   bool isEarlyClobber = false,
837                                   unsigned SubReg = 0, bool isDebug = false,
838                                   bool isInternalRead = false,
839                                   bool isRenamable = false) {
840     assert(!(isDead && !isDef) && "Dead flag on non-def");
841     assert(!(isKill && isDef) && "Kill flag on def");
842     MachineOperand Op(MachineOperand::MO_Register);
843     Op.IsDef = isDef;
844     Op.IsImp = isImp;
845     Op.IsDeadOrKill = isKill | isDead;
846     Op.IsRenamable = isRenamable;
847     Op.IsUndef = isUndef;
848     Op.IsInternalRead = isInternalRead;
849     Op.IsEarlyClobber = isEarlyClobber;
850     Op.TiedTo = 0;
851     Op.IsDebug = isDebug;
852     Op.SmallContents.RegNo = Reg;
853     Op.Contents.Reg.Prev = nullptr;
854     Op.Contents.Reg.Next = nullptr;
855     Op.setSubReg(SubReg);
856     return Op;
857   }
858   static MachineOperand CreateMBB(MachineBasicBlock *MBB,
859                                   unsigned TargetFlags = 0) {
860     MachineOperand Op(MachineOperand::MO_MachineBasicBlock);
861     Op.setMBB(MBB);
862     Op.setTargetFlags(TargetFlags);
863     return Op;
864   }
865   static MachineOperand CreateFI(int Idx) {
866     MachineOperand Op(MachineOperand::MO_FrameIndex);
867     Op.setIndex(Idx);
868     return Op;
869   }
870   static MachineOperand CreateCPI(unsigned Idx, int Offset,
871                                   unsigned TargetFlags = 0) {
872     MachineOperand Op(MachineOperand::MO_ConstantPoolIndex);
873     Op.setIndex(Idx);
874     Op.setOffset(Offset);
875     Op.setTargetFlags(TargetFlags);
876     return Op;
877   }
878   static MachineOperand CreateTargetIndex(unsigned Idx, int64_t Offset,
879                                           unsigned TargetFlags = 0) {
880     MachineOperand Op(MachineOperand::MO_TargetIndex);
881     Op.setIndex(Idx);
882     Op.setOffset(Offset);
883     Op.setTargetFlags(TargetFlags);
884     return Op;
885   }
886   static MachineOperand CreateJTI(unsigned Idx, unsigned TargetFlags = 0) {
887     MachineOperand Op(MachineOperand::MO_JumpTableIndex);
888     Op.setIndex(Idx);
889     Op.setTargetFlags(TargetFlags);
890     return Op;
891   }
892   static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset,
893                                  unsigned TargetFlags = 0) {
894     MachineOperand Op(MachineOperand::MO_GlobalAddress);
895     Op.Contents.OffsetedInfo.Val.GV = GV;
896     Op.setOffset(Offset);
897     Op.setTargetFlags(TargetFlags);
898     return Op;
899   }
900   static MachineOperand CreateES(const char *SymName,
901                                  unsigned TargetFlags = 0) {
902     MachineOperand Op(MachineOperand::MO_ExternalSymbol);
903     Op.Contents.OffsetedInfo.Val.SymbolName = SymName;
904     Op.setOffset(0); // Offset is always 0.
905     Op.setTargetFlags(TargetFlags);
906     return Op;
907   }
908   static MachineOperand CreateBA(const BlockAddress *BA, int64_t Offset,
909                                  unsigned TargetFlags = 0) {
910     MachineOperand Op(MachineOperand::MO_BlockAddress);
911     Op.Contents.OffsetedInfo.Val.BA = BA;
912     Op.setOffset(Offset);
913     Op.setTargetFlags(TargetFlags);
914     return Op;
915   }
916   /// CreateRegMask - Creates a register mask operand referencing Mask.  The
917   /// operand does not take ownership of the memory referenced by Mask, it
918   /// must remain valid for the lifetime of the operand.
919   ///
920   /// A RegMask operand represents a set of non-clobbered physical registers
921   /// on an instruction that clobbers many registers, typically a call.  The
922   /// bit mask has a bit set for each physreg that is preserved by this
923   /// instruction, as described in the documentation for
924   /// TargetRegisterInfo::getCallPreservedMask().
925   ///
926   /// Any physreg with a 0 bit in the mask is clobbered by the instruction.
927   ///
928   static MachineOperand CreateRegMask(const uint32_t *Mask) {
929     assert(Mask && "Missing register mask");
930     MachineOperand Op(MachineOperand::MO_RegisterMask);
931     Op.Contents.RegMask = Mask;
932     return Op;
933   }
934   static MachineOperand CreateRegLiveOut(const uint32_t *Mask) {
935     assert(Mask && "Missing live-out register mask");
936     MachineOperand Op(MachineOperand::MO_RegisterLiveOut);
937     Op.Contents.RegMask = Mask;
938     return Op;
939   }
940   static MachineOperand CreateMetadata(const MDNode *Meta) {
941     MachineOperand Op(MachineOperand::MO_Metadata);
942     Op.Contents.MD = Meta;
943     return Op;
944   }
945 
946   static MachineOperand CreateMCSymbol(MCSymbol *Sym,
947                                        unsigned TargetFlags = 0) {
948     MachineOperand Op(MachineOperand::MO_MCSymbol);
949     Op.Contents.Sym = Sym;
950     Op.setOffset(0);
951     Op.setTargetFlags(TargetFlags);
952     return Op;
953   }
954 
955   static MachineOperand CreateDbgInstrRef(unsigned InstrIdx, unsigned OpIdx) {
956     MachineOperand Op(MachineOperand::MO_DbgInstrRef);
957     Op.Contents.InstrRef.InstrIdx = InstrIdx;
958     Op.Contents.InstrRef.OpIdx = OpIdx;
959     return Op;
960   }
961 
962   static MachineOperand CreateCFIIndex(unsigned CFIIndex) {
963     MachineOperand Op(MachineOperand::MO_CFIIndex);
964     Op.Contents.CFIIndex = CFIIndex;
965     return Op;
966   }
967 
968   static MachineOperand CreateIntrinsicID(Intrinsic::ID ID) {
969     MachineOperand Op(MachineOperand::MO_IntrinsicID);
970     Op.Contents.IntrinsicID = ID;
971     return Op;
972   }
973 
974   static MachineOperand CreatePredicate(unsigned Pred) {
975     MachineOperand Op(MachineOperand::MO_Predicate);
976     Op.Contents.Pred = Pred;
977     return Op;
978   }
979 
980   static MachineOperand CreateShuffleMask(ArrayRef<int> Mask) {
981     MachineOperand Op(MachineOperand::MO_ShuffleMask);
982     Op.Contents.ShuffleMask = Mask;
983     return Op;
984   }
985 
986   friend class MachineInstr;
987   friend class MachineRegisterInfo;
988 
989 private:
990   // If this operand is currently a register operand, and if this is in a
991   // function, deregister the operand from the register's use/def list.
992   void removeRegFromUses();
993 
994   /// Artificial kinds for DenseMap usage.
995   enum : unsigned char {
996     MO_Empty = MO_Last + 1,
997     MO_Tombstone,
998   };
999 
1000   friend struct DenseMapInfo<MachineOperand>;
1001 
1002   //===--------------------------------------------------------------------===//
1003   // Methods for handling register use/def lists.
1004   //===--------------------------------------------------------------------===//
1005 
1006   /// isOnRegUseList - Return true if this operand is on a register use/def
1007   /// list or false if not.  This can only be called for register operands
1008   /// that are part of a machine instruction.
1009   bool isOnRegUseList() const {
1010     assert(isReg() && "Can only add reg operand to use lists");
1011     return Contents.Reg.Prev != nullptr;
1012   }
1013 };
1014 
1015 template <> struct DenseMapInfo<MachineOperand> {
1016   static MachineOperand getEmptyKey() {
1017     return MachineOperand(static_cast<MachineOperand::MachineOperandType>(
1018         MachineOperand::MO_Empty));
1019   }
1020   static MachineOperand getTombstoneKey() {
1021     return MachineOperand(static_cast<MachineOperand::MachineOperandType>(
1022         MachineOperand::MO_Tombstone));
1023   }
1024   static unsigned getHashValue(const MachineOperand &MO) {
1025     return hash_value(MO);
1026   }
1027   static bool isEqual(const MachineOperand &LHS, const MachineOperand &RHS) {
1028     if (LHS.getType() == static_cast<MachineOperand::MachineOperandType>(
1029                              MachineOperand::MO_Empty) ||
1030         LHS.getType() == static_cast<MachineOperand::MachineOperandType>(
1031                              MachineOperand::MO_Tombstone))
1032       return LHS.getType() == RHS.getType();
1033     return LHS.isIdenticalTo(RHS);
1034   }
1035 };
1036 
1037 inline raw_ostream &operator<<(raw_ostream &OS, const MachineOperand &MO) {
1038   MO.print(OS);
1039   return OS;
1040 }
1041 
1042 // See friend declaration above. This additional declaration is required in
1043 // order to compile LLVM with IBM xlC compiler.
1044 hash_code hash_value(const MachineOperand &MO);
1045 } // namespace llvm
1046 
1047 #endif
1048