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/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/MIRYamlMapping.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IRPrintingPasses.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/ModuleSlotTracker.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/YAMLTraits.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetSubtargetInfo.h"
37 /// This structure describes how to print out stack object references.
38 struct FrameIndexOperand {
43 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
44 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
46 /// Return an ordinary stack object reference.
47 static FrameIndexOperand create(StringRef Name, unsigned ID) {
48 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
51 /// Return a fixed stack object reference.
52 static FrameIndexOperand createFixed(unsigned ID) {
53 return FrameIndexOperand("", ID, /*IsFixed=*/true);
57 /// This class prints out the machine functions using the MIR serialization
61 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
62 /// Maps from stack object indices to operand indices which will be used when
63 /// printing frame index machine operands.
64 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
67 MIRPrinter(raw_ostream &OS) : OS(OS) {}
69 void print(const MachineFunction &MF);
71 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
72 const TargetRegisterInfo *TRI);
73 void convert(yaml::MachineFrameInfo &YamlMFI, const MachineFrameInfo &MFI);
74 void convert(yaml::MachineFunction &MF,
75 const MachineConstantPool &ConstantPool);
76 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
77 const MachineJumpTableInfo &JTI);
78 void convert(ModuleSlotTracker &MST, yaml::MachineBasicBlock &YamlMBB,
79 const MachineBasicBlock &MBB);
80 void convertStackObjects(yaml::MachineFunction &MF,
81 const MachineFrameInfo &MFI);
84 void initRegisterMaskIds(const MachineFunction &MF);
87 /// This class prints out the machine instructions using the MIR serialization
91 ModuleSlotTracker &MST;
92 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
93 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
96 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
97 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
98 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
99 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
100 StackObjectOperandMapping(StackObjectOperandMapping) {}
102 void print(const MachineInstr &MI);
103 void printMBBReference(const MachineBasicBlock &MBB);
104 void printStackObjectReference(int FrameIndex);
105 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI);
108 } // end anonymous namespace
113 /// This struct serializes the LLVM IR module.
114 template <> struct BlockScalarTraits<Module> {
115 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
116 Mod.print(OS, nullptr);
118 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
119 llvm_unreachable("LLVM Module is supposed to be parsed separately");
124 } // end namespace yaml
125 } // end namespace llvm
127 static void printReg(unsigned Reg, raw_ostream &OS,
128 const TargetRegisterInfo *TRI) {
129 // TODO: Print Stack Slots.
132 else if (TargetRegisterInfo::isVirtualRegister(Reg))
133 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
134 else if (Reg < TRI->getNumRegs())
135 OS << '%' << StringRef(TRI->getName(Reg)).lower();
137 llvm_unreachable("Can't print this kind of register yet");
140 void MIRPrinter::print(const MachineFunction &MF) {
141 initRegisterMaskIds(MF);
143 yaml::MachineFunction YamlMF;
144 YamlMF.Name = MF.getName();
145 YamlMF.Alignment = MF.getAlignment();
146 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
147 YamlMF.HasInlineAsm = MF.hasInlineAsm();
148 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
149 convert(YamlMF.FrameInfo, *MF.getFrameInfo());
150 convertStackObjects(YamlMF, *MF.getFrameInfo());
151 if (const auto *ConstantPool = MF.getConstantPool())
152 convert(YamlMF, *ConstantPool);
154 ModuleSlotTracker MST(MF.getFunction()->getParent());
155 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
156 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
158 for (const auto &MBB : MF) {
159 // TODO: Allow printing of non sequentially numbered MBBs.
160 // This is currently needed as the basic block references get their index
161 // from MBB.getNumber(), thus it should be sequential so that the parser can
162 // map back to the correct MBBs when parsing the output.
163 assert(MBB.getNumber() == I++ &&
164 "Can't print MBBs that aren't sequentially numbered");
166 yaml::MachineBasicBlock YamlMBB;
167 convert(MST, YamlMBB, MBB);
168 YamlMF.BasicBlocks.push_back(YamlMBB);
170 yaml::Output Out(OS);
174 void MIRPrinter::convert(yaml::MachineFunction &MF,
175 const MachineRegisterInfo &RegInfo,
176 const TargetRegisterInfo *TRI) {
177 MF.IsSSA = RegInfo.isSSA();
178 MF.TracksRegLiveness = RegInfo.tracksLiveness();
179 MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
181 // Print the virtual register definitions.
182 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
183 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
184 yaml::VirtualRegisterDefinition VReg;
187 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
188 MF.VirtualRegisters.push_back(VReg);
192 void MIRPrinter::convert(yaml::MachineFrameInfo &YamlMFI,
193 const MachineFrameInfo &MFI) {
194 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
195 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
196 YamlMFI.HasStackMap = MFI.hasStackMap();
197 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
198 YamlMFI.StackSize = MFI.getStackSize();
199 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
200 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
201 YamlMFI.AdjustsStack = MFI.adjustsStack();
202 YamlMFI.HasCalls = MFI.hasCalls();
203 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
204 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
205 YamlMFI.HasVAStart = MFI.hasVAStart();
206 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
209 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
210 const MachineFrameInfo &MFI) {
211 // Process fixed stack objects.
213 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
214 if (MFI.isDeadObjectIndex(I))
217 yaml::FixedMachineStackObject YamlObject;
219 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
220 ? yaml::FixedMachineStackObject::SpillSlot
221 : yaml::FixedMachineStackObject::DefaultType;
222 YamlObject.Offset = MFI.getObjectOffset(I);
223 YamlObject.Size = MFI.getObjectSize(I);
224 YamlObject.Alignment = MFI.getObjectAlignment(I);
225 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
226 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
227 MF.FixedStackObjects.push_back(YamlObject);
228 StackObjectOperandMapping.insert(
229 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
232 // Process ordinary stack objects.
234 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
235 if (MFI.isDeadObjectIndex(I))
238 yaml::MachineStackObject YamlObject;
240 if (const auto *Alloca = MFI.getObjectAllocation(I))
241 YamlObject.Name.Value =
242 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
243 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
244 ? yaml::MachineStackObject::SpillSlot
245 : MFI.isVariableSizedObjectIndex(I)
246 ? yaml::MachineStackObject::VariableSized
247 : yaml::MachineStackObject::DefaultType;
248 YamlObject.Offset = MFI.getObjectOffset(I);
249 YamlObject.Size = MFI.getObjectSize(I);
250 YamlObject.Alignment = MFI.getObjectAlignment(I);
252 MF.StackObjects.push_back(YamlObject);
253 StackObjectOperandMapping.insert(std::make_pair(
254 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
258 void MIRPrinter::convert(yaml::MachineFunction &MF,
259 const MachineConstantPool &ConstantPool) {
261 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
262 // TODO: Serialize target specific constant pool entries.
263 if (Constant.isMachineConstantPoolEntry())
264 llvm_unreachable("Can't print target specific constant pool entries yet");
266 yaml::MachineConstantPoolValue YamlConstant;
268 raw_string_ostream StrOS(Str);
269 Constant.Val.ConstVal->printAsOperand(StrOS);
270 YamlConstant.ID = ID++;
271 YamlConstant.Value = StrOS.str();
272 YamlConstant.Alignment = Constant.getAlignment();
273 MF.Constants.push_back(YamlConstant);
277 void MIRPrinter::convert(ModuleSlotTracker &MST,
278 yaml::MachineJumpTable &YamlJTI,
279 const MachineJumpTableInfo &JTI) {
280 YamlJTI.Kind = JTI.getEntryKind();
282 for (const auto &Table : JTI.getJumpTables()) {
284 yaml::MachineJumpTable::Entry Entry;
286 for (const auto *MBB : Table.MBBs) {
287 raw_string_ostream StrOS(Str);
288 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
289 .printMBBReference(*MBB);
290 Entry.Blocks.push_back(StrOS.str());
293 YamlJTI.Entries.push_back(Entry);
297 void MIRPrinter::convert(ModuleSlotTracker &MST,
298 yaml::MachineBasicBlock &YamlMBB,
299 const MachineBasicBlock &MBB) {
300 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
301 YamlMBB.ID = (unsigned)MBB.getNumber();
302 // TODO: Serialize unnamed BB references.
303 if (const auto *BB = MBB.getBasicBlock())
304 YamlMBB.Name.Value = BB->hasName() ? BB->getName() : "<unnamed bb>";
306 YamlMBB.Name.Value = "";
307 YamlMBB.Alignment = MBB.getAlignment();
308 YamlMBB.AddressTaken = MBB.hasAddressTaken();
309 YamlMBB.IsLandingPad = MBB.isLandingPad();
310 for (const auto *SuccMBB : MBB.successors()) {
312 raw_string_ostream StrOS(Str);
313 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
314 .printMBBReference(*SuccMBB);
315 YamlMBB.Successors.push_back(StrOS.str());
317 // Print the live in registers.
318 const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
319 assert(TRI && "Expected target register info");
320 for (auto I = MBB.livein_begin(), E = MBB.livein_end(); I != E; ++I) {
322 raw_string_ostream StrOS(Str);
323 printReg(*I, StrOS, TRI);
324 YamlMBB.LiveIns.push_back(StrOS.str());
326 // Print the machine instructions.
327 YamlMBB.Instructions.reserve(MBB.size());
329 for (const auto &MI : MBB) {
330 raw_string_ostream StrOS(Str);
331 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping).print(MI);
332 YamlMBB.Instructions.push_back(StrOS.str());
337 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
338 const auto *TRI = MF.getSubtarget().getRegisterInfo();
340 for (const uint32_t *Mask : TRI->getRegMasks())
341 RegisterMaskIds.insert(std::make_pair(Mask, I++));
344 void MIPrinter::print(const MachineInstr &MI) {
345 const auto &SubTarget = MI.getParent()->getParent()->getSubtarget();
346 const auto *TRI = SubTarget.getRegisterInfo();
347 assert(TRI && "Expected target register info");
348 const auto *TII = SubTarget.getInstrInfo();
349 assert(TII && "Expected target instruction info");
351 unsigned I = 0, E = MI.getNumOperands();
352 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
353 !MI.getOperand(I).isImplicit();
357 print(MI.getOperand(I), TRI);
362 if (MI.getFlag(MachineInstr::FrameSetup))
363 OS << "frame-setup ";
364 OS << TII->getName(MI.getOpcode());
365 // TODO: Print the bundling instruction flags, machine mem operands.
369 bool NeedComma = false;
373 print(MI.getOperand(I), TRI);
378 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
379 OS << "%bb." << MBB.getNumber();
380 if (const auto *BB = MBB.getBasicBlock()) {
382 OS << '.' << BB->getName();
386 void MIPrinter::printStackObjectReference(int FrameIndex) {
387 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
388 assert(ObjectInfo != StackObjectOperandMapping.end() &&
389 "Invalid frame index");
390 const FrameIndexOperand &Operand = ObjectInfo->second;
391 if (Operand.IsFixed) {
392 OS << "%fixed-stack." << Operand.ID;
395 OS << "%stack." << Operand.ID;
396 if (!Operand.Name.empty())
397 OS << '.' << Operand.Name;
400 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI) {
401 switch (Op.getType()) {
402 case MachineOperand::MO_Register:
403 // TODO: Print the other register flags.
405 OS << (Op.isDef() ? "implicit-def " : "implicit ");
412 printReg(Op.getReg(), OS, TRI);
413 // Print the sub register.
414 if (Op.getSubReg() != 0)
415 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg());
417 case MachineOperand::MO_Immediate:
420 case MachineOperand::MO_MachineBasicBlock:
421 printMBBReference(*Op.getMBB());
423 case MachineOperand::MO_FrameIndex:
424 printStackObjectReference(Op.getIndex());
426 case MachineOperand::MO_ConstantPoolIndex:
427 OS << "%const." << Op.getIndex();
428 // TODO: Print offset and target flags.
430 case MachineOperand::MO_JumpTableIndex:
431 OS << "%jump-table." << Op.getIndex();
432 // TODO: Print target flags.
434 case MachineOperand::MO_ExternalSymbol:
436 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
437 // TODO: Print the target flags.
439 case MachineOperand::MO_GlobalAddress:
440 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
441 // TODO: Print offset and target flags.
443 case MachineOperand::MO_RegisterMask: {
444 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
445 if (RegMaskInfo != RegisterMaskIds.end())
446 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
448 llvm_unreachable("Can't print this machine register mask yet.");
452 // TODO: Print the other machine operands.
453 llvm_unreachable("Can't print this machine operand at the moment");
457 void llvm::printMIR(raw_ostream &OS, const Module &M) {
458 yaml::Output Out(OS);
459 Out << const_cast<Module &>(M);
462 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
463 MIRPrinter Printer(OS);