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.NoVRegs = MF.getProperties().hasProperty(
179 MachineFunctionProperties::Property::NoVRegs);
180 YamlMF.Legalized = MF.getProperties().hasProperty(
181 MachineFunctionProperties::Property::Legalized);
182 YamlMF.RegBankSelected = MF.getProperties().hasProperty(
183 MachineFunctionProperties::Property::RegBankSelected);
184 YamlMF.Selected = MF.getProperties().hasProperty(
185 MachineFunctionProperties::Property::Selected);
187 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
188 ModuleSlotTracker MST(MF.getFunction()->getParent());
189 MST.incorporateFunction(*MF.getFunction());
190 convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
191 convertStackObjects(YamlMF, MF, MST);
192 if (const auto *ConstantPool = MF.getConstantPool())
193 convert(YamlMF, *ConstantPool);
194 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
195 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
196 raw_string_ostream StrOS(YamlMF.Body.Value.Value);
197 bool IsNewlineNeeded = false;
198 for (const auto &MBB : MF) {
201 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
203 IsNewlineNeeded = true;
206 yaml::Output Out(OS);
210 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
211 const TargetRegisterInfo *TRI) {
212 assert(RegMask && "Can't print an empty register mask");
213 OS << StringRef("CustomRegMask(");
215 bool IsRegInRegMaskFound = false;
216 for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
217 // Check whether the register is asserted in regmask.
218 if (RegMask[I / 32] & (1u << (I % 32))) {
219 if (IsRegInRegMaskFound)
221 printReg(I, OS, TRI);
222 IsRegInRegMaskFound = true;
229 void MIRPrinter::convert(yaml::MachineFunction &MF,
230 const MachineRegisterInfo &RegInfo,
231 const TargetRegisterInfo *TRI) {
232 MF.TracksRegLiveness = RegInfo.tracksLiveness();
234 // Print the virtual register definitions.
235 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
236 unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
237 yaml::VirtualRegisterDefinition VReg;
239 if (RegInfo.getRegClassOrNull(Reg))
241 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
242 else if (RegInfo.getRegBankOrNull(Reg))
243 VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
245 VReg.Class = std::string("_");
246 assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
247 "Generic registers must have a valid type");
249 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
251 printReg(PreferredReg, VReg.PreferredRegister, TRI);
252 MF.VirtualRegisters.push_back(VReg);
255 // Print the live ins.
256 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
257 yaml::MachineFunctionLiveIn LiveIn;
258 printReg(I->first, LiveIn.Register, TRI);
260 printReg(I->second, LiveIn.VirtualRegister, TRI);
261 MF.LiveIns.push_back(LiveIn);
264 // Prints the callee saved registers.
265 if (RegInfo.isUpdatedCSRsInitialized()) {
266 const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
267 std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
268 for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
269 yaml::FlowStringValue Reg;
270 printReg(*I, Reg, TRI);
271 CalleeSavedRegisters.push_back(Reg);
273 MF.CalleeSavedRegisters = CalleeSavedRegisters;
277 void MIRPrinter::convert(ModuleSlotTracker &MST,
278 yaml::MachineFrameInfo &YamlMFI,
279 const MachineFrameInfo &MFI) {
280 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
281 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
282 YamlMFI.HasStackMap = MFI.hasStackMap();
283 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
284 YamlMFI.StackSize = MFI.getStackSize();
285 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
286 YamlMFI.MaxAlignment = MFI.getMaxAlignment();
287 YamlMFI.AdjustsStack = MFI.adjustsStack();
288 YamlMFI.HasCalls = MFI.hasCalls();
289 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
290 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
291 YamlMFI.HasVAStart = MFI.hasVAStart();
292 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
293 if (MFI.getSavePoint()) {
294 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
295 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
296 .printMBBReference(*MFI.getSavePoint());
298 if (MFI.getRestorePoint()) {
299 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
300 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
301 .printMBBReference(*MFI.getRestorePoint());
305 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
306 const MachineFunction &MF,
307 ModuleSlotTracker &MST) {
308 const MachineFrameInfo &MFI = MF.getFrameInfo();
309 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
310 // Process fixed stack objects.
312 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
313 if (MFI.isDeadObjectIndex(I))
316 yaml::FixedMachineStackObject YamlObject;
318 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
319 ? yaml::FixedMachineStackObject::SpillSlot
320 : yaml::FixedMachineStackObject::DefaultType;
321 YamlObject.Offset = MFI.getObjectOffset(I);
322 YamlObject.Size = MFI.getObjectSize(I);
323 YamlObject.Alignment = MFI.getObjectAlignment(I);
324 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
325 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
326 YMF.FixedStackObjects.push_back(YamlObject);
327 StackObjectOperandMapping.insert(
328 std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
331 // Process ordinary stack objects.
333 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
334 if (MFI.isDeadObjectIndex(I))
337 yaml::MachineStackObject YamlObject;
339 if (const auto *Alloca = MFI.getObjectAllocation(I))
340 YamlObject.Name.Value =
341 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
342 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
343 ? yaml::MachineStackObject::SpillSlot
344 : MFI.isVariableSizedObjectIndex(I)
345 ? yaml::MachineStackObject::VariableSized
346 : yaml::MachineStackObject::DefaultType;
347 YamlObject.Offset = MFI.getObjectOffset(I);
348 YamlObject.Size = MFI.getObjectSize(I);
349 YamlObject.Alignment = MFI.getObjectAlignment(I);
351 YMF.StackObjects.push_back(YamlObject);
352 StackObjectOperandMapping.insert(std::make_pair(
353 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
356 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
357 yaml::StringValue Reg;
358 printReg(CSInfo.getReg(), Reg, TRI);
359 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
360 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
361 "Invalid stack object index");
362 const FrameIndexOperand &StackObject = StackObjectInfo->second;
363 if (StackObject.IsFixed)
364 YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
366 YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
368 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
369 auto LocalObject = MFI.getLocalFrameObjectMap(I);
370 auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
371 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
372 "Invalid stack object index");
373 const FrameIndexOperand &StackObject = StackObjectInfo->second;
374 assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
375 YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
378 // Print the stack object references in the frame information class after
379 // converting the stack objects.
380 if (MFI.hasStackProtectorIndex()) {
381 raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
382 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
383 .printStackObjectReference(MFI.getStackProtectorIndex());
386 // Print the debug variable information.
387 for (const MachineFunction::VariableDbgInfo &DebugVar :
388 MF.getVariableDbgInfo()) {
389 auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
390 assert(StackObjectInfo != StackObjectOperandMapping.end() &&
391 "Invalid stack object index");
392 const FrameIndexOperand &StackObject = StackObjectInfo->second;
393 assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
394 auto &Object = YMF.StackObjects[StackObject.ID];
396 raw_string_ostream StrOS(Object.DebugVar.Value);
397 DebugVar.Var->printAsOperand(StrOS, MST);
400 raw_string_ostream StrOS(Object.DebugExpr.Value);
401 DebugVar.Expr->printAsOperand(StrOS, MST);
404 raw_string_ostream StrOS(Object.DebugLoc.Value);
405 DebugVar.Loc->printAsOperand(StrOS, MST);
410 void MIRPrinter::convert(yaml::MachineFunction &MF,
411 const MachineConstantPool &ConstantPool) {
413 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
414 // TODO: Serialize target specific constant pool entries.
415 if (Constant.isMachineConstantPoolEntry())
416 llvm_unreachable("Can't print target specific constant pool entries yet");
418 yaml::MachineConstantPoolValue YamlConstant;
420 raw_string_ostream StrOS(Str);
421 Constant.Val.ConstVal->printAsOperand(StrOS);
422 YamlConstant.ID = ID++;
423 YamlConstant.Value = StrOS.str();
424 YamlConstant.Alignment = Constant.getAlignment();
425 MF.Constants.push_back(YamlConstant);
429 void MIRPrinter::convert(ModuleSlotTracker &MST,
430 yaml::MachineJumpTable &YamlJTI,
431 const MachineJumpTableInfo &JTI) {
432 YamlJTI.Kind = JTI.getEntryKind();
434 for (const auto &Table : JTI.getJumpTables()) {
436 yaml::MachineJumpTable::Entry Entry;
438 for (const auto *MBB : Table.MBBs) {
439 raw_string_ostream StrOS(Str);
440 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
441 .printMBBReference(*MBB);
442 Entry.Blocks.push_back(StrOS.str());
445 YamlJTI.Entries.push_back(Entry);
449 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
450 const auto *TRI = MF.getSubtarget().getRegisterInfo();
452 for (const uint32_t *Mask : TRI->getRegMasks())
453 RegisterMaskIds.insert(std::make_pair(Mask, I++));
456 void MIPrinter::print(const MachineBasicBlock &MBB) {
457 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
458 OS << "bb." << MBB.getNumber();
459 bool HasAttributes = false;
460 if (const auto *BB = MBB.getBasicBlock()) {
462 OS << "." << BB->getName();
464 HasAttributes = true;
466 int Slot = MST.getLocalSlot(BB);
468 OS << "<ir-block badref>";
470 OS << (Twine("%ir-block.") + Twine(Slot)).str();
473 if (MBB.hasAddressTaken()) {
474 OS << (HasAttributes ? ", " : " (");
475 OS << "address-taken";
476 HasAttributes = true;
479 OS << (HasAttributes ? ", " : " (");
481 HasAttributes = true;
483 if (MBB.getAlignment()) {
484 OS << (HasAttributes ? ", " : " (");
485 OS << "align " << MBB.getAlignment();
486 HasAttributes = true;
492 bool HasLineAttributes = false;
493 // Print the successors
494 if (!MBB.succ_empty()) {
495 OS.indent(2) << "successors: ";
496 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
497 if (I != MBB.succ_begin())
499 printMBBReference(**I);
500 if (MBB.hasSuccessorProbabilities())
502 << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
506 HasLineAttributes = true;
509 // Print the live in registers.
510 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
511 if (MRI.tracksLiveness() && !MBB.livein_empty()) {
512 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
513 OS.indent(2) << "liveins: ";
515 for (const auto &LI : MBB.liveins()) {
519 printReg(LI.PhysReg, OS, &TRI);
520 if (!LI.LaneMask.all())
521 OS << ":0x" << PrintLaneMask(LI.LaneMask);
524 HasLineAttributes = true;
527 if (HasLineAttributes)
529 bool IsInBundle = false;
530 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
531 const MachineInstr &MI = *I;
532 if (IsInBundle && !MI.isInsideBundle()) {
533 OS.indent(2) << "}\n";
536 OS.indent(IsInBundle ? 4 : 2);
538 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
545 OS.indent(2) << "}\n";
548 /// Return true when an instruction has tied register that can't be determined
549 /// by the instruction's descriptor.
550 static bool hasComplexRegisterTies(const MachineInstr &MI) {
551 const MCInstrDesc &MCID = MI.getDesc();
552 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
553 const auto &Operand = MI.getOperand(I);
554 if (!Operand.isReg() || Operand.isDef())
555 // Ignore the defined registers as MCID marks only the uses as tied.
557 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
558 int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
559 if (ExpectedTiedIdx != TiedIdx)
565 static LLT getTypeToPrint(const MachineInstr &MI, unsigned OpIdx,
566 SmallBitVector &PrintedTypes,
567 const MachineRegisterInfo &MRI) {
568 const MachineOperand &Op = MI.getOperand(OpIdx);
572 if (MI.isVariadic() || OpIdx >= MI.getNumExplicitOperands())
573 return MRI.getType(Op.getReg());
575 auto &OpInfo = MI.getDesc().OpInfo[OpIdx];
576 if (!OpInfo.isGenericType())
577 return MRI.getType(Op.getReg());
579 if (PrintedTypes[OpInfo.getGenericTypeIndex()])
582 PrintedTypes.set(OpInfo.getGenericTypeIndex());
583 return MRI.getType(Op.getReg());
586 void MIPrinter::print(const MachineInstr &MI) {
587 const auto *MF = MI.getParent()->getParent();
588 const auto &MRI = MF->getRegInfo();
589 const auto &SubTarget = MF->getSubtarget();
590 const auto *TRI = SubTarget.getRegisterInfo();
591 assert(TRI && "Expected target register info");
592 const auto *TII = SubTarget.getInstrInfo();
593 assert(TII && "Expected target instruction info");
594 if (MI.isCFIInstruction())
595 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
597 SmallBitVector PrintedTypes(8);
598 bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
599 unsigned I = 0, E = MI.getNumOperands();
600 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
601 !MI.getOperand(I).isImplicit();
605 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
606 getTypeToPrint(MI, I, PrintedTypes, MRI),
612 if (MI.getFlag(MachineInstr::FrameSetup))
613 OS << "frame-setup ";
614 OS << TII->getName(MI.getOpcode());
618 bool NeedComma = false;
622 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
623 getTypeToPrint(MI, I, PrintedTypes, MRI));
627 if (MI.getDebugLoc()) {
630 OS << " debug-location ";
631 MI.getDebugLoc()->printAsOperand(OS, MST);
634 if (!MI.memoperands_empty()) {
636 bool NeedComma = false;
637 for (const auto *Op : MI.memoperands()) {
646 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
647 OS << "%bb." << MBB.getNumber();
648 if (const auto *BB = MBB.getBasicBlock()) {
650 OS << '.' << BB->getName();
654 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
661 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
664 printLLVMNameWithoutPrefix(OS, BB.getName());
667 const Function *F = BB.getParent();
669 if (F == MST.getCurrentFunction()) {
670 Slot = MST.getLocalSlot(&BB);
672 ModuleSlotTracker CustomMST(F->getParent(),
673 /*ShouldInitializeAllMetadata=*/false);
674 CustomMST.incorporateFunction(*F);
675 Slot = CustomMST.getLocalSlot(&BB);
677 printIRSlotNumber(OS, Slot);
680 void MIPrinter::printIRValueReference(const Value &V) {
681 if (isa<GlobalValue>(V)) {
682 V.printAsOperand(OS, /*PrintType=*/false, MST);
685 if (isa<Constant>(V)) {
686 // Machine memory operands can load/store to/from constant value pointers.
688 V.printAsOperand(OS, /*PrintType=*/true, MST);
694 printLLVMNameWithoutPrefix(OS, V.getName());
697 printIRSlotNumber(OS, MST.getLocalSlot(&V));
700 void MIPrinter::printStackObjectReference(int FrameIndex) {
701 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
702 assert(ObjectInfo != StackObjectOperandMapping.end() &&
703 "Invalid frame index");
704 const FrameIndexOperand &Operand = ObjectInfo->second;
705 if (Operand.IsFixed) {
706 OS << "%fixed-stack." << Operand.ID;
709 OS << "%stack." << Operand.ID;
710 if (!Operand.Name.empty())
711 OS << '.' << Operand.Name;
714 void MIPrinter::printOffset(int64_t Offset) {
718 OS << " - " << -Offset;
721 OS << " + " << Offset;
724 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
725 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
726 for (const auto &I : Flags) {
734 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
735 if (!Op.getTargetFlags())
738 Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
739 assert(TII && "expected instruction info");
740 auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
741 OS << "target-flags(";
742 const bool HasDirectFlags = Flags.first;
743 const bool HasBitmaskFlags = Flags.second;
744 if (!HasDirectFlags && !HasBitmaskFlags) {
748 if (HasDirectFlags) {
749 if (const auto *Name = getTargetFlagName(TII, Flags.first))
752 OS << "<unknown target flag>";
754 if (!HasBitmaskFlags) {
758 bool IsCommaNeeded = HasDirectFlags;
759 unsigned BitMask = Flags.second;
760 auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
761 for (const auto &Mask : BitMasks) {
762 // Check if the flag's bitmask has the bits of the current mask set.
763 if ((BitMask & Mask.first) == Mask.first) {
766 IsCommaNeeded = true;
768 // Clear the bits which were serialized from the flag's bitmask.
769 BitMask &= ~(Mask.first);
773 // When the resulting flag's bitmask isn't zero, we know that we didn't
774 // serialize all of the bit flags.
777 OS << "<unknown bitmask target flag>";
782 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
783 const auto *TII = MF.getSubtarget().getInstrInfo();
784 assert(TII && "expected instruction info");
785 auto Indices = TII->getSerializableTargetIndices();
786 for (const auto &I : Indices) {
787 if (I.first == Index) {
794 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
795 unsigned I, bool ShouldPrintRegisterTies, LLT TypeToPrint,
797 printTargetFlags(Op);
798 switch (Op.getType()) {
799 case MachineOperand::MO_Register:
801 OS << (Op.isDef() ? "implicit-def " : "implicit ");
802 else if (!IsDef && Op.isDef())
803 // Print the 'def' flag only when the operand is defined after '='.
805 if (Op.isInternalRead())
813 if (Op.isEarlyClobber())
814 OS << "early-clobber ";
817 printReg(Op.getReg(), OS, TRI);
818 // Print the sub register.
819 if (Op.getSubReg() != 0)
820 OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
821 if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
822 OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
823 if (TypeToPrint.isValid())
824 OS << '(' << TypeToPrint << ')';
826 case MachineOperand::MO_Immediate:
829 case MachineOperand::MO_CImmediate:
830 Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
832 case MachineOperand::MO_FPImmediate:
833 Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
835 case MachineOperand::MO_MachineBasicBlock:
836 printMBBReference(*Op.getMBB());
838 case MachineOperand::MO_FrameIndex:
839 printStackObjectReference(Op.getIndex());
841 case MachineOperand::MO_ConstantPoolIndex:
842 OS << "%const." << Op.getIndex();
843 printOffset(Op.getOffset());
845 case MachineOperand::MO_TargetIndex: {
846 OS << "target-index(";
847 if (const auto *Name = getTargetIndexName(
848 *Op.getParent()->getParent()->getParent(), Op.getIndex()))
853 printOffset(Op.getOffset());
856 case MachineOperand::MO_JumpTableIndex:
857 OS << "%jump-table." << Op.getIndex();
859 case MachineOperand::MO_ExternalSymbol:
861 printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
862 printOffset(Op.getOffset());
864 case MachineOperand::MO_GlobalAddress:
865 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
866 printOffset(Op.getOffset());
868 case MachineOperand::MO_BlockAddress:
869 OS << "blockaddress(";
870 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
873 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
875 printOffset(Op.getOffset());
877 case MachineOperand::MO_RegisterMask: {
878 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
879 if (RegMaskInfo != RegisterMaskIds.end())
880 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
882 printCustomRegMask(Op.getRegMask(), OS, TRI);
885 case MachineOperand::MO_RegisterLiveOut: {
886 const uint32_t *RegMask = Op.getRegLiveOut();
888 bool IsCommaNeeded = false;
889 for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
890 if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
893 printReg(Reg, OS, TRI);
894 IsCommaNeeded = true;
900 case MachineOperand::MO_Metadata:
901 Op.getMetadata()->printAsOperand(OS, MST);
903 case MachineOperand::MO_MCSymbol:
904 OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
906 case MachineOperand::MO_CFIIndex: {
907 const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
908 print(MF.getFrameInstructions()[Op.getCFIIndex()], TRI);
911 case MachineOperand::MO_IntrinsicID: {
912 Intrinsic::ID ID = Op.getIntrinsicID();
913 if (ID < Intrinsic::num_intrinsics)
914 OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
916 const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
917 const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
918 OS << "intrinsic(@" << TII->getName(ID) << ')';
922 case MachineOperand::MO_Predicate: {
923 auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
924 OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
925 << CmpInst::getPredicateName(Pred) << ')';
931 void MIPrinter::print(const MachineMemOperand &Op) {
933 // TODO: Print operand's target specific flags.
936 if (Op.isNonTemporal())
937 OS << "non-temporal ";
938 if (Op.isDereferenceable())
939 OS << "dereferenceable ";
940 if (Op.isInvariant())
945 assert(Op.isStore() && "Non load machine operand must be a store");
949 if (Op.getSynchScope() == SynchronizationScope::SingleThread)
950 OS << "singlethread ";
952 if (Op.getOrdering() != AtomicOrdering::NotAtomic)
953 OS << toIRString(Op.getOrdering()) << ' ';
954 if (Op.getFailureOrdering() != AtomicOrdering::NotAtomic)
955 OS << toIRString(Op.getFailureOrdering()) << ' ';
958 if (const Value *Val = Op.getValue()) {
959 OS << (Op.isLoad() ? " from " : " into ");
960 printIRValueReference(*Val);
961 } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
962 OS << (Op.isLoad() ? " from " : " into ");
963 assert(PVal && "Expected a pseudo source value");
964 switch (PVal->kind()) {
965 case PseudoSourceValue::Stack:
968 case PseudoSourceValue::GOT:
971 case PseudoSourceValue::JumpTable:
974 case PseudoSourceValue::ConstantPool:
975 OS << "constant-pool";
977 case PseudoSourceValue::FixedStack:
978 printStackObjectReference(
979 cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
981 case PseudoSourceValue::GlobalValueCallEntry:
983 cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
984 OS, /*PrintType=*/false, MST);
986 case PseudoSourceValue::ExternalSymbolCallEntry:
987 OS << "call-entry $";
988 printLLVMNameWithoutPrefix(
989 OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
991 case PseudoSourceValue::TargetCustom:
992 llvm_unreachable("TargetCustom pseudo source values are not supported");
996 printOffset(Op.getOffset());
997 if (Op.getBaseAlignment() != Op.getSize())
998 OS << ", align " << Op.getBaseAlignment();
999 auto AAInfo = Op.getAAInfo();
1002 AAInfo.TBAA->printAsOperand(OS, MST);
1005 OS << ", !alias.scope ";
1006 AAInfo.Scope->printAsOperand(OS, MST);
1008 if (AAInfo.NoAlias) {
1009 OS << ", !noalias ";
1010 AAInfo.NoAlias->printAsOperand(OS, MST);
1012 if (Op.getRanges()) {
1014 Op.getRanges()->printAsOperand(OS, MST);
1019 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
1020 const TargetRegisterInfo *TRI) {
1021 int Reg = TRI->getLLVMRegNum(DwarfReg, true);
1026 printReg(Reg, OS, TRI);
1029 void MIPrinter::print(const MCCFIInstruction &CFI,
1030 const TargetRegisterInfo *TRI) {
1031 switch (CFI.getOperation()) {
1032 case MCCFIInstruction::OpSameValue:
1033 OS << "same_value ";
1035 OS << "<mcsymbol> ";
1036 printCFIRegister(CFI.getRegister(), OS, TRI);
1038 case MCCFIInstruction::OpOffset:
1041 OS << "<mcsymbol> ";
1042 printCFIRegister(CFI.getRegister(), OS, TRI);
1043 OS << ", " << CFI.getOffset();
1045 case MCCFIInstruction::OpDefCfaRegister:
1046 OS << "def_cfa_register ";
1048 OS << "<mcsymbol> ";
1049 printCFIRegister(CFI.getRegister(), OS, TRI);
1051 case MCCFIInstruction::OpDefCfaOffset:
1052 OS << "def_cfa_offset ";
1054 OS << "<mcsymbol> ";
1055 OS << CFI.getOffset();
1057 case MCCFIInstruction::OpDefCfa:
1060 OS << "<mcsymbol> ";
1061 printCFIRegister(CFI.getRegister(), OS, TRI);
1062 OS << ", " << CFI.getOffset();
1065 // TODO: Print the other CFI Operations.
1066 OS << "<unserializable cfi operation>";
1071 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1072 yaml::Output Out(OS);
1073 Out << const_cast<Module &>(M);
1076 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1077 MIRPrinter Printer(OS);