MIR Serialization: Fix serialization of unnamed IR block references.
[oota-llvm.git] / lib / CodeGen / MIRPrinter.cpp
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/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineMemOperand.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/MIRYamlMapping.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IRPrintingPasses.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ModuleSlotTracker.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/YAMLTraits.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
35
36 using namespace llvm;
37
38 namespace {
39
40 /// This structure describes how to print out stack object references.
41 struct FrameIndexOperand {
42   std::string Name;
43   unsigned ID;
44   bool IsFixed;
45
46   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
47       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
48
49   /// Return an ordinary stack object reference.
50   static FrameIndexOperand create(StringRef Name, unsigned ID) {
51     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
52   }
53
54   /// Return a fixed stack object reference.
55   static FrameIndexOperand createFixed(unsigned ID) {
56     return FrameIndexOperand("", ID, /*IsFixed=*/true);
57   }
58 };
59
60 } // end anonymous namespace
61
62 namespace llvm {
63
64 /// This class prints out the machine functions using the MIR serialization
65 /// format.
66 class MIRPrinter {
67   raw_ostream &OS;
68   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
69   /// Maps from stack object indices to operand indices which will be used when
70   /// printing frame index machine operands.
71   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
72
73 public:
74   MIRPrinter(raw_ostream &OS) : OS(OS) {}
75
76   void print(const MachineFunction &MF);
77
78   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
79                const TargetRegisterInfo *TRI);
80   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
81                const MachineFrameInfo &MFI);
82   void convert(yaml::MachineFunction &MF,
83                const MachineConstantPool &ConstantPool);
84   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
85                const MachineJumpTableInfo &JTI);
86   void convert(ModuleSlotTracker &MST, yaml::MachineBasicBlock &YamlMBB,
87                const MachineBasicBlock &MBB);
88   void convertStackObjects(yaml::MachineFunction &MF,
89                            const MachineFrameInfo &MFI,
90                            const TargetRegisterInfo *TRI);
91
92 private:
93   void initRegisterMaskIds(const MachineFunction &MF);
94 };
95
96 } // end namespace llvm
97
98 namespace {
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 MachineInstr &MI);
116   void printMBBReference(const MachineBasicBlock &MBB);
117   void printIRBlockReference(const BasicBlock &BB);
118   void printIRValueReference(const Value &V);
119   void printStackObjectReference(int FrameIndex);
120   void printOffset(int64_t Offset);
121   void printTargetFlags(const MachineOperand &Op);
122   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
123   void print(const MachineMemOperand &Op);
124
125   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
126 };
127
128 } // end anonymous namespace
129
130 namespace llvm {
131 namespace yaml {
132
133 /// This struct serializes the LLVM IR module.
134 template <> struct BlockScalarTraits<Module> {
135   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
136     Mod.print(OS, nullptr);
137   }
138   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
139     llvm_unreachable("LLVM Module is supposed to be parsed separately");
140     return "";
141   }
142 };
143
144 } // end namespace yaml
145 } // end namespace llvm
146
147 static void printReg(unsigned Reg, raw_ostream &OS,
148                      const TargetRegisterInfo *TRI) {
149   // TODO: Print Stack Slots.
150   if (!Reg)
151     OS << '_';
152   else if (TargetRegisterInfo::isVirtualRegister(Reg))
153     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
154   else if (Reg < TRI->getNumRegs())
155     OS << '%' << StringRef(TRI->getName(Reg)).lower();
156   else
157     llvm_unreachable("Can't print this kind of register yet");
158 }
159
160 static void printReg(unsigned Reg, yaml::StringValue &Dest,
161                      const TargetRegisterInfo *TRI) {
162   raw_string_ostream OS(Dest.Value);
163   printReg(Reg, OS, TRI);
164 }
165
166 void MIRPrinter::print(const MachineFunction &MF) {
167   initRegisterMaskIds(MF);
168
169   yaml::MachineFunction YamlMF;
170   YamlMF.Name = MF.getName();
171   YamlMF.Alignment = MF.getAlignment();
172   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
173   YamlMF.HasInlineAsm = MF.hasInlineAsm();
174   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
175   ModuleSlotTracker MST(MF.getFunction()->getParent());
176   MST.incorporateFunction(*MF.getFunction());
177   convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo());
178   convertStackObjects(YamlMF, *MF.getFrameInfo(),
179                       MF.getSubtarget().getRegisterInfo());
180   if (const auto *ConstantPool = MF.getConstantPool())
181     convert(YamlMF, *ConstantPool);
182   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
183     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
184   for (const auto &MBB : MF) {
185     yaml::MachineBasicBlock YamlMBB;
186     convert(MST, YamlMBB, MBB);
187     YamlMF.BasicBlocks.push_back(YamlMBB);
188   }
189   yaml::Output Out(OS);
190   Out << YamlMF;
191 }
192
193 void MIRPrinter::convert(yaml::MachineFunction &MF,
194                          const MachineRegisterInfo &RegInfo,
195                          const TargetRegisterInfo *TRI) {
196   MF.IsSSA = RegInfo.isSSA();
197   MF.TracksRegLiveness = RegInfo.tracksLiveness();
198   MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
199
200   // Print the virtual register definitions.
201   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
202     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
203     yaml::VirtualRegisterDefinition VReg;
204     VReg.ID = I;
205     VReg.Class =
206         StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
207     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
208     if (PreferredReg)
209       printReg(PreferredReg, VReg.PreferredRegister, TRI);
210     MF.VirtualRegisters.push_back(VReg);
211   }
212
213   // Print the live ins.
214   for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
215     yaml::MachineFunctionLiveIn LiveIn;
216     printReg(I->first, LiveIn.Register, TRI);
217     if (I->second)
218       printReg(I->second, LiveIn.VirtualRegister, TRI);
219     MF.LiveIns.push_back(LiveIn);
220   }
221 }
222
223 void MIRPrinter::convert(ModuleSlotTracker &MST,
224                          yaml::MachineFrameInfo &YamlMFI,
225                          const MachineFrameInfo &MFI) {
226   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
227   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
228   YamlMFI.HasStackMap = MFI.hasStackMap();
229   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
230   YamlMFI.StackSize = MFI.getStackSize();
231   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
232   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
233   YamlMFI.AdjustsStack = MFI.adjustsStack();
234   YamlMFI.HasCalls = MFI.hasCalls();
235   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
236   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
237   YamlMFI.HasVAStart = MFI.hasVAStart();
238   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
239   if (MFI.getSavePoint()) {
240     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
241     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
242         .printMBBReference(*MFI.getSavePoint());
243   }
244   if (MFI.getRestorePoint()) {
245     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
246     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
247         .printMBBReference(*MFI.getRestorePoint());
248   }
249 }
250
251 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
252                                      const MachineFrameInfo &MFI,
253                                      const TargetRegisterInfo *TRI) {
254   // Process fixed stack objects.
255   unsigned ID = 0;
256   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
257     if (MFI.isDeadObjectIndex(I))
258       continue;
259
260     yaml::FixedMachineStackObject YamlObject;
261     YamlObject.ID = ID;
262     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
263                           ? yaml::FixedMachineStackObject::SpillSlot
264                           : yaml::FixedMachineStackObject::DefaultType;
265     YamlObject.Offset = MFI.getObjectOffset(I);
266     YamlObject.Size = MFI.getObjectSize(I);
267     YamlObject.Alignment = MFI.getObjectAlignment(I);
268     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
269     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
270     MF.FixedStackObjects.push_back(YamlObject);
271     StackObjectOperandMapping.insert(
272         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
273   }
274
275   // Process ordinary stack objects.
276   ID = 0;
277   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
278     if (MFI.isDeadObjectIndex(I))
279       continue;
280
281     yaml::MachineStackObject YamlObject;
282     YamlObject.ID = ID;
283     if (const auto *Alloca = MFI.getObjectAllocation(I))
284       YamlObject.Name.Value =
285           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
286     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
287                           ? yaml::MachineStackObject::SpillSlot
288                           : MFI.isVariableSizedObjectIndex(I)
289                                 ? yaml::MachineStackObject::VariableSized
290                                 : yaml::MachineStackObject::DefaultType;
291     YamlObject.Offset = MFI.getObjectOffset(I);
292     YamlObject.Size = MFI.getObjectSize(I);
293     YamlObject.Alignment = MFI.getObjectAlignment(I);
294
295     MF.StackObjects.push_back(YamlObject);
296     StackObjectOperandMapping.insert(std::make_pair(
297         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
298   }
299
300   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
301     yaml::StringValue Reg;
302     printReg(CSInfo.getReg(), Reg, TRI);
303     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
304     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
305            "Invalid stack object index");
306     const FrameIndexOperand &StackObject = StackObjectInfo->second;
307     if (StackObject.IsFixed)
308       MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
309     else
310       MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
311   }
312 }
313
314 void MIRPrinter::convert(yaml::MachineFunction &MF,
315                          const MachineConstantPool &ConstantPool) {
316   unsigned ID = 0;
317   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
318     // TODO: Serialize target specific constant pool entries.
319     if (Constant.isMachineConstantPoolEntry())
320       llvm_unreachable("Can't print target specific constant pool entries yet");
321
322     yaml::MachineConstantPoolValue YamlConstant;
323     std::string Str;
324     raw_string_ostream StrOS(Str);
325     Constant.Val.ConstVal->printAsOperand(StrOS);
326     YamlConstant.ID = ID++;
327     YamlConstant.Value = StrOS.str();
328     YamlConstant.Alignment = Constant.getAlignment();
329     MF.Constants.push_back(YamlConstant);
330   }
331 }
332
333 void MIRPrinter::convert(ModuleSlotTracker &MST,
334                          yaml::MachineJumpTable &YamlJTI,
335                          const MachineJumpTableInfo &JTI) {
336   YamlJTI.Kind = JTI.getEntryKind();
337   unsigned ID = 0;
338   for (const auto &Table : JTI.getJumpTables()) {
339     std::string Str;
340     yaml::MachineJumpTable::Entry Entry;
341     Entry.ID = ID++;
342     for (const auto *MBB : Table.MBBs) {
343       raw_string_ostream StrOS(Str);
344       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
345           .printMBBReference(*MBB);
346       Entry.Blocks.push_back(StrOS.str());
347       Str.clear();
348     }
349     YamlJTI.Entries.push_back(Entry);
350   }
351 }
352
353 void MIRPrinter::convert(ModuleSlotTracker &MST,
354                          yaml::MachineBasicBlock &YamlMBB,
355                          const MachineBasicBlock &MBB) {
356   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
357   YamlMBB.ID = (unsigned)MBB.getNumber();
358   if (const auto *BB = MBB.getBasicBlock()) {
359     if (BB->hasName()) {
360       YamlMBB.Name.Value = BB->getName();
361     } else {
362       int Slot = MST.getLocalSlot(BB);
363       if (Slot == -1)
364         YamlMBB.IRBlock.Value = "<badref>";
365       else
366         YamlMBB.IRBlock.Value = (Twine("%ir-block.") + Twine(Slot)).str();
367     }
368   }
369   YamlMBB.Alignment = MBB.getAlignment();
370   YamlMBB.AddressTaken = MBB.hasAddressTaken();
371   YamlMBB.IsLandingPad = MBB.isLandingPad();
372   for (const auto *SuccMBB : MBB.successors()) {
373     std::string Str;
374     raw_string_ostream StrOS(Str);
375     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
376         .printMBBReference(*SuccMBB);
377     YamlMBB.Successors.push_back(StrOS.str());
378   }
379   if (MBB.hasSuccessorWeights()) {
380     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I)
381       YamlMBB.SuccessorWeights.push_back(
382           yaml::UnsignedValue(MBB.getSuccWeight(I)));
383   }
384   // Print the live in registers.
385   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
386   assert(TRI && "Expected target register info");
387   for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
388     std::string Str;
389     raw_string_ostream StrOS(Str);
390     printReg(*I, StrOS, TRI);
391     YamlMBB.LiveIns.push_back(StrOS.str());
392   }
393   // Print the machine instructions.
394   YamlMBB.Instructions.reserve(MBB.size());
395   std::string Str;
396   for (const auto &MI : MBB) {
397     raw_string_ostream StrOS(Str);
398     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
399     YamlMBB.Instructions.push_back(StrOS.str());
400     Str.clear();
401   }
402 }
403
404 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
405   const auto *TRI = MF.getSubtarget().getRegisterInfo();
406   unsigned I = 0;
407   for (const uint32_t *Mask : TRI->getRegMasks())
408     RegisterMaskIds.insert(std::make_pair(Mask, I++));
409 }
410
411 void MIPrinter::print(const MachineInstr &MI) {
412   const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
413   const auto *TRI = SubTarget.getRegisterInfo();
414   assert(TRI && "Expected target register info");
415   const auto *TII = SubTarget.getInstrInfo();
416   assert(TII && "Expected target instruction info");
417   if (MI.isCFIInstruction())
418     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
419
420   unsigned I = 0, E = MI.getNumOperands();
421   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
422          !MI.getOperand(I).isImplicit();
423        ++I) {
424     if (I)
425       OS << ", ";
426     print(MI.getOperand(I), TRI);
427   }
428
429   if (I)
430     OS << " = ";
431   if (MI.getFlag(MachineInstr::FrameSetup))
432     OS << "frame-setup ";
433   OS << TII->getName(MI.getOpcode());
434   // TODO: Print the bundling instruction flags.
435   if (I < E)
436     OS << ' ';
437
438   bool NeedComma = false;
439   for (; I < E; ++I) {
440     if (NeedComma)
441       OS << ", ";
442     print(MI.getOperand(I), TRI);
443     NeedComma = true;
444   }
445
446   if (MI.getDebugLoc()) {
447     if (NeedComma)
448       OS << ',';
449     OS << " debug-location ";
450     MI.getDebugLoc()->printAsOperand(OS, MST);
451   }
452
453   if (!MI.memoperands_empty()) {
454     OS << " :: ";
455     bool NeedComma = false;
456     for (const auto *Op : MI.memoperands()) {
457       if (NeedComma)
458         OS << ", ";
459       print(*Op);
460       NeedComma = true;
461     }
462   }
463 }
464
465 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
466   OS << "%bb." << MBB.getNumber();
467   if (const auto *BB = MBB.getBasicBlock()) {
468     if (BB->hasName())
469       OS << '.' << BB->getName();
470   }
471 }
472
473 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
474   OS << "%ir-block.";
475   if (BB.hasName()) {
476     printLLVMNameWithoutPrefix(OS, BB.getName());
477     return;
478   }
479   const Function *F = BB.getParent();
480   int Slot;
481   if (F == MST.getCurrentFunction()) {
482     Slot = MST.getLocalSlot(&BB);
483   } else {
484     ModuleSlotTracker CustomMST(F->getParent(),
485                                 /*ShouldInitializeAllMetadata=*/false);
486     CustomMST.incorporateFunction(*F);
487     Slot = CustomMST.getLocalSlot(&BB);
488   }
489   if (Slot == -1)
490     OS << "<badref>";
491   else
492     OS << Slot;
493 }
494
495 void MIPrinter::printIRValueReference(const Value &V) {
496   OS << "%ir.";
497   if (V.hasName()) {
498     printLLVMNameWithoutPrefix(OS, V.getName());
499     return;
500   }
501   // TODO: Serialize the unnamed IR value references.
502   OS << "<unserializable ir value>";
503 }
504
505 void MIPrinter::printStackObjectReference(int FrameIndex) {
506   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
507   assert(ObjectInfo != StackObjectOperandMapping.end() &&
508          "Invalid frame index");
509   const FrameIndexOperand &Operand = ObjectInfo->second;
510   if (Operand.IsFixed) {
511     OS << "%fixed-stack." << Operand.ID;
512     return;
513   }
514   OS << "%stack." << Operand.ID;
515   if (!Operand.Name.empty())
516     OS << '.' << Operand.Name;
517 }
518
519 void MIPrinter::printOffset(int64_t Offset) {
520   if (Offset == 0)
521     return;
522   if (Offset < 0) {
523     OS << " - " << -Offset;
524     return;
525   }
526   OS << " + " << Offset;
527 }
528
529 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
530   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
531   for (const auto &I : Flags) {
532     if (I.first == TF) {
533       return I.second;
534     }
535   }
536   return nullptr;
537 }
538
539 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
540   if (!Op.getTargetFlags())
541     return;
542   const auto *TII =
543       Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
544   assert(TII && "expected instruction info");
545   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
546   OS << "target-flags(";
547   if (const auto *Name = getTargetFlagName(TII, Flags.first))
548     OS << Name;
549   else
550     OS << "<unknown target flag>";
551   // TODO: Print the target's bit flags.
552   OS << ") ";
553 }
554
555 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
556   const auto *TII = MF.getSubtarget().getInstrInfo();
557   assert(TII && "expected instruction info");
558   auto Indices = TII->getSerializableTargetIndices();
559   for (const auto &I : Indices) {
560     if (I.first == Index) {
561       return I.second;
562     }
563   }
564   return nullptr;
565 }
566
567 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
568   printTargetFlags(Op);
569   switch (Op.getType()) {
570   case MachineOperand::MO_Register:
571     // TODO: Print the other register flags.
572     if (Op.isImplicit())
573       OS << (Op.isDef() ? "implicit-def " : "implicit ");
574     if (Op.isDead())
575       OS << "dead ";
576     if (Op.isKill())
577       OS << "killed ";
578     if (Op.isUndef())
579       OS << "undef ";
580     if (Op.isEarlyClobber())
581       OS << "early-clobber ";
582     if (Op.isDebug())
583       OS << "debug-use ";
584     printReg(Op.getReg(), OS, TRI);
585     // Print the sub register.
586     if (Op.getSubReg() != 0)
587       OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
588     break;
589   case MachineOperand::MO_Immediate:
590     OS << Op.getImm();
591     break;
592   case MachineOperand::MO_CImmediate:
593     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
594     break;
595   case MachineOperand::MO_FPImmediate:
596     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
597     break;
598   case MachineOperand::MO_MachineBasicBlock:
599     printMBBReference(*Op.getMBB());
600     break;
601   case MachineOperand::MO_FrameIndex:
602     printStackObjectReference(Op.getIndex());
603     break;
604   case MachineOperand::MO_ConstantPoolIndex:
605     OS << "%const." << Op.getIndex();
606     printOffset(Op.getOffset());
607     break;
608   case MachineOperand::MO_TargetIndex: {
609     OS << "target-index(";
610     if (const auto *Name = getTargetIndexName(
611             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
612       OS << Name;
613     else
614       OS << "<unknown>";
615     OS << ')';
616     printOffset(Op.getOffset());
617     break;
618   }
619   case MachineOperand::MO_JumpTableIndex:
620     OS << "%jump-table." << Op.getIndex();
621     break;
622   case MachineOperand::MO_ExternalSymbol:
623     OS << '$';
624     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
625     printOffset(Op.getOffset());
626     break;
627   case MachineOperand::MO_GlobalAddress:
628     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
629     printOffset(Op.getOffset());
630     break;
631   case MachineOperand::MO_BlockAddress:
632     OS << "blockaddress(";
633     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
634                                                         MST);
635     OS << ", ";
636     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
637     OS << ')';
638     printOffset(Op.getOffset());
639     break;
640   case MachineOperand::MO_RegisterMask: {
641     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
642     if (RegMaskInfo != RegisterMaskIds.end())
643       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
644     else
645       llvm_unreachable("Can't print this machine register mask yet.");
646     break;
647   }
648   case MachineOperand::MO_Metadata:
649     Op.getMetadata()->printAsOperand(OS, MST);
650     break;
651   case MachineOperand::MO_CFIIndex: {
652     const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
653     print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
654     break;
655   }
656   default:
657     // TODO: Print the other machine operands.
658     llvm_unreachable("Can't print this machine operand at the moment");
659   }
660 }
661
662 void MIPrinter::print(const MachineMemOperand &Op) {
663   OS << '(';
664   // TODO: Print operand's target specific flags.
665   if (Op.isVolatile())
666     OS << "volatile ";
667   if (Op.isNonTemporal())
668     OS << "non-temporal ";
669   if (Op.isInvariant())
670     OS << "invariant ";
671   if (Op.isLoad())
672     OS << "load ";
673   else {
674     assert(Op.isStore() && "Non load machine operand must be a store");
675     OS << "store ";
676   }
677   OS << Op.getSize() << (Op.isLoad() ? " from " : " into ");
678   if (const Value *Val = Op.getValue())
679     printIRValueReference(*Val);
680   // TODO: Print PseudoSourceValue.
681   // TODO: Print the base alignment.
682   // TODO: Print the metadata attributes.
683   OS << ')';
684 }
685
686 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
687                              const TargetRegisterInfo *TRI) {
688   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
689   if (Reg == -1) {
690     OS << "<badreg>";
691     return;
692   }
693   printReg(Reg, OS, TRI);
694 }
695
696 void MIPrinter::print(const MCCFIInstruction &CFI,
697                       const TargetRegisterInfo *TRI) {
698   switch (CFI.getOperation()) {
699   case MCCFIInstruction::OpOffset:
700     OS << ".cfi_offset ";
701     if (CFI.getLabel())
702       OS << "<mcsymbol> ";
703     printCFIRegister(CFI.getRegister(), OS, TRI);
704     OS << ", " << CFI.getOffset();
705     break;
706   case MCCFIInstruction::OpDefCfaRegister:
707     OS << ".cfi_def_cfa_register ";
708     if (CFI.getLabel())
709       OS << "<mcsymbol> ";
710     printCFIRegister(CFI.getRegister(), OS, TRI);
711     break;
712   case MCCFIInstruction::OpDefCfaOffset:
713     OS << ".cfi_def_cfa_offset ";
714     if (CFI.getLabel())
715       OS << "<mcsymbol> ";
716     OS << CFI.getOffset();
717     break;
718   case MCCFIInstruction::OpDefCfa:
719     OS << ".cfi_def_cfa ";
720     if (CFI.getLabel())
721       OS << "<mcsymbol> ";
722     printCFIRegister(CFI.getRegister(), OS, TRI);
723     OS << ", " << CFI.getOffset();
724     break;
725   default:
726     // TODO: Print the other CFI Operations.
727     OS << "<unserializable cfi operation>";
728     break;
729   }
730 }
731
732 void llvm::printMIR(raw_ostream &OS, const Module &M) {
733   yaml::Output Out(OS);
734   Out << const_cast<Module &>(M);
735 }
736
737 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
738   MIRPrinter Printer(OS);
739   Printer.print(MF);
740 }