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/Constants.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IRPrintingPasses.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/ModuleSlotTracker.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/YAMLTraits.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
39 /// This structure describes how to print out stack object references.
40 struct FrameIndexOperand {
45 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
46 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
48 /// Return an ordinary stack object reference.
49 static FrameIndexOperand create(StringRef Name, unsigned ID) {
50 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
53 /// Return a fixed stack object reference.
54 static FrameIndexOperand createFixed(unsigned ID) {
55 return FrameIndexOperand("", ID, /*IsFixed=*/true);
59 /// This class prints out the machine functions using the MIR serialization
63 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
64 /// Maps from stack object indices to operand indices which will be used when
65 /// printing frame index machine operands.
66 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
69 MIRPrinter(raw_ostream &OS) : OS(OS) {}
71 void print(const MachineFunction &MF);
73 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
74 const TargetRegisterInfo *TRI);
75 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
76 const MachineFrameInfo &MFI);
77 void convert(yaml::MachineFunction &MF,
78 const MachineConstantPool &ConstantPool);
79 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
80 const MachineJumpTableInfo &JTI);
81 void convert(ModuleSlotTracker &MST, yaml::MachineBasicBlock &YamlMBB,
82 const MachineBasicBlock &MBB);
83 void convertStackObjects(yaml::MachineFunction &MF,
84 const MachineFrameInfo &MFI,
85 const TargetRegisterInfo *TRI);
88 void initRegisterMaskIds(const MachineFunction &MF);
91 /// This class prints out the machine instructions using the MIR serialization
95 ModuleSlotTracker &MST;
96 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
97 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
100 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
101 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
102 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
103 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
104 StackObjectOperandMapping(StackObjectOperandMapping) {}
106 void print(const MachineInstr &MI);
107 void printMBBReference(const MachineBasicBlock &MBB);
108 void printIRBlockReference(const BasicBlock &BB);
109 void printStackObjectReference(int FrameIndex);
110 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
112 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
115 } // end anonymous namespace
120 /// This struct serializes the LLVM IR module.
121 template <> struct BlockScalarTraits<Module> {
122 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
123 Mod.print(OS, nullptr);
125 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
126 llvm_unreachable("LLVM Module is supposed to be parsed separately");
131 } // end namespace yaml
132 } // end namespace llvm
134 static void printReg(unsigned Reg, raw_ostream &OS,
135 const TargetRegisterInfo *TRI) {
136 // TODO: Print Stack Slots.
139 else if (TargetRegisterInfo::isVirtualRegister(Reg))
140 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
141 else if (Reg < TRI->getNumRegs())
142 OS << '%' << StringRef(TRI->getName(Reg)).lower();
144 llvm_unreachable("Can't print this kind of register yet");
147 static void printReg(unsigned Reg, yaml::StringValue &Dest,
148 const TargetRegisterInfo *TRI) {
149 raw_string_ostream OS(Dest.Value);
150 printReg(Reg, OS, TRI);
153 void MIRPrinter::print(const MachineFunction &MF) {
154 initRegisterMaskIds(MF);
156 yaml::MachineFunction YamlMF;
157 YamlMF.Name = MF.getName();
158 YamlMF.Alignment = MF.getAlignment();
159 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
160 YamlMF.HasInlineAsm = MF.hasInlineAsm();
161 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
162 ModuleSlotTracker MST(MF.getFunction()->getParent());
163 MST.incorporateFunction(*MF.getFunction());
164 convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo());
165 convertStackObjects(YamlMF, *MF.getFrameInfo(),
166 MF.getSubtarget().getRegisterInfo());
167 if (const auto *ConstantPool = MF.getConstantPool())
168 convert(YamlMF, *ConstantPool);
169 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
170 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
171 for (const auto &MBB : MF) {
172 yaml::MachineBasicBlock YamlMBB;
173 convert(MST, YamlMBB, MBB);
174 YamlMF.BasicBlocks.push_back(YamlMBB);
176 yaml::Output Out(OS);
180 void MIRPrinter::convert(yaml::MachineFunction &MF,
181 const MachineRegisterInfo &RegInfo,
182 const TargetRegisterInfo *TRI) {
183 MF.IsSSA = RegInfo.isSSA();
184 MF.TracksRegLiveness = RegInfo.tracksLiveness();
185 MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
187 // Print the virtual register definitions.
188 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
189 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
190 yaml::VirtualRegisterDefinition VReg;
193 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
194 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
196 printReg(PreferredReg, VReg.PreferredRegister, TRI);
197 MF.VirtualRegisters.push_back(VReg);
200 // Print the live ins.
201 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
202 yaml::MachineFunctionLiveIn LiveIn;
203 printReg(I->first, LiveIn.Register, TRI);
205 printReg(I->second, LiveIn.VirtualRegister, TRI);
206 MF.LiveIns.push_back(LiveIn);
210 void MIRPrinter::convert(ModuleSlotTracker &MST,
211 yaml::MachineFrameInfo &YamlMFI,
212 const MachineFrameInfo &MFI) {
213 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
214 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
215 YamlMFI.HasStackMap = MFI.hasStackMap();
216 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
217 YamlMFI.StackSize = MFI.getStackSize();
218 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
219 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
220 YamlMFI.AdjustsStack = MFI.adjustsStack();
221 YamlMFI.HasCalls = MFI.hasCalls();
222 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
223 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
224 YamlMFI.HasVAStart = MFI.hasVAStart();
225 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
226 if (MFI.getSavePoint()) {
227 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
228 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
229 .printMBBReference(*MFI.getSavePoint());
231 if (MFI.getRestorePoint()) {
232 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
233 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
234 .printMBBReference(*MFI.getRestorePoint());
238 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
239 const MachineFrameInfo &MFI,
240 const TargetRegisterInfo *TRI) {
241 // Process fixed stack objects.
243 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
244 if (MFI.isDeadObjectIndex(I))
247 yaml::FixedMachineStackObject YamlObject;
249 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
250 ? yaml::FixedMachineStackObject::SpillSlot
251 : yaml::FixedMachineStackObject::DefaultType;
252 YamlObject.Offset = MFI.getObjectOffset(I);
253 YamlObject.Size = MFI.getObjectSize(I);
254 YamlObject.Alignment = MFI.getObjectAlignment(I);
255 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
256 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
257 MF.FixedStackObjects.push_back(YamlObject);
258 StackObjectOperandMapping.insert(
259 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
262 // Process ordinary stack objects.
264 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
265 if (MFI.isDeadObjectIndex(I))
268 yaml::MachineStackObject YamlObject;
270 if (const auto *Alloca = MFI.getObjectAllocation(I))
271 YamlObject.Name.Value =
272 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
273 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
274 ? yaml::MachineStackObject::SpillSlot
275 : MFI.isVariableSizedObjectIndex(I)
276 ? yaml::MachineStackObject::VariableSized
277 : yaml::MachineStackObject::DefaultType;
278 YamlObject.Offset = MFI.getObjectOffset(I);
279 YamlObject.Size = MFI.getObjectSize(I);
280 YamlObject.Alignment = MFI.getObjectAlignment(I);
282 MF.StackObjects.push_back(YamlObject);
283 StackObjectOperandMapping.insert(std::make_pair(
284 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
287 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
288 yaml::StringValue Reg;
289 printReg(CSInfo.getReg(), Reg, TRI);
290 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
291 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
292 "Invalid stack object index");
293 const FrameIndexOperand &StackObject = StackObjectInfo->second;
294 if (StackObject.IsFixed)
295 MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
297 MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
301 void MIRPrinter::convert(yaml::MachineFunction &MF,
302 const MachineConstantPool &ConstantPool) {
304 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
305 // TODO: Serialize target specific constant pool entries.
306 if (Constant.isMachineConstantPoolEntry())
307 llvm_unreachable("Can't print target specific constant pool entries yet");
309 yaml::MachineConstantPoolValue YamlConstant;
311 raw_string_ostream StrOS(Str);
312 Constant.Val.ConstVal->printAsOperand(StrOS);
313 YamlConstant.ID = ID++;
314 YamlConstant.Value = StrOS.str();
315 YamlConstant.Alignment = Constant.getAlignment();
316 MF.Constants.push_back(YamlConstant);
320 void MIRPrinter::convert(ModuleSlotTracker &MST,
321 yaml::MachineJumpTable &YamlJTI,
322 const MachineJumpTableInfo &JTI) {
323 YamlJTI.Kind = JTI.getEntryKind();
325 for (const auto &Table : JTI.getJumpTables()) {
327 yaml::MachineJumpTable::Entry Entry;
329 for (const auto *MBB : Table.MBBs) {
330 raw_string_ostream StrOS(Str);
331 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
332 .printMBBReference(*MBB);
333 Entry.Blocks.push_back(StrOS.str());
336 YamlJTI.Entries.push_back(Entry);
340 void MIRPrinter::convert(ModuleSlotTracker &MST,
341 yaml::MachineBasicBlock &YamlMBB,
342 const MachineBasicBlock &MBB) {
343 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
344 YamlMBB.ID = (unsigned)MBB.getNumber();
345 if (const auto *BB = MBB.getBasicBlock()) {
347 YamlMBB.Name.Value = BB->getName();
349 int Slot = MST.getLocalSlot(BB);
351 YamlMBB.IRBlock.Value = "<badref>";
353 YamlMBB.IRBlock.Value = (Twine("%ir-block.") + Twine(Slot)).str();
356 YamlMBB.Alignment = MBB.getAlignment();
357 YamlMBB.AddressTaken = MBB.hasAddressTaken();
358 YamlMBB.IsLandingPad = MBB.isLandingPad();
359 for (const auto *SuccMBB : MBB.successors()) {
361 raw_string_ostream StrOS(Str);
362 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
363 .printMBBReference(*SuccMBB);
364 YamlMBB.Successors.push_back(StrOS.str());
366 // Print the live in registers.
367 const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
368 assert(TRI && "Expected target register info");
369 for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
371 raw_string_ostream StrOS(Str);
372 printReg(*I, StrOS, TRI);
373 YamlMBB.LiveIns.push_back(StrOS.str());
375 // Print the machine instructions.
376 YamlMBB.Instructions.reserve(MBB.size());
378 for (const auto &MI : MBB) {
379 raw_string_ostream StrOS(Str);
380 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
381 YamlMBB.Instructions.push_back(StrOS.str());
386 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
387 const auto *TRI = MF.getSubtarget().getRegisterInfo();
389 for (const uint32_t *Mask : TRI->getRegMasks())
390 RegisterMaskIds.insert(std::make_pair(Mask, I++));
393 void MIPrinter::print(const MachineInstr &MI) {
394 const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
395 const auto *TRI = SubTarget.getRegisterInfo();
396 assert(TRI && "Expected target register info");
397 const auto *TII = SubTarget.getInstrInfo();
398 assert(TII && "Expected target instruction info");
399 if (MI.isCFIInstruction())
400 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
402 unsigned I = 0, E = MI.getNumOperands();
403 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
404 !MI.getOperand(I).isImplicit();
408 print(MI.getOperand(I), TRI);
413 if (MI.getFlag(MachineInstr::FrameSetup))
414 OS << "frame-setup ";
415 OS << TII->getName(MI.getOpcode());
416 // TODO: Print the bundling instruction flags, machine mem operands.
420 bool NeedComma = false;
424 print(MI.getOperand(I), TRI);
428 if (MI.getDebugLoc()) {
431 OS << " debug-location ";
432 MI.getDebugLoc()->printAsOperand(OS, MST);
436 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
437 OS << "%bb." << MBB.getNumber();
438 if (const auto *BB = MBB.getBasicBlock()) {
440 OS << '.' << BB->getName();
444 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
447 printLLVMNameWithoutPrefix(OS, BB.getName());
450 int Slot = MST.getLocalSlot(&BB);
457 void MIPrinter::printStackObjectReference(int FrameIndex) {
458 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
459 assert(ObjectInfo != StackObjectOperandMapping.end() &&
460 "Invalid frame index");
461 const FrameIndexOperand &Operand = ObjectInfo->second;
462 if (Operand.IsFixed) {
463 OS << "%fixed-stack." << Operand.ID;
466 OS << "%stack." << Operand.ID;
467 if (!Operand.Name.empty())
468 OS << '.' << Operand.Name;
471 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
472 const auto *TII = MF.getSubtarget().getInstrInfo();
473 assert(TII && "expected instruction info");
474 auto Indices = TII->getSerializableTargetIndices();
475 for (const auto &I : Indices) {
476 if (I.first == Index) {
483 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
484 switch (Op.getType()) {
485 case MachineOperand::MO_Register:
486 // TODO: Print the other register flags.
488 OS << (Op.isDef() ? "implicit-def " : "implicit ");
495 printReg(Op.getReg(), OS, TRI);
496 // Print the sub register.
497 if (Op.getSubReg() != 0)
498 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
500 case MachineOperand::MO_Immediate:
503 case MachineOperand::MO_MachineBasicBlock:
504 printMBBReference(*Op.getMBB());
506 case MachineOperand::MO_FrameIndex:
507 printStackObjectReference(Op.getIndex());
509 case MachineOperand::MO_ConstantPoolIndex:
510 OS << "%const." << Op.getIndex();
511 // TODO: Print offset and target flags.
513 case MachineOperand::MO_TargetIndex: {
514 OS << "target-index(";
515 if (const auto *Name = getTargetIndexName(
516 *Op.getParent()->getParent()->getParent(), Op.getIndex()))
521 // TODO: Print the offset and target flags.
524 case MachineOperand::MO_JumpTableIndex:
525 OS << "%jump-table." << Op.getIndex();
526 // TODO: Print target flags.
528 case MachineOperand::MO_ExternalSymbol:
530 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
531 // TODO: Print the target flags.
533 case MachineOperand::MO_GlobalAddress:
534 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
535 // TODO: Print offset and target flags.
537 case MachineOperand::MO_BlockAddress:
538 OS << "blockaddress(";
539 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
542 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
544 // TODO: Print offset and target flags.
546 case MachineOperand::MO_RegisterMask: {
547 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
548 if (RegMaskInfo != RegisterMaskIds.end())
549 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
551 llvm_unreachable("Can't print this machine register mask yet.");
554 case MachineOperand::MO_Metadata:
555 Op.getMetadata()->printAsOperand(OS, MST);
557 case MachineOperand::MO_CFIIndex: {
558 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
559 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
563 // TODO: Print the other machine operands.
564 llvm_unreachable("Can't print this machine operand at the moment");
568 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
569 const TargetRegisterInfo *TRI) {
570 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
575 printReg(Reg, OS, TRI);
578 void MIPrinter::print(const MCCFIInstruction &CFI,
579 const TargetRegisterInfo *TRI) {
580 switch (CFI.getOperation()) {
581 case MCCFIInstruction::OpOffset:
582 OS << ".cfi_offset ";
585 printCFIRegister(CFI.getRegister(), OS, TRI);
586 OS << ", " << CFI.getOffset();
588 case MCCFIInstruction::OpDefCfaRegister:
589 OS << ".cfi_def_cfa_register ";
592 printCFIRegister(CFI.getRegister(), OS, TRI);
594 case MCCFIInstruction::OpDefCfaOffset:
595 OS << ".cfi_def_cfa_offset ";
598 OS << CFI.getOffset();
600 case MCCFIInstruction::OpDefCfa:
601 OS << ".cfi_def_cfa ";
604 printCFIRegister(CFI.getRegister(), OS, TRI);
605 OS << ", " << CFI.getOffset();
608 // TODO: Print the other CFI Operations.
609 OS << "<unserializable cfi operation>";
614 void llvm::printMIR(raw_ostream &OS, const Module &M) {
615 yaml::Output Out(OS);
616 Out << const_cast<Module &>(M);
619 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
620 MIRPrinter Printer(OS);