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