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