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