aa3031657cd59c74bf28c7ad4a05795623aeffeb
[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 convertStackObjects(yaml::MachineFunction &MF,
87                            const MachineFrameInfo &MFI,
88                            const TargetRegisterInfo *TRI);
89
90 private:
91   void initRegisterMaskIds(const MachineFunction &MF);
92 };
93
94 /// This class prints out the machine instructions using the MIR serialization
95 /// format.
96 class MIPrinter {
97   raw_ostream &OS;
98   ModuleSlotTracker &MST;
99   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
100   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
101
102 public:
103   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
104             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
105             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
106       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
107         StackObjectOperandMapping(StackObjectOperandMapping) {}
108
109   void print(const MachineBasicBlock &MBB);
110
111   void print(const MachineInstr &MI);
112   void printMBBReference(const MachineBasicBlock &MBB);
113   void printIRBlockReference(const BasicBlock &BB);
114   void printIRValueReference(const Value &V);
115   void printStackObjectReference(int FrameIndex);
116   void printOffset(int64_t Offset);
117   void printTargetFlags(const MachineOperand &Op);
118   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
119   void print(const MachineMemOperand &Op);
120
121   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
122 };
123
124 } // end namespace llvm
125
126 namespace llvm {
127 namespace yaml {
128
129 /// This struct serializes the LLVM IR module.
130 template <> struct BlockScalarTraits<Module> {
131   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
132     Mod.print(OS, nullptr);
133   }
134   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
135     llvm_unreachable("LLVM Module is supposed to be parsed separately");
136     return "";
137   }
138 };
139
140 } // end namespace yaml
141 } // end namespace llvm
142
143 static void printReg(unsigned Reg, raw_ostream &OS,
144                      const TargetRegisterInfo *TRI) {
145   // TODO: Print Stack Slots.
146   if (!Reg)
147     OS << '_';
148   else if (TargetRegisterInfo::isVirtualRegister(Reg))
149     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
150   else if (Reg < TRI->getNumRegs())
151     OS << '%' << StringRef(TRI->getName(Reg)).lower();
152   else
153     llvm_unreachable("Can't print this kind of register yet");
154 }
155
156 static void printReg(unsigned Reg, yaml::StringValue &Dest,
157                      const TargetRegisterInfo *TRI) {
158   raw_string_ostream OS(Dest.Value);
159   printReg(Reg, OS, TRI);
160 }
161
162 void MIRPrinter::print(const MachineFunction &MF) {
163   initRegisterMaskIds(MF);
164
165   yaml::MachineFunction YamlMF;
166   YamlMF.Name = MF.getName();
167   YamlMF.Alignment = MF.getAlignment();
168   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
169   YamlMF.HasInlineAsm = MF.hasInlineAsm();
170   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
171   ModuleSlotTracker MST(MF.getFunction()->getParent());
172   MST.incorporateFunction(*MF.getFunction());
173   convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo());
174   convertStackObjects(YamlMF, *MF.getFrameInfo(),
175                       MF.getSubtarget().getRegisterInfo());
176   if (const auto *ConstantPool = MF.getConstantPool())
177     convert(YamlMF, *ConstantPool);
178   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
179     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
180   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
181   bool IsNewlineNeeded = false;
182   for (const auto &MBB : MF) {
183     if (IsNewlineNeeded)
184       StrOS << "\n";
185     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
186         .print(MBB);
187     IsNewlineNeeded = true;
188   }
189   StrOS.flush();
190   yaml::Output Out(OS);
191   Out << YamlMF;
192 }
193
194 void MIRPrinter::convert(yaml::MachineFunction &MF,
195                          const MachineRegisterInfo &RegInfo,
196                          const TargetRegisterInfo *TRI) {
197   MF.IsSSA = RegInfo.isSSA();
198   MF.TracksRegLiveness = RegInfo.tracksLiveness();
199   MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
200
201   // Print the virtual register definitions.
202   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
203     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
204     yaml::VirtualRegisterDefinition VReg;
205     VReg.ID = I;
206     VReg.Class =
207         StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
208     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
209     if (PreferredReg)
210       printReg(PreferredReg, VReg.PreferredRegister, TRI);
211     MF.VirtualRegisters.push_back(VReg);
212   }
213
214   // Print the live ins.
215   for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
216     yaml::MachineFunctionLiveIn LiveIn;
217     printReg(I->first, LiveIn.Register, TRI);
218     if (I->second)
219       printReg(I->second, LiveIn.VirtualRegister, TRI);
220     MF.LiveIns.push_back(LiveIn);
221   }
222   // The used physical register mask is printed as an inverted callee saved
223   // register mask.
224   const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask();
225   if (UsedPhysRegMask.none())
226     return;
227   std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
228   for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) {
229     if (!UsedPhysRegMask[I]) {
230       yaml::FlowStringValue Reg;
231       printReg(I, Reg, TRI);
232       CalleeSavedRegisters.push_back(Reg);
233     }
234   }
235   MF.CalleeSavedRegisters = CalleeSavedRegisters;
236 }
237
238 void MIRPrinter::convert(ModuleSlotTracker &MST,
239                          yaml::MachineFrameInfo &YamlMFI,
240                          const MachineFrameInfo &MFI) {
241   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
242   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
243   YamlMFI.HasStackMap = MFI.hasStackMap();
244   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
245   YamlMFI.StackSize = MFI.getStackSize();
246   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
247   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
248   YamlMFI.AdjustsStack = MFI.adjustsStack();
249   YamlMFI.HasCalls = MFI.hasCalls();
250   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
251   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
252   YamlMFI.HasVAStart = MFI.hasVAStart();
253   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
254   if (MFI.getSavePoint()) {
255     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
256     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
257         .printMBBReference(*MFI.getSavePoint());
258   }
259   if (MFI.getRestorePoint()) {
260     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
261     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
262         .printMBBReference(*MFI.getRestorePoint());
263   }
264 }
265
266 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
267                                      const MachineFrameInfo &MFI,
268                                      const TargetRegisterInfo *TRI) {
269   // Process fixed stack objects.
270   unsigned ID = 0;
271   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
272     if (MFI.isDeadObjectIndex(I))
273       continue;
274
275     yaml::FixedMachineStackObject YamlObject;
276     YamlObject.ID = ID;
277     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
278                           ? yaml::FixedMachineStackObject::SpillSlot
279                           : yaml::FixedMachineStackObject::DefaultType;
280     YamlObject.Offset = MFI.getObjectOffset(I);
281     YamlObject.Size = MFI.getObjectSize(I);
282     YamlObject.Alignment = MFI.getObjectAlignment(I);
283     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
284     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
285     MF.FixedStackObjects.push_back(YamlObject);
286     StackObjectOperandMapping.insert(
287         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
288   }
289
290   // Process ordinary stack objects.
291   ID = 0;
292   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
293     if (MFI.isDeadObjectIndex(I))
294       continue;
295
296     yaml::MachineStackObject YamlObject;
297     YamlObject.ID = ID;
298     if (const auto *Alloca = MFI.getObjectAllocation(I))
299       YamlObject.Name.Value =
300           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
301     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
302                           ? yaml::MachineStackObject::SpillSlot
303                           : MFI.isVariableSizedObjectIndex(I)
304                                 ? yaml::MachineStackObject::VariableSized
305                                 : yaml::MachineStackObject::DefaultType;
306     YamlObject.Offset = MFI.getObjectOffset(I);
307     YamlObject.Size = MFI.getObjectSize(I);
308     YamlObject.Alignment = MFI.getObjectAlignment(I);
309
310     MF.StackObjects.push_back(YamlObject);
311     StackObjectOperandMapping.insert(std::make_pair(
312         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
313   }
314
315   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
316     yaml::StringValue Reg;
317     printReg(CSInfo.getReg(), Reg, TRI);
318     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
319     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
320            "Invalid stack object index");
321     const FrameIndexOperand &StackObject = StackObjectInfo->second;
322     if (StackObject.IsFixed)
323       MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
324     else
325       MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
326   }
327 }
328
329 void MIRPrinter::convert(yaml::MachineFunction &MF,
330                          const MachineConstantPool &ConstantPool) {
331   unsigned ID = 0;
332   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
333     // TODO: Serialize target specific constant pool entries.
334     if (Constant.isMachineConstantPoolEntry())
335       llvm_unreachable("Can't print target specific constant pool entries yet");
336
337     yaml::MachineConstantPoolValue YamlConstant;
338     std::string Str;
339     raw_string_ostream StrOS(Str);
340     Constant.Val.ConstVal->printAsOperand(StrOS);
341     YamlConstant.ID = ID++;
342     YamlConstant.Value = StrOS.str();
343     YamlConstant.Alignment = Constant.getAlignment();
344     MF.Constants.push_back(YamlConstant);
345   }
346 }
347
348 void MIRPrinter::convert(ModuleSlotTracker &MST,
349                          yaml::MachineJumpTable &YamlJTI,
350                          const MachineJumpTableInfo &JTI) {
351   YamlJTI.Kind = JTI.getEntryKind();
352   unsigned ID = 0;
353   for (const auto &Table : JTI.getJumpTables()) {
354     std::string Str;
355     yaml::MachineJumpTable::Entry Entry;
356     Entry.ID = ID++;
357     for (const auto *MBB : Table.MBBs) {
358       raw_string_ostream StrOS(Str);
359       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
360           .printMBBReference(*MBB);
361       Entry.Blocks.push_back(StrOS.str());
362       Str.clear();
363     }
364     YamlJTI.Entries.push_back(Entry);
365   }
366 }
367
368 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
369   const auto *TRI = MF.getSubtarget().getRegisterInfo();
370   unsigned I = 0;
371   for (const uint32_t *Mask : TRI->getRegMasks())
372     RegisterMaskIds.insert(std::make_pair(Mask, I++));
373 }
374
375 void MIPrinter::print(const MachineBasicBlock &MBB) {
376   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
377   OS << "bb." << MBB.getNumber();
378   bool HasAttributes = false;
379   if (const auto *BB = MBB.getBasicBlock()) {
380     if (BB->hasName()) {
381       OS << "." << BB->getName();
382     } else {
383       HasAttributes = true;
384       OS << " (";
385       int Slot = MST.getLocalSlot(BB);
386       if (Slot == -1)
387         OS << "<ir-block badref>";
388       else
389         OS << (Twine("%ir-block.") + Twine(Slot)).str();
390     }
391   }
392   if (MBB.hasAddressTaken()) {
393     OS << (HasAttributes ? ", " : " (");
394     OS << "address-taken";
395     HasAttributes = true;
396   }
397   if (MBB.isLandingPad()) {
398     OS << (HasAttributes ? ", " : " (");
399     OS << "landing-pad";
400     HasAttributes = true;
401   }
402   if (MBB.getAlignment()) {
403     OS << (HasAttributes ? ", " : " (");
404     OS << "align " << MBB.getAlignment();
405     HasAttributes = true;
406   }
407   if (HasAttributes)
408     OS << ")";
409   OS << ":\n";
410
411   bool HasLineAttributes = false;
412   // Print the successors
413   if (!MBB.succ_empty()) {
414     OS.indent(2) << "successors: ";
415     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
416       if (I != MBB.succ_begin())
417         OS << ", ";
418       printMBBReference(**I);
419       if (MBB.hasSuccessorWeights())
420         OS << '(' << MBB.getSuccWeight(I) << ')';
421     }
422     OS << "\n";
423     HasLineAttributes = true;
424   }
425
426   // Print the live in registers.
427   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
428   assert(TRI && "Expected target register info");
429   if (!MBB.livein_empty()) {
430     OS.indent(2) << "liveins: ";
431     for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
432       if (I != MBB.livein_begin())
433         OS << ", ";
434       printReg(*I, OS, TRI);
435     }
436     OS << "\n";
437     HasLineAttributes = true;
438   }
439
440   if (HasLineAttributes)
441     OS << "\n";
442   bool IsInBundle = false;
443   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
444     const MachineInstr &MI = *I;
445     if (IsInBundle && !MI.isInsideBundle()) {
446       OS.indent(2) << "}\n";
447       IsInBundle = false;
448     }
449     OS.indent(IsInBundle ? 4 : 2);
450     print(MI);
451     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
452       OS << " {";
453       IsInBundle = true;
454     }
455     OS << "\n";
456   }
457   if (IsInBundle)
458     OS.indent(2) << "}\n";
459 }
460
461 void MIPrinter::print(const MachineInstr &MI) {
462   const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
463   const auto *TRI = SubTarget.getRegisterInfo();
464   assert(TRI && "Expected target register info");
465   const auto *TII = SubTarget.getInstrInfo();
466   assert(TII && "Expected target instruction info");
467   if (MI.isCFIInstruction())
468     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
469
470   unsigned I = 0, E = MI.getNumOperands();
471   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
472          !MI.getOperand(I).isImplicit();
473        ++I) {
474     if (I)
475       OS << ", ";
476     print(MI.getOperand(I), TRI);
477   }
478
479   if (I)
480     OS << " = ";
481   if (MI.getFlag(MachineInstr::FrameSetup))
482     OS << "frame-setup ";
483   OS << TII->getName(MI.getOpcode());
484   if (I < E)
485     OS << ' ';
486
487   bool NeedComma = false;
488   for (; I < E; ++I) {
489     if (NeedComma)
490       OS << ", ";
491     print(MI.getOperand(I), TRI);
492     NeedComma = true;
493   }
494
495   if (MI.getDebugLoc()) {
496     if (NeedComma)
497       OS << ',';
498     OS << " debug-location ";
499     MI.getDebugLoc()->printAsOperand(OS, MST);
500   }
501
502   if (!MI.memoperands_empty()) {
503     OS << " :: ";
504     bool NeedComma = false;
505     for (const auto *Op : MI.memoperands()) {
506       if (NeedComma)
507         OS << ", ";
508       print(*Op);
509       NeedComma = true;
510     }
511   }
512 }
513
514 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
515   OS << "%bb." << MBB.getNumber();
516   if (const auto *BB = MBB.getBasicBlock()) {
517     if (BB->hasName())
518       OS << '.' << BB->getName();
519   }
520 }
521
522 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
523   OS << "%ir-block.";
524   if (BB.hasName()) {
525     printLLVMNameWithoutPrefix(OS, BB.getName());
526     return;
527   }
528   const Function *F = BB.getParent();
529   int Slot;
530   if (F == MST.getCurrentFunction()) {
531     Slot = MST.getLocalSlot(&BB);
532   } else {
533     ModuleSlotTracker CustomMST(F->getParent(),
534                                 /*ShouldInitializeAllMetadata=*/false);
535     CustomMST.incorporateFunction(*F);
536     Slot = CustomMST.getLocalSlot(&BB);
537   }
538   if (Slot == -1)
539     OS << "<badref>";
540   else
541     OS << Slot;
542 }
543
544 void MIPrinter::printIRValueReference(const Value &V) {
545   OS << "%ir.";
546   if (V.hasName()) {
547     printLLVMNameWithoutPrefix(OS, V.getName());
548     return;
549   }
550   // TODO: Serialize the unnamed IR value references.
551   OS << "<unserializable ir value>";
552 }
553
554 void MIPrinter::printStackObjectReference(int FrameIndex) {
555   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
556   assert(ObjectInfo != StackObjectOperandMapping.end() &&
557          "Invalid frame index");
558   const FrameIndexOperand &Operand = ObjectInfo->second;
559   if (Operand.IsFixed) {
560     OS << "%fixed-stack." << Operand.ID;
561     return;
562   }
563   OS << "%stack." << Operand.ID;
564   if (!Operand.Name.empty())
565     OS << '.' << Operand.Name;
566 }
567
568 void MIPrinter::printOffset(int64_t Offset) {
569   if (Offset == 0)
570     return;
571   if (Offset < 0) {
572     OS << " - " << -Offset;
573     return;
574   }
575   OS << " + " << Offset;
576 }
577
578 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
579   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
580   for (const auto &I : Flags) {
581     if (I.first == TF) {
582       return I.second;
583     }
584   }
585   return nullptr;
586 }
587
588 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
589   if (!Op.getTargetFlags())
590     return;
591   const auto *TII =
592       Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
593   assert(TII && "expected instruction info");
594   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
595   OS << "target-flags(";
596   if (const auto *Name = getTargetFlagName(TII, Flags.first))
597     OS << Name;
598   else
599     OS << "<unknown target flag>";
600   // TODO: Print the target's bit flags.
601   OS << ") ";
602 }
603
604 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
605   const auto *TII = MF.getSubtarget().getInstrInfo();
606   assert(TII && "expected instruction info");
607   auto Indices = TII->getSerializableTargetIndices();
608   for (const auto &I : Indices) {
609     if (I.first == Index) {
610       return I.second;
611     }
612   }
613   return nullptr;
614 }
615
616 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
617   printTargetFlags(Op);
618   switch (Op.getType()) {
619   case MachineOperand::MO_Register:
620     // FIXME: Serialize the tied register.
621     if (Op.isImplicit())
622       OS << (Op.isDef() ? "implicit-def " : "implicit ");
623     if (Op.isInternalRead())
624       OS << "internal ";
625     if (Op.isDead())
626       OS << "dead ";
627     if (Op.isKill())
628       OS << "killed ";
629     if (Op.isUndef())
630       OS << "undef ";
631     if (Op.isEarlyClobber())
632       OS << "early-clobber ";
633     if (Op.isDebug())
634       OS << "debug-use ";
635     printReg(Op.getReg(), OS, TRI);
636     // Print the sub register.
637     if (Op.getSubReg() != 0)
638       OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
639     break;
640   case MachineOperand::MO_Immediate:
641     OS << Op.getImm();
642     break;
643   case MachineOperand::MO_CImmediate:
644     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
645     break;
646   case MachineOperand::MO_FPImmediate:
647     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
648     break;
649   case MachineOperand::MO_MachineBasicBlock:
650     printMBBReference(*Op.getMBB());
651     break;
652   case MachineOperand::MO_FrameIndex:
653     printStackObjectReference(Op.getIndex());
654     break;
655   case MachineOperand::MO_ConstantPoolIndex:
656     OS << "%const." << Op.getIndex();
657     printOffset(Op.getOffset());
658     break;
659   case MachineOperand::MO_TargetIndex: {
660     OS << "target-index(";
661     if (const auto *Name = getTargetIndexName(
662             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
663       OS << Name;
664     else
665       OS << "<unknown>";
666     OS << ')';
667     printOffset(Op.getOffset());
668     break;
669   }
670   case MachineOperand::MO_JumpTableIndex:
671     OS << "%jump-table." << Op.getIndex();
672     break;
673   case MachineOperand::MO_ExternalSymbol:
674     OS << '$';
675     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
676     printOffset(Op.getOffset());
677     break;
678   case MachineOperand::MO_GlobalAddress:
679     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
680     printOffset(Op.getOffset());
681     break;
682   case MachineOperand::MO_BlockAddress:
683     OS << "blockaddress(";
684     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
685                                                         MST);
686     OS << ", ";
687     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
688     OS << ')';
689     printOffset(Op.getOffset());
690     break;
691   case MachineOperand::MO_RegisterMask: {
692     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
693     if (RegMaskInfo != RegisterMaskIds.end())
694       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
695     else
696       llvm_unreachable("Can't print this machine register mask yet.");
697     break;
698   }
699   case MachineOperand::MO_RegisterLiveOut: {
700     const uint32_t *RegMask = Op.getRegLiveOut();
701     OS << "liveout(";
702     bool IsCommaNeeded = false;
703     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
704       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
705         if (IsCommaNeeded)
706           OS << ", ";
707         printReg(Reg, OS, TRI);
708         IsCommaNeeded = true;
709       }
710     }
711     OS << ")";
712     break;
713   }
714   case MachineOperand::MO_Metadata:
715     Op.getMetadata()->printAsOperand(OS, MST);
716     break;
717   case MachineOperand::MO_CFIIndex: {
718     const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
719     print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
720     break;
721   }
722   default:
723     // TODO: Print the other machine operands.
724     llvm_unreachable("Can't print this machine operand at the moment");
725   }
726 }
727
728 void MIPrinter::print(const MachineMemOperand &Op) {
729   OS << '(';
730   // TODO: Print operand's target specific flags.
731   if (Op.isVolatile())
732     OS << "volatile ";
733   if (Op.isNonTemporal())
734     OS << "non-temporal ";
735   if (Op.isInvariant())
736     OS << "invariant ";
737   if (Op.isLoad())
738     OS << "load ";
739   else {
740     assert(Op.isStore() && "Non load machine operand must be a store");
741     OS << "store ";
742   }
743   OS << Op.getSize() << (Op.isLoad() ? " from " : " into ");
744   if (const Value *Val = Op.getValue()) {
745     printIRValueReference(*Val);
746   } else {
747     const PseudoSourceValue *PVal = Op.getPseudoValue();
748     assert(PVal && "Expected a pseudo source value");
749     switch (PVal->kind()) {
750     case PseudoSourceValue::Stack:
751       OS << "stack";
752       break;
753     case PseudoSourceValue::GOT:
754       OS << "got";
755       break;
756     case PseudoSourceValue::JumpTable:
757       OS << "jump-table";
758       break;
759     case PseudoSourceValue::ConstantPool:
760       OS << "constant-pool";
761       break;
762     case PseudoSourceValue::FixedStack:
763       printStackObjectReference(
764           cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
765       break;
766     case PseudoSourceValue::GlobalValueCallEntry:
767       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
768           OS, /*PrintType=*/false, MST);
769       break;
770     case PseudoSourceValue::ExternalSymbolCallEntry:
771       OS << '$';
772       printLLVMNameWithoutPrefix(
773           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
774       break;
775     }
776   }
777   printOffset(Op.getOffset());
778   if (Op.getBaseAlignment() != Op.getSize())
779     OS << ", align " << Op.getBaseAlignment();
780   auto AAInfo = Op.getAAInfo();
781   if (AAInfo.TBAA) {
782     OS << ", !tbaa ";
783     AAInfo.TBAA->printAsOperand(OS, MST);
784   }
785   if (AAInfo.Scope) {
786     OS << ", !alias.scope ";
787     AAInfo.Scope->printAsOperand(OS, MST);
788   }
789   if (AAInfo.NoAlias) {
790     OS << ", !noalias ";
791     AAInfo.NoAlias->printAsOperand(OS, MST);
792   }
793   // TODO: Print the ranges metadata.
794   OS << ')';
795 }
796
797 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
798                              const TargetRegisterInfo *TRI) {
799   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
800   if (Reg == -1) {
801     OS << "<badreg>";
802     return;
803   }
804   printReg(Reg, OS, TRI);
805 }
806
807 void MIPrinter::print(const MCCFIInstruction &CFI,
808                       const TargetRegisterInfo *TRI) {
809   switch (CFI.getOperation()) {
810   case MCCFIInstruction::OpSameValue:
811     OS << ".cfi_same_value ";
812     if (CFI.getLabel())
813       OS << "<mcsymbol> ";
814     printCFIRegister(CFI.getRegister(), OS, TRI);
815     break;
816   case MCCFIInstruction::OpOffset:
817     OS << ".cfi_offset ";
818     if (CFI.getLabel())
819       OS << "<mcsymbol> ";
820     printCFIRegister(CFI.getRegister(), OS, TRI);
821     OS << ", " << CFI.getOffset();
822     break;
823   case MCCFIInstruction::OpDefCfaRegister:
824     OS << ".cfi_def_cfa_register ";
825     if (CFI.getLabel())
826       OS << "<mcsymbol> ";
827     printCFIRegister(CFI.getRegister(), OS, TRI);
828     break;
829   case MCCFIInstruction::OpDefCfaOffset:
830     OS << ".cfi_def_cfa_offset ";
831     if (CFI.getLabel())
832       OS << "<mcsymbol> ";
833     OS << CFI.getOffset();
834     break;
835   case MCCFIInstruction::OpDefCfa:
836     OS << ".cfi_def_cfa ";
837     if (CFI.getLabel())
838       OS << "<mcsymbol> ";
839     printCFIRegister(CFI.getRegister(), OS, TRI);
840     OS << ", " << CFI.getOffset();
841     break;
842   default:
843     // TODO: Print the other CFI Operations.
844     OS << "<unserializable cfi operation>";
845     break;
846   }
847 }
848
849 void llvm::printMIR(raw_ostream &OS, const Module &M) {
850   yaml::Output Out(OS);
851   Out << const_cast<Module &>(M);
852 }
853
854 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
855   MIRPrinter Printer(OS);
856   Printer.print(MF);
857 }