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