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