IR: Update a comment and a bool that've been out of date since 2012
[oota-llvm.git] / lib / IR / AsmWriter.cpp
1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/IR/Writer.h
11 //
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/IR/AssemblyAnnotationWriter.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/Statepoint.h"
36 #include "llvm/IR/TypeFinder.h"
37 #include "llvm/IR/UseListOrder.h"
38 #include "llvm/IR/ValueSymbolTable.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <algorithm>
46 #include <cctype>
47 using namespace llvm;
48
49 // Make virtual table appear in this compilation unit.
50 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
51
52 //===----------------------------------------------------------------------===//
53 // Helper Functions
54 //===----------------------------------------------------------------------===//
55
56 namespace {
57 struct OrderMap {
58   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
59
60   unsigned size() const { return IDs.size(); }
61   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
62   std::pair<unsigned, bool> lookup(const Value *V) const {
63     return IDs.lookup(V);
64   }
65   void index(const Value *V) {
66     // Explicitly sequence get-size and insert-value operations to avoid UB.
67     unsigned ID = IDs.size() + 1;
68     IDs[V].first = ID;
69   }
70 };
71 }
72
73 static void orderValue(const Value *V, OrderMap &OM) {
74   if (OM.lookup(V).first)
75     return;
76
77   if (const Constant *C = dyn_cast<Constant>(V))
78     if (C->getNumOperands() && !isa<GlobalValue>(C))
79       for (const Value *Op : C->operands())
80         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
81           orderValue(Op, OM);
82
83   // Note: we cannot cache this lookup above, since inserting into the map
84   // changes the map's size, and thus affects the other IDs.
85   OM.index(V);
86 }
87
88 static OrderMap orderModule(const Module *M) {
89   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
90   // and ValueEnumerator::incorporateFunction().
91   OrderMap OM;
92
93   for (const GlobalVariable &G : M->globals()) {
94     if (G.hasInitializer())
95       if (!isa<GlobalValue>(G.getInitializer()))
96         orderValue(G.getInitializer(), OM);
97     orderValue(&G, OM);
98   }
99   for (const GlobalAlias &A : M->aliases()) {
100     if (!isa<GlobalValue>(A.getAliasee()))
101       orderValue(A.getAliasee(), OM);
102     orderValue(&A, OM);
103   }
104   for (const Function &F : *M) {
105     if (F.hasPrefixData())
106       if (!isa<GlobalValue>(F.getPrefixData()))
107         orderValue(F.getPrefixData(), OM);
108
109     if (F.hasPrologueData())
110       if (!isa<GlobalValue>(F.getPrologueData()))
111         orderValue(F.getPrologueData(), OM);
112
113     if (F.hasPersonalityFn())
114       if (!isa<GlobalValue>(F.getPersonalityFn()))
115         orderValue(F.getPersonalityFn(), OM);
116
117     orderValue(&F, OM);
118
119     if (F.isDeclaration())
120       continue;
121
122     for (const Argument &A : F.args())
123       orderValue(&A, OM);
124     for (const BasicBlock &BB : F) {
125       orderValue(&BB, OM);
126       for (const Instruction &I : BB) {
127         for (const Value *Op : I.operands())
128           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
129               isa<InlineAsm>(*Op))
130             orderValue(Op, OM);
131         orderValue(&I, OM);
132       }
133     }
134   }
135   return OM;
136 }
137
138 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
139                                          unsigned ID, const OrderMap &OM,
140                                          UseListOrderStack &Stack) {
141   // Predict use-list order for this one.
142   typedef std::pair<const Use *, unsigned> Entry;
143   SmallVector<Entry, 64> List;
144   for (const Use &U : V->uses())
145     // Check if this user will be serialized.
146     if (OM.lookup(U.getUser()).first)
147       List.push_back(std::make_pair(&U, List.size()));
148
149   if (List.size() < 2)
150     // We may have lost some users.
151     return;
152
153   bool GetsReversed =
154       !isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
155   if (auto *BA = dyn_cast<BlockAddress>(V))
156     ID = OM.lookup(BA->getBasicBlock()).first;
157   std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
158     const Use *LU = L.first;
159     const Use *RU = R.first;
160     if (LU == RU)
161       return false;
162
163     auto LID = OM.lookup(LU->getUser()).first;
164     auto RID = OM.lookup(RU->getUser()).first;
165
166     // If ID is 4, then expect: 7 6 5 1 2 3.
167     if (LID < RID) {
168       if (GetsReversed)
169         if (RID <= ID)
170           return true;
171       return false;
172     }
173     if (RID < LID) {
174       if (GetsReversed)
175         if (LID <= ID)
176           return false;
177       return true;
178     }
179
180     // LID and RID are equal, so we have different operands of the same user.
181     // Assume operands are added in order for all instructions.
182     if (GetsReversed)
183       if (LID <= ID)
184         return LU->getOperandNo() < RU->getOperandNo();
185     return LU->getOperandNo() > RU->getOperandNo();
186   });
187
188   if (std::is_sorted(
189           List.begin(), List.end(),
190           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
191     // Order is already correct.
192     return;
193
194   // Store the shuffle.
195   Stack.emplace_back(V, F, List.size());
196   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
197   for (size_t I = 0, E = List.size(); I != E; ++I)
198     Stack.back().Shuffle[I] = List[I].second;
199 }
200
201 static void predictValueUseListOrder(const Value *V, const Function *F,
202                                      OrderMap &OM, UseListOrderStack &Stack) {
203   auto &IDPair = OM[V];
204   assert(IDPair.first && "Unmapped value");
205   if (IDPair.second)
206     // Already predicted.
207     return;
208
209   // Do the actual prediction.
210   IDPair.second = true;
211   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
212     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
213
214   // Recursive descent into constants.
215   if (const Constant *C = dyn_cast<Constant>(V))
216     if (C->getNumOperands()) // Visit GlobalValues.
217       for (const Value *Op : C->operands())
218         if (isa<Constant>(Op)) // Visit GlobalValues.
219           predictValueUseListOrder(Op, F, OM, Stack);
220 }
221
222 static UseListOrderStack predictUseListOrder(const Module *M) {
223   OrderMap OM = orderModule(M);
224
225   // Use-list orders need to be serialized after all the users have been added
226   // to a value, or else the shuffles will be incomplete.  Store them per
227   // function in a stack.
228   //
229   // Aside from function order, the order of values doesn't matter much here.
230   UseListOrderStack Stack;
231
232   // We want to visit the functions backward now so we can list function-local
233   // constants in the last Function they're used in.  Module-level constants
234   // have already been visited above.
235   for (const Function &F : make_range(M->rbegin(), M->rend())) {
236     if (F.isDeclaration())
237       continue;
238     for (const BasicBlock &BB : F)
239       predictValueUseListOrder(&BB, &F, OM, Stack);
240     for (const Argument &A : F.args())
241       predictValueUseListOrder(&A, &F, OM, Stack);
242     for (const BasicBlock &BB : F)
243       for (const Instruction &I : BB)
244         for (const Value *Op : I.operands())
245           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
246             predictValueUseListOrder(Op, &F, OM, Stack);
247     for (const BasicBlock &BB : F)
248       for (const Instruction &I : BB)
249         predictValueUseListOrder(&I, &F, OM, Stack);
250   }
251
252   // Visit globals last.
253   for (const GlobalVariable &G : M->globals())
254     predictValueUseListOrder(&G, nullptr, OM, Stack);
255   for (const Function &F : *M)
256     predictValueUseListOrder(&F, nullptr, OM, Stack);
257   for (const GlobalAlias &A : M->aliases())
258     predictValueUseListOrder(&A, nullptr, OM, Stack);
259   for (const GlobalVariable &G : M->globals())
260     if (G.hasInitializer())
261       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
262   for (const GlobalAlias &A : M->aliases())
263     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
264   for (const Function &F : *M)
265     if (F.hasPrefixData())
266       predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
267
268   return Stack;
269 }
270
271 static const Module *getModuleFromVal(const Value *V) {
272   if (const Argument *MA = dyn_cast<Argument>(V))
273     return MA->getParent() ? MA->getParent()->getParent() : nullptr;
274
275   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
276     return BB->getParent() ? BB->getParent()->getParent() : nullptr;
277
278   if (const Instruction *I = dyn_cast<Instruction>(V)) {
279     const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
280     return M ? M->getParent() : nullptr;
281   }
282
283   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
284     return GV->getParent();
285
286   if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
287     for (const User *U : MAV->users())
288       if (isa<Instruction>(U))
289         if (const Module *M = getModuleFromVal(U))
290           return M;
291     return nullptr;
292   }
293
294   return nullptr;
295 }
296
297 static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
298   switch (cc) {
299   default:                         Out << "cc" << cc; break;
300   case CallingConv::Fast:          Out << "fastcc"; break;
301   case CallingConv::Cold:          Out << "coldcc"; break;
302   case CallingConv::WebKit_JS:     Out << "webkit_jscc"; break;
303   case CallingConv::AnyReg:        Out << "anyregcc"; break;
304   case CallingConv::PreserveMost:  Out << "preserve_mostcc"; break;
305   case CallingConv::PreserveAll:   Out << "preserve_allcc"; break;
306   case CallingConv::GHC:           Out << "ghccc"; break;
307   case CallingConv::X86_StdCall:   Out << "x86_stdcallcc"; break;
308   case CallingConv::X86_FastCall:  Out << "x86_fastcallcc"; break;
309   case CallingConv::X86_ThisCall:  Out << "x86_thiscallcc"; break;
310   case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
311   case CallingConv::Intel_OCL_BI:  Out << "intel_ocl_bicc"; break;
312   case CallingConv::ARM_APCS:      Out << "arm_apcscc"; break;
313   case CallingConv::ARM_AAPCS:     Out << "arm_aapcscc"; break;
314   case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
315   case CallingConv::MSP430_INTR:   Out << "msp430_intrcc"; break;
316   case CallingConv::PTX_Kernel:    Out << "ptx_kernel"; break;
317   case CallingConv::PTX_Device:    Out << "ptx_device"; break;
318   case CallingConv::X86_64_SysV:   Out << "x86_64_sysvcc"; break;
319   case CallingConv::X86_64_Win64:  Out << "x86_64_win64cc"; break;
320   case CallingConv::SPIR_FUNC:     Out << "spir_func"; break;
321   case CallingConv::SPIR_KERNEL:   Out << "spir_kernel"; break;
322   case CallingConv::HHVM:          Out << "hhvmcc"; break;
323   case CallingConv::HHVM_C:        Out << "hhvm_ccc"; break;
324   }
325 }
326
327 // PrintEscapedString - Print each character of the specified string, escaping
328 // it if it is not printable or if it is an escape char.
329 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
330   for (unsigned i = 0, e = Name.size(); i != e; ++i) {
331     unsigned char C = Name[i];
332     if (isprint(C) && C != '\\' && C != '"')
333       Out << C;
334     else
335       Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
336   }
337 }
338
339 enum PrefixType {
340   GlobalPrefix,
341   ComdatPrefix,
342   LabelPrefix,
343   LocalPrefix,
344   NoPrefix
345 };
346
347 void llvm::printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef Name) {
348   assert(!Name.empty() && "Cannot get empty name!");
349
350   // Scan the name to see if it needs quotes first.
351   bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
352   if (!NeedsQuotes) {
353     for (unsigned i = 0, e = Name.size(); i != e; ++i) {
354       // By making this unsigned, the value passed in to isalnum will always be
355       // in the range 0-255.  This is important when building with MSVC because
356       // its implementation will assert.  This situation can arise when dealing
357       // with UTF-8 multibyte characters.
358       unsigned char C = Name[i];
359       if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
360           C != '_') {
361         NeedsQuotes = true;
362         break;
363       }
364     }
365   }
366
367   // If we didn't need any quotes, just write out the name in one blast.
368   if (!NeedsQuotes) {
369     OS << Name;
370     return;
371   }
372
373   // Okay, we need quotes.  Output the quotes and escape any scary characters as
374   // needed.
375   OS << '"';
376   PrintEscapedString(Name, OS);
377   OS << '"';
378 }
379
380 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
381 /// (if the string only contains simple characters) or is surrounded with ""'s
382 /// (if it has special chars in it). Print it out.
383 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
384   switch (Prefix) {
385   case NoPrefix:
386     break;
387   case GlobalPrefix:
388     OS << '@';
389     break;
390   case ComdatPrefix:
391     OS << '$';
392     break;
393   case LabelPrefix:
394     break;
395   case LocalPrefix:
396     OS << '%';
397     break;
398   }
399   printLLVMNameWithoutPrefix(OS, Name);
400 }
401
402 /// Turn the specified name into an 'LLVM name', which is either prefixed with %
403 /// (if the string only contains simple characters) or is surrounded with ""'s
404 /// (if it has special chars in it). Print it out.
405 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
406   PrintLLVMName(OS, V->getName(),
407                 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
408 }
409
410
411 namespace {
412 class TypePrinting {
413   TypePrinting(const TypePrinting &) = delete;
414   void operator=(const TypePrinting&) = delete;
415 public:
416
417   /// NamedTypes - The named types that are used by the current module.
418   TypeFinder NamedTypes;
419
420   /// NumberedTypes - The numbered types, along with their value.
421   DenseMap<StructType*, unsigned> NumberedTypes;
422
423   TypePrinting() = default;
424
425   void incorporateTypes(const Module &M);
426
427   void print(Type *Ty, raw_ostream &OS);
428
429   void printStructBody(StructType *Ty, raw_ostream &OS);
430 };
431 } // namespace
432
433 void TypePrinting::incorporateTypes(const Module &M) {
434   NamedTypes.run(M, false);
435
436   // The list of struct types we got back includes all the struct types, split
437   // the unnamed ones out to a numbering and remove the anonymous structs.
438   unsigned NextNumber = 0;
439
440   std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
441   for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
442     StructType *STy = *I;
443
444     // Ignore anonymous types.
445     if (STy->isLiteral())
446       continue;
447
448     if (STy->getName().empty())
449       NumberedTypes[STy] = NextNumber++;
450     else
451       *NextToUse++ = STy;
452   }
453
454   NamedTypes.erase(NextToUse, NamedTypes.end());
455 }
456
457
458 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
459 /// use of type names or up references to shorten the type name where possible.
460 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
461   switch (Ty->getTypeID()) {
462   case Type::VoidTyID:      OS << "void"; return;
463   case Type::HalfTyID:      OS << "half"; return;
464   case Type::FloatTyID:     OS << "float"; return;
465   case Type::DoubleTyID:    OS << "double"; return;
466   case Type::X86_FP80TyID:  OS << "x86_fp80"; return;
467   case Type::FP128TyID:     OS << "fp128"; return;
468   case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
469   case Type::LabelTyID:     OS << "label"; return;
470   case Type::MetadataTyID:  OS << "metadata"; return;
471   case Type::X86_MMXTyID:   OS << "x86_mmx"; return;
472   case Type::TokenTyID:     OS << "token"; return;
473   case Type::IntegerTyID:
474     OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
475     return;
476
477   case Type::FunctionTyID: {
478     FunctionType *FTy = cast<FunctionType>(Ty);
479     print(FTy->getReturnType(), OS);
480     OS << " (";
481     for (FunctionType::param_iterator I = FTy->param_begin(),
482          E = FTy->param_end(); I != E; ++I) {
483       if (I != FTy->param_begin())
484         OS << ", ";
485       print(*I, OS);
486     }
487     if (FTy->isVarArg()) {
488       if (FTy->getNumParams()) OS << ", ";
489       OS << "...";
490     }
491     OS << ')';
492     return;
493   }
494   case Type::StructTyID: {
495     StructType *STy = cast<StructType>(Ty);
496
497     if (STy->isLiteral())
498       return printStructBody(STy, OS);
499
500     if (!STy->getName().empty())
501       return PrintLLVMName(OS, STy->getName(), LocalPrefix);
502
503     DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
504     if (I != NumberedTypes.end())
505       OS << '%' << I->second;
506     else  // Not enumerated, print the hex address.
507       OS << "%\"type " << STy << '\"';
508     return;
509   }
510   case Type::PointerTyID: {
511     PointerType *PTy = cast<PointerType>(Ty);
512     print(PTy->getElementType(), OS);
513     if (unsigned AddressSpace = PTy->getAddressSpace())
514       OS << " addrspace(" << AddressSpace << ')';
515     OS << '*';
516     return;
517   }
518   case Type::ArrayTyID: {
519     ArrayType *ATy = cast<ArrayType>(Ty);
520     OS << '[' << ATy->getNumElements() << " x ";
521     print(ATy->getElementType(), OS);
522     OS << ']';
523     return;
524   }
525   case Type::VectorTyID: {
526     VectorType *PTy = cast<VectorType>(Ty);
527     OS << "<" << PTy->getNumElements() << " x ";
528     print(PTy->getElementType(), OS);
529     OS << '>';
530     return;
531   }
532   }
533   llvm_unreachable("Invalid TypeID");
534 }
535
536 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
537   if (STy->isOpaque()) {
538     OS << "opaque";
539     return;
540   }
541
542   if (STy->isPacked())
543     OS << '<';
544
545   if (STy->getNumElements() == 0) {
546     OS << "{}";
547   } else {
548     StructType::element_iterator I = STy->element_begin();
549     OS << "{ ";
550     print(*I++, OS);
551     for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
552       OS << ", ";
553       print(*I, OS);
554     }
555
556     OS << " }";
557   }
558   if (STy->isPacked())
559     OS << '>';
560 }
561
562 namespace llvm {
563 //===----------------------------------------------------------------------===//
564 // SlotTracker Class: Enumerate slot numbers for unnamed values
565 //===----------------------------------------------------------------------===//
566 /// This class provides computation of slot numbers for LLVM Assembly writing.
567 ///
568 class SlotTracker {
569 public:
570   /// ValueMap - A mapping of Values to slot numbers.
571   typedef DenseMap<const Value*, unsigned> ValueMap;
572
573 private:
574   /// TheModule - The module for which we are holding slot numbers.
575   const Module* TheModule;
576
577   /// TheFunction - The function for which we are holding slot numbers.
578   const Function* TheFunction;
579   bool FunctionProcessed;
580   bool ShouldInitializeAllMetadata;
581
582   /// mMap - The slot map for the module level data.
583   ValueMap mMap;
584   unsigned mNext;
585
586   /// fMap - The slot map for the function level data.
587   ValueMap fMap;
588   unsigned fNext;
589
590   /// mdnMap - Map for MDNodes.
591   DenseMap<const MDNode*, unsigned> mdnMap;
592   unsigned mdnNext;
593
594   /// asMap - The slot map for attribute sets.
595   DenseMap<AttributeSet, unsigned> asMap;
596   unsigned asNext;
597 public:
598   /// Construct from a module.
599   ///
600   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
601   /// functions, giving correct numbering for metadata referenced only from
602   /// within a function (even if no functions have been initialized).
603   explicit SlotTracker(const Module *M,
604                        bool ShouldInitializeAllMetadata = false);
605   /// Construct from a function, starting out in incorp state.
606   ///
607   /// If \c ShouldInitializeAllMetadata, initializes all metadata in all
608   /// functions, giving correct numbering for metadata referenced only from
609   /// within a function (even if no functions have been initialized).
610   explicit SlotTracker(const Function *F,
611                        bool ShouldInitializeAllMetadata = false);
612
613   /// Return the slot number of the specified value in it's type
614   /// plane.  If something is not in the SlotTracker, return -1.
615   int getLocalSlot(const Value *V);
616   int getGlobalSlot(const GlobalValue *V);
617   int getMetadataSlot(const MDNode *N);
618   int getAttributeGroupSlot(AttributeSet AS);
619
620   /// If you'd like to deal with a function instead of just a module, use
621   /// this method to get its data into the SlotTracker.
622   void incorporateFunction(const Function *F) {
623     TheFunction = F;
624     FunctionProcessed = false;
625   }
626
627   const Function *getFunction() const { return TheFunction; }
628
629   /// After calling incorporateFunction, use this method to remove the
630   /// most recently incorporated function from the SlotTracker. This
631   /// will reset the state of the machine back to just the module contents.
632   void purgeFunction();
633
634   /// MDNode map iterators.
635   typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
636   mdn_iterator mdn_begin() { return mdnMap.begin(); }
637   mdn_iterator mdn_end() { return mdnMap.end(); }
638   unsigned mdn_size() const { return mdnMap.size(); }
639   bool mdn_empty() const { return mdnMap.empty(); }
640
641   /// AttributeSet map iterators.
642   typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
643   as_iterator as_begin()   { return asMap.begin(); }
644   as_iterator as_end()     { return asMap.end(); }
645   unsigned as_size() const { return asMap.size(); }
646   bool as_empty() const    { return asMap.empty(); }
647
648   /// This function does the actual initialization.
649   inline void initialize();
650
651   // Implementation Details
652 private:
653   /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
654   void CreateModuleSlot(const GlobalValue *V);
655
656   /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
657   void CreateMetadataSlot(const MDNode *N);
658
659   /// CreateFunctionSlot - Insert the specified Value* into the slot table.
660   void CreateFunctionSlot(const Value *V);
661
662   /// \brief Insert the specified AttributeSet into the slot table.
663   void CreateAttributeSetSlot(AttributeSet AS);
664
665   /// Add all of the module level global variables (and their initializers)
666   /// and function declarations, but not the contents of those functions.
667   void processModule();
668
669   /// Add all of the functions arguments, basic blocks, and instructions.
670   void processFunction();
671
672   /// Add all of the metadata from a function.
673   void processFunctionMetadata(const Function &F);
674
675   /// Add all of the metadata from an instruction.
676   void processInstructionMetadata(const Instruction &I);
677
678   SlotTracker(const SlotTracker &) = delete;
679   void operator=(const SlotTracker &) = delete;
680 };
681 } // namespace llvm
682
683 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
684                                      const Function *F)
685     : M(M), F(F), Machine(&Machine) {}
686
687 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
688                                      bool ShouldInitializeAllMetadata)
689     : MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
690                        : nullptr),
691       M(M), Machine(MachineStorage.get()) {}
692
693 ModuleSlotTracker::~ModuleSlotTracker() {}
694
695 void ModuleSlotTracker::incorporateFunction(const Function &F) {
696   if (!Machine)
697     return;
698
699   // Nothing to do if this is the right function already.
700   if (this->F == &F)
701     return;
702   if (this->F)
703     Machine->purgeFunction();
704   Machine->incorporateFunction(&F);
705   this->F = &F;
706 }
707
708 int ModuleSlotTracker::getLocalSlot(const Value *V) {
709   assert(F && "No function incorporated");
710   return Machine->getLocalSlot(V);
711 }
712
713 static SlotTracker *createSlotTracker(const Value *V) {
714   if (const Argument *FA = dyn_cast<Argument>(V))
715     return new SlotTracker(FA->getParent());
716
717   if (const Instruction *I = dyn_cast<Instruction>(V))
718     if (I->getParent())
719       return new SlotTracker(I->getParent()->getParent());
720
721   if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
722     return new SlotTracker(BB->getParent());
723
724   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
725     return new SlotTracker(GV->getParent());
726
727   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
728     return new SlotTracker(GA->getParent());
729
730   if (const Function *Func = dyn_cast<Function>(V))
731     return new SlotTracker(Func);
732
733   return nullptr;
734 }
735
736 #if 0
737 #define ST_DEBUG(X) dbgs() << X
738 #else
739 #define ST_DEBUG(X)
740 #endif
741
742 // Module level constructor. Causes the contents of the Module (sans functions)
743 // to be added to the slot table.
744 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
745     : TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
746       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
747       fNext(0), mdnNext(0), asNext(0) {}
748
749 // Function level constructor. Causes the contents of the Module and the one
750 // function provided to be added to the slot table.
751 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
752     : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
753       FunctionProcessed(false),
754       ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
755       fNext(0), mdnNext(0), asNext(0) {}
756
757 inline void SlotTracker::initialize() {
758   if (TheModule) {
759     processModule();
760     TheModule = nullptr; ///< Prevent re-processing next time we're called.
761   }
762
763   if (TheFunction && !FunctionProcessed)
764     processFunction();
765 }
766
767 // Iterate through all the global variables, functions, and global
768 // variable initializers and create slots for them.
769 void SlotTracker::processModule() {
770   ST_DEBUG("begin processModule!\n");
771
772   // Add all of the unnamed global variables to the value table.
773   for (const GlobalVariable &Var : TheModule->globals()) {
774     if (!Var.hasName())
775       CreateModuleSlot(&Var);
776   }
777
778   for (const GlobalAlias &A : TheModule->aliases()) {
779     if (!A.hasName())
780       CreateModuleSlot(&A);
781   }
782
783   // Add metadata used by named metadata.
784   for (const NamedMDNode &NMD : TheModule->named_metadata()) {
785     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
786       CreateMetadataSlot(NMD.getOperand(i));
787   }
788
789   for (const Function &F : *TheModule) {
790     if (!F.hasName())
791       // Add all the unnamed functions to the table.
792       CreateModuleSlot(&F);
793
794     if (ShouldInitializeAllMetadata)
795       processFunctionMetadata(F);
796
797     // Add all the function attributes to the table.
798     // FIXME: Add attributes of other objects?
799     AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
800     if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
801       CreateAttributeSetSlot(FnAttrs);
802   }
803
804   ST_DEBUG("end processModule!\n");
805 }
806
807 // Process the arguments, basic blocks, and instructions  of a function.
808 void SlotTracker::processFunction() {
809   ST_DEBUG("begin processFunction!\n");
810   fNext = 0;
811
812   // Process function metadata if it wasn't hit at the module-level.
813   if (!ShouldInitializeAllMetadata)
814     processFunctionMetadata(*TheFunction);
815
816   // Add all the function arguments with no names.
817   for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
818       AE = TheFunction->arg_end(); AI != AE; ++AI)
819     if (!AI->hasName())
820       CreateFunctionSlot(&*AI);
821
822   ST_DEBUG("Inserting Instructions:\n");
823
824   // Add all of the basic blocks and instructions with no names.
825   for (auto &BB : *TheFunction) {
826     if (!BB.hasName())
827       CreateFunctionSlot(&BB);
828
829     for (auto &I : BB) {
830       if (!I.getType()->isVoidTy() && !I.hasName())
831         CreateFunctionSlot(&I);
832
833       // We allow direct calls to any llvm.foo function here, because the
834       // target may not be linked into the optimizer.
835       if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
836         // Add all the call attributes to the table.
837         AttributeSet Attrs = CI->getAttributes().getFnAttributes();
838         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
839           CreateAttributeSetSlot(Attrs);
840       } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
841         // Add all the call attributes to the table.
842         AttributeSet Attrs = II->getAttributes().getFnAttributes();
843         if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
844           CreateAttributeSetSlot(Attrs);
845       }
846     }
847   }
848
849   FunctionProcessed = true;
850
851   ST_DEBUG("end processFunction!\n");
852 }
853
854 void SlotTracker::processFunctionMetadata(const Function &F) {
855   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
856   F.getAllMetadata(MDs);
857   for (auto &MD : MDs)
858     CreateMetadataSlot(MD.second);
859
860   for (auto &BB : F) {
861     for (auto &I : BB)
862       processInstructionMetadata(I);
863   }
864 }
865
866 void SlotTracker::processInstructionMetadata(const Instruction &I) {
867   // Process metadata used directly by intrinsics.
868   if (const CallInst *CI = dyn_cast<CallInst>(&I))
869     if (Function *F = CI->getCalledFunction())
870       if (F->isIntrinsic())
871         for (auto &Op : I.operands())
872           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
873             if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
874               CreateMetadataSlot(N);
875
876   // Process metadata attached to this instruction.
877   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
878   I.getAllMetadata(MDs);
879   for (auto &MD : MDs)
880     CreateMetadataSlot(MD.second);
881 }
882
883 /// Clean up after incorporating a function. This is the only way to get out of
884 /// the function incorporation state that affects get*Slot/Create*Slot. Function
885 /// incorporation state is indicated by TheFunction != 0.
886 void SlotTracker::purgeFunction() {
887   ST_DEBUG("begin purgeFunction!\n");
888   fMap.clear(); // Simply discard the function level map
889   TheFunction = nullptr;
890   FunctionProcessed = false;
891   ST_DEBUG("end purgeFunction!\n");
892 }
893
894 /// getGlobalSlot - Get the slot number of a global value.
895 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
896   // Check for uninitialized state and do lazy initialization.
897   initialize();
898
899   // Find the value in the module map
900   ValueMap::iterator MI = mMap.find(V);
901   return MI == mMap.end() ? -1 : (int)MI->second;
902 }
903
904 /// getMetadataSlot - Get the slot number of a MDNode.
905 int SlotTracker::getMetadataSlot(const MDNode *N) {
906   // Check for uninitialized state and do lazy initialization.
907   initialize();
908
909   // Find the MDNode in the module map
910   mdn_iterator MI = mdnMap.find(N);
911   return MI == mdnMap.end() ? -1 : (int)MI->second;
912 }
913
914
915 /// getLocalSlot - Get the slot number for a value that is local to a function.
916 int SlotTracker::getLocalSlot(const Value *V) {
917   assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
918
919   // Check for uninitialized state and do lazy initialization.
920   initialize();
921
922   ValueMap::iterator FI = fMap.find(V);
923   return FI == fMap.end() ? -1 : (int)FI->second;
924 }
925
926 int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
927   // Check for uninitialized state and do lazy initialization.
928   initialize();
929
930   // Find the AttributeSet in the module map.
931   as_iterator AI = asMap.find(AS);
932   return AI == asMap.end() ? -1 : (int)AI->second;
933 }
934
935 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
936 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
937   assert(V && "Can't insert a null Value into SlotTracker!");
938   assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
939   assert(!V->hasName() && "Doesn't need a slot!");
940
941   unsigned DestSlot = mNext++;
942   mMap[V] = DestSlot;
943
944   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
945            DestSlot << " [");
946   // G = Global, F = Function, A = Alias, o = other
947   ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
948             (isa<Function>(V) ? 'F' :
949              (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
950 }
951
952 /// CreateSlot - Create a new slot for the specified value if it has no name.
953 void SlotTracker::CreateFunctionSlot(const Value *V) {
954   assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
955
956   unsigned DestSlot = fNext++;
957   fMap[V] = DestSlot;
958
959   // G = Global, F = Function, o = other
960   ST_DEBUG("  Inserting value [" << V->getType() << "] = " << V << " slot=" <<
961            DestSlot << " [o]\n");
962 }
963
964 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
965 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
966   assert(N && "Can't insert a null Value into SlotTracker!");
967
968   unsigned DestSlot = mdnNext;
969   if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
970     return;
971   ++mdnNext;
972
973   // Recursively add any MDNodes referenced by operands.
974   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
975     if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
976       CreateMetadataSlot(Op);
977 }
978
979 void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
980   assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
981          "Doesn't need a slot!");
982
983   as_iterator I = asMap.find(AS);
984   if (I != asMap.end())
985     return;
986
987   unsigned DestSlot = asNext++;
988   asMap[AS] = DestSlot;
989 }
990
991 //===----------------------------------------------------------------------===//
992 // AsmWriter Implementation
993 //===----------------------------------------------------------------------===//
994
995 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
996                                    TypePrinting *TypePrinter,
997                                    SlotTracker *Machine,
998                                    const Module *Context);
999
1000 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1001                                    TypePrinting *TypePrinter,
1002                                    SlotTracker *Machine, const Module *Context,
1003                                    bool FromValue = false);
1004
1005 static const char *getPredicateText(unsigned predicate) {
1006   const char * pred = "unknown";
1007   switch (predicate) {
1008   case FCmpInst::FCMP_FALSE: pred = "false"; break;
1009   case FCmpInst::FCMP_OEQ:   pred = "oeq"; break;
1010   case FCmpInst::FCMP_OGT:   pred = "ogt"; break;
1011   case FCmpInst::FCMP_OGE:   pred = "oge"; break;
1012   case FCmpInst::FCMP_OLT:   pred = "olt"; break;
1013   case FCmpInst::FCMP_OLE:   pred = "ole"; break;
1014   case FCmpInst::FCMP_ONE:   pred = "one"; break;
1015   case FCmpInst::FCMP_ORD:   pred = "ord"; break;
1016   case FCmpInst::FCMP_UNO:   pred = "uno"; break;
1017   case FCmpInst::FCMP_UEQ:   pred = "ueq"; break;
1018   case FCmpInst::FCMP_UGT:   pred = "ugt"; break;
1019   case FCmpInst::FCMP_UGE:   pred = "uge"; break;
1020   case FCmpInst::FCMP_ULT:   pred = "ult"; break;
1021   case FCmpInst::FCMP_ULE:   pred = "ule"; break;
1022   case FCmpInst::FCMP_UNE:   pred = "une"; break;
1023   case FCmpInst::FCMP_TRUE:  pred = "true"; break;
1024   case ICmpInst::ICMP_EQ:    pred = "eq"; break;
1025   case ICmpInst::ICMP_NE:    pred = "ne"; break;
1026   case ICmpInst::ICMP_SGT:   pred = "sgt"; break;
1027   case ICmpInst::ICMP_SGE:   pred = "sge"; break;
1028   case ICmpInst::ICMP_SLT:   pred = "slt"; break;
1029   case ICmpInst::ICMP_SLE:   pred = "sle"; break;
1030   case ICmpInst::ICMP_UGT:   pred = "ugt"; break;
1031   case ICmpInst::ICMP_UGE:   pred = "uge"; break;
1032   case ICmpInst::ICMP_ULT:   pred = "ult"; break;
1033   case ICmpInst::ICMP_ULE:   pred = "ule"; break;
1034   }
1035   return pred;
1036 }
1037
1038 static void writeAtomicRMWOperation(raw_ostream &Out,
1039                                     AtomicRMWInst::BinOp Op) {
1040   switch (Op) {
1041   default: Out << " <unknown operation " << Op << ">"; break;
1042   case AtomicRMWInst::Xchg: Out << " xchg"; break;
1043   case AtomicRMWInst::Add:  Out << " add"; break;
1044   case AtomicRMWInst::Sub:  Out << " sub"; break;
1045   case AtomicRMWInst::And:  Out << " and"; break;
1046   case AtomicRMWInst::Nand: Out << " nand"; break;
1047   case AtomicRMWInst::Or:   Out << " or"; break;
1048   case AtomicRMWInst::Xor:  Out << " xor"; break;
1049   case AtomicRMWInst::Max:  Out << " max"; break;
1050   case AtomicRMWInst::Min:  Out << " min"; break;
1051   case AtomicRMWInst::UMax: Out << " umax"; break;
1052   case AtomicRMWInst::UMin: Out << " umin"; break;
1053   }
1054 }
1055
1056 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
1057   if (const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U)) {
1058     // Unsafe algebra implies all the others, no need to write them all out
1059     if (FPO->hasUnsafeAlgebra())
1060       Out << " fast";
1061     else {
1062       if (FPO->hasNoNaNs())
1063         Out << " nnan";
1064       if (FPO->hasNoInfs())
1065         Out << " ninf";
1066       if (FPO->hasNoSignedZeros())
1067         Out << " nsz";
1068       if (FPO->hasAllowReciprocal())
1069         Out << " arcp";
1070     }
1071   }
1072
1073   if (const OverflowingBinaryOperator *OBO =
1074         dyn_cast<OverflowingBinaryOperator>(U)) {
1075     if (OBO->hasNoUnsignedWrap())
1076       Out << " nuw";
1077     if (OBO->hasNoSignedWrap())
1078       Out << " nsw";
1079   } else if (const PossiblyExactOperator *Div =
1080                dyn_cast<PossiblyExactOperator>(U)) {
1081     if (Div->isExact())
1082       Out << " exact";
1083   } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
1084     if (GEP->isInBounds())
1085       Out << " inbounds";
1086   }
1087 }
1088
1089 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
1090                                   TypePrinting &TypePrinter,
1091                                   SlotTracker *Machine,
1092                                   const Module *Context) {
1093   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1094     if (CI->getType()->isIntegerTy(1)) {
1095       Out << (CI->getZExtValue() ? "true" : "false");
1096       return;
1097     }
1098     Out << CI->getValue();
1099     return;
1100   }
1101
1102   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1103     if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
1104         &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
1105       // We would like to output the FP constant value in exponential notation,
1106       // but we cannot do this if doing so will lose precision.  Check here to
1107       // make sure that we only output it in exponential format if we can parse
1108       // the value back and get the same value.
1109       //
1110       bool ignored;
1111       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1112       bool isInf = CFP->getValueAPF().isInfinity();
1113       bool isNaN = CFP->getValueAPF().isNaN();
1114       if (!isInf && !isNaN) {
1115         double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1116                                 CFP->getValueAPF().convertToFloat();
1117         SmallString<128> StrVal;
1118         raw_svector_ostream(StrVal) << Val;
1119
1120         // Check to make sure that the stringized number is not some string like
1121         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
1122         // that the string matches the "[-+]?[0-9]" regex.
1123         //
1124         if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1125             ((StrVal[0] == '-' || StrVal[0] == '+') &&
1126              (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1127           // Reparse stringized version!
1128           if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1129             Out << StrVal;
1130             return;
1131           }
1132         }
1133       }
1134       // Otherwise we could not reparse it to exactly the same value, so we must
1135       // output the string in hexadecimal format!  Note that loading and storing
1136       // floating point types changes the bits of NaNs on some hosts, notably
1137       // x86, so we must not use these types.
1138       static_assert(sizeof(double) == sizeof(uint64_t),
1139                     "assuming that double is 64 bits!");
1140       char Buffer[40];
1141       APFloat apf = CFP->getValueAPF();
1142       // Floats are represented in ASCII IR as double, convert.
1143       if (!isDouble)
1144         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1145                           &ignored);
1146       Out << "0x" <<
1147               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
1148                             Buffer+40);
1149       return;
1150     }
1151
1152     // Either half, or some form of long double.
1153     // These appear as a magic letter identifying the type, then a
1154     // fixed number of hex digits.
1155     Out << "0x";
1156     // Bit position, in the current word, of the next nibble to print.
1157     int shiftcount;
1158
1159     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1160       Out << 'K';
1161       // api needed to prevent premature destruction
1162       APInt api = CFP->getValueAPF().bitcastToAPInt();
1163       const uint64_t* p = api.getRawData();
1164       uint64_t word = p[1];
1165       shiftcount = 12;
1166       int width = api.getBitWidth();
1167       for (int j=0; j<width; j+=4, shiftcount-=4) {
1168         unsigned int nibble = (word>>shiftcount) & 15;
1169         if (nibble < 10)
1170           Out << (unsigned char)(nibble + '0');
1171         else
1172           Out << (unsigned char)(nibble - 10 + 'A');
1173         if (shiftcount == 0 && j+4 < width) {
1174           word = *p;
1175           shiftcount = 64;
1176           if (width-j-4 < 64)
1177             shiftcount = width-j-4;
1178         }
1179       }
1180       return;
1181     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1182       shiftcount = 60;
1183       Out << 'L';
1184     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1185       shiftcount = 60;
1186       Out << 'M';
1187     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1188       shiftcount = 12;
1189       Out << 'H';
1190     } else
1191       llvm_unreachable("Unsupported floating point type");
1192     // api needed to prevent premature destruction
1193     APInt api = CFP->getValueAPF().bitcastToAPInt();
1194     const uint64_t* p = api.getRawData();
1195     uint64_t word = *p;
1196     int width = api.getBitWidth();
1197     for (int j=0; j<width; j+=4, shiftcount-=4) {
1198       unsigned int nibble = (word>>shiftcount) & 15;
1199       if (nibble < 10)
1200         Out << (unsigned char)(nibble + '0');
1201       else
1202         Out << (unsigned char)(nibble - 10 + 'A');
1203       if (shiftcount == 0 && j+4 < width) {
1204         word = *(++p);
1205         shiftcount = 64;
1206         if (width-j-4 < 64)
1207           shiftcount = width-j-4;
1208       }
1209     }
1210     return;
1211   }
1212
1213   if (isa<ConstantAggregateZero>(CV)) {
1214     Out << "zeroinitializer";
1215     return;
1216   }
1217
1218   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1219     Out << "blockaddress(";
1220     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1221                            Context);
1222     Out << ", ";
1223     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1224                            Context);
1225     Out << ")";
1226     return;
1227   }
1228
1229   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1230     Type *ETy = CA->getType()->getElementType();
1231     Out << '[';
1232     TypePrinter.print(ETy, Out);
1233     Out << ' ';
1234     WriteAsOperandInternal(Out, CA->getOperand(0),
1235                            &TypePrinter, Machine,
1236                            Context);
1237     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1238       Out << ", ";
1239       TypePrinter.print(ETy, Out);
1240       Out << ' ';
1241       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1242                              Context);
1243     }
1244     Out << ']';
1245     return;
1246   }
1247
1248   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1249     // As a special case, print the array as a string if it is an array of
1250     // i8 with ConstantInt values.
1251     if (CA->isString()) {
1252       Out << "c\"";
1253       PrintEscapedString(CA->getAsString(), Out);
1254       Out << '"';
1255       return;
1256     }
1257
1258     Type *ETy = CA->getType()->getElementType();
1259     Out << '[';
1260     TypePrinter.print(ETy, Out);
1261     Out << ' ';
1262     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1263                            &TypePrinter, Machine,
1264                            Context);
1265     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1266       Out << ", ";
1267       TypePrinter.print(ETy, Out);
1268       Out << ' ';
1269       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1270                              Machine, Context);
1271     }
1272     Out << ']';
1273     return;
1274   }
1275
1276
1277   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1278     if (CS->getType()->isPacked())
1279       Out << '<';
1280     Out << '{';
1281     unsigned N = CS->getNumOperands();
1282     if (N) {
1283       Out << ' ';
1284       TypePrinter.print(CS->getOperand(0)->getType(), Out);
1285       Out << ' ';
1286
1287       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1288                              Context);
1289
1290       for (unsigned i = 1; i < N; i++) {
1291         Out << ", ";
1292         TypePrinter.print(CS->getOperand(i)->getType(), Out);
1293         Out << ' ';
1294
1295         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1296                                Context);
1297       }
1298       Out << ' ';
1299     }
1300
1301     Out << '}';
1302     if (CS->getType()->isPacked())
1303       Out << '>';
1304     return;
1305   }
1306
1307   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1308     Type *ETy = CV->getType()->getVectorElementType();
1309     Out << '<';
1310     TypePrinter.print(ETy, Out);
1311     Out << ' ';
1312     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1313                            Machine, Context);
1314     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1315       Out << ", ";
1316       TypePrinter.print(ETy, Out);
1317       Out << ' ';
1318       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1319                              Machine, Context);
1320     }
1321     Out << '>';
1322     return;
1323   }
1324
1325   if (isa<ConstantPointerNull>(CV)) {
1326     Out << "null";
1327     return;
1328   }
1329
1330   if (isa<ConstantTokenNone>(CV)) {
1331     Out << "none";
1332     return;
1333   }
1334
1335   if (isa<UndefValue>(CV)) {
1336     Out << "undef";
1337     return;
1338   }
1339
1340   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1341     Out << CE->getOpcodeName();
1342     WriteOptimizationInfo(Out, CE);
1343     if (CE->isCompare())
1344       Out << ' ' << getPredicateText(CE->getPredicate());
1345     Out << " (";
1346
1347     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1348       TypePrinter.print(GEP->getSourceElementType(), Out);
1349       Out << ", ";
1350     }
1351
1352     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1353       TypePrinter.print((*OI)->getType(), Out);
1354       Out << ' ';
1355       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1356       if (OI+1 != CE->op_end())
1357         Out << ", ";
1358     }
1359
1360     if (CE->hasIndices()) {
1361       ArrayRef<unsigned> Indices = CE->getIndices();
1362       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1363         Out << ", " << Indices[i];
1364     }
1365
1366     if (CE->isCast()) {
1367       Out << " to ";
1368       TypePrinter.print(CE->getType(), Out);
1369     }
1370
1371     Out << ')';
1372     return;
1373   }
1374
1375   Out << "<placeholder or erroneous Constant>";
1376 }
1377
1378 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1379                          TypePrinting *TypePrinter, SlotTracker *Machine,
1380                          const Module *Context) {
1381   Out << "!{";
1382   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1383     const Metadata *MD = Node->getOperand(mi);
1384     if (!MD)
1385       Out << "null";
1386     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1387       Value *V = MDV->getValue();
1388       TypePrinter->print(V->getType(), Out);
1389       Out << ' ';
1390       WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1391     } else {
1392       WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1393     }
1394     if (mi + 1 != me)
1395       Out << ", ";
1396   }
1397
1398   Out << "}";
1399 }
1400
1401 namespace {
1402 struct FieldSeparator {
1403   bool Skip;
1404   const char *Sep;
1405   FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1406 };
1407 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1408   if (FS.Skip) {
1409     FS.Skip = false;
1410     return OS;
1411   }
1412   return OS << FS.Sep;
1413 }
1414 struct MDFieldPrinter {
1415   raw_ostream &Out;
1416   FieldSeparator FS;
1417   TypePrinting *TypePrinter;
1418   SlotTracker *Machine;
1419   const Module *Context;
1420
1421   explicit MDFieldPrinter(raw_ostream &Out)
1422       : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1423   MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1424                  SlotTracker *Machine, const Module *Context)
1425       : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1426   }
1427   void printTag(const DINode *N);
1428   void printString(StringRef Name, StringRef Value,
1429                    bool ShouldSkipEmpty = true);
1430   void printMetadata(StringRef Name, const Metadata *MD,
1431                      bool ShouldSkipNull = true);
1432   template <class IntTy>
1433   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1434   void printBool(StringRef Name, bool Value);
1435   void printDIFlags(StringRef Name, unsigned Flags);
1436   template <class IntTy, class Stringifier>
1437   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1438                       bool ShouldSkipZero = true);
1439 };
1440 } // end namespace
1441
1442 void MDFieldPrinter::printTag(const DINode *N) {
1443   Out << FS << "tag: ";
1444   if (const char *Tag = dwarf::TagString(N->getTag()))
1445     Out << Tag;
1446   else
1447     Out << N->getTag();
1448 }
1449
1450 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1451                                  bool ShouldSkipEmpty) {
1452   if (ShouldSkipEmpty && Value.empty())
1453     return;
1454
1455   Out << FS << Name << ": \"";
1456   PrintEscapedString(Value, Out);
1457   Out << "\"";
1458 }
1459
1460 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1461                                    TypePrinting *TypePrinter,
1462                                    SlotTracker *Machine,
1463                                    const Module *Context) {
1464   if (!MD) {
1465     Out << "null";
1466     return;
1467   }
1468   WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1469 }
1470
1471 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1472                                    bool ShouldSkipNull) {
1473   if (ShouldSkipNull && !MD)
1474     return;
1475
1476   Out << FS << Name << ": ";
1477   writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1478 }
1479
1480 template <class IntTy>
1481 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1482   if (ShouldSkipZero && !Int)
1483     return;
1484
1485   Out << FS << Name << ": " << Int;
1486 }
1487
1488 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
1489   Out << FS << Name << ": " << (Value ? "true" : "false");
1490 }
1491
1492 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
1493   if (!Flags)
1494     return;
1495
1496   Out << FS << Name << ": ";
1497
1498   SmallVector<unsigned, 8> SplitFlags;
1499   unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
1500
1501   FieldSeparator FlagsFS(" | ");
1502   for (unsigned F : SplitFlags) {
1503     const char *StringF = DINode::getFlagString(F);
1504     assert(StringF && "Expected valid flag");
1505     Out << FlagsFS << StringF;
1506   }
1507   if (Extra || SplitFlags.empty())
1508     Out << FlagsFS << Extra;
1509 }
1510
1511 template <class IntTy, class Stringifier>
1512 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1513                                     Stringifier toString, bool ShouldSkipZero) {
1514   if (!Value)
1515     return;
1516
1517   Out << FS << Name << ": ";
1518   if (const char *S = toString(Value))
1519     Out << S;
1520   else
1521     Out << Value;
1522 }
1523
1524 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1525                                TypePrinting *TypePrinter, SlotTracker *Machine,
1526                                const Module *Context) {
1527   Out << "!GenericDINode(";
1528   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1529   Printer.printTag(N);
1530   Printer.printString("header", N->getHeader());
1531   if (N->getNumDwarfOperands()) {
1532     Out << Printer.FS << "operands: {";
1533     FieldSeparator IFS;
1534     for (auto &I : N->dwarf_operands()) {
1535       Out << IFS;
1536       writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1537     }
1538     Out << "}";
1539   }
1540   Out << ")";
1541 }
1542
1543 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1544                             TypePrinting *TypePrinter, SlotTracker *Machine,
1545                             const Module *Context) {
1546   Out << "!DILocation(";
1547   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1548   // Always output the line, since 0 is a relevant and important value for it.
1549   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1550   Printer.printInt("column", DL->getColumn());
1551   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1552   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1553   Out << ")";
1554 }
1555
1556 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1557                             TypePrinting *, SlotTracker *, const Module *) {
1558   Out << "!DISubrange(";
1559   MDFieldPrinter Printer(Out);
1560   Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1561   Printer.printInt("lowerBound", N->getLowerBound());
1562   Out << ")";
1563 }
1564
1565 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1566                               TypePrinting *, SlotTracker *, const Module *) {
1567   Out << "!DIEnumerator(";
1568   MDFieldPrinter Printer(Out);
1569   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1570   Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1571   Out << ")";
1572 }
1573
1574 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1575                              TypePrinting *, SlotTracker *, const Module *) {
1576   Out << "!DIBasicType(";
1577   MDFieldPrinter Printer(Out);
1578   if (N->getTag() != dwarf::DW_TAG_base_type)
1579     Printer.printTag(N);
1580   Printer.printString("name", N->getName());
1581   Printer.printInt("size", N->getSizeInBits());
1582   Printer.printInt("align", N->getAlignInBits());
1583   Printer.printDwarfEnum("encoding", N->getEncoding(),
1584                          dwarf::AttributeEncodingString);
1585   Out << ")";
1586 }
1587
1588 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1589                                TypePrinting *TypePrinter, SlotTracker *Machine,
1590                                const Module *Context) {
1591   Out << "!DIDerivedType(";
1592   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1593   Printer.printTag(N);
1594   Printer.printString("name", N->getName());
1595   Printer.printMetadata("scope", N->getRawScope());
1596   Printer.printMetadata("file", N->getRawFile());
1597   Printer.printInt("line", N->getLine());
1598   Printer.printMetadata("baseType", N->getRawBaseType(),
1599                         /* ShouldSkipNull */ false);
1600   Printer.printInt("size", N->getSizeInBits());
1601   Printer.printInt("align", N->getAlignInBits());
1602   Printer.printInt("offset", N->getOffsetInBits());
1603   Printer.printDIFlags("flags", N->getFlags());
1604   Printer.printMetadata("extraData", N->getRawExtraData());
1605   Out << ")";
1606 }
1607
1608 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1609                                  TypePrinting *TypePrinter,
1610                                  SlotTracker *Machine, const Module *Context) {
1611   Out << "!DICompositeType(";
1612   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1613   Printer.printTag(N);
1614   Printer.printString("name", N->getName());
1615   Printer.printMetadata("scope", N->getRawScope());
1616   Printer.printMetadata("file", N->getRawFile());
1617   Printer.printInt("line", N->getLine());
1618   Printer.printMetadata("baseType", N->getRawBaseType());
1619   Printer.printInt("size", N->getSizeInBits());
1620   Printer.printInt("align", N->getAlignInBits());
1621   Printer.printInt("offset", N->getOffsetInBits());
1622   Printer.printDIFlags("flags", N->getFlags());
1623   Printer.printMetadata("elements", N->getRawElements());
1624   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1625                          dwarf::LanguageString);
1626   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1627   Printer.printMetadata("templateParams", N->getRawTemplateParams());
1628   Printer.printString("identifier", N->getIdentifier());
1629   Out << ")";
1630 }
1631
1632 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1633                                   TypePrinting *TypePrinter,
1634                                   SlotTracker *Machine, const Module *Context) {
1635   Out << "!DISubroutineType(";
1636   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1637   Printer.printDIFlags("flags", N->getFlags());
1638   Printer.printMetadata("types", N->getRawTypeArray(),
1639                         /* ShouldSkipNull */ false);
1640   Out << ")";
1641 }
1642
1643 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1644                         SlotTracker *, const Module *) {
1645   Out << "!DIFile(";
1646   MDFieldPrinter Printer(Out);
1647   Printer.printString("filename", N->getFilename(),
1648                       /* ShouldSkipEmpty */ false);
1649   Printer.printString("directory", N->getDirectory(),
1650                       /* ShouldSkipEmpty */ false);
1651   Out << ")";
1652 }
1653
1654 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1655                                TypePrinting *TypePrinter, SlotTracker *Machine,
1656                                const Module *Context) {
1657   Out << "!DICompileUnit(";
1658   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1659   Printer.printDwarfEnum("language", N->getSourceLanguage(),
1660                          dwarf::LanguageString, /* ShouldSkipZero */ false);
1661   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1662   Printer.printString("producer", N->getProducer());
1663   Printer.printBool("isOptimized", N->isOptimized());
1664   Printer.printString("flags", N->getFlags());
1665   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1666                    /* ShouldSkipZero */ false);
1667   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1668   Printer.printInt("emissionKind", N->getEmissionKind(),
1669                    /* ShouldSkipZero */ false);
1670   Printer.printMetadata("enums", N->getRawEnumTypes());
1671   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1672   Printer.printMetadata("subprograms", N->getRawSubprograms());
1673   Printer.printMetadata("globals", N->getRawGlobalVariables());
1674   Printer.printMetadata("imports", N->getRawImportedEntities());
1675   Printer.printInt("dwoId", N->getDWOId());
1676   Out << ")";
1677 }
1678
1679 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1680                               TypePrinting *TypePrinter, SlotTracker *Machine,
1681                               const Module *Context) {
1682   Out << "!DISubprogram(";
1683   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1684   Printer.printString("name", N->getName());
1685   Printer.printString("linkageName", N->getLinkageName());
1686   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1687   Printer.printMetadata("file", N->getRawFile());
1688   Printer.printInt("line", N->getLine());
1689   Printer.printMetadata("type", N->getRawType());
1690   Printer.printBool("isLocal", N->isLocalToUnit());
1691   Printer.printBool("isDefinition", N->isDefinition());
1692   Printer.printInt("scopeLine", N->getScopeLine());
1693   Printer.printMetadata("containingType", N->getRawContainingType());
1694   Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1695                          dwarf::VirtualityString);
1696   Printer.printInt("virtualIndex", N->getVirtualIndex());
1697   Printer.printDIFlags("flags", N->getFlags());
1698   Printer.printBool("isOptimized", N->isOptimized());
1699   Printer.printMetadata("templateParams", N->getRawTemplateParams());
1700   Printer.printMetadata("declaration", N->getRawDeclaration());
1701   Printer.printMetadata("variables", N->getRawVariables());
1702   Out << ")";
1703 }
1704
1705 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1706                                 TypePrinting *TypePrinter, SlotTracker *Machine,
1707                                 const Module *Context) {
1708   Out << "!DILexicalBlock(";
1709   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1710   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1711   Printer.printMetadata("file", N->getRawFile());
1712   Printer.printInt("line", N->getLine());
1713   Printer.printInt("column", N->getColumn());
1714   Out << ")";
1715 }
1716
1717 static void writeDILexicalBlockFile(raw_ostream &Out,
1718                                     const DILexicalBlockFile *N,
1719                                     TypePrinting *TypePrinter,
1720                                     SlotTracker *Machine,
1721                                     const Module *Context) {
1722   Out << "!DILexicalBlockFile(";
1723   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1724   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1725   Printer.printMetadata("file", N->getRawFile());
1726   Printer.printInt("discriminator", N->getDiscriminator(),
1727                    /* ShouldSkipZero */ false);
1728   Out << ")";
1729 }
1730
1731 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1732                              TypePrinting *TypePrinter, SlotTracker *Machine,
1733                              const Module *Context) {
1734   Out << "!DINamespace(";
1735   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1736   Printer.printString("name", N->getName());
1737   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1738   Printer.printMetadata("file", N->getRawFile());
1739   Printer.printInt("line", N->getLine());
1740   Out << ")";
1741 }
1742
1743 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1744                           TypePrinting *TypePrinter, SlotTracker *Machine,
1745                           const Module *Context) {
1746   Out << "!DIModule(";
1747   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1748   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1749   Printer.printString("name", N->getName());
1750   Printer.printString("configMacros", N->getConfigurationMacros());
1751   Printer.printString("includePath", N->getIncludePath());
1752   Printer.printString("isysroot", N->getISysRoot());
1753   Out << ")";
1754 }
1755
1756
1757 static void writeDITemplateTypeParameter(raw_ostream &Out,
1758                                          const DITemplateTypeParameter *N,
1759                                          TypePrinting *TypePrinter,
1760                                          SlotTracker *Machine,
1761                                          const Module *Context) {
1762   Out << "!DITemplateTypeParameter(";
1763   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1764   Printer.printString("name", N->getName());
1765   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1766   Out << ")";
1767 }
1768
1769 static void writeDITemplateValueParameter(raw_ostream &Out,
1770                                           const DITemplateValueParameter *N,
1771                                           TypePrinting *TypePrinter,
1772                                           SlotTracker *Machine,
1773                                           const Module *Context) {
1774   Out << "!DITemplateValueParameter(";
1775   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1776   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1777     Printer.printTag(N);
1778   Printer.printString("name", N->getName());
1779   Printer.printMetadata("type", N->getRawType());
1780   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1781   Out << ")";
1782 }
1783
1784 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1785                                   TypePrinting *TypePrinter,
1786                                   SlotTracker *Machine, const Module *Context) {
1787   Out << "!DIGlobalVariable(";
1788   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1789   Printer.printString("name", N->getName());
1790   Printer.printString("linkageName", N->getLinkageName());
1791   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1792   Printer.printMetadata("file", N->getRawFile());
1793   Printer.printInt("line", N->getLine());
1794   Printer.printMetadata("type", N->getRawType());
1795   Printer.printBool("isLocal", N->isLocalToUnit());
1796   Printer.printBool("isDefinition", N->isDefinition());
1797   Printer.printMetadata("variable", N->getRawVariable());
1798   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1799   Out << ")";
1800 }
1801
1802 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1803                                  TypePrinting *TypePrinter,
1804                                  SlotTracker *Machine, const Module *Context) {
1805   Out << "!DILocalVariable(";
1806   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1807   Printer.printString("name", N->getName());
1808   Printer.printInt("arg", N->getArg());
1809   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1810   Printer.printMetadata("file", N->getRawFile());
1811   Printer.printInt("line", N->getLine());
1812   Printer.printMetadata("type", N->getRawType());
1813   Printer.printDIFlags("flags", N->getFlags());
1814   Out << ")";
1815 }
1816
1817 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1818                               TypePrinting *TypePrinter, SlotTracker *Machine,
1819                               const Module *Context) {
1820   Out << "!DIExpression(";
1821   FieldSeparator FS;
1822   if (N->isValid()) {
1823     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1824       const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1825       assert(OpStr && "Expected valid opcode");
1826
1827       Out << FS << OpStr;
1828       for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1829         Out << FS << I->getArg(A);
1830     }
1831   } else {
1832     for (const auto &I : N->getElements())
1833       Out << FS << I;
1834   }
1835   Out << ")";
1836 }
1837
1838 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1839                                 TypePrinting *TypePrinter, SlotTracker *Machine,
1840                                 const Module *Context) {
1841   Out << "!DIObjCProperty(";
1842   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1843   Printer.printString("name", N->getName());
1844   Printer.printMetadata("file", N->getRawFile());
1845   Printer.printInt("line", N->getLine());
1846   Printer.printString("setter", N->getSetterName());
1847   Printer.printString("getter", N->getGetterName());
1848   Printer.printInt("attributes", N->getAttributes());
1849   Printer.printMetadata("type", N->getRawType());
1850   Out << ")";
1851 }
1852
1853 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1854                                   TypePrinting *TypePrinter,
1855                                   SlotTracker *Machine, const Module *Context) {
1856   Out << "!DIImportedEntity(";
1857   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1858   Printer.printTag(N);
1859   Printer.printString("name", N->getName());
1860   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1861   Printer.printMetadata("entity", N->getRawEntity());
1862   Printer.printInt("line", N->getLine());
1863   Out << ")";
1864 }
1865
1866
1867 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1868                                     TypePrinting *TypePrinter,
1869                                     SlotTracker *Machine,
1870                                     const Module *Context) {
1871   if (Node->isDistinct())
1872     Out << "distinct ";
1873   else if (Node->isTemporary())
1874     Out << "<temporary!> "; // Handle broken code.
1875
1876   switch (Node->getMetadataID()) {
1877   default:
1878     llvm_unreachable("Expected uniquable MDNode");
1879 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1880   case Metadata::CLASS##Kind:                                                  \
1881     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
1882     break;
1883 #include "llvm/IR/Metadata.def"
1884   }
1885 }
1886
1887 // Full implementation of printing a Value as an operand with support for
1888 // TypePrinting, etc.
1889 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1890                                    TypePrinting *TypePrinter,
1891                                    SlotTracker *Machine,
1892                                    const Module *Context) {
1893   if (V->hasName()) {
1894     PrintLLVMName(Out, V);
1895     return;
1896   }
1897
1898   const Constant *CV = dyn_cast<Constant>(V);
1899   if (CV && !isa<GlobalValue>(CV)) {
1900     assert(TypePrinter && "Constants require TypePrinting!");
1901     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1902     return;
1903   }
1904
1905   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1906     Out << "asm ";
1907     if (IA->hasSideEffects())
1908       Out << "sideeffect ";
1909     if (IA->isAlignStack())
1910       Out << "alignstack ";
1911     // We don't emit the AD_ATT dialect as it's the assumed default.
1912     if (IA->getDialect() == InlineAsm::AD_Intel)
1913       Out << "inteldialect ";
1914     Out << '"';
1915     PrintEscapedString(IA->getAsmString(), Out);
1916     Out << "\", \"";
1917     PrintEscapedString(IA->getConstraintString(), Out);
1918     Out << '"';
1919     return;
1920   }
1921
1922   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1923     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1924                            Context, /* FromValue */ true);
1925     return;
1926   }
1927
1928   char Prefix = '%';
1929   int Slot;
1930   // If we have a SlotTracker, use it.
1931   if (Machine) {
1932     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1933       Slot = Machine->getGlobalSlot(GV);
1934       Prefix = '@';
1935     } else {
1936       Slot = Machine->getLocalSlot(V);
1937
1938       // If the local value didn't succeed, then we may be referring to a value
1939       // from a different function.  Translate it, as this can happen when using
1940       // address of blocks.
1941       if (Slot == -1)
1942         if ((Machine = createSlotTracker(V))) {
1943           Slot = Machine->getLocalSlot(V);
1944           delete Machine;
1945         }
1946     }
1947   } else if ((Machine = createSlotTracker(V))) {
1948     // Otherwise, create one to get the # and then destroy it.
1949     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1950       Slot = Machine->getGlobalSlot(GV);
1951       Prefix = '@';
1952     } else {
1953       Slot = Machine->getLocalSlot(V);
1954     }
1955     delete Machine;
1956     Machine = nullptr;
1957   } else {
1958     Slot = -1;
1959   }
1960
1961   if (Slot != -1)
1962     Out << Prefix << Slot;
1963   else
1964     Out << "<badref>";
1965 }
1966
1967 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1968                                    TypePrinting *TypePrinter,
1969                                    SlotTracker *Machine, const Module *Context,
1970                                    bool FromValue) {
1971   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1972     std::unique_ptr<SlotTracker> MachineStorage;
1973     if (!Machine) {
1974       MachineStorage = make_unique<SlotTracker>(Context);
1975       Machine = MachineStorage.get();
1976     }
1977     int Slot = Machine->getMetadataSlot(N);
1978     if (Slot == -1)
1979       // Give the pointer value instead of "badref", since this comes up all
1980       // the time when debugging.
1981       Out << "<" << N << ">";
1982     else
1983       Out << '!' << Slot;
1984     return;
1985   }
1986
1987   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
1988     Out << "!\"";
1989     PrintEscapedString(MDS->getString(), Out);
1990     Out << '"';
1991     return;
1992   }
1993
1994   auto *V = cast<ValueAsMetadata>(MD);
1995   assert(TypePrinter && "TypePrinter required for metadata values");
1996   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
1997          "Unexpected function-local metadata outside of value argument");
1998
1999   TypePrinter->print(V->getValue()->getType(), Out);
2000   Out << ' ';
2001   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2002 }
2003
2004 namespace {
2005 class AssemblyWriter {
2006   formatted_raw_ostream &Out;
2007   const Module *TheModule;
2008   std::unique_ptr<SlotTracker> SlotTrackerStorage;
2009   SlotTracker &Machine;
2010   TypePrinting TypePrinter;
2011   AssemblyAnnotationWriter *AnnotationWriter;
2012   SetVector<const Comdat *> Comdats;
2013   bool IsForDebug;
2014   bool ShouldPreserveUseListOrder;
2015   UseListOrderStack UseListOrders;
2016   SmallVector<StringRef, 8> MDNames;
2017
2018 public:
2019   /// Construct an AssemblyWriter with an external SlotTracker
2020   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2021                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2022                  bool ShouldPreserveUseListOrder = false);
2023
2024   void printMDNodeBody(const MDNode *MD);
2025   void printNamedMDNode(const NamedMDNode *NMD);
2026
2027   void printModule(const Module *M);
2028
2029   void writeOperand(const Value *Op, bool PrintType);
2030   void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
2031   void writeOperandBundles(ImmutableCallSite CS);
2032   void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2033   void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2034                           AtomicOrdering FailureOrdering,
2035                           SynchronizationScope SynchScope);
2036
2037   void writeAllMDNodes();
2038   void writeMDNode(unsigned Slot, const MDNode *Node);
2039   void writeAllAttributeGroups();
2040
2041   void printTypeIdentities();
2042   void printGlobal(const GlobalVariable *GV);
2043   void printAlias(const GlobalAlias *GV);
2044   void printComdat(const Comdat *C);
2045   void printFunction(const Function *F);
2046   void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
2047   void printBasicBlock(const BasicBlock *BB);
2048   void printInstructionLine(const Instruction &I);
2049   void printInstruction(const Instruction &I);
2050
2051   void printUseListOrder(const UseListOrder &Order);
2052   void printUseLists(const Function *F);
2053
2054 private:
2055   /// \brief Print out metadata attachments.
2056   void printMetadataAttachments(
2057       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2058       StringRef Separator);
2059
2060   // printInfoComment - Print a little comment after the instruction indicating
2061   // which slot it occupies.
2062   void printInfoComment(const Value &V);
2063
2064   // printGCRelocateComment - print comment after call to the gc.relocate
2065   // intrinsic indicating base and derived pointer names.
2066   void printGCRelocateComment(const Value &V);
2067 };
2068 } // namespace
2069
2070 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2071                                const Module *M, AssemblyAnnotationWriter *AAW,
2072                                bool IsForDebug, bool ShouldPreserveUseListOrder)
2073     : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2074       IsForDebug(IsForDebug),
2075       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2076   if (!TheModule)
2077     return;
2078   TypePrinter.incorporateTypes(*TheModule);
2079   for (const Function &F : *TheModule)
2080     if (const Comdat *C = F.getComdat())
2081       Comdats.insert(C);
2082   for (const GlobalVariable &GV : TheModule->globals())
2083     if (const Comdat *C = GV.getComdat())
2084       Comdats.insert(C);
2085 }
2086
2087 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2088   if (!Operand) {
2089     Out << "<null operand!>";
2090     return;
2091   }
2092   if (PrintType) {
2093     TypePrinter.print(Operand->getType(), Out);
2094     Out << ' ';
2095   }
2096   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2097 }
2098
2099 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2100                                  SynchronizationScope SynchScope) {
2101   if (Ordering == NotAtomic)
2102     return;
2103
2104   switch (SynchScope) {
2105   case SingleThread: Out << " singlethread"; break;
2106   case CrossThread: break;
2107   }
2108
2109   switch (Ordering) {
2110   default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2111   case Unordered: Out << " unordered"; break;
2112   case Monotonic: Out << " monotonic"; break;
2113   case Acquire: Out << " acquire"; break;
2114   case Release: Out << " release"; break;
2115   case AcquireRelease: Out << " acq_rel"; break;
2116   case SequentiallyConsistent: Out << " seq_cst"; break;
2117   }
2118 }
2119
2120 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2121                                         AtomicOrdering FailureOrdering,
2122                                         SynchronizationScope SynchScope) {
2123   assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2124
2125   switch (SynchScope) {
2126   case SingleThread: Out << " singlethread"; break;
2127   case CrossThread: break;
2128   }
2129
2130   switch (SuccessOrdering) {
2131   default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2132   case Unordered: Out << " unordered"; break;
2133   case Monotonic: Out << " monotonic"; break;
2134   case Acquire: Out << " acquire"; break;
2135   case Release: Out << " release"; break;
2136   case AcquireRelease: Out << " acq_rel"; break;
2137   case SequentiallyConsistent: Out << " seq_cst"; break;
2138   }
2139
2140   switch (FailureOrdering) {
2141   default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2142   case Unordered: Out << " unordered"; break;
2143   case Monotonic: Out << " monotonic"; break;
2144   case Acquire: Out << " acquire"; break;
2145   case Release: Out << " release"; break;
2146   case AcquireRelease: Out << " acq_rel"; break;
2147   case SequentiallyConsistent: Out << " seq_cst"; break;
2148   }
2149 }
2150
2151 void AssemblyWriter::writeParamOperand(const Value *Operand,
2152                                        AttributeSet Attrs, unsigned Idx) {
2153   if (!Operand) {
2154     Out << "<null operand!>";
2155     return;
2156   }
2157
2158   // Print the type
2159   TypePrinter.print(Operand->getType(), Out);
2160   // Print parameter attributes list
2161   if (Attrs.hasAttributes(Idx))
2162     Out << ' ' << Attrs.getAsString(Idx);
2163   Out << ' ';
2164   // Print the operand
2165   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2166 }
2167
2168 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2169   if (!CS.hasOperandBundles())
2170     return;
2171
2172   Out << " [ ";
2173
2174   bool FirstBundle = true;
2175   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2176     OperandBundleUse BU = CS.getOperandBundleAt(i);
2177
2178     if (!FirstBundle)
2179       Out << ", ";
2180     FirstBundle = false;
2181
2182     Out << '"';
2183     PrintEscapedString(BU.getTagName(), Out);
2184     Out << '"';
2185
2186     Out << '(';
2187
2188     bool FirstInput = true;
2189     for (const auto &Input : BU.Inputs) {
2190       if (!FirstInput)
2191         Out << ", ";
2192       FirstInput = false;
2193
2194       TypePrinter.print(Input->getType(), Out);
2195       Out << " ";
2196       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2197     }
2198
2199     Out << ')';
2200   }
2201
2202   Out << " ]";
2203 }
2204
2205 void AssemblyWriter::printModule(const Module *M) {
2206   Machine.initialize();
2207
2208   if (ShouldPreserveUseListOrder)
2209     UseListOrders = predictUseListOrder(M);
2210
2211   if (!M->getModuleIdentifier().empty() &&
2212       // Don't print the ID if it will start a new line (which would
2213       // require a comment char before it).
2214       M->getModuleIdentifier().find('\n') == std::string::npos)
2215     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2216
2217   const std::string &DL = M->getDataLayoutStr();
2218   if (!DL.empty())
2219     Out << "target datalayout = \"" << DL << "\"\n";
2220   if (!M->getTargetTriple().empty())
2221     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2222
2223   if (!M->getModuleInlineAsm().empty()) {
2224     Out << '\n';
2225
2226     // Split the string into lines, to make it easier to read the .ll file.
2227     StringRef Asm = M->getModuleInlineAsm();
2228     do {
2229       StringRef Front;
2230       std::tie(Front, Asm) = Asm.split('\n');
2231
2232       // We found a newline, print the portion of the asm string from the
2233       // last newline up to this newline.
2234       Out << "module asm \"";
2235       PrintEscapedString(Front, Out);
2236       Out << "\"\n";
2237     } while (!Asm.empty());
2238   }
2239
2240   printTypeIdentities();
2241
2242   // Output all comdats.
2243   if (!Comdats.empty())
2244     Out << '\n';
2245   for (const Comdat *C : Comdats) {
2246     printComdat(C);
2247     if (C != Comdats.back())
2248       Out << '\n';
2249   }
2250
2251   // Output all globals.
2252   if (!M->global_empty()) Out << '\n';
2253   for (const GlobalVariable &GV : M->globals()) {
2254     printGlobal(&GV); Out << '\n';
2255   }
2256
2257   // Output all aliases.
2258   if (!M->alias_empty()) Out << "\n";
2259   for (const GlobalAlias &GA : M->aliases())
2260     printAlias(&GA);
2261
2262   // Output global use-lists.
2263   printUseLists(nullptr);
2264
2265   // Output all of the functions.
2266   for (const Function &F : *M)
2267     printFunction(&F);
2268   assert(UseListOrders.empty() && "All use-lists should have been consumed");
2269
2270   // Output all attribute groups.
2271   if (!Machine.as_empty()) {
2272     Out << '\n';
2273     writeAllAttributeGroups();
2274   }
2275
2276   // Output named metadata.
2277   if (!M->named_metadata_empty()) Out << '\n';
2278
2279   for (const NamedMDNode &Node : M->named_metadata())
2280     printNamedMDNode(&Node);
2281
2282   // Output metadata.
2283   if (!Machine.mdn_empty()) {
2284     Out << '\n';
2285     writeAllMDNodes();
2286   }
2287 }
2288
2289 static void printMetadataIdentifier(StringRef Name,
2290                                     formatted_raw_ostream &Out) {
2291   if (Name.empty()) {
2292     Out << "<empty name> ";
2293   } else {
2294     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2295         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2296       Out << Name[0];
2297     else
2298       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2299     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2300       unsigned char C = Name[i];
2301       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2302           C == '.' || C == '_')
2303         Out << C;
2304       else
2305         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2306     }
2307   }
2308 }
2309
2310 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2311   Out << '!';
2312   printMetadataIdentifier(NMD->getName(), Out);
2313   Out << " = !{";
2314   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2315     if (i)
2316       Out << ", ";
2317     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2318     if (Slot == -1)
2319       Out << "<badref>";
2320     else
2321       Out << '!' << Slot;
2322   }
2323   Out << "}\n";
2324 }
2325
2326 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2327                          formatted_raw_ostream &Out) {
2328   switch (LT) {
2329   case GlobalValue::ExternalLinkage: break;
2330   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
2331   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
2332   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
2333   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
2334   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
2335   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
2336   case GlobalValue::CommonLinkage:        Out << "common ";         break;
2337   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
2338   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
2339   case GlobalValue::AvailableExternallyLinkage:
2340     Out << "available_externally ";
2341     break;
2342   }
2343 }
2344
2345 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2346                             formatted_raw_ostream &Out) {
2347   switch (Vis) {
2348   case GlobalValue::DefaultVisibility: break;
2349   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
2350   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2351   }
2352 }
2353
2354 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2355                                  formatted_raw_ostream &Out) {
2356   switch (SCT) {
2357   case GlobalValue::DefaultStorageClass: break;
2358   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2359   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2360   }
2361 }
2362
2363 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2364                                   formatted_raw_ostream &Out) {
2365   switch (TLM) {
2366     case GlobalVariable::NotThreadLocal:
2367       break;
2368     case GlobalVariable::GeneralDynamicTLSModel:
2369       Out << "thread_local ";
2370       break;
2371     case GlobalVariable::LocalDynamicTLSModel:
2372       Out << "thread_local(localdynamic) ";
2373       break;
2374     case GlobalVariable::InitialExecTLSModel:
2375       Out << "thread_local(initialexec) ";
2376       break;
2377     case GlobalVariable::LocalExecTLSModel:
2378       Out << "thread_local(localexec) ";
2379       break;
2380   }
2381 }
2382
2383 static void maybePrintComdat(formatted_raw_ostream &Out,
2384                              const GlobalObject &GO) {
2385   const Comdat *C = GO.getComdat();
2386   if (!C)
2387     return;
2388
2389   if (isa<GlobalVariable>(GO))
2390     Out << ',';
2391   Out << " comdat";
2392
2393   if (GO.getName() == C->getName())
2394     return;
2395
2396   Out << '(';
2397   PrintLLVMName(Out, C->getName(), ComdatPrefix);
2398   Out << ')';
2399 }
2400
2401 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2402   if (GV->isMaterializable())
2403     Out << "; Materializable\n";
2404
2405   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2406   Out << " = ";
2407
2408   if (!GV->hasInitializer() && GV->hasExternalLinkage())
2409     Out << "external ";
2410
2411   PrintLinkage(GV->getLinkage(), Out);
2412   PrintVisibility(GV->getVisibility(), Out);
2413   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2414   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2415   if (GV->hasUnnamedAddr())
2416     Out << "unnamed_addr ";
2417
2418   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2419     Out << "addrspace(" << AddressSpace << ") ";
2420   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2421   Out << (GV->isConstant() ? "constant " : "global ");
2422   TypePrinter.print(GV->getType()->getElementType(), Out);
2423
2424   if (GV->hasInitializer()) {
2425     Out << ' ';
2426     writeOperand(GV->getInitializer(), false);
2427   }
2428
2429   if (GV->hasSection()) {
2430     Out << ", section \"";
2431     PrintEscapedString(GV->getSection(), Out);
2432     Out << '"';
2433   }
2434   maybePrintComdat(Out, *GV);
2435   if (GV->getAlignment())
2436     Out << ", align " << GV->getAlignment();
2437
2438   printInfoComment(*GV);
2439 }
2440
2441 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2442   if (GA->isMaterializable())
2443     Out << "; Materializable\n";
2444
2445   WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
2446   Out << " = ";
2447
2448   PrintLinkage(GA->getLinkage(), Out);
2449   PrintVisibility(GA->getVisibility(), Out);
2450   PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2451   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2452   if (GA->hasUnnamedAddr())
2453     Out << "unnamed_addr ";
2454
2455   Out << "alias ";
2456
2457   TypePrinter.print(GA->getValueType(), Out);
2458
2459   Out << ", ";
2460
2461   const Constant *Aliasee = GA->getAliasee();
2462
2463   if (!Aliasee) {
2464     TypePrinter.print(GA->getType(), Out);
2465     Out << " <<NULL ALIASEE>>";
2466   } else {
2467     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2468   }
2469
2470   printInfoComment(*GA);
2471   Out << '\n';
2472 }
2473
2474 void AssemblyWriter::printComdat(const Comdat *C) {
2475   C->print(Out);
2476 }
2477
2478 void AssemblyWriter::printTypeIdentities() {
2479   if (TypePrinter.NumberedTypes.empty() &&
2480       TypePrinter.NamedTypes.empty())
2481     return;
2482
2483   Out << '\n';
2484
2485   // We know all the numbers that each type is used and we know that it is a
2486   // dense assignment.  Convert the map to an index table.
2487   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2488   for (DenseMap<StructType*, unsigned>::iterator I =
2489        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2490        I != E; ++I) {
2491     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2492     NumberedTypes[I->second] = I->first;
2493   }
2494
2495   // Emit all numbered types.
2496   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2497     Out << '%' << i << " = type ";
2498
2499     // Make sure we print out at least one level of the type structure, so
2500     // that we do not get %2 = type %2
2501     TypePrinter.printStructBody(NumberedTypes[i], Out);
2502     Out << '\n';
2503   }
2504
2505   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2506     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2507     Out << " = type ";
2508
2509     // Make sure we print out at least one level of the type structure, so
2510     // that we do not get %FILE = type %FILE
2511     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2512     Out << '\n';
2513   }
2514 }
2515
2516 /// printFunction - Print all aspects of a function.
2517 ///
2518 void AssemblyWriter::printFunction(const Function *F) {
2519   // Print out the return type and name.
2520   Out << '\n';
2521
2522   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2523
2524   if (F->isMaterializable())
2525     Out << "; Materializable\n";
2526
2527   const AttributeSet &Attrs = F->getAttributes();
2528   if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2529     AttributeSet AS = Attrs.getFnAttributes();
2530     std::string AttrStr;
2531
2532     unsigned Idx = 0;
2533     for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2534       if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2535         break;
2536
2537     for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2538          I != E; ++I) {
2539       Attribute Attr = *I;
2540       if (!Attr.isStringAttribute()) {
2541         if (!AttrStr.empty()) AttrStr += ' ';
2542         AttrStr += Attr.getAsString();
2543       }
2544     }
2545
2546     if (!AttrStr.empty())
2547       Out << "; Function Attrs: " << AttrStr << '\n';
2548   }
2549
2550   if (F->isDeclaration())
2551     Out << "declare ";
2552   else
2553     Out << "define ";
2554
2555   PrintLinkage(F->getLinkage(), Out);
2556   PrintVisibility(F->getVisibility(), Out);
2557   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2558
2559   // Print the calling convention.
2560   if (F->getCallingConv() != CallingConv::C) {
2561     PrintCallingConv(F->getCallingConv(), Out);
2562     Out << " ";
2563   }
2564
2565   FunctionType *FT = F->getFunctionType();
2566   if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2567     Out <<  Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2568   TypePrinter.print(F->getReturnType(), Out);
2569   Out << ' ';
2570   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2571   Out << '(';
2572   Machine.incorporateFunction(F);
2573
2574   // Loop over the arguments, printing them...
2575   if (F->isDeclaration() && !IsForDebug) {
2576     // We're only interested in the type here - don't print argument names.
2577     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2578       // Insert commas as we go... the first arg doesn't get a comma
2579       if (I)
2580         Out << ", ";
2581       // Output type...
2582       TypePrinter.print(FT->getParamType(I), Out);
2583
2584       if (Attrs.hasAttributes(I + 1))
2585         Out << ' ' << Attrs.getAsString(I + 1);
2586     }
2587   } else {
2588     // The arguments are meaningful here, print them in detail.
2589     unsigned Idx = 1;
2590     for (const Argument &Arg : F->args()) {
2591       // Insert commas as we go... the first arg doesn't get a comma
2592       if (Idx != 1)
2593         Out << ", ";
2594       printArgument(&Arg, Attrs, Idx++);
2595     }
2596   }
2597
2598   // Finish printing arguments...
2599   if (FT->isVarArg()) {
2600     if (FT->getNumParams()) Out << ", ";
2601     Out << "...";  // Output varargs portion of signature!
2602   }
2603   Out << ')';
2604   if (F->hasUnnamedAddr())
2605     Out << " unnamed_addr";
2606   if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2607     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2608   if (F->hasSection()) {
2609     Out << " section \"";
2610     PrintEscapedString(F->getSection(), Out);
2611     Out << '"';
2612   }
2613   maybePrintComdat(Out, *F);
2614   if (F->getAlignment())
2615     Out << " align " << F->getAlignment();
2616   if (F->hasGC())
2617     Out << " gc \"" << F->getGC() << '"';
2618   if (F->hasPrefixData()) {
2619     Out << " prefix ";
2620     writeOperand(F->getPrefixData(), true);
2621   }
2622   if (F->hasPrologueData()) {
2623     Out << " prologue ";
2624     writeOperand(F->getPrologueData(), true);
2625   }
2626   if (F->hasPersonalityFn()) {
2627     Out << " personality ";
2628     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2629   }
2630
2631   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2632   F->getAllMetadata(MDs);
2633   printMetadataAttachments(MDs, " ");
2634
2635   if (F->isDeclaration()) {
2636     Out << '\n';
2637   } else {
2638     Out << " {";
2639     // Output all of the function's basic blocks.
2640     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2641       printBasicBlock(&*I);
2642
2643     // Output the function's use-lists.
2644     printUseLists(F);
2645
2646     Out << "}\n";
2647   }
2648
2649   Machine.purgeFunction();
2650 }
2651
2652 /// printArgument - This member is called for every argument that is passed into
2653 /// the function.  Simply print it out
2654 ///
2655 void AssemblyWriter::printArgument(const Argument *Arg,
2656                                    AttributeSet Attrs, unsigned Idx) {
2657   // Output type...
2658   TypePrinter.print(Arg->getType(), Out);
2659
2660   // Output parameter attributes list
2661   if (Attrs.hasAttributes(Idx))
2662     Out << ' ' << Attrs.getAsString(Idx);
2663
2664   // Output name, if available...
2665   if (Arg->hasName()) {
2666     Out << ' ';
2667     PrintLLVMName(Out, Arg);
2668   }
2669 }
2670
2671 /// printBasicBlock - This member is called for each basic block in a method.
2672 ///
2673 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2674   if (BB->hasName()) {              // Print out the label if it exists...
2675     Out << "\n";
2676     PrintLLVMName(Out, BB->getName(), LabelPrefix);
2677     Out << ':';
2678   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
2679     Out << "\n; <label>:";
2680     int Slot = Machine.getLocalSlot(BB);
2681     if (Slot != -1)
2682       Out << Slot;
2683     else
2684       Out << "<badref>";
2685   }
2686
2687   if (!BB->getParent()) {
2688     Out.PadToColumn(50);
2689     Out << "; Error: Block without parent!";
2690   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
2691     // Output predecessors for the block.
2692     Out.PadToColumn(50);
2693     Out << ";";
2694     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2695
2696     if (PI == PE) {
2697       Out << " No predecessors!";
2698     } else {
2699       Out << " preds = ";
2700       writeOperand(*PI, false);
2701       for (++PI; PI != PE; ++PI) {
2702         Out << ", ";
2703         writeOperand(*PI, false);
2704       }
2705     }
2706   }
2707
2708   Out << "\n";
2709
2710   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2711
2712   // Output all of the instructions in the basic block...
2713   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2714     printInstructionLine(*I);
2715   }
2716
2717   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2718 }
2719
2720 /// printInstructionLine - Print an instruction and a newline character.
2721 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2722   printInstruction(I);
2723   Out << '\n';
2724 }
2725
2726 /// printGCRelocateComment - print comment after call to the gc.relocate
2727 /// intrinsic indicating base and derived pointer names.
2728 void AssemblyWriter::printGCRelocateComment(const Value &V) {
2729   assert(isGCRelocate(&V));
2730   GCRelocateOperands GCOps(cast<Instruction>(&V));
2731
2732   Out << " ; (";
2733   writeOperand(GCOps.getBasePtr(), false);
2734   Out << ", ";
2735   writeOperand(GCOps.getDerivedPtr(), false);
2736   Out << ")";
2737 }
2738
2739 /// printInfoComment - Print a little comment after the instruction indicating
2740 /// which slot it occupies.
2741 ///
2742 void AssemblyWriter::printInfoComment(const Value &V) {
2743   if (isGCRelocate(&V))
2744     printGCRelocateComment(V);
2745
2746   if (AnnotationWriter)
2747     AnnotationWriter->printInfoComment(V, Out);
2748 }
2749
2750 // This member is called for each Instruction in a function..
2751 void AssemblyWriter::printInstruction(const Instruction &I) {
2752   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2753
2754   // Print out indentation for an instruction.
2755   Out << "  ";
2756
2757   // Print out name if it exists...
2758   if (I.hasName()) {
2759     PrintLLVMName(Out, &I);
2760     Out << " = ";
2761   } else if (!I.getType()->isVoidTy()) {
2762     // Print out the def slot taken.
2763     int SlotNum = Machine.getLocalSlot(&I);
2764     if (SlotNum == -1)
2765       Out << "<badref> = ";
2766     else
2767       Out << '%' << SlotNum << " = ";
2768   }
2769
2770   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2771     if (CI->isMustTailCall())
2772       Out << "musttail ";
2773     else if (CI->isTailCall())
2774       Out << "tail ";
2775     else if (CI->isNoTailCall())
2776       Out << "notail ";
2777   }
2778
2779   // Print out the opcode...
2780   Out << I.getOpcodeName();
2781
2782   // If this is an atomic load or store, print out the atomic marker.
2783   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
2784       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2785     Out << " atomic";
2786
2787   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2788     Out << " weak";
2789
2790   // If this is a volatile operation, print out the volatile marker.
2791   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
2792       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2793       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2794       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2795     Out << " volatile";
2796
2797   // Print out optimization information.
2798   WriteOptimizationInfo(Out, &I);
2799
2800   // Print out the compare instruction predicates
2801   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2802     Out << ' ' << getPredicateText(CI->getPredicate());
2803
2804   // Print out the atomicrmw operation
2805   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2806     writeAtomicRMWOperation(Out, RMWI->getOperation());
2807
2808   // Print out the type of the operands...
2809   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2810
2811   // Special case conditional branches to swizzle the condition out to the front
2812   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2813     const BranchInst &BI(cast<BranchInst>(I));
2814     Out << ' ';
2815     writeOperand(BI.getCondition(), true);
2816     Out << ", ";
2817     writeOperand(BI.getSuccessor(0), true);
2818     Out << ", ";
2819     writeOperand(BI.getSuccessor(1), true);
2820
2821   } else if (isa<SwitchInst>(I)) {
2822     const SwitchInst& SI(cast<SwitchInst>(I));
2823     // Special case switch instruction to get formatting nice and correct.
2824     Out << ' ';
2825     writeOperand(SI.getCondition(), true);
2826     Out << ", ";
2827     writeOperand(SI.getDefaultDest(), true);
2828     Out << " [";
2829     for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2830          i != e; ++i) {
2831       Out << "\n    ";
2832       writeOperand(i.getCaseValue(), true);
2833       Out << ", ";
2834       writeOperand(i.getCaseSuccessor(), true);
2835     }
2836     Out << "\n  ]";
2837   } else if (isa<IndirectBrInst>(I)) {
2838     // Special case indirectbr instruction to get formatting nice and correct.
2839     Out << ' ';
2840     writeOperand(Operand, true);
2841     Out << ", [";
2842
2843     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2844       if (i != 1)
2845         Out << ", ";
2846       writeOperand(I.getOperand(i), true);
2847     }
2848     Out << ']';
2849   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2850     Out << ' ';
2851     TypePrinter.print(I.getType(), Out);
2852     Out << ' ';
2853
2854     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2855       if (op) Out << ", ";
2856       Out << "[ ";
2857       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2858       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2859     }
2860   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2861     Out << ' ';
2862     writeOperand(I.getOperand(0), true);
2863     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2864       Out << ", " << *i;
2865   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2866     Out << ' ';
2867     writeOperand(I.getOperand(0), true); Out << ", ";
2868     writeOperand(I.getOperand(1), true);
2869     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2870       Out << ", " << *i;
2871   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2872     Out << ' ';
2873     TypePrinter.print(I.getType(), Out);
2874     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2875       Out << '\n';
2876
2877     if (LPI->isCleanup())
2878       Out << "          cleanup";
2879
2880     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2881       if (i != 0 || LPI->isCleanup()) Out << "\n";
2882       if (LPI->isCatch(i))
2883         Out << "          catch ";
2884       else
2885         Out << "          filter ";
2886
2887       writeOperand(LPI->getClause(i), true);
2888     }
2889   } else if (const auto *CPI = dyn_cast<CatchPadInst>(&I)) {
2890     Out << " [";
2891     for (unsigned Op = 0, NumOps = CPI->getNumArgOperands(); Op < NumOps;
2892          ++Op) {
2893       if (Op > 0)
2894         Out << ", ";
2895       writeOperand(CPI->getArgOperand(Op), /*PrintType=*/true);
2896     }
2897     Out << "]\n          to ";
2898     writeOperand(CPI->getNormalDest(), /*PrintType=*/true);
2899     Out << " unwind ";
2900     writeOperand(CPI->getUnwindDest(), /*PrintType=*/true);
2901   } else if (const auto *TPI = dyn_cast<TerminatePadInst>(&I)) {
2902     Out << " [";
2903     for (unsigned Op = 0, NumOps = TPI->getNumArgOperands(); Op < NumOps;
2904          ++Op) {
2905       if (Op > 0)
2906         Out << ", ";
2907       writeOperand(TPI->getArgOperand(Op), /*PrintType=*/true);
2908     }
2909     Out << "] unwind ";
2910     if (TPI->hasUnwindDest())
2911       writeOperand(TPI->getUnwindDest(), /*PrintType=*/true);
2912     else
2913       Out << "to caller";
2914   } else if (const auto *CPI = dyn_cast<CleanupPadInst>(&I)) {
2915     Out << " [";
2916     for (unsigned Op = 0, NumOps = CPI->getNumOperands(); Op < NumOps; ++Op) {
2917       if (Op > 0)
2918         Out << ", ";
2919       writeOperand(CPI->getOperand(Op), /*PrintType=*/true);
2920     }
2921     Out << "]";
2922   } else if (isa<ReturnInst>(I) && !Operand) {
2923     Out << " void";
2924   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
2925     Out << ' ';
2926     writeOperand(CRI->getCatchPad(), /*PrintType=*/false);
2927
2928     Out << " to ";
2929     writeOperand(CRI->getSuccessor(), /*PrintType=*/true);
2930   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
2931     Out << ' ';
2932     writeOperand(CRI->getCleanupPad(), /*PrintType=*/false);
2933
2934     Out << " unwind ";
2935     if (CRI->hasUnwindDest())
2936       writeOperand(CRI->getUnwindDest(), /*PrintType=*/true);
2937     else
2938       Out << "to caller";
2939   } else if (const auto *CEPI = dyn_cast<CatchEndPadInst>(&I)) {
2940     Out << " unwind ";
2941     if (CEPI->hasUnwindDest())
2942       writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2943     else
2944       Out << "to caller";
2945   } else if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(&I)) {
2946     Out << ' ';
2947     writeOperand(CEPI->getCleanupPad(), /*PrintType=*/false);
2948
2949     Out << " unwind ";
2950     if (CEPI->hasUnwindDest())
2951       writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2952     else
2953       Out << "to caller";
2954   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2955     // Print the calling convention being used.
2956     if (CI->getCallingConv() != CallingConv::C) {
2957       Out << " ";
2958       PrintCallingConv(CI->getCallingConv(), Out);
2959     }
2960
2961     Operand = CI->getCalledValue();
2962     FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
2963     Type *RetTy = FTy->getReturnType();
2964     const AttributeSet &PAL = CI->getAttributes();
2965
2966     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2967       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2968
2969     // If possible, print out the short form of the call instruction.  We can
2970     // only do this if the first argument is a pointer to a nonvararg function,
2971     // and if the return type is not a pointer to a function.
2972     //
2973     Out << ' ';
2974     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2975     Out << ' ';
2976     writeOperand(Operand, false);
2977     Out << '(';
2978     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2979       if (op > 0)
2980         Out << ", ";
2981       writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2982     }
2983
2984     // Emit an ellipsis if this is a musttail call in a vararg function.  This
2985     // is only to aid readability, musttail calls forward varargs by default.
2986     if (CI->isMustTailCall() && CI->getParent() &&
2987         CI->getParent()->getParent() &&
2988         CI->getParent()->getParent()->isVarArg())
2989       Out << ", ...";
2990
2991     Out << ')';
2992     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2993       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2994
2995     writeOperandBundles(CI);
2996
2997   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2998     Operand = II->getCalledValue();
2999     FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
3000     Type *RetTy = FTy->getReturnType();
3001     const AttributeSet &PAL = II->getAttributes();
3002
3003     // Print the calling convention being used.
3004     if (II->getCallingConv() != CallingConv::C) {
3005       Out << " ";
3006       PrintCallingConv(II->getCallingConv(), Out);
3007     }
3008
3009     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
3010       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
3011
3012     // If possible, print out the short form of the invoke instruction. We can
3013     // only do this if the first argument is a pointer to a nonvararg function,
3014     // and if the return type is not a pointer to a function.
3015     //
3016     Out << ' ';
3017     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3018     Out << ' ';
3019     writeOperand(Operand, false);
3020     Out << '(';
3021     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3022       if (op)
3023         Out << ", ";
3024       writeParamOperand(II->getArgOperand(op), PAL, op + 1);
3025     }
3026
3027     Out << ')';
3028     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
3029       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3030
3031     writeOperandBundles(II);
3032
3033     Out << "\n          to ";
3034     writeOperand(II->getNormalDest(), true);
3035     Out << " unwind ";
3036     writeOperand(II->getUnwindDest(), true);
3037
3038   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3039     Out << ' ';
3040     if (AI->isUsedWithInAlloca())
3041       Out << "inalloca ";
3042     TypePrinter.print(AI->getAllocatedType(), Out);
3043
3044     // Explicitly write the array size if the code is broken, if it's an array
3045     // allocation, or if the type is not canonical for scalar allocations.  The
3046     // latter case prevents the type from mutating when round-tripping through
3047     // assembly.
3048     if (!AI->getArraySize() || AI->isArrayAllocation() ||
3049         !AI->getArraySize()->getType()->isIntegerTy(32)) {
3050       Out << ", ";
3051       writeOperand(AI->getArraySize(), true);
3052     }
3053     if (AI->getAlignment()) {
3054       Out << ", align " << AI->getAlignment();
3055     }
3056   } else if (isa<CastInst>(I)) {
3057     if (Operand) {
3058       Out << ' ';
3059       writeOperand(Operand, true);   // Work with broken code
3060     }
3061     Out << " to ";
3062     TypePrinter.print(I.getType(), Out);
3063   } else if (isa<VAArgInst>(I)) {
3064     if (Operand) {
3065       Out << ' ';
3066       writeOperand(Operand, true);   // Work with broken code
3067     }
3068     Out << ", ";
3069     TypePrinter.print(I.getType(), Out);
3070   } else if (Operand) {   // Print the normal way.
3071     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3072       Out << ' ';
3073       TypePrinter.print(GEP->getSourceElementType(), Out);
3074       Out << ',';
3075     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3076       Out << ' ';
3077       TypePrinter.print(LI->getType(), Out);
3078       Out << ',';
3079     }
3080
3081     // PrintAllTypes - Instructions who have operands of all the same type
3082     // omit the type from all but the first operand.  If the instruction has
3083     // different type operands (for example br), then they are all printed.
3084     bool PrintAllTypes = false;
3085     Type *TheType = Operand->getType();
3086
3087     // Select, Store and ShuffleVector always print all types.
3088     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3089         || isa<ReturnInst>(I)) {
3090       PrintAllTypes = true;
3091     } else {
3092       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3093         Operand = I.getOperand(i);
3094         // note that Operand shouldn't be null, but the test helps make dump()
3095         // more tolerant of malformed IR
3096         if (Operand && Operand->getType() != TheType) {
3097           PrintAllTypes = true;    // We have differing types!  Print them all!
3098           break;
3099         }
3100       }
3101     }
3102
3103     if (!PrintAllTypes) {
3104       Out << ' ';
3105       TypePrinter.print(TheType, Out);
3106     }
3107
3108     Out << ' ';
3109     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3110       if (i) Out << ", ";
3111       writeOperand(I.getOperand(i), PrintAllTypes);
3112     }
3113   }
3114
3115   // Print atomic ordering/alignment for memory operations
3116   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3117     if (LI->isAtomic())
3118       writeAtomic(LI->getOrdering(), LI->getSynchScope());
3119     if (LI->getAlignment())
3120       Out << ", align " << LI->getAlignment();
3121   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3122     if (SI->isAtomic())
3123       writeAtomic(SI->getOrdering(), SI->getSynchScope());
3124     if (SI->getAlignment())
3125       Out << ", align " << SI->getAlignment();
3126   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3127     writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3128                        CXI->getSynchScope());
3129   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3130     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3131   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3132     writeAtomic(FI->getOrdering(), FI->getSynchScope());
3133   }
3134
3135   // Print Metadata info.
3136   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3137   I.getAllMetadata(InstMD);
3138   printMetadataAttachments(InstMD, ", ");
3139
3140   // Print a nice comment.
3141   printInfoComment(I);
3142 }
3143
3144 void AssemblyWriter::printMetadataAttachments(
3145     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3146     StringRef Separator) {
3147   if (MDs.empty())
3148     return;
3149
3150   if (MDNames.empty())
3151     TheModule->getMDKindNames(MDNames);
3152
3153   for (const auto &I : MDs) {
3154     unsigned Kind = I.first;
3155     Out << Separator;
3156     if (Kind < MDNames.size()) {
3157       Out << "!";
3158       printMetadataIdentifier(MDNames[Kind], Out);
3159     } else
3160       Out << "!<unknown kind #" << Kind << ">";
3161     Out << ' ';
3162     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3163   }
3164 }
3165
3166 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3167   Out << '!' << Slot << " = ";
3168   printMDNodeBody(Node);
3169   Out << "\n";
3170 }
3171
3172 void AssemblyWriter::writeAllMDNodes() {
3173   SmallVector<const MDNode *, 16> Nodes;
3174   Nodes.resize(Machine.mdn_size());
3175   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3176        I != E; ++I)
3177     Nodes[I->second] = cast<MDNode>(I->first);
3178
3179   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3180     writeMDNode(i, Nodes[i]);
3181   }
3182 }
3183
3184 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3185   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3186 }
3187
3188 void AssemblyWriter::writeAllAttributeGroups() {
3189   std::vector<std::pair<AttributeSet, unsigned> > asVec;
3190   asVec.resize(Machine.as_size());
3191
3192   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3193        I != E; ++I)
3194     asVec[I->second] = *I;
3195
3196   for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3197          I = asVec.begin(), E = asVec.end(); I != E; ++I)
3198     Out << "attributes #" << I->second << " = { "
3199         << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3200 }
3201
3202 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3203   bool IsInFunction = Machine.getFunction();
3204   if (IsInFunction)
3205     Out << "  ";
3206
3207   Out << "uselistorder";
3208   if (const BasicBlock *BB =
3209           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3210     Out << "_bb ";
3211     writeOperand(BB->getParent(), false);
3212     Out << ", ";
3213     writeOperand(BB, false);
3214   } else {
3215     Out << " ";
3216     writeOperand(Order.V, true);
3217   }
3218   Out << ", { ";
3219
3220   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3221   Out << Order.Shuffle[0];
3222   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3223     Out << ", " << Order.Shuffle[I];
3224   Out << " }\n";
3225 }
3226
3227 void AssemblyWriter::printUseLists(const Function *F) {
3228   auto hasMore =
3229       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3230   if (!hasMore())
3231     // Nothing to do.
3232     return;
3233
3234   Out << "\n; uselistorder directives\n";
3235   while (hasMore()) {
3236     printUseListOrder(UseListOrders.back());
3237     UseListOrders.pop_back();
3238   }
3239 }
3240
3241 //===----------------------------------------------------------------------===//
3242 //                       External Interface declarations
3243 //===----------------------------------------------------------------------===//
3244
3245 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3246                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3247   SlotTracker SlotTable(this);
3248   formatted_raw_ostream OS(ROS);
3249   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3250                    ShouldPreserveUseListOrder);
3251   W.printModule(this);
3252 }
3253
3254 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3255   SlotTracker SlotTable(getParent());
3256   formatted_raw_ostream OS(ROS);
3257   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3258   W.printNamedMDNode(this);
3259 }
3260
3261 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3262   PrintLLVMName(ROS, getName(), ComdatPrefix);
3263   ROS << " = comdat ";
3264
3265   switch (getSelectionKind()) {
3266   case Comdat::Any:
3267     ROS << "any";
3268     break;
3269   case Comdat::ExactMatch:
3270     ROS << "exactmatch";
3271     break;
3272   case Comdat::Largest:
3273     ROS << "largest";
3274     break;
3275   case Comdat::NoDuplicates:
3276     ROS << "noduplicates";
3277     break;
3278   case Comdat::SameSize:
3279     ROS << "samesize";
3280     break;
3281   }
3282
3283   ROS << '\n';
3284 }
3285
3286 void Type::print(raw_ostream &OS, bool /*IsForDebug*/) const {
3287   TypePrinting TP;
3288   TP.print(const_cast<Type*>(this), OS);
3289
3290   // If the type is a named struct type, print the body as well.
3291   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3292     if (!STy->isLiteral()) {
3293       OS << " = type ";
3294       TP.printStructBody(STy, OS);
3295     }
3296 }
3297
3298 static bool isReferencingMDNode(const Instruction &I) {
3299   if (const auto *CI = dyn_cast<CallInst>(&I))
3300     if (Function *F = CI->getCalledFunction())
3301       if (F->isIntrinsic())
3302         for (auto &Op : I.operands())
3303           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3304             if (isa<MDNode>(V->getMetadata()))
3305               return true;
3306   return false;
3307 }
3308
3309 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3310   bool ShouldInitializeAllMetadata = false;
3311   if (auto *I = dyn_cast<Instruction>(this))
3312     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3313   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3314     ShouldInitializeAllMetadata = true;
3315
3316   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3317   print(ROS, MST, IsForDebug);
3318 }
3319
3320 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3321                   bool IsForDebug) const {
3322   formatted_raw_ostream OS(ROS);
3323   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3324   SlotTracker &SlotTable =
3325       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3326   auto incorporateFunction = [&](const Function *F) {
3327     if (F)
3328       MST.incorporateFunction(*F);
3329   };
3330
3331   if (const Instruction *I = dyn_cast<Instruction>(this)) {
3332     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3333     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3334     W.printInstruction(*I);
3335   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3336     incorporateFunction(BB->getParent());
3337     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3338     W.printBasicBlock(BB);
3339   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3340     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3341     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3342       W.printGlobal(V);
3343     else if (const Function *F = dyn_cast<Function>(GV))
3344       W.printFunction(F);
3345     else
3346       W.printAlias(cast<GlobalAlias>(GV));
3347   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3348     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3349   } else if (const Constant *C = dyn_cast<Constant>(this)) {
3350     TypePrinting TypePrinter;
3351     TypePrinter.print(C->getType(), OS);
3352     OS << ' ';
3353     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3354   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3355     this->printAsOperand(OS, /* PrintType */ true, MST);
3356   } else {
3357     llvm_unreachable("Unknown value to print out!");
3358   }
3359 }
3360
3361 /// Print without a type, skipping the TypePrinting object.
3362 ///
3363 /// \return \c true iff printing was successful.
3364 static bool printWithoutType(const Value &V, raw_ostream &O,
3365                              SlotTracker *Machine, const Module *M) {
3366   if (V.hasName() || isa<GlobalValue>(V) ||
3367       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3368     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3369     return true;
3370   }
3371   return false;
3372 }
3373
3374 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3375                                ModuleSlotTracker &MST) {
3376   TypePrinting TypePrinter;
3377   if (const Module *M = MST.getModule())
3378     TypePrinter.incorporateTypes(*M);
3379   if (PrintType) {
3380     TypePrinter.print(V.getType(), O);
3381     O << ' ';
3382   }
3383
3384   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3385                          MST.getModule());
3386 }
3387
3388 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3389                            const Module *M) const {
3390   if (!M)
3391     M = getModuleFromVal(this);
3392
3393   if (!PrintType)
3394     if (printWithoutType(*this, O, nullptr, M))
3395       return;
3396
3397   SlotTracker Machine(
3398       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3399   ModuleSlotTracker MST(Machine, M);
3400   printAsOperandImpl(*this, O, PrintType, MST);
3401 }
3402
3403 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3404                            ModuleSlotTracker &MST) const {
3405   if (!PrintType)
3406     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3407       return;
3408
3409   printAsOperandImpl(*this, O, PrintType, MST);
3410 }
3411
3412 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3413                               ModuleSlotTracker &MST, const Module *M,
3414                               bool OnlyAsOperand) {
3415   formatted_raw_ostream OS(ROS);
3416
3417   TypePrinting TypePrinter;
3418   if (M)
3419     TypePrinter.incorporateTypes(*M);
3420
3421   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3422                          /* FromValue */ true);
3423
3424   auto *N = dyn_cast<MDNode>(&MD);
3425   if (OnlyAsOperand || !N)
3426     return;
3427
3428   OS << " = ";
3429   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3430 }
3431
3432 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3433   ModuleSlotTracker MST(M, isa<MDNode>(this));
3434   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3435 }
3436
3437 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3438                               const Module *M) const {
3439   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3440 }
3441
3442 void Metadata::print(raw_ostream &OS, const Module *M,
3443                      bool /*IsForDebug*/) const {
3444   ModuleSlotTracker MST(M, isa<MDNode>(this));
3445   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3446 }
3447
3448 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3449                      const Module *M, bool /*IsForDebug*/) const {
3450   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3451 }
3452
3453 // Value::dump - allow easy printing of Values from the debugger.
3454 LLVM_DUMP_METHOD
3455 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3456
3457 // Type::dump - allow easy printing of Types from the debugger.
3458 LLVM_DUMP_METHOD
3459 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3460
3461 // Module::dump() - Allow printing of Modules from the debugger.
3462 LLVM_DUMP_METHOD
3463 void Module::dump() const {
3464   print(dbgs(), nullptr,
3465         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3466 }
3467
3468 // \brief Allow printing of Comdats from the debugger.
3469 LLVM_DUMP_METHOD
3470 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3471
3472 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3473 LLVM_DUMP_METHOD
3474 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3475
3476 LLVM_DUMP_METHOD
3477 void Metadata::dump() const { dump(nullptr); }
3478
3479 LLVM_DUMP_METHOD
3480 void Metadata::dump(const Module *M) const {
3481   print(dbgs(), M, /*IsForDebug=*/true);
3482   dbgs() << '\n';
3483 }