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