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