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