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       if (const DILocation *Loc = dyn_cast<DILocation>(N)) {
2299         writeDILocation(Out, Loc, TypePrinter, Machine, Context);
2300         return;
2301       }
2302       // Give the pointer value instead of "badref", since this comes up all
2303       // the time when debugging.
2304       Out << "<" << N << ">";
2305     } else
2306       Out << '!' << Slot;
2307     return;
2308   }
2309 
2310   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
2311     Out << "!\"";
2312     printEscapedString(MDS->getString(), Out);
2313     Out << '"';
2314     return;
2315   }
2316 
2317   auto *V = cast<ValueAsMetadata>(MD);
2318   assert(TypePrinter && "TypePrinter required for metadata values");
2319   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2320          "Unexpected function-local metadata outside of value argument");
2321 
2322   TypePrinter->print(V->getValue()->getType(), Out);
2323   Out << ' ';
2324   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2325 }
2326 
2327 namespace {
2328 
2329 class AssemblyWriter {
2330   formatted_raw_ostream &Out;
2331   const Module *TheModule = nullptr;
2332   const ModuleSummaryIndex *TheIndex = nullptr;
2333   std::unique_ptr<SlotTracker> SlotTrackerStorage;
2334   SlotTracker &Machine;
2335   TypePrinting TypePrinter;
2336   AssemblyAnnotationWriter *AnnotationWriter = nullptr;
2337   SetVector<const Comdat *> Comdats;
2338   bool IsForDebug;
2339   bool ShouldPreserveUseListOrder;
2340   UseListOrderStack UseListOrders;
2341   SmallVector<StringRef, 8> MDNames;
2342   /// Synchronization scope names registered with LLVMContext.
2343   SmallVector<StringRef, 8> SSNs;
2344   DenseMap<const GlobalValueSummary *, GlobalValue::GUID> SummaryToGUIDMap;
2345 
2346 public:
2347   /// Construct an AssemblyWriter with an external SlotTracker
2348   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2349                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2350                  bool ShouldPreserveUseListOrder = false);
2351 
2352   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2353                  const ModuleSummaryIndex *Index, bool IsForDebug);
2354 
2355   void printMDNodeBody(const MDNode *MD);
2356   void printNamedMDNode(const NamedMDNode *NMD);
2357 
2358   void printModule(const Module *M);
2359 
2360   void writeOperand(const Value *Op, bool PrintType);
2361   void writeParamOperand(const Value *Operand, AttributeSet Attrs);
2362   void writeOperandBundles(ImmutableCallSite CS);
2363   void writeSyncScope(const LLVMContext &Context,
2364                       SyncScope::ID SSID);
2365   void writeAtomic(const LLVMContext &Context,
2366                    AtomicOrdering Ordering,
2367                    SyncScope::ID SSID);
2368   void writeAtomicCmpXchg(const LLVMContext &Context,
2369                           AtomicOrdering SuccessOrdering,
2370                           AtomicOrdering FailureOrdering,
2371                           SyncScope::ID SSID);
2372 
2373   void writeAllMDNodes();
2374   void writeMDNode(unsigned Slot, const MDNode *Node);
2375   void writeAllAttributeGroups();
2376 
2377   void printTypeIdentities();
2378   void printGlobal(const GlobalVariable *GV);
2379   void printIndirectSymbol(const GlobalIndirectSymbol *GIS);
2380   void printComdat(const Comdat *C);
2381   void printFunction(const Function *F);
2382   void printArgument(const Argument *FA, AttributeSet Attrs);
2383   void printBasicBlock(const BasicBlock *BB);
2384   void printInstructionLine(const Instruction &I);
2385   void printInstruction(const Instruction &I);
2386 
2387   void printUseListOrder(const UseListOrder &Order);
2388   void printUseLists(const Function *F);
2389 
2390   void printModuleSummaryIndex();
2391   void printSummaryInfo(unsigned Slot, const ValueInfo &VI);
2392   void printSummary(const GlobalValueSummary &Summary);
2393   void printAliasSummary(const AliasSummary *AS);
2394   void printGlobalVarSummary(const GlobalVarSummary *GS);
2395   void printFunctionSummary(const FunctionSummary *FS);
2396   void printTypeIdSummary(const TypeIdSummary &TIS);
2397   void printTypeTestResolution(const TypeTestResolution &TTRes);
2398   void printArgs(const std::vector<uint64_t> &Args);
2399   void printWPDRes(const WholeProgramDevirtResolution &WPDRes);
2400   void printTypeIdInfo(const FunctionSummary::TypeIdInfo &TIDInfo);
2401   void printVFuncId(const FunctionSummary::VFuncId VFId);
2402   void
2403   printNonConstVCalls(const std::vector<FunctionSummary::VFuncId> VCallList,
2404                       const char *Tag);
2405   void
2406   printConstVCalls(const std::vector<FunctionSummary::ConstVCall> VCallList,
2407                    const char *Tag);
2408 
2409 private:
2410   /// Print out metadata attachments.
2411   void printMetadataAttachments(
2412       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2413       StringRef Separator);
2414 
2415   // printInfoComment - Print a little comment after the instruction indicating
2416   // which slot it occupies.
2417   void printInfoComment(const Value &V);
2418 
2419   // printGCRelocateComment - print comment after call to the gc.relocate
2420   // intrinsic indicating base and derived pointer names.
2421   void printGCRelocateComment(const GCRelocateInst &Relocate);
2422 };
2423 
2424 } // end anonymous namespace
2425 
2426 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2427                                const Module *M, AssemblyAnnotationWriter *AAW,
2428                                bool IsForDebug, bool ShouldPreserveUseListOrder)
2429     : Out(o), TheModule(M), Machine(Mac), TypePrinter(M), AnnotationWriter(AAW),
2430       IsForDebug(IsForDebug),
2431       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2432   if (!TheModule)
2433     return;
2434   for (const GlobalObject &GO : TheModule->global_objects())
2435     if (const Comdat *C = GO.getComdat())
2436       Comdats.insert(C);
2437 }
2438 
2439 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2440                                const ModuleSummaryIndex *Index, bool IsForDebug)
2441     : Out(o), TheIndex(Index), Machine(Mac), TypePrinter(/*Module=*/nullptr),
2442       IsForDebug(IsForDebug), ShouldPreserveUseListOrder(false) {}
2443 
2444 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2445   if (!Operand) {
2446     Out << "<null operand!>";
2447     return;
2448   }
2449   if (PrintType) {
2450     TypePrinter.print(Operand->getType(), Out);
2451     Out << ' ';
2452   }
2453   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2454 }
2455 
2456 void AssemblyWriter::writeSyncScope(const LLVMContext &Context,
2457                                     SyncScope::ID SSID) {
2458   switch (SSID) {
2459   case SyncScope::System: {
2460     break;
2461   }
2462   default: {
2463     if (SSNs.empty())
2464       Context.getSyncScopeNames(SSNs);
2465 
2466     Out << " syncscope(\"";
2467     printEscapedString(SSNs[SSID], Out);
2468     Out << "\")";
2469     break;
2470   }
2471   }
2472 }
2473 
2474 void AssemblyWriter::writeAtomic(const LLVMContext &Context,
2475                                  AtomicOrdering Ordering,
2476                                  SyncScope::ID SSID) {
2477   if (Ordering == AtomicOrdering::NotAtomic)
2478     return;
2479 
2480   writeSyncScope(Context, SSID);
2481   Out << " " << toIRString(Ordering);
2482 }
2483 
2484 void AssemblyWriter::writeAtomicCmpXchg(const LLVMContext &Context,
2485                                         AtomicOrdering SuccessOrdering,
2486                                         AtomicOrdering FailureOrdering,
2487                                         SyncScope::ID SSID) {
2488   assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2489          FailureOrdering != AtomicOrdering::NotAtomic);
2490 
2491   writeSyncScope(Context, SSID);
2492   Out << " " << toIRString(SuccessOrdering);
2493   Out << " " << toIRString(FailureOrdering);
2494 }
2495 
2496 void AssemblyWriter::writeParamOperand(const Value *Operand,
2497                                        AttributeSet Attrs) {
2498   if (!Operand) {
2499     Out << "<null operand!>";
2500     return;
2501   }
2502 
2503   // Print the type
2504   TypePrinter.print(Operand->getType(), Out);
2505   // Print parameter attributes list
2506   if (Attrs.hasAttributes())
2507     Out << ' ' << Attrs.getAsString();
2508   Out << ' ';
2509   // Print the operand
2510   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2511 }
2512 
2513 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2514   if (!CS.hasOperandBundles())
2515     return;
2516 
2517   Out << " [ ";
2518 
2519   bool FirstBundle = true;
2520   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2521     OperandBundleUse BU = CS.getOperandBundleAt(i);
2522 
2523     if (!FirstBundle)
2524       Out << ", ";
2525     FirstBundle = false;
2526 
2527     Out << '"';
2528     printEscapedString(BU.getTagName(), Out);
2529     Out << '"';
2530 
2531     Out << '(';
2532 
2533     bool FirstInput = true;
2534     for (const auto &Input : BU.Inputs) {
2535       if (!FirstInput)
2536         Out << ", ";
2537       FirstInput = false;
2538 
2539       TypePrinter.print(Input->getType(), Out);
2540       Out << " ";
2541       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2542     }
2543 
2544     Out << ')';
2545   }
2546 
2547   Out << " ]";
2548 }
2549 
2550 void AssemblyWriter::printModule(const Module *M) {
2551   Machine.initializeIfNeeded();
2552 
2553   if (ShouldPreserveUseListOrder)
2554     UseListOrders = predictUseListOrder(M);
2555 
2556   if (!M->getModuleIdentifier().empty() &&
2557       // Don't print the ID if it will start a new line (which would
2558       // require a comment char before it).
2559       M->getModuleIdentifier().find('\n') == std::string::npos)
2560     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2561 
2562   if (!M->getSourceFileName().empty()) {
2563     Out << "source_filename = \"";
2564     printEscapedString(M->getSourceFileName(), Out);
2565     Out << "\"\n";
2566   }
2567 
2568   const std::string &DL = M->getDataLayoutStr();
2569   if (!DL.empty())
2570     Out << "target datalayout = \"" << DL << "\"\n";
2571   if (!M->getTargetTriple().empty())
2572     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2573 
2574   if (!M->getModuleInlineAsm().empty()) {
2575     Out << '\n';
2576 
2577     // Split the string into lines, to make it easier to read the .ll file.
2578     StringRef Asm = M->getModuleInlineAsm();
2579     do {
2580       StringRef Front;
2581       std::tie(Front, Asm) = Asm.split('\n');
2582 
2583       // We found a newline, print the portion of the asm string from the
2584       // last newline up to this newline.
2585       Out << "module asm \"";
2586       printEscapedString(Front, Out);
2587       Out << "\"\n";
2588     } while (!Asm.empty());
2589   }
2590 
2591   printTypeIdentities();
2592 
2593   // Output all comdats.
2594   if (!Comdats.empty())
2595     Out << '\n';
2596   for (const Comdat *C : Comdats) {
2597     printComdat(C);
2598     if (C != Comdats.back())
2599       Out << '\n';
2600   }
2601 
2602   // Output all globals.
2603   if (!M->global_empty()) Out << '\n';
2604   for (const GlobalVariable &GV : M->globals()) {
2605     printGlobal(&GV); Out << '\n';
2606   }
2607 
2608   // Output all aliases.
2609   if (!M->alias_empty()) Out << "\n";
2610   for (const GlobalAlias &GA : M->aliases())
2611     printIndirectSymbol(&GA);
2612 
2613   // Output all ifuncs.
2614   if (!M->ifunc_empty()) Out << "\n";
2615   for (const GlobalIFunc &GI : M->ifuncs())
2616     printIndirectSymbol(&GI);
2617 
2618   // Output global use-lists.
2619   printUseLists(nullptr);
2620 
2621   // Output all of the functions.
2622   for (const Function &F : *M)
2623     printFunction(&F);
2624   assert(UseListOrders.empty() && "All use-lists should have been consumed");
2625 
2626   // Output all attribute groups.
2627   if (!Machine.as_empty()) {
2628     Out << '\n';
2629     writeAllAttributeGroups();
2630   }
2631 
2632   // Output named metadata.
2633   if (!M->named_metadata_empty()) Out << '\n';
2634 
2635   for (const NamedMDNode &Node : M->named_metadata())
2636     printNamedMDNode(&Node);
2637 
2638   // Output metadata.
2639   if (!Machine.mdn_empty()) {
2640     Out << '\n';
2641     writeAllMDNodes();
2642   }
2643 }
2644 
2645 void AssemblyWriter::printModuleSummaryIndex() {
2646   assert(TheIndex);
2647   Machine.initializeIndexIfNeeded();
2648 
2649   Out << "\n";
2650 
2651   // Print module path entries. To print in order, add paths to a vector
2652   // indexed by module slot.
2653   std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2654   std::string RegularLTOModuleName = "[Regular LTO]";
2655   moduleVec.resize(TheIndex->modulePaths().size());
2656   for (auto &ModPath : TheIndex->modulePaths())
2657     moduleVec[Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2658         // A module id of -1 is a special entry for a regular LTO module created
2659         // during the thin link.
2660         ModPath.second.first == -1u ? RegularLTOModuleName
2661                                     : (std::string)ModPath.first(),
2662         ModPath.second.second);
2663 
2664   unsigned i = 0;
2665   for (auto &ModPair : moduleVec) {
2666     Out << "^" << i++ << " = module: (";
2667     Out << "path: \"";
2668     printEscapedString(ModPair.first, Out);
2669     Out << "\", hash: (";
2670     FieldSeparator FS;
2671     for (auto Hash : ModPair.second)
2672       Out << FS << Hash;
2673     Out << "))\n";
2674   }
2675 
2676   // FIXME: Change AliasSummary to hold a ValueInfo instead of summary pointer
2677   // for aliasee (then update BitcodeWriter.cpp and remove get/setAliaseeGUID).
2678   for (auto &GlobalList : *TheIndex) {
2679     auto GUID = GlobalList.first;
2680     for (auto &Summary : GlobalList.second.SummaryList)
2681       SummaryToGUIDMap[Summary.get()] = GUID;
2682   }
2683 
2684   // Print the global value summary entries.
2685   for (auto &GlobalList : *TheIndex) {
2686     auto GUID = GlobalList.first;
2687     auto VI = TheIndex->getValueInfo(GlobalList);
2688     printSummaryInfo(Machine.getGUIDSlot(GUID), VI);
2689   }
2690 
2691   // Print the TypeIdMap entries.
2692   for (auto TidIter = TheIndex->typeIds().begin();
2693        TidIter != TheIndex->typeIds().end(); TidIter++) {
2694     Out << "^" << Machine.getTypeIdSlot(TidIter->second.first)
2695         << " = typeid: (name: \"" << TidIter->second.first << "\"";
2696     printTypeIdSummary(TidIter->second.second);
2697     Out << ") ; guid = " << TidIter->first << "\n";
2698   }
2699 }
2700 
2701 static const char *
2702 getWholeProgDevirtResKindName(WholeProgramDevirtResolution::Kind K) {
2703   switch (K) {
2704   case WholeProgramDevirtResolution::Indir:
2705     return "indir";
2706   case WholeProgramDevirtResolution::SingleImpl:
2707     return "singleImpl";
2708   case WholeProgramDevirtResolution::BranchFunnel:
2709     return "branchFunnel";
2710   }
2711   llvm_unreachable("invalid WholeProgramDevirtResolution kind");
2712 }
2713 
2714 static const char *getWholeProgDevirtResByArgKindName(
2715     WholeProgramDevirtResolution::ByArg::Kind K) {
2716   switch (K) {
2717   case WholeProgramDevirtResolution::ByArg::Indir:
2718     return "indir";
2719   case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2720     return "uniformRetVal";
2721   case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2722     return "uniqueRetVal";
2723   case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2724     return "virtualConstProp";
2725   }
2726   llvm_unreachable("invalid WholeProgramDevirtResolution::ByArg kind");
2727 }
2728 
2729 static const char *getTTResKindName(TypeTestResolution::Kind K) {
2730   switch (K) {
2731   case TypeTestResolution::Unsat:
2732     return "unsat";
2733   case TypeTestResolution::ByteArray:
2734     return "byteArray";
2735   case TypeTestResolution::Inline:
2736     return "inline";
2737   case TypeTestResolution::Single:
2738     return "single";
2739   case TypeTestResolution::AllOnes:
2740     return "allOnes";
2741   }
2742   llvm_unreachable("invalid TypeTestResolution kind");
2743 }
2744 
2745 void AssemblyWriter::printTypeTestResolution(const TypeTestResolution &TTRes) {
2746   Out << "typeTestRes: (kind: " << getTTResKindName(TTRes.TheKind)
2747       << ", sizeM1BitWidth: " << TTRes.SizeM1BitWidth;
2748 
2749   // The following fields are only used if the target does not support the use
2750   // of absolute symbols to store constants. Print only if non-zero.
2751   if (TTRes.AlignLog2)
2752     Out << ", alignLog2: " << TTRes.AlignLog2;
2753   if (TTRes.SizeM1)
2754     Out << ", sizeM1: " << TTRes.SizeM1;
2755   if (TTRes.BitMask)
2756     // BitMask is uint8_t which causes it to print the corresponding char.
2757     Out << ", bitMask: " << (unsigned)TTRes.BitMask;
2758   if (TTRes.InlineBits)
2759     Out << ", inlineBits: " << TTRes.InlineBits;
2760 
2761   Out << ")";
2762 }
2763 
2764 void AssemblyWriter::printTypeIdSummary(const TypeIdSummary &TIS) {
2765   Out << ", summary: (";
2766   printTypeTestResolution(TIS.TTRes);
2767   if (!TIS.WPDRes.empty()) {
2768     Out << ", wpdResolutions: (";
2769     FieldSeparator FS;
2770     for (auto &WPDRes : TIS.WPDRes) {
2771       Out << FS;
2772       Out << "(offset: " << WPDRes.first << ", ";
2773       printWPDRes(WPDRes.second);
2774       Out << ")";
2775     }
2776     Out << ")";
2777   }
2778   Out << ")";
2779 }
2780 
2781 void AssemblyWriter::printArgs(const std::vector<uint64_t> &Args) {
2782   Out << "args: (";
2783   FieldSeparator FS;
2784   for (auto arg : Args) {
2785     Out << FS;
2786     Out << arg;
2787   }
2788   Out << ")";
2789 }
2790 
2791 void AssemblyWriter::printWPDRes(const WholeProgramDevirtResolution &WPDRes) {
2792   Out << "wpdRes: (kind: ";
2793   Out << getWholeProgDevirtResKindName(WPDRes.TheKind);
2794 
2795   if (WPDRes.TheKind == WholeProgramDevirtResolution::SingleImpl)
2796     Out << ", singleImplName: \"" << WPDRes.SingleImplName << "\"";
2797 
2798   if (!WPDRes.ResByArg.empty()) {
2799     Out << ", resByArg: (";
2800     FieldSeparator FS;
2801     for (auto &ResByArg : WPDRes.ResByArg) {
2802       Out << FS;
2803       printArgs(ResByArg.first);
2804       Out << ", byArg: (kind: ";
2805       Out << getWholeProgDevirtResByArgKindName(ResByArg.second.TheKind);
2806       if (ResByArg.second.TheKind ==
2807               WholeProgramDevirtResolution::ByArg::UniformRetVal ||
2808           ResByArg.second.TheKind ==
2809               WholeProgramDevirtResolution::ByArg::UniqueRetVal)
2810         Out << ", info: " << ResByArg.second.Info;
2811 
2812       // The following fields are only used if the target does not support the
2813       // use of absolute symbols to store constants. Print only if non-zero.
2814       if (ResByArg.second.Byte || ResByArg.second.Bit)
2815         Out << ", byte: " << ResByArg.second.Byte
2816             << ", bit: " << ResByArg.second.Bit;
2817 
2818       Out << ")";
2819     }
2820     Out << ")";
2821   }
2822   Out << ")";
2823 }
2824 
2825 static const char *getSummaryKindName(GlobalValueSummary::SummaryKind SK) {
2826   switch (SK) {
2827   case GlobalValueSummary::AliasKind:
2828     return "alias";
2829   case GlobalValueSummary::FunctionKind:
2830     return "function";
2831   case GlobalValueSummary::GlobalVarKind:
2832     return "variable";
2833   }
2834   llvm_unreachable("invalid summary kind");
2835 }
2836 
2837 void AssemblyWriter::printAliasSummary(const AliasSummary *AS) {
2838   Out << ", aliasee: ";
2839   // The indexes emitted for distributed backends may not include the
2840   // aliasee summary (only if it is being imported directly). Handle
2841   // that case by just emitting "null" as the aliasee.
2842   if (AS->hasAliasee())
2843     Out << "^" << Machine.getGUIDSlot(SummaryToGUIDMap[&AS->getAliasee()]);
2844   else
2845     Out << "null";
2846 }
2847 
2848 void AssemblyWriter::printGlobalVarSummary(const GlobalVarSummary *GS) {
2849   Out << ", varFlags: (readonly: " << GS->VarFlags.ReadOnly << ")";
2850 }
2851 
2852 static std::string getLinkageName(GlobalValue::LinkageTypes LT) {
2853   switch (LT) {
2854   case GlobalValue::ExternalLinkage:
2855     return "external";
2856   case GlobalValue::PrivateLinkage:
2857     return "private";
2858   case GlobalValue::InternalLinkage:
2859     return "internal";
2860   case GlobalValue::LinkOnceAnyLinkage:
2861     return "linkonce";
2862   case GlobalValue::LinkOnceODRLinkage:
2863     return "linkonce_odr";
2864   case GlobalValue::WeakAnyLinkage:
2865     return "weak";
2866   case GlobalValue::WeakODRLinkage:
2867     return "weak_odr";
2868   case GlobalValue::CommonLinkage:
2869     return "common";
2870   case GlobalValue::AppendingLinkage:
2871     return "appending";
2872   case GlobalValue::ExternalWeakLinkage:
2873     return "extern_weak";
2874   case GlobalValue::AvailableExternallyLinkage:
2875     return "available_externally";
2876   }
2877   llvm_unreachable("invalid linkage");
2878 }
2879 
2880 // When printing the linkage types in IR where the ExternalLinkage is
2881 // not printed, and other linkage types are expected to be printed with
2882 // a space after the name.
2883 static std::string getLinkageNameWithSpace(GlobalValue::LinkageTypes LT) {
2884   if (LT == GlobalValue::ExternalLinkage)
2885     return "";
2886   return getLinkageName(LT) + " ";
2887 }
2888 
2889 void AssemblyWriter::printFunctionSummary(const FunctionSummary *FS) {
2890   Out << ", insts: " << FS->instCount();
2891 
2892   FunctionSummary::FFlags FFlags = FS->fflags();
2893   if (FFlags.ReadNone | FFlags.ReadOnly | FFlags.NoRecurse |
2894       FFlags.ReturnDoesNotAlias) {
2895     Out << ", funcFlags: (";
2896     Out << "readNone: " << FFlags.ReadNone;
2897     Out << ", readOnly: " << FFlags.ReadOnly;
2898     Out << ", noRecurse: " << FFlags.NoRecurse;
2899     Out << ", returnDoesNotAlias: " << FFlags.ReturnDoesNotAlias;
2900     Out << ", noInline: " << FFlags.NoInline;
2901     Out << ")";
2902   }
2903   if (!FS->calls().empty()) {
2904     Out << ", calls: (";
2905     FieldSeparator IFS;
2906     for (auto &Call : FS->calls()) {
2907       Out << IFS;
2908       Out << "(callee: ^" << Machine.getGUIDSlot(Call.first.getGUID());
2909       if (Call.second.getHotness() != CalleeInfo::HotnessType::Unknown)
2910         Out << ", hotness: " << getHotnessName(Call.second.getHotness());
2911       else if (Call.second.RelBlockFreq)
2912         Out << ", relbf: " << Call.second.RelBlockFreq;
2913       Out << ")";
2914     }
2915     Out << ")";
2916   }
2917 
2918   if (const auto *TIdInfo = FS->getTypeIdInfo())
2919     printTypeIdInfo(*TIdInfo);
2920 }
2921 
2922 void AssemblyWriter::printTypeIdInfo(
2923     const FunctionSummary::TypeIdInfo &TIDInfo) {
2924   Out << ", typeIdInfo: (";
2925   FieldSeparator TIDFS;
2926   if (!TIDInfo.TypeTests.empty()) {
2927     Out << TIDFS;
2928     Out << "typeTests: (";
2929     FieldSeparator FS;
2930     for (auto &GUID : TIDInfo.TypeTests) {
2931       auto TidIter = TheIndex->typeIds().equal_range(GUID);
2932       if (TidIter.first == TidIter.second) {
2933         Out << FS;
2934         Out << GUID;
2935         continue;
2936       }
2937       // Print all type id that correspond to this GUID.
2938       for (auto It = TidIter.first; It != TidIter.second; ++It) {
2939         Out << FS;
2940         auto Slot = Machine.getTypeIdSlot(It->second.first);
2941         assert(Slot != -1);
2942         Out << "^" << Slot;
2943       }
2944     }
2945     Out << ")";
2946   }
2947   if (!TIDInfo.TypeTestAssumeVCalls.empty()) {
2948     Out << TIDFS;
2949     printNonConstVCalls(TIDInfo.TypeTestAssumeVCalls, "typeTestAssumeVCalls");
2950   }
2951   if (!TIDInfo.TypeCheckedLoadVCalls.empty()) {
2952     Out << TIDFS;
2953     printNonConstVCalls(TIDInfo.TypeCheckedLoadVCalls, "typeCheckedLoadVCalls");
2954   }
2955   if (!TIDInfo.TypeTestAssumeConstVCalls.empty()) {
2956     Out << TIDFS;
2957     printConstVCalls(TIDInfo.TypeTestAssumeConstVCalls,
2958                      "typeTestAssumeConstVCalls");
2959   }
2960   if (!TIDInfo.TypeCheckedLoadConstVCalls.empty()) {
2961     Out << TIDFS;
2962     printConstVCalls(TIDInfo.TypeCheckedLoadConstVCalls,
2963                      "typeCheckedLoadConstVCalls");
2964   }
2965   Out << ")";
2966 }
2967 
2968 void AssemblyWriter::printVFuncId(const FunctionSummary::VFuncId VFId) {
2969   auto TidIter = TheIndex->typeIds().equal_range(VFId.GUID);
2970   if (TidIter.first == TidIter.second) {
2971     Out << "vFuncId: (";
2972     Out << "guid: " << VFId.GUID;
2973     Out << ", offset: " << VFId.Offset;
2974     Out << ")";
2975     return;
2976   }
2977   // Print all type id that correspond to this GUID.
2978   FieldSeparator FS;
2979   for (auto It = TidIter.first; It != TidIter.second; ++It) {
2980     Out << FS;
2981     Out << "vFuncId: (";
2982     auto Slot = Machine.getTypeIdSlot(It->second.first);
2983     assert(Slot != -1);
2984     Out << "^" << Slot;
2985     Out << ", offset: " << VFId.Offset;
2986     Out << ")";
2987   }
2988 }
2989 
2990 void AssemblyWriter::printNonConstVCalls(
2991     const std::vector<FunctionSummary::VFuncId> VCallList, const char *Tag) {
2992   Out << Tag << ": (";
2993   FieldSeparator FS;
2994   for (auto &VFuncId : VCallList) {
2995     Out << FS;
2996     printVFuncId(VFuncId);
2997   }
2998   Out << ")";
2999 }
3000 
3001 void AssemblyWriter::printConstVCalls(
3002     const std::vector<FunctionSummary::ConstVCall> VCallList, const char *Tag) {
3003   Out << Tag << ": (";
3004   FieldSeparator FS;
3005   for (auto &ConstVCall : VCallList) {
3006     Out << FS;
3007     Out << "(";
3008     printVFuncId(ConstVCall.VFunc);
3009     if (!ConstVCall.Args.empty()) {
3010       Out << ", ";
3011       printArgs(ConstVCall.Args);
3012     }
3013     Out << ")";
3014   }
3015   Out << ")";
3016 }
3017 
3018 void AssemblyWriter::printSummary(const GlobalValueSummary &Summary) {
3019   GlobalValueSummary::GVFlags GVFlags = Summary.flags();
3020   GlobalValue::LinkageTypes LT = (GlobalValue::LinkageTypes)GVFlags.Linkage;
3021   Out << getSummaryKindName(Summary.getSummaryKind()) << ": ";
3022   Out << "(module: ^" << Machine.getModulePathSlot(Summary.modulePath())
3023       << ", flags: (";
3024   Out << "linkage: " << getLinkageName(LT);
3025   Out << ", notEligibleToImport: " << GVFlags.NotEligibleToImport;
3026   Out << ", live: " << GVFlags.Live;
3027   Out << ", dsoLocal: " << GVFlags.DSOLocal;
3028   Out << ")";
3029 
3030   if (Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3031     printAliasSummary(cast<AliasSummary>(&Summary));
3032   else if (Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3033     printFunctionSummary(cast<FunctionSummary>(&Summary));
3034   else
3035     printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3036 
3037   auto RefList = Summary.refs();
3038   if (!RefList.empty()) {
3039     Out << ", refs: (";
3040     FieldSeparator FS;
3041     for (auto &Ref : RefList) {
3042       Out << FS;
3043       if (Ref.isReadOnly())
3044         Out << "readonly ";
3045       Out << "^" << Machine.getGUIDSlot(Ref.getGUID());
3046     }
3047     Out << ")";
3048   }
3049 
3050   Out << ")";
3051 }
3052 
3053 void AssemblyWriter::printSummaryInfo(unsigned Slot, const ValueInfo &VI) {
3054   Out << "^" << Slot << " = gv: (";
3055   if (!VI.name().empty())
3056     Out << "name: \"" << VI.name() << "\"";
3057   else
3058     Out << "guid: " << VI.getGUID();
3059   if (!VI.getSummaryList().empty()) {
3060     Out << ", summaries: (";
3061     FieldSeparator FS;
3062     for (auto &Summary : VI.getSummaryList()) {
3063       Out << FS;
3064       printSummary(*Summary);
3065     }
3066     Out << ")";
3067   }
3068   Out << ")";
3069   if (!VI.name().empty())
3070     Out << " ; guid = " << VI.getGUID();
3071   Out << "\n";
3072 }
3073 
3074 static void printMetadataIdentifier(StringRef Name,
3075                                     formatted_raw_ostream &Out) {
3076   if (Name.empty()) {
3077     Out << "<empty name> ";
3078   } else {
3079     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
3080         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
3081       Out << Name[0];
3082     else
3083       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
3084     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
3085       unsigned char C = Name[i];
3086       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
3087           C == '.' || C == '_')
3088         Out << C;
3089       else
3090         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
3091     }
3092   }
3093 }
3094 
3095 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
3096   Out << '!';
3097   printMetadataIdentifier(NMD->getName(), Out);
3098   Out << " = !{";
3099   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
3100     if (i)
3101       Out << ", ";
3102 
3103     // Write DIExpressions inline.
3104     // FIXME: Ban DIExpressions in NamedMDNodes, they will serve no purpose.
3105     MDNode *Op = NMD->getOperand(i);
3106     if (auto *Expr = dyn_cast<DIExpression>(Op)) {
3107       writeDIExpression(Out, Expr, nullptr, nullptr, nullptr);
3108       continue;
3109     }
3110 
3111     int Slot = Machine.getMetadataSlot(Op);
3112     if (Slot == -1)
3113       Out << "<badref>";
3114     else
3115       Out << '!' << Slot;
3116   }
3117   Out << "}\n";
3118 }
3119 
3120 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
3121                             formatted_raw_ostream &Out) {
3122   switch (Vis) {
3123   case GlobalValue::DefaultVisibility: break;
3124   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
3125   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
3126   }
3127 }
3128 
3129 static void PrintDSOLocation(const GlobalValue &GV,
3130                              formatted_raw_ostream &Out) {
3131   // GVs with local linkage or non default visibility are implicitly dso_local,
3132   // so we don't print it.
3133   bool Implicit = GV.hasLocalLinkage() ||
3134                   (!GV.hasExternalWeakLinkage() && !GV.hasDefaultVisibility());
3135   if (GV.isDSOLocal() && !Implicit)
3136     Out << "dso_local ";
3137 }
3138 
3139 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
3140                                  formatted_raw_ostream &Out) {
3141   switch (SCT) {
3142   case GlobalValue::DefaultStorageClass: break;
3143   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
3144   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
3145   }
3146 }
3147 
3148 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
3149                                   formatted_raw_ostream &Out) {
3150   switch (TLM) {
3151     case GlobalVariable::NotThreadLocal:
3152       break;
3153     case GlobalVariable::GeneralDynamicTLSModel:
3154       Out << "thread_local ";
3155       break;
3156     case GlobalVariable::LocalDynamicTLSModel:
3157       Out << "thread_local(localdynamic) ";
3158       break;
3159     case GlobalVariable::InitialExecTLSModel:
3160       Out << "thread_local(initialexec) ";
3161       break;
3162     case GlobalVariable::LocalExecTLSModel:
3163       Out << "thread_local(localexec) ";
3164       break;
3165   }
3166 }
3167 
3168 static StringRef getUnnamedAddrEncoding(GlobalVariable::UnnamedAddr UA) {
3169   switch (UA) {
3170   case GlobalVariable::UnnamedAddr::None:
3171     return "";
3172   case GlobalVariable::UnnamedAddr::Local:
3173     return "local_unnamed_addr";
3174   case GlobalVariable::UnnamedAddr::Global:
3175     return "unnamed_addr";
3176   }
3177   llvm_unreachable("Unknown UnnamedAddr");
3178 }
3179 
3180 static void maybePrintComdat(formatted_raw_ostream &Out,
3181                              const GlobalObject &GO) {
3182   const Comdat *C = GO.getComdat();
3183   if (!C)
3184     return;
3185 
3186   if (isa<GlobalVariable>(GO))
3187     Out << ',';
3188   Out << " comdat";
3189 
3190   if (GO.getName() == C->getName())
3191     return;
3192 
3193   Out << '(';
3194   PrintLLVMName(Out, C->getName(), ComdatPrefix);
3195   Out << ')';
3196 }
3197 
3198 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
3199   if (GV->isMaterializable())
3200     Out << "; Materializable\n";
3201 
3202   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
3203   Out << " = ";
3204 
3205   if (!GV->hasInitializer() && GV->hasExternalLinkage())
3206     Out << "external ";
3207 
3208   Out << getLinkageNameWithSpace(GV->getLinkage());
3209   PrintDSOLocation(*GV, Out);
3210   PrintVisibility(GV->getVisibility(), Out);
3211   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
3212   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
3213   StringRef UA = getUnnamedAddrEncoding(GV->getUnnamedAddr());
3214   if (!UA.empty())
3215       Out << UA << ' ';
3216 
3217   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
3218     Out << "addrspace(" << AddressSpace << ") ";
3219   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
3220   Out << (GV->isConstant() ? "constant " : "global ");
3221   TypePrinter.print(GV->getValueType(), Out);
3222 
3223   if (GV->hasInitializer()) {
3224     Out << ' ';
3225     writeOperand(GV->getInitializer(), false);
3226   }
3227 
3228   if (GV->hasSection()) {
3229     Out << ", section \"";
3230     printEscapedString(GV->getSection(), Out);
3231     Out << '"';
3232   }
3233   maybePrintComdat(Out, *GV);
3234   if (GV->getAlignment())
3235     Out << ", align " << GV->getAlignment();
3236 
3237   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3238   GV->getAllMetadata(MDs);
3239   printMetadataAttachments(MDs, ", ");
3240 
3241   auto Attrs = GV->getAttributes();
3242   if (Attrs.hasAttributes())
3243     Out << " #" << Machine.getAttributeGroupSlot(Attrs);
3244 
3245   printInfoComment(*GV);
3246 }
3247 
3248 void AssemblyWriter::printIndirectSymbol(const GlobalIndirectSymbol *GIS) {
3249   if (GIS->isMaterializable())
3250     Out << "; Materializable\n";
3251 
3252   WriteAsOperandInternal(Out, GIS, &TypePrinter, &Machine, GIS->getParent());
3253   Out << " = ";
3254 
3255   Out << getLinkageNameWithSpace(GIS->getLinkage());
3256   PrintDSOLocation(*GIS, Out);
3257   PrintVisibility(GIS->getVisibility(), Out);
3258   PrintDLLStorageClass(GIS->getDLLStorageClass(), Out);
3259   PrintThreadLocalModel(GIS->getThreadLocalMode(), Out);
3260   StringRef UA = getUnnamedAddrEncoding(GIS->getUnnamedAddr());
3261   if (!UA.empty())
3262       Out << UA << ' ';
3263 
3264   if (isa<GlobalAlias>(GIS))
3265     Out << "alias ";
3266   else if (isa<GlobalIFunc>(GIS))
3267     Out << "ifunc ";
3268   else
3269     llvm_unreachable("Not an alias or ifunc!");
3270 
3271   TypePrinter.print(GIS->getValueType(), Out);
3272 
3273   Out << ", ";
3274 
3275   const Constant *IS = GIS->getIndirectSymbol();
3276 
3277   if (!IS) {
3278     TypePrinter.print(GIS->getType(), Out);
3279     Out << " <<NULL ALIASEE>>";
3280   } else {
3281     writeOperand(IS, !isa<ConstantExpr>(IS));
3282   }
3283 
3284   printInfoComment(*GIS);
3285   Out << '\n';
3286 }
3287 
3288 void AssemblyWriter::printComdat(const Comdat *C) {
3289   C->print(Out);
3290 }
3291 
3292 void AssemblyWriter::printTypeIdentities() {
3293   if (TypePrinter.empty())
3294     return;
3295 
3296   Out << '\n';
3297 
3298   // Emit all numbered types.
3299   auto &NumberedTypes = TypePrinter.getNumberedTypes();
3300   for (unsigned I = 0, E = NumberedTypes.size(); I != E; ++I) {
3301     Out << '%' << I << " = type ";
3302 
3303     // Make sure we print out at least one level of the type structure, so
3304     // that we do not get %2 = type %2
3305     TypePrinter.printStructBody(NumberedTypes[I], Out);
3306     Out << '\n';
3307   }
3308 
3309   auto &NamedTypes = TypePrinter.getNamedTypes();
3310   for (unsigned I = 0, E = NamedTypes.size(); I != E; ++I) {
3311     PrintLLVMName(Out, NamedTypes[I]->getName(), LocalPrefix);
3312     Out << " = type ";
3313 
3314     // Make sure we print out at least one level of the type structure, so
3315     // that we do not get %FILE = type %FILE
3316     TypePrinter.printStructBody(NamedTypes[I], Out);
3317     Out << '\n';
3318   }
3319 }
3320 
3321 /// printFunction - Print all aspects of a function.
3322 void AssemblyWriter::printFunction(const Function *F) {
3323   // Print out the return type and name.
3324   Out << '\n';
3325 
3326   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
3327 
3328   if (F->isMaterializable())
3329     Out << "; Materializable\n";
3330 
3331   const AttributeList &Attrs = F->getAttributes();
3332   if (Attrs.hasAttributes(AttributeList::FunctionIndex)) {
3333     AttributeSet AS = Attrs.getFnAttributes();
3334     std::string AttrStr;
3335 
3336     for (const Attribute &Attr : AS) {
3337       if (!Attr.isStringAttribute()) {
3338         if (!AttrStr.empty()) AttrStr += ' ';
3339         AttrStr += Attr.getAsString();
3340       }
3341     }
3342 
3343     if (!AttrStr.empty())
3344       Out << "; Function Attrs: " << AttrStr << '\n';
3345   }
3346 
3347   Machine.incorporateFunction(F);
3348 
3349   if (F->isDeclaration()) {
3350     Out << "declare";
3351     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3352     F->getAllMetadata(MDs);
3353     printMetadataAttachments(MDs, " ");
3354     Out << ' ';
3355   } else
3356     Out << "define ";
3357 
3358   Out << getLinkageNameWithSpace(F->getLinkage());
3359   PrintDSOLocation(*F, Out);
3360   PrintVisibility(F->getVisibility(), Out);
3361   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
3362 
3363   // Print the calling convention.
3364   if (F->getCallingConv() != CallingConv::C) {
3365     PrintCallingConv(F->getCallingConv(), Out);
3366     Out << " ";
3367   }
3368 
3369   FunctionType *FT = F->getFunctionType();
3370   if (Attrs.hasAttributes(AttributeList::ReturnIndex))
3371     Out << Attrs.getAsString(AttributeList::ReturnIndex) << ' ';
3372   TypePrinter.print(F->getReturnType(), Out);
3373   Out << ' ';
3374   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
3375   Out << '(';
3376 
3377   // Loop over the arguments, printing them...
3378   if (F->isDeclaration() && !IsForDebug) {
3379     // We're only interested in the type here - don't print argument names.
3380     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
3381       // Insert commas as we go... the first arg doesn't get a comma
3382       if (I)
3383         Out << ", ";
3384       // Output type...
3385       TypePrinter.print(FT->getParamType(I), Out);
3386 
3387       AttributeSet ArgAttrs = Attrs.getParamAttributes(I);
3388       if (ArgAttrs.hasAttributes())
3389         Out << ' ' << ArgAttrs.getAsString();
3390     }
3391   } else {
3392     // The arguments are meaningful here, print them in detail.
3393     for (const Argument &Arg : F->args()) {
3394       // Insert commas as we go... the first arg doesn't get a comma
3395       if (Arg.getArgNo() != 0)
3396         Out << ", ";
3397       printArgument(&Arg, Attrs.getParamAttributes(Arg.getArgNo()));
3398     }
3399   }
3400 
3401   // Finish printing arguments...
3402   if (FT->isVarArg()) {
3403     if (FT->getNumParams()) Out << ", ";
3404     Out << "...";  // Output varargs portion of signature!
3405   }
3406   Out << ')';
3407   StringRef UA = getUnnamedAddrEncoding(F->getUnnamedAddr());
3408   if (!UA.empty())
3409     Out << ' ' << UA;
3410   // We print the function address space if it is non-zero or if we are writing
3411   // a module with a non-zero program address space or if there is no valid
3412   // Module* so that the file can be parsed without the datalayout string.
3413   const Module *Mod = F->getParent();
3414   if (F->getAddressSpace() != 0 || !Mod ||
3415       Mod->getDataLayout().getProgramAddressSpace() != 0)
3416     Out << " addrspace(" << F->getAddressSpace() << ")";
3417   if (Attrs.hasAttributes(AttributeList::FunctionIndex))
3418     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
3419   if (F->hasSection()) {
3420     Out << " section \"";
3421     printEscapedString(F->getSection(), Out);
3422     Out << '"';
3423   }
3424   maybePrintComdat(Out, *F);
3425   if (F->getAlignment())
3426     Out << " align " << F->getAlignment();
3427   if (F->hasGC())
3428     Out << " gc \"" << F->getGC() << '"';
3429   if (F->hasPrefixData()) {
3430     Out << " prefix ";
3431     writeOperand(F->getPrefixData(), true);
3432   }
3433   if (F->hasPrologueData()) {
3434     Out << " prologue ";
3435     writeOperand(F->getPrologueData(), true);
3436   }
3437   if (F->hasPersonalityFn()) {
3438     Out << " personality ";
3439     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
3440   }
3441 
3442   if (F->isDeclaration()) {
3443     Out << '\n';
3444   } else {
3445     SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
3446     F->getAllMetadata(MDs);
3447     printMetadataAttachments(MDs, " ");
3448 
3449     Out << " {";
3450     // Output all of the function's basic blocks.
3451     for (const BasicBlock &BB : *F)
3452       printBasicBlock(&BB);
3453 
3454     // Output the function's use-lists.
3455     printUseLists(F);
3456 
3457     Out << "}\n";
3458   }
3459 
3460   Machine.purgeFunction();
3461 }
3462 
3463 /// printArgument - This member is called for every argument that is passed into
3464 /// the function.  Simply print it out
3465 void AssemblyWriter::printArgument(const Argument *Arg, AttributeSet Attrs) {
3466   // Output type...
3467   TypePrinter.print(Arg->getType(), Out);
3468 
3469   // Output parameter attributes list
3470   if (Attrs.hasAttributes())
3471     Out << ' ' << Attrs.getAsString();
3472 
3473   // Output name, if available...
3474   if (Arg->hasName()) {
3475     Out << ' ';
3476     PrintLLVMName(Out, Arg);
3477   }
3478 }
3479 
3480 /// printBasicBlock - This member is called for each basic block in a method.
3481 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
3482   if (BB->hasName()) {              // Print out the label if it exists...
3483     Out << "\n";
3484     PrintLLVMName(Out, BB->getName(), LabelPrefix);
3485     Out << ':';
3486   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
3487     Out << "\n; <label>:";
3488     int Slot = Machine.getLocalSlot(BB);
3489     if (Slot != -1)
3490       Out << Slot << ":";
3491     else
3492       Out << "<badref>";
3493   }
3494 
3495   if (!BB->getParent()) {
3496     Out.PadToColumn(50);
3497     Out << "; Error: Block without parent!";
3498   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
3499     // Output predecessors for the block.
3500     Out.PadToColumn(50);
3501     Out << ";";
3502     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3503 
3504     if (PI == PE) {
3505       Out << " No predecessors!";
3506     } else {
3507       Out << " preds = ";
3508       writeOperand(*PI, false);
3509       for (++PI; PI != PE; ++PI) {
3510         Out << ", ";
3511         writeOperand(*PI, false);
3512       }
3513     }
3514   }
3515 
3516   Out << "\n";
3517 
3518   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
3519 
3520   // Output all of the instructions in the basic block...
3521   for (const Instruction &I : *BB) {
3522     printInstructionLine(I);
3523   }
3524 
3525   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
3526 }
3527 
3528 /// printInstructionLine - Print an instruction and a newline character.
3529 void AssemblyWriter::printInstructionLine(const Instruction &I) {
3530   printInstruction(I);
3531   Out << '\n';
3532 }
3533 
3534 /// printGCRelocateComment - print comment after call to the gc.relocate
3535 /// intrinsic indicating base and derived pointer names.
3536 void AssemblyWriter::printGCRelocateComment(const GCRelocateInst &Relocate) {
3537   Out << " ; (";
3538   writeOperand(Relocate.getBasePtr(), false);
3539   Out << ", ";
3540   writeOperand(Relocate.getDerivedPtr(), false);
3541   Out << ")";
3542 }
3543 
3544 /// printInfoComment - Print a little comment after the instruction indicating
3545 /// which slot it occupies.
3546 void AssemblyWriter::printInfoComment(const Value &V) {
3547   if (const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3548     printGCRelocateComment(*Relocate);
3549 
3550   if (AnnotationWriter)
3551     AnnotationWriter->printInfoComment(V, Out);
3552 }
3553 
3554 static void maybePrintCallAddrSpace(const Value *Operand, const Instruction *I,
3555                                     raw_ostream &Out) {
3556   // We print the address space of the call if it is non-zero.
3557   unsigned CallAddrSpace = Operand->getType()->getPointerAddressSpace();
3558   bool PrintAddrSpace = CallAddrSpace != 0;
3559   if (!PrintAddrSpace) {
3560     const Module *Mod = getModuleFromVal(I);
3561     // We also print it if it is zero but not equal to the program address space
3562     // or if we can't find a valid Module* to make it possible to parse
3563     // the resulting file even without a datalayout string.
3564     if (!Mod || Mod->getDataLayout().getProgramAddressSpace() != 0)
3565       PrintAddrSpace = true;
3566   }
3567   if (PrintAddrSpace)
3568     Out << " addrspace(" << CallAddrSpace << ")";
3569 }
3570 
3571 // This member is called for each Instruction in a function..
3572 void AssemblyWriter::printInstruction(const Instruction &I) {
3573   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
3574 
3575   // Print out indentation for an instruction.
3576   Out << "  ";
3577 
3578   // Print out name if it exists...
3579   if (I.hasName()) {
3580     PrintLLVMName(Out, &I);
3581     Out << " = ";
3582   } else if (!I.getType()->isVoidTy()) {
3583     // Print out the def slot taken.
3584     int SlotNum = Machine.getLocalSlot(&I);
3585     if (SlotNum == -1)
3586       Out << "<badref> = ";
3587     else
3588       Out << '%' << SlotNum << " = ";
3589   }
3590 
3591   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3592     if (CI->isMustTailCall())
3593       Out << "musttail ";
3594     else if (CI->isTailCall())
3595       Out << "tail ";
3596     else if (CI->isNoTailCall())
3597       Out << "notail ";
3598   }
3599 
3600   // Print out the opcode...
3601   Out << I.getOpcodeName();
3602 
3603   // If this is an atomic load or store, print out the atomic marker.
3604   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
3605       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
3606     Out << " atomic";
3607 
3608   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
3609     Out << " weak";
3610 
3611   // If this is a volatile operation, print out the volatile marker.
3612   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
3613       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
3614       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
3615       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
3616     Out << " volatile";
3617 
3618   // Print out optimization information.
3619   WriteOptimizationInfo(Out, &I);
3620 
3621   // Print out the compare instruction predicates
3622   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
3623     Out << ' ' << CmpInst::getPredicateName(CI->getPredicate());
3624 
3625   // Print out the atomicrmw operation
3626   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
3627     Out << ' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
3628 
3629   // Print out the type of the operands...
3630   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
3631 
3632   // Special case conditional branches to swizzle the condition out to the front
3633   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
3634     const BranchInst &BI(cast<BranchInst>(I));
3635     Out << ' ';
3636     writeOperand(BI.getCondition(), true);
3637     Out << ", ";
3638     writeOperand(BI.getSuccessor(0), true);
3639     Out << ", ";
3640     writeOperand(BI.getSuccessor(1), true);
3641 
3642   } else if (isa<SwitchInst>(I)) {
3643     const SwitchInst& SI(cast<SwitchInst>(I));
3644     // Special case switch instruction to get formatting nice and correct.
3645     Out << ' ';
3646     writeOperand(SI.getCondition(), true);
3647     Out << ", ";
3648     writeOperand(SI.getDefaultDest(), true);
3649     Out << " [";
3650     for (auto Case : SI.cases()) {
3651       Out << "\n    ";
3652       writeOperand(Case.getCaseValue(), true);
3653       Out << ", ";
3654       writeOperand(Case.getCaseSuccessor(), true);
3655     }
3656     Out << "\n  ]";
3657   } else if (isa<IndirectBrInst>(I)) {
3658     // Special case indirectbr instruction to get formatting nice and correct.
3659     Out << ' ';
3660     writeOperand(Operand, true);
3661     Out << ", [";
3662 
3663     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
3664       if (i != 1)
3665         Out << ", ";
3666       writeOperand(I.getOperand(i), true);
3667     }
3668     Out << ']';
3669   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
3670     Out << ' ';
3671     TypePrinter.print(I.getType(), Out);
3672     Out << ' ';
3673 
3674     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
3675       if (op) Out << ", ";
3676       Out << "[ ";
3677       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
3678       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
3679     }
3680   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
3681     Out << ' ';
3682     writeOperand(I.getOperand(0), true);
3683     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
3684       Out << ", " << *i;
3685   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
3686     Out << ' ';
3687     writeOperand(I.getOperand(0), true); Out << ", ";
3688     writeOperand(I.getOperand(1), true);
3689     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
3690       Out << ", " << *i;
3691   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
3692     Out << ' ';
3693     TypePrinter.print(I.getType(), Out);
3694     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
3695       Out << '\n';
3696 
3697     if (LPI->isCleanup())
3698       Out << "          cleanup";
3699 
3700     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
3701       if (i != 0 || LPI->isCleanup()) Out << "\n";
3702       if (LPI->isCatch(i))
3703         Out << "          catch ";
3704       else
3705         Out << "          filter ";
3706 
3707       writeOperand(LPI->getClause(i), true);
3708     }
3709   } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&I)) {
3710     Out << " within ";
3711     writeOperand(CatchSwitch->getParentPad(), /*PrintType=*/false);
3712     Out << " [";
3713     unsigned Op = 0;
3714     for (const BasicBlock *PadBB : CatchSwitch->handlers()) {
3715       if (Op > 0)
3716         Out << ", ";
3717       writeOperand(PadBB, /*PrintType=*/true);
3718       ++Op;
3719     }
3720     Out << "] unwind ";
3721     if (const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
3722       writeOperand(UnwindDest, /*PrintType=*/true);
3723     else
3724       Out << "to caller";
3725   } else if (const auto *FPI = dyn_cast<FuncletPadInst>(&I)) {
3726     Out << " within ";
3727     writeOperand(FPI->getParentPad(), /*PrintType=*/false);
3728     Out << " [";
3729     for (unsigned Op = 0, NumOps = FPI->getNumArgOperands(); Op < NumOps;
3730          ++Op) {
3731       if (Op > 0)
3732         Out << ", ";
3733       writeOperand(FPI->getArgOperand(Op), /*PrintType=*/true);
3734     }
3735     Out << ']';
3736   } else if (isa<ReturnInst>(I) && !Operand) {
3737     Out << " void";
3738   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
3739     Out << " from ";
3740     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3741 
3742     Out << " to ";
3743     writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3744   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
3745     Out << " from ";
3746     writeOperand(CRI->getOperand(0), /*PrintType=*/false);
3747 
3748     Out << " unwind ";
3749     if (CRI->hasUnwindDest())
3750       writeOperand(CRI->getOperand(1), /*PrintType=*/true);
3751     else
3752       Out << "to caller";
3753   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
3754     // Print the calling convention being used.
3755     if (CI->getCallingConv() != CallingConv::C) {
3756       Out << " ";
3757       PrintCallingConv(CI->getCallingConv(), Out);
3758     }
3759 
3760     Operand = CI->getCalledValue();
3761     FunctionType *FTy = CI->getFunctionType();
3762     Type *RetTy = FTy->getReturnType();
3763     const AttributeList &PAL = CI->getAttributes();
3764 
3765     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3766       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3767 
3768     // Only print addrspace(N) if necessary:
3769     maybePrintCallAddrSpace(Operand, &I, Out);
3770 
3771     // If possible, print out the short form of the call instruction.  We can
3772     // only do this if the first argument is a pointer to a nonvararg function,
3773     // and if the return type is not a pointer to a function.
3774     //
3775     Out << ' ';
3776     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3777     Out << ' ';
3778     writeOperand(Operand, false);
3779     Out << '(';
3780     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
3781       if (op > 0)
3782         Out << ", ";
3783       writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op));
3784     }
3785 
3786     // Emit an ellipsis if this is a musttail call in a vararg function.  This
3787     // is only to aid readability, musttail calls forward varargs by default.
3788     if (CI->isMustTailCall() && CI->getParent() &&
3789         CI->getParent()->getParent() &&
3790         CI->getParent()->getParent()->isVarArg())
3791       Out << ", ...";
3792 
3793     Out << ')';
3794     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3795       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3796 
3797     writeOperandBundles(CI);
3798   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
3799     Operand = II->getCalledValue();
3800     FunctionType *FTy = II->getFunctionType();
3801     Type *RetTy = FTy->getReturnType();
3802     const AttributeList &PAL = II->getAttributes();
3803 
3804     // Print the calling convention being used.
3805     if (II->getCallingConv() != CallingConv::C) {
3806       Out << " ";
3807       PrintCallingConv(II->getCallingConv(), Out);
3808     }
3809 
3810     if (PAL.hasAttributes(AttributeList::ReturnIndex))
3811       Out << ' ' << PAL.getAsString(AttributeList::ReturnIndex);
3812 
3813     // Only print addrspace(N) if necessary:
3814     maybePrintCallAddrSpace(Operand, &I, Out);
3815 
3816     // If possible, print out the short form of the invoke instruction. We can
3817     // only do this if the first argument is a pointer to a nonvararg function,
3818     // and if the return type is not a pointer to a function.
3819     //
3820     Out << ' ';
3821     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3822     Out << ' ';
3823     writeOperand(Operand, false);
3824     Out << '(';
3825     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3826       if (op)
3827         Out << ", ";
3828       writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op));
3829     }
3830 
3831     Out << ')';
3832     if (PAL.hasAttributes(AttributeList::FunctionIndex))
3833       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3834 
3835     writeOperandBundles(II);
3836 
3837     Out << "\n          to ";
3838     writeOperand(II->getNormalDest(), true);
3839     Out << " unwind ";
3840     writeOperand(II->getUnwindDest(), true);
3841   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3842     Out << ' ';
3843     if (AI->isUsedWithInAlloca())
3844       Out << "inalloca ";
3845     if (AI->isSwiftError())
3846       Out << "swifterror ";
3847     TypePrinter.print(AI->getAllocatedType(), Out);
3848 
3849     // Explicitly write the array size if the code is broken, if it's an array
3850     // allocation, or if the type is not canonical for scalar allocations.  The
3851     // latter case prevents the type from mutating when round-tripping through
3852     // assembly.
3853     if (!AI->getArraySize() || AI->isArrayAllocation() ||
3854         !AI->getArraySize()->getType()->isIntegerTy(32)) {
3855       Out << ", ";
3856       writeOperand(AI->getArraySize(), true);
3857     }
3858     if (AI->getAlignment()) {
3859       Out << ", align " << AI->getAlignment();
3860     }
3861 
3862     unsigned AddrSpace = AI->getType()->getAddressSpace();
3863     if (AddrSpace != 0) {
3864       Out << ", addrspace(" << AddrSpace << ')';
3865     }
3866   } else if (isa<CastInst>(I)) {
3867     if (Operand) {
3868       Out << ' ';
3869       writeOperand(Operand, true);   // Work with broken code
3870     }
3871     Out << " to ";
3872     TypePrinter.print(I.getType(), Out);
3873   } else if (isa<VAArgInst>(I)) {
3874     if (Operand) {
3875       Out << ' ';
3876       writeOperand(Operand, true);   // Work with broken code
3877     }
3878     Out << ", ";
3879     TypePrinter.print(I.getType(), Out);
3880   } else if (Operand) {   // Print the normal way.
3881     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3882       Out << ' ';
3883       TypePrinter.print(GEP->getSourceElementType(), Out);
3884       Out << ',';
3885     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3886       Out << ' ';
3887       TypePrinter.print(LI->getType(), Out);
3888       Out << ',';
3889     }
3890 
3891     // PrintAllTypes - Instructions who have operands of all the same type
3892     // omit the type from all but the first operand.  If the instruction has
3893     // different type operands (for example br), then they are all printed.
3894     bool PrintAllTypes = false;
3895     Type *TheType = Operand->getType();
3896 
3897     // Select, Store and ShuffleVector always print all types.
3898     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3899         || isa<ReturnInst>(I)) {
3900       PrintAllTypes = true;
3901     } else {
3902       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3903         Operand = I.getOperand(i);
3904         // note that Operand shouldn't be null, but the test helps make dump()
3905         // more tolerant of malformed IR
3906         if (Operand && Operand->getType() != TheType) {
3907           PrintAllTypes = true;    // We have differing types!  Print them all!
3908           break;
3909         }
3910       }
3911     }
3912 
3913     if (!PrintAllTypes) {
3914       Out << ' ';
3915       TypePrinter.print(TheType, Out);
3916     }
3917 
3918     Out << ' ';
3919     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3920       if (i) Out << ", ";
3921       writeOperand(I.getOperand(i), PrintAllTypes);
3922     }
3923   }
3924 
3925   // Print atomic ordering/alignment for memory operations
3926   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3927     if (LI->isAtomic())
3928       writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
3929     if (LI->getAlignment())
3930       Out << ", align " << LI->getAlignment();
3931   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3932     if (SI->isAtomic())
3933       writeAtomic(SI->getContext(), SI->getOrdering(), SI->getSyncScopeID());
3934     if (SI->getAlignment())
3935       Out << ", align " << SI->getAlignment();
3936   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3937     writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
3938                        CXI->getFailureOrdering(), CXI->getSyncScopeID());
3939   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3940     writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
3941                 RMWI->getSyncScopeID());
3942   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3943     writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
3944   }
3945 
3946   // Print Metadata info.
3947   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3948   I.getAllMetadata(InstMD);
3949   printMetadataAttachments(InstMD, ", ");
3950 
3951   // Print a nice comment.
3952   printInfoComment(I);
3953 }
3954 
3955 void AssemblyWriter::printMetadataAttachments(
3956     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3957     StringRef Separator) {
3958   if (MDs.empty())
3959     return;
3960 
3961   if (MDNames.empty())
3962     MDs[0].second->getContext().getMDKindNames(MDNames);
3963 
3964   for (const auto &I : MDs) {
3965     unsigned Kind = I.first;
3966     Out << Separator;
3967     if (Kind < MDNames.size()) {
3968       Out << "!";
3969       printMetadataIdentifier(MDNames[Kind], Out);
3970     } else
3971       Out << "!<unknown kind #" << Kind << ">";
3972     Out << ' ';
3973     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3974   }
3975 }
3976 
3977 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3978   Out << '!' << Slot << " = ";
3979   printMDNodeBody(Node);
3980   Out << "\n";
3981 }
3982 
3983 void AssemblyWriter::writeAllMDNodes() {
3984   SmallVector<const MDNode *, 16> Nodes;
3985   Nodes.resize(Machine.mdn_size());
3986   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3987        I != E; ++I)
3988     Nodes[I->second] = cast<MDNode>(I->first);
3989 
3990   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3991     writeMDNode(i, Nodes[i]);
3992   }
3993 }
3994 
3995 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3996   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3997 }
3998 
3999 void AssemblyWriter::writeAllAttributeGroups() {
4000   std::vector<std::pair<AttributeSet, unsigned>> asVec;
4001   asVec.resize(Machine.as_size());
4002 
4003   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
4004        I != E; ++I)
4005     asVec[I->second] = *I;
4006 
4007   for (const auto &I : asVec)
4008     Out << "attributes #" << I.second << " = { "
4009         << I.first.getAsString(true) << " }\n";
4010 }
4011 
4012 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
4013   bool IsInFunction = Machine.getFunction();
4014   if (IsInFunction)
4015     Out << "  ";
4016 
4017   Out << "uselistorder";
4018   if (const BasicBlock *BB =
4019           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
4020     Out << "_bb ";
4021     writeOperand(BB->getParent(), false);
4022     Out << ", ";
4023     writeOperand(BB, false);
4024   } else {
4025     Out << " ";
4026     writeOperand(Order.V, true);
4027   }
4028   Out << ", { ";
4029 
4030   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
4031   Out << Order.Shuffle[0];
4032   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
4033     Out << ", " << Order.Shuffle[I];
4034   Out << " }\n";
4035 }
4036 
4037 void AssemblyWriter::printUseLists(const Function *F) {
4038   auto hasMore =
4039       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
4040   if (!hasMore())
4041     // Nothing to do.
4042     return;
4043 
4044   Out << "\n; uselistorder directives\n";
4045   while (hasMore()) {
4046     printUseListOrder(UseListOrders.back());
4047     UseListOrders.pop_back();
4048   }
4049 }
4050 
4051 //===----------------------------------------------------------------------===//
4052 //                       External Interface declarations
4053 //===----------------------------------------------------------------------===//
4054 
4055 void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4056                      bool ShouldPreserveUseListOrder,
4057                      bool IsForDebug) const {
4058   SlotTracker SlotTable(this->getParent());
4059   formatted_raw_ostream OS(ROS);
4060   AssemblyWriter W(OS, SlotTable, this->getParent(), AAW,
4061                    IsForDebug,
4062                    ShouldPreserveUseListOrder);
4063   W.printFunction(this);
4064 }
4065 
4066 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
4067                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
4068   SlotTracker SlotTable(this);
4069   formatted_raw_ostream OS(ROS);
4070   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
4071                    ShouldPreserveUseListOrder);
4072   W.printModule(this);
4073 }
4074 
4075 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
4076   SlotTracker SlotTable(getParent());
4077   formatted_raw_ostream OS(ROS);
4078   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
4079   W.printNamedMDNode(this);
4080 }
4081 
4082 void NamedMDNode::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4083                         bool IsForDebug) const {
4084   Optional<SlotTracker> LocalST;
4085   SlotTracker *SlotTable;
4086   if (auto *ST = MST.getMachine())
4087     SlotTable = ST;
4088   else {
4089     LocalST.emplace(getParent());
4090     SlotTable = &*LocalST;
4091   }
4092 
4093   formatted_raw_ostream OS(ROS);
4094   AssemblyWriter W(OS, *SlotTable, getParent(), nullptr, IsForDebug);
4095   W.printNamedMDNode(this);
4096 }
4097 
4098 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
4099   PrintLLVMName(ROS, getName(), ComdatPrefix);
4100   ROS << " = comdat ";
4101 
4102   switch (getSelectionKind()) {
4103   case Comdat::Any:
4104     ROS << "any";
4105     break;
4106   case Comdat::ExactMatch:
4107     ROS << "exactmatch";
4108     break;
4109   case Comdat::Largest:
4110     ROS << "largest";
4111     break;
4112   case Comdat::NoDuplicates:
4113     ROS << "noduplicates";
4114     break;
4115   case Comdat::SameSize:
4116     ROS << "samesize";
4117     break;
4118   }
4119 
4120   ROS << '\n';
4121 }
4122 
4123 void Type::print(raw_ostream &OS, bool /*IsForDebug*/, bool NoDetails) const {
4124   TypePrinting TP;
4125   TP.print(const_cast<Type*>(this), OS);
4126 
4127   if (NoDetails)
4128     return;
4129 
4130   // If the type is a named struct type, print the body as well.
4131   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
4132     if (!STy->isLiteral()) {
4133       OS << " = type ";
4134       TP.printStructBody(STy, OS);
4135     }
4136 }
4137 
4138 static bool isReferencingMDNode(const Instruction &I) {
4139   if (const auto *CI = dyn_cast<CallInst>(&I))
4140     if (Function *F = CI->getCalledFunction())
4141       if (F->isIntrinsic())
4142         for (auto &Op : I.operands())
4143           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
4144             if (isa<MDNode>(V->getMetadata()))
4145               return true;
4146   return false;
4147 }
4148 
4149 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
4150   bool ShouldInitializeAllMetadata = false;
4151   if (auto *I = dyn_cast<Instruction>(this))
4152     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
4153   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
4154     ShouldInitializeAllMetadata = true;
4155 
4156   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
4157   print(ROS, MST, IsForDebug);
4158 }
4159 
4160 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
4161                   bool IsForDebug) const {
4162   formatted_raw_ostream OS(ROS);
4163   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
4164   SlotTracker &SlotTable =
4165       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
4166   auto incorporateFunction = [&](const Function *F) {
4167     if (F)
4168       MST.incorporateFunction(*F);
4169   };
4170 
4171   if (const Instruction *I = dyn_cast<Instruction>(this)) {
4172     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
4173     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
4174     W.printInstruction(*I);
4175   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
4176     incorporateFunction(BB->getParent());
4177     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
4178     W.printBasicBlock(BB);
4179   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
4180     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
4181     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
4182       W.printGlobal(V);
4183     else if (const Function *F = dyn_cast<Function>(GV))
4184       W.printFunction(F);
4185     else
4186       W.printIndirectSymbol(cast<GlobalIndirectSymbol>(GV));
4187   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
4188     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
4189   } else if (const Constant *C = dyn_cast<Constant>(this)) {
4190     TypePrinting TypePrinter;
4191     TypePrinter.print(C->getType(), OS);
4192     OS << ' ';
4193     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
4194   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
4195     this->printAsOperand(OS, /* PrintType */ true, MST);
4196   } else {
4197     llvm_unreachable("Unknown value to print out!");
4198   }
4199 }
4200 
4201 /// Print without a type, skipping the TypePrinting object.
4202 ///
4203 /// \return \c true iff printing was successful.
4204 static bool printWithoutType(const Value &V, raw_ostream &O,
4205                              SlotTracker *Machine, const Module *M) {
4206   if (V.hasName() || isa<GlobalValue>(V) ||
4207       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4208     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
4209     return true;
4210   }
4211   return false;
4212 }
4213 
4214 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
4215                                ModuleSlotTracker &MST) {
4216   TypePrinting TypePrinter(MST.getModule());
4217   if (PrintType) {
4218     TypePrinter.print(V.getType(), O);
4219     O << ' ';
4220   }
4221 
4222   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
4223                          MST.getModule());
4224 }
4225 
4226 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4227                            const Module *M) const {
4228   if (!M)
4229     M = getModuleFromVal(this);
4230 
4231   if (!PrintType)
4232     if (printWithoutType(*this, O, nullptr, M))
4233       return;
4234 
4235   SlotTracker Machine(
4236       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
4237   ModuleSlotTracker MST(Machine, M);
4238   printAsOperandImpl(*this, O, PrintType, MST);
4239 }
4240 
4241 void Value::printAsOperand(raw_ostream &O, bool PrintType,
4242                            ModuleSlotTracker &MST) const {
4243   if (!PrintType)
4244     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
4245       return;
4246 
4247   printAsOperandImpl(*this, O, PrintType, MST);
4248 }
4249 
4250 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
4251                               ModuleSlotTracker &MST, const Module *M,
4252                               bool OnlyAsOperand) {
4253   formatted_raw_ostream OS(ROS);
4254 
4255   TypePrinting TypePrinter(M);
4256 
4257   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
4258                          /* FromValue */ true);
4259 
4260   auto *N = dyn_cast<MDNode>(&MD);
4261   if (OnlyAsOperand || !N || isa<DIExpression>(MD))
4262     return;
4263 
4264   OS << " = ";
4265   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
4266 }
4267 
4268 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
4269   ModuleSlotTracker MST(M, isa<MDNode>(this));
4270   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4271 }
4272 
4273 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
4274                               const Module *M) const {
4275   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
4276 }
4277 
4278 void Metadata::print(raw_ostream &OS, const Module *M,
4279                      bool /*IsForDebug*/) const {
4280   ModuleSlotTracker MST(M, isa<MDNode>(this));
4281   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4282 }
4283 
4284 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
4285                      const Module *M, bool /*IsForDebug*/) const {
4286   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
4287 }
4288 
4289 void ModuleSummaryIndex::print(raw_ostream &ROS, bool IsForDebug) const {
4290   SlotTracker SlotTable(this);
4291   formatted_raw_ostream OS(ROS);
4292   AssemblyWriter W(OS, SlotTable, this, IsForDebug);
4293   W.printModuleSummaryIndex();
4294 }
4295 
4296 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4297 // Value::dump - allow easy printing of Values from the debugger.
4298 LLVM_DUMP_METHOD
4299 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4300 
4301 // Type::dump - allow easy printing of Types from the debugger.
4302 LLVM_DUMP_METHOD
4303 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
4304 
4305 // Module::dump() - Allow printing of Modules from the debugger.
4306 LLVM_DUMP_METHOD
4307 void Module::dump() const {
4308   print(dbgs(), nullptr,
4309         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
4310 }
4311 
4312 // Allow printing of Comdats from the debugger.
4313 LLVM_DUMP_METHOD
4314 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4315 
4316 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
4317 LLVM_DUMP_METHOD
4318 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4319 
4320 LLVM_DUMP_METHOD
4321 void Metadata::dump() const { dump(nullptr); }
4322 
4323 LLVM_DUMP_METHOD
4324 void Metadata::dump(const Module *M) const {
4325   print(dbgs(), M, /*IsForDebug=*/true);
4326   dbgs() << '\n';
4327 }
4328 
4329 // Allow printing of ModuleSummaryIndex from the debugger.
4330 LLVM_DUMP_METHOD
4331 void ModuleSummaryIndex::dump() const { print(dbgs(), /*IsForDebug=*/true); }
4332 #endif
4333