xref: /freebsd/contrib/llvm-project/llvm/lib/IR/AsmWriter.cpp (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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((isDigit(StrVal[0]) || ((StrVal[0] == '-' || StrVal[0] == '+') &&
1372                                        isDigit(StrVal[1]))) &&
1373                "[-+]?[0-9] regex does not match!");
1374         // Reparse stringized version!
1375         if (APFloat(APFloat::IEEEdouble(), StrVal).convertToDouble() == Val) {
1376           Out << StrVal;
1377           return;
1378         }
1379       }
1380       // Otherwise we could not reparse it to exactly the same value, so we must
1381       // output the string in hexadecimal format!  Note that loading and storing
1382       // floating point types changes the bits of NaNs on some hosts, notably
1383       // x86, so we must not use these types.
1384       static_assert(sizeof(double) == sizeof(uint64_t),
1385                     "assuming that double is 64 bits!");
1386       APFloat apf = APF;
1387       // Floats are represented in ASCII IR as double, convert.
1388       // FIXME: We should allow 32-bit hex float and remove this.
1389       if (!isDouble) {
1390         // A signaling NaN is quieted on conversion, so we need to recreate the
1391         // expected value after convert (quiet bit of the payload is clear).
1392         bool IsSNAN = apf.isSignaling();
1393         apf.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1394                     &ignored);
1395         if (IsSNAN) {
1396           APInt Payload = apf.bitcastToAPInt();
1397           apf = APFloat::getSNaN(APFloat::IEEEdouble(), apf.isNegative(),
1398                                  &Payload);
1399         }
1400       }
1401       Out << format_hex(apf.bitcastToAPInt().getZExtValue(), 0, /*Upper=*/true);
1402       return;
1403     }
1404 
1405     // Either half, bfloat or some form of long double.
1406     // These appear as a magic letter identifying the type, then a
1407     // fixed number of hex digits.
1408     Out << "0x";
1409     APInt API = APF.bitcastToAPInt();
1410     if (&APF.getSemantics() == &APFloat::x87DoubleExtended()) {
1411       Out << 'K';
1412       Out << format_hex_no_prefix(API.getHiBits(16).getZExtValue(), 4,
1413                                   /*Upper=*/true);
1414       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1415                                   /*Upper=*/true);
1416       return;
1417     } else if (&APF.getSemantics() == &APFloat::IEEEquad()) {
1418       Out << 'L';
1419       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1420                                   /*Upper=*/true);
1421       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1422                                   /*Upper=*/true);
1423     } else if (&APF.getSemantics() == &APFloat::PPCDoubleDouble()) {
1424       Out << 'M';
1425       Out << format_hex_no_prefix(API.getLoBits(64).getZExtValue(), 16,
1426                                   /*Upper=*/true);
1427       Out << format_hex_no_prefix(API.getHiBits(64).getZExtValue(), 16,
1428                                   /*Upper=*/true);
1429     } else if (&APF.getSemantics() == &APFloat::IEEEhalf()) {
1430       Out << 'H';
1431       Out << format_hex_no_prefix(API.getZExtValue(), 4,
1432                                   /*Upper=*/true);
1433     } else if (&APF.getSemantics() == &APFloat::BFloat()) {
1434       Out << 'R';
1435       Out << format_hex_no_prefix(API.getZExtValue(), 4,
1436                                   /*Upper=*/true);
1437     } else
1438       llvm_unreachable("Unsupported floating point type");
1439     return;
1440   }
1441 
1442   if (isa<ConstantAggregateZero>(CV)) {
1443     Out << "zeroinitializer";
1444     return;
1445   }
1446 
1447   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1448     Out << "blockaddress(";
1449     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1450                            Context);
1451     Out << ", ";
1452     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1453                            Context);
1454     Out << ")";
1455     return;
1456   }
1457 
1458   if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1459     Out << "dso_local_equivalent ";
1460     WriteAsOperandInternal(Out, Equiv->getGlobalValue(), &TypePrinter, Machine,
1461                            Context);
1462     return;
1463   }
1464 
1465   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1466     Type *ETy = CA->getType()->getElementType();
1467     Out << '[';
1468     TypePrinter.print(ETy, Out);
1469     Out << ' ';
1470     WriteAsOperandInternal(Out, CA->getOperand(0),
1471                            &TypePrinter, Machine,
1472                            Context);
1473     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1474       Out << ", ";
1475       TypePrinter.print(ETy, Out);
1476       Out << ' ';
1477       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1478                              Context);
1479     }
1480     Out << ']';
1481     return;
1482   }
1483 
1484   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1485     // As a special case, print the array as a string if it is an array of
1486     // i8 with ConstantInt values.
1487     if (CA->isString()) {
1488       Out << "c\"";
1489       printEscapedString(CA->getAsString(), Out);
1490       Out << '"';
1491       return;
1492     }
1493 
1494     Type *ETy = CA->getType()->getElementType();
1495     Out << '[';
1496     TypePrinter.print(ETy, Out);
1497     Out << ' ';
1498     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1499                            &TypePrinter, Machine,
1500                            Context);
1501     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1502       Out << ", ";
1503       TypePrinter.print(ETy, Out);
1504       Out << ' ';
1505       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1506                              Machine, Context);
1507     }
1508     Out << ']';
1509     return;
1510   }
1511 
1512   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1513     if (CS->getType()->isPacked())
1514       Out << '<';
1515     Out << '{';
1516     unsigned N = CS->getNumOperands();
1517     if (N) {
1518       Out << ' ';
1519       TypePrinter.print(CS->getOperand(0)->getType(), Out);
1520       Out << ' ';
1521 
1522       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1523                              Context);
1524 
1525       for (unsigned i = 1; i < N; i++) {
1526         Out << ", ";
1527         TypePrinter.print(CS->getOperand(i)->getType(), Out);
1528         Out << ' ';
1529 
1530         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1531                                Context);
1532       }
1533       Out << ' ';
1534     }
1535 
1536     Out << '}';
1537     if (CS->getType()->isPacked())
1538       Out << '>';
1539     return;
1540   }
1541 
1542   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1543     auto *CVVTy = cast<FixedVectorType>(CV->getType());
1544     Type *ETy = CVVTy->getElementType();
1545     Out << '<';
1546     TypePrinter.print(ETy, Out);
1547     Out << ' ';
1548     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1549                            Machine, Context);
1550     for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
1551       Out << ", ";
1552       TypePrinter.print(ETy, Out);
1553       Out << ' ';
1554       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1555                              Machine, Context);
1556     }
1557     Out << '>';
1558     return;
1559   }
1560 
1561   if (isa<ConstantPointerNull>(CV)) {
1562     Out << "null";
1563     return;
1564   }
1565 
1566   if (isa<ConstantTokenNone>(CV)) {
1567     Out << "none";
1568     return;
1569   }
1570 
1571   if (isa<PoisonValue>(CV)) {
1572     Out << "poison";
1573     return;
1574   }
1575 
1576   if (isa<UndefValue>(CV)) {
1577     Out << "undef";
1578     return;
1579   }
1580 
1581   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1582     Out << CE->getOpcodeName();
1583     WriteOptimizationInfo(Out, CE);
1584     if (CE->isCompare())
1585       Out << ' ' << CmpInst::getPredicateName(
1586                         static_cast<CmpInst::Predicate>(CE->getPredicate()));
1587     Out << " (";
1588 
1589     Optional<unsigned> InRangeOp;
1590     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1591       TypePrinter.print(GEP->getSourceElementType(), Out);
1592       Out << ", ";
1593       InRangeOp = GEP->getInRangeIndex();
1594       if (InRangeOp)
1595         ++*InRangeOp;
1596     }
1597 
1598     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1599       if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1600         Out << "inrange ";
1601       TypePrinter.print((*OI)->getType(), Out);
1602       Out << ' ';
1603       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1604       if (OI+1 != CE->op_end())
1605         Out << ", ";
1606     }
1607 
1608     if (CE->hasIndices()) {
1609       ArrayRef<unsigned> Indices = CE->getIndices();
1610       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1611         Out << ", " << Indices[i];
1612     }
1613 
1614     if (CE->isCast()) {
1615       Out << " to ";
1616       TypePrinter.print(CE->getType(), Out);
1617     }
1618 
1619     if (CE->getOpcode() == Instruction::ShuffleVector)
1620       PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
1621 
1622     Out << ')';
1623     return;
1624   }
1625 
1626   Out << "<placeholder or erroneous Constant>";
1627 }
1628 
1629 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1630                          TypePrinting *TypePrinter, SlotTracker *Machine,
1631                          const Module *Context) {
1632   Out << "!{";
1633   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1634     const Metadata *MD = Node->getOperand(mi);
1635     if (!MD)
1636       Out << "null";
1637     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1638       Value *V = MDV->getValue();
1639       TypePrinter->print(V->getType(), Out);
1640       Out << ' ';
1641       WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1642     } else {
1643       WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1644     }
1645     if (mi + 1 != me)
1646       Out << ", ";
1647   }
1648 
1649   Out << "}";
1650 }
1651 
1652 namespace {
1653 
1654 struct FieldSeparator {
1655   bool Skip = true;
1656   const char *Sep;
1657 
1658   FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1659 };
1660 
1661 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1662   if (FS.Skip) {
1663     FS.Skip = false;
1664     return OS;
1665   }
1666   return OS << FS.Sep;
1667 }
1668 
1669 struct MDFieldPrinter {
1670   raw_ostream &Out;
1671   FieldSeparator FS;
1672   TypePrinting *TypePrinter = nullptr;
1673   SlotTracker *Machine = nullptr;
1674   const Module *Context = nullptr;
1675 
1676   explicit MDFieldPrinter(raw_ostream &Out) : Out(Out) {}
1677   MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1678                  SlotTracker *Machine, const Module *Context)
1679       : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1680   }
1681 
1682   void printTag(const DINode *N);
1683   void printMacinfoType(const DIMacroNode *N);
1684   void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1685   void printString(StringRef Name, StringRef Value,
1686                    bool ShouldSkipEmpty = true);
1687   void printMetadata(StringRef Name, const Metadata *MD,
1688                      bool ShouldSkipNull = true);
1689   template <class IntTy>
1690   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1691   void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1692                   bool ShouldSkipZero);
1693   void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1694   void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1695   void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1696   template <class IntTy, class Stringifier>
1697   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1698                       bool ShouldSkipZero = true);
1699   void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1700   void printNameTableKind(StringRef Name,
1701                           DICompileUnit::DebugNameTableKind NTK);
1702 };
1703 
1704 } // end anonymous namespace
1705 
1706 void MDFieldPrinter::printTag(const DINode *N) {
1707   Out << FS << "tag: ";
1708   auto Tag = dwarf::TagString(N->getTag());
1709   if (!Tag.empty())
1710     Out << Tag;
1711   else
1712     Out << N->getTag();
1713 }
1714 
1715 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1716   Out << FS << "type: ";
1717   auto Type = dwarf::MacinfoString(N->getMacinfoType());
1718   if (!Type.empty())
1719     Out << Type;
1720   else
1721     Out << N->getMacinfoType();
1722 }
1723 
1724 void MDFieldPrinter::printChecksum(
1725     const DIFile::ChecksumInfo<StringRef> &Checksum) {
1726   Out << FS << "checksumkind: " << Checksum.getKindAsString();
1727   printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1728 }
1729 
1730 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1731                                  bool ShouldSkipEmpty) {
1732   if (ShouldSkipEmpty && Value.empty())
1733     return;
1734 
1735   Out << FS << Name << ": \"";
1736   printEscapedString(Value, Out);
1737   Out << "\"";
1738 }
1739 
1740 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1741                                    TypePrinting *TypePrinter,
1742                                    SlotTracker *Machine,
1743                                    const Module *Context) {
1744   if (!MD) {
1745     Out << "null";
1746     return;
1747   }
1748   WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1749 }
1750 
1751 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1752                                    bool ShouldSkipNull) {
1753   if (ShouldSkipNull && !MD)
1754     return;
1755 
1756   Out << FS << Name << ": ";
1757   writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1758 }
1759 
1760 template <class IntTy>
1761 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1762   if (ShouldSkipZero && !Int)
1763     return;
1764 
1765   Out << FS << Name << ": " << Int;
1766 }
1767 
1768 void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
1769                                 bool IsUnsigned, bool ShouldSkipZero) {
1770   if (ShouldSkipZero && Int.isNullValue())
1771     return;
1772 
1773   Out << FS << Name << ": ";
1774   Int.print(Out, !IsUnsigned);
1775 }
1776 
1777 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1778                                Optional<bool> Default) {
1779   if (Default && Value == *Default)
1780     return;
1781   Out << FS << Name << ": " << (Value ? "true" : "false");
1782 }
1783 
1784 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1785   if (!Flags)
1786     return;
1787 
1788   Out << FS << Name << ": ";
1789 
1790   SmallVector<DINode::DIFlags, 8> SplitFlags;
1791   auto Extra = DINode::splitFlags(Flags, SplitFlags);
1792 
1793   FieldSeparator FlagsFS(" | ");
1794   for (auto F : SplitFlags) {
1795     auto StringF = DINode::getFlagString(F);
1796     assert(!StringF.empty() && "Expected valid flag");
1797     Out << FlagsFS << StringF;
1798   }
1799   if (Extra || SplitFlags.empty())
1800     Out << FlagsFS << Extra;
1801 }
1802 
1803 void MDFieldPrinter::printDISPFlags(StringRef Name,
1804                                     DISubprogram::DISPFlags Flags) {
1805   // Always print this field, because no flags in the IR at all will be
1806   // interpreted as old-style isDefinition: true.
1807   Out << FS << Name << ": ";
1808 
1809   if (!Flags) {
1810     Out << 0;
1811     return;
1812   }
1813 
1814   SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
1815   auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
1816 
1817   FieldSeparator FlagsFS(" | ");
1818   for (auto F : SplitFlags) {
1819     auto StringF = DISubprogram::getFlagString(F);
1820     assert(!StringF.empty() && "Expected valid flag");
1821     Out << FlagsFS << StringF;
1822   }
1823   if (Extra || SplitFlags.empty())
1824     Out << FlagsFS << Extra;
1825 }
1826 
1827 void MDFieldPrinter::printEmissionKind(StringRef Name,
1828                                        DICompileUnit::DebugEmissionKind EK) {
1829   Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1830 }
1831 
1832 void MDFieldPrinter::printNameTableKind(StringRef Name,
1833                                         DICompileUnit::DebugNameTableKind NTK) {
1834   if (NTK == DICompileUnit::DebugNameTableKind::Default)
1835     return;
1836   Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1837 }
1838 
1839 template <class IntTy, class Stringifier>
1840 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1841                                     Stringifier toString, bool ShouldSkipZero) {
1842   if (!Value)
1843     return;
1844 
1845   Out << FS << Name << ": ";
1846   auto S = toString(Value);
1847   if (!S.empty())
1848     Out << S;
1849   else
1850     Out << Value;
1851 }
1852 
1853 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1854                                TypePrinting *TypePrinter, SlotTracker *Machine,
1855                                const Module *Context) {
1856   Out << "!GenericDINode(";
1857   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1858   Printer.printTag(N);
1859   Printer.printString("header", N->getHeader());
1860   if (N->getNumDwarfOperands()) {
1861     Out << Printer.FS << "operands: {";
1862     FieldSeparator IFS;
1863     for (auto &I : N->dwarf_operands()) {
1864       Out << IFS;
1865       writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1866     }
1867     Out << "}";
1868   }
1869   Out << ")";
1870 }
1871 
1872 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1873                             TypePrinting *TypePrinter, SlotTracker *Machine,
1874                             const Module *Context) {
1875   Out << "!DILocation(";
1876   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1877   // Always output the line, since 0 is a relevant and important value for it.
1878   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1879   Printer.printInt("column", DL->getColumn());
1880   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1881   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1882   Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1883                     /* Default */ false);
1884   Out << ")";
1885 }
1886 
1887 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1888                             TypePrinting *TypePrinter, SlotTracker *Machine,
1889                             const Module *Context) {
1890   Out << "!DISubrange(";
1891   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1892   if (auto *CE = N->getCount().dyn_cast<ConstantInt*>())
1893     Printer.printInt("count", CE->getSExtValue(), /* ShouldSkipZero */ false);
1894   else
1895     Printer.printMetadata("count", N->getCount().dyn_cast<DIVariable *>(),
1896                           /*ShouldSkipNull */ true);
1897 
1898   // A lowerBound of constant 0 should not be skipped, since it is different
1899   // from an unspecified lower bound (= nullptr).
1900   auto *LBound = N->getRawLowerBound();
1901   if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
1902     auto *LV = cast<ConstantInt>(LE->getValue());
1903     Printer.printInt("lowerBound", LV->getSExtValue(),
1904                      /* ShouldSkipZero */ false);
1905   } else
1906     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1907 
1908   auto *UBound = N->getRawUpperBound();
1909   if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
1910     auto *UV = cast<ConstantInt>(UE->getValue());
1911     Printer.printInt("upperBound", UV->getSExtValue(),
1912                      /* ShouldSkipZero */ false);
1913   } else
1914     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1915 
1916   auto *Stride = N->getRawStride();
1917   if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
1918     auto *SV = cast<ConstantInt>(SE->getValue());
1919     Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
1920   } else
1921     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1922 
1923   Out << ")";
1924 }
1925 
1926 static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
1927                                    TypePrinting *TypePrinter,
1928                                    SlotTracker *Machine,
1929                                    const Module *Context) {
1930   Out << "!DIGenericSubrange(";
1931   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1932 
1933   auto IsConstant = [&](Metadata *Bound) -> bool {
1934     if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
1935       return BE->isSignedConstant();
1936     }
1937     return false;
1938   };
1939 
1940   auto GetConstant = [&](Metadata *Bound) -> int64_t {
1941     assert(IsConstant(Bound) && "Expected constant");
1942     auto *BE = dyn_cast_or_null<DIExpression>(Bound);
1943     return static_cast<int64_t>(BE->getElement(1));
1944   };
1945 
1946   auto *Count = N->getRawCountNode();
1947   if (IsConstant(Count))
1948     Printer.printInt("count", GetConstant(Count),
1949                      /* ShouldSkipZero */ false);
1950   else
1951     Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1952 
1953   auto *LBound = N->getRawLowerBound();
1954   if (IsConstant(LBound))
1955     Printer.printInt("lowerBound", GetConstant(LBound),
1956                      /* ShouldSkipZero */ false);
1957   else
1958     Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1959 
1960   auto *UBound = N->getRawUpperBound();
1961   if (IsConstant(UBound))
1962     Printer.printInt("upperBound", GetConstant(UBound),
1963                      /* ShouldSkipZero */ false);
1964   else
1965     Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1966 
1967   auto *Stride = N->getRawStride();
1968   if (IsConstant(Stride))
1969     Printer.printInt("stride", GetConstant(Stride),
1970                      /* ShouldSkipZero */ false);
1971   else
1972     Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1973 
1974   Out << ")";
1975 }
1976 
1977 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1978                               TypePrinting *, SlotTracker *, const Module *) {
1979   Out << "!DIEnumerator(";
1980   MDFieldPrinter Printer(Out);
1981   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1982   Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
1983                      /*ShouldSkipZero=*/false);
1984   if (N->isUnsigned())
1985     Printer.printBool("isUnsigned", true);
1986   Out << ")";
1987 }
1988 
1989 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1990                              TypePrinting *, SlotTracker *, const Module *) {
1991   Out << "!DIBasicType(";
1992   MDFieldPrinter Printer(Out);
1993   if (N->getTag() != dwarf::DW_TAG_base_type)
1994     Printer.printTag(N);
1995   Printer.printString("name", N->getName());
1996   Printer.printInt("size", N->getSizeInBits());
1997   Printer.printInt("align", N->getAlignInBits());
1998   Printer.printDwarfEnum("encoding", N->getEncoding(),
1999                          dwarf::AttributeEncodingString);
2000   Printer.printDIFlags("flags", N->getFlags());
2001   Out << ")";
2002 }
2003 
2004 static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
2005                               TypePrinting *TypePrinter, SlotTracker *Machine,
2006                               const Module *Context) {
2007   Out << "!DIStringType(";
2008   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2009   if (N->getTag() != dwarf::DW_TAG_string_type)
2010     Printer.printTag(N);
2011   Printer.printString("name", N->getName());
2012   Printer.printMetadata("stringLength", N->getRawStringLength());
2013   Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
2014   Printer.printInt("size", N->getSizeInBits());
2015   Printer.printInt("align", N->getAlignInBits());
2016   Printer.printDwarfEnum("encoding", N->getEncoding(),
2017                          dwarf::AttributeEncodingString);
2018   Out << ")";
2019 }
2020 
2021 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2022                                TypePrinting *TypePrinter, SlotTracker *Machine,
2023                                const Module *Context) {
2024   Out << "!DIDerivedType(";
2025   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2026   Printer.printTag(N);
2027   Printer.printString("name", N->getName());
2028   Printer.printMetadata("scope", N->getRawScope());
2029   Printer.printMetadata("file", N->getRawFile());
2030   Printer.printInt("line", N->getLine());
2031   Printer.printMetadata("baseType", N->getRawBaseType(),
2032                         /* ShouldSkipNull */ false);
2033   Printer.printInt("size", N->getSizeInBits());
2034   Printer.printInt("align", N->getAlignInBits());
2035   Printer.printInt("offset", N->getOffsetInBits());
2036   Printer.printDIFlags("flags", N->getFlags());
2037   Printer.printMetadata("extraData", N->getRawExtraData());
2038   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2039     Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
2040                      /* ShouldSkipZero */ false);
2041   Out << ")";
2042 }
2043 
2044 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2045                                  TypePrinting *TypePrinter,
2046                                  SlotTracker *Machine, const Module *Context) {
2047   Out << "!DICompositeType(";
2048   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2049   Printer.printTag(N);
2050   Printer.printString("name", N->getName());
2051   Printer.printMetadata("scope", N->getRawScope());
2052   Printer.printMetadata("file", N->getRawFile());
2053   Printer.printInt("line", N->getLine());
2054   Printer.printMetadata("baseType", N->getRawBaseType());
2055   Printer.printInt("size", N->getSizeInBits());
2056   Printer.printInt("align", N->getAlignInBits());
2057   Printer.printInt("offset", N->getOffsetInBits());
2058   Printer.printDIFlags("flags", N->getFlags());
2059   Printer.printMetadata("elements", N->getRawElements());
2060   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
2061                          dwarf::LanguageString);
2062   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
2063   Printer.printMetadata("templateParams", N->getRawTemplateParams());
2064   Printer.printString("identifier", N->getIdentifier());
2065   Printer.printMetadata("discriminator", N->getRawDiscriminator());
2066   Printer.printMetadata("dataLocation", N->getRawDataLocation());
2067   Printer.printMetadata("associated", N->getRawAssociated());
2068   Printer.printMetadata("allocated", N->getRawAllocated());
2069   if (auto *RankConst = N->getRankConst())
2070     Printer.printInt("rank", RankConst->getSExtValue(),
2071                      /* ShouldSkipZero */ false);
2072   else
2073     Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2074   Out << ")";
2075 }
2076 
2077 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2078                                   TypePrinting *TypePrinter,
2079                                   SlotTracker *Machine, const Module *Context) {
2080   Out << "!DISubroutineType(";
2081   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2082   Printer.printDIFlags("flags", N->getFlags());
2083   Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
2084   Printer.printMetadata("types", N->getRawTypeArray(),
2085                         /* ShouldSkipNull */ false);
2086   Out << ")";
2087 }
2088 
2089 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
2090                         SlotTracker *, const Module *) {
2091   Out << "!DIFile(";
2092   MDFieldPrinter Printer(Out);
2093   Printer.printString("filename", N->getFilename(),
2094                       /* ShouldSkipEmpty */ false);
2095   Printer.printString("directory", N->getDirectory(),
2096                       /* ShouldSkipEmpty */ false);
2097   // Print all values for checksum together, or not at all.
2098   if (N->getChecksum())
2099     Printer.printChecksum(*N->getChecksum());
2100   Printer.printString("source", N->getSource().getValueOr(StringRef()),
2101                       /* ShouldSkipEmpty */ true);
2102   Out << ")";
2103 }
2104 
2105 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2106                                TypePrinting *TypePrinter, SlotTracker *Machine,
2107                                const Module *Context) {
2108   Out << "!DICompileUnit(";
2109   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2110   Printer.printDwarfEnum("language", N->getSourceLanguage(),
2111                          dwarf::LanguageString, /* ShouldSkipZero */ false);
2112   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2113   Printer.printString("producer", N->getProducer());
2114   Printer.printBool("isOptimized", N->isOptimized());
2115   Printer.printString("flags", N->getFlags());
2116   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
2117                    /* ShouldSkipZero */ false);
2118   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
2119   Printer.printEmissionKind("emissionKind", N->getEmissionKind());
2120   Printer.printMetadata("enums", N->getRawEnumTypes());
2121   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
2122   Printer.printMetadata("globals", N->getRawGlobalVariables());
2123   Printer.printMetadata("imports", N->getRawImportedEntities());
2124   Printer.printMetadata("macros", N->getRawMacros());
2125   Printer.printInt("dwoId", N->getDWOId());
2126   Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
2127   Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
2128                     false);
2129   Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
2130   Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
2131   Printer.printString("sysroot", N->getSysRoot());
2132   Printer.printString("sdk", N->getSDK());
2133   Out << ")";
2134 }
2135 
2136 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2137                               TypePrinting *TypePrinter, SlotTracker *Machine,
2138                               const Module *Context) {
2139   Out << "!DISubprogram(";
2140   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2141   Printer.printString("name", N->getName());
2142   Printer.printString("linkageName", N->getLinkageName());
2143   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2144   Printer.printMetadata("file", N->getRawFile());
2145   Printer.printInt("line", N->getLine());
2146   Printer.printMetadata("type", N->getRawType());
2147   Printer.printInt("scopeLine", N->getScopeLine());
2148   Printer.printMetadata("containingType", N->getRawContainingType());
2149   if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
2150       N->getVirtualIndex() != 0)
2151     Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
2152   Printer.printInt("thisAdjustment", N->getThisAdjustment());
2153   Printer.printDIFlags("flags", N->getFlags());
2154   Printer.printDISPFlags("spFlags", N->getSPFlags());
2155   Printer.printMetadata("unit", N->getRawUnit());
2156   Printer.printMetadata("templateParams", N->getRawTemplateParams());
2157   Printer.printMetadata("declaration", N->getRawDeclaration());
2158   Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
2159   Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2160   Out << ")";
2161 }
2162 
2163 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2164                                 TypePrinting *TypePrinter, SlotTracker *Machine,
2165                                 const Module *Context) {
2166   Out << "!DILexicalBlock(";
2167   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2168   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2169   Printer.printMetadata("file", N->getRawFile());
2170   Printer.printInt("line", N->getLine());
2171   Printer.printInt("column", N->getColumn());
2172   Out << ")";
2173 }
2174 
2175 static void writeDILexicalBlockFile(raw_ostream &Out,
2176                                     const DILexicalBlockFile *N,
2177                                     TypePrinting *TypePrinter,
2178                                     SlotTracker *Machine,
2179                                     const Module *Context) {
2180   Out << "!DILexicalBlockFile(";
2181   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2182   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2183   Printer.printMetadata("file", N->getRawFile());
2184   Printer.printInt("discriminator", N->getDiscriminator(),
2185                    /* ShouldSkipZero */ false);
2186   Out << ")";
2187 }
2188 
2189 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2190                              TypePrinting *TypePrinter, SlotTracker *Machine,
2191                              const Module *Context) {
2192   Out << "!DINamespace(";
2193   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2194   Printer.printString("name", N->getName());
2195   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2196   Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2197   Out << ")";
2198 }
2199 
2200 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2201                                TypePrinting *TypePrinter, SlotTracker *Machine,
2202                                const Module *Context) {
2203   Out << "!DICommonBlock(";
2204   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2205   Printer.printMetadata("scope", N->getRawScope(), false);
2206   Printer.printMetadata("declaration", N->getRawDecl(), false);
2207   Printer.printString("name", N->getName());
2208   Printer.printMetadata("file", N->getRawFile());
2209   Printer.printInt("line", N->getLineNo());
2210   Out << ")";
2211 }
2212 
2213 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2214                          TypePrinting *TypePrinter, SlotTracker *Machine,
2215                          const Module *Context) {
2216   Out << "!DIMacro(";
2217   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2218   Printer.printMacinfoType(N);
2219   Printer.printInt("line", N->getLine());
2220   Printer.printString("name", N->getName());
2221   Printer.printString("value", N->getValue());
2222   Out << ")";
2223 }
2224 
2225 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2226                              TypePrinting *TypePrinter, SlotTracker *Machine,
2227                              const Module *Context) {
2228   Out << "!DIMacroFile(";
2229   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2230   Printer.printInt("line", N->getLine());
2231   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2232   Printer.printMetadata("nodes", N->getRawElements());
2233   Out << ")";
2234 }
2235 
2236 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2237                           TypePrinting *TypePrinter, SlotTracker *Machine,
2238                           const Module *Context) {
2239   Out << "!DIModule(";
2240   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2241   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2242   Printer.printString("name", N->getName());
2243   Printer.printString("configMacros", N->getConfigurationMacros());
2244   Printer.printString("includePath", N->getIncludePath());
2245   Printer.printString("apinotes", N->getAPINotesFile());
2246   Printer.printMetadata("file", N->getRawFile());
2247   Printer.printInt("line", N->getLineNo());
2248   Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
2249   Out << ")";
2250 }
2251 
2252 
2253 static void writeDITemplateTypeParameter(raw_ostream &Out,
2254                                          const DITemplateTypeParameter *N,
2255                                          TypePrinting *TypePrinter,
2256                                          SlotTracker *Machine,
2257                                          const Module *Context) {
2258   Out << "!DITemplateTypeParameter(";
2259   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2260   Printer.printString("name", N->getName());
2261   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2262   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2263   Out << ")";
2264 }
2265 
2266 static void writeDITemplateValueParameter(raw_ostream &Out,
2267                                           const DITemplateValueParameter *N,
2268                                           TypePrinting *TypePrinter,
2269                                           SlotTracker *Machine,
2270                                           const Module *Context) {
2271   Out << "!DITemplateValueParameter(";
2272   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2273   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2274     Printer.printTag(N);
2275   Printer.printString("name", N->getName());
2276   Printer.printMetadata("type", N->getRawType());
2277   Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2278   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2279   Out << ")";
2280 }
2281 
2282 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2283                                   TypePrinting *TypePrinter,
2284                                   SlotTracker *Machine, const Module *Context) {
2285   Out << "!DIGlobalVariable(";
2286   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2287   Printer.printString("name", N->getName());
2288   Printer.printString("linkageName", N->getLinkageName());
2289   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2290   Printer.printMetadata("file", N->getRawFile());
2291   Printer.printInt("line", N->getLine());
2292   Printer.printMetadata("type", N->getRawType());
2293   Printer.printBool("isLocal", N->isLocalToUnit());
2294   Printer.printBool("isDefinition", N->isDefinition());
2295   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2296   Printer.printMetadata("templateParams", N->getRawTemplateParams());
2297   Printer.printInt("align", N->getAlignInBits());
2298   Out << ")";
2299 }
2300 
2301 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2302                                  TypePrinting *TypePrinter,
2303                                  SlotTracker *Machine, const Module *Context) {
2304   Out << "!DILocalVariable(";
2305   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2306   Printer.printString("name", N->getName());
2307   Printer.printInt("arg", N->getArg());
2308   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2309   Printer.printMetadata("file", N->getRawFile());
2310   Printer.printInt("line", N->getLine());
2311   Printer.printMetadata("type", N->getRawType());
2312   Printer.printDIFlags("flags", N->getFlags());
2313   Printer.printInt("align", N->getAlignInBits());
2314   Out << ")";
2315 }
2316 
2317 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2318                          TypePrinting *TypePrinter,
2319                          SlotTracker *Machine, const Module *Context) {
2320   Out << "!DILabel(";
2321   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2322   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2323   Printer.printString("name", N->getName());
2324   Printer.printMetadata("file", N->getRawFile());
2325   Printer.printInt("line", N->getLine());
2326   Out << ")";
2327 }
2328 
2329 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2330                               TypePrinting *TypePrinter, SlotTracker *Machine,
2331                               const Module *Context) {
2332   Out << "!DIExpression(";
2333   FieldSeparator FS;
2334   if (N->isValid()) {
2335     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
2336       auto OpStr = dwarf::OperationEncodingString(I->getOp());
2337       assert(!OpStr.empty() && "Expected valid opcode");
2338 
2339       Out << FS << OpStr;
2340       if (I->getOp() == dwarf::DW_OP_LLVM_convert) {
2341         Out << FS << I->getArg(0);
2342         Out << FS << dwarf::AttributeEncodingString(I->getArg(1));
2343       } else {
2344         for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
2345           Out << FS << I->getArg(A);
2346       }
2347     }
2348   } else {
2349     for (const auto &I : N->getElements())
2350       Out << FS << I;
2351   }
2352   Out << ")";
2353 }
2354 
2355 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2356                                             const DIGlobalVariableExpression *N,
2357                                             TypePrinting *TypePrinter,
2358                                             SlotTracker *Machine,
2359                                             const Module *Context) {
2360   Out << "!DIGlobalVariableExpression(";
2361   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2362   Printer.printMetadata("var", N->getVariable());
2363   Printer.printMetadata("expr", N->getExpression());
2364   Out << ")";
2365 }
2366 
2367 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2368                                 TypePrinting *TypePrinter, SlotTracker *Machine,
2369                                 const Module *Context) {
2370   Out << "!DIObjCProperty(";
2371   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2372   Printer.printString("name", N->getName());
2373   Printer.printMetadata("file", N->getRawFile());
2374   Printer.printInt("line", N->getLine());
2375   Printer.printString("setter", N->getSetterName());
2376   Printer.printString("getter", N->getGetterName());
2377   Printer.printInt("attributes", N->getAttributes());
2378   Printer.printMetadata("type", N->getRawType());
2379   Out << ")";
2380 }
2381 
2382 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2383                                   TypePrinting *TypePrinter,
2384                                   SlotTracker *Machine, const Module *Context) {
2385   Out << "!DIImportedEntity(";
2386   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
2387   Printer.printTag(N);
2388   Printer.printString("name", N->getName());
2389   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2390   Printer.printMetadata("entity", N->getRawEntity());
2391   Printer.printMetadata("file", N->getRawFile());
2392   Printer.printInt("line", N->getLine());
2393   Out << ")";
2394 }
2395 
2396 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2397                                     TypePrinting *TypePrinter,
2398                                     SlotTracker *Machine,
2399                                     const Module *Context) {
2400   if (Node->isDistinct())
2401     Out << "distinct ";
2402   else if (Node->isTemporary())
2403     Out << "<temporary!> "; // Handle broken code.
2404 
2405   switch (Node->getMetadataID()) {
2406   default:
2407     llvm_unreachable("Expected uniquable MDNode");
2408 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
2409   case Metadata::CLASS##Kind:                                                  \
2410     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
2411     break;
2412 #include "llvm/IR/Metadata.def"
2413   }
2414 }
2415 
2416 // Full implementation of printing a Value as an operand with support for
2417 // TypePrinting, etc.
2418 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2419                                    TypePrinting *TypePrinter,
2420                                    SlotTracker *Machine,
2421                                    const Module *Context) {
2422   if (V->hasName()) {
2423     PrintLLVMName(Out, V);
2424     return;
2425   }
2426 
2427   const Constant *CV = dyn_cast<Constant>(V);
2428   if (CV && !isa<GlobalValue>(CV)) {
2429     assert(TypePrinter && "Constants require TypePrinting!");
2430     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
2431     return;
2432   }
2433 
2434   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2435     Out << "asm ";
2436     if (IA->hasSideEffects())
2437       Out << "sideeffect ";
2438     if (IA->isAlignStack())
2439       Out << "alignstack ";
2440     // We don't emit the AD_ATT dialect as it's the assumed default.
2441     if (IA->getDialect() == InlineAsm::AD_Intel)
2442       Out << "inteldialect ";
2443     Out << '"';
2444     printEscapedString(IA->getAsmString(), Out);
2445     Out << "\", \"";
2446     printEscapedString(IA->getConstraintString(), Out);
2447     Out << '"';
2448     return;
2449   }
2450 
2451   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
2452     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
2453                            Context, /* FromValue */ true);
2454     return;
2455   }
2456 
2457   char Prefix = '%';
2458   int Slot;
2459   // If we have a SlotTracker, use it.
2460   if (Machine) {
2461     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2462       Slot = Machine->getGlobalSlot(GV);
2463       Prefix = '@';
2464     } else {
2465       Slot = Machine->getLocalSlot(V);
2466 
2467       // If the local value didn't succeed, then we may be referring to a value
2468       // from a different function.  Translate it, as this can happen when using
2469       // address of blocks.
2470       if (Slot == -1)
2471         if ((Machine = createSlotTracker(V))) {
2472           Slot = Machine->getLocalSlot(V);
2473           delete Machine;
2474         }
2475     }
2476   } else if ((Machine = createSlotTracker(V))) {
2477     // Otherwise, create one to get the # and then destroy it.
2478     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2479       Slot = Machine->getGlobalSlot(GV);
2480       Prefix = '@';
2481     } else {
2482       Slot = Machine->getLocalSlot(V);
2483     }
2484     delete Machine;
2485     Machine = nullptr;
2486   } else {
2487     Slot = -1;
2488   }
2489 
2490   if (Slot != -1)
2491     Out << Prefix << Slot;
2492   else
2493     Out << "<badref>";
2494 }
2495 
2496 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
2497                                    TypePrinting *TypePrinter,
2498                                    SlotTracker *Machine, const Module *Context,
2499                                    bool FromValue) {
2500   // Write DIExpressions inline when used as a value. Improves readability of
2501   // debug info intrinsics.
2502   if (const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2503     writeDIExpression(Out, Expr, TypePrinter, Machine, Context);
2504     return;
2505   }
2506 
2507   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2508     std::unique_ptr<SlotTracker> MachineStorage;
2509     if (!Machine) {
2510       MachineStorage = std::make_unique<SlotTracker>(Context);
2511       Machine = MachineStorage.get();
2512     }
2513     int Slot = Machine->getMetadataSlot(N);
2514     if (Slot == -1) {
2515       if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2516         writeDILocation(Out, Loc, TypePrinter, Machine, Context);
2517         return;
2518       }
2519       // Give the pointer value instead of "badref", since this comes up all
2520       // the time when debugging.
2521       Out << "<" << N << ">";
2522     } else
2523       Out << '!' << Slot;
2524     return;
2525   }
2526 
2527   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2528     Out << "!\"";
2529     printEscapedString(MDS->getString(), Out);
2530     Out << '"';
2531     return;
2532   }
2533 
2534   auto *V = cast<ValueAsMetadata>(MD);
2535   assert(TypePrinter && "TypePrinter required for metadata values");
2536   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2537          "Unexpected function-local metadata outside of value argument");
2538 
2539   TypePrinter->print(V->getValue()->getType(), Out);
2540   Out << ' ';
2541   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2542 }
2543 
2544 namespace {
2545 
2546 class AssemblyWriter {
2547   formatted_raw_ostream &Out;
2548   const Module *TheModule = nullptr;
2549   const ModuleSummaryIndex *TheIndex = nullptr;
2550   std::unique_ptr<SlotTracker> SlotTrackerStorage;
2551   SlotTracker &Machine;
2552   TypePrinting TypePrinter;
2553   AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2554   SetVector<const Comdat *> Comdats;
2555   bool IsForDebug;
2556   bool ShouldPreserveUseListOrder;
2557   UseListOrderStack UseListOrders;
2558   SmallVector<StringRef, 8> MDNames;
2559   /// Synchronization scope names registered with LLVMContext.
2560   SmallVector<StringRef, 8> SSNs;
2561   DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
2562 
2563 public:
2564   /// Construct an AssemblyWriter with an external SlotTracker
2565   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2566                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2567                  bool ShouldPreserveUseListOrder = false);
2568 
2569   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2570                  const ModuleSummaryIndex *Index, bool IsForDebug);
2571 
2572   void printMDNodeBody(const MDNode *MD);
2573   void printNamedMDNode(const NamedMDNode *NMD);
2574 
2575   void printModule(const Module *M);
2576 
2577   void writeOperand(const Value *Op, bool PrintType);
2578   void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2579   void writeOperandBundles(const CallBase *Call);
2580   void writeSyncScope(const LLVMContext &Context,
2581                       SyncScope::ID SSID);
2582   void writeAtomic(const LLVMContext &Context,
2583                    AtomicOrdering Ordering,
2584                    SyncScope::ID SSID);
2585   void writeAtomicCmpXchg(const LLVMContext &Context,
2586                           AtomicOrdering SuccessOrdering,
2587                           AtomicOrdering FailureOrdering,
2588                           SyncScope::ID SSID);
2589 
2590   void writeAllMDNodes();
2591   void writeMDNode(unsigned Slot, const MDNode *Node);
2592   void writeAttribute(const Attribute &Attr, bool InAttrGroup = false);
2593   void writeAttributeSet(const AttributeSet &AttrSet, bool InAttrGroup = false);
2594   void writeAllAttributeGroups();
2595 
2596   void printTypeIdentities();
2597   void printGlobal(const GlobalVariable *GV);
2598   void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2599   void printComdat(const Comdat *C);
2600   void printFunction(const Function *F);
2601   void printArgument(const Argument *FA, AttributeSet Attrs);
2602   void printBasicBlock(const BasicBlock *BB);
2603   void printInstructionLine(const Instruction &I);
2604   void printInstruction(const Instruction &I);
2605 
2606   void printUseListOrder(const UseListOrder &Order);
2607   void printUseLists(const Function *F);
2608 
2609   void printModuleSummaryIndex();
2610   void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2611   void printSummary(const GlobalValueSummary &Summary);
2612   void printAliasSummary(const AliasSummary *AS);
2613   void printGlobalVarSummary(const GlobalVarSummary *GS);
2614   void printFunctionSummary(const FunctionSummary *FS);
2615   void printTypeIdSummary(const TypeIdSummary &TIS);
2616   void printTypeIdCompatibleVtableSummary(const TypeIdCompatibleVtableInfo &TI);
2617   void printTypeTestResolution(const TypeTestResolution &TTRes);
2618   void printArgs(const std::vector<uint64_t> &Args);
2619   void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2620   void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2621   void printVFuncId(const FunctionSummary::VFuncId VFId);
2622   void
2623   printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> &VCallList,
2624                       const char *Tag);
2625   void
2626   printConstVCalls(const std::vector<FunctionSummary::ConstVCall> &VCallList,
2627                    const char *Tag);
2628 
2629 private:
2630   /// Print out metadata attachments.
2631   void printMetadataAttachments(
2632       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2633       StringRef Separator);
2634 
2635   // printInfoComment - Print a little comment after the instruction indicating
2636   // which slot it occupies.
2637   void printInfoComment(const Value &V);
2638 
2639   // printGCRelocateComment - print comment after call to the gc.relocate
2640   // intrinsic indicating base and derived pointer names.
2641   void printGCRelocateComment(const GCRelocateInst &Relocate);
2642 };
2643 
2644 } // end anonymous namespace
2645 
2646 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2647                                const Module *M, AssemblyAnnotationWriter *AAW,
2648                                bool IsForDebug, bool ShouldPreserveUseListOrder)
2649     : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2650       IsForDebug(IsForDebug),
2651       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2652   if (!TheModule)
2653     return;
2654   for (const GlobalObject &GO : TheModule->global_objects())
2655     if (const Comdat *C = GO.getComdat())
2656       Comdats.insert(C);
2657 }
2658 
2659 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2660                                const ModuleSummaryIndex *Index, bool IsForDebug)
2661     : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2662       IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2663 
2664 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2665   if (!Operand) {
2666     Out << "<null operand!>";
2667     return;
2668   }
2669   if (PrintType) {
2670     TypePrinter.print(Operand->getType(), Out);
2671     Out << ' ';
2672   }
2673   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2674 }
2675 
2676 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2677                                     SyncScope::ID SSID) {
2678   switch (SSID) {
2679   case SyncScope::System: {
2680     break;
2681   }
2682   default: {
2683     if (SSNs.empty())
2684       Context.getSyncScopeNames(SSNs);
2685 
2686     Out << " syncscope(\"";
2687     printEscapedString(SSNs[SSID], Out);
2688     Out << "\")";
2689     break;
2690   }
2691   }
2692 }
2693 
2694 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2695                                  AtomicOrdering Ordering,
2696                                  SyncScope::ID SSID) {
2697   if (Ordering == AtomicOrdering::NotAtomic)
2698     return;
2699 
2700   writeSyncScope(Context, SSID);
2701   Out << " " << toIRString(Ordering);
2702 }
2703 
2704 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2705                                         AtomicOrdering SuccessOrdering,
2706                                         AtomicOrdering FailureOrdering,
2707                                         SyncScope::ID SSID) {
2708   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2709          FailureOrdering != AtomicOrdering::NotAtomic);
2710 
2711   writeSyncScope(Context, SSID);
2712   Out << " " << toIRString(SuccessOrdering);
2713   Out << " " << toIRString(FailureOrdering);
2714 }
2715 
2716 void AssemblyWriter::writeParamOperand(const Value *Operand,
2717                                        AttributeSet Attrs) {
2718   if (!Operand) {
2719     Out << "<null operand!>";
2720     return;
2721   }
2722 
2723   // Print the type
2724   TypePrinter.print(Operand->getType(), Out);
2725   // Print parameter attributes list
2726   if (Attrs.hasAttributes()) {
2727     Out << ' ';
2728     writeAttributeSet(Attrs);
2729   }
2730   Out << ' ';
2731   // Print the operand
2732   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2733 }
2734 
2735 void AssemblyWriter::writeOperandBundles(const CallBase *Call) {
2736   if (!Call->hasOperandBundles())
2737     return;
2738 
2739   Out << " [ ";
2740 
2741   bool FirstBundle = true;
2742   for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) {
2743     OperandBundleUse BU = Call->getOperandBundleAt(i);
2744 
2745     if (!FirstBundle)
2746       Out << ", ";
2747     FirstBundle = false;
2748 
2749     Out << '"';
2750     printEscapedString(BU.getTagName(), Out);
2751     Out << '"';
2752 
2753     Out << '(';
2754 
2755     bool FirstInput = true;
2756     for (const auto &Input : BU.Inputs) {
2757       if (!FirstInput)
2758         Out << ", ";
2759       FirstInput = false;
2760 
2761       TypePrinter.print(Input->getType(), Out);
2762       Out << " ";
2763       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2764     }
2765 
2766     Out << ')';
2767   }
2768 
2769   Out << " ]";
2770 }
2771 
2772 void AssemblyWriter::printModule(const Module *M) {
2773   Machine.initializeIfNeeded();
2774 
2775   if (ShouldPreserveUseListOrder)
2776     UseListOrders = predictUseListOrder(M);
2777 
2778   if (!M->getModuleIdentifier().empty() &&
2779       // Don't print the ID if it will start a new line (which would
2780       // require a comment char before it).
2781       M->getModuleIdentifier().find('\n') == std::string::npos)
2782     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2783 
2784   if (!M->getSourceFileName().empty()) {
2785     Out << "source_filename = \"";
2786     printEscapedString(M->getSourceFileName(), Out);
2787     Out << "\"\n";
2788   }
2789 
2790   const std::string &DL = M->getDataLayoutStr();
2791   if (!DL.empty())
2792     Out << "target datalayout = \"" << DL << "\"\n";
2793   if (!M->getTargetTriple().empty())
2794     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2795 
2796   if (!M->getModuleInlineAsm().empty()) {
2797     Out << '\n';
2798 
2799     // Split the string into lines, to make it easier to read the .ll file.
2800     StringRef Asm = M->getModuleInlineAsm();
2801     do {
2802       StringRef Front;
2803       std::tie(Front, Asm) = Asm.split('\n');
2804 
2805       // We found a newline, print the portion of the asm string from the
2806       // last newline up to this newline.
2807       Out << "module asm \"";
2808       printEscapedString(Front, Out);
2809       Out << "\"\n";
2810     } while (!Asm.empty());
2811   }
2812 
2813   printTypeIdentities();
2814 
2815   // Output all comdats.
2816   if (!Comdats.empty())
2817     Out << '\n';
2818   for (const Comdat *C : Comdats) {
2819     printComdat(C);
2820     if (C != Comdats.back())
2821       Out << '\n';
2822   }
2823 
2824   // Output all globals.
2825   if (!M->global_empty()) Out << '\n';
2826   for (const GlobalVariable &GV : M->globals()) {
2827     printGlobal(&GV); Out << '\n';
2828   }
2829 
2830   // Output all aliases.
2831   if (!M->alias_empty()) Out << "\n";
2832   for (const GlobalAlias &GA : M->aliases())
2833     printIndirectSymbol(&GA);
2834 
2835   // Output all ifuncs.
2836   if (!M->ifunc_empty()) Out << "\n";
2837   for (const GlobalIFunc &GI : M->ifuncs())
2838     printIndirectSymbol(&GI);
2839 
2840   // Output global use-lists.
2841   printUseLists(nullptr);
2842 
2843   // Output all of the functions.
2844   for (const Function &F : *M) {
2845     Out << '\n';
2846     printFunction(&F);
2847   }
2848   assert(UseListOrders.empty() && "All use-lists should have been consumed");
2849 
2850   // Output all attribute groups.
2851   if (!Machine.as_empty()) {
2852     Out << '\n';
2853     writeAllAttributeGroups();
2854   }
2855 
2856   // Output named metadata.
2857   if (!M->named_metadata_empty()) Out << '\n';
2858 
2859   for (const NamedMDNode &Node : M->named_metadata())
2860     printNamedMDNode(&Node);
2861 
2862   // Output metadata.
2863   if (!Machine.mdn_empty()) {
2864     Out << '\n';
2865     writeAllMDNodes();
2866   }
2867 }
2868 
2869 void AssemblyWriter::printModuleSummaryIndex() {
2870   assert(TheIndex);
2871   int NumSlots = Machine.initializeIndexIfNeeded();
2872 
2873   Out << "\n";
2874 
2875   // Print module path entries. To print in order, add paths to a vector
2876   // indexed by module slot.
2877   std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2878   std::string RegularLTOModuleName =
2879       ModuleSummaryIndex::getRegularLTOModuleName();
2880   moduleVec.resize(TheIndex->modulePaths().size());
2881   for (auto &ModPath : TheIndex->modulePaths())
2882     moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2883         // A module id of -1 is a special entry for a regular LTO module created
2884         // during the thin link.
2885         ModPath.second.first == -1u ? RegularLTOModuleName
2886                                     : (std::string)std::string(ModPath.first()),
2887         ModPath.second.second);
2888 
2889   unsigned i = 0;
2890   for (auto &ModPair : moduleVec) {
2891     Out << "^" << i++ << " = module: (";
2892     Out << "path: \"";
2893     printEscapedString(ModPair.first, Out);
2894     Out << "\", hash: (";
2895     FieldSeparator FS;
2896     for (auto Hash : ModPair.second)
2897       Out << FS << Hash;
2898     Out << "))\n";
2899   }
2900 
2901   // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2902   // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2903   for (auto &GlobalList : *TheIndex) {
2904     auto GUID = GlobalList.first;
2905     for (auto &Summary : GlobalList.second.SummaryList)
2906       SummaryToGUIDMap[Summary.get()] = GUID;
2907   }
2908 
2909   // Print the global value summary entries.
2910   for (auto &GlobalList : *TheIndex) {
2911     auto GUID = GlobalList.first;
2912     auto VI = TheIndex->getValueInfo(GlobalList);
2913     printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2914   }
2915 
2916   // Print the TypeIdMap entries.
2917   for (auto TidIter = TheIndex->typeIds().begin();
2918        TidIter != TheIndex->typeIds().end(); TidIter++) {
2919     Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
2920         << " = typeid: (name: \"" << TidIter->second.first << "\"";
2921     printTypeIdSummary(TidIter->second.second);
2922     Out << ") ; guid = " << TidIter->first << "\n";
2923   }
2924 
2925   // Print the TypeIdCompatibleVtableMap entries.
2926   for (auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
2927     auto GUID = GlobalValue::getGUID(TId.first);
2928     Out << "^" << Machine.getGUIDSlot(GUID)
2929         << " = typeidCompatibleVTable: (name: \"" << TId.first << "\"";
2930     printTypeIdCompatibleVtableSummary(TId.second);
2931     Out << ") ; guid = " << GUID << "\n";
2932   }
2933 
2934   // Don't emit flags when it's not really needed (value is zero by default).
2935   if (TheIndex->getFlags()) {
2936     Out << "^" << NumSlots << " = flags: " << TheIndex->getFlags() << "\n";
2937     ++NumSlots;
2938   }
2939 
2940   Out << "^" << NumSlots << " = blockcount: " << TheIndex->getBlockCount()
2941       << "\n";
2942 }
2943 
2944 static const char *
2945 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2946   switch (K) {
2947   case WholeProgramDevirtResolution::Indir:
2948     return "indir";
2949   case WholeProgramDevirtResolution::SingleImpl:
2950     return "singleImpl";
2951   case WholeProgramDevirtResolution::BranchFunnel:
2952     return "branchFunnel";
2953   }
2954   llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2955 }
2956 
2957 static const char *getWholeProgDevirtResByArgKindName(
2958     WholeProgramDevirtResolution::ByArg::Kind K) {
2959   switch (K) {
2960   case WholeProgramDevirtResolution::ByArg::Indir:
2961     return "indir";
2962   case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2963     return "uniformRetVal";
2964   case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2965     return "uniqueRetVal";
2966   case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2967     return "virtualConstProp";
2968   }
2969   llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2970 }
2971 
2972 static const char *getTTResKindName(TypeTestResolution::Kind K) {
2973   switch (K) {
2974   case TypeTestResolution::Unknown:
2975     return "unknown";
2976   case TypeTestResolution::Unsat:
2977     return "unsat";
2978   case TypeTestResolution::ByteArray:
2979     return "byteArray";
2980   case TypeTestResolution::Inline:
2981     return "inline";
2982   case TypeTestResolution::Single:
2983     return "single";
2984   case TypeTestResolution::AllOnes:
2985     return "allOnes";
2986   }
2987   llvm_unreachable("invalid TypeTestResolution kind");
2988 }
2989 
2990 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2991   Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2992       << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2993 
2994   // The following fields are only used if the target does not support the use
2995   // of absolute symbols to store constants. Print only if non-zero.
2996   if (TTRes.AlignLog2)
2997     Out << ", alignLog2: " << TTRes.AlignLog2;
2998   if (TTRes.SizeM1)
2999     Out << ", sizeM1: " << TTRes.SizeM1;
3000   if (TTRes.BitMask)
3001     // BitMask is uint8_t which causes it to print the corresponding char.
3002     Out << ", bitMask: " << (unsigned)TTRes.BitMask;
3003   if (TTRes.InlineBits)
3004     Out << ", inlineBits: " << TTRes.InlineBits;
3005 
3006   Out << ")";
3007 }
3008 
3009 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
3010   Out << ", summary: (";
3011   printTypeTestResolution(TIS.TTRes);
3012   if (!TIS.WPDRes.empty()) {
3013     Out << ", wpdResolutions: (";
3014     FieldSeparator FS;
3015     for (auto &WPDRes : TIS.WPDRes) {
3016       Out << FS;
3017       Out << "(offset: " << WPDRes.first << ", ";
3018       printWPDRes(WPDRes.second);
3019       Out << ")";
3020     }
3021     Out << ")";
3022   }
3023   Out << ")";
3024 }
3025 
3026 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3027     const TypeIdCompatibleVtableInfo &TI) {
3028   Out << ", summary: (";
3029   FieldSeparator FS;
3030   for (auto &P : TI) {
3031     Out << FS;
3032     Out << "(offset: " << P.AddressPointOffset << ", ";
3033     Out << "^" << Machine.getGUIDSlot(P.VTableVI.getGUID());
3034     Out << ")";
3035   }
3036   Out << ")";
3037 }
3038 
3039 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
3040   Out << "args: (";
3041   FieldSeparator FS;
3042   for (auto arg : Args) {
3043     Out << FS;
3044     Out << arg;
3045   }
3046   Out << ")";
3047 }
3048 
3049 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
3050   Out << "wpdRes: (kind: ";
3051   Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
3052 
3053   if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
3054     Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
3055 
3056   if (!WPDRes.ResByArg.empty()) {
3057     Out << ", resByArg: (";
3058     FieldSeparator FS;
3059     for (auto &ResByArg : WPDRes.ResByArg) {
3060       Out << FS;
3061       printArgs(ResByArg.first);
3062       Out << ", byArg: (kind: ";
3063       Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
3064       if (ResByArg.second.TheKind ==
3065               WholeProgramDevirtResolution::ByArg::UniformRetVal ||
3066           ResByArg.second.TheKind ==
3067               WholeProgramDevirtResolution::ByArg::UniqueRetVal)
3068         Out << ", info: " << ResByArg.second.Info;
3069 
3070       // The following fields are only used if the target does not support the
3071       // use of absolute symbols to store constants. Print only if non-zero.
3072       if (ResByArg.second.Byte || ResByArg.second.Bit)
3073         Out << ", byte: " << ResByArg.second.Byte
3074             << ", bit: " << ResByArg.second.Bit;
3075 
3076       Out << ")";
3077     }
3078     Out << ")";
3079   }
3080   Out << ")";
3081 }
3082 
3083 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
3084   switch (SK) {
3085   case GlobalValueSummary::AliasKind:
3086     return "alias";
3087   case GlobalValueSummary::FunctionKind:
3088     return "function";
3089   case GlobalValueSummary::GlobalVarKind:
3090     return "variable";
3091   }
3092   llvm_unreachable("invalid summary kind");
3093 }
3094 
3095 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
3096   Out << ", aliasee: ";
3097   // The indexes emitted for distributed backends may not include the
3098   // aliasee summary (only if it is being imported directly). Handle
3099   // that case by just emitting "null" as the aliasee.
3100   if (AS->hasAliasee())
3101     Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
3102   else
3103     Out << "null";
3104 }
3105 
3106 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
3107   auto VTableFuncs = GS->vTableFuncs();
3108   Out << ", varFlags: (readonly: " << GS->VarFlags.MaybeReadOnly << ", "
3109       << "writeonly: " << GS->VarFlags.MaybeWriteOnly << ", "
3110       << "constant: " << GS->VarFlags.Constant;
3111   if (!VTableFuncs.empty())
3112     Out << ", "
3113         << "vcall_visibility: " << GS->VarFlags.VCallVisibility;
3114   Out << ")";
3115 
3116   if (!VTableFuncs.empty()) {
3117     Out << ", vTableFuncs: (";
3118     FieldSeparator FS;
3119     for (auto &P : VTableFuncs) {
3120       Out << FS;
3121       Out << "(virtFunc: ^" << Machine.getGUIDSlot(P.FuncVI.getGUID())
3122           << ", offset: " << P.VTableOffset;
3123       Out << ")";
3124     }
3125     Out << ")";
3126   }
3127 }
3128 
3129 static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
3130   switch (LT) {
3131   case GlobalValue::ExternalLinkage:
3132     return "external";
3133   case GlobalValue::PrivateLinkage:
3134     return "private";
3135   case GlobalValue::InternalLinkage:
3136     return "internal";
3137   case GlobalValue::LinkOnceAnyLinkage:
3138     return "linkonce";
3139   case GlobalValue::LinkOnceODRLinkage:
3140     return "linkonce_odr";
3141   case GlobalValue::WeakAnyLinkage:
3142     return "weak";
3143   case GlobalValue::WeakODRLinkage:
3144     return "weak_odr";
3145   case GlobalValue::CommonLinkage:
3146     return "common";
3147   case GlobalValue::AppendingLinkage:
3148     return "appending";
3149   case GlobalValue::ExternalWeakLinkage:
3150     return "extern_weak";
3151   case GlobalValue::AvailableExternallyLinkage:
3152     return "available_externally";
3153   }
3154   llvm_unreachable("invalid linkage");
3155 }
3156 
3157 // When printing the linkage types in IR where the ExternalLinkage is
3158 // not printed, and other linkage types are expected to be printed with
3159 // a space after the name.
3160 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
3161   if (LT == GlobalValue::ExternalLinkage)
3162     return "";
3163   return getLinkageName(LT) + " ";
3164 }
3165 
3166 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
3167   Out << ", insts: " << FS->instCount();
3168 
3169   FunctionSummary::FFlags FFlags = FS->fflags();
3170   if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
3171       FFlags.ReturnDoesNotAlias | FFlags.NoInline | FFlags.AlwaysInline) {
3172     Out << ", funcFlags: (";
3173     Out << "readNone: " << FFlags.ReadNone;
3174     Out << ", readOnly: " << FFlags.ReadOnly;
3175     Out << ", noRecurse: " << FFlags.NoRecurse;
3176     Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
3177     Out << ", noInline: " << FFlags.NoInline;
3178     Out << ", alwaysInline: " << FFlags.AlwaysInline;
3179     Out << ")";
3180   }
3181   if (!FS->calls().empty()) {
3182     Out << ", calls: (";
3183     FieldSeparator IFS;
3184     for (auto &Call : FS->calls()) {
3185       Out << IFS;
3186       Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
3187       if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
3188         Out << ", hotness: " << getHotnessName(Call.second.getHotness());
3189       else if (Call.second.RelBlockFreq)
3190         Out << ", relbf: " << Call.second.RelBlockFreq;
3191       Out << ")";
3192     }
3193     Out << ")";
3194   }
3195 
3196   if (const auto *TIdInfo = FS->getTypeIdInfo())
3197     printTypeIdInfo(*TIdInfo);
3198 
3199   auto PrintRange = [&](const ConstantRange &Range) {
3200     Out << "[" << Range.getSignedMin() << ", " << Range.getSignedMax() << "]";
3201   };
3202 
3203   if (!FS->paramAccesses().empty()) {
3204     Out << ", params: (";
3205     FieldSeparator IFS;
3206     for (auto &PS : FS->paramAccesses()) {
3207       Out << IFS;
3208       Out << "(param: " << PS.ParamNo;
3209       Out << ", offset: ";
3210       PrintRange(PS.Use);
3211       if (!PS.Calls.empty()) {
3212         Out << ", calls: (";
3213         FieldSeparator IFS;
3214         for (auto &Call : PS.Calls) {
3215           Out << IFS;
3216           Out << "(callee: ^" << Machine.getGUIDSlot(Call.Callee.getGUID());
3217           Out << ", param: " << Call.ParamNo;
3218           Out << ", offset: ";
3219           PrintRange(Call.Offsets);
3220           Out << ")";
3221         }
3222         Out << ")";
3223       }
3224       Out << ")";
3225     }
3226     Out << ")";
3227   }
3228 }
3229 
3230 void AssemblyWriter::printTypeIdInfo(
3231     const FunctionSummary::TypeIdInfo &TIDInfo) {
3232   Out << ", typeIdInfo: (";
3233   FieldSeparator TIDFS;
3234   if (!TIDInfo.TypeTests.empty()) {
3235     Out << TIDFS;
3236     Out << "typeTests: (";
3237     FieldSeparator FS;
3238     for (auto &GUID : TIDInfo.TypeTests) {
3239       auto TidIter = TheIndex->typeIds().equal_range(GUID);
3240       if (TidIter.first == TidIter.second) {
3241         Out << FS;
3242         Out << GUID;
3243         continue;
3244       }
3245       // Print all type id that correspond to this GUID.
3246       for (auto It = TidIter.first; It != TidIter.second; ++It) {
3247         Out << FS;
3248         auto Slot = Machine.getTypeIdSlot(It->second.first);
3249         assert(Slot != -1);
3250         Out << "^" << Slot;
3251       }
3252     }
3253     Out << ")";
3254   }
3255   if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
3256     Out << TIDFS;
3257     printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
3258   }
3259   if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
3260     Out << TIDFS;
3261     printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
3262   }
3263   if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
3264     Out << TIDFS;
3265     printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
3266                      "typeTestAssumeConstVCalls");
3267   }
3268   if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
3269     Out << TIDFS;
3270     printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
3271                      "typeCheckedLoadConstVCalls");
3272   }
3273   Out << ")";
3274 }
3275 
3276 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
3277   auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
3278   if (TidIter.first == TidIter.second) {
3279     Out << "vFuncId: (";
3280     Out << "guid: " << VFId.GUID;
3281     Out << ", offset: " << VFId.Offset;
3282     Out << ")";
3283     return;
3284   }
3285   // Print all type id that correspond to this GUID.
3286   FieldSeparator FS;
3287   for (auto It = TidIter.first; It != TidIter.second; ++It) {
3288     Out << FS;
3289     Out << "vFuncId: (";
3290     auto Slot = Machine.getTypeIdSlot(It->second.first);
3291     assert(Slot != -1);
3292     Out << "^" << Slot;
3293     Out << ", offset: " << VFId.Offset;
3294     Out << ")";
3295   }
3296 }
3297 
3298 void AssemblyWriter::printNonConstVCalls(
3299     const std::vector<FunctionSummary::VFuncId> &VCallList, const char *Tag) {
3300   Out << Tag << ": (";
3301   FieldSeparator FS;
3302   for (auto &VFuncId : VCallList) {
3303     Out << FS;
3304     printVFuncId(VFuncId);
3305   }
3306   Out << ")";
3307 }
3308 
3309 void AssemblyWriter::printConstVCalls(
3310     const std::vector<FunctionSummary::ConstVCall> &VCallList,
3311     const char *Tag) {
3312   Out << Tag << ": (";
3313   FieldSeparator FS;
3314   for (auto &ConstVCall : VCallList) {
3315     Out << FS;
3316     Out << "(";
3317     printVFuncId(ConstVCall.VFunc);
3318     if (!ConstVCall.Args.empty()) {
3319       Out << ", ";
3320       printArgs(ConstVCall.Args);
3321     }
3322     Out << ")";
3323   }
3324   Out << ")";
3325 }
3326 
3327 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3328   GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3329   GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3330   Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3331   Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3332       << ", flags: (";
3333   Out << "linkage: " << getLinkageName(LT);
3334   Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3335   Out << ", live: " << GVFlags.Live;
3336   Out << ", dsoLocal: " << GVFlags.DSOLocal;
3337   Out << ", canAutoHide: " << GVFlags.CanAutoHide;
3338   Out << ")";
3339 
3340   if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3341     printAliasSummary(cast<AliasSummary>(&Summary));
3342   else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3343     printFunctionSummary(cast<FunctionSummary>(&Summary));
3344   else
3345     printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3346 
3347   auto RefList = Summary.refs();
3348   if (!RefList.empty()) {
3349     Out << ", refs: (";
3350     FieldSeparator FS;
3351     for (auto &Ref : RefList) {
3352       Out << FS;
3353       if (Ref.isReadOnly())
3354         Out << "readonly ";
3355       else if (Ref.isWriteOnly())
3356         Out << "writeonly ";
3357       Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3358     }
3359     Out << ")";
3360   }
3361 
3362   Out << ")";
3363 }
3364 
3365 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3366   Out << "^" << Slot << " = gv: (";
3367   if (!VI.name().empty())
3368     Out << "name: \"" << VI.name() << "\"";
3369   else
3370     Out << "guid: " << VI.getGUID();
3371   if (!VI.getSummaryList().empty()) {
3372     Out << ", summaries: (";
3373     FieldSeparator FS;
3374     for (auto &Summary : VI.getSummaryList()) {
3375       Out << FS;
3376       printSummary(*Summary);
3377     }
3378     Out << ")";
3379   }
3380   Out << ")";
3381   if (!VI.name().empty())
3382     Out << " ; guid = " << VI.getGUID();
3383   Out << "\n";
3384 }
3385 
3386 static void printMetadataIdentifier(StringRef Name,
3387                                     formatted_raw_ostream &Out) {
3388   if (Name.empty()) {
3389     Out << "<empty name> ";
3390   } else {
3391     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3392         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3393       Out << Name[0];
3394     else
3395       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3396     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3397       unsigned char C = Name[i];
3398       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3399           C == '.' || C == '_')
3400         Out << C;
3401       else
3402         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3403     }
3404   }
3405 }
3406 
3407 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3408   Out << '!';
3409   printMetadataIdentifier(NMD->getName(), Out);
3410   Out << " = !{";
3411   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3412     if (i)
3413       Out << ", ";
3414 
3415     // Write DIExpressions inline.
3416     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3417     MDNode *Op = NMD->getOperand(i);
3418     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3419       writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3420       continue;
3421     }
3422 
3423     int Slot = Machine.getMetadataSlot(Op);
3424     if (Slot == -1)
3425       Out << "<badref>";
3426     else
3427       Out << '!' << Slot;
3428   }
3429   Out << "}\n";
3430 }
3431 
3432 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
3433                             formatted_raw_ostream &Out) {
3434   switch (Vis) {
3435   case GlobalValue::DefaultVisibility: break;
3436   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
3437   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3438   }
3439 }
3440 
3441 static void PrintDSOLocation(const GlobalValue &GV,
3442                              formatted_raw_ostream &Out) {
3443   if (GV.isDSOLocal() && !GV.isImplicitDSOLocal())
3444     Out << "dso_local ";
3445 }
3446 
3447 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3448                                  formatted_raw_ostream &Out) {
3449   switch (SCT) {
3450   case GlobalValue::DefaultStorageClass: break;
3451   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3452   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3453   }
3454 }
3455 
3456 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3457                                   formatted_raw_ostream &Out) {
3458   switch (TLM) {
3459     case GlobalVariable::NotThreadLocal:
3460       break;
3461     case GlobalVariable::GeneralDynamicTLSModel:
3462       Out << "thread_local ";
3463       break;
3464     case GlobalVariable::LocalDynamicTLSModel:
3465       Out << "thread_local(localdynamic) ";
3466       break;
3467     case GlobalVariable::InitialExecTLSModel:
3468       Out << "thread_local(initialexec) ";
3469       break;
3470     case GlobalVariable::LocalExecTLSModel:
3471       Out << "thread_local(localexec) ";
3472       break;
3473   }
3474 }
3475 
3476 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3477   switch (UA) {
3478   case GlobalVariable::UnnamedAddr::None:
3479     return "";
3480   case GlobalVariable::UnnamedAddr::Local:
3481     return "local_unnamed_addr";
3482   case GlobalVariable::UnnamedAddr::Global:
3483     return "unnamed_addr";
3484   }
3485   llvm_unreachable("Unknown UnnamedAddr");
3486 }
3487 
3488 static void maybePrintComdat(formatted_raw_ostream &Out,
3489                              const GlobalObject &GO) {
3490   const Comdat *C = GO.getComdat();
3491   if (!C)
3492     return;
3493 
3494   if (isa<GlobalVariable>(GO))
3495     Out << ',';
3496   Out << " comdat";
3497 
3498   if (GO.getName() == C->getName())
3499     return;
3500 
3501   Out << '(';
3502   PrintLLVMName(Out, C->getName(), ComdatPrefix);
3503   Out << ')';
3504 }
3505 
3506 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3507   if (GV->isMaterializable())
3508     Out << "; Materializable\n";
3509 
3510   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
3511   Out << " = ";
3512 
3513   if (!GV->hasInitializer() && GV->hasExternalLinkage())
3514     Out << "external ";
3515 
3516   Out << getLinkageNameWithSpace(GV->getLinkage());
3517   PrintDSOLocation(*GV, Out);
3518   PrintVisibility(GV->getVisibility(), Out);
3519   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
3520   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
3521   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3522   if (!UA.empty())
3523       Out << UA << ' ';
3524 
3525   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3526     Out << "addrspace(" << AddressSpace << ") ";
3527   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3528   Out << (GV->isConstant() ? "constant " : "global ");
3529   TypePrinter.print(GV->getValueType(), Out);
3530 
3531   if (GV->hasInitializer()) {
3532     Out << ' ';
3533     writeOperand(GV->getInitializer(), false);
3534   }
3535 
3536   if (GV->hasSection()) {
3537     Out << ", section \"";
3538     printEscapedString(GV->getSection(), Out);
3539     Out << '"';
3540   }
3541   if (GV->hasPartition()) {
3542     Out << ", partition \"";
3543     printEscapedString(GV->getPartition(), Out);
3544     Out << '"';
3545   }
3546 
3547   maybePrintComdat(Out, *GV);
3548   if (GV->getAlignment())
3549     Out << ", align " << GV->getAlignment();
3550 
3551   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3552   GV->getAllMetadata(MDs);
3553   printMetadataAttachments(MDs, ", ");
3554 
3555   auto Attrs = GV->getAttributes();
3556   if (Attrs.hasAttributes())
3557     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3558 
3559   printInfoComment(*GV);
3560 }
3561 
3562 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3563   if (GIS->isMaterializable())
3564     Out << "; Materializable\n";
3565 
3566   WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
3567   Out << " = ";
3568 
3569   Out << getLinkageNameWithSpace(GIS->getLinkage());
3570   PrintDSOLocation(*GIS, Out);
3571   PrintVisibility(GIS->getVisibility(), Out);
3572   PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
3573   PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
3574   StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
3575   if (!UA.empty())
3576       Out << UA << ' ';
3577 
3578   if (isa<GlobalAlias>(GIS))
3579     Out << "alias ";
3580   else if (isa<GlobalIFunc>(GIS))
3581     Out << "ifunc ";
3582   else
3583     llvm_unreachable("Not an alias or ifunc!");
3584 
3585   TypePrinter.print(GIS->getValueType(), Out);
3586 
3587   Out << ", ";
3588 
3589   const Constant *IS = GIS->getIndirectSymbol();
3590 
3591   if (!IS) {
3592     TypePrinter.print(GIS->getType(), Out);
3593     Out << " <<NULL ALIASEE>>";
3594   } else {
3595     writeOperand(IS, !isa<ConstantExpr>(IS));
3596   }
3597 
3598   if (GIS->hasPartition()) {
3599     Out << ", partition \"";
3600     printEscapedString(GIS->getPartition(), Out);
3601     Out << '"';
3602   }
3603 
3604   printInfoComment(*GIS);
3605   Out << '\n';
3606 }
3607 
3608 void AssemblyWriter::printComdat(const Comdat *C) {
3609   C->print(Out);
3610 }
3611 
3612 void AssemblyWriter::printTypeIdentities() {
3613   if (TypePrinter.empty())
3614     return;
3615 
3616   Out << '\n';
3617 
3618   // Emit all numbered types.
3619   auto &NumberedTypes = TypePrinter.getNumberedTypes();
3620   for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3621     Out << '%' << I << " = type ";
3622 
3623     // Make sure we print out at least one level of the type structure, so
3624     // that we do not get %2 = type %2
3625     TypePrinter.printStructBody(NumberedTypes[I], Out);
3626     Out << '\n';
3627   }
3628 
3629   auto &NamedTypes = TypePrinter.getNamedTypes();
3630   for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3631     PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
3632     Out << " = type ";
3633 
3634     // Make sure we print out at least one level of the type structure, so
3635     // that we do not get %FILE = type %FILE
3636     TypePrinter.printStructBody(NamedTypes[I], Out);
3637     Out << '\n';
3638   }
3639 }
3640 
3641 /// printFunction - Print all aspects of a function.
3642 void AssemblyWriter::printFunction(const Function *F) {
3643   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3644 
3645   if (F->isMaterializable())
3646     Out << "; Materializable\n";
3647 
3648   const AttributeList &Attrs = F->getAttributes();
3649   if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
3650     AttributeSet AS = Attrs.getFnAttributes();
3651     std::string AttrStr;
3652 
3653     for (const Attribute &Attr : AS) {
3654       if (!Attr.isStringAttribute()) {
3655         if (!AttrStr.empty()) AttrStr += ' ';
3656         AttrStr += Attr.getAsString();
3657       }
3658     }
3659 
3660     if (!AttrStr.empty())
3661       Out << "; Function Attrs: " << AttrStr << '\n';
3662   }
3663 
3664   Machine.incorporateFunction(F);
3665 
3666   if (F->isDeclaration()) {
3667     Out << "declare";
3668     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3669     F->getAllMetadata(MDs);
3670     printMetadataAttachments(MDs, " ");
3671     Out << ' ';
3672   } else
3673     Out << "define ";
3674 
3675   Out << getLinkageNameWithSpace(F->getLinkage());
3676   PrintDSOLocation(*F, Out);
3677   PrintVisibility(F->getVisibility(), Out);
3678   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3679 
3680   // Print the calling convention.
3681   if (F->getCallingConv() != CallingConv::C) {
3682     PrintCallingConv(F->getCallingConv(), Out);
3683     Out << " ";
3684   }
3685 
3686   FunctionType *FT = F->getFunctionType();
3687   if (Attrs.hasAttributes(AttributeList::ReturnIndex))
3688     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3689   TypePrinter.print(F->getReturnType(), Out);
3690   Out << ' ';
3691   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
3692   Out << '(';
3693 
3694   // Loop over the arguments, printing them...
3695   if (F->isDeclaration() && !IsForDebug) {
3696     // We're only interested in the type here - don't print argument names.
3697     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3698       // Insert commas as we go... the first arg doesn't get a comma
3699       if (I)
3700         Out << ", ";
3701       // Output type...
3702       TypePrinter.print(FT->getParamType(I), Out);
3703 
3704       AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3705       if (ArgAttrs.hasAttributes()) {
3706         Out << ' ';
3707         writeAttributeSet(ArgAttrs);
3708       }
3709     }
3710   } else {
3711     // The arguments are meaningful here, print them in detail.
3712     for (const Argument &Arg : F->args()) {
3713       // Insert commas as we go... the first arg doesn't get a comma
3714       if (Arg.getArgNo() != 0)
3715         Out << ", ";
3716       printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
3717     }
3718   }
3719 
3720   // Finish printing arguments...
3721   if (FT->isVarArg()) {
3722     if (FT->getNumParams()) Out << ", ";
3723     Out << "...";  // Output varargs portion of signature!
3724   }
3725   Out << ')';
3726   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3727   if (!UA.empty())
3728     Out << ' ' << UA;
3729   // We print the function address space if it is non-zero or if we are writing
3730   // a module with a non-zero program address space or if there is no valid
3731   // Module* so that the file can be parsed without the datalayout string.
3732   const Module *Mod = F->getParent();
3733   if (F->getAddressSpace() != 0 || !Mod ||
3734       Mod->getDataLayout().getProgramAddressSpace() != 0)
3735     Out << " addrspace(" << F->getAddressSpace() << ")";
3736   if (Attrs.hasAttributes(AttributeList::FunctionIndex))
3737     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
3738   if (F->hasSection()) {
3739     Out << " section \"";
3740     printEscapedString(F->getSection(), Out);
3741     Out << '"';
3742   }
3743   if (F->hasPartition()) {
3744     Out << " partition \"";
3745     printEscapedString(F->getPartition(), Out);
3746     Out << '"';
3747   }
3748   maybePrintComdat(Out, *F);
3749   if (F->getAlignment())
3750     Out << " align " << F->getAlignment();
3751   if (F->hasGC())
3752     Out << " gc \"" << F->getGC() << '"';
3753   if (F->hasPrefixData()) {
3754     Out << " prefix ";
3755     writeOperand(F->getPrefixData(), true);
3756   }
3757   if (F->hasPrologueData()) {
3758     Out << " prologue ";
3759     writeOperand(F->getPrologueData(), true);
3760   }
3761   if (F->hasPersonalityFn()) {
3762     Out << " personality ";
3763     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3764   }
3765 
3766   if (F->isDeclaration()) {
3767     Out << '\n';
3768   } else {
3769     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3770     F->getAllMetadata(MDs);
3771     printMetadataAttachments(MDs, " ");
3772 
3773     Out << " {";
3774     // Output all of the function's basic blocks.
3775     for (const BasicBlock &BB : *F)
3776       printBasicBlock(&BB);
3777 
3778     // Output the function's use-lists.
3779     printUseLists(F);
3780 
3781     Out << "}\n";
3782   }
3783 
3784   Machine.purgeFunction();
3785 }
3786 
3787 /// printArgument - This member is called for every argument that is passed into
3788 /// the function.  Simply print it out
3789 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3790   // Output type...
3791   TypePrinter.print(Arg->getType(), Out);
3792 
3793   // Output parameter attributes list
3794   if (Attrs.hasAttributes()) {
3795     Out << ' ';
3796     writeAttributeSet(Attrs);
3797   }
3798 
3799   // Output name, if available...
3800   if (Arg->hasName()) {
3801     Out << ' ';
3802     PrintLLVMName(Out, Arg);
3803   } else {
3804     int Slot = Machine.getLocalSlot(Arg);
3805     assert(Slot != -1 && "expect argument in function here");
3806     Out << " %" << Slot;
3807   }
3808 }
3809 
3810 /// printBasicBlock - This member is called for each basic block in a method.
3811 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3812   assert(BB && BB->getParent() && "block without parent!");
3813   bool IsEntryBlock = BB == &BB->getParent()->getEntryBlock();
3814   if (BB->hasName()) {              // Print out the label if it exists...
3815     Out << "\n";
3816     PrintLLVMName(Out, BB->getName(), LabelPrefix);
3817     Out << ':';
3818   } else if (!IsEntryBlock) {
3819     Out << "\n";
3820     int Slot = Machine.getLocalSlot(BB);
3821     if (Slot != -1)
3822       Out << Slot << ":";
3823     else
3824       Out << "<badref>:";
3825   }
3826 
3827   if (!IsEntryBlock) {
3828     // Output predecessors for the block.
3829     Out.PadToColumn(50);
3830     Out << ";";
3831     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3832 
3833     if (PI == PE) {
3834       Out << " No predecessors!";
3835     } else {
3836       Out << " preds = ";
3837       writeOperand(*PI, false);
3838       for (++PI; PI != PE; ++PI) {
3839         Out << ", ";
3840         writeOperand(*PI, false);
3841       }
3842     }
3843   }
3844 
3845   Out << "\n";
3846 
3847   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3848 
3849   // Output all of the instructions in the basic block...
3850   for (const Instruction &I : *BB) {
3851     printInstructionLine(I);
3852   }
3853 
3854   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3855 }
3856 
3857 /// printInstructionLine - Print an instruction and a newline character.
3858 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3859   printInstruction(I);
3860   Out << '\n';
3861 }
3862 
3863 /// printGCRelocateComment - print comment after call to the gc.relocate
3864 /// intrinsic indicating base and derived pointer names.
3865 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3866   Out << " ; (";
3867   writeOperand(Relocate.getBasePtr(), false);
3868   Out << ", ";
3869   writeOperand(Relocate.getDerivedPtr(), false);
3870   Out << ")";
3871 }
3872 
3873 /// printInfoComment - Print a little comment after the instruction indicating
3874 /// which slot it occupies.
3875 void AssemblyWriter::printInfoComment(const Value &V) {
3876   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3877     printGCRelocateComment(*Relocate);
3878 
3879   if (AnnotationWriter)
3880     AnnotationWriter->printInfoComment(V, Out);
3881 }
3882 
3883 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
3884                                     raw_ostream &Out) {
3885   // We print the address space of the call if it is non-zero.
3886   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
3887   bool PrintAddrSpace = CallAddrSpace != 0;
3888   if (!PrintAddrSpace) {
3889     const Module *Mod = getModuleFromVal(I);
3890     // We also print it if it is zero but not equal to the program address space
3891     // or if we can't find a valid Module* to make it possible to parse
3892     // the resulting file even without a datalayout string.
3893     if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
3894       PrintAddrSpace = true;
3895   }
3896   if (PrintAddrSpace)
3897     Out << " addrspace(" << CallAddrSpace << ")";
3898 }
3899 
3900 // This member is called for each Instruction in a function..
3901 void AssemblyWriter::printInstruction(const Instruction &I) {
3902   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
3903 
3904   // Print out indentation for an instruction.
3905   Out << "  ";
3906 
3907   // Print out name if it exists...
3908   if (I.hasName()) {
3909     PrintLLVMName(Out, &I);
3910     Out << " = ";
3911   } else if (!I.getType()->isVoidTy()) {
3912     // Print out the def slot taken.
3913     int SlotNum = Machine.getLocalSlot(&I);
3914     if (SlotNum == -1)
3915       Out << "<badref> = ";
3916     else
3917       Out << '%' << SlotNum << " = ";
3918   }
3919 
3920   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3921     if (CI->isMustTailCall())
3922       Out << "musttail ";
3923     else if (CI->isTailCall())
3924       Out << "tail ";
3925     else if (CI->isNoTailCall())
3926       Out << "notail ";
3927   }
3928 
3929   // Print out the opcode...
3930   Out << I.getOpcodeName();
3931 
3932   // If this is an atomic load or store, print out the atomic marker.
3933   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
3934       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3935     Out << " atomic";
3936 
3937   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3938     Out << " weak";
3939 
3940   // If this is a volatile operation, print out the volatile marker.
3941   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
3942       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3943       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3944       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3945     Out << " volatile";
3946 
3947   // Print out optimization information.
3948   WriteOptimizationInfo(Out, &I);
3949 
3950   // Print out the compare instruction predicates
3951   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
3952     Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
3953 
3954   // Print out the atomicrmw operation
3955   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
3956     Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
3957 
3958   // Print out the type of the operands...
3959   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
3960 
3961   // Special case conditional branches to swizzle the condition out to the front
3962   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
3963     const BranchInst &BI(cast<BranchInst>(I));
3964     Out << ' ';
3965     writeOperand(BI.getCondition(), true);
3966     Out << ", ";
3967     writeOperand(BI.getSuccessor(0), true);
3968     Out << ", ";
3969     writeOperand(BI.getSuccessor(1), true);
3970 
3971   } else if (isa<SwitchInst>(I)) {
3972     const SwitchInst& SI(cast<SwitchInst>(I));
3973     // Special case switch instruction to get formatting nice and correct.
3974     Out << ' ';
3975     writeOperand(SI.getCondition(), true);
3976     Out << ", ";
3977     writeOperand(SI.getDefaultDest(), true);
3978     Out << " [";
3979     for (auto Case : SI.cases()) {
3980       Out << "\n    ";
3981       writeOperand(Case.getCaseValue(), true);
3982       Out << ", ";
3983       writeOperand(Case.getCaseSuccessor(), true);
3984     }
3985     Out << "\n  ]";
3986   } else if (isa<IndirectBrInst>(I)) {
3987     // Special case indirectbr instruction to get formatting nice and correct.
3988     Out << ' ';
3989     writeOperand(Operand, true);
3990     Out << ", [";
3991 
3992     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3993       if (i != 1)
3994         Out << ", ";
3995       writeOperand(I.getOperand(i), true);
3996     }
3997     Out << ']';
3998   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3999     Out << ' ';
4000     TypePrinter.print(I.getType(), Out);
4001     Out << ' ';
4002 
4003     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
4004       if (op) Out << ", ";
4005       Out << "[ ";
4006       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
4007       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
4008     }
4009   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
4010     Out << ' ';
4011     writeOperand(I.getOperand(0), true);
4012     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
4013       Out << ", " << *i;
4014   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
4015     Out << ' ';
4016     writeOperand(I.getOperand(0), true); Out << ", ";
4017     writeOperand(I.getOperand(1), true);
4018     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
4019       Out << ", " << *i;
4020   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
4021     Out << ' ';
4022     TypePrinter.print(I.getType(), Out);
4023     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
4024       Out << '\n';
4025 
4026     if (LPI->isCleanup())
4027       Out << "          cleanup";
4028 
4029     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
4030       if (i != 0 || LPI->isCleanup()) Out << "\n";
4031       if (LPI->isCatch(i))
4032         Out << "          catch ";
4033       else
4034         Out << "          filter ";
4035 
4036       writeOperand(LPI->getClause(i), true);
4037     }
4038   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
4039     Out << " within ";
4040     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
4041     Out << " [";
4042     unsigned Op = 0;
4043     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
4044       if (Op > 0)
4045         Out << ", ";
4046       writeOperand(PadBB, /*PrintType=*/true);
4047       ++Op;
4048     }
4049     Out << "] unwind ";
4050     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
4051       writeOperand(UnwindDest, /*PrintType=*/true);
4052     else
4053       Out << "to caller";
4054   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
4055     Out << " within ";
4056     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
4057     Out << " [";
4058     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
4059          ++Op) {
4060       if (Op > 0)
4061         Out << ", ";
4062       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
4063     }
4064     Out << ']';
4065   } else if (isa<ReturnInst>(I) && !Operand) {
4066     Out << " void";
4067   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
4068     Out << " from ";
4069     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4070 
4071     Out << " to ";
4072     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4073   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
4074     Out << " from ";
4075     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
4076 
4077     Out << " unwind ";
4078     if (CRI->hasUnwindDest())
4079       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
4080     else
4081       Out << "to caller";
4082   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
4083     // Print the calling convention being used.
4084     if (CI->getCallingConv() != CallingConv::C) {
4085       Out << " ";
4086       PrintCallingConv(CI->getCallingConv(), Out);
4087     }
4088 
4089     Operand = CI->getCalledOperand();
4090     FunctionType *FTy = CI->getFunctionType();
4091     Type *RetTy = FTy->getReturnType();
4092     const AttributeList &PAL = CI->getAttributes();
4093 
4094     if (PAL.hasAttributes(AttributeList::ReturnIndex))
4095       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4096 
4097     // Only print addrspace(N) if necessary:
4098     maybePrintCallAddrSpace(Operand, &I, Out);
4099 
4100     // If possible, print out the short form of the call instruction.  We can
4101     // only do this if the first argument is a pointer to a nonvararg function,
4102     // and if the return type is not a pointer to a function.
4103     //
4104     Out << ' ';
4105     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4106     Out << ' ';
4107     writeOperand(Operand, false);
4108     Out << '(';
4109     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
4110       if (op > 0)
4111         Out << ", ";
4112       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
4113     }
4114 
4115     // Emit an ellipsis if this is a musttail call in a vararg function.  This
4116     // is only to aid readability, musttail calls forward varargs by default.
4117     if (CI->isMustTailCall() && CI->getParent() &&
4118         CI->getParent()->getParent() &&
4119         CI->getParent()->getParent()->isVarArg())
4120       Out << ", ...";
4121 
4122     Out << ')';
4123     if (PAL.hasAttributes(AttributeList::FunctionIndex))
4124       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
4125 
4126     writeOperandBundles(CI);
4127   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
4128     Operand = II->getCalledOperand();
4129     FunctionType *FTy = II->getFunctionType();
4130     Type *RetTy = FTy->getReturnType();
4131     const AttributeList &PAL = II->getAttributes();
4132 
4133     // Print the calling convention being used.
4134     if (II->getCallingConv() != CallingConv::C) {
4135       Out << " ";
4136       PrintCallingConv(II->getCallingConv(), Out);
4137     }
4138 
4139     if (PAL.hasAttributes(AttributeList::ReturnIndex))
4140       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4141 
4142     // Only print addrspace(N) if necessary:
4143     maybePrintCallAddrSpace(Operand, &I, Out);
4144 
4145     // If possible, print out the short form of the invoke instruction. We can
4146     // only do this if the first argument is a pointer to a nonvararg function,
4147     // and if the return type is not a pointer to a function.
4148     //
4149     Out << ' ';
4150     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4151     Out << ' ';
4152     writeOperand(Operand, false);
4153     Out << '(';
4154     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
4155       if (op)
4156         Out << ", ";
4157       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
4158     }
4159 
4160     Out << ')';
4161     if (PAL.hasAttributes(AttributeList::FunctionIndex))
4162       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
4163 
4164     writeOperandBundles(II);
4165 
4166     Out << "\n          to ";
4167     writeOperand(II->getNormalDest(), true);
4168     Out << " unwind ";
4169     writeOperand(II->getUnwindDest(), true);
4170   } else if (const CallBrInst *CBI = dyn_cast<CallBrInst>(&I)) {
4171     Operand = CBI->getCalledOperand();
4172     FunctionType *FTy = CBI->getFunctionType();
4173     Type *RetTy = FTy->getReturnType();
4174     const AttributeList &PAL = CBI->getAttributes();
4175 
4176     // Print the calling convention being used.
4177     if (CBI->getCallingConv() != CallingConv::C) {
4178       Out << " ";
4179       PrintCallingConv(CBI->getCallingConv(), Out);
4180     }
4181 
4182     if (PAL.hasAttributes(AttributeList::ReturnIndex))
4183       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
4184 
4185     // If possible, print out the short form of the callbr instruction. We can
4186     // only do this if the first argument is a pointer to a nonvararg function,
4187     // and if the return type is not a pointer to a function.
4188     //
4189     Out << ' ';
4190     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
4191     Out << ' ';
4192     writeOperand(Operand, false);
4193     Out << '(';
4194     for (unsigned op = 0, Eop = CBI->getNumArgOperands(); op < Eop; ++op) {
4195       if (op)
4196         Out << ", ";
4197       writeParamOperand(CBI->getArgOperand(op), PAL.getParamAttributes(op));
4198     }
4199 
4200     Out << ')';
4201     if (PAL.hasAttributes(AttributeList::FunctionIndex))
4202       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
4203 
4204     writeOperandBundles(CBI);
4205 
4206     Out << "\n          to ";
4207     writeOperand(CBI->getDefaultDest(), true);
4208     Out << " [";
4209     for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i) {
4210       if (i != 0)
4211         Out << ", ";
4212       writeOperand(CBI->getIndirectDest(i), true);
4213     }
4214     Out << ']';
4215   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
4216     Out << ' ';
4217     if (AI->isUsedWithInAlloca())
4218       Out << "inalloca ";
4219     if (AI->isSwiftError())
4220       Out << "swifterror ";
4221     TypePrinter.print(AI->getAllocatedType(), Out);
4222 
4223     // Explicitly write the array size if the code is broken, if it's an array
4224     // allocation, or if the type is not canonical for scalar allocations.  The
4225     // latter case prevents the type from mutating when round-tripping through
4226     // assembly.
4227     if (!AI->getArraySize() || AI->isArrayAllocation() ||
4228         !AI->getArraySize()->getType()->isIntegerTy(32)) {
4229       Out << ", ";
4230       writeOperand(AI->getArraySize(), true);
4231     }
4232     if (AI->getAlignment()) {
4233       Out << ", align " << AI->getAlignment();
4234     }
4235 
4236     unsigned AddrSpace = AI->getType()->getAddressSpace();
4237     if (AddrSpace != 0) {
4238       Out << ", addrspace(" << AddrSpace << ')';
4239     }
4240   } else if (isa<CastInst>(I)) {
4241     if (Operand) {
4242       Out << ' ';
4243       writeOperand(Operand, true);   // Work with broken code
4244     }
4245     Out << " to ";
4246     TypePrinter.print(I.getType(), Out);
4247   } else if (isa<VAArgInst>(I)) {
4248     if (Operand) {
4249       Out << ' ';
4250       writeOperand(Operand, true);   // Work with broken code
4251     }
4252     Out << ", ";
4253     TypePrinter.print(I.getType(), Out);
4254   } else if (Operand) {   // Print the normal way.
4255     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4256       Out << ' ';
4257       TypePrinter.print(GEP->getSourceElementType(), Out);
4258       Out << ',';
4259     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
4260       Out << ' ';
4261       TypePrinter.print(LI->getType(), Out);
4262       Out << ',';
4263     }
4264 
4265     // PrintAllTypes - Instructions who have operands of all the same type
4266     // omit the type from all but the first operand.  If the instruction has
4267     // different type operands (for example br), then they are all printed.
4268     bool PrintAllTypes = false;
4269     Type *TheType = Operand->getType();
4270 
4271     // Select, Store and ShuffleVector always print all types.
4272     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
4273         || isa<ReturnInst>(I)) {
4274       PrintAllTypes = true;
4275     } else {
4276       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
4277         Operand = I.getOperand(i);
4278         // note that Operand shouldn't be null, but the test helps make dump()
4279         // more tolerant of malformed IR
4280         if (Operand && Operand->getType() != TheType) {
4281           PrintAllTypes = true;    // We have differing types!  Print them all!
4282           break;
4283         }
4284       }
4285     }
4286 
4287     if (!PrintAllTypes) {
4288       Out << ' ';
4289       TypePrinter.print(TheType, Out);
4290     }
4291 
4292     Out << ' ';
4293     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
4294       if (i) Out << ", ";
4295       writeOperand(I.getOperand(i), PrintAllTypes);
4296     }
4297   }
4298 
4299   // Print atomic ordering/alignment for memory operations
4300   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
4301     if (LI->isAtomic())
4302       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4303     if (LI->getAlignment())
4304       Out << ", align " << LI->getAlignment();
4305   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
4306     if (SI->isAtomic())
4307       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
4308     if (SI->getAlignment())
4309       Out << ", align " << SI->getAlignment();
4310   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
4311     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4312                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
4313   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
4314     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4315                 RMWI->getSyncScopeID());
4316   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
4317     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4318   } else if (const ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(&I)) {
4319     PrintShuffleMask(Out, SVI->getType(), SVI->getShuffleMask());
4320   }
4321 
4322   // Print Metadata info.
4323   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
4324   I.getAllMetadata(InstMD);
4325   printMetadataAttachments(InstMD, ", ");
4326 
4327   // Print a nice comment.
4328   printInfoComment(I);
4329 }
4330 
4331 void AssemblyWriter::printMetadataAttachments(
4332     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
4333     StringRef Separator) {
4334   if (MDs.empty())
4335     return;
4336 
4337   if (MDNames.empty())
4338     MDs[0].second->getContext().getMDKindNames(MDNames);
4339 
4340   for (const auto &I : MDs) {
4341     unsigned Kind = I.first;
4342     Out << Separator;
4343     if (Kind < MDNames.size()) {
4344       Out << "!";
4345       printMetadataIdentifier(MDNames[Kind], Out);
4346     } else
4347       Out << "!<unknown kind #" << Kind << ">";
4348     Out << ' ';
4349     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
4350   }
4351 }
4352 
4353 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
4354   Out << '!' << Slot << " = ";
4355   printMDNodeBody(Node);
4356   Out << "\n";
4357 }
4358 
4359 void AssemblyWriter::writeAllMDNodes() {
4360   SmallVector<const MDNode *, 16> Nodes;
4361   Nodes.resize(Machine.mdn_size());
4362   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
4363        I != E; ++I)
4364     Nodes[I->second] = cast<MDNode>(I->first);
4365 
4366   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4367     writeMDNode(i, Nodes[i]);
4368   }
4369 }
4370 
4371 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
4372   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
4373 }
4374 
4375 void AssemblyWriter::writeAttribute(const Attribute &Attr, bool InAttrGroup) {
4376   if (!Attr.isTypeAttribute()) {
4377     Out << Attr.getAsString(InAttrGroup);
4378     return;
4379   }
4380 
4381   assert((Attr.hasAttribute(Attribute::ByVal) ||
4382           Attr.hasAttribute(Attribute::StructRet) ||
4383           Attr.hasAttribute(Attribute::ByRef) ||
4384           Attr.hasAttribute(Attribute::Preallocated)) &&
4385          "unexpected type attr");
4386 
4387   if (Attr.hasAttribute(Attribute::ByVal)) {
4388     Out << "byval";
4389   } else if (Attr.hasAttribute(Attribute::StructRet)) {
4390     Out << "sret";
4391   } else if (Attr.hasAttribute(Attribute::ByRef)) {
4392     Out << "byref";
4393   } else {
4394     Out << "preallocated";
4395   }
4396 
4397   if (Type *Ty = Attr.getValueAsType()) {
4398     Out << '(';
4399     TypePrinter.print(Ty, Out);
4400     Out << ')';
4401   }
4402 }
4403 
4404 void AssemblyWriter::writeAttributeSet(const AttributeSet &AttrSet,
4405                                        bool InAttrGroup) {
4406   bool FirstAttr = true;
4407   for (const auto &Attr : AttrSet) {
4408     if (!FirstAttr)
4409       Out << ' ';
4410     writeAttribute(Attr, InAttrGroup);
4411     FirstAttr = false;
4412   }
4413 }
4414 
4415 void AssemblyWriter::writeAllAttributeGroups() {
4416   std::vector<std::pair<AttributeSet, unsigned>> asVec;
4417   asVec.resize(Machine.as_size());
4418 
4419   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
4420        I != E; ++I)
4421     asVec[I->second] = *I;
4422 
4423   for (const auto &I : asVec)
4424     Out << "attributes #" << I.second << " = { "
4425         << I.first.getAsString(true) << " }\n";
4426 }
4427 
4428 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
4429   bool IsInFunction = Machine.getFunction();
4430   if (IsInFunction)
4431     Out << "  ";
4432 
4433   Out << "uselistorder";
4434   if (const BasicBlock *BB =
4435           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
4436     Out << "_bb ";
4437     writeOperand(BB->getParent(), false);
4438     Out << ", ";
4439     writeOperand(BB, false);
4440   } else {
4441     Out << " ";
4442     writeOperand(Order.V, true);
4443   }
4444   Out << ", { ";
4445 
4446   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
4447   Out << Order.Shuffle[0];
4448   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
4449     Out << ", " << Order.Shuffle[I];
4450   Out << " }\n";
4451 }
4452 
4453 void AssemblyWriter::printUseLists(const Function *F) {
4454   auto hasMore =
4455       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
4456   if (!hasMore())
4457     // Nothing to do.
4458     return;
4459 
4460   Out << "\n; uselistorder directives\n";
4461   while (hasMore()) {
4462     printUseListOrder(UseListOrders.back());
4463     UseListOrders.pop_back();
4464   }
4465 }
4466 
4467 //===----------------------------------------------------------------------===//
4468 //                       External Interface declarations
4469 //===----------------------------------------------------------------------===//
4470 
4471 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4472                      bool ShouldPreserveUseListOrder,
4473                      bool IsForDebug) const {
4474   SlotTracker SlotTable(this->getParent());
4475   formatted_raw_ostream OS(ROS);
4476   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4477                    IsForDebug,
4478                    ShouldPreserveUseListOrder);
4479   W.printFunction(this);
4480 }
4481 
4482 void BasicBlock::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4483                      bool ShouldPreserveUseListOrder,
4484                      bool IsForDebug) const {
4485   SlotTracker SlotTable(this->getParent());
4486   formatted_raw_ostream OS(ROS);
4487   AssemblyWriter W(OS, SlotTable, this->getModule(), AAW,
4488                    IsForDebug,
4489                    ShouldPreserveUseListOrder);
4490   W.printBasicBlock(this);
4491 }
4492 
4493 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4494                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4495   SlotTracker SlotTable(this);
4496   formatted_raw_ostream OS(ROS);
4497   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4498                    ShouldPreserveUseListOrder);
4499   W.printModule(this);
4500 }
4501 
4502 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4503   SlotTracker SlotTable(getParent());
4504   formatted_raw_ostream OS(ROS);
4505   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4506   W.printNamedMDNode(this);
4507 }
4508 
4509 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4510                         bool IsForDebug) const {
4511   Optional<SlotTracker> LocalST;
4512   SlotTracker *SlotTable;
4513   if (auto *ST = MST.getMachine())
4514     SlotTable = ST;
4515   else {
4516     LocalST.emplace(getParent());
4517     SlotTable = &*LocalST;
4518   }
4519 
4520   formatted_raw_ostream OS(ROS);
4521   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4522   W.printNamedMDNode(this);
4523 }
4524 
4525 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4526   PrintLLVMName(ROS, getName(), ComdatPrefix);
4527   ROS << " = comdat ";
4528 
4529   switch (getSelectionKind()) {
4530   case Comdat::Any:
4531     ROS << "any";
4532     break;
4533   case Comdat::ExactMatch:
4534     ROS << "exactmatch";
4535     break;
4536   case Comdat::Largest:
4537     ROS << "largest";
4538     break;
4539   case Comdat::NoDuplicates:
4540     ROS << "noduplicates";
4541     break;
4542   case Comdat::SameSize:
4543     ROS << "samesize";
4544     break;
4545   }
4546 
4547   ROS << '\n';
4548 }
4549 
4550 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4551   TypePrinting TP;
4552   TP.print(const_cast<Type*>(this), OS);
4553 
4554   if (NoDetails)
4555     return;
4556 
4557   // If the type is a named struct type, print the body as well.
4558   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4559     if (!STy->isLiteral()) {
4560       OS << " = type ";
4561       TP.printStructBody(STy, OS);
4562     }
4563 }
4564 
4565 static bool isReferencingMDNode(const Instruction &I) {
4566   if (const auto *CI = dyn_cast<CallInst>(&I))
4567     if (Function *F = CI->getCalledFunction())
4568       if (F->isIntrinsic())
4569         for (auto &Op : I.operands())
4570           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4571             if (isa<MDNode>(V->getMetadata()))
4572               return true;
4573   return false;
4574 }
4575 
4576 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4577   bool ShouldInitializeAllMetadata = false;
4578   if (auto *I = dyn_cast<Instruction>(this))
4579     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4580   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4581     ShouldInitializeAllMetadata = true;
4582 
4583   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4584   print(ROS, MST, IsForDebug);
4585 }
4586 
4587 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4588                   bool IsForDebug) const {
4589   formatted_raw_ostream OS(ROS);
4590   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4591   SlotTracker &SlotTable =
4592       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4593   auto incorporateFunction = [&](const Function *F) {
4594     if (F)
4595       MST.incorporateFunction(*F);
4596   };
4597 
4598   if (const Instruction *I = dyn_cast<Instruction>(this)) {
4599     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4600     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4601     W.printInstruction(*I);
4602   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4603     incorporateFunction(BB->getParent());
4604     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4605     W.printBasicBlock(BB);
4606   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4607     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4608     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4609       W.printGlobal(V);
4610     else if (const Function *F = dyn_cast<Function>(GV))
4611       W.printFunction(F);
4612     else
4613       W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
4614   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4615     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4616   } else if (const Constant *C = dyn_cast<Constant>(this)) {
4617     TypePrinting TypePrinter;
4618     TypePrinter.print(C->getType(), OS);
4619     OS << ' ';
4620     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
4621   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4622     this->printAsOperand(OS, /* PrintType */ true, MST);
4623   } else {
4624     llvm_unreachable("Unknown value to print out!");
4625   }
4626 }
4627 
4628 /// Print without a type, skipping the TypePrinting object.
4629 ///
4630 /// \return \c true iff printing was successful.
4631 static bool printWithoutType(const Value &V, raw_ostream &O,
4632                              SlotTracker *Machine, const Module *M) {
4633   if (V.hasName() || isa<GlobalValue>(V) ||
4634       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4635     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4636     return true;
4637   }
4638   return false;
4639 }
4640 
4641 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4642                                ModuleSlotTracker &MST) {
4643   TypePrinting TypePrinter(MST.getModule());
4644   if (PrintType) {
4645     TypePrinter.print(V.getType(), O);
4646     O << ' ';
4647   }
4648 
4649   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4650                          MST.getModule());
4651 }
4652 
4653 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4654                            const Module *M) const {
4655   if (!M)
4656     M = getModuleFromVal(this);
4657 
4658   if (!PrintType)
4659     if (printWithoutType(*this, O, nullptr, M))
4660       return;
4661 
4662   SlotTracker Machine(
4663       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4664   ModuleSlotTracker MST(Machine, M);
4665   printAsOperandImpl(*this, O, PrintType, MST);
4666 }
4667 
4668 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4669                            ModuleSlotTracker &MST) const {
4670   if (!PrintType)
4671     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4672       return;
4673 
4674   printAsOperandImpl(*this, O, PrintType, MST);
4675 }
4676 
4677 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4678                               ModuleSlotTracker &MST, const Module *M,
4679                               bool OnlyAsOperand) {
4680   formatted_raw_ostream OS(ROS);
4681 
4682   TypePrinting TypePrinter(M);
4683 
4684   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
4685                          /* FromValue */ true);
4686 
4687   auto *N = dyn_cast<MDNode>(&MD);
4688   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
4689     return;
4690 
4691   OS << " = ";
4692   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
4693 }
4694 
4695 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4696   ModuleSlotTracker MST(M, isa<MDNode>(this));
4697   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4698 }
4699 
4700 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4701                               const Module *M) const {
4702   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4703 }
4704 
4705 void Metadata::print(raw_ostream &OS, const Module *M,
4706                      bool /*IsForDebug*/) const {
4707   ModuleSlotTracker MST(M, isa<MDNode>(this));
4708   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4709 }
4710 
4711 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
4712                      const Module *M, bool /*IsForDebug*/) const {
4713   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4714 }
4715 
4716 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4717   SlotTracker SlotTable(this);
4718   formatted_raw_ostream OS(ROS);
4719   AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4720   W.printModuleSummaryIndex();
4721 }
4722 
4723 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4724 // Value::dump - allow easy printing of Values from the debugger.
4725 LLVM_DUMP_METHOD
4726 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4727 
4728 // Type::dump - allow easy printing of Types from the debugger.
4729 LLVM_DUMP_METHOD
4730 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4731 
4732 // Module::dump() - Allow printing of Modules from the debugger.
4733 LLVM_DUMP_METHOD
4734 void Module::dump() const {
4735   print(dbgs(), nullptr,
4736         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4737 }
4738 
4739 // Allow printing of Comdats from the debugger.
4740 LLVM_DUMP_METHOD
4741 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4742 
4743 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4744 LLVM_DUMP_METHOD
4745 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4746 
4747 LLVM_DUMP_METHOD
4748 void Metadata::dump() const { dump(nullptr); }
4749 
4750 LLVM_DUMP_METHOD
4751 void Metadata::dump(const Module *M) const {
4752   print(dbgs(), M, /*IsForDebug=*/true);
4753   dbgs() << '\n';
4754 }
4755 
4756 // Allow printing of ModuleSummaryIndex from the debugger.
4757 LLVM_DUMP_METHOD
4758 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4759 #endif
4760