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