xref: /llvm-project/llvm/lib/CodeGen/MachineOperand.cpp (revision 0b5bdceabfeaf67c91e5ccfed0320a82781f555c)
1 //===- lib/CodeGen/MachineOperand.cpp -------------------------------------===//
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 /// \file Methods common to all machine operands.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/MachineOperand.h"
15 #include "llvm/Analysis/Loads.h"
16 #include "llvm/CodeGen/MIRPrinter.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineJumpTableInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/TargetInstrInfo.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/IRPrintingPasses.h"
24 #include "llvm/IR/ModuleSlotTracker.h"
25 #include "llvm/Target/TargetIntrinsicInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 
28 using namespace llvm;
29 
30 static cl::opt<int>
31     PrintRegMaskNumRegs("print-regmask-num-regs",
32                         cl::desc("Number of registers to limit to when "
33                                  "printing regmask operands in IR dumps. "
34                                  "unlimited = -1"),
35                         cl::init(32), cl::Hidden);
36 
37 static const MachineFunction *getMFIfAvailable(const MachineOperand &MO) {
38   if (const MachineInstr *MI = MO.getParent())
39     if (const MachineBasicBlock *MBB = MI->getParent())
40       if (const MachineFunction *MF = MBB->getParent())
41         return MF;
42   return nullptr;
43 }
44 static MachineFunction *getMFIfAvailable(MachineOperand &MO) {
45   return const_cast<MachineFunction *>(
46       getMFIfAvailable(const_cast<const MachineOperand &>(MO)));
47 }
48 
49 void MachineOperand::setReg(unsigned Reg) {
50   if (getReg() == Reg)
51     return; // No change.
52 
53   // Otherwise, we have to change the register.  If this operand is embedded
54   // into a machine function, we need to update the old and new register's
55   // use/def lists.
56   if (MachineFunction *MF = getMFIfAvailable(*this)) {
57     MachineRegisterInfo &MRI = MF->getRegInfo();
58     MRI.removeRegOperandFromUseList(this);
59     SmallContents.RegNo = Reg;
60     MRI.addRegOperandToUseList(this);
61     return;
62   }
63 
64   // Otherwise, just change the register, no problem.  :)
65   SmallContents.RegNo = Reg;
66 }
67 
68 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
69                                   const TargetRegisterInfo &TRI) {
70   assert(TargetRegisterInfo::isVirtualRegister(Reg));
71   if (SubIdx && getSubReg())
72     SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
73   setReg(Reg);
74   if (SubIdx)
75     setSubReg(SubIdx);
76 }
77 
78 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
79   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
80   if (getSubReg()) {
81     Reg = TRI.getSubReg(Reg, getSubReg());
82     // Note that getSubReg() may return 0 if the sub-register doesn't exist.
83     // That won't happen in legal code.
84     setSubReg(0);
85     if (isDef())
86       setIsUndef(false);
87   }
88   setReg(Reg);
89 }
90 
91 /// Change a def to a use, or a use to a def.
92 void MachineOperand::setIsDef(bool Val) {
93   assert(isReg() && "Wrong MachineOperand accessor");
94   assert((!Val || !isDebug()) && "Marking a debug operation as def");
95   if (IsDef == Val)
96     return;
97   assert(!IsDeadOrKill && "Changing def/use with dead/kill set not supported");
98   // MRI may keep uses and defs in different list positions.
99   if (MachineFunction *MF = getMFIfAvailable(*this)) {
100     MachineRegisterInfo &MRI = MF->getRegInfo();
101     MRI.removeRegOperandFromUseList(this);
102     IsDef = Val;
103     MRI.addRegOperandToUseList(this);
104     return;
105   }
106   IsDef = Val;
107 }
108 
109 bool MachineOperand::isRenamable() const {
110   assert(isReg() && "Wrong MachineOperand accessor");
111   assert(TargetRegisterInfo::isPhysicalRegister(getReg()) &&
112          "isRenamable should only be checked on physical registers");
113   return IsRenamable;
114 }
115 
116 void MachineOperand::setIsRenamable(bool Val) {
117   assert(isReg() && "Wrong MachineOperand accessor");
118   assert(TargetRegisterInfo::isPhysicalRegister(getReg()) &&
119          "setIsRenamable should only be called on physical registers");
120   if (const MachineInstr *MI = getParent())
121     if ((isDef() && MI->hasExtraDefRegAllocReq()) ||
122         (isUse() && MI->hasExtraSrcRegAllocReq()))
123       assert(!Val && "isRenamable should be false for "
124                      "hasExtraDefRegAllocReq/hasExtraSrcRegAllocReq opcodes");
125   IsRenamable = Val;
126 }
127 
128 void MachineOperand::setIsRenamableIfNoExtraRegAllocReq() {
129   if (const MachineInstr *MI = getParent())
130     if ((isDef() && MI->hasExtraDefRegAllocReq()) ||
131         (isUse() && MI->hasExtraSrcRegAllocReq()))
132       return;
133 
134   setIsRenamable(true);
135 }
136 
137 // If this operand is currently a register operand, and if this is in a
138 // function, deregister the operand from the register's use/def list.
139 void MachineOperand::removeRegFromUses() {
140   if (!isReg() || !isOnRegUseList())
141     return;
142 
143   if (MachineFunction *MF = getMFIfAvailable(*this))
144     MF->getRegInfo().removeRegOperandFromUseList(this);
145 }
146 
147 /// ChangeToImmediate - Replace this operand with a new immediate operand of
148 /// the specified value.  If an operand is known to be an immediate already,
149 /// the setImm method should be used.
150 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
151   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
152 
153   removeRegFromUses();
154 
155   OpKind = MO_Immediate;
156   Contents.ImmVal = ImmVal;
157 }
158 
159 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
160   assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
161 
162   removeRegFromUses();
163 
164   OpKind = MO_FPImmediate;
165   Contents.CFP = FPImm;
166 }
167 
168 void MachineOperand::ChangeToES(const char *SymName,
169                                 unsigned char TargetFlags) {
170   assert((!isReg() || !isTied()) &&
171          "Cannot change a tied operand into an external symbol");
172 
173   removeRegFromUses();
174 
175   OpKind = MO_ExternalSymbol;
176   Contents.OffsetedInfo.Val.SymbolName = SymName;
177   setOffset(0); // Offset is always 0.
178   setTargetFlags(TargetFlags);
179 }
180 
181 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
182   assert((!isReg() || !isTied()) &&
183          "Cannot change a tied operand into an MCSymbol");
184 
185   removeRegFromUses();
186 
187   OpKind = MO_MCSymbol;
188   Contents.Sym = Sym;
189 }
190 
191 void MachineOperand::ChangeToFrameIndex(int Idx) {
192   assert((!isReg() || !isTied()) &&
193          "Cannot change a tied operand into a FrameIndex");
194 
195   removeRegFromUses();
196 
197   OpKind = MO_FrameIndex;
198   setIndex(Idx);
199 }
200 
201 void MachineOperand::ChangeToTargetIndex(unsigned Idx, int64_t Offset,
202                                          unsigned char TargetFlags) {
203   assert((!isReg() || !isTied()) &&
204          "Cannot change a tied operand into a FrameIndex");
205 
206   removeRegFromUses();
207 
208   OpKind = MO_TargetIndex;
209   setIndex(Idx);
210   setOffset(Offset);
211   setTargetFlags(TargetFlags);
212 }
213 
214 /// ChangeToRegister - Replace this operand with a new register operand of
215 /// the specified value.  If an operand is known to be an register already,
216 /// the setReg method should be used.
217 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
218                                       bool isKill, bool isDead, bool isUndef,
219                                       bool isDebug) {
220   MachineRegisterInfo *RegInfo = nullptr;
221   if (MachineFunction *MF = getMFIfAvailable(*this))
222     RegInfo = &MF->getRegInfo();
223   // If this operand is already a register operand, remove it from the
224   // register's use/def lists.
225   bool WasReg = isReg();
226   if (RegInfo && WasReg)
227     RegInfo->removeRegOperandFromUseList(this);
228 
229   // Change this to a register and set the reg#.
230   assert(!(isDead && !isDef) && "Dead flag on non-def");
231   assert(!(isKill && isDef) && "Kill flag on def");
232   OpKind = MO_Register;
233   SmallContents.RegNo = Reg;
234   SubReg_TargetFlags = 0;
235   IsDef = isDef;
236   IsImp = isImp;
237   IsDeadOrKill = isKill | isDead;
238   IsRenamable = false;
239   IsUndef = isUndef;
240   IsInternalRead = false;
241   IsEarlyClobber = false;
242   IsDebug = isDebug;
243   // Ensure isOnRegUseList() returns false.
244   Contents.Reg.Prev = nullptr;
245   // Preserve the tie when the operand was already a register.
246   if (!WasReg)
247     TiedTo = 0;
248 
249   // If this operand is embedded in a function, add the operand to the
250   // register's use/def list.
251   if (RegInfo)
252     RegInfo->addRegOperandToUseList(this);
253 }
254 
255 /// isIdenticalTo - Return true if this operand is identical to the specified
256 /// operand. Note that this should stay in sync with the hash_value overload
257 /// below.
258 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
259   if (getType() != Other.getType() ||
260       getTargetFlags() != Other.getTargetFlags())
261     return false;
262 
263   switch (getType()) {
264   case MachineOperand::MO_Register:
265     return getReg() == Other.getReg() && isDef() == Other.isDef() &&
266            getSubReg() == Other.getSubReg();
267   case MachineOperand::MO_Immediate:
268     return getImm() == Other.getImm();
269   case MachineOperand::MO_CImmediate:
270     return getCImm() == Other.getCImm();
271   case MachineOperand::MO_FPImmediate:
272     return getFPImm() == Other.getFPImm();
273   case MachineOperand::MO_MachineBasicBlock:
274     return getMBB() == Other.getMBB();
275   case MachineOperand::MO_FrameIndex:
276     return getIndex() == Other.getIndex();
277   case MachineOperand::MO_ConstantPoolIndex:
278   case MachineOperand::MO_TargetIndex:
279     return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
280   case MachineOperand::MO_JumpTableIndex:
281     return getIndex() == Other.getIndex();
282   case MachineOperand::MO_GlobalAddress:
283     return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
284   case MachineOperand::MO_ExternalSymbol:
285     return strcmp(getSymbolName(), Other.getSymbolName()) == 0 &&
286            getOffset() == Other.getOffset();
287   case MachineOperand::MO_BlockAddress:
288     return getBlockAddress() == Other.getBlockAddress() &&
289            getOffset() == Other.getOffset();
290   case MachineOperand::MO_RegisterMask:
291   case MachineOperand::MO_RegisterLiveOut: {
292     // Shallow compare of the two RegMasks
293     const uint32_t *RegMask = getRegMask();
294     const uint32_t *OtherRegMask = Other.getRegMask();
295     if (RegMask == OtherRegMask)
296       return true;
297 
298     if (const MachineFunction *MF = getMFIfAvailable(*this)) {
299       // Calculate the size of the RegMask
300       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
301       unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
302 
303       // Deep compare of the two RegMasks
304       return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
305     }
306     // We don't know the size of the RegMask, so we can't deep compare the two
307     // reg masks.
308     return false;
309   }
310   case MachineOperand::MO_MCSymbol:
311     return getMCSymbol() == Other.getMCSymbol();
312   case MachineOperand::MO_CFIIndex:
313     return getCFIIndex() == Other.getCFIIndex();
314   case MachineOperand::MO_Metadata:
315     return getMetadata() == Other.getMetadata();
316   case MachineOperand::MO_IntrinsicID:
317     return getIntrinsicID() == Other.getIntrinsicID();
318   case MachineOperand::MO_Predicate:
319     return getPredicate() == Other.getPredicate();
320   }
321   llvm_unreachable("Invalid machine operand type");
322 }
323 
324 // Note: this must stay exactly in sync with isIdenticalTo above.
325 hash_code llvm::hash_value(const MachineOperand &MO) {
326   switch (MO.getType()) {
327   case MachineOperand::MO_Register:
328     // Register operands don't have target flags.
329     return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
330   case MachineOperand::MO_Immediate:
331     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
332   case MachineOperand::MO_CImmediate:
333     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
334   case MachineOperand::MO_FPImmediate:
335     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
336   case MachineOperand::MO_MachineBasicBlock:
337     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
338   case MachineOperand::MO_FrameIndex:
339     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
340   case MachineOperand::MO_ConstantPoolIndex:
341   case MachineOperand::MO_TargetIndex:
342     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
343                         MO.getOffset());
344   case MachineOperand::MO_JumpTableIndex:
345     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
346   case MachineOperand::MO_ExternalSymbol:
347     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
348                         MO.getSymbolName());
349   case MachineOperand::MO_GlobalAddress:
350     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
351                         MO.getOffset());
352   case MachineOperand::MO_BlockAddress:
353     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getBlockAddress(),
354                         MO.getOffset());
355   case MachineOperand::MO_RegisterMask:
356   case MachineOperand::MO_RegisterLiveOut:
357     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
358   case MachineOperand::MO_Metadata:
359     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
360   case MachineOperand::MO_MCSymbol:
361     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
362   case MachineOperand::MO_CFIIndex:
363     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
364   case MachineOperand::MO_IntrinsicID:
365     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
366   case MachineOperand::MO_Predicate:
367     return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
368   }
369   llvm_unreachable("Invalid machine operand type");
370 }
371 
372 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
373 // it.
374 static void tryToGetTargetInfo(const MachineOperand &MO,
375                                const TargetRegisterInfo *&TRI,
376                                const TargetIntrinsicInfo *&IntrinsicInfo) {
377   if (const MachineFunction *MF = getMFIfAvailable(MO)) {
378     TRI = MF->getSubtarget().getRegisterInfo();
379     IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
380   }
381 }
382 
383 static void printOffset(raw_ostream &OS, int64_t Offset) {
384   if (Offset == 0)
385     return;
386   if (Offset < 0) {
387     OS << " - " << -Offset;
388     return;
389   }
390   OS << " + " << Offset;
391 }
392 
393 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
394   const auto *TII = MF.getSubtarget().getInstrInfo();
395   assert(TII && "expected instruction info");
396   auto Indices = TII->getSerializableTargetIndices();
397   auto Found = find_if(Indices, [&](const std::pair<int, const char *> &I) {
398     return I.first == Index;
399   });
400   if (Found != Indices.end())
401     return Found->second;
402   return nullptr;
403 }
404 
405 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
406   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
407   for (const auto &I : Flags) {
408     if (I.first == TF) {
409       return I.second;
410     }
411   }
412   return nullptr;
413 }
414 
415 void MachineOperand::printSubregIdx(raw_ostream &OS, uint64_t Index,
416                                     const TargetRegisterInfo *TRI) {
417   OS << "%subreg.";
418   if (TRI)
419     OS << TRI->getSubRegIndexName(Index);
420   else
421     OS << Index;
422 }
423 
424 void MachineOperand::printTargetFlags(raw_ostream &OS,
425                                       const MachineOperand &Op) {
426   if (!Op.getTargetFlags())
427     return;
428   const MachineFunction *MF = getMFIfAvailable(Op);
429   if (!MF)
430     return;
431 
432   const auto *TII = MF->getSubtarget().getInstrInfo();
433   assert(TII && "expected instruction info");
434   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
435   OS << "target-flags(";
436   const bool HasDirectFlags = Flags.first;
437   const bool HasBitmaskFlags = Flags.second;
438   if (!HasDirectFlags && !HasBitmaskFlags) {
439     OS << "<unknown>) ";
440     return;
441   }
442   if (HasDirectFlags) {
443     if (const auto *Name = getTargetFlagName(TII, Flags.first))
444       OS << Name;
445     else
446       OS << "<unknown target flag>";
447   }
448   if (!HasBitmaskFlags) {
449     OS << ") ";
450     return;
451   }
452   bool IsCommaNeeded = HasDirectFlags;
453   unsigned BitMask = Flags.second;
454   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
455   for (const auto &Mask : BitMasks) {
456     // Check if the flag's bitmask has the bits of the current mask set.
457     if ((BitMask & Mask.first) == Mask.first) {
458       if (IsCommaNeeded)
459         OS << ", ";
460       IsCommaNeeded = true;
461       OS << Mask.second;
462       // Clear the bits which were serialized from the flag's bitmask.
463       BitMask &= ~(Mask.first);
464     }
465   }
466   if (BitMask) {
467     // When the resulting flag's bitmask isn't zero, we know that we didn't
468     // serialize all of the bit flags.
469     if (IsCommaNeeded)
470       OS << ", ";
471     OS << "<unknown bitmask target flag>";
472   }
473   OS << ") ";
474 }
475 
476 void MachineOperand::printSymbol(raw_ostream &OS, MCSymbol &Sym) {
477   OS << "<mcsymbol " << Sym << ">";
478 }
479 
480 void MachineOperand::printStackObjectReference(raw_ostream &OS,
481                                                unsigned FrameIndex,
482                                                bool IsFixed, StringRef Name) {
483   if (IsFixed) {
484     OS << "%fixed-stack." << FrameIndex;
485     return;
486   }
487 
488   OS << "%stack." << FrameIndex;
489   if (!Name.empty())
490     OS << '.' << Name;
491 }
492 
493 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
494                            const TargetIntrinsicInfo *IntrinsicInfo) const {
495   tryToGetTargetInfo(*this, TRI, IntrinsicInfo);
496   ModuleSlotTracker DummyMST(nullptr);
497   print(OS, DummyMST, LLT{}, /*PrintDef=*/false,
498         /*ShouldPrintRegisterTies=*/true,
499         /*TiedOperandIdx=*/0, TRI, IntrinsicInfo);
500 }
501 
502 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
503                            LLT TypeToPrint, bool PrintDef,
504                            bool ShouldPrintRegisterTies,
505                            unsigned TiedOperandIdx,
506                            const TargetRegisterInfo *TRI,
507                            const TargetIntrinsicInfo *IntrinsicInfo) const {
508   printTargetFlags(OS, *this);
509   switch (getType()) {
510   case MachineOperand::MO_Register: {
511     unsigned Reg = getReg();
512     if (isImplicit())
513       OS << (isDef() ? "implicit-def " : "implicit ");
514     else if (PrintDef && isDef())
515       // Print the 'def' flag only when the operand is defined after '='.
516       OS << "def ";
517     if (isInternalRead())
518       OS << "internal ";
519     if (isDead())
520       OS << "dead ";
521     if (isKill())
522       OS << "killed ";
523     if (isUndef())
524       OS << "undef ";
525     if (isEarlyClobber())
526       OS << "early-clobber ";
527     if (isDebug())
528       OS << "debug-use ";
529     if (TargetRegisterInfo::isPhysicalRegister(getReg()) && isRenamable())
530       OS << "renamable ";
531     OS << printReg(Reg, TRI);
532     // Print the sub register.
533     if (unsigned SubReg = getSubReg()) {
534       if (TRI)
535         OS << '.' << TRI->getSubRegIndexName(SubReg);
536       else
537         OS << ".subreg" << SubReg;
538     }
539     // Print the register class / bank.
540     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
541       if (const MachineFunction *MF = getMFIfAvailable(*this)) {
542         const MachineRegisterInfo &MRI = MF->getRegInfo();
543         if (!PrintDef || MRI.def_empty(Reg)) {
544           OS << ':';
545           OS << printRegClassOrBank(Reg, MRI, TRI);
546         }
547       }
548     }
549     // Print ties.
550     if (ShouldPrintRegisterTies && isTied() && !isDef())
551       OS << "(tied-def " << TiedOperandIdx << ")";
552     // Print types.
553     if (TypeToPrint.isValid())
554       OS << '(' << TypeToPrint << ')';
555     break;
556   }
557   case MachineOperand::MO_Immediate:
558     OS << getImm();
559     break;
560   case MachineOperand::MO_CImmediate:
561     getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
562     break;
563   case MachineOperand::MO_FPImmediate:
564     if (getFPImm()->getType()->isFloatTy()) {
565       OS << getFPImm()->getValueAPF().convertToFloat();
566     } else if (getFPImm()->getType()->isHalfTy()) {
567       APFloat APF = getFPImm()->getValueAPF();
568       bool Unused;
569       APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &Unused);
570       OS << "half " << APF.convertToFloat();
571     } else if (getFPImm()->getType()->isFP128Ty()) {
572       APFloat APF = getFPImm()->getValueAPF();
573       SmallString<16> Str;
574       getFPImm()->getValueAPF().toString(Str);
575       OS << "quad " << Str;
576     } else if (getFPImm()->getType()->isX86_FP80Ty()) {
577       APFloat APF = getFPImm()->getValueAPF();
578       OS << "x86_fp80 0xK";
579       APInt API = APF.bitcastToAPInt();
580       OS << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
581                                  /*Upper=*/true);
582       OS << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
583                                  /*Upper=*/true);
584     } else {
585       OS << getFPImm()->getValueAPF().convertToDouble();
586     }
587     break;
588   case MachineOperand::MO_MachineBasicBlock:
589     OS << printMBBReference(*getMBB());
590     break;
591   case MachineOperand::MO_FrameIndex: {
592     int FrameIndex = getIndex();
593     bool IsFixed = false;
594     StringRef Name;
595     if (const MachineFunction *MF = getMFIfAvailable(*this)) {
596       const MachineFrameInfo &MFI = MF->getFrameInfo();
597       IsFixed = MFI.isFixedObjectIndex(FrameIndex);
598       if (const AllocaInst *Alloca = MFI.getObjectAllocation(FrameIndex))
599         if (Alloca->hasName())
600           Name = Alloca->getName();
601       if (IsFixed)
602         FrameIndex -= MFI.getObjectIndexBegin();
603     }
604     printStackObjectReference(OS, FrameIndex, IsFixed, Name);
605     break;
606   }
607   case MachineOperand::MO_ConstantPoolIndex:
608     OS << "%const." << getIndex();
609     printOffset(OS, getOffset());
610     break;
611   case MachineOperand::MO_TargetIndex: {
612     OS << "target-index(";
613     const char *Name = "<unknown>";
614     if (const MachineFunction *MF = getMFIfAvailable(*this))
615       if (const auto *TargetIndexName = getTargetIndexName(*MF, getIndex()))
616         Name = TargetIndexName;
617     OS << Name << ')';
618     printOffset(OS, getOffset());
619     break;
620   }
621   case MachineOperand::MO_JumpTableIndex:
622     OS << printJumpTableEntryReference(getIndex());
623     break;
624   case MachineOperand::MO_GlobalAddress:
625     getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
626     printOffset(OS, getOffset());
627     break;
628   case MachineOperand::MO_ExternalSymbol: {
629     StringRef Name = getSymbolName();
630     OS << '$';
631     if (Name.empty()) {
632       OS << "\"\"";
633     } else {
634       printLLVMNameWithoutPrefix(OS, Name);
635     }
636     printOffset(OS, getOffset());
637     break;
638   }
639   case MachineOperand::MO_BlockAddress:
640     OS << '<';
641     getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
642     if (getOffset())
643       OS << "+" << getOffset();
644     OS << '>';
645     break;
646   case MachineOperand::MO_RegisterMask: {
647     OS << "<regmask";
648     if (TRI) {
649       unsigned NumRegsInMask = 0;
650       unsigned NumRegsEmitted = 0;
651       for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
652         unsigned MaskWord = i / 32;
653         unsigned MaskBit = i % 32;
654         if (getRegMask()[MaskWord] & (1 << MaskBit)) {
655           if (PrintRegMaskNumRegs < 0 ||
656               NumRegsEmitted <= static_cast<unsigned>(PrintRegMaskNumRegs)) {
657             OS << " " << printReg(i, TRI);
658             NumRegsEmitted++;
659           }
660           NumRegsInMask++;
661         }
662       }
663       if (NumRegsEmitted != NumRegsInMask)
664         OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
665     } else {
666       OS << " ...";
667     }
668     OS << ">";
669     break;
670   }
671   case MachineOperand::MO_RegisterLiveOut: {
672     const uint32_t *RegMask = getRegLiveOut();
673     OS << "liveout(";
674     if (!TRI) {
675       OS << "<unknown>";
676     } else {
677       bool IsCommaNeeded = false;
678       for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
679         if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
680           if (IsCommaNeeded)
681             OS << ", ";
682           OS << printReg(Reg, TRI);
683           IsCommaNeeded = true;
684         }
685       }
686     }
687     OS << ")";
688     break;
689   }
690   case MachineOperand::MO_Metadata:
691     getMetadata()->printAsOperand(OS, MST);
692     break;
693   case MachineOperand::MO_MCSymbol:
694     printSymbol(OS, *getMCSymbol());
695     break;
696   case MachineOperand::MO_CFIIndex:
697     OS << "<call frame instruction>";
698     break;
699   case MachineOperand::MO_IntrinsicID: {
700     Intrinsic::ID ID = getIntrinsicID();
701     if (ID < Intrinsic::num_intrinsics)
702       OS << "<intrinsic:@" << Intrinsic::getName(ID, None) << '>';
703     else if (IntrinsicInfo)
704       OS << "<intrinsic:@" << IntrinsicInfo->getName(ID) << '>';
705     else
706       OS << "<intrinsic:" << ID << '>';
707     break;
708   }
709   case MachineOperand::MO_Predicate: {
710     auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
711     OS << '<' << (CmpInst::isIntPredicate(Pred) ? "intpred" : "floatpred")
712        << CmpInst::getPredicateName(Pred) << '>';
713     break;
714   }
715   }
716 }
717 
718 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
719 LLVM_DUMP_METHOD void MachineOperand::dump() const { dbgs() << *this << '\n'; }
720 #endif
721 
722 //===----------------------------------------------------------------------===//
723 // MachineMemOperand Implementation
724 //===----------------------------------------------------------------------===//
725 
726 /// getAddrSpace - Return the LLVM IR address space number that this pointer
727 /// points into.
728 unsigned MachinePointerInfo::getAddrSpace() const { return AddrSpace; }
729 
730 /// isDereferenceable - Return true if V is always dereferenceable for
731 /// Offset + Size byte.
732 bool MachinePointerInfo::isDereferenceable(unsigned Size, LLVMContext &C,
733                                            const DataLayout &DL) const {
734   if (!V.is<const Value *>())
735     return false;
736 
737   const Value *BasePtr = V.get<const Value *>();
738   if (BasePtr == nullptr)
739     return false;
740 
741   return isDereferenceableAndAlignedPointer(
742       BasePtr, 1, APInt(DL.getPointerSizeInBits(), Offset + Size), DL);
743 }
744 
745 /// getConstantPool - Return a MachinePointerInfo record that refers to the
746 /// constant pool.
747 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
748   return MachinePointerInfo(MF.getPSVManager().getConstantPool());
749 }
750 
751 /// getFixedStack - Return a MachinePointerInfo record that refers to the
752 /// the specified FrameIndex.
753 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
754                                                      int FI, int64_t Offset) {
755   return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
756 }
757 
758 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
759   return MachinePointerInfo(MF.getPSVManager().getJumpTable());
760 }
761 
762 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
763   return MachinePointerInfo(MF.getPSVManager().getGOT());
764 }
765 
766 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
767                                                 int64_t Offset, uint8_t ID) {
768   return MachinePointerInfo(MF.getPSVManager().getStack(), Offset, ID);
769 }
770 
771 MachinePointerInfo MachinePointerInfo::getUnknownStack(MachineFunction &MF) {
772   return MachinePointerInfo(MF.getDataLayout().getAllocaAddrSpace());
773 }
774 
775 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
776                                      uint64_t s, unsigned int a,
777                                      const AAMDNodes &AAInfo,
778                                      const MDNode *Ranges, SyncScope::ID SSID,
779                                      AtomicOrdering Ordering,
780                                      AtomicOrdering FailureOrdering)
781     : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
782       AAInfo(AAInfo), Ranges(Ranges) {
783   assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue *>() ||
784           isa<PointerType>(PtrInfo.V.get<const Value *>()->getType())) &&
785          "invalid pointer value");
786   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
787   assert((isLoad() || isStore()) && "Not a load/store!");
788 
789   AtomicInfo.SSID = static_cast<unsigned>(SSID);
790   assert(getSyncScopeID() == SSID && "Value truncated");
791   AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
792   assert(getOrdering() == Ordering && "Value truncated");
793   AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
794   assert(getFailureOrdering() == FailureOrdering && "Value truncated");
795 }
796 
797 /// Profile - Gather unique data for the object.
798 ///
799 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
800   ID.AddInteger(getOffset());
801   ID.AddInteger(Size);
802   ID.AddPointer(getOpaqueValue());
803   ID.AddInteger(getFlags());
804   ID.AddInteger(getBaseAlignment());
805 }
806 
807 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
808   // The Value and Offset may differ due to CSE. But the flags and size
809   // should be the same.
810   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
811   assert(MMO->getSize() == getSize() && "Size mismatch!");
812 
813   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
814     // Update the alignment value.
815     BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
816     // Also update the base and offset, because the new alignment may
817     // not be applicable with the old ones.
818     PtrInfo = MMO->PtrInfo;
819   }
820 }
821 
822 /// getAlignment - Return the minimum known alignment in bytes of the
823 /// actual memory reference.
824 uint64_t MachineMemOperand::getAlignment() const {
825   return MinAlign(getBaseAlignment(), getOffset());
826 }
827 
828 void MachineMemOperand::print(raw_ostream &OS) const {
829   ModuleSlotTracker DummyMST(nullptr);
830   print(OS, DummyMST);
831 }
832 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
833   assert((isLoad() || isStore()) && "SV has to be a load, store or both.");
834 
835   if (isVolatile())
836     OS << "Volatile ";
837 
838   if (isLoad())
839     OS << "LD";
840   if (isStore())
841     OS << "ST";
842   OS << getSize();
843 
844   // Print the address information.
845   OS << "[";
846   if (const Value *V = getValue())
847     V->printAsOperand(OS, /*PrintType=*/false, MST);
848   else if (const PseudoSourceValue *PSV = getPseudoValue())
849     PSV->printCustom(OS);
850   else
851     OS << "<unknown>";
852 
853   unsigned AS = getAddrSpace();
854   if (AS != 0)
855     OS << "(addrspace=" << AS << ')';
856 
857   // If the alignment of the memory reference itself differs from the alignment
858   // of the base pointer, print the base alignment explicitly, next to the base
859   // pointer.
860   if (getBaseAlignment() != getAlignment())
861     OS << "(align=" << getBaseAlignment() << ")";
862 
863   if (getOffset() != 0)
864     OS << "+" << getOffset();
865   OS << "]";
866 
867   // Print the alignment of the reference.
868   if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
869     OS << "(align=" << getAlignment() << ")";
870 
871   // Print TBAA info.
872   if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
873     OS << "(tbaa=";
874     if (TBAAInfo->getNumOperands() > 0)
875       TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
876     else
877       OS << "<unknown>";
878     OS << ")";
879   }
880 
881   // Print AA scope info.
882   if (const MDNode *ScopeInfo = getAAInfo().Scope) {
883     OS << "(alias.scope=";
884     if (ScopeInfo->getNumOperands() > 0)
885       for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
886         ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
887         if (i != ie - 1)
888           OS << ",";
889       }
890     else
891       OS << "<unknown>";
892     OS << ")";
893   }
894 
895   // Print AA noalias scope info.
896   if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
897     OS << "(noalias=";
898     if (NoAliasInfo->getNumOperands() > 0)
899       for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
900         NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
901         if (i != ie - 1)
902           OS << ",";
903       }
904     else
905       OS << "<unknown>";
906     OS << ")";
907   }
908 
909   if (const MDNode *Ranges = getRanges()) {
910     unsigned NumRanges = Ranges->getNumOperands();
911     if (NumRanges != 0) {
912       OS << "(ranges=";
913 
914       for (unsigned I = 0; I != NumRanges; ++I) {
915         Ranges->getOperand(I)->printAsOperand(OS, MST);
916         if (I != NumRanges - 1)
917           OS << ',';
918       }
919 
920       OS << ')';
921     }
922   }
923 
924   if (isNonTemporal())
925     OS << "(nontemporal)";
926   if (isDereferenceable())
927     OS << "(dereferenceable)";
928   if (isInvariant())
929     OS << "(invariant)";
930   if (getFlags() & MOTargetFlag1)
931     OS << "(flag1)";
932   if (getFlags() & MOTargetFlag2)
933     OS << "(flag2)";
934   if (getFlags() & MOTargetFlag3)
935     OS << "(flag3)";
936 }
937