[IR] Add support for empty tokens
[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 isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
1112       bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
1113       bool isInf = CFP->getValueAPF().isInfinity();
1114       bool isNaN = CFP->getValueAPF().isNaN();
1115       if (!isHalf && !isInf && !isNaN) {
1116         double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
1117                                 CFP->getValueAPF().convertToFloat();
1118         SmallString<128> StrVal;
1119         raw_svector_ostream(StrVal) << Val;
1120
1121         // Check to make sure that the stringized number is not some string like
1122         // "Inf" or NaN, that atof will accept, but the lexer will not.  Check
1123         // that the string matches the "[-+]?[0-9]" regex.
1124         //
1125         if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1126             ((StrVal[0] == '-' || StrVal[0] == '+') &&
1127              (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
1128           // Reparse stringized version!
1129           if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
1130             Out << StrVal;
1131             return;
1132           }
1133         }
1134       }
1135       // Otherwise we could not reparse it to exactly the same value, so we must
1136       // output the string in hexadecimal format!  Note that loading and storing
1137       // floating point types changes the bits of NaNs on some hosts, notably
1138       // x86, so we must not use these types.
1139       static_assert(sizeof(double) == sizeof(uint64_t),
1140                     "assuming that double is 64 bits!");
1141       char Buffer[40];
1142       APFloat apf = CFP->getValueAPF();
1143       // Halves and floats are represented in ASCII IR as double, convert.
1144       if (!isDouble)
1145         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1146                           &ignored);
1147       Out << "0x" <<
1148               utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
1149                             Buffer+40);
1150       return;
1151     }
1152
1153     // Either half, or some form of long double.
1154     // These appear as a magic letter identifying the type, then a
1155     // fixed number of hex digits.
1156     Out << "0x";
1157     // Bit position, in the current word, of the next nibble to print.
1158     int shiftcount;
1159
1160     if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
1161       Out << 'K';
1162       // api needed to prevent premature destruction
1163       APInt api = CFP->getValueAPF().bitcastToAPInt();
1164       const uint64_t* p = api.getRawData();
1165       uint64_t word = p[1];
1166       shiftcount = 12;
1167       int width = api.getBitWidth();
1168       for (int j=0; j<width; j+=4, shiftcount-=4) {
1169         unsigned int nibble = (word>>shiftcount) & 15;
1170         if (nibble < 10)
1171           Out << (unsigned char)(nibble + '0');
1172         else
1173           Out << (unsigned char)(nibble - 10 + 'A');
1174         if (shiftcount == 0 && j+4 < width) {
1175           word = *p;
1176           shiftcount = 64;
1177           if (width-j-4 < 64)
1178             shiftcount = width-j-4;
1179         }
1180       }
1181       return;
1182     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
1183       shiftcount = 60;
1184       Out << 'L';
1185     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
1186       shiftcount = 60;
1187       Out << 'M';
1188     } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
1189       shiftcount = 12;
1190       Out << 'H';
1191     } else
1192       llvm_unreachable("Unsupported floating point type");
1193     // api needed to prevent premature destruction
1194     APInt api = CFP->getValueAPF().bitcastToAPInt();
1195     const uint64_t* p = api.getRawData();
1196     uint64_t word = *p;
1197     int width = api.getBitWidth();
1198     for (int j=0; j<width; j+=4, shiftcount-=4) {
1199       unsigned int nibble = (word>>shiftcount) & 15;
1200       if (nibble < 10)
1201         Out << (unsigned char)(nibble + '0');
1202       else
1203         Out << (unsigned char)(nibble - 10 + 'A');
1204       if (shiftcount == 0 && j+4 < width) {
1205         word = *(++p);
1206         shiftcount = 64;
1207         if (width-j-4 < 64)
1208           shiftcount = width-j-4;
1209       }
1210     }
1211     return;
1212   }
1213
1214   if (isa<ConstantAggregateZero>(CV)) {
1215     Out << "zeroinitializer";
1216     return;
1217   }
1218
1219   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1220     Out << "blockaddress(";
1221     WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
1222                            Context);
1223     Out << ", ";
1224     WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
1225                            Context);
1226     Out << ")";
1227     return;
1228   }
1229
1230   if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1231     Type *ETy = CA->getType()->getElementType();
1232     Out << '[';
1233     TypePrinter.print(ETy, Out);
1234     Out << ' ';
1235     WriteAsOperandInternal(Out, CA->getOperand(0),
1236                            &TypePrinter, Machine,
1237                            Context);
1238     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1239       Out << ", ";
1240       TypePrinter.print(ETy, Out);
1241       Out << ' ';
1242       WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
1243                              Context);
1244     }
1245     Out << ']';
1246     return;
1247   }
1248
1249   if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
1250     // As a special case, print the array as a string if it is an array of
1251     // i8 with ConstantInt values.
1252     if (CA->isString()) {
1253       Out << "c\"";
1254       PrintEscapedString(CA->getAsString(), Out);
1255       Out << '"';
1256       return;
1257     }
1258
1259     Type *ETy = CA->getType()->getElementType();
1260     Out << '[';
1261     TypePrinter.print(ETy, Out);
1262     Out << ' ';
1263     WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
1264                            &TypePrinter, Machine,
1265                            Context);
1266     for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
1267       Out << ", ";
1268       TypePrinter.print(ETy, Out);
1269       Out << ' ';
1270       WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
1271                              Machine, Context);
1272     }
1273     Out << ']';
1274     return;
1275   }
1276
1277
1278   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1279     if (CS->getType()->isPacked())
1280       Out << '<';
1281     Out << '{';
1282     unsigned N = CS->getNumOperands();
1283     if (N) {
1284       Out << ' ';
1285       TypePrinter.print(CS->getOperand(0)->getType(), Out);
1286       Out << ' ';
1287
1288       WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1289                              Context);
1290
1291       for (unsigned i = 1; i < N; i++) {
1292         Out << ", ";
1293         TypePrinter.print(CS->getOperand(i)->getType(), Out);
1294         Out << ' ';
1295
1296         WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1297                                Context);
1298       }
1299       Out << ' ';
1300     }
1301
1302     Out << '}';
1303     if (CS->getType()->isPacked())
1304       Out << '>';
1305     return;
1306   }
1307
1308   if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1309     Type *ETy = CV->getType()->getVectorElementType();
1310     Out << '<';
1311     TypePrinter.print(ETy, Out);
1312     Out << ' ';
1313     WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
1314                            Machine, Context);
1315     for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
1316       Out << ", ";
1317       TypePrinter.print(ETy, Out);
1318       Out << ' ';
1319       WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
1320                              Machine, Context);
1321     }
1322     Out << '>';
1323     return;
1324   }
1325
1326   if (isa<ConstantPointerNull>(CV)) {
1327     Out << "null";
1328     return;
1329   }
1330
1331   if (isa<ConstantTokenNone>(CV)) {
1332     Out << "none";
1333     return;
1334   }
1335
1336   if (isa<UndefValue>(CV)) {
1337     Out << "undef";
1338     return;
1339   }
1340
1341   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1342     Out << CE->getOpcodeName();
1343     WriteOptimizationInfo(Out, CE);
1344     if (CE->isCompare())
1345       Out << ' ' << getPredicateText(CE->getPredicate());
1346     Out << " (";
1347
1348     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1349       TypePrinter.print(GEP->getSourceElementType(), Out);
1350       Out << ", ";
1351     }
1352
1353     for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1354       TypePrinter.print((*OI)->getType(), Out);
1355       Out << ' ';
1356       WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1357       if (OI+1 != CE->op_end())
1358         Out << ", ";
1359     }
1360
1361     if (CE->hasIndices()) {
1362       ArrayRef<unsigned> Indices = CE->getIndices();
1363       for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1364         Out << ", " << Indices[i];
1365     }
1366
1367     if (CE->isCast()) {
1368       Out << " to ";
1369       TypePrinter.print(CE->getType(), Out);
1370     }
1371
1372     Out << ')';
1373     return;
1374   }
1375
1376   Out << "<placeholder or erroneous Constant>";
1377 }
1378
1379 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1380                          TypePrinting *TypePrinter, SlotTracker *Machine,
1381                          const Module *Context) {
1382   Out << "!{";
1383   for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1384     const Metadata *MD = Node->getOperand(mi);
1385     if (!MD)
1386       Out << "null";
1387     else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1388       Value *V = MDV->getValue();
1389       TypePrinter->print(V->getType(), Out);
1390       Out << ' ';
1391       WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
1392     } else {
1393       WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1394     }
1395     if (mi + 1 != me)
1396       Out << ", ";
1397   }
1398
1399   Out << "}";
1400 }
1401
1402 namespace {
1403 struct FieldSeparator {
1404   bool Skip;
1405   const char *Sep;
1406   FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
1407 };
1408 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1409   if (FS.Skip) {
1410     FS.Skip = false;
1411     return OS;
1412   }
1413   return OS << FS.Sep;
1414 }
1415 struct MDFieldPrinter {
1416   raw_ostream &Out;
1417   FieldSeparator FS;
1418   TypePrinting *TypePrinter;
1419   SlotTracker *Machine;
1420   const Module *Context;
1421
1422   explicit MDFieldPrinter(raw_ostream &Out)
1423       : Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
1424   MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
1425                  SlotTracker *Machine, const Module *Context)
1426       : Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
1427   }
1428   void printTag(const DINode *N);
1429   void printString(StringRef Name, StringRef Value,
1430                    bool ShouldSkipEmpty = true);
1431   void printMetadata(StringRef Name, const Metadata *MD,
1432                      bool ShouldSkipNull = true);
1433   template <class IntTy>
1434   void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1435   void printBool(StringRef Name, bool Value);
1436   void printDIFlags(StringRef Name, unsigned Flags);
1437   template <class IntTy, class Stringifier>
1438   void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1439                       bool ShouldSkipZero = true);
1440 };
1441 } // end namespace
1442
1443 void MDFieldPrinter::printTag(const DINode *N) {
1444   Out << FS << "tag: ";
1445   if (const char *Tag = dwarf::TagString(N->getTag()))
1446     Out << Tag;
1447   else
1448     Out << N->getTag();
1449 }
1450
1451 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1452                                  bool ShouldSkipEmpty) {
1453   if (ShouldSkipEmpty && Value.empty())
1454     return;
1455
1456   Out << FS << Name << ": \"";
1457   PrintEscapedString(Value, Out);
1458   Out << "\"";
1459 }
1460
1461 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1462                                    TypePrinting *TypePrinter,
1463                                    SlotTracker *Machine,
1464                                    const Module *Context) {
1465   if (!MD) {
1466     Out << "null";
1467     return;
1468   }
1469   WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
1470 }
1471
1472 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1473                                    bool ShouldSkipNull) {
1474   if (ShouldSkipNull && !MD)
1475     return;
1476
1477   Out << FS << Name << ": ";
1478   writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
1479 }
1480
1481 template <class IntTy>
1482 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1483   if (ShouldSkipZero && !Int)
1484     return;
1485
1486   Out << FS << Name << ": " << Int;
1487 }
1488
1489 void MDFieldPrinter::printBool(StringRef Name, bool Value) {
1490   Out << FS << Name << ": " << (Value ? "true" : "false");
1491 }
1492
1493 void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
1494   if (!Flags)
1495     return;
1496
1497   Out << FS << Name << ": ";
1498
1499   SmallVector<unsigned, 8> SplitFlags;
1500   unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
1501
1502   FieldSeparator FlagsFS(" | ");
1503   for (unsigned F : SplitFlags) {
1504     const char *StringF = DINode::getFlagString(F);
1505     assert(StringF && "Expected valid flag");
1506     Out << FlagsFS << StringF;
1507   }
1508   if (Extra || SplitFlags.empty())
1509     Out << FlagsFS << Extra;
1510 }
1511
1512 template <class IntTy, class Stringifier>
1513 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1514                                     Stringifier toString, bool ShouldSkipZero) {
1515   if (!Value)
1516     return;
1517
1518   Out << FS << Name << ": ";
1519   if (const char *S = toString(Value))
1520     Out << S;
1521   else
1522     Out << Value;
1523 }
1524
1525 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1526                                TypePrinting *TypePrinter, SlotTracker *Machine,
1527                                const Module *Context) {
1528   Out << "!GenericDINode(";
1529   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1530   Printer.printTag(N);
1531   Printer.printString("header", N->getHeader());
1532   if (N->getNumDwarfOperands()) {
1533     Out << Printer.FS << "operands: {";
1534     FieldSeparator IFS;
1535     for (auto &I : N->dwarf_operands()) {
1536       Out << IFS;
1537       writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
1538     }
1539     Out << "}";
1540   }
1541   Out << ")";
1542 }
1543
1544 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1545                             TypePrinting *TypePrinter, SlotTracker *Machine,
1546                             const Module *Context) {
1547   Out << "!DILocation(";
1548   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1549   // Always output the line, since 0 is a relevant and important value for it.
1550   Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1551   Printer.printInt("column", DL->getColumn());
1552   Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1553   Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1554   Out << ")";
1555 }
1556
1557 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1558                             TypePrinting *, SlotTracker *, const Module *) {
1559   Out << "!DISubrange(";
1560   MDFieldPrinter Printer(Out);
1561   Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
1562   Printer.printInt("lowerBound", N->getLowerBound());
1563   Out << ")";
1564 }
1565
1566 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1567                               TypePrinting *, SlotTracker *, const Module *) {
1568   Out << "!DIEnumerator(";
1569   MDFieldPrinter Printer(Out);
1570   Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1571   Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
1572   Out << ")";
1573 }
1574
1575 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1576                              TypePrinting *, SlotTracker *, const Module *) {
1577   Out << "!DIBasicType(";
1578   MDFieldPrinter Printer(Out);
1579   if (N->getTag() != dwarf::DW_TAG_base_type)
1580     Printer.printTag(N);
1581   Printer.printString("name", N->getName());
1582   Printer.printInt("size", N->getSizeInBits());
1583   Printer.printInt("align", N->getAlignInBits());
1584   Printer.printDwarfEnum("encoding", N->getEncoding(),
1585                          dwarf::AttributeEncodingString);
1586   Out << ")";
1587 }
1588
1589 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
1590                                TypePrinting *TypePrinter, SlotTracker *Machine,
1591                                const Module *Context) {
1592   Out << "!DIDerivedType(";
1593   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1594   Printer.printTag(N);
1595   Printer.printString("name", N->getName());
1596   Printer.printMetadata("scope", N->getRawScope());
1597   Printer.printMetadata("file", N->getRawFile());
1598   Printer.printInt("line", N->getLine());
1599   Printer.printMetadata("baseType", N->getRawBaseType(),
1600                         /* ShouldSkipNull */ false);
1601   Printer.printInt("size", N->getSizeInBits());
1602   Printer.printInt("align", N->getAlignInBits());
1603   Printer.printInt("offset", N->getOffsetInBits());
1604   Printer.printDIFlags("flags", N->getFlags());
1605   Printer.printMetadata("extraData", N->getRawExtraData());
1606   Out << ")";
1607 }
1608
1609 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
1610                                  TypePrinting *TypePrinter,
1611                                  SlotTracker *Machine, const Module *Context) {
1612   Out << "!DICompositeType(";
1613   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1614   Printer.printTag(N);
1615   Printer.printString("name", N->getName());
1616   Printer.printMetadata("scope", N->getRawScope());
1617   Printer.printMetadata("file", N->getRawFile());
1618   Printer.printInt("line", N->getLine());
1619   Printer.printMetadata("baseType", N->getRawBaseType());
1620   Printer.printInt("size", N->getSizeInBits());
1621   Printer.printInt("align", N->getAlignInBits());
1622   Printer.printInt("offset", N->getOffsetInBits());
1623   Printer.printDIFlags("flags", N->getFlags());
1624   Printer.printMetadata("elements", N->getRawElements());
1625   Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
1626                          dwarf::LanguageString);
1627   Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
1628   Printer.printMetadata("templateParams", N->getRawTemplateParams());
1629   Printer.printString("identifier", N->getIdentifier());
1630   Out << ")";
1631 }
1632
1633 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
1634                                   TypePrinting *TypePrinter,
1635                                   SlotTracker *Machine, const Module *Context) {
1636   Out << "!DISubroutineType(";
1637   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1638   Printer.printDIFlags("flags", N->getFlags());
1639   Printer.printMetadata("types", N->getRawTypeArray(),
1640                         /* ShouldSkipNull */ false);
1641   Out << ")";
1642 }
1643
1644 static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
1645                         SlotTracker *, const Module *) {
1646   Out << "!DIFile(";
1647   MDFieldPrinter Printer(Out);
1648   Printer.printString("filename", N->getFilename(),
1649                       /* ShouldSkipEmpty */ false);
1650   Printer.printString("directory", N->getDirectory(),
1651                       /* ShouldSkipEmpty */ false);
1652   Out << ")";
1653 }
1654
1655 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
1656                                TypePrinting *TypePrinter, SlotTracker *Machine,
1657                                const Module *Context) {
1658   Out << "!DICompileUnit(";
1659   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1660   Printer.printDwarfEnum("language", N->getSourceLanguage(),
1661                          dwarf::LanguageString, /* ShouldSkipZero */ false);
1662   Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
1663   Printer.printString("producer", N->getProducer());
1664   Printer.printBool("isOptimized", N->isOptimized());
1665   Printer.printString("flags", N->getFlags());
1666   Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
1667                    /* ShouldSkipZero */ false);
1668   Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
1669   Printer.printInt("emissionKind", N->getEmissionKind(),
1670                    /* ShouldSkipZero */ false);
1671   Printer.printMetadata("enums", N->getRawEnumTypes());
1672   Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
1673   Printer.printMetadata("subprograms", N->getRawSubprograms());
1674   Printer.printMetadata("globals", N->getRawGlobalVariables());
1675   Printer.printMetadata("imports", N->getRawImportedEntities());
1676   Printer.printInt("dwoId", N->getDWOId());
1677   Out << ")";
1678 }
1679
1680 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
1681                               TypePrinting *TypePrinter, SlotTracker *Machine,
1682                               const Module *Context) {
1683   Out << "!DISubprogram(";
1684   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1685   Printer.printString("name", N->getName());
1686   Printer.printString("linkageName", N->getLinkageName());
1687   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1688   Printer.printMetadata("file", N->getRawFile());
1689   Printer.printInt("line", N->getLine());
1690   Printer.printMetadata("type", N->getRawType());
1691   Printer.printBool("isLocal", N->isLocalToUnit());
1692   Printer.printBool("isDefinition", N->isDefinition());
1693   Printer.printInt("scopeLine", N->getScopeLine());
1694   Printer.printMetadata("containingType", N->getRawContainingType());
1695   Printer.printDwarfEnum("virtuality", N->getVirtuality(),
1696                          dwarf::VirtualityString);
1697   Printer.printInt("virtualIndex", N->getVirtualIndex());
1698   Printer.printDIFlags("flags", N->getFlags());
1699   Printer.printBool("isOptimized", N->isOptimized());
1700   Printer.printMetadata("templateParams", N->getRawTemplateParams());
1701   Printer.printMetadata("declaration", N->getRawDeclaration());
1702   Printer.printMetadata("variables", N->getRawVariables());
1703   Out << ")";
1704 }
1705
1706 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
1707                                 TypePrinting *TypePrinter, SlotTracker *Machine,
1708                                 const Module *Context) {
1709   Out << "!DILexicalBlock(";
1710   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1711   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1712   Printer.printMetadata("file", N->getRawFile());
1713   Printer.printInt("line", N->getLine());
1714   Printer.printInt("column", N->getColumn());
1715   Out << ")";
1716 }
1717
1718 static void writeDILexicalBlockFile(raw_ostream &Out,
1719                                     const DILexicalBlockFile *N,
1720                                     TypePrinting *TypePrinter,
1721                                     SlotTracker *Machine,
1722                                     const Module *Context) {
1723   Out << "!DILexicalBlockFile(";
1724   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1725   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1726   Printer.printMetadata("file", N->getRawFile());
1727   Printer.printInt("discriminator", N->getDiscriminator(),
1728                    /* ShouldSkipZero */ false);
1729   Out << ")";
1730 }
1731
1732 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
1733                              TypePrinting *TypePrinter, SlotTracker *Machine,
1734                              const Module *Context) {
1735   Out << "!DINamespace(";
1736   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1737   Printer.printString("name", N->getName());
1738   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1739   Printer.printMetadata("file", N->getRawFile());
1740   Printer.printInt("line", N->getLine());
1741   Out << ")";
1742 }
1743
1744 static void writeDIModule(raw_ostream &Out, const DIModule *N,
1745                           TypePrinting *TypePrinter, SlotTracker *Machine,
1746                           const Module *Context) {
1747   Out << "!DIModule(";
1748   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1749   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1750   Printer.printString("name", N->getName());
1751   Printer.printString("configMacros", N->getConfigurationMacros());
1752   Printer.printString("includePath", N->getIncludePath());
1753   Printer.printString("isysroot", N->getISysRoot());
1754   Out << ")";
1755 }
1756
1757
1758 static void writeDITemplateTypeParameter(raw_ostream &Out,
1759                                          const DITemplateTypeParameter *N,
1760                                          TypePrinting *TypePrinter,
1761                                          SlotTracker *Machine,
1762                                          const Module *Context) {
1763   Out << "!DITemplateTypeParameter(";
1764   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1765   Printer.printString("name", N->getName());
1766   Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
1767   Out << ")";
1768 }
1769
1770 static void writeDITemplateValueParameter(raw_ostream &Out,
1771                                           const DITemplateValueParameter *N,
1772                                           TypePrinting *TypePrinter,
1773                                           SlotTracker *Machine,
1774                                           const Module *Context) {
1775   Out << "!DITemplateValueParameter(";
1776   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1777   if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
1778     Printer.printTag(N);
1779   Printer.printString("name", N->getName());
1780   Printer.printMetadata("type", N->getRawType());
1781   Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
1782   Out << ")";
1783 }
1784
1785 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
1786                                   TypePrinting *TypePrinter,
1787                                   SlotTracker *Machine, const Module *Context) {
1788   Out << "!DIGlobalVariable(";
1789   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1790   Printer.printString("name", N->getName());
1791   Printer.printString("linkageName", N->getLinkageName());
1792   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1793   Printer.printMetadata("file", N->getRawFile());
1794   Printer.printInt("line", N->getLine());
1795   Printer.printMetadata("type", N->getRawType());
1796   Printer.printBool("isLocal", N->isLocalToUnit());
1797   Printer.printBool("isDefinition", N->isDefinition());
1798   Printer.printMetadata("variable", N->getRawVariable());
1799   Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
1800   Out << ")";
1801 }
1802
1803 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
1804                                  TypePrinting *TypePrinter,
1805                                  SlotTracker *Machine, const Module *Context) {
1806   Out << "!DILocalVariable(";
1807   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1808   Printer.printString("name", N->getName());
1809   Printer.printInt("arg", N->getArg());
1810   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1811   Printer.printMetadata("file", N->getRawFile());
1812   Printer.printInt("line", N->getLine());
1813   Printer.printMetadata("type", N->getRawType());
1814   Printer.printDIFlags("flags", N->getFlags());
1815   Out << ")";
1816 }
1817
1818 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
1819                               TypePrinting *TypePrinter, SlotTracker *Machine,
1820                               const Module *Context) {
1821   Out << "!DIExpression(";
1822   FieldSeparator FS;
1823   if (N->isValid()) {
1824     for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
1825       const char *OpStr = dwarf::OperationEncodingString(I->getOp());
1826       assert(OpStr && "Expected valid opcode");
1827
1828       Out << FS << OpStr;
1829       for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
1830         Out << FS << I->getArg(A);
1831     }
1832   } else {
1833     for (const auto &I : N->getElements())
1834       Out << FS << I;
1835   }
1836   Out << ")";
1837 }
1838
1839 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
1840                                 TypePrinting *TypePrinter, SlotTracker *Machine,
1841                                 const Module *Context) {
1842   Out << "!DIObjCProperty(";
1843   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1844   Printer.printString("name", N->getName());
1845   Printer.printMetadata("file", N->getRawFile());
1846   Printer.printInt("line", N->getLine());
1847   Printer.printString("setter", N->getSetterName());
1848   Printer.printString("getter", N->getGetterName());
1849   Printer.printInt("attributes", N->getAttributes());
1850   Printer.printMetadata("type", N->getRawType());
1851   Out << ")";
1852 }
1853
1854 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
1855                                   TypePrinting *TypePrinter,
1856                                   SlotTracker *Machine, const Module *Context) {
1857   Out << "!DIImportedEntity(";
1858   MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
1859   Printer.printTag(N);
1860   Printer.printString("name", N->getName());
1861   Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
1862   Printer.printMetadata("entity", N->getRawEntity());
1863   Printer.printInt("line", N->getLine());
1864   Out << ")";
1865 }
1866
1867
1868 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1869                                     TypePrinting *TypePrinter,
1870                                     SlotTracker *Machine,
1871                                     const Module *Context) {
1872   if (Node->isDistinct())
1873     Out << "distinct ";
1874   else if (Node->isTemporary())
1875     Out << "<temporary!> "; // Handle broken code.
1876
1877   switch (Node->getMetadataID()) {
1878   default:
1879     llvm_unreachable("Expected uniquable MDNode");
1880 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1881   case Metadata::CLASS##Kind:                                                  \
1882     write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context);       \
1883     break;
1884 #include "llvm/IR/Metadata.def"
1885   }
1886 }
1887
1888 // Full implementation of printing a Value as an operand with support for
1889 // TypePrinting, etc.
1890 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1891                                    TypePrinting *TypePrinter,
1892                                    SlotTracker *Machine,
1893                                    const Module *Context) {
1894   if (V->hasName()) {
1895     PrintLLVMName(Out, V);
1896     return;
1897   }
1898
1899   const Constant *CV = dyn_cast<Constant>(V);
1900   if (CV && !isa<GlobalValue>(CV)) {
1901     assert(TypePrinter && "Constants require TypePrinting!");
1902     WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1903     return;
1904   }
1905
1906   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1907     Out << "asm ";
1908     if (IA->hasSideEffects())
1909       Out << "sideeffect ";
1910     if (IA->isAlignStack())
1911       Out << "alignstack ";
1912     // We don't emit the AD_ATT dialect as it's the assumed default.
1913     if (IA->getDialect() == InlineAsm::AD_Intel)
1914       Out << "inteldialect ";
1915     Out << '"';
1916     PrintEscapedString(IA->getAsmString(), Out);
1917     Out << "\", \"";
1918     PrintEscapedString(IA->getConstraintString(), Out);
1919     Out << '"';
1920     return;
1921   }
1922
1923   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
1924     WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
1925                            Context, /* FromValue */ true);
1926     return;
1927   }
1928
1929   char Prefix = '%';
1930   int Slot;
1931   // If we have a SlotTracker, use it.
1932   if (Machine) {
1933     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1934       Slot = Machine->getGlobalSlot(GV);
1935       Prefix = '@';
1936     } else {
1937       Slot = Machine->getLocalSlot(V);
1938
1939       // If the local value didn't succeed, then we may be referring to a value
1940       // from a different function.  Translate it, as this can happen when using
1941       // address of blocks.
1942       if (Slot == -1)
1943         if ((Machine = createSlotTracker(V))) {
1944           Slot = Machine->getLocalSlot(V);
1945           delete Machine;
1946         }
1947     }
1948   } else if ((Machine = createSlotTracker(V))) {
1949     // Otherwise, create one to get the # and then destroy it.
1950     if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1951       Slot = Machine->getGlobalSlot(GV);
1952       Prefix = '@';
1953     } else {
1954       Slot = Machine->getLocalSlot(V);
1955     }
1956     delete Machine;
1957     Machine = nullptr;
1958   } else {
1959     Slot = -1;
1960   }
1961
1962   if (Slot != -1)
1963     Out << Prefix << Slot;
1964   else
1965     Out << "<badref>";
1966 }
1967
1968 static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
1969                                    TypePrinting *TypePrinter,
1970                                    SlotTracker *Machine, const Module *Context,
1971                                    bool FromValue) {
1972   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
1973     std::unique_ptr<SlotTracker> MachineStorage;
1974     if (!Machine) {
1975       MachineStorage = make_unique<SlotTracker>(Context);
1976       Machine = MachineStorage.get();
1977     }
1978     int Slot = Machine->getMetadataSlot(N);
1979     if (Slot == -1)
1980       // Give the pointer value instead of "badref", since this comes up all
1981       // the time when debugging.
1982       Out << "<" << N << ">";
1983     else
1984       Out << '!' << Slot;
1985     return;
1986   }
1987
1988   if (const MDString *MDS = dyn_cast<MDString>(MD)) {
1989     Out << "!\"";
1990     PrintEscapedString(MDS->getString(), Out);
1991     Out << '"';
1992     return;
1993   }
1994
1995   auto *V = cast<ValueAsMetadata>(MD);
1996   assert(TypePrinter && "TypePrinter required for metadata values");
1997   assert((FromValue || !isa<LocalAsMetadata>(V)) &&
1998          "Unexpected function-local metadata outside of value argument");
1999
2000   TypePrinter->print(V->getValue()->getType(), Out);
2001   Out << ' ';
2002   WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
2003 }
2004
2005 namespace {
2006 class AssemblyWriter {
2007   formatted_raw_ostream &Out;
2008   const Module *TheModule;
2009   std::unique_ptr<SlotTracker> SlotTrackerStorage;
2010   SlotTracker &Machine;
2011   TypePrinting TypePrinter;
2012   AssemblyAnnotationWriter *AnnotationWriter;
2013   SetVector<const Comdat *> Comdats;
2014   bool IsForDebug;
2015   bool ShouldPreserveUseListOrder;
2016   UseListOrderStack UseListOrders;
2017   SmallVector<StringRef, 8> MDNames;
2018
2019 public:
2020   /// Construct an AssemblyWriter with an external SlotTracker
2021   AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
2022                  AssemblyAnnotationWriter *AAW, bool IsForDebug,
2023                  bool ShouldPreserveUseListOrder = false);
2024
2025   void printMDNodeBody(const MDNode *MD);
2026   void printNamedMDNode(const NamedMDNode *NMD);
2027
2028   void printModule(const Module *M);
2029
2030   void writeOperand(const Value *Op, bool PrintType);
2031   void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
2032   void writeOperandBundles(ImmutableCallSite CS);
2033   void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
2034   void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2035                           AtomicOrdering FailureOrdering,
2036                           SynchronizationScope SynchScope);
2037
2038   void writeAllMDNodes();
2039   void writeMDNode(unsigned Slot, const MDNode *Node);
2040   void writeAllAttributeGroups();
2041
2042   void printTypeIdentities();
2043   void printGlobal(const GlobalVariable *GV);
2044   void printAlias(const GlobalAlias *GV);
2045   void printComdat(const Comdat *C);
2046   void printFunction(const Function *F);
2047   void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
2048   void printBasicBlock(const BasicBlock *BB);
2049   void printInstructionLine(const Instruction &I);
2050   void printInstruction(const Instruction &I);
2051
2052   void printUseListOrder(const UseListOrder &Order);
2053   void printUseLists(const Function *F);
2054
2055 private:
2056   /// \brief Print out metadata attachments.
2057   void printMetadataAttachments(
2058       const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
2059       StringRef Separator);
2060
2061   // printInfoComment - Print a little comment after the instruction indicating
2062   // which slot it occupies.
2063   void printInfoComment(const Value &V);
2064
2065   // printGCRelocateComment - print comment after call to the gc.relocate
2066   // intrinsic indicating base and derived pointer names.
2067   void printGCRelocateComment(const Value &V);
2068 };
2069 } // namespace
2070
2071 AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
2072                                const Module *M, AssemblyAnnotationWriter *AAW,
2073                                bool IsForDebug, bool ShouldPreserveUseListOrder)
2074     : Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
2075       IsForDebug(IsForDebug),
2076       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2077   if (!TheModule)
2078     return;
2079   TypePrinter.incorporateTypes(*TheModule);
2080   for (const Function &F : *TheModule)
2081     if (const Comdat *C = F.getComdat())
2082       Comdats.insert(C);
2083   for (const GlobalVariable &GV : TheModule->globals())
2084     if (const Comdat *C = GV.getComdat())
2085       Comdats.insert(C);
2086 }
2087
2088 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
2089   if (!Operand) {
2090     Out << "<null operand!>";
2091     return;
2092   }
2093   if (PrintType) {
2094     TypePrinter.print(Operand->getType(), Out);
2095     Out << ' ';
2096   }
2097   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2098 }
2099
2100 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
2101                                  SynchronizationScope SynchScope) {
2102   if (Ordering == NotAtomic)
2103     return;
2104
2105   switch (SynchScope) {
2106   case SingleThread: Out << " singlethread"; break;
2107   case CrossThread: break;
2108   }
2109
2110   switch (Ordering) {
2111   default: Out << " <bad ordering " << int(Ordering) << ">"; break;
2112   case Unordered: Out << " unordered"; break;
2113   case Monotonic: Out << " monotonic"; break;
2114   case Acquire: Out << " acquire"; break;
2115   case Release: Out << " release"; break;
2116   case AcquireRelease: Out << " acq_rel"; break;
2117   case SequentiallyConsistent: Out << " seq_cst"; break;
2118   }
2119 }
2120
2121 void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
2122                                         AtomicOrdering FailureOrdering,
2123                                         SynchronizationScope SynchScope) {
2124   assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
2125
2126   switch (SynchScope) {
2127   case SingleThread: Out << " singlethread"; break;
2128   case CrossThread: break;
2129   }
2130
2131   switch (SuccessOrdering) {
2132   default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
2133   case Unordered: Out << " unordered"; break;
2134   case Monotonic: Out << " monotonic"; break;
2135   case Acquire: Out << " acquire"; break;
2136   case Release: Out << " release"; break;
2137   case AcquireRelease: Out << " acq_rel"; break;
2138   case SequentiallyConsistent: Out << " seq_cst"; break;
2139   }
2140
2141   switch (FailureOrdering) {
2142   default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
2143   case Unordered: Out << " unordered"; break;
2144   case Monotonic: Out << " monotonic"; break;
2145   case Acquire: Out << " acquire"; break;
2146   case Release: Out << " release"; break;
2147   case AcquireRelease: Out << " acq_rel"; break;
2148   case SequentiallyConsistent: Out << " seq_cst"; break;
2149   }
2150 }
2151
2152 void AssemblyWriter::writeParamOperand(const Value *Operand,
2153                                        AttributeSet Attrs, unsigned Idx) {
2154   if (!Operand) {
2155     Out << "<null operand!>";
2156     return;
2157   }
2158
2159   // Print the type
2160   TypePrinter.print(Operand->getType(), Out);
2161   // Print parameter attributes list
2162   if (Attrs.hasAttributes(Idx))
2163     Out << ' ' << Attrs.getAsString(Idx);
2164   Out << ' ';
2165   // Print the operand
2166   WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
2167 }
2168
2169 void AssemblyWriter::writeOperandBundles(ImmutableCallSite CS) {
2170   if (!CS.hasOperandBundles())
2171     return;
2172
2173   Out << " [ ";
2174
2175   bool FirstBundle = true;
2176   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2177     OperandBundleUse BU = CS.getOperandBundleAt(i);
2178
2179     if (!FirstBundle)
2180       Out << ", ";
2181     FirstBundle = false;
2182
2183     Out << '"';
2184     PrintEscapedString(BU.getTagName(), Out);
2185     Out << '"';
2186
2187     Out << '(';
2188
2189     bool FirstInput = true;
2190     for (const auto &Input : BU.Inputs) {
2191       if (!FirstInput)
2192         Out << ", ";
2193       FirstInput = false;
2194
2195       TypePrinter.print(Input->getType(), Out);
2196       Out << " ";
2197       WriteAsOperandInternal(Out, Input, &TypePrinter, &Machine, TheModule);
2198     }
2199
2200     Out << ')';
2201   }
2202
2203   Out << " ]";
2204 }
2205
2206 void AssemblyWriter::printModule(const Module *M) {
2207   Machine.initialize();
2208
2209   if (ShouldPreserveUseListOrder)
2210     UseListOrders = predictUseListOrder(M);
2211
2212   if (!M->getModuleIdentifier().empty() &&
2213       // Don't print the ID if it will start a new line (which would
2214       // require a comment char before it).
2215       M->getModuleIdentifier().find('\n') == std::string::npos)
2216     Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
2217
2218   const std::string &DL = M->getDataLayoutStr();
2219   if (!DL.empty())
2220     Out << "target datalayout = \"" << DL << "\"\n";
2221   if (!M->getTargetTriple().empty())
2222     Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
2223
2224   if (!M->getModuleInlineAsm().empty()) {
2225     Out << '\n';
2226
2227     // Split the string into lines, to make it easier to read the .ll file.
2228     StringRef Asm = M->getModuleInlineAsm();
2229     do {
2230       StringRef Front;
2231       std::tie(Front, Asm) = Asm.split('\n');
2232
2233       // We found a newline, print the portion of the asm string from the
2234       // last newline up to this newline.
2235       Out << "module asm \"";
2236       PrintEscapedString(Front, Out);
2237       Out << "\"\n";
2238     } while (!Asm.empty());
2239   }
2240
2241   printTypeIdentities();
2242
2243   // Output all comdats.
2244   if (!Comdats.empty())
2245     Out << '\n';
2246   for (const Comdat *C : Comdats) {
2247     printComdat(C);
2248     if (C != Comdats.back())
2249       Out << '\n';
2250   }
2251
2252   // Output all globals.
2253   if (!M->global_empty()) Out << '\n';
2254   for (const GlobalVariable &GV : M->globals()) {
2255     printGlobal(&GV); Out << '\n';
2256   }
2257
2258   // Output all aliases.
2259   if (!M->alias_empty()) Out << "\n";
2260   for (const GlobalAlias &GA : M->aliases())
2261     printAlias(&GA);
2262
2263   // Output global use-lists.
2264   printUseLists(nullptr);
2265
2266   // Output all of the functions.
2267   for (const Function &F : *M)
2268     printFunction(&F);
2269   assert(UseListOrders.empty() && "All use-lists should have been consumed");
2270
2271   // Output all attribute groups.
2272   if (!Machine.as_empty()) {
2273     Out << '\n';
2274     writeAllAttributeGroups();
2275   }
2276
2277   // Output named metadata.
2278   if (!M->named_metadata_empty()) Out << '\n';
2279
2280   for (const NamedMDNode &Node : M->named_metadata())
2281     printNamedMDNode(&Node);
2282
2283   // Output metadata.
2284   if (!Machine.mdn_empty()) {
2285     Out << '\n';
2286     writeAllMDNodes();
2287   }
2288 }
2289
2290 static void printMetadataIdentifier(StringRef Name,
2291                                     formatted_raw_ostream &Out) {
2292   if (Name.empty()) {
2293     Out << "<empty name> ";
2294   } else {
2295     if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
2296         Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
2297       Out << Name[0];
2298     else
2299       Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
2300     for (unsigned i = 1, e = Name.size(); i != e; ++i) {
2301       unsigned char C = Name[i];
2302       if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
2303           C == '.' || C == '_')
2304         Out << C;
2305       else
2306         Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
2307     }
2308   }
2309 }
2310
2311 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
2312   Out << '!';
2313   printMetadataIdentifier(NMD->getName(), Out);
2314   Out << " = !{";
2315   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2316     if (i)
2317       Out << ", ";
2318     int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
2319     if (Slot == -1)
2320       Out << "<badref>";
2321     else
2322       Out << '!' << Slot;
2323   }
2324   Out << "}\n";
2325 }
2326
2327 static void PrintLinkage(GlobalValue::LinkageTypes LT,
2328                          formatted_raw_ostream &Out) {
2329   switch (LT) {
2330   case GlobalValue::ExternalLinkage: break;
2331   case GlobalValue::PrivateLinkage:       Out << "private ";        break;
2332   case GlobalValue::InternalLinkage:      Out << "internal ";       break;
2333   case GlobalValue::LinkOnceAnyLinkage:   Out << "linkonce ";       break;
2334   case GlobalValue::LinkOnceODRLinkage:   Out << "linkonce_odr ";   break;
2335   case GlobalValue::WeakAnyLinkage:       Out << "weak ";           break;
2336   case GlobalValue::WeakODRLinkage:       Out << "weak_odr ";       break;
2337   case GlobalValue::CommonLinkage:        Out << "common ";         break;
2338   case GlobalValue::AppendingLinkage:     Out << "appending ";      break;
2339   case GlobalValue::ExternalWeakLinkage:  Out << "extern_weak ";    break;
2340   case GlobalValue::AvailableExternallyLinkage:
2341     Out << "available_externally ";
2342     break;
2343   }
2344 }
2345
2346 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
2347                             formatted_raw_ostream &Out) {
2348   switch (Vis) {
2349   case GlobalValue::DefaultVisibility: break;
2350   case GlobalValue::HiddenVisibility:    Out << "hidden "; break;
2351   case GlobalValue::ProtectedVisibility: Out << "protected "; break;
2352   }
2353 }
2354
2355 static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
2356                                  formatted_raw_ostream &Out) {
2357   switch (SCT) {
2358   case GlobalValue::DefaultStorageClass: break;
2359   case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
2360   case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
2361   }
2362 }
2363
2364 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
2365                                   formatted_raw_ostream &Out) {
2366   switch (TLM) {
2367     case GlobalVariable::NotThreadLocal:
2368       break;
2369     case GlobalVariable::GeneralDynamicTLSModel:
2370       Out << "thread_local ";
2371       break;
2372     case GlobalVariable::LocalDynamicTLSModel:
2373       Out << "thread_local(localdynamic) ";
2374       break;
2375     case GlobalVariable::InitialExecTLSModel:
2376       Out << "thread_local(initialexec) ";
2377       break;
2378     case GlobalVariable::LocalExecTLSModel:
2379       Out << "thread_local(localexec) ";
2380       break;
2381   }
2382 }
2383
2384 static void maybePrintComdat(formatted_raw_ostream &Out,
2385                              const GlobalObject &GO) {
2386   const Comdat *C = GO.getComdat();
2387   if (!C)
2388     return;
2389
2390   if (isa<GlobalVariable>(GO))
2391     Out << ',';
2392   Out << " comdat";
2393
2394   if (GO.getName() == C->getName())
2395     return;
2396
2397   Out << '(';
2398   PrintLLVMName(Out, C->getName(), ComdatPrefix);
2399   Out << ')';
2400 }
2401
2402 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
2403   if (GV->isMaterializable())
2404     Out << "; Materializable\n";
2405
2406   WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
2407   Out << " = ";
2408
2409   if (!GV->hasInitializer() && GV->hasExternalLinkage())
2410     Out << "external ";
2411
2412   PrintLinkage(GV->getLinkage(), Out);
2413   PrintVisibility(GV->getVisibility(), Out);
2414   PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
2415   PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
2416   if (GV->hasUnnamedAddr())
2417     Out << "unnamed_addr ";
2418
2419   if (unsigned AddressSpace = GV->getType()->getAddressSpace())
2420     Out << "addrspace(" << AddressSpace << ") ";
2421   if (GV->isExternallyInitialized()) Out << "externally_initialized ";
2422   Out << (GV->isConstant() ? "constant " : "global ");
2423   TypePrinter.print(GV->getType()->getElementType(), Out);
2424
2425   if (GV->hasInitializer()) {
2426     Out << ' ';
2427     writeOperand(GV->getInitializer(), false);
2428   }
2429
2430   if (GV->hasSection()) {
2431     Out << ", section \"";
2432     PrintEscapedString(GV->getSection(), Out);
2433     Out << '"';
2434   }
2435   maybePrintComdat(Out, *GV);
2436   if (GV->getAlignment())
2437     Out << ", align " << GV->getAlignment();
2438
2439   printInfoComment(*GV);
2440 }
2441
2442 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
2443   if (GA->isMaterializable())
2444     Out << "; Materializable\n";
2445
2446   WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
2447   Out << " = ";
2448
2449   PrintLinkage(GA->getLinkage(), Out);
2450   PrintVisibility(GA->getVisibility(), Out);
2451   PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
2452   PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
2453   if (GA->hasUnnamedAddr())
2454     Out << "unnamed_addr ";
2455
2456   Out << "alias ";
2457
2458   TypePrinter.print(GA->getValueType(), Out);
2459
2460   Out << ", ";
2461
2462   const Constant *Aliasee = GA->getAliasee();
2463
2464   if (!Aliasee) {
2465     TypePrinter.print(GA->getType(), Out);
2466     Out << " <<NULL ALIASEE>>";
2467   } else {
2468     writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
2469   }
2470
2471   printInfoComment(*GA);
2472   Out << '\n';
2473 }
2474
2475 void AssemblyWriter::printComdat(const Comdat *C) {
2476   C->print(Out);
2477 }
2478
2479 void AssemblyWriter::printTypeIdentities() {
2480   if (TypePrinter.NumberedTypes.empty() &&
2481       TypePrinter.NamedTypes.empty())
2482     return;
2483
2484   Out << '\n';
2485
2486   // We know all the numbers that each type is used and we know that it is a
2487   // dense assignment.  Convert the map to an index table.
2488   std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
2489   for (DenseMap<StructType*, unsigned>::iterator I =
2490        TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
2491        I != E; ++I) {
2492     assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
2493     NumberedTypes[I->second] = I->first;
2494   }
2495
2496   // Emit all numbered types.
2497   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
2498     Out << '%' << i << " = type ";
2499
2500     // Make sure we print out at least one level of the type structure, so
2501     // that we do not get %2 = type %2
2502     TypePrinter.printStructBody(NumberedTypes[i], Out);
2503     Out << '\n';
2504   }
2505
2506   for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
2507     PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
2508     Out << " = type ";
2509
2510     // Make sure we print out at least one level of the type structure, so
2511     // that we do not get %FILE = type %FILE
2512     TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
2513     Out << '\n';
2514   }
2515 }
2516
2517 /// printFunction - Print all aspects of a function.
2518 ///
2519 void AssemblyWriter::printFunction(const Function *F) {
2520   // Print out the return type and name.
2521   Out << '\n';
2522
2523   if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
2524
2525   if (F->isMaterializable())
2526     Out << "; Materializable\n";
2527
2528   const AttributeSet &Attrs = F->getAttributes();
2529   if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
2530     AttributeSet AS = Attrs.getFnAttributes();
2531     std::string AttrStr;
2532
2533     unsigned Idx = 0;
2534     for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
2535       if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
2536         break;
2537
2538     for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
2539          I != E; ++I) {
2540       Attribute Attr = *I;
2541       if (!Attr.isStringAttribute()) {
2542         if (!AttrStr.empty()) AttrStr += ' ';
2543         AttrStr += Attr.getAsString();
2544       }
2545     }
2546
2547     if (!AttrStr.empty())
2548       Out << "; Function Attrs: " << AttrStr << '\n';
2549   }
2550
2551   if (F->isDeclaration())
2552     Out << "declare ";
2553   else
2554     Out << "define ";
2555
2556   PrintLinkage(F->getLinkage(), Out);
2557   PrintVisibility(F->getVisibility(), Out);
2558   PrintDLLStorageClass(F->getDLLStorageClass(), Out);
2559
2560   // Print the calling convention.
2561   if (F->getCallingConv() != CallingConv::C) {
2562     PrintCallingConv(F->getCallingConv(), Out);
2563     Out << " ";
2564   }
2565
2566   FunctionType *FT = F->getFunctionType();
2567   if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
2568     Out <<  Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
2569   TypePrinter.print(F->getReturnType(), Out);
2570   Out << ' ';
2571   WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
2572   Out << '(';
2573   Machine.incorporateFunction(F);
2574
2575   // Loop over the arguments, printing them...
2576   if (F->isDeclaration() && !IsForDebug) {
2577     // We're only interested in the type here - don't print argument names.
2578     for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
2579       // Insert commas as we go... the first arg doesn't get a comma
2580       if (I)
2581         Out << ", ";
2582       // Output type...
2583       TypePrinter.print(FT->getParamType(I), Out);
2584
2585       if (Attrs.hasAttributes(I + 1))
2586         Out << ' ' << Attrs.getAsString(I + 1);
2587     }
2588   } else {
2589     // The arguments are meaningful here, print them in detail.
2590     unsigned Idx = 1;
2591     for (const Argument &Arg : F->args()) {
2592       // Insert commas as we go... the first arg doesn't get a comma
2593       if (Idx != 1)
2594         Out << ", ";
2595       printArgument(&Arg, Attrs, Idx++);
2596     }
2597   }
2598
2599   // Finish printing arguments...
2600   if (FT->isVarArg()) {
2601     if (FT->getNumParams()) Out << ", ";
2602     Out << "...";  // Output varargs portion of signature!
2603   }
2604   Out << ')';
2605   if (F->hasUnnamedAddr())
2606     Out << " unnamed_addr";
2607   if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
2608     Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
2609   if (F->hasSection()) {
2610     Out << " section \"";
2611     PrintEscapedString(F->getSection(), Out);
2612     Out << '"';
2613   }
2614   maybePrintComdat(Out, *F);
2615   if (F->getAlignment())
2616     Out << " align " << F->getAlignment();
2617   if (F->hasGC())
2618     Out << " gc \"" << F->getGC() << '"';
2619   if (F->hasPrefixData()) {
2620     Out << " prefix ";
2621     writeOperand(F->getPrefixData(), true);
2622   }
2623   if (F->hasPrologueData()) {
2624     Out << " prologue ";
2625     writeOperand(F->getPrologueData(), true);
2626   }
2627   if (F->hasPersonalityFn()) {
2628     Out << " personality ";
2629     writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
2630   }
2631
2632   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2633   F->getAllMetadata(MDs);
2634   printMetadataAttachments(MDs, " ");
2635
2636   if (F->isDeclaration()) {
2637     Out << '\n';
2638   } else {
2639     Out << " {";
2640     // Output all of the function's basic blocks.
2641     for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
2642       printBasicBlock(&*I);
2643
2644     // Output the function's use-lists.
2645     printUseLists(F);
2646
2647     Out << "}\n";
2648   }
2649
2650   Machine.purgeFunction();
2651 }
2652
2653 /// printArgument - This member is called for every argument that is passed into
2654 /// the function.  Simply print it out
2655 ///
2656 void AssemblyWriter::printArgument(const Argument *Arg,
2657                                    AttributeSet Attrs, unsigned Idx) {
2658   // Output type...
2659   TypePrinter.print(Arg->getType(), Out);
2660
2661   // Output parameter attributes list
2662   if (Attrs.hasAttributes(Idx))
2663     Out << ' ' << Attrs.getAsString(Idx);
2664
2665   // Output name, if available...
2666   if (Arg->hasName()) {
2667     Out << ' ';
2668     PrintLLVMName(Out, Arg);
2669   }
2670 }
2671
2672 /// printBasicBlock - This member is called for each basic block in a method.
2673 ///
2674 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
2675   if (BB->hasName()) {              // Print out the label if it exists...
2676     Out << "\n";
2677     PrintLLVMName(Out, BB->getName(), LabelPrefix);
2678     Out << ':';
2679   } else if (!BB->use_empty()) {      // Don't print block # of no uses...
2680     Out << "\n; <label>:";
2681     int Slot = Machine.getLocalSlot(BB);
2682     if (Slot != -1)
2683       Out << Slot;
2684     else
2685       Out << "<badref>";
2686   }
2687
2688   if (!BB->getParent()) {
2689     Out.PadToColumn(50);
2690     Out << "; Error: Block without parent!";
2691   } else if (BB != &BB->getParent()->getEntryBlock()) {  // Not the entry block?
2692     // Output predecessors for the block.
2693     Out.PadToColumn(50);
2694     Out << ";";
2695     const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2696
2697     if (PI == PE) {
2698       Out << " No predecessors!";
2699     } else {
2700       Out << " preds = ";
2701       writeOperand(*PI, false);
2702       for (++PI; PI != PE; ++PI) {
2703         Out << ", ";
2704         writeOperand(*PI, false);
2705       }
2706     }
2707   }
2708
2709   Out << "\n";
2710
2711   if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
2712
2713   // Output all of the instructions in the basic block...
2714   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2715     printInstructionLine(*I);
2716   }
2717
2718   if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
2719 }
2720
2721 /// printInstructionLine - Print an instruction and a newline character.
2722 void AssemblyWriter::printInstructionLine(const Instruction &I) {
2723   printInstruction(I);
2724   Out << '\n';
2725 }
2726
2727 /// printGCRelocateComment - print comment after call to the gc.relocate
2728 /// intrinsic indicating base and derived pointer names.
2729 void AssemblyWriter::printGCRelocateComment(const Value &V) {
2730   assert(isGCRelocate(&V));
2731   GCRelocateOperands GCOps(cast<Instruction>(&V));
2732
2733   Out << " ; (";
2734   writeOperand(GCOps.getBasePtr(), false);
2735   Out << ", ";
2736   writeOperand(GCOps.getDerivedPtr(), false);
2737   Out << ")";
2738 }
2739
2740 /// printInfoComment - Print a little comment after the instruction indicating
2741 /// which slot it occupies.
2742 ///
2743 void AssemblyWriter::printInfoComment(const Value &V) {
2744   if (isGCRelocate(&V))
2745     printGCRelocateComment(V);
2746
2747   if (AnnotationWriter)
2748     AnnotationWriter->printInfoComment(V, Out);
2749 }
2750
2751 // This member is called for each Instruction in a function..
2752 void AssemblyWriter::printInstruction(const Instruction &I) {
2753   if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
2754
2755   // Print out indentation for an instruction.
2756   Out << "  ";
2757
2758   // Print out name if it exists...
2759   if (I.hasName()) {
2760     PrintLLVMName(Out, &I);
2761     Out << " = ";
2762   } else if (!I.getType()->isVoidTy()) {
2763     // Print out the def slot taken.
2764     int SlotNum = Machine.getLocalSlot(&I);
2765     if (SlotNum == -1)
2766       Out << "<badref> = ";
2767     else
2768       Out << '%' << SlotNum << " = ";
2769   }
2770
2771   if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2772     if (CI->isMustTailCall())
2773       Out << "musttail ";
2774     else if (CI->isTailCall())
2775       Out << "tail ";
2776     else if (CI->isNoTailCall())
2777       Out << "notail ";
2778   }
2779
2780   // Print out the opcode...
2781   Out << I.getOpcodeName();
2782
2783   // If this is an atomic load or store, print out the atomic marker.
2784   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isAtomic()) ||
2785       (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
2786     Out << " atomic";
2787
2788   if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
2789     Out << " weak";
2790
2791   // If this is a volatile operation, print out the volatile marker.
2792   if ((isa<LoadInst>(I)  && cast<LoadInst>(I).isVolatile()) ||
2793       (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
2794       (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
2795       (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
2796     Out << " volatile";
2797
2798   // Print out optimization information.
2799   WriteOptimizationInfo(Out, &I);
2800
2801   // Print out the compare instruction predicates
2802   if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
2803     Out << ' ' << getPredicateText(CI->getPredicate());
2804
2805   // Print out the atomicrmw operation
2806   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
2807     writeAtomicRMWOperation(Out, RMWI->getOperation());
2808
2809   // Print out the type of the operands...
2810   const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
2811
2812   // Special case conditional branches to swizzle the condition out to the front
2813   if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
2814     const BranchInst &BI(cast<BranchInst>(I));
2815     Out << ' ';
2816     writeOperand(BI.getCondition(), true);
2817     Out << ", ";
2818     writeOperand(BI.getSuccessor(0), true);
2819     Out << ", ";
2820     writeOperand(BI.getSuccessor(1), true);
2821
2822   } else if (isa<SwitchInst>(I)) {
2823     const SwitchInst& SI(cast<SwitchInst>(I));
2824     // Special case switch instruction to get formatting nice and correct.
2825     Out << ' ';
2826     writeOperand(SI.getCondition(), true);
2827     Out << ", ";
2828     writeOperand(SI.getDefaultDest(), true);
2829     Out << " [";
2830     for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2831          i != e; ++i) {
2832       Out << "\n    ";
2833       writeOperand(i.getCaseValue(), true);
2834       Out << ", ";
2835       writeOperand(i.getCaseSuccessor(), true);
2836     }
2837     Out << "\n  ]";
2838   } else if (isa<IndirectBrInst>(I)) {
2839     // Special case indirectbr instruction to get formatting nice and correct.
2840     Out << ' ';
2841     writeOperand(Operand, true);
2842     Out << ", [";
2843
2844     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2845       if (i != 1)
2846         Out << ", ";
2847       writeOperand(I.getOperand(i), true);
2848     }
2849     Out << ']';
2850   } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
2851     Out << ' ';
2852     TypePrinter.print(I.getType(), Out);
2853     Out << ' ';
2854
2855     for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
2856       if (op) Out << ", ";
2857       Out << "[ ";
2858       writeOperand(PN->getIncomingValue(op), false); Out << ", ";
2859       writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
2860     }
2861   } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
2862     Out << ' ';
2863     writeOperand(I.getOperand(0), true);
2864     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
2865       Out << ", " << *i;
2866   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
2867     Out << ' ';
2868     writeOperand(I.getOperand(0), true); Out << ", ";
2869     writeOperand(I.getOperand(1), true);
2870     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
2871       Out << ", " << *i;
2872   } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
2873     Out << ' ';
2874     TypePrinter.print(I.getType(), Out);
2875     if (LPI->isCleanup() || LPI->getNumClauses() != 0)
2876       Out << '\n';
2877
2878     if (LPI->isCleanup())
2879       Out << "          cleanup";
2880
2881     for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
2882       if (i != 0 || LPI->isCleanup()) Out << "\n";
2883       if (LPI->isCatch(i))
2884         Out << "          catch ";
2885       else
2886         Out << "          filter ";
2887
2888       writeOperand(LPI->getClause(i), true);
2889     }
2890   } else if (const auto *CPI = dyn_cast<CatchPadInst>(&I)) {
2891     Out << " [";
2892     for (unsigned Op = 0, NumOps = CPI->getNumArgOperands(); Op < NumOps;
2893          ++Op) {
2894       if (Op > 0)
2895         Out << ", ";
2896       writeOperand(CPI->getArgOperand(Op), /*PrintType=*/true);
2897     }
2898     Out << "]\n          to ";
2899     writeOperand(CPI->getNormalDest(), /*PrintType=*/true);
2900     Out << " unwind ";
2901     writeOperand(CPI->getUnwindDest(), /*PrintType=*/true);
2902   } else if (const auto *TPI = dyn_cast<TerminatePadInst>(&I)) {
2903     Out << " [";
2904     for (unsigned Op = 0, NumOps = TPI->getNumArgOperands(); Op < NumOps;
2905          ++Op) {
2906       if (Op > 0)
2907         Out << ", ";
2908       writeOperand(TPI->getArgOperand(Op), /*PrintType=*/true);
2909     }
2910     Out << "] unwind ";
2911     if (TPI->hasUnwindDest())
2912       writeOperand(TPI->getUnwindDest(), /*PrintType=*/true);
2913     else
2914       Out << "to caller";
2915   } else if (const auto *CPI = dyn_cast<CleanupPadInst>(&I)) {
2916     Out << " [";
2917     for (unsigned Op = 0, NumOps = CPI->getNumOperands(); Op < NumOps; ++Op) {
2918       if (Op > 0)
2919         Out << ", ";
2920       writeOperand(CPI->getOperand(Op), /*PrintType=*/true);
2921     }
2922     Out << "]";
2923   } else if (isa<ReturnInst>(I) && !Operand) {
2924     Out << " void";
2925   } else if (const auto *CRI = dyn_cast<CatchReturnInst>(&I)) {
2926     Out << ' ';
2927     writeOperand(CRI->getCatchPad(), /*PrintType=*/false);
2928
2929     Out << " to ";
2930     writeOperand(CRI->getSuccessor(), /*PrintType=*/true);
2931   } else if (const auto *CRI = dyn_cast<CleanupReturnInst>(&I)) {
2932     Out << ' ';
2933     writeOperand(CRI->getCleanupPad(), /*PrintType=*/false);
2934
2935     Out << " unwind ";
2936     if (CRI->hasUnwindDest())
2937       writeOperand(CRI->getUnwindDest(), /*PrintType=*/true);
2938     else
2939       Out << "to caller";
2940   } else if (const auto *CEPI = dyn_cast<CatchEndPadInst>(&I)) {
2941     Out << " unwind ";
2942     if (CEPI->hasUnwindDest())
2943       writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2944     else
2945       Out << "to caller";
2946   } else if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(&I)) {
2947     Out << ' ';
2948     writeOperand(CEPI->getCleanupPad(), /*PrintType=*/false);
2949
2950     Out << " unwind ";
2951     if (CEPI->hasUnwindDest())
2952       writeOperand(CEPI->getUnwindDest(), /*PrintType=*/true);
2953     else
2954       Out << "to caller";
2955   } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
2956     // Print the calling convention being used.
2957     if (CI->getCallingConv() != CallingConv::C) {
2958       Out << " ";
2959       PrintCallingConv(CI->getCallingConv(), Out);
2960     }
2961
2962     Operand = CI->getCalledValue();
2963     FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
2964     Type *RetTy = FTy->getReturnType();
2965     const AttributeSet &PAL = CI->getAttributes();
2966
2967     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
2968       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
2969
2970     // If possible, print out the short form of the call instruction.  We can
2971     // only do this if the first argument is a pointer to a nonvararg function,
2972     // and if the return type is not a pointer to a function.
2973     //
2974     Out << ' ';
2975     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
2976     Out << ' ';
2977     writeOperand(Operand, false);
2978     Out << '(';
2979     for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
2980       if (op > 0)
2981         Out << ", ";
2982       writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
2983     }
2984
2985     // Emit an ellipsis if this is a musttail call in a vararg function.  This
2986     // is only to aid readability, musttail calls forward varargs by default.
2987     if (CI->isMustTailCall() && CI->getParent() &&
2988         CI->getParent()->getParent() &&
2989         CI->getParent()->getParent()->isVarArg())
2990       Out << ", ...";
2991
2992     Out << ')';
2993     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
2994       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
2995
2996     writeOperandBundles(CI);
2997
2998   } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
2999     Operand = II->getCalledValue();
3000     FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
3001     Type *RetTy = FTy->getReturnType();
3002     const AttributeSet &PAL = II->getAttributes();
3003
3004     // Print the calling convention being used.
3005     if (II->getCallingConv() != CallingConv::C) {
3006       Out << " ";
3007       PrintCallingConv(II->getCallingConv(), Out);
3008     }
3009
3010     if (PAL.hasAttributes(AttributeSet::ReturnIndex))
3011       Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
3012
3013     // If possible, print out the short form of the invoke instruction. We can
3014     // only do this if the first argument is a pointer to a nonvararg function,
3015     // and if the return type is not a pointer to a function.
3016     //
3017     Out << ' ';
3018     TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
3019     Out << ' ';
3020     writeOperand(Operand, false);
3021     Out << '(';
3022     for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
3023       if (op)
3024         Out << ", ";
3025       writeParamOperand(II->getArgOperand(op), PAL, op + 1);
3026     }
3027
3028     Out << ')';
3029     if (PAL.hasAttributes(AttributeSet::FunctionIndex))
3030       Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
3031
3032     writeOperandBundles(II);
3033
3034     Out << "\n          to ";
3035     writeOperand(II->getNormalDest(), true);
3036     Out << " unwind ";
3037     writeOperand(II->getUnwindDest(), true);
3038
3039   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
3040     Out << ' ';
3041     if (AI->isUsedWithInAlloca())
3042       Out << "inalloca ";
3043     TypePrinter.print(AI->getAllocatedType(), Out);
3044
3045     // Explicitly write the array size if the code is broken, if it's an array
3046     // allocation, or if the type is not canonical for scalar allocations.  The
3047     // latter case prevents the type from mutating when round-tripping through
3048     // assembly.
3049     if (!AI->getArraySize() || AI->isArrayAllocation() ||
3050         !AI->getArraySize()->getType()->isIntegerTy(32)) {
3051       Out << ", ";
3052       writeOperand(AI->getArraySize(), true);
3053     }
3054     if (AI->getAlignment()) {
3055       Out << ", align " << AI->getAlignment();
3056     }
3057   } else if (isa<CastInst>(I)) {
3058     if (Operand) {
3059       Out << ' ';
3060       writeOperand(Operand, true);   // Work with broken code
3061     }
3062     Out << " to ";
3063     TypePrinter.print(I.getType(), Out);
3064   } else if (isa<VAArgInst>(I)) {
3065     if (Operand) {
3066       Out << ' ';
3067       writeOperand(Operand, true);   // Work with broken code
3068     }
3069     Out << ", ";
3070     TypePrinter.print(I.getType(), Out);
3071   } else if (Operand) {   // Print the normal way.
3072     if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
3073       Out << ' ';
3074       TypePrinter.print(GEP->getSourceElementType(), Out);
3075       Out << ',';
3076     } else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
3077       Out << ' ';
3078       TypePrinter.print(LI->getType(), Out);
3079       Out << ',';
3080     }
3081
3082     // PrintAllTypes - Instructions who have operands of all the same type
3083     // omit the type from all but the first operand.  If the instruction has
3084     // different type operands (for example br), then they are all printed.
3085     bool PrintAllTypes = false;
3086     Type *TheType = Operand->getType();
3087
3088     // Select, Store and ShuffleVector always print all types.
3089     if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
3090         || isa<ReturnInst>(I)) {
3091       PrintAllTypes = true;
3092     } else {
3093       for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
3094         Operand = I.getOperand(i);
3095         // note that Operand shouldn't be null, but the test helps make dump()
3096         // more tolerant of malformed IR
3097         if (Operand && Operand->getType() != TheType) {
3098           PrintAllTypes = true;    // We have differing types!  Print them all!
3099           break;
3100         }
3101       }
3102     }
3103
3104     if (!PrintAllTypes) {
3105       Out << ' ';
3106       TypePrinter.print(TheType, Out);
3107     }
3108
3109     Out << ' ';
3110     for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
3111       if (i) Out << ", ";
3112       writeOperand(I.getOperand(i), PrintAllTypes);
3113     }
3114   }
3115
3116   // Print atomic ordering/alignment for memory operations
3117   if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
3118     if (LI->isAtomic())
3119       writeAtomic(LI->getOrdering(), LI->getSynchScope());
3120     if (LI->getAlignment())
3121       Out << ", align " << LI->getAlignment();
3122   } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
3123     if (SI->isAtomic())
3124       writeAtomic(SI->getOrdering(), SI->getSynchScope());
3125     if (SI->getAlignment())
3126       Out << ", align " << SI->getAlignment();
3127   } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
3128     writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
3129                        CXI->getSynchScope());
3130   } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
3131     writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
3132   } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
3133     writeAtomic(FI->getOrdering(), FI->getSynchScope());
3134   }
3135
3136   // Print Metadata info.
3137   SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
3138   I.getAllMetadata(InstMD);
3139   printMetadataAttachments(InstMD, ", ");
3140
3141   // Print a nice comment.
3142   printInfoComment(I);
3143 }
3144
3145 void AssemblyWriter::printMetadataAttachments(
3146     const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
3147     StringRef Separator) {
3148   if (MDs.empty())
3149     return;
3150
3151   if (MDNames.empty())
3152     TheModule->getMDKindNames(MDNames);
3153
3154   for (const auto &I : MDs) {
3155     unsigned Kind = I.first;
3156     Out << Separator;
3157     if (Kind < MDNames.size()) {
3158       Out << "!";
3159       printMetadataIdentifier(MDNames[Kind], Out);
3160     } else
3161       Out << "!<unknown kind #" << Kind << ">";
3162     Out << ' ';
3163     WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
3164   }
3165 }
3166
3167 void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
3168   Out << '!' << Slot << " = ";
3169   printMDNodeBody(Node);
3170   Out << "\n";
3171 }
3172
3173 void AssemblyWriter::writeAllMDNodes() {
3174   SmallVector<const MDNode *, 16> Nodes;
3175   Nodes.resize(Machine.mdn_size());
3176   for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
3177        I != E; ++I)
3178     Nodes[I->second] = cast<MDNode>(I->first);
3179
3180   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3181     writeMDNode(i, Nodes[i]);
3182   }
3183 }
3184
3185 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
3186   WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
3187 }
3188
3189 void AssemblyWriter::writeAllAttributeGroups() {
3190   std::vector<std::pair<AttributeSet, unsigned> > asVec;
3191   asVec.resize(Machine.as_size());
3192
3193   for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
3194        I != E; ++I)
3195     asVec[I->second] = *I;
3196
3197   for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
3198          I = asVec.begin(), E = asVec.end(); I != E; ++I)
3199     Out << "attributes #" << I->second << " = { "
3200         << I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
3201 }
3202
3203 void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
3204   bool IsInFunction = Machine.getFunction();
3205   if (IsInFunction)
3206     Out << "  ";
3207
3208   Out << "uselistorder";
3209   if (const BasicBlock *BB =
3210           IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
3211     Out << "_bb ";
3212     writeOperand(BB->getParent(), false);
3213     Out << ", ";
3214     writeOperand(BB, false);
3215   } else {
3216     Out << " ";
3217     writeOperand(Order.V, true);
3218   }
3219   Out << ", { ";
3220
3221   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3222   Out << Order.Shuffle[0];
3223   for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
3224     Out << ", " << Order.Shuffle[I];
3225   Out << " }\n";
3226 }
3227
3228 void AssemblyWriter::printUseLists(const Function *F) {
3229   auto hasMore =
3230       [&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
3231   if (!hasMore())
3232     // Nothing to do.
3233     return;
3234
3235   Out << "\n; uselistorder directives\n";
3236   while (hasMore()) {
3237     printUseListOrder(UseListOrders.back());
3238     UseListOrders.pop_back();
3239   }
3240 }
3241
3242 //===----------------------------------------------------------------------===//
3243 //                       External Interface declarations
3244 //===----------------------------------------------------------------------===//
3245
3246 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
3247                    bool ShouldPreserveUseListOrder, bool IsForDebug) const {
3248   SlotTracker SlotTable(this);
3249   formatted_raw_ostream OS(ROS);
3250   AssemblyWriter W(OS, SlotTable, this, AAW, IsForDebug,
3251                    ShouldPreserveUseListOrder);
3252   W.printModule(this);
3253 }
3254
3255 void NamedMDNode::print(raw_ostream &ROS, bool IsForDebug) const {
3256   SlotTracker SlotTable(getParent());
3257   formatted_raw_ostream OS(ROS);
3258   AssemblyWriter W(OS, SlotTable, getParent(), nullptr, IsForDebug);
3259   W.printNamedMDNode(this);
3260 }
3261
3262 void Comdat::print(raw_ostream &ROS, bool /*IsForDebug*/) const {
3263   PrintLLVMName(ROS, getName(), ComdatPrefix);
3264   ROS << " = comdat ";
3265
3266   switch (getSelectionKind()) {
3267   case Comdat::Any:
3268     ROS << "any";
3269     break;
3270   case Comdat::ExactMatch:
3271     ROS << "exactmatch";
3272     break;
3273   case Comdat::Largest:
3274     ROS << "largest";
3275     break;
3276   case Comdat::NoDuplicates:
3277     ROS << "noduplicates";
3278     break;
3279   case Comdat::SameSize:
3280     ROS << "samesize";
3281     break;
3282   }
3283
3284   ROS << '\n';
3285 }
3286
3287 void Type::print(raw_ostream &OS, bool /*IsForDebug*/) const {
3288   TypePrinting TP;
3289   TP.print(const_cast<Type*>(this), OS);
3290
3291   // If the type is a named struct type, print the body as well.
3292   if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
3293     if (!STy->isLiteral()) {
3294       OS << " = type ";
3295       TP.printStructBody(STy, OS);
3296     }
3297 }
3298
3299 static bool isReferencingMDNode(const Instruction &I) {
3300   if (const auto *CI = dyn_cast<CallInst>(&I))
3301     if (Function *F = CI->getCalledFunction())
3302       if (F->isIntrinsic())
3303         for (auto &Op : I.operands())
3304           if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
3305             if (isa<MDNode>(V->getMetadata()))
3306               return true;
3307   return false;
3308 }
3309
3310 void Value::print(raw_ostream &ROS, bool IsForDebug) const {
3311   bool ShouldInitializeAllMetadata = false;
3312   if (auto *I = dyn_cast<Instruction>(this))
3313     ShouldInitializeAllMetadata = isReferencingMDNode(*I);
3314   else if (isa<Function>(this) || isa<MetadataAsValue>(this))
3315     ShouldInitializeAllMetadata = true;
3316
3317   ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
3318   print(ROS, MST, IsForDebug);
3319 }
3320
3321 void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST,
3322                   bool IsForDebug) const {
3323   formatted_raw_ostream OS(ROS);
3324   SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
3325   SlotTracker &SlotTable =
3326       MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
3327   auto incorporateFunction = [&](const Function *F) {
3328     if (F)
3329       MST.incorporateFunction(*F);
3330   };
3331
3332   if (const Instruction *I = dyn_cast<Instruction>(this)) {
3333     incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
3334     AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr, IsForDebug);
3335     W.printInstruction(*I);
3336   } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
3337     incorporateFunction(BB->getParent());
3338     AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr, IsForDebug);
3339     W.printBasicBlock(BB);
3340   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
3341     AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr, IsForDebug);
3342     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
3343       W.printGlobal(V);
3344     else if (const Function *F = dyn_cast<Function>(GV))
3345       W.printFunction(F);
3346     else
3347       W.printAlias(cast<GlobalAlias>(GV));
3348   } else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
3349     V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
3350   } else if (const Constant *C = dyn_cast<Constant>(this)) {
3351     TypePrinting TypePrinter;
3352     TypePrinter.print(C->getType(), OS);
3353     OS << ' ';
3354     WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
3355   } else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
3356     this->printAsOperand(OS, /* PrintType */ true, MST);
3357   } else {
3358     llvm_unreachable("Unknown value to print out!");
3359   }
3360 }
3361
3362 /// Print without a type, skipping the TypePrinting object.
3363 ///
3364 /// \return \c true iff printing was successful.
3365 static bool printWithoutType(const Value &V, raw_ostream &O,
3366                              SlotTracker *Machine, const Module *M) {
3367   if (V.hasName() || isa<GlobalValue>(V) ||
3368       (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
3369     WriteAsOperandInternal(O, &V, nullptr, Machine, M);
3370     return true;
3371   }
3372   return false;
3373 }
3374
3375 static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
3376                                ModuleSlotTracker &MST) {
3377   TypePrinting TypePrinter;
3378   if (const Module *M = MST.getModule())
3379     TypePrinter.incorporateTypes(*M);
3380   if (PrintType) {
3381     TypePrinter.print(V.getType(), O);
3382     O << ' ';
3383   }
3384
3385   WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
3386                          MST.getModule());
3387 }
3388
3389 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3390                            const Module *M) const {
3391   if (!M)
3392     M = getModuleFromVal(this);
3393
3394   if (!PrintType)
3395     if (printWithoutType(*this, O, nullptr, M))
3396       return;
3397
3398   SlotTracker Machine(
3399       M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
3400   ModuleSlotTracker MST(Machine, M);
3401   printAsOperandImpl(*this, O, PrintType, MST);
3402 }
3403
3404 void Value::printAsOperand(raw_ostream &O, bool PrintType,
3405                            ModuleSlotTracker &MST) const {
3406   if (!PrintType)
3407     if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
3408       return;
3409
3410   printAsOperandImpl(*this, O, PrintType, MST);
3411 }
3412
3413 static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
3414                               ModuleSlotTracker &MST, const Module *M,
3415                               bool OnlyAsOperand) {
3416   formatted_raw_ostream OS(ROS);
3417
3418   TypePrinting TypePrinter;
3419   if (M)
3420     TypePrinter.incorporateTypes(*M);
3421
3422   WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
3423                          /* FromValue */ true);
3424
3425   auto *N = dyn_cast<MDNode>(&MD);
3426   if (OnlyAsOperand || !N)
3427     return;
3428
3429   OS << " = ";
3430   WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
3431 }
3432
3433 void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
3434   ModuleSlotTracker MST(M, isa<MDNode>(this));
3435   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3436 }
3437
3438 void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
3439                               const Module *M) const {
3440   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
3441 }
3442
3443 void Metadata::print(raw_ostream &OS, const Module *M,
3444                      bool /*IsForDebug*/) const {
3445   ModuleSlotTracker MST(M, isa<MDNode>(this));
3446   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3447 }
3448
3449 void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
3450                      const Module *M, bool /*IsForDebug*/) const {
3451   printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
3452 }
3453
3454 // Value::dump - allow easy printing of Values from the debugger.
3455 LLVM_DUMP_METHOD
3456 void Value::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3457
3458 // Type::dump - allow easy printing of Types from the debugger.
3459 LLVM_DUMP_METHOD
3460 void Type::dump() const { print(dbgs(), /*IsForDebug=*/true); dbgs() << '\n'; }
3461
3462 // Module::dump() - Allow printing of Modules from the debugger.
3463 LLVM_DUMP_METHOD
3464 void Module::dump() const {
3465   print(dbgs(), nullptr,
3466         /*ShouldPreserveUseListOrder=*/false, /*IsForDebug=*/true);
3467 }
3468
3469 // \brief Allow printing of Comdats from the debugger.
3470 LLVM_DUMP_METHOD
3471 void Comdat::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3472
3473 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
3474 LLVM_DUMP_METHOD
3475 void NamedMDNode::dump() const { print(dbgs(), /*IsForDebug=*/true); }
3476
3477 LLVM_DUMP_METHOD
3478 void Metadata::dump() const { dump(nullptr); }
3479
3480 LLVM_DUMP_METHOD
3481 void Metadata::dump(const Module *M) const {
3482   print(dbgs(), M, /*IsForDebug=*/true);
3483   dbgs() << '\n';
3484 }