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