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