MIR Serialization: Serialize UsedPhysRegMask from the machine register info.
[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   // The used physical register mask is printed as an inverted callee saved
222   // register mask.
223   const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask();
224   if (UsedPhysRegMask.none())
225     return;
226   std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
227   for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) {
228     if (!UsedPhysRegMask[I]) {
229       yaml::FlowStringValue Reg;
230       printReg(I, Reg, TRI);
231       CalleeSavedRegisters.push_back(Reg);
232     }
233   }
234   MF.CalleeSavedRegisters = CalleeSavedRegisters;
235 }
236
237 void MIRPrinter::convert(ModuleSlotTracker &MST,
238                          yaml::MachineFrameInfo &YamlMFI,
239                          const MachineFrameInfo &MFI) {
240   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
241   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
242   YamlMFI.HasStackMap = MFI.hasStackMap();
243   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
244   YamlMFI.StackSize = MFI.getStackSize();
245   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
246   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
247   YamlMFI.AdjustsStack = MFI.adjustsStack();
248   YamlMFI.HasCalls = MFI.hasCalls();
249   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
250   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
251   YamlMFI.HasVAStart = MFI.hasVAStart();
252   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
253   if (MFI.getSavePoint()) {
254     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
255     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
256         .printMBBReference(*MFI.getSavePoint());
257   }
258   if (MFI.getRestorePoint()) {
259     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
260     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
261         .printMBBReference(*MFI.getRestorePoint());
262   }
263 }
264
265 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
266                                      const MachineFrameInfo &MFI,
267                                      const TargetRegisterInfo *TRI) {
268   // Process fixed stack objects.
269   unsigned ID = 0;
270   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
271     if (MFI.isDeadObjectIndex(I))
272       continue;
273
274     yaml::FixedMachineStackObject YamlObject;
275     YamlObject.ID = ID;
276     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
277                           ? yaml::FixedMachineStackObject::SpillSlot
278                           : yaml::FixedMachineStackObject::DefaultType;
279     YamlObject.Offset = MFI.getObjectOffset(I);
280     YamlObject.Size = MFI.getObjectSize(I);
281     YamlObject.Alignment = MFI.getObjectAlignment(I);
282     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
283     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
284     MF.FixedStackObjects.push_back(YamlObject);
285     StackObjectOperandMapping.insert(
286         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
287   }
288
289   // Process ordinary stack objects.
290   ID = 0;
291   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
292     if (MFI.isDeadObjectIndex(I))
293       continue;
294
295     yaml::MachineStackObject YamlObject;
296     YamlObject.ID = ID;
297     if (const auto *Alloca = MFI.getObjectAllocation(I))
298       YamlObject.Name.Value =
299           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
300     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
301                           ? yaml::MachineStackObject::SpillSlot
302                           : MFI.isVariableSizedObjectIndex(I)
303                                 ? yaml::MachineStackObject::VariableSized
304                                 : yaml::MachineStackObject::DefaultType;
305     YamlObject.Offset = MFI.getObjectOffset(I);
306     YamlObject.Size = MFI.getObjectSize(I);
307     YamlObject.Alignment = MFI.getObjectAlignment(I);
308
309     MF.StackObjects.push_back(YamlObject);
310     StackObjectOperandMapping.insert(std::make_pair(
311         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
312   }
313
314   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
315     yaml::StringValue Reg;
316     printReg(CSInfo.getReg(), Reg, TRI);
317     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
318     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
319            "Invalid stack object index");
320     const FrameIndexOperand &StackObject = StackObjectInfo->second;
321     if (StackObject.IsFixed)
322       MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
323     else
324       MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
325   }
326 }
327
328 void MIRPrinter::convert(yaml::MachineFunction &MF,
329                          const MachineConstantPool &ConstantPool) {
330   unsigned ID = 0;
331   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
332     // TODO: Serialize target specific constant pool entries.
333     if (Constant.isMachineConstantPoolEntry())
334       llvm_unreachable("Can't print target specific constant pool entries yet");
335
336     yaml::MachineConstantPoolValue YamlConstant;
337     std::string Str;
338     raw_string_ostream StrOS(Str);
339     Constant.Val.ConstVal->printAsOperand(StrOS);
340     YamlConstant.ID = ID++;
341     YamlConstant.Value = StrOS.str();
342     YamlConstant.Alignment = Constant.getAlignment();
343     MF.Constants.push_back(YamlConstant);
344   }
345 }
346
347 void MIRPrinter::convert(ModuleSlotTracker &MST,
348                          yaml::MachineJumpTable &YamlJTI,
349                          const MachineJumpTableInfo &JTI) {
350   YamlJTI.Kind = JTI.getEntryKind();
351   unsigned ID = 0;
352   for (const auto &Table : JTI.getJumpTables()) {
353     std::string Str;
354     yaml::MachineJumpTable::Entry Entry;
355     Entry.ID = ID++;
356     for (const auto *MBB : Table.MBBs) {
357       raw_string_ostream StrOS(Str);
358       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
359           .printMBBReference(*MBB);
360       Entry.Blocks.push_back(StrOS.str());
361       Str.clear();
362     }
363     YamlJTI.Entries.push_back(Entry);
364   }
365 }
366
367 void MIRPrinter::convert(ModuleSlotTracker &MST,
368                          yaml::MachineBasicBlock &YamlMBB,
369                          const MachineBasicBlock &MBB) {
370   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
371   YamlMBB.ID = (unsigned)MBB.getNumber();
372   if (const auto *BB = MBB.getBasicBlock()) {
373     if (BB->hasName()) {
374       YamlMBB.Name.Value = BB->getName();
375     } else {
376       int Slot = MST.getLocalSlot(BB);
377       if (Slot == -1)
378         YamlMBB.IRBlock.Value = "<badref>";
379       else
380         YamlMBB.IRBlock.Value = (Twine("%ir-block.") + Twine(Slot)).str();
381     }
382   }
383   YamlMBB.Alignment = MBB.getAlignment();
384   YamlMBB.AddressTaken = MBB.hasAddressTaken();
385   YamlMBB.IsLandingPad = MBB.isLandingPad();
386   for (const auto *SuccMBB : MBB.successors()) {
387     std::string Str;
388     raw_string_ostream StrOS(Str);
389     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
390         .printMBBReference(*SuccMBB);
391     YamlMBB.Successors.push_back(StrOS.str());
392   }
393   if (MBB.hasSuccessorWeights()) {
394     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I)
395       YamlMBB.SuccessorWeights.push_back(
396           yaml::UnsignedValue(MBB.getSuccWeight(I)));
397   }
398   // Print the live in registers.
399   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
400   assert(TRI && "Expected target register info");
401   for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
402     std::string Str;
403     raw_string_ostream StrOS(Str);
404     printReg(*I, StrOS, TRI);
405     YamlMBB.LiveIns.push_back(StrOS.str());
406   }
407   // Print the machine instructions.
408   YamlMBB.Instructions.reserve(MBB.size());
409   std::string Str;
410   for (const auto &MI : MBB) {
411     raw_string_ostream StrOS(Str);
412     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
413     YamlMBB.Instructions.push_back(StrOS.str());
414     Str.clear();
415   }
416 }
417
418 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
419   const auto *TRI = MF.getSubtarget().getRegisterInfo();
420   unsigned I = 0;
421   for (const uint32_t *Mask : TRI->getRegMasks())
422     RegisterMaskIds.insert(std::make_pair(Mask, I++));
423 }
424
425 void MIPrinter::print(const MachineInstr &MI) {
426   const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
427   const auto *TRI = SubTarget.getRegisterInfo();
428   assert(TRI && "Expected target register info");
429   const auto *TII = SubTarget.getInstrInfo();
430   assert(TII && "Expected target instruction info");
431   if (MI.isCFIInstruction())
432     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
433
434   unsigned I = 0, E = MI.getNumOperands();
435   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
436          !MI.getOperand(I).isImplicit();
437        ++I) {
438     if (I)
439       OS << ", ";
440     print(MI.getOperand(I), TRI);
441   }
442
443   if (I)
444     OS << " = ";
445   if (MI.getFlag(MachineInstr::FrameSetup))
446     OS << "frame-setup ";
447   OS << TII->getName(MI.getOpcode());
448   // TODO: Print the bundling instruction flags.
449   if (I < E)
450     OS << ' ';
451
452   bool NeedComma = false;
453   for (; I < E; ++I) {
454     if (NeedComma)
455       OS << ", ";
456     print(MI.getOperand(I), TRI);
457     NeedComma = true;
458   }
459
460   if (MI.getDebugLoc()) {
461     if (NeedComma)
462       OS << ',';
463     OS << " debug-location ";
464     MI.getDebugLoc()->printAsOperand(OS, MST);
465   }
466
467   if (!MI.memoperands_empty()) {
468     OS << " :: ";
469     bool NeedComma = false;
470     for (const auto *Op : MI.memoperands()) {
471       if (NeedComma)
472         OS << ", ";
473       print(*Op);
474       NeedComma = true;
475     }
476   }
477 }
478
479 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
480   OS << "%bb." << MBB.getNumber();
481   if (const auto *BB = MBB.getBasicBlock()) {
482     if (BB->hasName())
483       OS << '.' << BB->getName();
484   }
485 }
486
487 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
488   OS << "%ir-block.";
489   if (BB.hasName()) {
490     printLLVMNameWithoutPrefix(OS, BB.getName());
491     return;
492   }
493   const Function *F = BB.getParent();
494   int Slot;
495   if (F == MST.getCurrentFunction()) {
496     Slot = MST.getLocalSlot(&BB);
497   } else {
498     ModuleSlotTracker CustomMST(F->getParent(),
499                                 /*ShouldInitializeAllMetadata=*/false);
500     CustomMST.incorporateFunction(*F);
501     Slot = CustomMST.getLocalSlot(&BB);
502   }
503   if (Slot == -1)
504     OS << "<badref>";
505   else
506     OS << Slot;
507 }
508
509 void MIPrinter::printIRValueReference(const Value &V) {
510   OS << "%ir.";
511   if (V.hasName()) {
512     printLLVMNameWithoutPrefix(OS, V.getName());
513     return;
514   }
515   // TODO: Serialize the unnamed IR value references.
516   OS << "<unserializable ir value>";
517 }
518
519 void MIPrinter::printStackObjectReference(int FrameIndex) {
520   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
521   assert(ObjectInfo != StackObjectOperandMapping.end() &&
522          "Invalid frame index");
523   const FrameIndexOperand &Operand = ObjectInfo->second;
524   if (Operand.IsFixed) {
525     OS << "%fixed-stack." << Operand.ID;
526     return;
527   }
528   OS << "%stack." << Operand.ID;
529   if (!Operand.Name.empty())
530     OS << '.' << Operand.Name;
531 }
532
533 void MIPrinter::printOffset(int64_t Offset) {
534   if (Offset == 0)
535     return;
536   if (Offset < 0) {
537     OS << " - " << -Offset;
538     return;
539   }
540   OS << " + " << Offset;
541 }
542
543 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
544   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
545   for (const auto &I : Flags) {
546     if (I.first == TF) {
547       return I.second;
548     }
549   }
550   return nullptr;
551 }
552
553 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
554   if (!Op.getTargetFlags())
555     return;
556   const auto *TII =
557       Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
558   assert(TII && "expected instruction info");
559   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
560   OS << "target-flags(";
561   if (const auto *Name = getTargetFlagName(TII, Flags.first))
562     OS << Name;
563   else
564     OS << "<unknown target flag>";
565   // TODO: Print the target's bit flags.
566   OS << ") ";
567 }
568
569 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
570   const auto *TII = MF.getSubtarget().getInstrInfo();
571   assert(TII && "expected instruction info");
572   auto Indices = TII->getSerializableTargetIndices();
573   for (const auto &I : Indices) {
574     if (I.first == Index) {
575       return I.second;
576     }
577   }
578   return nullptr;
579 }
580
581 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
582   printTargetFlags(Op);
583   switch (Op.getType()) {
584   case MachineOperand::MO_Register:
585     // TODO: Print the other register flags.
586     if (Op.isImplicit())
587       OS << (Op.isDef() ? "implicit-def " : "implicit ");
588     if (Op.isDead())
589       OS << "dead ";
590     if (Op.isKill())
591       OS << "killed ";
592     if (Op.isUndef())
593       OS << "undef ";
594     if (Op.isEarlyClobber())
595       OS << "early-clobber ";
596     if (Op.isDebug())
597       OS << "debug-use ";
598     printReg(Op.getReg(), OS, TRI);
599     // Print the sub register.
600     if (Op.getSubReg() != 0)
601       OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
602     break;
603   case MachineOperand::MO_Immediate:
604     OS << Op.getImm();
605     break;
606   case MachineOperand::MO_CImmediate:
607     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
608     break;
609   case MachineOperand::MO_FPImmediate:
610     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
611     break;
612   case MachineOperand::MO_MachineBasicBlock:
613     printMBBReference(*Op.getMBB());
614     break;
615   case MachineOperand::MO_FrameIndex:
616     printStackObjectReference(Op.getIndex());
617     break;
618   case MachineOperand::MO_ConstantPoolIndex:
619     OS << "%const." << Op.getIndex();
620     printOffset(Op.getOffset());
621     break;
622   case MachineOperand::MO_TargetIndex: {
623     OS << "target-index(";
624     if (const auto *Name = getTargetIndexName(
625             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
626       OS << Name;
627     else
628       OS << "<unknown>";
629     OS << ')';
630     printOffset(Op.getOffset());
631     break;
632   }
633   case MachineOperand::MO_JumpTableIndex:
634     OS << "%jump-table." << Op.getIndex();
635     break;
636   case MachineOperand::MO_ExternalSymbol:
637     OS << '$';
638     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
639     printOffset(Op.getOffset());
640     break;
641   case MachineOperand::MO_GlobalAddress:
642     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
643     printOffset(Op.getOffset());
644     break;
645   case MachineOperand::MO_BlockAddress:
646     OS << "blockaddress(";
647     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
648                                                         MST);
649     OS << ", ";
650     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
651     OS << ')';
652     printOffset(Op.getOffset());
653     break;
654   case MachineOperand::MO_RegisterMask: {
655     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
656     if (RegMaskInfo != RegisterMaskIds.end())
657       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
658     else
659       llvm_unreachable("Can't print this machine register mask yet.");
660     break;
661   }
662   case MachineOperand::MO_RegisterLiveOut: {
663     const uint32_t *RegMask = Op.getRegLiveOut();
664     OS << "liveout(";
665     bool IsCommaNeeded = false;
666     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
667       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
668         if (IsCommaNeeded)
669           OS << ", ";
670         printReg(Reg, OS, TRI);
671         IsCommaNeeded = true;
672       }
673     }
674     OS << ")";
675     break;
676   }
677   case MachineOperand::MO_Metadata:
678     Op.getMetadata()->printAsOperand(OS, MST);
679     break;
680   case MachineOperand::MO_CFIIndex: {
681     const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
682     print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
683     break;
684   }
685   default:
686     // TODO: Print the other machine operands.
687     llvm_unreachable("Can't print this machine operand at the moment");
688   }
689 }
690
691 void MIPrinter::print(const MachineMemOperand &Op) {
692   OS << '(';
693   // TODO: Print operand's target specific flags.
694   if (Op.isVolatile())
695     OS << "volatile ";
696   if (Op.isNonTemporal())
697     OS << "non-temporal ";
698   if (Op.isInvariant())
699     OS << "invariant ";
700   if (Op.isLoad())
701     OS << "load ";
702   else {
703     assert(Op.isStore() && "Non load machine operand must be a store");
704     OS << "store ";
705   }
706   OS << Op.getSize() << (Op.isLoad() ? " from " : " into ");
707   if (const Value *Val = Op.getValue())
708     printIRValueReference(*Val);
709   // TODO: Print PseudoSourceValue.
710   printOffset(Op.getOffset());
711   if (Op.getBaseAlignment() != Op.getSize())
712     OS << ", align " << Op.getBaseAlignment();
713   // TODO: Print the metadata attributes.
714   OS << ')';
715 }
716
717 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
718                              const TargetRegisterInfo *TRI) {
719   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
720   if (Reg == -1) {
721     OS << "<badreg>";
722     return;
723   }
724   printReg(Reg, OS, TRI);
725 }
726
727 void MIPrinter::print(const MCCFIInstruction &CFI,
728                       const TargetRegisterInfo *TRI) {
729   switch (CFI.getOperation()) {
730   case MCCFIInstruction::OpOffset:
731     OS << ".cfi_offset ";
732     if (CFI.getLabel())
733       OS << "<mcsymbol> ";
734     printCFIRegister(CFI.getRegister(), OS, TRI);
735     OS << ", " << CFI.getOffset();
736     break;
737   case MCCFIInstruction::OpDefCfaRegister:
738     OS << ".cfi_def_cfa_register ";
739     if (CFI.getLabel())
740       OS << "<mcsymbol> ";
741     printCFIRegister(CFI.getRegister(), OS, TRI);
742     break;
743   case MCCFIInstruction::OpDefCfaOffset:
744     OS << ".cfi_def_cfa_offset ";
745     if (CFI.getLabel())
746       OS << "<mcsymbol> ";
747     OS << CFI.getOffset();
748     break;
749   case MCCFIInstruction::OpDefCfa:
750     OS << ".cfi_def_cfa ";
751     if (CFI.getLabel())
752       OS << "<mcsymbol> ";
753     printCFIRegister(CFI.getRegister(), OS, TRI);
754     OS << ", " << CFI.getOffset();
755     break;
756   default:
757     // TODO: Print the other CFI Operations.
758     OS << "<unserializable cfi operation>";
759     break;
760   }
761 }
762
763 void llvm::printMIR(raw_ostream &OS, const Module &M) {
764   yaml::Output Out(OS);
765   Out << const_cast<Module &>(M);
766 }
767
768 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
769   MIRPrinter Printer(OS);
770   Printer.print(MF);
771 }