1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the class that prints out the LLVM IR and machine
11 // functions using the MIR serialization format.
13 //===----------------------------------------------------------------------===//
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"
38 /// This structure describes how to print out stack object references.
39 struct FrameIndexOperand {
44 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
45 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
47 /// Return an ordinary stack object reference.
48 static FrameIndexOperand create(StringRef Name, unsigned ID) {
49 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
52 /// Return a fixed stack object reference.
53 static FrameIndexOperand createFixed(unsigned ID) {
54 return FrameIndexOperand("", ID, /*IsFixed=*/true);
58 /// This class prints out the machine functions using the MIR serialization
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;
68 MIRPrinter(raw_ostream &OS) : OS(OS) {}
70 void print(const MachineFunction &MF);
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);
85 void initRegisterMaskIds(const MachineFunction &MF);
88 /// This class prints out the machine instructions using the MIR serialization
92 ModuleSlotTracker &MST;
93 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
94 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
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) {}
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);
108 void print(const MCCFIInstruction &CFI);
111 } // end anonymous namespace
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);
121 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
122 llvm_unreachable("LLVM Module is supposed to be parsed separately");
127 } // end namespace yaml
128 } // end namespace llvm
130 static void printReg(unsigned Reg, raw_ostream &OS,
131 const TargetRegisterInfo *TRI) {
132 // TODO: Print Stack Slots.
135 else if (TargetRegisterInfo::isVirtualRegister(Reg))
136 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
137 else if (Reg < TRI->getNumRegs())
138 OS << '%' << StringRef(TRI->getName(Reg)).lower();
140 llvm_unreachable("Can't print this kind of register yet");
143 void MIRPrinter::print(const MachineFunction &MF) {
144 initRegisterMaskIds(MF);
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);
157 ModuleSlotTracker MST(MF.getFunction()->getParent());
158 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
159 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
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");
169 yaml::MachineBasicBlock YamlMBB;
170 convert(MST, YamlMBB, MBB);
171 YamlMF.BasicBlocks.push_back(YamlMBB);
173 yaml::Output Out(OS);
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();
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;
190 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
191 MF.VirtualRegisters.push_back(VReg);
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();
212 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
213 const MachineFrameInfo &MFI) {
214 // Process fixed stack objects.
216 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
217 if (MFI.isDeadObjectIndex(I))
220 yaml::FixedMachineStackObject YamlObject;
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++)));
235 // Process ordinary stack objects.
237 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
238 if (MFI.isDeadObjectIndex(I))
241 yaml::MachineStackObject YamlObject;
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);
255 MF.StackObjects.push_back(YamlObject);
256 StackObjectOperandMapping.insert(std::make_pair(
257 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
261 void MIRPrinter::convert(yaml::MachineFunction &MF,
262 const MachineConstantPool &ConstantPool) {
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");
269 yaml::MachineConstantPoolValue YamlConstant;
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);
280 void MIRPrinter::convert(ModuleSlotTracker &MST,
281 yaml::MachineJumpTable &YamlJTI,
282 const MachineJumpTableInfo &JTI) {
283 YamlJTI.Kind = JTI.getEntryKind();
285 for (const auto &Table : JTI.getJumpTables()) {
287 yaml::MachineJumpTable::Entry Entry;
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());
296 YamlJTI.Entries.push_back(Entry);
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>";
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()) {
315 raw_string_ostream StrOS(Str);
316 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
317 .printMBBReference(*SuccMBB);
318 YamlMBB.Successors.push_back(StrOS.str());
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) {
325 raw_string_ostream StrOS(Str);
326 printReg(*I, StrOS, TRI);
327 YamlMBB.LiveIns.push_back(StrOS.str());
329 // Print the machine instructions.
330 YamlMBB.Instructions.reserve(MBB.size());
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());
340 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
341 const auto *TRI = MF.getSubtarget().getRegisterInfo();
343 for (const uint32_t *Mask : TRI->getRegMasks())
344 RegisterMaskIds.insert(std::make_pair(Mask, I++));
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");
356 unsigned I = 0, E = MI.getNumOperands();
357 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
358 !MI.getOperand(I).isImplicit();
362 print(MI.getOperand(I), TRI);
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.
374 bool NeedComma = false;
378 print(MI.getOperand(I), TRI);
383 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
384 OS << "%bb." << MBB.getNumber();
385 if (const auto *BB = MBB.getBasicBlock()) {
387 OS << '.' << BB->getName();
391 void MIPrinter::printStackObjectReference(int FrameIndex) {
392 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
393 assert(ObjectInfo != StackObjectOperandMapping.end() &&
394 "Invalid frame index");
395 const FrameIndexOperand &Operand = ObjectInfo->second;
396 if (Operand.IsFixed) {
397 OS << "%fixed-stack." << Operand.ID;
400 OS << "%stack." << Operand.ID;
401 if (!Operand.Name.empty())
402 OS << '.' << Operand.Name;
405 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
406 switch (Op.getType()) {
407 case MachineOperand::MO_Register:
408 // TODO: Print the other register flags.
410 OS << (Op.isDef() ? "implicit-def " : "implicit ");
417 printReg(Op.getReg(), OS, TRI);
418 // Print the sub register.
419 if (Op.getSubReg() != 0)
420 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
422 case MachineOperand::MO_Immediate:
425 case MachineOperand::MO_MachineBasicBlock:
426 printMBBReference(*Op.getMBB());
428 case MachineOperand::MO_FrameIndex:
429 printStackObjectReference(Op.getIndex());
431 case MachineOperand::MO_ConstantPoolIndex:
432 OS << "%const." << Op.getIndex();
433 // TODO: Print offset and target flags.
435 case MachineOperand::MO_JumpTableIndex:
436 OS << "%jump-table." << Op.getIndex();
437 // TODO: Print target flags.
439 case MachineOperand::MO_ExternalSymbol:
441 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
442 // TODO: Print the target flags.
444 case MachineOperand::MO_GlobalAddress:
445 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
446 // TODO: Print offset and target flags.
448 case MachineOperand::MO_RegisterMask: {
449 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
450 if (RegMaskInfo != RegisterMaskIds.end())
451 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
453 llvm_unreachable("Can't print this machine register mask yet.");
456 case MachineOperand::MO_CFIIndex: {
457 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
458 print(MMI.getFrameInstructions()[Op.getCFIIndex()]);
462 // TODO: Print the other machine operands.
463 llvm_unreachable("Can't print this machine operand at the moment");
467 void MIPrinter::print(const MCCFIInstruction &CFI) {
468 switch (CFI.getOperation()) {
469 case MCCFIInstruction::OpDefCfaOffset:
470 OS << ".cfi_def_cfa_offset ";
473 OS << CFI.getOffset();
476 // TODO: Print the other CFI Operations.
477 OS << "<unserializable cfi operation>";
482 void llvm::printMIR(raw_ostream &OS, const Module &M) {
483 yaml::Output Out(OS);
484 Out << const_cast<Module &>(M);
487 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
488 MIRPrinter Printer(OS);