1 //===- AsmWriter.cpp - Printing LLVM as an assembly file ------------------===//
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 library implements `print` family of functions in classes like
10 // Module, Function, Value, etc. In-memory representation of those classes is
11 // converted to IR strings.
12 //
13 // Note that these routines must be extremely tolerant of various errors in the
14 // LLVM code, because it can be used for debugging transformations.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/iterator_range.h"
31 #include "llvm/BinaryFormat/Dwarf.h"
32 #include "llvm/Config/llvm-config.h"
33 #include "llvm/IR/Argument.h"
34 #include "llvm/IR/AssemblyAnnotationWriter.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/CFG.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Comdat.h"
40 #include "llvm/IR/Constant.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DebugInfoMetadata.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalAlias.h"
46 #include "llvm/IR/GlobalIFunc.h"
47 #include "llvm/IR/GlobalIndirectSymbol.h"
48 #include "llvm/IR/GlobalObject.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/GlobalVariable.h"
51 #include "llvm/IR/IRPrintingPasses.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/InstrTypes.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/Metadata.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/ModuleSlotTracker.h"
60 #include "llvm/IR/ModuleSummaryIndex.h"
61 #include "llvm/IR/Operator.h"
62 #include "llvm/IR/Statepoint.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/TypeFinder.h"
65 #include "llvm/IR/Use.h"
66 #include "llvm/IR/UseListOrder.h"
67 #include "llvm/IR/User.h"
68 #include "llvm/IR/Value.h"
69 #include "llvm/Support/AtomicOrdering.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/Format.h"
75 #include "llvm/Support/FormattedStream.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include <algorithm>
78 #include <cassert>
79 #include <cctype>
80 #include <cstddef>
81 #include <cstdint>
82 #include <iterator>
83 #include <memory>
84 #include <string>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 // Make virtual table appear in this compilation unit.
92 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() = default;
93 
94 //===----------------------------------------------------------------------===//
95 // Helper Functions
96 //===----------------------------------------------------------------------===//
97 
98 namespace {
99 
100 struct OrderMap {
101   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
102 
103   unsigned size() const { return IDs.size(); }
104   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
105 
106   std::pair<unsigned, bool> lookup(const Value *V) const {
107     return IDs.lookup(V);
108   }
109 
110   void index(const Value *V) {
111     // Explicitly sequence get-size and insert-value operations to avoid UB.
112     unsigned ID = IDs.size() + 1;
113     IDs[V].first = ID;
114   }
115 };
116 
117 } // end anonymous namespace
118 
119 /// Look for a value that might be wrapped as metadata, e.g. a value in a
120 /// metadata operand. Returns the input value as-is if it is not wrapped.
121 static const Value *skipMetadataWrapper(const Value *V) {
122   if (const auto *MAV = dyn_cast<MetadataAsValue>(V))
123     if (const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
124       return VAM->getValue();
125   return V;
126 }
127 
128 static void orderValue(const Value *V, OrderMap &OM) {
129   if (OM.lookup(V).first)
130     return;
131 
132   if (const Constant *C = dyn_cast<Constant>(V))
133     if (C->getNumOperands() && !isa<GlobalValue>(C))
134       for (const Value *Op : C->operands())
135         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
136           orderValue(Op, OM);
137 
138   // Note: we cannot cache this lookup above, since inserting into the map
139   // changes the map's size, and thus affects the other IDs.
140   OM.index(V);
141 }
142 
143 static OrderMap orderModule(const Module *M) {
144   OrderMap OM;
145 
146   for (const GlobalVariable &G : M->globals()) {
147     if (G.hasInitializer())
148       if (!isa<GlobalValue>(G.getInitializer()))
149         orderValue(G.getInitializer(), OM);
150     orderValue(&G, OM);
151   }
152   for (const GlobalAlias &A : M->aliases()) {
153     if (!isa<GlobalValue>(A.getAliasee()))
154       orderValue(A.getAliasee(), OM);
155     orderValue(&A, OM);
156   }
157   for (const GlobalIFunc &I : M->ifuncs()) {
158     if (!isa<GlobalValue>(I.getResolver()))
159       orderValue(I.getResolver(), OM);
160     orderValue(&I, OM);
161   }
162   for (const Function &F : *M) {
163     for (const Use &U : F.operands())
164       if (!isa<GlobalValue>(U.get()))
165         orderValue(U.get(), OM);
166 
167     orderValue(&F, OM);
168 
169     if (F.isDeclaration())
170       continue;
171 
172     for (const Argument &A : F.args())
173       orderValue(&A, OM);
174     for (const BasicBlock &BB : F) {
175       orderValue(&BB, OM);
176       for (const Instruction &I : BB) {
177         for (const Value *Op : I.operands()) {
178           Op = skipMetadataWrapper(Op);
179           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
180               isa<InlineAsm>(*Op))
181             orderValue(Op, OM);
182         }
183         orderValue(&I, OM);
184       }
185     }
186   }
187   return OM;
188 }
189 
190 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
191                                          unsigned ID, const OrderMap &OM,
192                                          UseListOrderStack &Stack) {
193   // Predict use-list order for this one.
194   using Entry = std::pair<const Use *, unsigned>;
195   SmallVector<Entry, 64> List;
196   for (const Use &U : V->uses())
197     // Check if this user will be serialized.
198     if (OM.lookup(U.getUser()).first)
199       List.push_back(std::make_pair(&U, List.size()));
200 
201   if (List.size() < 2)
202     // We may have lost some users.
203     return;
204 
205   bool GetsReversed =
206       !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
207   if (auto *BA = dyn_cast<BlockAddress>(V))
208     ID = OM.lookup(BA->getBasicBlock()).first;
209   llvm::sort(List, [&](const Entry &L, const Entry &R) {
210     const Use *LU = L.first;
211     const Use *RU = R.first;
212     if (LU == RU)
213       return false;
214 
215     auto LID = OM.lookup(LU->getUser()).first;
216     auto RID = OM.lookup(RU->getUser()).first;
217 
218     // If ID is 4, then expect: 7 6 5 1 2 3.
219     if (LID < RID) {
220       if (GetsReversed)
221         if (RID <= ID)
222           return true;
223       return false;
224     }
225     if (RID < LID) {
226       if (GetsReversed)
227         if (LID <= ID)
228           return false;
229       return true;
230     }
231 
232     // LID and RID are equal, so we have different operands of the same user.
233     // Assume operands are added in order for all instructions.
234     if (GetsReversed)
235       if (LID <= ID)
236         return LU->getOperandNo() < RU->getOperandNo();
237     return LU->getOperandNo() > RU->getOperandNo();
238   });
239 
240   if (llvm::is_sorted(List, [](const Entry &L, const Entry &R) {
241         return L.second < R.second;
242       }))
243     // Order is already correct.
244     return;
245 
246   // Store the shuffle.
247   Stack.emplace_back(V, F, List.size());
248   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
249   for (size_t I = 0, E = List.size(); I != E; ++I)
250     Stack.back().Shuffle[I] = List[I].second;
251 }
252 
253 static void predictValueUseListOrder(const Value *V, const Function *F,
254                                      OrderMap &OM, UseListOrderStack &Stack) {
255   auto &IDPair = OM[V];
256   assert(IDPair.first && "Unmapped value");
257   if (IDPair.second)
258     // Already predicted.
259     return;
260 
261   // Do the actual prediction.
262   IDPair.second = true;
263   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
264     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
265 
266   // Recursive descent into constants.
267   if (const Constant *C = dyn_cast<Constant>(V))
268     if (C->getNumOperands()) // Visit GlobalValues.
269       for (const Value *Op : C->operands())
270         if (isa<Constant>(Op)) // Visit GlobalValues.
271           predictValueUseListOrder(Op, F, OM, Stack);
272 }
273 
274 static UseListOrderStack predictUseListOrder(const Module *M) {
275   OrderMap OM = orderModule(M);
276 
277   // Use-list orders need to be serialized after all the users have been added
278   // to a value, or else the shuffles will be incomplete.  Store them per
279   // function in a stack.
280   //
281   // Aside from function order, the order of values doesn't matter much here.
282   UseListOrderStack Stack;
283 
284   // We want to visit the functions backward now so we can list function-local
285   // constants in the last Function they're used in.  Module-level constants
286   // have already been visited above.
287   for (const Function &F : make_range(M->rbegin(), M->rend())) {
288     if (F.isDeclaration())
289       continue;
290     for (const BasicBlock &BB : F)
291       predictValueUseListOrder(&BB, &F, OM, Stack);
292     for (const Argument &A : F.args())
293       predictValueUseListOrder(&A, &F, OM, Stack);
294     for (const BasicBlock &BB : F)
295       for (const Instruction &I : BB)
296         for (const Value *Op : I.operands()) {
297           Op = skipMetadataWrapper(Op);
298           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
299             predictValueUseListOrder(Op, &F, OM, Stack);
300         }
301     for (const BasicBlock &BB : F)
302       for (const Instruction &I : BB)
303         predictValueUseListOrder(&I, &F, OM, Stack);
304   }
305 
306   // Visit globals last.
307   for (const GlobalVariable &G : M->globals())
308     predictValueUseListOrder(&G, nullptr, OM, Stack);
309   for (const Function &F : *M)
310     predictValueUseListOrder(&F, nullptr, OM, Stack);
311   for (const GlobalAlias &A : M->aliases())
312     predictValueUseListOrder(&A, nullptr, OM, Stack);
313   for (const GlobalIFunc &I : M->ifuncs())
314     predictValueUseListOrder(&I, nullptr, OM, Stack);
315   for (const GlobalVariable &G : M->globals())
316     if (G.hasInitializer())
317       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
318   for (const GlobalAlias &A : M->aliases())
319     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
320   for (const GlobalIFunc &I : M->ifuncs())
321     predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
322   for (const Function &F : *M)
323     for (const Use &U : F.operands())
324       predictValueUseListOrder(U.get(), nullptr, OM, Stack);
325 
326   return Stack;
327 }
328 
329 static const Module *getModuleFromVal(const Value *V) {
330   if (const Argument *MA = dyn_cast<Argument>(V))
331     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
332 
333   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
334     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
335 
336   if (const Instruction *I = dyn_cast<Instruction>(V)) {
337     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
338     return M ? M->getParent() : nullptr;
339   }
340 
341   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
342     return GV->getParent();
343 
344   if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
345     for (const User *U : MAV->users())
346       if (isa<Instruction>(U))
347         if (const Module *M = getModuleFromVal(U))
348           return M;
349     return nullptr;
350   }
351 
352   return nullptr;
353 }
354 
355 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
356   switch (cc) {
357   default:                         Out << "cc" << cc; break;
358   case CallingConv::Fast:          Out << "fastcc"; break;
359   case CallingConv::Cold:          Out << "coldcc"; break;
360   case CallingConv::WebKit_JS:     Out << "webkit_jscc"; break;
361   case CallingConv::AnyReg:        Out << "anyregcc"; break;
362   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
363   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
364   case CallingConv::CXX_FAST_TLS:  Out << "cxx_fast_tlscc"; break;
365   case CallingConv::GHC:           Out << "ghccc"; break;
366   case CallingConv::Tail:          Out << "tailcc"; break;
367   case CallingConv::CFGuard_Check: Out << "cfguard_checkcc"; break;
368   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
369   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
370   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
371   case CallingConv::X86_RegCall:   Out << "x86_regcallcc"; break;
372   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
373   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
374   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
375   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
376   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
377   case CallingConv::AArch64_VectorCall: Out << "aarch64_vector_pcs"; break;
378   case CallingConv::AArch64_SVE_VectorCall:
379     Out << "aarch64_sve_vector_pcs";
380     break;
381   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
382   case CallingConv::AVR_INTR:      Out << "avr_intrcc "; break;
383   case CallingConv::AVR_SIGNAL:    Out << "avr_signalcc "; break;
384   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
385   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
386   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
387   case CallingConv::Win64:         Out << "win64cc"; break;
388   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
389   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
390   case CallingConv::Swift:         Out << "swiftcc"; break;
391   case CallingConv::X86_INTR:      Out << "x86_intrcc"; break;
392   case CallingConv::HHVM:          Out << "hhvmcc"; break;
393   case CallingConv::HHVM_C:        Out << "hhvm_ccc"; break;
394   case CallingConv::AMDGPU_VS:     Out << "amdgpu_vs"; break;
395   case CallingConv::AMDGPU_LS:     Out << "amdgpu_ls"; break;
396   case CallingConv::AMDGPU_HS:     Out << "amdgpu_hs"; break;
397   case CallingConv::AMDGPU_ES:     Out << "amdgpu_es"; break;
398   case CallingConv::AMDGPU_GS:     Out << "amdgpu_gs"; break;
399   case CallingConv::AMDGPU_PS:     Out << "amdgpu_ps"; break;
400   case CallingConv::AMDGPU_CS:     Out << "amdgpu_cs"; break;
401   case CallingConv::AMDGPU_KERNEL: Out << "amdgpu_kernel"; break;
402   case CallingConv::AMDGPU_Gfx:    Out << "amdgpu_gfx"; break;
403   }
404 }
405 
406 enum PrefixType {
407   GlobalPrefix,
408   ComdatPrefix,
409   LabelPrefix,
410   LocalPrefix,
411   NoPrefix
412 };
413 
414 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
415   assert(!Name.empty() && "Cannot get empty name!");
416 
417   // Scan the name to see if it needs quotes first.
418   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
419   if (!NeedsQuotes) {
420     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
421       // By making this unsigned, the value passed in to isalnum will always be
422       // in the range 0-255.  This is important when building with MSVC because
423       // its implementation will assert.  This situation can arise when dealing
424       // with UTF-8 multibyte characters.
425       unsigned char C = Name[i];
426       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
427           C != '_') {
428         NeedsQuotes = true;
429         break;
430       }
431     }
432   }
433 
434   // If we didn't need any quotes, just write out the name in one blast.
435   if (!NeedsQuotes) {
436     OS << Name;
437     return;
438   }
439 
440   // Okay, we need quotes.  Output the quotes and escape any scary characters as
441   // needed.
442   OS << '"';
443   printEscapedString(Name, OS);
444   OS << '"';
445 }
446 
447 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
448 /// (if the string only contains simple characters) or is surrounded with ""'s
449 /// (if it has special chars in it). Print it out.
450 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
451   switch (Prefix) {
452   case NoPrefix:
453     break;
454   case GlobalPrefix:
455     OS << '@';
456     break;
457   case ComdatPrefix:
458     OS << '$';
459     break;
460   case LabelPrefix:
461     break;
462   case LocalPrefix:
463     OS << '%';
464     break;
465   }
466   printLLVMNameWithoutPrefix(OS, Name);
467 }
468 
469 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
470 /// (if the string only contains simple characters) or is surrounded with ""'s
471 /// (if it has special chars in it). Print it out.
472 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
473   PrintLLVMName(OS, V->getName(),
474                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
475 }
476 
477 static void PrintShuffleMask(raw_ostream &Out, Type *Ty, ArrayRef<int> Mask) {
478   Out << ", <";
479   if (isa<ScalableVectorType>(Ty))
480     Out << "vscale x ";
481   Out << Mask.size() << " x i32> ";
482   bool FirstElt = true;
483   if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
484     Out << "zeroinitializer";
485   } else if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) {
486     Out << "undef";
487   } else {
488     Out << "<";
489     for (int Elt : Mask) {
490       if (FirstElt)
491         FirstElt = false;
492       else
493         Out << ", ";
494       Out << "i32 ";
495       if (Elt == UndefMaskElem)
496         Out << "undef";
497       else
498         Out << Elt;
499     }
500     Out << ">";
501   }
502 }
503 
504 namespace {
505 
506 class TypePrinting {
507 public:
508   TypePrinting(const Module *M = nullptr) : DeferredM(M) {}
509 
510   TypePrinting(const TypePrinting &) = delete;
511   TypePrinting &operator=(const TypePrinting &) = delete;
512 
513   /// The named types that are used by the current module.
514   TypeFinder &getNamedTypes();
515 
516   /// The numbered types, number to type mapping.
517   std::vector<StructType *> &getNumberedTypes();
518 
519   bool empty();
520 
521   void print(Type *Ty, raw_ostream &OS);
522 
523   void printStructBody(StructType *Ty, raw_ostream &OS);
524 
525 private:
526   void incorporateTypes();
527 
528   /// A module to process lazily when needed. Set to nullptr as soon as used.
529   const Module *DeferredM;
530 
531   TypeFinder NamedTypes;
532 
533   // The numbered types, along with their value.
534   DenseMap<StructType *, unsigned> Type2Number;
535 
536   std::vector<StructType *> NumberedTypes;
537 };
538 
539 } // end anonymous namespace
540 
541 TypeFinder &TypePrinting::getNamedTypes() {
542   incorporateTypes();
543   return NamedTypes;
544 }
545 
546 std::vector<StructType *> &TypePrinting::getNumberedTypes() {
547   incorporateTypes();
548 
549   // We know all the numbers that each type is used and we know that it is a
550   // dense assignment. Convert the map to an index table, if it's not done
551   // already (judging from the sizes):
552   if (NumberedTypes.size() == Type2Number.size())
553     return NumberedTypes;
554 
555   NumberedTypes.resize(Type2Number.size());
556   for (const auto &P : Type2Number) {
557     assert(P.second < NumberedTypes.size() && "Didn't get a dense numbering?");
558     assert(!NumberedTypes[P.second] && "Didn't get a unique numbering?");
559     NumberedTypes[P.second] = P.first;
560   }
561   return NumberedTypes;
562 }
563 
564 bool TypePrinting::empty() {
565   incorporateTypes();
566   return NamedTypes.empty() && Type2Number.empty();
567 }
568 
569 void TypePrinting::incorporateTypes() {
570   if (!DeferredM)
571     return;
572 
573   NamedTypes.run(*DeferredM, false);
574   DeferredM = nullptr;
575 
576   // The list of struct types we got back includes all the struct types, split
577   // the unnamed ones out to a numbering and remove the anonymous structs.
578   unsigned NextNumber = 0;
579 
580   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
581   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
582     StructType *STy = *I;
583 
584     // Ignore anonymous types.
585     if (STy->isLiteral())
586       continue;
587 
588     if (STy->getName().empty())
589       Type2Number[STy] = NextNumber++;
590     else
591       *NextToUse++ = STy;
592   }
593 
594   NamedTypes.erase(NextToUse, NamedTypes.end());
595 }
596 
597 /// Write the specified type to the specified raw_ostream, making use of type
598 /// names or up references to shorten the type name where possible.
599 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
600   switch (Ty->getTypeID()) {
601   case Type::VoidTyID:      OS << "void"; return;
602   case Type::HalfTyID:      OS << "half"; return;
603   case Type::BFloatTyID:    OS << "bfloat"; return;
604   case Type::FloatTyID:     OS << "float"; return;
605   case Type::DoubleTyID:    OS << "double"; return;
606   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
607   case Type::FP128TyID:     OS << "fp128"; return;
608   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
609   case Type::LabelTyID:     OS << "label"; return;
610   case Type::MetadataTyID:  OS << "metadata"; return;
611   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
612   case Type::TokenTyID:     OS << "token"; return;
613   case Type::IntegerTyID:
614     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
615     return;
616 
617   case Type::FunctionTyID: {
618     FunctionType *FTy = cast<FunctionType>(Ty);
619     print(FTy->getReturnType(), OS);
620     OS << " (";
621     for (FunctionType::param_iterator I = FTy->param_begin(),
622          E = FTy->param_end(); I != E; ++I) {
623       if (I != FTy->param_begin())
624         OS << ", ";
625       print(*I, OS);
626     }
627     if (FTy->isVarArg()) {
628       if (FTy->getNumParams()) OS << ", ";
629       OS << "...";
630     }
631     OS << ')';
632     return;
633   }
634   case Type::StructTyID: {
635     StructType *STy = cast<StructType>(Ty);
636 
637     if (STy->isLiteral())
638       return printStructBody(STy, OS);
639 
640     if (!STy->getName().empty())
641       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
642 
643     incorporateTypes();
644     const auto I = Type2Number.find(STy);
645     if (I != Type2Number.end())
646       OS << '%' << I->second;
647     else  // Not enumerated, print the hex address.
648       OS << "%\"type " << STy << '\"';
649     return;
650   }
651   case Type::PointerTyID: {
652     PointerType *PTy = cast<PointerType>(Ty);
653     print(PTy->getElementType(), OS);
654     if (unsigned AddressSpace = PTy->getAddressSpace())
655       OS << " addrspace(" << AddressSpace << ')';
656     OS << '*';
657     return;
658   }
659   case Type::ArrayTyID: {
660     ArrayType *ATy = cast<ArrayType>(Ty);
661     OS << '[' << ATy->getNumElements() << " x ";
662     print(ATy->getElementType(), OS);
663     OS << ']';
664     return;
665   }
666   case Type::FixedVectorTyID:
667   case Type::ScalableVectorTyID: {
668     VectorType *PTy = cast<VectorType>(Ty);
669     ElementCount EC = PTy->getElementCount();
670     OS << "<";
671     if (EC.isScalable())
672       OS << "vscale x ";
673     OS << EC.getKnownMinValue() << " x ";
674     print(PTy->getElementType(), OS);
675     OS << '>';
676     return;
677   }
678   }
679   llvm_unreachable("Invalid TypeID");
680 }
681 
682 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
683   if (STy->isOpaque()) {
684     OS << "opaque";
685     return;
686   }
687 
688   if (STy->isPacked())
689     OS << '<';
690 
691   if (STy->getNumElements() == 0) {
692     OS << "{}";
693   } else {
694     StructType::element_iterator I = STy->element_begin();
695     OS << "{ ";
696     print(*I++, OS);
697     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
698       OS << ", ";
699       print(*I, OS);
700     }
701 
702     OS << " }";
703   }
704   if (STy->isPacked())
705     OS << '>';
706 }
707 
708 namespace llvm {
709 
710 //===----------------------------------------------------------------------===//
711 // SlotTracker Class: Enumerate slot numbers for unnamed values
712 //===----------------------------------------------------------------------===//
713 /// This class provides computation of slot numbers for LLVM Assembly writing.
714 ///
715 class SlotTracker {
716 public:
717   /// ValueMap - A mapping of Values to slot numbers.
718   using ValueMap = DenseMap<const Value *, unsigned>;
719 
720 private:
721   /// TheModule - The module for which we are holding slot numbers.
722   const Module* TheModule;
723 
724   /// TheFunction - The function for which we are holding slot numbers.
725   const Function* TheFunction = nullptr;
726   bool FunctionProcessed = false;
727   bool ShouldInitializeAllMetadata;
728 
729   /// The summary index for which we are holding slot numbers.
730   const ModuleSummaryIndex *TheIndex = nullptr;
731 
732   /// mMap - The slot map for the module level data.
733   ValueMap mMap;
734   unsigned mNext = 0;
735 
736   /// fMap - The slot map for the function level data.
737   ValueMap fMap;
738   unsigned fNext = 0;
739 
740   /// mdnMap - Map for MDNodes.
741   DenseMap<const MDNode*, unsigned> mdnMap;
742   unsigned mdnNext = 0;
743 
744   /// asMap - The slot map for attribute sets.
745   DenseMap<AttributeSet, unsigned> asMap;
746   unsigned asNext = 0;
747 
748   /// ModulePathMap - The slot map for Module paths used in the summary index.
749   StringMap<unsigned> ModulePathMap;
750   unsigned ModulePathNext = 0;
751 
752   /// GUIDMap - The slot map for GUIDs used in the summary index.
753   DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
754   unsigned GUIDNext = 0;
755 
756   /// TypeIdMap - The slot map for type ids used in the summary index.
757   StringMap<unsigned> TypeIdMap;
758   unsigned TypeIdNext = 0;
759 
760 public:
761   /// Construct from a module.
762   ///
763   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
764   /// functions, giving correct numbering for metadata referenced only from
765   /// within a function (even if no functions have been initialized).
766   explicit SlotTracker(const Module *M,
767                        bool ShouldInitializeAllMetadata = false);
768 
769   /// Construct from a function, starting out in incorp state.
770   ///
771   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
772   /// functions, giving correct numbering for metadata referenced only from
773   /// within a function (even if no functions have been initialized).
774   explicit SlotTracker(const Function *F,
775                        bool ShouldInitializeAllMetadata = false);
776 
777   /// Construct from a module summary index.
778   explicit SlotTracker(const ModuleSummaryIndex *Index);
779 
780   SlotTracker(const SlotTracker &) = delete;
781   SlotTracker &operator=(const SlotTracker &) = delete;
782 
783   /// Return the slot number of the specified value in it's type
784   /// plane.  If something is not in the SlotTracker, return -1.
785   int getLocalSlot(const Value *V);
786   int getGlobalSlot(const GlobalValue *V);
787   int getMetadataSlot(const MDNode *N);
788   int getAttributeGroupSlot(AttributeSet AS);
789   int getModulePathSlot(StringRef Path);
790   int getGUIDSlot(GlobalValue::GUID GUID);
791   int getTypeIdSlot(StringRef Id);
792 
793   /// If you'd like to deal with a function instead of just a module, use
794   /// this method to get its data into the SlotTracker.
795   void incorporateFunction(const Function *F) {
796     TheFunction = F;
797     FunctionProcessed = false;
798   }
799 
800   const Function *getFunction() const { return TheFunction; }
801 
802   /// After calling incorporateFunction, use this method to remove the
803   /// most recently incorporated function from the SlotTracker. This
804   /// will reset the state of the machine back to just the module contents.
805   void purgeFunction();
806 
807   /// MDNode map iterators.
808   using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
809 
810   mdn_iterator mdn_begin() { return mdnMap.begin(); }
811   mdn_iterator mdn_end() { return mdnMap.end(); }
812   unsigned mdn_size() const { return mdnMap.size(); }
813   bool mdn_empty() const { return mdnMap.empty(); }
814 
815   /// AttributeSet map iterators.
816   using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
817 
818   as_iterator as_begin()   { return asMap.begin(); }
819   as_iterator as_end()     { return asMap.end(); }
820   unsigned as_size() const { return asMap.size(); }
821   bool as_empty() const    { return asMap.empty(); }
822 
823   /// GUID map iterators.
824   using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
825 
826   /// These functions do the actual initialization.
827   inline void initializeIfNeeded();
828   int initializeIndexIfNeeded();
829 
830   // Implementation Details
831 private:
832   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
833   void CreateModuleSlot(const GlobalValue *V);
834 
835   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
836   void CreateMetadataSlot(const MDNode *N);
837 
838   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
839   void CreateFunctionSlot(const Value *V);
840 
841   /// Insert the specified AttributeSet into the slot table.
842   void CreateAttributeSetSlot(AttributeSet AS);
843 
844   inline void CreateModulePathSlot(StringRef Path);
845   void CreateGUIDSlot(GlobalValue::GUID GUID);
846   void CreateTypeIdSlot(StringRef Id);
847 
848   /// Add all of the module level global variables (and their initializers)
849   /// and function declarations, but not the contents of those functions.
850   void processModule();
851   // Returns number of allocated slots
852   int processIndex();
853 
854   /// Add all of the functions arguments, basic blocks, and instructions.
855   void processFunction();
856 
857   /// Add the metadata directly attached to a GlobalObject.
858   void processGlobalObjectMetadata(const GlobalObject &GO);
859 
860   /// Add all of the metadata from a function.
861   void processFunctionMetadata(const Function &F);
862 
863   /// Add all of the metadata from an instruction.
864   void processInstructionMetadata(const Instruction &I);
865 };
866 
867 } // end namespace llvm
868 
869 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
870                                      const Function *F)
871     : M(M), F(F), Machine(&Machine) {}
872 
873 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
874                                      bool ShouldInitializeAllMetadata)
875     : ShouldCreateStorage(M),
876       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
877 
878 ModuleSlotTracker::~ModuleSlotTracker() = default;
879 
880 SlotTracker *ModuleSlotTracker::getMachine() {
881   if (!ShouldCreateStorage)
882     return Machine;
883 
884   ShouldCreateStorage = false;
885   MachineStorage =
886       std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
887   Machine = MachineStorage.get();
888   return Machine;
889 }
890 
891 void ModuleSlotTracker::incorporateFunction(const Function &F) {
892   // Using getMachine() may lazily create the slot tracker.
893   if (!getMachine())
894     return;
895 
896   // Nothing to do if this is the right function already.
897   if (this->F == &F)
898     return;
899   if (this->F)
900     Machine->purgeFunction();
901   Machine->incorporateFunction(&F);
902   this->F = &F;
903 }
904 
905 int ModuleSlotTracker::getLocalSlot(const Value *V) {
906   assert(F && "No function incorporated");
907   return Machine->getLocalSlot(V);
908 }
909 
910 static SlotTracker *createSlotTracker(const Value *V) {
911   if (const Argument *FA = dyn_cast<Argument>(V))
912     return new SlotTracker(FA->getParent());
913 
914   if (const Instruction *I = dyn_cast<Instruction>(V))
915     if (I->getParent())
916       return new SlotTracker(I->getParent()->getParent());
917 
918   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
919     return new SlotTracker(BB->getParent());
920 
921   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
922     return new SlotTracker(GV->getParent());
923 
924   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
925     return new SlotTracker(GA->getParent());
926 
927   if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
928     return new SlotTracker(GIF->getParent());
929 
930   if (const Function *Func = dyn_cast<Function>(V))
931     return new SlotTracker(Func);
932 
933   return nullptr;
934 }
935 
936 #if 0
937 #define ST_DEBUG(X) dbgs() << X
938 #else
939 #define ST_DEBUG(X)
940 #endif
941 
942 // Module level constructor. Causes the contents of the Module (sans functions)
943 // to be added to the slot table.
944 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
945     : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
946 
947 // Function level constructor. Causes the contents of the Module and the one
948 // function provided to be added to the slot table.
949 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
950     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
951       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
952 
953 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
954     : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
955 
956 inline void SlotTracker::initializeIfNeeded() {
957   if (TheModule) {
958     processModule();
959     TheModule = nullptr; ///< Prevent re-processing next time we're called.
960   }
961 
962   if (TheFunction && !FunctionProcessed)
963     processFunction();
964 }
965 
966 int SlotTracker::initializeIndexIfNeeded() {
967   if (!TheIndex)
968     return 0;
969   int NumSlots = processIndex();
970   TheIndex = nullptr; ///< Prevent re-processing next time we're called.
971   return NumSlots;
972 }
973 
974 // Iterate through all the global variables, functions, and global
975 // variable initializers and create slots for them.
976 void SlotTracker::processModule() {
977   ST_DEBUG("begin processModule!\n");
978 
979   // Add all of the unnamed global variables to the value table.
980   for (const GlobalVariable &Var : TheModule->globals()) {
981     if (!Var.hasName())
982       CreateModuleSlot(&Var);
983     processGlobalObjectMetadata(Var);
984     auto Attrs = Var.getAttributes();
985     if (Attrs.hasAttributes())
986       CreateAttributeSetSlot(Attrs);
987   }
988 
989   for (const GlobalAlias &A : TheModule->aliases()) {
990     if (!A.hasName())
991       CreateModuleSlot(&A);
992   }
993 
994   for (const GlobalIFunc &I : TheModule->ifuncs()) {
995     if (!I.hasName())
996       CreateModuleSlot(&I);
997   }
998 
999   // Add metadata used by named metadata.
1000   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
1001     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
1002       CreateMetadataSlot(NMD.getOperand(i));
1003   }
1004 
1005   for (const Function &F : *TheModule) {
1006     if (!F.hasName())
1007       // Add all the unnamed functions to the table.
1008       CreateModuleSlot(&F);
1009 
1010     if (ShouldInitializeAllMetadata)
1011       processFunctionMetadata(F);
1012 
1013     // Add all the function attributes to the table.
1014     // FIXME: Add attributes of other objects?
1015     AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
1016     if (FnAttrs.hasAttributes())
1017       CreateAttributeSetSlot(FnAttrs);
1018   }
1019 
1020   ST_DEBUG("end processModule!\n");
1021 }
1022 
1023 // Process the arguments, basic blocks, and instructions  of a function.
1024 void SlotTracker::processFunction() {
1025   ST_DEBUG("begin processFunction!\n");
1026   fNext = 0;
1027 
1028   // Process function metadata if it wasn't hit at the module-level.
1029   if (!ShouldInitializeAllMetadata)
1030     processFunctionMetadata(*TheFunction);
1031 
1032   // Add all the function arguments with no names.
1033   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1034       AE = TheFunction->arg_end(); AI != AE; ++AI)
1035     if (!AI->hasName())
1036       CreateFunctionSlot(&*AI);
1037 
1038   ST_DEBUG("Inserting Instructions:\n");
1039 
1040   // Add all of the basic blocks and instructions with no names.
1041   for (auto &BB : *TheFunction) {
1042     if (!BB.hasName())
1043       CreateFunctionSlot(&BB);
1044 
1045     for (auto &I : BB) {
1046       if (!I.getType()->isVoidTy() && !I.hasName())
1047         CreateFunctionSlot(&I);
1048 
1049       // We allow direct calls to any llvm.foo function here, because the
1050       // target may not be linked into the optimizer.
1051       if (const auto *Call = dyn_cast<CallBase>(&I)) {
1052         // Add all the call attributes to the table.
1053         AttributeSet Attrs = Call->getAttributes().getFnAttributes();
1054         if (Attrs.hasAttributes())
1055           CreateAttributeSetSlot(Attrs);
1056       }
1057     }
1058   }
1059 
1060   FunctionProcessed = true;
1061 
1062   ST_DEBUG("end processFunction!\n");
1063 }
1064 
1065 // Iterate through all the GUID in the index and create slots for them.
1066 int SlotTracker::processIndex() {
1067   ST_DEBUG("begin processIndex!\n");
1068   assert(TheIndex);
1069 
1070   // The first block of slots are just the module ids, which start at 0 and are
1071   // assigned consecutively. Since the StringMap iteration order isn't
1072   // guaranteed, use a std::map to order by module ID before assigning slots.
1073   std::map<uint64_t, StringRef> ModuleIdToPathMap;
1074   for (auto &ModPath : TheIndex->modulePaths())
1075     ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
1076   for (auto &ModPair : ModuleIdToPathMap)
1077     CreateModulePathSlot(ModPair.second);
1078 
1079   // Start numbering the GUIDs after the module ids.
1080   GUIDNext = ModulePathNext;
1081 
1082   for (auto &GlobalList : *TheIndex)
1083     CreateGUIDSlot(GlobalList.first);
1084 
1085   for (auto &TId : TheIndex->typeIdCompatibleVtableMap())
1086     CreateGUIDSlot(GlobalValue::getGUID(TId.first));
1087 
1088   // Start numbering the TypeIds after the GUIDs.
1089   TypeIdNext = GUIDNext;
1090   for (auto TidIter = TheIndex->typeIds().begin();
1091        TidIter != TheIndex->typeIds().end(); TidIter++)
1092     CreateTypeIdSlot(TidIter->second.first);
1093 
1094   ST_DEBUG("end processIndex!\n");
1095   return TypeIdNext;
1096 }
1097 
1098 void SlotTracker::processGlobalObjectMetadata(const GlobalObject &GO) {
1099   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1100   GO.getAllMetadata(MDs);
1101   for (auto &MD : MDs)
1102     CreateMetadataSlot(MD.second);
1103 }
1104 
1105 void SlotTracker::processFunctionMetadata(const Function &F) {
1106   processGlobalObjectMetadata(F);
1107   for (auto &BB : F) {
1108     for (auto &I : BB)
1109       processInstructionMetadata(I);
1110   }
1111 }
1112 
1113 void SlotTracker::processInstructionMetadata(const Instruction &I) {
1114   // Process metadata used directly by intrinsics.
1115   if (const CallInst *CI = dyn_cast<CallInst>(&I))
1116     if (Function *F = CI->getCalledFunction())
1117       if (F->isIntrinsic())
1118         for (auto &Op : I.operands())
1119           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
1120             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
1121               CreateMetadataSlot(N);
1122 
1123   // Process metadata attached to this instruction.
1124   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1125   I.getAllMetadata(MDs);
1126   for (auto &MD : MDs)
1127     CreateMetadataSlot(MD.second);
1128 }
1129 
1130 /// Clean up after incorporating a function. This is the only way to get out of
1131 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1132 /// incorporation state is indicated by TheFunction != 0.
1133 void SlotTracker::purgeFunction() {
1134   ST_DEBUG("begin purgeFunction!\n");
1135   fMap.clear(); // Simply discard the function level map
1136   TheFunction = nullptr;
1137   FunctionProcessed = false;
1138   ST_DEBUG("end purgeFunction!\n");
1139 }
1140 
1141 /// getGlobalSlot - Get the slot number of a global value.
1142 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
1143   // Check for uninitialized state and do lazy initialization.
1144   initializeIfNeeded();
1145 
1146   // Find the value in the module map
1147   ValueMap::iterator MI = mMap.find(V);
1148   return MI == mMap.end() ? -1 : (int)MI->second;
1149 }
1150 
1151 /// getMetadataSlot - Get the slot number of a MDNode.
1152 int SlotTracker::getMetadataSlot(const MDNode *N) {
1153   // Check for uninitialized state and do lazy initialization.
1154   initializeIfNeeded();
1155 
1156   // Find the MDNode in the module map
1157   mdn_iterator MI = mdnMap.find(N);
1158   return MI == mdnMap.end() ? -1 : (int)MI->second;
1159 }
1160 
1161 /// getLocalSlot - Get the slot number for a value that is local to a function.
1162 int SlotTracker::getLocalSlot(const Value *V) {
1163   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1164 
1165   // Check for uninitialized state and do lazy initialization.
1166   initializeIfNeeded();
1167 
1168   ValueMap::iterator FI = fMap.find(V);
1169   return FI == fMap.end() ? -1 : (int)FI->second;
1170 }
1171 
1172 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
1173   // Check for uninitialized state and do lazy initialization.
1174   initializeIfNeeded();
1175 
1176   // Find the AttributeSet in the module map.
1177   as_iterator AI = asMap.find(AS);
1178   return AI == asMap.end() ? -1 : (int)AI->second;
1179 }
1180 
1181 int SlotTracker::getModulePathSlot(StringRef Path) {
1182   // Check for uninitialized state and do lazy initialization.
1183   initializeIndexIfNeeded();
1184 
1185   // Find the Module path in the map
1186   auto I = ModulePathMap.find(Path);
1187   return I == ModulePathMap.end() ? -1 : (int)I->second;
1188 }
1189 
1190 int SlotTracker::getGUIDSlot(GlobalValue::GUID GUID) {
1191   // Check for uninitialized state and do lazy initialization.
1192   initializeIndexIfNeeded();
1193 
1194   // Find the GUID in the map
1195   guid_iterator I = GUIDMap.find(GUID);
1196   return I == GUIDMap.end() ? -1 : (int)I->second;
1197 }
1198 
1199 int SlotTracker::getTypeIdSlot(StringRef Id) {
1200   // Check for uninitialized state and do lazy initialization.
1201   initializeIndexIfNeeded();
1202 
1203   // Find the TypeId string in the map
1204   auto I = TypeIdMap.find(Id);
1205   return I == TypeIdMap.end() ? -1 : (int)I->second;
1206 }
1207 
1208 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1209 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
1210   assert(V && "Can't insert a null Value into SlotTracker!");
1211   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
1212   assert(!V->hasName() && "Doesn't need a slot!");
1213 
1214   unsigned DestSlot = mNext++;
1215   mMap[V] = DestSlot;
1216 
1217   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1218            DestSlot << " [");
1219   // G = Global, F = Function, A = Alias, I = IFunc, o = other
1220   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1221             (isa<Function>(V) ? 'F' :
1222              (isa<GlobalAlias>(V) ? 'A' :
1223               (isa<GlobalIFunc>(V) ? 'I' : 'o')))) << "]\n");
1224 }
1225 
1226 /// CreateSlot - Create a new slot for the specified value if it has no name.
1227 void SlotTracker::CreateFunctionSlot(const Value *V) {
1228   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
1229 
1230   unsigned DestSlot = fNext++;
1231   fMap[V] = DestSlot;
1232 
1233   // G = Global, F = Function, o = other
1234   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1235            DestSlot << " [o]\n");
1236 }
1237 
1238 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
1239 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
1240   assert(N && "Can't insert a null Value into SlotTracker!");
1241 
1242   // Don't make slots for DIExpressions. We just print them inline everywhere.
1243   if (isa<DIExpression>(N))
1244     return;
1245 
1246   unsigned DestSlot = mdnNext;
1247   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
1248     return;
1249   ++mdnNext;
1250 
1251   // Recursively add any MDNodes referenced by operands.
1252   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1253     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
1254       CreateMetadataSlot(Op);
1255 }
1256 
1257 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
1258   assert(AS.hasAttributes() && "Doesn't need a slot!");
1259 
1260   as_iterator I = asMap.find(AS);
1261   if (I != asMap.end())
1262     return;
1263 
1264   unsigned DestSlot = asNext++;
1265   asMap[AS] = DestSlot;
1266 }
1267 
1268 /// Create a new slot for the specified Module
1269 void SlotTracker::CreateModulePathSlot(StringRef Path) {
1270   ModulePathMap[Path] = ModulePathNext++;
1271 }
1272 
1273 /// Create a new slot for the specified GUID
1274 void SlotTracker::CreateGUIDSlot(GlobalValue::GUID GUID) {
1275   GUIDMap[GUID] = GUIDNext++;
1276 }
1277 
1278 /// Create a new slot for the specified Id
1279 void SlotTracker::CreateTypeIdSlot(StringRef Id) {
1280   TypeIdMap[Id] = TypeIdNext++;
1281 }
1282 
1283 //===----------------------------------------------------------------------===//
1284 // AsmWriter Implementation
1285 //===----------------------------------------------------------------------===//
1286 
1287 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1288                                    TypePrinting *TypePrinter,
1289                                    SlotTracker *Machine,
1290                                    const Module *Context);
1291 
1292 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1293                                    TypePrinting *TypePrinter,
1294                                    SlotTracker *Machine, const Module *Context,
1295                                    bool FromValue = false);
1296 
1297 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1298   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1299     // 'Fast' is an abbreviation for all fast-math-flags.
1300     if (FPO->isFast())
1301       Out << " fast";
1302     else {
1303       if (FPO->hasAllowReassoc())
1304         Out << " reassoc";
1305       if (FPO->hasNoNaNs())
1306         Out << " nnan";
1307       if (FPO->hasNoInfs())
1308         Out << " ninf";
1309       if (FPO->hasNoSignedZeros())
1310         Out << " nsz";
1311       if (FPO->hasAllowReciprocal())
1312         Out << " arcp";
1313       if (FPO->hasAllowContract())
1314         Out << " contract";
1315       if (FPO->hasApproxFunc())
1316         Out << " afn";
1317     }
1318   }
1319 
1320   if (const OverflowingBinaryOperator *OBO =
1321         dyn_cast<OverflowingBinaryOperator>(U)) {
1322     if (OBO->hasNoUnsignedWrap())
1323       Out << " nuw";
1324     if (OBO->hasNoSignedWrap())
1325       Out << " nsw";
1326   } else if (const PossiblyExactOperator *Div =
1327                dyn_cast<PossiblyExactOperator>(U)) {
1328     if (Div->isExact())
1329       Out << " exact";
1330   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1331     if (GEP->isInBounds())
1332       Out << " inbounds";
1333   }
1334 }
1335 
1336 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1337                                   TypePrinting &TypePrinter,
1338                                   SlotTracker *Machine,
1339                                   const Module *Context) {
1340   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1341     if (CI->getType()->isIntegerTy(1)) {
1342       Out << (CI->getZExtValue() ? "true" : "false");
1343       return;
1344     }
1345     Out << CI->getValue();
1346     return;
1347   }
1348 
1349   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1350     const APFloat &APF = CFP->getValueAPF();
1351     if (&APF.getSemantics() == &APFloat::IEEEsingle() ||
1352         &APF.getSemantics() == &APFloat::IEEEdouble()) {
1353       // We would like to output the FP constant value in exponential notation,
1354       // but we cannot do this if doing so will lose precision.  Check here to
1355       // make sure that we only output it in exponential format if we can parse
1356       // the value back and get the same value.
1357       //
1358       bool ignored;
1359       bool isDouble = &APF.getSemantics() == &APFloat::IEEEdouble();
1360       bool isInf = APF.isInfinity();
1361       bool isNaN = APF.isNaN();
1362       if (!isInf && !isNaN) {
1363         double Val = isDouble ? APF.convertToDouble() : APF.convertToFloat();
1364         SmallString<128> StrVal;
1365         APF.toString(StrVal, 6, 0, false);
1366         // Check to make sure that the stringized number is not some string like
1367         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
1368         // that the string matches the "[-+]?[0-9]" regex.
1369         //
1370         assert(((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1371                 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1372                  (StrVal[1] >= '0' && StrVal[1] <= '9'))) &&
1373                "[-+]?[0-9] regex does not match!");
1374         // Reparse stringized version!
1375         if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1376           Out << StrVal;
1377           return;
1378         }
1379       }
1380       // Otherwise we could not reparse it to exactly the same value, so we must
1381       // output the string in hexadecimal format!  Note that loading and storing
1382       // floating point types changes the bits of NaNs on some hosts, notably
1383       // x86, so we must not use these types.
1384       static_assert(sizeof(double) == sizeof(uint64_t),
1385                     "assuming that double is 64 bits!");
1386       APFloat apf = APF;
1387       // Floats are represented in ASCII IR as double, convert.
1388       // FIXME: We should allow 32-bit hex float and remove this.
1389       if (!isDouble) {
1390         // A signaling NaN is quieted on conversion, so we need to recreate the
1391         // expected value after convert (quiet bit of the payload is clear).
1392         bool IsSNAN = apf.isSignaling();
1393         apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1394                     &ignored);
1395         if (IsSNAN) {
1396           APInt Payload = apf.bitcastToAPInt();
1397           apf = APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(),
1398                                  &Payload);
1399         }
1400       }
1401       Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1402       return;
1403     }
1404 
1405     // Either half, bfloat or some form of long double.
1406     // These appear as a magic letter identifying the type, then a
1407     // fixed number of hex digits.
1408     Out << "0x";
1409     APInt API = APF.bitcastToAPInt();
1410     if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1411       Out << 'K';
1412       Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1413                                   /*Upper=*/true);
1414       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1415                                   /*Upper=*/true);
1416       return;
1417     } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1418       Out << 'L';
1419       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1420                                   /*Upper=*/true);
1421       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1422                                   /*Upper=*/true);
1423     } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1424       Out << 'M';
1425       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1426                                   /*Upper=*/true);
1427       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1428                                   /*Upper=*/true);
1429     } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1430       Out << 'H';
1431       Out << format_hex_no_prefix(API.getZExtValue(), 4,
1432                                   /*Upper=*/true);
1433     } else if (&APF.getSemantics() == &APFloat::BFloat()) {
1434       Out << 'R';
1435       Out << format_hex_no_prefix(API.getZExtValue(), 4,
1436                                   /*Upper=*/true);
1437     } else
1438       llvm_unreachable("Unsupported floating point type");
1439     return;
1440   }
1441 
1442   if (isa<ConstantAggregateZero>(CV)) {
1443     Out << "zeroinitializer";
1444     return;
1445   }
1446 
1447   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1448     Out << "blockaddress(";
1449     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1450                            Context);
1451     Out << ", ";
1452     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1453                            Context);
1454     Out << ")";
1455     return;
1456   }
1457 
1458   if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1459     Out << "dso_local_equivalent ";
1460     WriteAsOperandInternal(Out, Equiv->getGlobalValue(), &TypePrinter, Machine,
1461                            Context);
1462     return;
1463   }
1464 
1465   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1466     Type *ETy = CA->getType()->getElementType();
1467     Out << '[';
1468     TypePrinter.print(ETy, Out);
1469     Out << ' ';
1470     WriteAsOperandInternal(Out, CA->getOperand(0),
1471                            &TypePrinter, Machine,
1472                            Context);
1473     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1474       Out << ", ";
1475       TypePrinter.print(ETy, Out);
1476       Out << ' ';
1477       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1478                              Context);
1479     }
1480     Out << ']';
1481     return;
1482   }
1483 
1484   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1485     // As a special case, print the array as a string if it is an array of
1486     // i8 with ConstantInt values.
1487     if (CA->isString()) {
1488       Out << "c\"";
1489       printEscapedString(CA->getAsString(), Out);
1490       Out << '"';
1491       return;
1492     }
1493 
1494     Type *ETy = CA->getType()->getElementType();
1495     Out << '[';
1496     TypePrinter.print(ETy, Out);
1497     Out << ' ';
1498     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1499                            &TypePrinter, Machine,
1500                            Context);
1501     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1502       Out << ", ";
1503       TypePrinter.print(ETy, Out);
1504       Out << ' ';
1505       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1506                              Machine, Context);
1507     }
1508     Out << ']';
1509     return;
1510   }
1511 
1512   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1513     if (CS->getType()->isPacked())
1514       Out << '<';
1515     Out << '{';
1516     unsigned N = CS->getNumOperands();
1517     if (N) {
1518       Out << ' ';
1519       TypePrinter.print(CS->getOperand(0)->getType(), Out);
1520       Out << ' ';
1521 
1522       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1523                              Context);
1524 
1525       for (unsigned i = 1; i < N; i++) {
1526         Out << ", ";
1527         TypePrinter.print(CS->getOperand(i)->getType(), Out);
1528         Out << ' ';
1529 
1530         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1531                                Context);
1532       }
1533       Out << ' ';
1534     }
1535 
1536     Out << '}';
1537     if (CS->getType()->isPacked())
1538       Out << '>';
1539     return;
1540   }
1541 
1542   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1543     auto *CVVTy = cast<FixedVectorType>(CV->getType());
1544     Type *ETy = CVVTy->getElementType();
1545     Out << '<';
1546     TypePrinter.print(ETy, Out);
1547     Out << ' ';
1548     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1549                            Machine, Context);
1550     for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
1551       Out << ", ";
1552       TypePrinter.print(ETy, Out);
1553       Out << ' ';
1554       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1555                              Machine, Context);
1556     }
1557     Out << '>';
1558     return;
1559   }
1560 
1561   if (isa<ConstantPointerNull>(CV)) {
1562     Out << "null";
1563     return;
1564   }
1565 
1566   if (isa<ConstantTokenNone>(CV)) {
1567     Out << "none";
1568     return;
1569   }
1570 
1571   if (isa<UndefValue>(CV)) {
1572     Out << "undef";
1573     return;
1574   }
1575 
1576   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1577     Out << CE->getOpcodeName();
1578     WriteOptimizationInfo(Out, CE);
1579     if (CE->isCompare())
1580       Out << ' ' << CmpInst::getPredicateName(
1581                         static_cast<CmpInst::Predicate>(CE->getPredicate()));
1582     Out << " (";
1583 
1584     Optional<unsigned> InRangeOp;
1585     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1586       TypePrinter.print(GEP->getSourceElementType(), Out);
1587       Out << ", ";
1588       InRangeOp = GEP->getInRangeIndex();
1589       if (InRangeOp)
1590         ++*InRangeOp;
1591     }
1592 
1593     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1594       if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1595         Out << "inrange ";
1596       TypePrinter.print((*OI)->getType(), Out);
1597       Out << ' ';
1598       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1599       if (OI+1 != CE->op_end())
1600         Out << ", ";
1601     }
1602 
1603     if (CE->hasIndices()) {
1604       ArrayRef<unsigned> Indices = CE->getIndices();
1605       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1606         Out << ", " << Indices[i];
1607     }
1608 
1609     if (CE->isCast()) {
1610       Out << " to ";
1611       TypePrinter.print(CE->getType(), Out);
1612     }
1613 
1614     if (CE->getOpcode() == Instruction::ShuffleVector)
1615       PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
1616 
1617     Out << ')';
1618     return;
1619   }
1620 
1621   Out << "<placeholder or erroneous Constant>";
1622 }
1623 
1624 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1625                          TypePrinting *TypePrinter, SlotTracker *Machine,
1626                          const Module *Context) {
1627   Out << "!{";
1628   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1629     const Metadata *MD = Node->getOperand(mi);
1630     if (!MD)
1631       Out << "null";
1632     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1633       Value *V = MDV->getValue();
1634       TypePrinter->print(V->getType(), Out);
1635       Out << ' ';
1636       WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1637     } else {
1638       WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1639     }
1640     if (mi + 1 != me)
1641       Out << ", ";
1642   }
1643 
1644   Out << "}";
1645 }
1646 
1647 namespace {
1648 
1649 struct FieldSeparator {
1650   bool Skip = true;
1651   const char *Sep;
1652 
1653   FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1654 };
1655 
1656 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1657   if (FS.Skip) {
1658     FS.Skip = false;
1659     return OS;
1660   }
1661   return OS << FS.Sep;
1662 }
1663 
1664 struct MDFieldPrinter {
1665   raw_ostream &Out;
1666   FieldSeparator FS;
1667   TypePrinting *TypePrinter = nullptr;
1668   SlotTracker *Machine = nullptr;
1669   const Module *Context = nullptr;
1670 
1671   explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
1672   MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1673                  SlotTracker *Machine, const Module *Context)
1674       : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1675   }
1676 
1677   void printTag(const DINode *N);
1678   void printMacinfoType(const DIMacroNode *N);
1679   void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1680   void printString(StringRef Name, StringRef Value,
1681                    bool ShouldSkipEmpty = true);
1682   void printMetadata(StringRef Name, const Metadata *MD,
1683                      bool ShouldSkipNull = true);
1684   template <class IntTy>
1685   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1686   void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1687                   bool ShouldSkipZero);
1688   void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1689   void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1690   void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1691   template <class IntTy, class Stringifier>
1692   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1693                       bool ShouldSkipZero = true);
1694   void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1695   void printNameTableKind(StringRef Name,
1696                           DICompileUnit::DebugNameTableKind NTK);
1697 };
1698 
1699 } // end anonymous namespace
1700 
1701 void MDFieldPrinter::printTag(const DINode *N) {
1702   Out << FS << "tag: ";
1703   auto Tag = dwarf::TagString(N->getTag());
1704   if (!Tag.empty())
1705     Out << Tag;
1706   else
1707     Out << N->getTag();
1708 }
1709 
1710 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1711   Out << FS << "type: ";
1712   auto Type = dwarf::MacinfoString(N->getMacinfoType());
1713   if (!Type.empty())
1714     Out << Type;
1715   else
1716     Out << N->getMacinfoType();
1717 }
1718 
1719 void MDFieldPrinter::printChecksum(
1720     const DIFile::ChecksumInfo<StringRef> &Checksum) {
1721   Out << FS << "checksumkind: " << Checksum.getKindAsString();
1722   printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1723 }
1724 
1725 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1726                                  bool ShouldSkipEmpty) {
1727   if (ShouldSkipEmpty && Value.empty())
1728     return;
1729 
1730   Out << FS << Name << ": \"";
1731   printEscapedString(Value, Out);
1732   Out << "\"";
1733 }
1734 
1735 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1736                                    TypePrinting *TypePrinter,
1737                                    SlotTracker *Machine,
1738                                    const Module *Context) {
1739   if (!MD) {
1740     Out << "null";
1741     return;
1742   }
1743   WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1744 }
1745 
1746 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1747                                    bool ShouldSkipNull) {
1748   if (ShouldSkipNull && !MD)
1749     return;
1750 
1751   Out << FS << Name << ": ";
1752   writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1753 }
1754 
1755 template <class IntTy>
1756 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1757   if (ShouldSkipZero && !Int)
1758     return;
1759 
1760   Out << FS << Name << ": " << Int;
1761 }
1762 
1763 void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
1764                                 bool IsUnsigned, bool ShouldSkipZero) {
1765   if (ShouldSkipZero && Int.isNullValue())
1766     return;
1767 
1768   Out << FS << Name << ": ";
1769   Int.print(Out, !IsUnsigned);
1770 }
1771 
1772 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1773                                Optional<bool> Default) {
1774   if (Default && Value == *Default)
1775     return;
1776   Out << FS << Name << ": " << (Value ? "true" : "false");
1777 }
1778 
1779 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1780   if (!Flags)
1781     return;
1782 
1783   Out << FS << Name << ": ";
1784 
1785   SmallVector<DINode::DIFlags, 8> SplitFlags;
1786   auto Extra = DINode::splitFlags(Flags, SplitFlags);
1787 
1788   FieldSeparator FlagsFS(" | ");
1789   for (auto F : SplitFlags) {
1790     auto StringF = DINode::getFlagString(F);
1791     assert(!StringF.empty() && "Expected valid flag");
1792     Out << FlagsFS << StringF;
1793   }
1794   if (Extra || SplitFlags.empty())
1795     Out << FlagsFS << Extra;
1796 }
1797 
1798 void MDFieldPrinter::printDISPFlags(StringRef Name,
1799                                     DISubprogram::DISPFlags Flags) {
1800   // Always print this field, because no flags in the IR at all will be
1801   // interpreted as old-style isDefinition: true.
1802   Out << FS << Name << ": ";
1803 
1804   if (!Flags) {
1805     Out << 0;
1806     return;
1807   }
1808 
1809   SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
1810   auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
1811 
1812   FieldSeparator FlagsFS(" | ");
1813   for (auto F : SplitFlags) {
1814     auto StringF = DISubprogram::getFlagString(F);
1815     assert(!StringF.empty() && "Expected valid flag");
1816     Out << FlagsFS << StringF;
1817   }
1818   if (Extra || SplitFlags.empty())
1819     Out << FlagsFS << Extra;
1820 }
1821 
1822 void MDFieldPrinter::printEmissionKind(StringRef Name,
1823                                        DICompileUnit::DebugEmissionKind EK) {
1824   Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1825 }
1826 
1827 void MDFieldPrinter::printNameTableKind(StringRef Name,
1828                                         DICompileUnit::DebugNameTableKind NTK) {
1829   if (NTK == DICompileUnit::DebugNameTableKind::Default)
1830     return;
1831   Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1832 }
1833 
1834 template <class IntTy, class Stringifier>
1835 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1836                                     Stringifier toString, bool ShouldSkipZero) {
1837   if (!Value)
1838     return;
1839 
1840   Out << FS << Name << ": ";
1841   auto S = toString(Value);
1842   if (!S.empty())
1843     Out << S;
1844   else
1845     Out << Value;
1846 }
1847 
1848 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1849                                TypePrinting *TypePrinter, SlotTracker *Machine,
1850                                const Module *Context) {
1851   Out << "!GenericDINode(";
1852   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1853   Printer.printTag(N);
1854   Printer.printString("header", N->getHeader());
1855   if (N->getNumDwarfOperands()) {
1856     Out << Printer.FS << "operands: {";
1857     FieldSeparator IFS;
1858     for (auto &I : N->dwarf_operands()) {
1859       Out << IFS;
1860       writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1861     }
1862     Out << "}";
1863   }
1864   Out << ")";
1865 }
1866 
1867 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1868                             TypePrinting *TypePrinter, SlotTracker *Machine,
1869                             const Module *Context) {
1870   Out << "!DILocation(";
1871   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1872   // Always output the line, since 0 is a relevant and important value for it.
1873   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1874   Printer.printInt("column", DL->getColumn());
1875   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1876   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1877   Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1878                     /* Default */ false);
1879   Out << ")";
1880 }
1881 
1882 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1883                             TypePrinting *TypePrinter, SlotTracker *Machine,
1884                             const Module *Context) {
1885   Out << "!DISubrange(";
1886   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1887   if (auto *CE = N->getCount().dyn_cast<ConstantInt*>())
1888     Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false);
1889   else
1890     Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable *>(),
1891                           /*ShouldSkipNull */ true);
1892 
1893   // A lowerBound of constant 0 should not be skipped, since it is different
1894   // from an unspecified lower bound (= nullptr).
1895   auto *LBound = N->getRawLowerBound();
1896   if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
1897     auto *LV = cast<ConstantInt>(LE->getValue());
1898     Printer.printInt("lowerBound", LV->getSExtValue(),
1899                      /* ShouldSkipZero */ false);
1900   } else
1901     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1902 
1903   auto *UBound = N->getRawUpperBound();
1904   if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
1905     auto *UV = cast<ConstantInt>(UE->getValue());
1906     Printer.printInt("upperBound", UV->getSExtValue(),
1907                      /* ShouldSkipZero */ false);
1908   } else
1909     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1910 
1911   auto *Stride = N->getRawStride();
1912   if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
1913     auto *SV = cast<ConstantInt>(SE->getValue());
1914     Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
1915   } else
1916     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1917 
1918   Out << ")";
1919 }
1920 
1921 static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
1922                                    TypePrinting *TypePrinter,
1923                                    SlotTracker *Machine,
1924                                    const Module *Context) {
1925   Out << "!DIGenericSubrange(";
1926   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1927 
1928   auto IsConstant = [&](Metadata *Bound) -> bool {
1929     if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
1930       return BE->isSignedConstant();
1931     }
1932     return false;
1933   };
1934 
1935   auto GetConstant = [&](Metadata *Bound) -> int64_t {
1936     assert(IsConstant(Bound) && "Expected constant");
1937     auto *BE = dyn_cast_or_null<DIExpression>(Bound);
1938     return static_cast<int64_t>(BE->getElement(1));
1939   };
1940 
1941   auto *Count = N->getRawCountNode();
1942   if (IsConstant(Count))
1943     Printer.printInt("count", GetConstant(Count),
1944                      /* ShouldSkipZero */ false);
1945   else
1946     Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1947 
1948   auto *LBound = N->getRawLowerBound();
1949   if (IsConstant(LBound))
1950     Printer.printInt("lowerBound", GetConstant(LBound),
1951                      /* ShouldSkipZero */ false);
1952   else
1953     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1954 
1955   auto *UBound = N->getRawUpperBound();
1956   if (IsConstant(UBound))
1957     Printer.printInt("upperBound", GetConstant(UBound),
1958                      /* ShouldSkipZero */ false);
1959   else
1960     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1961 
1962   auto *Stride = N->getRawStride();
1963   if (IsConstant(Stride))
1964     Printer.printInt("stride", GetConstant(Stride),
1965                      /* ShouldSkipZero */ false);
1966   else
1967     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1968 
1969   Out << ")";
1970 }
1971 
1972 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1973                               TypePrinting *, SlotTracker *, const Module *) {
1974   Out << "!DIEnumerator(";
1975   MDFieldPrinter Printer(Out);
1976   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1977   Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
1978                      /*ShouldSkipZero=*/false);
1979   if (N->isUnsigned())
1980     Printer.printBool("isUnsigned", true);
1981   Out << ")";
1982 }
1983 
1984 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1985                              TypePrinting *, SlotTracker *, const Module *) {
1986   Out << "!DIBasicType(";
1987   MDFieldPrinter Printer(Out);
1988   if (N->getTag() != dwarf::DW_TAG_base_type)
1989     Printer.printTag(N);
1990   Printer.printString("name", N->getName());
1991   Printer.printInt("size", N->getSizeInBits());
1992   Printer.printInt("align", N->getAlignInBits());
1993   Printer.printDwarfEnum("encoding", N->getEncoding(),
1994                          dwarf::AttributeEncodingString);
1995   Printer.printDIFlags("flags", N->getFlags());
1996   Out << ")";
1997 }
1998 
1999 static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
2000                               TypePrinting *TypePrinter, SlotTracker *Machine,
2001                               const Module *Context) {
2002   Out << "!DIStringType(";
2003   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2004   if (N->getTag() != dwarf::DW_TAG_string_type)
2005     Printer.printTag(N);
2006   Printer.printString("name", N->getName());
2007   Printer.printMetadata("stringLength", N->getRawStringLength());
2008   Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
2009   Printer.printInt("size", N->getSizeInBits());
2010   Printer.printInt("align", N->getAlignInBits());
2011   Printer.printDwarfEnum("encoding", N->getEncoding(),
2012                          dwarf::AttributeEncodingString);
2013   Out << ")";
2014 }
2015 
2016 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2017                                TypePrinting *TypePrinter, SlotTracker *Machine,
2018                                const Module *Context) {
2019   Out << "!DIDerivedType(";
2020   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2021   Printer.printTag(N);
2022   Printer.printString("name", N->getName());
2023   Printer.printMetadata("scope", N->getRawScope());
2024   Printer.printMetadata("file", N->getRawFile());
2025   Printer.printInt("line", N->getLine());
2026   Printer.printMetadata("baseType", N->getRawBaseType(),
2027                         /* ShouldSkipNull */ false);
2028   Printer.printInt("size", N->getSizeInBits());
2029   Printer.printInt("align", N->getAlignInBits());
2030   Printer.printInt("offset", N->getOffsetInBits());
2031   Printer.printDIFlags("flags", N->getFlags());
2032   Printer.printMetadata("extraData", N->getRawExtraData());
2033   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2034     Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
2035                      /* ShouldSkipZero */ false);
2036   Out << ")";
2037 }
2038 
2039 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2040                                  TypePrinting *TypePrinter,
2041                                  SlotTracker *Machine, const Module *Context) {
2042   Out << "!DICompositeType(";
2043   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2044   Printer.printTag(N);
2045   Printer.printString("name", N->getName());
2046   Printer.printMetadata("scope", N->getRawScope());
2047   Printer.printMetadata("file", N->getRawFile());
2048   Printer.printInt("line", N->getLine());
2049   Printer.printMetadata("baseType", N->getRawBaseType());
2050   Printer.printInt("size", N->getSizeInBits());
2051   Printer.printInt("align", N->getAlignInBits());
2052   Printer.printInt("offset", N->getOffsetInBits());
2053   Printer.printDIFlags("flags", N->getFlags());
2054   Printer.printMetadata("elements", N->getRawElements());
2055   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
2056                          dwarf::LanguageString);
2057   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
2058   Printer.printMetadata("templateParams", N->getRawTemplateParams());
2059   Printer.printString("identifier", N->getIdentifier());
2060   Printer.printMetadata("discriminator", N->getRawDiscriminator());
2061   Printer.printMetadata("dataLocation", N->getRawDataLocation());
2062   Printer.printMetadata("associated", N->getRawAssociated());
2063   Printer.printMetadata("allocated", N->getRawAllocated());
2064   if (auto *RankConst = N->getRankConst())
2065     Printer.printInt("rank", RankConst->getSExtValue(),
2066                      /* ShouldSkipZero */ false);
2067   else
2068     Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2069   Out << ")";
2070 }
2071 
2072 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2073                                   TypePrinting *TypePrinter,
2074                                   SlotTracker *Machine, const Module *Context) {
2075   Out << "!DISubroutineType(";
2076   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2077   Printer.printDIFlags("flags", N->getFlags());
2078   Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
2079   Printer.printMetadata("types", N->getRawTypeArray(),
2080                         /* ShouldSkipNull */ false);
2081   Out << ")";
2082 }
2083 
2084 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
2085                         SlotTracker *, const Module *) {
2086   Out << "!DIFile(";
2087   MDFieldPrinter Printer(Out);
2088   Printer.printString("filename", N->getFilename(),
2089                       /* ShouldSkipEmpty */ false);
2090   Printer.printString("directory", N->getDirectory(),
2091                       /* ShouldSkipEmpty */ false);
2092   // Print all values for checksum together, or not at all.
2093   if (N->getChecksum())
2094     Printer.printChecksum(*N->getChecksum());
2095   Printer.printString("source", N->getSource().getValueOr(StringRef()),
2096                       /* ShouldSkipEmpty */ true);
2097   Out << ")";
2098 }
2099 
2100 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2101                                TypePrinting *TypePrinter, SlotTracker *Machine,
2102                                const Module *Context) {
2103   Out << "!DICompileUnit(";
2104   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2105   Printer.printDwarfEnum("language", N->getSourceLanguage(),
2106                          dwarf::LanguageString, /* ShouldSkipZero */ false);
2107   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2108   Printer.printString("producer", N->getProducer());
2109   Printer.printBool("isOptimized", N->isOptimized());
2110   Printer.printString("flags", N->getFlags());
2111   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
2112                    /* ShouldSkipZero */ false);
2113   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
2114   Printer.printEmissionKind("emissionKind", N->getEmissionKind());
2115   Printer.printMetadata("enums", N->getRawEnumTypes());
2116   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
2117   Printer.printMetadata("globals", N->getRawGlobalVariables());
2118   Printer.printMetadata("imports", N->getRawImportedEntities());
2119   Printer.printMetadata("macros", N->getRawMacros());
2120   Printer.printInt("dwoId", N->getDWOId());
2121   Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
2122   Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
2123                     false);
2124   Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
2125   Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
2126   Printer.printString("sysroot", N->getSysRoot());
2127   Printer.printString("sdk", N->getSDK());
2128   Out << ")";
2129 }
2130 
2131 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2132                               TypePrinting *TypePrinter, SlotTracker *Machine,
2133                               const Module *Context) {
2134   Out << "!DISubprogram(";
2135   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2136   Printer.printString("name", N->getName());
2137   Printer.printString("linkageName", N->getLinkageName());
2138   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2139   Printer.printMetadata("file", N->getRawFile());
2140   Printer.printInt("line", N->getLine());
2141   Printer.printMetadata("type", N->getRawType());
2142   Printer.printInt("scopeLine", N->getScopeLine());
2143   Printer.printMetadata("containingType", N->getRawContainingType());
2144   if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
2145       N->getVirtualIndex() != 0)
2146     Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
2147   Printer.printInt("thisAdjustment", N->getThisAdjustment());
2148   Printer.printDIFlags("flags", N->getFlags());
2149   Printer.printDISPFlags("spFlags", N->getSPFlags());
2150   Printer.printMetadata("unit", N->getRawUnit());
2151   Printer.printMetadata("templateParams", N->getRawTemplateParams());
2152   Printer.printMetadata("declaration", N->getRawDeclaration());
2153   Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
2154   Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2155   Out << ")";
2156 }
2157 
2158 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2159                                 TypePrinting *TypePrinter, SlotTracker *Machine,
2160                                 const Module *Context) {
2161   Out << "!DILexicalBlock(";
2162   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2163   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2164   Printer.printMetadata("file", N->getRawFile());
2165   Printer.printInt("line", N->getLine());
2166   Printer.printInt("column", N->getColumn());
2167   Out << ")";
2168 }
2169 
2170 static void writeDILexicalBlockFile(raw_ostream &Out,
2171                                     const DILexicalBlockFile *N,
2172                                     TypePrinting *TypePrinter,
2173                                     SlotTracker *Machine,
2174                                     const Module *Context) {
2175   Out << "!DILexicalBlockFile(";
2176   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2177   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2178   Printer.printMetadata("file", N->getRawFile());
2179   Printer.printInt("discriminator", N->getDiscriminator(),
2180                    /* ShouldSkipZero */ false);
2181   Out << ")";
2182 }
2183 
2184 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2185                              TypePrinting *TypePrinter, SlotTracker *Machine,
2186                              const Module *Context) {
2187   Out << "!DINamespace(";
2188   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2189   Printer.printString("name", N->getName());
2190   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2191   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2192   Out << ")";
2193 }
2194 
2195 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2196                                TypePrinting *TypePrinter, SlotTracker *Machine,
2197                                const Module *Context) {
2198   Out << "!DICommonBlock(";
2199   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2200   Printer.printMetadata("scope", N->getRawScope(), false);
2201   Printer.printMetadata("declaration", N->getRawDecl(), false);
2202   Printer.printString("name", N->getName());
2203   Printer.printMetadata("file", N->getRawFile());
2204   Printer.printInt("line", N->getLineNo());
2205   Out << ")";
2206 }
2207 
2208 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2209                          TypePrinting *TypePrinter, SlotTracker *Machine,
2210                          const Module *Context) {
2211   Out << "!DIMacro(";
2212   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2213   Printer.printMacinfoType(N);
2214   Printer.printInt("line", N->getLine());
2215   Printer.printString("name", N->getName());
2216   Printer.printString("value", N->getValue());
2217   Out << ")";
2218 }
2219 
2220 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2221                              TypePrinting *TypePrinter, SlotTracker *Machine,
2222                              const Module *Context) {
2223   Out << "!DIMacroFile(";
2224   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2225   Printer.printInt("line", N->getLine());
2226   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2227   Printer.printMetadata("nodes", N->getRawElements());
2228   Out << ")";
2229 }
2230 
2231 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2232                           TypePrinting *TypePrinter, SlotTracker *Machine,
2233                           const Module *Context) {
2234   Out << "!DIModule(";
2235   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2236   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2237   Printer.printString("name", N->getName());
2238   Printer.printString("configMacros", N->getConfigurationMacros());
2239   Printer.printString("includePath", N->getIncludePath());
2240   Printer.printString("apinotes", N->getAPINotesFile());
2241   Printer.printMetadata("file", N->getRawFile());
2242   Printer.printInt("line", N->getLineNo());
2243   Out << ")";
2244 }
2245 
2246 
2247 static void writeDITemplateTypeParameter(raw_ostream &Out,
2248                                          const DITemplateTypeParameter *N,
2249                                          TypePrinting *TypePrinter,
2250                                          SlotTracker *Machine,
2251                                          const Module *Context) {
2252   Out << "!DITemplateTypeParameter(";
2253   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2254   Printer.printString("name", N->getName());
2255   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2256   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2257   Out << ")";
2258 }
2259 
2260 static void writeDITemplateValueParameter(raw_ostream &Out,
2261                                           const DITemplateValueParameter *N,
2262                                           TypePrinting *TypePrinter,
2263                                           SlotTracker *Machine,
2264                                           const Module *Context) {
2265   Out << "!DITemplateValueParameter(";
2266   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2267   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2268     Printer.printTag(N);
2269   Printer.printString("name", N->getName());
2270   Printer.printMetadata("type", N->getRawType());
2271   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2272   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2273   Out << ")";
2274 }
2275 
2276 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2277                                   TypePrinting *TypePrinter,
2278                                   SlotTracker *Machine, const Module *Context) {
2279   Out << "!DIGlobalVariable(";
2280   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2281   Printer.printString("name", N->getName());
2282   Printer.printString("linkageName", N->getLinkageName());
2283   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2284   Printer.printMetadata("file", N->getRawFile());
2285   Printer.printInt("line", N->getLine());
2286   Printer.printMetadata("type", N->getRawType());
2287   Printer.printBool("isLocal", N->isLocalToUnit());
2288   Printer.printBool("isDefinition", N->isDefinition());
2289   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2290   Printer.printMetadata("templateParams", N->getRawTemplateParams());
2291   Printer.printInt("align", N->getAlignInBits());
2292   Out << ")";
2293 }
2294 
2295 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2296                                  TypePrinting *TypePrinter,
2297                                  SlotTracker *Machine, const Module *Context) {
2298   Out << "!DILocalVariable(";
2299   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2300   Printer.printString("name", N->getName());
2301   Printer.printInt("arg", N->getArg());
2302   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2303   Printer.printMetadata("file", N->getRawFile());
2304   Printer.printInt("line", N->getLine());
2305   Printer.printMetadata("type", N->getRawType());
2306   Printer.printDIFlags("flags", N->getFlags());
2307   Printer.printInt("align", N->getAlignInBits());
2308   Out << ")";
2309 }
2310 
2311 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2312                          TypePrinting *TypePrinter,
2313                          SlotTracker *Machine, const Module *Context) {
2314   Out << "!DILabel(";
2315   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2316   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2317   Printer.printString("name", N->getName());
2318   Printer.printMetadata("file", N->getRawFile());
2319   Printer.printInt("line", N->getLine());
2320   Out << ")";
2321 }
2322 
2323 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2324                               TypePrinting *TypePrinter, SlotTracker *Machine,
2325                               const Module *Context) {
2326   Out << "!DIExpression(";
2327   FieldSeparator FS;
2328   if (N->isValid()) {
2329     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
2330       auto OpStr = dwarf::OperationEncodingString(I->getOp());
2331       assert(!OpStr.empty() && "Expected valid opcode");
2332 
2333       Out << FS << OpStr;
2334       if (I->getOp() == dwarf::DW_OP_LLVM_convert) {
2335         Out << FS << I->getArg(0);
2336         Out << FS << dwarf::AttributeEncodingString(I->getArg(1));
2337       } else {
2338         for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
2339           Out << FS << I->getArg(A);
2340       }
2341     }
2342   } else {
2343     for (const auto &I : N->getElements())
2344       Out << FS << I;
2345   }
2346   Out << ")";
2347 }
2348 
2349 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2350                                             const DIGlobalVariableExpression *N,
2351                                             TypePrinting *TypePrinter,
2352                                             SlotTracker *Machine,
2353                                             const Module *Context) {
2354   Out << "!DIGlobalVariableExpression(";
2355   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2356   Printer.printMetadata("var", N->getVariable());
2357   Printer.printMetadata("expr", N->getExpression());
2358   Out << ")";
2359 }
2360 
2361 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2362                                 TypePrinting *TypePrinter, SlotTracker *Machine,
2363                                 const Module *Context) {
2364   Out << "!DIObjCProperty(";
2365   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2366   Printer.printString("name", N->getName());
2367   Printer.printMetadata("file", N->getRawFile());
2368   Printer.printInt("line", N->getLine());
2369   Printer.printString("setter", N->getSetterName());
2370   Printer.printString("getter", N->getGetterName());
2371   Printer.printInt("attributes", N->getAttributes());
2372   Printer.printMetadata("type", N->getRawType());
2373   Out << ")";
2374 }
2375 
2376 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2377                                   TypePrinting *TypePrinter,
2378                                   SlotTracker *Machine, const Module *Context) {
2379   Out << "!DIImportedEntity(";
2380   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2381   Printer.printTag(N);
2382   Printer.printString("name", N->getName());
2383   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2384   Printer.printMetadata("entity", N->getRawEntity());
2385   Printer.printMetadata("file", N->getRawFile());
2386   Printer.printInt("line", N->getLine());
2387   Out << ")";
2388 }
2389 
2390 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2391                                     TypePrinting *TypePrinter,
2392                                     SlotTracker *Machine,
2393                                     const Module *Context) {
2394   if (Node->isDistinct())
2395     Out << "distinct ";
2396   else if (Node->isTemporary())
2397     Out << "<temporary!> "; // Handle broken code.
2398 
2399   switch (Node->getMetadataID()) {
2400   default:
2401     llvm_unreachable("Expected uniquable MDNode");
2402 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
2403   case Metadata::CLASS##Kind:                                                  \
2404     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
2405     break;
2406 #include "llvm/IR/Metadata.def"
2407   }
2408 }
2409 
2410 // Full implementation of printing a Value as an operand with support for
2411 // TypePrinting, etc.
2412 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2413                                    TypePrinting *TypePrinter,
2414                                    SlotTracker *Machine,
2415                                    const Module *Context) {
2416   if (V->hasName()) {
2417     PrintLLVMName(Out, V);
2418     return;
2419   }
2420 
2421   const Constant *CV = dyn_cast<Constant>(V);
2422   if (CV && !isa<GlobalValue>(CV)) {
2423     assert(TypePrinter && "Constants require TypePrinting!");
2424     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
2425     return;
2426   }
2427 
2428   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2429     Out << "asm ";
2430     if (IA->hasSideEffects())
2431       Out << "sideeffect ";
2432     if (IA->isAlignStack())
2433       Out << "alignstack ";
2434     // We don't emit the AD_ATT dialect as it's the assumed default.
2435     if (IA->getDialect() == InlineAsm::AD_Intel)
2436       Out << "inteldialect ";
2437     Out << '"';
2438     printEscapedString(IA->getAsmString(), Out);
2439     Out << "\", \"";
2440     printEscapedString(IA->getConstraintString(), Out);
2441     Out << '"';
2442     return;
2443   }
2444 
2445   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2446     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
2447                            Context, /* FromValue */ true);
2448     return;
2449   }
2450 
2451   char Prefix = '%';
2452   int Slot;
2453   // If we have a SlotTracker, use it.
2454   if (Machine) {
2455     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2456       Slot = Machine->getGlobalSlot(GV);
2457       Prefix = '@';
2458     } else {
2459       Slot = Machine->getLocalSlot(V);
2460 
2461       // If the local value didn't succeed, then we may be referring to a value
2462       // from a different function.  Translate it, as this can happen when using
2463       // address of blocks.
2464       if (Slot == -1)
2465         if ((Machine = createSlotTracker(V))) {
2466           Slot = Machine->getLocalSlot(V);
2467           delete Machine;
2468         }
2469     }
2470   } else if ((Machine = createSlotTracker(V))) {
2471     // Otherwise, create one to get the # and then destroy it.
2472     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2473       Slot = Machine->getGlobalSlot(GV);
2474       Prefix = '@';
2475     } else {
2476       Slot = Machine->getLocalSlot(V);
2477     }
2478     delete Machine;
2479     Machine = nullptr;
2480   } else {
2481     Slot = -1;
2482   }
2483 
2484   if (Slot != -1)
2485     Out << Prefix << Slot;
2486   else
2487     Out << "<badref>";
2488 }
2489 
2490 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2491                                    TypePrinting *TypePrinter,
2492                                    SlotTracker *Machine, const Module *Context,
2493                                    bool FromValue) {
2494   // Write DIExpressions inline when used as a value. Improves readability of
2495   // debug info intrinsics.
2496   if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2497     writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
2498     return;
2499   }
2500 
2501   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2502     std::unique_ptr<SlotTracker> MachineStorage;
2503     if (!Machine) {
2504       MachineStorage = std::make_unique<SlotTracker>(Context);
2505       Machine = MachineStorage.get();
2506     }
2507     int Slot = Machine->getMetadataSlot(N);
2508     if (Slot == -1) {
2509       if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2510         writeDILocation(Out, Loc, TypePrinter, Machine, Context);
2511         return;
2512       }
2513       // Give the pointer value instead of "badref", since this comes up all
2514       // the time when debugging.
2515       Out << "<" << N << ">";
2516     } else
2517       Out << '!' << Slot;
2518     return;
2519   }
2520 
2521   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2522     Out << "!\"";
2523     printEscapedString(MDS->getString(), Out);
2524     Out << '"';
2525     return;
2526   }
2527 
2528   auto *V = cast<ValueAsMetadata>(MD);
2529   assert(TypePrinter && "TypePrinter required for metadata values");
2530   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2531          "Unexpected function-local metadata outside of value argument");
2532 
2533   TypePrinter->print(V->getValue()->getType(), Out);
2534   Out << ' ';
2535   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2536 }
2537 
2538 namespace {
2539 
2540 class AssemblyWriter {
2541   formatted_raw_ostream &Out;
2542   const Module *TheModule = nullptr;
2543   const ModuleSummaryIndex *TheIndex = nullptr;
2544   std::unique_ptr<SlotTracker> SlotTrackerStorage;
2545   SlotTracker &Machine;
2546   TypePrinting TypePrinter;
2547   AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2548   SetVector<const Comdat *> Comdats;
2549   bool IsForDebug;
2550   bool ShouldPreserveUseListOrder;
2551   UseListOrderStack UseListOrders;
2552   SmallVector<StringRef, 8> MDNames;
2553   /// Synchronization scope names registered with LLVMContext.
2554   SmallVector<StringRef, 8> SSNs;
2555   DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
2556 
2557 public:
2558   /// Construct an AssemblyWriter with an external SlotTracker
2559   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2560                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2561                  bool ShouldPreserveUseListOrder = false);
2562 
2563   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2564                  const ModuleSummaryIndex *Index, bool IsForDebug);
2565 
2566   void printMDNodeBody(const MDNode *MD);
2567   void printNamedMDNode(const NamedMDNode *NMD);
2568 
2569   void printModule(const Module *M);
2570 
2571   void writeOperand(const Value *Op, bool PrintType);
2572   void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2573   void writeOperandBundles(const CallBase *Call);
2574   void writeSyncScope(const LLVMContext &Context,
2575                       SyncScope::ID SSID);
2576   void writeAtomic(const LLVMContext &Context,
2577                    AtomicOrdering Ordering,
2578                    SyncScope::ID SSID);
2579   void writeAtomicCmpXchg(const LLVMContext &Context,
2580                           AtomicOrdering SuccessOrdering,
2581                           AtomicOrdering FailureOrdering,
2582                           SyncScope::ID SSID);
2583 
2584   void writeAllMDNodes();
2585   void writeMDNode(unsigned Slot, const MDNode *Node);
2586   void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
2587   void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
2588   void writeAllAttributeGroups();
2589 
2590   void printTypeIdentities();
2591   void printGlobal(const GlobalVariable *GV);
2592   void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2593   void printComdat(const Comdat *C);
2594   void printFunction(const Function *F);
2595   void printArgument(const Argument *FA, AttributeSet Attrs);
2596   void printBasicBlock(const BasicBlock *BB);
2597   void printInstructionLine(const Instruction &I);
2598   void printInstruction(const Instruction &I);
2599 
2600   void printUseListOrder(const UseListOrder &Order);
2601   void printUseLists(const Function *F);
2602 
2603   void printModuleSummaryIndex();
2604   void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2605   void printSummary(const GlobalValueSummary &Summary);
2606   void printAliasSummary(const AliasSummary *AS);
2607   void printGlobalVarSummary(const GlobalVarSummary *GS);
2608   void printFunctionSummary(const FunctionSummary *FS);
2609   void printTypeIdSummary(const TypeIdSummary &TIS);
2610   void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
2611   void printTypeTestResolution(const TypeTestResolution &TTRes);
2612   void printArgs(const std::vector<uint64_t> &Args);
2613   void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2614   void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2615   void printVFuncId(const FunctionSummary::VFuncId VFId);
2616   void
2617   printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
2618                       const char *Tag);
2619   void
2620   printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
2621                    const char *Tag);
2622 
2623 private:
2624   /// Print out metadata attachments.
2625   void printMetadataAttachments(
2626       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2627       StringRef Separator);
2628 
2629   // printInfoComment - Print a little comment after the instruction indicating
2630   // which slot it occupies.
2631   void printInfoComment(const Value &V);
2632 
2633   // printGCRelocateComment - print comment after call to the gc.relocate
2634   // intrinsic indicating base and derived pointer names.
2635   void printGCRelocateComment(const GCRelocateInst &Relocate);
2636 };
2637 
2638 } // end anonymous namespace
2639 
2640 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2641                                const Module *M, AssemblyAnnotationWriter *AAW,
2642                                bool IsForDebug, bool ShouldPreserveUseListOrder)
2643     : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2644       IsForDebug(IsForDebug),
2645       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2646   if (!TheModule)
2647     return;
2648   for (const GlobalObject &GO : TheModule->global_objects())
2649     if (const Comdat *C = GO.getComdat())
2650       Comdats.insert(C);
2651 }
2652 
2653 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2654                                const ModuleSummaryIndex *Index, bool IsForDebug)
2655     : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2656       IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2657 
2658 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2659   if (!Operand) {
2660     Out << "<null operand!>";
2661     return;
2662   }
2663   if (PrintType) {
2664     TypePrinter.print(Operand->getType(), Out);
2665     Out << ' ';
2666   }
2667   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2668 }
2669 
2670 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2671                                     SyncScope::ID SSID) {
2672   switch (SSID) {
2673   case SyncScope::System: {
2674     break;
2675   }
2676   default: {
2677     if (SSNs.empty())
2678       Context.getSyncScopeNames(SSNs);
2679 
2680     Out << " syncscope(\"";
2681     printEscapedString(SSNs[SSID], Out);
2682     Out << "\")";
2683     break;
2684   }
2685   }
2686 }
2687 
2688 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2689                                  AtomicOrdering Ordering,
2690                                  SyncScope::ID SSID) {
2691   if (Ordering == AtomicOrdering::NotAtomic)
2692     return;
2693 
2694   writeSyncScope(Context, SSID);
2695   Out << " " << toIRString(Ordering);
2696 }
2697 
2698 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2699                                         AtomicOrdering SuccessOrdering,
2700                                         AtomicOrdering FailureOrdering,
2701                                         SyncScope::ID SSID) {
2702   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2703          FailureOrdering != AtomicOrdering::NotAtomic);
2704 
2705   writeSyncScope(Context, SSID);
2706   Out << " " << toIRString(SuccessOrdering);
2707   Out << " " << toIRString(FailureOrdering);
2708 }
2709 
2710 void AssemblyWriter::writeParamOperand(const Value *Operand,
2711                                        AttributeSet Attrs) {
2712   if (!Operand) {
2713     Out << "<null operand!>";
2714     return;
2715   }
2716 
2717   // Print the type
2718   TypePrinter.print(Operand->getType(), Out);
2719   // Print parameter attributes list
2720   if (Attrs.hasAttributes()) {
2721     Out << ' ';
2722     writeAttributeSet(Attrs);
2723   }
2724   Out << ' ';
2725   // Print the operand
2726   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2727 }
2728 
2729 void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
2730   if (!Call->hasOperandBundles())
2731     return;
2732 
2733   Out << " [ ";
2734 
2735   bool FirstBundle = true;
2736   for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
2737     OperandBundleUse BU = Call->getOperandBundleAt(i);
2738 
2739     if (!FirstBundle)
2740       Out << ", ";
2741     FirstBundle = false;
2742 
2743     Out << '"';
2744     printEscapedString(BU.getTagName(), Out);
2745     Out << '"';
2746 
2747     Out << '(';
2748 
2749     bool FirstInput = true;
2750     for (const auto &Input : BU.Inputs) {
2751       if (!FirstInput)
2752         Out << ", ";
2753       FirstInput = false;
2754 
2755       TypePrinter.print(Input->getType(), Out);
2756       Out << " ";
2757       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2758     }
2759 
2760     Out << ')';
2761   }
2762 
2763   Out << " ]";
2764 }
2765 
2766 void AssemblyWriter::printModule(const Module *M) {
2767   Machine.initializeIfNeeded();
2768 
2769   if (ShouldPreserveUseListOrder)
2770     UseListOrders = predictUseListOrder(M);
2771 
2772   if (!M->getModuleIdentifier().empty() &&
2773       // Don't print the ID if it will start a new line (which would
2774       // require a comment char before it).
2775       M->getModuleIdentifier().find('\n') == std::string::npos)
2776     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2777 
2778   if (!M->getSourceFileName().empty()) {
2779     Out << "source_filename = \"";
2780     printEscapedString(M->getSourceFileName(), Out);
2781     Out << "\"\n";
2782   }
2783 
2784   const std::string &DL = M->getDataLayoutStr();
2785   if (!DL.empty())
2786     Out << "target datalayout = \"" << DL << "\"\n";
2787   if (!M->getTargetTriple().empty())
2788     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2789 
2790   if (!M->getModuleInlineAsm().empty()) {
2791     Out << '\n';
2792 
2793     // Split the string into lines, to make it easier to read the .ll file.
2794     StringRef Asm = M->getModuleInlineAsm();
2795     do {
2796       StringRef Front;
2797       std::tie(Front, Asm) = Asm.split('\n');
2798 
2799       // We found a newline, print the portion of the asm string from the
2800       // last newline up to this newline.
2801       Out << "module asm \"";
2802       printEscapedString(Front, Out);
2803       Out << "\"\n";
2804     } while (!Asm.empty());
2805   }
2806 
2807   printTypeIdentities();
2808 
2809   // Output all comdats.
2810   if (!Comdats.empty())
2811     Out << '\n';
2812   for (const Comdat *C : Comdats) {
2813     printComdat(C);
2814     if (C != Comdats.back())
2815       Out << '\n';
2816   }
2817 
2818   // Output all globals.
2819   if (!M->global_empty()) Out << '\n';
2820   for (const GlobalVariable &GV : M->globals()) {
2821     printGlobal(&GV); Out << '\n';
2822   }
2823 
2824   // Output all aliases.
2825   if (!M->alias_empty()) Out << "\n";
2826   for (const GlobalAlias &GA : M->aliases())
2827     printIndirectSymbol(&GA);
2828 
2829   // Output all ifuncs.
2830   if (!M->ifunc_empty()) Out << "\n";
2831   for (const GlobalIFunc &GI : M->ifuncs())
2832     printIndirectSymbol(&GI);
2833 
2834   // Output global use-lists.
2835   printUseLists(nullptr);
2836 
2837   // Output all of the functions.
2838   for (const Function &F : *M) {
2839     Out << '\n';
2840     printFunction(&F);
2841   }
2842   assert(UseListOrders.empty() && "All use-lists should have been consumed");
2843 
2844   // Output all attribute groups.
2845   if (!Machine.as_empty()) {
2846     Out << '\n';
2847     writeAllAttributeGroups();
2848   }
2849 
2850   // Output named metadata.
2851   if (!M->named_metadata_empty()) Out << '\n';
2852 
2853   for (const NamedMDNode &Node : M->named_metadata())
2854     printNamedMDNode(&Node);
2855 
2856   // Output metadata.
2857   if (!Machine.mdn_empty()) {
2858     Out << '\n';
2859     writeAllMDNodes();
2860   }
2861 }
2862 
2863 void AssemblyWriter::printModuleSummaryIndex() {
2864   assert(TheIndex);
2865   int NumSlots = Machine.initializeIndexIfNeeded();
2866 
2867   Out << "\n";
2868 
2869   // Print module path entries. To print in order, add paths to a vector
2870   // indexed by module slot.
2871   std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2872   std::string RegularLTOModuleName =
2873       ModuleSummaryIndex::getRegularLTOModuleName();
2874   moduleVec.resize(TheIndex->modulePaths().size());
2875   for (auto &ModPath : TheIndex->modulePaths())
2876     moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2877         // A module id of -1 is a special entry for a regular LTO module created
2878         // during the thin link.
2879         ModPath.second.first == -1u ? RegularLTOModuleName
2880                                     : (std::string)std::string(ModPath.first()),
2881         ModPath.second.second);
2882 
2883   unsigned i = 0;
2884   for (auto &ModPair : moduleVec) {
2885     Out << "^" << i++ << " = module: (";
2886     Out << "path: \"";
2887     printEscapedString(ModPair.first, Out);
2888     Out << "\", hash: (";
2889     FieldSeparator FS;
2890     for (auto Hash : ModPair.second)
2891       Out << FS << Hash;
2892     Out << "))\n";
2893   }
2894 
2895   // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2896   // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2897   for (auto &GlobalList : *TheIndex) {
2898     auto GUID = GlobalList.first;
2899     for (auto &Summary : GlobalList.second.SummaryList)
2900       SummaryToGUIDMap[Summary.get()] = GUID;
2901   }
2902 
2903   // Print the global value summary entries.
2904   for (auto &GlobalList : *TheIndex) {
2905     auto GUID = GlobalList.first;
2906     auto VI = TheIndex->getValueInfo(GlobalList);
2907     printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2908   }
2909 
2910   // Print the TypeIdMap entries.
2911   for (auto TidIter = TheIndex->typeIds().begin();
2912        TidIter != TheIndex->typeIds().end(); TidIter++) {
2913     Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
2914         << " = typeid: (name: \"" << TidIter->second.first << "\"";
2915     printTypeIdSummary(TidIter->second.second);
2916     Out << ") ; guid = " << TidIter->first << "\n";
2917   }
2918 
2919   // Print the TypeIdCompatibleVtableMap entries.
2920   for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
2921     auto GUID = GlobalValue::getGUID(TId.first);
2922     Out << "^" << Machine.getGUIDSlot(GUID)
2923         << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
2924     printTypeIdCompatibleVtableSummary(TId.second);
2925     Out << ") ; guid = " << GUID << "\n";
2926   }
2927 
2928   // Don't emit flags when it's not really needed (value is zero by default).
2929   if (TheIndex->getFlags()) {
2930     Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
2931     ++NumSlots;
2932   }
2933 
2934   Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
2935       << "\n";
2936 }
2937 
2938 static const char *
2939 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2940   switch (K) {
2941   case WholeProgramDevirtResolution::Indir:
2942     return "indir";
2943   case WholeProgramDevirtResolution::SingleImpl:
2944     return "singleImpl";
2945   case WholeProgramDevirtResolution::BranchFunnel:
2946     return "branchFunnel";
2947   }
2948   llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2949 }
2950 
2951 static const char *getWholeProgDevirtResByArgKindName(
2952     WholeProgramDevirtResolution::ByArg::Kind K) {
2953   switch (K) {
2954   case WholeProgramDevirtResolution::ByArg::Indir:
2955     return "indir";
2956   case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2957     return "uniformRetVal";
2958   case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2959     return "uniqueRetVal";
2960   case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2961     return "virtualConstProp";
2962   }
2963   llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2964 }
2965 
2966 static const char *getTTResKindName(TypeTestResolution::Kind K) {
2967   switch (K) {
2968   case TypeTestResolution::Unknown:
2969     return "unknown";
2970   case TypeTestResolution::Unsat:
2971     return "unsat";
2972   case TypeTestResolution::ByteArray:
2973     return "byteArray";
2974   case TypeTestResolution::Inline:
2975     return "inline";
2976   case TypeTestResolution::Single:
2977     return "single";
2978   case TypeTestResolution::AllOnes:
2979     return "allOnes";
2980   }
2981   llvm_unreachable("invalid TypeTestResolution kind");
2982 }
2983 
2984 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2985   Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2986       << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2987 
2988   // The following fields are only used if the target does not support the use
2989   // of absolute symbols to store constants. Print only if non-zero.
2990   if (TTRes.AlignLog2)
2991     Out << ", alignLog2: " << TTRes.AlignLog2;
2992   if (TTRes.SizeM1)
2993     Out << ", sizeM1: " << TTRes.SizeM1;
2994   if (TTRes.BitMask)
2995     // BitMask is uint8_t which causes it to print the corresponding char.
2996     Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2997   if (TTRes.InlineBits)
2998     Out << ", inlineBits: " << TTRes.InlineBits;
2999 
3000   Out << ")";
3001 }
3002 
3003 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
3004   Out << ", summary: (";
3005   printTypeTestResolution(TIS.TTRes);
3006   if (!TIS.WPDRes.empty()) {
3007     Out << ", wpdResolutions: (";
3008     FieldSeparator FS;
3009     for (auto &WPDRes : TIS.WPDRes) {
3010       Out << FS;
3011       Out << "(offset: " << WPDRes.first << ", ";
3012       printWPDRes(WPDRes.second);
3013       Out << ")";
3014     }
3015     Out << ")";
3016   }
3017   Out << ")";
3018 }
3019 
3020 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3021     const TypeIdCompatibleVtableInfo &TI) {
3022   Out << ", summary: (";
3023   FieldSeparator FS;
3024   for (auto &P : TI) {
3025     Out << FS;
3026     Out << "(offset: " << P.AddressPointOffset << ", ";
3027     Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
3028     Out << ")";
3029   }
3030   Out << ")";
3031 }
3032 
3033 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
3034   Out << "args: (";
3035   FieldSeparator FS;
3036   for (auto arg : Args) {
3037     Out << FS;
3038     Out << arg;
3039   }
3040   Out << ")";
3041 }
3042 
3043 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
3044   Out << "wpdRes: (kind: ";
3045   Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
3046 
3047   if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
3048     Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
3049 
3050   if (!WPDRes.ResByArg.empty()) {
3051     Out << ", resByArg: (";
3052     FieldSeparator FS;
3053     for (auto &ResByArg : WPDRes.ResByArg) {
3054       Out << FS;
3055       printArgs(ResByArg.first);
3056       Out << ", byArg: (kind: ";
3057       Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
3058       if (ResByArg.second.TheKind ==
3059               WholeProgramDevirtResolution::ByArg::UniformRetVal ||
3060           ResByArg.second.TheKind ==
3061               WholeProgramDevirtResolution::ByArg::UniqueRetVal)
3062         Out << ", info: " << ResByArg.second.Info;
3063 
3064       // The following fields are only used if the target does not support the
3065       // use of absolute symbols to store constants. Print only if non-zero.
3066       if (ResByArg.second.Byte || ResByArg.second.Bit)
3067         Out << ", byte: " << ResByArg.second.Byte
3068             << ", bit: " << ResByArg.second.Bit;
3069 
3070       Out << ")";
3071     }
3072     Out << ")";
3073   }
3074   Out << ")";
3075 }
3076 
3077 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
3078   switch (SK) {
3079   case GlobalValueSummary::AliasKind:
3080     return "alias";
3081   case GlobalValueSummary::FunctionKind:
3082     return "function";
3083   case GlobalValueSummary::GlobalVarKind:
3084     return "variable";
3085   }
3086   llvm_unreachable("invalid summary kind");
3087 }
3088 
3089 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
3090   Out << ", aliasee: ";
3091   // The indexes emitted for distributed backends may not include the
3092   // aliasee summary (only if it is being imported directly). Handle
3093   // that case by just emitting "null" as the aliasee.
3094   if (AS->hasAliasee())
3095     Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
3096   else
3097     Out << "null";
3098 }
3099 
3100 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
3101   auto VTableFuncs = GS->vTableFuncs();
3102   Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
3103       << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
3104       << "constant: " << GS->VarFlags.Constant;
3105   if (!VTableFuncs.empty())
3106     Out << ", "
3107         << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
3108   Out << ")";
3109 
3110   if (!VTableFuncs.empty()) {
3111     Out << ", vTableFuncs: (";
3112     FieldSeparator FS;
3113     for (auto &P : VTableFuncs) {
3114       Out << FS;
3115       Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
3116           << ", offset: " << P.VTableOffset;
3117       Out << ")";
3118     }
3119     Out << ")";
3120   }
3121 }
3122 
3123 static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
3124   switch (LT) {
3125   case GlobalValue::ExternalLinkage:
3126     return "external";
3127   case GlobalValue::PrivateLinkage:
3128     return "private";
3129   case GlobalValue::InternalLinkage:
3130     return "internal";
3131   case GlobalValue::LinkOnceAnyLinkage:
3132     return "linkonce";
3133   case GlobalValue::LinkOnceODRLinkage:
3134     return "linkonce_odr";
3135   case GlobalValue::WeakAnyLinkage:
3136     return "weak";
3137   case GlobalValue::WeakODRLinkage:
3138     return "weak_odr";
3139   case GlobalValue::CommonLinkage:
3140     return "common";
3141   case GlobalValue::AppendingLinkage:
3142     return "appending";
3143   case GlobalValue::ExternalWeakLinkage:
3144     return "extern_weak";
3145   case GlobalValue::AvailableExternallyLinkage:
3146     return "available_externally";
3147   }
3148   llvm_unreachable("invalid linkage");
3149 }
3150 
3151 // When printing the linkage types in IR where the ExternalLinkage is
3152 // not printed, and other linkage types are expected to be printed with
3153 // a space after the name.
3154 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
3155   if (LT == GlobalValue::ExternalLinkage)
3156     return "";
3157   return getLinkageName(LT) + " ";
3158 }
3159 
3160 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
3161   Out << ", insts: " << FS->instCount();
3162 
3163   FunctionSummary::FFlags FFlags = FS->fflags();
3164   if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
3165       FFlags.ReturnDoesNotAlias | FFlags.NoInline | FFlags.AlwaysInline) {
3166     Out << ", funcFlags: (";
3167     Out << "readNone: " << FFlags.ReadNone;
3168     Out << ", readOnly: " << FFlags.ReadOnly;
3169     Out << ", noRecurse: " << FFlags.NoRecurse;
3170     Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
3171     Out << ", noInline: " << FFlags.NoInline;
3172     Out << ", alwaysInline: " << FFlags.AlwaysInline;
3173     Out << ")";
3174   }
3175   if (!FS->calls().empty()) {
3176     Out << ", calls: (";
3177     FieldSeparator IFS;
3178     for (auto &Call : FS->calls()) {
3179       Out << IFS;
3180       Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
3181       if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
3182         Out << ", hotness: " << getHotnessName(Call.second.getHotness());
3183       else if (Call.second.RelBlockFreq)
3184         Out << ", relbf: " << Call.second.RelBlockFreq;
3185       Out << ")";
3186     }
3187     Out << ")";
3188   }
3189 
3190   if (const auto *TIdInfo = FS->getTypeIdInfo())
3191     printTypeIdInfo(*TIdInfo);
3192 
3193   auto PrintRange = [&](const ConstantRange &Range) {
3194     Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
3195   };
3196 
3197   if (!FS->paramAccesses().empty()) {
3198     Out << ", params: (";
3199     FieldSeparator IFS;
3200     for (auto &PS : FS->paramAccesses()) {
3201       Out << IFS;
3202       Out << "(param: " << PS.ParamNo;
3203       Out << ", offset: ";
3204       PrintRange(PS.Use);
3205       if (!PS.Calls.empty()) {
3206         Out << ", calls: (";
3207         FieldSeparator IFS;
3208         for (auto &Call : PS.Calls) {
3209           Out << IFS;
3210           Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
3211           Out << ", param: " << Call.ParamNo;
3212           Out << ", offset: ";
3213           PrintRange(Call.Offsets);
3214           Out << ")";
3215         }
3216         Out << ")";
3217       }
3218       Out << ")";
3219     }
3220     Out << ")";
3221   }
3222 }
3223 
3224 void AssemblyWriter::printTypeIdInfo(
3225     const FunctionSummary::TypeIdInfo &TIDInfo) {
3226   Out << ", typeIdInfo: (";
3227   FieldSeparator TIDFS;
3228   if (!TIDInfo.TypeTests.empty()) {
3229     Out << TIDFS;
3230     Out << "typeTests: (";
3231     FieldSeparator FS;
3232     for (auto &GUID : TIDInfo.TypeTests) {
3233       auto TidIter = TheIndex->typeIds().equal_range(GUID);
3234       if (TidIter.first == TidIter.second) {
3235         Out << FS;
3236         Out << GUID;
3237         continue;
3238       }
3239       // Print all type id that correspond to this GUID.
3240       for (auto It = TidIter.first; It != TidIter.second; ++It) {
3241         Out << FS;
3242         auto Slot = Machine.getTypeIdSlot(It->second.first);
3243         assert(Slot != -1);
3244         Out << "^" << Slot;
3245       }
3246     }
3247     Out << ")";
3248   }
3249   if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
3250     Out << TIDFS;
3251     printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
3252   }
3253   if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
3254     Out << TIDFS;
3255     printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
3256   }
3257   if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
3258     Out << TIDFS;
3259     printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
3260                      "typeTestAssumeConstVCalls");
3261   }
3262   if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
3263     Out << TIDFS;
3264     printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
3265                      "typeCheckedLoadConstVCalls");
3266   }
3267   Out << ")";
3268 }
3269 
3270 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
3271   auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
3272   if (TidIter.first == TidIter.second) {
3273     Out << "vFuncId: (";
3274     Out << "guid: " << VFId.GUID;
3275     Out << ", offset: " << VFId.Offset;
3276     Out << ")";
3277     return;
3278   }
3279   // Print all type id that correspond to this GUID.
3280   FieldSeparator FS;
3281   for (auto It = TidIter.first; It != TidIter.second; ++It) {
3282     Out << FS;
3283     Out << "vFuncId: (";
3284     auto Slot = Machine.getTypeIdSlot(It->second.first);
3285     assert(Slot != -1);
3286     Out << "^" << Slot;
3287     Out << ", offset: " << VFId.Offset;
3288     Out << ")";
3289   }
3290 }
3291 
3292 void AssemblyWriter::printNonConstVCalls(
3293     const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
3294   Out << Tag << ": (";
3295   FieldSeparator FS;
3296   for (auto &VFuncId : VCallList) {
3297     Out << FS;
3298     printVFuncId(VFuncId);
3299   }
3300   Out << ")";
3301 }
3302 
3303 void AssemblyWriter::printConstVCalls(
3304     const std::vector<FunctionSummary::ConstVCall> &VCallList,
3305     const char *Tag) {
3306   Out << Tag << ": (";
3307   FieldSeparator FS;
3308   for (auto &ConstVCall : VCallList) {
3309     Out << FS;
3310     Out << "(";
3311     printVFuncId(ConstVCall.VFunc);
3312     if (!ConstVCall.Args.empty()) {
3313       Out << ", ";
3314       printArgs(ConstVCall.Args);
3315     }
3316     Out << ")";
3317   }
3318   Out << ")";
3319 }
3320 
3321 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3322   GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3323   GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3324   Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3325   Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3326       << ", flags: (";
3327   Out << "linkage: " << getLinkageName(LT);
3328   Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3329   Out << ", live: " << GVFlags.Live;
3330   Out << ", dsoLocal: " << GVFlags.DSOLocal;
3331   Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3332   Out << ")";
3333 
3334   if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3335     printAliasSummary(cast<AliasSummary>(&Summary));
3336   else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3337     printFunctionSummary(cast<FunctionSummary>(&Summary));
3338   else
3339     printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3340 
3341   auto RefList = Summary.refs();
3342   if (!RefList.empty()) {
3343     Out << ", refs: (";
3344     FieldSeparator FS;
3345     for (auto &Ref : RefList) {
3346       Out << FS;
3347       if (Ref.isReadOnly())
3348         Out << "readonly ";
3349       else if (Ref.isWriteOnly())
3350         Out << "writeonly ";
3351       Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3352     }
3353     Out << ")";
3354   }
3355 
3356   Out << ")";
3357 }
3358 
3359 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3360   Out << "^" << Slot << " = gv: (";
3361   if (!VI.name().empty())
3362     Out << "name: \"" << VI.name() << "\"";
3363   else
3364     Out << "guid: " << VI.getGUID();
3365   if (!VI.getSummaryList().empty()) {
3366     Out << ", summaries: (";
3367     FieldSeparator FS;
3368     for (auto &Summary : VI.getSummaryList()) {
3369       Out << FS;
3370       printSummary(*Summary);
3371     }
3372     Out << ")";
3373   }
3374   Out << ")";
3375   if (!VI.name().empty())
3376     Out << " ; guid = " << VI.getGUID();
3377   Out << "\n";
3378 }
3379 
3380 static void printMetadataIdentifier(StringRef Name,
3381                                     formatted_raw_ostream &Out) {
3382   if (Name.empty()) {
3383     Out << "<empty name> ";
3384   } else {
3385     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3386         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3387       Out << Name[0];
3388     else
3389       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3390     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3391       unsigned char C = Name[i];
3392       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3393           C == '.' || C == '_')
3394         Out << C;
3395       else
3396         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3397     }
3398   }
3399 }
3400 
3401 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3402   Out << '!';
3403   printMetadataIdentifier(NMD->getName(), Out);
3404   Out << " = !{";
3405   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3406     if (i)
3407       Out << ", ";
3408 
3409     // Write DIExpressions inline.
3410     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3411     MDNode *Op = NMD->getOperand(i);
3412     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3413       writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3414       continue;
3415     }
3416 
3417     int Slot = Machine.getMetadataSlot(Op);
3418     if (Slot == -1)
3419       Out << "<badref>";
3420     else
3421       Out << '!' << Slot;
3422   }
3423   Out << "}\n";
3424 }
3425 
3426 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
3427                             formatted_raw_ostream &Out) {
3428   switch (Vis) {
3429   case GlobalValue::DefaultVisibility: break;
3430   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
3431   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3432   }
3433 }
3434 
3435 static void PrintDSOLocation(const GlobalValue &GV,
3436                              formatted_raw_ostream &Out) {
3437   if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
3438     Out << "dso_local ";
3439 }
3440 
3441 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3442                                  formatted_raw_ostream &Out) {
3443   switch (SCT) {
3444   case GlobalValue::DefaultStorageClass: break;
3445   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3446   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3447   }
3448 }
3449 
3450 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3451                                   formatted_raw_ostream &Out) {
3452   switch (TLM) {
3453     case GlobalVariable::NotThreadLocal:
3454       break;
3455     case GlobalVariable::GeneralDynamicTLSModel:
3456       Out << "thread_local ";
3457       break;
3458     case GlobalVariable::LocalDynamicTLSModel:
3459       Out << "thread_local(localdynamic) ";
3460       break;
3461     case GlobalVariable::InitialExecTLSModel:
3462       Out << "thread_local(initialexec) ";
3463       break;
3464     case GlobalVariable::LocalExecTLSModel:
3465       Out << "thread_local(localexec) ";
3466       break;
3467   }
3468 }
3469 
3470 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3471   switch (UA) {
3472   case GlobalVariable::UnnamedAddr::None:
3473     return "";
3474   case GlobalVariable::UnnamedAddr::Local:
3475     return "local_unnamed_addr";
3476   case GlobalVariable::UnnamedAddr::Global:
3477     return "unnamed_addr";
3478   }
3479   llvm_unreachable("Unknown UnnamedAddr");
3480 }
3481 
3482 static void maybePrintComdat(formatted_raw_ostream &Out,
3483                              const GlobalObject &GO) {
3484   const Comdat *C = GO.getComdat();
3485   if (!C)
3486     return;
3487 
3488   if (isa<GlobalVariable>(GO))
3489     Out << ',';
3490   Out << " comdat";
3491 
3492   if (GO.getName() == C->getName())
3493     return;
3494 
3495   Out << '(';
3496   PrintLLVMName(Out, C->getName(), ComdatPrefix);
3497   Out << ')';
3498 }
3499 
3500 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3501   if (GV->isMaterializable())
3502     Out << "; Materializable\n";
3503 
3504   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
3505   Out << " = ";
3506 
3507   if (!GV->hasInitializer() && GV->hasExternalLinkage())
3508     Out << "external ";
3509 
3510   Out << getLinkageNameWithSpace(GV->getLinkage());
3511   PrintDSOLocation(*GV, Out);
3512   PrintVisibility(GV->getVisibility(), Out);
3513   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
3514   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
3515   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3516   if (!UA.empty())
3517       Out << UA << ' ';
3518 
3519   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3520     Out << "addrspace(" << AddressSpace << ") ";
3521   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3522   Out << (GV->isConstant() ? "constant " : "global ");
3523   TypePrinter.print(GV->getValueType(), Out);
3524 
3525   if (GV->hasInitializer()) {
3526     Out << ' ';
3527     writeOperand(GV->getInitializer(), false);
3528   }
3529 
3530   if (GV->hasSection()) {
3531     Out << ", section \"";
3532     printEscapedString(GV->getSection(), Out);
3533     Out << '"';
3534   }
3535   if (GV->hasPartition()) {
3536     Out << ", partition \"";
3537     printEscapedString(GV->getPartition(), Out);
3538     Out << '"';
3539   }
3540 
3541   maybePrintComdat(Out, *GV);
3542   if (GV->getAlignment())
3543     Out << ", align " << GV->getAlignment();
3544 
3545   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3546   GV->getAllMetadata(MDs);
3547   printMetadataAttachments(MDs, ", ");
3548 
3549   auto Attrs = GV->getAttributes();
3550   if (Attrs.hasAttributes())
3551     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3552 
3553   printInfoComment(*GV);
3554 }
3555 
3556 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3557   if (GIS->isMaterializable())
3558     Out << "; Materializable\n";
3559 
3560   WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
3561   Out << " = ";
3562 
3563   Out << getLinkageNameWithSpace(GIS->getLinkage());
3564   PrintDSOLocation(*GIS, Out);
3565   PrintVisibility(GIS->getVisibility(), Out);
3566   PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
3567   PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
3568   StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
3569   if (!UA.empty())
3570       Out << UA << ' ';
3571 
3572   if (isa<GlobalAlias>(GIS))
3573     Out << "alias ";
3574   else if (isa<GlobalIFunc>(GIS))
3575     Out << "ifunc ";
3576   else
3577     llvm_unreachable("Not an alias or ifunc!");
3578 
3579   TypePrinter.print(GIS->getValueType(), Out);
3580 
3581   Out << ", ";
3582 
3583   const Constant *IS = GIS->getIndirectSymbol();
3584 
3585   if (!IS) {
3586     TypePrinter.print(GIS->getType(), Out);
3587     Out << " <<NULL ALIASEE>>";
3588   } else {
3589     writeOperand(IS, !isa<ConstantExpr>(IS));
3590   }
3591 
3592   if (GIS->hasPartition()) {
3593     Out << ", partition \"";
3594     printEscapedString(GIS->getPartition(), Out);
3595     Out << '"';
3596   }
3597 
3598   printInfoComment(*GIS);
3599   Out << '\n';
3600 }
3601 
3602 void AssemblyWriter::printComdat(const Comdat *C) {
3603   C->print(Out);
3604 }
3605 
3606 void AssemblyWriter::printTypeIdentities() {
3607   if (TypePrinter.empty())
3608     return;
3609 
3610   Out << '\n';
3611 
3612   // Emit all numbered types.
3613   auto &NumberedTypes = TypePrinter.getNumberedTypes();
3614   for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3615     Out << '%' << I << " = type ";
3616 
3617     // Make sure we print out at least one level of the type structure, so
3618     // that we do not get %2 = type %2
3619     TypePrinter.printStructBody(NumberedTypes[I], Out);
3620     Out << '\n';
3621   }
3622 
3623   auto &NamedTypes = TypePrinter.getNamedTypes();
3624   for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3625     PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
3626     Out << " = type ";
3627 
3628     // Make sure we print out at least one level of the type structure, so
3629     // that we do not get %FILE = type %FILE
3630     TypePrinter.printStructBody(NamedTypes[I], Out);
3631     Out << '\n';
3632   }
3633 }
3634 
3635 /// printFunction - Print all aspects of a function.
3636 void AssemblyWriter::printFunction(const Function *F) {
3637   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3638 
3639   if (F->isMaterializable())
3640     Out << "; Materializable\n";
3641 
3642   const AttributeList &Attrs = F->getAttributes();
3643   if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
3644     AttributeSet AS = Attrs.getFnAttributes();
3645     std::string AttrStr;
3646 
3647     for (const Attribute &Attr : AS) {
3648       if (!Attr.isStringAttribute()) {
3649         if (!AttrStr.empty()) AttrStr += ' ';
3650         AttrStr += Attr.getAsString();
3651       }
3652     }
3653 
3654     if (!AttrStr.empty())
3655       Out << "; Function Attrs: " << AttrStr << '\n';
3656   }
3657 
3658   Machine.incorporateFunction(F);
3659 
3660   if (F->isDeclaration()) {
3661     Out << "declare";
3662     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3663     F->getAllMetadata(MDs);
3664     printMetadataAttachments(MDs, " ");
3665     Out << ' ';
3666   } else
3667     Out << "define ";
3668 
3669   Out << getLinkageNameWithSpace(F->getLinkage());
3670   PrintDSOLocation(*F, Out);
3671   PrintVisibility(F->getVisibility(), Out);
3672   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3673 
3674   // Print the calling convention.
3675   if (F->getCallingConv() != CallingConv::C) {
3676     PrintCallingConv(F->getCallingConv(), Out);
3677     Out << " ";
3678   }
3679 
3680   FunctionType *FT = F->getFunctionType();
3681   if (Attrs.hasAttributes(AttributeList::ReturnIndex))
3682     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3683   TypePrinter.print(F->getReturnType(), Out);
3684   Out << ' ';
3685   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
3686   Out << '(';
3687 
3688   // Loop over the arguments, printing them...
3689   if (F->isDeclaration() && !IsForDebug) {
3690     // We're only interested in the type here - don't print argument names.
3691     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3692       // Insert commas as we go... the first arg doesn't get a comma
3693       if (I)
3694         Out << ", ";
3695       // Output type...
3696       TypePrinter.print(FT->getParamType(I), Out);
3697 
3698       AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3699       if (ArgAttrs.hasAttributes()) {
3700         Out << ' ';
3701         writeAttributeSet(ArgAttrs);
3702       }
3703     }
3704   } else {
3705     // The arguments are meaningful here, print them in detail.
3706     for (const Argument &Arg : F->args()) {
3707       // Insert commas as we go... the first arg doesn't get a comma
3708       if (Arg.getArgNo() != 0)
3709         Out << ", ";
3710       printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
3711     }
3712   }
3713 
3714   // Finish printing arguments...
3715   if (FT->isVarArg()) {
3716     if (FT->getNumParams()) Out << ", ";
3717     Out << "...";  // Output varargs portion of signature!
3718   }
3719   Out << ')';
3720   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3721   if (!UA.empty())
3722     Out << ' ' << UA;
3723   // We print the function address space if it is non-zero or if we are writing
3724   // a module with a non-zero program address space or if there is no valid
3725   // Module* so that the file can be parsed without the datalayout string.
3726   const Module *Mod = F->getParent();
3727   if (F->getAddressSpace() != 0 || !Mod ||
3728       Mod->getDataLayout().getProgramAddressSpace() != 0)
3729     Out << " addrspace(" << F->getAddressSpace() << ")";
3730   if (Attrs.hasAttributes(AttributeList::FunctionIndex))
3731     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
3732   if (F->hasSection()) {
3733     Out << " section \"";
3734     printEscapedString(F->getSection(), Out);
3735     Out << '"';
3736   }
3737   if (F->hasPartition()) {
3738     Out << " partition \"";
3739     printEscapedString(F->getPartition(), Out);
3740     Out << '"';
3741   }
3742   maybePrintComdat(Out, *F);
3743   if (F->getAlignment())
3744     Out << " align " << F->getAlignment();
3745   if (F->hasGC())
3746     Out << " gc \"" << F->getGC() << '"';
3747   if (F->hasPrefixData()) {
3748     Out << " prefix ";
3749     writeOperand(F->getPrefixData(), true);
3750   }
3751   if (F->hasPrologueData()) {
3752     Out << " prologue ";
3753     writeOperand(F->getPrologueData(), true);
3754   }
3755   if (F->hasPersonalityFn()) {
3756     Out << " personality ";
3757     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3758   }
3759 
3760   if (F->isDeclaration()) {
3761     Out << '\n';
3762   } else {
3763     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3764     F->getAllMetadata(MDs);
3765     printMetadataAttachments(MDs, " ");
3766 
3767     Out << " {";
3768     // Output all of the function's basic blocks.
3769     for (const BasicBlock &BB : *F)
3770       printBasicBlock(&BB);
3771 
3772     // Output the function's use-lists.
3773     printUseLists(F);
3774 
3775     Out << "}\n";
3776   }
3777 
3778   Machine.purgeFunction();
3779 }
3780 
3781 /// printArgument - This member is called for every argument that is passed into
3782 /// the function.  Simply print it out
3783 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3784   // Output type...
3785   TypePrinter.print(Arg->getType(), Out);
3786 
3787   // Output parameter attributes list
3788   if (Attrs.hasAttributes()) {
3789     Out << ' ';
3790     writeAttributeSet(Attrs);
3791   }
3792 
3793   // Output name, if available...
3794   if (Arg->hasName()) {
3795     Out << ' ';
3796     PrintLLVMName(Out, Arg);
3797   } else {
3798     int Slot = Machine.getLocalSlot(Arg);
3799     assert(Slot != -1 && "expect argument in function here");
3800     Out << " %" << Slot;
3801   }
3802 }
3803 
3804 /// printBasicBlock - This member is called for each basic block in a method.
3805 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3806   assert(BB && BB->getParent() && "block without parent!");
3807   bool IsEntryBlock = BB == &BB->getParent()->getEntryBlock();
3808   if (BB->hasName()) {              // Print out the label if it exists...
3809     Out << "\n";
3810     PrintLLVMName(Out, BB->getName(), LabelPrefix);
3811     Out << ':';
3812   } else if (!IsEntryBlock) {
3813     Out << "\n";
3814     int Slot = Machine.getLocalSlot(BB);
3815     if (Slot != -1)
3816       Out << Slot << ":";
3817     else
3818       Out << "<badref>:";
3819   }
3820 
3821   if (!IsEntryBlock) {
3822     // Output predecessors for the block.
3823     Out.PadToColumn(50);
3824     Out << ";";
3825     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3826 
3827     if (PI == PE) {
3828       Out << " No predecessors!";
3829     } else {
3830       Out << " preds = ";
3831       writeOperand(*PI, false);
3832       for (++PI; PI != PE; ++PI) {
3833         Out << ", ";
3834         writeOperand(*PI, false);
3835       }
3836     }
3837   }
3838 
3839   Out << "\n";
3840 
3841   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3842 
3843   // Output all of the instructions in the basic block...
3844   for (const Instruction &I : *BB) {
3845     printInstructionLine(I);
3846   }
3847 
3848   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3849 }
3850 
3851 /// printInstructionLine - Print an instruction and a newline character.
3852 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3853   printInstruction(I);
3854   Out << '\n';
3855 }
3856 
3857 /// printGCRelocateComment - print comment after call to the gc.relocate
3858 /// intrinsic indicating base and derived pointer names.
3859 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3860   Out << " ; (";
3861   writeOperand(Relocate.getBasePtr(), false);
3862   Out << ", ";
3863   writeOperand(Relocate.getDerivedPtr(), false);
3864   Out << ")";
3865 }
3866 
3867 /// printInfoComment - Print a little comment after the instruction indicating
3868 /// which slot it occupies.
3869 void AssemblyWriter::printInfoComment(const Value &V) {
3870   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3871     printGCRelocateComment(*Relocate);
3872 
3873   if (AnnotationWriter)
3874     AnnotationWriter->printInfoComment(V, Out);
3875 }
3876 
3877 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
3878                                     raw_ostream &Out) {
3879   // We print the address space of the call if it is non-zero.
3880   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
3881   bool PrintAddrSpace = CallAddrSpace != 0;
3882   if (!PrintAddrSpace) {
3883     const Module *Mod = getModuleFromVal(I);
3884     // We also print it if it is zero but not equal to the program address space
3885     // or if we can't find a valid Module* to make it possible to parse
3886     // the resulting file even without a datalayout string.
3887     if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
3888       PrintAddrSpace = true;
3889   }
3890   if (PrintAddrSpace)
3891     Out << " addrspace(" << CallAddrSpace << ")";
3892 }
3893 
3894 // This member is called for each Instruction in a function..
3895 void AssemblyWriter::printInstruction(const Instruction &I) {
3896   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
3897 
3898   // Print out indentation for an instruction.
3899   Out << "  ";
3900 
3901   // Print out name if it exists...
3902   if (I.hasName()) {
3903     PrintLLVMName(Out, &I);
3904     Out << " = ";
3905   } else if (!I.getType()->isVoidTy()) {
3906     // Print out the def slot taken.
3907     int SlotNum = Machine.getLocalSlot(&I);
3908     if (SlotNum == -1)
3909       Out << "<badref> = ";
3910     else
3911       Out << '%' << SlotNum << " = ";
3912   }
3913 
3914   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3915     if (CI->isMustTailCall())
3916       Out << "musttail ";
3917     else if (CI->isTailCall())
3918       Out << "tail ";
3919     else if (CI->isNoTailCall())
3920       Out << "notail ";
3921   }
3922 
3923   // Print out the opcode...
3924   Out << I.getOpcodeName();
3925 
3926   // If this is an atomic load or store, print out the atomic marker.
3927   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
3928       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3929     Out << " atomic";
3930 
3931   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3932     Out << " weak";
3933 
3934   // If this is a volatile operation, print out the volatile marker.
3935   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
3936       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3937       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3938       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3939     Out << " volatile";
3940 
3941   // Print out optimization information.
3942   WriteOptimizationInfo(Out, &I);
3943 
3944   // Print out the compare instruction predicates
3945   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
3946     Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
3947 
3948   // Print out the atomicrmw operation
3949   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
3950     Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
3951 
3952   // Print out the type of the operands...
3953   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
3954 
3955   // Special case conditional branches to swizzle the condition out to the front
3956   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
3957     const BranchInst &BI(cast<BranchInst>(I));
3958     Out << ' ';
3959     writeOperand(BI.getCondition(), true);
3960     Out << ", ";
3961     writeOperand(BI.getSuccessor(0), true);
3962     Out << ", ";
3963     writeOperand(BI.getSuccessor(1), true);
3964 
3965   } else if (isa<SwitchInst>(I)) {
3966     const SwitchInst& SI(cast<SwitchInst>(I));
3967     // Special case switch instruction to get formatting nice and correct.
3968     Out << ' ';
3969     writeOperand(SI.getCondition(), true);
3970     Out << ", ";
3971     writeOperand(SI.getDefaultDest(), true);
3972     Out << " [";
3973     for (auto Case : SI.cases()) {
3974       Out << "\n    ";
3975       writeOperand(Case.getCaseValue(), true);
3976       Out << ", ";
3977       writeOperand(Case.getCaseSuccessor(), true);
3978     }
3979     Out << "\n  ]";
3980   } else if (isa<IndirectBrInst>(I)) {
3981     // Special case indirectbr instruction to get formatting nice and correct.
3982     Out << ' ';
3983     writeOperand(Operand, true);
3984     Out << ", [";
3985 
3986     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3987       if (i != 1)
3988         Out << ", ";
3989       writeOperand(I.getOperand(i), true);
3990     }
3991     Out << ']';
3992   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3993     Out << ' ';
3994     TypePrinter.print(I.getType(), Out);
3995     Out << ' ';
3996 
3997     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
3998       if (op) Out << ", ";
3999       Out << "[ ";
4000       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
4001       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
4002     }
4003   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
4004     Out << ' ';
4005     writeOperand(I.getOperand(0), true);
4006     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
4007       Out << ", " << *i;
4008   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
4009     Out << ' ';
4010     writeOperand(I.getOperand(0), true); Out << ", ";
4011     writeOperand(I.getOperand(1), true);
4012     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
4013       Out << ", " << *i;
4014   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
4015     Out << ' ';
4016     TypePrinter.print(I.getType(), Out);
4017     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
4018       Out << '\n';
4019 
4020     if (LPI->isCleanup())
4021       Out << "          cleanup";
4022 
4023     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
4024       if (i != 0 || LPI->isCleanup()) Out << "\n";
4025       if (LPI->isCatch(i))
4026         Out << "          catch ";
4027       else
4028         Out << "          filter ";
4029 
4030       writeOperand(LPI->getClause(i), true);
4031     }
4032   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
4033     Out << " within ";
4034     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
4035     Out << " [";
4036     unsigned Op = 0;
4037     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
4038       if (Op > 0)
4039         Out << ", ";
4040       writeOperand(PadBB, /*PrintType=*/true);
4041       ++Op;
4042     }
4043     Out << "] unwind ";
4044     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
4045       writeOperand(UnwindDest, /*PrintType=*/true);
4046     else
4047       Out << "to caller";
4048   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
4049     Out << " within ";
4050     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
4051     Out << " [";
4052     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
4053          ++Op) {
4054       if (Op > 0)
4055         Out << ", ";
4056       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
4057     }
4058     Out << ']';
4059   } else if (isa<ReturnInst>(I) && !Operand) {
4060     Out << " void";
4061   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
4062     Out << " from ";
4063     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4064 
4065     Out << " to ";
4066     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4067   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
4068     Out << " from ";
4069     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4070 
4071     Out << " unwind ";
4072     if (CRI->hasUnwindDest())
4073       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4074     else
4075       Out << "to caller";
4076   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4077     // Print the calling convention being used.
4078     if (CI->getCallingConv() != CallingConv::C) {
4079       Out << " ";
4080       PrintCallingConv(CI->getCallingConv(), Out);
4081     }
4082 
4083     Operand = CI->getCalledOperand();
4084     FunctionType *FTy = CI->getFunctionType();
4085     Type *RetTy = FTy->getReturnType();
4086     const AttributeList &PAL = CI->getAttributes();
4087 
4088     if (PAL.hasAttributes(AttributeList::ReturnIndex))
4089       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4090 
4091     // Only print addrspace(N) if necessary:
4092     maybePrintCallAddrSpace(Operand, &I, Out);
4093 
4094     // If possible, print out the short form of the call instruction.  We can
4095     // only do this if the first argument is a pointer to a nonvararg function,
4096     // and if the return type is not a pointer to a function.
4097     //
4098     Out << ' ';
4099     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4100     Out << ' ';
4101     writeOperand(Operand, false);
4102     Out << '(';
4103     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
4104       if (op > 0)
4105         Out << ", ";
4106       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
4107     }
4108 
4109     // Emit an ellipsis if this is a musttail call in a vararg function.  This
4110     // is only to aid readability, musttail calls forward varargs by default.
4111     if (CI->isMustTailCall() && CI->getParent() &&
4112         CI->getParent()->getParent() &&
4113         CI->getParent()->getParent()->isVarArg())
4114       Out << ", ...";
4115 
4116     Out << ')';
4117     if (PAL.hasAttributes(AttributeList::FunctionIndex))
4118       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
4119 
4120     writeOperandBundles(CI);
4121   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
4122     Operand = II->getCalledOperand();
4123     FunctionType *FTy = II->getFunctionType();
4124     Type *RetTy = FTy->getReturnType();
4125     const AttributeList &PAL = II->getAttributes();
4126 
4127     // Print the calling convention being used.
4128     if (II->getCallingConv() != CallingConv::C) {
4129       Out << " ";
4130       PrintCallingConv(II->getCallingConv(), Out);
4131     }
4132 
4133     if (PAL.hasAttributes(AttributeList::ReturnIndex))
4134       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4135 
4136     // Only print addrspace(N) if necessary:
4137     maybePrintCallAddrSpace(Operand, &I, Out);
4138 
4139     // If possible, print out the short form of the invoke instruction. We can
4140     // only do this if the first argument is a pointer to a nonvararg function,
4141     // and if the return type is not a pointer to a function.
4142     //
4143     Out << ' ';
4144     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4145     Out << ' ';
4146     writeOperand(Operand, false);
4147     Out << '(';
4148     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
4149       if (op)
4150         Out << ", ";
4151       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
4152     }
4153 
4154     Out << ')';
4155     if (PAL.hasAttributes(AttributeList::FunctionIndex))
4156       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
4157 
4158     writeOperandBundles(II);
4159 
4160     Out << "\n          to ";
4161     writeOperand(II->getNormalDest(), true);
4162     Out << " unwind ";
4163     writeOperand(II->getUnwindDest(), true);
4164   } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
4165     Operand = CBI->getCalledOperand();
4166     FunctionType *FTy = CBI->getFunctionType();
4167     Type *RetTy = FTy->getReturnType();
4168     const AttributeList &PAL = CBI->getAttributes();
4169 
4170     // Print the calling convention being used.
4171     if (CBI->getCallingConv() != CallingConv::C) {
4172       Out << " ";
4173       PrintCallingConv(CBI->getCallingConv(), Out);
4174     }
4175 
4176     if (PAL.hasAttributes(AttributeList::ReturnIndex))
4177       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4178 
4179     // If possible, print out the short form of the callbr instruction. We can
4180     // only do this if the first argument is a pointer to a nonvararg function,
4181     // and if the return type is not a pointer to a function.
4182     //
4183     Out << ' ';
4184     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4185     Out << ' ';
4186     writeOperand(Operand, false);
4187     Out << '(';
4188     for (unsigned op = 0, Eop = CBI->getNumArgOperands(); op < Eop; ++op) {
4189       if (op)
4190         Out << ", ";
4191       writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttributes(op));
4192     }
4193 
4194     Out << ')';
4195     if (PAL.hasAttributes(AttributeList::FunctionIndex))
4196       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
4197 
4198     writeOperandBundles(CBI);
4199 
4200     Out << "\n          to ";
4201     writeOperand(CBI->getDefaultDest(), true);
4202     Out << " [";
4203     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
4204       if (i != 0)
4205         Out << ", ";
4206       writeOperand(CBI->getIndirectDest(i), true);
4207     }
4208     Out << ']';
4209   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
4210     Out << ' ';
4211     if (AI->isUsedWithInAlloca())
4212       Out << "inalloca ";
4213     if (AI->isSwiftError())
4214       Out << "swifterror ";
4215     TypePrinter.print(AI->getAllocatedType(), Out);
4216 
4217     // Explicitly write the array size if the code is broken, if it's an array
4218     // allocation, or if the type is not canonical for scalar allocations.  The
4219     // latter case prevents the type from mutating when round-tripping through
4220     // assembly.
4221     if (!AI->getArraySize() || AI->isArrayAllocation() ||
4222         !AI->getArraySize()->getType()->isIntegerTy(32)) {
4223       Out << ", ";
4224       writeOperand(AI->getArraySize(), true);
4225     }
4226     if (AI->getAlignment()) {
4227       Out << ", align " << AI->getAlignment();
4228     }
4229 
4230     unsigned AddrSpace = AI->getType()->getAddressSpace();
4231     if (AddrSpace != 0) {
4232       Out << ", addrspace(" << AddrSpace << ')';
4233     }
4234   } else if (isa<CastInst>(I)) {
4235     if (Operand) {
4236       Out << ' ';
4237       writeOperand(Operand, true);   // Work with broken code
4238     }
4239     Out << " to ";
4240     TypePrinter.print(I.getType(), Out);
4241   } else if (isa<VAArgInst>(I)) {
4242     if (Operand) {
4243       Out << ' ';
4244       writeOperand(Operand, true);   // Work with broken code
4245     }
4246     Out << ", ";
4247     TypePrinter.print(I.getType(), Out);
4248   } else if (Operand) {   // Print the normal way.
4249     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4250       Out << ' ';
4251       TypePrinter.print(GEP->getSourceElementType(), Out);
4252       Out << ',';
4253     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
4254       Out << ' ';
4255       TypePrinter.print(LI->getType(), Out);
4256       Out << ',';
4257     }
4258 
4259     // PrintAllTypes - Instructions who have operands of all the same type
4260     // omit the type from all but the first operand.  If the instruction has
4261     // different type operands (for example br), then they are all printed.
4262     bool PrintAllTypes = false;
4263     Type *TheType = Operand->getType();
4264 
4265     // Select, Store and ShuffleVector always print all types.
4266     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
4267         || isa<ReturnInst>(I)) {
4268       PrintAllTypes = true;
4269     } else {
4270       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
4271         Operand = I.getOperand(i);
4272         // note that Operand shouldn't be null, but the test helps make dump()
4273         // more tolerant of malformed IR
4274         if (Operand && Operand->getType() != TheType) {
4275           PrintAllTypes = true;    // We have differing types!  Print them all!
4276           break;
4277         }
4278       }
4279     }
4280 
4281     if (!PrintAllTypes) {
4282       Out << ' ';
4283       TypePrinter.print(TheType, Out);
4284     }
4285 
4286     Out << ' ';
4287     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
4288       if (i) Out << ", ";
4289       writeOperand(I.getOperand(i), PrintAllTypes);
4290     }
4291   }
4292 
4293   // Print atomic ordering/alignment for memory operations
4294   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
4295     if (LI->isAtomic())
4296       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4297     if (LI->getAlignment())
4298       Out << ", align " << LI->getAlignment();
4299   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4300     if (SI->isAtomic())
4301       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4302     if (SI->getAlignment())
4303       Out << ", align " << SI->getAlignment();
4304   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
4305     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4306                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
4307   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
4308     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4309                 RMWI->getSyncScopeID());
4310   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
4311     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4312   } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
4313     PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
4314   }
4315 
4316   // Print Metadata info.
4317   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
4318   I.getAllMetadata(InstMD);
4319   printMetadataAttachments(InstMD, ", ");
4320 
4321   // Print a nice comment.
4322   printInfoComment(I);
4323 }
4324 
4325 void AssemblyWriter::printMetadataAttachments(
4326     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
4327     StringRef Separator) {
4328   if (MDs.empty())
4329     return;
4330 
4331   if (MDNames.empty())
4332     MDs[0].second->getContext().getMDKindNames(MDNames);
4333 
4334   for (const auto &I : MDs) {
4335     unsigned Kind = I.first;
4336     Out << Separator;
4337     if (Kind < MDNames.size()) {
4338       Out << "!";
4339       printMetadataIdentifier(MDNames[Kind], Out);
4340     } else
4341       Out << "!<unknown kind #" << Kind << ">";
4342     Out << ' ';
4343     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
4344   }
4345 }
4346 
4347 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
4348   Out << '!' << Slot << " = ";
4349   printMDNodeBody(Node);
4350   Out << "\n";
4351 }
4352 
4353 void AssemblyWriter::writeAllMDNodes() {
4354   SmallVector<const MDNode *, 16> Nodes;
4355   Nodes.resize(Machine.mdn_size());
4356   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
4357        I != E; ++I)
4358     Nodes[I->second] = cast<MDNode>(I->first);
4359 
4360   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4361     writeMDNode(i, Nodes[i]);
4362   }
4363 }
4364 
4365 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4366   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
4367 }
4368 
4369 void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
4370   if (!Attr.isTypeAttribute()) {
4371     Out << Attr.getAsString(InAttrGroup);
4372     return;
4373   }
4374 
4375   assert((Attr.hasAttribute(Attribute::ByVal) ||
4376           Attr.hasAttribute(Attribute::StructRet) ||
4377           Attr.hasAttribute(Attribute::ByRef) ||
4378           Attr.hasAttribute(Attribute::Preallocated)) &&
4379          "unexpected type attr");
4380 
4381   if (Attr.hasAttribute(Attribute::ByVal)) {
4382     Out << "byval";
4383   } else if (Attr.hasAttribute(Attribute::StructRet)) {
4384     Out << "sret";
4385   } else if (Attr.hasAttribute(Attribute::ByRef)) {
4386     Out << "byref";
4387   } else {
4388     Out << "preallocated";
4389   }
4390 
4391   if (Type *Ty = Attr.getValueAsType()) {
4392     Out << '(';
4393     TypePrinter.print(Ty, Out);
4394     Out << ')';
4395   }
4396 }
4397 
4398 void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
4399                                        bool InAttrGroup) {
4400   bool FirstAttr = true;
4401   for (const auto &Attr : AttrSet) {
4402     if (!FirstAttr)
4403       Out << ' ';
4404     writeAttribute(Attr, InAttrGroup);
4405     FirstAttr = false;
4406   }
4407 }
4408 
4409 void AssemblyWriter::writeAllAttributeGroups() {
4410   std::vector<std::pair<AttributeSet, unsigned>> asVec;
4411   asVec.resize(Machine.as_size());
4412 
4413   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
4414        I != E; ++I)
4415     asVec[I->second] = *I;
4416 
4417   for (const auto &I : asVec)
4418     Out << "attributes #" << I.second << " = { "
4419         << I.first.getAsString(true) << " }\n";
4420 }
4421 
4422 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
4423   bool IsInFunction = Machine.getFunction();
4424   if (IsInFunction)
4425     Out << "  ";
4426 
4427   Out << "uselistorder";
4428   if (const BasicBlock *BB =
4429           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
4430     Out << "_bb ";
4431     writeOperand(BB->getParent(), false);
4432     Out << ", ";
4433     writeOperand(BB, false);
4434   } else {
4435     Out << " ";
4436     writeOperand(Order.V, true);
4437   }
4438   Out << ", { ";
4439 
4440   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
4441   Out << Order.Shuffle[0];
4442   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
4443     Out << ", " << Order.Shuffle[I];
4444   Out << " }\n";
4445 }
4446 
4447 void AssemblyWriter::printUseLists(const Function *F) {
4448   auto hasMore =
4449       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
4450   if (!hasMore())
4451     // Nothing to do.
4452     return;
4453 
4454   Out << "\n; uselistorder directives\n";
4455   while (hasMore()) {
4456     printUseListOrder(UseListOrders.back());
4457     UseListOrders.pop_back();
4458   }
4459 }
4460 
4461 //===----------------------------------------------------------------------===//
4462 //                       External Interface declarations
4463 //===----------------------------------------------------------------------===//
4464 
4465 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4466                      bool ShouldPreserveUseListOrder,
4467                      bool IsForDebug) const {
4468   SlotTracker SlotTable(this->getParent());
4469   formatted_raw_ostream OS(ROS);
4470   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4471                    IsForDebug,
4472                    ShouldPreserveUseListOrder);
4473   W.printFunction(this);
4474 }
4475 
4476 void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4477                      bool ShouldPreserveUseListOrder,
4478                      bool IsForDebug) const {
4479   SlotTracker SlotTable(this->getParent());
4480   formatted_raw_ostream OS(ROS);
4481   AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
4482                    IsForDebug,
4483                    ShouldPreserveUseListOrder);
4484   W.printBasicBlock(this);
4485 }
4486 
4487 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4488                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4489   SlotTracker SlotTable(this);
4490   formatted_raw_ostream OS(ROS);
4491   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4492                    ShouldPreserveUseListOrder);
4493   W.printModule(this);
4494 }
4495 
4496 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4497   SlotTracker SlotTable(getParent());
4498   formatted_raw_ostream OS(ROS);
4499   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4500   W.printNamedMDNode(this);
4501 }
4502 
4503 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4504                         bool IsForDebug) const {
4505   Optional<SlotTracker> LocalST;
4506   SlotTracker *SlotTable;
4507   if (auto *ST = MST.getMachine())
4508     SlotTable = ST;
4509   else {
4510     LocalST.emplace(getParent());
4511     SlotTable = &*LocalST;
4512   }
4513 
4514   formatted_raw_ostream OS(ROS);
4515   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4516   W.printNamedMDNode(this);
4517 }
4518 
4519 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4520   PrintLLVMName(ROS, getName(), ComdatPrefix);
4521   ROS << " = comdat ";
4522 
4523   switch (getSelectionKind()) {
4524   case Comdat::Any:
4525     ROS << "any";
4526     break;
4527   case Comdat::ExactMatch:
4528     ROS << "exactmatch";
4529     break;
4530   case Comdat::Largest:
4531     ROS << "largest";
4532     break;
4533   case Comdat::NoDuplicates:
4534     ROS << "noduplicates";
4535     break;
4536   case Comdat::SameSize:
4537     ROS << "samesize";
4538     break;
4539   }
4540 
4541   ROS << '\n';
4542 }
4543 
4544 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4545   TypePrinting TP;
4546   TP.print(const_cast<Type*>(this), OS);
4547 
4548   if (NoDetails)
4549     return;
4550 
4551   // If the type is a named struct type, print the body as well.
4552   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4553     if (!STy->isLiteral()) {
4554       OS << " = type ";
4555       TP.printStructBody(STy, OS);
4556     }
4557 }
4558 
4559 static bool isReferencingMDNode(const Instruction &I) {
4560   if (const auto *CI = dyn_cast<CallInst>(&I))
4561     if (Function *F = CI->getCalledFunction())
4562       if (F->isIntrinsic())
4563         for (auto &Op : I.operands())
4564           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4565             if (isa<MDNode>(V->getMetadata()))
4566               return true;
4567   return false;
4568 }
4569 
4570 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4571   bool ShouldInitializeAllMetadata = false;
4572   if (auto *I = dyn_cast<Instruction>(this))
4573     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4574   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4575     ShouldInitializeAllMetadata = true;
4576 
4577   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4578   print(ROS, MST, IsForDebug);
4579 }
4580 
4581 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4582                   bool IsForDebug) const {
4583   formatted_raw_ostream OS(ROS);
4584   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4585   SlotTracker &SlotTable =
4586       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4587   auto incorporateFunction = [&](const Function *F) {
4588     if (F)
4589       MST.incorporateFunction(*F);
4590   };
4591 
4592   if (const Instruction *I = dyn_cast<Instruction>(this)) {
4593     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4594     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4595     W.printInstruction(*I);
4596   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4597     incorporateFunction(BB->getParent());
4598     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4599     W.printBasicBlock(BB);
4600   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4601     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4602     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4603       W.printGlobal(V);
4604     else if (const Function *F = dyn_cast<Function>(GV))
4605       W.printFunction(F);
4606     else
4607       W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
4608   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4609     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4610   } else if (const Constant *C = dyn_cast<Constant>(this)) {
4611     TypePrinting TypePrinter;
4612     TypePrinter.print(C->getType(), OS);
4613     OS << ' ';
4614     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
4615   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4616     this->printAsOperand(OS, /* PrintType */ true, MST);
4617   } else {
4618     llvm_unreachable("Unknown value to print out!");
4619   }
4620 }
4621 
4622 /// Print without a type, skipping the TypePrinting object.
4623 ///
4624 /// \return \c true iff printing was successful.
4625 static bool printWithoutType(const Value &V, raw_ostream &O,
4626                              SlotTracker *Machine, const Module *M) {
4627   if (V.hasName() || isa<GlobalValue>(V) ||
4628       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4629     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4630     return true;
4631   }
4632   return false;
4633 }
4634 
4635 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4636                                ModuleSlotTracker &MST) {
4637   TypePrinting TypePrinter(MST.getModule());
4638   if (PrintType) {
4639     TypePrinter.print(V.getType(), O);
4640     O << ' ';
4641   }
4642 
4643   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4644                          MST.getModule());
4645 }
4646 
4647 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4648                            const Module *M) const {
4649   if (!M)
4650     M = getModuleFromVal(this);
4651 
4652   if (!PrintType)
4653     if (printWithoutType(*this, O, nullptr, M))
4654       return;
4655 
4656   SlotTracker Machine(
4657       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4658   ModuleSlotTracker MST(Machine, M);
4659   printAsOperandImpl(*this, O, PrintType, MST);
4660 }
4661 
4662 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4663                            ModuleSlotTracker &MST) const {
4664   if (!PrintType)
4665     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4666       return;
4667 
4668   printAsOperandImpl(*this, O, PrintType, MST);
4669 }
4670 
4671 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4672                               ModuleSlotTracker &MST, const Module *M,
4673                               bool OnlyAsOperand) {
4674   formatted_raw_ostream OS(ROS);
4675 
4676   TypePrinting TypePrinter(M);
4677 
4678   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
4679                          /* FromValue */ true);
4680 
4681   auto *N = dyn_cast<MDNode>(&MD);
4682   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
4683     return;
4684 
4685   OS << " = ";
4686   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
4687 }
4688 
4689 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4690   ModuleSlotTracker MST(M, isa<MDNode>(this));
4691   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4692 }
4693 
4694 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4695                               const Module *M) const {
4696   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4697 }
4698 
4699 void Metadata::print(raw_ostream &OS, const Module *M,
4700                      bool /*IsForDebug*/) const {
4701   ModuleSlotTracker MST(M, isa<MDNode>(this));
4702   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4703 }
4704 
4705 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
4706                      const Module *M, bool /*IsForDebug*/) const {
4707   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4708 }
4709 
4710 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4711   SlotTracker SlotTable(this);
4712   formatted_raw_ostream OS(ROS);
4713   AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4714   W.printModuleSummaryIndex();
4715 }
4716 
4717 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4718 // Value::dump - allow easy printing of Values from the debugger.
4719 LLVM_DUMP_METHOD
4720 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4721 
4722 // Type::dump - allow easy printing of Types from the debugger.
4723 LLVM_DUMP_METHOD
4724 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4725 
4726 // Module::dump() - Allow printing of Modules from the debugger.
4727 LLVM_DUMP_METHOD
4728 void Module::dump() const {
4729   print(dbgs(), nullptr,
4730         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4731 }
4732 
4733 // Allow printing of Comdats from the debugger.
4734 LLVM_DUMP_METHOD
4735 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4736 
4737 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4738 LLVM_DUMP_METHOD
4739 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4740 
4741 LLVM_DUMP_METHOD
4742 void Metadata::dump() const { dump(nullptr); }
4743 
4744 LLVM_DUMP_METHOD
4745 void Metadata::dump(const Module *M) const {
4746   print(dbgs(), M, /*IsForDebug=*/true);
4747   dbgs() << '\n';
4748 }
4749 
4750 // Allow printing of ModuleSummaryIndex from the debugger.
4751 LLVM_DUMP_METHOD
4752 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4753 #endif
4754