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