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