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