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