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