1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the class that prints out the LLVM IR and machine
10 // functions using the MIR serialization format.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/MIRPrinter.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallBitVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
24 #include "llvm/CodeGen/MIRYamlMapping.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/TargetInstrInfo.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/CodeGen/TargetFrameLowering.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/MCContext.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 static cl::opt<bool> PrintLocations("mir-debug-loc", cl::Hidden, cl::init(true),
83                                     cl::desc("Print MIR debug-locations"));
84 
85 namespace {
86 
87 /// This structure describes how to print out stack object references.
88 struct FrameIndexOperand {
89   std::string Name;
90   unsigned ID;
91   bool IsFixed;
92 
93   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
94       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
95 
96   /// Return an ordinary stack object reference.
97   static FrameIndexOperand create(StringRef Name, unsigned ID) {
98     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
99   }
100 
101   /// Return a fixed stack object reference.
102   static FrameIndexOperand createFixed(unsigned ID) {
103     return FrameIndexOperand("", ID, /*IsFixed=*/true);
104   }
105 };
106 
107 } // end anonymous namespace
108 
109 namespace llvm {
110 
111 /// This class prints out the machine functions using the MIR serialization
112 /// format.
113 class MIRPrinter {
114   raw_ostream &OS;
115   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
116   /// Maps from stack object indices to operand indices which will be used when
117   /// printing frame index machine operands.
118   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
119 
120 public:
121   MIRPrinter(raw_ostream &OS) : OS(OS) {}
122 
123   void print(const MachineFunction &MF);
124 
125   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
126                const TargetRegisterInfo *TRI);
127   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
128                const MachineFrameInfo &MFI);
129   void convert(yaml::MachineFunction &MF,
130                const MachineConstantPool &ConstantPool);
131   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
132                const MachineJumpTableInfo &JTI);
133   void convertStackObjects(yaml::MachineFunction &YMF,
134                            const MachineFunction &MF, ModuleSlotTracker &MST);
135   void convertCallSiteObjects(yaml::MachineFunction &YMF,
136                               const MachineFunction &MF,
137                               ModuleSlotTracker &MST);
138 
139 private:
140   void initRegisterMaskIds(const MachineFunction &MF);
141 };
142 
143 /// This class prints out the machine instructions using the MIR serialization
144 /// format.
145 class MIPrinter {
146   raw_ostream &OS;
147   ModuleSlotTracker &MST;
148   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
149   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
150   /// Synchronization scope names registered with LLVMContext.
151   SmallVector<StringRef, 8> SSNs;
152 
153   bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
154   bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
155 
156 public:
157   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
158             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
159             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
160       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
161         StackObjectOperandMapping(StackObjectOperandMapping) {}
162 
163   void print(const MachineBasicBlock &MBB);
164 
165   void print(const MachineInstr &MI);
166   void printStackObjectReference(int FrameIndex);
167   void print(const MachineInstr &MI, unsigned OpIdx,
168              const TargetRegisterInfo *TRI, const TargetInstrInfo *TII,
169              bool ShouldPrintRegisterTies, LLT TypeToPrint,
170              bool PrintDef = true);
171 };
172 
173 } // end namespace llvm
174 
175 namespace llvm {
176 namespace yaml {
177 
178 /// This struct serializes the LLVM IR module.
179 template <> struct BlockScalarTraits<Module> {
180   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
181     Mod.print(OS, nullptr);
182   }
183 
184   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
185     llvm_unreachable("LLVM Module is supposed to be parsed separately");
186     return "";
187   }
188 };
189 
190 } // end namespace yaml
191 } // end namespace llvm
192 
193 static void printRegMIR(unsigned Reg, yaml::StringValue &Dest,
194                         const TargetRegisterInfo *TRI) {
195   raw_string_ostream OS(Dest.Value);
196   OS << printReg(Reg, TRI);
197 }
198 
199 void MIRPrinter::print(const MachineFunction &MF) {
200   initRegisterMaskIds(MF);
201 
202   yaml::MachineFunction YamlMF;
203   YamlMF.Name = MF.getName();
204   YamlMF.Alignment = MF.getAlignment();
205   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
206   YamlMF.HasWinCFI = MF.hasWinCFI();
207 
208   YamlMF.Legalized = MF.getProperties().hasProperty(
209       MachineFunctionProperties::Property::Legalized);
210   YamlMF.RegBankSelected = MF.getProperties().hasProperty(
211       MachineFunctionProperties::Property::RegBankSelected);
212   YamlMF.Selected = MF.getProperties().hasProperty(
213       MachineFunctionProperties::Property::Selected);
214   YamlMF.FailedISel = MF.getProperties().hasProperty(
215       MachineFunctionProperties::Property::FailedISel);
216 
217   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
218   ModuleSlotTracker MST(MF.getFunction().getParent());
219   MST.incorporateFunction(MF.getFunction());
220   convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
221   convertStackObjects(YamlMF, MF, MST);
222   convertCallSiteObjects(YamlMF, MF, MST);
223   if (const auto *ConstantPool = MF.getConstantPool())
224     convert(YamlMF, *ConstantPool);
225   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
226     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
227 
228   const TargetMachine &TM = MF.getTarget();
229   YamlMF.MachineFuncInfo =
230       std::unique_ptr<yaml::MachineFunctionInfo>(TM.convertFuncInfoToYAML(MF));
231 
232   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
233   bool IsNewlineNeeded = false;
234   for (const auto &MBB : MF) {
235     if (IsNewlineNeeded)
236       StrOS << "\n";
237     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
238         .print(MBB);
239     IsNewlineNeeded = true;
240   }
241   StrOS.flush();
242   yaml::Output Out(OS);
243   if (!SimplifyMIR)
244       Out.setWriteDefaultValues(true);
245   Out << YamlMF;
246 }
247 
248 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
249                                const TargetRegisterInfo *TRI) {
250   assert(RegMask && "Can't print an empty register mask");
251   OS << StringRef("CustomRegMask(");
252 
253   bool IsRegInRegMaskFound = false;
254   for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
255     // Check whether the register is asserted in regmask.
256     if (RegMask[I / 32] & (1u << (I % 32))) {
257       if (IsRegInRegMaskFound)
258         OS << ',';
259       OS << printReg(I, TRI);
260       IsRegInRegMaskFound = true;
261     }
262   }
263 
264   OS << ')';
265 }
266 
267 static void printRegClassOrBank(unsigned Reg, yaml::StringValue &Dest,
268                                 const MachineRegisterInfo &RegInfo,
269                                 const TargetRegisterInfo *TRI) {
270   raw_string_ostream OS(Dest.Value);
271   OS << printRegClassOrBank(Reg, RegInfo, TRI);
272 }
273 
274 template <typename T>
275 static void
276 printStackObjectDbgInfo(const MachineFunction::VariableDbgInfo &DebugVar,
277                         T &Object, ModuleSlotTracker &MST) {
278   std::array<std::string *, 3> Outputs{{&Object.DebugVar.Value,
279                                         &Object.DebugExpr.Value,
280                                         &Object.DebugLoc.Value}};
281   std::array<const Metadata *, 3> Metas{{DebugVar.Var,
282                                         DebugVar.Expr,
283                                         DebugVar.Loc}};
284   for (unsigned i = 0; i < 3; ++i) {
285     raw_string_ostream StrOS(*Outputs[i]);
286     Metas[i]->printAsOperand(StrOS, MST);
287   }
288 }
289 
290 void MIRPrinter::convert(yaml::MachineFunction &MF,
291                          const MachineRegisterInfo &RegInfo,
292                          const TargetRegisterInfo *TRI) {
293   MF.TracksRegLiveness = RegInfo.tracksLiveness();
294 
295   // Print the virtual register definitions.
296   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
297     unsigned Reg = Register::index2VirtReg(I);
298     yaml::VirtualRegisterDefinition VReg;
299     VReg.ID = I;
300     if (RegInfo.getVRegName(Reg) != "")
301       continue;
302     ::printRegClassOrBank(Reg, VReg.Class, RegInfo, TRI);
303     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
304     if (PreferredReg)
305       printRegMIR(PreferredReg, VReg.PreferredRegister, TRI);
306     MF.VirtualRegisters.push_back(VReg);
307   }
308 
309   // Print the live ins.
310   for (std::pair<unsigned, unsigned> LI : RegInfo.liveins()) {
311     yaml::MachineFunctionLiveIn LiveIn;
312     printRegMIR(LI.first, LiveIn.Register, TRI);
313     if (LI.second)
314       printRegMIR(LI.second, LiveIn.VirtualRegister, TRI);
315     MF.LiveIns.push_back(LiveIn);
316   }
317 
318   // Prints the callee saved registers.
319   if (RegInfo.isUpdatedCSRsInitialized()) {
320     const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
321     std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
322     for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
323       yaml::FlowStringValue Reg;
324       printRegMIR(*I, Reg, TRI);
325       CalleeSavedRegisters.push_back(Reg);
326     }
327     MF.CalleeSavedRegisters = CalleeSavedRegisters;
328   }
329 }
330 
331 void MIRPrinter::convert(ModuleSlotTracker &MST,
332                          yaml::MachineFrameInfo &YamlMFI,
333                          const MachineFrameInfo &MFI) {
334   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
335   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
336   YamlMFI.HasStackMap = MFI.hasStackMap();
337   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
338   YamlMFI.StackSize = MFI.getStackSize();
339   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
340   YamlMFI.MaxAlignment = MFI.getMaxAlign().value();
341   YamlMFI.AdjustsStack = MFI.adjustsStack();
342   YamlMFI.HasCalls = MFI.hasCalls();
343   YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
344     ? MFI.getMaxCallFrameSize() : ~0u;
345   YamlMFI.CVBytesOfCalleeSavedRegisters =
346       MFI.getCVBytesOfCalleeSavedRegisters();
347   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
348   YamlMFI.HasVAStart = MFI.hasVAStart();
349   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
350   YamlMFI.LocalFrameSize = MFI.getLocalFrameSize();
351   if (MFI.getSavePoint()) {
352     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
353     StrOS << printMBBReference(*MFI.getSavePoint());
354   }
355   if (MFI.getRestorePoint()) {
356     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
357     StrOS << printMBBReference(*MFI.getRestorePoint());
358   }
359 }
360 
361 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
362                                      const MachineFunction &MF,
363                                      ModuleSlotTracker &MST) {
364   const MachineFrameInfo &MFI = MF.getFrameInfo();
365   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
366   // Process fixed stack objects.
367   unsigned ID = 0;
368   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
369     if (MFI.isDeadObjectIndex(I))
370       continue;
371 
372     yaml::FixedMachineStackObject YamlObject;
373     YamlObject.ID = ID;
374     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
375                           ? yaml::FixedMachineStackObject::SpillSlot
376                           : yaml::FixedMachineStackObject::DefaultType;
377     YamlObject.Offset = MFI.getObjectOffset(I);
378     YamlObject.Size = MFI.getObjectSize(I);
379     YamlObject.Alignment = MFI.getObjectAlign(I);
380     YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
381     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
382     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
383     YMF.FixedStackObjects.push_back(YamlObject);
384     StackObjectOperandMapping.insert(
385         std::make_pair(I, FrameIndexOperand::createFixed(ID)));
386     ++ID;
387     assert(YMF.FixedStackObjects.size() == ID);
388   }
389 
390   // Process ordinary stack objects.
391   ID = 0;
392   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
393     if (MFI.isDeadObjectIndex(I))
394       continue;
395 
396     yaml::MachineStackObject YamlObject;
397     YamlObject.ID = ID;
398     if (const auto *Alloca = MFI.getObjectAllocation(I))
399       YamlObject.Name.Value = std::string(
400           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>");
401     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
402                           ? yaml::MachineStackObject::SpillSlot
403                           : MFI.isVariableSizedObjectIndex(I)
404                                 ? yaml::MachineStackObject::VariableSized
405                                 : yaml::MachineStackObject::DefaultType;
406     YamlObject.Offset = MFI.getObjectOffset(I);
407     YamlObject.Size = MFI.getObjectSize(I);
408     YamlObject.Alignment = MFI.getObjectAlign(I);
409     YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
410 
411     YMF.StackObjects.push_back(YamlObject);
412     StackObjectOperandMapping.insert(std::make_pair(
413         I, FrameIndexOperand::create(YamlObject.Name.Value, ID)));
414     ++ID;
415     assert(YMF.StackObjects.size() == ID);
416   }
417 
418   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
419     if (!CSInfo.isSpilledToReg() && MFI.isDeadObjectIndex(CSInfo.getFrameIdx()))
420       continue;
421 
422     yaml::StringValue Reg;
423     printRegMIR(CSInfo.getReg(), Reg, TRI);
424     if (!CSInfo.isSpilledToReg()) {
425       auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
426       assert(StackObjectInfo != StackObjectOperandMapping.end() &&
427              "Invalid stack object index");
428       const FrameIndexOperand &StackObject = StackObjectInfo->second;
429       if (StackObject.IsFixed) {
430         YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
431         YMF.FixedStackObjects[StackObject.ID].CalleeSavedRestored =
432           CSInfo.isRestored();
433       } else {
434         YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
435         YMF.StackObjects[StackObject.ID].CalleeSavedRestored =
436           CSInfo.isRestored();
437       }
438     }
439   }
440   for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
441     auto LocalObject = MFI.getLocalFrameObjectMap(I);
442     auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
443     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
444            "Invalid stack object index");
445     const FrameIndexOperand &StackObject = StackObjectInfo->second;
446     assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
447     YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
448   }
449 
450   // Print the stack object references in the frame information class after
451   // converting the stack objects.
452   if (MFI.hasStackProtectorIndex()) {
453     raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
454     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
455         .printStackObjectReference(MFI.getStackProtectorIndex());
456   }
457 
458   // Print the debug variable information.
459   for (const MachineFunction::VariableDbgInfo &DebugVar :
460        MF.getVariableDbgInfo()) {
461     auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
462     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
463            "Invalid stack object index");
464     const FrameIndexOperand &StackObject = StackObjectInfo->second;
465     if (StackObject.IsFixed) {
466       auto &Object = YMF.FixedStackObjects[StackObject.ID];
467       printStackObjectDbgInfo(DebugVar, Object, MST);
468     } else {
469       auto &Object = YMF.StackObjects[StackObject.ID];
470       printStackObjectDbgInfo(DebugVar, Object, MST);
471     }
472   }
473 }
474 
475 void MIRPrinter::convertCallSiteObjects(yaml::MachineFunction &YMF,
476                                         const MachineFunction &MF,
477                                         ModuleSlotTracker &MST) {
478   const auto *TRI = MF.getSubtarget().getRegisterInfo();
479   for (auto CSInfo : MF.getCallSitesInfo()) {
480     yaml::CallSiteInfo YmlCS;
481     yaml::CallSiteInfo::MachineInstrLoc CallLocation;
482 
483     // Prepare instruction position.
484     MachineBasicBlock::const_instr_iterator CallI = CSInfo.first->getIterator();
485     CallLocation.BlockNum = CallI->getParent()->getNumber();
486     // Get call instruction offset from the beginning of block.
487     CallLocation.Offset =
488         std::distance(CallI->getParent()->instr_begin(), CallI);
489     YmlCS.CallLocation = CallLocation;
490     // Construct call arguments and theirs forwarding register info.
491     for (auto ArgReg : CSInfo.second) {
492       yaml::CallSiteInfo::ArgRegPair YmlArgReg;
493       YmlArgReg.ArgNo = ArgReg.ArgNo;
494       printRegMIR(ArgReg.Reg, YmlArgReg.Reg, TRI);
495       YmlCS.ArgForwardingRegs.emplace_back(YmlArgReg);
496     }
497     YMF.CallSitesInfo.push_back(YmlCS);
498   }
499 
500   // Sort call info by position of call instructions.
501   llvm::sort(YMF.CallSitesInfo.begin(), YMF.CallSitesInfo.end(),
502              [](yaml::CallSiteInfo A, yaml::CallSiteInfo B) {
503                if (A.CallLocation.BlockNum == B.CallLocation.BlockNum)
504                  return A.CallLocation.Offset < B.CallLocation.Offset;
505                return A.CallLocation.BlockNum < B.CallLocation.BlockNum;
506              });
507 }
508 
509 void MIRPrinter::convert(yaml::MachineFunction &MF,
510                          const MachineConstantPool &ConstantPool) {
511   unsigned ID = 0;
512   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
513     std::string Str;
514     raw_string_ostream StrOS(Str);
515     if (Constant.isMachineConstantPoolEntry()) {
516       Constant.Val.MachineCPVal->print(StrOS);
517     } else {
518       Constant.Val.ConstVal->printAsOperand(StrOS);
519     }
520 
521     yaml::MachineConstantPoolValue YamlConstant;
522     YamlConstant.ID = ID++;
523     YamlConstant.Value = StrOS.str();
524     YamlConstant.Alignment = MaybeAlign(Constant.getAlignment());
525     YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry();
526 
527     MF.Constants.push_back(YamlConstant);
528   }
529 }
530 
531 void MIRPrinter::convert(ModuleSlotTracker &MST,
532                          yaml::MachineJumpTable &YamlJTI,
533                          const MachineJumpTableInfo &JTI) {
534   YamlJTI.Kind = JTI.getEntryKind();
535   unsigned ID = 0;
536   for (const auto &Table : JTI.getJumpTables()) {
537     std::string Str;
538     yaml::MachineJumpTable::Entry Entry;
539     Entry.ID = ID++;
540     for (const auto *MBB : Table.MBBs) {
541       raw_string_ostream StrOS(Str);
542       StrOS << printMBBReference(*MBB);
543       Entry.Blocks.push_back(StrOS.str());
544       Str.clear();
545     }
546     YamlJTI.Entries.push_back(Entry);
547   }
548 }
549 
550 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
551   const auto *TRI = MF.getSubtarget().getRegisterInfo();
552   unsigned I = 0;
553   for (const uint32_t *Mask : TRI->getRegMasks())
554     RegisterMaskIds.insert(std::make_pair(Mask, I++));
555 }
556 
557 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
558                            SmallVectorImpl<MachineBasicBlock*> &Result,
559                            bool &IsFallthrough) {
560   SmallPtrSet<MachineBasicBlock*,8> Seen;
561 
562   for (const MachineInstr &MI : MBB) {
563     if (MI.isPHI())
564       continue;
565     for (const MachineOperand &MO : MI.operands()) {
566       if (!MO.isMBB())
567         continue;
568       MachineBasicBlock *Succ = MO.getMBB();
569       auto RP = Seen.insert(Succ);
570       if (RP.second)
571         Result.push_back(Succ);
572     }
573   }
574   MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
575   IsFallthrough = I == MBB.end() || !I->isBarrier();
576 }
577 
578 bool
579 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
580   if (MBB.succ_size() <= 1)
581     return true;
582   if (!MBB.hasSuccessorProbabilities())
583     return true;
584 
585   SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
586                                               MBB.Probs.end());
587   BranchProbability::normalizeProbabilities(Normalized.begin(),
588                                             Normalized.end());
589   SmallVector<BranchProbability,8> Equal(Normalized.size());
590   BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
591 
592   return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
593 }
594 
595 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
596   SmallVector<MachineBasicBlock*,8> GuessedSuccs;
597   bool GuessedFallthrough;
598   guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
599   if (GuessedFallthrough) {
600     const MachineFunction &MF = *MBB.getParent();
601     MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
602     if (NextI != MF.end()) {
603       MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
604       if (!is_contained(GuessedSuccs, Next))
605         GuessedSuccs.push_back(Next);
606     }
607   }
608   if (GuessedSuccs.size() != MBB.succ_size())
609     return false;
610   return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
611 }
612 
613 void MIPrinter::print(const MachineBasicBlock &MBB) {
614   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
615   OS << "bb." << MBB.getNumber();
616   bool HasAttributes = false;
617   if (const auto *BB = MBB.getBasicBlock()) {
618     if (BB->hasName()) {
619       OS << "." << BB->getName();
620     } else {
621       HasAttributes = true;
622       OS << " (";
623       int Slot = MST.getLocalSlot(BB);
624       if (Slot == -1)
625         OS << "<ir-block badref>";
626       else
627         OS << (Twine("%ir-block.") + Twine(Slot)).str();
628     }
629   }
630   if (MBB.hasAddressTaken()) {
631     OS << (HasAttributes ? ", " : " (");
632     OS << "address-taken";
633     HasAttributes = true;
634   }
635   if (MBB.isEHPad()) {
636     OS << (HasAttributes ? ", " : " (");
637     OS << "landing-pad";
638     HasAttributes = true;
639   }
640   if (MBB.isEHFuncletEntry()) {
641     OS << (HasAttributes ? ", " : " (");
642     OS << "ehfunclet-entry";
643     HasAttributes = true;
644   }
645   if (MBB.getAlignment() != Align(1)) {
646     OS << (HasAttributes ? ", " : " (");
647     OS << "align " << MBB.getAlignment().value();
648     HasAttributes = true;
649   }
650   if (MBB.getSectionID() != MBBSectionID(0)) {
651     OS << (HasAttributes ? ", " : " (");
652     OS << "bbsections ";
653     switch (MBB.getSectionID().Type) {
654     case MBBSectionID::SectionType::Exception:
655       OS << "Exception";
656       break;
657     case MBBSectionID::SectionType::Cold:
658       OS << "Cold";
659       break;
660     default:
661       OS << MBB.getSectionID().Number;
662     }
663     HasAttributes = true;
664   }
665   if (HasAttributes)
666     OS << ")";
667   OS << ":\n";
668 
669   bool HasLineAttributes = false;
670   // Print the successors
671   bool canPredictProbs = canPredictBranchProbabilities(MBB);
672   // Even if the list of successors is empty, if we cannot guess it,
673   // we need to print it to tell the parser that the list is empty.
674   // This is needed, because MI model unreachable as empty blocks
675   // with an empty successor list. If the parser would see that
676   // without the successor list, it would guess the code would
677   // fallthrough.
678   if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs ||
679       !canPredictSuccessors(MBB)) {
680     OS.indent(2) << "successors: ";
681     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
682       if (I != MBB.succ_begin())
683         OS << ", ";
684       OS << printMBBReference(**I);
685       if (!SimplifyMIR || !canPredictProbs)
686         OS << '('
687            << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
688            << ')';
689     }
690     OS << "\n";
691     HasLineAttributes = true;
692   }
693 
694   // Print the live in registers.
695   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
696   if (MRI.tracksLiveness() && !MBB.livein_empty()) {
697     const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
698     OS.indent(2) << "liveins: ";
699     bool First = true;
700     for (const auto &LI : MBB.liveins()) {
701       if (!First)
702         OS << ", ";
703       First = false;
704       OS << printReg(LI.PhysReg, &TRI);
705       if (!LI.LaneMask.all())
706         OS << ":0x" << PrintLaneMask(LI.LaneMask);
707     }
708     OS << "\n";
709     HasLineAttributes = true;
710   }
711 
712   if (HasLineAttributes)
713     OS << "\n";
714   bool IsInBundle = false;
715   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
716     const MachineInstr &MI = *I;
717     if (IsInBundle && !MI.isInsideBundle()) {
718       OS.indent(2) << "}\n";
719       IsInBundle = false;
720     }
721     OS.indent(IsInBundle ? 4 : 2);
722     print(MI);
723     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
724       OS << " {";
725       IsInBundle = true;
726     }
727     OS << "\n";
728   }
729   if (IsInBundle)
730     OS.indent(2) << "}\n";
731 }
732 
733 void MIPrinter::print(const MachineInstr &MI) {
734   const auto *MF = MI.getMF();
735   const auto &MRI = MF->getRegInfo();
736   const auto &SubTarget = MF->getSubtarget();
737   const auto *TRI = SubTarget.getRegisterInfo();
738   assert(TRI && "Expected target register info");
739   const auto *TII = SubTarget.getInstrInfo();
740   assert(TII && "Expected target instruction info");
741   if (MI.isCFIInstruction())
742     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
743 
744   SmallBitVector PrintedTypes(8);
745   bool ShouldPrintRegisterTies = MI.hasComplexRegisterTies();
746   unsigned I = 0, E = MI.getNumOperands();
747   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
748          !MI.getOperand(I).isImplicit();
749        ++I) {
750     if (I)
751       OS << ", ";
752     print(MI, I, TRI, TII, ShouldPrintRegisterTies,
753           MI.getTypeToPrint(I, PrintedTypes, MRI),
754           /*PrintDef=*/false);
755   }
756 
757   if (I)
758     OS << " = ";
759   if (MI.getFlag(MachineInstr::FrameSetup))
760     OS << "frame-setup ";
761   if (MI.getFlag(MachineInstr::FrameDestroy))
762     OS << "frame-destroy ";
763   if (MI.getFlag(MachineInstr::FmNoNans))
764     OS << "nnan ";
765   if (MI.getFlag(MachineInstr::FmNoInfs))
766     OS << "ninf ";
767   if (MI.getFlag(MachineInstr::FmNsz))
768     OS << "nsz ";
769   if (MI.getFlag(MachineInstr::FmArcp))
770     OS << "arcp ";
771   if (MI.getFlag(MachineInstr::FmContract))
772     OS << "contract ";
773   if (MI.getFlag(MachineInstr::FmAfn))
774     OS << "afn ";
775   if (MI.getFlag(MachineInstr::FmReassoc))
776     OS << "reassoc ";
777   if (MI.getFlag(MachineInstr::NoUWrap))
778     OS << "nuw ";
779   if (MI.getFlag(MachineInstr::NoSWrap))
780     OS << "nsw ";
781   if (MI.getFlag(MachineInstr::IsExact))
782     OS << "exact ";
783   if (MI.getFlag(MachineInstr::NoFPExcept))
784     OS << "nofpexcept ";
785 
786   OS << TII->getName(MI.getOpcode());
787   if (I < E)
788     OS << ' ';
789 
790   bool NeedComma = false;
791   for (; I < E; ++I) {
792     if (NeedComma)
793       OS << ", ";
794     print(MI, I, TRI, TII, ShouldPrintRegisterTies,
795           MI.getTypeToPrint(I, PrintedTypes, MRI));
796     NeedComma = true;
797   }
798 
799   // Print any optional symbols attached to this instruction as-if they were
800   // operands.
801   if (MCSymbol *PreInstrSymbol = MI.getPreInstrSymbol()) {
802     if (NeedComma)
803       OS << ',';
804     OS << " pre-instr-symbol ";
805     MachineOperand::printSymbol(OS, *PreInstrSymbol);
806     NeedComma = true;
807   }
808   if (MCSymbol *PostInstrSymbol = MI.getPostInstrSymbol()) {
809     if (NeedComma)
810       OS << ',';
811     OS << " post-instr-symbol ";
812     MachineOperand::printSymbol(OS, *PostInstrSymbol);
813     NeedComma = true;
814   }
815   if (MDNode *HeapAllocMarker = MI.getHeapAllocMarker()) {
816     if (NeedComma)
817       OS << ',';
818     OS << " heap-alloc-marker ";
819     HeapAllocMarker->printAsOperand(OS, MST);
820     NeedComma = true;
821   }
822 
823   if (PrintLocations) {
824     if (const DebugLoc &DL = MI.getDebugLoc()) {
825       if (NeedComma)
826         OS << ',';
827       OS << " debug-location ";
828       DL->printAsOperand(OS, MST);
829     }
830   }
831 
832   if (!MI.memoperands_empty()) {
833     OS << " :: ";
834     const LLVMContext &Context = MF->getFunction().getContext();
835     const MachineFrameInfo &MFI = MF->getFrameInfo();
836     bool NeedComma = false;
837     for (const auto *Op : MI.memoperands()) {
838       if (NeedComma)
839         OS << ", ";
840       Op->print(OS, MST, SSNs, Context, &MFI, TII);
841       NeedComma = true;
842     }
843   }
844 }
845 
846 void MIPrinter::printStackObjectReference(int FrameIndex) {
847   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
848   assert(ObjectInfo != StackObjectOperandMapping.end() &&
849          "Invalid frame index");
850   const FrameIndexOperand &Operand = ObjectInfo->second;
851   MachineOperand::printStackObjectReference(OS, Operand.ID, Operand.IsFixed,
852                                             Operand.Name);
853 }
854 
855 static std::string formatOperandComment(std::string Comment) {
856   if (Comment.empty())
857     return Comment;
858   return std::string(" /* " + Comment + " */");
859 }
860 
861 void MIPrinter::print(const MachineInstr &MI, unsigned OpIdx,
862                       const TargetRegisterInfo *TRI,
863                       const TargetInstrInfo *TII,
864                       bool ShouldPrintRegisterTies, LLT TypeToPrint,
865                       bool PrintDef) {
866   const MachineOperand &Op = MI.getOperand(OpIdx);
867   std::string MOComment = TII->createMIROperandComment(MI, Op, OpIdx, TRI);
868 
869   switch (Op.getType()) {
870   case MachineOperand::MO_Immediate:
871     if (MI.isOperandSubregIdx(OpIdx)) {
872       MachineOperand::printTargetFlags(OS, Op);
873       MachineOperand::printSubRegIdx(OS, Op.getImm(), TRI);
874       break;
875     }
876     LLVM_FALLTHROUGH;
877   case MachineOperand::MO_Register:
878   case MachineOperand::MO_CImmediate:
879   case MachineOperand::MO_FPImmediate:
880   case MachineOperand::MO_MachineBasicBlock:
881   case MachineOperand::MO_ConstantPoolIndex:
882   case MachineOperand::MO_TargetIndex:
883   case MachineOperand::MO_JumpTableIndex:
884   case MachineOperand::MO_ExternalSymbol:
885   case MachineOperand::MO_GlobalAddress:
886   case MachineOperand::MO_RegisterLiveOut:
887   case MachineOperand::MO_Metadata:
888   case MachineOperand::MO_MCSymbol:
889   case MachineOperand::MO_CFIIndex:
890   case MachineOperand::MO_IntrinsicID:
891   case MachineOperand::MO_Predicate:
892   case MachineOperand::MO_BlockAddress:
893   case MachineOperand::MO_ShuffleMask: {
894     unsigned TiedOperandIdx = 0;
895     if (ShouldPrintRegisterTies && Op.isReg() && Op.isTied() && !Op.isDef())
896       TiedOperandIdx = Op.getParent()->findTiedOperandIdx(OpIdx);
897     const TargetIntrinsicInfo *TII = MI.getMF()->getTarget().getIntrinsicInfo();
898     Op.print(OS, MST, TypeToPrint, OpIdx, PrintDef, /*IsStandalone=*/false,
899              ShouldPrintRegisterTies, TiedOperandIdx, TRI, TII);
900       OS << formatOperandComment(MOComment);
901     break;
902   }
903   case MachineOperand::MO_FrameIndex:
904     printStackObjectReference(Op.getIndex());
905     break;
906   case MachineOperand::MO_RegisterMask: {
907     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
908     if (RegMaskInfo != RegisterMaskIds.end())
909       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
910     else
911       printCustomRegMask(Op.getRegMask(), OS, TRI);
912     break;
913   }
914   }
915 }
916 
917 void MIRFormatter::printIRValue(raw_ostream &OS, const Value &V,
918                                 ModuleSlotTracker &MST) {
919   if (isa<GlobalValue>(V)) {
920     V.printAsOperand(OS, /*PrintType=*/false, MST);
921     return;
922   }
923   if (isa<Constant>(V)) {
924     // Machine memory operands can load/store to/from constant value pointers.
925     OS << '`';
926     V.printAsOperand(OS, /*PrintType=*/true, MST);
927     OS << '`';
928     return;
929   }
930   OS << "%ir.";
931   if (V.hasName()) {
932     printLLVMNameWithoutPrefix(OS, V.getName());
933     return;
934   }
935   int Slot = MST.getCurrentFunction() ? MST.getLocalSlot(&V) : -1;
936   MachineOperand::printIRSlotNumber(OS, Slot);
937 }
938 
939 void llvm::printMIR(raw_ostream &OS, const Module &M) {
940   yaml::Output Out(OS);
941   Out << const_cast<Module &>(M);
942 }
943 
944 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
945   MIRPrinter Printer(OS);
946   Printer.print(MF);
947 }
948