1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
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 // This file implements the class that prints out the LLVM IR and machine
11 // functions using the MIR serialization format.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "MIRPrinter.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
18 #include "llvm/CodeGen/MIRYamlMapping.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineMemOperand.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ModuleSlotTracker.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/YAMLTraits.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetIntrinsicInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 
41 using namespace llvm;
42 
43 namespace {
44 
45 /// This structure describes how to print out stack object references.
46 struct FrameIndexOperand {
47   std::string Name;
48   unsigned ID;
49   bool IsFixed;
50 
51   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
52       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
53 
54   /// Return an ordinary stack object reference.
55   static FrameIndexOperand create(StringRef Name, unsigned ID) {
56     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
57   }
58 
59   /// Return a fixed stack object reference.
60   static FrameIndexOperand createFixed(unsigned ID) {
61     return FrameIndexOperand("", ID, /*IsFixed=*/true);
62   }
63 };
64 
65 } // end anonymous namespace
66 
67 namespace llvm {
68 
69 /// This class prints out the machine functions using the MIR serialization
70 /// format.
71 class MIRPrinter {
72   raw_ostream &OS;
73   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
74   /// Maps from stack object indices to operand indices which will be used when
75   /// printing frame index machine operands.
76   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
77 
78 public:
79   MIRPrinter(raw_ostream &OS) : OS(OS) {}
80 
81   void print(const MachineFunction &MF);
82 
83   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
84                const TargetRegisterInfo *TRI);
85   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
86                const MachineFrameInfo &MFI);
87   void convert(yaml::MachineFunction &MF,
88                const MachineConstantPool &ConstantPool);
89   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
90                const MachineJumpTableInfo &JTI);
91   void convertStackObjects(yaml::MachineFunction &MF,
92                            const MachineFrameInfo &MFI, MachineModuleInfo &MMI,
93                            ModuleSlotTracker &MST,
94                            const TargetRegisterInfo *TRI);
95 
96 private:
97   void initRegisterMaskIds(const MachineFunction &MF);
98 };
99 
100 /// This class prints out the machine instructions using the MIR serialization
101 /// format.
102 class MIPrinter {
103   raw_ostream &OS;
104   ModuleSlotTracker &MST;
105   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
106   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
107 
108 public:
109   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
110             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
111             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
112       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
113         StackObjectOperandMapping(StackObjectOperandMapping) {}
114 
115   void print(const MachineBasicBlock &MBB);
116 
117   void print(const MachineInstr &MI);
118   void printMBBReference(const MachineBasicBlock &MBB);
119   void printIRBlockReference(const BasicBlock &BB);
120   void printIRValueReference(const Value &V);
121   void printStackObjectReference(int FrameIndex);
122   void printOffset(int64_t Offset);
123   void printTargetFlags(const MachineOperand &Op);
124   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
125              unsigned I, bool ShouldPrintRegisterTies,
126              const MachineRegisterInfo *MRI = nullptr, bool IsDef = false);
127   void print(const MachineMemOperand &Op);
128 
129   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
130 };
131 
132 } // end namespace llvm
133 
134 namespace llvm {
135 namespace yaml {
136 
137 /// This struct serializes the LLVM IR module.
138 template <> struct BlockScalarTraits<Module> {
139   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
140     Mod.print(OS, nullptr);
141   }
142   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
143     llvm_unreachable("LLVM Module is supposed to be parsed separately");
144     return "";
145   }
146 };
147 
148 } // end namespace yaml
149 } // end namespace llvm
150 
151 static void printReg(unsigned Reg, raw_ostream &OS,
152                      const TargetRegisterInfo *TRI) {
153   // TODO: Print Stack Slots.
154   if (!Reg)
155     OS << '_';
156   else if (TargetRegisterInfo::isVirtualRegister(Reg))
157     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
158   else if (Reg < TRI->getNumRegs())
159     OS << '%' << StringRef(TRI->getName(Reg)).lower();
160   else
161     llvm_unreachable("Can't print this kind of register yet");
162 }
163 
164 static void printReg(unsigned Reg, yaml::StringValue &Dest,
165                      const TargetRegisterInfo *TRI) {
166   raw_string_ostream OS(Dest.Value);
167   printReg(Reg, OS, TRI);
168 }
169 
170 void MIRPrinter::print(const MachineFunction &MF) {
171   initRegisterMaskIds(MF);
172 
173   yaml::MachineFunction YamlMF;
174   YamlMF.Name = MF.getName();
175   YamlMF.Alignment = MF.getAlignment();
176   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
177   YamlMF.HasInlineAsm = MF.hasInlineAsm();
178   YamlMF.AllVRegsAllocated = MF.getProperties().hasProperty(
179       MachineFunctionProperties::Property::AllVRegsAllocated);
180 
181   YamlMF.Legalized = MF.getProperties().hasProperty(
182       MachineFunctionProperties::Property::Legalized);
183   YamlMF.RegBankSelected = MF.getProperties().hasProperty(
184       MachineFunctionProperties::Property::RegBankSelected);
185   YamlMF.Selected = MF.getProperties().hasProperty(
186       MachineFunctionProperties::Property::Selected);
187 
188   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
189   ModuleSlotTracker MST(MF.getFunction()->getParent());
190   MST.incorporateFunction(*MF.getFunction());
191   convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
192   convertStackObjects(YamlMF, MF.getFrameInfo(), MF.getMMI(), MST,
193                       MF.getSubtarget().getRegisterInfo());
194   if (const auto *ConstantPool = MF.getConstantPool())
195     convert(YamlMF, *ConstantPool);
196   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
197     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
198   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
199   bool IsNewlineNeeded = false;
200   for (const auto &MBB : MF) {
201     if (IsNewlineNeeded)
202       StrOS << "\n";
203     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
204         .print(MBB);
205     IsNewlineNeeded = true;
206   }
207   StrOS.flush();
208   yaml::Output Out(OS);
209   Out << YamlMF;
210 }
211 
212 void MIRPrinter::convert(yaml::MachineFunction &MF,
213                          const MachineRegisterInfo &RegInfo,
214                          const TargetRegisterInfo *TRI) {
215   MF.TracksRegLiveness = RegInfo.tracksLiveness();
216   MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
217 
218   // Print the virtual register definitions.
219   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
220     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
221     yaml::VirtualRegisterDefinition VReg;
222     VReg.ID = I;
223     if (RegInfo.getRegClassOrNull(Reg))
224       VReg.Class =
225           StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
226     else if (RegInfo.getRegBankOrNull(Reg))
227       VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
228     else {
229       VReg.Class = std::string("_");
230       assert(RegInfo.getSize(Reg) && "Generic registers must have a size");
231     }
232     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
233     if (PreferredReg)
234       printReg(PreferredReg, VReg.PreferredRegister, TRI);
235     MF.VirtualRegisters.push_back(VReg);
236   }
237 
238   // Print the live ins.
239   for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
240     yaml::MachineFunctionLiveIn LiveIn;
241     printReg(I->first, LiveIn.Register, TRI);
242     if (I->second)
243       printReg(I->second, LiveIn.VirtualRegister, TRI);
244     MF.LiveIns.push_back(LiveIn);
245   }
246   // The used physical register mask is printed as an inverted callee saved
247   // register mask.
248   const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask();
249   if (UsedPhysRegMask.none())
250     return;
251   std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
252   for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) {
253     if (!UsedPhysRegMask[I]) {
254       yaml::FlowStringValue Reg;
255       printReg(I, Reg, TRI);
256       CalleeSavedRegisters.push_back(Reg);
257     }
258   }
259   MF.CalleeSavedRegisters = CalleeSavedRegisters;
260 }
261 
262 void MIRPrinter::convert(ModuleSlotTracker &MST,
263                          yaml::MachineFrameInfo &YamlMFI,
264                          const MachineFrameInfo &MFI) {
265   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
266   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
267   YamlMFI.HasStackMap = MFI.hasStackMap();
268   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
269   YamlMFI.StackSize = MFI.getStackSize();
270   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
271   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
272   YamlMFI.AdjustsStack = MFI.adjustsStack();
273   YamlMFI.HasCalls = MFI.hasCalls();
274   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
275   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
276   YamlMFI.HasVAStart = MFI.hasVAStart();
277   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
278   if (MFI.getSavePoint()) {
279     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
280     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
281         .printMBBReference(*MFI.getSavePoint());
282   }
283   if (MFI.getRestorePoint()) {
284     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
285     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
286         .printMBBReference(*MFI.getRestorePoint());
287   }
288 }
289 
290 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
291                                      const MachineFrameInfo &MFI,
292                                      MachineModuleInfo &MMI,
293                                      ModuleSlotTracker &MST,
294                                      const TargetRegisterInfo *TRI) {
295   // Process fixed stack objects.
296   unsigned ID = 0;
297   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
298     if (MFI.isDeadObjectIndex(I))
299       continue;
300 
301     yaml::FixedMachineStackObject YamlObject;
302     YamlObject.ID = ID;
303     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
304                           ? yaml::FixedMachineStackObject::SpillSlot
305                           : yaml::FixedMachineStackObject::DefaultType;
306     YamlObject.Offset = MFI.getObjectOffset(I);
307     YamlObject.Size = MFI.getObjectSize(I);
308     YamlObject.Alignment = MFI.getObjectAlignment(I);
309     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
310     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
311     MF.FixedStackObjects.push_back(YamlObject);
312     StackObjectOperandMapping.insert(
313         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
314   }
315 
316   // Process ordinary stack objects.
317   ID = 0;
318   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
319     if (MFI.isDeadObjectIndex(I))
320       continue;
321 
322     yaml::MachineStackObject YamlObject;
323     YamlObject.ID = ID;
324     if (const auto *Alloca = MFI.getObjectAllocation(I))
325       YamlObject.Name.Value =
326           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
327     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
328                           ? yaml::MachineStackObject::SpillSlot
329                           : MFI.isVariableSizedObjectIndex(I)
330                                 ? yaml::MachineStackObject::VariableSized
331                                 : yaml::MachineStackObject::DefaultType;
332     YamlObject.Offset = MFI.getObjectOffset(I);
333     YamlObject.Size = MFI.getObjectSize(I);
334     YamlObject.Alignment = MFI.getObjectAlignment(I);
335 
336     MF.StackObjects.push_back(YamlObject);
337     StackObjectOperandMapping.insert(std::make_pair(
338         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
339   }
340 
341   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
342     yaml::StringValue Reg;
343     printReg(CSInfo.getReg(), Reg, TRI);
344     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
345     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
346            "Invalid stack object index");
347     const FrameIndexOperand &StackObject = StackObjectInfo->second;
348     if (StackObject.IsFixed)
349       MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
350     else
351       MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
352   }
353   for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
354     auto LocalObject = MFI.getLocalFrameObjectMap(I);
355     auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
356     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
357            "Invalid stack object index");
358     const FrameIndexOperand &StackObject = StackObjectInfo->second;
359     assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
360     MF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
361   }
362 
363   // Print the stack object references in the frame information class after
364   // converting the stack objects.
365   if (MFI.hasStackProtectorIndex()) {
366     raw_string_ostream StrOS(MF.FrameInfo.StackProtector.Value);
367     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
368         .printStackObjectReference(MFI.getStackProtectorIndex());
369   }
370 
371   // Print the debug variable information.
372   for (MachineModuleInfo::VariableDbgInfo &DebugVar :
373        MMI.getVariableDbgInfo()) {
374     auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
375     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
376            "Invalid stack object index");
377     const FrameIndexOperand &StackObject = StackObjectInfo->second;
378     assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
379     auto &Object = MF.StackObjects[StackObject.ID];
380     {
381       raw_string_ostream StrOS(Object.DebugVar.Value);
382       DebugVar.Var->printAsOperand(StrOS, MST);
383     }
384     {
385       raw_string_ostream StrOS(Object.DebugExpr.Value);
386       DebugVar.Expr->printAsOperand(StrOS, MST);
387     }
388     {
389       raw_string_ostream StrOS(Object.DebugLoc.Value);
390       DebugVar.Loc->printAsOperand(StrOS, MST);
391     }
392   }
393 }
394 
395 void MIRPrinter::convert(yaml::MachineFunction &MF,
396                          const MachineConstantPool &ConstantPool) {
397   unsigned ID = 0;
398   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
399     // TODO: Serialize target specific constant pool entries.
400     if (Constant.isMachineConstantPoolEntry())
401       llvm_unreachable("Can't print target specific constant pool entries yet");
402 
403     yaml::MachineConstantPoolValue YamlConstant;
404     std::string Str;
405     raw_string_ostream StrOS(Str);
406     Constant.Val.ConstVal->printAsOperand(StrOS);
407     YamlConstant.ID = ID++;
408     YamlConstant.Value = StrOS.str();
409     YamlConstant.Alignment = Constant.getAlignment();
410     MF.Constants.push_back(YamlConstant);
411   }
412 }
413 
414 void MIRPrinter::convert(ModuleSlotTracker &MST,
415                          yaml::MachineJumpTable &YamlJTI,
416                          const MachineJumpTableInfo &JTI) {
417   YamlJTI.Kind = JTI.getEntryKind();
418   unsigned ID = 0;
419   for (const auto &Table : JTI.getJumpTables()) {
420     std::string Str;
421     yaml::MachineJumpTable::Entry Entry;
422     Entry.ID = ID++;
423     for (const auto *MBB : Table.MBBs) {
424       raw_string_ostream StrOS(Str);
425       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
426           .printMBBReference(*MBB);
427       Entry.Blocks.push_back(StrOS.str());
428       Str.clear();
429     }
430     YamlJTI.Entries.push_back(Entry);
431   }
432 }
433 
434 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
435   const auto *TRI = MF.getSubtarget().getRegisterInfo();
436   unsigned I = 0;
437   for (const uint32_t *Mask : TRI->getRegMasks())
438     RegisterMaskIds.insert(std::make_pair(Mask, I++));
439 }
440 
441 void MIPrinter::print(const MachineBasicBlock &MBB) {
442   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
443   OS << "bb." << MBB.getNumber();
444   bool HasAttributes = false;
445   if (const auto *BB = MBB.getBasicBlock()) {
446     if (BB->hasName()) {
447       OS << "." << BB->getName();
448     } else {
449       HasAttributes = true;
450       OS << " (";
451       int Slot = MST.getLocalSlot(BB);
452       if (Slot == -1)
453         OS << "<ir-block badref>";
454       else
455         OS << (Twine("%ir-block.") + Twine(Slot)).str();
456     }
457   }
458   if (MBB.hasAddressTaken()) {
459     OS << (HasAttributes ? ", " : " (");
460     OS << "address-taken";
461     HasAttributes = true;
462   }
463   if (MBB.isEHPad()) {
464     OS << (HasAttributes ? ", " : " (");
465     OS << "landing-pad";
466     HasAttributes = true;
467   }
468   if (MBB.getAlignment()) {
469     OS << (HasAttributes ? ", " : " (");
470     OS << "align " << MBB.getAlignment();
471     HasAttributes = true;
472   }
473   if (HasAttributes)
474     OS << ")";
475   OS << ":\n";
476 
477   bool HasLineAttributes = false;
478   // Print the successors
479   if (!MBB.succ_empty()) {
480     OS.indent(2) << "successors: ";
481     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
482       if (I != MBB.succ_begin())
483         OS << ", ";
484       printMBBReference(**I);
485       if (MBB.hasSuccessorProbabilities())
486         OS << '(' << MBB.getSuccProbability(I) << ')';
487     }
488     OS << "\n";
489     HasLineAttributes = true;
490   }
491 
492   // Print the live in registers.
493   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
494   assert(TRI && "Expected target register info");
495   if (!MBB.livein_empty()) {
496     OS.indent(2) << "liveins: ";
497     bool First = true;
498     for (const auto &LI : MBB.liveins()) {
499       if (!First)
500         OS << ", ";
501       First = false;
502       printReg(LI.PhysReg, OS, TRI);
503       if (LI.LaneMask != ~0u)
504         OS << ':' << PrintLaneMask(LI.LaneMask);
505     }
506     OS << "\n";
507     HasLineAttributes = true;
508   }
509 
510   if (HasLineAttributes)
511     OS << "\n";
512   bool IsInBundle = false;
513   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
514     const MachineInstr &MI = *I;
515     if (IsInBundle && !MI.isInsideBundle()) {
516       OS.indent(2) << "}\n";
517       IsInBundle = false;
518     }
519     OS.indent(IsInBundle ? 4 : 2);
520     print(MI);
521     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
522       OS << " {";
523       IsInBundle = true;
524     }
525     OS << "\n";
526   }
527   if (IsInBundle)
528     OS.indent(2) << "}\n";
529 }
530 
531 /// Return true when an instruction has tied register that can't be determined
532 /// by the instruction's descriptor.
533 static bool hasComplexRegisterTies(const MachineInstr &MI) {
534   const MCInstrDesc &MCID = MI.getDesc();
535   for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
536     const auto &Operand = MI.getOperand(I);
537     if (!Operand.isReg() || Operand.isDef())
538       // Ignore the defined registers as MCID marks only the uses as tied.
539       continue;
540     int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
541     int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
542     if (ExpectedTiedIdx != TiedIdx)
543       return true;
544   }
545   return false;
546 }
547 
548 void MIPrinter::print(const MachineInstr &MI) {
549   const auto *MF = MI.getParent()->getParent();
550   const auto &MRI = MF->getRegInfo();
551   const auto &SubTarget = MF->getSubtarget();
552   const auto *TRI = SubTarget.getRegisterInfo();
553   assert(TRI && "Expected target register info");
554   const auto *TII = SubTarget.getInstrInfo();
555   assert(TII && "Expected target instruction info");
556   if (MI.isCFIInstruction())
557     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
558 
559   bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
560   unsigned I = 0, E = MI.getNumOperands();
561   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
562          !MI.getOperand(I).isImplicit();
563        ++I) {
564     if (I)
565       OS << ", ";
566     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies, &MRI,
567           /*IsDef=*/true);
568   }
569 
570   if (I)
571     OS << " = ";
572   if (MI.getFlag(MachineInstr::FrameSetup))
573     OS << "frame-setup ";
574   OS << TII->getName(MI.getOpcode());
575   if (isPreISelGenericOpcode(MI.getOpcode())) {
576     assert(MI.getType().isValid() && "Generic instructions must have a type");
577     unsigned NumTypes = MI.getNumTypes();
578     OS << (NumTypes > 1 ? " {" : "") << ' ';
579     for (unsigned i = 0; i < NumTypes; ++i) {
580       MI.getType(i).print(OS);
581       if (i + 1 != NumTypes)
582         OS <<  ", ";
583     }
584     OS << (NumTypes > 1 ? " }" : "") << ' ';
585   }
586   if (I < E)
587     OS << ' ';
588 
589   bool NeedComma = false;
590   for (; I < E; ++I) {
591     if (NeedComma)
592       OS << ", ";
593     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies);
594     NeedComma = true;
595   }
596 
597   if (MI.getDebugLoc()) {
598     if (NeedComma)
599       OS << ',';
600     OS << " debug-location ";
601     MI.getDebugLoc()->printAsOperand(OS, MST);
602   }
603 
604   if (!MI.memoperands_empty()) {
605     OS << " :: ";
606     bool NeedComma = false;
607     for (const auto *Op : MI.memoperands()) {
608       if (NeedComma)
609         OS << ", ";
610       print(*Op);
611       NeedComma = true;
612     }
613   }
614 }
615 
616 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
617   OS << "%bb." << MBB.getNumber();
618   if (const auto *BB = MBB.getBasicBlock()) {
619     if (BB->hasName())
620       OS << '.' << BB->getName();
621   }
622 }
623 
624 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
625   if (Slot == -1)
626     OS << "<badref>";
627   else
628     OS << Slot;
629 }
630 
631 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
632   OS << "%ir-block.";
633   if (BB.hasName()) {
634     printLLVMNameWithoutPrefix(OS, BB.getName());
635     return;
636   }
637   const Function *F = BB.getParent();
638   int Slot;
639   if (F == MST.getCurrentFunction()) {
640     Slot = MST.getLocalSlot(&BB);
641   } else {
642     ModuleSlotTracker CustomMST(F->getParent(),
643                                 /*ShouldInitializeAllMetadata=*/false);
644     CustomMST.incorporateFunction(*F);
645     Slot = CustomMST.getLocalSlot(&BB);
646   }
647   printIRSlotNumber(OS, Slot);
648 }
649 
650 void MIPrinter::printIRValueReference(const Value &V) {
651   if (isa<GlobalValue>(V)) {
652     V.printAsOperand(OS, /*PrintType=*/false, MST);
653     return;
654   }
655   if (isa<Constant>(V)) {
656     // Machine memory operands can load/store to/from constant value pointers.
657     OS << '`';
658     V.printAsOperand(OS, /*PrintType=*/true, MST);
659     OS << '`';
660     return;
661   }
662   OS << "%ir.";
663   if (V.hasName()) {
664     printLLVMNameWithoutPrefix(OS, V.getName());
665     return;
666   }
667   printIRSlotNumber(OS, MST.getLocalSlot(&V));
668 }
669 
670 void MIPrinter::printStackObjectReference(int FrameIndex) {
671   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
672   assert(ObjectInfo != StackObjectOperandMapping.end() &&
673          "Invalid frame index");
674   const FrameIndexOperand &Operand = ObjectInfo->second;
675   if (Operand.IsFixed) {
676     OS << "%fixed-stack." << Operand.ID;
677     return;
678   }
679   OS << "%stack." << Operand.ID;
680   if (!Operand.Name.empty())
681     OS << '.' << Operand.Name;
682 }
683 
684 void MIPrinter::printOffset(int64_t Offset) {
685   if (Offset == 0)
686     return;
687   if (Offset < 0) {
688     OS << " - " << -Offset;
689     return;
690   }
691   OS << " + " << Offset;
692 }
693 
694 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
695   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
696   for (const auto &I : Flags) {
697     if (I.first == TF) {
698       return I.second;
699     }
700   }
701   return nullptr;
702 }
703 
704 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
705   if (!Op.getTargetFlags())
706     return;
707   const auto *TII =
708       Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
709   assert(TII && "expected instruction info");
710   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
711   OS << "target-flags(";
712   const bool HasDirectFlags = Flags.first;
713   const bool HasBitmaskFlags = Flags.second;
714   if (!HasDirectFlags && !HasBitmaskFlags) {
715     OS << "<unknown>) ";
716     return;
717   }
718   if (HasDirectFlags) {
719     if (const auto *Name = getTargetFlagName(TII, Flags.first))
720       OS << Name;
721     else
722       OS << "<unknown target flag>";
723   }
724   if (!HasBitmaskFlags) {
725     OS << ") ";
726     return;
727   }
728   bool IsCommaNeeded = HasDirectFlags;
729   unsigned BitMask = Flags.second;
730   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
731   for (const auto &Mask : BitMasks) {
732     // Check if the flag's bitmask has the bits of the current mask set.
733     if ((BitMask & Mask.first) == Mask.first) {
734       if (IsCommaNeeded)
735         OS << ", ";
736       IsCommaNeeded = true;
737       OS << Mask.second;
738       // Clear the bits which were serialized from the flag's bitmask.
739       BitMask &= ~(Mask.first);
740     }
741   }
742   if (BitMask) {
743     // When the resulting flag's bitmask isn't zero, we know that we didn't
744     // serialize all of the bit flags.
745     if (IsCommaNeeded)
746       OS << ", ";
747     OS << "<unknown bitmask target flag>";
748   }
749   OS << ") ";
750 }
751 
752 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
753   const auto *TII = MF.getSubtarget().getInstrInfo();
754   assert(TII && "expected instruction info");
755   auto Indices = TII->getSerializableTargetIndices();
756   for (const auto &I : Indices) {
757     if (I.first == Index) {
758       return I.second;
759     }
760   }
761   return nullptr;
762 }
763 
764 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
765                       unsigned I, bool ShouldPrintRegisterTies,
766                       const MachineRegisterInfo *MRI, bool IsDef) {
767   printTargetFlags(Op);
768   switch (Op.getType()) {
769   case MachineOperand::MO_Register:
770     if (Op.isImplicit())
771       OS << (Op.isDef() ? "implicit-def " : "implicit ");
772     else if (!IsDef && Op.isDef())
773       // Print the 'def' flag only when the operand is defined after '='.
774       OS << "def ";
775     if (Op.isInternalRead())
776       OS << "internal ";
777     if (Op.isDead())
778       OS << "dead ";
779     if (Op.isKill())
780       OS << "killed ";
781     if (Op.isUndef())
782       OS << "undef ";
783     if (Op.isEarlyClobber())
784       OS << "early-clobber ";
785     if (Op.isDebug())
786       OS << "debug-use ";
787     printReg(Op.getReg(), OS, TRI);
788     // Print the sub register.
789     if (Op.getSubReg() != 0)
790       OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
791     if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
792       OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
793     assert((!IsDef || MRI) && "for IsDef, MRI must be provided");
794     if (IsDef && MRI->getSize(Op.getReg()))
795       OS << '(' << MRI->getSize(Op.getReg()) << ')';
796     break;
797   case MachineOperand::MO_Immediate:
798     OS << Op.getImm();
799     break;
800   case MachineOperand::MO_CImmediate:
801     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
802     break;
803   case MachineOperand::MO_FPImmediate:
804     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
805     break;
806   case MachineOperand::MO_MachineBasicBlock:
807     printMBBReference(*Op.getMBB());
808     break;
809   case MachineOperand::MO_FrameIndex:
810     printStackObjectReference(Op.getIndex());
811     break;
812   case MachineOperand::MO_ConstantPoolIndex:
813     OS << "%const." << Op.getIndex();
814     printOffset(Op.getOffset());
815     break;
816   case MachineOperand::MO_TargetIndex: {
817     OS << "target-index(";
818     if (const auto *Name = getTargetIndexName(
819             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
820       OS << Name;
821     else
822       OS << "<unknown>";
823     OS << ')';
824     printOffset(Op.getOffset());
825     break;
826   }
827   case MachineOperand::MO_JumpTableIndex:
828     OS << "%jump-table." << Op.getIndex();
829     break;
830   case MachineOperand::MO_ExternalSymbol:
831     OS << '$';
832     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
833     printOffset(Op.getOffset());
834     break;
835   case MachineOperand::MO_GlobalAddress:
836     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
837     printOffset(Op.getOffset());
838     break;
839   case MachineOperand::MO_BlockAddress:
840     OS << "blockaddress(";
841     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
842                                                         MST);
843     OS << ", ";
844     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
845     OS << ')';
846     printOffset(Op.getOffset());
847     break;
848   case MachineOperand::MO_RegisterMask: {
849     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
850     if (RegMaskInfo != RegisterMaskIds.end())
851       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
852     else
853       llvm_unreachable("Can't print this machine register mask yet.");
854     break;
855   }
856   case MachineOperand::MO_RegisterLiveOut: {
857     const uint32_t *RegMask = Op.getRegLiveOut();
858     OS << "liveout(";
859     bool IsCommaNeeded = false;
860     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
861       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
862         if (IsCommaNeeded)
863           OS << ", ";
864         printReg(Reg, OS, TRI);
865         IsCommaNeeded = true;
866       }
867     }
868     OS << ")";
869     break;
870   }
871   case MachineOperand::MO_Metadata:
872     Op.getMetadata()->printAsOperand(OS, MST);
873     break;
874   case MachineOperand::MO_MCSymbol:
875     OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
876     break;
877   case MachineOperand::MO_CFIIndex: {
878     const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
879     print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
880     break;
881   }
882   case MachineOperand::MO_IntrinsicID: {
883     Intrinsic::ID ID = Op.getIntrinsicID();
884     if (ID < Intrinsic::num_intrinsics)
885       OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
886     else {
887       const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
888       const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
889       OS << "intrinsic(@" << TII->getName(ID) << ')';
890     }
891     break;
892   }
893   case MachineOperand::MO_Predicate: {
894     auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
895     OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
896        << CmpInst::getPredicateName(Pred) << ')';
897     break;
898   }
899   }
900 }
901 
902 void MIPrinter::print(const MachineMemOperand &Op) {
903   OS << '(';
904   // TODO: Print operand's target specific flags.
905   if (Op.isVolatile())
906     OS << "volatile ";
907   if (Op.isNonTemporal())
908     OS << "non-temporal ";
909   if (Op.isInvariant())
910     OS << "invariant ";
911   if (Op.isLoad())
912     OS << "load ";
913   else {
914     assert(Op.isStore() && "Non load machine operand must be a store");
915     OS << "store ";
916   }
917   OS << Op.getSize();
918   if (const Value *Val = Op.getValue()) {
919     OS << (Op.isLoad() ? " from " : " into ");
920     printIRValueReference(*Val);
921   } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
922     OS << (Op.isLoad() ? " from " : " into ");
923     assert(PVal && "Expected a pseudo source value");
924     switch (PVal->kind()) {
925     case PseudoSourceValue::Stack:
926       OS << "stack";
927       break;
928     case PseudoSourceValue::GOT:
929       OS << "got";
930       break;
931     case PseudoSourceValue::JumpTable:
932       OS << "jump-table";
933       break;
934     case PseudoSourceValue::ConstantPool:
935       OS << "constant-pool";
936       break;
937     case PseudoSourceValue::FixedStack:
938       printStackObjectReference(
939           cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
940       break;
941     case PseudoSourceValue::GlobalValueCallEntry:
942       OS << "call-entry ";
943       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
944           OS, /*PrintType=*/false, MST);
945       break;
946     case PseudoSourceValue::ExternalSymbolCallEntry:
947       OS << "call-entry $";
948       printLLVMNameWithoutPrefix(
949           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
950       break;
951     }
952   }
953   printOffset(Op.getOffset());
954   if (Op.getBaseAlignment() != Op.getSize())
955     OS << ", align " << Op.getBaseAlignment();
956   auto AAInfo = Op.getAAInfo();
957   if (AAInfo.TBAA) {
958     OS << ", !tbaa ";
959     AAInfo.TBAA->printAsOperand(OS, MST);
960   }
961   if (AAInfo.Scope) {
962     OS << ", !alias.scope ";
963     AAInfo.Scope->printAsOperand(OS, MST);
964   }
965   if (AAInfo.NoAlias) {
966     OS << ", !noalias ";
967     AAInfo.NoAlias->printAsOperand(OS, MST);
968   }
969   if (Op.getRanges()) {
970     OS << ", !range ";
971     Op.getRanges()->printAsOperand(OS, MST);
972   }
973   OS << ')';
974 }
975 
976 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
977                              const TargetRegisterInfo *TRI) {
978   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
979   if (Reg == -1) {
980     OS << "<badreg>";
981     return;
982   }
983   printReg(Reg, OS, TRI);
984 }
985 
986 void MIPrinter::print(const MCCFIInstruction &CFI,
987                       const TargetRegisterInfo *TRI) {
988   switch (CFI.getOperation()) {
989   case MCCFIInstruction::OpSameValue:
990     OS << "same_value ";
991     if (CFI.getLabel())
992       OS << "<mcsymbol> ";
993     printCFIRegister(CFI.getRegister(), OS, TRI);
994     break;
995   case MCCFIInstruction::OpOffset:
996     OS << "offset ";
997     if (CFI.getLabel())
998       OS << "<mcsymbol> ";
999     printCFIRegister(CFI.getRegister(), OS, TRI);
1000     OS << ", " << CFI.getOffset();
1001     break;
1002   case MCCFIInstruction::OpDefCfaRegister:
1003     OS << "def_cfa_register ";
1004     if (CFI.getLabel())
1005       OS << "<mcsymbol> ";
1006     printCFIRegister(CFI.getRegister(), OS, TRI);
1007     break;
1008   case MCCFIInstruction::OpDefCfaOffset:
1009     OS << "def_cfa_offset ";
1010     if (CFI.getLabel())
1011       OS << "<mcsymbol> ";
1012     OS << CFI.getOffset();
1013     break;
1014   case MCCFIInstruction::OpDefCfa:
1015     OS << "def_cfa ";
1016     if (CFI.getLabel())
1017       OS << "<mcsymbol> ";
1018     printCFIRegister(CFI.getRegister(), OS, TRI);
1019     OS << ", " << CFI.getOffset();
1020     break;
1021   default:
1022     // TODO: Print the other CFI Operations.
1023     OS << "<unserializable cfi operation>";
1024     break;
1025   }
1026 }
1027 
1028 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1029   yaml::Output Out(OS);
1030   Out << const_cast<Module &>(M);
1031 }
1032 
1033 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1034   MIRPrinter Printer(OS);
1035   Printer.print(MF);
1036 }
1037