xref: /llvm-project/llvm/lib/CodeGen/MachineOperand.cpp (revision cb2683d46a5287b29b2494348f1921f7caed5c68)
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 const char *getTargetIndexName(const MachineFunction &MF, int Index) {
384   const auto *TII = MF.getSubtarget().getInstrInfo();
385   assert(TII && "expected instruction info");
386   auto Indices = TII->getSerializableTargetIndices();
387   auto Found = find_if(Indices, [&](const std::pair<int, const char *> &I) {
388     return I.first == Index;
389   });
390   if (Found != Indices.end())
391     return Found->second;
392   return nullptr;
393 }
394 
395 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
396   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
397   for (const auto &I : Flags) {
398     if (I.first == TF) {
399       return I.second;
400     }
401   }
402   return nullptr;
403 }
404 
405 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
406                              const TargetRegisterInfo *TRI) {
407   if (!TRI) {
408     OS << "%dwarfreg." << DwarfReg;
409     return;
410   }
411 
412   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
413   if (Reg == -1) {
414     OS << "<badreg>";
415     return;
416   }
417   OS << printReg(Reg, TRI);
418 }
419 
420 void MachineOperand::printSubregIdx(raw_ostream &OS, uint64_t Index,
421                                     const TargetRegisterInfo *TRI) {
422   OS << "%subreg.";
423   if (TRI)
424     OS << TRI->getSubRegIndexName(Index);
425   else
426     OS << Index;
427 }
428 
429 void MachineOperand::printTargetFlags(raw_ostream &OS,
430                                       const MachineOperand &Op) {
431   if (!Op.getTargetFlags())
432     return;
433   const MachineFunction *MF = getMFIfAvailable(Op);
434   if (!MF)
435     return;
436 
437   const auto *TII = MF->getSubtarget().getInstrInfo();
438   assert(TII && "expected instruction info");
439   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
440   OS << "target-flags(";
441   const bool HasDirectFlags = Flags.first;
442   const bool HasBitmaskFlags = Flags.second;
443   if (!HasDirectFlags && !HasBitmaskFlags) {
444     OS << "<unknown>) ";
445     return;
446   }
447   if (HasDirectFlags) {
448     if (const auto *Name = getTargetFlagName(TII, Flags.first))
449       OS << Name;
450     else
451       OS << "<unknown target flag>";
452   }
453   if (!HasBitmaskFlags) {
454     OS << ") ";
455     return;
456   }
457   bool IsCommaNeeded = HasDirectFlags;
458   unsigned BitMask = Flags.second;
459   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
460   for (const auto &Mask : BitMasks) {
461     // Check if the flag's bitmask has the bits of the current mask set.
462     if ((BitMask & Mask.first) == Mask.first) {
463       if (IsCommaNeeded)
464         OS << ", ";
465       IsCommaNeeded = true;
466       OS << Mask.second;
467       // Clear the bits which were serialized from the flag's bitmask.
468       BitMask &= ~(Mask.first);
469     }
470   }
471   if (BitMask) {
472     // When the resulting flag's bitmask isn't zero, we know that we didn't
473     // serialize all of the bit flags.
474     if (IsCommaNeeded)
475       OS << ", ";
476     OS << "<unknown bitmask target flag>";
477   }
478   OS << ") ";
479 }
480 
481 void MachineOperand::printSymbol(raw_ostream &OS, MCSymbol &Sym) {
482   OS << "<mcsymbol " << Sym << ">";
483 }
484 
485 void MachineOperand::printStackObjectReference(raw_ostream &OS,
486                                                unsigned FrameIndex,
487                                                bool IsFixed, StringRef Name) {
488   if (IsFixed) {
489     OS << "%fixed-stack." << FrameIndex;
490     return;
491   }
492 
493   OS << "%stack." << FrameIndex;
494   if (!Name.empty())
495     OS << '.' << Name;
496 }
497 
498 void MachineOperand::printOperandOffset(raw_ostream &OS, int64_t Offset) {
499   if (Offset == 0)
500     return;
501   if (Offset < 0) {
502     OS << " - " << -Offset;
503     return;
504   }
505   OS << " + " << Offset;
506 }
507 
508 static void printCFI(raw_ostream &OS, const MCCFIInstruction &CFI,
509                      const TargetRegisterInfo *TRI) {
510   switch (CFI.getOperation()) {
511   case MCCFIInstruction::OpSameValue:
512     OS << "same_value ";
513     if (MCSymbol *Label = CFI.getLabel())
514       MachineOperand::printSymbol(OS, *Label);
515     printCFIRegister(CFI.getRegister(), OS, TRI);
516     break;
517   case MCCFIInstruction::OpRememberState:
518     OS << "remember_state ";
519     if (MCSymbol *Label = CFI.getLabel())
520       MachineOperand::printSymbol(OS, *Label);
521     break;
522   case MCCFIInstruction::OpRestoreState:
523     OS << "restore_state ";
524     if (MCSymbol *Label = CFI.getLabel())
525       MachineOperand::printSymbol(OS, *Label);
526     break;
527   case MCCFIInstruction::OpOffset:
528     OS << "offset ";
529     if (MCSymbol *Label = CFI.getLabel())
530       MachineOperand::printSymbol(OS, *Label);
531     printCFIRegister(CFI.getRegister(), OS, TRI);
532     OS << ", " << CFI.getOffset();
533     break;
534   case MCCFIInstruction::OpDefCfaRegister:
535     OS << "def_cfa_register ";
536     if (MCSymbol *Label = CFI.getLabel())
537       MachineOperand::printSymbol(OS, *Label);
538     printCFIRegister(CFI.getRegister(), OS, TRI);
539     break;
540   case MCCFIInstruction::OpDefCfaOffset:
541     OS << "def_cfa_offset ";
542     if (MCSymbol *Label = CFI.getLabel())
543       MachineOperand::printSymbol(OS, *Label);
544     OS << CFI.getOffset();
545     break;
546   case MCCFIInstruction::OpDefCfa:
547     OS << "def_cfa ";
548     if (MCSymbol *Label = CFI.getLabel())
549       MachineOperand::printSymbol(OS, *Label);
550     printCFIRegister(CFI.getRegister(), OS, TRI);
551     OS << ", " << CFI.getOffset();
552     break;
553   case MCCFIInstruction::OpRelOffset:
554     OS << "rel_offset ";
555     if (MCSymbol *Label = CFI.getLabel())
556       MachineOperand::printSymbol(OS, *Label);
557     printCFIRegister(CFI.getRegister(), OS, TRI);
558     OS << ", " << CFI.getOffset();
559     break;
560   case MCCFIInstruction::OpAdjustCfaOffset:
561     OS << "adjust_cfa_offset ";
562     if (MCSymbol *Label = CFI.getLabel())
563       MachineOperand::printSymbol(OS, *Label);
564     OS << CFI.getOffset();
565     break;
566   case MCCFIInstruction::OpRestore:
567     OS << "restore ";
568     if (MCSymbol *Label = CFI.getLabel())
569       MachineOperand::printSymbol(OS, *Label);
570     printCFIRegister(CFI.getRegister(), OS, TRI);
571     break;
572   case MCCFIInstruction::OpEscape: {
573     OS << "escape ";
574     if (MCSymbol *Label = CFI.getLabel())
575       MachineOperand::printSymbol(OS, *Label);
576     if (!CFI.getValues().empty()) {
577       size_t e = CFI.getValues().size() - 1;
578       for (size_t i = 0; i < e; ++i)
579         OS << format("0x%02x", uint8_t(CFI.getValues()[i])) << ", ";
580       OS << format("0x%02x", uint8_t(CFI.getValues()[e])) << ", ";
581     }
582     break;
583   }
584   case MCCFIInstruction::OpUndefined:
585     OS << "undefined ";
586     if (MCSymbol *Label = CFI.getLabel())
587       MachineOperand::printSymbol(OS, *Label);
588     printCFIRegister(CFI.getRegister(), OS, TRI);
589     break;
590   case MCCFIInstruction::OpRegister:
591     OS << "register ";
592     if (MCSymbol *Label = CFI.getLabel())
593       MachineOperand::printSymbol(OS, *Label);
594     printCFIRegister(CFI.getRegister(), OS, TRI);
595     OS << ", ";
596     printCFIRegister(CFI.getRegister2(), OS, TRI);
597     break;
598   case MCCFIInstruction::OpWindowSave:
599     OS << "window_save ";
600     if (MCSymbol *Label = CFI.getLabel())
601       MachineOperand::printSymbol(OS, *Label);
602     break;
603   default:
604     // TODO: Print the other CFI Operations.
605     OS << "<unserializable cfi directive>";
606     break;
607   }
608 }
609 
610 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
611                            const TargetIntrinsicInfo *IntrinsicInfo) const {
612   tryToGetTargetInfo(*this, TRI, IntrinsicInfo);
613   ModuleSlotTracker DummyMST(nullptr);
614   print(OS, DummyMST, LLT{}, /*PrintDef=*/false,
615         /*ShouldPrintRegisterTies=*/true,
616         /*TiedOperandIdx=*/0, TRI, IntrinsicInfo);
617 }
618 
619 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
620                            LLT TypeToPrint, bool PrintDef,
621                            bool ShouldPrintRegisterTies,
622                            unsigned TiedOperandIdx,
623                            const TargetRegisterInfo *TRI,
624                            const TargetIntrinsicInfo *IntrinsicInfo) const {
625   printTargetFlags(OS, *this);
626   switch (getType()) {
627   case MachineOperand::MO_Register: {
628     unsigned Reg = getReg();
629     if (isImplicit())
630       OS << (isDef() ? "implicit-def " : "implicit ");
631     else if (PrintDef && isDef())
632       // Print the 'def' flag only when the operand is defined after '='.
633       OS << "def ";
634     if (isInternalRead())
635       OS << "internal ";
636     if (isDead())
637       OS << "dead ";
638     if (isKill())
639       OS << "killed ";
640     if (isUndef())
641       OS << "undef ";
642     if (isEarlyClobber())
643       OS << "early-clobber ";
644     if (isDebug())
645       OS << "debug-use ";
646     if (TargetRegisterInfo::isPhysicalRegister(getReg()) && isRenamable())
647       OS << "renamable ";
648     OS << printReg(Reg, TRI);
649     // Print the sub register.
650     if (unsigned SubReg = getSubReg()) {
651       if (TRI)
652         OS << '.' << TRI->getSubRegIndexName(SubReg);
653       else
654         OS << ".subreg" << SubReg;
655     }
656     // Print the register class / bank.
657     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
658       if (const MachineFunction *MF = getMFIfAvailable(*this)) {
659         const MachineRegisterInfo &MRI = MF->getRegInfo();
660         if (!PrintDef || MRI.def_empty(Reg)) {
661           OS << ':';
662           OS << printRegClassOrBank(Reg, MRI, TRI);
663         }
664       }
665     }
666     // Print ties.
667     if (ShouldPrintRegisterTies && isTied() && !isDef())
668       OS << "(tied-def " << TiedOperandIdx << ")";
669     // Print types.
670     if (TypeToPrint.isValid())
671       OS << '(' << TypeToPrint << ')';
672     break;
673   }
674   case MachineOperand::MO_Immediate:
675     OS << getImm();
676     break;
677   case MachineOperand::MO_CImmediate:
678     getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
679     break;
680   case MachineOperand::MO_FPImmediate:
681     getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
682     break;
683   case MachineOperand::MO_MachineBasicBlock:
684     OS << printMBBReference(*getMBB());
685     break;
686   case MachineOperand::MO_FrameIndex: {
687     int FrameIndex = getIndex();
688     bool IsFixed = false;
689     StringRef Name;
690     if (const MachineFunction *MF = getMFIfAvailable(*this)) {
691       const MachineFrameInfo &MFI = MF->getFrameInfo();
692       IsFixed = MFI.isFixedObjectIndex(FrameIndex);
693       if (const AllocaInst *Alloca = MFI.getObjectAllocation(FrameIndex))
694         if (Alloca->hasName())
695           Name = Alloca->getName();
696       if (IsFixed)
697         FrameIndex -= MFI.getObjectIndexBegin();
698     }
699     printStackObjectReference(OS, FrameIndex, IsFixed, Name);
700     break;
701   }
702   case MachineOperand::MO_ConstantPoolIndex:
703     OS << "%const." << getIndex();
704     printOperandOffset(OS, getOffset());
705     break;
706   case MachineOperand::MO_TargetIndex: {
707     OS << "target-index(";
708     const char *Name = "<unknown>";
709     if (const MachineFunction *MF = getMFIfAvailable(*this))
710       if (const auto *TargetIndexName = getTargetIndexName(*MF, getIndex()))
711         Name = TargetIndexName;
712     OS << Name << ')';
713     printOperandOffset(OS, getOffset());
714     break;
715   }
716   case MachineOperand::MO_JumpTableIndex:
717     OS << printJumpTableEntryReference(getIndex());
718     break;
719   case MachineOperand::MO_GlobalAddress:
720     getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
721     printOperandOffset(OS, getOffset());
722     break;
723   case MachineOperand::MO_ExternalSymbol: {
724     StringRef Name = getSymbolName();
725     OS << '$';
726     if (Name.empty()) {
727       OS << "\"\"";
728     } else {
729       printLLVMNameWithoutPrefix(OS, Name);
730     }
731     printOperandOffset(OS, getOffset());
732     break;
733   }
734   case MachineOperand::MO_BlockAddress:
735     OS << '<';
736     getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
737     if (getOffset())
738       OS << "+" << getOffset();
739     OS << '>';
740     break;
741   case MachineOperand::MO_RegisterMask: {
742     OS << "<regmask";
743     if (TRI) {
744       unsigned NumRegsInMask = 0;
745       unsigned NumRegsEmitted = 0;
746       for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
747         unsigned MaskWord = i / 32;
748         unsigned MaskBit = i % 32;
749         if (getRegMask()[MaskWord] & (1 << MaskBit)) {
750           if (PrintRegMaskNumRegs < 0 ||
751               NumRegsEmitted <= static_cast<unsigned>(PrintRegMaskNumRegs)) {
752             OS << " " << printReg(i, TRI);
753             NumRegsEmitted++;
754           }
755           NumRegsInMask++;
756         }
757       }
758       if (NumRegsEmitted != NumRegsInMask)
759         OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
760     } else {
761       OS << " ...";
762     }
763     OS << ">";
764     break;
765   }
766   case MachineOperand::MO_RegisterLiveOut: {
767     const uint32_t *RegMask = getRegLiveOut();
768     OS << "liveout(";
769     if (!TRI) {
770       OS << "<unknown>";
771     } else {
772       bool IsCommaNeeded = false;
773       for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
774         if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
775           if (IsCommaNeeded)
776             OS << ", ";
777           OS << printReg(Reg, TRI);
778           IsCommaNeeded = true;
779         }
780       }
781     }
782     OS << ")";
783     break;
784   }
785   case MachineOperand::MO_Metadata:
786     getMetadata()->printAsOperand(OS, MST);
787     break;
788   case MachineOperand::MO_MCSymbol:
789     printSymbol(OS, *getMCSymbol());
790     break;
791   case MachineOperand::MO_CFIIndex: {
792     if (const MachineFunction *MF = getMFIfAvailable(*this))
793       printCFI(OS, MF->getFrameInstructions()[getCFIIndex()], TRI);
794     else
795       OS << "<cfi directive>";
796     break;
797   }
798   case MachineOperand::MO_IntrinsicID: {
799     Intrinsic::ID ID = getIntrinsicID();
800     if (ID < Intrinsic::num_intrinsics)
801       OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
802     else if (IntrinsicInfo)
803       OS << "intrinsic(@" << IntrinsicInfo->getName(ID) << ')';
804     else
805       OS << "intrinsic(" << ID << ')';
806     break;
807   }
808   case MachineOperand::MO_Predicate: {
809     auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
810     OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
811        << CmpInst::getPredicateName(Pred) << ')';
812     break;
813   }
814   }
815 }
816 
817 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
818 LLVM_DUMP_METHOD void MachineOperand::dump() const { dbgs() << *this << '\n'; }
819 #endif
820 
821 //===----------------------------------------------------------------------===//
822 // MachineMemOperand Implementation
823 //===----------------------------------------------------------------------===//
824 
825 /// getAddrSpace - Return the LLVM IR address space number that this pointer
826 /// points into.
827 unsigned MachinePointerInfo::getAddrSpace() const { return AddrSpace; }
828 
829 /// isDereferenceable - Return true if V is always dereferenceable for
830 /// Offset + Size byte.
831 bool MachinePointerInfo::isDereferenceable(unsigned Size, LLVMContext &C,
832                                            const DataLayout &DL) const {
833   if (!V.is<const Value *>())
834     return false;
835 
836   const Value *BasePtr = V.get<const Value *>();
837   if (BasePtr == nullptr)
838     return false;
839 
840   return isDereferenceableAndAlignedPointer(
841       BasePtr, 1, APInt(DL.getPointerSizeInBits(), Offset + Size), DL);
842 }
843 
844 /// getConstantPool - Return a MachinePointerInfo record that refers to the
845 /// constant pool.
846 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
847   return MachinePointerInfo(MF.getPSVManager().getConstantPool());
848 }
849 
850 /// getFixedStack - Return a MachinePointerInfo record that refers to the
851 /// the specified FrameIndex.
852 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
853                                                      int FI, int64_t Offset) {
854   return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
855 }
856 
857 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
858   return MachinePointerInfo(MF.getPSVManager().getJumpTable());
859 }
860 
861 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
862   return MachinePointerInfo(MF.getPSVManager().getGOT());
863 }
864 
865 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
866                                                 int64_t Offset, uint8_t ID) {
867   return MachinePointerInfo(MF.getPSVManager().getStack(), Offset, ID);
868 }
869 
870 MachinePointerInfo MachinePointerInfo::getUnknownStack(MachineFunction &MF) {
871   return MachinePointerInfo(MF.getDataLayout().getAllocaAddrSpace());
872 }
873 
874 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
875                                      uint64_t s, unsigned int a,
876                                      const AAMDNodes &AAInfo,
877                                      const MDNode *Ranges, SyncScope::ID SSID,
878                                      AtomicOrdering Ordering,
879                                      AtomicOrdering FailureOrdering)
880     : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
881       AAInfo(AAInfo), Ranges(Ranges) {
882   assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue *>() ||
883           isa<PointerType>(PtrInfo.V.get<const Value *>()->getType())) &&
884          "invalid pointer value");
885   assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
886   assert((isLoad() || isStore()) && "Not a load/store!");
887 
888   AtomicInfo.SSID = static_cast<unsigned>(SSID);
889   assert(getSyncScopeID() == SSID && "Value truncated");
890   AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
891   assert(getOrdering() == Ordering && "Value truncated");
892   AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
893   assert(getFailureOrdering() == FailureOrdering && "Value truncated");
894 }
895 
896 /// Profile - Gather unique data for the object.
897 ///
898 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
899   ID.AddInteger(getOffset());
900   ID.AddInteger(Size);
901   ID.AddPointer(getOpaqueValue());
902   ID.AddInteger(getFlags());
903   ID.AddInteger(getBaseAlignment());
904 }
905 
906 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
907   // The Value and Offset may differ due to CSE. But the flags and size
908   // should be the same.
909   assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
910   assert(MMO->getSize() == getSize() && "Size mismatch!");
911 
912   if (MMO->getBaseAlignment() >= getBaseAlignment()) {
913     // Update the alignment value.
914     BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
915     // Also update the base and offset, because the new alignment may
916     // not be applicable with the old ones.
917     PtrInfo = MMO->PtrInfo;
918   }
919 }
920 
921 /// getAlignment - Return the minimum known alignment in bytes of the
922 /// actual memory reference.
923 uint64_t MachineMemOperand::getAlignment() const {
924   return MinAlign(getBaseAlignment(), getOffset());
925 }
926 
927 void MachineMemOperand::print(raw_ostream &OS) const {
928   ModuleSlotTracker DummyMST(nullptr);
929   print(OS, DummyMST);
930 }
931 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
932   assert((isLoad() || isStore()) && "SV has to be a load, store or both.");
933 
934   if (isVolatile())
935     OS << "Volatile ";
936 
937   if (isLoad())
938     OS << "LD";
939   if (isStore())
940     OS << "ST";
941   OS << getSize();
942 
943   // Print the address information.
944   OS << "[";
945   if (const Value *V = getValue())
946     V->printAsOperand(OS, /*PrintType=*/false, MST);
947   else if (const PseudoSourceValue *PSV = getPseudoValue())
948     PSV->printCustom(OS);
949   else
950     OS << "<unknown>";
951 
952   unsigned AS = getAddrSpace();
953   if (AS != 0)
954     OS << "(addrspace=" << AS << ')';
955 
956   // If the alignment of the memory reference itself differs from the alignment
957   // of the base pointer, print the base alignment explicitly, next to the base
958   // pointer.
959   if (getBaseAlignment() != getAlignment())
960     OS << "(align=" << getBaseAlignment() << ")";
961 
962   if (getOffset() != 0)
963     OS << "+" << getOffset();
964   OS << "]";
965 
966   // Print the alignment of the reference.
967   if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
968     OS << "(align=" << getAlignment() << ")";
969 
970   // Print TBAA info.
971   if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
972     OS << "(tbaa=";
973     if (TBAAInfo->getNumOperands() > 0)
974       TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
975     else
976       OS << "<unknown>";
977     OS << ")";
978   }
979 
980   // Print AA scope info.
981   if (const MDNode *ScopeInfo = getAAInfo().Scope) {
982     OS << "(alias.scope=";
983     if (ScopeInfo->getNumOperands() > 0)
984       for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
985         ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
986         if (i != ie - 1)
987           OS << ",";
988       }
989     else
990       OS << "<unknown>";
991     OS << ")";
992   }
993 
994   // Print AA noalias scope info.
995   if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
996     OS << "(noalias=";
997     if (NoAliasInfo->getNumOperands() > 0)
998       for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
999         NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
1000         if (i != ie - 1)
1001           OS << ",";
1002       }
1003     else
1004       OS << "<unknown>";
1005     OS << ")";
1006   }
1007 
1008   if (const MDNode *Ranges = getRanges()) {
1009     unsigned NumRanges = Ranges->getNumOperands();
1010     if (NumRanges != 0) {
1011       OS << "(ranges=";
1012 
1013       for (unsigned I = 0; I != NumRanges; ++I) {
1014         Ranges->getOperand(I)->printAsOperand(OS, MST);
1015         if (I != NumRanges - 1)
1016           OS << ',';
1017       }
1018 
1019       OS << ')';
1020     }
1021   }
1022 
1023   if (isNonTemporal())
1024     OS << "(nontemporal)";
1025   if (isDereferenceable())
1026     OS << "(dereferenceable)";
1027   if (isInvariant())
1028     OS << "(invariant)";
1029   if (getFlags() & MOTargetFlag1)
1030     OS << "(flag1)";
1031   if (getFlags() & MOTargetFlag2)
1032     OS << "(flag2)";
1033   if (getFlags() & MOTargetFlag3)
1034     OS << "(flag3)";
1035 }
1036