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