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