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