LLVM  3.7.0
MIRPrinter.cpp
Go to the documentation of this file.
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"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/Module.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;
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 static void printReg(unsigned Reg, raw_ostream &OS,
94  const TargetRegisterInfo *TRI) {
95  // TODO: Print Stack Slots.
96  if (!Reg)
97  OS << '_';
99  OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
100  else if (Reg < TRI->getNumRegs())
101  OS << '%' << StringRef(TRI->getName(Reg)).lower();
102  else
103  llvm_unreachable("Can't print this kind of register yet");
104 }
105 
106 void MIRPrinter::print(const MachineFunction &MF) {
107  initRegisterMaskIds(MF);
108 
109  yaml::MachineFunction YamlMF;
110  YamlMF.Name = MF.getName();
111  YamlMF.Alignment = MF.getAlignment();
113  YamlMF.HasInlineAsm = MF.hasInlineAsm();
114  convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
115  convert(YamlMF.FrameInfo, *MF.getFrameInfo());
116  convertStackObjects(YamlMF, *MF.getFrameInfo());
117 
118  int I = 0;
120  for (const auto &MBB : MF) {
121  // TODO: Allow printing of non sequentially numbered MBBs.
122  // This is currently needed as the basic block references get their index
123  // from MBB.getNumber(), thus it should be sequential so that the parser can
124  // map back to the correct MBBs when parsing the output.
125  assert(MBB.getNumber() == I++ &&
126  "Can't print MBBs that aren't sequentially numbered");
127  (void)I;
128  yaml::MachineBasicBlock YamlMBB;
129  convert(MST, YamlMBB, MBB);
130  YamlMF.BasicBlocks.push_back(YamlMBB);
131  }
132  yaml::Output Out(OS);
133  Out << YamlMF;
134 }
135 
136 void MIRPrinter::convert(yaml::MachineFunction &MF,
137  const MachineRegisterInfo &RegInfo,
138  const TargetRegisterInfo *TRI) {
139  MF.IsSSA = RegInfo.isSSA();
140  MF.TracksRegLiveness = RegInfo.tracksLiveness();
142 
143  // Print the virtual register definitions.
144  for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
147  VReg.ID = I;
148  VReg.Class =
149  StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
150  MF.VirtualRegisters.push_back(VReg);
151  }
152 }
153 
154 void MIRPrinter::convert(yaml::MachineFrameInfo &YamlMFI,
155  const MachineFrameInfo &MFI) {
158  YamlMFI.HasStackMap = MFI.hasStackMap();
159  YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
160  YamlMFI.StackSize = MFI.getStackSize();
161  YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
162  YamlMFI.MaxAlignment = MFI.getMaxAlignment();
163  YamlMFI.AdjustsStack = MFI.adjustsStack();
164  YamlMFI.HasCalls = MFI.hasCalls();
165  YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
167  YamlMFI.HasVAStart = MFI.hasVAStart();
169 }
170 
171 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
172  const MachineFrameInfo &MFI) {
173  // Process fixed stack objects.
174  unsigned ID = 0;
175  for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
176  if (MFI.isDeadObjectIndex(I))
177  continue;
178 
180  YamlObject.ID = ID++;
181  YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
184  YamlObject.Offset = MFI.getObjectOffset(I);
185  YamlObject.Size = MFI.getObjectSize(I);
186  YamlObject.Alignment = MFI.getObjectAlignment(I);
187  YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
188  YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
189  MF.FixedStackObjects.push_back(YamlObject);
190  // TODO: Store the mapping between fixed object IDs and object indices to
191  // print the fixed stack object references correctly.
192  }
193 
194  // Process ordinary stack objects.
195  ID = 0;
196  for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
197  if (MFI.isDeadObjectIndex(I))
198  continue;
199 
200  yaml::MachineStackObject YamlObject;
201  YamlObject.ID = ID++;
202  YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
207  YamlObject.Offset = MFI.getObjectOffset(I);
208  YamlObject.Size = MFI.getObjectSize(I);
209  YamlObject.Alignment = MFI.getObjectAlignment(I);
210 
211  MF.StackObjects.push_back(YamlObject);
212  // TODO: Store the mapping between object IDs and object indices to print
213  // the stack object references correctly.
214  }
215 }
216 
217 void MIRPrinter::convert(ModuleSlotTracker &MST,
218  yaml::MachineBasicBlock &YamlMBB,
219  const MachineBasicBlock &MBB) {
220  assert(MBB.getNumber() >= 0 && "Invalid MBB number");
221  YamlMBB.ID = (unsigned)MBB.getNumber();
222  // TODO: Serialize unnamed BB references.
223  if (const auto *BB = MBB.getBasicBlock())
224  YamlMBB.Name.Value = BB->hasName() ? BB->getName() : "<unnamed bb>";
225  else
226  YamlMBB.Name.Value = "";
227  YamlMBB.Alignment = MBB.getAlignment();
228  YamlMBB.AddressTaken = MBB.hasAddressTaken();
229  YamlMBB.IsLandingPad = MBB.isLandingPad();
230  for (const auto *SuccMBB : MBB.successors()) {
231  std::string Str;
232  raw_string_ostream StrOS(Str);
233  MIPrinter(StrOS, MST, RegisterMaskIds).printMBBReference(*SuccMBB);
234  YamlMBB.Successors.push_back(StrOS.str());
235  }
236  // Print the live in registers.
237  const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
238  assert(TRI && "Expected target register info");
239  for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
240  std::string Str;
241  raw_string_ostream StrOS(Str);
242  printReg(*I, StrOS, TRI);
243  YamlMBB.LiveIns.push_back(StrOS.str());
244  }
245  // Print the machine instructions.
246  YamlMBB.Instructions.reserve(MBB.size());
247  std::string Str;
248  for (const auto &MI : MBB) {
249  raw_string_ostream StrOS(Str);
250  MIPrinter(StrOS, MST, RegisterMaskIds).print(MI);
251  YamlMBB.Instructions.push_back(StrOS.str());
252  Str.clear();
253  }
254 }
255 
256 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
257  const auto *TRI = MF.getSubtarget().getRegisterInfo();
258  unsigned I = 0;
259  for (const uint32_t *Mask : TRI->getRegMasks())
260  RegisterMaskIds.insert(std::make_pair(Mask, I++));
261 }
262 
263 void MIPrinter::print(const MachineInstr &MI) {
264  const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
265  const auto *TRI = SubTarget.getRegisterInfo();
266  assert(TRI && "Expected target register info");
267  const auto *TII = SubTarget.getInstrInfo();
268  assert(TII && "Expected target instruction info");
269 
270  unsigned I = 0, E = MI.getNumOperands();
271  for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
272  !MI.getOperand(I).isImplicit();
273  ++I) {
274  if (I)
275  OS << ", ";
276  print(MI.getOperand(I), TRI);
277  }
278 
279  if (I)
280  OS << " = ";
281  OS << TII->getName(MI.getOpcode());
282  // TODO: Print the instruction flags, machine mem operands.
283  if (I < E)
284  OS << ' ';
285 
286  bool NeedComma = false;
287  for (; I < E; ++I) {
288  if (NeedComma)
289  OS << ", ";
290  print(MI.getOperand(I), TRI);
291  NeedComma = true;
292  }
293 }
294 
295 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
296  OS << "%bb." << MBB.getNumber();
297  if (const auto *BB = MBB.getBasicBlock()) {
298  if (BB->hasName())
299  OS << '.' << BB->getName();
300  }
301 }
302 
303 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
304  switch (Op.getType()) {
306  // TODO: Print the other register flags.
307  if (Op.isImplicit())
308  OS << (Op.isDef() ? "implicit-def " : "implicit ");
309  if (Op.isDead())
310  OS << "dead ";
311  if (Op.isKill())
312  OS << "killed ";
313  if (Op.isUndef())
314  OS << "undef ";
315  printReg(Op.getReg(), OS, TRI);
316  // Print the sub register.
317  if (Op.getSubReg() != 0)
318  OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
319  break;
321  OS << Op.getImm();
322  break;
324  printMBBReference(*Op.getMBB());
325  break;
327  Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
328  // TODO: Print offset and target flags.
329  break;
331  auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
332  if (RegMaskInfo != RegisterMaskIds.end())
333  OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
334  else
335  llvm_unreachable("Can't print this machine register mask yet.");
336  break;
337  }
338  default:
339  // TODO: Print the other machine operands.
340  llvm_unreachable("Can't print this machine operand at the moment");
341  }
342 }
343 
344 void llvm::printMIR(raw_ostream &OS, const Module &M) {
345  yaml::Output Out(OS);
346  Out << const_cast<Module &>(M);
347 }
348 
350  MIRPrinter Printer(OS);
351  Printer.print(MF);
352 }
bool isImplicit() const
const MachineFunction * getParent() const
getParent - Return the MachineFunction containing this basic block.
std::vector< FlowStringValue > Successors
unsigned getAlignment() const
getAlignment - Return the alignment (log2, not bytes) of the function.
const GlobalValue * getGlobal() const
static StringRef input(StringRef Str, void *Ctxt, Module &Mod)
Definition: MIRPrinter.cpp:84
static unsigned virtReg2Index(unsigned Reg)
virtReg2Index - Convert a virtual register number to a 0-based index.
MachineBasicBlock * getMBB() const
static unsigned index2VirtReg(unsigned Index)
index2VirtReg - Convert a 0-based index to a virtual register number.
int getNumber() const
getNumber - MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a M...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
bool isDead() const
static bool isVirtualRegister(unsigned Reg)
isVirtualRegister - Return true if the specified register number is in the virtual register namespace...
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
bool isReturnAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
MachineBasicBlock reference.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
Manage lifetime of a slot tracker for printing IR.
print alias Alias Set Printer
iterator_range< succ_iterator > successors()
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW, bool ShouldPreserveUseListOrder=false) const
Print the module to an output stream with an optional AssemblyAnnotationWriter.
Definition: AsmWriter.cpp:3146
unsigned getMaxAlignment() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
Mask of preserved registers.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects...
livein_iterator livein_begin() const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const HexagonInstrInfo * TII
Serializable representation of the fixed stack object from the MachineFrameInfo class.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const TargetRegisterClass * getRegClass(unsigned Reg) const
getRegClass - Return the register class of the specified virtual register.
Reg
All possible values of the reg field in the ModR/M byte.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
bool isUndef() const
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:271
bool isVariableSizedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a variable sized object.
bool isKill() const
int getObjectIndexBegin() const
Return the minimum frame object index.
std::vector< VirtualRegisterDefinition > VirtualRegisters
int getOffsetAdjustment() const
Return the correction for frame offsets.
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:3287
const char * getRegClassName(const TargetRegisterClass *Class) const
getRegClassName - Returns the name of the register class.
bool isImmutableObjectIndex(int ObjectIdx) const
isImmutableObjectIndex - Returns true if the specified index corresponds to an immutable object...
int64_t getImm() const
const BasicBlock * getBasicBlock() const
getBasicBlock - Return the LLVM basic block that this instance corresponded to originally.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:267
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:120
std::vector< FlowStringValue > LiveIns
bool hasStackMap() const
This method may be called any time after instruction selection is complete to determine if there is a...
Address of a global value.
Serializable representation of stack object from the MachineFrameInfo class.
bool isAliasedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to an object that might be pointed to by an LLVM IR v...
livein_iterator livein_end() const
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:273
bool hasVAStart() const
Returns true if the function calls the llvm.va_start intrinsic.
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
virtual ArrayRef< const char * > getRegMaskNames() const =0
std::vector< MachineStackObject > StackObjects
Serializable representation of MachineFrameInfo.
static void printReg(unsigned Reg, raw_ostream &OS, const TargetRegisterInfo *TRI)
Definition: MIRPrinter.cpp:93
void printMIR(raw_ostream &OS, const Module &M)
Print LLVM IR using the MIR serialization format to the given output stream.
Definition: MIRPrinter.cpp:344
unsigned getSubReg() const
The Output class is used to generate a yaml document from in-memory structs and vectors.
Definition: YAMLTraits.h:1115
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
bool hasCalls() const
Return true if the current function has any function calls.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
MachineOperand class - Representation of each machine instruction operand.
unsigned getObjectAlignment(int ObjectIdx) const
Return the alignment of the specified stack object.
Module.h This file contains the declarations for the Module class.
unsigned getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call...
MachineFrameInfo * getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
std::vector< MachineBasicBlock > BasicBlocks
const char * getSubRegIndexName(unsigned SubIdx) const
getSubRegIndexName - Return the human-readable symbolic target-specific name for the specified SubReg...
std::vector< StringValue > Instructions
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:51
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
bool hasAddressTaken() const
hasAddressTaken - Test whether this block is potentially the target of an indirect branch...
bool hasPatchPoint() const
This method may be called any time after instruction selection is complete to determine if there is a...
bool isLandingPad() const
isLandingPad - Returns true if the block is a landing pad.
static void output(const Module &Mod, void *Ctxt, raw_ostream &OS)
Definition: MIRPrinter.cpp:81
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
virtual ArrayRef< const uint32_t * > getRegMasks() const =0
Return all the call-preserved register masks defined for this target.
This class should be specialized by type that requires custom conversion to/from a YAML literal block...
Definition: YAMLTraits.h:141
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
#define I(x, y, z)
Definition: MD5.cpp:54
unsigned getReg() const
getReg - Returns the register number.
std::vector< FixedMachineStackObject > FixedStackObjects
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:465
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:365
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:38
bool hasOpaqueSPAdjustment() const
Returns true if the function contains opaque dynamic stack adjustments.
const char * getName(unsigned RegNo) const
Return the human-readable symbolic target-specific name for the specified physical register...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
int getObjectIndexEnd() const
Return one past the maximum frame object index.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
std::string lower() const
Definition: StringRef.cpp:117
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool hasMustTailInVarArgFunc() const
Returns true if the function is variadic and contains a musttail call.
unsigned getAlignment() const
getAlignment - Return alignment of the basic block.