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