MIR Serialization: Serialize the jump table index operands.
[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/MachineFunction.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/MIRYamlMapping.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/ModuleSlotTracker.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/YAMLTraits.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetSubtargetInfo.h"
30
31 using namespace llvm;
32
33 namespace {
34
35 /// This class prints out the machine functions using the MIR serialization
36 /// format.
37 class MIRPrinter {
38   raw_ostream &OS;
39   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
40
41 public:
42   MIRPrinter(raw_ostream &OS) : OS(OS) {}
43
44   void print(const MachineFunction &MF);
45
46   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
47                const TargetRegisterInfo *TRI);
48   void convert(yaml::MachineFrameInfo &YamlMFI, const MachineFrameInfo &MFI);
49   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
50                const MachineJumpTableInfo &JTI);
51   void convert(ModuleSlotTracker &MST, yaml::MachineBasicBlock &YamlMBB,
52                const MachineBasicBlock &MBB);
53   void convertStackObjects(yaml::MachineFunction &MF,
54                            const MachineFrameInfo &MFI);
55
56 private:
57   void initRegisterMaskIds(const MachineFunction &MF);
58 };
59
60 /// This class prints out the machine instructions using the MIR serialization
61 /// format.
62 class MIPrinter {
63   raw_ostream &OS;
64   ModuleSlotTracker &MST;
65   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
66
67 public:
68   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
69             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds)
70       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds) {}
71
72   void print(const MachineInstr &MI);
73   void printMBBReference(const MachineBasicBlock &MBB);
74   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
75 };
76
77 } // end anonymous namespace
78
79 namespace llvm {
80 namespace yaml {
81
82 /// This struct serializes the LLVM IR module.
83 template <> struct BlockScalarTraits<Module> {
84   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
85     Mod.print(OS, nullptr);
86   }
87   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
88     llvm_unreachable("LLVM Module is supposed to be parsed separately");
89     return "";
90   }
91 };
92
93 } // end namespace yaml
94 } // end namespace llvm
95
96 static void printReg(unsigned Reg, raw_ostream &OS,
97                      const TargetRegisterInfo *TRI) {
98   // TODO: Print Stack Slots.
99   if (!Reg)
100     OS << '_';
101   else if (TargetRegisterInfo::isVirtualRegister(Reg))
102     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
103   else if (Reg < TRI->getNumRegs())
104     OS << '%' << StringRef(TRI->getName(Reg)).lower();
105   else
106     llvm_unreachable("Can't print this kind of register yet");
107 }
108
109 void MIRPrinter::print(const MachineFunction &MF) {
110   initRegisterMaskIds(MF);
111
112   yaml::MachineFunction YamlMF;
113   YamlMF.Name = MF.getName();
114   YamlMF.Alignment = MF.getAlignment();
115   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
116   YamlMF.HasInlineAsm = MF.hasInlineAsm();
117   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
118   convert(YamlMF.FrameInfo, *MF.getFrameInfo());
119   convertStackObjects(YamlMF, *MF.getFrameInfo());
120
121   ModuleSlotTracker MST(MF.getFunction()->getParent());
122   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
123     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
124   int I = 0;
125   for (const auto &MBB : MF) {
126     // TODO: Allow printing of non sequentially numbered MBBs.
127     // This is currently needed as the basic block references get their index
128     // from MBB.getNumber(), thus it should be sequential so that the parser can
129     // map back to the correct MBBs when parsing the output.
130     assert(MBB.getNumber() == I++ &&
131            "Can't print MBBs that aren't sequentially numbered");
132     (void)I;
133     yaml::MachineBasicBlock YamlMBB;
134     convert(MST, YamlMBB, MBB);
135     YamlMF.BasicBlocks.push_back(YamlMBB);
136   }
137   yaml::Output Out(OS);
138   Out << YamlMF;
139 }
140
141 void MIRPrinter::convert(yaml::MachineFunction &MF,
142                          const MachineRegisterInfo &RegInfo,
143                          const TargetRegisterInfo *TRI) {
144   MF.IsSSA = RegInfo.isSSA();
145   MF.TracksRegLiveness = RegInfo.tracksLiveness();
146   MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
147
148   // Print the virtual register definitions.
149   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
150     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
151     yaml::VirtualRegisterDefinition VReg;
152     VReg.ID = I;
153     VReg.Class =
154         StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
155     MF.VirtualRegisters.push_back(VReg);
156   }
157 }
158
159 void MIRPrinter::convert(yaml::MachineFrameInfo &YamlMFI,
160                          const MachineFrameInfo &MFI) {
161   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
162   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
163   YamlMFI.HasStackMap = MFI.hasStackMap();
164   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
165   YamlMFI.StackSize = MFI.getStackSize();
166   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
167   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
168   YamlMFI.AdjustsStack = MFI.adjustsStack();
169   YamlMFI.HasCalls = MFI.hasCalls();
170   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
171   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
172   YamlMFI.HasVAStart = MFI.hasVAStart();
173   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
174 }
175
176 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
177                                      const MachineFrameInfo &MFI) {
178   // Process fixed stack objects.
179   unsigned ID = 0;
180   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
181     if (MFI.isDeadObjectIndex(I))
182       continue;
183
184     yaml::FixedMachineStackObject YamlObject;
185     YamlObject.ID = ID++;
186     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
187                           ? yaml::FixedMachineStackObject::SpillSlot
188                           : yaml::FixedMachineStackObject::DefaultType;
189     YamlObject.Offset = MFI.getObjectOffset(I);
190     YamlObject.Size = MFI.getObjectSize(I);
191     YamlObject.Alignment = MFI.getObjectAlignment(I);
192     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
193     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
194     MF.FixedStackObjects.push_back(YamlObject);
195     // TODO: Store the mapping between fixed object IDs and object indices to
196     // print the fixed stack object references correctly.
197   }
198
199   // Process ordinary stack objects.
200   ID = 0;
201   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
202     if (MFI.isDeadObjectIndex(I))
203       continue;
204
205     yaml::MachineStackObject YamlObject;
206     YamlObject.ID = ID++;
207     if (const auto *Alloca = MFI.getObjectAllocation(I))
208       YamlObject.Name.Value =
209           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
210     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
211                           ? yaml::MachineStackObject::SpillSlot
212                           : MFI.isVariableSizedObjectIndex(I)
213                                 ? yaml::MachineStackObject::VariableSized
214                                 : yaml::MachineStackObject::DefaultType;
215     YamlObject.Offset = MFI.getObjectOffset(I);
216     YamlObject.Size = MFI.getObjectSize(I);
217     YamlObject.Alignment = MFI.getObjectAlignment(I);
218
219     MF.StackObjects.push_back(YamlObject);
220     // TODO: Store the mapping between object IDs and object indices to print
221     // the stack object references correctly.
222   }
223 }
224
225 void MIRPrinter::convert(ModuleSlotTracker &MST,
226                          yaml::MachineJumpTable &YamlJTI,
227                          const MachineJumpTableInfo &JTI) {
228   YamlJTI.Kind = JTI.getEntryKind();
229   unsigned ID = 0;
230   for (const auto &Table : JTI.getJumpTables()) {
231     std::string Str;
232     yaml::MachineJumpTable::Entry Entry;
233     Entry.ID = ID++;
234     for (const auto *MBB : Table.MBBs) {
235       raw_string_ostream StrOS(Str);
236       MIPrinter(StrOS, MST, RegisterMaskIds).printMBBReference(*MBB);
237       Entry.Blocks.push_back(StrOS.str());
238       Str.clear();
239     }
240     YamlJTI.Entries.push_back(Entry);
241   }
242 }
243
244 void MIRPrinter::convert(ModuleSlotTracker &MST,
245                          yaml::MachineBasicBlock &YamlMBB,
246                          const MachineBasicBlock &MBB) {
247   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
248   YamlMBB.ID = (unsigned)MBB.getNumber();
249   // TODO: Serialize unnamed BB references.
250   if (const auto *BB = MBB.getBasicBlock())
251     YamlMBB.Name.Value = BB->hasName() ? BB->getName() : "<unnamed bb>";
252   else
253     YamlMBB.Name.Value = "";
254   YamlMBB.Alignment = MBB.getAlignment();
255   YamlMBB.AddressTaken = MBB.hasAddressTaken();
256   YamlMBB.IsLandingPad = MBB.isLandingPad();
257   for (const auto *SuccMBB : MBB.successors()) {
258     std::string Str;
259     raw_string_ostream StrOS(Str);
260     MIPrinter(StrOS, MST, RegisterMaskIds).printMBBReference(*SuccMBB);
261     YamlMBB.Successors.push_back(StrOS.str());
262   }
263   // Print the live in registers.
264   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
265   assert(TRI && "Expected target register info");
266   for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
267     std::string Str;
268     raw_string_ostream StrOS(Str);
269     printReg(*I, StrOS, TRI);
270     YamlMBB.LiveIns.push_back(StrOS.str());
271   }
272   // Print the machine instructions.
273   YamlMBB.Instructions.reserve(MBB.size());
274   std::string Str;
275   for (const auto &MI : MBB) {
276     raw_string_ostream StrOS(Str);
277     MIPrinter(StrOS, MST, RegisterMaskIds).print(MI);
278     YamlMBB.Instructions.push_back(StrOS.str());
279     Str.clear();
280   }
281 }
282
283 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
284   const auto *TRI = MF.getSubtarget().getRegisterInfo();
285   unsigned I = 0;
286   for (const uint32_t *Mask : TRI->getRegMasks())
287     RegisterMaskIds.insert(std::make_pair(Mask, I++));
288 }
289
290 void MIPrinter::print(const MachineInstr &MI) {
291   const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
292   const auto *TRI = SubTarget.getRegisterInfo();
293   assert(TRI && "Expected target register info");
294   const auto *TII = SubTarget.getInstrInfo();
295   assert(TII && "Expected target instruction info");
296
297   unsigned I = 0, E = MI.getNumOperands();
298   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
299          !MI.getOperand(I).isImplicit();
300        ++I) {
301     if (I)
302       OS << ", ";
303     print(MI.getOperand(I), TRI);
304   }
305
306   if (I)
307     OS << " = ";
308   OS << TII->getName(MI.getOpcode());
309   // TODO: Print the instruction flags, machine mem operands.
310   if (I < E)
311     OS << ' ';
312
313   bool NeedComma = false;
314   for (; I < E; ++I) {
315     if (NeedComma)
316       OS << ", ";
317     print(MI.getOperand(I), TRI);
318     NeedComma = true;
319   }
320 }
321
322 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
323   OS << "%bb." << MBB.getNumber();
324   if (const auto *BB = MBB.getBasicBlock()) {
325     if (BB->hasName())
326       OS << '.' << BB->getName();
327   }
328 }
329
330 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
331   switch (Op.getType()) {
332   case MachineOperand::MO_Register:
333     // TODO: Print the other register flags.
334     if (Op.isImplicit())
335       OS << (Op.isDef() ? "implicit-def " : "implicit ");
336     if (Op.isDead())
337       OS << "dead ";
338     if (Op.isKill())
339       OS << "killed ";
340     if (Op.isUndef())
341       OS << "undef ";
342     printReg(Op.getReg(), OS, TRI);
343     // Print the sub register.
344     if (Op.getSubReg() != 0)
345       OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
346     break;
347   case MachineOperand::MO_Immediate:
348     OS << Op.getImm();
349     break;
350   case MachineOperand::MO_MachineBasicBlock:
351     printMBBReference(*Op.getMBB());
352     break;
353   case MachineOperand::MO_JumpTableIndex:
354     OS << "%jump-table." << Op.getIndex();
355     // TODO: Print target flags.
356     break;
357   case MachineOperand::MO_GlobalAddress:
358     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
359     // TODO: Print offset and target flags.
360     break;
361   case MachineOperand::MO_RegisterMask: {
362     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
363     if (RegMaskInfo != RegisterMaskIds.end())
364       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
365     else
366       llvm_unreachable("Can't print this machine register mask yet.");
367     break;
368   }
369   default:
370     // TODO: Print the other machine operands.
371     llvm_unreachable("Can't print this machine operand at the moment");
372   }
373 }
374
375 void llvm::printMIR(raw_ostream &OS, const Module &M) {
376   yaml::Output Out(OS);
377   Out << const_cast<Module &>(M);
378 }
379
380 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
381   MIRPrinter Printer(OS);
382   Printer.print(MF);
383 }