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