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