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