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/ADT/SmallBitVector.h"
18 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
19 #include "llvm/CodeGen/MIRYamlMapping.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineMemOperand.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/IRPrintingPasses.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/YAMLTraits.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetIntrinsicInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
47 /// This structure describes how to print out stack object references.
48 struct FrameIndexOperand {
53 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
54 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
56 /// Return an ordinary stack object reference.
57 static FrameIndexOperand create(StringRef Name, unsigned ID) {
58 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
61 /// Return a fixed stack object reference.
62 static FrameIndexOperand createFixed(unsigned ID) {
63 return FrameIndexOperand("", ID, /*IsFixed=*/true);
67 } // end anonymous namespace
71 /// This class prints out the machine functions using the MIR serialization
75 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
76 /// Maps from stack object indices to operand indices which will be used when
77 /// printing frame index machine operands.
78 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
81 MIRPrinter(raw_ostream &OS) : OS(OS) {}
83 void print(const MachineFunction &MF);
85 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
86 const TargetRegisterInfo *TRI);
87 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
88 const MachineFrameInfo &MFI);
89 void convert(yaml::MachineFunction &MF,
90 const MachineConstantPool &ConstantPool);
91 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
92 const MachineJumpTableInfo &JTI);
93 void convertStackObjects(yaml::MachineFunction &YMF,
94 const MachineFunction &MF, ModuleSlotTracker &MST);
97 void initRegisterMaskIds(const MachineFunction &MF);
100 /// This class prints out the machine instructions using the MIR serialization
104 ModuleSlotTracker &MST;
105 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
106 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
109 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
110 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
111 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
112 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
113 StackObjectOperandMapping(StackObjectOperandMapping) {}
115 void print(const MachineBasicBlock &MBB);
117 void print(const MachineInstr &MI);
118 void printMBBReference(const MachineBasicBlock &MBB);
119 void printIRBlockReference(const BasicBlock &BB);
120 void printIRValueReference(const Value &V);
121 void printStackObjectReference(int FrameIndex);
122 void printOffset(int64_t Offset);
123 void printTargetFlags(const MachineOperand &Op);
124 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
125 unsigned I, bool ShouldPrintRegisterTies,
126 LLT TypeToPrint, bool IsDef = false);
127 void print(const MachineMemOperand &Op);
129 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
132 } // end namespace llvm
137 /// This struct serializes the LLVM IR module.
138 template <> struct BlockScalarTraits<Module> {
139 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
140 Mod.print(OS, nullptr);
142 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
143 llvm_unreachable("LLVM Module is supposed to be parsed separately");
148 } // end namespace yaml
149 } // end namespace llvm
151 static void printReg(unsigned Reg, raw_ostream &OS,
152 const TargetRegisterInfo *TRI) {
153 // TODO: Print Stack Slots.
156 else if (TargetRegisterInfo::isVirtualRegister(Reg))
157 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
158 else if (Reg < TRI->getNumRegs())
159 OS << '%' << StringRef(TRI->getName(Reg)).lower();
161 llvm_unreachable("Can't print this kind of register yet");
164 static void printReg(unsigned Reg, yaml::StringValue &Dest,
165 const TargetRegisterInfo *TRI) {
166 raw_string_ostream OS(Dest.Value);
167 printReg(Reg, OS, TRI);
170 void MIRPrinter::print(const MachineFunction &MF) {
171 initRegisterMaskIds(MF);
173 yaml::MachineFunction YamlMF;
174 YamlMF.Name = MF.getName();
175 YamlMF.Alignment = MF.getAlignment();
176 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
178 YamlMF.Legalized = MF.getProperties().hasProperty(
179 MachineFunctionProperties::Property::Legalized);
180 YamlMF.RegBankSelected = MF.getProperties().hasProperty(
181 MachineFunctionProperties::Property::RegBankSelected);
182 YamlMF.Selected = MF.getProperties().hasProperty(
183 MachineFunctionProperties::Property::Selected);
185 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
186 ModuleSlotTracker MST(MF.getFunction()->getParent());
187 MST.incorporateFunction(*MF.getFunction());
188 convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
189 convertStackObjects(YamlMF, MF, MST);
190 if (const auto *ConstantPool = MF.getConstantPool())
191 convert(YamlMF, *ConstantPool);
192 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
193 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
194 raw_string_ostream StrOS(YamlMF.Body.Value.Value);
195 bool IsNewlineNeeded = false;
196 for (const auto &MBB : MF) {
199 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
201 IsNewlineNeeded = true;
204 yaml::Output Out(OS);
208 void MIRPrinter::convert(yaml::MachineFunction &MF,
209 const MachineRegisterInfo &RegInfo,
210 const TargetRegisterInfo *TRI) {
211 MF.TracksRegLiveness = RegInfo.tracksLiveness();
213 // Print the virtual register definitions.
214 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
215 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
216 yaml::VirtualRegisterDefinition VReg;
218 if (RegInfo.getRegClassOrNull(Reg))
220 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
221 else if (RegInfo.getRegBankOrNull(Reg))
222 VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
224 VReg.Class = std::string("_");
225 assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
226 "Generic registers must have a valid type");
228 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
230 printReg(PreferredReg, VReg.PreferredRegister, TRI);
231 MF.VirtualRegisters.push_back(VReg);
234 // Print the live ins.
235 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
236 yaml::MachineFunctionLiveIn LiveIn;
237 printReg(I->first, LiveIn.Register, TRI);
239 printReg(I->second, LiveIn.VirtualRegister, TRI);
240 MF.LiveIns.push_back(LiveIn);
242 // The used physical register mask is printed as an inverted callee saved
244 const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask();
245 if (UsedPhysRegMask.none())
247 std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
248 for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) {
249 if (!UsedPhysRegMask[I]) {
250 yaml::FlowStringValue Reg;
251 printReg(I, Reg, TRI);
252 CalleeSavedRegisters.push_back(Reg);
255 MF.CalleeSavedRegisters = CalleeSavedRegisters;
258 void MIRPrinter::convert(ModuleSlotTracker &MST,
259 yaml::MachineFrameInfo &YamlMFI,
260 const MachineFrameInfo &MFI) {
261 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
262 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
263 YamlMFI.HasStackMap = MFI.hasStackMap();
264 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
265 YamlMFI.StackSize = MFI.getStackSize();
266 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
267 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
268 YamlMFI.AdjustsStack = MFI.adjustsStack();
269 YamlMFI.HasCalls = MFI.hasCalls();
270 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
271 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
272 YamlMFI.HasVAStart = MFI.hasVAStart();
273 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
274 if (MFI.getSavePoint()) {
275 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
276 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
277 .printMBBReference(*MFI.getSavePoint());
279 if (MFI.getRestorePoint()) {
280 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
281 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
282 .printMBBReference(*MFI.getRestorePoint());
286 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
287 const MachineFunction &MF,
288 ModuleSlotTracker &MST) {
289 const MachineFrameInfo &MFI = MF.getFrameInfo();
290 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
291 // Process fixed stack objects.
293 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
294 if (MFI.isDeadObjectIndex(I))
297 yaml::FixedMachineStackObject YamlObject;
299 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
300 ? yaml::FixedMachineStackObject::SpillSlot
301 : yaml::FixedMachineStackObject::DefaultType;
302 YamlObject.Offset = MFI.getObjectOffset(I);
303 YamlObject.Size = MFI.getObjectSize(I);
304 YamlObject.Alignment = MFI.getObjectAlignment(I);
305 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
306 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
307 YMF.FixedStackObjects.push_back(YamlObject);
308 StackObjectOperandMapping.insert(
309 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
312 // Process ordinary stack objects.
314 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
315 if (MFI.isDeadObjectIndex(I))
318 yaml::MachineStackObject YamlObject;
320 if (const auto *Alloca = MFI.getObjectAllocation(I))
321 YamlObject.Name.Value =
322 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
323 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
324 ? yaml::MachineStackObject::SpillSlot
325 : MFI.isVariableSizedObjectIndex(I)
326 ? yaml::MachineStackObject::VariableSized
327 : yaml::MachineStackObject::DefaultType;
328 YamlObject.Offset = MFI.getObjectOffset(I);
329 YamlObject.Size = MFI.getObjectSize(I);
330 YamlObject.Alignment = MFI.getObjectAlignment(I);
332 YMF.StackObjects.push_back(YamlObject);
333 StackObjectOperandMapping.insert(std::make_pair(
334 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
337 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
338 yaml::StringValue Reg;
339 printReg(CSInfo.getReg(), Reg, TRI);
340 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
341 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
342 "Invalid stack object index");
343 const FrameIndexOperand &StackObject = StackObjectInfo->second;
344 if (StackObject.IsFixed)
345 YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
347 YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
349 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
350 auto LocalObject = MFI.getLocalFrameObjectMap(I);
351 auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
352 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
353 "Invalid stack object index");
354 const FrameIndexOperand &StackObject = StackObjectInfo->second;
355 assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
356 YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
359 // Print the stack object references in the frame information class after
360 // converting the stack objects.
361 if (MFI.hasStackProtectorIndex()) {
362 raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
363 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
364 .printStackObjectReference(MFI.getStackProtectorIndex());
367 // Print the debug variable information.
368 for (const MachineFunction::VariableDbgInfo &DebugVar :
369 MF.getVariableDbgInfo()) {
370 auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
371 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
372 "Invalid stack object index");
373 const FrameIndexOperand &StackObject = StackObjectInfo->second;
374 assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
375 auto &Object = YMF.StackObjects[StackObject.ID];
377 raw_string_ostream StrOS(Object.DebugVar.Value);
378 DebugVar.Var->printAsOperand(StrOS, MST);
381 raw_string_ostream StrOS(Object.DebugExpr.Value);
382 DebugVar.Expr->printAsOperand(StrOS, MST);
385 raw_string_ostream StrOS(Object.DebugLoc.Value);
386 DebugVar.Loc->printAsOperand(StrOS, MST);
391 void MIRPrinter::convert(yaml::MachineFunction &MF,
392 const MachineConstantPool &ConstantPool) {
394 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
395 // TODO: Serialize target specific constant pool entries.
396 if (Constant.isMachineConstantPoolEntry())
397 llvm_unreachable("Can't print target specific constant pool entries yet");
399 yaml::MachineConstantPoolValue YamlConstant;
401 raw_string_ostream StrOS(Str);
402 Constant.Val.ConstVal->printAsOperand(StrOS);
403 YamlConstant.ID = ID++;
404 YamlConstant.Value = StrOS.str();
405 YamlConstant.Alignment = Constant.getAlignment();
406 MF.Constants.push_back(YamlConstant);
410 void MIRPrinter::convert(ModuleSlotTracker &MST,
411 yaml::MachineJumpTable &YamlJTI,
412 const MachineJumpTableInfo &JTI) {
413 YamlJTI.Kind = JTI.getEntryKind();
415 for (const auto &Table : JTI.getJumpTables()) {
417 yaml::MachineJumpTable::Entry Entry;
419 for (const auto *MBB : Table.MBBs) {
420 raw_string_ostream StrOS(Str);
421 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
422 .printMBBReference(*MBB);
423 Entry.Blocks.push_back(StrOS.str());
426 YamlJTI.Entries.push_back(Entry);
430 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
431 const auto *TRI = MF.getSubtarget().getRegisterInfo();
433 for (const uint32_t *Mask : TRI->getRegMasks())
434 RegisterMaskIds.insert(std::make_pair(Mask, I++));
437 void MIPrinter::print(const MachineBasicBlock &MBB) {
438 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
439 OS << "bb." << MBB.getNumber();
440 bool HasAttributes = false;
441 if (const auto *BB = MBB.getBasicBlock()) {
443 OS << "." << BB->getName();
445 HasAttributes = true;
447 int Slot = MST.getLocalSlot(BB);
449 OS << "<ir-block badref>";
451 OS << (Twine("%ir-block.") + Twine(Slot)).str();
454 if (MBB.hasAddressTaken()) {
455 OS << (HasAttributes ? ", " : " (");
456 OS << "address-taken";
457 HasAttributes = true;
460 OS << (HasAttributes ? ", " : " (");
462 HasAttributes = true;
464 if (MBB.getAlignment()) {
465 OS << (HasAttributes ? ", " : " (");
466 OS << "align " << MBB.getAlignment();
467 HasAttributes = true;
473 bool HasLineAttributes = false;
474 // Print the successors
475 if (!MBB.succ_empty()) {
476 OS.indent(2) << "successors: ";
477 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
478 if (I != MBB.succ_begin())
480 printMBBReference(**I);
481 if (MBB.hasSuccessorProbabilities())
483 << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
487 HasLineAttributes = true;
490 // Print the live in registers.
491 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
492 if (MRI.tracksLiveness() && !MBB.livein_empty()) {
493 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
494 OS.indent(2) << "liveins: ";
496 for (const auto &LI : MBB.liveins()) {
500 printReg(LI.PhysReg, OS, &TRI);
501 if (!LI.LaneMask.all())
502 OS << ":0x" << PrintLaneMask(LI.LaneMask);
505 HasLineAttributes = true;
508 if (HasLineAttributes)
510 bool IsInBundle = false;
511 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
512 const MachineInstr &MI = *I;
513 if (IsInBundle && !MI.isInsideBundle()) {
514 OS.indent(2) << "}\n";
517 OS.indent(IsInBundle ? 4 : 2);
519 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
526 OS.indent(2) << "}\n";
529 /// Return true when an instruction has tied register that can't be determined
530 /// by the instruction's descriptor.
531 static bool hasComplexRegisterTies(const MachineInstr &MI) {
532 const MCInstrDesc &MCID = MI.getDesc();
533 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
534 const auto &Operand = MI.getOperand(I);
535 if (!Operand.isReg() || Operand.isDef())
536 // Ignore the defined registers as MCID marks only the uses as tied.
538 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
539 int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
540 if (ExpectedTiedIdx != TiedIdx)
546 static LLT getTypeToPrint(const MachineInstr &MI, unsigned OpIdx,
547 SmallBitVector &PrintedTypes,
548 const MachineRegisterInfo &MRI) {
549 const MachineOperand &Op = MI.getOperand(OpIdx);
553 if (MI.isVariadic() || OpIdx >= MI.getNumExplicitOperands())
554 return MRI.getType(Op.getReg());
556 auto &OpInfo = MI.getDesc().OpInfo[OpIdx];
557 if (!OpInfo.isGenericType())
558 return MRI.getType(Op.getReg());
560 if (PrintedTypes[OpInfo.getGenericTypeIndex()])
563 PrintedTypes.set(OpInfo.getGenericTypeIndex());
564 return MRI.getType(Op.getReg());
567 void MIPrinter::print(const MachineInstr &MI) {
568 const auto *MF = MI.getParent()->getParent();
569 const auto &MRI = MF->getRegInfo();
570 const auto &SubTarget = MF->getSubtarget();
571 const auto *TRI = SubTarget.getRegisterInfo();
572 assert(TRI && "Expected target register info");
573 const auto *TII = SubTarget.getInstrInfo();
574 assert(TII && "Expected target instruction info");
575 if (MI.isCFIInstruction())
576 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
578 SmallBitVector PrintedTypes(8);
579 bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
580 unsigned I = 0, E = MI.getNumOperands();
581 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
582 !MI.getOperand(I).isImplicit();
586 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
587 getTypeToPrint(MI, I, PrintedTypes, MRI),
593 if (MI.getFlag(MachineInstr::FrameSetup))
594 OS << "frame-setup ";
595 OS << TII->getName(MI.getOpcode());
599 bool NeedComma = false;
603 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
604 getTypeToPrint(MI, I, PrintedTypes, MRI));
608 if (MI.getDebugLoc()) {
611 OS << " debug-location ";
612 MI.getDebugLoc()->printAsOperand(OS, MST);
615 if (!MI.memoperands_empty()) {
617 bool NeedComma = false;
618 for (const auto *Op : MI.memoperands()) {
627 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
628 OS << "%bb." << MBB.getNumber();
629 if (const auto *BB = MBB.getBasicBlock()) {
631 OS << '.' << BB->getName();
635 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
642 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
645 printLLVMNameWithoutPrefix(OS, BB.getName());
648 const Function *F = BB.getParent();
650 if (F == MST.getCurrentFunction()) {
651 Slot = MST.getLocalSlot(&BB);
653 ModuleSlotTracker CustomMST(F->getParent(),
654 /*ShouldInitializeAllMetadata=*/false);
655 CustomMST.incorporateFunction(*F);
656 Slot = CustomMST.getLocalSlot(&BB);
658 printIRSlotNumber(OS, Slot);
661 void MIPrinter::printIRValueReference(const Value &V) {
662 if (isa<GlobalValue>(V)) {
663 V.printAsOperand(OS, /*PrintType=*/false, MST);
666 if (isa<Constant>(V)) {
667 // Machine memory operands can load/store to/from constant value pointers.
669 V.printAsOperand(OS, /*PrintType=*/true, MST);
675 printLLVMNameWithoutPrefix(OS, V.getName());
678 printIRSlotNumber(OS, MST.getLocalSlot(&V));
681 void MIPrinter::printStackObjectReference(int FrameIndex) {
682 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
683 assert(ObjectInfo != StackObjectOperandMapping.end() &&
684 "Invalid frame index");
685 const FrameIndexOperand &Operand = ObjectInfo->second;
686 if (Operand.IsFixed) {
687 OS << "%fixed-stack." << Operand.ID;
690 OS << "%stack." << Operand.ID;
691 if (!Operand.Name.empty())
692 OS << '.' << Operand.Name;
695 void MIPrinter::printOffset(int64_t Offset) {
699 OS << " - " << -Offset;
702 OS << " + " << Offset;
705 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
706 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
707 for (const auto &I : Flags) {
715 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
716 if (!Op.getTargetFlags())
719 Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
720 assert(TII && "expected instruction info");
721 auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
722 OS << "target-flags(";
723 const bool HasDirectFlags = Flags.first;
724 const bool HasBitmaskFlags = Flags.second;
725 if (!HasDirectFlags && !HasBitmaskFlags) {
729 if (HasDirectFlags) {
730 if (const auto *Name = getTargetFlagName(TII, Flags.first))
733 OS << "<unknown target flag>";
735 if (!HasBitmaskFlags) {
739 bool IsCommaNeeded = HasDirectFlags;
740 unsigned BitMask = Flags.second;
741 auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
742 for (const auto &Mask : BitMasks) {
743 // Check if the flag's bitmask has the bits of the current mask set.
744 if ((BitMask & Mask.first) == Mask.first) {
747 IsCommaNeeded = true;
749 // Clear the bits which were serialized from the flag's bitmask.
750 BitMask &= ~(Mask.first);
754 // When the resulting flag's bitmask isn't zero, we know that we didn't
755 // serialize all of the bit flags.
758 OS << "<unknown bitmask target flag>";
763 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
764 const auto *TII = MF.getSubtarget().getInstrInfo();
765 assert(TII && "expected instruction info");
766 auto Indices = TII->getSerializableTargetIndices();
767 for (const auto &I : Indices) {
768 if (I.first == Index) {
775 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
776 unsigned I, bool ShouldPrintRegisterTies, LLT TypeToPrint,
778 printTargetFlags(Op);
779 switch (Op.getType()) {
780 case MachineOperand::MO_Register:
782 OS << (Op.isDef() ? "implicit-def " : "implicit ");
783 else if (!IsDef && Op.isDef())
784 // Print the 'def' flag only when the operand is defined after '='.
786 if (Op.isInternalRead())
794 if (Op.isEarlyClobber())
795 OS << "early-clobber ";
798 printReg(Op.getReg(), OS, TRI);
799 // Print the sub register.
800 if (Op.getSubReg() != 0)
801 OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
802 if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
803 OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
804 if (TypeToPrint.isValid())
805 OS << '(' << TypeToPrint << ')';
807 case MachineOperand::MO_Immediate:
810 case MachineOperand::MO_CImmediate:
811 Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
813 case MachineOperand::MO_FPImmediate:
814 Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
816 case MachineOperand::MO_MachineBasicBlock:
817 printMBBReference(*Op.getMBB());
819 case MachineOperand::MO_FrameIndex:
820 printStackObjectReference(Op.getIndex());
822 case MachineOperand::MO_ConstantPoolIndex:
823 OS << "%const." << Op.getIndex();
824 printOffset(Op.getOffset());
826 case MachineOperand::MO_TargetIndex: {
827 OS << "target-index(";
828 if (const auto *Name = getTargetIndexName(
829 *Op.getParent()->getParent()->getParent(), Op.getIndex()))
834 printOffset(Op.getOffset());
837 case MachineOperand::MO_JumpTableIndex:
838 OS << "%jump-table." << Op.getIndex();
840 case MachineOperand::MO_ExternalSymbol:
842 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
843 printOffset(Op.getOffset());
845 case MachineOperand::MO_GlobalAddress:
846 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
847 printOffset(Op.getOffset());
849 case MachineOperand::MO_BlockAddress:
850 OS << "blockaddress(";
851 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
854 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
856 printOffset(Op.getOffset());
858 case MachineOperand::MO_RegisterMask: {
859 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
860 if (RegMaskInfo != RegisterMaskIds.end())
861 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
863 llvm_unreachable("Can't print this machine register mask yet.");
866 case MachineOperand::MO_RegisterLiveOut: {
867 const uint32_t *RegMask = Op.getRegLiveOut();
869 bool IsCommaNeeded = false;
870 for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
871 if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
874 printReg(Reg, OS, TRI);
875 IsCommaNeeded = true;
881 case MachineOperand::MO_Metadata:
882 Op.getMetadata()->printAsOperand(OS, MST);
884 case MachineOperand::MO_MCSymbol:
885 OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
887 case MachineOperand::MO_CFIIndex: {
888 const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
889 print(MF.getFrameInstructions()[Op.getCFIIndex()], TRI);
892 case MachineOperand::MO_IntrinsicID: {
893 Intrinsic::ID ID = Op.getIntrinsicID();
894 if (ID < Intrinsic::num_intrinsics)
895 OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
897 const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
898 const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
899 OS << "intrinsic(@" << TII->getName(ID) << ')';
903 case MachineOperand::MO_Predicate: {
904 auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
905 OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
906 << CmpInst::getPredicateName(Pred) << ')';
912 void MIPrinter::print(const MachineMemOperand &Op) {
914 // TODO: Print operand's target specific flags.
917 if (Op.isNonTemporal())
918 OS << "non-temporal ";
919 if (Op.isDereferenceable())
920 OS << "dereferenceable ";
921 if (Op.isInvariant())
926 assert(Op.isStore() && "Non load machine operand must be a store");
930 if (const Value *Val = Op.getValue()) {
931 OS << (Op.isLoad() ? " from " : " into ");
932 printIRValueReference(*Val);
933 } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
934 OS << (Op.isLoad() ? " from " : " into ");
935 assert(PVal && "Expected a pseudo source value");
936 switch (PVal->kind()) {
937 case PseudoSourceValue::Stack:
940 case PseudoSourceValue::GOT:
943 case PseudoSourceValue::JumpTable:
946 case PseudoSourceValue::ConstantPool:
947 OS << "constant-pool";
949 case PseudoSourceValue::FixedStack:
950 printStackObjectReference(
951 cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
953 case PseudoSourceValue::GlobalValueCallEntry:
955 cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
956 OS, /*PrintType=*/false, MST);
958 case PseudoSourceValue::ExternalSymbolCallEntry:
959 OS << "call-entry $";
960 printLLVMNameWithoutPrefix(
961 OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
963 case PseudoSourceValue::TargetCustom:
964 llvm_unreachable("TargetCustom pseudo source values are not supported");
968 printOffset(Op.getOffset());
969 if (Op.getBaseAlignment() != Op.getSize())
970 OS << ", align " << Op.getBaseAlignment();
971 auto AAInfo = Op.getAAInfo();
974 AAInfo.TBAA->printAsOperand(OS, MST);
977 OS << ", !alias.scope ";
978 AAInfo.Scope->printAsOperand(OS, MST);
980 if (AAInfo.NoAlias) {
982 AAInfo.NoAlias->printAsOperand(OS, MST);
984 if (Op.getRanges()) {
986 Op.getRanges()->printAsOperand(OS, MST);
991 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
992 const TargetRegisterInfo *TRI) {
993 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
998 printReg(Reg, OS, TRI);
1001 void MIPrinter::print(const MCCFIInstruction &CFI,
1002 const TargetRegisterInfo *TRI) {
1003 switch (CFI.getOperation()) {
1004 case MCCFIInstruction::OpSameValue:
1005 OS << "same_value ";
1007 OS << "<mcsymbol> ";
1008 printCFIRegister(CFI.getRegister(), OS, TRI);
1010 case MCCFIInstruction::OpOffset:
1013 OS << "<mcsymbol> ";
1014 printCFIRegister(CFI.getRegister(), OS, TRI);
1015 OS << ", " << CFI.getOffset();
1017 case MCCFIInstruction::OpDefCfaRegister:
1018 OS << "def_cfa_register ";
1020 OS << "<mcsymbol> ";
1021 printCFIRegister(CFI.getRegister(), OS, TRI);
1023 case MCCFIInstruction::OpDefCfaOffset:
1024 OS << "def_cfa_offset ";
1026 OS << "<mcsymbol> ";
1027 OS << CFI.getOffset();
1029 case MCCFIInstruction::OpDefCfa:
1032 OS << "<mcsymbol> ";
1033 printCFIRegister(CFI.getRegister(), OS, TRI);
1034 OS << ", " << CFI.getOffset();
1037 // TODO: Print the other CFI Operations.
1038 OS << "<unserializable cfi operation>";
1043 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1044 yaml::Output Out(OS);
1045 Out << const_cast<Module &>(M);
1048 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1049 MIRPrinter Printer(OS);