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