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