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