]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/MIRPrinter.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r301441, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / MIRPrinter.cpp
1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the class that prints out the LLVM IR and machine
11 // functions using the MIR serialization format.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
42
43 using namespace llvm;
44
45 namespace {
46
47 /// This structure describes how to print out stack object references.
48 struct FrameIndexOperand {
49   std::string Name;
50   unsigned ID;
51   bool IsFixed;
52
53   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
54       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
55
56   /// Return an ordinary stack object reference.
57   static FrameIndexOperand create(StringRef Name, unsigned ID) {
58     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
59   }
60
61   /// Return a fixed stack object reference.
62   static FrameIndexOperand createFixed(unsigned ID) {
63     return FrameIndexOperand("", ID, /*IsFixed=*/true);
64   }
65 };
66
67 } // end anonymous namespace
68
69 namespace llvm {
70
71 /// This class prints out the machine functions using the MIR serialization
72 /// format.
73 class MIRPrinter {
74   raw_ostream &OS;
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;
79
80 public:
81   MIRPrinter(raw_ostream &OS) : OS(OS) {}
82
83   void print(const MachineFunction &MF);
84
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);
95
96 private:
97   void initRegisterMaskIds(const MachineFunction &MF);
98 };
99
100 /// This class prints out the machine instructions using the MIR serialization
101 /// format.
102 class MIPrinter {
103   raw_ostream &OS;
104   ModuleSlotTracker &MST;
105   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
106   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
107
108 public:
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) {}
114
115   void print(const MachineBasicBlock &MBB);
116
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);
128
129   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
130 };
131
132 } // end namespace llvm
133
134 namespace llvm {
135 namespace yaml {
136
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);
141   }
142   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
143     llvm_unreachable("LLVM Module is supposed to be parsed separately");
144     return "";
145   }
146 };
147
148 } // end namespace yaml
149 } // end namespace llvm
150
151 static void printReg(unsigned Reg, raw_ostream &OS,
152                      const TargetRegisterInfo *TRI) {
153   // TODO: Print Stack Slots.
154   if (!Reg)
155     OS << '_';
156   else if (TargetRegisterInfo::isVirtualRegister(Reg))
157     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
158   else if (Reg < TRI->getNumRegs())
159     OS << '%' << StringRef(TRI->getName(Reg)).lower();
160   else
161     llvm_unreachable("Can't print this kind of register yet");
162 }
163
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);
168 }
169
170 void MIRPrinter::print(const MachineFunction &MF) {
171   initRegisterMaskIds(MF);
172
173   yaml::MachineFunction YamlMF;
174   YamlMF.Name = MF.getName();
175   YamlMF.Alignment = MF.getAlignment();
176   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
177
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);
186
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) {
199     if (IsNewlineNeeded)
200       StrOS << "\n";
201     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
202         .print(MBB);
203     IsNewlineNeeded = true;
204   }
205   StrOS.flush();
206   yaml::Output Out(OS);
207   Out << YamlMF;
208 }
209
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(");
214
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)
220         OS << ',';
221       printReg(I, OS, TRI);
222       IsRegInRegMaskFound = true;
223     }
224   }
225
226   OS << ')';
227 }
228
229 void MIRPrinter::convert(yaml::MachineFunction &MF,
230                          const MachineRegisterInfo &RegInfo,
231                          const TargetRegisterInfo *TRI) {
232   MF.TracksRegLiveness = RegInfo.tracksLiveness();
233
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;
238     VReg.ID = I;
239     if (RegInfo.getRegClassOrNull(Reg))
240       VReg.Class =
241           StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
242     else if (RegInfo.getRegBankOrNull(Reg))
243       VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
244     else {
245       VReg.Class = std::string("_");
246       assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
247              "Generic registers must have a valid type");
248     }
249     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
250     if (PreferredReg)
251       printReg(PreferredReg, VReg.PreferredRegister, TRI);
252     MF.VirtualRegisters.push_back(VReg);
253   }
254
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);
259     if (I->second)
260       printReg(I->second, LiveIn.VirtualRegister, TRI);
261     MF.LiveIns.push_back(LiveIn);
262   }
263
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);
272     }
273     MF.CalleeSavedRegisters = CalleeSavedRegisters;
274   }
275 }
276
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());
297   }
298   if (MFI.getRestorePoint()) {
299     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
300     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
301         .printMBBReference(*MFI.getRestorePoint());
302   }
303 }
304
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.
311   unsigned ID = 0;
312   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
313     if (MFI.isDeadObjectIndex(I))
314       continue;
315
316     yaml::FixedMachineStackObject YamlObject;
317     YamlObject.ID = ID;
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++)));
329   }
330
331   // Process ordinary stack objects.
332   ID = 0;
333   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
334     if (MFI.isDeadObjectIndex(I))
335       continue;
336
337     yaml::MachineStackObject YamlObject;
338     YamlObject.ID = ID;
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);
350
351     YMF.StackObjects.push_back(YamlObject);
352     StackObjectOperandMapping.insert(std::make_pair(
353         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
354   }
355
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;
365     else
366       YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
367   }
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;
376   }
377
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());
384   }
385
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];
395     {
396       raw_string_ostream StrOS(Object.DebugVar.Value);
397       DebugVar.Var->printAsOperand(StrOS, MST);
398     }
399     {
400       raw_string_ostream StrOS(Object.DebugExpr.Value);
401       DebugVar.Expr->printAsOperand(StrOS, MST);
402     }
403     {
404       raw_string_ostream StrOS(Object.DebugLoc.Value);
405       DebugVar.Loc->printAsOperand(StrOS, MST);
406     }
407   }
408 }
409
410 void MIRPrinter::convert(yaml::MachineFunction &MF,
411                          const MachineConstantPool &ConstantPool) {
412   unsigned ID = 0;
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");
417
418     yaml::MachineConstantPoolValue YamlConstant;
419     std::string Str;
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);
426   }
427 }
428
429 void MIRPrinter::convert(ModuleSlotTracker &MST,
430                          yaml::MachineJumpTable &YamlJTI,
431                          const MachineJumpTableInfo &JTI) {
432   YamlJTI.Kind = JTI.getEntryKind();
433   unsigned ID = 0;
434   for (const auto &Table : JTI.getJumpTables()) {
435     std::string Str;
436     yaml::MachineJumpTable::Entry Entry;
437     Entry.ID = ID++;
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());
443       Str.clear();
444     }
445     YamlJTI.Entries.push_back(Entry);
446   }
447 }
448
449 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
450   const auto *TRI = MF.getSubtarget().getRegisterInfo();
451   unsigned I = 0;
452   for (const uint32_t *Mask : TRI->getRegMasks())
453     RegisterMaskIds.insert(std::make_pair(Mask, I++));
454 }
455
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()) {
461     if (BB->hasName()) {
462       OS << "." << BB->getName();
463     } else {
464       HasAttributes = true;
465       OS << " (";
466       int Slot = MST.getLocalSlot(BB);
467       if (Slot == -1)
468         OS << "<ir-block badref>";
469       else
470         OS << (Twine("%ir-block.") + Twine(Slot)).str();
471     }
472   }
473   if (MBB.hasAddressTaken()) {
474     OS << (HasAttributes ? ", " : " (");
475     OS << "address-taken";
476     HasAttributes = true;
477   }
478   if (MBB.isEHPad()) {
479     OS << (HasAttributes ? ", " : " (");
480     OS << "landing-pad";
481     HasAttributes = true;
482   }
483   if (MBB.getAlignment()) {
484     OS << (HasAttributes ? ", " : " (");
485     OS << "align " << MBB.getAlignment();
486     HasAttributes = true;
487   }
488   if (HasAttributes)
489     OS << ")";
490   OS << ":\n";
491
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())
498         OS << ", ";
499       printMBBReference(**I);
500       if (MBB.hasSuccessorProbabilities())
501         OS << '('
502            << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
503            << ')';
504     }
505     OS << "\n";
506     HasLineAttributes = true;
507   }
508
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: ";
514     bool First = true;
515     for (const auto &LI : MBB.liveins()) {
516       if (!First)
517         OS << ", ";
518       First = false;
519       printReg(LI.PhysReg, OS, &TRI);
520       if (!LI.LaneMask.all())
521         OS << ":0x" << PrintLaneMask(LI.LaneMask);
522     }
523     OS << "\n";
524     HasLineAttributes = true;
525   }
526
527   if (HasLineAttributes)
528     OS << "\n";
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";
534       IsInBundle = false;
535     }
536     OS.indent(IsInBundle ? 4 : 2);
537     print(MI);
538     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
539       OS << " {";
540       IsInBundle = true;
541     }
542     OS << "\n";
543   }
544   if (IsInBundle)
545     OS.indent(2) << "}\n";
546 }
547
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.
556       continue;
557     int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
558     int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
559     if (ExpectedTiedIdx != TiedIdx)
560       return true;
561   }
562   return false;
563 }
564
565 static LLT getTypeToPrint(const MachineInstr &MI, unsigned OpIdx,
566                           SmallBitVector &PrintedTypes,
567                           const MachineRegisterInfo &MRI) {
568   const MachineOperand &Op = MI.getOperand(OpIdx);
569   if (!Op.isReg())
570     return LLT{};
571
572   if (MI.isVariadic() || OpIdx >= MI.getNumExplicitOperands())
573     return MRI.getType(Op.getReg());
574
575   auto &OpInfo = MI.getDesc().OpInfo[OpIdx];
576   if (!OpInfo.isGenericType())
577     return MRI.getType(Op.getReg());
578
579   if (PrintedTypes[OpInfo.getGenericTypeIndex()])
580     return LLT{};
581
582   PrintedTypes.set(OpInfo.getGenericTypeIndex());
583   return MRI.getType(Op.getReg());
584 }
585
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");
596
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();
602        ++I) {
603     if (I)
604       OS << ", ";
605     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
606           getTypeToPrint(MI, I, PrintedTypes, MRI),
607           /*IsDef=*/true);
608   }
609
610   if (I)
611     OS << " = ";
612   if (MI.getFlag(MachineInstr::FrameSetup))
613     OS << "frame-setup ";
614   OS << TII->getName(MI.getOpcode());
615   if (I < E)
616     OS << ' ';
617
618   bool NeedComma = false;
619   for (; I < E; ++I) {
620     if (NeedComma)
621       OS << ", ";
622     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
623           getTypeToPrint(MI, I, PrintedTypes, MRI));
624     NeedComma = true;
625   }
626
627   if (MI.getDebugLoc()) {
628     if (NeedComma)
629       OS << ',';
630     OS << " debug-location ";
631     MI.getDebugLoc()->printAsOperand(OS, MST);
632   }
633
634   if (!MI.memoperands_empty()) {
635     OS << " :: ";
636     bool NeedComma = false;
637     for (const auto *Op : MI.memoperands()) {
638       if (NeedComma)
639         OS << ", ";
640       print(*Op);
641       NeedComma = true;
642     }
643   }
644 }
645
646 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
647   OS << "%bb." << MBB.getNumber();
648   if (const auto *BB = MBB.getBasicBlock()) {
649     if (BB->hasName())
650       OS << '.' << BB->getName();
651   }
652 }
653
654 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
655   if (Slot == -1)
656     OS << "<badref>";
657   else
658     OS << Slot;
659 }
660
661 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
662   OS << "%ir-block.";
663   if (BB.hasName()) {
664     printLLVMNameWithoutPrefix(OS, BB.getName());
665     return;
666   }
667   const Function *F = BB.getParent();
668   int Slot;
669   if (F == MST.getCurrentFunction()) {
670     Slot = MST.getLocalSlot(&BB);
671   } else {
672     ModuleSlotTracker CustomMST(F->getParent(),
673                                 /*ShouldInitializeAllMetadata=*/false);
674     CustomMST.incorporateFunction(*F);
675     Slot = CustomMST.getLocalSlot(&BB);
676   }
677   printIRSlotNumber(OS, Slot);
678 }
679
680 void MIPrinter::printIRValueReference(const Value &V) {
681   if (isa<GlobalValue>(V)) {
682     V.printAsOperand(OS, /*PrintType=*/false, MST);
683     return;
684   }
685   if (isa<Constant>(V)) {
686     // Machine memory operands can load/store to/from constant value pointers.
687     OS << '`';
688     V.printAsOperand(OS, /*PrintType=*/true, MST);
689     OS << '`';
690     return;
691   }
692   OS << "%ir.";
693   if (V.hasName()) {
694     printLLVMNameWithoutPrefix(OS, V.getName());
695     return;
696   }
697   printIRSlotNumber(OS, MST.getLocalSlot(&V));
698 }
699
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;
707     return;
708   }
709   OS << "%stack." << Operand.ID;
710   if (!Operand.Name.empty())
711     OS << '.' << Operand.Name;
712 }
713
714 void MIPrinter::printOffset(int64_t Offset) {
715   if (Offset == 0)
716     return;
717   if (Offset < 0) {
718     OS << " - " << -Offset;
719     return;
720   }
721   OS << " + " << Offset;
722 }
723
724 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
725   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
726   for (const auto &I : Flags) {
727     if (I.first == TF) {
728       return I.second;
729     }
730   }
731   return nullptr;
732 }
733
734 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
735   if (!Op.getTargetFlags())
736     return;
737   const auto *TII =
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) {
745     OS << "<unknown>) ";
746     return;
747   }
748   if (HasDirectFlags) {
749     if (const auto *Name = getTargetFlagName(TII, Flags.first))
750       OS << Name;
751     else
752       OS << "<unknown target flag>";
753   }
754   if (!HasBitmaskFlags) {
755     OS << ") ";
756     return;
757   }
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) {
764       if (IsCommaNeeded)
765         OS << ", ";
766       IsCommaNeeded = true;
767       OS << Mask.second;
768       // Clear the bits which were serialized from the flag's bitmask.
769       BitMask &= ~(Mask.first);
770     }
771   }
772   if (BitMask) {
773     // When the resulting flag's bitmask isn't zero, we know that we didn't
774     // serialize all of the bit flags.
775     if (IsCommaNeeded)
776       OS << ", ";
777     OS << "<unknown bitmask target flag>";
778   }
779   OS << ") ";
780 }
781
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) {
788       return I.second;
789     }
790   }
791   return nullptr;
792 }
793
794 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
795                       unsigned I, bool ShouldPrintRegisterTies, LLT TypeToPrint,
796                       bool IsDef) {
797   printTargetFlags(Op);
798   switch (Op.getType()) {
799   case MachineOperand::MO_Register:
800     if (Op.isImplicit())
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 '='.
804       OS << "def ";
805     if (Op.isInternalRead())
806       OS << "internal ";
807     if (Op.isDead())
808       OS << "dead ";
809     if (Op.isKill())
810       OS << "killed ";
811     if (Op.isUndef())
812       OS << "undef ";
813     if (Op.isEarlyClobber())
814       OS << "early-clobber ";
815     if (Op.isDebug())
816       OS << "debug-use ";
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 << ')';
825     break;
826   case MachineOperand::MO_Immediate:
827     OS << Op.getImm();
828     break;
829   case MachineOperand::MO_CImmediate:
830     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
831     break;
832   case MachineOperand::MO_FPImmediate:
833     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
834     break;
835   case MachineOperand::MO_MachineBasicBlock:
836     printMBBReference(*Op.getMBB());
837     break;
838   case MachineOperand::MO_FrameIndex:
839     printStackObjectReference(Op.getIndex());
840     break;
841   case MachineOperand::MO_ConstantPoolIndex:
842     OS << "%const." << Op.getIndex();
843     printOffset(Op.getOffset());
844     break;
845   case MachineOperand::MO_TargetIndex: {
846     OS << "target-index(";
847     if (const auto *Name = getTargetIndexName(
848             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
849       OS << Name;
850     else
851       OS << "<unknown>";
852     OS << ')';
853     printOffset(Op.getOffset());
854     break;
855   }
856   case MachineOperand::MO_JumpTableIndex:
857     OS << "%jump-table." << Op.getIndex();
858     break;
859   case MachineOperand::MO_ExternalSymbol:
860     OS << '$';
861     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
862     printOffset(Op.getOffset());
863     break;
864   case MachineOperand::MO_GlobalAddress:
865     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
866     printOffset(Op.getOffset());
867     break;
868   case MachineOperand::MO_BlockAddress:
869     OS << "blockaddress(";
870     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
871                                                         MST);
872     OS << ", ";
873     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
874     OS << ')';
875     printOffset(Op.getOffset());
876     break;
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();
881     else
882       printCustomRegMask(Op.getRegMask(), OS, TRI);
883     break;
884   }
885   case MachineOperand::MO_RegisterLiveOut: {
886     const uint32_t *RegMask = Op.getRegLiveOut();
887     OS << "liveout(";
888     bool IsCommaNeeded = false;
889     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
890       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
891         if (IsCommaNeeded)
892           OS << ", ";
893         printReg(Reg, OS, TRI);
894         IsCommaNeeded = true;
895       }
896     }
897     OS << ")";
898     break;
899   }
900   case MachineOperand::MO_Metadata:
901     Op.getMetadata()->printAsOperand(OS, MST);
902     break;
903   case MachineOperand::MO_MCSymbol:
904     OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
905     break;
906   case MachineOperand::MO_CFIIndex: {
907     const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
908     print(MF.getFrameInstructions()[Op.getCFIIndex()], TRI);
909     break;
910   }
911   case MachineOperand::MO_IntrinsicID: {
912     Intrinsic::ID ID = Op.getIntrinsicID();
913     if (ID < Intrinsic::num_intrinsics)
914       OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
915     else {
916       const MachineFunction &MF = *Op.getParent()->getParent()->getParent();
917       const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
918       OS << "intrinsic(@" << TII->getName(ID) << ')';
919     }
920     break;
921   }
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) << ')';
926     break;
927   }
928   }
929 }
930
931 void MIPrinter::print(const MachineMemOperand &Op) {
932   OS << '(';
933   // TODO: Print operand's target specific flags.
934   if (Op.isVolatile())
935     OS << "volatile ";
936   if (Op.isNonTemporal())
937     OS << "non-temporal ";
938   if (Op.isDereferenceable())
939     OS << "dereferenceable ";
940   if (Op.isInvariant())
941     OS << "invariant ";
942   if (Op.isLoad())
943     OS << "load ";
944   else {
945     assert(Op.isStore() && "Non load machine operand must be a store");
946     OS << "store ";
947   }
948
949   if (Op.getSynchScope() == SynchronizationScope::SingleThread)
950     OS << "singlethread ";
951
952   if (Op.getOrdering() != AtomicOrdering::NotAtomic)
953     OS << toIRString(Op.getOrdering()) << ' ';
954   if (Op.getFailureOrdering() != AtomicOrdering::NotAtomic)
955     OS << toIRString(Op.getFailureOrdering()) << ' ';
956
957   OS << Op.getSize();
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:
966       OS << "stack";
967       break;
968     case PseudoSourceValue::GOT:
969       OS << "got";
970       break;
971     case PseudoSourceValue::JumpTable:
972       OS << "jump-table";
973       break;
974     case PseudoSourceValue::ConstantPool:
975       OS << "constant-pool";
976       break;
977     case PseudoSourceValue::FixedStack:
978       printStackObjectReference(
979           cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
980       break;
981     case PseudoSourceValue::GlobalValueCallEntry:
982       OS << "call-entry ";
983       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
984           OS, /*PrintType=*/false, MST);
985       break;
986     case PseudoSourceValue::ExternalSymbolCallEntry:
987       OS << "call-entry $";
988       printLLVMNameWithoutPrefix(
989           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
990       break;
991     case PseudoSourceValue::TargetCustom:
992       llvm_unreachable("TargetCustom pseudo source values are not supported");
993       break;
994     }
995   }
996   printOffset(Op.getOffset());
997   if (Op.getBaseAlignment() != Op.getSize())
998     OS << ", align " << Op.getBaseAlignment();
999   auto AAInfo = Op.getAAInfo();
1000   if (AAInfo.TBAA) {
1001     OS << ", !tbaa ";
1002     AAInfo.TBAA->printAsOperand(OS, MST);
1003   }
1004   if (AAInfo.Scope) {
1005     OS << ", !alias.scope ";
1006     AAInfo.Scope->printAsOperand(OS, MST);
1007   }
1008   if (AAInfo.NoAlias) {
1009     OS << ", !noalias ";
1010     AAInfo.NoAlias->printAsOperand(OS, MST);
1011   }
1012   if (Op.getRanges()) {
1013     OS << ", !range ";
1014     Op.getRanges()->printAsOperand(OS, MST);
1015   }
1016   OS << ')';
1017 }
1018
1019 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
1020                              const TargetRegisterInfo *TRI) {
1021   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
1022   if (Reg == -1) {
1023     OS << "<badreg>";
1024     return;
1025   }
1026   printReg(Reg, OS, TRI);
1027 }
1028
1029 void MIPrinter::print(const MCCFIInstruction &CFI,
1030                       const TargetRegisterInfo *TRI) {
1031   switch (CFI.getOperation()) {
1032   case MCCFIInstruction::OpSameValue:
1033     OS << "same_value ";
1034     if (CFI.getLabel())
1035       OS << "<mcsymbol> ";
1036     printCFIRegister(CFI.getRegister(), OS, TRI);
1037     break;
1038   case MCCFIInstruction::OpOffset:
1039     OS << "offset ";
1040     if (CFI.getLabel())
1041       OS << "<mcsymbol> ";
1042     printCFIRegister(CFI.getRegister(), OS, TRI);
1043     OS << ", " << CFI.getOffset();
1044     break;
1045   case MCCFIInstruction::OpDefCfaRegister:
1046     OS << "def_cfa_register ";
1047     if (CFI.getLabel())
1048       OS << "<mcsymbol> ";
1049     printCFIRegister(CFI.getRegister(), OS, TRI);
1050     break;
1051   case MCCFIInstruction::OpDefCfaOffset:
1052     OS << "def_cfa_offset ";
1053     if (CFI.getLabel())
1054       OS << "<mcsymbol> ";
1055     OS << CFI.getOffset();
1056     break;
1057   case MCCFIInstruction::OpDefCfa:
1058     OS << "def_cfa ";
1059     if (CFI.getLabel())
1060       OS << "<mcsymbol> ";
1061     printCFIRegister(CFI.getRegister(), OS, TRI);
1062     OS << ", " << CFI.getOffset();
1063     break;
1064   default:
1065     // TODO: Print the other CFI Operations.
1066     OS << "<unserializable cfi operation>";
1067     break;
1068   }
1069 }
1070
1071 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1072   yaml::Output Out(OS);
1073   Out << const_cast<Module &>(M);
1074 }
1075
1076 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1077   MIRPrinter Printer(OS);
1078   Printer.print(MF);
1079 }