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