1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the class that prints out the LLVM IR and machine
11 // functions using the MIR serialization format.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "MIRPrinter.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
18 #include "llvm/CodeGen/MIRYamlMapping.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineMemOperand.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ModuleSlotTracker.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/YAMLTraits.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
38 
39 using namespace llvm;
40 
41 namespace {
42 
43 /// This structure describes how to print out stack object references.
44 struct FrameIndexOperand {
45   std::string Name;
46   unsigned ID;
47   bool IsFixed;
48 
49   FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
50       : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
51 
52   /// Return an ordinary stack object reference.
53   static FrameIndexOperand create(StringRef Name, unsigned ID) {
54     return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
55   }
56 
57   /// Return a fixed stack object reference.
58   static FrameIndexOperand createFixed(unsigned ID) {
59     return FrameIndexOperand("", ID, /*IsFixed=*/true);
60   }
61 };
62 
63 } // end anonymous namespace
64 
65 namespace llvm {
66 
67 /// This class prints out the machine functions using the MIR serialization
68 /// format.
69 class MIRPrinter {
70   raw_ostream &OS;
71   DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
72   /// Maps from stack object indices to operand indices which will be used when
73   /// printing frame index machine operands.
74   DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
75 
76 public:
77   MIRPrinter(raw_ostream &OS) : OS(OS) {}
78 
79   void print(const MachineFunction &MF);
80 
81   void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
82                const TargetRegisterInfo *TRI);
83   void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
84                const MachineFrameInfo &MFI);
85   void convert(yaml::MachineFunction &MF,
86                const MachineConstantPool &ConstantPool);
87   void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
88                const MachineJumpTableInfo &JTI);
89   void convertStackObjects(yaml::MachineFunction &MF,
90                            const MachineFrameInfo &MFI, MachineModuleInfo &MMI,
91                            ModuleSlotTracker &MST,
92                            const TargetRegisterInfo *TRI);
93 
94 private:
95   void initRegisterMaskIds(const MachineFunction &MF);
96 };
97 
98 /// This class prints out the machine instructions using the MIR serialization
99 /// format.
100 class MIPrinter {
101   raw_ostream &OS;
102   ModuleSlotTracker &MST;
103   const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
104   const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
105 
106 public:
107   MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
108             const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
109             const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
110       : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
111         StackObjectOperandMapping(StackObjectOperandMapping) {}
112 
113   void print(const MachineBasicBlock &MBB);
114 
115   void print(const MachineInstr &MI);
116   void printMBBReference(const MachineBasicBlock &MBB);
117   void printIRBlockReference(const BasicBlock &BB);
118   void printIRValueReference(const Value &V);
119   void printStackObjectReference(int FrameIndex);
120   void printOffset(int64_t Offset);
121   void printTargetFlags(const MachineOperand &Op);
122   void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
123              unsigned I, bool ShouldPrintRegisterTies,
124              const MachineRegisterInfo *MRI = nullptr, bool IsDef = false);
125   void print(const MachineMemOperand &Op);
126 
127   void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
128 };
129 
130 } // end namespace llvm
131 
132 namespace llvm {
133 namespace yaml {
134 
135 /// This struct serializes the LLVM IR module.
136 template <> struct BlockScalarTraits<Module> {
137   static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
138     Mod.print(OS, nullptr);
139   }
140   static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
141     llvm_unreachable("LLVM Module is supposed to be parsed separately");
142     return "";
143   }
144 };
145 
146 } // end namespace yaml
147 } // end namespace llvm
148 
149 static void printReg(unsigned Reg, raw_ostream &OS,
150                      const TargetRegisterInfo *TRI) {
151   // TODO: Print Stack Slots.
152   if (!Reg)
153     OS << '_';
154   else if (TargetRegisterInfo::isVirtualRegister(Reg))
155     OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
156   else if (Reg < TRI->getNumRegs())
157     OS << '%' << StringRef(TRI->getName(Reg)).lower();
158   else
159     llvm_unreachable("Can't print this kind of register yet");
160 }
161 
162 static void printReg(unsigned Reg, yaml::StringValue &Dest,
163                      const TargetRegisterInfo *TRI) {
164   raw_string_ostream OS(Dest.Value);
165   printReg(Reg, OS, TRI);
166 }
167 
168 void MIRPrinter::print(const MachineFunction &MF) {
169   initRegisterMaskIds(MF);
170 
171   yaml::MachineFunction YamlMF;
172   YamlMF.Name = MF.getName();
173   YamlMF.Alignment = MF.getAlignment();
174   YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
175   YamlMF.HasInlineAsm = MF.hasInlineAsm();
176   YamlMF.AllVRegsAllocated = MF.getProperties().hasProperty(
177       MachineFunctionProperties::Property::AllVRegsAllocated);
178 
179   convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
180   ModuleSlotTracker MST(MF.getFunction()->getParent());
181   MST.incorporateFunction(*MF.getFunction());
182   convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo());
183   convertStackObjects(YamlMF, *MF.getFrameInfo(), MF.getMMI(), MST,
184                       MF.getSubtarget().getRegisterInfo());
185   if (const auto *ConstantPool = MF.getConstantPool())
186     convert(YamlMF, *ConstantPool);
187   if (const auto *JumpTableInfo = MF.getJumpTableInfo())
188     convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
189   raw_string_ostream StrOS(YamlMF.Body.Value.Value);
190   bool IsNewlineNeeded = false;
191   for (const auto &MBB : MF) {
192     if (IsNewlineNeeded)
193       StrOS << "\n";
194     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
195         .print(MBB);
196     IsNewlineNeeded = true;
197   }
198   StrOS.flush();
199   yaml::Output Out(OS);
200   Out << YamlMF;
201 }
202 
203 void MIRPrinter::convert(yaml::MachineFunction &MF,
204                          const MachineRegisterInfo &RegInfo,
205                          const TargetRegisterInfo *TRI) {
206   MF.IsSSA = RegInfo.isSSA();
207   MF.TracksRegLiveness = RegInfo.tracksLiveness();
208   MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled();
209 
210   // Print the virtual register definitions.
211   for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
212     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
213     yaml::VirtualRegisterDefinition VReg;
214     VReg.ID = I;
215     if (RegInfo.getRegClassOrNull(Reg))
216       VReg.Class =
217           StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
218     else if (RegInfo.getRegBankOrNull(Reg))
219       VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
220     else {
221       VReg.Class = std::string("_");
222       assert(RegInfo.getSize(Reg) && "Generic registers must have a size");
223     }
224     unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
225     if (PreferredReg)
226       printReg(PreferredReg, VReg.PreferredRegister, TRI);
227     MF.VirtualRegisters.push_back(VReg);
228   }
229 
230   // Print the live ins.
231   for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
232     yaml::MachineFunctionLiveIn LiveIn;
233     printReg(I->first, LiveIn.Register, TRI);
234     if (I->second)
235       printReg(I->second, LiveIn.VirtualRegister, TRI);
236     MF.LiveIns.push_back(LiveIn);
237   }
238   // The used physical register mask is printed as an inverted callee saved
239   // register mask.
240   const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask();
241   if (UsedPhysRegMask.none())
242     return;
243   std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
244   for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) {
245     if (!UsedPhysRegMask[I]) {
246       yaml::FlowStringValue Reg;
247       printReg(I, Reg, TRI);
248       CalleeSavedRegisters.push_back(Reg);
249     }
250   }
251   MF.CalleeSavedRegisters = CalleeSavedRegisters;
252 }
253 
254 void MIRPrinter::convert(ModuleSlotTracker &MST,
255                          yaml::MachineFrameInfo &YamlMFI,
256                          const MachineFrameInfo &MFI) {
257   YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
258   YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
259   YamlMFI.HasStackMap = MFI.hasStackMap();
260   YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
261   YamlMFI.StackSize = MFI.getStackSize();
262   YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
263   YamlMFI.MaxAlignment = MFI.getMaxAlignment();
264   YamlMFI.AdjustsStack = MFI.adjustsStack();
265   YamlMFI.HasCalls = MFI.hasCalls();
266   YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize();
267   YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
268   YamlMFI.HasVAStart = MFI.hasVAStart();
269   YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
270   if (MFI.getSavePoint()) {
271     raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
272     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
273         .printMBBReference(*MFI.getSavePoint());
274   }
275   if (MFI.getRestorePoint()) {
276     raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
277     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
278         .printMBBReference(*MFI.getRestorePoint());
279   }
280 }
281 
282 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF,
283                                      const MachineFrameInfo &MFI,
284                                      MachineModuleInfo &MMI,
285                                      ModuleSlotTracker &MST,
286                                      const TargetRegisterInfo *TRI) {
287   // Process fixed stack objects.
288   unsigned ID = 0;
289   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
290     if (MFI.isDeadObjectIndex(I))
291       continue;
292 
293     yaml::FixedMachineStackObject YamlObject;
294     YamlObject.ID = ID;
295     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
296                           ? yaml::FixedMachineStackObject::SpillSlot
297                           : yaml::FixedMachineStackObject::DefaultType;
298     YamlObject.Offset = MFI.getObjectOffset(I);
299     YamlObject.Size = MFI.getObjectSize(I);
300     YamlObject.Alignment = MFI.getObjectAlignment(I);
301     YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
302     YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
303     MF.FixedStackObjects.push_back(YamlObject);
304     StackObjectOperandMapping.insert(
305         std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
306   }
307 
308   // Process ordinary stack objects.
309   ID = 0;
310   for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
311     if (MFI.isDeadObjectIndex(I))
312       continue;
313 
314     yaml::MachineStackObject YamlObject;
315     YamlObject.ID = ID;
316     if (const auto *Alloca = MFI.getObjectAllocation(I))
317       YamlObject.Name.Value =
318           Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
319     YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
320                           ? yaml::MachineStackObject::SpillSlot
321                           : MFI.isVariableSizedObjectIndex(I)
322                                 ? yaml::MachineStackObject::VariableSized
323                                 : yaml::MachineStackObject::DefaultType;
324     YamlObject.Offset = MFI.getObjectOffset(I);
325     YamlObject.Size = MFI.getObjectSize(I);
326     YamlObject.Alignment = MFI.getObjectAlignment(I);
327 
328     MF.StackObjects.push_back(YamlObject);
329     StackObjectOperandMapping.insert(std::make_pair(
330         I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
331   }
332 
333   for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
334     yaml::StringValue Reg;
335     printReg(CSInfo.getReg(), Reg, TRI);
336     auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
337     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
338            "Invalid stack object index");
339     const FrameIndexOperand &StackObject = StackObjectInfo->second;
340     if (StackObject.IsFixed)
341       MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
342     else
343       MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
344   }
345   for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
346     auto LocalObject = MFI.getLocalFrameObjectMap(I);
347     auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
348     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
349            "Invalid stack object index");
350     const FrameIndexOperand &StackObject = StackObjectInfo->second;
351     assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
352     MF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
353   }
354 
355   // Print the stack object references in the frame information class after
356   // converting the stack objects.
357   if (MFI.hasStackProtectorIndex()) {
358     raw_string_ostream StrOS(MF.FrameInfo.StackProtector.Value);
359     MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
360         .printStackObjectReference(MFI.getStackProtectorIndex());
361   }
362 
363   // Print the debug variable information.
364   for (MachineModuleInfo::VariableDbgInfo &DebugVar :
365        MMI.getVariableDbgInfo()) {
366     auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
367     assert(StackObjectInfo != StackObjectOperandMapping.end() &&
368            "Invalid stack object index");
369     const FrameIndexOperand &StackObject = StackObjectInfo->second;
370     assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
371     auto &Object = MF.StackObjects[StackObject.ID];
372     {
373       raw_string_ostream StrOS(Object.DebugVar.Value);
374       DebugVar.Var->printAsOperand(StrOS, MST);
375     }
376     {
377       raw_string_ostream StrOS(Object.DebugExpr.Value);
378       DebugVar.Expr->printAsOperand(StrOS, MST);
379     }
380     {
381       raw_string_ostream StrOS(Object.DebugLoc.Value);
382       DebugVar.Loc->printAsOperand(StrOS, MST);
383     }
384   }
385 }
386 
387 void MIRPrinter::convert(yaml::MachineFunction &MF,
388                          const MachineConstantPool &ConstantPool) {
389   unsigned ID = 0;
390   for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
391     // TODO: Serialize target specific constant pool entries.
392     if (Constant.isMachineConstantPoolEntry())
393       llvm_unreachable("Can't print target specific constant pool entries yet");
394 
395     yaml::MachineConstantPoolValue YamlConstant;
396     std::string Str;
397     raw_string_ostream StrOS(Str);
398     Constant.Val.ConstVal->printAsOperand(StrOS);
399     YamlConstant.ID = ID++;
400     YamlConstant.Value = StrOS.str();
401     YamlConstant.Alignment = Constant.getAlignment();
402     MF.Constants.push_back(YamlConstant);
403   }
404 }
405 
406 void MIRPrinter::convert(ModuleSlotTracker &MST,
407                          yaml::MachineJumpTable &YamlJTI,
408                          const MachineJumpTableInfo &JTI) {
409   YamlJTI.Kind = JTI.getEntryKind();
410   unsigned ID = 0;
411   for (const auto &Table : JTI.getJumpTables()) {
412     std::string Str;
413     yaml::MachineJumpTable::Entry Entry;
414     Entry.ID = ID++;
415     for (const auto *MBB : Table.MBBs) {
416       raw_string_ostream StrOS(Str);
417       MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
418           .printMBBReference(*MBB);
419       Entry.Blocks.push_back(StrOS.str());
420       Str.clear();
421     }
422     YamlJTI.Entries.push_back(Entry);
423   }
424 }
425 
426 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
427   const auto *TRI = MF.getSubtarget().getRegisterInfo();
428   unsigned I = 0;
429   for (const uint32_t *Mask : TRI->getRegMasks())
430     RegisterMaskIds.insert(std::make_pair(Mask, I++));
431 }
432 
433 void MIPrinter::print(const MachineBasicBlock &MBB) {
434   assert(MBB.getNumber() >= 0 && "Invalid MBB number");
435   OS << "bb." << MBB.getNumber();
436   bool HasAttributes = false;
437   if (const auto *BB = MBB.getBasicBlock()) {
438     if (BB->hasName()) {
439       OS << "." << BB->getName();
440     } else {
441       HasAttributes = true;
442       OS << " (";
443       int Slot = MST.getLocalSlot(BB);
444       if (Slot == -1)
445         OS << "<ir-block badref>";
446       else
447         OS << (Twine("%ir-block.") + Twine(Slot)).str();
448     }
449   }
450   if (MBB.hasAddressTaken()) {
451     OS << (HasAttributes ? ", " : " (");
452     OS << "address-taken";
453     HasAttributes = true;
454   }
455   if (MBB.isEHPad()) {
456     OS << (HasAttributes ? ", " : " (");
457     OS << "landing-pad";
458     HasAttributes = true;
459   }
460   if (MBB.getAlignment()) {
461     OS << (HasAttributes ? ", " : " (");
462     OS << "align " << MBB.getAlignment();
463     HasAttributes = true;
464   }
465   if (HasAttributes)
466     OS << ")";
467   OS << ":\n";
468 
469   bool HasLineAttributes = false;
470   // Print the successors
471   if (!MBB.succ_empty()) {
472     OS.indent(2) << "successors: ";
473     for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
474       if (I != MBB.succ_begin())
475         OS << ", ";
476       printMBBReference(**I);
477       if (MBB.hasSuccessorProbabilities())
478         OS << '(' << MBB.getSuccProbability(I) << ')';
479     }
480     OS << "\n";
481     HasLineAttributes = true;
482   }
483 
484   // Print the live in registers.
485   const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo();
486   assert(TRI && "Expected target register info");
487   if (!MBB.livein_empty()) {
488     OS.indent(2) << "liveins: ";
489     bool First = true;
490     for (const auto &LI : MBB.liveins()) {
491       if (!First)
492         OS << ", ";
493       First = false;
494       printReg(LI.PhysReg, OS, TRI);
495       if (LI.LaneMask != ~0u)
496         OS << ':' << PrintLaneMask(LI.LaneMask);
497     }
498     OS << "\n";
499     HasLineAttributes = true;
500   }
501 
502   if (HasLineAttributes)
503     OS << "\n";
504   bool IsInBundle = false;
505   for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
506     const MachineInstr &MI = *I;
507     if (IsInBundle && !MI.isInsideBundle()) {
508       OS.indent(2) << "}\n";
509       IsInBundle = false;
510     }
511     OS.indent(IsInBundle ? 4 : 2);
512     print(MI);
513     if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
514       OS << " {";
515       IsInBundle = true;
516     }
517     OS << "\n";
518   }
519   if (IsInBundle)
520     OS.indent(2) << "}\n";
521 }
522 
523 /// Return true when an instruction has tied register that can't be determined
524 /// by the instruction's descriptor.
525 static bool hasComplexRegisterTies(const MachineInstr &MI) {
526   const MCInstrDesc &MCID = MI.getDesc();
527   for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
528     const auto &Operand = MI.getOperand(I);
529     if (!Operand.isReg() || Operand.isDef())
530       // Ignore the defined registers as MCID marks only the uses as tied.
531       continue;
532     int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
533     int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
534     if (ExpectedTiedIdx != TiedIdx)
535       return true;
536   }
537   return false;
538 }
539 
540 void MIPrinter::print(const MachineInstr &MI) {
541   const auto *MF = MI.getParent()->getParent();
542   const auto &MRI = MF->getRegInfo();
543   const auto &SubTarget = MF->getSubtarget();
544   const auto *TRI = SubTarget.getRegisterInfo();
545   assert(TRI && "Expected target register info");
546   const auto *TII = SubTarget.getInstrInfo();
547   assert(TII && "Expected target instruction info");
548   if (MI.isCFIInstruction())
549     assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
550 
551   bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
552   unsigned I = 0, E = MI.getNumOperands();
553   for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
554          !MI.getOperand(I).isImplicit();
555        ++I) {
556     if (I)
557       OS << ", ";
558     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies, &MRI,
559           /*IsDef=*/true);
560   }
561 
562   if (I)
563     OS << " = ";
564   if (MI.getFlag(MachineInstr::FrameSetup))
565     OS << "frame-setup ";
566   OS << TII->getName(MI.getOpcode());
567   if (isPreISelGenericOpcode(MI.getOpcode())) {
568     assert(MI.getType().isValid() && "Generic instructions must have a type");
569     unsigned NumTypes = MI.getNumTypes();
570     OS << (NumTypes > 1 ? " {" : "") << ' ';
571     for (unsigned i = 0; i < NumTypes; ++i) {
572       MI.getType(i).print(OS);
573       if (i + 1 != NumTypes)
574         OS <<  ", ";
575     }
576     OS << (NumTypes > 1 ? " }" : "") << ' ';
577   }
578   if (I < E)
579     OS << ' ';
580 
581   bool NeedComma = false;
582   for (; I < E; ++I) {
583     if (NeedComma)
584       OS << ", ";
585     print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies);
586     NeedComma = true;
587   }
588 
589   if (MI.getDebugLoc()) {
590     if (NeedComma)
591       OS << ',';
592     OS << " debug-location ";
593     MI.getDebugLoc()->printAsOperand(OS, MST);
594   }
595 
596   if (!MI.memoperands_empty()) {
597     OS << " :: ";
598     bool NeedComma = false;
599     for (const auto *Op : MI.memoperands()) {
600       if (NeedComma)
601         OS << ", ";
602       print(*Op);
603       NeedComma = true;
604     }
605   }
606 }
607 
608 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
609   OS << "%bb." << MBB.getNumber();
610   if (const auto *BB = MBB.getBasicBlock()) {
611     if (BB->hasName())
612       OS << '.' << BB->getName();
613   }
614 }
615 
616 static void printIRSlotNumber(raw_ostream &OS, int Slot) {
617   if (Slot == -1)
618     OS << "<badref>";
619   else
620     OS << Slot;
621 }
622 
623 void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
624   OS << "%ir-block.";
625   if (BB.hasName()) {
626     printLLVMNameWithoutPrefix(OS, BB.getName());
627     return;
628   }
629   const Function *F = BB.getParent();
630   int Slot;
631   if (F == MST.getCurrentFunction()) {
632     Slot = MST.getLocalSlot(&BB);
633   } else {
634     ModuleSlotTracker CustomMST(F->getParent(),
635                                 /*ShouldInitializeAllMetadata=*/false);
636     CustomMST.incorporateFunction(*F);
637     Slot = CustomMST.getLocalSlot(&BB);
638   }
639   printIRSlotNumber(OS, Slot);
640 }
641 
642 void MIPrinter::printIRValueReference(const Value &V) {
643   if (isa<GlobalValue>(V)) {
644     V.printAsOperand(OS, /*PrintType=*/false, MST);
645     return;
646   }
647   if (isa<Constant>(V)) {
648     // Machine memory operands can load/store to/from constant value pointers.
649     OS << '`';
650     V.printAsOperand(OS, /*PrintType=*/true, MST);
651     OS << '`';
652     return;
653   }
654   OS << "%ir.";
655   if (V.hasName()) {
656     printLLVMNameWithoutPrefix(OS, V.getName());
657     return;
658   }
659   printIRSlotNumber(OS, MST.getLocalSlot(&V));
660 }
661 
662 void MIPrinter::printStackObjectReference(int FrameIndex) {
663   auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
664   assert(ObjectInfo != StackObjectOperandMapping.end() &&
665          "Invalid frame index");
666   const FrameIndexOperand &Operand = ObjectInfo->second;
667   if (Operand.IsFixed) {
668     OS << "%fixed-stack." << Operand.ID;
669     return;
670   }
671   OS << "%stack." << Operand.ID;
672   if (!Operand.Name.empty())
673     OS << '.' << Operand.Name;
674 }
675 
676 void MIPrinter::printOffset(int64_t Offset) {
677   if (Offset == 0)
678     return;
679   if (Offset < 0) {
680     OS << " - " << -Offset;
681     return;
682   }
683   OS << " + " << Offset;
684 }
685 
686 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
687   auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
688   for (const auto &I : Flags) {
689     if (I.first == TF) {
690       return I.second;
691     }
692   }
693   return nullptr;
694 }
695 
696 void MIPrinter::printTargetFlags(const MachineOperand &Op) {
697   if (!Op.getTargetFlags())
698     return;
699   const auto *TII =
700       Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo();
701   assert(TII && "expected instruction info");
702   auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
703   OS << "target-flags(";
704   const bool HasDirectFlags = Flags.first;
705   const bool HasBitmaskFlags = Flags.second;
706   if (!HasDirectFlags && !HasBitmaskFlags) {
707     OS << "<unknown>) ";
708     return;
709   }
710   if (HasDirectFlags) {
711     if (const auto *Name = getTargetFlagName(TII, Flags.first))
712       OS << Name;
713     else
714       OS << "<unknown target flag>";
715   }
716   if (!HasBitmaskFlags) {
717     OS << ") ";
718     return;
719   }
720   bool IsCommaNeeded = HasDirectFlags;
721   unsigned BitMask = Flags.second;
722   auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
723   for (const auto &Mask : BitMasks) {
724     // Check if the flag's bitmask has the bits of the current mask set.
725     if ((BitMask & Mask.first) == Mask.first) {
726       if (IsCommaNeeded)
727         OS << ", ";
728       IsCommaNeeded = true;
729       OS << Mask.second;
730       // Clear the bits which were serialized from the flag's bitmask.
731       BitMask &= ~(Mask.first);
732     }
733   }
734   if (BitMask) {
735     // When the resulting flag's bitmask isn't zero, we know that we didn't
736     // serialize all of the bit flags.
737     if (IsCommaNeeded)
738       OS << ", ";
739     OS << "<unknown bitmask target flag>";
740   }
741   OS << ") ";
742 }
743 
744 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
745   const auto *TII = MF.getSubtarget().getInstrInfo();
746   assert(TII && "expected instruction info");
747   auto Indices = TII->getSerializableTargetIndices();
748   for (const auto &I : Indices) {
749     if (I.first == Index) {
750       return I.second;
751     }
752   }
753   return nullptr;
754 }
755 
756 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
757                       unsigned I, bool ShouldPrintRegisterTies,
758                       const MachineRegisterInfo *MRI, bool IsDef) {
759   printTargetFlags(Op);
760   switch (Op.getType()) {
761   case MachineOperand::MO_Register:
762     if (Op.isImplicit())
763       OS << (Op.isDef() ? "implicit-def " : "implicit ");
764     else if (!IsDef && Op.isDef())
765       // Print the 'def' flag only when the operand is defined after '='.
766       OS << "def ";
767     if (Op.isInternalRead())
768       OS << "internal ";
769     if (Op.isDead())
770       OS << "dead ";
771     if (Op.isKill())
772       OS << "killed ";
773     if (Op.isUndef())
774       OS << "undef ";
775     if (Op.isEarlyClobber())
776       OS << "early-clobber ";
777     if (Op.isDebug())
778       OS << "debug-use ";
779     printReg(Op.getReg(), OS, TRI);
780     // Print the sub register.
781     if (Op.getSubReg() != 0)
782       OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
783     if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
784       OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
785     assert((!IsDef || MRI) && "for IsDef, MRI must be provided");
786     if (IsDef && MRI->getSize(Op.getReg()))
787       OS << '(' << MRI->getSize(Op.getReg()) << ')';
788     break;
789   case MachineOperand::MO_Immediate:
790     OS << Op.getImm();
791     break;
792   case MachineOperand::MO_CImmediate:
793     Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
794     break;
795   case MachineOperand::MO_FPImmediate:
796     Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
797     break;
798   case MachineOperand::MO_MachineBasicBlock:
799     printMBBReference(*Op.getMBB());
800     break;
801   case MachineOperand::MO_FrameIndex:
802     printStackObjectReference(Op.getIndex());
803     break;
804   case MachineOperand::MO_ConstantPoolIndex:
805     OS << "%const." << Op.getIndex();
806     printOffset(Op.getOffset());
807     break;
808   case MachineOperand::MO_TargetIndex: {
809     OS << "target-index(";
810     if (const auto *Name = getTargetIndexName(
811             *Op.getParent()->getParent()->getParent(), Op.getIndex()))
812       OS << Name;
813     else
814       OS << "<unknown>";
815     OS << ')';
816     printOffset(Op.getOffset());
817     break;
818   }
819   case MachineOperand::MO_JumpTableIndex:
820     OS << "%jump-table." << Op.getIndex();
821     break;
822   case MachineOperand::MO_ExternalSymbol:
823     OS << '$';
824     printLLVMNameWithoutPrefix(OS, Op.getSymbolName());
825     printOffset(Op.getOffset());
826     break;
827   case MachineOperand::MO_GlobalAddress:
828     Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
829     printOffset(Op.getOffset());
830     break;
831   case MachineOperand::MO_BlockAddress:
832     OS << "blockaddress(";
833     Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
834                                                         MST);
835     OS << ", ";
836     printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
837     OS << ')';
838     printOffset(Op.getOffset());
839     break;
840   case MachineOperand::MO_RegisterMask: {
841     auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
842     if (RegMaskInfo != RegisterMaskIds.end())
843       OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
844     else
845       llvm_unreachable("Can't print this machine register mask yet.");
846     break;
847   }
848   case MachineOperand::MO_RegisterLiveOut: {
849     const uint32_t *RegMask = Op.getRegLiveOut();
850     OS << "liveout(";
851     bool IsCommaNeeded = false;
852     for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
853       if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
854         if (IsCommaNeeded)
855           OS << ", ";
856         printReg(Reg, OS, TRI);
857         IsCommaNeeded = true;
858       }
859     }
860     OS << ")";
861     break;
862   }
863   case MachineOperand::MO_Metadata:
864     Op.getMetadata()->printAsOperand(OS, MST);
865     break;
866   case MachineOperand::MO_MCSymbol:
867     OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
868     break;
869   case MachineOperand::MO_CFIIndex: {
870     const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI();
871     print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI);
872     break;
873   }
874   }
875 }
876 
877 void MIPrinter::print(const MachineMemOperand &Op) {
878   OS << '(';
879   // TODO: Print operand's target specific flags.
880   if (Op.isVolatile())
881     OS << "volatile ";
882   if (Op.isNonTemporal())
883     OS << "non-temporal ";
884   if (Op.isInvariant())
885     OS << "invariant ";
886   if (Op.isLoad())
887     OS << "load ";
888   else {
889     assert(Op.isStore() && "Non load machine operand must be a store");
890     OS << "store ";
891   }
892   OS << Op.getSize();
893   if (const Value *Val = Op.getValue()) {
894     OS << (Op.isLoad() ? " from " : " into ");
895     printIRValueReference(*Val);
896   } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
897     OS << (Op.isLoad() ? " from " : " into ");
898     assert(PVal && "Expected a pseudo source value");
899     switch (PVal->kind()) {
900     case PseudoSourceValue::Stack:
901       OS << "stack";
902       break;
903     case PseudoSourceValue::GOT:
904       OS << "got";
905       break;
906     case PseudoSourceValue::JumpTable:
907       OS << "jump-table";
908       break;
909     case PseudoSourceValue::ConstantPool:
910       OS << "constant-pool";
911       break;
912     case PseudoSourceValue::FixedStack:
913       printStackObjectReference(
914           cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
915       break;
916     case PseudoSourceValue::GlobalValueCallEntry:
917       OS << "call-entry ";
918       cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
919           OS, /*PrintType=*/false, MST);
920       break;
921     case PseudoSourceValue::ExternalSymbolCallEntry:
922       OS << "call-entry $";
923       printLLVMNameWithoutPrefix(
924           OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
925       break;
926     }
927   }
928   printOffset(Op.getOffset());
929   if (Op.getBaseAlignment() != Op.getSize())
930     OS << ", align " << Op.getBaseAlignment();
931   auto AAInfo = Op.getAAInfo();
932   if (AAInfo.TBAA) {
933     OS << ", !tbaa ";
934     AAInfo.TBAA->printAsOperand(OS, MST);
935   }
936   if (AAInfo.Scope) {
937     OS << ", !alias.scope ";
938     AAInfo.Scope->printAsOperand(OS, MST);
939   }
940   if (AAInfo.NoAlias) {
941     OS << ", !noalias ";
942     AAInfo.NoAlias->printAsOperand(OS, MST);
943   }
944   if (Op.getRanges()) {
945     OS << ", !range ";
946     Op.getRanges()->printAsOperand(OS, MST);
947   }
948   OS << ')';
949 }
950 
951 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
952                              const TargetRegisterInfo *TRI) {
953   int Reg = TRI->getLLVMRegNum(DwarfReg, true);
954   if (Reg == -1) {
955     OS << "<badreg>";
956     return;
957   }
958   printReg(Reg, OS, TRI);
959 }
960 
961 void MIPrinter::print(const MCCFIInstruction &CFI,
962                       const TargetRegisterInfo *TRI) {
963   switch (CFI.getOperation()) {
964   case MCCFIInstruction::OpSameValue:
965     OS << "same_value ";
966     if (CFI.getLabel())
967       OS << "<mcsymbol> ";
968     printCFIRegister(CFI.getRegister(), OS, TRI);
969     break;
970   case MCCFIInstruction::OpOffset:
971     OS << "offset ";
972     if (CFI.getLabel())
973       OS << "<mcsymbol> ";
974     printCFIRegister(CFI.getRegister(), OS, TRI);
975     OS << ", " << CFI.getOffset();
976     break;
977   case MCCFIInstruction::OpDefCfaRegister:
978     OS << "def_cfa_register ";
979     if (CFI.getLabel())
980       OS << "<mcsymbol> ";
981     printCFIRegister(CFI.getRegister(), OS, TRI);
982     break;
983   case MCCFIInstruction::OpDefCfaOffset:
984     OS << "def_cfa_offset ";
985     if (CFI.getLabel())
986       OS << "<mcsymbol> ";
987     OS << CFI.getOffset();
988     break;
989   case MCCFIInstruction::OpDefCfa:
990     OS << "def_cfa ";
991     if (CFI.getLabel())
992       OS << "<mcsymbol> ";
993     printCFIRegister(CFI.getRegister(), OS, TRI);
994     OS << ", " << CFI.getOffset();
995     break;
996   default:
997     // TODO: Print the other CFI Operations.
998     OS << "<unserializable cfi operation>";
999     break;
1000   }
1001 }
1002 
1003 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1004   yaml::Output Out(OS);
1005   Out << const_cast<Module &>(M);
1006 }
1007 
1008 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
1009   MIRPrinter Printer(OS);
1010   Printer.print(MF);
1011 }
1012