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