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,
83 const TargetRegisterInfo *TRI);
86 void initRegisterMaskIds(const MachineFunction &MF);
89 /// This class prints out the machine instructions using the MIR serialization
93 ModuleSlotTracker &MST;
94 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
95 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
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) {}
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);
109 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
112 } // end anonymous namespace
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);
122 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
123 llvm_unreachable("LLVM Module is supposed to be parsed separately");
128 } // end namespace yaml
129 } // end namespace llvm
131 static void printReg(unsigned Reg, raw_ostream &OS,
132 const TargetRegisterInfo *TRI) {
133 // TODO: Print Stack Slots.
136 else if (TargetRegisterInfo::isVirtualRegister(Reg))
137 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
138 else if (Reg < TRI->getNumRegs())
139 OS << '%' << StringRef(TRI->getName(Reg)).lower();
141 llvm_unreachable("Can't print this kind of register yet");
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);
150 void MIRPrinter::print(const MachineFunction &MF) {
151 initRegisterMaskIds(MF);
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);
165 ModuleSlotTracker MST(MF.getFunction()->getParent());
166 MST.incorporateFunction(*MF.getFunction());
167 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
168 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
170 for (const auto &MBB : MF) {
171 // TODO: Allow printing of non sequentially numbered MBBs.
172 // This is currently needed as the basic block references get their index
173 // from MBB.getNumber(), thus it should be sequential so that the parser can
174 // map back to the correct MBBs when parsing the output.
175 assert(MBB.getNumber() == I++ &&
176 "Can't print MBBs that aren't sequentially numbered");
178 yaml::MachineBasicBlock YamlMBB;
179 convert(MST, YamlMBB, MBB);
180 YamlMF.BasicBlocks.push_back(YamlMBB);
182 yaml::Output Out(OS);
186 void MIRPrinter::convert(yaml::MachineFunction &MF,
187 const MachineRegisterInfo &RegInfo,
188 const TargetRegisterInfo *TRI) {
189 MF.IsSSA = RegInfo.isSSA();
190 MF.TracksRegLiveness = RegInfo.tracksLiveness();
191 MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
193 // Print the virtual register definitions.
194 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
195 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
196 yaml::VirtualRegisterDefinition VReg;
199 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
200 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
202 printReg(PreferredReg, VReg.PreferredRegister, TRI);
203 MF.VirtualRegisters.push_back(VReg);
206 // Print the live ins.
207 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
208 yaml::MachineFunctionLiveIn LiveIn;
209 printReg(I->first, LiveIn.Register, TRI);
211 printReg(I->second, LiveIn.VirtualRegister, TRI);
212 MF.LiveIns.push_back(LiveIn);
216 void MIRPrinter::convert(yaml::MachineFrameInfo &YamlMFI,
217 const MachineFrameInfo &MFI) {
218 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
219 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
220 YamlMFI.HasStackMap = MFI.hasStackMap();
221 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
222 YamlMFI.StackSize = MFI.getStackSize();
223 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
224 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
225 YamlMFI.AdjustsStack = MFI.adjustsStack();
226 YamlMFI.HasCalls = MFI.hasCalls();
227 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
228 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
229 YamlMFI.HasVAStart = MFI.hasVAStart();
230 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
233 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
234 const MachineFrameInfo &MFI,
235 const TargetRegisterInfo *TRI) {
236 // Process fixed stack objects.
238 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
239 if (MFI.isDeadObjectIndex(I))
242 yaml::FixedMachineStackObject YamlObject;
244 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
245 ? yaml::FixedMachineStackObject::SpillSlot
246 : yaml::FixedMachineStackObject::DefaultType;
247 YamlObject.Offset = MFI.getObjectOffset(I);
248 YamlObject.Size = MFI.getObjectSize(I);
249 YamlObject.Alignment = MFI.getObjectAlignment(I);
250 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
251 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
252 MF.FixedStackObjects.push_back(YamlObject);
253 StackObjectOperandMapping.insert(
254 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
257 // Process ordinary stack objects.
259 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
260 if (MFI.isDeadObjectIndex(I))
263 yaml::MachineStackObject YamlObject;
265 if (const auto *Alloca = MFI.getObjectAllocation(I))
266 YamlObject.Name.Value =
267 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
268 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
269 ? yaml::MachineStackObject::SpillSlot
270 : MFI.isVariableSizedObjectIndex(I)
271 ? yaml::MachineStackObject::VariableSized
272 : yaml::MachineStackObject::DefaultType;
273 YamlObject.Offset = MFI.getObjectOffset(I);
274 YamlObject.Size = MFI.getObjectSize(I);
275 YamlObject.Alignment = MFI.getObjectAlignment(I);
277 MF.StackObjects.push_back(YamlObject);
278 StackObjectOperandMapping.insert(std::make_pair(
279 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
282 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
283 yaml::StringValue Reg;
284 printReg(CSInfo.getReg(), Reg, TRI);
285 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
286 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
287 "Invalid stack object index");
288 const FrameIndexOperand &StackObject = StackObjectInfo->second;
289 if (StackObject.IsFixed)
290 MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
292 MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
296 void MIRPrinter::convert(yaml::MachineFunction &MF,
297 const MachineConstantPool &ConstantPool) {
299 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
300 // TODO: Serialize target specific constant pool entries.
301 if (Constant.isMachineConstantPoolEntry())
302 llvm_unreachable("Can't print target specific constant pool entries yet");
304 yaml::MachineConstantPoolValue YamlConstant;
306 raw_string_ostream StrOS(Str);
307 Constant.Val.ConstVal->printAsOperand(StrOS);
308 YamlConstant.ID = ID++;
309 YamlConstant.Value = StrOS.str();
310 YamlConstant.Alignment = Constant.getAlignment();
311 MF.Constants.push_back(YamlConstant);
315 void MIRPrinter::convert(ModuleSlotTracker &MST,
316 yaml::MachineJumpTable &YamlJTI,
317 const MachineJumpTableInfo &JTI) {
318 YamlJTI.Kind = JTI.getEntryKind();
320 for (const auto &Table : JTI.getJumpTables()) {
322 yaml::MachineJumpTable::Entry Entry;
324 for (const auto *MBB : Table.MBBs) {
325 raw_string_ostream StrOS(Str);
326 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
327 .printMBBReference(*MBB);
328 Entry.Blocks.push_back(StrOS.str());
331 YamlJTI.Entries.push_back(Entry);
335 void MIRPrinter::convert(ModuleSlotTracker &MST,
336 yaml::MachineBasicBlock &YamlMBB,
337 const MachineBasicBlock &MBB) {
338 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
339 YamlMBB.ID = (unsigned)MBB.getNumber();
340 if (const auto *BB = MBB.getBasicBlock()) {
342 YamlMBB.Name.Value = BB->getName();
344 int Slot = MST.getLocalSlot(BB);
346 YamlMBB.IRBlock.Value = "<badref>";
348 YamlMBB.IRBlock.Value = (Twine("%ir-block.") + Twine(Slot)).str();
351 YamlMBB.Alignment = MBB.getAlignment();
352 YamlMBB.AddressTaken = MBB.hasAddressTaken();
353 YamlMBB.IsLandingPad = MBB.isLandingPad();
354 for (const auto *SuccMBB : MBB.successors()) {
356 raw_string_ostream StrOS(Str);
357 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
358 .printMBBReference(*SuccMBB);
359 YamlMBB.Successors.push_back(StrOS.str());
361 // Print the live in registers.
362 const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
363 assert(TRI && "Expected target register info");
364 for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
366 raw_string_ostream StrOS(Str);
367 printReg(*I, StrOS, TRI);
368 YamlMBB.LiveIns.push_back(StrOS.str());
370 // Print the machine instructions.
371 YamlMBB.Instructions.reserve(MBB.size());
373 for (const auto &MI : MBB) {
374 raw_string_ostream StrOS(Str);
375 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
376 YamlMBB.Instructions.push_back(StrOS.str());
381 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
382 const auto *TRI = MF.getSubtarget().getRegisterInfo();
384 for (const uint32_t *Mask : TRI->getRegMasks())
385 RegisterMaskIds.insert(std::make_pair(Mask, I++));
388 void MIPrinter::print(const MachineInstr &MI) {
389 const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
390 const auto *TRI = SubTarget.getRegisterInfo();
391 assert(TRI && "Expected target register info");
392 const auto *TII = SubTarget.getInstrInfo();
393 assert(TII && "Expected target instruction info");
394 if (MI.isCFIInstruction())
395 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
397 unsigned I = 0, E = MI.getNumOperands();
398 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
399 !MI.getOperand(I).isImplicit();
403 print(MI.getOperand(I), TRI);
408 if (MI.getFlag(MachineInstr::FrameSetup))
409 OS << "frame-setup ";
410 OS << TII->getName(MI.getOpcode());
411 // TODO: Print the bundling instruction flags, machine mem operands.
415 bool NeedComma = false;
419 print(MI.getOperand(I), TRI);
423 if (MI.getDebugLoc()) {
426 OS << " debug-location ";
427 MI.getDebugLoc()->printAsOperand(OS, MST);
431 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
432 OS << "%bb." << MBB.getNumber();
433 if (const auto *BB = MBB.getBasicBlock()) {
435 OS << '.' << BB->getName();
439 void MIPrinter::printStackObjectReference(int FrameIndex) {
440 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
441 assert(ObjectInfo != StackObjectOperandMapping.end() &&
442 "Invalid frame index");
443 const FrameIndexOperand &Operand = ObjectInfo->second;
444 if (Operand.IsFixed) {
445 OS << "%fixed-stack." << Operand.ID;
448 OS << "%stack." << Operand.ID;
449 if (!Operand.Name.empty())
450 OS << '.' << Operand.Name;
453 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
454 switch (Op.getType()) {
455 case MachineOperand::MO_Register:
456 // TODO: Print the other register flags.
458 OS << (Op.isDef() ? "implicit-def " : "implicit ");
465 printReg(Op.getReg(), OS, TRI);
466 // Print the sub register.
467 if (Op.getSubReg() != 0)
468 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
470 case MachineOperand::MO_Immediate:
473 case MachineOperand::MO_MachineBasicBlock:
474 printMBBReference(*Op.getMBB());
476 case MachineOperand::MO_FrameIndex:
477 printStackObjectReference(Op.getIndex());
479 case MachineOperand::MO_ConstantPoolIndex:
480 OS << "%const." << Op.getIndex();
481 // TODO: Print offset and target flags.
483 case MachineOperand::MO_JumpTableIndex:
484 OS << "%jump-table." << Op.getIndex();
485 // TODO: Print target flags.
487 case MachineOperand::MO_ExternalSymbol:
489 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
490 // TODO: Print the target flags.
492 case MachineOperand::MO_GlobalAddress:
493 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
494 // TODO: Print offset and target flags.
496 case MachineOperand::MO_RegisterMask: {
497 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
498 if (RegMaskInfo != RegisterMaskIds.end())
499 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
501 llvm_unreachable("Can't print this machine register mask yet.");
504 case MachineOperand::MO_Metadata:
505 Op.getMetadata()->printAsOperand(OS, MST);
507 case MachineOperand::MO_CFIIndex: {
508 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
509 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
513 // TODO: Print the other machine operands.
514 llvm_unreachable("Can't print this machine operand at the moment");
518 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
519 const TargetRegisterInfo *TRI) {
520 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
525 printReg(Reg, OS, TRI);
528 void MIPrinter::print(const MCCFIInstruction &CFI,
529 const TargetRegisterInfo *TRI) {
530 switch (CFI.getOperation()) {
531 case MCCFIInstruction::OpOffset:
532 OS << ".cfi_offset ";
535 printCFIRegister(CFI.getRegister(), OS, TRI);
536 OS << ", " << CFI.getOffset();
538 case MCCFIInstruction::OpDefCfaRegister:
539 OS << ".cfi_def_cfa_register ";
542 printCFIRegister(CFI.getRegister(), OS, TRI);
544 case MCCFIInstruction::OpDefCfaOffset:
545 OS << ".cfi_def_cfa_offset ";
548 OS << CFI.getOffset();
551 // TODO: Print the other CFI Operations.
552 OS << "<unserializable cfi operation>";
557 void llvm::printMIR(raw_ostream &OS, const Module &M) {
558 yaml::Output Out(OS);
559 Out << const_cast<Module &>(M);
562 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
563 MIRPrinter Printer(OS);