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/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
26 #include "llvm/CodeGen/MIRYamlMapping.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetRegisterInfo.h"
39 #include "llvm/CodeGen/TargetSubtargetInfo.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DebugInfo.h"
43 #include "llvm/IR/DebugLoc.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalValue.h"
46 #include "llvm/IR/IRPrintingPasses.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/IR/ModuleSlotTracker.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/MC/LaneBitmask.h"
54 #include "llvm/MC/MCDwarf.h"
55 #include "llvm/MC/MCSymbol.h"
56 #include "llvm/Support/AtomicOrdering.h"
57 #include "llvm/Support/BranchProbability.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/Format.h"
62 #include "llvm/Support/LowLevelTypeImpl.h"
63 #include "llvm/Support/YAMLTraits.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetIntrinsicInfo.h"
66 #include "llvm/Target/TargetMachine.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cinttypes>
70 #include <cstdint>
71 #include <iterator>
72 #include <string>
73 #include <utility>
74 #include <vector>
75 
76 using namespace llvm;
77 
78 static cl::opt<bool> SimplifyMIR(
79     "simplify-mir", cl::Hidden,
80     cl::desc("Leave out unnecessary information when printing MIR"));
81 
82 namespace {
83 
84 /// This structure describes how to print out stack object references.
85 struct FrameIndexOperand {
86   std::string Name;
87   unsigned ID;
88   bool IsFixed;
89 
90   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
91       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
92 
93   /// Return an ordinary stack object reference.
94   static FrameIndexOperand create(StringRef Name, unsigned ID) {
95     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
96   }
97 
98   /// Return a fixed stack object reference.
99   static FrameIndexOperand createFixed(unsigned ID) {
100     return FrameIndexOperand("", ID, /*IsFixed=*/true);
101   }
102 };
103 
104 } // end anonymous namespace
105 
106 namespace llvm {
107 
108 /// This class prints out the machine functions using the MIR serialization
109 /// format.
110 class MIRPrinter {
111   raw_ostream &OS;
112   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
113   /// Maps from stack object indices to operand indices which will be used when
114   /// printing frame index machine operands.
115   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
116 
117 public:
118   MIRPrinter(raw_ostream &OS) : OS(OS) {}
119 
120   void print(const MachineFunction &MF);
121 
122   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
123                const TargetRegisterInfo *TRI);
124   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
125                const MachineFrameInfo &MFI);
126   void convert(yaml::MachineFunction &MF,
127                const MachineConstantPool &ConstantPool);
128   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
129                const MachineJumpTableInfo &JTI);
130   void convertStackObjects(yaml::MachineFunction &YMF,
131                            const MachineFunction &MF, ModuleSlotTracker &MST);
132 
133 private:
134   void initRegisterMaskIds(const MachineFunction &MF);
135 };
136 
137 /// This class prints out the machine instructions using the MIR serialization
138 /// format.
139 class MIPrinter {
140   raw_ostream &OS;
141   ModuleSlotTracker &MST;
142   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
143   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
144   /// Synchronization scope names registered with LLVMContext.
145   SmallVector<StringRef, 8> SSNs;
146 
147   bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
148   bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
149 
150 public:
151   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
152             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
153             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
154       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
155         StackObjectOperandMapping(StackObjectOperandMapping) {}
156 
157   void print(const MachineBasicBlock &MBB);
158 
159   void print(const MachineInstr &MI);
160   void printIRBlockReference(const BasicBlock &BB);
161   void printIRValueReference(const Value &V);
162   void printStackObjectReference(int FrameIndex);
163   void printOffset(int64_t Offset);
164   void printTargetFlags(const MachineOperand &Op);
165   void print(const MachineInstr &MI, unsigned OpIdx,
166              const TargetRegisterInfo *TRI, bool ShouldPrintRegisterTies,
167              LLT TypeToPrint, bool PrintDef = true);
168   void print(const LLVMContext &Context, const TargetInstrInfo &TII,
169              const MachineMemOperand &Op);
170   void printSyncScope(const LLVMContext &Context, SyncScope::ID SSID);
171 
172   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
173 };
174 
175 } // end namespace llvm
176 
177 namespace llvm {
178 namespace yaml {
179 
180 /// This struct serializes the LLVM IR module.
181 template <> struct BlockScalarTraits<Module> {
182   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
183     Mod.print(OS, nullptr);
184   }
185 
186   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
187     llvm_unreachable("LLVM Module is supposed to be parsed separately");
188     return "";
189   }
190 };
191 
192 } // end namespace yaml
193 } // end namespace llvm
194 
195 static void printRegMIR(unsigned Reg, yaml::StringValue &Dest,
196                         const TargetRegisterInfo *TRI) {
197   raw_string_ostream OS(Dest.Value);
198   OS << printReg(Reg, TRI);
199 }
200 
201 void MIRPrinter::print(const MachineFunction &MF) {
202   initRegisterMaskIds(MF);
203 
204   yaml::MachineFunction YamlMF;
205   YamlMF.Name = MF.getName();
206   YamlMF.Alignment = MF.getAlignment();
207   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
208 
209   YamlMF.Legalized = MF.getProperties().hasProperty(
210       MachineFunctionProperties::Property::Legalized);
211   YamlMF.RegBankSelected = MF.getProperties().hasProperty(
212       MachineFunctionProperties::Property::RegBankSelected);
213   YamlMF.Selected = MF.getProperties().hasProperty(
214       MachineFunctionProperties::Property::Selected);
215 
216   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
217   ModuleSlotTracker MST(MF.getFunction()->getParent());
218   MST.incorporateFunction(*MF.getFunction());
219   convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
220   convertStackObjects(YamlMF, MF, MST);
221   if (const auto *ConstantPool = MF.getConstantPool())
222     convert(YamlMF, *ConstantPool);
223   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
224     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
225   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
226   bool IsNewlineNeeded = false;
227   for (const auto &MBB : MF) {
228     if (IsNewlineNeeded)
229       StrOS << "\n";
230     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
231         .print(MBB);
232     IsNewlineNeeded = true;
233   }
234   StrOS.flush();
235   yaml::Output Out(OS);
236   if (!SimplifyMIR)
237       Out.setWriteDefaultValues(true);
238   Out << YamlMF;
239 }
240 
241 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
242                                const TargetRegisterInfo *TRI) {
243   assert(RegMask && "Can't print an empty register mask");
244   OS << StringRef("CustomRegMask(");
245 
246   bool IsRegInRegMaskFound = false;
247   for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
248     // Check whether the register is asserted in regmask.
249     if (RegMask[I / 32] & (1u << (I % 32))) {
250       if (IsRegInRegMaskFound)
251         OS << ',';
252       OS << printReg(I, TRI);
253       IsRegInRegMaskFound = true;
254     }
255   }
256 
257   OS << ')';
258 }
259 
260 static void printRegClassOrBank(unsigned Reg, yaml::StringValue &Dest,
261                                 const MachineRegisterInfo &RegInfo,
262                                 const TargetRegisterInfo *TRI) {
263   raw_string_ostream OS(Dest.Value);
264   OS << printRegClassOrBank(Reg, RegInfo, TRI);
265 }
266 
267 
268 void MIRPrinter::convert(yaml::MachineFunction &MF,
269                          const MachineRegisterInfo &RegInfo,
270                          const TargetRegisterInfo *TRI) {
271   MF.TracksRegLiveness = RegInfo.tracksLiveness();
272 
273   // Print the virtual register definitions.
274   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
275     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
276     yaml::VirtualRegisterDefinition VReg;
277     VReg.ID = I;
278     ::printRegClassOrBank(Reg, VReg.Class, RegInfo, TRI);
279     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
280     if (PreferredReg)
281       printRegMIR(PreferredReg, VReg.PreferredRegister, TRI);
282     MF.VirtualRegisters.push_back(VReg);
283   }
284 
285   // Print the live ins.
286   for (std::pair<unsigned, unsigned> LI : RegInfo.liveins()) {
287     yaml::MachineFunctionLiveIn LiveIn;
288     printRegMIR(LI.first, LiveIn.Register, TRI);
289     if (LI.second)
290       printRegMIR(LI.second, LiveIn.VirtualRegister, TRI);
291     MF.LiveIns.push_back(LiveIn);
292   }
293 
294   // Prints the callee saved registers.
295   if (RegInfo.isUpdatedCSRsInitialized()) {
296     const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
297     std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
298     for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
299       yaml::FlowStringValue Reg;
300       printRegMIR(*I, Reg, TRI);
301       CalleeSavedRegisters.push_back(Reg);
302     }
303     MF.CalleeSavedRegisters = CalleeSavedRegisters;
304   }
305 }
306 
307 void MIRPrinter::convert(ModuleSlotTracker &MST,
308                          yaml::MachineFrameInfo &YamlMFI,
309                          const MachineFrameInfo &MFI) {
310   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
311   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
312   YamlMFI.HasStackMap = MFI.hasStackMap();
313   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
314   YamlMFI.StackSize = MFI.getStackSize();
315   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
316   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
317   YamlMFI.AdjustsStack = MFI.adjustsStack();
318   YamlMFI.HasCalls = MFI.hasCalls();
319   YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
320     ? MFI.getMaxCallFrameSize() : ~0u;
321   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
322   YamlMFI.HasVAStart = MFI.hasVAStart();
323   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
324   if (MFI.getSavePoint()) {
325     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
326     StrOS << printMBBReference(*MFI.getSavePoint());
327   }
328   if (MFI.getRestorePoint()) {
329     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
330     StrOS << printMBBReference(*MFI.getRestorePoint());
331   }
332 }
333 
334 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
335                                      const MachineFunction &MF,
336                                      ModuleSlotTracker &MST) {
337   const MachineFrameInfo &MFI = MF.getFrameInfo();
338   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
339   // Process fixed stack objects.
340   unsigned ID = 0;
341   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
342     if (MFI.isDeadObjectIndex(I))
343       continue;
344 
345     yaml::FixedMachineStackObject YamlObject;
346     YamlObject.ID = ID;
347     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
348                           ? yaml::FixedMachineStackObject::SpillSlot
349                           : yaml::FixedMachineStackObject::DefaultType;
350     YamlObject.Offset = MFI.getObjectOffset(I);
351     YamlObject.Size = MFI.getObjectSize(I);
352     YamlObject.Alignment = MFI.getObjectAlignment(I);
353     YamlObject.StackID = MFI.getStackID(I);
354     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
355     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
356     YMF.FixedStackObjects.push_back(YamlObject);
357     StackObjectOperandMapping.insert(
358         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
359   }
360 
361   // Process ordinary stack objects.
362   ID = 0;
363   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
364     if (MFI.isDeadObjectIndex(I))
365       continue;
366 
367     yaml::MachineStackObject YamlObject;
368     YamlObject.ID = ID;
369     if (const auto *Alloca = MFI.getObjectAllocation(I))
370       YamlObject.Name.Value =
371           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
372     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
373                           ? yaml::MachineStackObject::SpillSlot
374                           : MFI.isVariableSizedObjectIndex(I)
375                                 ? yaml::MachineStackObject::VariableSized
376                                 : yaml::MachineStackObject::DefaultType;
377     YamlObject.Offset = MFI.getObjectOffset(I);
378     YamlObject.Size = MFI.getObjectSize(I);
379     YamlObject.Alignment = MFI.getObjectAlignment(I);
380     YamlObject.StackID = MFI.getStackID(I);
381 
382     YMF.StackObjects.push_back(YamlObject);
383     StackObjectOperandMapping.insert(std::make_pair(
384         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
385   }
386 
387   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
388     yaml::StringValue Reg;
389     printRegMIR(CSInfo.getReg(), Reg, TRI);
390     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
391     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
392            "Invalid stack object index");
393     const FrameIndexOperand &StackObject = StackObjectInfo->second;
394     if (StackObject.IsFixed) {
395       YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
396       YMF.FixedStackObjects[StackObject.ID].CalleeSavedRestored =
397         CSInfo.isRestored();
398     } else {
399       YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
400       YMF.StackObjects[StackObject.ID].CalleeSavedRestored =
401         CSInfo.isRestored();
402     }
403   }
404   for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
405     auto LocalObject = MFI.getLocalFrameObjectMap(I);
406     auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
407     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
408            "Invalid stack object index");
409     const FrameIndexOperand &StackObject = StackObjectInfo->second;
410     assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
411     YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
412   }
413 
414   // Print the stack object references in the frame information class after
415   // converting the stack objects.
416   if (MFI.hasStackProtectorIndex()) {
417     raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
418     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
419         .printStackObjectReference(MFI.getStackProtectorIndex());
420   }
421 
422   // Print the debug variable information.
423   for (const MachineFunction::VariableDbgInfo &DebugVar :
424        MF.getVariableDbgInfo()) {
425     auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
426     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
427            "Invalid stack object index");
428     const FrameIndexOperand &StackObject = StackObjectInfo->second;
429     assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
430     auto &Object = YMF.StackObjects[StackObject.ID];
431     {
432       raw_string_ostream StrOS(Object.DebugVar.Value);
433       DebugVar.Var->printAsOperand(StrOS, MST);
434     }
435     {
436       raw_string_ostream StrOS(Object.DebugExpr.Value);
437       DebugVar.Expr->printAsOperand(StrOS, MST);
438     }
439     {
440       raw_string_ostream StrOS(Object.DebugLoc.Value);
441       DebugVar.Loc->printAsOperand(StrOS, MST);
442     }
443   }
444 }
445 
446 void MIRPrinter::convert(yaml::MachineFunction &MF,
447                          const MachineConstantPool &ConstantPool) {
448   unsigned ID = 0;
449   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
450     std::string Str;
451     raw_string_ostream StrOS(Str);
452     if (Constant.isMachineConstantPoolEntry()) {
453       Constant.Val.MachineCPVal->print(StrOS);
454     } else {
455       Constant.Val.ConstVal->printAsOperand(StrOS);
456     }
457 
458     yaml::MachineConstantPoolValue YamlConstant;
459     YamlConstant.ID = ID++;
460     YamlConstant.Value = StrOS.str();
461     YamlConstant.Alignment = Constant.getAlignment();
462     YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry();
463 
464     MF.Constants.push_back(YamlConstant);
465   }
466 }
467 
468 void MIRPrinter::convert(ModuleSlotTracker &MST,
469                          yaml::MachineJumpTable &YamlJTI,
470                          const MachineJumpTableInfo &JTI) {
471   YamlJTI.Kind = JTI.getEntryKind();
472   unsigned ID = 0;
473   for (const auto &Table : JTI.getJumpTables()) {
474     std::string Str;
475     yaml::MachineJumpTable::Entry Entry;
476     Entry.ID = ID++;
477     for (const auto *MBB : Table.MBBs) {
478       raw_string_ostream StrOS(Str);
479       StrOS << printMBBReference(*MBB);
480       Entry.Blocks.push_back(StrOS.str());
481       Str.clear();
482     }
483     YamlJTI.Entries.push_back(Entry);
484   }
485 }
486 
487 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
488   const auto *TRI = MF.getSubtarget().getRegisterInfo();
489   unsigned I = 0;
490   for (const uint32_t *Mask : TRI->getRegMasks())
491     RegisterMaskIds.insert(std::make_pair(Mask, I++));
492 }
493 
494 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
495                            SmallVectorImpl<MachineBasicBlock*> &Result,
496                            bool &IsFallthrough) {
497   SmallPtrSet<MachineBasicBlock*,8> Seen;
498 
499   for (const MachineInstr &MI : MBB) {
500     if (MI.isPHI())
501       continue;
502     for (const MachineOperand &MO : MI.operands()) {
503       if (!MO.isMBB())
504         continue;
505       MachineBasicBlock *Succ = MO.getMBB();
506       auto RP = Seen.insert(Succ);
507       if (RP.second)
508         Result.push_back(Succ);
509     }
510   }
511   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
512   IsFallthrough = I == MBB.end() || !I->isBarrier();
513 }
514 
515 bool
516 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
517   if (MBB.succ_size() <= 1)
518     return true;
519   if (!MBB.hasSuccessorProbabilities())
520     return true;
521 
522   SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
523                                               MBB.Probs.end());
524   BranchProbability::normalizeProbabilities(Normalized.begin(),
525                                             Normalized.end());
526   SmallVector<BranchProbability,8> Equal(Normalized.size());
527   BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
528 
529   return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
530 }
531 
532 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
533   SmallVector<MachineBasicBlock*,8> GuessedSuccs;
534   bool GuessedFallthrough;
535   guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
536   if (GuessedFallthrough) {
537     const MachineFunction &MF = *MBB.getParent();
538     MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
539     if (NextI != MF.end()) {
540       MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
541       if (!is_contained(GuessedSuccs, Next))
542         GuessedSuccs.push_back(Next);
543     }
544   }
545   if (GuessedSuccs.size() != MBB.succ_size())
546     return false;
547   return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
548 }
549 
550 void MIPrinter::print(const MachineBasicBlock &MBB) {
551   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
552   OS << "bb." << MBB.getNumber();
553   bool HasAttributes = false;
554   if (const auto *BB = MBB.getBasicBlock()) {
555     if (BB->hasName()) {
556       OS << "." << BB->getName();
557     } else {
558       HasAttributes = true;
559       OS << " (";
560       int Slot = MST.getLocalSlot(BB);
561       if (Slot == -1)
562         OS << "<ir-block badref>";
563       else
564         OS << (Twine("%ir-block.") + Twine(Slot)).str();
565     }
566   }
567   if (MBB.hasAddressTaken()) {
568     OS << (HasAttributes ? ", " : " (");
569     OS << "address-taken";
570     HasAttributes = true;
571   }
572   if (MBB.isEHPad()) {
573     OS << (HasAttributes ? ", " : " (");
574     OS << "landing-pad";
575     HasAttributes = true;
576   }
577   if (MBB.getAlignment()) {
578     OS << (HasAttributes ? ", " : " (");
579     OS << "align " << MBB.getAlignment();
580     HasAttributes = true;
581   }
582   if (HasAttributes)
583     OS << ")";
584   OS << ":\n";
585 
586   bool HasLineAttributes = false;
587   // Print the successors
588   bool canPredictProbs = canPredictBranchProbabilities(MBB);
589   // Even if the list of successors is empty, if we cannot guess it,
590   // we need to print it to tell the parser that the list is empty.
591   // This is needed, because MI model unreachable as empty blocks
592   // with an empty successor list. If the parser would see that
593   // without the successor list, it would guess the code would
594   // fallthrough.
595   if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs ||
596       !canPredictSuccessors(MBB)) {
597     OS.indent(2) << "successors: ";
598     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
599       if (I != MBB.succ_begin())
600         OS << ", ";
601       OS << printMBBReference(**I);
602       if (!SimplifyMIR || !canPredictProbs)
603         OS << '('
604            << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
605            << ')';
606     }
607     OS << "\n";
608     HasLineAttributes = true;
609   }
610 
611   // Print the live in registers.
612   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
613   if (MRI.tracksLiveness() && !MBB.livein_empty()) {
614     const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
615     OS.indent(2) << "liveins: ";
616     bool First = true;
617     for (const auto &LI : MBB.liveins()) {
618       if (!First)
619         OS << ", ";
620       First = false;
621       OS << printReg(LI.PhysReg, &TRI);
622       if (!LI.LaneMask.all())
623         OS << ":0x" << PrintLaneMask(LI.LaneMask);
624     }
625     OS << "\n";
626     HasLineAttributes = true;
627   }
628 
629   if (HasLineAttributes)
630     OS << "\n";
631   bool IsInBundle = false;
632   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
633     const MachineInstr &MI = *I;
634     if (IsInBundle && !MI.isInsideBundle()) {
635       OS.indent(2) << "}\n";
636       IsInBundle = false;
637     }
638     OS.indent(IsInBundle ? 4 : 2);
639     print(MI);
640     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
641       OS << " {";
642       IsInBundle = true;
643     }
644     OS << "\n";
645   }
646   if (IsInBundle)
647     OS.indent(2) << "}\n";
648 }
649 
650 void MIPrinter::print(const MachineInstr &MI) {
651   const auto *MF = MI.getMF();
652   const auto &MRI = MF->getRegInfo();
653   const auto &SubTarget = MF->getSubtarget();
654   const auto *TRI = SubTarget.getRegisterInfo();
655   assert(TRI && "Expected target register info");
656   const auto *TII = SubTarget.getInstrInfo();
657   assert(TII && "Expected target instruction info");
658   if (MI.isCFIInstruction())
659     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
660 
661   SmallBitVector PrintedTypes(8);
662   bool ShouldPrintRegisterTies = MI.hasComplexRegisterTies();
663   unsigned I = 0, E = MI.getNumOperands();
664   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
665          !MI.getOperand(I).isImplicit();
666        ++I) {
667     if (I)
668       OS << ", ";
669     print(MI, I, TRI, ShouldPrintRegisterTies,
670           MI.getTypeToPrint(I, PrintedTypes, MRI),
671           /*PrintDef=*/false);
672   }
673 
674   if (I)
675     OS << " = ";
676   if (MI.getFlag(MachineInstr::FrameSetup))
677     OS << "frame-setup ";
678   OS << TII->getName(MI.getOpcode());
679   if (I < E)
680     OS << ' ';
681 
682   bool NeedComma = false;
683   for (; I < E; ++I) {
684     if (NeedComma)
685       OS << ", ";
686     print(MI, I, TRI, ShouldPrintRegisterTies,
687           MI.getTypeToPrint(I, PrintedTypes, MRI));
688     NeedComma = true;
689   }
690 
691   if (MI.getDebugLoc()) {
692     if (NeedComma)
693       OS << ',';
694     OS << " debug-location ";
695     MI.getDebugLoc()->printAsOperand(OS, MST);
696   }
697 
698   if (!MI.memoperands_empty()) {
699     OS << " :: ";
700     const LLVMContext &Context = MF->getFunction()->getContext();
701     bool NeedComma = false;
702     for (const auto *Op : MI.memoperands()) {
703       if (NeedComma)
704         OS << ", ";
705       print(Context, *TII, *Op);
706       NeedComma = true;
707     }
708   }
709 }
710 
711 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
712   if (Slot == -1)
713     OS << "<badref>";
714   else
715     OS << Slot;
716 }
717 
718 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
719   OS << "%ir-block.";
720   if (BB.hasName()) {
721     printLLVMNameWithoutPrefix(OS, BB.getName());
722     return;
723   }
724   const Function *F = BB.getParent();
725   int Slot;
726   if (F == MST.getCurrentFunction()) {
727     Slot = MST.getLocalSlot(&BB);
728   } else {
729     ModuleSlotTracker CustomMST(F->getParent(),
730                                 /*ShouldInitializeAllMetadata=*/false);
731     CustomMST.incorporateFunction(*F);
732     Slot = CustomMST.getLocalSlot(&BB);
733   }
734   printIRSlotNumber(OS, Slot);
735 }
736 
737 void MIPrinter::printIRValueReference(const Value &V) {
738   if (isa<GlobalValue>(V)) {
739     V.printAsOperand(OS, /*PrintType=*/false, MST);
740     return;
741   }
742   if (isa<Constant>(V)) {
743     // Machine memory operands can load/store to/from constant value pointers.
744     OS << '`';
745     V.printAsOperand(OS, /*PrintType=*/true, MST);
746     OS << '`';
747     return;
748   }
749   OS << "%ir.";
750   if (V.hasName()) {
751     printLLVMNameWithoutPrefix(OS, V.getName());
752     return;
753   }
754   printIRSlotNumber(OS, MST.getLocalSlot(&V));
755 }
756 
757 void MIPrinter::printStackObjectReference(int FrameIndex) {
758   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
759   assert(ObjectInfo != StackObjectOperandMapping.end() &&
760          "Invalid frame index");
761   const FrameIndexOperand &Operand = ObjectInfo->second;
762   if (Operand.IsFixed) {
763     OS << "%fixed-stack." << Operand.ID;
764     return;
765   }
766   OS << "%stack." << Operand.ID;
767   if (!Operand.Name.empty())
768     OS << '.' << Operand.Name;
769 }
770 
771 void MIPrinter::printOffset(int64_t Offset) {
772   if (Offset == 0)
773     return;
774   if (Offset < 0) {
775     OS << " - " << -Offset;
776     return;
777   }
778   OS << " + " << Offset;
779 }
780 
781 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
782   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
783   for (const auto &I : Flags) {
784     if (I.first == TF) {
785       return I.second;
786     }
787   }
788   return nullptr;
789 }
790 
791 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
792   if (!Op.getTargetFlags())
793     return;
794   const auto *TII = Op.getParent()->getMF()->getSubtarget().getInstrInfo();
795   assert(TII && "expected instruction info");
796   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
797   OS << "target-flags(";
798   const bool HasDirectFlags = Flags.first;
799   const bool HasBitmaskFlags = Flags.second;
800   if (!HasDirectFlags && !HasBitmaskFlags) {
801     OS << "<unknown>) ";
802     return;
803   }
804   if (HasDirectFlags) {
805     if (const auto *Name = getTargetFlagName(TII, Flags.first))
806       OS << Name;
807     else
808       OS << "<unknown target flag>";
809   }
810   if (!HasBitmaskFlags) {
811     OS << ") ";
812     return;
813   }
814   bool IsCommaNeeded = HasDirectFlags;
815   unsigned BitMask = Flags.second;
816   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
817   for (const auto &Mask : BitMasks) {
818     // Check if the flag's bitmask has the bits of the current mask set.
819     if ((BitMask & Mask.first) == Mask.first) {
820       if (IsCommaNeeded)
821         OS << ", ";
822       IsCommaNeeded = true;
823       OS << Mask.second;
824       // Clear the bits which were serialized from the flag's bitmask.
825       BitMask &= ~(Mask.first);
826     }
827   }
828   if (BitMask) {
829     // When the resulting flag's bitmask isn't zero, we know that we didn't
830     // serialize all of the bit flags.
831     if (IsCommaNeeded)
832       OS << ", ";
833     OS << "<unknown bitmask target flag>";
834   }
835   OS << ") ";
836 }
837 
838 void MIPrinter::print(const MachineInstr &MI, unsigned OpIdx,
839                       const TargetRegisterInfo *TRI,
840                       bool ShouldPrintRegisterTies, LLT TypeToPrint,
841                       bool PrintDef) {
842   const MachineOperand &Op = MI.getOperand(OpIdx);
843   printTargetFlags(Op);
844   switch (Op.getType()) {
845   case MachineOperand::MO_Immediate:
846     if (MI.isOperandSubregIdx(OpIdx)) {
847       MachineOperand::printSubregIdx(OS, Op.getImm(), TRI);
848       break;
849     }
850     LLVM_FALLTHROUGH;
851   case MachineOperand::MO_Register:
852   case MachineOperand::MO_CImmediate:
853   case MachineOperand::MO_MachineBasicBlock:
854   case MachineOperand::MO_ConstantPoolIndex:
855   case MachineOperand::MO_TargetIndex:
856   case MachineOperand::MO_JumpTableIndex: {
857     unsigned TiedOperandIdx = 0;
858     if (ShouldPrintRegisterTies && Op.isReg() && Op.isTied() && !Op.isDef())
859       TiedOperandIdx = Op.getParent()->findTiedOperandIdx(OpIdx);
860     const TargetIntrinsicInfo *TII = MI.getMF()->getTarget().getIntrinsicInfo();
861     Op.print(OS, MST, TypeToPrint, PrintDef, ShouldPrintRegisterTies,
862              TiedOperandIdx, TRI, TII);
863     break;
864   }
865   case MachineOperand::MO_FPImmediate:
866     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
867     break;
868   case MachineOperand::MO_FrameIndex:
869     printStackObjectReference(Op.getIndex());
870     break;
871   case MachineOperand::MO_ExternalSymbol: {
872     StringRef Name = Op.getSymbolName();
873     OS << '$';
874     if (Name.empty()) {
875       OS << "\"\"";
876     } else {
877       printLLVMNameWithoutPrefix(OS, Name);
878     }
879     printOffset(Op.getOffset());
880     break;
881   }
882   case MachineOperand::MO_GlobalAddress:
883     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
884     printOffset(Op.getOffset());
885     break;
886   case MachineOperand::MO_BlockAddress:
887     OS << "blockaddress(";
888     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
889                                                         MST);
890     OS << ", ";
891     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
892     OS << ')';
893     printOffset(Op.getOffset());
894     break;
895   case MachineOperand::MO_RegisterMask: {
896     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
897     if (RegMaskInfo != RegisterMaskIds.end())
898       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
899     else
900       printCustomRegMask(Op.getRegMask(), OS, TRI);
901     break;
902   }
903   case MachineOperand::MO_RegisterLiveOut: {
904     const uint32_t *RegMask = Op.getRegLiveOut();
905     OS << "liveout(";
906     bool IsCommaNeeded = false;
907     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
908       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
909         if (IsCommaNeeded)
910           OS << ", ";
911         OS << printReg(Reg, TRI);
912         IsCommaNeeded = true;
913       }
914     }
915     OS << ")";
916     break;
917   }
918   case MachineOperand::MO_Metadata:
919     Op.getMetadata()->printAsOperand(OS, MST);
920     break;
921   case MachineOperand::MO_MCSymbol:
922     OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
923     break;
924   case MachineOperand::MO_CFIIndex: {
925     const MachineFunction &MF = *Op.getParent()->getMF();
926     print(MF.getFrameInstructions()[Op.getCFIIndex()], TRI);
927     break;
928   }
929   case MachineOperand::MO_IntrinsicID: {
930     Intrinsic::ID ID = Op.getIntrinsicID();
931     if (ID < Intrinsic::num_intrinsics)
932       OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
933     else {
934       const MachineFunction &MF = *Op.getParent()->getMF();
935       const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
936       OS << "intrinsic(@" << TII->getName(ID) << ')';
937     }
938     break;
939   }
940   case MachineOperand::MO_Predicate: {
941     auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
942     OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
943        << CmpInst::getPredicateName(Pred) << ')';
944     break;
945   }
946   }
947 }
948 
949 static const char *getTargetMMOFlagName(const TargetInstrInfo &TII,
950                                         unsigned TMMOFlag) {
951   auto Flags = TII.getSerializableMachineMemOperandTargetFlags();
952   for (const auto &I : Flags) {
953     if (I.first == TMMOFlag) {
954       return I.second;
955     }
956   }
957   return nullptr;
958 }
959 
960 void MIPrinter::print(const LLVMContext &Context, const TargetInstrInfo &TII,
961                       const MachineMemOperand &Op) {
962   OS << '(';
963   if (Op.isVolatile())
964     OS << "volatile ";
965   if (Op.isNonTemporal())
966     OS << "non-temporal ";
967   if (Op.isDereferenceable())
968     OS << "dereferenceable ";
969   if (Op.isInvariant())
970     OS << "invariant ";
971   if (Op.getFlags() & MachineMemOperand::MOTargetFlag1)
972     OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag1)
973        << "\" ";
974   if (Op.getFlags() & MachineMemOperand::MOTargetFlag2)
975     OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag2)
976        << "\" ";
977   if (Op.getFlags() & MachineMemOperand::MOTargetFlag3)
978     OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag3)
979        << "\" ";
980 
981   assert((Op.isLoad() || Op.isStore()) && "machine memory operand must be a load or store (or both)");
982   if (Op.isLoad())
983     OS << "load ";
984   if (Op.isStore())
985     OS << "store ";
986 
987   printSyncScope(Context, Op.getSyncScopeID());
988 
989   if (Op.getOrdering() != AtomicOrdering::NotAtomic)
990     OS << toIRString(Op.getOrdering()) << ' ';
991   if (Op.getFailureOrdering() != AtomicOrdering::NotAtomic)
992     OS << toIRString(Op.getFailureOrdering()) << ' ';
993 
994   OS << Op.getSize();
995   if (const Value *Val = Op.getValue()) {
996     OS << ((Op.isLoad() && Op.isStore()) ? " on "
997                                          : Op.isLoad() ? " from " : " into ");
998     printIRValueReference(*Val);
999   } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
1000     OS << ((Op.isLoad() && Op.isStore()) ? " on "
1001                                          : Op.isLoad() ? " from " : " into ");
1002     assert(PVal && "Expected a pseudo source value");
1003     switch (PVal->kind()) {
1004     case PseudoSourceValue::Stack:
1005       OS << "stack";
1006       break;
1007     case PseudoSourceValue::GOT:
1008       OS << "got";
1009       break;
1010     case PseudoSourceValue::JumpTable:
1011       OS << "jump-table";
1012       break;
1013     case PseudoSourceValue::ConstantPool:
1014       OS << "constant-pool";
1015       break;
1016     case PseudoSourceValue::FixedStack:
1017       printStackObjectReference(
1018           cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
1019       break;
1020     case PseudoSourceValue::GlobalValueCallEntry:
1021       OS << "call-entry ";
1022       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
1023           OS, /*PrintType=*/false, MST);
1024       break;
1025     case PseudoSourceValue::ExternalSymbolCallEntry:
1026       OS << "call-entry $";
1027       printLLVMNameWithoutPrefix(
1028           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
1029       break;
1030     case PseudoSourceValue::TargetCustom:
1031       llvm_unreachable("TargetCustom pseudo source values are not supported");
1032       break;
1033     }
1034   }
1035   printOffset(Op.getOffset());
1036   if (Op.getBaseAlignment() != Op.getSize())
1037     OS << ", align " << Op.getBaseAlignment();
1038   auto AAInfo = Op.getAAInfo();
1039   if (AAInfo.TBAA) {
1040     OS << ", !tbaa ";
1041     AAInfo.TBAA->printAsOperand(OS, MST);
1042   }
1043   if (AAInfo.Scope) {
1044     OS << ", !alias.scope ";
1045     AAInfo.Scope->printAsOperand(OS, MST);
1046   }
1047   if (AAInfo.NoAlias) {
1048     OS << ", !noalias ";
1049     AAInfo.NoAlias->printAsOperand(OS, MST);
1050   }
1051   if (Op.getRanges()) {
1052     OS << ", !range ";
1053     Op.getRanges()->printAsOperand(OS, MST);
1054   }
1055   OS << ')';
1056 }
1057 
1058 void MIPrinter::printSyncScope(const LLVMContext &Context, SyncScope::ID SSID) {
1059   switch (SSID) {
1060   case SyncScope::System: {
1061     break;
1062   }
1063   default: {
1064     if (SSNs.empty())
1065       Context.getSyncScopeNames(SSNs);
1066 
1067     OS << "syncscope(\"";
1068     PrintEscapedString(SSNs[SSID], OS);
1069     OS << "\") ";
1070     break;
1071   }
1072   }
1073 }
1074 
1075 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
1076                              const TargetRegisterInfo *TRI) {
1077   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
1078   if (Reg == -1) {
1079     OS << "<badreg>";
1080     return;
1081   }
1082   OS << printReg(Reg, TRI);
1083 }
1084 
1085 void MIPrinter::print(const MCCFIInstruction &CFI,
1086                       const TargetRegisterInfo *TRI) {
1087   switch (CFI.getOperation()) {
1088   case MCCFIInstruction::OpSameValue:
1089     OS << "same_value ";
1090     if (CFI.getLabel())
1091       OS << "<mcsymbol> ";
1092     printCFIRegister(CFI.getRegister(), OS, TRI);
1093     break;
1094   case MCCFIInstruction::OpOffset:
1095     OS << "offset ";
1096     if (CFI.getLabel())
1097       OS << "<mcsymbol> ";
1098     printCFIRegister(CFI.getRegister(), OS, TRI);
1099     OS << ", " << CFI.getOffset();
1100     break;
1101   case MCCFIInstruction::OpDefCfaRegister:
1102     OS << "def_cfa_register ";
1103     if (CFI.getLabel())
1104       OS << "<mcsymbol> ";
1105     printCFIRegister(CFI.getRegister(), OS, TRI);
1106     break;
1107   case MCCFIInstruction::OpDefCfaOffset:
1108     OS << "def_cfa_offset ";
1109     if (CFI.getLabel())
1110       OS << "<mcsymbol> ";
1111     OS << CFI.getOffset();
1112     break;
1113   case MCCFIInstruction::OpDefCfa:
1114     OS << "def_cfa ";
1115     if (CFI.getLabel())
1116       OS << "<mcsymbol> ";
1117     printCFIRegister(CFI.getRegister(), OS, TRI);
1118     OS << ", " << CFI.getOffset();
1119     break;
1120   case MCCFIInstruction::OpRestore:
1121     OS << "restore ";
1122     if (CFI.getLabel())
1123       OS << "<mcsymbol> ";
1124     printCFIRegister(CFI.getRegister(), OS, TRI);
1125     break;
1126   default:
1127     // TODO: Print the other CFI Operations.
1128     OS << "<unserializable cfi operation>";
1129     break;
1130   }
1131 }
1132 
1133 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1134   yaml::Output Out(OS);
1135   Out << const_cast<Module &>(M);
1136 }
1137 
1138 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1139   MIRPrinter Printer(OS);
1140   Printer.print(MF);
1141 }
1142