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