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