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 "llvm/CodeGen/MIRPrinter.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallBitVector.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
25 #include "llvm/CodeGen/MIRYamlMapping.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/TargetInstrInfo.h"
37 #include "llvm/CodeGen/TargetRegisterInfo.h"
38 #include "llvm/CodeGen/TargetSubtargetInfo.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DebugInfo.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/IRPrintingPasses.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/IR/ModuleSlotTracker.h"
51 #include "llvm/IR/Value.h"
52 #include "llvm/MC/LaneBitmask.h"
53 #include "llvm/MC/MCDwarf.h"
54 #include "llvm/MC/MCSymbol.h"
55 #include "llvm/Support/AtomicOrdering.h"
56 #include "llvm/Support/BranchProbability.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/CommandLine.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/Format.h"
61 #include "llvm/Support/LowLevelTypeImpl.h"
62 #include "llvm/Support/YAMLTraits.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetIntrinsicInfo.h"
65 #include "llvm/Target/TargetMachine.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cinttypes>
69 #include <cstdint>
70 #include <iterator>
71 #include <string>
72 #include <utility>
73 #include <vector>
74 
75 using namespace llvm;
76 
77 static cl::opt<bool> SimplifyMIR(
78     "simplify-mir", cl::Hidden,
79     cl::desc("Leave out unnecessary information when printing MIR"));
80 
81 namespace {
82 
83 /// This structure describes how to print out stack object references.
84 struct FrameIndexOperand {
85   std::string Name;
86   unsigned ID;
87   bool IsFixed;
88 
89   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
90       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
91 
92   /// Return an ordinary stack object reference.
93   static FrameIndexOperand create(StringRef Name, unsigned ID) {
94     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
95   }
96 
97   /// Return a fixed stack object reference.
98   static FrameIndexOperand createFixed(unsigned ID) {
99     return FrameIndexOperand("", ID, /*IsFixed=*/true);
100   }
101 };
102 
103 } // end anonymous namespace
104 
105 namespace llvm {
106 
107 /// This class prints out the machine functions using the MIR serialization
108 /// format.
109 class MIRPrinter {
110   raw_ostream &OS;
111   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
112   /// Maps from stack object indices to operand indices which will be used when
113   /// printing frame index machine operands.
114   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
115 
116 public:
117   MIRPrinter(raw_ostream &OS) : OS(OS) {}
118 
119   void print(const MachineFunction &MF);
120 
121   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
122                const TargetRegisterInfo *TRI);
123   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
124                const MachineFrameInfo &MFI);
125   void convert(yaml::MachineFunction &MF,
126                const MachineConstantPool &ConstantPool);
127   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
128                const MachineJumpTableInfo &JTI);
129   void convertStackObjects(yaml::MachineFunction &YMF,
130                            const MachineFunction &MF, ModuleSlotTracker &MST);
131 
132 private:
133   void initRegisterMaskIds(const MachineFunction &MF);
134 };
135 
136 /// This class prints out the machine instructions using the MIR serialization
137 /// format.
138 class MIPrinter {
139   raw_ostream &OS;
140   ModuleSlotTracker &MST;
141   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
142   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
143   /// Synchronization scope names registered with LLVMContext.
144   SmallVector<StringRef, 8> SSNs;
145 
146   bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
147   bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
148 
149 public:
150   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
151             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
152             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
153       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
154         StackObjectOperandMapping(StackObjectOperandMapping) {}
155 
156   void print(const MachineBasicBlock &MBB);
157 
158   void print(const MachineInstr &MI);
159   void printStackObjectReference(int FrameIndex);
160   void print(const MachineInstr &MI, unsigned OpIdx,
161              const TargetRegisterInfo *TRI, bool ShouldPrintRegisterTies,
162              LLT TypeToPrint, bool PrintDef = true);
163 };
164 
165 } // end namespace llvm
166 
167 namespace llvm {
168 namespace yaml {
169 
170 /// This struct serializes the LLVM IR module.
171 template <> struct BlockScalarTraits<Module> {
172   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
173     Mod.print(OS, nullptr);
174   }
175 
176   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
177     llvm_unreachable("LLVM Module is supposed to be parsed separately");
178     return "";
179   }
180 };
181 
182 } // end namespace yaml
183 } // end namespace llvm
184 
185 static void printRegMIR(unsigned Reg, yaml::StringValue &Dest,
186                         const TargetRegisterInfo *TRI) {
187   raw_string_ostream OS(Dest.Value);
188   OS << printReg(Reg, TRI);
189 }
190 
191 void MIRPrinter::print(const MachineFunction &MF) {
192   initRegisterMaskIds(MF);
193 
194   yaml::MachineFunction YamlMF;
195   YamlMF.Name = MF.getName();
196   YamlMF.Alignment = MF.getAlignment();
197   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
198 
199   YamlMF.Legalized = MF.getProperties().hasProperty(
200       MachineFunctionProperties::Property::Legalized);
201   YamlMF.RegBankSelected = MF.getProperties().hasProperty(
202       MachineFunctionProperties::Property::RegBankSelected);
203   YamlMF.Selected = MF.getProperties().hasProperty(
204       MachineFunctionProperties::Property::Selected);
205   YamlMF.FailedISel = MF.getProperties().hasProperty(
206       MachineFunctionProperties::Property::FailedISel);
207 
208   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
209   ModuleSlotTracker MST(MF.getFunction().getParent());
210   MST.incorporateFunction(MF.getFunction());
211   convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
212   convertStackObjects(YamlMF, MF, MST);
213   if (const auto *ConstantPool = MF.getConstantPool())
214     convert(YamlMF, *ConstantPool);
215   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
216     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
217   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
218   bool IsNewlineNeeded = false;
219   for (const auto &MBB : MF) {
220     if (IsNewlineNeeded)
221       StrOS << "\n";
222     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
223         .print(MBB);
224     IsNewlineNeeded = true;
225   }
226   StrOS.flush();
227   yaml::Output Out(OS);
228   if (!SimplifyMIR)
229       Out.setWriteDefaultValues(true);
230   Out << YamlMF;
231 }
232 
233 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
234                                const TargetRegisterInfo *TRI) {
235   assert(RegMask && "Can't print an empty register mask");
236   OS << StringRef("CustomRegMask(");
237 
238   bool IsRegInRegMaskFound = false;
239   for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
240     // Check whether the register is asserted in regmask.
241     if (RegMask[I / 32] & (1u << (I % 32))) {
242       if (IsRegInRegMaskFound)
243         OS << ',';
244       OS << printReg(I, TRI);
245       IsRegInRegMaskFound = true;
246     }
247   }
248 
249   OS << ')';
250 }
251 
252 static void printRegClassOrBank(unsigned Reg, yaml::StringValue &Dest,
253                                 const MachineRegisterInfo &RegInfo,
254                                 const TargetRegisterInfo *TRI) {
255   raw_string_ostream OS(Dest.Value);
256   OS << printRegClassOrBank(Reg, RegInfo, TRI);
257 }
258 
259 
260 void MIRPrinter::convert(yaml::MachineFunction &MF,
261                          const MachineRegisterInfo &RegInfo,
262                          const TargetRegisterInfo *TRI) {
263   MF.TracksRegLiveness = RegInfo.tracksLiveness();
264 
265   // Print the virtual register definitions.
266   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
267     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
268     yaml::VirtualRegisterDefinition VReg;
269     VReg.ID = I;
270     ::printRegClassOrBank(Reg, VReg.Class, RegInfo, TRI);
271     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
272     if (PreferredReg)
273       printRegMIR(PreferredReg, VReg.PreferredRegister, TRI);
274     MF.VirtualRegisters.push_back(VReg);
275   }
276 
277   // Print the live ins.
278   for (std::pair<unsigned, unsigned> LI : RegInfo.liveins()) {
279     yaml::MachineFunctionLiveIn LiveIn;
280     printRegMIR(LI.first, LiveIn.Register, TRI);
281     if (LI.second)
282       printRegMIR(LI.second, LiveIn.VirtualRegister, TRI);
283     MF.LiveIns.push_back(LiveIn);
284   }
285 
286   // Prints the callee saved registers.
287   if (RegInfo.isUpdatedCSRsInitialized()) {
288     const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
289     std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
290     for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
291       yaml::FlowStringValue Reg;
292       printRegMIR(*I, Reg, TRI);
293       CalleeSavedRegisters.push_back(Reg);
294     }
295     MF.CalleeSavedRegisters = CalleeSavedRegisters;
296   }
297 }
298 
299 void MIRPrinter::convert(ModuleSlotTracker &MST,
300                          yaml::MachineFrameInfo &YamlMFI,
301                          const MachineFrameInfo &MFI) {
302   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
303   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
304   YamlMFI.HasStackMap = MFI.hasStackMap();
305   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
306   YamlMFI.StackSize = MFI.getStackSize();
307   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
308   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
309   YamlMFI.AdjustsStack = MFI.adjustsStack();
310   YamlMFI.HasCalls = MFI.hasCalls();
311   YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
312     ? MFI.getMaxCallFrameSize() : ~0u;
313   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
314   YamlMFI.HasVAStart = MFI.hasVAStart();
315   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
316   if (MFI.getSavePoint()) {
317     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
318     StrOS << printMBBReference(*MFI.getSavePoint());
319   }
320   if (MFI.getRestorePoint()) {
321     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
322     StrOS << printMBBReference(*MFI.getRestorePoint());
323   }
324 }
325 
326 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
327                                      const MachineFunction &MF,
328                                      ModuleSlotTracker &MST) {
329   const MachineFrameInfo &MFI = MF.getFrameInfo();
330   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
331   // Process fixed stack objects.
332   unsigned ID = 0;
333   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
334     if (MFI.isDeadObjectIndex(I))
335       continue;
336 
337     yaml::FixedMachineStackObject YamlObject;
338     YamlObject.ID = ID;
339     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
340                           ? yaml::FixedMachineStackObject::SpillSlot
341                           : yaml::FixedMachineStackObject::DefaultType;
342     YamlObject.Offset = MFI.getObjectOffset(I);
343     YamlObject.Size = MFI.getObjectSize(I);
344     YamlObject.Alignment = MFI.getObjectAlignment(I);
345     YamlObject.StackID = MFI.getStackID(I);
346     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
347     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
348     YMF.FixedStackObjects.push_back(YamlObject);
349     StackObjectOperandMapping.insert(
350         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
351   }
352 
353   // Process ordinary stack objects.
354   ID = 0;
355   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
356     if (MFI.isDeadObjectIndex(I))
357       continue;
358 
359     yaml::MachineStackObject YamlObject;
360     YamlObject.ID = ID;
361     if (const auto *Alloca = MFI.getObjectAllocation(I))
362       YamlObject.Name.Value =
363           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
364     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
365                           ? yaml::MachineStackObject::SpillSlot
366                           : MFI.isVariableSizedObjectIndex(I)
367                                 ? yaml::MachineStackObject::VariableSized
368                                 : yaml::MachineStackObject::DefaultType;
369     YamlObject.Offset = MFI.getObjectOffset(I);
370     YamlObject.Size = MFI.getObjectSize(I);
371     YamlObject.Alignment = MFI.getObjectAlignment(I);
372     YamlObject.StackID = MFI.getStackID(I);
373 
374     YMF.StackObjects.push_back(YamlObject);
375     StackObjectOperandMapping.insert(std::make_pair(
376         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
377   }
378 
379   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
380     yaml::StringValue Reg;
381     printRegMIR(CSInfo.getReg(), Reg, TRI);
382     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
383     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
384            "Invalid stack object index");
385     const FrameIndexOperand &StackObject = StackObjectInfo->second;
386     if (StackObject.IsFixed) {
387       YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
388       YMF.FixedStackObjects[StackObject.ID].CalleeSavedRestored =
389         CSInfo.isRestored();
390     } else {
391       YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
392       YMF.StackObjects[StackObject.ID].CalleeSavedRestored =
393         CSInfo.isRestored();
394     }
395   }
396   for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
397     auto LocalObject = MFI.getLocalFrameObjectMap(I);
398     auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
399     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
400            "Invalid stack object index");
401     const FrameIndexOperand &StackObject = StackObjectInfo->second;
402     assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
403     YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
404   }
405 
406   // Print the stack object references in the frame information class after
407   // converting the stack objects.
408   if (MFI.hasStackProtectorIndex()) {
409     raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
410     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
411         .printStackObjectReference(MFI.getStackProtectorIndex());
412   }
413 
414   // Print the debug variable information.
415   for (const MachineFunction::VariableDbgInfo &DebugVar :
416        MF.getVariableDbgInfo()) {
417     auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
418     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
419            "Invalid stack object index");
420     const FrameIndexOperand &StackObject = StackObjectInfo->second;
421     assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
422     auto &Object = YMF.StackObjects[StackObject.ID];
423     {
424       raw_string_ostream StrOS(Object.DebugVar.Value);
425       DebugVar.Var->printAsOperand(StrOS, MST);
426     }
427     {
428       raw_string_ostream StrOS(Object.DebugExpr.Value);
429       DebugVar.Expr->printAsOperand(StrOS, MST);
430     }
431     {
432       raw_string_ostream StrOS(Object.DebugLoc.Value);
433       DebugVar.Loc->printAsOperand(StrOS, MST);
434     }
435   }
436 }
437 
438 void MIRPrinter::convert(yaml::MachineFunction &MF,
439                          const MachineConstantPool &ConstantPool) {
440   unsigned ID = 0;
441   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
442     std::string Str;
443     raw_string_ostream StrOS(Str);
444     if (Constant.isMachineConstantPoolEntry()) {
445       Constant.Val.MachineCPVal->print(StrOS);
446     } else {
447       Constant.Val.ConstVal->printAsOperand(StrOS);
448     }
449 
450     yaml::MachineConstantPoolValue YamlConstant;
451     YamlConstant.ID = ID++;
452     YamlConstant.Value = StrOS.str();
453     YamlConstant.Alignment = Constant.getAlignment();
454     YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry();
455 
456     MF.Constants.push_back(YamlConstant);
457   }
458 }
459 
460 void MIRPrinter::convert(ModuleSlotTracker &MST,
461                          yaml::MachineJumpTable &YamlJTI,
462                          const MachineJumpTableInfo &JTI) {
463   YamlJTI.Kind = JTI.getEntryKind();
464   unsigned ID = 0;
465   for (const auto &Table : JTI.getJumpTables()) {
466     std::string Str;
467     yaml::MachineJumpTable::Entry Entry;
468     Entry.ID = ID++;
469     for (const auto *MBB : Table.MBBs) {
470       raw_string_ostream StrOS(Str);
471       StrOS << printMBBReference(*MBB);
472       Entry.Blocks.push_back(StrOS.str());
473       Str.clear();
474     }
475     YamlJTI.Entries.push_back(Entry);
476   }
477 }
478 
479 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
480   const auto *TRI = MF.getSubtarget().getRegisterInfo();
481   unsigned I = 0;
482   for (const uint32_t *Mask : TRI->getRegMasks())
483     RegisterMaskIds.insert(std::make_pair(Mask, I++));
484 }
485 
486 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
487                            SmallVectorImpl<MachineBasicBlock*> &Result,
488                            bool &IsFallthrough) {
489   SmallPtrSet<MachineBasicBlock*,8> Seen;
490 
491   for (const MachineInstr &MI : MBB) {
492     if (MI.isPHI())
493       continue;
494     for (const MachineOperand &MO : MI.operands()) {
495       if (!MO.isMBB())
496         continue;
497       MachineBasicBlock *Succ = MO.getMBB();
498       auto RP = Seen.insert(Succ);
499       if (RP.second)
500         Result.push_back(Succ);
501     }
502   }
503   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
504   IsFallthrough = I == MBB.end() || !I->isBarrier();
505 }
506 
507 bool
508 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
509   if (MBB.succ_size() <= 1)
510     return true;
511   if (!MBB.hasSuccessorProbabilities())
512     return true;
513 
514   SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
515                                               MBB.Probs.end());
516   BranchProbability::normalizeProbabilities(Normalized.begin(),
517                                             Normalized.end());
518   SmallVector<BranchProbability,8> Equal(Normalized.size());
519   BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
520 
521   return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
522 }
523 
524 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
525   SmallVector<MachineBasicBlock*,8> GuessedSuccs;
526   bool GuessedFallthrough;
527   guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
528   if (GuessedFallthrough) {
529     const MachineFunction &MF = *MBB.getParent();
530     MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
531     if (NextI != MF.end()) {
532       MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
533       if (!is_contained(GuessedSuccs, Next))
534         GuessedSuccs.push_back(Next);
535     }
536   }
537   if (GuessedSuccs.size() != MBB.succ_size())
538     return false;
539   return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
540 }
541 
542 void MIPrinter::print(const MachineBasicBlock &MBB) {
543   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
544   OS << "bb." << MBB.getNumber();
545   bool HasAttributes = false;
546   if (const auto *BB = MBB.getBasicBlock()) {
547     if (BB->hasName()) {
548       OS << "." << BB->getName();
549     } else {
550       HasAttributes = true;
551       OS << " (";
552       int Slot = MST.getLocalSlot(BB);
553       if (Slot == -1)
554         OS << "<ir-block badref>";
555       else
556         OS << (Twine("%ir-block.") + Twine(Slot)).str();
557     }
558   }
559   if (MBB.hasAddressTaken()) {
560     OS << (HasAttributes ? ", " : " (");
561     OS << "address-taken";
562     HasAttributes = true;
563   }
564   if (MBB.isEHPad()) {
565     OS << (HasAttributes ? ", " : " (");
566     OS << "landing-pad";
567     HasAttributes = true;
568   }
569   if (MBB.getAlignment()) {
570     OS << (HasAttributes ? ", " : " (");
571     OS << "align " << MBB.getAlignment();
572     HasAttributes = true;
573   }
574   if (HasAttributes)
575     OS << ")";
576   OS << ":\n";
577 
578   bool HasLineAttributes = false;
579   // Print the successors
580   bool canPredictProbs = canPredictBranchProbabilities(MBB);
581   // Even if the list of successors is empty, if we cannot guess it,
582   // we need to print it to tell the parser that the list is empty.
583   // This is needed, because MI model unreachable as empty blocks
584   // with an empty successor list. If the parser would see that
585   // without the successor list, it would guess the code would
586   // fallthrough.
587   if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs ||
588       !canPredictSuccessors(MBB)) {
589     OS.indent(2) << "successors: ";
590     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
591       if (I != MBB.succ_begin())
592         OS << ", ";
593       OS << printMBBReference(**I);
594       if (!SimplifyMIR || !canPredictProbs)
595         OS << '('
596            << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
597            << ')';
598     }
599     OS << "\n";
600     HasLineAttributes = true;
601   }
602 
603   // Print the live in registers.
604   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
605   if (MRI.tracksLiveness() && !MBB.livein_empty()) {
606     const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
607     OS.indent(2) << "liveins: ";
608     bool First = true;
609     for (const auto &LI : MBB.liveins()) {
610       if (!First)
611         OS << ", ";
612       First = false;
613       OS << printReg(LI.PhysReg, &TRI);
614       if (!LI.LaneMask.all())
615         OS << ":0x" << PrintLaneMask(LI.LaneMask);
616     }
617     OS << "\n";
618     HasLineAttributes = true;
619   }
620 
621   if (HasLineAttributes)
622     OS << "\n";
623   bool IsInBundle = false;
624   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
625     const MachineInstr &MI = *I;
626     if (IsInBundle && !MI.isInsideBundle()) {
627       OS.indent(2) << "}\n";
628       IsInBundle = false;
629     }
630     OS.indent(IsInBundle ? 4 : 2);
631     print(MI);
632     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
633       OS << " {";
634       IsInBundle = true;
635     }
636     OS << "\n";
637   }
638   if (IsInBundle)
639     OS.indent(2) << "}\n";
640 }
641 
642 void MIPrinter::print(const MachineInstr &MI) {
643   const auto *MF = MI.getMF();
644   const auto &MRI = MF->getRegInfo();
645   const auto &SubTarget = MF->getSubtarget();
646   const auto *TRI = SubTarget.getRegisterInfo();
647   assert(TRI && "Expected target register info");
648   const auto *TII = SubTarget.getInstrInfo();
649   assert(TII && "Expected target instruction info");
650   if (MI.isCFIInstruction())
651     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
652 
653   SmallBitVector PrintedTypes(8);
654   bool ShouldPrintRegisterTies = MI.hasComplexRegisterTies();
655   unsigned I = 0, E = MI.getNumOperands();
656   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
657          !MI.getOperand(I).isImplicit();
658        ++I) {
659     if (I)
660       OS << ", ";
661     print(MI, I, TRI, ShouldPrintRegisterTies,
662           MI.getTypeToPrint(I, PrintedTypes, MRI),
663           /*PrintDef=*/false);
664   }
665 
666   if (I)
667     OS << " = ";
668   if (MI.getFlag(MachineInstr::FrameSetup))
669     OS << "frame-setup ";
670   if (MI.getFlag(MachineInstr::FrameDestroy))
671     OS << "frame-destroy ";
672 
673   OS << TII->getName(MI.getOpcode());
674   if (I < E)
675     OS << ' ';
676 
677   bool NeedComma = false;
678   for (; I < E; ++I) {
679     if (NeedComma)
680       OS << ", ";
681     print(MI, I, TRI, ShouldPrintRegisterTies,
682           MI.getTypeToPrint(I, PrintedTypes, MRI));
683     NeedComma = true;
684   }
685 
686   if (const DebugLoc &DL = MI.getDebugLoc()) {
687     if (NeedComma)
688       OS << ',';
689     OS << " debug-location ";
690     DL->printAsOperand(OS, MST);
691   }
692 
693   if (!MI.memoperands_empty()) {
694     OS << " :: ";
695     const LLVMContext &Context = MF->getFunction().getContext();
696     const MachineFrameInfo &MFI = MF->getFrameInfo();
697     bool NeedComma = false;
698     for (const auto *Op : MI.memoperands()) {
699       if (NeedComma)
700         OS << ", ";
701       Op->print(OS, MST, SSNs, Context, &MFI, TII);
702       NeedComma = true;
703     }
704   }
705 }
706 
707 void MIPrinter::printStackObjectReference(int FrameIndex) {
708   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
709   assert(ObjectInfo != StackObjectOperandMapping.end() &&
710          "Invalid frame index");
711   const FrameIndexOperand &Operand = ObjectInfo->second;
712   MachineOperand::printStackObjectReference(OS, Operand.ID, Operand.IsFixed,
713                                             Operand.Name);
714 }
715 
716 void MIPrinter::print(const MachineInstr &MI, unsigned OpIdx,
717                       const TargetRegisterInfo *TRI,
718                       bool ShouldPrintRegisterTies, LLT TypeToPrint,
719                       bool PrintDef) {
720   const MachineOperand &Op = MI.getOperand(OpIdx);
721   switch (Op.getType()) {
722   case MachineOperand::MO_Immediate:
723     if (MI.isOperandSubregIdx(OpIdx)) {
724       MachineOperand::printTargetFlags(OS, Op);
725       MachineOperand::printSubRegIdx(OS, Op.getImm(), TRI);
726       break;
727     }
728     LLVM_FALLTHROUGH;
729   case MachineOperand::MO_Register:
730   case MachineOperand::MO_CImmediate:
731   case MachineOperand::MO_FPImmediate:
732   case MachineOperand::MO_MachineBasicBlock:
733   case MachineOperand::MO_ConstantPoolIndex:
734   case MachineOperand::MO_TargetIndex:
735   case MachineOperand::MO_JumpTableIndex:
736   case MachineOperand::MO_ExternalSymbol:
737   case MachineOperand::MO_GlobalAddress:
738   case MachineOperand::MO_RegisterLiveOut:
739   case MachineOperand::MO_Metadata:
740   case MachineOperand::MO_MCSymbol:
741   case MachineOperand::MO_CFIIndex:
742   case MachineOperand::MO_IntrinsicID:
743   case MachineOperand::MO_Predicate:
744   case MachineOperand::MO_BlockAddress: {
745     unsigned TiedOperandIdx = 0;
746     if (ShouldPrintRegisterTies && Op.isReg() && Op.isTied() && !Op.isDef())
747       TiedOperandIdx = Op.getParent()->findTiedOperandIdx(OpIdx);
748     const TargetIntrinsicInfo *TII = MI.getMF()->getTarget().getIntrinsicInfo();
749     Op.print(OS, MST, TypeToPrint, PrintDef, /*IsStandalone=*/false,
750              ShouldPrintRegisterTies, TiedOperandIdx, TRI, TII);
751     break;
752   }
753   case MachineOperand::MO_FrameIndex:
754     printStackObjectReference(Op.getIndex());
755     break;
756   case MachineOperand::MO_RegisterMask: {
757     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
758     if (RegMaskInfo != RegisterMaskIds.end())
759       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
760     else
761       printCustomRegMask(Op.getRegMask(), OS, TRI);
762     break;
763   }
764   }
765 }
766 
767 void llvm::printMIR(raw_ostream &OS, const Module &M) {
768   yaml::Output Out(OS);
769   Out << const_cast<Module &>(M);
770 }
771 
772 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
773   MIRPrinter Printer(OS);
774   Printer.print(MF);
775 }
776